python/qmp/protocol: add open_with_socket()

Instead of listening for incoming connections with a SocketAddr, add a
new method open_with_socket() that accepts an existing socket.

Signed-off-by: Marc-André Lureau <marcandre.lureau@redhat.com>
Reviewed-by: Daniel P. Berrangé <berrange@redhat.com>
Message-id: 20230111080101.969151-2-marcandre.lureau@redhat.com
Signed-off-by: John Snow <jsnow@redhat.com>
This commit is contained in:
Marc-André Lureau 2023-01-11 12:00:59 +04:00 committed by John Snow
parent 166464c6ce
commit a3cfea92e2

View file

@ -18,6 +18,7 @@ from asyncio import StreamReader, StreamWriter
from enum import Enum from enum import Enum
from functools import wraps from functools import wraps
import logging import logging
import socket
from ssl import SSLContext from ssl import SSLContext
from typing import ( from typing import (
Any, Any,
@ -296,6 +297,19 @@ class AsyncProtocol(Generic[T]):
await self.accept() await self.accept()
assert self.runstate == Runstate.RUNNING assert self.runstate == Runstate.RUNNING
@upper_half
@require(Runstate.IDLE)
async def open_with_socket(self, sock: socket.socket) -> None:
"""
Start connection with given socket.
:param sock: A socket.
:raise StateError: When the `Runstate` is not `IDLE`.
"""
self._reader, self._writer = await asyncio.open_connection(sock=sock)
self._set_state(Runstate.CONNECTING)
@upper_half @upper_half
@require(Runstate.IDLE) @require(Runstate.IDLE)
async def start_server(self, address: SocketAddrT, async def start_server(self, address: SocketAddrT,
@ -343,6 +357,7 @@ class AsyncProtocol(Generic[T]):
protocol-level failure occurs while establishing a new protocol-level failure occurs while establishing a new
session, the wrapped error may also be an `QMPError`. session, the wrapped error may also be an `QMPError`.
""" """
if not self._reader:
if self._accepted is None: if self._accepted is None:
raise QMPError("Cannot call accept() before start_server().") raise QMPError("Cannot call accept() before start_server().")
await self._session_guard( await self._session_guard(