api.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  1. """This file defines the interface between the ray client worker
  2. and the overall ray module API.
  3. """
  4. import json
  5. import logging
  6. from concurrent.futures import Future
  7. from typing import TYPE_CHECKING, Any, Callable, List, Optional, Union
  8. from ray._common import ray_option_utils
  9. from ray.util.client.runtime_context import _ClientWorkerPropertyAPI
  10. if TYPE_CHECKING:
  11. from ray.actor import ActorClass
  12. from ray.core.generated.ray_client_pb2 import DataResponse
  13. from ray.remote_function import RemoteFunction
  14. from ray.util.client.common import ClientActorHandle, ClientObjectRef, ClientStub
  15. logger = logging.getLogger(__name__)
  16. def _as_bytes(value):
  17. if isinstance(value, str):
  18. return value.encode("utf-8")
  19. return value
  20. class _ClientAPI:
  21. """The Client-side methods corresponding to the ray API. Delegates
  22. to the Client Worker that contains the connection to the ClientServer.
  23. """
  24. def __init__(self, worker=None):
  25. self.worker = worker
  26. def get(self, vals, *, timeout=None):
  27. """get is the hook stub passed on to replace `ray.get`
  28. Args:
  29. vals: [Client]ObjectRef or list of these refs to retrieve.
  30. timeout: Optional timeout in milliseconds
  31. """
  32. return self.worker.get(vals, timeout=timeout)
  33. def put(self, *args, **kwargs):
  34. """put is the hook stub passed on to replace `ray.put`
  35. Args:
  36. val: The value to `put`.
  37. args: opaque arguments
  38. kwargs: opaque keyword arguments
  39. """
  40. return self.worker.put(*args, **kwargs)
  41. def wait(self, *args, **kwargs):
  42. """wait is the hook stub passed on to replace `ray.wait`
  43. Args:
  44. args: opaque arguments
  45. kwargs: opaque keyword arguments
  46. """
  47. return self.worker.wait(*args, **kwargs)
  48. def remote(self, *args, **kwargs):
  49. """remote is the hook stub passed on to replace `ray.remote`.
  50. This sets up remote functions or actors, as the decorator,
  51. but does not execute them.
  52. Args:
  53. args: opaque arguments
  54. kwargs: opaque keyword arguments
  55. """
  56. # Delayed import to avoid a cyclic import
  57. from ray.util.client.common import remote_decorator
  58. if len(args) == 1 and len(kwargs) == 0 and callable(args[0]):
  59. # This is the case where the decorator is just @ray.remote.
  60. return remote_decorator(options=None)(args[0])
  61. assert (
  62. len(args) == 0 and len(kwargs) > 0
  63. ), ray_option_utils.remote_args_error_string
  64. return remote_decorator(options=kwargs)
  65. # TODO(mwtian): consider adding _internal_ prefix to call_remote /
  66. # call_release / call_retain.
  67. def call_remote(self, instance: "ClientStub", *args, **kwargs) -> List[Future]:
  68. """call_remote is called by stub objects to execute them remotely.
  69. This is used by stub objects in situations where they're called
  70. with .remote, eg, `f.remote()` or `actor_cls.remote()`.
  71. This allows the client stub objects to delegate execution to be
  72. implemented in the most effective way whether it's in the client,
  73. clientserver, or raylet worker.
  74. Args:
  75. instance: The Client-side stub reference to a remote object
  76. args: opaque arguments
  77. kwargs: opaque keyword arguments
  78. """
  79. return self.worker.call_remote(instance, *args, **kwargs)
  80. def call_release(self, id: bytes) -> None:
  81. """Attempts to release an object reference.
  82. When client references are destructed, they release their reference,
  83. which can opportunistically send a notification through the datachannel
  84. to release the reference being held for that object on the server.
  85. Args:
  86. id: The id of the reference to release on the server side.
  87. """
  88. return self.worker.call_release(id)
  89. def call_retain(self, id: bytes) -> None:
  90. """Attempts to retain a client object reference.
  91. Increments the reference count on the client side, to prevent
  92. the client worker from attempting to release the server reference.
  93. Args:
  94. id: The id of the reference to retain on the client side.
  95. """
  96. return self.worker.call_retain(id)
  97. def close(self) -> None:
  98. """close cleans up an API connection by closing any channels or
  99. shutting down any servers gracefully.
  100. """
  101. return self.worker.close()
  102. def get_actor(
  103. self, name: str, namespace: Optional[str] = None
  104. ) -> "ClientActorHandle":
  105. """Returns a handle to an actor by name.
  106. Args:
  107. name: The name passed to this actor by
  108. Actor.options(name="name").remote()
  109. """
  110. return self.worker.get_actor(name, namespace)
  111. def list_named_actors(self, all_namespaces: bool = False) -> List[str]:
  112. """List all named actors in the system.
  113. Actors must have been created with Actor.options(name="name").remote().
  114. This works for both detached & non-detached actors.
  115. By default, only actors in the current namespace will be returned
  116. and the returned entries will simply be their name.
  117. If `all_namespaces` is set to True, all actors in the cluster will be
  118. returned regardless of namespace, and the retunred entries will be of
  119. the form '<namespace>/<name>'.
  120. """
  121. return self.worker.list_named_actors(all_namespaces)
  122. def kill(self, actor: "ClientActorHandle", *, no_restart=True):
  123. """kill forcibly stops an actor running in the cluster
  124. Args:
  125. no_restart: Whether this actor should be restarted if it's a
  126. restartable actor.
  127. """
  128. return self.worker.terminate_actor(actor, no_restart)
  129. def cancel(self, obj: "ClientObjectRef", *, force=False, recursive=True):
  130. """Cancels a task on the cluster.
  131. If the specified task is pending execution, it will not be executed. If
  132. the task is currently executing, the behavior depends on the ``force``
  133. flag, as per `ray.cancel()`
  134. Only non-actor tasks can be canceled. Canceled tasks will not be
  135. retried (max_retries will not be respected).
  136. Args:
  137. object_ref: ObjectRef returned by the task
  138. that should be canceled.
  139. force: Whether to force-kill a running task by killing
  140. the worker that is running the task.
  141. recursive: Whether to try to cancel tasks submitted by
  142. the task specified.
  143. """
  144. return self.worker.terminate_task(obj, force, recursive)
  145. # Various metadata methods for the client that are defined in the protocol.
  146. def is_initialized(self) -> bool:
  147. """True if our client is connected, and if the server is initialized.
  148. Returns:
  149. A boolean determining if the client is connected and
  150. server initialized.
  151. """
  152. return self.worker.is_initialized()
  153. def nodes(self):
  154. """Get a list of the nodes in the cluster (for debugging only).
  155. Returns:
  156. Information about the Ray clients in the cluster.
  157. """
  158. # This should be imported here, otherwise, it will error doc build.
  159. import ray.core.generated.ray_client_pb2 as ray_client_pb2
  160. return self.worker.get_cluster_info(ray_client_pb2.ClusterInfoType.NODES)
  161. def method(self, *args, **kwargs):
  162. """Annotate an actor method
  163. Args:
  164. num_returns: The number of object refs that should be returned by
  165. invocations of this actor method.
  166. """
  167. # NOTE: So this follows the same logic as in ray/actor.py::method()
  168. # The reason to duplicate it here is to simplify the client mode
  169. # redirection logic. As the annotated method gets pickled and sent to
  170. # the server from the client it carries this private variable, it
  171. # activates the same logic on the server side; so there's no need to
  172. # pass anything else. It's inside the class definition that becomes an
  173. # actor. Similar annotations would follow the same way.
  174. valid_kwargs = ["num_returns", "concurrency_group"]
  175. error_string = (
  176. "The @ray.method decorator must be applied using at least one of "
  177. f"the arguments in the list {valid_kwargs}, for example "
  178. "'@ray.method(num_returns=2)'."
  179. )
  180. assert len(args) == 0 and len(kwargs) > 0, error_string
  181. for key in kwargs:
  182. key_error_string = (
  183. f'Unexpected keyword argument to @ray.method: "{key}". The '
  184. f"supported keyword arguments are {valid_kwargs}"
  185. )
  186. assert key in valid_kwargs, key_error_string
  187. def annotate_method(method):
  188. if "num_returns" in kwargs:
  189. method.__ray_num_returns__ = kwargs["num_returns"]
  190. if "concurrency_group" in kwargs:
  191. method.__ray_concurrency_group__ = kwargs["concurrency_group"]
  192. return method
  193. return annotate_method
  194. def cluster_resources(self):
  195. """Get the current total cluster resources.
  196. Note that this information can grow stale as nodes are added to or
  197. removed from the cluster.
  198. Returns:
  199. A dictionary mapping resource name to the total quantity of that
  200. resource in the cluster.
  201. """
  202. # This should be imported here, otherwise, it will error doc build.
  203. import ray.core.generated.ray_client_pb2 as ray_client_pb2
  204. return self.worker.get_cluster_info(
  205. ray_client_pb2.ClusterInfoType.CLUSTER_RESOURCES
  206. )
  207. def available_resources(self):
  208. """Get the current available cluster resources.
  209. This is different from `cluster_resources` in that this will return
  210. idle (available) resources rather than total resources.
  211. Note that this information can grow stale as tasks start and finish.
  212. Returns:
  213. A dictionary mapping resource name to the total quantity of that
  214. resource in the cluster.
  215. """
  216. # This should be imported here, otherwise, it will error doc build.
  217. import ray.core.generated.ray_client_pb2 as ray_client_pb2
  218. return self.worker.get_cluster_info(
  219. ray_client_pb2.ClusterInfoType.AVAILABLE_RESOURCES
  220. )
  221. def get_runtime_context(self):
  222. """Return a Ray RuntimeContext describing the state on the server
  223. Returns:
  224. A RuntimeContext wrapping a client making get_cluster_info calls.
  225. """
  226. return _ClientWorkerPropertyAPI(self.worker).build_runtime_context()
  227. # Client process isn't assigned any GPUs.
  228. def get_gpu_ids(self) -> list:
  229. return []
  230. def timeline(self, filename: Optional[str] = None) -> Optional[List[Any]]:
  231. logger.warning(
  232. "Timeline will include events from other clients using this server."
  233. )
  234. # This should be imported here, otherwise, it will error doc build.
  235. import ray.core.generated.ray_client_pb2 as ray_client_pb2
  236. all_events = self.worker.get_cluster_info(
  237. ray_client_pb2.ClusterInfoType.TIMELINE
  238. )
  239. if filename is not None:
  240. with open(filename, "w") as outfile:
  241. json.dump(all_events, outfile)
  242. else:
  243. return all_events
  244. def _internal_kv_initialized(self) -> bool:
  245. """Hook for internal_kv._internal_kv_initialized."""
  246. # NOTE(edoakes): the kv is always initialized because we initialize it
  247. # manually in the proxier with a GCS client if Ray hasn't been
  248. # initialized yet.
  249. return True
  250. def _internal_kv_exists(
  251. self, key: Union[str, bytes], *, namespace: Optional[Union[str, bytes]] = None
  252. ) -> bool:
  253. """Hook for internal_kv._internal_kv_exists."""
  254. return self.worker.internal_kv_exists(
  255. _as_bytes(key), namespace=_as_bytes(namespace)
  256. )
  257. def _internal_kv_get(
  258. self, key: Union[str, bytes], *, namespace: Optional[Union[str, bytes]] = None
  259. ) -> bytes:
  260. """Hook for internal_kv._internal_kv_get."""
  261. return self.worker.internal_kv_get(
  262. _as_bytes(key), namespace=_as_bytes(namespace)
  263. )
  264. def _internal_kv_put(
  265. self,
  266. key: Union[str, bytes],
  267. value: Union[str, bytes],
  268. overwrite: bool = True,
  269. *,
  270. namespace: Optional[Union[str, bytes]] = None,
  271. ) -> bool:
  272. """Hook for internal_kv._internal_kv_put."""
  273. return self.worker.internal_kv_put(
  274. _as_bytes(key), _as_bytes(value), overwrite, namespace=_as_bytes(namespace)
  275. )
  276. def _internal_kv_del(
  277. self,
  278. key: Union[str, bytes],
  279. *,
  280. del_by_prefix: bool = False,
  281. namespace: Optional[Union[str, bytes]] = None,
  282. ) -> int:
  283. """Hook for internal_kv._internal_kv_del."""
  284. return self.worker.internal_kv_del(
  285. _as_bytes(key), del_by_prefix=del_by_prefix, namespace=_as_bytes(namespace)
  286. )
  287. def _internal_kv_list(
  288. self,
  289. prefix: Union[str, bytes],
  290. *,
  291. namespace: Optional[Union[str, bytes]] = None,
  292. ) -> List[bytes]:
  293. """Hook for internal_kv._internal_kv_list."""
  294. return self.worker.internal_kv_list(
  295. _as_bytes(prefix), namespace=_as_bytes(namespace)
  296. )
  297. def _pin_runtime_env_uri(self, uri: str, expiration_s: int) -> None:
  298. """Hook for internal_kv._pin_runtime_env_uri."""
  299. return self.worker.pin_runtime_env_uri(uri, expiration_s)
  300. def _convert_actor(self, actor: "ActorClass") -> str:
  301. """Register a ClientActorClass for the ActorClass and return a UUID"""
  302. return self.worker._convert_actor(actor)
  303. def _convert_function(self, func: "RemoteFunction") -> str:
  304. """Register a ClientRemoteFunc for the ActorClass and return a UUID"""
  305. return self.worker._convert_function(func)
  306. def _get_converted(self, key: str) -> "ClientStub":
  307. """Given a UUID, return the converted object"""
  308. return self.worker._get_converted(key)
  309. def _converted_key_exists(self, key: str) -> bool:
  310. """Check if a key UUID is present in the store of converted objects."""
  311. return self.worker._converted_key_exists(key)
  312. def __getattr__(self, key: str):
  313. if not key.startswith("_"):
  314. raise NotImplementedError(
  315. "Not available in Ray client: `ray.{}`. This method is only "
  316. "available within Ray remote functions and is not yet "
  317. "implemented in the client API.".format(key)
  318. )
  319. return self.__getattribute__(key)
  320. def _register_callback(
  321. self, ref: "ClientObjectRef", callback: Callable[["DataResponse"], None]
  322. ) -> None:
  323. self.worker.register_callback(ref, callback)
  324. def _get_dashboard_url(self) -> str:
  325. import ray.core.generated.ray_client_pb2 as ray_client_pb2
  326. return self.worker.get_cluster_info(
  327. ray_client_pb2.ClusterInfoType.DASHBOARD_URL
  328. ).get("dashboard_url", "")