Exemplo n.º 1
0
def main(reactor, cred, masterIP, masterPort, commPort, uid):
    f = open('/opt/rce/data/env.log', 'w') # TODO: Hardcoded? 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(lambda ref: setattr(client, '_avatar', ref))
    d.addErrback(_err)

    reactor.run(installSignalHandlers=False)

    f.close()
Exemplo n.º 2
0
 def clientConnectionLost(self, connector, reason, reconnecting=1):
     zenlog.debug("Lost connection to %s:%s - %s", connector.host, connector.port, reason.getErrorMessage())
     self._perspective = None
     self._cancelConnectTimeout()
     PBClientFactory.clientConnectionLost(self, connector, reason, reconnecting=reconnecting)
     RCF = protocol.ReconnectingClientFactory
     RCF.clientConnectionLost(self, connector, reason)
Exemplo n.º 3
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
Exemplo n.º 4
0
 def clientConnectionLost(self, connector, reason):
     PBClientFactory.clientConnectionLost(self,
                                          connector,
                                          reason,
                                          reconnecting=True)
     RCF = protocol.ReconnectingClientFactory
     RCF.clientConnectionLost(self, connector, reason)
Exemplo n.º 5
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
Exemplo n.º 6
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()
Exemplo n.º 7
0
 def clientConnectionFailed(self, connector, reason):
     log.debug("clientConnectionFailed %s", reason)
     self._perspective = None
     self._cancelConnectTimeout()
     PBClientFactory.clientConnectionFailed(self, connector, reason)
     protocol.ReconnectingClientFactory.clientConnectionFailed(
         self, connector, reason)
Exemplo n.º 8
0
 def clientConnectionMade(self, broker):
     log.debug("clientConnectionMade")
     self.resetDelay()
     self._cancelConnectTimeout()
     PBClientFactory.clientConnectionMade(self, broker)
     if self._creds:
         self._startConnectTimeout("Login")
         self._login(self._creds)
Exemplo n.º 9
0
 def clientConnectionFailed(self, connector, reason):
     PBClientFactory.clientConnectionFailed(self, connector, reason)
     # Twisted-1.3 erroneously abandons the connection on non-UserErrors.
     # To avoid this bug, don't upcall, and implement the correct version
     # of the method here.
     if self.continueTrying:
         self.connector = connector
         self.retry()
Exemplo n.º 10
0
 def clientConnectionMade(self, broker):
     log.debug("clientConnectionMade")
     self.resetDelay()
     self._cancelConnectTimeout()
     PBClientFactory.clientConnectionMade(self, broker)
     if self._creds:
         self._startConnectTimeout("Login")
         self._login(self._creds)
Exemplo n.º 11
0
 def clientConnectionMade(self, broker):
     self.resetDelay()
     PBClientFactory.clientConnectionMade(self, broker)
     if self._doingLogin:
         self.doLogin(self._root)
     if self._doingGetPerspective:
         self.doGetPerspective(self._root)
     self.gotRootObject(self._root)
Exemplo n.º 12
0
 def clientConnectionFailed(self, connector, reason):
     PBClientFactory.clientConnectionFailed(self, connector, reason)
     # Twisted-1.3 erroneously abandons the connection on non-UserErrors.
     # To avoid this bug, don't upcall, and implement the correct version
     # of the method here.
     if self.continueTrying:
         self.connector = connector
         self.retry()
Exemplo n.º 13
0
 def clientConnectionMade(self, broker):
     self.resetDelay()
     PBClientFactory.clientConnectionMade(self, broker)
     if self._doingLogin:
         self.doLogin(self._root)
     if self._doingGetPerspective:
         self.doGetPerspective(self._root)
     self.gotRootObject(self._root)
Exemplo n.º 14
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
Exemplo n.º 15
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: ")
Exemplo n.º 16
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
Exemplo n.º 17
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()
Exemplo n.º 18
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()
Exemplo n.º 19
0
 def clientConnectionLost(self, connector, reason):
     ''' '''
     PBClientFactory.clientConnectionLost(self,
                                          connector,
                                          reason,
                                          reconnecting=True)
     protocol.ReconnectingClientFactory.clientConnectionLost(
         self,
         connector,
         reason,
     )
Exemplo n.º 20
0
 def clientConnectionMade(self, broker):
     zenlog.debug("Connected")
     self._cancelConnectTimeout()
     self.resetDelay()
     PBClientFactory.clientConnectionMade(self, broker)
     if self._doingLogin:
         self._startConnectTimeout("Login")
         self.doLogin(self._root)
     if self._doingGetPerspective:
         self.doGetPerspective(self._root)
     self.gotRootObject(self._root)
Exemplo n.º 21
0
 def clientConnectionFailed(self, connector, reason):
     zenlog.debug("Failed to create connection to %s:%s - %s", connector.host, connector.port, reason)
     self._perspective = None
     self._cancelConnectTimeout()
     PBClientFactory.clientConnectionFailed(self, connector, reason)
     # Twisted-1.3 erroneously abandons the connection on non-UserErrors.
     # To avoid this bug, don't upcall, and implement the correct version
     # of the method here.
     if self.continueTrying:
         self.connector = connector
         self.retry()
Exemplo n.º 22
0
 def clientConnectionLost(self, connector, reason, reconnecting=1):
     zenlog.debug("Lost connection to %s:%s - %s", connector.host,
                  connector.port, reason.getErrorMessage())
     self._perspective = None
     self._cancelConnectTimeout()
     PBClientFactory.clientConnectionLost(self,
                                          connector,
                                          reason,
                                          reconnecting=reconnecting)
     RCF = protocol.ReconnectingClientFactory
     RCF.clientConnectionLost(self, connector, reason)
Exemplo n.º 23
0
 def clientConnectionMade(self, broker):
     zenlog.debug("Connected")
     self._cancelConnectTimeout()
     self.resetDelay()
     PBClientFactory.clientConnectionMade(self, broker)
     if self._doingLogin:
         self._startConnectTimeout("Login")
         self.doLogin(self._root)
     if self._doingGetPerspective:
         self.doGetPerspective(self._root)
     self.gotRootObject(self._root)
Exemplo n.º 24
0
 def clientConnectionFailed(self, connector, reason):
     zenlog.debug("Failed to create connection to %s:%s - %s",
                  connector.host, connector.port, reason)
     self._perspective = None
     self._cancelConnectTimeout()
     PBClientFactory.clientConnectionFailed(self, connector, reason)
     # Twisted-1.3 erroneously abandons the connection on non-UserErrors.
     # To avoid this bug, don't upcall, and implement the correct version
     # of the method here.
     if self.continueTrying:
         self.connector = connector
         self.retry()
Exemplo n.º 25
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()
Exemplo n.º 26
0
class UbuntuOneClient(object):
    """Root object that provides access to all the remote objects."""

    def __init__(self):
        """Create a new instance."""
        self.status = None
        self.events = None
        self.sync_daemon = None
        self.file_system = None
        self.shares = None
        self.config = None
        self.folders = None
        self.public_files = None
        self.factory = None
        self.client = None

    @defer.inlineCallbacks
    def _request_remote_objects(self, root):
        """Request all the diff remote objects used for the communication."""
        status = yield root.callRemote('get_status')
        self.status = StatusClient(status)

        events = yield root.callRemote('get_events')
        self.events = EventsClient(events)

        sync_daemon = yield root.callRemote('get_sync_daemon')
        self.sync_daemon = SyncDaemonClient(sync_daemon)

        file_system = yield root.callRemote('get_file_system')
        self.file_system = FileSystemClient(file_system)

        shares = yield root.callRemote('get_shares')
        self.shares = SharesClient(shares)

        config = yield root.callRemote('get_config')
        self.config = ConfigClient(config)

        folders = yield root.callRemote('get_folders')
        self.folders = FoldersClient(folders)

        public_files = yield root.callRemote('get_public_files')
        self.public_files = PublicFilesClient(public_files)

        defer.returnValue(self)

    @defer.inlineCallbacks
    def connect(self):
        """Connect to the syncdaemon service."""
        # pylint: disable=W0702
        try:
            # connect to the remote objects
            self.factory = PBClientFactory()
            self.client = yield ipc_client_connect(self.factory)
            root = yield self.factory.getRootObject()
            yield self._request_remote_objects(root)
            yield self.register_to_signals()
            defer.returnValue(self)
        except Exception, e:
            raise SyncDaemonClientConnectionError(
                            'Could not connect to the syncdaemon ipc.', e)
Exemplo n.º 27
0
    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()
Exemplo n.º 28
0
 def __init__(self, connectTimeout=30, pingPerspective=True, pingInterval=30, pingtimeout=120):
     PBClientFactory.__init__(self)
     self._creds = None
     self._scheduledConnectTimeout = None
     self._connectTimeout = connectTimeout
     # should the perspective be pinged. Perspective must have a ping method. Deprecated => Always False.
     self._shouldPingPerspective = pingPerspective
     # how often to ping
     self._pingInterval = pingInterval
     # how long to wait for a ping before closing connection
     self._pingTimeoutTime = pingtimeout
     # ref to the scheduled ping timeout call
     self._pingTimeout = None
     # looping call doing the ping
     self._pingCheck = None
     self._perspective = None
Exemplo n.º 29
0
    def __init__(self):
        PBClientFactory.__init__(self)

        # Attribute defaults:
        self.uuid               = ""
	self.computeChunkSize	= 10
	self.computeInterval	= 1 # sec
	self.generator		= None  # functor
	self.outputBuffer	= []
	self.reportInterval	= 5 # sec
        self.taskQueue		= deque()
	self.scheduler		= None  # set in WorkerDaemon
	self.taskmaster         = None  # set in WorkerDaemon
        
        deferred    = self.getRootObject()
        deferred.addCallback(self.initProxy)
Exemplo n.º 30
0
    def __init__(self):
        PBClientFactory.__init__(self)

        # Attribute defaults:
        self.uuid = ""
        self.computeChunkSize = 10
        self.computeInterval = 1  # sec
        self.generator = None  # functor
        self.outputBuffer = []
        self.reportInterval = 5  # sec
        self.taskQueue = deque()
        self.scheduler = None  # set in WorkerDaemon
        self.taskmaster = None  # set in WorkerDaemon

        deferred = self.getRootObject()
        deferred.addCallback(self.initProxy)
Exemplo n.º 31
0
    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
Exemplo n.º 32
0
class ForwardOutput(Output):

    implements(IOutput)

    def configure(self, section):
        self.forwardserver = section.getString('forwarding address', None)
        self.forwardport = section.getInt('forwarding port', None)
        self.retryinterval = section.getInt('retry interval', 10)
        self.forwardedevents = getStat("terane.output.%s.forwardedevents" % self.name, 0)
        self.stalerefs = getStat("terane.output.%s.stalerefs" % self.name, 0)
        
    def startService(self):
        Output.startService(self)
        self._client = None
        self._listener = None
        self._remote = None
        self._backoff = None
        self._reconnect()

    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)
Exemplo n.º 33
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())
Exemplo n.º 34
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())
Exemplo n.º 35
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: ")
Exemplo n.º 36
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_port)
     root = yield self.factory.getRootObject()
     yield self._request_remote_objects(root)
     yield self.register_to_signals()
Exemplo n.º 37
0
def main(reactor, cred, masterIP, masterPort, internalIF, bridgeIF, envPort,
         rootfsDir, confDir, dataDir, srcDir, pkgDir, maxNr):
    log.startLogging(sys.stdout)
    
    def _err(reason):
        print(reason)
        reactor.stop()
    
    factory = PBClientFactory()
    reactor.connectTCP(masterIP, masterPort, factory)
    
    client = ContainerClient(reactor, masterIP, internalIF, bridgeIF, envPort,
                             rootfsDir, confDir, dataDir, srcDir, pkgDir)
    
    d = factory.login(cred, (client, maxNr))
    d.addCallback(lambda ref: setattr(client, '_avatar', ref))
    d.addErrback(_err)
    
    reactor.addSystemEventTrigger('before', 'shutdown', client.terminate)
    reactor.run()
Exemplo n.º 38
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)
Exemplo n.º 39
0
 def __init__(self,
              connectTimeout=30,
              pingPerspective=True,
              pingInterval=30,
              pingtimeout=120):
     PBClientFactory.__init__(self)
     self._creds = None
     self._scheduledConnectTimeout = None
     self._connectTimeout = connectTimeout
     # should the perspective be pinged. Perspective must have a ping method. Deprecated => Always False.
     self._shouldPingPerspective = pingPerspective
     # how often to ping
     self._pingInterval = pingInterval
     # how long to wait for a ping before closing connection
     self._pingTimeoutTime = pingtimeout
     # ref to the scheduled ping timeout call
     self._pingTimeout = None
     # looping call doing the ping
     self._pingCheck = None
     self._perspective = None
Exemplo n.º 40
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()
Exemplo n.º 41
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()
Exemplo n.º 42
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()
Exemplo n.º 43
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()
Exemplo n.º 44
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()
Exemplo n.º 45
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()
Exemplo n.º 46
0
 def connect(self):
     """Connect to the sso service."""
     ac = ActivationClient(get_activation_config())
     port = yield ac.get_active_port()
     # got the port, lets try and connect to it and get the diff
     # remote objects for the wrappers
     self.factory = PBClientFactory()
     # the reactor does have a connectTCP method
     # pylint: disable=E1101
     self.client = reactor.connectTCP(LOCALHOST, port, self.factory)
     # pylint: enable=E1101
     root = yield self.factory.getRootObject()
     client = yield self._request_remote_objects(root)
     defer.returnValue(client)
Exemplo n.º 47
0
 def connect(self):
     """Connect to the syncdaemon service."""
     # pylint: disable=W0702
     try:
         # connect to the remote objects
         self.factory = PBClientFactory()
         self.client = yield ipc_client_connect(self.factory)
         root = yield self.factory.getRootObject()
         yield self._request_remote_objects(root)
         yield self.register_to_signals()
         defer.returnValue(self)
     except Exception, e:
         raise SyncDaemonClientConnectionError(
                         'Could not connect to the syncdaemon ipc.', e)
Exemplo n.º 48
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)
Exemplo n.º 49
0
 def connect(self):
     """Connect to the syncdaemon service."""
     yield self.connection_lock.acquire()
     try:
         if self.client is None:
             # connect to the remote objects
             self.factory = PBClientFactory()
             self.client = yield ipc_client_connect(self.factory)
             root = yield self.factory.getRootObject()
             yield self._request_remote_objects(root)
             yield self.register_to_signals()
         defer.returnValue(self)
     except Exception as e:
         raise SyncDaemonClientConnectionError(
             'Could not connect to the syncdaemon ipc.', e)
     finally:
         self.connection_lock.release()
Exemplo n.º 50
0
class ForwardOutput(Output):

    implements(IOutput)

    def configure(self, section):
        self.forwardserver = section.getString('forwarding address', None)
        self.forwardport = section.getInt('forwarding port', None)
        self.retryinterval = section.getInt('retry interval', 10)
        self.forwardedevents = getStat(
            "terane.output.%s.forwardedevents" % self.name, 0)
        self.stalerefs = getStat("terane.output.%s.stalerefs" % self.name, 0)

    def startService(self):
        Output.startService(self)
        self._client = None
        self._listener = None
        self._remote = None
        self._backoff = None
        self._reconnect()

    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)
Exemplo n.º 51
0
class UbuntuSSOClient(object):
    """Root client that provides access to the sso API."""

    def __init__(self):
        self.sso_login = None
        self.cred_management = None
        self.factory = None
        self.client = None

    @defer.inlineCallbacks
    def _request_remote_objects(self, root):
        """Get the status remote object."""
        sso_login = yield root.callRemote('get_sso_login')
        logger.debug('SSOLogin is %s', sso_login)
        self.sso_login = SSOLoginClient(sso_login)
        cred_management = yield root.callRemote('get_cred_manager')
        self.cred_management = CredentialsManagementClient(cred_management)
        defer.returnValue(self)

    @defer.inlineCallbacks
    def connect(self):
        """Connect to the sso service."""
        ac = ActivationClient(get_activation_config())
        port = yield ac.get_active_port()
        # got the port, lets try and connect to it and get the diff
        # remote objects for the wrappers
        self.factory = PBClientFactory()
        # the reactor does have a connectTCP method
        # pylint: disable=E1101
        self.client = reactor.connectTCP(LOCALHOST, port, self.factory)
        # pylint: enable=E1101
        root = yield self.factory.getRootObject()
        client = yield self._request_remote_objects(root)
        defer.returnValue(client)

    def disconnect(self):
        """Disconnect from the process."""
        if self.client:
            self.client.disconnect()
Exemplo n.º 52
0
 def clientConnectionLost(self, connector, reason, reconnecting=1):
     PBClientFactory.clientConnectionLost(self, connector, reason,
                                          reconnecting=reconnecting)
     RCF = protocol.ReconnectingClientFactory
     RCF.clientConnectionLost(self, connector, reason)
Exemplo n.º 53
0
 def __init__(self):
     PBClientFactory.__init__(self)
     self._doingLogin = False
     self._doingGetPerspective = False
Exemplo n.º 54
0
 def buildProtocol(self, addr):
     return PBClientFactory.buildProtocol(self, addr)
Exemplo n.º 55
0
class BaseClient(object):
    """Client that will connect to the service listening on the description.

    Inherit from this class and define service_name, service_description and
    service_cmdline so they return the proper values.

    The service_cmdline must be redefined so it returns the command line to
    execute to run the service, if it's not running.

    If 'connect' is called, 'disconnect' should be called when done.

    """

    # a mapping of (client name, client class (an instance of RemoteClient))
    clients = {}
    service_name = None
    service_description = None
    service_cmdline = None

    def __init__(self):
        self.factory = None
        self.client = None
        for client in self.clients:
            setattr(self, client, None)

    @defer.inlineCallbacks
    def _request_remote_objects(self, root):
        """Request all the diff remote objects used for the communication."""
        logger.debug('Requesting remote objects (%r) for %s',
                     self.clients.keys(), self.__class__.__name__)
        for name, client_class in self.clients.items():
            remote = yield root.callRemote('get_%s' % name)
            setattr(self, name, client_class(self, remote))

    @defer.inlineCallbacks
    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()

    @defer.inlineCallbacks
    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()

    @defer.inlineCallbacks
    def register_to_signals(self):
        """Register all the clients to their signals."""
        for name in self.clients:
            client = getattr(self, name)
            yield client.register_to_signals()

    @defer.inlineCallbacks
    def unregister_to_signals(self):
        """Unregister from the all the client's signals."""
        for name in self.clients:
            client = getattr(self, name)
            yield client.unregister_to_signals()

    @defer.inlineCallbacks
    def disconnect(self):
        """Disconnect from the process."""
        yield self.unregister_to_signals()
        if self.client:
            self.client.disconnect()
Exemplo n.º 56
0
 def buildProtocol(self, addr):
     return PBClientFactory.buildProtocol(self, addr)
Exemplo n.º 57
0
 def clientConnectionMade(self, broker):
     self.resetDelay()
     PBClientFactory.clientConnectionMade(self, broker)
     self.doLogin(self._root, broker)
     self.gotRootObject(self._root)
Exemplo n.º 58
0
 def clientConnectionMade(self, broker):
     self.resetDelay()
     PBClientFactory.clientConnectionMade(self, broker)
     self.doLogin(self._root, broker)
     self.gotRootObject(self._root)
Exemplo n.º 59
0
 def __init__(self):
     PBClientFactory.__init__(self)
     self._doingLogin = False
     self._doingGetPerspective = False
Exemplo n.º 60
0
 def clientConnectionFailed(self, connector, reason):
     PBClientFactory.clientConnectionFailed(self, connector, reason)
     if self.continueTrying:
         self.connector = connector
         self.retry()