当前位置: 首页>>代码示例>>Python>>正文


Python DeferredLock.release方法代码示例

本文整理汇总了Python中twisted.internet.defer.DeferredLock.release方法的典型用法代码示例。如果您正苦于以下问题:Python DeferredLock.release方法的具体用法?Python DeferredLock.release怎么用?Python DeferredLock.release使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在twisted.internet.defer.DeferredLock的用法示例。


在下文中一共展示了DeferredLock.release方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: Client

# 需要导入模块: from twisted.internet.defer import DeferredLock [as 别名]
# 或者: from twisted.internet.defer.DeferredLock import release [as 别名]
class Client(object):
    def __init__(self, specFilename, exchange='signals'):
        self.exchange = exchange
        spec = txamqp.spec.load(specFilename)

        delegate = TwistedDelegate()
        self.clientConnected = ClientCreator(reactor, AMQClient,
                                             delegate=delegate, vhost="/",
                                     spec=spec).connectTCP("localhost", 5672)
        self.conn = None
        self.chan = None
        self.finishLock = DeferredLock()

    @inlineCallbacks
    def finishChannelOpen(self):
        yield self.finishLock.acquire()
        if self.conn is None:
            print "opening connection for", self
            self.conn = yield self.clientConnected

            authentication = {"LOGIN": "guest", "PASSWORD": "guest"}
            yield self.conn.start(authentication)

        if self.chan is None:
            self.chan = yield self.conn.channel(1)
            yield self.chan.channel_open()
            yield self.newChan()
            print "made channel for", self
        self.finishLock.release()
            
    def newChan(self):
        # called once when the new channel is opened
        return succeed(None)
开发者ID:drewp,项目名称:magma,代码行数:35,代码来源:mqclient.py

示例2: NotificationConnector

# 需要导入模块: from twisted.internet.defer import DeferredLock [as 别名]
# 或者: from twisted.internet.defer.DeferredLock import release [as 别名]
class NotificationConnector(object):
    """Provide ready-to-use AMQP channels."""

    def __init__(self, service, clock=reactor):
        """
        @param service: An object implementing the same whenConnected() API as
            the twisted.application.internet.ClientService class.
        @param clock: An object implementing IReactorTime.
        """
        self._service = service
        self._clock = clock
        self._channel = None
        self._channel_lock = DeferredLock()

    @inlineCallbacks
    def __call__(self):
        """
        @return: A deferred firing with a ready-to-use txamqp.protocol.Channel.
        """
        # Serialize calls, in order to setup new channels only once.
        yield self._channel_lock.acquire()
        try:
            if self._channel and self._channel.client.closed:
                # If we have a client but it's closed, let's wait for it to be
                # fully disconnected and spin a reactor iteration to give
                # change to the AMQClient.connectionLost callback chain to
                # settle (in particular our ClientService will be notified and
                # will start connecting again).
                yield self._channel.client.disconnected.wait()
                yield deferLater(self._clock, 0, lambda: None)

            client = yield self._service.whenConnected()
            channel = yield client.channel(1)
            # Check if we got a new channel, and initialize it if so.
            if channel is not self._channel:
                self._channel = channel
                yield self._channel.channel_open()
                # This tells the broker to deliver us at most one message at
                # a time to support using multiple processes (e.g. in a
                # load-balanced/HA deployment). If NotificationSource.get()
                # gets called against the same UUID first by process A and then
                # when it completes by process B, we're guaranteed that process
                # B will see the very next message in the queue, because
                # process A hasn't fetched any more messages than the one it
                # received. See #729140.
                yield self._channel.basic_qos(prefetch_count=1)
        finally:
            self._channel_lock.release()
        returnValue(self._channel)
开发者ID:CanonicalLtd,项目名称:txlongpoll,代码行数:51,代码来源:notification.py

示例3: emailer

# 需要导入模块: from twisted.internet.defer import DeferredLock [as 别名]
# 或者: from twisted.internet.defer.DeferredLock import release [as 别名]
class emailer( LabradServer ):
    name = 'Email Server'
    
    @inlineCallbacks
    def initServer( self ):
        self.username, self.fromaddr, self.password = yield self.getInfoReg()
        self.password = base64.b64decode(self.password)
        self.toaddrs = {}
        self.smtp = 'smtp.gmail.com:587'
        self.sending = DeferredLock()
    
    @inlineCallbacks
    def getInfoReg(self):
        reg = self.client.registry
        yield reg.cd(['Servers','Email Server'])
        username = yield reg.get('username')
        fromaddr = yield reg.get('address')
        password = yield reg.get('password')
        returnValue([username,fromaddr,password])
        
    @setting(0, "Set Recipients", recepients = '*s', returns = '')
    def setRecepients(self, c, recepients):
        """Set the recipients of the email as a list of strings of email addresses"""
        self.toaddrs[c.ID] = recepients
    
    @setting(1, "Send", subject = 's', message = 's', returns = '')
    def selectDP(self, c, subject, message):
        """Select Double Pass in the current context"""
        if not self.toaddrs[c.ID]: raise Exception("Recipients not set")
        yield self.sending.acquire()  
        session = smtplib.SMTP(self.smtp)
        session.starttls()
        session.login(self.username,self.password)
        toaddrs = self.toaddrs[c.ID]
        msg = MIMEMultipart()
        msg['From'] = self.fromaddr
        msg['To'] = COMMASPACE.join(toaddrs)
        msg['Subject'] = subject
        msg.attach(MIMEText(message, 'plain'))    
        session.sendmail(self.fromaddr, toaddrs, msg.as_string())
        session.quit()
        self.sending.release()
    
    def initContext(self, c):
        """Initialize a new context object."""
        pass
    
    def expireContext(self, c):
        del(self.toaddrs[c.ID])
开发者ID:HaeffnerLab,项目名称:HaeffnerLabLattice,代码行数:51,代码来源:emailer.py

示例4: __init__

# 需要导入模块: from twisted.internet.defer import DeferredLock [as 别名]
# 或者: from twisted.internet.defer.DeferredLock import release [as 别名]
class _DhcpSetterCommon:
    # Provides support common code for shutting down on shutdown, and
    # handles locking.
    def __init__(self):
        self._lock = DeferredLock()
        self.is_shutdown = False
        reactor.addSystemEventTrigger('before', 'shutdown', self._shutdown)
    
    @inlineCallbacks
    def _cb(self, old_state, new_state):
        if self.is_shutdown:
            return
        yield self._lock.acquire()
        try:
            yield self._locked_cb(old_state, new_state)
        finally:
            self._lock.release()
    
    @inlineCallbacks
    def _shutdown(self):
        #print "Shutdown", self
        yield self._cb(None, None)
        self.is_shutdown = True
开发者ID:PR2,项目名称:linux_networking,代码行数:25,代码来源:dhcp_apply_config.py

示例5: __init__

# 需要导入模块: from twisted.internet.defer import DeferredLock [as 别名]
# 或者: from twisted.internet.defer.DeferredLock import release [as 别名]
class InterfaceUpper:
    def __init__(self, iface):
        self.iface = iface
        self._lock = DeferredLock()
        CompositeStatePublisher(lambda x: x, [
            netlink_monitor.get_state_publisher(iface, IFSTATE.PLUGGED),
            netlink_monitor.get_state_publisher(iface, IFSTATE.UP),
        ]).subscribe(self._cb)
        self._is_shutdown = False
        self.state = None
        reactor.addSystemEventTrigger('before', 'shutdown', self._shutdown)
   
    @inlineCallbacks
    def restart(self):
        yield self._lock.acquire()
        try:
            yield system.system('ifconfig', self.iface, '0.0.0.0')
            yield system.system('ifconfig', self.iface, 'down')
        finally:
            self._lock.release()

    @inlineCallbacks
    def _cb(self, old_state, new_state):
        plugged, up = new_state
        self.state = new_state
        if plugged and not up and not self._is_shutdown:
            yield self._lock.acquire()
            try:
                yield system.system('ifconfig', self.iface, 'up')
            finally:
                self._lock.release()

    @inlineCallbacks
    def _shutdown(self):
        self._is_shutdown = True
        if self.state:
            yield self.restart()
开发者ID:PR2,项目名称:linux_networking,代码行数:39,代码来源:interface_upper.py

示例6: Pulser_729

# 需要导入模块: from twisted.internet.defer import DeferredLock [as 别名]
# 或者: from twisted.internet.defer.DeferredLock import release [as 别名]
class Pulser_729(LabradServer):
    
    name = 'Pulser_729'
       
    def initServer(self):
        self.api  = api()
        self.inCommunication = DeferredLock()
        self.initializeBoard()
    
    def initializeBoard(self):
        connected = self.api.connectOKBoard()
        if not connected:
            raise Exception("Pulser Not Found")
    
    @setting(0, 'Reset DDS', returns = '')
    def resetDDS(self , c):
        """
        Reset the ram position to 0
        """
        yield self.inCommunication.acquire()
        yield deferToThread(self.api.resetAllDDS)
        self.inCommunication.release()
        
    @setting(1, "Program DDS", program = '*(is)', returns = '')
    def programDDS(self, c, program):
        """
        Programs the DDS, the input is a tuple of channel numbers and buf objects for the channels
        """
        yield self.inCommunication.acquire()
        yield deferToThread(self._programDDSSequence, program)
        self.inCommunication.release()
    
    @setting(2, "Reinitialize DDS", returns = '')
    def reinitializeDDS(self, c):
        """
        Reprograms the DDS chip to its initial state
        """
        yield self.inCommunication.acquire()
        yield deferToThread(self.api.initializeDDS)
        self.inCommunication.release()
    
    def _programDDSSequence(self, program):
        '''takes the parsed dds sequence and programs the board with it'''
        for chan, buf in program:
            self.api.setDDSchannel(chan)
            self.api.programDDS(buf)
        self.api.resetAllDDS()
    
    def wait(self, seconds, result=None):
        """Returns a deferred that will be fired later"""
        d = Deferred()
        reactor.callLater(seconds, d.callback, result)
        return d
开发者ID:ahusain,项目名称:Haeffner-Lab-LabRAD-Tools,代码行数:55,代码来源:pulser_729.py

示例7: Dataset

# 需要导入模块: from twisted.internet.defer import DeferredLock [as 别名]
# 或者: from twisted.internet.defer.DeferredLock import release [as 别名]
class Dataset(QtCore.QObject):
    
    def __init__(self, data_vault, context, dataset_location,reactor):
        super(Dataset, self).__init__()
        self.data = None
        self.accessingData = DeferredLock()
        self.reactor = reactor
        self.dataset_location = dataset_location
        self.data_vault = data_vault
        self.updateCounter = 0
        self.context = context
        self.connectDataVault()
        self.setupListeners()

    @inlineCallbacks
    def connectDataVault(self):
        yield self.data_vault.cd(self.dataset_location[0], context = self.context)
        path, dataset_name = yield self.data_vault.open(self.dataset_location[1], context = self.context)
        self.dataset_name = dataset_name

    @inlineCallbacks
    def setupListeners(self):
        yield self.data_vault.signal__data_available(11111, context = self.context)
        yield self.data_vault.addListener(listener = self.updateData, source = None, ID = 11111, context = self.context)


    @inlineCallbacks
    def openDataset(self):
        yield self.data_vault.cd(self.dataset_location[0], context = self.context)
        yield self.data_vault.open(self.dataset_location[1], context = self.context)

    @inlineCallbacks
    def getParameters(self):
        parameters = yield self.data_vault.parameters(context = self.context)
        parameterValues = []
        for parameter in parameters:
            parameterValue = yield self.data_vault.get_parameter(parameter, context = self.context)
            parameterValues.append( (parameter, parameterValue) )
        returnValue(parameterValues)

    def updateData(self, x, y):
        self.updateCounter += 1
        self.getData()

    @inlineCallbacks
    def getData(self):
        Data = yield self.data_vault.get(100, context = self.context)
        if (self.data == None):
            yield self.accessingData.acquire()
            try:
                self.data = Data.asarray
            except:
                self.data = Data
            self.accessingData.release()
        else:
            yield self.accessingData.acquire()
            try:
                self.data = np.append(self.data, Data.asarray, 0)
            except:
                self.data = np.append(self.data, Data, 0)
            self.accessingData.release()

    @inlineCallbacks
    def getLabels(self):
        labels = []
        yield self.openDataset()
        variables = yield self.data_vault.variables(context = self.context)
        for i in range(len(variables[1])):
            labels.append(variables[1][i][1] + ' - ' + self.dataset_name)
        returnValue(labels)

    @inlineCallbacks
    def disconnectDataSignal(self):
        yield self.data_vault.removeListener(listener = self.updateData, source = None, ID = 11111, context = self.context)
开发者ID:HaeffnerLab,项目名称:Haeffner-Lab-LabRAD-Tools,代码行数:76,代码来源:Dataset.py

示例8: DAC

# 需要导入模块: from twisted.internet.defer import DeferredLock [as 别名]
# 或者: from twisted.internet.defer.DeferredLock import release [as 别名]
class DAC(LabradServer):
    
    name = 'DAC'
    onNewVoltage = Signal(123556, 'signal: new voltage', '(sv)')
    
    @inlineCallbacks
    def initServer(self):
        self.api_dac  = api_dac()
        self.inCommunication = DeferredLock()
        connected = self.api_dac.connectOKBoard()
        if not connected:
            raise Exception ("Could not connect to DAC")
        self.d = yield self.initializeDAC()
        self.listeners = set()     
    
    @inlineCallbacks
    def initializeDAC(self):
        '''creates dictionary for information storage'''
        d = {}
        for name,channel_number,min_voltage,vpp in [
                             ('comp1', 0, -40.0, 80.0),
                             ('comp2', 1, -40.0, 80.0),
                             ('endcap1', 2, -9.9552, 20.0),
                             ('endcap2', 3, -9.9561, 20.0),
                             ]:
            chan = dac_channel(name, channel_number, min_voltage, vpp)
            chan.voltage = yield self.getRegValue(name)
            d[name] = chan
            value = self.voltage_to_val(chan.voltage, chan.min_voltage, chan.vpp)
            yield self.do_set_voltage(channel_number, value)
        returnValue( d )
    
    @inlineCallbacks
    def getRegValue(self, name):
        yield self.client.registry.cd(['','Servers', 'DAC'], True)
        try:
            voltage = yield self.client.registry.get(name)
        except Exception:
            print '{} not found in registry'.format(name)
            voltage = 0
        returnValue(voltage)
            
    @setting(0, "Set Voltage",channel = 's', voltage = 'v[V]', returns = '')
    def setVoltage(self, c, channel, voltage):
        try:
            chan = self.d[channel]
            minim,total,channel_number = chan.min_voltage, chan.vpp, chan.channel_number
        except KeyError:
            raise Exception ("Channel {} not found".format(channel))
        voltage = voltage['V']
        value = self.voltage_to_val(voltage, minim, total)
        yield self.do_set_voltage(channel_number, value)
        chan.voltage = voltage
        self.notifyOtherListeners(c, (channel, voltage), self.onNewVoltage)
    
    @inlineCallbacks
    def do_set_voltage(self, channel_number, value):
        yield self.inCommunication.acquire()
        try:
            yield deferToThread(self.api_dac.setVoltage, channel_number, value)
            confirmation = yield deferToThread(self.api_dac.getVoltage, channel_number)
            print 'setting value', value
            if not value == confirmation:
                raise Exception("Board did not set the voltage not set properly")
        except Exception as e:
            raise e
        finally:
            self.inCommunication.release()
        
    def voltage_to_val(self, voltage, minim, total, prec = 16):
        '''converts voltage of a channel to FPGA-understood sequential value'''
        value = int((voltage - minim) / total * (2 ** prec  - 1) )
        if not  0 <= value <= 2**16 - 1: raise Exception ("Voltage Out of Range")
        return value
           
    @setting(1, "Get Voltage", channel = 's', returns = 'v[V]')
    def getVoltage(self, c, channel):
        try:
            voltage = self.d[channel].voltage
        except KeyError:
            raise Exception ("Channel {} not found".format(channel))
        return WithUnit(voltage, 'V')
    
    @setting(2, "Get Range", channel = 's', returns = '(v[V]v[V])')
    def getRange(self, c, channel):
        try:
            chan = self.d[channel]
            minim,maxim = chan.min_voltage,chan.max_voltage
        except KeyError:
            raise Exception ("Channel {} not found".format(channel))
        return (WithUnit(minim,'V'), WithUnit(maxim, 'V'))
    
    def notifyOtherListeners(self, context, message, f):
        """
        Notifies all listeners except the one in the given context, executing function f
        """
        notified = self.listeners.copy()
        notified.remove(context.ID)
        f(message,notified)
    
#.........这里部分代码省略.........
开发者ID:HaeffnerLab,项目名称:HaeffnerLabLattice,代码行数:103,代码来源:dac.py

示例9: Pulser

# 需要导入模块: from twisted.internet.defer import DeferredLock [as 别名]
# 或者: from twisted.internet.defer.DeferredLock import release [as 别名]
class Pulser(DDS, LineTrigger):
    
    name = 'Pulser'
    onSwitch = Signal(611051, 'signal: switch toggled', '(ss)')
    
    #@inlineCallbacks
    def initServer(self):
        self.api  = api()
        self.channelDict = hardwareConfiguration.channelDict
        self.collectionTime = hardwareConfiguration.collectionTime
        self.collectionMode = hardwareConfiguration.collectionMode
        self.sequenceType = hardwareConfiguration.sequenceType
        self.isProgrammed = hardwareConfiguration.isProgrammed
        self.timeResolution = float(hardwareConfiguration.timeResolution)
        self.ddsDict = hardwareConfiguration.ddsDict
        self.timeResolvedResolution = hardwareConfiguration.timeResolvedResolution
        self.remoteChannels = hardwareConfiguration.remoteChannels
        self.collectionTimeRange = hardwareConfiguration.collectionTimeRange
        self.sequenceTimeRange = hardwareConfiguration.sequenceTimeRange
        self.haveSecondPMT = hardwareConfiguration.secondPMT
        self.haveDAC = hardwareConfiguration.DAC
        self.inCommunication = DeferredLock()
        self.clear_next_pmt_counts = 0
        self.hwconfigpath = os.path.dirname(inspect.getfile(hardwareConfiguration))
        print self.hwconfigpath
        #LineTrigger.initialize(self)
        #self.initializeBoard()
        #yield self.initializeRemote()
        #self.initializeSettings()
        #yield self.initializeDDS()
        self.ddsLock = True
        self.listeners = set()

    def initializeBoard(self):
        connected = self.api.connectOKBoard()
        if not connected:
            raise Exception ("Pulser Not Found")
            
    def initializeSettings(self):
        for channel in self.channelDict.itervalues():
            channelnumber = channel.channelnumber
            if channel.ismanual:
                state = self.cnot(channel.manualinv, channel.manualstate)
                self.api.setManual(channelnumber, state)
            else:
                self.api.setAuto(channelnumber, channel.autoinv)
    
    @inlineCallbacks
    def initializeRemote(self):
        self.remoteConnections = {}
        if len(self.remoteChannels):
            from labrad.wrappers import connectAsync
            for name,rc in self.remoteChannels.iteritems():
                try:
                    self.remoteConnections[name] = yield connectAsync(rc.ip)
                    print 'Connected to {}'.format(name)
                except:
                    print 'Not Able to connect to {}'.format(name)
                    self.remoteConnections[name] = None

    @setting(0, "New Sequence", returns = '')
    def newSequence(self, c):
        """
        Create New Pulse Sequence
        """
        c['sequence'] = Sequence(self)
    
    @setting(1, "Program Sequence", returns = '')
    def programSequence(self, c, sequence):
        """
        Programs Pulser with the current sequence.
        """
        #print "program sequence"
        sequence = c.get('sequence')
        if not sequence: raise Exception("Please create new sequence first")
        dds,ttl = sequence.progRepresentation()
        yield self.inCommunication.acquire()
        yield deferToThread(self.api.programBoard, ttl)
        if dds is not None: yield self._programDDSSequence(dds)
        self.inCommunication.release()
        self.isProgrammed = True
        #self.api.resetAllDDS()
        #print "done programming"

    @setting(37, 'Get dds program representation', returns = '*(ss)')
    def get_dds_program_representation(self,c):   
        sequence = c.get('sequence')
        dds, ttl = sequence.progRepresentation()
        # As labrad cannot handle returnig the bytearray, we convert it to string first
        for key, value in dds.iteritems():
            dds[key] = str(value)
        # It also cannot handle dictionaries, so we recreate it as a list of tuples
        passable = dds.items()
        return passable

    @setting(38, 'Program dds and ttl')
    def program_dds_and_ttl(self,c,dds,ttl):
        dds = bytearray(dds)
        ttl = bytearray(ttl)
        yield self.inCommunication.acquire()
#.........这里部分代码省略.........
开发者ID:Arvad,项目名称:YbDDSControl,代码行数:103,代码来源:DummyPulser.py

示例10: DACServer

# 需要导入模块: from twisted.internet.defer import DeferredLock [as 别名]
# 或者: from twisted.internet.defer.DeferredLock import release [as 别名]

#.........这里部分代码省略.........
    @inlineCallbacks
    def setVoltages(self, c, newPosition = currentPosition, writeSMAs = False):
        n = newPosition
        newVoltageSet = []
        for e in hc.elec_dict.keys():
            av = self.voltageMatrix[e][n]
            newVoltageSet.append( (e, av) )

        # if changing DAC FPGA voltage set, write sma voltages. 
        if writeSMAs: 
            for s in hc.sma_dict.keys(): newVoltageSet.append( (s, self.currentVoltages[s]) )
        yield self.setIndividualAnalogVoltages(c, newVoltageSet)
        newVoltageSet.append(newVoltageSet[len(newVoltageSet)-1])
        self.currentPosition = n

        yield self.registry.cd(self.registryPath + [self.CfileName])
        yield self.registry.set('position', self.currentPosition)

    @inlineCallbacks
    def writeToFPGA(self, c):
        yield self.resetFIFODAC()
        for i in range(len(self.queue.setDict[self.queue.currentSet])):
            v = self.queue.get()            
            yield self.setDACVoltages(v.hexRep)
            print v.channel.name, v.analogVoltage
            self.currentVoltages[v.channel.name] = v.analogVoltage
            self.notifyOtherListeners(c)

    @inlineCallbacks
    def setDACVoltages(self, stringy):
        yield self.inCommunication.acquire()
        yield deferToThread(self.api.setDACVoltage, stringy)
        # self.api.setDACVoltage(stringy)
        self.inCommunication.release()
    
    @inlineCallbacks
    def resetFIFODAC(self):
        yield self.inCommunication.acquire()
        yield deferToThread(self.api.resetFIFODAC)
        # self.api.resetFIFODAC()
        self.inCommunication.release()            

    @setting( 2, "Set Digital Voltages", digitalVoltages = '*v', setNum = 'i', returns = '')
    def setDigitalVoltages( self, c, digitalVoltages, setNum):
        """
        Pass digitalVoltages, a list of digital voltages to update.
        Currently, there must be one for each port.
        """
        l = zip(self.dacDict.keys(), digitalVoltages)
        self.setIndivDigVoltages(c, l, setNum)

    @setting( 3, "Set Analog Voltages", analogVoltages = '*v', setNum = 'i', returns = '')
    def setAnalogVoltages( self, c, analogVoltages, setNum):
        """
        Pass analogVoltages, a list of analog voltages to update.
        Currently, there must be one for each port.
        """
        l = zip(self.dacDict.keys(), analogVoltages)
        yield self.setIndivAnaVoltages(c, l, setNum)

    @setting( 4, "Set Individual Digital Voltages", digitalVoltages = '*(si)', returns = '')
    def setIndividualDigitalVoltages(self, c, digitalVoltages, setNum = 0):
        """
        Pass a list of tuples of the form:
        (portNum, newVolts)
        """
开发者ID:HaeffnerLab,项目名称:sqip,代码行数:70,代码来源:DACServer_old.py

示例11: SqlFuse

# 需要导入模块: from twisted.internet.defer import DeferredLock [as 别名]
# 或者: from twisted.internet.defer.DeferredLock import release [as 别名]

#.........这里部分代码省略.........
        ## xattr back-end. The table uses IDs because they're much shorter than the names.
        ## This code only handles the name/ID caching; actual attribute access is in the inode.

    @inlineCallbacks
    def xattr_name(self, xid, db):
        """\
			xattr key-to-name translation.

			Data consistency states that there must be one.
			"""
        try:
            returnValue(self._xattr_name[xid])
        except KeyError:
            pass

        yield self._xattr_lock.acquire()
        try:
            try:
                returnValue(self._xattr_name[xid])
            except KeyError:
                pass

            name, = yield db.DoFn("select name from xattr_name where id=${xid}", xid=xid)

            self._xattr_name[xid] = name
            self._xattr_id[name] = xid

            def _drop():
                del self._xattr_name[xid]
                del self._xattr_id[name]

            db.call_rolledback(_drop)
        finally:
            self._xattr_lock.release()

        returnValue(name)

    @inlineCallbacks
    def xattr_id(self, name, db, add=False):
        """\
			xattr name-to-key translation.

			Remembers null mappings, or creates a new one if @add is set.
			"""
        if len(name) == 0 or len(name) > self.info.attrnamelen:
            raise IOError(errno.ENAMETOOLONG)
        try:
            returnValue(self._xattr_id[name])
        except KeyError:
            pass

        try:
            yield self._xattr_lock.acquire()

            try:
                returnValue(self._xattr_id[name])
            except KeyError:
                pass

            try:
                xid, = yield db.DoFn("select id from xattr_name where name=${name}", name=name)
            except NoData:
                if not add:
                    self._xattr_id[name] = None
                    returnValue(None)
                xid = yield db.Do("insert into xattr_name(name) values(${name})", name=name)
开发者ID:arielsalvo,项目名称:sqlfuse,代码行数:70,代码来源:main.py

示例12: Agent

# 需要导入模块: from twisted.internet.defer import DeferredLock [as 别名]
# 或者: from twisted.internet.defer.DeferredLock import release [as 别名]

#.........这里部分代码省略.........
                )

    def should_reannounce(self):
        """Small method which acts as a trigger for :meth:`reannounce`"""
        if self.reannounce_lock.locked or self.shutting_down:
            return False

        contacted = config.master_contacted(update=False)
        if contacted is None:
            return True

        return utility.total_seconds(
            datetime.utcnow() - contacted) > config["agent_master_reannounce"]

    @inlineCallbacks
    def reannounce(self, force=False):
        """
        Method which is used to periodically contact the master.  This
        method is generally called as part of a scheduled task.
        """
        # Attempt to acquire the reannounce lock but fail after 70%
        # of the total time between reannouncements elapses.  This should
        # help prevent an accumulation of requests in the event the master
        # is having issues.
        try:
            yield self.reannounce_lock.acquire(
                config["agent_master_reannounce"] * .70
            )
        except utility.LockTimeoutError:
            svclog.debug("Timed out while waiting to acquire reannounce_lock")
            returnValue(None)

        if not self.should_reannounce() and not force:
            yield self.reannounce_lock.release()
            returnValue(None)

        svclog.debug("Announcing %s to master", config["agent_hostname"])
        data = None
        num_retry_errors = 0
        while True:  # for retries
            try:
                response = yield post_direct(
                    self.agent_api(),
                    data={
                        "state": config["state"],
                        "current_assignments": config.get(
                            "current_assignments", {} # may not be set yet
                        ),
                        "free_ram": memory.free_ram(),
                        "disks": disks.disks(as_dict=True)
                    }
                )

            except (ResponseNeverReceived, RequestTransmissionFailed) as error:
                num_retry_errors += 1
                if num_retry_errors > config["broken_connection_max_retry"]:
                    svclog.error(
                        "Failed to announce self to the master, "
                        "caught try-again type errors %s times in a row.",
                        num_retry_errors)
                    break
                else:
                    svclog.debug("While announcing self to master, caught "
                                 "%s. Retrying immediately.",
                                 error.__class__.__name__)
            except Exception as error:
开发者ID:xlhtc007,项目名称:pyfarm-agent,代码行数:70,代码来源:service.py

示例13: TriggerFPGA

# 需要导入模块: from twisted.internet.defer import DeferredLock [as 别名]
# 或者: from twisted.internet.defer.DeferredLock import release [as 别名]
class TriggerFPGA(LabradServer):
    name = 'Trigger'
    onNewUpdate = Signal(SIGNALID, 'signal: switch toggled', '(sb)')
    
    def initServer(self):
        self.inCommunication = DeferredLock()
        self.connectOKBoard()
        #create dictionary for triggers and switches in the form 'trigger':channel;'switch:(channel , logicnotnegated, state'
        #the state written below represents the initial state of the server
        self.dict = {
                     'Triggers':{'PaulBox':0},
                     'Switches':{'866':[0x01,True, True], 'BluePI':[0x02,True, False], '397LocalHeating':[0x04,True,False]}
                     }
        self.initializeChannels()
        self.listeners = set()
        
    def connectOKBoard(self):
        self.xem = None
        fp = ok.FrontPanel()
        module_count = fp.GetDeviceCount()
        print "Found {} unused modules".format(module_count)
        for i in range(module_count):
            serial = fp.GetDeviceListSerial(i)
            tmp = ok.FrontPanel()
            tmp.OpenBySerial(serial)
            id = tmp.GetDeviceID()
            if id == okDeviceID:
                self.xem = tmp
                print 'Connected to {}'.format(id)
                self.programOKBoard(self.xem)
                return
        print 'Not found {}'.format(okDeviceID)
        print 'Will try again in {} seconds'.format(devicePollingPeriod)
        reactor.callLater(devicePollingPeriod, self.connectOKBoard)
    
    def programOKBoard(self, xem):
        print 'Programming FPGA'
        basepath = os.environ.get('LABRADPATH',None)
        if not basepath:
            raise Exception('Please set your LABRADPATH environment variable')
        path = os.path.join(basepath,'sqip/okfpgaservers/trigger.bit')
        prog = xem.ConfigureFPGA(path)
        if prog: raise("Not able to program FPGA")
        pll = ok.PLL22150()
        xem.GetEepromPLL22150Configuration(pll)
        pll.SetDiv1(pll.DivSrc_VCO,4)
        xem.SetPLL22150Configuration(pll)
    
    def initializeChannels(self):
        for switchName in self.dict['Switches'].keys():
            channel = self.dict['Switches'][switchName][0]
            value = self.dict['Switches'][switchName][1]
            initialize = self.dict['Switches'][switchName][2]
            if initialize:
                print 'initializing {0} to {1}'.format(switchName, value)
                self._switch( channel, value)
        
    def _isSequenceDone(self):
        self.xem.UpdateTriggerOuts()
        return self.xem.IsTriggered(0x6A,0b00000001)
    
    def _trigger(self, channel):
        self.xem.ActivateTriggerIn(0x40, channel)
    
    def _switch(self, channel, value):
        if value:
            self.xem.SetWireInValue(0x00,channel,channel)
        else:
            self.xem.SetWireInValue(0x00,0x00,channel)
        self.xem.UpdateWireIns()
    
    @setting(0, 'Get Trigger Channels', returns = '*s')
    def getTriggerChannels(self, c):
        """
        Returns available channels for triggering
        """
        return self.dict['Triggers'].keys()
    
    @setting(1, 'Get Switching Channels', returns = '*s')
    def getSwitchingChannels(self, c):
        """
        Returns available channels for switching
        """
        return self.dict['Switches'].keys()
    
    @setting(2, 'Trigger', channelName = 's')
    def trigger(self, c, channelName):
        """
        Triggers the select channel
        """
        if channelName not in self.dict['Triggers'].keys(): raise Exception("Incorrect Channel")
        yield self.inCommunication.acquire()
        channel = self.dict['Triggers'][channelName]
        yield deferToThread(self._trigger, channel)
        yield self.inCommunication.release()
    
    @setting(3, 'Switch', channelName = 's', state= 'b')
    def switch(self, c, channelName, state):  
        """
        Switches the given channel
#.........这里部分代码省略.........
开发者ID:noli,项目名称:HaeffnerLabSQIP,代码行数:103,代码来源:trigger_ok.py

示例14: FreqCounterFPGA

# 需要导入模块: from twisted.internet.defer import DeferredLock [as 别名]
# 或者: from twisted.internet.defer.DeferredLock import release [as 别名]
class FreqCounterFPGA(LabradServer):
    name = 'FreqCounter'
    
    def initServer(self):
        self.collectionTime = {0:1.0,1:1.0} #default collection times in the format channel:time(sec)
        self.inCommunication = DeferredLock()
        self.connectOKBoard()
    
    def connectOKBoard(self):
        self.xem = None
        fp = ok.FrontPanel()
        module_count = fp.GetDeviceCount()
        print "Found {} unused modules".format(module_count)
        for i in range(module_count):
            serial = fp.GetDeviceListSerial(i)
            tmp = ok.FrontPanel()
            tmp.OpenBySerial(serial)
            id = tmp.GetDeviceID()
            if id == okDeviceID:
                self.xem = tmp
                print 'Connected to {}'.format(id)
                self.programOKBoard(self.xem)
                return
        print 'Not found {}'.format(okDeviceID)
        print 'Will try again in {} seconds'.format(devicePollingPeriod)
        reactor.callLater(devicePollingPeriod, self.connectOKBoard)
    
    def programOKBoard(self, xem):
        print 'Programming FPGA'
        basepath = os.environ.get('LABRADPATH',None)
        if not basepath:
            raise Exception('Please set your LABRADPATH environment variable')
        path = os.path.join(basepath,'lattice/okfpgaservers/freqcounter.bit')
        prog = xem.ConfigureFPGA(path)
        if prog: raise("Not able to program FPGA")
        pll = ok.PLL22150()
        xem.GetEepromPLL22150Configuration(pll)
        pll.SetDiv1(pll.DivSrc_VCO,4)
        xem.SetPLL22150Configuration(pll)
    
    def _resetFIFO(channel, self):
        if channel == 0:
            self.xem.ActivateTriggerIn(0x40,0)
        elif channel == 1:
            self.xem.ActivateTriggerIn(0x40,1)
        
    def _setUpdateTime(self, channel, time):
        if channel == 0:
            self.xem.SetWireInValue(0x01,int(1000 * time))
        elif channel == 1:
            self.xem.SetWireInValue(0x02,int(1000 * time))
        self.xem.UpdateWireIns()
    
    @setting(0, 'Get Channels', returns = '*w')
    def getChannels(self, c):
        """
        Get Available Channels
        """
        return self.collectionTime.keys()
       
    @setting(1, 'Set Collection Time', channel = 'w', time = 'v', returns = '')
    def setCollectTime(self, c, channel, time):
        """
        Set collection time for the given channel
        """
        time = float(time)
        if not 0.0<time<5.0: raise('incorrect collection time')
        if channel not in self.collectionTime.keys(): raise("Incorrect channel")
        self.collectionTime[channel] = time
        yield self.inCommunication.acquire()
        yield deferToThread(self._setUpdateTime, channel, time)
        self.inCommunication.release()

    @setting(2, 'Reset FIFO', channel = 'w', returns = '')
    def resetFIFO(self,c, channel):
        """
        Resets the FIFO on board, deleting all queued counts
        """
        if channel not in self.collectionTime.keys(): raise("Incorrect channel")
        yield self.inCommunication.acquire()
        yield deferToThread(self._resetFIFO, channel)
        self.inCommunication.release()
    
    @setting(3, 'Get All Counts', channel = 'w', returns = '*(vv)')
    def getALLCounts(self, c, channel):
        """
        Returns the list of counts stored on the FPGA in the form (v1,v2) where v1 is the count rate in Hz
        and v2 is the approximate time of acquisition.
        
        NOTE: For some reason, FGPA ReadFromBlockPipeOut never time outs, so can not implement requesting more packets than
        currently stored because it may hang the device.
        """
        if channel not in self.collectionTime.keys(): raise("Incorrect channel")
        yield self.inCommunication.acquire()
        countlist = yield deferToThread(self.doGetAllCounts, channel)
        self.inCommunication.release()
        returnValue(countlist)
        
    def doGetAllCounts(self, channel):
        inFIFO = self._countsInFIFO(channel)
#.........这里部分代码省略.........
开发者ID:HaeffnerLab,项目名称:sqip,代码行数:103,代码来源:frequency_counter_ok.py

示例15: UnitRelationLifecycle

# 需要导入模块: from twisted.internet.defer import DeferredLock [as 别名]
# 或者: from twisted.internet.defer.DeferredLock import release [as 别名]
class UnitRelationLifecycle(object):
    """Unit Relation Lifcycle management.

    Provides for watching related units in a relation, and executing hooks
    in response to changes. The lifecycle is driven by the workflow.

    The Unit relation lifecycle glues together a number of components.
    It controls a watcher that recieves watch events from zookeeper,
    and it controls a hook scheduler which gets fed those events. When
    the scheduler wants to execute a hook, the executor is called with
    the hook path and the hook invoker.

    **Relation hook invocation do not maintain global order or
    determinism across relations**. They only maintain ordering and
    determinism within a relation. A shared scheduler across relations
    would be needed to maintain such behavior.
    """

    def __init__(self, client, unit_name, unit_relation, relation_name, unit_path, executor):
        self._client = client
        self._unit_path = unit_path
        self._relation_name = relation_name
        self._unit_relation = unit_relation
        self._executor = executor
        self._run_lock = DeferredLock()
        self._log = logging.getLogger("unit.relation.lifecycle")
        self._error_handler = None

        self._scheduler = HookScheduler(client,
                                        self._execute_change_hook,
                                        self._unit_relation,
                                        self._relation_name,
                                        unit_name=unit_name)
        self._watcher = None

    @inlineCallbacks
    def _execute_change_hook(self, context, change, hook_name=None):
        """Invoked by the contained HookScheduler, to execute a hook.

        We utilize the HookExecutor to execute the hook, if an
        error occurs, it will be reraised, unless an error handler
        is specified see ``set_hook_error_handler``.
        """
        socket_path = os.path.join(self._unit_path, HOOK_SOCKET_FILE)
        if hook_name is None:
            if change.change_type == "departed":
                hook_names = [
                    "%s-relation-departed" % self._relation_name]
            elif change.change_type == "joined":
                hook_names = [
                    "%s-relation-joined" % self._relation_name,
                    "%s-relation-changed" % self._relation_name]
            else:
                hook_names = ["%s-relation-changed" % self._relation_name]
        else:
            hook_names = [hook_name]

        invoker = RelationInvoker(
            context, change, "constant", socket_path, self._unit_path,
            hook_log)

        for hook_name in hook_names:
            hook_path = os.path.join(
                self._unit_path, "charm", "hooks", hook_name)
            yield self._run_lock.acquire()
            self._log.debug("Executing hook %s", hook_name)
            try:
                yield self._executor(invoker, hook_path)
            except Exception, e:
                yield self._run_lock.release()
                self._log.warn("Error in %s hook: %s", hook_name, e)

                if not self._error_handler:
                    raise
                self._log.info(
                    "Invoked error handler for %s hook", hook_name)
                # We can't hold the run lock, when we invoke the error
                # handler, or we get a deadlock if the handler
                # manipulates the lifecycle.
                yield self._error_handler(change, e)
            else:
                yield self._run_lock.release()
开发者ID:mcclurmc,项目名称:juju,代码行数:84,代码来源:lifecycle.py


注:本文中的twisted.internet.defer.DeferredLock.release方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。