dht.py 14 KB

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