コード例 #1
0
    def test_dumber(self):
        """
        L{IReactorUNIX.connectUNIX} can be used to connect a client to a server
        started with L{IReactorUNIX.listenUNIX}.
        """
        filename = self.mktemp()
        serverFactory = MyServerFactory()
        serverConnMade = defer.Deferred()
        serverFactory.protocolConnectionMade = serverConnMade
        unixPort = reactor.listenUNIX(filename, serverFactory)
        self.addCleanup(unixPort.stopListening)
        clientFactory = MyClientFactory()
        clientConnMade = defer.Deferred()
        clientFactory.protocolConnectionMade = clientConnMade
        reactor.connectUNIX(filename, clientFactory)
        d = defer.gatherResults([serverConnMade, clientConnMade])

        def allConnected(args):
            serverProtocol, clientProtocol = args
            # Incidental assertion which may or may not be redundant with some
            # other test.  This probably deserves its own test method.
            self.assertEqual(clientFactory.peerAddresses,
                             [address.UNIXAddress(filename)])

            clientProtocol.transport.loseConnection()
            serverProtocol.transport.loseConnection()

        d.addCallback(allConnected)
        return d
コード例 #2
0
ファイル: server.py プロジェクト: udoprog/metap2p
 def listen(self, reactor):
   if self.simulate:
     reactor.connectUNIX(self.get_simsocket(self.uri), PeerFactory(peer), timeout = 2)
     self.debug("Listening at", self.get_simsocket(self.uri))
   else:
     reactor.listenTCP(self.port, ServerFactory(self, self.serversession), interface = self.host)
     self.debug("Listening at", self.uri)
コード例 #3
0
ファイル: test_unix.py プロジェクト: fxia22/ASM_xf
 def testDumber(self):
     filename = tempfile.mktemp()
     l = reactor.listenUNIX(filename, Factory())
     reactor.connectUNIX(filename, TestClientFactory())
     for i in xrange(100):
         reactor.iterate()
     l.stopListening()
コード例 #4
0
ファイル: cmelissi.py プロジェクト: akatsoulas/client
def main():
    parser = OptionParser()
    parser.add_option(
        "--socket",
        help="UNIX socket where melissi client listens",
        default=os.path.expanduser("~/.config/melisi/melisi.sock"),
    )
    (options, args) = parser.parse_args()

    commands = {
        "auth": auth,
        "disconnect": disconnect,
        "connect": connect,
        "register": register,
        "checkbusy": checkbusy,
        "sethost": sethost,
        "deleteuser": deleteuser,
        "addshare": addshare,
        "removeshare": removeshare,
    }

    if len(args) < 1:
        usage(commands)
        sys.exit(0)

    try:
        commands[args[0]](args[1:])
    except KeyError:
        usage(commands)
        sys.exit(1)

    melisi_commander = MelisiCommander(command_list)
    reactor.connectUNIX(options.socket, melisi_commander)
    reactor.callLater(2, _timeout)
    reactor.run()
コード例 #5
0
ファイル: test_unix.py プロジェクト: marcelpetersen/localnews
    def test_dumber(self):
        """
        L{IReactorUNIX.connectUNIX} can be used to connect a client to a server
        started with L{IReactorUNIX.listenUNIX}.
        """
        filename = self.mktemp()
        serverFactory = MyServerFactory()
        serverConnMade = defer.Deferred()
        serverFactory.protocolConnectionMade = serverConnMade
        unixPort = reactor.listenUNIX(filename, serverFactory)
        self.addCleanup(unixPort.stopListening)
        clientFactory = MyClientFactory()
        clientConnMade = defer.Deferred()
        clientFactory.protocolConnectionMade = clientConnMade
        reactor.connectUNIX(filename, clientFactory)
        d = defer.gatherResults([serverConnMade, clientConnMade])
        def allConnected(args):
            serverProtocol, clientProtocol = args
            # Incidental assertion which may or may not be redundant with some
            # other test.  This probably deserves its own test method.
            self.assertEqual(clientFactory.peerAddresses,
                             [address.UNIXAddress(filename)])

            clientProtocol.transport.loseConnection()
            serverProtocol.transport.loseConnection()
        d.addCallback(allConnected)
        return d
コード例 #6
0
 def startFactory(self):
     """Tell the other end that we are done starting up.
     """
     # Import reactor here to avoid installing default at startup
     from twisted.internet import reactor
     reactor.connectUNIX('zomne_startup_complete.socket',
                         NotificationFactory())
コード例 #7
0
ファイル: pbclient.py プロジェクト: HapPiNeHsSs/hideout
 def connectUNIX(self, sock_path):
     if not self.factory:
         self.factory = pb.PBClientFactory()
         self.factory.clientConnectionFailed = self._onConnectionFailed
         self.factory.clientConnectionLost = self._onConnectionLost
     reactor.connectUNIX(sock_path)
     self.factory.getRootObject().addCallbacks(self.connected, self.onError)
コード例 #8
0
 def __init__(self):
     initMsg = {"id": "client connected"}
     self.msgFactory = CbClientFactory(self.processMsg, initMsg)
     reactor.connectUNIX("tmpSoc", self.msgFactory, timeout=1)
     reactor.callLater(3, self.process)
     print ModuleName, "starting reactor"
     reactor.run()
コード例 #9
0
ファイル: client.py プロジェクト: tobixx/txmsgpackrpc
    def connect_UNIX(address,
                     connectTimeout=None,
                     waitTimeout=None,
                     maxRetries=5):
        """
        Connect RPC server via UNIX socket. Returns C{t.i.d.Deferred} that will
        callback with C{handler.SimpleConnectionHandler} object or errback with
        C{ConnectionError} if all connection attempts will fail.

        @param address: path to a unix socket on the filesystem.
        @type address: C{int}
        @param connectTimeout: number of seconds to wait before assuming
            the connection has failed.
        @type connectTimeout: C{int}
        @param waitTimeout: number of seconds the protocol waits for activity
            on a connection before reconnecting it.
        @type waitTimeout: C{int}
        @param maxRetries: maximum number of consecutive unsuccessful connection
            attempts, after which no further connection attempts will be made. If
            this is not explicitly set, no maximum is applied. Default is 5.
        @type maxRetries: C{int}
        @return Deferred that callbacks with C{handler.SimpleConnectionHandler}
            object or errbacks with C{ConnectionError}.
        @rtype C{t.i.d.Deferred}
        """
        factory = MsgpackClientFactory(connectTimeout=connectTimeout,
                                       waitTimeout=waitTimeout)
        factory.maxRetries = maxRetries

        reactor.connectUNIX(address, factory, timeout=connectTimeout)

        d = factory.handler.waitForConnection()
        d.addCallback(lambda conn: factory.handler)

        return d
コード例 #10
0
    def __init__(self, argv):
        logging.basicConfig(filename=CB_LOGFILE,
                            level=CB_LOGGING_LEVEL,
                            format='%(asctime)s %(message)s')
        self.appClass = "none"  # Should be overwritten by app
        self.cbFactory = {}
        self.adtInstances = []
        self.doStop = False
        self.friendlyLookup = {}
        self.configured = False
        self.status = "ok"
        self.bridge_id = "unconfigured"

        if len(argv) < 3:
            logging.error("%s cbApp improper number of arguments", ModuleName)
            exit(1)
        managerSocket = argv[1]
        self.id = argv[2]
        logging.info("%s Hello from %s", ModuleName, self.id)
        procname.setprocname(self.id)

        initMsg = {"id": self.id, "type": "app", "status": "req-config"}
        self.managerFactory = CbClientFactory(self.processManager, initMsg)
        reactor.connectUNIX(managerSocket, self.managerFactory, timeout=2)

        reactor.callLater(TIME_TO_MONITOR_STATUS, self.sendStatus)
        reactor.run()
コード例 #11
0
ファイル: pbclient.py プロジェクト: HapPiNeHsSs/hideout
 def connectUNIX(self, sock_path):
     if not self.factory:
         self.factory = pb.PBClientFactory()
         self.factory.clientConnectionFailed = self._onConnectionFailed
         self.factory.clientConnectionLost = self._onConnectionLost
     reactor.connectUNIX(sock_path)
     self.factory.getRootObject().addCallbacks(self.connected, self.onError)
コード例 #12
0
 def cbConfigure(self, config):
     """Config is based on what apps are available."""
     #logging.debug("%s %s Configuration: %s ", ModuleName, self.id, config)
     self.name = config["name"]
     self.friendly_name = config["friendly_name"]
     self.device = config["btAdpt"]
     self.addr = config["btAddr"]
     self.sim = int(config["sim"])
     for app in config["apps"]:
         iName = app["id"]
         if iName not in self.appInstances:
             # configureig may be called again with updated config
             name = app["name"]
             adtSoc = app["adtSoc"]
             self.appInstances.append(iName)
             self.cbFactory[iName] = CbServerFactory(self.onAppMessage)
             reactor.listenUNIX(adtSoc, self.cbFactory[iName])
     if "zwave_socket" in config:
         initMsg = {"id": self.id, "request": "init"}
         self.zwaveFactory = CbClientFactory(self.onZwaveMessage, initMsg)
         reactor.connectUNIX(config["zwave_socket"],
                             self.zwaveFactory,
                             timeout=30)
     self.onConfigureMessage(config)
     self.configured = True
コード例 #13
0
ファイル: zomnesrv.py プロジェクト: jonathanj/nevow
    def startFactory(self):
        """Tell the other end that we are done starting up.
        """
        # Import reactor here to avoid installing default at startup
        from twisted.internet import reactor

        reactor.connectUNIX("zomne_startup_complete.socket", NotificationFactory())
コード例 #14
0
    def render(self, request):
        """Render this request, from my server.

        This will always be asynchronous, and therefore return NOT_DONE_YET.
        It spins off a request to the pb client, and either adds it to the list
        of pending issues or requests it immediately, depending on if the
        client is already connected.
        """
        if not self.publisher:
            self.pending.append(request)
            if not self.waiting:
                self.waiting = 1
                bf = pb.PBClientFactory()
                timeout = 10
                if self.host == "unix":
                    reactor.connectUNIX(self.port, bf, timeout)
                else:
                    reactor.connectTCP(self.host, self.port, bf, timeout)
                d = bf.getRootObject()
                d.addCallbacks(self.connected, self.notConnected)

        else:
            i = Issue(request)
            self.publisher.callRemote('request', request).addCallbacks(i.finished, i.failed)
        return server.NOT_DONE_YET
コード例 #15
0
ファイル: unix.py プロジェクト: AnthonyNystrom/YoGoMee
def connect(host, port, options, verifyHostKey, userAuthObject):
    if options['nocache']: 
        return defer.fail(ConchError('not using connection caching'))
    d = defer.Deferred()
    filename = os.path.expanduser("~/.conch-%s-%s-%i" % (userAuthObject.user, host, port))
    factory = SSHUnixClientFactory(d, options, userAuthObject)
    reactor.connectUNIX(filename, factory, timeout=2, checkPID=1)
    return d
コード例 #16
0
ファイル: clientconnection.py プロジェクト: kvj/mp-twisted
def do_connect(listener, reconnect = False):
    if not hasattr(socket, 'AF_UNIX') or common.config.getboolean('Client', 'force_tcp'):
        logging.info('Open tcp port')
        reactor.connectTCP('localhost', common.config.getint('Server', 'port'), ConnectionFactory(listener, reconnect))
    else:
        logging.info('Open file socket')
        reactor.connectUNIX(common.config.get('Server', 'file'), ConnectionFactory(listener, reconnect))
    logging.info("Client started")
コード例 #17
0
ファイル: test_protocol.py プロジェクト: jordane/nagcat
 def setUp(self):
     sock = self.mktemp()
     serverfactory = DummyCacheServer()
     self.server = reactor.listenUNIX(sock, serverfactory)
     deferred = defer.Deferred()
     self.client = protocol.RRDCacheClient(deferred, True)
     reactor.connectUNIX(sock, self.client)
     return deferred
コード例 #18
0
ファイル: mpv.py プロジェクト: niol/deejayd
 def __try_connect(self):
     if not self.factory.conn:
         if self.__connect_tries < 5:
             reactor.connectUNIX(self.socket_path(), self.factory)
             reactor.callLater(1, self.__try_connect)
         else:
             log.err('ctrl:mpv: Could not connect to player process, '
                     'giving up.')
コード例 #19
0
ファイル: test_unix.py プロジェクト: fxia22/ASM_xf
 def testMode(self):
     filename = tempfile.mktemp()
     l = reactor.listenUNIX(filename, Factory(), mode = 0600)
     self.assertEquals(stat.S_IMODE(os.stat(filename)[0]), 0600)
     reactor.connectUNIX(filename, TestClientFactory())
     for i in xrange(100):
         reactor.iterate()
     l.stopListening()
コード例 #20
0
 def run(module, *m_args, **p_kwargs):
     sock_name = sock(module, next(sock_counter))
     process(python_m(module, sock_name, *m_args), **p_kwargs)
     yield sleep(2)
     conn = pb.PBClientFactory()
     reactor.connectUNIX(sock_name, conn)
     obj = yield conn.getRootObject()
     remotes.append(obj)
     defer.returnValue(obj)
コード例 #21
0
 def test_connect_with_max_retries(self):
     """
     If L{MethodCallClientFactory.maxRetries} is set, then the factory
     will give up trying to connect after that amout of times.
     """
     self.port.stopListening()
     self.client.maxRetries = 0
     reactor.connectUNIX(self.socket, self.client)
     yield self.assertFailure(self.client.getRemoteObject(), ConnectError)
コード例 #22
0
ファイル: unix.py プロジェクト: hitzjd/Balance-Simulate
def connect(host, port, options, verifyHostKey, userAuthObject):
    if options['nocache']:
        return defer.fail(ConchError('not using connection caching'))
    d = defer.Deferred()
    filename = os.path.expanduser("~/.conch-%s-%s-%i" %
                                  (userAuthObject.user, host, port))
    factory = SSHUnixClientFactory(d, options, userAuthObject)
    reactor.connectUNIX(filename, factory, timeout=2, checkPID=1)
    return d
コード例 #23
0
ファイル: nodes.py プロジェクト: ProgramLeague/Castle-Online
 def connect(self):
     if self._node["type"] == "tcp":
         reactor.connectTCP(self._node["host"], self._node["port"], self)
     elif self._node["type"] == "unix":
         reactor.connectUNIX(self._node["addr"], self)
     else:
         log.err("Unknown connect type")
         
     self.getRootObject().addCallback(self._proxy.insert, self._node["name"])
コード例 #24
0
ファイル: txtarantool.py プロジェクト: zlobspb/txtarantool
def makeUnixConnection(path, poolsize, reconnect, isLazy):
    factory = TarantoolFactory(poolsize, isLazy, UnixConnectionHandler)
    factory.continueTrying = reconnect
    for x in xrange(poolsize):
        reactor.connectUNIX(path, factory)

    if isLazy:
        return factory.handler
    else:
        return factory.deferred
コード例 #25
0
ファイル: badgerproxyctl.py プロジェクト: isotoma/badgerproxy
def _run(config, args):
    factory = pb.PBClientFactory()
    reactor.connectUNIX(config.socket, factory)
    try:
        perspective = yield factory.login(UsernamePassword("guest", "guest"))
        yield perspective.callRemote('add_dns', args[0], args[1], int(args[2]))
        print "Record added"
    except Exception as e:
        print "Error: ", str(e)

    reactor.stop()
コード例 #26
0
 def testStoppingServer(self):
     factory = protocol.ServerFactory()
     factory.protocol = wire.Echo
     t = internet.UNIXServer('echo.skt', factory)
     t.startService()
     t.stopService()
     self.failIf(t.running)
     factory = protocol.ClientFactory()
     d = defer.Deferred()
     factory.clientConnectionFailed = lambda *args: d.callback(None)
     reactor.connectUNIX('echo.skt', factory)
     return d
コード例 #27
0
 def testStoppingServer(self):
     factory = protocol.ServerFactory()
     factory.protocol = wire.Echo
     t = internet.UNIXServer("echo.skt", factory)
     t.startService()
     t.stopService()
     self.assertFalse(t.running)
     factory = protocol.ClientFactory()
     d = defer.Deferred()
     factory.clientConnectionFailed = lambda *args: d.callback(None)
     reactor.connectUNIX("echo.skt", factory)
     return d
コード例 #28
0
ファイル: txdocker.py プロジェクト: hydface2/mcloud
    def attach(self, container_id, ticket_id, skip_terminal=False):

        d = defer.Deferred()
        protocol = Attach(d, container_id)

        def stdin_on_input(channel, data):
            protocol.stdin_on_input(data)

        def stdout_write(data):
            self.task_stdout(ticket_id, data)

        def log_write(data):
            self.task_log(ticket_id, b64decode(data))

        try:
            if skip_terminal:
                protocol.stdout_write = log_write
            else:
                protocol.stdout_write = stdout_write

                self.eb.on('task.stdin.%s' % int(ticket_id), stdin_on_input)

            f = AttachFactory(protocol)

            proto, url = self.url.split('://')
            url = url.strip('/')

            print 'url::::::::::::::::'
            print url
            if ':' in url:
                host, port = url.split(':')
            else:
                host = url
                port = 2376 if proto == 'https' else 2375

            if proto == 'https':
                from mcloud.ssl import CtxFactory
                pkey = load_privatekey(FILETYPE_PEM, self.key)
                cert = load_certificate(FILETYPE_PEM, self.crt)
                reactor.connectSSL(host, int(port), f, CtxFactory(pkey, cert))
            else:
                if proto == 'unix':
                    reactor.connectUNIX(host, f)
                else:
                    reactor.connectTCP(host, port, f)

            yield d

        finally:
            if not skip_terminal:
                self.eb.cancel('task.stdin.%s' % int(ticket_id),
                               stdin_on_input)
コード例 #29
0
ファイル: txdocker.py プロジェクト: hydface2/mcloud
    def attach(self, container_id, ticket_id, skip_terminal=False):

        d = defer.Deferred()
        protocol = Attach(d, container_id)

        def stdin_on_input(channel, data):
            protocol.stdin_on_input(data)

        def stdout_write(data):
            self.task_stdout(ticket_id, data)

        def log_write(data):
            self.task_log(ticket_id, b64decode(data))

        try:
            if skip_terminal:
                protocol.stdout_write = log_write
            else:
                protocol.stdout_write = stdout_write

                self.eb.on('task.stdin.%s' % int(ticket_id), stdin_on_input)

            f = AttachFactory(protocol)

            proto, url = self.url.split('://')
            url = url.strip('/')

            print 'url::::::::::::::::'
            print url
            if ':' in url:
                host, port = url.split(':')
            else:
                host = url
                port = 2376 if proto == 'https' else 2375

            if proto == 'https':
                from mcloud.ssl import CtxFactory
                pkey = load_privatekey(FILETYPE_PEM, self.key)
                cert = load_certificate(FILETYPE_PEM, self.crt)
                reactor.connectSSL(host, int(port), f, CtxFactory(pkey, cert))
            else:
                if proto == 'unix':
                    reactor.connectUNIX(host, f)
                else:
                    reactor.connectTCP(host, port, f)


            yield d

        finally:
            if not skip_terminal:
                self.eb.cancel('task.stdin.%s' % int(ticket_id), stdin_on_input)
コード例 #30
0
ファイル: pb4client.py プロジェクト: BillAndersan/twisted
def getSomeObjectAt(host, port, timeout=None, objname="root"):
    from twisted.internet import defer
    from twisted.spread.pb import Broker, BrokerClientFactory
    d = defer.Deferred()
    b = Broker(1)
    bf = BrokerClientFactory(b)
    my_ObjectRetrieval(b, d, objname)
    if host == "unix":
        # every time you use this, God kills a kitten
        reactor.connectUNIX(port, bf, timeout)
    else:
        reactor.connectTCP(host, port, bf, timeout)
    return d
コード例 #31
0
ファイル: pb4client.py プロジェクト: pabitra10/company-crawl
def getSomeObjectAt(host, port, timeout=None, objname="root"):
    from twisted.internet import defer
    from twisted.spread.pb import Broker, BrokerClientFactory
    d = defer.Deferred()
    b = Broker(1)
    bf = BrokerClientFactory(b)
    my_ObjectRetrieval(b, d, objname)
    if host == "unix":
        # every time you use this, God kills a kitten
        reactor.connectUNIX(port, bf, timeout)
    else:
        reactor.connectTCP(host, port, bf, timeout)
    return d
コード例 #32
0
def sendlines(socket, lines=''):
    """
    Connect to a specified `socket` and send the given `lines`.
    
    Assumes the socket exists.
    """
    try:
        factory = EditorClientFactory(lines)
        reactor.connectUNIX(socket, factory)
        reactor.run()
    except: 
        return False
    else:
        return True
コード例 #33
0
ファイル: mpd_new.py プロジェクト: bverdu/onDemand
def get_Mpd(addr='127.0.0.1', port=6600, cover_dir='/var/lib/mpd/'):
    f = Mpd_factory(cover_dir=cover_dir)
    if addr.startswith('/') or addr.startswith('~'):
        reactor.connectUNIX(addr, f)  # @UndefinedVariable
#         from twisted.internet.endpoints import UNIXClientEndpoint
#         edp = UNIXClientEndpoint(reactor, addr)
#         edp.connect(f)
    else:
        reactor.connectTCP(addr, port, f)  # @UndefinedVariable
#         from twisted.internet.endpoints import TCP4ClientEndpoint
#         edp = TCP4ClientEndpoint(reactor, addr, port)
#         edp.connect(f)

    return None, f
コード例 #34
0
def sendlines(socket, lines=''):
    """
    Connect to a specified `socket` and send the given `lines`.
    
    Assumes the socket exists.
    """
    try:
        factory = EditorClientFactory(lines)
        reactor.connectUNIX(socket, factory)
        reactor.run()
    except:
        return False
    else:
        return True
コード例 #35
0
 def testStoppingServer(self):
     if not interfaces.IReactorUNIX(reactor, None):
         raise unittest.SkipTest, "This reactor does not support UNIX domain sockets"
     factory = protocol.ServerFactory()
     factory.protocol = wire.Echo
     t = internet.UNIXServer('echo.skt', factory)
     t.startService()
     t.stopService()
     self.failIf(t.running)
     factory = protocol.ClientFactory()
     d = defer.Deferred()
     factory.clientConnectionFailed = lambda *args: d.callback(None)
     reactor.connectUNIX('echo.skt', factory)
     return d
コード例 #36
0
ファイル: test_application.py プロジェクト: Berimor66/mythbox
 def testStoppingServer(self):
     if not interfaces.IReactorUNIX(reactor, None):
         raise unittest.SkipTest, "This reactor does not support UNIX domain sockets"
     factory = protocol.ServerFactory()
     factory.protocol = wire.Echo
     t = internet.UNIXServer('echo.skt', factory)
     t.startService()
     t.stopService()
     self.failIf(t.running)
     factory = protocol.ClientFactory()
     d = defer.Deferred()
     factory.clientConnectionFailed = lambda *args: d.callback(None)
     reactor.connectUNIX('echo.skt', factory)
     return d
コード例 #37
0
ファイル: twist.py プロジェクト: jordane/nagcat
    def open(self, address, pidfile=None):
        """Open connection to rrdcached

        @param address: path to rrdcached's UNIX socket
        @type address: str
        @param pidfile: optionally check rrdcached's pid file
        @type pidfile: str
        """

        deferred = defer.Deferred()
        self._client = protocol.RRDCacheClient(deferred)
        reactor.connectUNIX(address, self._client, checkPID=pidfile)
        self.update = self._update_cache
        return deferred
コード例 #38
0
 def testStoppingServer(self):
     if not interfaces.IReactorUNIX(reactor, None):
         raise unittest.SkipTest, "This reactor does not support UNIX domain sockets"
     factory = protocol.ServerFactory()
     factory.protocol = wire.Echo
     t = internet.UNIXServer('echo.skt', factory)
     t.startService()
     t.stopService()
     self.failIf(t.running)
     factory = protocol.ClientFactory()
     l = []
     factory.clientConnectionFailed = lambda *args: l.append(None)
     reactor.connectUNIX('echo.skt', factory)
     util.spinWhile(lambda: not l)
     self.assertEqual(l, [None])
コード例 #39
0
 def testStoppingServer(self):
     if not interfaces.IReactorUNIX(reactor, None):
         raise unittest.SkipTest, "This reactor does not support UNIX domain sockets"
     factory = protocol.ServerFactory()
     factory.protocol = wire.Echo
     t = internet.UNIXServer("echo.skt", factory)
     t.startService()
     t.stopService()
     self.failIf(t.running)
     factory = protocol.ClientFactory()
     l = []
     factory.clientConnectionFailed = lambda *args: l.append(None)
     reactor.connectUNIX("echo.skt", factory)
     util.spinWhile(lambda: not l)
     self.assertEqual(l, [None])
コード例 #40
0
def remote_module(mname, *m_args, **p_kwargs):
    """Run a PB-using module in a separate process and give back its root object.

    param mname: module name
    param *m_args: CLI args, will be added after `python -m mname`
    param *p_kwargs: will be passed to the process executor
    """
    sock_name = sock(mname, next(_sock_counter))
    process(python_m(mname, sock_name, *m_args), **p_kwargs)
    yield sleep(2)  # wait for it to bind
    conn = pb.PBClientFactory()
    from twisted.internet import reactor
    reactor.connectUNIX(sock_name, conn)
    obj = yield conn.getRootObject()
    defer.returnValue(obj)
コード例 #41
0
ファイル: _base.py プロジェクト: rubo77/synapse
    def setUp(self):
        self.hs = yield setup_test_homeserver(
            "blue",
            http_client=None,
            federation_client=Mock(),
            ratelimiter=NonCallableMock(spec_set=[
                "send_message",
            ]),
        )
        self.hs.get_ratelimiter().send_message.return_value = (True, 0)

        self.master_store = self.hs.get_datastore()
        self.slaved_store = self.STORE_TYPE(self.hs.get_db_conn(), self.hs)
        self.event_id = 0

        server_factory = ReplicationStreamProtocolFactory(self.hs)
        # XXX: mktemp is unsafe and should never be used. but we're just a test.
        path = tempfile.mktemp(prefix="base_slaved_store_test_case_socket")
        listener = reactor.listenUNIX(path, server_factory)
        self.addCleanup(listener.stopListening)
        self.streamer = server_factory.streamer

        self.replication_handler = ReplicationClientHandler(self.slaved_store)
        client_factory = ReplicationClientFactory(
            self.hs, "client_name", self.replication_handler
        )
        client_connector = reactor.connectUNIX(path, client_factory)
        self.addCleanup(client_factory.stopTrying)
        self.addCleanup(client_connector.disconnect)
コード例 #42
0
    def setUp(self):
        self.hs = yield setup_test_homeserver(
            "blue",
            http_client=None,
            federation_client=Mock(),
            ratelimiter=NonCallableMock(spec_set=[
                "send_message",
            ]),
        )
        self.hs.get_ratelimiter().send_message.return_value = (True, 0)

        self.master_store = self.hs.get_datastore()
        self.slaved_store = self.STORE_TYPE(self.hs.get_db_conn(), self.hs)
        self.event_id = 0

        server_factory = ReplicationStreamProtocolFactory(self.hs)
        # XXX: mktemp is unsafe and should never be used. but we're just a test.
        path = tempfile.mktemp(prefix="base_slaved_store_test_case_socket")
        listener = reactor.listenUNIX(path, server_factory)
        self.addCleanup(listener.stopListening)
        self.streamer = server_factory.streamer

        self.replication_handler = TestReplicationClientHandler(self.slaved_store)
        client_factory = ReplicationClientFactory(
            self.hs, "client_name", self.replication_handler
        )
        client_connector = reactor.connectUNIX(path, client_factory)
        self.addCleanup(client_factory.stopTrying)
        self.addCleanup(client_connector.disconnect)
コード例 #43
0
def loopbackUNIX(server, client, noisy=True):
    """Run session between server and client protocol instances over UNIX socket."""
    path = tempfile.mktemp()
    from twisted.internet import reactor
    f = policies.WrappingFactory(protocol.Factory())
    serverWrapper = _FireOnClose(f, server)
    f.noisy = noisy
    f.buildProtocol = lambda addr: serverWrapper
    serverPort = reactor.listenUNIX(path, f)
    clientF = LoopbackClientFactory(client)
    clientF.noisy = noisy
    reactor.connectUNIX(path, clientF)
    d = clientF.deferred
    d.addCallback(lambda x: serverWrapper.deferred)
    d.addCallback(lambda x: serverPort.stopListening())
    return d
コード例 #44
0
ファイル: broker.py プロジェクト: f3at/feat
 def _connect_as_slave(self):
     cb = defer.Deferred()
     self.factory = SlaveFactory(self, cb)
     self.connector = reactor.connectUNIX( #@UndefinedVariable
         self.socket_path, self.factory, timeout=1)
     cb.addBoth(defer.bridge_param, self._set_idle, True)
     return cb
コード例 #45
0
ファイル: loopback.py プロジェクト: JohnDoes95/project_parser
def loopbackUNIX(server, client, noisy=True):
    """Run session between server and client protocol instances over UNIX socket."""
    path = tempfile.mktemp()
    from twisted.internet import reactor
    f = policies.WrappingFactory(protocol.Factory())
    serverWrapper = _FireOnClose(f, server)
    f.noisy = noisy
    f.buildProtocol = lambda addr: serverWrapper
    serverPort = reactor.listenUNIX(path, f)
    clientF = LoopbackClientFactory(client)
    clientF.noisy = noisy
    reactor.connectUNIX(path, clientF)
    d = clientF.deferred
    d.addCallback(lambda x: serverWrapper.deferred)
    d.addCallback(lambda x: serverPort.stopListening())
    return d
コード例 #46
0
def get_Mpd(addr='127.0.0.1', port=6600, cover_dir='/var/lib/mpd/'):
    f = Mpd_factory(cover_dir=cover_dir)
    if addr.startswith('/') or addr.startswith('~'):
        reactor.connectUNIX(addr, f)  # @UndefinedVariable
#         from twisted.internet.endpoints import UNIXClientEndpoint
#         edp = UNIXClientEndpoint(reactor, addr)
#         edp.connect(f)
    else:
        reactor.connectTCP(addr, port, f)  # @UndefinedVariable


#         from twisted.internet.endpoints import TCP4ClientEndpoint
#         edp = TCP4ClientEndpoint(reactor, addr, port)
#         edp.connect(f)

    return None, f
コード例 #47
0
ファイル: zwavectrl_a.py プロジェクト: ContinuumBridge/bridge
    def __init__(self, argv):
        procname.setprocname('cbzwavectrl')
        self.status = "ok"
        self.state = "stopped"
        self.include = False
        self.exclude = False
        self.getting = False
        self.resetBoard = False
        self.getStrs = []
        self.cbFactory = {}
        self.adaptors = []
        self.found = []
        self.listen = []
        self.postToUrls = []
        if len(argv) < 3:
            print("error, Improper number of arguments")
            exit(1)
        managerSocket = argv[1]
        self.id = argv[2]
        self.fromTime = str(int(time.time()) - 1)

        # Connection to manager
        initMsg = {"id": self.id, "type": "zwave", "status": "req-config"}
        self.managerFactory = CbClientFactory(self.onManagerMessage, initMsg)
        self.managerConnect = reactor.connectUNIX(managerSocket,
                                                  self.managerFactory,
                                                  timeout=10)
        reactor.run()
コード例 #48
0
ファイル: 35416__base.py プロジェクト: ldesiqueira/synapse-1
    def setUp(self):
        self.hs = yield setup_test_homeserver(
            "blue",
            http_client=None,
            replication_layer=Mock(),
            ratelimiter=NonCallableMock(spec_set=[
                "send_message",
            ]),
        )
        self.hs.get_ratelimiter().send_message.return_value = (True, 0)

        self.master_store = self.hs.get_datastore()
        self.slaved_store = self.STORE_TYPE(self.hs.get_db_conn(), self.hs)
        self.event_id = 0

        server_factory = ReplicationStreamProtocolFactory(self.hs)
        listener = reactor.listenUNIX("\0xxx", server_factory)
        self.addCleanup(listener.stopListening)
        self.streamer = server_factory.streamer

        self.replication_handler = ReplicationClientHandler(self.slaved_store)
        client_factory = ReplicationClientFactory(
            self.hs, "client_name", self.replication_handler
        )
        client_connector = reactor.connectUNIX("\0xxx", client_factory)
        self.addCleanup(client_factory.stopTrying)
        self.addCleanup(client_connector.disconnect)
コード例 #49
0
ファイル: twbackend.py プロジェクト: sssst315/beah
def start_backend(backend, host=None, port=None,
        adaptor=ControllerAdaptor_Backend_JSON,
        byef=None):
    conf = config.get_conf('beah-backend')
    host = host or conf.get('DEFAULT', 'INTERFACE')
    port = port or conf.get('DEFAULT', 'PORT')
    if os.name == 'posix':
        socket = conf.get('DEFAULT', 'SOCKET')
        # 0. check SOCKET_OPT (socket given on command line)
        if parse_bool(conf.get('DEFAULT', 'SOCKET_OPT')) and socket != '':
            port = ''
        # 1. check INTERFACE - if not empty nor localhost: must use TCP
        if not localhost_(host):
            socket = ''
        # 2. check PORT_OPT (port given on command line)
        if parse_bool(conf.get('DEFAULT', 'PORT_OPT')) and port != '':
            socket = ''
    else:
        socket = ''
    backend_factory = BackendFactory(backend, adaptor, byef)
    if socket != '':
        return reactor.connectUNIX(socket, backend_factory)
    elif port and host:
        return reactor.connectTCP(host, int(port), backend_factory)
    elif port:
        if not parse_bool(conf.get('DEFAULT', 'IPV6_DISABLED')):
            return connect_loopback(int(port),
                                    backend_factory)
        else:
            return connect_loopback(int(port),
                                    backend_factory,
                                    ipv6_disabled=True)
    else:
        raise EnvironmentError('Either socket or port must be configured.')
コード例 #50
0
 def testMode(self):
     filename = self.mktemp()
     f = Factory(self, filename)
     l = reactor.listenUNIX(filename, f, mode = 0600)
     self.assertEquals(stat.S_IMODE(os.stat(filename)[0]), 0600)
     tcf = TestClientFactory(self, filename)
     c = reactor.connectUNIX(filename, tcf)
     self._addPorts(l, c.transport)
コード例 #51
0
def loopbackUNIX(server, client, noisy=True):
    """Run session between server and client protocol instances over UNIX socket."""
    path = tempfile.mktemp()
    from twisted.internet import reactor
    f = protocol.Factory()
    f.noisy = noisy
    f.buildProtocol = lambda addr, p=server: p
    serverPort = reactor.listenUNIX(path, f)
    reactor.iterate()
    clientF = LoopbackClientFactory(client)
    clientF.noisy = noisy
    reactor.connectUNIX(path, clientF)

    spinUntil(lambda :clientF.disconnected)        # A
    spinWhile(lambda :server.transport.connected)  # B
    serverPort.stopListening()
    spinWhile(lambda :serverPort.connected)        # C
コード例 #52
0
ファイル: loopback.py プロジェクト: UstadMobile/eXePUB
def loopbackUNIX(server, client, noisy=True):
    """Run session between server and client protocol instances over UNIX socket."""
    path = tempfile.mktemp()
    from twisted.internet import reactor
    f = protocol.Factory()
    f.noisy = noisy
    f.buildProtocol = lambda addr, p=server: p
    serverPort = reactor.listenUNIX(path, f)
    reactor.iterate()
    clientF = LoopbackClientFactory(client)
    clientF.noisy = noisy
    reactor.connectUNIX(path, clientF)

    spinUntil(lambda: clientF.disconnected)  # A
    spinWhile(lambda: server.transport.connected)  # B
    serverPort.stopListening()
    spinWhile(lambda: serverPort.connected)  # C
コード例 #53
0
 def testMode(self):
     filename = self.mktemp()
     f = Factory(self, filename)
     l = reactor.listenUNIX(filename, f, mode = 0600)
     self.assertEquals(stat.S_IMODE(os.stat(filename)[0]), 0600)
     tcf = TestClientFactory(self, filename)
     c = reactor.connectUNIX(filename, tcf)
     self._addPorts(l, c.transport)
コード例 #54
0
 def testDumber(self):
     filename = self.mktemp()
     f = Factory(self, filename)
     l = reactor.listenUNIX(filename, f)
     tcf = TestClientFactory(self, filename)
     c = reactor.connectUNIX(filename, tcf)
     spinUntil(lambda :getattr(f.protocol, 'made', None) and
                       getattr(tcf.protocol, 'made', None))
     self._addPorts(l, c.transport, tcf.protocol.transport, f.protocol.transport)
コード例 #55
0
ファイル: conch.py プロジェクト: fxia22/ASM_xf
def doConnect():
    log.deferr = handleError # HACK
    if '@' in options['host']:
        options['user'], options['host'] = options['host'].split('@',1)
    if not options.identitys:
        options.identitys = ['~/.ssh/id_rsa', '~/.ssh/id_dsa']
    host = options['host']
    if not options['user']:
        options['user'] = getpass.getuser() 
    if not options['port']:
        options['port'] = 22
    else:
        options['port'] = int(options['port'])
    filename = os.path.expanduser("~/.conch-%(user)s-%(host)s-%(port)s" % options)
    if not options['nocache'] and os.path.exists(filename):
        reactor.connectUNIX(filename, SSHUnixClientFactory(), timeout=2)
    else:
        reactor.connectTCP(options['host'], options['port'], SSHClientFactory())
コード例 #56
0
ファイル: test_unix.py プロジェクト: adde88/python2.7_mana
 def testDumber(self):
     filename = self.mktemp()
     f = Factory(self, filename)
     l = reactor.listenUNIX(filename, f)
     tcf = TestClientFactory(self, filename)
     c = reactor.connectUNIX(filename, tcf)
     d = defer.gatherResults([f.deferred, tcf.deferred])
     d.addCallback(lambda x: self._addPorts(
         l, c.transport, tcf.protocol.transport, f.protocol.transport))
     return d
コード例 #57
0
def connect_socket(q, address_type, address, access_control, access_control_param):
    factory = EventProtocolClientFactory(q)
    if address_type == cs.SOCKET_ADDRESS_TYPE_UNIX:
        reactor.connectUNIX(address, factory)
    elif address_type == cs.SOCKET_ADDRESS_TYPE_IPV4:
        ip, port = address
        assert port > 0

        if access_control == cs.SOCKET_ACCESS_CONTROL_PORT:
            # connect from the ip/port specified
            # This means the test will fail if the port is already binded. It
            # would be better to bind the port before connecting but that's
            # not easily doable with twisted...
            c = MyTCPConnector(ip, port, factory, 30, access_control_param, reactor)
            c.connect()
        else:
            reactor.connectTCP(ip, port, factory)
    else:
        assert False
コード例 #58
0
    def test_pidFile(self):
        """
        A lockfile is created and locked when L{IReactorUNIX.listenUNIX} is
        called and released when the Deferred returned by the L{IListeningPort}
        provider's C{stopListening} method is called back.
        """
        filename = self.mktemp()
        serverFactory = MyServerFactory()
        serverConnMade = defer.Deferred()
        serverFactory.protocolConnectionMade = serverConnMade
        unixPort = reactor.listenUNIX(filename, serverFactory, wantPID=True)
        self.assertTrue(lockfile.isLocked(filename + ".lock"))

        # XXX This part would test something about the checkPID parameter, but
        # it doesn't actually.  It should be rewritten to test the several
        # different possible behaviors.  -exarkun
        clientFactory = MyClientFactory()
        clientConnMade = defer.Deferred()
        clientFactory.protocolConnectionMade = clientConnMade
        reactor.connectUNIX(filename, clientFactory, checkPID=1)

        d = defer.gatherResults([serverConnMade, clientConnMade])

        def _portStuff(args):
            serverProtocol, clientProto = args

            # Incidental assertion which may or may not be redundant with some
            # other test.  This probably deserves its own test method.
            self.assertEqual(
                clientFactory.peerAddresses, [address.UNIXAddress(filename)]
            )

            clientProto.transport.loseConnection()
            serverProtocol.transport.loseConnection()
            return unixPort.stopListening()

        d.addCallback(_portStuff)

        def _check(ignored):
            self.assertFalse(lockfile.isLocked(filename + ".lock"), "locked")

        d.addCallback(_check)
        return d