Пример #1
0
def _main_async(reactor, argv=None, _abort_for_test=False):
    if argv is None:
        argv = sys.argv

    if not _abort_for_test:
        # Some log messages would be discarded if we did not set up things early.
        configure_logging()

    # Option parsing is done before importing the main modules so as to avoid the cost of initializing gnuradio if we are aborting early. TODO: Make that happen for createConfig too.
    argParser = argparse.ArgumentParser(prog=argv[0])
    argParser.add_argument('config_path',
                           metavar='CONFIG',
                           help='path of configuration directory or file')
    argParser.add_argument(
        '--create',
        dest='createConfig',
        action='store_true',
        help='write template configuration file to CONFIG and exit')
    argParser.add_argument('-g, --go',
                           dest='openBrowser',
                           action='store_true',
                           help='open the UI in a web browser')
    argParser.add_argument(
        '--force-run',
        dest='force_run',
        action='store_true',
        help='Run DSP even if no client is connected (for debugging).')
    args = argParser.parse_args(args=argv[1:])

    # Verify we can actually run.
    # Note that this must be done before we actually load core modules, because we might get an import error then.
    version_report = yield _check_versions()
    if version_report:
        print(version_report, file=sys.stderr)
        sys.exit(1)

    # Write config file and exit, if asked to do so.
    if args.createConfig:
        write_default_config(args.config_path)
        _log.info('Created default configuration at: {config_path}',
                  config_path=args.config_path)
        sys.exit(0)  # TODO: Consider using a return value or something instead

    # Refuse to run as root.
    if hasattr(os, 'getuid') and os.getuid() == 0:
        print(
            'Network services should not be run as root. Refusing to start ShinySDR.',
            file=sys.stderr)
        sys.exit(1)

    # Read config file.
    config_obj = Config(reactor=reactor, log=_log)
    try:
        execute_config(config_obj, args.config_path)
        yield config_obj._wait_and_validate()
    except ConfigException:
        print_config_exception(sys.exc_info(), sys.stderr)
        defer.returnValue(None)
        return

    _log.info('Constructing...')
    app = config_obj._create_app()

    reactor.addSystemEventTrigger('during', 'shutdown', app.close_all_devices)

    _log.info('Restoring state...')
    pfg = PersistenceFileGlue(reactor=reactor,
                              root_object=app,
                              filename=config_obj._state_filename,
                              get_defaults=_app_defaults)

    _log.info('Starting web server...')
    services = MultiService()
    for maker in config_obj._service_makers:
        IService(maker(app)).setServiceParent(services)
    services.startService()

    _log.info('ShinySDR is ready.')

    for service in services:
        # TODO: should have an interface (currently no proper module to put it in)
        service.announce(args.openBrowser)

    if args.force_run:
        _log.debug('force_run')
        # TODO kludge, make this less digging into guts
        app.get_receive_flowgraph().get_monitor().state()['fft'].subscribe2(
            lambda v: None, the_subscription_context)

    if _abort_for_test:
        services.stopService()
        yield pfg.sync()
        defer.returnValue(app)
    else:
        yield defer.Deferred()  # never fires
Пример #2
0
    def __init__(self):
        ws.WebSocketClientProtocol.__init__(self)

        self.opened = defer.Deferred()
        self.closed = defer.Deferred()
 def getHeadline(self, input):
     self.d = defer.Deferred()
     reactor.callLater(1, self.processHeadline, input)
     self.d.addCallback(self._toHTML)
     return self.d
Пример #4
0
    def run_flow(self,
                 duration,
                 tasks=None,
                 start_d=None,
                 start_flow=True,
                 stop_flow=True):

        self.debug('run_flow: tasks: %r' % (tasks, ))
        flow_d = start_d

        if tasks is None:
            tasks = []

        if flow_d is None:
            if start_flow:
                flow_d = self.start_flow()
            else:
                flow_d = defer.succeed(True)

        flow_started_finished = [False, False]

        guard_d = None
        timeout_d = defer.Deferred()
        stop_d = defer.Deferred()
        stop_timeout_d = defer.Deferred()
        chained_d = None

        callids = [None, None, None]  # callLater ids: stop_d,
        # timeout_d, fire_chained

        if tasks:
            # if have tasks, run simultaneously with the main timer deferred
            chained_d = defer.DeferredList([stop_d] + tasks,
                                           fireOnOneErrback=1,
                                           consumeErrors=1)

            def chained_failed(failure):
                self.info('chained_failed: %r' % (failure, ))
                failure.trap(defer.FirstError)
                return failure.value.subFailure

            chained_d.addErrback(chained_failed)
        else:
            # otherwise, just idle...
            chained_d = stop_d

        def start_complete(result):
            self.debug('start_complete: %r' % (result, ))
            flow_started_finished[0] = True
            callids[0] = reactor.callLater(duration, stop_d.callback, None)
            if tasks:

                def _fire_chained():
                    callids[2] = None
                    for t in tasks:
                        try:
                            t.callback(result)
                        except defer.AlreadyCalledError:
                            pass

                callids[2] = reactor.callLater(0, _fire_chained)
            return chained_d

        def flow_complete(result):
            self.debug('flow_complete: %r' % (result, ))
            flow_started_finished[1] = True
            return result

        def flow_timed_out():
            self.debug('flow_timed_out!')
            if not flow_started_finished[0]:
                timeout_d.errback(StartTimeout('flow start timed out'))
            elif not flow_started_finished[1]:
                timeout_d.errback(FlowTimeout('flow run timed out'))
            else:
                stop_timeout_d.errback(StopTimeout('flow stop timed out'))

        def clean_calls(result):
            self.debug('clean_calls: %r' % (result, ))
            for i, cid in enumerate(callids):
                if cid is not None:
                    if cid.active():
                        cid.cancel()
                    callids[i] = None
            return result

        flow_d.addCallback(start_complete)
        flow_d.addCallback(flow_complete)

        guard_d = defer.DeferredList([flow_d, timeout_d],
                                     consumeErrors=1,
                                     fireOnOneErrback=1,
                                     fireOnOneCallback=1)

        def guard_failed(failure):
            self.info('guard_failed: %r' % (failure, ))
            failure.trap(defer.FirstError)
            return failure.value.subFailure

        if stop_flow:

            def _force_stop_flow(result):
                self.debug('_force_stop_flow: %r' % (result, ))
                d = defer.DeferredList([self.stop_flow(), stop_timeout_d],
                                       fireOnOneErrback=1,
                                       fireOnOneCallback=1,
                                       consumeErrors=1)

                def _return_orig_result(stop_result):
                    if isinstance(result, failure.Failure):
                        # always return the run's failure first
                        # what do I return if both the run and stop failed?
                        self.debug('_return_orig[R]: %r' % (result, ))
                        return result
                    elif isinstance(stop_result, failure.Failure):
                        # return failure from stop
                        self.debug('_return_orig[S]: %r' % (stop_result, ))
                        return stop_result
                    return result

                def force_stop_failed(failure):
                    self.info('force_stop_failed: %r' % (failure, ))
                    failure.trap(defer.FirstError)
                    return failure.value.subFailure

                d.addCallbacks(lambda r: r[0], force_stop_failed)
                d.addBoth(_return_orig_result)
                return d

            guard_d.addBoth(_force_stop_flow)

        guard_d.addErrback(guard_failed)
        guard_d.addBoth(clean_calls)

        callids[1] = reactor.callLater(self.guard_timeout, flow_timed_out)
        return guard_d
 def close(self):
     self.closing = defer.Deferred()
     self._maybe_fire_closing()
     return self.closing
Пример #6
0
 def _registerDeferredAsOutputChannel(self):
     d = defer.Deferred()
     self.addOutput(d.callback)
     return d
Пример #7
0
 def __init__(self):
     BuildStep.__init__(self)
     self._deferred = defer.Deferred()
Пример #8
0
    def gotListeningPort(listeningPort):
        def cancel(d):
            listeningPort.stopListening()

        return defer.Deferred(cancel)
Пример #9
0
 def __init__(self, stream, boundary):
     self.stream = stream
     self.boundary = boundary
     self.data = ''
     self.deferred = defer.Deferred()
Пример #10
0
    def update(self, data, tid=None):

        dd = defer.Deferred()
        log.debug('update requested')  # : %s %s' % (data, self.length))

        def updated(res):
            log.debug('playlist updated')
            if len(self.tracks) > 0:
                self.mpd.idArray = id_array(self.tracks)
                self.mpd.oh_eventPLAYLIST(self.mpd.idArray, 'idarray')
                self.plsversion = self.mpd.status['playlist']
                if tid:
                    if int(tid) in self.tracks:
                        dd.callback(tid)
                    else:
                        dd.errback()

        def format_track(track):

            en = et.Element('Entry')
            i = et.Element('Id')
            if 'id' not in track:
                log.critical('issue with playlist :%s' % track)
            i.text = track['id']
            en.append(i)
            uri = et.Element('Uri')
            uri.text = track['url'].decode('utf-8')
            en.append(uri)
            md = et.Element('Metadata')
            md.text = didl_encode(track)
            en.append(md)
            return (
                en,
                track,
            )

        def setter(res, pos):
            # print('playlist detail: %s %s' % (pos, res))
            self.details[pos] = res

        if data is not None:
            if not isinstance(data, list):
                data = [data]
            if self.length == 0:
                log.debug('empty')
                self.tracks = []
                self.details = []
                return
            else:
                l = []
                delta = self.length - len(self.tracks)
                # print('delta= %d' % delta)
                if delta >= 0:
                    for track in data:
                        #                         self.cache_cover(track)
                        try:
                            if int(track['Pos']) >= len(self.tracks):
                                self.tracks.append(int(track['Id']))
                                d = self.mpd.call('playlistid', track['Id'])
                                d.addCallback(self.get_cover, track['Id'])
                                d.addCallback(mpd_decode)
                                d.addCallback(format_track)
                                d.addCallback(self.details.append)
                            else:
                                self.tracks[int(track['Pos'])] = int(
                                    track['Id'])
                                d = self.mpd.call('playlistid', track['Id'])
                                d.addCallback(self.get_cover)
                                d.addCallback(mpd_decode)
                                d.addCallback(format_track)
                                d.addCallback(setter, int(track['Pos']))
                            l.append(d)
                        except:
                            continue
                else:
                    for track in data:
                        if 'Id' not in track:
                            continue
                        if track == {}:
                            self.tracks.pop()
                            self.details.pop()
                            delta += 1
                            continue
                        if delta < 0:
                            self.tracks.pop(int(track['Pos']))
                            self.details.pop(int(track['Pos']))
                            delta += 1
                        else:
                            self.tracks[int(track['Pos'])] = int(track['Id'])
                            d = self.mpd.call('playlistid', track['Id'])
                            d.addCallback(self.get_cover)
                            d.addCallback(mpd_decode)
                            d.addCallback(format_track)
                            d.addCallback(setter, int(track['Pos']))
                            l.append(d)
                if len(l) > 0:
                    dl = defer.gatherResults(l, consumeErrors=False)
                    dl.addCallback(updated)
        else:
            log.warn('Playlist update request returned no data')
        if tid:
            return dd
        else:
            dd = None
Пример #11
0
    def startService(self):
        assert not self._already_started, "can only start the master once"
        self._already_started = True

        log.msg("Starting BuildMaster -- buildbot.version: %s" %
                buildbot.version)

        # Set umask
        if self.umask is not None:
            os.umask(self.umask)

        # first, apply all monkeypatches
        monkeypatches.patch_all()

        # we want to wait until the reactor is running, so we can call
        # reactor.stop() for fatal errors
        d = defer.Deferred()
        self.reactor.callWhenRunning(d.callback, None)
        yield d

        startup_succeed = False
        try:
            yield self.initLock.acquire()
            # load the configuration file, treating errors as fatal
            try:
                # run the master.cfg in thread, so that it can use blocking
                # code
                self.config = yield threads.deferToThreadPool(
                    self.reactor, self.reactor.getThreadPool(),
                    self.config_loader.loadConfig)

            except config.ConfigErrors as e:
                log.msg("Configuration Errors:")
                for msg in e.errors:
                    log.msg("  " + msg)
                log.msg("Halting master.")
                self.reactor.stop()
                return
            except Exception:
                log.err(failure.Failure(), 'while starting BuildMaster')
                self.reactor.stop()
                return

            # set up services that need access to the config before everything
            # else gets told to reconfig
            try:
                yield self.db.setup()
            except exceptions.DatabaseNotReadyError:
                # (message was already logged)
                self.reactor.stop()
                return

            self.mq.setup()

            if hasattr(signal, "SIGHUP"):

                def sighup(*args):
                    eventually(self.reconfig)

                signal.signal(signal.SIGHUP, sighup)

            if hasattr(signal, "SIGUSR1"):

                def sigusr1(*args):
                    eventually(self.botmaster.cleanShutdown)

                signal.signal(signal.SIGUSR1, sigusr1)

            # get the masterid so other services can use it in
            # startup/reconfig.  This goes directly to the DB since the data
            # API isn't initialized yet, and anyway, this method is aware of
            # the DB API since it just called its setup function
            self.masterid = yield self.db.masters.findMasterId(name=self.name)

            # mark this master as stopped, in case it crashed before
            yield self.data.updates.masterStopped(name=self.name,
                                                  masterid=self.masterid)

            # call the parent method
            yield service.AsyncMultiService.startService(self)

            # We make sure the housekeeping is done before configuring in order to cleanup
            # any remaining claimed schedulers or change sources from zombie
            # masters
            yield self.data.updates.expireMasters(forceHouseKeeping=True)

            # give all services a chance to load the new configuration, rather
            # than the base configuration
            yield self.reconfigServiceWithBuildbotConfig(self.config)

            # Mark the master as active now that mq is running
            yield self.data.updates.masterActive(name=self.name,
                                                 masterid=self.masterid)

            # Start the heartbeat timer
            yield self.masterHeartbeatService.setServiceParent(self)

            # send the statistics to buildbot.net, without waiting
            self.sendBuildbotNetUsageData()
            startup_succeed = True
        except Exception:
            f = failure.Failure()
            log.err(f, 'while starting BuildMaster')
            self.reactor.stop()

        finally:
            if startup_succeed:
                log.msg("BuildMaster is running")
            else:
                log.msg("BuildMaster startup failed")

            yield self.initLock.release()
            self._master_initialized = True
Пример #12
0
 def setup_waiter((bsid,brids)):
     d = defer.Deferred()
     self._waiters[bsid] = (d, brids)
     self._updateWaiters()
     return d
Пример #13
0
 def __init__(self):
     self.deferred = defer.Deferred()
     self.out = b''
     self.err = b''
     self.exitcode = None
Пример #14
0
 def __init__(self):
     self.deferred = defer.Deferred()
     self.io = StringIO()
     self.write = self.io.write
 def setUp(self):
     """Set up."""
     self.connlost_deferred = defer.Deferred()
     return super(AQCancelTestBase, self).setUp()
Пример #16
0
def deferUntilLater(secs, result=None):
    d = defer.Deferred()
    reactor.callLater(secs, d.callback, result)
    return d
Пример #17
0
 def prepare(self):
     self.d = defer.Deferred()
     return self.d
Пример #18
0
    def handleMessage(self, lmsg):
        """Implements the LLRP client state machine."""
        logger.debug('LLRPMessage received in state %s: %s', self.state, lmsg)
        msgName = lmsg.getName()
        lmsg.peername = self.peername

        # call per-message callbacks
        logger.debug('starting message callbacks for %s', msgName)
        for fn in self._message_callbacks[msgName]:
            fn(lmsg)
        logger.debug('done with message callbacks for %s', msgName)

        # keepalives can occur at any time
        if msgName == 'KEEPALIVE':
            self.send_KEEPALIVE_ACK()
            return

        if msgName == 'RO_ACCESS_REPORT' and \
                self.state != LLRPClient.STATE_INVENTORYING:
            logger.debug('ignoring RO_ACCESS_REPORT because not inventorying')
            return

        logger.debug('in handleMessage(%s), there are %d Deferreds', msgName,
                     len(self._deferreds[msgName]))

        #######
        # LLRP client state machine follows.  Beware: gets thorny.  Note the
        # order of the LLRPClient.STATE_* fields.
        #######

        # in DISCONNECTED, CONNECTING, and CONNECTED states, expect only
        # READER_EVENT_NOTIFICATION messages.
        if self.state in (LLRPClient.STATE_DISCONNECTED,
                          LLRPClient.STATE_CONNECTING,
                          LLRPClient.STATE_CONNECTED):
            if msgName != 'READER_EVENT_NOTIFICATION':
                logger.error('unexpected message %s while connecting', msgName)
                return

            if not lmsg.isSuccess():
                try:
                    status = lmsg.msgdict[msgName]\
                        ['ReaderEventNotificationData']\
                        ['ConnectionAttemptEvent']['Status']
                except KeyError:
                    status = '(unknown status)'
                logger.fatal('Could not start session on reader: %s', status)
                return

            self.processDeferreds(msgName, lmsg.isSuccess())

            # a Deferred to call when we get GET_READER_CAPABILITIES_RESPONSE
            d = defer.Deferred()
            d.addCallback(self._setState_wrapper, LLRPClient.STATE_CONNECTED)
            d.addErrback(self.panic, 'GET_READER_CAPABILITIES failed')
            self.send_GET_READER_CAPABILITIES(onCompletion=d)

        # in state SENT_GET_CAPABILITIES, expect only GET_CAPABILITIES_RESPONSE;
        # respond to this message by advancing to state CONNECTED.
        elif self.state == LLRPClient.STATE_SENT_GET_CAPABILITIES:
            if msgName != 'GET_READER_CAPABILITIES_RESPONSE':
                logger.error(
                    'unexpected response %s when getting capabilities',
                    msgName)
                return

            if not lmsg.isSuccess():
                status = lmsg.msgdict[msgName]['LLRPStatus']['StatusCode']
                err = lmsg.msgdict[msgName]['LLRPStatus']['ErrorDescription']
                logger.fatal('Error %s getting capabilities: %s', status, err)
                return

            self.capabilities = lmsg.msgdict[
                'GET_READER_CAPABILITIES_RESPONSE']
            logger.debug('Capabilities: %s', pprint.pformat(self.capabilities))
            try:
                self.parseCapabilities(self.capabilities)
            except LLRPError as err:
                logger.exception('Capabilities mismatch')
                raise err

            self.processDeferreds(msgName, lmsg.isSuccess())

            if self.reset_on_connect:
                d = self.stopPolitely(disconnect=False)
                if self.start_inventory:
                    d.addCallback(self.startInventory)
            elif self.start_inventory:
                self.startInventory()

        # in state SENT_ADD_ROSPEC, expect only ADD_ROSPEC_RESPONSE; respond to
        # favorable ADD_ROSPEC_RESPONSE by enabling the added ROSpec and
        # advancing to state SENT_ENABLE_ROSPEC.
        elif self.state == LLRPClient.STATE_SENT_ADD_ROSPEC:
            if msgName != 'ADD_ROSPEC_RESPONSE':
                logger.error('unexpected response %s when adding ROSpec',
                             msgName)
                return

            if not lmsg.isSuccess():
                status = lmsg.msgdict[msgName]['LLRPStatus']['StatusCode']
                err = lmsg.msgdict[msgName]['LLRPStatus']['ErrorDescription']
                logger.fatal('Error %s adding ROSpec: %s', status, err)
                return

            self.processDeferreds(msgName, lmsg.isSuccess())

        # in state PAUSING, we have sent a DISABLE_ROSPEC, so expect only
        # DISABLE_ROSPEC_RESPONSE.  advance to state PAUSED.
        elif self.state == LLRPClient.STATE_PAUSING:
            if msgName != 'DISABLE_ROSPEC_RESPONSE':
                logger.error(
                    'unexpected response %s '
                    ' when disabling ROSpec', msgName)

            if not lmsg.isSuccess():
                status = lmsg.msgdict[msgName]['LLRPStatus']['StatusCode']
                err = lmsg.msgdict[msgName]['LLRPStatus']['ErrorDescription']
                logger.error('DISABLE_ROSPEC failed with status %s: %s',
                             status, err)
                logger.warn('Error %s disabling ROSpec: %s', status, err)

            self.processDeferreds(msgName, lmsg.isSuccess())

        # in state SENT_ENABLE_ROSPEC, expect only ENABLE_ROSPEC_RESPONSE;
        # respond to favorable ENABLE_ROSPEC_RESPONSE by starting the enabled
        # ROSpec and advancing to state INVENTORYING.
        elif self.state == LLRPClient.STATE_SENT_ENABLE_ROSPEC:
            if msgName != 'ENABLE_ROSPEC_RESPONSE':
                logger.error('unexpected response %s when enabling ROSpec',
                             msgName)

            if not lmsg.isSuccess():
                status = lmsg.msgdict[msgName]['LLRPStatus']['StatusCode']
                err = lmsg.msgdict[msgName]['LLRPStatus']['ErrorDescription']
                logger.error('ENABLE_ROSPEC failed with status %s: %s', status,
                             err)
                logger.fatal('Error %s enabling ROSpec: %s', status, err)
                return

            self.processDeferreds(msgName, lmsg.isSuccess())

        elif self.state == LLRPClient.STATE_INVENTORYING:
            if msgName not in ('RO_ACCESS_REPORT', 'READER_EVENT_NOTIFICATION',
                               'ADD_ACCESSSPEC_RESPONSE',
                               'ENABLE_ACCESSSPEC_RESPONSE',
                               'DISABLE_ACCESSSPEC_RESPONSE',
                               'DELETE_ACCESSSPEC_RESPONSE'):
                logger.error('unexpected message %s while inventorying',
                             msgName)
                return

            self.processDeferreds(msgName, lmsg.isSuccess())

        elif self.state == LLRPClient.STATE_SENT_DELETE_ACCESSSPEC:
            if msgName != 'DELETE_ACCESSSPEC_RESPONSE':
                logger.error('unexpected response %s when deleting AccessSpec',
                             msgName)

            self.processDeferreds(msgName, lmsg.isSuccess())

        elif self.state == LLRPClient.STATE_SENT_DELETE_ROSPEC:
            if msgName != 'DELETE_ROSPEC_RESPONSE':
                logger.error('unexpected response %s when deleting ROSpec',
                             msgName)

            if lmsg.isSuccess():
                logger.info('reader finished inventory')
                if self.disconnecting:
                    self.setState(LLRPClient.STATE_DISCONNECTED)
                else:
                    self.setState(LLRPClient.STATE_CONNECTED)

            else:
                status = lmsg.msgdict[msgName]['LLRPStatus']['StatusCode']
                err = lmsg.msgdict[msgName]['LLRPStatus']['ErrorDescription']
                logger.error('DELETE_ROSPEC failed with status %s: %s', status,
                             err)

            self.processDeferreds(msgName, lmsg.isSuccess())
            if self.disconnecting:
                logger.info('disconnecting')
                self.transport.loseConnection()

        else:
            logger.warn('message %s received in unknown state!', msgName)

        if self._deferreds[msgName]:
            logger.error(
                'there should NOT be Deferreds left for %s,'
                ' but there are!', msgName)
Пример #19
0
 def make_unsafe():
     self.safe_kick = defer.Deferred()
     self.ticker.add_delay(10, make_safe)
Пример #20
0
    def startAccess(self,
                    readWords=None,
                    writeWords=None,
                    target=None,
                    accessStopParam=None,
                    accessSpecID=1,
                    param=None,
                    *args):
        m = Message_struct['AccessSpec']
        if not target:
            target = {
                'MB': 0,
                'Pointer': 0,
                'MaskBitCount': 0,
                'TagMask': '',
                'DataBitCount': 0,
                'TagData': ''
            }

        opSpecParam = {
            'OpSpecID': 0,
            'AccessPassword': 0,
        }

        if readWords:
            opSpecParam['MB'] = readWords['MB']
            opSpecParam['WordPtr'] = readWords['WordPtr']
            opSpecParam['WordCount'] = readWords['WordCount']
            if 'OpSpecID' in readWords:
                opSpecParam['OpSpecID'] = readWords['OpSpecID']
            if 'AccessPassword' in readWords:
                opSpecParam['AccessPassword'] = readWords['AccessPassword']

        elif writeWords:
            opSpecParam['MB'] = writeWords['MB']
            opSpecParam['WordPtr'] = writeWords['WordPtr']
            opSpecParam['WriteDataWordCount'] = writeWords[
                'WriteDataWordCount']
            opSpecParam['WriteData'] = writeWords['WriteData']
            if 'OpSpecID' in writeWords:
                opSpecParam['OpSpecID'] = writeWords['OpSpecID']
            if 'AccessPassword' in writeWords:
                opSpecParam['AccessPassword'] = writeWords['AccessPassword']

        elif param:
            # special parameters like C1G2Lock
            opSpecParam = param

        else:
            raise LLRPError('startAccess requires readWords or writeWords.')

        if not accessStopParam:
            accessStopParam = {}
            accessStopParam['AccessSpecStopTriggerType'] = 1
            accessStopParam['OperationCountValue'] = 5

        accessSpec = {
            'Type': m['type'],
            'AccessSpecID': accessSpecID,
            'AntennaID': 0,  # all antennas
            'ProtocolID': AirProtocol['EPCGlobalClass1Gen2'],
            'C': False,  # disabled by default
            'ROSpecID': 0,  # all ROSpecs
            'AccessSpecStopTrigger': accessStopParam,
            'AccessCommand': {
                'TagSpecParameter': {
                    'C1G2TargetTag': {  # XXX correct values?
                        'MB': target['MB'],
                        'M': 1,
                        'Pointer': target['Pointer'],
                        'MaskBitCount': target['MaskBitCount'],
                        'TagMask': target['TagMask'],
                        'DataBitCount': target['DataBitCount'],
                        'TagData': target['TagData']
                    }
                },
                'OpSpecParameter': opSpecParam,
            },
            'AccessReportSpec': {
                'AccessReportTrigger': 1  # report at end of access
            }
        }

        d = defer.Deferred()
        d.addCallback(self.send_ENABLE_ACCESSSPEC, accessSpecID)
        d.addErrback(self.panic, 'ADD_ACCESSSPEC failed')

        self.send_ADD_ACCESSSPEC(accessSpec, onCompletion=d)
Пример #21
0
 def startStep(*args, **kw):
     # Now interrupt the build
     b.stopBuild("stop it")
     return defer.Deferred()
Пример #22
0
    def test_verify_json_objects_for_server_awaits_previous_requests(self):
        key1 = signedjson.key.generate_signing_key(1)

        kr = keyring.Keyring(self.hs)
        json1 = {}
        signedjson.sign.sign_json(json1, "server10", key1)

        persp_resp = {
            "server_keys": [
                self.mock_perspective_server.get_signed_key(
                    "server10", signedjson.key.get_verify_key(key1))
            ]
        }
        persp_deferred = defer.Deferred()

        @defer.inlineCallbacks
        def get_perspectives(**kwargs):
            self.assertEquals(LoggingContext.current_context().request, "11")
            with PreserveLoggingContext():
                yield persp_deferred
            return persp_resp

        self.http_client.post_json.side_effect = get_perspectives

        # start off a first set of lookups
        @defer.inlineCallbacks
        def first_lookup():
            with LoggingContext("11") as context_11:
                context_11.request = "11"

                res_deferreds = kr.verify_json_objects_for_server([
                    ("server10", json1, 0, "test10"),
                    ("server11", {}, 0, "test11")
                ])

                # the unsigned json should be rejected pretty quickly
                self.assertTrue(res_deferreds[1].called)
                try:
                    yield res_deferreds[1]
                    self.assertFalse("unsigned json didn't cause a failure")
                except SynapseError:
                    pass

                self.assertFalse(res_deferreds[0].called)
                res_deferreds[0].addBoth(self.check_context, None)

                yield make_deferred_yieldable(res_deferreds[0])

                # let verify_json_objects_for_server finish its work before we kill the
                # logcontext
                yield self.clock.sleep(0)

        d0 = first_lookup()

        # wait a tick for it to send the request to the perspectives server
        # (it first tries the datastore)
        self.pump()
        self.http_client.post_json.assert_called_once()

        # a second request for a server with outstanding requests
        # should block rather than start a second call
        @defer.inlineCallbacks
        def second_lookup():
            with LoggingContext("12") as context_12:
                context_12.request = "12"
                self.http_client.post_json.reset_mock()
                self.http_client.post_json.return_value = defer.Deferred()

                res_deferreds_2 = kr.verify_json_objects_for_server([
                    ("server10", json1, 0, "test")
                ])
                res_deferreds_2[0].addBoth(self.check_context, None)
                yield make_deferred_yieldable(res_deferreds_2[0])

                # let verify_json_objects_for_server finish its work before we kill the
                # logcontext
                yield self.clock.sleep(0)

        d2 = second_lookup()

        self.pump()
        self.http_client.post_json.assert_not_called()

        # complete the first request
        persp_deferred.callback(persp_resp)
        self.get_success(d0)
        self.get_success(d2)
Пример #23
0
def delayed_d(time, val):
    """Insert some delay into callback chain."""

    d = defer.Deferred()
    reactor.callLater(time, d.callback, val)
    return d
Пример #24
0
 def remote_deferredJelly(self):
     d = defer.Deferred()
     d.addCallback(self.raiseJelly)
     d.callback(None)
     return d
from twisted.internet import defer


def canceller(d):
    print "I need to cancel this deferred:", d
    print "Firing the deferred with a result"
    d.callback('result')


def callback(res):
    print 'callback got:', res


def errback(err):
    print 'errback got:', err


d = defer.Deferred(canceller)  # created by lower-level code
d.addCallbacks(callback, errback)  # added by higher-level code
d.cancel()
print 'done'
Пример #26
0
 def remote_deferredSecurity(self):
     d = defer.Deferred()
     d.addCallback(self.raiseSecurity)
     d.callback(None)
     return d
Пример #27
0
 def __init__(self, uri):
     ws.WebSocketClientFactory.__init__(self, uri)
     self.proto = None
     self.connected = defer.Deferred()
Пример #28
0
 def stopService(self):
     self.d = defer.Deferred()
     return self.d
 def __init__(self):
     service.AsyncMultiService.__init__(self)
     self.app = self.router_url = None
     self.serviceDeferred = defer.Deferred()
     self.service = None
Пример #30
0
 def __init__(self):
     self.deferred = defer.Deferred()