示例#1
0
    def release(self):
        """
        Releases the lock previously locked by a call to acquire().
        Returns None.
        """

        thrCurrent = currentThread()

        self._lock()
        try:

            if self.__log: self._log("releasing exclusive")
            if self.__debug:
                assert self._invariant(), "SharedLock invariant failed: %s in %s" % \
                                          (self._debug_dump(), trace_string())

            if thrCurrent is not self.thrOwner:
                raise Exception("Current thread has not acquired the lock")

            # the thread releases its exclusive lock

            self.intOwnerDepth -= 1
            if self.intOwnerDepth > 0:
                if self.__debug:
                    assert self._invariant(), "SharedLock invariant failed: %s in %s" % \
                                              (self._debug_dump(), trace_string())
                if self.__log: self._log("released exclusive")
                return

            self.thrOwner = None

            # a decision is made which pending thread(s) to awake (if any)

            self._release_threads()
            
            if self.__debug:
                assert self._invariant(), "SharedLock invariant failed: %s in %s" % \
                                          (self._debug_dump(), trace_string())
            if self.__log: self._log("released exclusive")

        finally:
            self._unlock()
示例#2
0
    def release(self):
        """
        Releases the lock previously locked by a call to acquire().
        Returns None.
        """

        thrCurrent = currentThread()

        self._lock()
        try:

            if self.__log: self._log("releasing exclusive")
            if self.__debug:
                assert self._invariant(), "SharedLock invariant failed: %s in %s" % \
                                          (self._debug_dump(), trace_string())

            if thrCurrent is not self.thrOwner:
                raise Exception("Current thread has not acquired the lock")

            # the thread releases its exclusive lock

            self.intOwnerDepth -= 1
            if self.intOwnerDepth > 0:
                if self.__debug:
                    assert self._invariant(), "SharedLock invariant failed: %s in %s" % \
                                              (self._debug_dump(), trace_string())
                if self.__log: self._log("released exclusive")
                return

            self.thrOwner = None

            # a decision is made which pending thread(s) to awake (if any)

            self._release_threads()

            if self.__debug:
                assert self._invariant(), "SharedLock invariant failed: %s in %s" % \
                                          (self._debug_dump(), trace_string())
            if self.__log: self._log("released exclusive")

        finally:
            self._unlock()
示例#3
0
    def release_shared(self):
        """
        Releases the lock previously locked by a call to acquire_shared().
        Returns None.
        """

        thrCurrent = currentThread()

        self._lock()
        try:

            if self.__log: self._log("releasing shared")
            if self.__debug:
                assert self._invariant(), "SharedLock invariant failed: %s in %s" % \
                                          (self._debug_dump(), trace_string())

            if thrCurrent not in self.dicUsers:
                raise Exception("Current thread has not acquired the lock")
                
            # the thread releases its shared lock

            self.dicUsers[thrCurrent] -= 1
            if self.dicUsers[thrCurrent] > 0:
                if self.__debug:
                    assert self._invariant(), "SharedLock invariant failed: %s in %s" % \
                                              (self._debug_dump(), trace_string())
                if self.__log: self._log("released shared")
                return
            else:
                del self.dicUsers[thrCurrent]

            # a decision is made which pending thread(s) to awake (if any)

            self._release_threads()
            
            if self.__debug:
                assert self._invariant(), "SharedLock invariant failed: %s in %s" % \
                                          (self._debug_dump(), trace_string())
            if self.__log: self._log("released shared")

        finally:
            self._unlock()
示例#4
0
    def release_shared(self):
        """
        Releases the lock previously locked by a call to acquire_shared().
        Returns None.
        """

        thrCurrent = currentThread()

        self._lock()
        try:

            if self.__log: self._log("releasing shared")
            if self.__debug:
                assert self._invariant(), "SharedLock invariant failed: %s in %s" % \
                                          (self._debug_dump(), trace_string())

            if thrCurrent not in self.dicUsers:
                raise Exception("Current thread has not acquired the lock")

            # the thread releases its shared lock

            self.dicUsers[thrCurrent] -= 1
            if self.dicUsers[thrCurrent] > 0:
                if self.__debug:
                    assert self._invariant(), "SharedLock invariant failed: %s in %s" % \
                                              (self._debug_dump(), trace_string())
                if self.__log: self._log("released shared")
                return
            else:
                del self.dicUsers[thrCurrent]

            # a decision is made which pending thread(s) to awake (if any)

            self._release_threads()

            if self.__debug:
                assert self._invariant(), "SharedLock invariant failed: %s in %s" % \
                                          (self._debug_dump(), trace_string())
            if self.__log: self._log("released shared")

        finally:
            self._unlock()
示例#5
0
    def _execute_sql(self, sql, params):

        try:
            param_list = ", ".join("@{0:s} = {1:s}".format(n, v) for n, v in params.items())
            at_params = { n: "@{0:s}".format(n) for n in params.keys() }
            sql = sql.format(**at_params)
        except:
            ResourceError.rethrow(recoverable = True, terminal = False)

        cursor = self._connection.cursor()
        try:

            for n, v in params.items():
                cursor.execute("SET @{0:s}={1:s}".format(n, v))

            pmnc.log.info(">> {0:s}".format(sql))
            if param_list:
                if pmnc.log.debug:
                    pmnc.log.debug("-- {0:s} -- ({1:s})".format(sql, param_list))

            records = []
            try:

                cursor.execute(sql)
                rowcount = cursor.rowcount

                if rowcount >= 0:
                    pmnc.log.info("<< OK, {0:d} record(s)".format(rowcount))
                    if rowcount > 0 and cursor.description:
                        column_names = [ t[0] for t in cursor.description ]
                        for record in cursor.fetchall():
                            records.append(dict(zip(column_names, record)))
                else:
                    pmnc.log.info("<< OK")

            except MySQL_Error as e:
                code, message = e.args[0].args
                pmnc.log.warning("<< {0:s}{1:s} !! MySQL_Error(\"[{2:d}] {3:s}\") in {4:s}".\
                                 format(sql, " -- ({0:s})".format(param_list)
                                        if param_list else "", code, message, trace_string()))
                SQLResourceError.rethrow(recoverable = True,
                        code = code, description = message) # note that there is no state
            except Exception:
                pmnc.log.warning("<< {0:s}{1:s} !! {2:s}".\
                                 format(sql, " -- ({0:s})".format(param_list)
                                        if param_list else "", exc_string()))
                ResourceError.rethrow(recoverable = True)
            else:
                return records

        finally:
            cursor.close()
示例#6
0
    def _execute_sql(self, sql, params):

        try:
            sql, params = self._convert_to_qmarks(sql, params)
            param_list = ", ".join(map(lambda x: isinstance(x, str)
                                                 and "'{0:s}'".format(x)
                                                 or str(x), params))
        except:
            ResourceError.rethrow(recoverable = True, terminal = False)

        pmnc.log.info(">> {0:s}".format(sql))
        if param_list:
            if pmnc.log.debug:
                pmnc.log.debug("-- {0:s} -- ({1:s})".format(sql, param_list))

        records = []
        try:

            self._cursor.execute(sql, params)

            rowcount = self._cursor.rowcount
            if rowcount >= 0:
                pmnc.log.info("<< OK, {0:d} record(s)".format(rowcount))
                if self._cursor.description and rowcount > 0:
                    column_names = [ t[0].decode("ascii") for t in self._cursor.description ]
                    for record in self._cursor.fetchall():
                        records.append(dict(zip(column_names, record)))
            else:
                pmnc.log.info("<< OK")

        except ProgrammingError as e:
            try:
                level, state, message = map(self._decode_message, e.args)
            except:
                state, message = "PG800", str(e)
            state = state.upper()
            pmnc.log.warning("<< {0:s}{1:s} !! PostgreSQL_Error(\"[{2:s}] {3:s}\") in {4:s}".\
                             format(sql, " -- ({0:s})".format(param_list)
                                    if param_list else "", state, message, trace_string()))
            SQLResourceError.rethrow(
                    state = state, description = message, # note that there is no code
                    recoverable = True, terminal = state[:2] not in self._safe_states)
        except:
            pmnc.log.warning("<< {0:s}{1:s} !! {2:s}".\
                             format(sql, " -- ({0:s})".format(param_list)
                                    if param_list else "", exc_string()))
            ResourceError.rethrow(recoverable = True)
        else:
            return records
示例#7
0
    def _execute_sql(self, sql, params):

        try:
            sql, params = self._convert_bind_points(sql, params)
            param_list = ", ".join("{0:s}={1:s}".format(k, isinstance(v, str) and "'{0:s}'".format(v) or str(v))
                                   for k, v in params.items())
        except:
            ResourceError.rethrow(recoverable = True, terminal = False)

        pmnc.log.info(">> {0:s}".format(sql))
        if param_list:
            if pmnc.log.debug:
                pmnc.log.debug("-- {0:s} -- ({1:s})".format(sql, param_list))

        records = []
        try:

            self._cursor.execute(sql, params)

            rowcount = self._cursor.rowcount
            if rowcount >= 0:
                pmnc.log.info("<< OK, {0:d} record(s)".format(rowcount))
                if self._cursor.description and rowcount > 0:
                    column_names = [ t.name for t in self._cursor.description ]
                    for record in self._cursor.fetchall():
                        records.append(dict(zip(column_names, record)))
            else:
                pmnc.log.info("<< OK")

        except PGError as e:
            state, message = e.pgcode, " ".join(s.strip() for s in e.pgerror.split("\n"))
            pmnc.log.warning("<< {0:s}{1:s} !! {2:s}(\"{3:s}{4:s}\") in {5:s}".\
                             format(sql, " -- ({0:s})".format(param_list) if param_list else "",
                                    e.__class__.__name__, "[{0:s}] ".format(state) if state else "",
                                    message, trace_string()))
            SQLResourceError.rethrow(
                    state = state, description = message, # note that there is no code
                    recoverable = True, terminal = not state or state[:2] not in self._safe_states)

        except:
            pmnc.log.warning("<< {0:s}{1:s} !! {2:s}".\
                             format(sql, " -- ({0:s})".format(param_list)
                                    if param_list else "", exc_string()))
            ResourceError.rethrow(recoverable = True)
        else:
            return records
示例#8
0
 def _log(self, s):
     self.__log("{0:s} {1:s} in {2:s}".format(
         s, self._dump(), exc_string.trace_string(skip=1)))
示例#9
0
 def _log(self, s):
     self.__log("{0:s} {1:s} in {2:s}".format(s, self._dump(),
                                              exc_string.trace_string(skip = 1)))
示例#10
0
    def _execute_sql(self, sql, params):

        try:
            sql, params = self._convert_to_named(sql, params)
            param_list = ", ".join(map(lambda n_v: "{0:s} = {1:s}".\
                                       format(n_v[0], isinstance(n_v[1], str) and
                                                      "'{0:s}'".format(n_v[1]) or str(n_v[1])),
                                       params.items()))
        except:
            ResourceError.rethrow(recoverable = True, terminal = False)

        pmnc.log.info(">> {0:s}".format(sql))
        if param_list:
            if pmnc.log.debug:
                pmnc.log.debug("-- {0:s} -- ({1:s})".format(sql, param_list))

        try:

            cursor = self._connection.cursor()
            try:

                # avoid using floats with numbers

                cursor.numbersAsStrings = True

                # avoid truncation of timestamps and intervals

                param_sizes = {}
                for n, v in params.items():
                    if isinstance(v, datetime):
                        param_sizes[n] = TIMESTAMP
                    elif isinstance(v, timedelta):
                        param_sizes[n] = INTERVAL
                if param_sizes:
                    cursor.setinputsizes(**param_sizes)

                # execute the query, making stored procedure a special case

                execute = self._execute_parser.match(sql)
                if execute:
                    proc_name = execute.group(1)
                    result = self._connection.cursor()
                    try:
                        params.update(result = result) # providing out sys_refcursor parameter result
                        cursor.callproc(proc_name, keywordParameters = params)
                    finally:
                        try:
                            cursor.close()
                        finally:
                            cursor = result
                else:
                    cursor.execute(sql, **params)

                # extract the result

                if cursor.description is not None:
                    description = tuple(dict(name = t[0], type_name = t[1].__name__) for t in cursor.description)
                    records = [ { field["name"]: self.cx_TYPE(field["type_name"], value)
                                  for field, value in zip(description, record) } for record in cursor ]
                else:
                    records = [] # not a SELECT query

                records_affected = cursor.rowcount

            finally:
                cursor.close()

            if records_affected > 0:
                pmnc.log.info("<< OK, {0:d} record(s)".format(records_affected))
            else:
                pmnc.log.info("<< OK")

        except Oracle_Error as e:
            e = e.args[0]
            if isinstance(e, _Oracle_Error):
                code, message = e.code, e.message
            else:
                code, message = -1, "cx_Oracle error: {0:s}".format(str(e))
            pmnc.log.warning("<< {0:s}{1:s} !! Oracle_Error(\"{2:d}: {3:s}\") in {4:s}".\
                             format(sql, " -- ({0:s})".format(param_list)
                                    if param_list else "", code, message, trace_string()))
            SQLResourceError.rethrow(
                    code = code, description = message, recoverable = True) # note that there is no state
        except:
            pmnc.log.warning("<< {0:s}{1:s} !! {2:s}".\
                             format(sql, " -- ({0:s})".format(param_list)
                                    if param_list else "", exc_string()))
            ResourceError.rethrow(recoverable = True)
        else:
            return records
示例#11
0
 def _log(self, s):
     thrCurrent = currentThread()
     self.__log("%s @ %.08x %s %s @ %.08x in %s" %
                (thrCurrent.getName(), id(thrCurrent), s,
                 self._debug_dump(), id(self), trace_string()))
示例#12
0
    def acquire_shared(self, timeout = None):
        """
        Attempts to acquire the lock in shared mode within the optional 
        timeout. If the timeout is not specified, waits for the lock
        infinitely. Returns True if the lock has been acquired, False
        otherwise.
        """

        thrCurrent = currentThread()

        self._lock()
        try:

            if self.__log: self._log("acquiring shared")
            if self.__debug:
                assert self._invariant(), "SharedLock invariant failed: %s in %s" % \
                                          (self._debug_dump(), trace_string())

            # this thread already has shared lock, the count is incremented

            if thrCurrent in self.dicUsers: 
                self.dicUsers[thrCurrent] += 1
                if self.__debug:
                    assert self._invariant(), "SharedLock invariant failed: %s in %s" % \
                                              (self._debug_dump(), trace_string())
                if self.__log: self._log("acquired shared")
                return True

            # this thread already has exclusive lock, now it also has shared

            elif thrCurrent is self.thrOwner: 
                if thrCurrent in self.dicUsers:
                    self.dicUsers[thrCurrent] += 1
                else:
                    self.dicUsers[thrCurrent] = 1
                if self.__debug:
                    assert self._invariant(), "SharedLock invariant failed: %s in %s" % \
                                              (self._debug_dump(), trace_string())
                if self.__log: self._log("acquired shared")
                return True

            # a thread acquires shared lock whenever there is no owner
            # nor pending owners (to prevent owners starvation)

            elif not self._has_owner() and not self._has_pending_owners():
                self.dicUsers[thrCurrent] = 1
                if self.__debug:
                    assert self._invariant(), "SharedLock invariant failed: %s in %s" % \
                                              (self._debug_dump(), trace_string())
                if self.__log: self._log("acquired shared")
                return True

            # otherwise the thread registers itself as a pending user

            else:

                evtEvent = self._pick_event()
                self.lstUsers.append((thrCurrent, evtEvent, 1))

            if self.__debug:
                assert self._invariant(), "SharedLock invariant failed: %s in %s" % \
                                          (self._debug_dump(), trace_string())
            if self.__log: self._log("waiting for shared")

        finally:
            self._unlock()

        return self._acquire_event(evtEvent, timeout) # the thread waits for a lock release
示例#13
0
    def acquire(self, timeout = None):
        """
        Attempts to acquire the lock exclusively within the optional timeout.
        If the timeout is not specified, waits for the lock infinitely.
        Returns True if the lock has been acquired, False otherwise.
        """

        thrCurrent = currentThread()

        self._lock()
        try:

            if self.__log: self._log("acquiring exclusive")
            if self.__debug:
                assert self._invariant(), "SharedLock invariant failed: %s in %s" % \
                                          (self._debug_dump(), trace_string())

            # this thread already has exclusive lock, the count is incremented

            if thrCurrent is self.thrOwner:

                self.intOwnerDepth += 1
                if self.__debug:
                    assert self._invariant(), "SharedLock invariant failed: %s in %s" % \
                                              (self._debug_dump(), trace_string())
                if self.__log: self._log("acquired exclusive")
                return True

            # this thread already has shared lock, this is the most complicated case

            elif thrCurrent in self.dicUsers:
                
                # the thread gets exclusive lock immediately if there is no other threads

                if self.dicUsers.keys() == [thrCurrent] \
                and not self._has_pending_users() and not self._has_pending_owners():
                    
                    self.thrOwner = thrCurrent
                    self.intOwnerDepth = 1
                    if self.__debug:
                        assert self._invariant(), "SharedLock invariant failed: %s in %s" % \
                                                  (self._debug_dump(), trace_string())
                    if self.__log: self._log("acquired exclusive")
                    return True

                # the thread releases its shared lock in hope for the future
                # exclusive one

                intSharedDepth = self.dicUsers.pop(thrCurrent) # that many times it had shared lock

                evtEvent = self._pick_event()
                self.lstOwners.append((thrCurrent, evtEvent, intSharedDepth)) # it will be given them back

                self._release_threads()

            # a thread acquires exclusive lock whenever there is no
            # current owner nor running users

            elif not self._has_owner() and not self._has_users():

                self.thrOwner = thrCurrent
                self.intOwnerDepth = 1
                if self.__debug:
                    assert self._invariant(), "SharedLock invariant failed: %s in %s" % \
                                              (self._debug_dump(), trace_string())
                if self.__log: self._log("acquired exclusive")
                return True

            # otherwise the thread registers itself as a pending owner with no
            # prior record of holding shared lock

            else: 

                evtEvent = self._pick_event()
                self.lstOwners.append((thrCurrent, evtEvent, 0))

            if self.__debug:
                assert self._invariant(), "SharedLock invariant failed: %s in %s" % \
                                          (self._debug_dump(), trace_string())
            if self.__log: self._log("waiting for exclusive")

        finally:
            self._unlock()

        return self._acquire_event(evtEvent, timeout) # the thread waits for a lock release
示例#14
0
    def _acquire_event(self, _evtEvent, timeout): # puts the thread to sleep until the
                                                  # lock is acquired or timeout elapses

        if timeout is None:
            _evtEvent.wait()
            result = True
        else:
            _evtEvent.wait(timeout)
            result = _evtEvent.isSet()

        thrCurrent = currentThread()

        self._lock()
        try:

            # even if result indicates failure, the thread might still be having
            # the lock (race condition between the isSet() and _lock() above)

            if not result:
                result = _evtEvent.isSet()

            # if the lock has not been acquired, the thread must be removed from
            # the pending list it's on. in case the thread was waiting for the
            # exclusive lock and it previously had shared locks, it's put to sleep
            # again this time infinitely (!), waiting for its shared locks back

            boolReAcquireShared = False

            if not result: # the thread has failed to acquire the lock
                
                for i, (thrUser, evtEvent, intSharedDepth) in enumerate(self.lstUsers):
                    if thrUser is thrCurrent and evtEvent is _evtEvent:
                        assert intSharedDepth == 1
                        del self.lstUsers[i]
                        break
                else:
                    for i, (thrOwner, evtEvent, intSharedDepth) in enumerate(self.lstOwners):
                        if thrOwner is thrCurrent and evtEvent is _evtEvent:
                            del self.lstOwners[i]
                            if intSharedDepth > 0:
                                if not self._has_owner():
                                    self.dicUsers[thrCurrent] = intSharedDepth
                                else:
                                    self.lstUsers.append((thrCurrent, _evtEvent, intSharedDepth))
                                    boolReAcquireShared = True
                            break
                    else:
                        assert False, "Invalid thread for %s in %s" % \
                                      (self._debug_dump(), trace_string())

                # if a thread has failed to acquire a lock, it's identical as if it had
                # it and then released, therefore other threads should be released now

                self._release_threads()

            if not boolReAcquireShared:
                _evtEvent.clear()
                self._unpick_event(_evtEvent)

            if self.__debug:
                assert self._invariant(), "SharedLock invariant failed: %s in %s" % \
                                          (self._debug_dump(), trace_string())

            if result:
                if self.__log: self._log("acquired")
            else:
                if self.__log: self._log("timed out in %.02f second(s) waiting for" % timeout)
                if boolReAcquireShared:
                    if self.__log: self._log("acquiring %d previously owned shared lock(s) for" % intSharedDepth)

        finally:
            self._unlock()

        if boolReAcquireShared:
            assert self._acquire_event(_evtEvent, None)
            return False

        return result
示例#15
0
    def _acquire_event(self, _evtEvent,
                       timeout):  # puts the thread to sleep until the
        # lock is acquired or timeout elapses

        if timeout is None:
            _evtEvent.wait()
            result = True
        else:
            _evtEvent.wait(timeout)
            result = _evtEvent.isSet()

        thrCurrent = currentThread()

        self._lock()
        try:

            # even if result indicates failure, the thread might still be having
            # the lock (race condition between the isSet() and _lock() above)

            if not result:
                result = _evtEvent.isSet()

            # if the lock has not been acquired, the thread must be removed from
            # the pending list it's on. in case the thread was waiting for the
            # exclusive lock and it previously had shared locks, it's put to sleep
            # again this time infinitely (!), waiting for its shared locks back

            boolReAcquireShared = False

            if not result:  # the thread has failed to acquire the lock

                for i, (thrUser, evtEvent,
                        intSharedDepth) in enumerate(self.lstUsers):
                    if thrUser is thrCurrent and evtEvent is _evtEvent:
                        assert intSharedDepth == 1
                        del self.lstUsers[i]
                        break
                else:
                    for i, (thrOwner, evtEvent,
                            intSharedDepth) in enumerate(self.lstOwners):
                        if thrOwner is thrCurrent and evtEvent is _evtEvent:
                            del self.lstOwners[i]
                            if intSharedDepth > 0:
                                if not self._has_owner():
                                    self.dicUsers[thrCurrent] = intSharedDepth
                                else:
                                    self.lstUsers.append(
                                        (thrCurrent, _evtEvent,
                                         intSharedDepth))
                                    boolReAcquireShared = True
                            break
                    else:
                        assert False, "Invalid thread for %s in %s" % \
                                      (self._debug_dump(), trace_string())

                # if a thread has failed to acquire a lock, it's identical as if it had
                # it and then released, therefore other threads should be released now

                self._release_threads()

            if not boolReAcquireShared:
                _evtEvent.clear()
                self._unpick_event(_evtEvent)

            if self.__debug:
                assert self._invariant(), "SharedLock invariant failed: %s in %s" % \
                                          (self._debug_dump(), trace_string())

            if result:
                if self.__log: self._log("acquired")
            else:
                if self.__log:
                    self._log("timed out in %.02f second(s) waiting for" %
                              timeout)
                if boolReAcquireShared:
                    if self.__log:
                        self._log(
                            "acquiring %d previously owned shared lock(s) for"
                            % intSharedDepth)

        finally:
            self._unlock()

        if boolReAcquireShared:
            assert self._acquire_event(_evtEvent, None)
            return False

        return result
示例#16
0
    def acquire(self, timeout=None):
        """
        Attempts to acquire the lock exclusively within the optional timeout.
        If the timeout is not specified, waits for the lock infinitely.
        Returns True if the lock has been acquired, False otherwise.
        """

        thrCurrent = currentThread()

        self._lock()
        try:

            if self.__log: self._log("acquiring exclusive")
            if self.__debug:
                assert self._invariant(), "SharedLock invariant failed: %s in %s" % \
                                          (self._debug_dump(), trace_string())

            # this thread already has exclusive lock, the count is incremented

            if thrCurrent is self.thrOwner:

                self.intOwnerDepth += 1
                if self.__debug:
                    assert self._invariant(), "SharedLock invariant failed: %s in %s" % \
                                              (self._debug_dump(), trace_string())
                if self.__log: self._log("acquired exclusive")
                return True

            # this thread already has shared lock, this is the most complicated case

            elif thrCurrent in self.dicUsers:

                # the thread gets exclusive lock immediately if there is no other threads

                if self.dicUsers.keys() == [thrCurrent] \
                and not self._has_pending_users() and not self._has_pending_owners():

                    self.thrOwner = thrCurrent
                    self.intOwnerDepth = 1
                    if self.__debug:
                        assert self._invariant(), "SharedLock invariant failed: %s in %s" % \
                                                  (self._debug_dump(), trace_string())
                    if self.__log: self._log("acquired exclusive")
                    return True

                # the thread releases its shared lock in hope for the future
                # exclusive one

                intSharedDepth = self.dicUsers.pop(
                    thrCurrent)  # that many times it had shared lock

                evtEvent = self._pick_event()
                self.lstOwners.append(
                    (thrCurrent, evtEvent,
                     intSharedDepth))  # it will be given them back

                self._release_threads()

            # a thread acquires exclusive lock whenever there is no
            # current owner nor running users

            elif not self._has_owner() and not self._has_users():

                self.thrOwner = thrCurrent
                self.intOwnerDepth = 1
                if self.__debug:
                    assert self._invariant(), "SharedLock invariant failed: %s in %s" % \
                                              (self._debug_dump(), trace_string())
                if self.__log: self._log("acquired exclusive")
                return True

            # otherwise the thread registers itself as a pending owner with no
            # prior record of holding shared lock

            else:

                evtEvent = self._pick_event()
                self.lstOwners.append((thrCurrent, evtEvent, 0))

            if self.__debug:
                assert self._invariant(), "SharedLock invariant failed: %s in %s" % \
                                          (self._debug_dump(), trace_string())
            if self.__log: self._log("waiting for exclusive")

        finally:
            self._unlock()

        return self._acquire_event(
            evtEvent, timeout)  # the thread waits for a lock release
示例#17
0
    def acquire_shared(self, timeout=None):
        """
        Attempts to acquire the lock in shared mode within the optional 
        timeout. If the timeout is not specified, waits for the lock
        infinitely. Returns True if the lock has been acquired, False
        otherwise.
        """

        thrCurrent = currentThread()

        self._lock()
        try:

            if self.__log: self._log("acquiring shared")
            if self.__debug:
                assert self._invariant(), "SharedLock invariant failed: %s in %s" % \
                                          (self._debug_dump(), trace_string())

            # this thread already has shared lock, the count is incremented

            if thrCurrent in self.dicUsers:
                self.dicUsers[thrCurrent] += 1
                if self.__debug:
                    assert self._invariant(), "SharedLock invariant failed: %s in %s" % \
                                              (self._debug_dump(), trace_string())
                if self.__log: self._log("acquired shared")
                return True

            # this thread already has exclusive lock, now it also has shared

            elif thrCurrent is self.thrOwner:
                if thrCurrent in self.dicUsers:
                    self.dicUsers[thrCurrent] += 1
                else:
                    self.dicUsers[thrCurrent] = 1
                if self.__debug:
                    assert self._invariant(), "SharedLock invariant failed: %s in %s" % \
                                              (self._debug_dump(), trace_string())
                if self.__log: self._log("acquired shared")
                return True

            # a thread acquires shared lock whenever there is no owner
            # nor pending owners (to prevent owners starvation)

            elif not self._has_owner() and not self._has_pending_owners():
                self.dicUsers[thrCurrent] = 1
                if self.__debug:
                    assert self._invariant(), "SharedLock invariant failed: %s in %s" % \
                                              (self._debug_dump(), trace_string())
                if self.__log: self._log("acquired shared")
                return True

            # otherwise the thread registers itself as a pending user

            else:

                evtEvent = self._pick_event()
                self.lstUsers.append((thrCurrent, evtEvent, 1))

            if self.__debug:
                assert self._invariant(), "SharedLock invariant failed: %s in %s" % \
                                          (self._debug_dump(), trace_string())
            if self.__log: self._log("waiting for shared")

        finally:
            self._unlock()

        return self._acquire_event(
            evtEvent, timeout)  # the thread waits for a lock release
示例#18
0
 def _log(self, s):
     thrCurrent = currentThread()
     self.__log("%s @ %.08x %s %s @ %.08x in %s" 
               % (thrCurrent.getName(), id(thrCurrent), s, 
                  self._debug_dump(), id(self), trace_string()))
    def _execute_sql(self, sql, params):

        try:
            sql, params = self._convert_to_qmarks(sql, params)
            param_list = ", ".join(map(lambda t_s_v: "{0:s}({1:s})".\
                                       format(t_s_v[0], isinstance(t_s_v[2], str)
                                                        and "'{0:s}'".format(t_s_v[2])
                                                        or str(t_s_v[2])), params))
        except:
            ResourceError.rethrow(recoverable = True, terminal = False)

        pmnc.log.info(">> {0:s}".format(sql))
        if param_list:
            if pmnc.log.debug:
                pmnc.log.debug("-- {0:s} -- ({1:s})".format(sql, param_list))

        records = []
        try:

            command = com_client.Dispatch("ADODB.Command")
            command.CommandText = sql
            command.CommandType = 1 # adCmdText

            for i, (param_type, param_size, param_value) in enumerate(params):
                param = command.CreateParameter(None, ADODataTypes[param_type], 1, # adParamInput
                                                param_size, param_value)
                if param_type in ("adDecimal", "adNumeric"):
                    param.Precision = self.precision
                    param.NumericScale = self.scale
                command.Parameters.Append(param)

            command.ActiveConnection = self._connection
            command.Prepared = True

            recordset = command.Execute()[0]

            if recordset.State == 1: # adStateOpen
                try:
                    while not recordset.EOF:
                        records.append({ field.Name: TypeValueWrapper((field.Type, field.Value))
                                         for field in recordset.Fields })
                        recordset.MoveNext()
                finally:
                    recordset.Close()
                pmnc.log.info("<< OK, {0:d} record(s)".format(len(records)))
            else:
                pmnc.log.info("<< OK")

        except com_error:
            tb, code, state, description = self._extract_adodb_error()
            state_brace = " [{0:s}]".format(state) if state is not None else ""
            pmnc.log.warning("<< {0:s}{1:s} !! ADODB_Error(\"{2:d}:{3:s} {4:s}\") in {5:s}".\
                             format(sql, " -- ({0:s})".format(param_list) if param_list else "",
                                    code, state_brace, description, trace_string()))
            SQLResourceError.rethrow(
                    code = code, state = state, description = description,
                    recoverable = True, terminal = state[:2] not in self._safe_states)
        except:
            pmnc.log.warning("<< {0:s}{1:s} !! {2:s}".\
                             format(sql, " -- ({0:s})".format(param_list)
                                    if param_list else "", exc_string()))
            ResourceError.rethrow(recoverable = True)
        else:
            return records