Python asyncio.open_unix_connection() Examples

The following are 30 code examples of asyncio.open_unix_connection(). 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 asyncio , or try the search function .
Example #1
Source File: run.py    From pop with Apache License 2.0 8 votes vote down vote up
def send(hub, worker, payload):
    '''
    Send the given payload to the given worker, yield iterations based on the
    returns from the remote.
    '''
    mp = msgpack.dumps(payload, use_bin_type=True)
    mp += hub.proc.DELIM
    reader, writer = await asyncio.open_unix_connection(path=worker['path'])
    writer.write(mp)
    await writer.drain()
    final_ret = True
    while True:
        ret = await reader.readuntil(hub.proc.DELIM)
        p_ret = ret[:-len(hub.proc.DELIM)]
        i_flag = p_ret[-1:]
        ret = msgpack.loads(p_ret[:-1], raw=False)
        if i_flag == hub.proc.D_FLAG:
            # break for the end of the sequence
            break
        yield ret
        final_ret = False
    if final_ret:
        yield ret 
Example #2
Source File: test_rpc_during_beam_sync.py    From trinity with MIT License 7 votes vote down vote up
def get_ipc_response(
        jsonrpc_ipc_pipe_path,
        request_msg,
        event_loop,
        event_bus):

    # Give event subsriptions a moment to propagate.
    await asyncio.sleep(0.01)

    assert wait_for(jsonrpc_ipc_pipe_path), "IPC server did not successfully start with IPC file"

    reader, writer = await asyncio.open_unix_connection(str(jsonrpc_ipc_pipe_path))

    writer.write(request_msg)
    await writer.drain()
    result_bytes = b''
    while not can_decode_json(result_bytes):
        result_bytes += await asyncio.tasks.wait_for(reader.readuntil(b'}'), 0.25)

    writer.close()
    return json.loads(result_bytes.decode()) 
Example #3
Source File: __init__.py    From aioh2 with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _setUp(self):
        self.r, self.w = yield from asyncio.open_unix_connection(self.path)
        config = H2Configuration(header_encoding='utf-8')
        self.conn = H2Connection(config=config)
        self.conn.initiate_connection()
        self.w.write(self.conn.data_to_send())
        events = yield from self._expect_events(3)
        self.assertIsInstance(events[0], RemoteSettingsChanged)
        self.assertIsInstance(events[1], RemoteSettingsChanged)
        self.assertIsInstance(events[2], SettingsAcknowledged)

        self.assertIsInstance((yield from self.server.events.get()),
                              RemoteSettingsChanged)
        self.assertIsInstance((yield from self.server.events.get()),
                              SettingsAcknowledged)
        self.assertIsInstance((yield from self.server.events.get()),
                              SettingsAcknowledged) 
Example #4
Source File: test_responder.py    From postfix-mta-sts-resolver with MIT License 6 votes vote down vote up
def test_unix_responder(unix_responder, params):
    (request, response), bufsize = params
    resp, path = unix_responder
    stream_reader = netstring.StreamReader()
    string_reader = stream_reader.next_string()
    assert os.stat(path).st_mode & 0o777 == 0o666
    reader, writer = await asyncio.open_unix_connection(path)
    try:
        writer.write(netstring.encode(request))
        res = b''
        while True:
            try:
                part = string_reader.read()
            except netstring.WantRead:
                data = await reader.read(bufsize)
                assert data
                stream_reader.feed(data)
            else:
                if not part:
                    break
                res += part
        assert res == response
    finally:
        writer.close() 
Example #5
Source File: test_ipc.py    From trinity with MIT License 6 votes vote down vote up
def get_ipc_response(
        jsonrpc_ipc_pipe_path,
        request_msg,
        event_loop,
        event_bus):

    # Give event subsriptions a moment to propagate.
    await asyncio.sleep(0.01)

    assert wait_for(jsonrpc_ipc_pipe_path), "IPC server did not successfully start with IPC file"

    reader, writer = await asyncio.open_unix_connection(str(jsonrpc_ipc_pipe_path))

    writer.write(request_msg)
    await writer.drain()
    result_bytes = b''
    while not can_decode_json(result_bytes):
        result_bytes += await asyncio.tasks.wait_for(reader.readuntil(b'}'), 0.25)

    writer.close()
    return json.loads(result_bytes.decode()) 
Example #6
Source File: baseclient.py    From pypresence with MIT License 6 votes vote down vote up
def handshake(self):
        if sys.platform == 'linux' or sys.platform == 'darwin':
            self.sock_reader, self.sock_writer = await asyncio.open_unix_connection(self.ipc_path, loop=self.loop)
        elif sys.platform == 'win32' or sys.platform == 'win64':
            self.sock_reader = asyncio.StreamReader(loop=self.loop)
            reader_protocol = asyncio.StreamReaderProtocol(
                self.sock_reader, loop=self.loop)
            try:
                self.sock_writer, _ = await self.loop.create_pipe_connection(lambda: reader_protocol, self.ipc_path)
            except FileNotFoundError:
                raise InvalidPipe
        self.send_data(0, {'v': 1, 'client_id': self.client_id})
        data = await self.sock_reader.read(1024)
        code, length = struct.unpack('<ii', data[:8])
        if self._events_on:
            self.sock_reader.feed_data = self.on_event 
Example #7
Source File: test_server.py    From aioconsole with GNU General Public License v3.0 6 votes vote down vote up
def test_uds_server(event_loop, tmpdir):
    path = str(tmpdir / "test.uds")
    server = await start_console_server(path=path, banner="test")

    stream = io.StringIO()
    print_server(server, "test console", file=stream)
    expected = "The test console is being served on {}\n"
    assert stream.getvalue() == expected.format(path)

    address = server.sockets[0].getsockname()
    reader, writer = await asyncio.open_unix_connection(address)
    assert (await reader.readline()) == b"test\n"
    writer.write(b"1+1\n")
    assert (await reader.readline()) == b">>> 2\n"
    writer.write_eof()
    assert (await reader.readline()) == b">>> \n"
    writer.close()
    if compat.PY37:
        await writer.wait_closed()
    server.close()
    await server.wait_closed() 
Example #8
Source File: __init__.py    From qubes-core-admin-client with GNU Lesser General Public License v2.1 5 votes vote down vote up
def _get_events_reader(self, vm=None) -> (asyncio.StreamReader, callable):
        '''Make connection to qubesd and return stream to read events from

        :param vm: Specific VM for which events should be handled, use None
        to handle events from all VMs (and non-VM objects)
        :return stream to read events from and a cleanup function
        (call it to terminate qubesd connection)'''
        if vm is not None:
            dest = vm.name
        else:
            dest = 'dom0'

        if self.app.qubesd_connection_type == 'socket':
            reader, writer = yield from asyncio.open_unix_connection(
                qubesadmin.config.QUBESD_SOCKET)
            writer.write(self._api_method.encode() + b'+ ')  # method+arg
            writer.write(b'dom0 ')  # source
            writer.write(b'name ' + dest.encode('ascii') + b'\0')  # dest
            writer.write_eof()

            def cleanup_func():
                '''Close connection to qubesd'''
                writer.close()
        elif self.app.qubesd_connection_type == 'qrexec':
            proc = yield from asyncio.create_subprocess_exec(
                'qrexec-client-vm', dest, self._api_method,
                stdin=subprocess.PIPE, stdout=subprocess.PIPE)

            proc.stdin.write_eof()
            reader = proc.stdout

            def cleanup_func():
                '''Close connection to qubesd'''
                try:
                    proc.kill()
                except ProcessLookupError:
                    pass
        else:
            raise NotImplementedError('Unsupported qubesd connection type: '
                                      + self.app.qubesd_connection_type)
        return reader, cleanup_func 
Example #9
Source File: link.py    From synapse with Apache License 2.0 5 votes vote down vote up
def unixconnect(path):
    '''
    Connect to a PF_UNIX server listening on the given path.
    '''
    reader, writer = await asyncio.open_unix_connection(path=path)
    info = {'path': path, 'unix': True}
    return await Link.anit(reader, writer, info=info) 
Example #10
Source File: test_streams.py    From android_universal with MIT License 5 votes vote down vote up
def test_open_unix_connection(self):
        with test_utils.run_test_unix_server() as httpd:
            conn_fut = asyncio.open_unix_connection(httpd.address,
                                                    loop=self.loop)
            self._basetest_open_connection(conn_fut) 
Example #11
Source File: test_streams.py    From android_universal with MIT License 5 votes vote down vote up
def test_open_unix_connection_no_loop_ssl(self):
        with test_utils.run_test_unix_server(use_ssl=True) as httpd:
            conn_fut = asyncio.open_unix_connection(
                httpd.address,
                ssl=test_utils.dummy_ssl_context(),
                server_hostname='',
                loop=self.loop)

            self._basetest_open_connection_no_loop_ssl(conn_fut) 
Example #12
Source File: test_streams.py    From android_universal with MIT License 5 votes vote down vote up
def test_open_unix_connection_error(self):
        with test_utils.run_test_unix_server() as httpd:
            conn_fut = asyncio.open_unix_connection(httpd.address,
                                                    loop=self.loop)
            self._basetest_open_connection_error(conn_fut) 
Example #13
Source File: test_streams.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_open_unix_connection_error(self):
        with test_utils.run_test_unix_server() as httpd:
            conn_fut = asyncio.open_unix_connection(httpd.address,
                                                    loop=self.loop)
            self._basetest_open_connection_error(conn_fut) 
Example #14
Source File: test_streams.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_open_unix_connection_no_loop_ssl(self):
        with test_utils.run_test_unix_server(use_ssl=True) as httpd:
            conn_fut = asyncio.open_unix_connection(
                httpd.address,
                ssl=test_utils.dummy_ssl_context(),
                server_hostname='',
                loop=self.loop)

            self._basetest_open_connection_no_loop_ssl(conn_fut) 
Example #15
Source File: test_streams.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_open_unix_connection(self):
        with test_utils.run_test_unix_server() as httpd:
            conn_fut = asyncio.open_unix_connection(httpd.address,
                                                    loop=self.loop)
            self._basetest_open_connection(conn_fut) 
Example #16
Source File: client.py    From aiorpc with Do What The F*ck You Want To Public License 5 votes vote down vote up
def _open_connection(self):
        _logger.debug("connect to %s:%s...", *self.getpeername())
        if self._host:
            reader, writer = await asyncio.open_connection(self._host, self._port, loop=self._loop)
        else:
            reader, writer = await asyncio.open_unix_connection(self._path, loop=self._loop)
        self._conn = Connection(reader, writer,
                                msgpack.Unpacker(raw=False,
                                                 **self._unpack_params))
        _logger.debug("Connection to %s:%s established", *self.getpeername()) 
Example #17
Source File: endpoint.py    From lahja with MIT License 5 votes vote down vote up
def connect_to(cls, path: Path) -> ConnectionAPI:
        reader, writer = await asyncio.open_unix_connection(str(path))
        return cls(reader, writer) 
Example #18
Source File: test_streams.py    From annotated-py-projects with MIT License 5 votes vote down vote up
def test_open_unix_connection_error(self):
        with test_utils.run_test_unix_server() as httpd:
            conn_fut = asyncio.open_unix_connection(httpd.address,
                                                    loop=self.loop)
            self._basetest_open_connection_error(conn_fut) 
Example #19
Source File: discordRichPresencePlex.py    From discord-rich-presence-plex with MIT License 5 votes vote down vote up
def handshake(self):
		try:
			if (isLinux):
				self.pipeReader, self.pipeWriter = await asyncio.open_unix_connection(self.IPCPipe, loop = self.loop)
			else:
				self.pipeReader = asyncio.StreamReader(loop = self.loop)
				self.pipeWriter, _ = await self.loop.create_pipe_connection(lambda: asyncio.StreamReaderProtocol(self.pipeReader, loop = self.loop), self.IPCPipe)
			self.write(0, {"v": 1, "client_id": self.clientID})
			await self.read()
			self.running = True
		except Exception as e:
			self.child.log("[HANDSHAKE] " + str(e)) 
Example #20
Source File: qubesd_query.py    From qubes-core-admin with GNU Lesser General Public License v2.1 5 votes vote down vote up
def qubesd_client(socket, payload, *args):
    '''
    Connect to qubesd, send request and passthrough response to stdout

    :param socket: path to qubesd socket
    :param payload: payload of the request
    :param args: request to qubesd
    :return:
    '''
    try:
        reader, writer = yield from asyncio.open_unix_connection(socket)
    except asyncio.CancelledError:
        return 1

    for arg in args:
        writer.write(arg.encode('ascii'))
        writer.write(b'\0')
    writer.write(payload)
    writer.write_eof()

    try:
        header_data = yield from reader.read(1)
        returncode = int(header_data)
        sys.stdout.buffer.write(header_data)  # pylint: disable=no-member
        while not reader.at_eof():
            data = yield from reader.read(4096)
            sys.stdout.buffer.write(data)  # pylint: disable=no-member
            sys.stdout.flush()
        return returncode
    except asyncio.CancelledError:
        return 1
    finally:
        writer.close() 
Example #21
Source File: test_streams.py    From annotated-py-projects with MIT License 5 votes vote down vote up
def test_open_unix_connection_no_loop_ssl(self):
        with test_utils.run_test_unix_server(use_ssl=True) as httpd:
            conn_fut = asyncio.open_unix_connection(
                httpd.address,
                ssl=test_utils.dummy_ssl_context(),
                server_hostname='',
                loop=self.loop)

            self._basetest_open_connection_no_loop_ssl(conn_fut) 
Example #22
Source File: test_streams.py    From annotated-py-projects with MIT License 5 votes vote down vote up
def test_open_unix_connection(self):
        with test_utils.run_test_unix_server() as httpd:
            conn_fut = asyncio.open_unix_connection(httpd.address,
                                                    loop=self.loop)
            self._basetest_open_connection(conn_fut) 
Example #23
Source File: server.py    From python-proxy with MIT License 5 votes vote down vote up
def server_run(self, handler):
        errwait = 0
        while not self.closed:
            if self.uri.unix:
                wait = asyncio.open_unix_connection(path=self.uri.bind)
            else:
                wait = asyncio.open_connection(host=self.uri.host_name, port=self.uri.port, local_addr=(self.uri.lbind, 0) if self.uri.lbind else None)
            try:
                reader, writer = await asyncio.wait_for(wait, timeout=SOCKET_TIMEOUT)
                writer.write(self.uri.auth)
                self.writer = writer
                try:
                    data = await reader.read_n(1)
                except asyncio.TimeoutError:
                    data = None
                if data and data[0] != 0:
                    reader._buffer[0:0] = data
                    asyncio.ensure_future(handler(reader, writer))
                else:
                    writer.close()
                errwait = 0
            except Exception as ex:
                try:
                    writer.close()
                except Exception:
                    pass
                if not self.closed:
                    await asyncio.sleep(errwait)
                    errwait = min(errwait*1.3 + 0.1, 30) 
Example #24
Source File: test_streams.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_open_unix_connection(self):
        with test_utils.run_test_unix_server() as httpd:
            conn_fut = asyncio.open_unix_connection(httpd.address,
                                                    loop=self.loop)
            self._basetest_open_connection(conn_fut) 
Example #25
Source File: test_streams.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_open_unix_connection_no_loop_ssl(self):
        with test_utils.run_test_unix_server(use_ssl=True) as httpd:
            conn_fut = asyncio.open_unix_connection(
                httpd.address,
                ssl=test_utils.dummy_ssl_context(),
                server_hostname='',
                loop=self.loop)

            self._basetest_open_connection_no_loop_ssl(conn_fut) 
Example #26
Source File: test_streams.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_open_unix_connection_error(self):
        with test_utils.run_test_unix_server() as httpd:
            conn_fut = asyncio.open_unix_connection(httpd.address,
                                                    loop=self.loop)
            self._basetest_open_connection_error(conn_fut) 
Example #27
Source File: connection.py    From aredis with MIT License 5 votes vote down vote up
def _connect(self):
        reader, writer = await exec_with_timeout(
            asyncio.open_unix_connection(path=self.path,
                                         ssl=self.ssl_context,
                                         loop=self.loop),
            self._connect_timeout,
            loop=self.loop
        )
        self._reader = reader
        self._writer = writer
        await self.on_connect() 
Example #28
Source File: test_streams.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_open_unix_connection(self):
        with test_utils.run_test_unix_server() as httpd:
            conn_fut = asyncio.open_unix_connection(httpd.address,
                                                    loop=self.loop)
            self._basetest_open_connection(conn_fut) 
Example #29
Source File: test_streams.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_open_unix_connection_no_loop_ssl(self):
        with test_utils.run_test_unix_server(use_ssl=True) as httpd:
            conn_fut = asyncio.open_unix_connection(
                httpd.address,
                ssl=test_utils.dummy_ssl_context(),
                server_hostname='',
                loop=self.loop)

            self._basetest_open_connection_no_loop_ssl(conn_fut) 
Example #30
Source File: test_streams.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_open_unix_connection_error(self):
        with test_utils.run_test_unix_server() as httpd:
            conn_fut = asyncio.open_unix_connection(httpd.address,
                                                    loop=self.loop)
            self._basetest_open_connection_error(conn_fut)