dht.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. from __future__ import annotations
  2. import asyncio
  3. import multiprocessing as mp
  4. import os
  5. import signal
  6. from functools import partial
  7. from typing import Awaitable, Callable, Iterable, List, Optional, Sequence, TypeVar, Union
  8. from multiaddr import Multiaddr
  9. from hivemind.dht.node import DEFAULT_NUM_WORKERS, DHTNode
  10. from hivemind.dht.routing import DHTKey, DHTValue, Subkey
  11. from hivemind.dht.validation import CompositeValidator, RecordValidatorBase
  12. from hivemind.p2p import P2P, PeerID
  13. from hivemind.utils import MPFuture, get_logger, switch_to_uvloop
  14. from hivemind.utils.timed_storage import DHTExpiration, ValueWithExpiration
  15. logger = get_logger(__name__)
  16. ReturnType = TypeVar("ReturnType")
  17. class DHT(mp.Process):
  18. """
  19. A high-level interface to a hivemind DHT that runs a single DHT node in a background process.
  20. * hivemind servers periodically announce their experts via declare_experts (dht_handler.py)
  21. * trainers find most suitable experts via RemoteMixtureOfExperts (beam_search.py)
  22. :param initial_peers: multiaddrs of one or more active DHT peers (if you want to join an existing DHT)
  23. :param start: if True, automatically starts the background process on creation. Otherwise await manual start
  24. :param daemon: if True, the background process is marked as daemon and automatically terminated after main process
  25. :param num_workers: declare_experts and get_experts will use up to this many parallel workers
  26. (but no more than one per key)
  27. :param expiration: experts declared from this node expire after this many seconds (default = 5 minutes)
  28. :param record_validators: instances of RecordValidatorBase used for signing and validating stored records.
  29. The validators will be combined using the CompositeValidator class. It merges them when possible
  30. (according to their `.merge_with()` policies) and orders them according to the `.priority` properties.
  31. :param shutdown_timeout: when calling .shutdown, wait for up to this many seconds before terminating
  32. :param await_ready: if True, the constructor waits until the DHT process is ready to process incoming requests
  33. :param kwargs: any other params will be forwarded to DHTNode and hivemind.p2p.P2P upon creation
  34. """
  35. _node: DHTNode
  36. def __init__(
  37. self,
  38. initial_peers: Optional[Sequence[Union[Multiaddr, str]]] = None,
  39. *,
  40. start: bool,
  41. p2p: Optional[P2P] = None,
  42. daemon: bool = True,
  43. num_workers: int = DEFAULT_NUM_WORKERS,
  44. record_validators: Iterable[RecordValidatorBase] = (),
  45. shutdown_timeout: float = 3,
  46. await_ready: bool = True,
  47. **kwargs,
  48. ):
  49. self._parent_pid = os.getpid()
  50. self._origin_pid = os.getpid()
  51. super().__init__()
  52. if not (
  53. initial_peers is None
  54. or (
  55. isinstance(initial_peers, Sequence)
  56. and all(isinstance(item, (Multiaddr, str)) for item in initial_peers)
  57. )
  58. ):
  59. raise TypeError("initial_peers should be of type Optional[Sequence[Union[Multiaddr, str]]]")
  60. self.initial_peers = initial_peers
  61. self.kwargs = kwargs
  62. self.num_workers = num_workers
  63. self._record_validator = CompositeValidator(record_validators)
  64. self._inner_pipe, self._outer_pipe = mp.Pipe(duplex=True)
  65. self.shutdown_timeout = shutdown_timeout
  66. self._ready = MPFuture()
  67. self.daemon = daemon
  68. # These values will be fetched from the child process when requested
  69. self._peer_id = None
  70. self._client_mode = None
  71. self._p2p_replica = None
  72. self._daemon_listen_maddr = p2p.daemon_listen_maddr if p2p is not None else None
  73. if start:
  74. self.run_in_background(await_ready=await_ready)
  75. def run(self) -> None:
  76. """Serve DHT forever. This function will not return until DHT node is shut down"""
  77. loop = switch_to_uvloop()
  78. pipe_semaphore = asyncio.Semaphore(value=0)
  79. loop.add_reader(self._inner_pipe.fileno(), pipe_semaphore.release)
  80. async def _run():
  81. # Set SIG_IGN handler to SIGINT
  82. signal.signal(signal.SIGINT, signal.SIG_IGN)
  83. try:
  84. if self._daemon_listen_maddr is not None:
  85. replicated_p2p = await P2P.replicate(self._daemon_listen_maddr)
  86. else:
  87. replicated_p2p = None
  88. self._node = await DHTNode.create(
  89. initial_peers=self.initial_peers,
  90. num_workers=self.num_workers,
  91. record_validator=self._record_validator,
  92. p2p=replicated_p2p,
  93. **self.kwargs,
  94. )
  95. except Exception as e:
  96. # Loglevel is DEBUG since normally the exception is propagated to the caller
  97. logger.debug(e, exc_info=True)
  98. self._ready.set_exception(e)
  99. return
  100. self._ready.set_result(None)
  101. while True:
  102. await pipe_semaphore.acquire()
  103. try:
  104. method, args, kwargs = self._inner_pipe.recv()
  105. except (OSError, ConnectionError, RuntimeError) as e:
  106. logger.exception(e)
  107. break
  108. task = asyncio.create_task(getattr(self, method)(*args, **kwargs))
  109. if method == "_shutdown":
  110. await task
  111. break
  112. loop.run_until_complete(_run())
  113. def run_in_background(self, await_ready: bool = True, timeout: Optional[float] = None) -> None:
  114. """
  115. Starts DHT in a background process. if await_ready, this method will wait until background dht
  116. is ready to process incoming requests or for :timeout: seconds max.
  117. """
  118. self.start()
  119. if await_ready:
  120. self.wait_until_ready(timeout)
  121. def wait_until_ready(self, timeout: Optional[float] = None) -> None:
  122. self._ready.result(timeout=timeout)
  123. def shutdown(self) -> None:
  124. """Shut down a running dht process"""
  125. if self.is_alive():
  126. self._outer_pipe.send(("_shutdown", [], {}))
  127. self.join(self.shutdown_timeout)
  128. if self.is_alive():
  129. logger.warning("DHT did not shut down within the grace period; terminating it the hard way")
  130. self.terminate()
  131. async def _shutdown(self):
  132. await self._node.shutdown()
  133. def get(
  134. self, key: DHTKey, latest: bool = False, return_future: bool = False, **kwargs
  135. ) -> Union[Optional[ValueWithExpiration[DHTValue]], MPFuture]:
  136. """
  137. Search for a key across DHT and return either first or latest entry (if found).
  138. :param key: same key as in node.store(...)
  139. :param latest: if True, finds the latest value, otherwise finds any non-expired value (which is much faster)
  140. :param return_future: if False (default), return when finished. Otherwise return MPFuture and run in background.
  141. :param kwargs: parameters forwarded to DHTNode.get_many_by_id
  142. :returns: (value, expiration time); if value was not found, returns None
  143. """
  144. assert os.getpid() != self.pid, "calling *external* DHT interface from inside DHT will result in a deadlock"
  145. future = MPFuture()
  146. self._outer_pipe.send(("_get", [], dict(key=key, latest=latest, future=future, **kwargs)))
  147. return future if return_future else future.result()
  148. async def _get(self, key: DHTKey, latest: bool, future: MPFuture, **kwargs):
  149. try:
  150. result = await self._node.get(key, latest=latest, **kwargs)
  151. if not future.done():
  152. future.set_result(result)
  153. except BaseException as e:
  154. if not future.done():
  155. future.set_exception(e)
  156. raise
  157. def store(
  158. self,
  159. key: DHTKey,
  160. value: DHTValue,
  161. expiration_time: DHTExpiration,
  162. subkey: Optional[Subkey] = None,
  163. return_future: bool = False,
  164. **kwargs,
  165. ) -> Union[bool, MPFuture]:
  166. """
  167. Find num_replicas best nodes to store (key, value) and store it there until expiration time.
  168. :param key: msgpack-serializable key to be associated with value until expiration.
  169. :param value: msgpack-serializable value to be stored under a given key until expiration.
  170. :param expiration_time: absolute time when the entry should expire, based on hivemind.get_dht_time()
  171. :param subkey: if specified, add a value under that subkey instead of overwriting key (see DHTNode.store_many)
  172. :param return_future: if False (default), return when finished. Otherwise return MPFuture and run in background.
  173. :returns: True if store succeeds, False if it fails (due to no response or newer value)
  174. """
  175. assert os.getpid() != self.pid, "calling *external* DHT interface from inside DHT will result in a deadlock"
  176. future = MPFuture()
  177. self._outer_pipe.send(
  178. (
  179. "_store",
  180. [],
  181. dict(key=key, value=value, expiration_time=expiration_time, subkey=subkey, future=future, **kwargs),
  182. )
  183. )
  184. return future if return_future else future.result()
  185. async def _store(
  186. self,
  187. key: DHTKey,
  188. value: DHTValue,
  189. expiration_time: DHTExpiration,
  190. subkey: Optional[Subkey],
  191. future: MPFuture,
  192. **kwargs,
  193. ):
  194. try:
  195. result = await self._node.store(key, value, expiration_time, subkey=subkey, **kwargs)
  196. if not future.done():
  197. future.set_result(result)
  198. except BaseException as e:
  199. if not future.done():
  200. future.set_exception(e)
  201. raise
  202. def run_coroutine(
  203. self, coro: Callable[[DHT, DHTNode], Awaitable[ReturnType]], return_future: bool = False
  204. ) -> Union[ReturnType, MPFuture[ReturnType]]:
  205. """
  206. Execute an asynchronous function on a DHT participant and return results. This is meant as an interface
  207. for running custom functions DHT for special cases (e.g. declare experts, beam search)
  208. :param coro: async function to be executed. Receives 2 arguments: this DHT daemon and a running DHTNode
  209. :param return_future: if False (default), return when finished. Otherwise return MPFuture and run in background.
  210. :returns: coroutine outputs or MPFuture for these outputs
  211. :note: the coroutine will be executed inside the DHT process. As such, any changes to global variables or
  212. DHT fields made by this coroutine will not be accessible from the host process.
  213. :note: all time-consuming operations in coro should be asynchronous (e.g. asyncio.sleep instead of time.sleep)
  214. or use asyncio.get_event_loop().run_in_executor(...) to prevent coroutine from blocking background DHT tasks
  215. :note: when run_coroutine is called with return_future=False, MPFuture can be cancelled to interrupt the task.
  216. """
  217. assert os.getpid() != self.pid, "calling *external* DHT interface from inside DHT will result in a deadlock"
  218. future = MPFuture()
  219. self._outer_pipe.send(("_run_coroutine", [], dict(coro=coro, future=future)))
  220. return future if return_future else future.result()
  221. async def _run_coroutine(
  222. self, coro: Callable[[DHT, DHTNode], Awaitable[ReturnType]], future: MPFuture[ReturnType]
  223. ):
  224. try:
  225. future.set_result(await coro(self, self._node))
  226. except BaseException as e:
  227. logger.exception("Caught an exception when running a coroutine:")
  228. future.set_exception(e)
  229. def add_validators(self, record_validators: Iterable[RecordValidatorBase]) -> None:
  230. if not self._ready.done():
  231. raise RuntimeError(
  232. "Can't append new validators before the DHT process has started. "
  233. "Consider adding them to the initial list via DHT.__init__(record_validators=...)"
  234. )
  235. self.run_coroutine(partial(DHT._add_validators, record_validators=record_validators))
  236. @staticmethod
  237. async def _add_validators(_dht: DHT, node: DHTNode, record_validators: Iterable[RecordValidatorBase]) -> None:
  238. node.protocol.record_validator.extend(record_validators)
  239. @property
  240. def peer_id(self) -> PeerID:
  241. if self._peer_id is None:
  242. if os.getpid() == self.pid:
  243. self._peer_id = self._node.peer_id
  244. else:
  245. # note: we cannot run_coroutine from the same pid because it would deadlock the event loop
  246. self._peer_id = self.run_coroutine(DHT._get_peer_id)
  247. return self._peer_id
  248. @staticmethod
  249. async def _get_peer_id(_dht: DHT, node: DHTNode) -> PeerID:
  250. return node.peer_id
  251. @property
  252. def client_mode(self) -> bool:
  253. if self._client_mode is None:
  254. self._client_mode = self.run_coroutine(DHT._get_client_mode)
  255. return self._client_mode
  256. @staticmethod
  257. async def _get_client_mode(_dht: DHT, node: DHTNode) -> bool:
  258. return node.protocol.client_mode
  259. def get_visible_maddrs(self, latest: bool = False) -> List[Multiaddr]:
  260. """
  261. Get multiaddrs of the current DHT node that should be accessible by other peers.
  262. :param latest: ask the P2P daemon to refresh the visible multiaddrs
  263. """
  264. return self.run_coroutine(partial(DHT._get_visible_maddrs, latest=latest))
  265. @staticmethod
  266. async def _get_visible_maddrs(_dht: DHT, node: DHTNode, latest: bool = False) -> List[Multiaddr]:
  267. return await node.get_visible_maddrs(latest=latest)
  268. async def replicate_p2p(self) -> P2P:
  269. """
  270. Get a replica of a P2P instance used in the DHT process internally.
  271. The replica uses the same P2P daemon as the DHT and only works while DHT is alive.
  272. """
  273. if self._p2p_replica is None or self._origin_pid != os.getpid():
  274. self._origin_pid = os.getpid()
  275. daemon_listen_maddr = self.run_coroutine(DHT._get_p2p_daemon_listen_maddr)
  276. self._p2p_replica = await P2P.replicate(daemon_listen_maddr)
  277. return self._p2p_replica
  278. @staticmethod
  279. async def _get_p2p_daemon_listen_maddr(_dht: DHT, node: DHTNode) -> Multiaddr:
  280. return node.p2p.daemon_listen_maddr
  281. def __del__(self):
  282. if self._parent_pid == os.getpid() and self.is_alive():
  283. self.shutdown()