p2p_daemon.py 25 KB

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