def test_http(self):
        """
        When connecting to a HTTP server, a PB connection times
        out.
        """
        result = Deferred()

        site = Site(Data("", "text/plain"))
        client = HangCheckFactory(PBClientFactory(),
                                  lambda: result.callback(None))

        self.patch(HangCheckProtocol, '_HUNG_CONNECTION_TIMEOUT', 0.1)

        connected_server_and_client(
            self,
            site,
            client,
        )

        timer = reactor.callLater(2, result.cancel)
        result.addCallback(lambda _: timer.cancel())

        def check_for_timeout(reason):
            reason.trap(CancelledError)
            raise Exception("Didn't not hangup")

        result.addErrback(check_for_timeout)

        return result
Exemple #2
0
def main(reactor, cred, masterIP, masterPort, commPort, uid):
    f = open('/opt/rce/data/env.log', 'w')  # TODO: Use os.getenv('HOME') ?
    log.startLogging(f)

    rospy.init_node('RCE_Master')
    print 'connect to ', masterIP, masterPort

    factory = PBClientFactory()
    reactor.connectTCP(masterIP, masterPort, factory)

    client = EnvironmentClient(reactor, commPort)

    def terminate():
        reactor.callFromThread(client.terminate)
        reactor.callFromThread(reactor.stop)

    rospy.on_shutdown(terminate)

    def _err(reason):
        print(reason)
        terminate()

    d = factory.login(cred, (client, uid))
    d.addCallback(client.registerAvatar)
    d.addCallback(client.createEnvironment)
    d.addErrback(_err)

    reactor.run(installSignalHandlers=False)

    f.close()
    def test_http(self):
        """
        When connecting to a HTTP server, a PB connection times
        out.
        """
        result = defer.Deferred()

        site = Site(Data("", "text/plain"))
        client = HangCheckFactory(
            PBClientFactory(), lambda: result.callback(None))

        self.patch(HangCheckProtocol, '_HUNG_CONNECTION_TIMEOUT', 0.1)

        d_connected = connected_server_and_client(
            self, site, client,
        )

        def cancel_all():
            result.cancel()
            d_connected.cancel()

        timer = reactor.callLater(2, cancel_all)

        try:
            yield result
        except defer.CancelledError:
            raise Exception('Timeout did not happen')
        finally:
            d_connected.cancel()
            timer.cancel()
Exemple #4
0
    def login(self, userID, robotID, password):
        """ Callback for Robot connection to login and authenticate.

            @param userID:      User ID under which the robot is logging in.
            @type  userID:      str

            @param robotID:     Unique ID of the robot in the namespace of the
                                user under which the robot is logging in.
            @type  robotID:     str

            @param password:    Hashed password as hex-encoded string which is
                                used to authenticate the user.
            @type  password:    str

            @return:            Representation of the connection to the robot
                                which is used in the Robot process.
                                (type: rce.robot.Connection)
            @rtype:             twisted.internet.defer.Deferred
        """
        conn = Connection(self, userID, robotID)

        factory = PBClientFactory()
        self._reactor.connectTCP(self._masterIP, self._masterPort, factory)

        d = factory.login(UsernamePassword(userID, password))
        d.addCallback(self._cbAuthenticated, conn)
        d.addCallback(self._cbConnected, conn)
        d.addCallback(lambda _: conn)
        return d
Exemple #5
0
 def connect(self):
     """Connect to the remote service."""
     self.factory = PBClientFactory()
     self.client = yield client_connect(self.factory, self.service_name,
                                        self.service_cmdline,
                                        self.service_description)
     root = yield self.factory.getRootObject()
     yield self._request_remote_objects(root)
     yield self.register_to_signals()
Exemple #6
0
    def connectionMade(self):
        """ Create a PBClientFactory and connect to master when ConsoleClient
            connected to StandardIO. Prompt user for Username
        """
        HistoricRecvLine.connectionMade(self)
        self._factory = PBClientFactory()

        reactor.connectTCP(self._masterIP, self._console_port, self._factory)  #@UndefinedVariable
        self.terminal.write("Username: ")
Exemple #7
0
 def run(self, *args, **kwargs):
     def connected(reference):
         self._reference = reference
         return super(Client, self).run(*args, **kwargs)
     client = PBClientFactory()
     d = client.getRootObject()
     d.addCallback(connected)
     self._reactor.connectTCP('127.0.0.1', self._port, client)
     return d
Exemple #8
0
 def reconnect(self):
     """Reconnect with the server."""
     self.factory = PBClientFactory()
     self.client = yield client_connect(self.factory, self.service_name,
                                        self.service_cmdline,
                                        self.service_description)
     root = yield self.factory.getRootObject()
     # loop over the already present remote clients and reset their remotes
     for name in self.clients:
         remote = yield root.callRemote('get_%s' % name)
         remote_client = getattr(self, name)
         remote_client.remote = remote
     yield self.register_to_signals()
Exemple #9
0
def _sendMessage(channel, message):
    """
    Establish a connection to the bot and direct it to send the given message
    to the given channel.

    @type channel: C{str}
    @type message: C{str}
    """
    messageFactory = PBClientFactory()
    reactor.connectTCP(BOT_HOST, BOT_PORT, messageFactory)

    def cbGotRoot(rootObj):
        return rootObj.callRemote('message', channel, message)

    rootDeferred = messageFactory.getRootObject()
    rootDeferred.addCallback(cbGotRoot)
    rootDeferred.addErrback(err)
    rootDeferred.addCallback(lambda ign: reactor.stop())
Exemple #10
0
 def _reconnect(self):
     try:
         if self._client:
             self._client.disconnect()
         self._client = PBClientFactory()
         if self._listener:
             self._listener.disconnect()
         self._listener = reactor.connectTCP(self.forwardserver,
                                             self.forwardport, self._client)
         self._remote = self._client.login(Anonymous())
         self._remote.addCallback(self._login)
         self._remote.addErrback(self._loginFailed)
     except Exception, e:
         logger.error(
             "[output:%s] failed to connect to remote collector: %s" %
             (self.name, str(e)))
         logger.error("[output:%s] will retry to connect in %i seconds" %
                      (self.name, self.retryinterval))
         self._backoff = reactor.callLater(self.retryinterval,
                                           self._reconnect)
Exemple #11
0
def main():
    """
    Connect to a PB server running on port 8800 on localhost and log in to
    it, both anonymously and using a username/password it will recognize.
    """
    startLogging(stdout)
    factory = PBClientFactory()
    reactor.connectTCP("localhost", 8800, factory)

    anonymousLogin = factory.login(Anonymous())
    anonymousLogin.addCallback(connected)
    anonymousLogin.addErrback(error, "Anonymous login failed")

    usernameLogin = factory.login(UsernamePassword("user1", "pass1"))
    usernameLogin.addCallback(connected)
    usernameLogin.addErrback(error, "Username/password login failed")

    bothDeferreds = gatherResults([anonymousLogin, usernameLogin])
    bothDeferreds.addCallback(finished)

    reactor.run()
Exemple #12
0
def main(reactor, cred, masterIP, masterPort, consolePort, extIP, extPort,
         commPort, pkgPath, customConverters):
    log.startLogging(sys.stdout)

    def _err(reason):
        print(reason)
        reactor.stop()

    factory = PBClientFactory()
    reactor.connectTCP(masterIP, masterPort, factory)

    rosPath = []
    for path in get_ros_paths() + [p for p, _ in pkgPath]:
        if path not in rosPath:
            rosPath.append(path)

    loader = Loader(rosPath)
    converter = Converter(loader)

    for customConverter in customConverters:
        # Get correct path/name of the converter
        module, className = customConverter.rsplit('.', 1)

        # Load the converter
        mod = __import__(module, fromlist=[className])
        converter.addCustomConverter(getattr(mod, className))

    client = RobotClient(reactor, masterIP, consolePort, commPort, extIP,
                         extPort, loader, converter)
    d = factory.login(cred, client)
    d.addCallback(lambda ref: setattr(client, '_avatar', ref))
    d.addErrback(_err)

    # portal = Portal(client, (client,))
    robot = CloudEngineWebSocketFactory(client,
                                        'ws://localhost:{0}'.format(extPort))
    listenWS(robot)

    reactor.addSystemEventTrigger('before', 'shutdown', client.terminate)
    reactor.run()
Exemple #13
0
def main(reactor, cred, masterIP, masterPort, masterPassword, infraPasswd,
         bridgeIF, internalIP, bridgeIP, envPort, rosproxyPort, rootfsDir,
         confDir, dataDir, pkgDir, ubuntuRel, rosRel, data):
    log.startLogging(sys.stdout)

    def _err(reason):
        print(reason)
        reactor.stop()

    factory = PBClientFactory()
    reactor.connectTCP(masterIP, masterPort, factory)

    client = ContainerClient(reactor, masterIP, masterPort, masterPassword,
                             infraPasswd, bridgeIF, internalIP, bridgeIP,
                             envPort, rosproxyPort, rootfsDir, confDir,
                             dataDir, pkgDir, ubuntuRel, rosRel, data)

    d = factory.login(cred, (client, data))
    d.addCallback(lambda ref: setattr(client, '_avatar', ref))
    d.addErrback(_err)

    reactor.addSystemEventTrigger('before', 'shutdown', client.terminate)
    reactor.run()