Exemplo n.º 1
0
    def __init__(self, factory, serializers=None):
        """
        Ctor.

        :param factory: A callable that produces instances that implement
           :class:`autobahn.wamp.interfaces.ITransportHandler`
        :type factory: callable
        :param serializers: A list of WAMP serializers to use (or None for default
           serializers). Serializers must implement
           :class:`autobahn.wamp.interfaces.ISerializer`.
        :type serializers: list
        """
        if callable(factory):
            self._factory = factory
        else:
            self._factory = lambda: factory

        if serializers is None:
            serializers = []

            # try CBOR WAMP serializer
            try:
                from autobahn.wamp.serializer import CBORSerializer
                serializers.append(CBORSerializer(batched=True))
                serializers.append(CBORSerializer())
            except ImportError:
                pass

            # try MsgPack WAMP serializer
            try:
                from autobahn.wamp.serializer import MsgPackSerializer
                serializers.append(MsgPackSerializer(batched=True))
                serializers.append(MsgPackSerializer())
            except ImportError:
                pass

            # try UBJSON WAMP serializer
            try:
                from autobahn.wamp.serializer import UBJSONSerializer
                serializers.append(UBJSONSerializer(batched=True))
                serializers.append(UBJSONSerializer())
            except ImportError:
                pass

            # try JSON WAMP serializer
            try:
                from autobahn.wamp.serializer import JsonSerializer
                serializers.append(JsonSerializer(batched=True))
                serializers.append(JsonSerializer())
            except ImportError:
                pass

            if not serializers:
                raise Exception(u'Could not import any WAMP serializer')

        self._serializers = {}
        for ser in serializers:
            self._serializers[ser.SERIALIZER_ID] = ser

        self._protocols = [u'wamp.2.{}'.format(ser.SERIALIZER_ID) for ser in serializers]
Exemplo n.º 2
0
    def __init__(self, factory, serializers=None):
        """

        :param factory: A callable that produces instances that implement
            :class:`autobahn.wamp.interfaces.ITransportHandler`
        :type factory: callable

        :param serializers: A list of WAMP serializers to use (or ``None``
            for all available serializers).
        :type serializers: list of objects implementing
            :class:`autobahn.wamp.interfaces.ISerializer`
        """
        if callable(factory):
            self._factory = factory
        else:
            self._factory = lambda: factory

        if serializers is None:
            serializers = []

            # try CBOR WAMP serializer
            try:
                from autobahn.wamp.serializer import CBORSerializer
                serializers.append(CBORSerializer(batched=True))
                serializers.append(CBORSerializer())
            except ImportError:
                pass

            # try MsgPack WAMP serializer
            try:
                from autobahn.wamp.serializer import MsgPackSerializer
                serializers.append(MsgPackSerializer(batched=True))
                serializers.append(MsgPackSerializer())
            except ImportError:
                pass

            # try UBJSON WAMP serializer
            try:
                from autobahn.wamp.serializer import UBJSONSerializer
                serializers.append(UBJSONSerializer(batched=True))
                serializers.append(UBJSONSerializer())
            except ImportError:
                pass

            # try JSON WAMP serializer
            try:
                from autobahn.wamp.serializer import JsonSerializer
                serializers.append(JsonSerializer(batched=True))
                serializers.append(JsonSerializer())
            except ImportError:
                pass

            if not serializers:
                raise Exception("could not import any WAMP serializers")

        self._serializers = {}
        for ser in serializers:
            self._serializers[ser.RAWSOCKET_SERIALIZER_ID] = ser
Exemplo n.º 3
0
    def __init__(self, factory, serializers=None, debug_wamp=False):
        """
        Ctor.

        :param factory: A callable that produces instances that implement
           :class:`autobahn.wamp.interfaces.ITransportHandler`
        :type factory: callable
        :param serializers: A list of WAMP serializers to use (or None for default
           serializers). Serializers must implement
           :class:`autobahn.wamp.interfaces.ISerializer`.
        :type serializers: list
        """
        assert (callable(factory))
        self._factory = factory

        self.debug_wamp = debug_wamp

        if serializers is None:
            serializers = []

            # try CBOR WAMP serializer
            try:
                from autobahn.wamp.serializer import CBORSerializer
                serializers.append(CBORSerializer(batched=True))
                serializers.append(CBORSerializer())
            except ImportError:
                pass

            # try MsgPack WAMP serializer
            try:
                from autobahn.wamp.serializer import MsgPackSerializer
                serializers.append(MsgPackSerializer(batched=True))
                serializers.append(MsgPackSerializer())
            except ImportError:
                pass

            # try JSON WAMP serializer
            try:
                from autobahn.wamp.serializer import JsonSerializer
                serializers.append(JsonSerializer(batched=True))
                serializers.append(JsonSerializer())
            except ImportError:
                pass

            if not serializers:
                raise Exception("could not import any WAMP serializers")

        self._serializers = {}
        for ser in serializers:
            self._serializers[ser.SERIALIZER_ID] = ser

        self._protocols = [
            "wamp.2.%s" % ser.SERIALIZER_ID for ser in serializers
        ]
Exemplo n.º 4
0
    def __init__(self, factory, serializer=None):
        """

        :param factory: A callable that produces instances that implement
            :class:`autobahn.wamp.interfaces.ITransportHandler`
        :type factory: callable

        :param serializer: The WAMP serializer to use (or ``None`` for
           "best" serializer, chosen as the first serializer available from
           this list: CBOR, MessagePack, UBJSON, JSON).
        :type serializer: object implementing :class:`autobahn.wamp.interfaces.ISerializer`
        """
        if callable(factory):
            self._factory = factory
        else:
            self._factory = lambda: factory

        if serializer is None:

            # try CBOR WAMP serializer
            try:
                from autobahn.wamp.serializer import CBORSerializer
                serializer = CBORSerializer()
            except ImportError:
                pass

        if serializer is None:

            # try MsgPack WAMP serializer
            try:
                from autobahn.wamp.serializer import MsgPackSerializer
                serializer = MsgPackSerializer()
            except ImportError:
                pass

        if serializer is None:

            # try UBJSON WAMP serializer
            try:
                from autobahn.wamp.serializer import UBJSONSerializer
                serializer = UBJSONSerializer()
            except ImportError:
                pass

        if serializer is None:
            # try JSON WAMP serializer
            try:
                from autobahn.wamp.serializer import JsonSerializer
                serializer = JsonSerializer()
            except ImportError:
                pass

        if serializer is None:
            raise Exception("could not import any WAMP serializer")

        self._serializer = serializer
Exemplo n.º 5
0
    def __init__(self, factory, serializer=None):
        """

        :param factory: A callable that produces instances that implement
            :class:`autobahn.wamp.interfaces.ITransportHandler`
        :type factory: callable
        :param serializer: The WAMP serializer to use (or None for default
           serializer). Serializers must implement
           :class:`autobahn.wamp.interfaces.ISerializer`.
        :type serializer: obj
        """
        if callable(factory):
            self._factory = factory
        else:
            self._factory = lambda: factory

        if serializer is None:

            # try CBOR WAMP serializer
            try:
                from autobahn.wamp.serializer import CBORSerializer
                serializer = CBORSerializer()
            except ImportError:
                pass

        if serializer is None:

            # try MsgPack WAMP serializer
            try:
                from autobahn.wamp.serializer import MsgPackSerializer
                serializer = MsgPackSerializer()
            except ImportError:
                pass

        if serializer is None:

            # try UBJSON WAMP serializer
            try:
                from autobahn.wamp.serializer import UBJSONSerializer
                serializer = UBJSONSerializer()
            except ImportError:
                pass

        if serializer is None:
            # try JSON WAMP serializer
            try:
                from autobahn.wamp.serializer import JsonSerializer
                serializer = JsonSerializer()
            except ImportError:
                pass

        if serializer is None:
            raise Exception("could not import any WAMP serializer")

        self._serializer = serializer
Exemplo n.º 6
0
    def __init__(self, factory, config):

        # transport configuration
        self._config = config

        # WAMP serializer
        #
        serid = config.get('serializer', 'json')

        if serid == 'json':
            # try JSON WAMP serializer
            try:
                from autobahn.wamp.serializer import JsonSerializer
                serializer = JsonSerializer()
            except ImportError:
                raise Exception("could not load WAMP-JSON serializer")

        elif serid == 'msgpack':
            # try MessagePack WAMP serializer
            try:
                from autobahn.wamp.serializer import MsgPackSerializer
                serializer = MsgPackSerializer()
                serializer._serializer.ENABLE_V5 = False  # FIXME
            except ImportError:
                raise Exception("could not load WAMP-MessagePack serializer")

        elif serid == 'cbor':
            # try CBOR WAMP serializer
            try:
                from autobahn.wamp.serializer import CBORSerializer
                serializer = CBORSerializer()
            except ImportError:
                raise Exception("could not load WAMP-CBOR serializer")

        else:
            raise Exception("invalid WAMP serializer '{}'".format(serid))

        rawsocket.WampRawSocketClientFactory.__init__(self, factory,
                                                      serializer)
Exemplo n.º 7
0
    def __init__(self, factory, config):

        # remember transport configuration
        #
        self._config = config

        # explicit list of WAMP serializers
        #
        if 'serializers' in config:
            serializers = []
            sers = set(config['serializers'])

            if 'flatbuffers' in sers:
                # try FlatBuffers WAMP serializer
                try:
                    from autobahn.wamp.serializer import FlatBuffersSerializer
                    serializers.append(FlatBuffersSerializer())
                except ImportError:
                    self.log.warn(
                        "Warning: could not load WAMP-FlatBuffers serializer")
                else:
                    sers.discard('flatbuffers')

            if 'cbor' in sers:
                # try CBOR WAMP serializer
                try:
                    from autobahn.wamp.serializer import CBORSerializer
                    serializers.append(CBORSerializer())
                except ImportError:
                    self.log.warn(
                        "Warning: could not load WAMP-CBOR serializer")
                else:
                    sers.discard('cbor')

            if 'msgpack' in sers:
                # try MsgPack WAMP serializer
                try:
                    from autobahn.wamp.serializer import MsgPackSerializer
                    serializer = MsgPackSerializer()
                    serializer._serializer.ENABLE_V5 = False  # FIXME
                    serializers.append(serializer)
                except ImportError:
                    self.log.warn(
                        "Warning: could not load WAMP-MsgPack serializer")
                else:
                    sers.discard('msgpack')

            if 'ubjson' in sers:
                # try UBJSON WAMP serializer
                try:
                    from autobahn.wamp.serializer import UBJSONSerializer
                    serializers.append(UBJSONSerializer(batched=True))
                    serializers.append(UBJSONSerializer())
                except ImportError:
                    self.log.warn(
                        "Warning: could not load WAMP-UBJSON serializer")
                else:
                    sers.discard('ubjson')

            if 'json' in sers:
                # try JSON WAMP serializer
                try:
                    from autobahn.wamp.serializer import JsonSerializer
                    serializers.append(JsonSerializer())
                except ImportError:
                    self.log.warn(
                        "Warning: could not load WAMP-JSON serializer")
                else:
                    sers.discard('json')

            if not serializers:
                raise Exception("no valid WAMP serializers specified")

            if len(sers) > 0:
                raise Exception(
                    "invalid WAMP serializers specified (the following were unprocessed) {}"
                    .format(sers))

        else:
            serializers = None

        rawsocket.WampRawSocketServerFactory.__init__(self, factory,
                                                      serializers)

        if 'options' in config:
            set_rawsocket_options(self, config['options'])

        self.log.debug(
            "RawSocket transport factory created using {serializers} serializers, max. message size {maxsize}",
            serializers=serializers,
            maxsize=self._max_message_size)
Exemplo n.º 8
0
    def __init__(self, factory, cbdir, config, templates):
        """

        :param factory: WAMP session factory.
        :type factory: An instance of ..

        :param cbdir: The Crossbar.io node directory.
        :type cbdir: str

        :param config: Crossbar transport configuration.
        :type config: dict

        :param templates:
        :type templates:
        """
        self.debug_traffic = config.get('debug_traffic', False)

        options = config.get('options', {})

        # announce Crossbar.io server version
        #
        self.showServerVersion = options.get('show_server_version',
                                             self.showServerVersion)
        if self.showServerVersion:
            server = "Crossbar/{}".format(crossbar.__version__)
        else:
            # do not disclose crossbar version
            server = "Crossbar"

        # external (public) listening port (eg when running behind a reverse proxy)
        #
        externalPort = options.get('external_port', None)

        # explicit list of WAMP serializers
        #
        if 'serializers' in config:
            serializers = []
            sers = set(config['serializers'])

            if 'flatbuffers' in sers:
                # try FlatBuffers WAMP serializer
                try:
                    from autobahn.wamp.serializer import FlatBuffersSerializer
                    serializers.append(FlatBuffersSerializer(batched=True))
                    serializers.append(FlatBuffersSerializer())
                except ImportError('FlatBuffersSerializer'):
                    self.log.warn(
                        "Warning: could not load WAMP-FlatBuffers serializer")
                else:
                    sers.discard('flatbuffers')

            if 'cbor' in sers:
                # try CBOR WAMP serializer
                try:
                    from autobahn.wamp.serializer import CBORSerializer
                    serializers.append(CBORSerializer(batched=True))
                    serializers.append(CBORSerializer())
                except ImportError('CBORSerializer'):
                    self.log.warn(
                        "Warning: could not load WAMP-CBOR serializer")
                else:
                    sers.discard('cbor')

            if 'msgpack' in sers:
                # try MsgPack WAMP serializer
                try:
                    from autobahn.wamp.serializer import MsgPackSerializer
                    serializers.append(MsgPackSerializer(batched=True))
                    serializers.append(MsgPackSerializer())
                except ImportError('MsgPackSerializer'):
                    self.log.warn(
                        "Warning: could not load WAMP-MsgPack serializer")
                else:
                    sers.discard('msgpack')

            if 'ubjson' in sers:
                # try UBJSON WAMP serializer
                try:
                    from autobahn.wamp.serializer import UBJSONSerializer
                    serializers.append(UBJSONSerializer(batched=True))
                    serializers.append(UBJSONSerializer())
                except ImportError('UBJSONSerializer'):
                    self.log.warn(
                        "Warning: could not load WAMP-UBJSON serializer")
                else:
                    sers.discard('ubjson')

            if 'json' in sers:
                # try JSON WAMP serializer
                try:
                    from autobahn.wamp.serializer import JsonSerializer
                    serializers.append(JsonSerializer(batched=True))
                    serializers.append(JsonSerializer())
                except ImportError('JsonSerializer'):
                    self.log.warn(
                        "Warning: could not load WAMP-JSON serializer")
                else:
                    sers.discard('json')

            if not serializers:
                raise Exception("no valid WAMP serializers specified")

            if len(sers) > 0:
                raise Exception(
                    "invalid WAMP serializers specified (the following were unprocessed) {}"
                    .format(sers))

        else:
            serializers = None

        websocket.WampWebSocketServerFactory.__init__(
            self,
            factory,
            serializers=serializers,
            url=config.get('url', None),
            server=server,
            externalPort=externalPort)

        # Crossbar.io node directory
        self._cbdir = cbdir

        # transport configuration
        self._config = config

        # Jinja2 templates for 404 etc
        self._templates = templates

        # enable cookie tracking if a cookie store is configured
        if 'cookie' in config:
            # cookie store configuration item
            cookie_config = config['cookie']

            # cookie store
            cookie_store_config = cookie_config['store']
            cookie_store_type = cookie_store_config['type']

            # setup ephemeral, memory-backed cookie store
            if cookie_store_type == 'memory':
                self._cookiestore = CookieStoreMemoryBacked(cookie_config)
                self.log.info("Memory-backed cookie store active.")

            # setup persistent, file-backed cookie store
            elif cookie_store_type == 'file':
                cookie_store_file = os.path.abspath(
                    os.path.join(self._cbdir, cookie_store_config['filename']))
                self._cookiestore = CookieStoreFileBacked(
                    cookie_store_file, cookie_config)
                self.log.info(
                    "File-backed cookie store active {cookie_store_file}",
                    cookie_store_file=hlval(cookie_store_file))

            # setup persistent, database-backed cookie store
            elif cookie_store_type == 'database':
                cookie_dbpath = os.path.abspath(
                    os.path.join(self._cbdir, cookie_store_config['path']))
                self._cookiestore = CookieStoreDatabaseBacked(
                    cookie_dbpath, cookie_config)
                self.log.info(
                    "Database-backed cookie store active! [cookiestore={cookiestore}]",
                    cookiestore=hltype(CookieStoreDatabaseBacked))

            else:
                # should not arrive here as the config should have been checked before
                raise NotImplementedError(
                    '{}: implementation of cookiestore of type "{}" missing'.
                    format(self.__class__.__name__, cookie_store_type))
        else:
            # this disables cookie tracking (both with or without WAMP-cookie authentication)
            self._cookiestore = None

        # set WebSocket options
        set_websocket_options(self, options)
Exemplo n.º 9
0
    args = parser.parse_args()

    # start logging
    if args.debug:
        txaio.start_logging(level='debug')
    else:
        txaio.start_logging(level='info')

    # explicitly select serializer
    if args.serializer == 'unspecified':
        serializers = None
    else:
        serializers = []

        if args.serializer in ['cbor', 'all']:
            serializers.append(CBORSerializer())

        if args.serializer in ['msgpack', 'all']:
            serializers.append(MsgPackSerializer())

        if args.serializer in ['json', 'all']:
            serializers.append(JsonSerializer())

    # any extra info we want to forward to our ClientSession (in self.config.extra)
    extra = {}

    # now actually run a WAMP client using our session class ClientSession
    runner = ApplicationRunner(url=args.url,
                               realm=args.realm,
                               extra=extra,
                               serializers=serializers)
Exemplo n.º 10
0
                        default=None,
                        help='The worker number when parallel degree > 1.')

    parser.add_argument('--iterations',
                        dest='iter',
                        type=int,
                        default=10,
                        help='Number of iterations before exiting.')

    args = parser.parse_args()

    if args.parallel > 1:
        dl = []
        for realm in args.realms.split(','):
            for i in range(args.parallel):
                cmd = [sys.executable, '-u', os.path.abspath(__file__), '--url', args.url, '--realm', realm, '--worker={}'.format(i)]
                done = Deferred()
                worker = Worker(done)
                reactor.spawnProcess(worker, cmd[0], args=cmd, usePTY=True)
                dl.append(done)
        all = gatherResults(dl)
        reactor.run()
    else:
        extra = {
            'worker': args.worker,
            'iter': args.iter,
        }

        runner = ApplicationRunner(url=args.url, realm=args.realm, extra=extra, serializers=[CBORSerializer()])
        runner.run(PipelinedClient, auto_reconnect=True)
Exemplo n.º 11
0
    def __init__(self,
                 factory,
                 serializers=None,
                 timeout=10,
                 killAfter=30,
                 queueLimitBytes=128 * 1024,
                 queueLimitMessages=100,
                 debug_transport_id=None,
                 reactor=None):
        """
        Create new HTTP WAMP Web resource.

        :param factory: A (router) session factory.
        :type factory: Instance of :class:`autobahn.twisted.wamp.RouterSessionFactory`.
        :param serializers: List of WAMP serializers.
        :type serializers: list of obj (which implement :class:`autobahn.wamp.interfaces.ISerializer`)
        :param timeout: XHR polling timeout in seconds.
        :type timeout: int
        :param killAfter: Kill WAMP session after inactivity in seconds.
        :type killAfter: int
        :param queueLimitBytes: Kill WAMP session after accumulation of this many bytes in send queue (XHR poll).
        :type queueLimitBytes: int
        :param queueLimitMessages: Kill WAMP session after accumulation of this many message in send queue (XHR poll).
        :type queueLimitMessages: int
        :param debug: Enable debug logging.
        :type debug: bool
        :param debug_transport_id: If given, use this fixed transport ID.
        :type debug_transport_id: str
        :param reactor: The Twisted reactor to run under.
        :type reactor: obj
        """
        Resource.__init__(self)

        # RouterSessionFactory
        self._factory = factory

        # lazy import to avoid reactor install upon module import
        if reactor is None:
            from twisted.internet import reactor
        self.reactor = reactor

        self._debug_transport_id = debug_transport_id
        self._timeout = timeout
        self._killAfter = killAfter
        self._queueLimitBytes = queueLimitBytes
        self._queueLimitMessages = queueLimitMessages

        if serializers is None:
            serializers = []

            # try CBOR WAMP serializer
            try:
                from autobahn.wamp.serializer import CBORSerializer
                serializers.append(CBORSerializer(batched=True))
                serializers.append(CBORSerializer())
            except ImportError:
                pass

            # try MsgPack WAMP serializer
            try:
                from autobahn.wamp.serializer import MsgPackSerializer
                serializers.append(MsgPackSerializer(batched=True))
                serializers.append(MsgPackSerializer())
            except ImportError:
                pass

            # try UBJSON WAMP serializer
            try:
                from autobahn.wamp.serializer import UBJSONSerializer
                serializers.append(UBJSONSerializer(batched=True))
                serializers.append(UBJSONSerializer())
            except ImportError:
                pass

            # try JSON WAMP serializer
            try:
                from autobahn.wamp.serializer import JsonSerializer
                serializers.append(JsonSerializer(batched=True))
                serializers.append(JsonSerializer())
            except ImportError:
                pass

            if not serializers:
                raise Exception("could not import any WAMP serializers")

        self._serializers = {}
        for ser in serializers:
            self._serializers[ser.SERIALIZER_ID] = ser

        self._transports = {}

        # <Base URL>/open
        #
        self.putChild(b"open", WampLongPollResourceOpen(self))

        self.log.debug("WampLongPollResource initialized")
Exemplo n.º 12
0
    def __init__(self, factory, config):

        # remember transport configuration
        #
        self._config = config

        # explicit list of WAMP serializers
        #
        if u'serializers' in config:
            serializers = []
            sers = set(config['serializers'])

            if u'cbor' in sers:
                # try CBOR WAMP serializer
                try:
                    from autobahn.wamp.serializer import CBORSerializer
                    serializers.append(CBORSerializer())
                except ImportError:
                    self.log.warn(
                        "Warning: could not load WAMP-CBOR serializer")
                else:
                    sers.discard('cbor')

            if u'msgpack' in sers:
                # try MsgPack WAMP serializer
                try:
                    from autobahn.wamp.serializer import MsgPackSerializer
                    serializer = MsgPackSerializer()
                    serializer._serializer.ENABLE_V5 = False  # FIXME
                    serializers.append(serializer)
                except ImportError:
                    self.log.warn(
                        "Warning: could not load WAMP-MsgPack serializer")
                else:
                    sers.discard('msgpack')

            if u'json' in sers:
                # try JSON WAMP serializer
                try:
                    from autobahn.wamp.serializer import JsonSerializer
                    serializers.append(JsonSerializer())
                except ImportError:
                    self.log.warn(
                        "Warning: could not load WAMP-JSON serializer")
                else:
                    sers.discard('json')

            if not serializers:
                raise Exception("no valid WAMP serializers specified")

            if len(sers) > 0:
                raise Exception(
                    "invalid WAMP serializers specified (the following were unprocessed) {}"
                    .format(sers))

        else:
            serializers = None

        # Maximum message size
        #
        self._max_message_size = config.get('max_message_size',
                                            128 * 1024)  # default is 128kB

        rawsocket.WampRawSocketServerFactory.__init__(self, factory,
                                                      serializers)

        self.log.debug(
            "RawSocket transport factory created using {serializers} serializers, max. message size {maxsize}",
            serializers=serializers,
            maxsize=self._max_message_size)
Exemplo n.º 13
0
    async def start(self, reactor, url=None, realm=None, profile=None):
        """
        Start main application. This will read the user configuration, potentially asking
        for a user password.

        :param reactor: Twisted reactor to use.
        :param url: Optionally override network URL as defined in profile.
        :param realm: Optionally override network URL as defined in profile.
        :param profile: User profile name to load.
        :return:
        """
        txaio.start_logging(level='info')

        self.log.info('ok, application starting for user profile "{profile}"',
                      profile=profile)

        if not os.path.isdir(self.DOTDIR):
            os.mkdir(self.DOTDIR)
            self.log.info('dotdir created: "{dotdir}"', dotdir=self.DOTDIR)

        self._config_path = config_path = os.path.join(self.DOTDIR,
                                                       self.DOTFILE)
        self._profile_name = profile or 'default'
        if not os.path.isfile(self._config_path):
            self.log.info('no config exist under "{config_path}"',
                          config_path=self._config_path)
            self._config = UserConfig(self._config_path)
            self._profile = None
        else:
            self._config = UserConfig(self._config_path)

            # FIXME: start modal dialog to get password from user

            def getpw():
                return '123secret'

            self._config.load(cb_get_password=getpw)
            if self._profile_name not in self._config.profiles:
                raise click.ClickException(
                    'no such profile "{}" in config "{}" with {} profiles'.
                    format(self._profile_name, config_path,
                           len(self._config.profiles)))
            else:
                self._profile = self._config.profiles[self._profile_name]
                self.log.info(
                    'user profile "{profile_name}" loaded from "{config_path}":\n\n',
                    config_path=self._config_path,
                    profile_name=self._profile_name)
                pprint(self._profile.marshal())
                print('\n\n')

        extra = {
            'ready': txaio.create_future(),
            'done': txaio.create_future(),
            'running': True,
            'config': self._config,
            'config_path': self._config_path,
            'profile': self._profile,
            'profile_name': self._profile_name,
        }
        # XBR network node used as a directory server and gateway to XBR smart contracts
        network_url = url or (self._profile.network_url
                              if self._profile and self._profile.network_url
                              else 'ws://localhost:8090/ws')

        # WAMP realm on network node, usually "xbrnetwork"
        network_realm = realm or (self._profile.network_realm if self._profile
                                  and self._profile.network_realm else
                                  'xbrnetwork')

        runner = ApplicationRunner(url=network_url,
                                   realm=network_realm,
                                   extra=extra,
                                   serializers=[CBORSerializer()])

        self.log.info(
            'ok, now connecting to "{network_url}", joining realm "{network_realm}" ..',
            network_url=network_url,
            network_realm=network_realm)
        await runner.run(ApplicationClient,
                         reactor=reactor,
                         auto_reconnect=True,
                         start_reactor=False)
        self.log.info('ok, application client connected!')

        session, details = await extra['ready']
        self.log.info('ok, application session joined: {details}',
                      details=details)

        def on_exit(_):
            self.log.info('exiting application ..')
            extra['running'] = False
            txaio.resolve(extra['done'], None)

        win = ApplicationWindow(reactor, session, self._config,
                                self._config_path, self._profile,
                                self._profile_name)
        win.connect("cancel", on_exit)
        win.connect("destroy", on_exit)
        win.show_all()

        await win.start()

        ticks = 0
        while extra['running']:
            ticks += 1
            self.log.info(
                'ok, application main task still running at tick {ticks}',
                ticks=ticks)
            await sleep(5)

        self.log.info('ok, application main task ended!')
Exemplo n.º 14
0
def _main():
    parser = argparse.ArgumentParser()

    parser.add_argument('command',
                        type=str,
                        choices=_COMMANDS,
                        const='noop',
                        nargs='?',
                        help='Command to run')

    parser.add_argument('-d',
                        '--debug',
                        action='store_true',
                        help='Enable debug output.')

    parser.add_argument('--url',
                        dest='url',
                        type=str,
                        default='wss://planet.xbr.network/ws',
                        help='The router URL (default: "wss://planet.xbr.network/ws").')

    parser.add_argument('--realm',
                        dest='realm',
                        type=str,
                        default='xbrnetwork',
                        help='The realm to join (default: "xbrnetwork").')

    parser.add_argument('--ethkey',
                        dest='ethkey',
                        type=str,
                        help='Private Ethereum key (32 bytes as HEX encoded string)')

    parser.add_argument('--cskey',
                        dest='cskey',
                        type=str,
                        help='Private WAMP-cryptosign authentication key (32 bytes as HEX encoded string)')

    parser.add_argument('--username',
                        dest='username',
                        type=str,
                        default=None,
                        help='For on-boarding, the new member username.')

    parser.add_argument('--email',
                        dest='email',
                        type=str,
                        default=None,
                        help='For on-boarding, the new member email address.')

    parser.add_argument('--market',
                        dest='market',
                        type=str,
                        default=None,
                        help='For creating new markets, the market UUID.')

    parser.add_argument('--market_title',
                        dest='market_title',
                        type=str,
                        default=None,
                        help='For creating new markets, the market title.')

    parser.add_argument('--market_label',
                        dest='market_label',
                        type=str,
                        default=None,
                        help='For creating new markets, the market label.')

    parser.add_argument('--market_homepage',
                        dest='market_homepage',
                        type=str,
                        default=None,
                        help='For creating new markets, the market homepage.')

    parser.add_argument('--provider_security',
                        dest='provider_security',
                        type=int,
                        default=None,
                        help='')

    parser.add_argument('--consumer_security',
                        dest='consumer_security',
                        type=int,
                        default=None,
                        help='')

    parser.add_argument('--market_fee',
                        dest='market_fee',
                        type=int,
                        default=None,
                        help='')

    parser.add_argument('--marketmaker',
                        dest='marketmaker',
                        type=str,
                        default=None,
                        help='For creating new markets, the market maker address.')

    parser.add_argument('--actor_type',
                        dest='actor_type',
                        type=int,
                        choices=sorted([ActorType.CONSUMER, ActorType.PROVIDER, ActorType.PROVIDER_CONSUMER]),
                        default=None,
                        help='Actor type: PROVIDER = 1, CONSUMER = 2, PROVIDER_CONSUMER (both) = 3')

    parser.add_argument('--vcode',
                        dest='vcode',
                        type=str,
                        default=None,
                        help='For verifications of actions, the verification UUID.')

    parser.add_argument('--vaction',
                        dest='vaction',
                        type=str,
                        default=None,
                        help='For verifications of actions (on-board, create-market, ..), the verification code.')

    parser.add_argument('--channel',
                        dest='channel',
                        type=str,
                        default=None,
                        help='For creating new channel, the channel UUID.')

    parser.add_argument('--channel_type',
                        dest='channel_type',
                        type=int,
                        choices=sorted([ChannelType.PAYING, ChannelType.PAYMENT]),
                        default=None,
                        help='Channel type: Seller (PAYING) = 1, Buyer (PAYMENT) = 2')

    parser.add_argument('--delegate',
                        dest='delegate',
                        type=str,
                        default=None,
                        help='For creating new channel, the delegate address.')

    parser.add_argument('--amount',
                        dest='amount',
                        type=int,
                        default=None,
                        help='Amount to open the channel with. In tokens of the market coin type, used as means of payment in the market of the channel.')

    args = parser.parse_args()

    if args.command == 'version':
        print('')
        print(' XBR CLI v{}\n'.format(__version__))
        print('   XBRToken   contract address: {} [source: {}]'.format(hlid(XBR_DEBUG_TOKEN_ADDR), XBR_DEBUG_TOKEN_ADDR_SRC))
        print('   XBRNetwork contract address: {} [source: {}]'.format(hlid(XBR_DEBUG_NETWORK_ADDR), XBR_DEBUG_NETWORK_ADDR_SRC))
        print('   XBRMarket  contract address: {} [source: {}]'.format(hlid(XBR_DEBUG_MARKET_ADDR), XBR_DEBUG_MARKET_ADDR_SRC))
        print('   XBRCatalog contract address: {} [source: {}]'.format(hlid(XBR_DEBUG_CATALOG_ADDR), XBR_DEBUG_CATALOG_ADDR_SRC))
        print('   XBRChannel contract address: {} [source: {}]'.format(hlid(XBR_DEBUG_CHANNEL_ADDR), XBR_DEBUG_CHANNEL_ADDR_SRC))
        print('')
    else:
        if args.command is None or args.command == 'noop':
            print('no command given. select from: {}'.format(', '.join(_COMMANDS)))
            sys.exit(0)

        # read or create a user profile
        profile = load_or_create_profile()

        # only start txaio logging after above, which runs click (interactively)
        if args.debug:
            txaio.start_logging(level='debug')
        else:
            txaio.start_logging(level='info')

        log = txaio.make_logger()

        log.info('XBR CLI {version}', version=hlid('v' + __version__))
        log.info('Profile {profile} loaded from {path}', profile=hlval(profile.name), path=hlval(profile.path))

        extra = {
            # user profile and defaults
            'profile': profile,

            # allow to override, and add more arguments from the command line
            'command': args.command,
            'ethkey': binascii.a2b_hex(args.ethkey[2:]) if args.ethkey else None,
            'cskey': binascii.a2b_hex(args.cskey[2:]) if args.cskey else None,
            'username': args.username,
            'email': args.email,
            'market': uuid.UUID(args.market) if args.market else None,
            'market_title': args.market_title,
            'market_label': args.market_label,
            'market_homepage': args.market_homepage,
            'market_provider_security': args.provider_security or 0,
            'market_consumer_security': args.consumer_security or 0,
            'market_fee': args.market_fee or 0,
            'marketmaker': binascii.a2b_hex(args.marketmaker[2:]) if args.marketmaker else None,
            'actor_type': args.actor_type,
            'vcode': args.vcode,
            'vaction': uuid.UUID(args.vaction) if args.vaction else None,
            'channel': uuid.UUID(args.channel) if args.channel else None,
            'channel_type': args.channel_type,
            'delegate': binascii.a2b_hex(args.delegate[2:]) if args.delegate else None,
            'amount': args.amount or 0,
        }
        runner = ApplicationRunner(url=args.url, realm=args.realm, extra=extra, serializers=[CBORSerializer()])

        try:
            log.info('Connecting to "{url}" {realm} ..',
                     url=hlval(args.url), realm=('at realm "' + hlval(args.realm) + '"' if args.realm else ''))
            runner.run(Client, auto_reconnect=False)
        except Exception as e:
            print(e)
            sys.exit(1)
        else:
            sys.exit(0)
Exemplo n.º 15
0
    def __init__(self, factory, cbdir, config, templates):
        """
        Ctor.

        :param factory: WAMP session factory.
        :type factory: An instance of ..
        :param cbdir: The Crossbar.io node directory.
        :type cbdir: str
        :param config: Crossbar transport configuration.
        :type config: dict
        """
        self.debug_traffic = config.get('debug_traffic', False)

        options = config.get('options', {})

        self.showServerVersion = options.get('show_server_version',
                                             self.showServerVersion)
        if self.showServerVersion:
            server = "Crossbar/{}".format(crossbar.__version__)
        else:
            server = "Crossbar"
        externalPort = options.get('external_port', None)

        # explicit list of WAMP serializers
        #
        if 'serializers' in config:
            serializers = []
            sers = set(config['serializers'])

            if u'cbor' in sers:
                # try CBOR WAMP serializer
                try:
                    from autobahn.wamp.serializer import CBORSerializer
                    serializers.append(CBORSerializer(batched=True))
                    serializers.append(CBORSerializer())
                except ImportError:
                    self.log.warn(
                        "Warning: could not load WAMP-CBOR serializer")
                else:
                    sers.discard(u'cbor')

            if u'msgpack' in sers:
                # try MsgPack WAMP serializer
                try:
                    from autobahn.wamp.serializer import MsgPackSerializer
                    serializers.append(MsgPackSerializer(batched=True))
                    serializers.append(MsgPackSerializer())
                except ImportError:
                    self.log.warn(
                        "Warning: could not load WAMP-MsgPack serializer")
                else:
                    sers.discard('msgpack')

            if u'ubjson' in sers:
                # try UBJSON WAMP serializer
                try:
                    from autobahn.wamp.serializer import UBJSONSerializer
                    serializers.append(UBJSONSerializer(batched=True))
                    serializers.append(UBJSONSerializer())
                except ImportError:
                    self.log.warn(
                        "Warning: could not load WAMP-UBJSON serializer")
                else:
                    sers.discard(u'ubjson')

            if u'json' in sers:
                # try JSON WAMP serializer
                try:
                    from autobahn.wamp.serializer import JsonSerializer
                    serializers.append(JsonSerializer(batched=True))
                    serializers.append(JsonSerializer())
                except ImportError:
                    self.log.warn(
                        "Warning: could not load WAMP-JSON serializer")
                else:
                    sers.discard(u'json')

            if not serializers:
                raise Exception("no valid WAMP serializers specified")

            if len(sers) > 0:
                raise Exception(
                    "invalid WAMP serializers specified (the following were unprocessed) {}"
                    .format(sers))

        else:
            serializers = None

        websocket.WampWebSocketServerFactory.__init__(
            self,
            factory,
            serializers=serializers,
            url=config.get('url', None),
            server=server,
            externalPort=externalPort)

        # Crossbar.io node directory
        self._cbdir = cbdir

        # transport configuration
        self._config = config

        # Jinja2 templates for 404 etc
        self._templates = templates

        # cookie tracking
        if 'cookie' in config:
            cookie_store_type = config['cookie']['store']['type']

            # ephemeral, memory-backed cookie store
            if cookie_store_type == 'memory':
                self._cookiestore = CookieStoreMemoryBacked(config['cookie'])
                self.log.info("Memory-backed cookie store active.")

            # persistent, file-backed cookie store
            elif cookie_store_type == 'file':
                cookie_store_file = os.path.abspath(
                    os.path.join(self._cbdir,
                                 config['cookie']['store']['filename']))
                self._cookiestore = CookieStoreFileBacked(
                    cookie_store_file, config['cookie'])
                self.log.info(
                    "File-backed cookie store active {cookie_store_file}",
                    cookie_store_file=cookie_store_file)

            else:
                # should not arrive here as the config should have been checked before
                raise Exception("logic error")
        else:
            self._cookiestore = None

        # set WebSocket options
        set_websocket_options(self, options)
Exemplo n.º 16
0
    parser.add_argument('--verifications',
                        dest='verifications',
                        default='.crossbar/.verifications',
                        type=str,
                        help='XBR node verifications directory')

    args = parser.parse_args()

    if args.debug:
        txaio.start_logging(level='debug')
    else:
        txaio.start_logging(level='info')

    if not args.email:
        args.email = '{}@nodomain'.format(args.username)

    extra = {
        'ethkey': binascii.a2b_hex(args.ethkey),
        'cskey': binascii.a2b_hex(args.cskey),
        'username': args.username,
        'email': args.email,
        'verifications': args.verifications,
    }

    runner = ApplicationRunner(url=args.url,
                               realm=args.realm,
                               extra=extra,
                               serializers=[CBORSerializer()])
    runner.run(XbrDelegate, auto_reconnect=True)
Exemplo n.º 17
0
def _main():
    parser = argparse.ArgumentParser()

    parser.add_argument('command', type=str, choices=_COMMANDS,
                        help='Command to run')

    parser.add_argument('-d',
                        '--debug',
                        action='store_true',
                        help='Enable debug output.')

    parser.add_argument('--url',
                        dest='url',
                        type=str,
                        default='wss://planet.xbr.network/ws',
                        help='The router URL (default: "wss://planet.xbr.network/ws").')

    parser.add_argument('--realm',
                        dest='realm',
                        type=str,
                        default='xbrnetwork',
                        help='The realm to join (default: "xbrnetwork").')

    parser.add_argument('--ethkey',
                        dest='ethkey',
                        type=str,
                        help='Private Ethereum key (32 bytes as HEX encoded string)')

    parser.add_argument('--cskey',
                        dest='cskey',
                        type=str,
                        help='Private WAMP-cryptosign authentication key (32 bytes as HEX encoded string)')

    parser.add_argument('--username',
                        dest='username',
                        type=str,
                        default=None,
                        help='For on-boarding, the new member username.')

    parser.add_argument('--email',
                        dest='email',
                        type=str,
                        default=None,
                        help='For on-boarding, the new member email address.')

    parser.add_argument('--market',
                        dest='market',
                        type=str,
                        default=None,
                        help='For creating new markets, the market UUID.')

    parser.add_argument('--market_title',
                        dest='market_title',
                        type=str,
                        default=None,
                        help='For creating new markets, the market title.')

    parser.add_argument('--market_label',
                        dest='market_label',
                        type=str,
                        default=None,
                        help='For creating new markets, the market label.')

    parser.add_argument('--market_homepage',
                        dest='market_homepage',
                        type=str,
                        default=None,
                        help='For creating new markets, the market homepage.')

    parser.add_argument('--provider_security',
                        dest='provider_security',
                        type=int,
                        default=None,
                        help='')

    parser.add_argument('--consumer_security',
                        dest='consumer_security',
                        type=int,
                        default=None,
                        help='')

    parser.add_argument('--market_fee',
                        dest='market_fee',
                        type=int,
                        default=None,
                        help='')

    parser.add_argument('--marketmaker',
                        dest='marketmaker',
                        type=str,
                        default=None,
                        help='For creating new markets, the market maker address.')

    parser.add_argument('--actor_type',
                        dest='actor_type',
                        type=int,
                        choices=sorted([ActorType.CONSUMER, ActorType.PROVIDER, ActorType.PROVIDER_CONSUMER]),
                        default=None,
                        help='Actor type: PROVIDER = 1, CONSUMER = 2, PROVIDER_CONSUMER (both) = 3')

    parser.add_argument('--vcode',
                        dest='vcode',
                        type=str,
                        default=None,
                        help='For verifications of actions, the verification UUID.')

    parser.add_argument('--vaction',
                        dest='vaction',
                        type=str,
                        default=None,
                        help='For verifications of actions (on-board, create-market, ..), the verification code.')

    parser.add_argument('--channel',
                        dest='channel',
                        type=str,
                        default=None,
                        help='For creating new channel, the channel UUID.')

    parser.add_argument('--channel_type',
                        dest='channel_type',
                        type=int,
                        choices=sorted([ChannelType.PAYING, ChannelType.PAYMENT]),
                        default=None,
                        help='Channel type: Seller (PAYING) = 1, Buyer (PAYMENT) = 2')

    parser.add_argument('--delegate',
                        dest='delegate',
                        type=str,
                        default=None,
                        help='For creating new channel, the delegate address.')

    parser.add_argument('--amount',
                        dest='amount',
                        type=int,
                        default=None,
                        help='Amount to open the channel with. In tokens of the market coin type, used as means of payment in the market of the channel.')

    args = parser.parse_args()

    if args.debug:
        txaio.start_logging(level='debug')
    else:
        txaio.start_logging(level='info')

    extra = {
        'command': args.command,
        'ethkey': binascii.a2b_hex(args.ethkey[2:]),
        'cskey': binascii.a2b_hex(args.cskey[2:]),
        'username': args.username,
        'email': args.email,
        'market': uuid.UUID(args.market) if args.market else None,
        'market_title': args.market_title,
        'market_label': args.market_label,
        'market_homepage': args.market_homepage,
        'market_provider_security': args.provider_security or 0,
        'market_consumer_security': args.consumer_security or 0,
        'market_fee': args.market_fee or 0,
        'marketmaker': binascii.a2b_hex(args.marketmaker[2:]) if args.marketmaker else None,
        'actor_type': args.actor_type,
        'vcode': args.vcode,
        'vaction': uuid.UUID(args.vaction) if args.vaction else None,
        'channel': uuid.UUID(args.channel) if args.channel else None,
        'channel_type': args.channel_type,
        'delegate': binascii.a2b_hex(args.delegate[2:]) if args.delegate else None,
        'amount': args.amount or 0,
    }
    runner = ApplicationRunner(url=args.url, realm=args.realm, extra=extra, serializers=[CBORSerializer()])

    try:
        runner.run(Client, auto_reconnect=False)
    except Exception as e:
        print(e)
        sys.exit(1)
    else:
        sys.exit(0)