Exemplo n.º 1
0
async def hello_process(
    server: "CPIAServer", message: Message, planet: Optional[str] = None
) -> Message:
    """Run the process hello command.

    This command creates a process the first time it's run.
    """
    if planet is None:
        planet = "Jupiter"

    if "hello_process" not in server.store:
        server.store["hello_process"] = create_process(server, create_state)

    recv, send = server.store["hello_process"]

    await send(planet)

    try:
        old_planet, new_planet = await recv()
    except ReceiveError:
        return message

    LOGGER.info(
        "Hello! The old planet was %s. The new planet is %s", old_planet, new_planet
    )

    reply = message.copy()
    reply.data["old_planet"] = old_planet
    reply.data["new_planet"] = new_planet

    return reply
Exemplo n.º 2
0
async def hello_persistent(
    server: "CPIAServer", message: Message, planet: Optional[str] = None
) -> Message:
    """Run the persistent hello command.

    This command creates a state the first time it's run.
    """
    if planet is None:
        planet = "Jupiter"

    if "hello_persistent_state" not in server.store:
        server.store["hello_persistent_state"] = create_state()

    command_task = server.store["hello_persistent_state"]

    old_planet, new_planet = command_task(planet)

    LOGGER.info(
        "Hello! The old planet was %s. The new planet is %s", old_planet, new_planet
    )

    reply = message.copy()
    reply.data["old_planet"] = old_planet
    reply.data["new_planet"] = new_planet

    return reply
Exemplo n.º 3
0
async def hello(
    server: "CPIAServer", message: Message, planet: Optional[str] = None
) -> Message:
    """Run the hello command."""
    if planet is None:
        planet = "Jupiter"
    LOGGER.info("Hello %s!", planet)
    return message
Exemplo n.º 4
0
        async def check_args(server, message, **data):  # type: ignore
            """Check arguments."""
            try:
                data = vol_schema(data)
            except vol.Invalid as exc:
                err = humanize_error(data, exc)
                LOGGER.error("Received invalid data for command %s: %s",
                             message.command, err)
                return Message(client=message.client,
                               command="invalid",
                               data=data)

            return await func(server, message, **data)
Exemplo n.º 5
0
    async def async_recv() -> Any:
        """Receive data from the process connection asynchronously."""
        while True:
            if not prc.is_alive() or parent_conn.poll():
                break
            await asyncio.sleep(0.5)

        if not prc.is_alive():
            raise ReceiveError
        try:
            return await server.add_executor_job(parent_conn.recv)
        except EOFError as exc:
            LOGGER.debug("Nothing more to receive")
            raise ReceiveError from exc
Exemplo n.º 6
0
async def hello_slow(
    server: "CPIAServer", message: Message, planet: Optional[str] = None
) -> Message:
    """Run the slow hello command."""
    if planet is None:
        planet = "Jupiter"

    result = await server.run_process_job(do_cpu_work)

    LOGGER.info("Hello %s! The result is %s", planet, result)

    reply = message.copy()
    reply.data["result"] = result

    return reply
Exemplo n.º 7
0
async def tcp_client(message: str,
                     host: str = "127.0.0.1",
                     port: int = 8555) -> None:
    """Connect to server and send message."""
    reader, writer = await asyncio.open_connection(host, port)
    data = await reader.readline()
    version_msg = data.decode()
    LOGGER.debug("Version message: %s", version_msg.strip())

    LOGGER.info("Send: %r", message)
    writer.write(message.encode())
    await writer.drain()

    data = await reader.readline()
    LOGGER.info("Received: %r", data.decode())

    LOGGER.debug("Closing the connection")
    writer.close()
    await writer.wait_closed()
Exemplo n.º 8
0
def func_wrapper(create_callback: Callable, conn: Connection,
                 *args: Any) -> None:
    """Wrap a function with connection to receive and send data."""
    running = True

    # pylint: disable=unused-argument
    def handle_signal(signum: int, frame: Any) -> None:
        """Handle signal."""
        nonlocal running
        running = False
        conn.close()

    signal.signal(signal.SIGTERM, handle_signal)
    signal.signal(signal.SIGINT, handle_signal)

    try:
        callback = create_callback(*args)
    except Exception as exc:  # pylint: disable=broad-except
        LOGGER.error("Failed to create callback: %s", exc)
        return

    while running:

        while running:
            if conn.poll():
                break
            sleep(0.5)

        try:
            data = conn.recv()
        except EOFError:
            LOGGER.debug("Nothing more to receive")
            break
        except OSError:
            LOGGER.debug("Connection is closed")
            break
        try:
            result = callback(data)
        except Exception as exc:  # pylint: disable=broad-except
            LOGGER.error("Failed to run callback: %s", exc)
            break

        if not running:
            break
        try:
            conn.send(result)
        except ValueError:
            LOGGER.error("Failed to send result %s", result)
        except OSError:
            LOGGER.debug("Connection is closed")
            break

    LOGGER.debug("Exiting process")