p2p_daemon.py 26 KB

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