Пример #1
0
    def __init__(self, endpoint, ident, secret, retryPolicy=None):
        super(ClientSessionService, self).__init__()

        self.ident = ident

        self.read_queue = defer.DeferredQueue()
        self.subscriptions = set()
        self.protocol = None

        from twisted.internet import reactor

        if isinstance(endpoint, str):
            self.client_endpoint = clientFromString(reactor, endpoint)
        elif hasattr(endpoint, 'connect'):
            self.client_endpoint = endpoint
        else:
            raise ValueError(
                'endpoint must be a str or implement IStreamClientEndpoint')

        self.client_factory = ClientFactory.forProtocol(
            _Protocol, ident, secret)
        self.client_factory.service = self

        self.client_service = ClientService(
            self.client_endpoint,
            self.client_factory,
            retryPolicy=retryPolicy,
        )
        self.client_service.setServiceParent(self)

        self.whenConnected = defer.Deferred()
Пример #2
0
def makeSubscriberService(endpoint, local_ivo, validators, handlers, filters):
    """Create a reconnecting VOEvent subscriber service.

    Parameters
    ----------
    endpoint : implements `twisted.internet.interfaces.IStreamClientEndpoint`
        The endpoint to which the service will connect.
    local_ivo : `str` or `None`
        IVOA identifier for the subscriber.
    validators : `list` of implementers of `~comet.icomet.IValidator`.
        Validators which will be applied to incoming events. Events which fail
        validation will be rejected.
    handlers : `list` of implementers of `~comet.icomet.IHandler`.
        Handlers to which events which pass validation will be passed.
    filters : `list` of `str`
        XPath filters. Will be passed to upstream as a request to filter the
        alerts being sent.

    Notes
    -----
    Upstream brokes may not provide support for XPath filtering; in this case,
    the filters suppplied will be ignored.

    Reconnection is handled according to the default policies of
    `twisted.application.internet.ClientService`.
    """
    factory = VOEventSubscriberFactory(local_ivo, validators,handlers, filters)
    service = ClientService(endpoint, factory)

    return service
Пример #3
0
def connect():
    endpoint = TCP4ClientEndpoint(reactor, '127.0.0.1', 8750)
    factory = Factory()
    factory.protocol = amp.AMP
    service = ClientService(endpoint, factory, retryPolicy=backoffPolicy(0.5, 15.0))
    service.startService()
    return service.whenConnected()
Пример #4
0
    def getMapUpdaterComponentService(self, url, realm, mapUpdater):
        def create(config):
            try:
                session = MapUpdaterComponent(mapUpdater, config)
            except Exception as e:
                # the app component could not be created .. fatal
                print(e)
            else:
                session.debug_app = True
                return session

        sessionFactory = ApplicationSessionFactory(
            ComponentConfig(realm, None))
        sessionFactory.session = create

        transportFactory = WampWebSocketClientFactory(
            sessionFactory, url=url)
        transportFactory.noisy = False
        transportFactory.autoPingInterval = 30
        transportFactory.autoPingTimeout = 30

        isSecure, host, port, resource, path, params = parseWsUrl(url)

        endpoint = HostnameEndpoint(reactor, host.encode('utf8'), port)
        if isSecure:
            contextFactory = optionsForClientTLS(hostname=host)
            endpoint = wrapClientTLS(contextFactory, endpoint)
        return ClientService(endpoint, transportFactory)
Пример #5
0
    def __init__(self, endpoint, factory, devid, username, password):

        self.client = ClientService(endpoint, factory)
        self.connected = False
        self.devid = devid
        self.username = username
        self.password = password
        self.messages = []
Пример #6
0
 def _makeService(self):
     """
     Construct a service for the endpoint as described.
     """
     factory = WebSocketClientFactory()
     factory.protocol = SlackProtocol
     factory.bot = self.bot
     return ClientService(self.bot, factory)
Пример #7
0
 def connect(self, host, port, reconnect=True):
     """Initiate outgoing connection, either persistent or no"""
     print("Initiating connection to %s:%d" % (host, port))
     ep = TCP4ClientEndpoint(self._reactor, host, port)
     if reconnect:
         service = ClientService(ep, self, retryPolicy=lambda x: 1)
         service.startService()
     else:
         ep.connect(self)
Пример #8
0
    def __init__(self, url=None, conn_string=None, authParams=None, reactor=None, **options):
        ''' Creates the client, but does not connect to the server automatically.
        Optional keyword parameters (**options) for...
           Client: url (required), authParams, reactor, conn_string, debug, factory
           protocol: url (required), authParams, heartbeat_interval
           rpc: rpcAckTimeout, rpcResponseTimeout, subscriptionTimeout
           record: recordReadAckTimeout, merge_strategy, recordReadTimeout, recordDeleteTimeout, recordDeepCopy,
           presence: subscriptionTimeout
        '''

        if not url or url is None:
            raise ValueError(
                "url is None; you must specify a  URL for the deepstream server, e.g. ws://localhost:6020/deepstream")
        parse_result = urlparse(url)
        if not authParams or authParams is None:
            authParams = {}
            if parse_result.username and parse_result.password:
                authParams['username'] = parse_result.username
                authParams['password'] = parse_result.password
        if not conn_string or conn_string is None:
            if parse_result.scheme == 'ws':
                if parse_result.hostname:
                    conn_string = 'tcp:%s' % parse_result.hostname
                if parse_result.port:
                    conn_string += ':%s' % parse_result.port
                else:
                    conn_string += ':6020'
        if not conn_string or conn_string is None:
            raise ValueError(
                "Could not parse conn string from URL; you must specify a Twisted endpoint descriptor for the server, e.g. tcp:127.0.0.1:6020")
        if not reactor or reactor is None:
            from twisted.internet import reactor
        self.reactor = reactor
        factory = options.pop('factory', WSDeepstreamFactory)
        self._factory = factory(url, self, debug=options.pop('debug', False), reactor=reactor, **options)
        self._endpoint = clientFromString(reactor, conn_string)
        self._service = ClientService(self._endpoint, self._factory)  # Handles reconnection for us

        EventEmitter.__init__(self)
        self._connection = ConnectionInterface(self, url)
        self._presence = PresenceHandler(self._connection, self, **options)
        self._event = EventHandler(self._connection, self, **options)
        self._rpc = RPCHandler(self._connection, self, **options)
        self._record = RecordHandler(self._connection, self, **options)
        self._message_callbacks = dict()

        self._message_callbacks[
            constants.topic.PRESENCE] = self._presence.handle
        self._message_callbacks[
            constants.topic.EVENT] = self._event.handle
        self._message_callbacks[
            constants.topic.RPC] = self._rpc.handle
        self._message_callbacks[
            constants.topic.RECORD] = self._record.handle
        self._message_callbacks[
            constants.topic.ERROR] = self._on_error
Пример #9
0
 def __init__(self, reactor, endpoint, elements, encoding, clock=None):
     self.__reactor = reactor
     self.__elements = elements
     self.__encoding = encoding
     
     self.__client_service = ClientService(
         endpoint=endpoint,
         factory=Factory.forProtocol(_ControllerProtocol),
         clock=clock)
     self.__client_service.startService()
Пример #10
0
 def start(self):
     """Start connecting to ZenHub."""
     self.__stopping = False
     factory = ZenPBClientFactory()
     self.__service = ClientService(
         self.__endpoint,
         factory,
         retryPolicy=backoffPolicy(initialDelay=0.5, factor=3.0),
     )
     self.__service.startService()
     self.__prepForConnection()
Пример #11
0
    def SetupConnection(self, host, port):
        self.__log.debug("Setting up connection! %s %s " % (host, port))

        factory = Factory.forProtocol(NeoNode)
        endpoint = clientFromString(reactor,"tcp:host=%s:port=%s:timeout=5" % (host,port))

        connectingService = ClientService(
            endpoint,
            factory,
            retryPolicy=backoffPolicy(.5, factor=3.0)
        )
        connectingService.startService()
Пример #12
0
def main():
    from twisted.internet import reactor, ssl
    # Simple 'TrackMarket' example displaying all events processed
    tlsctx = optionsForClientTLS(u'ws.bitcoin.de', None)
    endpoint = endpoints.SSL4ClientEndpoint(reactor, 'ws.bitcoin.de', 443,
                                            tlsctx)
    factory = BitcoinDEMarket()

    connService = ClientService(endpoint, factory)
    connService.startService()

    reactor.run()
Пример #13
0
    def __init__(self, reactor):
        self.reactor = reactor

        print "BitcoinDESubscribeFactory - constructor"

        tlsctx = optionsForClientTLS(u'ws.bitcoin.de')  #,trustRoot=None)
        self.endpoint = endpoints.SSL4ClientEndpoint(self.reactor,
                                                     'ws.bitcoin.de', 443,
                                                     tlsctx)
        self.factory = BitcoinDESubscribeFactory()

        self.connService = ClientService(self.endpoint, self.factory)
        self.connService.startService()
Пример #14
0
 def build_irc(self):
     """The main starting method that creates a protocol object
     according to the config variables, ready for whenever
     the reactor starts running.
     """
     wlog('building irc')
     if self.tx_irc_client:
         raise Exception('irc already built')
     if self.usessl.lower() == 'true' and not self.socks5.lower() == 'true':
         factory = TxIRCFactory(self)
         ctx = ClientContextFactory()
         reactor.connectSSL(self.serverport[0], self.serverport[1],
                            factory, ctx)
     elif self.socks5.lower() == 'true':
         factory = TxIRCFactory(self)
         #str() casts needed else unicode error
         torEndpoint = TCP4ClientEndpoint(reactor, str(self.socks5_host),
                                          self.socks5_port)
         ircEndpoint = SOCKS5ClientEndpoint(str(self.serverport[0]),
                                            self.serverport[1], torEndpoint)
         if self.usessl.lower() == 'true':
             ctx = ClientContextFactory()
             tlsEndpoint = TLSWrapClientEndpoint(ctx, ircEndpoint)
             myRS = ClientService(tlsEndpoint, factory)
             myRS.startService()
         else:
             myRS = ClientService(ircEndpoint, factory)
             myRS.startService()
     else:
         try:
             factory = TxIRCFactory(self)
             wlog('build_irc: ', self.serverport[0], self.serverport[1],
                  self.channel)
             self.tcp_connector = reactor.connectTCP(
                     self.serverport[0], self.serverport[1], factory)
         except Exception as e:
             wlog('error in buildirc: ' + repr(e))
Пример #15
0
    def _create_client_service(self, nodeurl, api_token):
        url = parse(nodeurl)
        wsurl = url.replace(scheme="ws").child("private", "logs", "v1")

        factory = WebSocketClientFactory(
            url=wsurl.to_uri().to_text(),
            headers={
                "Authorization": "{} {}".format("tahoe-lafs", api_token),
            },
        )
        factory.protocol = TahoeLogReader
        factory.streamedlogs = self

        endpoint = TCP4ClientEndpoint(self._reactor, url.host, url.port)
        client_service = ClientService(endpoint, factory, clock=self._reactor)
        return client_service
Пример #16
0
    def test_wb_heartbeat(self):
        """
        If heartbeat checks fail due to network issues, we keep re-trying
        until the network recovers.
        """
        self.service.stopService()

        # Put a TCP proxy between NotificationSource and RabbitMQ, to simulate
        # packets getting dropped on the floor.
        proxy = ProxyService(self.rabbit.config.hostname,
                             self.rabbit.config.port)
        proxy.startService()
        self.addCleanup(proxy.stopService)
        self.endpoint._port = proxy.port
        self.service = ClientService(self.endpoint,
                                     self.factory,
                                     retryPolicy=self.policy)
        self.connector._service = self.service
        self.service.startService()

        # This will make the connector setup the channel before we call
        # get(), so by the time we call it in the next line all
        # connector-related deferreds will fire synchronously and the
        # code will block on basic-consume.
        channel = yield self.connector()

        deferred = self.source.get("uuid", 0)

        # Start dropping packets on the floor
        proxy.block()

        # Publish a notification, which won't be delivered just yet.
        yield self.channel.basic_publish(routing_key="uuid",
                                         content=Content("hello"))

        # Wait for the first connection to terminate, because heartbeat
        # checks will fail.
        yield channel.client.disconnected.wait()

        # Now let packets flow again.
        proxy.unblock()

        # The situation got recovered.
        notification = yield deferred
        self.assertEqual("hello", notification.payload)
        self.assertEqual(2, proxy.connections)
Пример #17
0
def make_plugin(config, http=None):
    slack_config = SlackConfig(config)

    api_client = SlackWebClient(slack_config.token)
    endpoint = SlackEndpoint(api_client)
    plugin = SlackPlugin(api_client)
    factory = SlackClientFactory(
        plugin=plugin,
        useragent="Harold ([email protected])",
    )
    factory.setProtocolOptions(
        autoPingInterval=5,
        autoPingTimeout=10,
    )
    service = ClientService(endpoint, factory)
    plugin.add_service(service)
    return plugin
Пример #18
0
def make_plugin(application, app_config):
    slack_config = config.parse_config(app_config, {
        "token": config.String,
    })

    api_client = SlackWebClient(slack_config.token)
    endpoint = SlackEndpoint(api_client)
    plugin = SlackPlugin(api_client)
    factory = SlackClientFactory(
        plugin=plugin,
        useragent="Harold ([email protected])",
    )
    factory.setProtocolOptions(
        autoPingInterval=5,
        autoPingTimeout=10,
    )
    service = ClientService(endpoint, factory)
    service.setServiceParent(application)
    return plugin
Пример #19
0
 def start(self):
     for server in cycle(self.config['default_servers']):
         endpoint = clientFromString(reactor, 'tcp:{}:{}'.format(*server))
         self.service = ClientService(endpoint, StratumClientFactory(self))
         self.service.startService()
         try:
             self.client = yield self.service.whenConnected(
                 failAfterFailures=2)
             yield self.ensure_server_version()
             self._on_connected_controller.add(True)
             yield self.client.on_disconnected.first
         except CancelledError:
             return
         except Exception as e:
             pass
         finally:
             self.client = None
         if not self.running:
             return
Пример #20
0
    def __init__(
        self,
        host: str,
        port: int,
        maximum_buffer: int = 1000,
        level=logging.NOTSET,
        _reactor=None,
    ):
        super().__init__(level=level)
        self.host = host
        self.port = port
        self.maximum_buffer = maximum_buffer

        self._buffer = deque()  # type: Deque[logging.LogRecord]
        self._connection_waiter = None  # type: Optional[Deferred]
        self._producer = None  # type: Optional[LogProducer]

        # Connect without DNS lookups if it's a direct IP.
        if _reactor is None:
            from twisted.internet import reactor

            _reactor = reactor

        try:
            ip = ip_address(self.host)
            if isinstance(ip, IPv4Address):
                endpoint = TCP4ClientEndpoint(
                    _reactor, self.host,
                    self.port)  # type: IStreamClientEndpoint
            elif isinstance(ip, IPv6Address):
                endpoint = TCP6ClientEndpoint(_reactor, self.host, self.port)
            else:
                raise ValueError("Unknown IP address provided: %s" %
                                 (self.host, ))
        except ValueError:
            endpoint = HostnameEndpoint(_reactor, self.host, self.port)

        factory = Factory.forProtocol(Protocol)
        self._service = ClientService(endpoint, factory, clock=_reactor)
        self._service.startService()
        self._stopping = False
        self._connect()
Пример #21
0
    def start(self) -> None:

        # Connect without DNS lookups if it's a direct IP.
        try:
            ip = ip_address(self.host)
            if isinstance(ip, IPv4Address):
                endpoint = TCP4ClientEndpoint(
                    self.hs.get_reactor(), self.host, self.port
                )
            elif isinstance(ip, IPv6Address):
                endpoint = TCP6ClientEndpoint(
                    self.hs.get_reactor(), self.host, self.port
                )
        except ValueError:
            endpoint = HostnameEndpoint(self.hs.get_reactor(), self.host, self.port)

        factory = Factory.forProtocol(Protocol)
        self._service = ClientService(endpoint, factory, clock=self.hs.get_reactor())
        self._service.startService()
        self._connect()
Пример #22
0
    def connect_samsung(self, p_device_obj):
        def cb_connectedNow(SamsungClient):
            LOG.debug('Connected Now')
            SamsungClient.send_command('1PWRQSTN')

        def eb_failed(fail_reason):
            LOG.warn(
                "initial Samsung connection failed: {}".format(fail_reason))
            l_ReconnectingService.stopService()

        l_reactor = self.m_pyhouse_obj._Twisted.Reactor
        try:
            # l_host = convert.long_to_str(p_device_obj.IPv4)
            l_host = 'samsung-tv'
            l_port = p_device_obj.Port
            l_endpoint_str = 'tcp:{}:port={}'.format(l_host, l_port)
            l_endpoint = clientFromString(l_reactor, l_endpoint_str)
            l_factory = Factory.forProtocol(SamsungProtocol)
            l_ReconnectingService = ClientService(l_endpoint, l_factory)
            l_ReconnectingService.setName('Samsung ')
            waitForConnection = l_ReconnectingService.whenConnected(
                failAfterFailures=1)
            LOG.debug('Endpoint: {}'.format(l_endpoint_str))
            LOG.debug('{}'.format(
                PrettyFormatAny.form(l_endpoint, 'Endpoint', 190)))
            LOG.debug('{}'.format(
                PrettyFormatAny.form(l_factory, 'Factory', 190)))
            LOG.debug('{}'.format(
                PrettyFormatAny.form(l_ReconnectingService, 'ReconnectService',
                                     190)))

            waitForConnection.addCallbacks(cb_connectedNow, eb_failed)
            l_ReconnectingService.startService()
            p_device_obj._Endpoint = l_endpoint
            p_device_obj._Factory = l_factory
            p_device_obj._isRunning = True
            LOG.info("Started Samsung - Host:{}; Port:{}".format(
                l_host, l_port))
        except Exception as e_err:
            LOG.error('Error found: {}'.format(e_err))
        pass
Пример #23
0
 def start(self):
     for server in cycle(self.config['default_servers']):
         connection_string = 'tcp:{}:{}'.format(*server)
         endpoint = clientFromString(reactor, connection_string)
         log.debug("Attempting connection to SPV wallet server: %s", connection_string)
         self.service = ClientService(endpoint, StratumClientFactory(self))
         self.service.startService()
         try:
             self.client = yield self.service.whenConnected(failAfterFailures=2)
             yield self.ensure_server_version()
             log.info("Successfully connected to SPV wallet server: %s", connection_string)
             self._on_connected_controller.add(True)
             yield self.client.on_disconnected.first
         except CancelledError:
             return
         except Exception:  # pylint: disable=broad-except
             log.exception("Connecting to %s raised an exception:", connection_string)
         finally:
             self.client = None
         if not self.running:
             return
Пример #24
0
    def setUp(self):
        super(NotificationSourceIntegrationTest, self).setUp()
        self.endpoint = AMQEndpoint(reactor,
                                    self.rabbit.config.hostname,
                                    self.rabbit.config.port,
                                    username="******",
                                    password="******",
                                    heartbeat=1)
        self.policy = backoffPolicy(initialDelay=0)
        self.factory = AMQFactory(spec=AMQP0_8_SPEC_PATH)
        self.service = ClientService(self.endpoint,
                                     self.factory,
                                     retryPolicy=self.policy)
        self.connector = NotificationConnector(self.service)
        self.source = NotificationSource(self.connector)

        self.client = yield self.endpoint.connect(self.factory)
        self.channel = yield self.client.channel(1)
        yield self.channel.channel_open()
        yield self.channel.queue_declare(queue="uuid")

        self.service.startService()
Пример #25
0
    def run(self, make, start_reactor=True, auto_reconnect=False, log_level='info', endpoint=None, reactor=None):
        """
        Run the application component.

        :param make: A factory that produces instances of :class:`autobahn.twisted.wamp.ApplicationSession`
           when called with an instance of :class:`autobahn.wamp.types.ComponentConfig`.
        :type make: callable

        :param start_reactor: When ``True`` (the default) this method starts
           the Twisted reactor and doesn't return until the reactor
           stops. If there are any problems starting the reactor or
           connect()-ing, we stop the reactor and raise the exception
           back to the caller.

        :returns: None is returned, unless you specify
            ``start_reactor=False`` in which case the Deferred that
            connect() returns is returned; this will callback() with
            an IProtocol instance, which will actually be an instance
            of :class:`WampWebSocketClientProtocol`
        """
        self.log.debug('{klass}.run()', klass=self.__class__.__name__)

        if start_reactor:
            # only select framework, set loop and start logging when we are asked
            # start the reactor - otherwise we are running in a program that likely
            # already tool care of all this.
            from twisted.internet import reactor
            txaio.use_twisted()
            txaio.config.loop = reactor
            txaio.start_logging(level=log_level)

        if callable(make):
            # factory for use ApplicationSession
            def create():
                cfg = ComponentConfig(self.realm, self.extra, runner=self)
                try:
                    session = make(cfg)
                except Exception:
                    self.log.failure('ApplicationSession could not be instantiated: {log_failure.value}')
                    if start_reactor and reactor.running:
                        reactor.stop()
                    raise
                else:
                    return session
        else:
            create = make

        if self.url.startswith(u'rs'):
            # try to parse RawSocket URL ..
            isSecure, host, port = parse_rs_url(self.url)

            # use the first configured serializer if any (which means, auto-choose "best")
            serializer = self.serializers[0] if self.serializers else None

            # create a WAMP-over-RawSocket transport client factory
            transport_factory = WampRawSocketClientFactory(create, serializer=serializer)

        else:
            # try to parse WebSocket URL ..
            isSecure, host, port, resource, path, params = parse_ws_url(self.url)

            # create a WAMP-over-WebSocket transport client factory
            transport_factory = WampWebSocketClientFactory(create, url=self.url, serializers=self.serializers, proxy=self.proxy, headers=self.headers)

            # client WebSocket settings - similar to:
            # - http://crossbar.io/docs/WebSocket-Compression/#production-settings
            # - http://crossbar.io/docs/WebSocket-Options/#production-settings

            # The permessage-deflate extensions offered to the server ..
            offers = [PerMessageDeflateOffer()]

            # Function to accept permessage_delate responses from the server ..
            def accept(response):
                if isinstance(response, PerMessageDeflateResponse):
                    return PerMessageDeflateResponseAccept(response)

            # set WebSocket options for all client connections
            transport_factory.setProtocolOptions(maxFramePayloadSize=1048576,
                                                 maxMessagePayloadSize=1048576,
                                                 autoFragmentSize=65536,
                                                 failByDrop=False,
                                                 openHandshakeTimeout=2.5,
                                                 closeHandshakeTimeout=1.,
                                                 tcpNoDelay=True,
                                                 autoPingInterval=10.,
                                                 autoPingTimeout=5.,
                                                 autoPingSize=4,
                                                 perMessageCompressionOffers=offers,
                                                 perMessageCompressionAccept=accept)

        # supress pointless log noise
        transport_factory.noisy = False

        if endpoint:
            client = endpoint
        else:
            # if user passed ssl= but isn't using isSecure, we'll never
            # use the ssl argument which makes no sense.
            context_factory = None
            if self.ssl is not None:
                if not isSecure:
                    raise RuntimeError(
                        'ssl= argument value passed to %s conflicts with the "ws:" '
                        'prefix of the url argument. Did you mean to use "wss:"?' %
                        self.__class__.__name__)
                context_factory = self.ssl
            elif isSecure:
                from twisted.internet.ssl import optionsForClientTLS
                context_factory = optionsForClientTLS(host)

            from twisted.internet import reactor
            if self.proxy is not None:
                from twisted.internet.endpoints import TCP4ClientEndpoint
                client = TCP4ClientEndpoint(reactor, self.proxy['host'], self.proxy['port'])
                transport_factory.contextFactory = context_factory
            elif isSecure:
                from twisted.internet.endpoints import SSL4ClientEndpoint
                assert context_factory is not None
                client = SSL4ClientEndpoint(reactor, host, port, context_factory)
            else:
                from twisted.internet.endpoints import TCP4ClientEndpoint
                client = TCP4ClientEndpoint(reactor, host, port)

        # as the reactor shuts down, we wish to wait until we've sent
        # out our "Goodbye" message; leave() returns a Deferred that
        # fires when the transport gets to STATE_CLOSED
        def cleanup(proto):
            if hasattr(proto, '_session') and proto._session is not None:
                if proto._session.is_attached():
                    return proto._session.leave()
                elif proto._session.is_connected():
                    return proto._session.disconnect()

        # when our proto was created and connected, make sure it's cleaned
        # up properly later on when the reactor shuts down for whatever reason
        def init_proto(proto):
            self._connect_successes += 1
            reactor.addSystemEventTrigger('before', 'shutdown', cleanup, proto)
            return proto

        use_service = False
        if auto_reconnect:
            try:
                # since Twisted 16.1.0
                from twisted.application.internet import ClientService
                from twisted.application.internet import backoffPolicy
                use_service = True
            except ImportError:
                use_service = False

        if use_service:
            # this code path is automatically reconnecting ..
            self.log.debug('using t.a.i.ClientService')

            if self.max_retries or self.initial_retry_delay or self.max_retry_delay or self.retry_delay_growth or self.retry_delay_jitter:
                kwargs = {}
                for key, val in [('initialDelay', self.initial_retry_delay),
                                 ('maxDelay', self.max_retry_delay),
                                 ('factor', self.retry_delay_growth),
                                 ('jitter', lambda: random.random() * self.retry_delay_jitter)]:
                    if val:
                        kwargs[key] = val

                # retry policy that will only try to reconnect if we connected
                # successfully at least once before (so it fails on host unreachable etc ..)
                def retry(failed_attempts):
                    if self._connect_successes > 0 and (self.max_retries == -1 or failed_attempts < self.max_retries):
                        return backoffPolicy(**kwargs)(failed_attempts)
                    else:
                        print('hit stop')
                        self.stop()
                        return 100000000000000
            else:
                retry = backoffPolicy()

            self._client_service = ClientService(client, transport_factory, retryPolicy=retry)
            self._client_service.startService()

            d = self._client_service.whenConnected()

        else:
            # this code path is only connecting once!
            self.log.debug('using t.i.e.connect()')

            d = client.connect(transport_factory)

        # if we connect successfully, the arg is a WampWebSocketClientProtocol
        d.addCallback(init_proto)

        # if the user didn't ask us to start the reactor, then they
        # get to deal with any connect errors themselves.
        if start_reactor:
            # if an error happens in the connect(), we save the underlying
            # exception so that after the event-loop exits we can re-raise
            # it to the caller.

            class ErrorCollector(object):
                exception = None

                def __call__(self, failure):
                    self.exception = failure.value
                    reactor.stop()
            connect_error = ErrorCollector()
            d.addErrback(connect_error)

            # now enter the Twisted reactor loop
            reactor.run()

            # if we exited due to a connection error, raise that to the
            # caller
            if connect_error.exception:
                raise connect_error.exception

        else:
            # let the caller handle any errors
            return d
Пример #26
0
    def __init__(self,
                 buildmaster_host,
                 port,
                 name,
                 passwd,
                 basedir,
                 keepalive,
                 usePTY=None,
                 keepaliveTimeout=None,
                 umask=None,
                 maxdelay=None,
                 numcpus=None,
                 unicode_encoding=None,
                 useTls=None,
                 allow_shutdown=None,
                 maxRetries=None,
                 connection_string=None):

        assert usePTY is None, "worker-side usePTY is not supported anymore"
        assert (connection_string is None
                or (buildmaster_host, port) == (None, None)), (
                    "If you want to supply a connection string, "
                    "then set host and port to None")

        service.MultiService.__init__(self)
        WorkerBase.__init__(self,
                            name,
                            basedir,
                            umask=umask,
                            unicode_encoding=unicode_encoding)
        if keepalive == 0:
            keepalive = None

        name = unicode2bytes(name, self.bot.unicode_encoding)
        passwd = unicode2bytes(passwd, self.bot.unicode_encoding)

        self.numcpus = numcpus
        self.shutdown_loop = None

        if allow_shutdown == 'signal':
            if not hasattr(signal, 'SIGHUP'):
                raise ValueError("Can't install signal handler")
        elif allow_shutdown == 'file':
            self.shutdown_file = os.path.join(basedir, 'shutdown.stamp')
            self.shutdown_mtime = 0

        self.allow_shutdown = allow_shutdown
        bf = self.bf = BotFactory(buildmaster_host, port, keepalive, maxdelay)
        bf.startLogin(credentials.UsernamePassword(name, passwd),
                      client=self.bot)
        if connection_string is None:
            if useTls:
                connection_type = 'tls'
            else:
                connection_type = 'tcp'

            connection_string = '{}:host={}:port={}'.format(
                connection_type,
                buildmaster_host.replace(':', r'\:'),  # escape ipv6 addresses
                port)
        endpoint = clientFromString(reactor, connection_string)

        def policy(attempt):
            if maxRetries and attempt >= maxRetries:
                reactor.stop()
            return backoffPolicy()(attempt)

        pb_service = ClientService(endpoint, bf, retryPolicy=policy)
        self.addService(pb_service)
Пример #27
0
                self.room_name.encode() + b"\n" + self.user_name.encode() +
                b": " + data)
        else:
            self.messanger.connectionLost()
            self.messanger = None
            sys.stdin = sys.__stdin__
            sys.stdout = sys.__stdout__
            self.transport.write(b"LEAVE" + self.room_name.encode())

    def catch_leave(self,
                    data):  # Data == None. Will change if implement ACK!!/NACK
        self.converse()

    def catch_message(self, data):
        self.messanger.dataSend(data)

    def catch_create(self, data):
        mssg = {"NACK": "No. Try again.\n", "ACK": "We've made your room.\n"}
        sys.stdout.write(mssg[data.decode()])
        self.converse()

    def panic(self):
        sys.stdout.write("PANIC!!!!\n")


socket = TCP4ClientEndpoint(reactor, serverIP, serverPort)
proto = connectProtocol(socket, Client())
theConnection = ClientService(socket, proto)
theConnection.startService()
reactor.run()  # Begin running Twisted's OS interacting processes.
Пример #28
0
        # this is to clean up stuff. it is not our business to
        # possibly reconnect the underlying connection
        self._countdown -= 1
        if self._countdown <= 0:
            try:
                reactor.stop()
            except ReactorNotRunning:
                pass


if __name__ == '__main__':
    txaio.start_logging(level='info')

    # create a WAMP session object. this is reused across multiple
    # reconnects (if automatically reconnected)
    session = MyAppSession(ComponentConfig('realm1', {}))

    # create a WAMP transport factory
    transport = WampWebSocketClientFactory(session,
                                           url='ws://localhost:8080/ws')

    # create a connecting endpoint
    endpoint = TCP4ClientEndpoint(reactor, 'localhost', 8080)

    # create and start an automatically reconnecting client
    service = ClientService(endpoint, transport)
    service.startService()

    # enter the event loop
    reactor.run()
Пример #29
0
    def makeReconnector(self,
                        fireImmediately=True,
                        startService=True,
                        protocolType=Protocol,
                        **kw):
        """
        Create a L{ClientService} along with a L{ConnectInformation} indicating
        the connections in progress on its endpoint.

        @param fireImmediately: Should all of the endpoint connection attempts
            fire synchronously?
        @type fireImmediately: L{bool}

        @param startService: Should the L{ClientService} be started before
            being returned?
        @type startService: L{bool}

        @param protocolType: a 0-argument callable returning a new L{IProtocol}
            provider to be used for application-level protocol connections.

        @param kw: Arbitrary keyword arguments to be passed on to
            L{ClientService}

        @return: a 2-tuple of L{ConnectInformation} (for information about test
            state) and L{ClientService} (the system under test).  The
            L{ConnectInformation} has 2 additional attributes;
            C{applicationFactory} and C{applicationProtocols}, which refer to
            the unwrapped protocol factory and protocol instances passed in to
            L{ClientService} respectively.
        """
        nkw = {}
        nkw.update(clock=Clock())
        nkw.update(kw)
        clock = nkw['clock']
        cq, endpoint = endpointForTesting(fireImmediately=fireImmediately)

        # `endpointForTesting` is totally generic to any LLPI client that uses
        # endpoints, and maintains all its state internally; however,
        # applicationProtocols and applicationFactory are bonus attributes that
        # are only specifically interesitng to tests that use wrapper
        # protocols.  For now, set them here, externally.

        applicationProtocols = cq.applicationProtocols = []

        class RememberingFactory(Factory, object):
            protocol = protocolType

            def buildProtocol(self, addr):
                result = super(RememberingFactory, self).buildProtocol(addr)
                applicationProtocols.append(result)
                return result

        cq.applicationFactory = factory = RememberingFactory()

        service = ClientService(endpoint, factory, **nkw)

        def stop():
            service._protocol = None
            if service.running:
                service.stopService()
            # Ensure that we don't leave any state in the reactor after
            # stopService.
            self.assertEqual(clock.getDelayedCalls(), [])

        self.addCleanup(stop)
        if startService:
            service.startService()
        return cq, service
Пример #30
0
                                        '|'.join(dynamic_commands.keys()) +
                                        ')\s*).*')
    static_commands_regex = re.compile(
        '\s*(' + triggers + ')\s*((' +
        '|'.join(cmd_cfg['static_commands'].keys()) + ')\s*).*')
    help_command_regex = re.compile('\s*(' + triggers + ')\s*(help\s*).*')

    markov = MarkovBrain(config['brain']['brain_file'],
                         config['brain']['chain_length'],
                         config['brain']['max_words'])

    # Lookup actual address for host (twisted only uses ipv6 if given an explicit ipv6 address)
    host_info = socket.getaddrinfo(irc_cfg['host'], irc_cfg['port'], 0, 0,
                                   socket.IPPROTO_TCP,
                                   socket.AI_CANONNAME)[0][4]
    client_string = "%s:%s:%u" % ('tls' if irc_cfg['ssl'] else 'tcp',
                                  host_info[0].replace(':',
                                                       '\:'), host_info[1])

    endpoint = clientFromString(reactor, client_string)
    bot_client_service = ClientService(
        endpoint,
        sadfaceBotFactory(config, markov, dynamic_commands,
                          dynamic_commands_regex, static_commands_regex,
                          help_command_regex))
    bot_client_service.startService()

    reactor.run()

    markov.close()