Python twisted.internet.endpoints.UNIXClientEndpoint() Examples

The following are 17 code examples of twisted.internet.endpoints.UNIXClientEndpoint(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module twisted.internet.endpoints , or try the search function .
Example #1
Source File: _conch.py    From flocker with Apache License 2.0 6 votes vote down vote up
def get_connection_helper(reactor, address, username, port):
    """
    Get a :class:`twisted.conch.endpoints._ISSHConnectionCreator` to connect to
    the given remote.

    :param reactor: Reactor to connect with.
    :param bytes address: The address of the remote host to connect to.
    :param bytes username: The user to connect as.
    :param int port: The port of the ssh server to connect to.

    :return _ISSHConnectionCreator:
    """
    try:
        agentEndpoint = UNIXClientEndpoint(
            reactor, os.environ["SSH_AUTH_SOCK"])
    except KeyError:
        agentEndpoint = None

    return _NewConnectionHelper(
        reactor, address, port, None, username,
        keys=None,
        password=None,
        agentEndpoint=agentEndpoint,
        knownHosts=KnownHostsFile.fromPath(FilePath("/dev/null")),
        ui=ConsoleUI(lambda: _ReadFile(b"yes"))) 
Example #2
Source File: test_endpoints.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def createClientEndpoint(self, reactor, clientFactory, **connectArgs):
        """
        Create an L{UNIXClientEndpoint} and return the values needed to verify
        its behaviour.

        @param reactor: A fake L{IReactorUNIX} that L{UNIXClientEndpoint} can
            call L{IReactorUNIX.connectUNIX} on.
        @param clientFactory: The thing that we expect to be passed to our
            L{IStreamClientEndpoint.connect} implementation.
        @param connectArgs: Optional dictionary of arguments to
            L{IReactorUNIX.connectUNIX}
        """
        address = UNIXAddress(self.mktemp())

        return (endpoints.UNIXClientEndpoint(reactor, address.name,
                                             **connectArgs),
                (address.name, clientFactory,
                 connectArgs.get('timeout', 30),
                 connectArgs.get('checkPID', 0)),
                address) 
Example #3
Source File: memcachepool.py    From ccs-calendarserver with Apache License 2.0 6 votes vote down vote up
def installPools(pools, maxClients=5, reactor=None):
    if reactor is None:
        from twisted.internet import reactor
    for name, pool in pools.items():
        if pool["ClientEnabled"]:
            if pool.get("MemcacheSocket"):
                ep = UNIXClientEndpoint(reactor, pool["MemcacheSocket"])
            else:
                ep = GAIEndpoint(reactor, pool["BindAddress"], pool["Port"])

            _installPool(
                name,
                pool["HandleCacheTypes"],
                ep,
                maxClients,
                reactor,
            ) 
Example #4
Source File: test_endpoints.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def createClientEndpoint(self, reactor, clientFactory, **connectArgs):
        """
        Create an L{UNIXClientEndpoint} and return the values needed to verify
        its behaviour.

        @param reactor: A fake L{IReactorUNIX} that L{UNIXClientEndpoint} can
            call L{IReactorUNIX.connectUNIX} on.
        @param clientFactory: The thing that we expect to be passed to our
            L{IStreamClientEndpoint.connect} implementation.
        @param connectArgs: Optional dictionary of arguments to
            L{IReactorUNIX.connectUNIX}
        """
        address = UNIXAddress(self.mktemp())

        return (endpoints.UNIXClientEndpoint(reactor, address.name,
                                             **connectArgs),
                (address.name, clientFactory,
                 connectArgs.get('timeout', 30),
                 connectArgs.get('checkPID', 0)),
                address) 
Example #5
Source File: test_endpoints.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def createClientEndpoint(self, reactor, clientFactory, **connectArgs):
        """
        Create an L{UNIXClientEndpoint} and return the values needed to verify
        its behaviour.

        @param reactor: A fake L{IReactorUNIX} that L{UNIXClientEndpoint} can
            call L{IReactorUNIX.connectUNIX} on.
        @param clientFactory: The thing that we expect to be passed to our
            L{IStreamClientEndpoint.connect} implementation.
        @param connectArgs: Optional dictionary of arguments to
            L{IReactorUNIX.connectUNIX}
        """
        address = UNIXAddress(self.mktemp())

        return (endpoints.UNIXClientEndpoint(reactor, address.name,
                                             **connectArgs),
                (address.name, clientFactory,
                 connectArgs.get('timeout', 30),
                 connectArgs.get('checkPID', 0)),
                address) 
Example #6
Source File: test_endpoints.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def test_unix(self):
        """
        When passed a UNIX strports description, L{endpoints.clientFromString}
        returns a L{UNIXClientEndpoint} instance initialized with the values
        from the string.
        """
        reactor = object()
        client = endpoints.clientFromString(
            reactor,
            "unix:path=/var/foo/bar:lockfile=1:timeout=9")
        self.assertIsInstance(client, endpoints.UNIXClientEndpoint)
        self.assertIs(client._reactor, reactor)
        self.assertEqual(client._path, "/var/foo/bar")
        self.assertEqual(client._timeout, 9)
        self.assertTrue(client._checkPID) 
Example #7
Source File: test_hpe_plugin.py    From python-hpedockerplugin with Apache License 2.0 5 votes vote down vote up
def endpointForURI(self, uri):
        return UNIXClientEndpoint(self.reactor, hpe_sock_path) 
Example #8
Source File: fixtures.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def addCluster(self, protocol, rack_controller):
        """Add a new stub cluster using the given `protocol`.

        The `protocol` should be an instance of `amp.AMP`.

        :return: A `Deferred` that fires with the connected protocol
            instance.
        """
        endpoint = endpoints.UNIXClientEndpoint(reactor, self.sockfile)
        protocol = yield endpoints.connectProtocol(endpoint, protocol)

        # Mock the registration into the database, as the rack controller is
        # already created. We reset this once registration is complete so as
        # to not interfere with other tests.
        registered = rack_controller
        patcher = MonkeyPatcher()
        patcher.add_patch(
            rackcontrollers, "register", (lambda *args, **kwargs: registered)
        )

        # Register the rack controller with the region.
        patcher.patch()
        try:
            yield protocol.callRemote(
                region.RegisterRackController,
                system_id=rack_controller.system_id,
                hostname=rack_controller.hostname,
                interfaces={},
                url=urlparse(""),
            )
        finally:
            patcher.restore()

        defer.returnValue(protocol) 
Example #9
Source File: test_endpoints.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def test_unix(self):
        """
        When passed a UNIX strports description, L{endpointClient} returns a
        L{UNIXClientEndpoint} instance initialized with the values from the
        string.
        """
        reactor = object()
        client = endpoints.clientFromString(
            reactor,
            "unix:path=/var/foo/bar:lockfile=1:timeout=9")
        self.assertIsInstance(client, endpoints.UNIXClientEndpoint)
        self.assertIdentical(client._reactor, reactor)
        self.assertEquals(client._path, "/var/foo/bar")
        self.assertEquals(client._timeout, 9)
        self.assertEquals(client._checkPID, True) 
Example #10
Source File: test_unix.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def client(self, reactor, serverAddress):
        """
        Construct a UNIX client endpoint.
        """
        return UNIXClientEndpoint(reactor, serverAddress.name) 
Example #11
Source File: test_endpoints.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def test_unixPathPositionalArg(self):
        """
        When passed a UNIX strports description specifying path as a positional
        argument, L{endpoints.clientFromString} returns a L{UNIXClientEndpoint}
        instance initialized with the values from the string.
        """
        reactor = object()
        client = endpoints.clientFromString(
            reactor,
            "unix:/var/foo/bar:lockfile=1:timeout=9")
        self.assertIsInstance(client, endpoints.UNIXClientEndpoint)
        self.assertIs(client._reactor, reactor)
        self.assertEqual(client._path, "/var/foo/bar")
        self.assertEqual(client._timeout, 9)
        self.assertTrue(client._checkPID) 
Example #12
Source File: testtools.py    From flocker with Apache License 2.0 5 votes vote down vote up
def build_UNIX_integration_tests(mixin_class, name, fixture):
    """
    Build ``AsyncTestCase`` class that runs the tests in the mixin class with
    real queries over a UNIX socket.

    :param mixin_class: A mixin class for ``AsyncTestCase`` that relies on
        having a ``self.scenario``.

    :param name: A ``str``, the name of the test category.

    :param fixture: A callable that takes a ``AsyncTestCase`` and returns a
        ``klein.Klein`` object.

    :return: A L``AsyncTestCase`` class.
    """
    class RealTests(mixin_class, AsyncTestCase):
        """
        Tests that endpoints are available over the network interfaces that
        real API users will be connecting from.
        """
        def setUp(self):
            # We use relpath as you can't bind to a path longer than 107
            # chars. You can easily get an absolute path that long
            # from mktemp, but rather strangely bind doesn't care
            # how long the abspath is, so we call relpath here and
            # it should work as long as our method names aren't too long
            path = os.path.relpath(self.mktemp())
            self.app = fixture(self)
            self.port = reactor.listenUNIX(
                path, Site(self.app.resource()),
            )
            self.addCleanup(self.port.stopListening)
            self.agent = ProxyAgent(UNIXClientEndpoint(reactor, path), reactor)
            super(RealTests, self).setUp()

    RealTests.__name__ += name
    RealTests.__module__ = mixin_class.__module__
    return RealTests

# Fakes for testing Twisted Web servers.  Unverified.  Belongs in Twisted.
# https://twistedmatrix.com/trac/ticket/3274 
Example #13
Source File: test_unix.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def client(self, reactor, serverAddress):
        """
        Construct a UNIX client endpoint.
        """
        return UNIXClientEndpoint(reactor, serverAddress.name) 
Example #14
Source File: test_endpoints.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def test_unixPathPositionalArg(self):
        """
        When passed a UNIX strports description specifying path as a positional
        argument, L{endpoints.clientFromString} returns a L{UNIXClientEndpoint}
        instance initialized with the values from the string.
        """
        reactor = object()
        client = endpoints.clientFromString(
            reactor,
            "unix:/var/foo/bar:lockfile=1:timeout=9")
        self.assertIsInstance(client, endpoints.UNIXClientEndpoint)
        self.assertIs(client._reactor, reactor)
        self.assertEqual(client._path, "/var/foo/bar")
        self.assertEqual(client._timeout, 9)
        self.assertTrue(client._checkPID) 
Example #15
Source File: test_endpoints.py    From Safejumper-for-Desktop with GNU General Public License v2.0 5 votes vote down vote up
def test_unix(self):
        """
        When passed a UNIX strports description, L{endpoints.clientFromString}
        returns a L{UNIXClientEndpoint} instance initialized with the values
        from the string.
        """
        reactor = object()
        client = endpoints.clientFromString(
            reactor,
            "unix:path=/var/foo/bar:lockfile=1:timeout=9")
        self.assertIsInstance(client, endpoints.UNIXClientEndpoint)
        self.assertIs(client._reactor, reactor)
        self.assertEqual(client._path, "/var/foo/bar")
        self.assertEqual(client._timeout, 9)
        self.assertTrue(client._checkPID) 
Example #16
Source File: _keys.py    From flocker with Apache License 2.0 4 votes vote down vote up
def ensure_agent_has_ssh_key(reactor, key):
    """
    Check that the running ssh-agent has the private key corresponding to the
    provided key.

    :param reactor: The reactor to use to connect to the agent.
    :param Key key: The ssh key to check for in the agent.

    :return Deferred: That fires with a successful result if the key is found.
       Otherwise, fails with ``AgentNotFound`` or ``KeyNotFound``.
    """
    try:
        agent_socket = os.environ["SSH_AUTH_SOCK"]
    except KeyError:
        return fail(AgentNotFound())

    if not key.isPublic():
        key = key.public()

    action = start_action(
        action_type="flocker.provision.ssh:check_agent_has_ssh_keys",
        key_fingerprint=key.fingerprint(),
        agent_socket=agent_socket)

    with action.context():

        agent_endpoint = UNIXClientEndpoint(reactor, agent_socket)
        agent_protocol = SSHAgentClient()
        connected = DeferredContext(
            connectProtocol(agent_endpoint, agent_protocol))
        connected.addCallback(lambda _: agent_protocol.requestIdentities())

        def check_keys(results):
            for key_data, comment in results:
                agent_key = Key.fromString(key_data, type='blob')
                Message.new(
                    message_type="flocker.provision.ssh:agent_key",
                    key_fingerprint=agent_key.fingerprint(),
                    commnet=comment).write()
                if agent_key == key:
                    return True
            raise KeyNotFound(expected_key=key)
        connected.addCallback(check_keys)

        def disconnect(result):
            agent_protocol.transport.loseConnection()
            return result
        connected.addBoth(disconnect)

        return connected.addActionFinish() 
Example #17
Source File: __init__.py    From maas with GNU Affero General Public License v3.0 4 votes vote down vote up
def connect(self, cluster, region):
        """Wire up a connection between cluster and region.

        Uses a UNIX socket to very rapidly connect the two ends.

        :type cluster: `twisted.internet.interfaces.IProtocol`
        :type region: `twisted.internet.interfaces.IProtocol`
        """
        # Wire up the region and cluster protocols via the sockfile.
        sockfile = path.join(self.sockdir.path, next(self.socknames))

        class RegionFactory(Factory):
            def buildProtocol(self, addr):
                return region

        # `doUpdate` has already been called, but with no connections the
        # mocked `_fetch_rpc_info` caused no `maas_url` to be set on the
        # RPC service. Set the `maas_url` to the one set on the fixture.
        self.rpc_service.maas_url = self.maas_url

        endpoint_region = endpoints.UNIXServerEndpoint(reactor, sockfile)
        port = yield endpoint_region.listen(RegionFactory())

        endpoint_cluster = endpoints.UNIXClientEndpoint(reactor, sockfile)
        client = yield endpoints.connectProtocol(endpoint_cluster, cluster)

        # Wait for the client to be fully connected. Because onReady will have
        # been capped-off by now (see ClusterClient.connectionMade) this will
        # not raise any exceptions. In some ways this is convenient because it
        # allows the resulting issues to be encountered within test code.
        yield client.ready.get()

        @inlineCallbacks
        def shutdown():
            # We need to make sure that everything is shutdown correctly. TLS
            # seems to make this even more important: it complains loudly if
            # connections are not closed cleanly. An interesting article to
            # read now is Jono Lange's "How to Disconnect in Twisted, Really"
            # <http://mumak.net/stuff/twisted-disconnect.html>.
            yield port.loseConnection()
            yield port.deferred
            if region.transport is not None:
                yield region.transport.loseConnection()
                yield region.onConnectionLost
            if client.transport is not None:
                yield client.transport.loseConnection()
                yield client.onConnectionLost

        # Fixtures don't wait for deferred work in clean-up tasks (or anywhere
        # else), so we can't use `self.addCleanup(shutdown)` here. We need to
        # get the user to add `shutdown` to the clean-up tasks for the *test*,
        # on the assumption they're using a test framework that accommodates
        # deferred work (like testtools with `MAASTwistedRunTest`).
        returnValue(shutdown)


# An iterable of names for new dynamically-created AMP protocol factories.