p2p_daemon.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629
  1. import asyncio
  2. import json
  3. import logging
  4. import os
  5. import secrets
  6. from collections.abc import AsyncIterable as AsyncIterableABC
  7. from contextlib import closing, suppress
  8. from dataclasses import dataclass
  9. from datetime import datetime
  10. from importlib.resources import path
  11. from typing import Any, AsyncIterator, Awaitable, Callable, Dict, List, Optional, Sequence, Tuple, Type, TypeVar, Union
  12. from google.protobuf.message import Message
  13. from multiaddr import Multiaddr
  14. import hivemind.hivemind_cli as cli
  15. import hivemind.p2p.p2p_daemon_bindings.p2pclient as p2pclient
  16. from hivemind.p2p.p2p_daemon_bindings.control import DEFAULT_MAX_MSG_SIZE, P2PDaemonError, P2PHandlerError
  17. from hivemind.p2p.p2p_daemon_bindings.datastructures import PeerID, PeerInfo, StreamInfo
  18. from hivemind.proto.p2pd_pb2 import RPCError
  19. from hivemind.utils.asyncio import as_aiter, asingle
  20. from hivemind.utils.logging import get_logger, golog_level_to_python, loglevel, python_level_to_golog
  21. from hivemind.utils.networking import get_free_port
  22. logger = get_logger(__name__)
  23. P2PD_FILENAME = "p2pd"
  24. @dataclass(frozen=True)
  25. class P2PContext(object):
  26. handle_name: str
  27. local_id: PeerID
  28. remote_id: PeerID = None
  29. class P2P:
  30. """
  31. This class is responsible for establishing peer-to-peer connections through NAT and/or firewalls.
  32. It creates and manages a libp2p daemon (https://libp2p.io) in a background process,
  33. then terminates it when P2P is shut down. In order to communicate, a P2P instance should
  34. either use one or more initial_peers that will connect it to the rest of the swarm or
  35. use the public IPFS network (https://ipfs.io).
  36. For incoming connections, P2P instances add RPC handlers that may be accessed by other peers:
  37. - `P2P.add_protobuf_handler` accepts a protobuf message and returns another protobuf
  38. - `P2P.add_binary_stream_handler` transfers raw data using bi-directional streaming interface
  39. To access these handlers, a P2P instance can `P2P.call_protobuf_handler`/`P2P.call_binary_stream_handler`,
  40. using the recipient's unique `P2P.peer_id` and the name of the corresponding handler.
  41. """
  42. HEADER_LEN = 8
  43. BYTEORDER = "big"
  44. MESSAGE_MARKER = b"\x00"
  45. ERROR_MARKER = b"\x01"
  46. END_OF_STREAM = RPCError()
  47. DHT_MODE_MAPPING = {
  48. "auto": {"dht": 1},
  49. "server": {"dhtServer": 1},
  50. "client": {"dhtClient": 1},
  51. }
  52. FORCE_REACHABILITY_MAPPING = {
  53. "public": {"forceReachabilityPublic": 1},
  54. "private": {"forceReachabilityPrivate": 1},
  55. }
  56. _UNIX_SOCKET_PREFIX = "/unix/tmp/hivemind-"
  57. def __init__(self):
  58. self.peer_id = None
  59. self._client = None
  60. self._child = None
  61. self._alive = False
  62. self._reader_task = None
  63. self._listen_task = None
  64. @classmethod
  65. async def create(
  66. cls,
  67. initial_peers: Optional[Sequence[Union[Multiaddr, str]]] = None,
  68. *,
  69. announce_maddrs: Optional[Sequence[Union[Multiaddr, str]]] = None,
  70. auto_nat: bool = True,
  71. conn_manager: bool = True,
  72. dht_mode: str = "server",
  73. force_reachability: Optional[str] = None,
  74. host_maddrs: Optional[Sequence[Union[Multiaddr, str]]] = ("/ip4/127.0.0.1/tcp/0",),
  75. identity_path: Optional[str] = None,
  76. idle_timeout: float = 30,
  77. nat_port_map: bool = True,
  78. quic: bool = False,
  79. relay_hop_limit: int = 0,
  80. startup_timeout: float = 15,
  81. tls: bool = True,
  82. use_auto_relay: bool = False,
  83. use_ipfs: bool = False,
  84. use_relay: bool = True,
  85. use_relay_hop: bool = False,
  86. use_relay_discovery: bool = False,
  87. persistent_conn_max_msg_size: int = DEFAULT_MAX_MSG_SIZE,
  88. ) -> "P2P":
  89. """
  90. Start a new p2pd process and connect to it.
  91. :param initial_peers: List of bootstrap peers
  92. :param auto_nat: Enables the AutoNAT service
  93. :param announce_maddrs: Visible multiaddrs that the peer will announce
  94. for external connections from other p2p instances
  95. :param conn_manager: Enables the Connection Manager
  96. :param dht_mode: libp2p DHT mode (auto/client/server).
  97. Defaults to "server" to make collaborations work in local networks.
  98. Details: https://pkg.go.dev/github.com/libp2p/go-libp2p-kad-dht#ModeOpt
  99. :param force_reachability: Force reachability mode (public/private)
  100. :param host_maddrs: Multiaddrs to listen for external connections from other p2p instances
  101. :param identity_path: Path to a pre-generated private key file. If defined, makes the peer ID deterministic.
  102. May be generated using ``./p2p-keygen`` from ``go-libp2p-daemon``.
  103. :param idle_timeout: kill daemon if client has been idle for a given number of
  104. seconds before opening persistent streams
  105. :param nat_port_map: Enables NAT port mapping
  106. :param quic: Enables the QUIC transport
  107. :param relay_hop_limit: sets the hop limit for hop relays
  108. :param startup_timeout: raise a P2PDaemonError if the daemon does not start in ``startup_timeout`` seconds
  109. :param tls: Enables TLS1.3 channel security protocol
  110. :param use_auto_relay: enables autorelay
  111. :param use_ipfs: Bootstrap to IPFS (incompatible with initial_peers)
  112. :param use_relay: enables circuit relay
  113. :param use_relay_hop: enables hop for relay
  114. :param use_relay_discovery: enables passive discovery for relay
  115. :return: a wrapper for the p2p daemon
  116. """
  117. assert not (
  118. initial_peers and use_ipfs
  119. ), "User-defined initial_peers and use_ipfs=True are incompatible, please choose one option"
  120. self = cls()
  121. with path(cli, P2PD_FILENAME) as p:
  122. p2pd_path = p
  123. self._daemon_listen_port = get_free_port()
  124. self._client_listen_port = get_free_port()
  125. self._daemon_listen_maddr = Multiaddr(f'/ip4/127.0.0.1/tcp/{self._daemon_listen_port}')
  126. self._client_listen_maddr = Multiaddr(f'/ip4/127.0.0.1/tcp/{self._client_listen_port}')
  127. need_bootstrap = bool(initial_peers) or use_ipfs
  128. process_kwargs = cls.DHT_MODE_MAPPING.get(dht_mode, {"dht": 0})
  129. process_kwargs.update(cls.FORCE_REACHABILITY_MAPPING.get(force_reachability, {}))
  130. for param, value in [
  131. ("bootstrapPeers", initial_peers),
  132. ("hostAddrs", host_maddrs),
  133. ("announceAddrs", announce_maddrs),
  134. ]:
  135. if value:
  136. process_kwargs[param] = self._maddrs_to_str(value)
  137. if identity_path is not None:
  138. process_kwargs["id"] = identity_path
  139. proc_args = self._make_process_args(
  140. str(p2pd_path),
  141. autoRelay=use_auto_relay,
  142. autonat=auto_nat,
  143. b=need_bootstrap,
  144. connManager=conn_manager,
  145. idleTimeout=f"{idle_timeout}s",
  146. listen=self._daemon_listen_maddr,
  147. natPortMap=nat_port_map,
  148. quic=quic,
  149. relay=use_relay,
  150. relayDiscovery=use_relay_discovery,
  151. relayHop=use_relay_hop,
  152. relayHopLimit=relay_hop_limit,
  153. tls=tls,
  154. persistentConnMaxMsgSize=persistent_conn_max_msg_size,
  155. **process_kwargs,
  156. )
  157. env = os.environ.copy()
  158. env.setdefault("GOLOG_LOG_LEVEL", python_level_to_golog(loglevel))
  159. env["GOLOG_LOG_FMT"] = "json"
  160. logger.debug(f"Launching {proc_args}")
  161. self._child = await asyncio.subprocess.create_subprocess_exec(
  162. *proc_args, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.STDOUT, env=env
  163. )
  164. self._alive = True
  165. ready = asyncio.Future()
  166. self._reader_task = asyncio.create_task(self._read_outputs(ready))
  167. try:
  168. await asyncio.wait_for(ready, startup_timeout)
  169. except asyncio.TimeoutError:
  170. await self.shutdown()
  171. raise P2PDaemonError(f"Daemon failed to start in {startup_timeout:.1f} seconds")
  172. self._client = await p2pclient.Client.create(
  173. control_maddr=self._daemon_listen_maddr,
  174. listen_maddr=self._client_listen_maddr,
  175. persistent_conn_max_msg_size=persistent_conn_max_msg_size,
  176. )
  177. await self._ping_daemon()
  178. return self
  179. @classmethod
  180. async def replicate(cls, daemon_listen_maddr: Multiaddr) -> "P2P":
  181. """
  182. Connect to existing p2p daemon
  183. :param daemon_listen_maddr: multiaddr of the existing p2p daemon
  184. :return: new wrapper for the existing p2p daemon
  185. """
  186. self = cls()
  187. # There is no child under control
  188. # Use external already running p2pd
  189. self._child = None
  190. self._alive = True
  191. socket_uid = secrets.token_urlsafe(8)
  192. self._daemon_listen_maddr = daemon_listen_maddr
  193. self._client_listen_maddr = Multiaddr(cls._UNIX_SOCKET_PREFIX + f"p2pclient-{socket_uid}.sock")
  194. self._client = await p2pclient.Client.create(self._daemon_listen_maddr, self._client_listen_maddr)
  195. await self._ping_daemon()
  196. return self
  197. async def _ping_daemon(self) -> None:
  198. self.peer_id, self._visible_maddrs = await self._client.identify()
  199. logger.debug(f"Launched p2pd with peer id = {self.peer_id}, host multiaddrs = {self._visible_maddrs}")
  200. async def get_visible_maddrs(self, latest: bool = False) -> List[Multiaddr]:
  201. """
  202. Get multiaddrs of the current peer that should be accessible by other peers.
  203. :param latest: ask the P2P daemon to refresh the visible multiaddrs
  204. """
  205. if latest:
  206. _, self._visible_maddrs = await self._client.identify()
  207. if not self._visible_maddrs:
  208. raise ValueError(f"No multiaddrs found for peer {self.peer_id}")
  209. p2p_maddr = Multiaddr(f"/p2p/{self.peer_id.to_base58()}")
  210. return [addr.encapsulate(p2p_maddr) for addr in self._visible_maddrs]
  211. async def list_peers(self) -> List[PeerInfo]:
  212. return list(await self._client.list_peers())
  213. async def wait_for_at_least_n_peers(self, n_peers: int, attempts: int = 3, delay: float = 1) -> None:
  214. for _ in range(attempts):
  215. peers = await self._client.list_peers()
  216. if len(peers) >= n_peers:
  217. return
  218. await asyncio.sleep(delay)
  219. raise RuntimeError("Not enough peers")
  220. @property
  221. def daemon_listen_maddr(self) -> Multiaddr:
  222. return self._daemon_listen_maddr
  223. @staticmethod
  224. async def send_raw_data(data: bytes, writer: asyncio.StreamWriter, *, drain: bool = True) -> None:
  225. writer.write(len(data).to_bytes(P2P.HEADER_LEN, P2P.BYTEORDER))
  226. writer.write(data)
  227. if drain:
  228. await writer.drain()
  229. @staticmethod
  230. async def receive_raw_data(reader: asyncio.StreamReader) -> bytes:
  231. header = await reader.readexactly(P2P.HEADER_LEN)
  232. content_length = int.from_bytes(header, P2P.BYTEORDER)
  233. return await reader.readexactly(content_length)
  234. TInputProtobuf = TypeVar("TInputProtobuf")
  235. TOutputProtobuf = TypeVar("TOutputProtobuf")
  236. @staticmethod
  237. async def send_protobuf(protobuf: Union[TOutputProtobuf, RPCError], writer: asyncio.StreamWriter, *, chunk_size: int = 2 ** 16) -> None:
  238. if isinstance(protobuf, RPCError):
  239. writer.write(P2P.ERROR_MARKER)
  240. else:
  241. writer.write(P2P.MESSAGE_MARKER)
  242. data = memoryview(protobuf.SerializeToString())
  243. writer.write(len(data).to_bytes(P2P.HEADER_LEN, P2P.BYTEORDER))
  244. for offset in range(0, len(data), chunk_size):
  245. P2P.send_raw_data(data[offset : offset + chunk_size], writer, drain=True)
  246. @staticmethod
  247. async def receive_protobuf(
  248. input_protobuf_type: Type[Message], reader: asyncio.StreamReader
  249. ) -> Tuple[Optional[TInputProtobuf], Optional[RPCError]]:
  250. msg_type = await reader.readexactly(1)
  251. if msg_type == P2P.MESSAGE_MARKER:
  252. protobuf = input_protobuf_type()
  253. header = await reader.readexactly(P2P.HEADER_LEN)
  254. content_length = int.from_bytes(header, P2P.BYTEORDER)
  255. data = bytearray(content_length)
  256. offset = 0
  257. while offset < len(data):
  258. chunk = await P2P.receive_raw_data(reader)
  259. buf[offset : offset + len(chunk)] = chunk
  260. offset += len(chunk)
  261. protobuf.ParseFromString(data)
  262. return protobuf, None
  263. elif msg_type == P2P.ERROR_MARKER:
  264. protobuf = RPCError()
  265. protobuf.ParseFromString(await P2P.receive_raw_data(reader))
  266. return None, protobuf
  267. else:
  268. raise TypeError("Invalid Protobuf message type")
  269. TInputStream = AsyncIterator[TInputProtobuf]
  270. TOutputStream = AsyncIterator[TOutputProtobuf]
  271. async def _add_protobuf_stream_handler(
  272. self,
  273. name: str,
  274. handler: Callable[[TInputStream, P2PContext], TOutputStream],
  275. input_protobuf_type: Type[Message],
  276. max_prefetch: int = 5,
  277. ) -> None:
  278. """
  279. :param max_prefetch: Maximum number of items to prefetch from the request stream.
  280. ``max_prefetch <= 0`` means unlimited.
  281. :note: Since the cancel messages are sent via the input stream,
  282. they will not be received while the prefetch buffer is full.
  283. """
  284. async def _handle_stream(
  285. stream_info: StreamInfo, reader: asyncio.StreamReader, writer: asyncio.StreamWriter
  286. ) -> None:
  287. context = P2PContext(
  288. handle_name=name,
  289. local_id=self.peer_id,
  290. remote_id=stream_info.peer_id,
  291. )
  292. requests = asyncio.Queue(max_prefetch)
  293. async def _read_stream() -> P2P.TInputStream:
  294. while True:
  295. request = await requests.get()
  296. if request is None:
  297. break
  298. yield request
  299. async def _process_stream() -> None:
  300. try:
  301. async for response in handler(_read_stream(), context):
  302. try:
  303. await P2P.send_protobuf(response, writer)
  304. except Exception:
  305. # The connection is unexpectedly closed by the caller or broken.
  306. # The loglevel is DEBUG since the actual error will be reported on the caller
  307. logger.debug("Exception while sending response:", exc_info=True)
  308. break
  309. except Exception as e:
  310. logger.warning("Handler failed with the exception:", exc_info=True)
  311. with suppress(Exception):
  312. # Sometimes `e` is a connection error, so it is okay if we fail to report `e` to the caller
  313. await P2P.send_protobuf(RPCError(message=str(e)), writer)
  314. with closing(writer):
  315. processing_task = asyncio.create_task(_process_stream())
  316. try:
  317. while True:
  318. receive_task = asyncio.create_task(P2P.receive_protobuf(input_protobuf_type, reader))
  319. await asyncio.wait({processing_task, receive_task}, return_when=asyncio.FIRST_COMPLETED)
  320. if processing_task.done():
  321. receive_task.cancel()
  322. return
  323. if receive_task.done():
  324. try:
  325. request, _ = await receive_task
  326. except asyncio.IncompleteReadError: # Connection is closed (the client cancelled or died)
  327. return
  328. await requests.put(request) # `request` is None for the end-of-stream message
  329. except Exception:
  330. logger.warning("Exception while receiving requests:", exc_info=True)
  331. finally:
  332. processing_task.cancel()
  333. await self.add_binary_stream_handler(name, _handle_stream)
  334. async def _iterate_protobuf_stream_handler(
  335. self, peer_id: PeerID, name: str, requests: TInputStream, output_protobuf_type: Type[Message]
  336. ) -> TOutputStream:
  337. _, reader, writer = await self.call_binary_stream_handler(peer_id, name)
  338. async def _write_to_stream() -> None:
  339. async for request in requests:
  340. await P2P.send_protobuf(request, writer)
  341. await P2P.send_protobuf(P2P.END_OF_STREAM, writer)
  342. with closing(writer):
  343. writing_task = asyncio.create_task(_write_to_stream())
  344. try:
  345. while True:
  346. try:
  347. response, err = await P2P.receive_protobuf(output_protobuf_type, reader)
  348. except asyncio.IncompleteReadError: # Connection is closed
  349. break
  350. if err is not None:
  351. raise P2PHandlerError(f"Failed to call handler `{name}` at {peer_id}: {err.message}")
  352. yield response
  353. await writing_task
  354. finally:
  355. writing_task.cancel()
  356. async def add_protobuf_handler(
  357. self,
  358. name: str,
  359. handler: Callable[
  360. [Union[TInputProtobuf, TInputStream], P2PContext], Union[Awaitable[TOutputProtobuf], TOutputStream]
  361. ],
  362. input_protobuf_type: Type[Message],
  363. *,
  364. stream_input: bool = False,
  365. stream_output: bool = False,
  366. ) -> None:
  367. """
  368. :param stream_input: If True, assume ``handler`` to take ``TInputStream``
  369. (not just ``TInputProtobuf``) as input.
  370. :param stream_output: If True, assume ``handler`` to return ``TOutputStream``
  371. (not ``Awaitable[TOutputProtobuf]``).
  372. """
  373. if not stream_input and not stream_output:
  374. await self._add_protobuf_unary_handler(name, handler, input_protobuf_type)
  375. return
  376. async def _stream_handler(requests: P2P.TInputStream, context: P2PContext) -> P2P.TOutputStream:
  377. input = requests if stream_input else await asingle(requests)
  378. output = handler(input, context)
  379. if isinstance(output, AsyncIterableABC):
  380. async for item in output:
  381. yield item
  382. else:
  383. yield await output
  384. await self._add_protobuf_stream_handler(name, _stream_handler, input_protobuf_type)
  385. async def _add_protobuf_unary_handler(
  386. self,
  387. handle_name: str,
  388. handler: Callable[[TInputProtobuf, P2PContext], Awaitable[TOutputProtobuf]],
  389. input_protobuf_type: Type[Message],
  390. ) -> None:
  391. """
  392. Register a request-response (unary) handler. Unary requests and responses
  393. are sent through persistent multiplexed connections to the daemon for the
  394. sake of reducing the number of open files.
  395. :param handle_name: name of the handler (protocol id)
  396. :param handler: function handling the unary requests
  397. :param input_protobuf_type: protobuf type of the request
  398. """
  399. async def _unary_handler(request: bytes, remote_id: PeerID) -> bytes:
  400. input_serialized = input_protobuf_type.FromString(request)
  401. context = P2PContext(
  402. handle_name=handle_name,
  403. local_id=self.peer_id,
  404. remote_id=remote_id,
  405. )
  406. response = await handler(input_serialized, context)
  407. return response.SerializeToString()
  408. await self._client.add_unary_handler(handle_name, _unary_handler)
  409. async def call_protobuf_handler(
  410. self,
  411. peer_id: PeerID,
  412. name: str,
  413. input: Union[TInputProtobuf, TInputStream],
  414. output_protobuf_type: Type[Message],
  415. ) -> Awaitable[TOutputProtobuf]:
  416. if not isinstance(input, AsyncIterableABC):
  417. return await self._call_unary_protobuf_handler(peer_id, name, input, output_protobuf_type)
  418. responses = self._iterate_protobuf_stream_handler(peer_id, name, input, output_protobuf_type)
  419. return await asingle(responses)
  420. async def _call_unary_protobuf_handler(
  421. self,
  422. peer_id: PeerID,
  423. handle_name: str,
  424. input: TInputProtobuf,
  425. output_protobuf_type: Type[Message],
  426. ) -> Awaitable[TOutputProtobuf]:
  427. serialized_input = input.SerializeToString()
  428. response = await self._client.call_unary_handler(peer_id, handle_name, serialized_input)
  429. return output_protobuf_type.FromString(response)
  430. def iterate_protobuf_handler(
  431. self,
  432. peer_id: PeerID,
  433. name: str,
  434. input: Union[TInputProtobuf, TInputStream],
  435. output_protobuf_type: Type[Message],
  436. ) -> TOutputStream:
  437. requests = input if isinstance(input, AsyncIterableABC) else as_aiter(input)
  438. return self._iterate_protobuf_stream_handler(peer_id, name, requests, output_protobuf_type)
  439. def _start_listening(self) -> None:
  440. async def listen() -> None:
  441. async with self._client.listen():
  442. await asyncio.Future() # Wait until this task will be cancelled in _terminate()
  443. self._listen_task = asyncio.create_task(listen())
  444. async def add_binary_stream_handler(self, name: str, handler: p2pclient.StreamHandler) -> None:
  445. if self._listen_task is None:
  446. self._start_listening()
  447. await self._client.stream_handler(name, handler)
  448. async def call_binary_stream_handler(
  449. self, peer_id: PeerID, handler_name: str
  450. ) -> Tuple[StreamInfo, asyncio.StreamReader, asyncio.StreamWriter]:
  451. return await self._client.stream_open(peer_id, (handler_name,))
  452. def __del__(self):
  453. self._terminate()
  454. @property
  455. def is_alive(self) -> bool:
  456. return self._alive
  457. async def shutdown(self) -> None:
  458. self._terminate()
  459. if self._child is not None:
  460. await self._child.wait()
  461. def _terminate(self) -> None:
  462. if self._client is not None:
  463. self._client.close()
  464. if self._listen_task is not None:
  465. self._listen_task.cancel()
  466. if self._reader_task is not None:
  467. self._reader_task.cancel()
  468. self._alive = False
  469. if self._child is not None and self._child.returncode is None:
  470. self._child.terminate()
  471. logger.debug(f"Terminated p2pd with id = {self.peer_id}")
  472. with suppress(FileNotFoundError):
  473. os.remove(self._daemon_listen_maddr["unix"])
  474. with suppress(FileNotFoundError):
  475. os.remove(self._client_listen_maddr["unix"])
  476. @staticmethod
  477. def _make_process_args(*args, **kwargs) -> List[str]:
  478. proc_args = []
  479. proc_args.extend(str(entry) for entry in args)
  480. proc_args.extend(
  481. f"-{key}={P2P._convert_process_arg_type(value)}" if value is not None else f"-{key}"
  482. for key, value in kwargs.items()
  483. )
  484. return proc_args
  485. @staticmethod
  486. def _convert_process_arg_type(val: Any) -> Any:
  487. if isinstance(val, bool):
  488. return int(val)
  489. return val
  490. @staticmethod
  491. def _maddrs_to_str(maddrs: List[Multiaddr]) -> str:
  492. return ",".join(str(addr) for addr in maddrs)
  493. async def _read_outputs(self, ready: asyncio.Future) -> None:
  494. last_line = None
  495. while True:
  496. line = await self._child.stdout.readline()
  497. if not line: # Stream closed
  498. break
  499. last_line = line.rstrip().decode(errors="ignore")
  500. self._log_p2pd_message(last_line)
  501. if last_line.startswith("Peer ID:"):
  502. ready.set_result(None)
  503. if not ready.done():
  504. ready.set_exception(P2PDaemonError(f"Daemon failed to start: {last_line}"))
  505. @staticmethod
  506. def _log_p2pd_message(line: str) -> None:
  507. if '"logger"' not in line: # User-friendly info from p2pd stdout
  508. logger.debug(line, extra={"caller": "p2pd"})
  509. return
  510. try:
  511. record = json.loads(line)
  512. caller = record["caller"]
  513. level = golog_level_to_python(record["level"])
  514. if level <= logging.WARNING:
  515. # Many Go loggers are excessively verbose (e.g. show warnings for unreachable peers),
  516. # so we downgrade INFO and WARNING messages to DEBUG.
  517. # The Go verbosity can still be controlled via the GOLOG_LOG_LEVEL env variable.
  518. # Details: https://github.com/ipfs/go-log#golog_log_level
  519. level = logging.DEBUG
  520. message = record["msg"]
  521. if "error" in record:
  522. message += f": {record['error']}"
  523. logger.log(
  524. level,
  525. message,
  526. extra={
  527. "origin_created": datetime.strptime(record["ts"], "%Y-%m-%dT%H:%M:%S.%f%z").timestamp(),
  528. "caller": caller,
  529. },
  530. )
  531. except Exception:
  532. # Parsing errors are unlikely, but we don't want to lose these messages anyway
  533. logger.warning(line, extra={"caller": "p2pd"})
  534. logger.exception("Failed to parse go-log message:")