ZTWHHH commited on
Commit
0d284ed
·
verified ·
1 Parent(s): d757134

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. vllm/lib/python3.10/site-packages/ray/dashboard/__init__.py +0 -0
  2. vllm/lib/python3.10/site-packages/ray/dashboard/agent.py +456 -0
  3. vllm/lib/python3.10/site-packages/ray/dashboard/consts.py +90 -0
  4. vllm/lib/python3.10/site-packages/ray/dashboard/dashboard.py +275 -0
  5. vllm/lib/python3.10/site-packages/ray/dashboard/dashboard_metrics.py +123 -0
  6. vllm/lib/python3.10/site-packages/ray/dashboard/datacenter.py +288 -0
  7. vllm/lib/python3.10/site-packages/ray/dashboard/head.py +344 -0
  8. vllm/lib/python3.10/site-packages/ray/dashboard/http_server_agent.py +83 -0
  9. vllm/lib/python3.10/site-packages/ray/dashboard/http_server_head.py +289 -0
  10. vllm/lib/python3.10/site-packages/ray/dashboard/k8s_utils.py +111 -0
  11. vllm/lib/python3.10/site-packages/ray/dashboard/memory_utils.py +524 -0
  12. vllm/lib/python3.10/site-packages/ray/dashboard/modules/__init__.py +0 -0
  13. vllm/lib/python3.10/site-packages/ray/dashboard/modules/actor/__init__.py +0 -0
  14. vllm/lib/python3.10/site-packages/ray/dashboard/modules/actor/__pycache__/__init__.cpython-310.pyc +0 -0
  15. vllm/lib/python3.10/site-packages/ray/dashboard/modules/actor/__pycache__/actor_consts.cpython-310.pyc +0 -0
  16. vllm/lib/python3.10/site-packages/ray/dashboard/modules/actor/__pycache__/actor_head.cpython-310.pyc +0 -0
  17. vllm/lib/python3.10/site-packages/ray/dashboard/modules/actor/actor_consts.py +5 -0
  18. vllm/lib/python3.10/site-packages/ray/dashboard/modules/actor/actor_head.py +356 -0
  19. vllm/lib/python3.10/site-packages/ray/dashboard/modules/dashboard_sdk.py +418 -0
  20. vllm/lib/python3.10/site-packages/ray/dashboard/modules/healthz/__pycache__/__init__.cpython-310.pyc +0 -0
  21. vllm/lib/python3.10/site-packages/ray/dashboard/modules/healthz/__pycache__/healthz_agent.cpython-310.pyc +0 -0
  22. vllm/lib/python3.10/site-packages/ray/dashboard/modules/healthz/__pycache__/healthz_head.cpython-310.pyc +0 -0
  23. vllm/lib/python3.10/site-packages/ray/dashboard/modules/healthz/healthz_agent.py +54 -0
  24. vllm/lib/python3.10/site-packages/ray/dashboard/modules/healthz/healthz_head.py +41 -0
  25. vllm/lib/python3.10/site-packages/ray/dashboard/modules/healthz/utils.py +24 -0
  26. vllm/lib/python3.10/site-packages/ray/dashboard/modules/job/__init__.py +0 -0
  27. vllm/lib/python3.10/site-packages/ray/dashboard/modules/node/__init__.py +0 -0
  28. vllm/lib/python3.10/site-packages/ray/dashboard/modules/reporter/__init__.py +0 -0
  29. vllm/lib/python3.10/site-packages/ray/dashboard/modules/reporter/__pycache__/profile_manager.cpython-310.pyc +0 -0
  30. vllm/lib/python3.10/site-packages/ray/dashboard/modules/reporter/__pycache__/reporter_agent.cpython-310.pyc +0 -0
  31. vllm/lib/python3.10/site-packages/ray/dashboard/modules/reporter/__pycache__/reporter_consts.cpython-310.pyc +0 -0
  32. vllm/lib/python3.10/site-packages/ray/dashboard/modules/reporter/__pycache__/reporter_head.cpython-310.pyc +0 -0
  33. vllm/lib/python3.10/site-packages/ray/dashboard/modules/reporter/reporter_agent.py +1305 -0
  34. vllm/lib/python3.10/site-packages/ray/dashboard/modules/reporter/reporter_consts.py +7 -0
  35. vllm/lib/python3.10/site-packages/ray/dashboard/modules/reporter/reporter_head.py +669 -0
  36. vllm/lib/python3.10/site-packages/ray/dashboard/modules/serve/__init__.py +0 -0
  37. vllm/lib/python3.10/site-packages/ray/dashboard/modules/serve/__pycache__/__init__.cpython-310.pyc +0 -0
  38. vllm/lib/python3.10/site-packages/ray/dashboard/modules/serve/__pycache__/sdk.cpython-310.pyc +0 -0
  39. vllm/lib/python3.10/site-packages/ray/dashboard/modules/serve/__pycache__/serve_agent.cpython-310.pyc +0 -0
  40. vllm/lib/python3.10/site-packages/ray/dashboard/modules/serve/__pycache__/serve_head.cpython-310.pyc +0 -0
  41. vllm/lib/python3.10/site-packages/ray/dashboard/modules/serve/__pycache__/serve_rest_api_impl.cpython-310.pyc +0 -0
  42. vllm/lib/python3.10/site-packages/ray/dashboard/modules/serve/sdk.py +85 -0
  43. vllm/lib/python3.10/site-packages/ray/dashboard/modules/serve/serve_agent.py +11 -0
  44. vllm/lib/python3.10/site-packages/ray/dashboard/modules/serve/serve_head.py +10 -0
  45. vllm/lib/python3.10/site-packages/ray/dashboard/modules/serve/serve_rest_api_impl.py +260 -0
  46. vllm/lib/python3.10/site-packages/ray/dashboard/modules/snapshot/__init__.py +0 -0
  47. vllm/lib/python3.10/site-packages/ray/dashboard/modules/snapshot/__pycache__/snapshot_head.cpython-310.pyc +0 -0
  48. vllm/lib/python3.10/site-packages/ray/dashboard/modules/train/__init__.py +0 -0
  49. vllm/lib/python3.10/site-packages/ray/dashboard/modules/version.py +18 -0
  50. vllm/lib/python3.10/site-packages/ray/dashboard/optional_deps.py +21 -0
vllm/lib/python3.10/site-packages/ray/dashboard/__init__.py ADDED
File without changes
vllm/lib/python3.10/site-packages/ray/dashboard/agent.py ADDED
@@ -0,0 +1,456 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import asyncio
3
+ import json
4
+ import logging
5
+ import logging.handlers
6
+ import os
7
+ import pathlib
8
+ import signal
9
+ import sys
10
+
11
+ import ray
12
+ import ray._private.ray_constants as ray_constants
13
+ import ray._private.services
14
+ import ray._private.utils
15
+ import ray.dashboard.consts as dashboard_consts
16
+ import ray.dashboard.utils as dashboard_utils
17
+ from ray._private.gcs_utils import GcsAioClient
18
+ from ray._private.process_watcher import create_check_raylet_task
19
+ from ray._private.ray_constants import AGENT_GRPC_MAX_MESSAGE_LENGTH
20
+ from ray._private.ray_logging import configure_log_file, setup_component_logger
21
+
22
+ logger = logging.getLogger(__name__)
23
+
24
+
25
+ class DashboardAgent:
26
+ def __init__(
27
+ self,
28
+ node_ip_address,
29
+ dashboard_agent_port,
30
+ gcs_address,
31
+ cluster_id_hex,
32
+ minimal,
33
+ metrics_export_port=None,
34
+ node_manager_port=None,
35
+ listen_port=ray_constants.DEFAULT_DASHBOARD_AGENT_LISTEN_PORT,
36
+ disable_metrics_collection: bool = False,
37
+ *, # the following are required kwargs
38
+ object_store_name: str,
39
+ raylet_name: str,
40
+ log_dir: str,
41
+ temp_dir: str,
42
+ session_dir: str,
43
+ logging_params: dict,
44
+ agent_id: int,
45
+ session_name: str,
46
+ ):
47
+ """Initialize the DashboardAgent object."""
48
+ # Public attributes are accessible for all agent modules.
49
+ self.ip = node_ip_address
50
+ self.minimal = minimal
51
+
52
+ assert gcs_address is not None
53
+ self.gcs_address = gcs_address
54
+ self.cluster_id_hex = cluster_id_hex
55
+
56
+ self.temp_dir = temp_dir
57
+ self.session_dir = session_dir
58
+ self.log_dir = log_dir
59
+ self.dashboard_agent_port = dashboard_agent_port
60
+ self.metrics_export_port = metrics_export_port
61
+ self.node_manager_port = node_manager_port
62
+ self.listen_port = listen_port
63
+ self.object_store_name = object_store_name
64
+ self.raylet_name = raylet_name
65
+ self.logging_params = logging_params
66
+ self.node_id = os.environ["RAY_NODE_ID"]
67
+ self.metrics_collection_disabled = disable_metrics_collection
68
+ self.agent_id = agent_id
69
+ self.session_name = session_name
70
+
71
+ # grpc server is None in mininal.
72
+ self.server = None
73
+ # http_server is None in minimal.
74
+ self.http_server = None
75
+
76
+ # Used by the agent and sub-modules.
77
+ self.gcs_aio_client = GcsAioClient(
78
+ address=self.gcs_address,
79
+ nums_reconnect_retry=ray._config.gcs_rpc_server_reconnect_timeout_s(),
80
+ cluster_id=self.cluster_id_hex,
81
+ )
82
+
83
+ if not self.minimal:
84
+ self._init_non_minimal()
85
+
86
+ def _init_non_minimal(self):
87
+ from ray._private.gcs_pubsub import GcsAioPublisher
88
+ from ray.dashboard.http_server_agent import HttpServerAgent
89
+
90
+ self.aio_publisher = GcsAioPublisher(address=self.gcs_address)
91
+
92
+ try:
93
+ from grpc import aio as aiogrpc
94
+ except ImportError:
95
+ from grpc.experimental import aio as aiogrpc
96
+
97
+ # We would want to suppress deprecating warnings from aiogrpc library
98
+ # with the usage of asyncio.get_event_loop() in python version >=3.10
99
+ # This could be removed once https://github.com/grpc/grpc/issues/32526
100
+ # is released, and we used higher versions of grpcio that that.
101
+ if sys.version_info.major >= 3 and sys.version_info.minor >= 10:
102
+ import warnings
103
+
104
+ with warnings.catch_warnings():
105
+ warnings.simplefilter("ignore", category=DeprecationWarning)
106
+ aiogrpc.init_grpc_aio()
107
+ else:
108
+ aiogrpc.init_grpc_aio()
109
+
110
+ self.server = aiogrpc.server(
111
+ options=(
112
+ ("grpc.so_reuseport", 0),
113
+ (
114
+ "grpc.max_send_message_length",
115
+ AGENT_GRPC_MAX_MESSAGE_LENGTH,
116
+ ), # noqa
117
+ (
118
+ "grpc.max_receive_message_length",
119
+ AGENT_GRPC_MAX_MESSAGE_LENGTH,
120
+ ),
121
+ ) # noqa
122
+ )
123
+ grpc_ip = "127.0.0.1" if self.ip == "127.0.0.1" else "0.0.0.0"
124
+ try:
125
+ self.grpc_port = ray._private.tls_utils.add_port_to_grpc_server(
126
+ self.server, f"{grpc_ip}:{self.dashboard_agent_port}"
127
+ )
128
+ except Exception:
129
+ # TODO(SongGuyang): Catch the exception here because there is
130
+ # port conflict issue which brought from static port. We should
131
+ # remove this after we find better port resolution.
132
+ logger.exception(
133
+ "Failed to add port to grpc server. Agent will stay alive but "
134
+ "disable the grpc service."
135
+ )
136
+ self.server = None
137
+ self.grpc_port = None
138
+ else:
139
+ logger.info("Dashboard agent grpc address: %s:%s", grpc_ip, self.grpc_port)
140
+
141
+ # If the agent is not minimal it should start the http server
142
+ # to communicate with the dashboard in a head node.
143
+ # Http server is not started in the minimal version because
144
+ # it requires additional dependencies that are not
145
+ # included in the minimal ray package.
146
+ self.http_server = HttpServerAgent(self.ip, self.listen_port)
147
+
148
+ def _load_modules(self):
149
+ """Load dashboard agent modules."""
150
+ modules = []
151
+ agent_cls_list = dashboard_utils.get_all_modules(
152
+ dashboard_utils.DashboardAgentModule
153
+ )
154
+ for cls in agent_cls_list:
155
+ logger.info(
156
+ "Loading %s: %s", dashboard_utils.DashboardAgentModule.__name__, cls
157
+ )
158
+ c = cls(self)
159
+ modules.append(c)
160
+ logger.info("Loaded %d modules.", len(modules))
161
+ return modules
162
+
163
+ @property
164
+ def http_session(self):
165
+ assert (
166
+ self.http_server
167
+ ), "Accessing unsupported API (HttpServerAgent) in a minimal ray."
168
+ return self.http_server.http_session
169
+
170
+ @property
171
+ def publisher(self):
172
+ assert (
173
+ self.aio_publisher
174
+ ), "Accessing unsupported API (GcsAioPublisher) in a minimal ray."
175
+ return self.aio_publisher
176
+
177
+ def get_node_id(self) -> str:
178
+ return self.node_id
179
+
180
+ async def run(self):
181
+ # Start a grpc asyncio server.
182
+ if self.server:
183
+ await self.server.start()
184
+
185
+ modules = self._load_modules()
186
+
187
+ if self.http_server:
188
+ try:
189
+ await self.http_server.start(modules)
190
+ except Exception:
191
+ # TODO(SongGuyang): Catch the exception here because there is
192
+ # port conflict issue which brought from static port. We should
193
+ # remove this after we find better port resolution.
194
+ logger.exception(
195
+ "Failed to start http server. Agent will stay alive but "
196
+ "disable the http service."
197
+ )
198
+
199
+ # Write the dashboard agent port to kv.
200
+ # TODO: Use async version if performance is an issue
201
+ # -1 should indicate that http server is not started.
202
+ http_port = -1 if not self.http_server else self.http_server.http_port
203
+ grpc_port = -1 if not self.server else self.grpc_port
204
+ await self.gcs_aio_client.internal_kv_put(
205
+ f"{dashboard_consts.DASHBOARD_AGENT_PORT_PREFIX}{self.node_id}".encode(),
206
+ json.dumps([http_port, grpc_port]).encode(),
207
+ True,
208
+ namespace=ray_constants.KV_NAMESPACE_DASHBOARD,
209
+ )
210
+
211
+ tasks = [m.run(self.server) for m in modules]
212
+
213
+ if sys.platform not in ["win32", "cygwin"]:
214
+
215
+ def callback(msg):
216
+ logger.info(
217
+ f"Terminated Raylet: ip={self.ip}, node_id={self.node_id}. {msg}"
218
+ )
219
+
220
+ check_parent_task = create_check_raylet_task(
221
+ self.log_dir, self.gcs_address, callback, loop
222
+ )
223
+ tasks.append(check_parent_task)
224
+
225
+ if self.server:
226
+ tasks.append(self.server.wait_for_termination())
227
+ else:
228
+
229
+ async def wait_forever():
230
+ while True:
231
+ await asyncio.sleep(3600)
232
+
233
+ tasks.append(wait_forever())
234
+
235
+ await asyncio.gather(*tasks)
236
+
237
+ if self.http_server:
238
+ await self.http_server.cleanup()
239
+
240
+
241
+ def open_capture_files(log_dir):
242
+ filename = f"agent-{args.agent_id}"
243
+ return (
244
+ ray._private.utils.open_log(pathlib.Path(log_dir) / f"{filename}.out"),
245
+ ray._private.utils.open_log(pathlib.Path(log_dir) / f"{filename}.err"),
246
+ )
247
+
248
+
249
+ if __name__ == "__main__":
250
+ parser = argparse.ArgumentParser(description="Dashboard agent.")
251
+ parser.add_argument(
252
+ "--node-ip-address",
253
+ required=True,
254
+ type=str,
255
+ help="the IP address of this node.",
256
+ )
257
+ parser.add_argument(
258
+ "--gcs-address", required=True, type=str, help="The address (ip:port) of GCS."
259
+ )
260
+ parser.add_argument(
261
+ "--cluster-id-hex",
262
+ required=True,
263
+ type=str,
264
+ help="The cluster id in hex.",
265
+ )
266
+ parser.add_argument(
267
+ "--metrics-export-port",
268
+ required=True,
269
+ type=int,
270
+ help="The port to expose metrics through Prometheus.",
271
+ )
272
+ parser.add_argument(
273
+ "--dashboard-agent-port",
274
+ required=True,
275
+ type=int,
276
+ help="The port on which the dashboard agent will receive GRPCs.",
277
+ )
278
+ parser.add_argument(
279
+ "--node-manager-port",
280
+ required=True,
281
+ type=int,
282
+ help="The port to use for starting the node manager",
283
+ )
284
+ parser.add_argument(
285
+ "--object-store-name",
286
+ required=True,
287
+ type=str,
288
+ default=None,
289
+ help="The socket name of the plasma store",
290
+ )
291
+ parser.add_argument(
292
+ "--listen-port",
293
+ required=False,
294
+ type=int,
295
+ default=ray_constants.DEFAULT_DASHBOARD_AGENT_LISTEN_PORT,
296
+ help="Port for HTTP server to listen on",
297
+ )
298
+ parser.add_argument(
299
+ "--raylet-name",
300
+ required=True,
301
+ type=str,
302
+ default=None,
303
+ help="The socket path of the raylet process",
304
+ )
305
+ parser.add_argument(
306
+ "--logging-level",
307
+ required=False,
308
+ type=lambda s: logging.getLevelName(s.upper()),
309
+ default=ray_constants.LOGGER_LEVEL,
310
+ choices=ray_constants.LOGGER_LEVEL_CHOICES,
311
+ help=ray_constants.LOGGER_LEVEL_HELP,
312
+ )
313
+ parser.add_argument(
314
+ "--logging-format",
315
+ required=False,
316
+ type=str,
317
+ default=ray_constants.LOGGER_FORMAT,
318
+ help=ray_constants.LOGGER_FORMAT_HELP,
319
+ )
320
+ parser.add_argument(
321
+ "--logging-filename",
322
+ required=False,
323
+ type=str,
324
+ default=dashboard_consts.DASHBOARD_AGENT_LOG_FILENAME,
325
+ help="Specify the name of log file, "
326
+ 'log to stdout if set empty, default is "{}".'.format(
327
+ dashboard_consts.DASHBOARD_AGENT_LOG_FILENAME
328
+ ),
329
+ )
330
+ parser.add_argument(
331
+ "--logging-rotate-bytes",
332
+ required=False,
333
+ type=int,
334
+ default=ray_constants.LOGGING_ROTATE_BYTES,
335
+ help="Specify the max bytes for rotating "
336
+ "log file, default is {} bytes.".format(ray_constants.LOGGING_ROTATE_BYTES),
337
+ )
338
+ parser.add_argument(
339
+ "--logging-rotate-backup-count",
340
+ required=False,
341
+ type=int,
342
+ default=ray_constants.LOGGING_ROTATE_BACKUP_COUNT,
343
+ help="Specify the backup count of rotated log file, default is {}.".format(
344
+ ray_constants.LOGGING_ROTATE_BACKUP_COUNT
345
+ ),
346
+ )
347
+ parser.add_argument(
348
+ "--log-dir",
349
+ required=True,
350
+ type=str,
351
+ default=None,
352
+ help="Specify the path of log directory.",
353
+ )
354
+ parser.add_argument(
355
+ "--temp-dir",
356
+ required=True,
357
+ type=str,
358
+ default=None,
359
+ help="Specify the path of the temporary directory use by Ray process.",
360
+ )
361
+ parser.add_argument(
362
+ "--session-dir",
363
+ required=True,
364
+ type=str,
365
+ default=None,
366
+ help="Specify the path of this session.",
367
+ )
368
+
369
+ parser.add_argument(
370
+ "--minimal",
371
+ action="store_true",
372
+ help=(
373
+ "Minimal agent only contains a subset of features that don't "
374
+ "require additional dependencies installed when ray is installed "
375
+ "by `pip install 'ray[default]'`."
376
+ ),
377
+ )
378
+ parser.add_argument(
379
+ "--disable-metrics-collection",
380
+ action="store_true",
381
+ help=("If this arg is set, metrics report won't be enabled from the agent."),
382
+ )
383
+ parser.add_argument(
384
+ "--agent-id",
385
+ required=True,
386
+ type=int,
387
+ help="ID to report when registering with raylet",
388
+ default=os.getpid(),
389
+ )
390
+ parser.add_argument(
391
+ "--session-name",
392
+ required=False,
393
+ type=str,
394
+ default=None,
395
+ help="The session name (cluster id) of this cluster.",
396
+ )
397
+
398
+ args = parser.parse_args()
399
+
400
+ try:
401
+ logging_params = dict(
402
+ logging_level=args.logging_level,
403
+ logging_format=args.logging_format,
404
+ log_dir=args.log_dir,
405
+ filename=args.logging_filename,
406
+ max_bytes=args.logging_rotate_bytes,
407
+ backup_count=args.logging_rotate_backup_count,
408
+ )
409
+ logger = setup_component_logger(**logging_params)
410
+
411
+ # Initialize event loop, see Dashboard init code for caveat
412
+ # w.r.t grpc server init in the DashboardAgent initializer.
413
+ loop = ray._private.utils.get_or_create_event_loop()
414
+
415
+ # Setup stdout/stderr redirect files
416
+ out_file, err_file = open_capture_files(args.log_dir)
417
+ configure_log_file(out_file, err_file)
418
+
419
+ agent = DashboardAgent(
420
+ args.node_ip_address,
421
+ args.dashboard_agent_port,
422
+ args.gcs_address,
423
+ args.cluster_id_hex,
424
+ args.minimal,
425
+ temp_dir=args.temp_dir,
426
+ session_dir=args.session_dir,
427
+ log_dir=args.log_dir,
428
+ metrics_export_port=args.metrics_export_port,
429
+ node_manager_port=args.node_manager_port,
430
+ listen_port=args.listen_port,
431
+ object_store_name=args.object_store_name,
432
+ raylet_name=args.raylet_name,
433
+ logging_params=logging_params,
434
+ disable_metrics_collection=args.disable_metrics_collection,
435
+ agent_id=args.agent_id,
436
+ session_name=args.session_name,
437
+ )
438
+
439
+ def sigterm_handler():
440
+ logger.warning("Exiting with SIGTERM immediately...")
441
+ # Exit code 0 will be considered as an expected shutdown
442
+ os._exit(signal.SIGTERM)
443
+
444
+ if sys.platform != "win32":
445
+ # TODO(rickyyx): we currently do not have any logic for actual
446
+ # graceful termination in the agent. Most of the underlying
447
+ # async tasks run by the agent head doesn't handle CancelledError.
448
+ # So a truly graceful shutdown is not trivial w/o much refactoring.
449
+ # Re-open the issue: https://github.com/ray-project/ray/issues/25518
450
+ # if a truly graceful shutdown is required.
451
+ loop.add_signal_handler(signal.SIGTERM, sigterm_handler)
452
+
453
+ loop.run_until_complete(agent.run())
454
+ except Exception:
455
+ logger.exception("Agent is working abnormally. It will exit immediately.")
456
+ exit(1)
vllm/lib/python3.10/site-packages/ray/dashboard/consts.py ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ from ray._private.ray_constants import env_bool, env_integer
4
+
5
+ DASHBOARD_LOG_FILENAME = "dashboard.log"
6
+ DASHBOARD_AGENT_PORT_PREFIX = "DASHBOARD_AGENT_PORT_PREFIX:"
7
+ DASHBOARD_AGENT_LOG_FILENAME = "dashboard_agent.log"
8
+ DASHBOARD_AGENT_CHECK_PARENT_INTERVAL_S_ENV_NAME = (
9
+ "RAY_DASHBOARD_AGENT_CHECK_PARENT_INTERVAL_S" # noqa
10
+ )
11
+ DASHBOARD_AGENT_CHECK_PARENT_INTERVAL_S = env_integer(
12
+ DASHBOARD_AGENT_CHECK_PARENT_INTERVAL_S_ENV_NAME, 0.4
13
+ )
14
+ # The maximum time that parent can be considered
15
+ # as dead before agent kills itself.
16
+ _PARENT_DEATH_THREASHOLD = 5
17
+ RAY_STATE_SERVER_MAX_HTTP_REQUEST_ENV_NAME = "RAY_STATE_SERVER_MAX_HTTP_REQUEST"
18
+ # Default number of in-progress requests to the state api server.
19
+ RAY_STATE_SERVER_MAX_HTTP_REQUEST = env_integer(
20
+ RAY_STATE_SERVER_MAX_HTTP_REQUEST_ENV_NAME, 100
21
+ )
22
+ # Max allowed number of in-progress requests could be configured.
23
+ RAY_STATE_SERVER_MAX_HTTP_REQUEST_ALLOWED = 1000
24
+
25
+ RAY_DASHBOARD_STATS_PURGING_INTERVAL = env_integer(
26
+ "RAY_DASHBOARD_STATS_PURGING_INTERVAL", 60 * 10
27
+ )
28
+ RAY_DASHBOARD_STATS_UPDATING_INTERVAL = env_integer(
29
+ "RAY_DASHBOARD_STATS_UPDATING_INTERVAL", 15
30
+ )
31
+ DASHBOARD_RPC_ADDRESS = "dashboard_rpc"
32
+ DASHBOARD_RPC_PORT = env_integer("RAY_DASHBOARD_RPC_PORT", 0)
33
+ GCS_SERVER_ADDRESS = "GcsServerAddress"
34
+ # GCS check alive
35
+ GCS_CHECK_ALIVE_INTERVAL_SECONDS = env_integer("GCS_CHECK_ALIVE_INTERVAL_SECONDS", 5)
36
+ GCS_RPC_TIMEOUT_SECONDS = env_integer("RAY_DASHBOARD_GCS_RPC_TIMEOUT_SECONDS", 60)
37
+ # aiohttp_cache
38
+ AIOHTTP_CACHE_TTL_SECONDS = 2
39
+ AIOHTTP_CACHE_MAX_SIZE = 128
40
+ AIOHTTP_CACHE_DISABLE_ENVIRONMENT_KEY = "RAY_DASHBOARD_NO_CACHE"
41
+ # Default value for datacenter (the default value in protobuf)
42
+ DEFAULT_LANGUAGE = "PYTHON"
43
+ DEFAULT_JOB_ID = "ffff"
44
+ # Hook that is invoked on the dashboard `/api/component_activities` endpoint.
45
+ # Environment variable stored here should be a callable that does not
46
+ # take any arguments and should return a dictionary mapping
47
+ # activity component type (str) to
48
+ # ray.dashboard.modules.snapshot.snapshot_head.RayActivityResponse.
49
+ # Example: "your.module.ray_cluster_activity_hook".
50
+ RAY_CLUSTER_ACTIVITY_HOOK = "RAY_CLUSTER_ACTIVITY_HOOK"
51
+
52
+ # The number of candidate agents
53
+ CANDIDATE_AGENT_NUMBER = max(env_integer("CANDIDATE_AGENT_NUMBER", 1), 1)
54
+ # when head receive JobSubmitRequest, maybe not any agent is available,
55
+ # we need to wait for agents in other node start
56
+ WAIT_AVAILABLE_AGENT_TIMEOUT = 10
57
+ TRY_TO_GET_AGENT_INFO_INTERVAL_SECONDS = 0.5
58
+ RAY_JOB_ALLOW_DRIVER_ON_WORKER_NODES_ENV_VAR = "RAY_JOB_ALLOW_DRIVER_ON_WORKER_NODES"
59
+ RAY_STREAM_RUNTIME_ENV_LOG_TO_JOB_DRIVER_LOG_ENV_VAR = (
60
+ "RAY_STREAM_RUNTIME_ENV_LOG_TO_JOB_DRIVER_LOG"
61
+ )
62
+
63
+ # The max time to wait for the JobSupervisor to start before failing the job.
64
+ DEFAULT_JOB_START_TIMEOUT_SECONDS = 60 * 15
65
+ RAY_JOB_START_TIMEOUT_SECONDS_ENV_VAR = "RAY_JOB_START_TIMEOUT_SECONDS"
66
+ # Port that dashboard prometheus metrics will be exported to
67
+ DASHBOARD_METRIC_PORT = env_integer("DASHBOARD_METRIC_PORT", 44227)
68
+
69
+ NODE_TAG_KEYS = ["ip", "Version", "SessionName", "IsHeadNode"]
70
+ GPU_TAG_KEYS = NODE_TAG_KEYS + ["GpuDeviceName", "GpuIndex"]
71
+ CLUSTER_TAG_KEYS = ["node_type", "Version", "SessionName"]
72
+ COMPONENT_METRICS_TAG_KEYS = ["ip", "pid", "Version", "Component", "SessionName"]
73
+
74
+ # Dashboard metrics are tracked separately at the dashboard. TODO(sang): Support GCS.
75
+ AVAILABLE_COMPONENT_NAMES_FOR_METRICS = {
76
+ "workers",
77
+ "raylet",
78
+ "agent",
79
+ "dashboard",
80
+ "gcs",
81
+ }
82
+ METRICS_INPUT_ROOT = os.path.join(
83
+ os.path.dirname(__file__), "modules", "metrics", "export"
84
+ )
85
+ PROMETHEUS_CONFIG_INPUT_PATH = os.path.join(
86
+ METRICS_INPUT_ROOT, "prometheus", "prometheus.yml"
87
+ )
88
+ PARENT_HEALTH_CHECK_BY_PIPE = env_bool(
89
+ "RAY_enable_pipe_based_agent_to_parent_health_check", False
90
+ )
vllm/lib/python3.10/site-packages/ray/dashboard/dashboard.py ADDED
@@ -0,0 +1,275 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import logging
3
+ import logging.handlers
4
+ import os
5
+ import platform
6
+ import signal
7
+ import sys
8
+ import traceback
9
+ from typing import Optional, Set
10
+
11
+ import ray._private.ray_constants as ray_constants
12
+ import ray._private.services
13
+ import ray._private.utils
14
+ import ray.dashboard.consts as dashboard_consts
15
+ import ray.dashboard.head as dashboard_head
16
+ import ray.dashboard.utils as dashboard_utils
17
+ from ray._private.ray_logging import setup_component_logger
18
+
19
+ # Logger for this module. It should be configured at the entry point
20
+ # into the program using Ray. Ray provides a default configuration at
21
+ # entry/init points.
22
+ logger = logging.getLogger(__name__)
23
+
24
+
25
+ class Dashboard:
26
+ """A dashboard process for monitoring Ray nodes.
27
+
28
+ This dashboard is made up of a REST API which collates data published by
29
+ Reporter processes on nodes into a json structure, and a webserver
30
+ which polls said API for display purposes.
31
+
32
+ Args:
33
+ host: Host address of dashboard aiohttp server.
34
+ port: Port number of dashboard aiohttp server.
35
+ port_retries: The retry times to select a valid port.
36
+ gcs_address: GCS address of the cluster.
37
+ cluster_id_hex: Cluster ID hex string.
38
+ grpc_port: Port used to listen for gRPC on.
39
+ node_ip_address: The IP address of the dashboard.
40
+ serve_frontend: If configured, frontend HTML
41
+ is not served from the dashboard.
42
+ log_dir: Log directory of dashboard.
43
+ """
44
+
45
+ def __init__(
46
+ self,
47
+ host: str,
48
+ port: int,
49
+ port_retries: int,
50
+ gcs_address: str,
51
+ cluster_id_hex: str,
52
+ grpc_port: int,
53
+ node_ip_address: str,
54
+ log_dir: str = None,
55
+ temp_dir: str = None,
56
+ session_dir: str = None,
57
+ minimal: bool = False,
58
+ serve_frontend: bool = True,
59
+ modules_to_load: Optional[Set[str]] = None,
60
+ ):
61
+ self.dashboard_head = dashboard_head.DashboardHead(
62
+ http_host=host,
63
+ http_port=port,
64
+ http_port_retries=port_retries,
65
+ gcs_address=gcs_address,
66
+ cluster_id_hex=cluster_id_hex,
67
+ node_ip_address=node_ip_address,
68
+ grpc_port=grpc_port,
69
+ log_dir=log_dir,
70
+ temp_dir=temp_dir,
71
+ session_dir=session_dir,
72
+ minimal=minimal,
73
+ serve_frontend=serve_frontend,
74
+ modules_to_load=modules_to_load,
75
+ )
76
+
77
+ async def run(self):
78
+ await self.dashboard_head.run()
79
+
80
+
81
+ if __name__ == "__main__":
82
+ parser = argparse.ArgumentParser(description="Ray dashboard.")
83
+ parser.add_argument(
84
+ "--host", required=True, type=str, help="The host to use for the HTTP server."
85
+ )
86
+ parser.add_argument(
87
+ "--port", required=True, type=int, help="The port to use for the HTTP server."
88
+ )
89
+ parser.add_argument(
90
+ "--port-retries",
91
+ required=False,
92
+ type=int,
93
+ default=0,
94
+ help="The retry times to select a valid port.",
95
+ )
96
+ parser.add_argument(
97
+ "--gcs-address", required=True, type=str, help="The address (ip:port) of GCS."
98
+ )
99
+ parser.add_argument(
100
+ "--cluster-id-hex", required=True, type=str, help="The cluster ID in hex."
101
+ )
102
+ parser.add_argument(
103
+ "--grpc-port",
104
+ required=False,
105
+ type=int,
106
+ default=dashboard_consts.DASHBOARD_RPC_PORT,
107
+ help="The port for the dashboard to listen for gRPC on.",
108
+ )
109
+ parser.add_argument(
110
+ "--node-ip-address",
111
+ required=True,
112
+ type=str,
113
+ help="The IP address of the node where this is running.",
114
+ )
115
+ parser.add_argument(
116
+ "--logging-level",
117
+ required=False,
118
+ type=lambda s: logging.getLevelName(s.upper()),
119
+ default=ray_constants.LOGGER_LEVEL,
120
+ choices=ray_constants.LOGGER_LEVEL_CHOICES,
121
+ help=ray_constants.LOGGER_LEVEL_HELP,
122
+ )
123
+ parser.add_argument(
124
+ "--logging-format",
125
+ required=False,
126
+ type=str,
127
+ default=ray_constants.LOGGER_FORMAT,
128
+ help=ray_constants.LOGGER_FORMAT_HELP,
129
+ )
130
+ parser.add_argument(
131
+ "--logging-filename",
132
+ required=False,
133
+ type=str,
134
+ default=dashboard_consts.DASHBOARD_LOG_FILENAME,
135
+ help="Specify the name of log file, "
136
+ 'log to stdout if set empty, default is "{}"'.format(
137
+ dashboard_consts.DASHBOARD_LOG_FILENAME
138
+ ),
139
+ )
140
+ parser.add_argument(
141
+ "--logging-rotate-bytes",
142
+ required=False,
143
+ type=int,
144
+ default=ray_constants.LOGGING_ROTATE_BYTES,
145
+ help="Specify the max bytes for rotating "
146
+ "log file, default is {} bytes.".format(ray_constants.LOGGING_ROTATE_BYTES),
147
+ )
148
+ parser.add_argument(
149
+ "--logging-rotate-backup-count",
150
+ required=False,
151
+ type=int,
152
+ default=ray_constants.LOGGING_ROTATE_BACKUP_COUNT,
153
+ help="Specify the backup count of rotated log file, default is {}.".format(
154
+ ray_constants.LOGGING_ROTATE_BACKUP_COUNT
155
+ ),
156
+ )
157
+ parser.add_argument(
158
+ "--log-dir",
159
+ required=True,
160
+ type=str,
161
+ default=None,
162
+ help="Specify the path of log directory.",
163
+ )
164
+ parser.add_argument(
165
+ "--temp-dir",
166
+ required=True,
167
+ type=str,
168
+ default=None,
169
+ help="Specify the path of the temporary directory use by Ray process.",
170
+ )
171
+ parser.add_argument(
172
+ "--session-dir",
173
+ required=True,
174
+ type=str,
175
+ default=None,
176
+ help="Specify the path of the session directory of the cluster.",
177
+ )
178
+ parser.add_argument(
179
+ "--minimal",
180
+ action="store_true",
181
+ help=(
182
+ "Minimal dashboard only contains a subset of features that don't "
183
+ "require additional dependencies installed when ray is installed "
184
+ "by `pip install ray[default]`."
185
+ ),
186
+ )
187
+ parser.add_argument(
188
+ "--modules-to-load",
189
+ required=False,
190
+ default=None,
191
+ help=(
192
+ "Specify the list of module names in [module_1],[module_2] format."
193
+ "E.g., JobHead,StateHead... "
194
+ "If nothing is specified, all modules are loaded."
195
+ ),
196
+ )
197
+ parser.add_argument(
198
+ "--disable-frontend",
199
+ action="store_true",
200
+ help=("If configured, frontend html is not served from the server."),
201
+ )
202
+
203
+ args = parser.parse_args()
204
+
205
+ try:
206
+ setup_component_logger(
207
+ logging_level=args.logging_level,
208
+ logging_format=args.logging_format,
209
+ log_dir=args.log_dir,
210
+ filename=args.logging_filename,
211
+ max_bytes=args.logging_rotate_bytes,
212
+ backup_count=args.logging_rotate_backup_count,
213
+ )
214
+
215
+ if args.modules_to_load:
216
+ modules_to_load = set(args.modules_to_load.strip(" ,").split(","))
217
+ else:
218
+ # None == default.
219
+ modules_to_load = None
220
+
221
+ # NOTE: Creating and attaching the event loop to the main OS thread be called
222
+ # before initializing Dashboard, which will initialize the grpc aio server,
223
+ # which assumes a working event loop. Ref:
224
+ # https://github.com/grpc/grpc/blob/master/src/python/grpcio/grpc/_cython/_cygrpc/aio/common.pyx.pxi#L174-L188
225
+ loop = ray._private.utils.get_or_create_event_loop()
226
+ dashboard = Dashboard(
227
+ host=args.host,
228
+ port=args.port,
229
+ port_retries=args.port_retries,
230
+ gcs_address=args.gcs_address,
231
+ cluster_id_hex=args.cluster_id_hex,
232
+ grpc_port=args.grpc_port,
233
+ node_ip_address=args.node_ip_address,
234
+ log_dir=args.log_dir,
235
+ temp_dir=args.temp_dir,
236
+ session_dir=args.session_dir,
237
+ minimal=args.minimal,
238
+ serve_frontend=(not args.disable_frontend),
239
+ modules_to_load=modules_to_load,
240
+ )
241
+
242
+ def sigterm_handler():
243
+ logger.warning("Exiting with SIGTERM immediately...")
244
+ os._exit(signal.SIGTERM)
245
+
246
+ if sys.platform != "win32":
247
+ # TODO(rickyyx): we currently do not have any logic for actual
248
+ # graceful termination in the dashboard. Most of the underlying
249
+ # async tasks run by the dashboard head doesn't handle CancelledError.
250
+ # So a truly graceful shutdown is not trivial w/o much refactoring.
251
+ # Re-open the issue: https://github.com/ray-project/ray/issues/25518
252
+ # if a truly graceful shutdown is required.
253
+ loop.add_signal_handler(signal.SIGTERM, sigterm_handler)
254
+
255
+ loop.run_until_complete(dashboard.run())
256
+ except Exception as e:
257
+ traceback_str = ray._private.utils.format_error_message(traceback.format_exc())
258
+ message = (
259
+ f"The dashboard on node {platform.uname()[1]} "
260
+ f"failed with the following "
261
+ f"error:\n{traceback_str}"
262
+ )
263
+ if isinstance(e, dashboard_utils.FrontendNotFoundError):
264
+ logger.warning(message)
265
+ else:
266
+ logger.error(message)
267
+ raise e
268
+
269
+ # Something went wrong, so push an error to all drivers.
270
+ gcs_publisher = ray._raylet.GcsPublisher(address=args.gcs_address)
271
+ ray._private.utils.publish_error_to_driver(
272
+ ray_constants.DASHBOARD_DIED_ERROR,
273
+ message,
274
+ gcs_publisher=gcs_publisher,
275
+ )
vllm/lib/python3.10/site-packages/ray/dashboard/dashboard_metrics.py ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Optional
2
+
3
+ from ray.dashboard.consts import COMPONENT_METRICS_TAG_KEYS
4
+
5
+
6
+ class NullMetric:
7
+ """Mock metric class to be used in case of prometheus_client import error."""
8
+
9
+ def set(self, *args, **kwargs):
10
+ pass
11
+
12
+ def observe(self, *args, **kwargs):
13
+ pass
14
+
15
+ def inc(self, *args, **kwargs):
16
+ pass
17
+
18
+
19
+ try:
20
+
21
+ from prometheus_client import CollectorRegistry, Counter, Gauge, Histogram
22
+
23
+ # The metrics in this class should be kept in sync with
24
+ # python/ray/tests/test_metrics_agent.py
25
+ class DashboardPrometheusMetrics:
26
+ def __init__(self, registry: Optional[CollectorRegistry] = None):
27
+ self.registry: CollectorRegistry = registry or CollectorRegistry(
28
+ auto_describe=True
29
+ )
30
+ # Buckets: 5ms, 10ms, 25ms, 50ms, 75ms
31
+ # 100ms, 250ms, 500ms, 750ms
32
+ # 1s, 2.5s, 5s, 7.5s, 10s
33
+ # 20s, 40s, 60s
34
+ # used for API duration
35
+ histogram_buckets_s = [
36
+ 0.005,
37
+ 0.01,
38
+ 0.025,
39
+ 0.05,
40
+ 0.075,
41
+ 0.1,
42
+ 0.25,
43
+ 0.5,
44
+ 0.75,
45
+ 1,
46
+ 2.5,
47
+ 5,
48
+ 7.5,
49
+ 10,
50
+ 20,
51
+ 40,
52
+ 60,
53
+ ]
54
+ self.metrics_request_duration = Histogram(
55
+ "dashboard_api_requests_duration_seconds",
56
+ "Total duration in seconds per endpoint",
57
+ ("endpoint", "http_status", "Version", "SessionName", "Component"),
58
+ unit="seconds",
59
+ namespace="ray",
60
+ registry=self.registry,
61
+ buckets=histogram_buckets_s,
62
+ )
63
+ self.metrics_request_count = Counter(
64
+ "dashboard_api_requests_count",
65
+ "Total requests count per endpoint",
66
+ (
67
+ "method",
68
+ "endpoint",
69
+ "http_status",
70
+ "Version",
71
+ "SessionName",
72
+ "Component",
73
+ ),
74
+ unit="requests",
75
+ namespace="ray",
76
+ registry=self.registry,
77
+ )
78
+ self.metrics_event_loop_tasks = Gauge(
79
+ "dashboard_event_loop_tasks",
80
+ "Number of tasks currently pending in the event loop's queue.",
81
+ tuple(COMPONENT_METRICS_TAG_KEYS),
82
+ unit="tasks",
83
+ namespace="ray",
84
+ registry=self.registry,
85
+ )
86
+ self.metrics_event_loop_lag = Gauge(
87
+ "dashboard_event_loop_lag",
88
+ "Event loop lag in seconds.",
89
+ tuple(COMPONENT_METRICS_TAG_KEYS),
90
+ unit="seconds",
91
+ namespace="ray",
92
+ registry=self.registry,
93
+ )
94
+ self.metrics_dashboard_cpu = Gauge(
95
+ "component_cpu",
96
+ "Dashboard CPU percentage usage.",
97
+ tuple(COMPONENT_METRICS_TAG_KEYS),
98
+ unit="percentage",
99
+ namespace="ray",
100
+ registry=self.registry,
101
+ )
102
+ self.metrics_dashboard_mem_uss = Gauge(
103
+ "component_uss",
104
+ "USS usage of all components on the node.",
105
+ tuple(COMPONENT_METRICS_TAG_KEYS),
106
+ unit="mb",
107
+ namespace="ray",
108
+ registry=self.registry,
109
+ )
110
+ self.metrics_dashboard_mem_rss = Gauge(
111
+ "component_rss",
112
+ "RSS usage of all components on the node.",
113
+ tuple(COMPONENT_METRICS_TAG_KEYS),
114
+ unit="mb",
115
+ namespace="ray",
116
+ registry=self.registry,
117
+ )
118
+
119
+ except ImportError:
120
+
121
+ class DashboardPrometheusMetrics(object):
122
+ def __getattr__(self, attr):
123
+ return NullMetric()
vllm/lib/python3.10/site-packages/ray/dashboard/datacenter.py ADDED
@@ -0,0 +1,288 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ from typing import Any, List, Optional
3
+
4
+ import ray.dashboard.consts as dashboard_consts
5
+ from ray._private.utils import (
6
+ get_or_create_event_loop,
7
+ parse_pg_formatted_resources_to_original,
8
+ )
9
+ from ray.dashboard.utils import (
10
+ Dict,
11
+ MutableNotificationDict,
12
+ async_loop_forever,
13
+ compose_state_message,
14
+ )
15
+
16
+ logger = logging.getLogger(__name__)
17
+
18
+
19
+ # NOT thread safe. Every assignment must be on the main event loop thread.
20
+ class DataSource:
21
+ # {node id hex(str): node stats(dict of GetNodeStatsReply
22
+ # in node_manager.proto)}
23
+ node_stats = Dict()
24
+ # {node id hex(str): node physical stats(dict from reporter_agent.py)}
25
+ node_physical_stats = Dict()
26
+ # {actor id hex(str): actor table data(dict of ActorTableData
27
+ # in gcs.proto)}
28
+ actors = MutableNotificationDict()
29
+ # {job id hex(str): job table data(dict of JobTableData in gcs.proto)}
30
+ # {node id hex(str): dashboard agent [http port(int), grpc port(int)]}
31
+ agents = Dict()
32
+ # {node id hex(str): gcs node info(dict of GcsNodeInfo in gcs.proto)}
33
+ nodes = Dict()
34
+ # {node id hex(str): worker list}
35
+ node_workers = Dict()
36
+ # {node id hex(str): {actor id hex(str): actor table data}}
37
+ node_actors = MutableNotificationDict()
38
+ # {worker id(str): core worker stats}
39
+ core_worker_stats = Dict()
40
+ # {job id hex(str): {event id(str): event dict}}
41
+ events = Dict()
42
+
43
+
44
+ class DataOrganizer:
45
+ head_node_ip = None
46
+
47
+ @staticmethod
48
+ @async_loop_forever(dashboard_consts.RAY_DASHBOARD_STATS_PURGING_INTERVAL)
49
+ async def purge():
50
+ # Purge data that is out of date.
51
+ # These data sources are maintained by DashboardHead,
52
+ # we do not needs to purge them:
53
+ # * agents
54
+ # * nodes
55
+ alive_nodes = {
56
+ node_id
57
+ for node_id, node_info in DataSource.nodes.items()
58
+ if node_info["state"] == "ALIVE"
59
+ }
60
+ for key in DataSource.node_stats.keys() - alive_nodes:
61
+ DataSource.node_stats.pop(key)
62
+
63
+ for key in DataSource.node_physical_stats.keys() - alive_nodes:
64
+ DataSource.node_physical_stats.pop(key)
65
+
66
+ @classmethod
67
+ @async_loop_forever(dashboard_consts.RAY_DASHBOARD_STATS_UPDATING_INTERVAL)
68
+ async def organize(cls, thread_pool_executor):
69
+ """
70
+ Organizes data: read from (node_physical_stats, node_stats) and updates
71
+ (node_workers, node_worker_stats).
72
+
73
+ This methods is not really async, but DataSource is not thread safe so we need
74
+ to make sure it's on the main event loop thread. To avoid blocking the main
75
+ event loop, we yield after each node processed.
76
+ """
77
+ loop = get_or_create_event_loop()
78
+
79
+ node_workers = {}
80
+ core_worker_stats = {}
81
+
82
+ # NOTE: We copy keys of the `DataSource.nodes` to make sure
83
+ # it doesn't change during the iteration (since its being updated
84
+ # from another async task)
85
+ for node_id in list(DataSource.nodes.keys()):
86
+ node_physical_stats = DataSource.node_physical_stats.get(node_id, {})
87
+ node_stats = DataSource.node_stats.get(node_id, {})
88
+ # Offloads the blocking operation to a thread pool executor. This also
89
+ # yields to the event loop.
90
+ workers = await loop.run_in_executor(
91
+ thread_pool_executor,
92
+ cls._extract_workers_for_node,
93
+ node_physical_stats,
94
+ node_stats,
95
+ )
96
+
97
+ for worker in workers:
98
+ for stats in worker.get("coreWorkerStats", []):
99
+ worker_id = stats["workerId"]
100
+ core_worker_stats[worker_id] = stats
101
+
102
+ node_workers[node_id] = workers
103
+
104
+ DataSource.node_workers.reset(node_workers)
105
+ DataSource.core_worker_stats.reset(core_worker_stats)
106
+
107
+ @classmethod
108
+ def _extract_workers_for_node(cls, node_physical_stats, node_stats):
109
+ workers = []
110
+ # Merge coreWorkerStats (node stats) to workers (node physical stats)
111
+ pid_to_worker_stats = {}
112
+ pid_to_language = {}
113
+ pid_to_job_id = {}
114
+
115
+ for core_worker_stats in node_stats.get("coreWorkersStats", []):
116
+ pid = core_worker_stats["pid"]
117
+
118
+ pid_to_worker_stats[pid] = core_worker_stats
119
+ pid_to_language[pid] = core_worker_stats["language"]
120
+ pid_to_job_id[pid] = core_worker_stats["jobId"]
121
+
122
+ for worker in node_physical_stats.get("workers", []):
123
+ worker = dict(worker)
124
+ pid = worker["pid"]
125
+
126
+ core_worker_stats = pid_to_worker_stats.get(pid)
127
+ # Empty list means core worker stats is not available.
128
+ worker["coreWorkerStats"] = [core_worker_stats] if core_worker_stats else []
129
+ worker["language"] = pid_to_language.get(
130
+ pid, dashboard_consts.DEFAULT_LANGUAGE
131
+ )
132
+ worker["jobId"] = pid_to_job_id.get(pid, dashboard_consts.DEFAULT_JOB_ID)
133
+
134
+ workers.append(worker)
135
+
136
+ return workers
137
+
138
+ @classmethod
139
+ async def get_node_info(cls, node_id, get_summary=False):
140
+ node_physical_stats = dict(DataSource.node_physical_stats.get(node_id, {}))
141
+ node_stats = dict(DataSource.node_stats.get(node_id, {}))
142
+ node = DataSource.nodes.get(node_id, {})
143
+
144
+ if get_summary:
145
+ node_physical_stats.pop("workers", None)
146
+ node_stats.pop("workersStats", None)
147
+ else:
148
+ node_stats.pop("coreWorkersStats", None)
149
+ store_stats = node_stats.get("storeStats", {})
150
+ used = int(store_stats.get("objectStoreBytesUsed", 0))
151
+ # objectStoreBytesAvail == total in the object_manager.cc definition.
152
+ total = int(store_stats.get("objectStoreBytesAvail", 0))
153
+ ray_stats = {
154
+ "object_store_used_memory": used,
155
+ "object_store_available_memory": total - used,
156
+ }
157
+
158
+ node_info = node_physical_stats
159
+ # Merge node stats to node physical stats under raylet
160
+ node_info["raylet"] = node_stats
161
+ node_info["raylet"].update(ray_stats)
162
+
163
+ # Merge GcsNodeInfo to node physical stats
164
+ node_info["raylet"].update(node)
165
+ death_info = node.get("deathInfo", {})
166
+ node_info["raylet"]["stateMessage"] = compose_state_message(
167
+ death_info.get("reason", None), death_info.get("reasonMessage", None)
168
+ )
169
+
170
+ if not get_summary:
171
+ actor_table_entries = DataSource.node_actors.get(node_id, {})
172
+
173
+ # Merge actors to node physical stats
174
+ node_info["actors"] = {
175
+ actor_id: await DataOrganizer._get_actor_info(actor_table_entry)
176
+ for actor_id, actor_table_entry in actor_table_entries.items()
177
+ }
178
+
179
+ # Update workers to node physical stats
180
+ node_info["workers"] = DataSource.node_workers.get(node_id, [])
181
+
182
+ return node_info
183
+
184
+ @classmethod
185
+ async def get_all_node_summary(cls):
186
+ return [
187
+ # NOTE: We're intentionally awaiting in a loop to avoid excessive
188
+ # concurrency spinning up excessive # of tasks for large clusters
189
+ await DataOrganizer.get_node_info(node_id, get_summary=True)
190
+ for node_id in DataSource.nodes.keys()
191
+ ]
192
+
193
+ @classmethod
194
+ async def get_agent_infos(
195
+ cls, target_node_ids: Optional[List[str]] = None
196
+ ) -> Dict[str, Dict[str, Any]]:
197
+ """Fetches running Agent (like HTTP/gRPC ports, IP, etc) running on every node
198
+
199
+ :param target_node_ids: Target node ids to fetch agent info for. If omitted will
200
+ fetch the info for all agents
201
+ """
202
+
203
+ # Return all available agent infos in case no target node-ids were provided
204
+ target_node_ids = target_node_ids or DataSource.agents.keys()
205
+
206
+ missing_node_ids = [
207
+ node_id for node_id in target_node_ids if node_id not in DataSource.agents
208
+ ]
209
+ if missing_node_ids:
210
+ logger.warning(
211
+ f"Agent info was not found for {missing_node_ids}"
212
+ f" (having agent infos for {list(DataSource.agents.keys())})"
213
+ )
214
+ return {}
215
+
216
+ def _create_agent_info(node_id: str):
217
+ (http_port, grpc_port) = DataSource.agents[node_id]
218
+ node_ip = DataSource.nodes[node_id]["nodeManagerAddress"]
219
+
220
+ return dict(
221
+ ipAddress=node_ip,
222
+ httpPort=int(http_port or -1),
223
+ grpcPort=int(grpc_port or -1),
224
+ httpAddress=f"{node_ip}:{http_port}",
225
+ )
226
+
227
+ return {node_id: _create_agent_info(node_id) for node_id in target_node_ids}
228
+
229
+ @classmethod
230
+ async def get_actor_infos(cls, actor_ids: Optional[List[str]] = None):
231
+ target_actor_table_entries: dict[str, Optional[dict]]
232
+ if actor_ids is not None:
233
+ target_actor_table_entries = {
234
+ actor_id: DataSource.actors.get(actor_id) for actor_id in actor_ids
235
+ }
236
+ else:
237
+ target_actor_table_entries = DataSource.actors
238
+
239
+ return {
240
+ actor_id: await DataOrganizer._get_actor_info(actor_table_entry)
241
+ for actor_id, actor_table_entry in target_actor_table_entries.items()
242
+ }
243
+
244
+ @staticmethod
245
+ async def _get_actor_info(actor):
246
+ if actor is None:
247
+ return None
248
+
249
+ actor = dict(actor)
250
+ worker_id = actor["address"]["workerId"]
251
+ core_worker_stats = DataSource.core_worker_stats.get(worker_id, {})
252
+ actor_constructor = core_worker_stats.get(
253
+ "actorTitle", "Unknown actor constructor"
254
+ )
255
+ actor["actorConstructor"] = actor_constructor
256
+ actor.update(core_worker_stats)
257
+
258
+ # TODO(fyrestone): remove this, give a link from actor
259
+ # info to worker info in front-end.
260
+ node_id = actor["address"]["rayletId"]
261
+ pid = core_worker_stats.get("pid")
262
+ node_physical_stats = DataSource.node_physical_stats.get(node_id, {})
263
+ actor_process_stats = None
264
+ actor_process_gpu_stats = []
265
+ if pid:
266
+ for process_stats in node_physical_stats.get("workers", []):
267
+ if process_stats["pid"] == pid:
268
+ actor_process_stats = process_stats
269
+ break
270
+
271
+ for gpu_stats in node_physical_stats.get("gpus", []):
272
+ # gpu_stats.get("processes") can be None, an empty list or a
273
+ # list of dictionaries.
274
+ for process in gpu_stats.get("processesPids") or []:
275
+ if process["pid"] == pid:
276
+ actor_process_gpu_stats.append(gpu_stats)
277
+ break
278
+
279
+ actor["gpus"] = actor_process_gpu_stats
280
+ actor["processStats"] = actor_process_stats
281
+ actor["mem"] = node_physical_stats.get("mem", [])
282
+
283
+ required_resources = parse_pg_formatted_resources_to_original(
284
+ actor["requiredResources"]
285
+ )
286
+ actor["requiredResources"] = required_resources
287
+
288
+ return actor
vllm/lib/python3.10/site-packages/ray/dashboard/head.py ADDED
@@ -0,0 +1,344 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import logging
3
+ from concurrent.futures import ThreadPoolExecutor
4
+ from pathlib import Path
5
+ from typing import Optional, Set
6
+
7
+ import ray.dashboard.consts as dashboard_consts
8
+ import ray.dashboard.utils as dashboard_utils
9
+ import ray.experimental.internal_kv as internal_kv
10
+ from ray._private import ray_constants
11
+ from ray._private.gcs_utils import GcsAioClient
12
+ from ray._private.ray_constants import env_integer
13
+ from ray._private.usage.usage_lib import TagKey, record_extra_usage_tag
14
+ from ray._raylet import GcsClient
15
+ from ray.dashboard.consts import DASHBOARD_METRIC_PORT
16
+ from ray.dashboard.dashboard_metrics import DashboardPrometheusMetrics
17
+ from ray.dashboard.datacenter import DataOrganizer
18
+ from ray.dashboard.utils import DashboardHeadModule, async_loop_forever
19
+
20
+ try:
21
+ import prometheus_client
22
+ except ImportError:
23
+ prometheus_client = None
24
+
25
+
26
+ logger = logging.getLogger(__name__)
27
+
28
+ GRPC_CHANNEL_OPTIONS = (
29
+ *ray_constants.GLOBAL_GRPC_OPTIONS,
30
+ ("grpc.max_send_message_length", ray_constants.GRPC_CPP_MAX_MESSAGE_SIZE),
31
+ ("grpc.max_receive_message_length", ray_constants.GRPC_CPP_MAX_MESSAGE_SIZE),
32
+ )
33
+
34
+ # NOTE: Executor in this head is intentionally constrained to just 1 thread by
35
+ # default to limit its concurrency, therefore reducing potential for
36
+ # GIL contention
37
+ RAY_DASHBOARD_DASHBOARD_HEAD_TPE_MAX_WORKERS = env_integer(
38
+ "RAY_DASHBOARD_DASHBOARD_HEAD_TPE_MAX_WORKERS", 1
39
+ )
40
+
41
+
42
+ def initialize_grpc_port_and_server(grpc_ip, grpc_port):
43
+ try:
44
+ from grpc import aio as aiogrpc
45
+ except ImportError:
46
+ from grpc.experimental import aio as aiogrpc
47
+
48
+ import ray._private.tls_utils
49
+
50
+ aiogrpc.init_grpc_aio()
51
+
52
+ server = aiogrpc.server(options=(("grpc.so_reuseport", 0),))
53
+
54
+ grpc_port = ray._private.tls_utils.add_port_to_grpc_server(
55
+ server, f"{grpc_ip}:{grpc_port}"
56
+ )
57
+
58
+ return server, grpc_port
59
+
60
+
61
+ class DashboardHead:
62
+ def __init__(
63
+ self,
64
+ http_host: str,
65
+ http_port: int,
66
+ http_port_retries: int,
67
+ gcs_address: str,
68
+ cluster_id_hex: str,
69
+ node_ip_address: str,
70
+ grpc_port: int,
71
+ log_dir: str,
72
+ temp_dir: str,
73
+ session_dir: str,
74
+ minimal: bool,
75
+ serve_frontend: bool,
76
+ modules_to_load: Optional[Set[str]] = None,
77
+ ):
78
+ """
79
+ Args:
80
+ http_host: The host address for the Http server.
81
+ http_port: The port for the Http server.
82
+ http_port_retries: The maximum retry to bind ports for the Http server.
83
+ gcs_address: The GCS address in the {address}:{port} format.
84
+ log_dir: The log directory. E.g., /tmp/session_latest/logs.
85
+ temp_dir: The temp directory. E.g., /tmp.
86
+ session_dir: The session directory. E.g., tmp/session_latest.
87
+ minimal: Whether or not it will load the minimal modules.
88
+ serve_frontend: If configured, frontend HTML is
89
+ served from the dashboard.
90
+ grpc_port: The port used to listen for gRPC on.
91
+ modules_to_load: A set of module name in string to load.
92
+ By default (None), it loads all available modules.
93
+ Note that available modules could be changed depending on
94
+ minimal flags.
95
+ """
96
+ self.minimal = minimal
97
+ self.serve_frontend = serve_frontend
98
+ # If it is the minimal mode, we shouldn't serve frontend.
99
+ if self.minimal:
100
+ self.serve_frontend = False
101
+ # Public attributes are accessible for all head modules.
102
+ # Walkaround for issue: https://github.com/ray-project/ray/issues/7084
103
+ self.http_host = "127.0.0.1" if http_host == "localhost" else http_host
104
+ self.http_port = http_port
105
+ self.http_port_retries = http_port_retries
106
+ self._modules_to_load = modules_to_load
107
+ self._modules_loaded = False
108
+
109
+ self._executor = ThreadPoolExecutor(
110
+ max_workers=RAY_DASHBOARD_DASHBOARD_HEAD_TPE_MAX_WORKERS,
111
+ thread_name_prefix="dashboard_head_executor",
112
+ )
113
+
114
+ self.gcs_address = None
115
+ assert gcs_address is not None
116
+ self.gcs_address = gcs_address
117
+ self.cluster_id_hex = cluster_id_hex
118
+ self.log_dir = log_dir
119
+ self.temp_dir = temp_dir
120
+ self.session_dir = session_dir
121
+ self.session_name = Path(session_dir).name
122
+ self.aiogrpc_gcs_channel = None
123
+ self.gcs_aio_client = None
124
+ self.gcs_error_subscriber = None
125
+ self.gcs_log_subscriber = None
126
+ self.ip = node_ip_address
127
+ DataOrganizer.head_node_ip = self.ip
128
+
129
+ if self.minimal:
130
+ self.server, self.grpc_port = None, None
131
+ else:
132
+ grpc_ip = "127.0.0.1" if self.ip == "127.0.0.1" else "0.0.0.0"
133
+ self.server, self.grpc_port = initialize_grpc_port_and_server(
134
+ grpc_ip, grpc_port
135
+ )
136
+ logger.info("Dashboard head grpc address: %s:%s", grpc_ip, self.grpc_port)
137
+ # If the dashboard is started as non-minimal version, http server should
138
+ # be configured to expose APIs.
139
+ self.http_server = None
140
+
141
+ async def _configure_http_server(self, modules):
142
+ from ray.dashboard.http_server_head import HttpServerDashboardHead
143
+
144
+ self.http_server = HttpServerDashboardHead(
145
+ self.ip,
146
+ self.http_host,
147
+ self.http_port,
148
+ self.http_port_retries,
149
+ self.gcs_address,
150
+ self.session_name,
151
+ self.metrics,
152
+ )
153
+ await self.http_server.run(modules)
154
+
155
+ @property
156
+ def http_session(self):
157
+ if not self._modules_loaded and not self.http_server:
158
+ # When the dashboard is still starting up, this property gets
159
+ # called as part of the method_route_table_factory magic. In
160
+ # this case, the property is not actually used but the magic
161
+ # method calls every property to look for a route to add to
162
+ # the global route table. It should be okay for http_server
163
+ # to still be None at this point.
164
+ return None
165
+ assert self.http_server, "Accessing unsupported API in a minimal ray."
166
+ return self.http_server.http_session
167
+
168
+ @async_loop_forever(dashboard_consts.GCS_CHECK_ALIVE_INTERVAL_SECONDS)
169
+ async def _gcs_check_alive(self):
170
+ try:
171
+ # If gcs is permanently dead, gcs client will exit the process
172
+ # (see gcs_rpc_client.h)
173
+ await self.gcs_aio_client.check_alive(node_ips=[], timeout=None)
174
+ except Exception:
175
+ logger.warning("Failed to check gcs aliveness, will retry", exc_info=True)
176
+
177
+ def _load_modules(self, modules_to_load: Optional[Set[str]] = None):
178
+ """Load dashboard head modules.
179
+
180
+ Args:
181
+ modules: A list of module names to load. By default (None),
182
+ it loads all modules.
183
+ """
184
+ modules = []
185
+ head_cls_list = dashboard_utils.get_all_modules(DashboardHeadModule)
186
+
187
+ # Select modules to load.
188
+ modules_to_load = modules_to_load or {m.__name__ for m in head_cls_list}
189
+ logger.info("Modules to load: %s", modules_to_load)
190
+
191
+ for cls in head_cls_list:
192
+ logger.info("Loading %s: %s", DashboardHeadModule.__name__, cls)
193
+ if cls.__name__ in modules_to_load:
194
+ c = cls(self)
195
+ modules.append(c)
196
+
197
+ # Verify modules are loaded as expected.
198
+ loaded_modules = {type(m).__name__ for m in modules}
199
+ if loaded_modules != modules_to_load:
200
+ assert False, (
201
+ "Actual loaded modules, {}, doesn't match the requested modules "
202
+ "to load, {}".format(loaded_modules, modules_to_load)
203
+ )
204
+
205
+ self._modules_loaded = True
206
+ logger.info("Loaded %d modules. %s", len(modules), modules)
207
+ return modules
208
+
209
+ async def _setup_metrics(self, gcs_aio_client):
210
+ metrics = DashboardPrometheusMetrics()
211
+
212
+ # Setup prometheus metrics export server
213
+ assert internal_kv._internal_kv_initialized()
214
+ assert gcs_aio_client is not None
215
+ address = f"{self.ip}:{DASHBOARD_METRIC_PORT}"
216
+ await gcs_aio_client.internal_kv_put(
217
+ "DashboardMetricsAddress".encode(), address.encode(), True, namespace=None
218
+ )
219
+ if prometheus_client:
220
+ try:
221
+ logger.info(
222
+ "Starting dashboard metrics server on port {}".format(
223
+ DASHBOARD_METRIC_PORT
224
+ )
225
+ )
226
+ kwargs = {"addr": "127.0.0.1"} if self.ip == "127.0.0.1" else {}
227
+ prometheus_client.start_http_server(
228
+ port=DASHBOARD_METRIC_PORT,
229
+ registry=metrics.registry,
230
+ **kwargs,
231
+ )
232
+ except Exception:
233
+ logger.exception(
234
+ "An exception occurred while starting the metrics server."
235
+ )
236
+ elif not prometheus_client:
237
+ logger.warning(
238
+ "`prometheus_client` not found, so metrics will not be exported."
239
+ )
240
+
241
+ return metrics
242
+
243
+ async def run(self):
244
+ gcs_address = self.gcs_address
245
+
246
+ # Dashboard will handle connection failure automatically
247
+ self.gcs_client = GcsClient(
248
+ address=gcs_address, nums_reconnect_retry=0, cluster_id=self.cluster_id_hex
249
+ )
250
+ self.gcs_aio_client = GcsAioClient(
251
+ address=gcs_address, nums_reconnect_retry=0, cluster_id=self.cluster_id_hex
252
+ )
253
+ internal_kv._initialize_internal_kv(self.gcs_client)
254
+
255
+ if self.minimal:
256
+ self.aiogrpc_gcs_channel = None
257
+ self.metrics = None
258
+ else:
259
+ from ray._private.gcs_utils import GcsChannel
260
+
261
+ # TODO(ryw): once we removed the old gcs client, also remove this.
262
+ gcs_channel = GcsChannel(gcs_address=gcs_address, aio=True)
263
+ gcs_channel.connect()
264
+ self.aiogrpc_gcs_channel = gcs_channel.channel()
265
+
266
+ self.metrics = await self._setup_metrics(self.gcs_aio_client)
267
+ try:
268
+ assert internal_kv._internal_kv_initialized()
269
+ # Note: We always record the usage, but it is not reported
270
+ # if the usage stats is disabled.
271
+ record_extra_usage_tag(TagKey.DASHBOARD_USED, "False")
272
+ except Exception as e:
273
+ logger.warning(
274
+ "Failed to record the dashboard usage. "
275
+ "This error message is harmless and can be ignored. "
276
+ f"Error: {e}"
277
+ )
278
+
279
+ # Start a grpc asyncio server.
280
+ if self.server:
281
+ await self.server.start()
282
+
283
+ async def _async_notify():
284
+ """Notify signals from queue."""
285
+ while True:
286
+ co = await dashboard_utils.NotifyQueue.get()
287
+ try:
288
+ await co
289
+ except Exception:
290
+ logger.exception(f"Error notifying coroutine {co}")
291
+
292
+ modules = self._load_modules(self._modules_to_load)
293
+
294
+ http_host, http_port = self.http_host, self.http_port
295
+ if self.serve_frontend:
296
+ logger.info("Initialize the http server.")
297
+ await self._configure_http_server(modules)
298
+ http_host, http_port = self.http_server.get_address()
299
+ logger.info(f"http server initialized at {http_host}:{http_port}")
300
+ else:
301
+ logger.info("http server disabled.")
302
+
303
+ # We need to expose dashboard's node's ip for other worker nodes
304
+ # if it's listening to all interfaces.
305
+ dashboard_http_host = (
306
+ self.ip
307
+ if self.http_host != ray_constants.DEFAULT_DASHBOARD_IP
308
+ else http_host
309
+ )
310
+ # This synchronous code inside an async context is not great.
311
+ # It is however acceptable, because this only gets run once
312
+ # during initialization and therefore cannot block the event loop.
313
+ # This could be done better in the future, including
314
+ # removing the polling on the Ray side, by communicating the
315
+ # server address to Ray via stdin / stdout or a pipe.
316
+ self.gcs_client.internal_kv_put(
317
+ ray_constants.DASHBOARD_ADDRESS.encode(),
318
+ f"{dashboard_http_host}:{http_port}".encode(),
319
+ True,
320
+ namespace=ray_constants.KV_NAMESPACE_DASHBOARD,
321
+ )
322
+ self.gcs_client.internal_kv_put(
323
+ dashboard_consts.DASHBOARD_RPC_ADDRESS.encode(),
324
+ f"{self.ip}:{self.grpc_port}".encode(),
325
+ True,
326
+ namespace=ray_constants.KV_NAMESPACE_DASHBOARD,
327
+ )
328
+
329
+ # Freeze signal after all modules loaded.
330
+ dashboard_utils.SignalManager.freeze()
331
+ concurrent_tasks = [
332
+ self._gcs_check_alive(),
333
+ _async_notify(),
334
+ DataOrganizer.purge(),
335
+ DataOrganizer.organize(self._executor),
336
+ ]
337
+ for m in modules:
338
+ concurrent_tasks.append(m.run(self.server))
339
+ if self.server:
340
+ concurrent_tasks.append(self.server.wait_for_termination())
341
+ await asyncio.gather(*concurrent_tasks)
342
+
343
+ if self.http_server:
344
+ await self.http_server.cleanup()
vllm/lib/python3.10/site-packages/ray/dashboard/http_server_agent.py ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+
3
+ from packaging.version import Version
4
+
5
+ import ray.dashboard.optional_utils as dashboard_optional_utils
6
+ from ray._private.utils import get_or_create_event_loop
7
+ from ray.dashboard.optional_deps import aiohttp, aiohttp_cors, hdrs
8
+
9
+ logger = logging.getLogger(__name__)
10
+ routes = dashboard_optional_utils.DashboardAgentRouteTable
11
+
12
+
13
+ class HttpServerAgent:
14
+ def __init__(self, ip, listen_port):
15
+ self.ip = ip
16
+ self.listen_port = listen_port
17
+ self.http_host = None
18
+ self.http_port = None
19
+ self.http_session = None
20
+ self.runner = None
21
+
22
+ async def start(self, modules):
23
+ # Create a http session for all modules.
24
+ # aiohttp<4.0.0 uses a 'loop' variable, aiohttp>=4.0.0 doesn't anymore
25
+ if Version(aiohttp.__version__) < Version("4.0.0"):
26
+ self.http_session = aiohttp.ClientSession(loop=get_or_create_event_loop())
27
+ else:
28
+ self.http_session = aiohttp.ClientSession()
29
+
30
+ # Bind routes for every module so that each module
31
+ # can use decorator-style routes.
32
+ for c in modules:
33
+ dashboard_optional_utils.DashboardAgentRouteTable.bind(c)
34
+
35
+ app = aiohttp.web.Application()
36
+ app.add_routes(routes=routes.bound_routes())
37
+
38
+ # Enable CORS on all routes.
39
+ cors = aiohttp_cors.setup(
40
+ app,
41
+ defaults={
42
+ "*": aiohttp_cors.ResourceOptions(
43
+ allow_credentials=True,
44
+ expose_headers="*",
45
+ allow_methods="*",
46
+ allow_headers=("Content-Type", "X-Header"),
47
+ )
48
+ },
49
+ )
50
+ for route in list(app.router.routes()):
51
+ cors.add(route)
52
+
53
+ self.runner = aiohttp.web.AppRunner(app)
54
+ await self.runner.setup()
55
+ try:
56
+ site = aiohttp.web.TCPSite(
57
+ self.runner,
58
+ "127.0.0.1" if self.ip == "127.0.0.1" else "0.0.0.0",
59
+ self.listen_port,
60
+ )
61
+ await site.start()
62
+ except OSError as e:
63
+ logger.error(
64
+ f"Agent port #{self.listen_port} already in use. "
65
+ "Failed to start agent. "
66
+ f"Ensure port #{self.listen_port} is available, and then try again."
67
+ )
68
+ raise e
69
+ self.http_host, self.http_port, *_ = site._server.sockets[0].getsockname()
70
+ logger.info(
71
+ "Dashboard agent http address: %s:%s", self.http_host, self.http_port
72
+ )
73
+
74
+ # Dump registered http routes.
75
+ dump_routes = [r for r in app.router.routes() if r.method != hdrs.METH_HEAD]
76
+ for r in dump_routes:
77
+ logger.info(r)
78
+ logger.info("Registered %s routes.", len(dump_routes))
79
+
80
+ async def cleanup(self):
81
+ # Wait for finish signal.
82
+ await self.runner.cleanup()
83
+ await self.http_session.close()
vllm/lib/python3.10/site-packages/ray/dashboard/http_server_head.py ADDED
@@ -0,0 +1,289 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import errno
3
+ import ipaddress
4
+ import logging
5
+ import os
6
+ import pathlib
7
+ import sys
8
+ import time
9
+ from math import floor
10
+
11
+ from packaging.version import Version
12
+
13
+ import ray
14
+ import ray.dashboard.optional_utils as dashboard_optional_utils
15
+ import ray.dashboard.timezone_utils as timezone_utils
16
+ import ray.dashboard.utils as dashboard_utils
17
+ from ray._private.usage.usage_lib import TagKey, record_extra_usage_tag
18
+ from ray._private.utils import get_or_create_event_loop
19
+ from ray.dashboard.dashboard_metrics import DashboardPrometheusMetrics
20
+
21
+ # All third-party dependencies that are not included in the minimal Ray
22
+ # installation must be included in this file. This allows us to determine if
23
+ # the agent has the necessary dependencies to be started.
24
+ from ray.dashboard.optional_deps import aiohttp, hdrs
25
+
26
+ # Logger for this module. It should be configured at the entry point
27
+ # into the program using Ray. Ray provides a default configuration at
28
+ # entry/init points.
29
+ logger = logging.getLogger(__name__)
30
+ routes = dashboard_optional_utils.DashboardHeadRouteTable
31
+
32
+ # Env var that enables follow_symlinks for serving UI static files.
33
+ # This is an advanced setting that should only be used with special Ray installations
34
+ # where the dashboard build files are symlinked to a different directory.
35
+ # This is not recommended for most users and can pose a security risk.
36
+ # Please reference the aiohttp docs here:
37
+ # https://docs.aiohttp.org/en/stable/web_reference.html#aiohttp.web.UrlDispatcher.add_static
38
+ ENV_VAR_FOLLOW_SYMLINKS = "RAY_DASHBOARD_BUILD_FOLLOW_SYMLINKS"
39
+ FOLLOW_SYMLINKS_ENABLED = os.environ.get(ENV_VAR_FOLLOW_SYMLINKS) == "1"
40
+ if FOLLOW_SYMLINKS_ENABLED:
41
+ logger.warning(
42
+ "Enabling RAY_DASHBOARD_BUILD_FOLLOW_SYMLINKS is not recommended as it "
43
+ "allows symlinks to directories outside the dashboard build folder. "
44
+ "You may accidentally expose files on your system outside of the "
45
+ "build directory."
46
+ )
47
+
48
+
49
+ def setup_static_dir():
50
+ build_dir = os.path.join(
51
+ os.path.dirname(os.path.abspath(__file__)), "client", "build"
52
+ )
53
+ module_name = os.path.basename(os.path.dirname(__file__))
54
+ if not os.path.isdir(build_dir):
55
+ raise dashboard_utils.FrontendNotFoundError(
56
+ errno.ENOENT,
57
+ "Dashboard build directory not found. If installing "
58
+ "from source, please follow the additional steps "
59
+ "required to build the dashboard"
60
+ f"(cd python/ray/{module_name}/client "
61
+ "&& npm ci "
62
+ "&& npm run build)",
63
+ build_dir,
64
+ )
65
+
66
+ static_dir = os.path.join(build_dir, "static")
67
+ routes.static("/static", static_dir, follow_symlinks=FOLLOW_SYMLINKS_ENABLED)
68
+ return build_dir
69
+
70
+
71
+ class HttpServerDashboardHead:
72
+ def __init__(
73
+ self,
74
+ ip: str,
75
+ http_host: str,
76
+ http_port: int,
77
+ http_port_retries: int,
78
+ gcs_address: str,
79
+ session_name: str,
80
+ metrics: DashboardPrometheusMetrics,
81
+ ):
82
+ self.ip = ip
83
+ self.http_host = http_host
84
+ self.http_port = http_port
85
+ self.http_port_retries = http_port_retries
86
+ self.head_node_ip = gcs_address.split(":")[0]
87
+ self.metrics = metrics
88
+ self._session_name = session_name
89
+
90
+ # Below attirubtes are filled after `run` API is invoked.
91
+ self.runner = None
92
+
93
+ # Setup Dashboard Routes
94
+ try:
95
+ build_dir = setup_static_dir()
96
+ logger.info("Setup static dir for dashboard: %s", build_dir)
97
+ except dashboard_utils.FrontendNotFoundError as ex:
98
+ # Not to raise FrontendNotFoundError due to NPM incompatibilities
99
+ # with Windows.
100
+ # Please refer to ci.sh::build_dashboard_front_end()
101
+ if sys.platform in ["win32", "cygwin"]:
102
+ logger.warning(ex)
103
+ else:
104
+ raise ex
105
+ dashboard_optional_utils.DashboardHeadRouteTable.bind(self)
106
+
107
+ # Create a http session for all modules.
108
+ # aiohttp<4.0.0 uses a 'loop' variable, aiohttp>=4.0.0 doesn't anymore
109
+ if Version(aiohttp.__version__) < Version("4.0.0"):
110
+ self.http_session = aiohttp.ClientSession(loop=get_or_create_event_loop())
111
+ else:
112
+ self.http_session = aiohttp.ClientSession()
113
+
114
+ @routes.get("/")
115
+ async def get_index(self, req) -> aiohttp.web.FileResponse:
116
+ try:
117
+ # This API will be no-op after the first report.
118
+ # Note: We always record the usage, but it is not reported
119
+ # if the usage stats is disabled.
120
+ record_extra_usage_tag(TagKey.DASHBOARD_USED, "True")
121
+ except Exception as e:
122
+ logger.warning(
123
+ "Failed to record the dashboard usage. "
124
+ "This error message is harmless and can be ignored. "
125
+ f"Error: {e}"
126
+ )
127
+ resp = aiohttp.web.FileResponse(
128
+ os.path.join(
129
+ os.path.dirname(os.path.abspath(__file__)), "client/build/index.html"
130
+ )
131
+ )
132
+ resp.headers["Cache-Control"] = "no-cache"
133
+ return resp
134
+
135
+ @routes.get("/favicon.ico")
136
+ async def get_favicon(self, req) -> aiohttp.web.FileResponse:
137
+ return aiohttp.web.FileResponse(
138
+ os.path.join(
139
+ os.path.dirname(os.path.abspath(__file__)), "client/build/favicon.ico"
140
+ )
141
+ )
142
+
143
+ @routes.get("/timezone")
144
+ async def get_timezone(self, req) -> aiohttp.web.Response:
145
+ try:
146
+ current_timezone = timezone_utils.get_current_timezone_info()
147
+ return aiohttp.web.json_response(current_timezone)
148
+
149
+ except Exception as e:
150
+ logger.error(f"Error getting timezone: {e}")
151
+ return aiohttp.web.Response(
152
+ status=500, text="Internal Server Error:" + str(e)
153
+ )
154
+
155
+ def get_address(self):
156
+ assert self.http_host and self.http_port
157
+ return self.http_host, self.http_port
158
+
159
+ @aiohttp.web.middleware
160
+ async def path_clean_middleware(self, request, handler):
161
+ if request.path.startswith("/static") or request.path.startswith("/logs"):
162
+ parent = pathlib.PurePosixPath(
163
+ "/logs" if request.path.startswith("/logs") else "/static"
164
+ )
165
+
166
+ # If the destination is not relative to the expected directory,
167
+ # then the user is attempting path traversal, so deny the request.
168
+ request_path = pathlib.PurePosixPath(
169
+ pathlib.posixpath.realpath(request.path)
170
+ )
171
+ if request_path != parent and parent not in request_path.parents:
172
+ logger.info(
173
+ f"Rejecting {request_path=} because it is not relative to {parent=}"
174
+ )
175
+ raise aiohttp.web.HTTPForbidden()
176
+ return await handler(request)
177
+
178
+ @aiohttp.web.middleware
179
+ async def browsers_no_post_put_middleware(self, request, handler):
180
+ if (
181
+ # A best effort test for browser traffic. All common browsers
182
+ # start with Mozilla at the time of writing.
183
+ request.headers["User-Agent"].startswith("Mozilla")
184
+ and request.method in [hdrs.METH_POST, hdrs.METH_PUT]
185
+ ):
186
+ return aiohttp.web.Response(
187
+ status=405, text="Method Not Allowed for browser traffic."
188
+ )
189
+
190
+ return await handler(request)
191
+
192
+ @aiohttp.web.middleware
193
+ async def metrics_middleware(self, request, handler):
194
+ start_time = time.monotonic()
195
+
196
+ try:
197
+ response = await handler(request)
198
+ status_tag = f"{floor(response.status / 100)}xx"
199
+ return response
200
+ except (Exception, asyncio.CancelledError):
201
+ status_tag = "5xx"
202
+ raise
203
+ finally:
204
+ resp_time = time.monotonic() - start_time
205
+ try:
206
+ self.metrics.metrics_request_duration.labels(
207
+ endpoint=handler.__name__,
208
+ http_status=status_tag,
209
+ Version=ray.__version__,
210
+ SessionName=self._session_name,
211
+ Component="dashboard",
212
+ ).observe(resp_time)
213
+ self.metrics.metrics_request_count.labels(
214
+ method=request.method,
215
+ endpoint=handler.__name__,
216
+ http_status=status_tag,
217
+ Version=ray.__version__,
218
+ SessionName=self._session_name,
219
+ Component="dashboard",
220
+ ).inc()
221
+ except Exception as e:
222
+ logger.exception(f"Error emitting api metrics: {e}")
223
+
224
+ @aiohttp.web.middleware
225
+ async def cache_control_static_middleware(self, request, handler):
226
+ if request.path.startswith("/static"):
227
+ response = await handler(request)
228
+ response.headers["Cache-Control"] = "max-age=31536000"
229
+ return response
230
+ return await handler(request)
231
+
232
+ async def run(self, modules):
233
+ # Bind http routes of each module.
234
+ for c in modules:
235
+ dashboard_optional_utils.DashboardHeadRouteTable.bind(c)
236
+
237
+ # Http server should be initialized after all modules loaded.
238
+ # working_dir uploads for job submission can be up to 100MiB.
239
+ app = aiohttp.web.Application(
240
+ client_max_size=100 * 1024**2,
241
+ middlewares=[
242
+ self.metrics_middleware,
243
+ self.path_clean_middleware,
244
+ self.browsers_no_post_put_middleware,
245
+ self.cache_control_static_middleware,
246
+ ],
247
+ )
248
+ app.add_routes(routes=routes.bound_routes())
249
+
250
+ self.runner = aiohttp.web.AppRunner(
251
+ app,
252
+ access_log_format=(
253
+ "%a %t '%r' %s %b bytes %D us " "'%{Referer}i' '%{User-Agent}i'"
254
+ ),
255
+ )
256
+ await self.runner.setup()
257
+ last_ex = None
258
+ for i in range(1 + self.http_port_retries):
259
+ try:
260
+ site = aiohttp.web.TCPSite(self.runner, self.http_host, self.http_port)
261
+ await site.start()
262
+ break
263
+ except OSError as e:
264
+ last_ex = e
265
+ self.http_port += 1
266
+ logger.warning("Try to use port %s: %s", self.http_port, e)
267
+ else:
268
+ raise Exception(
269
+ f"Failed to find a valid port for dashboard after "
270
+ f"{self.http_port_retries} retries: {last_ex}"
271
+ )
272
+ self.http_host, self.http_port, *_ = site._server.sockets[0].getsockname()
273
+ self.http_host = (
274
+ self.ip
275
+ if ipaddress.ip_address(self.http_host).is_unspecified
276
+ else self.http_host
277
+ )
278
+ logger.info(
279
+ "Dashboard head http address: %s:%s", self.http_host, self.http_port
280
+ )
281
+ # Dump registered http routes.
282
+ dump_routes = [r for r in app.router.routes() if r.method != hdrs.METH_HEAD]
283
+ for r in dump_routes:
284
+ logger.info(r)
285
+ logger.info("Registered %s routes.", len(dump_routes))
286
+
287
+ async def cleanup(self):
288
+ # Wait for finish signal.
289
+ await self.runner.cleanup()
vllm/lib/python3.10/site-packages/ray/dashboard/k8s_utils.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+
3
+ from ray._private.utils import get_num_cpus
4
+
5
+ logger = logging.getLogger(__name__)
6
+
7
+ CPU_USAGE_PATH = "/sys/fs/cgroup/cpuacct/cpuacct.usage"
8
+ CPU_USAGE_PATH_V2 = "/sys/fs/cgroup/cpu.stat"
9
+ PROC_STAT_PATH = "/proc/stat"
10
+
11
+ container_num_cpus = None
12
+ host_num_cpus = None
13
+
14
+ last_cpu_usage = None
15
+ last_system_usage = None
16
+
17
+
18
+ def cpu_percent():
19
+ """Estimate CPU usage percent for Ray pod managed by Kubernetes
20
+ Operator.
21
+
22
+ Computed by the following steps
23
+ (1) Replicate the logic used by 'docker stats' cli command.
24
+ See https://github.com/docker/cli/blob/c0a6b1c7b30203fbc28cd619acb901a95a80e30e/cli/command/container/stats_helpers.go#L166.
25
+ (2) Divide by the number of CPUs available to the container, so that
26
+ e.g. full capacity use of 2 CPUs will read as 100%,
27
+ rather than 200%.
28
+
29
+ Step (1) above works by
30
+ dividing delta in cpu usage by
31
+ delta in total host cpu usage, averaged over host's cpus.
32
+
33
+ Since deltas are not initially available, return 0.0 on first call.
34
+ """ # noqa
35
+ global last_system_usage
36
+ global last_cpu_usage
37
+ try:
38
+ cpu_usage = _cpu_usage()
39
+ system_usage = _system_usage()
40
+ # Return 0.0 on first call.
41
+ if last_system_usage is None:
42
+ cpu_percent = 0.0
43
+ else:
44
+ cpu_delta = cpu_usage - last_cpu_usage
45
+ # "System time passed." (Typically close to clock time.)
46
+ system_delta = (system_usage - last_system_usage) / _host_num_cpus()
47
+
48
+ quotient = cpu_delta / system_delta
49
+ cpu_percent = round(quotient * 100 / get_num_cpus(), 1)
50
+ last_system_usage = system_usage
51
+ last_cpu_usage = cpu_usage
52
+ # Computed percentage might be slightly above 100%.
53
+ return min(cpu_percent, 100.0)
54
+ except Exception:
55
+ logger.exception("Error computing CPU usage of Ray Kubernetes pod.")
56
+ return 0.0
57
+
58
+
59
+ def _cpu_usage():
60
+ """Compute total cpu usage of the container in nanoseconds
61
+ by reading from cpuacct in cgroups v1 or cpu.stat in cgroups v2."""
62
+ try:
63
+ # cgroups v1
64
+ return int(open(CPU_USAGE_PATH).read())
65
+ except FileNotFoundError:
66
+ # cgroups v2
67
+ cpu_stat_text = open(CPU_USAGE_PATH_V2).read()
68
+ # e.g. "usage_usec 16089294616"
69
+ cpu_stat_first_line = cpu_stat_text.split("\n")[0]
70
+ # get the second word of the first line, cast as an integer
71
+ # this is the CPU usage is microseconds
72
+ cpu_usec = int(cpu_stat_first_line.split()[1])
73
+ # Convert to nanoseconds and return.
74
+ return cpu_usec * 1000
75
+
76
+
77
+ def _system_usage():
78
+ """
79
+ Computes total CPU usage of the host in nanoseconds.
80
+
81
+ Logic taken from here:
82
+ https://github.com/moby/moby/blob/b42ac8d370a8ef8ec720dff0ca9dfb3530ac0a6a/daemon/stats/collector_unix.go#L31
83
+
84
+ See also the /proc/stat entry here:
85
+ https://man7.org/linux/man-pages/man5/proc.5.html
86
+ """ # noqa
87
+ cpu_summary_str = open(PROC_STAT_PATH).read().split("\n")[0]
88
+ parts = cpu_summary_str.split()
89
+ assert parts[0] == "cpu"
90
+ usage_data = parts[1:8]
91
+ total_clock_ticks = sum(int(entry) for entry in usage_data)
92
+ # 100 clock ticks per second, 10^9 ns per second
93
+ usage_ns = total_clock_ticks * 10**7
94
+ return usage_ns
95
+
96
+
97
+ def _host_num_cpus():
98
+ """Number of physical CPUs, obtained by parsing /proc/stat."""
99
+ global host_num_cpus
100
+ if host_num_cpus is None:
101
+ proc_stat_lines = open(PROC_STAT_PATH).read().split("\n")
102
+ split_proc_stat_lines = [line.split() for line in proc_stat_lines]
103
+ cpu_lines = [
104
+ split_line
105
+ for split_line in split_proc_stat_lines
106
+ if len(split_line) > 0 and "cpu" in split_line[0]
107
+ ]
108
+ # Number of lines starting with a word including 'cpu', subtracting
109
+ # 1 for the first summary line.
110
+ host_num_cpus = len(cpu_lines) - 1
111
+ return host_num_cpus
vllm/lib/python3.10/site-packages/ray/dashboard/memory_utils.py ADDED
@@ -0,0 +1,524 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import base64
2
+ import logging
3
+ from collections import defaultdict
4
+ from enum import Enum
5
+ from typing import List
6
+
7
+ import ray
8
+ from ray._private.internal_api import node_stats
9
+ from ray._raylet import ActorID, JobID, TaskID
10
+
11
+ logger = logging.getLogger(__name__)
12
+
13
+ # These values are used to calculate if objectRefs are actor handles.
14
+ TASKID_BYTES_SIZE = TaskID.size()
15
+ ACTORID_BYTES_SIZE = ActorID.size()
16
+ JOBID_BYTES_SIZE = JobID.size()
17
+
18
+
19
+ def decode_object_ref_if_needed(object_ref: str) -> bytes:
20
+ """Decode objectRef bytes string.
21
+
22
+ gRPC reply contains an objectRef that is encodded by Base64.
23
+ This function is used to decode the objectRef.
24
+ Note that there are times that objectRef is already decoded as
25
+ a hex string. In this case, just convert it to a binary number.
26
+ """
27
+ if object_ref.endswith("="):
28
+ # If the object ref ends with =, that means it is base64 encoded.
29
+ # Object refs will always have = as a padding
30
+ # when it is base64 encoded because objectRef is always 20B.
31
+ return base64.standard_b64decode(object_ref)
32
+ else:
33
+ return ray._private.utils.hex_to_binary(object_ref)
34
+
35
+
36
+ class SortingType(Enum):
37
+ PID = 1
38
+ OBJECT_SIZE = 3
39
+ REFERENCE_TYPE = 4
40
+
41
+
42
+ class GroupByType(Enum):
43
+ NODE_ADDRESS = "node"
44
+ STACK_TRACE = "stack_trace"
45
+
46
+
47
+ class ReferenceType(Enum):
48
+ # We don't use enum because enum is not json serializable.
49
+ ACTOR_HANDLE = "ACTOR_HANDLE"
50
+ PINNED_IN_MEMORY = "PINNED_IN_MEMORY"
51
+ LOCAL_REFERENCE = "LOCAL_REFERENCE"
52
+ USED_BY_PENDING_TASK = "USED_BY_PENDING_TASK"
53
+ CAPTURED_IN_OBJECT = "CAPTURED_IN_OBJECT"
54
+ UNKNOWN_STATUS = "UNKNOWN_STATUS"
55
+
56
+
57
+ def get_sorting_type(sort_by: str):
58
+ """Translate string input into SortingType instance"""
59
+ sort_by = sort_by.upper()
60
+ if sort_by == "PID":
61
+ return SortingType.PID
62
+ elif sort_by == "OBJECT_SIZE":
63
+ return SortingType.OBJECT_SIZE
64
+ elif sort_by == "REFERENCE_TYPE":
65
+ return SortingType.REFERENCE_TYPE
66
+ else:
67
+ raise Exception(
68
+ "The sort-by input provided is not one of\
69
+ PID, OBJECT_SIZE, or REFERENCE_TYPE."
70
+ )
71
+
72
+
73
+ def get_group_by_type(group_by: str):
74
+ """Translate string input into GroupByType instance"""
75
+ group_by = group_by.upper()
76
+ if group_by == "NODE_ADDRESS":
77
+ return GroupByType.NODE_ADDRESS
78
+ elif group_by == "STACK_TRACE":
79
+ return GroupByType.STACK_TRACE
80
+ else:
81
+ raise Exception(
82
+ "The group-by input provided is not one of\
83
+ NODE_ADDRESS or STACK_TRACE."
84
+ )
85
+
86
+
87
+ class MemoryTableEntry:
88
+ def __init__(
89
+ self, *, object_ref: dict, node_address: str, is_driver: bool, pid: int
90
+ ):
91
+ # worker info
92
+ self.is_driver = is_driver
93
+ self.pid = pid
94
+ self.node_address = node_address
95
+
96
+ # object info
97
+ self.task_status = object_ref.get("taskStatus", "?")
98
+ if self.task_status == "NIL":
99
+ self.task_status = "-"
100
+ self.attempt_number = int(object_ref.get("attemptNumber", 0)) + 1
101
+ self.object_size = int(object_ref.get("objectSize", -1))
102
+ self.call_site = object_ref.get("callSite", "<Unknown>")
103
+ if len(self.call_site) == 0:
104
+ self.call_site = "disabled"
105
+ self.object_ref = ray.ObjectRef(
106
+ decode_object_ref_if_needed(object_ref["objectId"])
107
+ )
108
+
109
+ # reference info
110
+ self.local_ref_count = int(object_ref.get("localRefCount", 0))
111
+ self.pinned_in_memory = bool(object_ref.get("pinnedInMemory", False))
112
+ self.submitted_task_ref_count = int(object_ref.get("submittedTaskRefCount", 0))
113
+ self.contained_in_owned = [
114
+ ray.ObjectRef(decode_object_ref_if_needed(object_ref))
115
+ for object_ref in object_ref.get("containedInOwned", [])
116
+ ]
117
+ self.reference_type = self._get_reference_type()
118
+
119
+ def is_valid(self) -> bool:
120
+ # If the entry doesn't have a reference type or some invalid state,
121
+ # (e.g., no object ref presented), it is considered invalid.
122
+ if (
123
+ not self.pinned_in_memory
124
+ and self.local_ref_count == 0
125
+ and self.submitted_task_ref_count == 0
126
+ and len(self.contained_in_owned) == 0
127
+ ):
128
+ return False
129
+ elif self.object_ref.is_nil():
130
+ return False
131
+ else:
132
+ return True
133
+
134
+ def group_key(self, group_by_type: GroupByType) -> str:
135
+ if group_by_type == GroupByType.NODE_ADDRESS:
136
+ return self.node_address
137
+ elif group_by_type == GroupByType.STACK_TRACE:
138
+ return self.call_site
139
+ else:
140
+ raise ValueError(f"group by type {group_by_type} is invalid.")
141
+
142
+ def _get_reference_type(self) -> str:
143
+ if self._is_object_ref_actor_handle():
144
+ return ReferenceType.ACTOR_HANDLE.value
145
+ if self.pinned_in_memory:
146
+ return ReferenceType.PINNED_IN_MEMORY.value
147
+ elif self.submitted_task_ref_count > 0:
148
+ return ReferenceType.USED_BY_PENDING_TASK.value
149
+ elif self.local_ref_count > 0:
150
+ return ReferenceType.LOCAL_REFERENCE.value
151
+ elif len(self.contained_in_owned) > 0:
152
+ return ReferenceType.CAPTURED_IN_OBJECT.value
153
+ else:
154
+ return ReferenceType.UNKNOWN_STATUS.value
155
+
156
+ def _is_object_ref_actor_handle(self) -> bool:
157
+ object_ref_hex = self.object_ref.hex()
158
+
159
+ # We need to multiply 2 because we need bits size instead of bytes size.
160
+ taskid_random_bits_size = (TASKID_BYTES_SIZE - ACTORID_BYTES_SIZE) * 2
161
+ actorid_random_bits_size = (ACTORID_BYTES_SIZE - JOBID_BYTES_SIZE) * 2
162
+
163
+ # random (8B) | ActorID(6B) | flag (2B) | index (6B)
164
+ # ActorID(6B) == ActorRandomByte(4B) + JobID(2B)
165
+ # If random bytes are all 'f', but ActorRandomBytes
166
+ # are not all 'f', that means it is an actor creation
167
+ # task, which is an actor handle.
168
+ random_bits = object_ref_hex[:taskid_random_bits_size]
169
+ actor_random_bits = object_ref_hex[
170
+ taskid_random_bits_size : taskid_random_bits_size + actorid_random_bits_size
171
+ ]
172
+ if random_bits == "f" * 16 and not actor_random_bits == "f" * 24:
173
+ return True
174
+ else:
175
+ return False
176
+
177
+ def as_dict(self):
178
+ return {
179
+ "object_ref": self.object_ref.hex(),
180
+ "pid": self.pid,
181
+ "node_ip_address": self.node_address,
182
+ "object_size": self.object_size,
183
+ "reference_type": self.reference_type,
184
+ "call_site": self.call_site,
185
+ "task_status": self.task_status,
186
+ "attempt_number": self.attempt_number,
187
+ "local_ref_count": self.local_ref_count,
188
+ "pinned_in_memory": self.pinned_in_memory,
189
+ "submitted_task_ref_count": self.submitted_task_ref_count,
190
+ "contained_in_owned": [
191
+ object_ref.hex() for object_ref in self.contained_in_owned
192
+ ],
193
+ "type": "Driver" if self.is_driver else "Worker",
194
+ }
195
+
196
+ def __str__(self):
197
+ return self.__repr__()
198
+
199
+ def __repr__(self):
200
+ return str(self.as_dict())
201
+
202
+
203
+ class MemoryTable:
204
+ def __init__(
205
+ self,
206
+ entries: List[MemoryTableEntry],
207
+ group_by_type: GroupByType = GroupByType.NODE_ADDRESS,
208
+ sort_by_type: SortingType = SortingType.PID,
209
+ ):
210
+ self.table = entries
211
+ # Group is a list of memory tables grouped by a group key.
212
+ self.group = {}
213
+ self.summary = defaultdict(int)
214
+ # NOTE YOU MUST SORT TABLE BEFORE GROUPING.
215
+ # self._group_by(..)._sort_by(..) != self._sort_by(..)._group_by(..)
216
+ if group_by_type and sort_by_type:
217
+ self.setup(group_by_type, sort_by_type)
218
+ elif group_by_type:
219
+ self._group_by(group_by_type)
220
+ elif sort_by_type:
221
+ self._sort_by(sort_by_type)
222
+
223
+ def setup(self, group_by_type: GroupByType, sort_by_type: SortingType):
224
+ """Setup memory table.
225
+
226
+ This will sort entries first and group them after.
227
+ Sort order will be still kept.
228
+ """
229
+ self._sort_by(sort_by_type)._group_by(group_by_type)
230
+ for group_memory_table in self.group.values():
231
+ group_memory_table.summarize()
232
+ self.summarize()
233
+ return self
234
+
235
+ def insert_entry(self, entry: MemoryTableEntry):
236
+ self.table.append(entry)
237
+
238
+ def summarize(self):
239
+ # Reset summary.
240
+ total_object_size = 0
241
+ total_local_ref_count = 0
242
+ total_pinned_in_memory = 0
243
+ total_used_by_pending_task = 0
244
+ total_captured_in_objects = 0
245
+ total_actor_handles = 0
246
+
247
+ for entry in self.table:
248
+ if entry.object_size > 0:
249
+ total_object_size += entry.object_size
250
+ if entry.reference_type == ReferenceType.LOCAL_REFERENCE.value:
251
+ total_local_ref_count += 1
252
+ elif entry.reference_type == ReferenceType.PINNED_IN_MEMORY.value:
253
+ total_pinned_in_memory += 1
254
+ elif entry.reference_type == ReferenceType.USED_BY_PENDING_TASK.value:
255
+ total_used_by_pending_task += 1
256
+ elif entry.reference_type == ReferenceType.CAPTURED_IN_OBJECT.value:
257
+ total_captured_in_objects += 1
258
+ elif entry.reference_type == ReferenceType.ACTOR_HANDLE.value:
259
+ total_actor_handles += 1
260
+
261
+ self.summary = {
262
+ "total_object_size": total_object_size,
263
+ "total_local_ref_count": total_local_ref_count,
264
+ "total_pinned_in_memory": total_pinned_in_memory,
265
+ "total_used_by_pending_task": total_used_by_pending_task,
266
+ "total_captured_in_objects": total_captured_in_objects,
267
+ "total_actor_handles": total_actor_handles,
268
+ }
269
+ return self
270
+
271
+ def _sort_by(self, sorting_type: SortingType):
272
+ if sorting_type == SortingType.PID:
273
+ self.table.sort(key=lambda entry: entry.pid)
274
+ elif sorting_type == SortingType.OBJECT_SIZE:
275
+ self.table.sort(key=lambda entry: entry.object_size)
276
+ elif sorting_type == SortingType.REFERENCE_TYPE:
277
+ self.table.sort(key=lambda entry: entry.reference_type)
278
+ else:
279
+ raise ValueError(f"Give sorting type: {sorting_type} is invalid.")
280
+ return self
281
+
282
+ def _group_by(self, group_by_type: GroupByType):
283
+ """Group entries and summarize the result.
284
+
285
+ NOTE: Each group is another MemoryTable.
286
+ """
287
+ # Reset group
288
+ self.group = {}
289
+
290
+ # Build entries per group.
291
+ group = defaultdict(list)
292
+ for entry in self.table:
293
+ group[entry.group_key(group_by_type)].append(entry)
294
+
295
+ # Build a group table.
296
+ for group_key, entries in group.items():
297
+ self.group[group_key] = MemoryTable(
298
+ entries, group_by_type=None, sort_by_type=None
299
+ )
300
+ for group_key, group_memory_table in self.group.items():
301
+ group_memory_table.summarize()
302
+ return self
303
+
304
+ def as_dict(self):
305
+ return {
306
+ "summary": self.summary,
307
+ "group": {
308
+ group_key: {
309
+ "entries": group_memory_table.get_entries(),
310
+ "summary": group_memory_table.summary,
311
+ }
312
+ for group_key, group_memory_table in self.group.items()
313
+ },
314
+ }
315
+
316
+ def get_entries(self) -> List[dict]:
317
+ return [entry.as_dict() for entry in self.table]
318
+
319
+ def __repr__(self):
320
+ return str(self.as_dict())
321
+
322
+ def __str__(self):
323
+ return self.__repr__()
324
+
325
+
326
+ def construct_memory_table(
327
+ workers_stats: List,
328
+ group_by: GroupByType = GroupByType.NODE_ADDRESS,
329
+ sort_by=SortingType.OBJECT_SIZE,
330
+ ) -> MemoryTable:
331
+ memory_table_entries = []
332
+ for core_worker_stats in workers_stats:
333
+ pid = core_worker_stats["pid"]
334
+ is_driver = core_worker_stats.get("workerType") == "DRIVER"
335
+ node_address = core_worker_stats["ipAddress"]
336
+ object_refs = core_worker_stats.get("objectRefs", [])
337
+
338
+ for object_ref in object_refs:
339
+ memory_table_entry = MemoryTableEntry(
340
+ object_ref=object_ref,
341
+ node_address=node_address,
342
+ is_driver=is_driver,
343
+ pid=pid,
344
+ )
345
+ if memory_table_entry.is_valid():
346
+ memory_table_entries.append(memory_table_entry)
347
+ memory_table = MemoryTable(
348
+ memory_table_entries, group_by_type=group_by, sort_by_type=sort_by
349
+ )
350
+ return memory_table
351
+
352
+
353
+ def track_reference_size(group):
354
+ """Returns dictionary mapping reference type
355
+ to memory usage for a given memory table group."""
356
+ d = defaultdict(int)
357
+ table_name = {
358
+ "LOCAL_REFERENCE": "total_local_ref_count",
359
+ "PINNED_IN_MEMORY": "total_pinned_in_memory",
360
+ "USED_BY_PENDING_TASK": "total_used_by_pending_task",
361
+ "CAPTURED_IN_OBJECT": "total_captured_in_objects",
362
+ "ACTOR_HANDLE": "total_actor_handles",
363
+ }
364
+ for entry in group["entries"]:
365
+ size = entry["object_size"]
366
+ if size == -1:
367
+ # size not recorded
368
+ size = 0
369
+ d[table_name[entry["reference_type"]]] += size
370
+ return d
371
+
372
+
373
+ def memory_summary(
374
+ state,
375
+ group_by="NODE_ADDRESS",
376
+ sort_by="OBJECT_SIZE",
377
+ line_wrap=True,
378
+ unit="B",
379
+ num_entries=None,
380
+ ) -> str:
381
+ # Get terminal size
382
+ import shutil
383
+
384
+ from ray.dashboard.modules.node.node_head import node_stats_to_dict
385
+
386
+ size = shutil.get_terminal_size((80, 20)).columns
387
+ line_wrap_threshold = 137
388
+
389
+ # Unit conversions
390
+ units = {"B": 10**0, "KB": 10**3, "MB": 10**6, "GB": 10**9}
391
+
392
+ # Fetch core memory worker stats, store as a dictionary
393
+ core_worker_stats = []
394
+ for raylet in state.node_table():
395
+ if not raylet["Alive"]:
396
+ continue
397
+ try:
398
+ stats = node_stats_to_dict(
399
+ node_stats(raylet["NodeManagerAddress"], raylet["NodeManagerPort"])
400
+ )
401
+ except RuntimeError:
402
+ continue
403
+ core_worker_stats.extend(stats["coreWorkersStats"])
404
+ assert type(stats) is dict and "coreWorkersStats" in stats
405
+
406
+ # Build memory table with "group_by" and "sort_by" parameters
407
+ group_by, sort_by = get_group_by_type(group_by), get_sorting_type(sort_by)
408
+ memory_table = construct_memory_table(
409
+ core_worker_stats, group_by, sort_by
410
+ ).as_dict()
411
+ assert "summary" in memory_table and "group" in memory_table
412
+
413
+ # Build memory summary
414
+ mem = ""
415
+ group_by, sort_by = group_by.name.lower().replace(
416
+ "_", " "
417
+ ), sort_by.name.lower().replace("_", " ")
418
+ summary_labels = [
419
+ "Mem Used by Objects",
420
+ "Local References",
421
+ "Pinned",
422
+ "Used by task",
423
+ "Captured in Objects",
424
+ "Actor Handles",
425
+ ]
426
+ summary_string = "{:<19} {:<16} {:<12} {:<13} {:<19} {:<13}\n"
427
+
428
+ object_ref_labels = [
429
+ "IP Address",
430
+ "PID",
431
+ "Type",
432
+ "Call Site",
433
+ "Status",
434
+ "Attampt",
435
+ "Size",
436
+ "Reference Type",
437
+ "Object Ref",
438
+ ]
439
+ object_ref_string = "{:<13} | {:<8} | {:<7} | {:<9} \
440
+ | {:<9} | {:<8} | {:<8} | {:<14} | {:<10}\n"
441
+
442
+ if size > line_wrap_threshold and line_wrap:
443
+ object_ref_string = "{:<15} {:<5} {:<6} {:<22} {:<14} {:<8} {:<6} \
444
+ {:<18} {:<56}\n"
445
+
446
+ mem += f"Grouping by {group_by}...\
447
+ Sorting by {sort_by}...\
448
+ Display {num_entries if num_entries is not None else 'all'}\
449
+ entries per group...\n\n\n"
450
+
451
+ for key, group in memory_table["group"].items():
452
+ # Group summary
453
+ summary = group["summary"]
454
+ ref_size = track_reference_size(group)
455
+ for k, v in summary.items():
456
+ if k == "total_object_size":
457
+ summary[k] = str(v / units[unit]) + f" {unit}"
458
+ else:
459
+ summary[k] = str(v) + f", ({ref_size[k] / units[unit]} {unit})"
460
+ mem += f"--- Summary for {group_by}: {key} ---\n"
461
+ mem += summary_string.format(*summary_labels)
462
+ mem += summary_string.format(*summary.values()) + "\n"
463
+
464
+ # Memory table per group
465
+ mem += f"--- Object references for {group_by}: {key} ---\n"
466
+ mem += object_ref_string.format(*object_ref_labels)
467
+ n = 1 # Counter for num entries per group
468
+ for entry in group["entries"]:
469
+ if num_entries is not None and n > num_entries:
470
+ break
471
+ entry["object_size"] = (
472
+ str(entry["object_size"] / units[unit]) + f" {unit}"
473
+ if entry["object_size"] > -1
474
+ else "?"
475
+ )
476
+ num_lines = 1
477
+ if size > line_wrap_threshold and line_wrap:
478
+ call_site_length = 22
479
+ if len(entry["call_site"]) == 0:
480
+ entry["call_site"] = ["disabled"]
481
+ else:
482
+ entry["call_site"] = [
483
+ entry["call_site"][i : i + call_site_length]
484
+ for i in range(0, len(entry["call_site"]), call_site_length)
485
+ ]
486
+
487
+ task_status_length = 12
488
+ entry["task_status"] = [
489
+ entry["task_status"][i : i + task_status_length]
490
+ for i in range(0, len(entry["task_status"]), task_status_length)
491
+ ]
492
+ num_lines = max(len(entry["call_site"]), len(entry["task_status"]))
493
+
494
+ else:
495
+ mem += "\n"
496
+ object_ref_values = [
497
+ entry["node_ip_address"],
498
+ entry["pid"],
499
+ entry["type"],
500
+ entry["call_site"],
501
+ entry["task_status"],
502
+ entry["attempt_number"],
503
+ entry["object_size"],
504
+ entry["reference_type"],
505
+ entry["object_ref"],
506
+ ]
507
+ for i in range(len(object_ref_values)):
508
+ if not isinstance(object_ref_values[i], list):
509
+ object_ref_values[i] = [object_ref_values[i]]
510
+ object_ref_values[i].extend(
511
+ ["" for x in range(num_lines - len(object_ref_values[i]))]
512
+ )
513
+ for i in range(num_lines):
514
+ row = [elem[i] for elem in object_ref_values]
515
+ mem += object_ref_string.format(*row)
516
+ mem += "\n"
517
+ n += 1
518
+
519
+ mem += (
520
+ "To record callsite information for each ObjectRef created, set "
521
+ "env variable RAY_record_ref_creation_sites=1\n\n"
522
+ )
523
+
524
+ return mem
vllm/lib/python3.10/site-packages/ray/dashboard/modules/__init__.py ADDED
File without changes
vllm/lib/python3.10/site-packages/ray/dashboard/modules/actor/__init__.py ADDED
File without changes
vllm/lib/python3.10/site-packages/ray/dashboard/modules/actor/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (177 Bytes). View file
 
vllm/lib/python3.10/site-packages/ray/dashboard/modules/actor/__pycache__/actor_consts.cpython-310.pyc ADDED
Binary file (325 Bytes). View file
 
vllm/lib/python3.10/site-packages/ray/dashboard/modules/actor/__pycache__/actor_head.cpython-310.pyc ADDED
Binary file (10.7 kB). View file
 
vllm/lib/python3.10/site-packages/ray/dashboard/modules/actor/actor_consts.py ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ import ray
2
+
3
+ ACTOR_CHANNEL = "ACTOR"
4
+ NIL_NODE_ID = ray.NodeID.nil().hex()
5
+ RETRY_GET_ALL_ACTOR_INFO_INTERVAL_SECONDS = 1
vllm/lib/python3.10/site-packages/ray/dashboard/modules/actor/actor_head.py ADDED
@@ -0,0 +1,356 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import abc
2
+ import asyncio
3
+ import logging
4
+ import os
5
+ from collections import defaultdict, deque
6
+ from concurrent.futures import ThreadPoolExecutor
7
+ from typing import Any, Dict, Optional
8
+
9
+ import aiohttp.web
10
+
11
+ import ray
12
+ import ray.dashboard.optional_utils as dashboard_optional_utils
13
+ import ray.dashboard.utils as dashboard_utils
14
+ from ray import ActorID
15
+ from ray._private.gcs_pubsub import GcsAioActorSubscriber
16
+ from ray._private.utils import get_or_create_event_loop
17
+ from ray.core.generated import gcs_pb2, gcs_service_pb2, gcs_service_pb2_grpc
18
+ from ray.dashboard.consts import GCS_RPC_TIMEOUT_SECONDS
19
+ from ray.dashboard.datacenter import DataOrganizer, DataSource
20
+ from ray.dashboard.modules.actor import actor_consts
21
+
22
+ logger = logging.getLogger(__name__)
23
+ routes = dashboard_optional_utils.DashboardHeadRouteTable
24
+
25
+ MAX_DESTROYED_ACTORS_TO_CACHE = max(
26
+ 0, ray._config.maximum_gcs_destroyed_actor_cached_count()
27
+ )
28
+
29
+ ACTOR_CLEANUP_FREQUENCY = 1 # seconds
30
+
31
+
32
+ ACTOR_TABLE_STATE_COLUMNS = (
33
+ "state",
34
+ "address",
35
+ "numRestarts",
36
+ "timestamp",
37
+ "pid",
38
+ "exitDetail",
39
+ "startTime",
40
+ "endTime",
41
+ "reprName",
42
+ )
43
+
44
+
45
+ def actor_table_data_to_dict(message):
46
+ orig_message = dashboard_utils.message_to_dict(
47
+ message,
48
+ {
49
+ "actorId",
50
+ "parentId",
51
+ "jobId",
52
+ "workerId",
53
+ "rayletId",
54
+ "callerId",
55
+ "taskId",
56
+ "parentTaskId",
57
+ "sourceActorId",
58
+ "placementGroupId",
59
+ },
60
+ always_print_fields_with_no_presence=True,
61
+ )
62
+ # The complete schema for actor table is here:
63
+ # src/ray/protobuf/gcs.proto
64
+ # It is super big and for dashboard, we don't need that much information.
65
+ # Only preserve the necessary ones here for memory usage.
66
+ fields = {
67
+ "actorId",
68
+ "jobId",
69
+ "pid",
70
+ "address",
71
+ "state",
72
+ "name",
73
+ "numRestarts",
74
+ "timestamp",
75
+ "className",
76
+ "startTime",
77
+ "endTime",
78
+ "reprName",
79
+ "placementGroupId",
80
+ }
81
+ light_message = {k: v for (k, v) in orig_message.items() if k in fields}
82
+ light_message["actorClass"] = orig_message["className"]
83
+ exit_detail = "-"
84
+ if "deathCause" in orig_message:
85
+ context = orig_message["deathCause"]
86
+ if "actorDiedErrorContext" in context:
87
+ exit_detail = context["actorDiedErrorContext"]["errorMessage"] # noqa
88
+ elif "runtimeEnvFailedContext" in context:
89
+ exit_detail = context["runtimeEnvFailedContext"]["errorMessage"] # noqa
90
+ elif "actorUnschedulableContext" in context:
91
+ exit_detail = context["actorUnschedulableContext"]["errorMessage"] # noqa
92
+ elif "creationTaskFailureContext" in context:
93
+ exit_detail = context["creationTaskFailureContext"][
94
+ "formattedExceptionString"
95
+ ] # noqa
96
+ light_message["exitDetail"] = exit_detail
97
+ light_message["startTime"] = int(light_message["startTime"])
98
+ light_message["endTime"] = int(light_message["endTime"])
99
+ light_message["requiredResources"] = dict(message.required_resources)
100
+
101
+ return light_message
102
+
103
+
104
+ class GetAllActorInfoClient(abc.ABC):
105
+ """
106
+ Gets all actor info from GCS via gRPC ActorInfoGcsService.GetAllActorInfo.
107
+ It makes the call via GcsAioClient or a direct gRPC stub, depends on the env var
108
+ RAY_USE_OLD_GCS_CLIENT.
109
+ """
110
+
111
+ @classmethod
112
+ def create(cls, *args, **kwargs):
113
+ use_old_client = os.getenv("RAY_USE_OLD_GCS_CLIENT") == "1"
114
+ if use_old_client:
115
+ return GetAllActorInfoFromGrpc(*args, **kwargs)
116
+ else:
117
+ return GetAllActorInfoFromNewGcsClient(*args, **kwargs)
118
+
119
+ @abc.abstractmethod
120
+ def __call__(self, *, timeout_s: int, state: Optional[str] = None):
121
+ pass
122
+
123
+
124
+ class GetAllActorInfoFromNewGcsClient(GetAllActorInfoClient):
125
+ def __init__(self, dashboard_head):
126
+ self.gcs_aio_client = dashboard_head.gcs_aio_client
127
+
128
+ async def __call__(
129
+ self, *, timeout, state: Optional[str] = None
130
+ ) -> Dict[ActorID, gcs_pb2.ActorTableData]:
131
+ return await self.gcs_aio_client.get_all_actor_info(
132
+ timeout=timeout, actor_state_name=state
133
+ )
134
+
135
+
136
+ class GetAllActorInfoFromGrpc(GetAllActorInfoClient):
137
+ def __init__(self, dashboard_head):
138
+ gcs_channel = dashboard_head.aiogrpc_gcs_channel
139
+ self._gcs_actor_info_stub = gcs_service_pb2_grpc.ActorInfoGcsServiceStub(
140
+ gcs_channel
141
+ )
142
+
143
+ async def __call__(
144
+ self, *, timeout, state: Optional[str] = None
145
+ ) -> Dict[ActorID, gcs_pb2.ActorTableData]:
146
+ request = gcs_service_pb2.GetAllActorInfoRequest()
147
+
148
+ reply = await self._gcs_actor_info_stub.GetAllActorInfo(
149
+ request,
150
+ timeout=timeout,
151
+ filters=gcs_service_pb2.GetAllActorInfoRequest.Filters(state=state)
152
+ if state
153
+ else None,
154
+ )
155
+
156
+ if reply.status.code != 0:
157
+ raise Exception(f"Failed to GetAllActorInfo: {reply.status.message}")
158
+
159
+ return {
160
+ ActorID(message.actor_id): message for message in reply.actor_table_data
161
+ }
162
+
163
+
164
+ class ActorHead(dashboard_utils.DashboardHeadModule):
165
+ def __init__(self, dashboard_head):
166
+ super().__init__(dashboard_head)
167
+
168
+ self._gcs_actor_channel_subscriber = None
169
+ self.get_all_actor_info_client = None
170
+ # A queue of dead actors in order of when they died
171
+ self.destroyed_actors_queue = deque()
172
+
173
+ # -- Internal state --
174
+ self._loop = get_or_create_event_loop()
175
+ # NOTE: This executor is intentionally constrained to just 1 thread to
176
+ # limit its concurrency, therefore reducing potential for GIL contention
177
+ self._executor = ThreadPoolExecutor(
178
+ max_workers=1, thread_name_prefix="actor_head_executor"
179
+ )
180
+
181
+ async def _update_actors(self):
182
+ """
183
+ Processes actor info. First gets all actors from GCS, then subscribes to
184
+ actor updates. For each actor update, updates DataSource.node_actors and
185
+ DataSource.actors.
186
+ """
187
+
188
+ # To prevent Time-of-check to time-of-use issue [1], the get-all-actor-info
189
+ # happens after the subscription. That is, an update between get-all-actor-info
190
+ # and the subscription is not missed.
191
+ #
192
+ # [1] https://en.wikipedia.org/wiki/Time-of-check_to_time-of-use
193
+ gcs_addr = self._dashboard_head.gcs_address
194
+ actor_channel_subscriber = GcsAioActorSubscriber(address=gcs_addr)
195
+ await actor_channel_subscriber.subscribe()
196
+
197
+ # Get all actor info.
198
+ while True:
199
+ try:
200
+ logger.info("Getting all actor info from GCS.")
201
+
202
+ actor_dicts = await self._get_all_actors()
203
+ # Update actors
204
+ DataSource.actors.reset(actor_dicts)
205
+
206
+ # Update node actors and job actors.
207
+ node_actors = defaultdict(dict)
208
+ for actor_id_bytes, updated_actor_table in actor_dicts.items():
209
+ node_id = updated_actor_table["address"]["rayletId"]
210
+ # Update only when node_id is not Nil.
211
+ if node_id != actor_consts.NIL_NODE_ID:
212
+ node_actors[node_id][actor_id_bytes] = updated_actor_table
213
+
214
+ # Update node's actor info
215
+ DataSource.node_actors.reset(node_actors)
216
+
217
+ logger.info("Received %d actor info from GCS.", len(actor_dicts))
218
+
219
+ # Break, once all initial actors are successfully fetched
220
+ break
221
+ except Exception as e:
222
+ logger.exception("Error Getting all actor info from GCS", exc_info=e)
223
+ await asyncio.sleep(
224
+ actor_consts.RETRY_GET_ALL_ACTOR_INFO_INTERVAL_SECONDS
225
+ )
226
+
227
+ # Pull incremental updates from the GCS channel
228
+ while True:
229
+ try:
230
+ updated_actor_table_entries = await self._poll_updated_actor_table_data(
231
+ actor_channel_subscriber
232
+ )
233
+
234
+ for (
235
+ actor_id,
236
+ updated_actor_table,
237
+ ) in updated_actor_table_entries.items():
238
+ self._process_updated_actor_table(actor_id, updated_actor_table)
239
+
240
+ # TODO emit metrics
241
+ logger.debug(
242
+ f"Total events processed: {len(updated_actor_table_entries)}, "
243
+ f"queue size: {actor_channel_subscriber.queue_size}"
244
+ )
245
+
246
+ except Exception as e:
247
+ logger.exception("Error processing actor info from GCS.", exc_info=e)
248
+
249
+ async def _poll_updated_actor_table_data(
250
+ self, actor_channel_subscriber: GcsAioActorSubscriber
251
+ ) -> Dict[str, Dict[str, Any]]:
252
+ # TODO make batch size configurable
253
+ batch = await actor_channel_subscriber.poll(batch_size=200)
254
+
255
+ # NOTE: We're offloading conversion to a TPE to make sure we're not
256
+ # blocking the event-loop for prolonged period of time irrespective
257
+ # of the batch size
258
+ def _convert_to_dict():
259
+ return {
260
+ actor_id_bytes.hex(): actor_table_data_to_dict(actor_table_data_message)
261
+ for actor_id_bytes, actor_table_data_message in batch
262
+ if actor_id_bytes is not None
263
+ }
264
+
265
+ return await self._loop.run_in_executor(self._executor, _convert_to_dict)
266
+
267
+ def _process_updated_actor_table(
268
+ self, actor_id: str, actor_table_data: Dict[str, Any]
269
+ ):
270
+ """NOTE: This method has to be executed on the event-loop, provided that it accesses
271
+ DataSource data structures (to follow its thread-safety model)"""
272
+
273
+ # If actor is not new registered but updated, we only update
274
+ # states related fields.
275
+ actor = DataSource.actors.get(actor_id)
276
+
277
+ if actor and actor_table_data["state"] != "DEPENDENCIES_UNREADY":
278
+ for k in ACTOR_TABLE_STATE_COLUMNS:
279
+ if k in actor_table_data:
280
+ actor[k] = actor_table_data[k]
281
+ actor_table_data = actor
282
+
283
+ actor_id = actor_table_data["actorId"]
284
+ node_id = actor_table_data["address"]["rayletId"]
285
+
286
+ if actor_table_data["state"] == "DEAD":
287
+ self.destroyed_actors_queue.append(actor_id)
288
+
289
+ # Update actors.
290
+ DataSource.actors[actor_id] = actor_table_data
291
+ # Update node actors (only when node_id is not Nil).
292
+ if node_id != actor_consts.NIL_NODE_ID:
293
+ node_actors = DataSource.node_actors.get(node_id, {})
294
+ node_actors[actor_id] = actor_table_data
295
+ DataSource.node_actors[node_id] = node_actors
296
+
297
+ async def _get_all_actors(self) -> Dict[str, dict]:
298
+ actors = await self.get_all_actor_info_client(timeout=GCS_RPC_TIMEOUT_SECONDS)
299
+
300
+ # NOTE: We're offloading conversion to a TPE to make sure we're not
301
+ # blocking the event-loop for prolonged period of time for large clusters
302
+ def _convert_to_dict():
303
+ return {
304
+ actor_id.hex(): actor_table_data_to_dict(actor_table_data)
305
+ for actor_id, actor_table_data in actors.items()
306
+ }
307
+
308
+ return await self._loop.run_in_executor(self._executor, _convert_to_dict)
309
+
310
+ async def _cleanup_actors(self):
311
+ while True:
312
+ try:
313
+ while len(self.destroyed_actors_queue) > MAX_DESTROYED_ACTORS_TO_CACHE:
314
+ actor_id = self.destroyed_actors_queue.popleft()
315
+ if actor_id in DataSource.actors:
316
+ actor = DataSource.actors.pop(actor_id)
317
+ node_id = actor["address"].get("rayletId")
318
+ if node_id and node_id != actor_consts.NIL_NODE_ID:
319
+ del DataSource.node_actors[node_id][actor_id]
320
+ await asyncio.sleep(ACTOR_CLEANUP_FREQUENCY)
321
+ except Exception:
322
+ logger.exception("Error cleaning up actor info from GCS.")
323
+
324
+ @routes.get("/logical/actors")
325
+ @dashboard_optional_utils.aiohttp_cache
326
+ async def get_all_actors(self, req) -> aiohttp.web.Response:
327
+ actors = await DataOrganizer.get_actor_infos()
328
+ return dashboard_optional_utils.rest_response(
329
+ success=True,
330
+ message="All actors fetched.",
331
+ actors=actors,
332
+ # False to avoid converting Ray resource name to google style.
333
+ # It's not necessary here because the fields are already
334
+ # google formatted when protobuf was converted into dict.
335
+ convert_google_style=False,
336
+ )
337
+
338
+ @routes.get("/logical/actors/{actor_id}")
339
+ @dashboard_optional_utils.aiohttp_cache
340
+ async def get_actor(self, req) -> aiohttp.web.Response:
341
+ actor_id = req.match_info.get("actor_id")
342
+ actors = await DataOrganizer.get_actor_infos(actor_ids=[actor_id])
343
+ return dashboard_optional_utils.rest_response(
344
+ success=True, message="Actor details fetched.", detail=actors[actor_id]
345
+ )
346
+
347
+ async def run(self, server):
348
+ self.get_all_actor_info_client = GetAllActorInfoClient.create(
349
+ self._dashboard_head
350
+ )
351
+
352
+ await asyncio.gather(self._update_actors(), self._cleanup_actors())
353
+
354
+ @staticmethod
355
+ def is_minimal_module():
356
+ return False
vllm/lib/python3.10/site-packages/ray/dashboard/modules/dashboard_sdk.py ADDED
@@ -0,0 +1,418 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import dataclasses
2
+ import importlib
3
+ import json
4
+ import logging
5
+ import os
6
+ import ssl
7
+ import tempfile
8
+ from pathlib import Path
9
+ from typing import Any, Dict, List, Optional, Union
10
+
11
+ import packaging.version
12
+ import yaml
13
+
14
+ import ray
15
+ from ray._private.runtime_env.packaging import (
16
+ create_package,
17
+ get_uri_for_directory,
18
+ get_uri_for_package,
19
+ )
20
+ from ray._private.runtime_env.py_modules import upload_py_modules_if_needed
21
+ from ray._private.runtime_env.working_dir import upload_working_dir_if_needed
22
+ from ray._private.utils import split_address
23
+ from ray.autoscaler._private.cli_logger import cli_logger
24
+ from ray.dashboard.modules.job.common import uri_to_http_components
25
+ from ray.util.annotations import DeveloperAPI, PublicAPI
26
+
27
+ try:
28
+ import requests
29
+ except ImportError:
30
+ requests = None
31
+
32
+
33
+ logger = logging.getLogger(__name__)
34
+ logger.setLevel(logging.INFO)
35
+
36
+ # By default, connect to local cluster.
37
+ DEFAULT_DASHBOARD_ADDRESS = "http://localhost:8265"
38
+
39
+
40
+ def parse_runtime_env_args(
41
+ runtime_env: Optional[str] = None,
42
+ runtime_env_json: Optional[str] = None,
43
+ working_dir: Optional[str] = None,
44
+ ):
45
+ """
46
+ Generates a runtime_env dictionary using `runtime_env`, `runtime_env_json`,
47
+ and `working_dir` CLI options. Only one of `runtime_env` or
48
+ `runtime_env_json` may be defined. `working_dir` overwrites the
49
+ `working_dir` from any other option.
50
+ """
51
+
52
+ final_runtime_env = {}
53
+ if runtime_env is not None:
54
+ if runtime_env_json is not None:
55
+ raise ValueError(
56
+ "Only one of --runtime_env and --runtime-env-json can be provided."
57
+ )
58
+ with open(runtime_env, "r") as f:
59
+ final_runtime_env = yaml.safe_load(f)
60
+
61
+ elif runtime_env_json is not None:
62
+ final_runtime_env = json.loads(runtime_env_json)
63
+
64
+ if working_dir is not None:
65
+ if "working_dir" in final_runtime_env:
66
+ cli_logger.warning(
67
+ "Overriding runtime_env working_dir with --working-dir option"
68
+ )
69
+
70
+ final_runtime_env["working_dir"] = working_dir
71
+
72
+ return final_runtime_env
73
+
74
+
75
+ @dataclasses.dataclass
76
+ class ClusterInfo:
77
+ address: str
78
+ cookies: Optional[Dict[str, Any]] = None
79
+ metadata: Optional[Dict[str, Any]] = None
80
+ headers: Optional[Dict[str, Any]] = None
81
+
82
+
83
+ # TODO (shrekris-anyscale): renaming breaks compatibility, do NOT rename
84
+ def get_job_submission_client_cluster_info(
85
+ address: str,
86
+ # For backwards compatibility
87
+ *,
88
+ # only used in importlib case in parse_cluster_info, but needed
89
+ # in function signature.
90
+ create_cluster_if_needed: Optional[bool] = False,
91
+ cookies: Optional[Dict[str, Any]] = None,
92
+ metadata: Optional[Dict[str, Any]] = None,
93
+ headers: Optional[Dict[str, Any]] = None,
94
+ _use_tls: Optional[bool] = False,
95
+ ) -> ClusterInfo:
96
+ """Get address, cookies, and metadata used for SubmissionClient.
97
+
98
+ If no port is specified in `address`, the Ray dashboard default will be
99
+ inserted.
100
+
101
+ Args:
102
+ address: Address without the module prefix that is passed
103
+ to SubmissionClient.
104
+ create_cluster_if_needed: Indicates whether the cluster
105
+ of the address returned needs to be running. Ray doesn't
106
+ start a cluster before interacting with jobs, but other
107
+ implementations may do so.
108
+
109
+ Returns:
110
+ ClusterInfo object consisting of address, cookies, and metadata
111
+ for SubmissionClient to use.
112
+ """
113
+
114
+ scheme = "https" if _use_tls else "http"
115
+ return ClusterInfo(
116
+ address=f"{scheme}://{address}",
117
+ cookies=cookies,
118
+ metadata=metadata,
119
+ headers=headers,
120
+ )
121
+
122
+
123
+ def parse_cluster_info(
124
+ address: Optional[str] = None,
125
+ create_cluster_if_needed: bool = False,
126
+ cookies: Optional[Dict[str, Any]] = None,
127
+ metadata: Optional[Dict[str, Any]] = None,
128
+ headers: Optional[Dict[str, Any]] = None,
129
+ ) -> ClusterInfo:
130
+ """Create a cluster if needed and return its address, cookies, and metadata."""
131
+ if address is None:
132
+ if (
133
+ ray.is_initialized()
134
+ and ray._private.worker.global_worker.node.address_info["webui_url"]
135
+ is not None
136
+ ):
137
+ address = (
138
+ "http://"
139
+ f"{ray._private.worker.global_worker.node.address_info['webui_url']}"
140
+ )
141
+ logger.info(
142
+ f"No address provided but Ray is running; using address {address}."
143
+ )
144
+ else:
145
+ logger.info(
146
+ f"No address provided, defaulting to {DEFAULT_DASHBOARD_ADDRESS}."
147
+ )
148
+ address = DEFAULT_DASHBOARD_ADDRESS
149
+
150
+ if address == "auto":
151
+ raise ValueError("Internal error: unexpected address 'auto'.")
152
+
153
+ if "://" not in address:
154
+ # Default to HTTP.
155
+ logger.info(
156
+ "No scheme (e.g. 'http://') or module string (e.g. 'ray://') "
157
+ f"provided in address {address}, defaulting to HTTP."
158
+ )
159
+ address = f"http://{address}"
160
+
161
+ module_string, inner_address = split_address(address)
162
+
163
+ if module_string == "ray":
164
+ raise ValueError(f"Internal error: unexpected Ray Client address {address}.")
165
+ # If user passes http(s)://, go through normal parsing.
166
+ if module_string in {"http", "https"}:
167
+ return get_job_submission_client_cluster_info(
168
+ inner_address,
169
+ create_cluster_if_needed=create_cluster_if_needed,
170
+ cookies=cookies,
171
+ metadata=metadata,
172
+ headers=headers,
173
+ _use_tls=(module_string == "https"),
174
+ )
175
+ # Try to dynamically import the function to get cluster info.
176
+ else:
177
+ try:
178
+ module = importlib.import_module(module_string)
179
+ except Exception:
180
+ raise RuntimeError(
181
+ f"Module: {module_string} does not exist.\n"
182
+ f"This module was parsed from address: {address}"
183
+ ) from None
184
+ assert "get_job_submission_client_cluster_info" in dir(module), (
185
+ f"Module: {module_string} does "
186
+ "not have `get_job_submission_client_cluster_info`.\n"
187
+ f"This module was parsed from address: {address}"
188
+ )
189
+
190
+ return module.get_job_submission_client_cluster_info(
191
+ inner_address,
192
+ create_cluster_if_needed=create_cluster_if_needed,
193
+ cookies=cookies,
194
+ metadata=metadata,
195
+ headers=headers,
196
+ )
197
+
198
+
199
+ class SubmissionClient:
200
+ def __init__(
201
+ self,
202
+ address: Optional[str] = None,
203
+ create_cluster_if_needed: bool = False,
204
+ cookies: Optional[Dict[str, Any]] = None,
205
+ metadata: Optional[Dict[str, Any]] = None,
206
+ headers: Optional[Dict[str, Any]] = None,
207
+ verify: Optional[Union[str, bool]] = True,
208
+ ):
209
+ # Remove any trailing slashes
210
+ if address is not None and address.endswith("/"):
211
+ address = address.rstrip("/")
212
+ logger.debug(
213
+ "The submission address cannot contain trailing slashes. Removing "
214
+ f'them from the requested submission address of "{address}".'
215
+ )
216
+
217
+ cluster_info = parse_cluster_info(
218
+ address, create_cluster_if_needed, cookies, metadata, headers
219
+ )
220
+ self._address = cluster_info.address
221
+ self._cookies = cluster_info.cookies
222
+ self._default_metadata = cluster_info.metadata or {}
223
+ # Headers used for all requests sent to job server, optional and only
224
+ # needed for cases like authentication to remote cluster.
225
+ self._headers = cluster_info.headers
226
+ # Set SSL verify parameter for the requests library and create an ssl_context
227
+ # object when needed for the aiohttp library.
228
+ self._verify = verify
229
+ if isinstance(self._verify, str):
230
+ if os.path.isdir(self._verify):
231
+ cafile, capath = None, self._verify
232
+ elif os.path.isfile(self._verify):
233
+ cafile, capath = self._verify, None
234
+ else:
235
+ raise FileNotFoundError(
236
+ f"Path to CA certificates: '{self._verify}', does not exist."
237
+ )
238
+ self._ssl_context = ssl.create_default_context(cafile=cafile, capath=capath)
239
+ else:
240
+ if self._verify is False:
241
+ self._ssl_context = False
242
+ else:
243
+ self._ssl_context = None
244
+
245
+ def _check_connection_and_version(
246
+ self, min_version: str = "1.9", version_error_message: str = None
247
+ ):
248
+ self._check_connection_and_version_with_url(min_version, version_error_message)
249
+
250
+ def _check_connection_and_version_with_url(
251
+ self,
252
+ min_version: str = "1.9",
253
+ version_error_message: str = None,
254
+ url: str = "/api/version",
255
+ ):
256
+ if version_error_message is None:
257
+ version_error_message = (
258
+ f"Please ensure the cluster is running Ray {min_version} or higher."
259
+ )
260
+
261
+ try:
262
+ r = self._do_request("GET", url)
263
+ if r.status_code == 404:
264
+ raise RuntimeError(
265
+ "Version check returned 404. " + version_error_message
266
+ )
267
+ r.raise_for_status()
268
+
269
+ running_ray_version = r.json()["ray_version"]
270
+ if packaging.version.parse(running_ray_version) < packaging.version.parse(
271
+ min_version
272
+ ):
273
+ raise RuntimeError(
274
+ f"Ray version {running_ray_version} is running on the cluster. "
275
+ + version_error_message
276
+ )
277
+ except requests.exceptions.ConnectionError:
278
+ raise ConnectionError(
279
+ f"Failed to connect to Ray at address: {self._address}."
280
+ )
281
+
282
+ def _raise_error(self, r: "requests.Response"):
283
+ raise RuntimeError(
284
+ f"Request failed with status code {r.status_code}: {r.text}."
285
+ )
286
+
287
+ def _do_request(
288
+ self,
289
+ method: str,
290
+ endpoint: str,
291
+ *,
292
+ data: Optional[bytes] = None,
293
+ json_data: Optional[dict] = None,
294
+ **kwargs,
295
+ ) -> "requests.Response":
296
+ """Perform the actual HTTP request
297
+
298
+ Keyword arguments other than "cookies", "headers" are forwarded to the
299
+ `requests.request()`.
300
+ """
301
+ url = self._address + endpoint
302
+ logger.debug(f"Sending request to {url} with json data: {json_data or {}}.")
303
+ return requests.request(
304
+ method,
305
+ url,
306
+ cookies=self._cookies,
307
+ data=data,
308
+ json=json_data,
309
+ headers=self._headers,
310
+ verify=self._verify,
311
+ **kwargs,
312
+ )
313
+
314
+ def _package_exists(
315
+ self,
316
+ package_uri: str,
317
+ ) -> bool:
318
+ protocol, package_name = uri_to_http_components(package_uri)
319
+ r = self._do_request("GET", f"/api/packages/{protocol}/{package_name}")
320
+
321
+ if r.status_code == 200:
322
+ logger.debug(f"Package {package_uri} already exists.")
323
+ return True
324
+ elif r.status_code == 404:
325
+ logger.debug(f"Package {package_uri} does not exist.")
326
+ return False
327
+ else:
328
+ self._raise_error(r)
329
+
330
+ def _upload_package(
331
+ self,
332
+ package_uri: str,
333
+ package_path: str,
334
+ include_parent_dir: Optional[bool] = False,
335
+ excludes: Optional[List[str]] = None,
336
+ is_file: bool = False,
337
+ ) -> bool:
338
+ logger.info(f"Uploading package {package_uri}.")
339
+ with tempfile.TemporaryDirectory() as tmp_dir:
340
+ protocol, package_name = uri_to_http_components(package_uri)
341
+ if is_file:
342
+ package_file = Path(package_path)
343
+ else:
344
+ package_file = Path(tmp_dir) / package_name
345
+ create_package(
346
+ package_path,
347
+ package_file,
348
+ include_parent_dir=include_parent_dir,
349
+ excludes=excludes,
350
+ )
351
+ try:
352
+ r = self._do_request(
353
+ "PUT",
354
+ f"/api/packages/{protocol}/{package_name}",
355
+ data=package_file.read_bytes(),
356
+ )
357
+ if r.status_code != 200:
358
+ self._raise_error(r)
359
+ finally:
360
+ # If the package is a user's existing file, don't delete it.
361
+ if not is_file:
362
+ package_file.unlink()
363
+
364
+ def _upload_package_if_needed(
365
+ self,
366
+ package_path: str,
367
+ include_parent_dir: bool = False,
368
+ excludes: Optional[List[str]] = None,
369
+ is_file: bool = False,
370
+ ) -> str:
371
+ if is_file:
372
+ package_uri = get_uri_for_package(Path(package_path))
373
+ else:
374
+ package_uri = get_uri_for_directory(package_path, excludes=excludes)
375
+
376
+ if not self._package_exists(package_uri):
377
+ self._upload_package(
378
+ package_uri,
379
+ package_path,
380
+ include_parent_dir=include_parent_dir,
381
+ excludes=excludes,
382
+ is_file=is_file,
383
+ )
384
+ else:
385
+ logger.info(f"Package {package_uri} already exists, skipping upload.")
386
+
387
+ return package_uri
388
+
389
+ def _upload_working_dir_if_needed(self, runtime_env: Dict[str, Any]):
390
+ def _upload_fn(working_dir, excludes, is_file=False):
391
+ self._upload_package_if_needed(
392
+ working_dir,
393
+ include_parent_dir=False,
394
+ excludes=excludes,
395
+ is_file=is_file,
396
+ )
397
+
398
+ upload_working_dir_if_needed(runtime_env, upload_fn=_upload_fn)
399
+
400
+ def _upload_py_modules_if_needed(self, runtime_env: Dict[str, Any]):
401
+ def _upload_fn(module_path, excludes, is_file=False):
402
+ self._upload_package_if_needed(
403
+ module_path, include_parent_dir=True, excludes=excludes, is_file=is_file
404
+ )
405
+
406
+ upload_py_modules_if_needed(runtime_env, upload_fn=_upload_fn)
407
+
408
+ @PublicAPI(stability="beta")
409
+ def get_version(self) -> str:
410
+ r = self._do_request("GET", "/api/version")
411
+ if r.status_code == 200:
412
+ return r.json().get("version")
413
+ else:
414
+ self._raise_error(r)
415
+
416
+ @DeveloperAPI
417
+ def get_address(self) -> str:
418
+ return self._address
vllm/lib/python3.10/site-packages/ray/dashboard/modules/healthz/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (179 Bytes). View file
 
vllm/lib/python3.10/site-packages/ray/dashboard/modules/healthz/__pycache__/healthz_agent.cpython-310.pyc ADDED
Binary file (2.16 kB). View file
 
vllm/lib/python3.10/site-packages/ray/dashboard/modules/healthz/__pycache__/healthz_head.cpython-310.pyc ADDED
Binary file (1.88 kB). View file
 
vllm/lib/python3.10/site-packages/ray/dashboard/modules/healthz/healthz_agent.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from aiohttp.web import Request, Response
2
+
3
+ import ray.dashboard.optional_utils as optional_utils
4
+ import ray.dashboard.utils as dashboard_utils
5
+ import ray.exceptions
6
+ from ray.dashboard.modules.healthz.utils import HealthChecker
7
+
8
+ routes = optional_utils.DashboardAgentRouteTable
9
+
10
+
11
+ class HealthzAgent(dashboard_utils.DashboardAgentModule):
12
+ """Health check in the agent.
13
+
14
+ This module adds health check related endpoint to the agent to check
15
+ local components' health.
16
+ """
17
+
18
+ def __init__(self, dashboard_agent):
19
+ super().__init__(dashboard_agent)
20
+ self._health_checker = HealthChecker(
21
+ dashboard_agent.gcs_aio_client,
22
+ f"{dashboard_agent.ip}:{dashboard_agent.node_manager_port}",
23
+ )
24
+
25
+ @routes.get("/api/local_raylet_healthz")
26
+ async def health_check(self, req: Request) -> Response:
27
+ try:
28
+ alive = await self._health_checker.check_local_raylet_liveness()
29
+ if alive is False:
30
+ return Response(status=503, text="Local Raylet failed")
31
+ except ray.exceptions.RpcError as e:
32
+ # We only consider the error other than GCS unreachable as raylet failure
33
+ # to avoid false positive.
34
+ # In case of GCS failed, Raylet will crash eventually if GCS is not back
35
+ # within a given time and the check will fail since agent can't live
36
+ # without a local raylet.
37
+ if e.rpc_code not in (
38
+ ray._raylet.GRPC_STATUS_CODE_UNAVAILABLE,
39
+ ray._raylet.GRPC_STATUS_CODE_UNKNOWN,
40
+ ray._raylet.GRPC_STATUS_CODE_DEADLINE_EXCEEDED,
41
+ ):
42
+ return Response(status=503, text=f"Health check failed due to: {e}")
43
+
44
+ return Response(
45
+ text="success",
46
+ content_type="application/text",
47
+ )
48
+
49
+ async def run(self, server):
50
+ pass
51
+
52
+ @staticmethod
53
+ def is_minimal_module():
54
+ return False
vllm/lib/python3.10/site-packages/ray/dashboard/modules/healthz/healthz_head.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from aiohttp.web import HTTPServiceUnavailable, Request, Response
2
+
3
+ import ray.dashboard.optional_utils as optional_utils
4
+ import ray.dashboard.utils as dashboard_utils
5
+ from ray.dashboard.modules.healthz.utils import HealthChecker
6
+
7
+ routes = optional_utils.DashboardHeadRouteTable
8
+
9
+
10
+ class HealthzHead(dashboard_utils.DashboardHeadModule):
11
+ """Health check in the head.
12
+
13
+ This module adds health check related endpoint to the head to check
14
+ GCS's heath.
15
+ """
16
+
17
+ def __init__(self, dashboard_head):
18
+ super().__init__(dashboard_head)
19
+ self._health_checker = HealthChecker(dashboard_head.gcs_aio_client)
20
+
21
+ @routes.get("/api/gcs_healthz")
22
+ async def health_check(self, req: Request) -> Response:
23
+ alive = False
24
+ try:
25
+ alive = await self._health_checker.check_gcs_liveness()
26
+ if alive is True:
27
+ return Response(
28
+ text="success",
29
+ content_type="application/text",
30
+ )
31
+ except Exception as e:
32
+ return HTTPServiceUnavailable(reason=f"Health check failed: {e}")
33
+
34
+ return HTTPServiceUnavailable(reason="Health check failed")
35
+
36
+ async def run(self, server):
37
+ pass
38
+
39
+ @staticmethod
40
+ def is_minimal_module():
41
+ return True
vllm/lib/python3.10/site-packages/ray/dashboard/modules/healthz/utils.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Optional
2
+
3
+ from ray._private.gcs_utils import GcsAioClient
4
+
5
+
6
+ class HealthChecker:
7
+ def __init__(
8
+ self, gcs_aio_client: GcsAioClient, local_node_address: Optional[str] = None
9
+ ):
10
+ self._gcs_aio_client = gcs_aio_client
11
+ self._local_node_address = local_node_address
12
+
13
+ async def check_local_raylet_liveness(self) -> bool:
14
+ if self._local_node_address is None:
15
+ return False
16
+
17
+ liveness = await self._gcs_aio_client.check_alive(
18
+ [self._local_node_address.encode()], 0.1
19
+ )
20
+ return liveness[0]
21
+
22
+ async def check_gcs_liveness(self) -> bool:
23
+ await self._gcs_aio_client.check_alive([], 0.1)
24
+ return True
vllm/lib/python3.10/site-packages/ray/dashboard/modules/job/__init__.py ADDED
File without changes
vllm/lib/python3.10/site-packages/ray/dashboard/modules/node/__init__.py ADDED
File without changes
vllm/lib/python3.10/site-packages/ray/dashboard/modules/reporter/__init__.py ADDED
File without changes
vllm/lib/python3.10/site-packages/ray/dashboard/modules/reporter/__pycache__/profile_manager.cpython-310.pyc ADDED
Binary file (9.96 kB). View file
 
vllm/lib/python3.10/site-packages/ray/dashboard/modules/reporter/__pycache__/reporter_agent.cpython-310.pyc ADDED
Binary file (26.8 kB). View file
 
vllm/lib/python3.10/site-packages/ray/dashboard/modules/reporter/__pycache__/reporter_consts.cpython-310.pyc ADDED
Binary file (368 Bytes). View file
 
vllm/lib/python3.10/site-packages/ray/dashboard/modules/reporter/__pycache__/reporter_head.cpython-310.pyc ADDED
Binary file (17 kB). View file
 
vllm/lib/python3.10/site-packages/ray/dashboard/modules/reporter/reporter_agent.py ADDED
@@ -0,0 +1,1305 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import datetime
3
+ import json
4
+ import logging
5
+ import os
6
+ import socket
7
+ import sys
8
+ import traceback
9
+ from collections import defaultdict
10
+ from concurrent.futures import ThreadPoolExecutor
11
+ from typing import List, Optional, Tuple, TypedDict, Union
12
+
13
+ from opencensus.stats import stats as stats_module
14
+ from prometheus_client.core import REGISTRY
15
+
16
+ import ray
17
+ import ray._private.prometheus_exporter as prometheus_exporter
18
+ import ray._private.services
19
+ import ray._private.utils
20
+ import ray.dashboard.modules.reporter.reporter_consts as reporter_consts
21
+ import ray.dashboard.utils as dashboard_utils
22
+ from ray._private import utils
23
+ from ray._private.metrics_agent import Gauge, MetricsAgent, Record
24
+ from ray._private.ray_constants import DEBUG_AUTOSCALING_STATUS, env_integer
25
+ from ray._raylet import WorkerID
26
+ from ray.core.generated import reporter_pb2, reporter_pb2_grpc
27
+ from ray.dashboard import k8s_utils
28
+ from ray.dashboard.consts import (
29
+ CLUSTER_TAG_KEYS,
30
+ COMPONENT_METRICS_TAG_KEYS,
31
+ GCS_RPC_TIMEOUT_SECONDS,
32
+ GPU_TAG_KEYS,
33
+ NODE_TAG_KEYS,
34
+ )
35
+ from ray.dashboard.modules.reporter.profile_manager import (
36
+ CpuProfilingManager,
37
+ MemoryProfilingManager,
38
+ )
39
+
40
+ import psutil
41
+
42
+ logger = logging.getLogger(__name__)
43
+
44
+ enable_gpu_usage_check = True
45
+
46
+ # Are we in a K8s pod?
47
+ IN_KUBERNETES_POD = "KUBERNETES_SERVICE_HOST" in os.environ
48
+ # Flag to enable showing disk usage when running in a K8s pod,
49
+ # disk usage defined as the result of running psutil.disk_usage("/")
50
+ # in the Ray container.
51
+ ENABLE_K8S_DISK_USAGE = os.environ.get("RAY_DASHBOARD_ENABLE_K8S_DISK_USAGE") == "1"
52
+ # Try to determine if we're in a container.
53
+ IN_CONTAINER = os.path.exists("/sys/fs/cgroup")
54
+ # Using existence of /sys/fs/cgroup as the criterion is consistent with
55
+ # Ray's existing resource logic, see e.g. ray._private.utils.get_num_cpus().
56
+
57
+ # NOTE: Executor in this head is intentionally constrained to just 1 thread by
58
+ # default to limit its concurrency, therefore reducing potential for
59
+ # GIL contention
60
+ RAY_DASHBOARD_REPORTER_AGENT_TPE_MAX_WORKERS = env_integer(
61
+ "RAY_DASHBOARD_REPORTER_AGENT_TPE_MAX_WORKERS", 1
62
+ )
63
+
64
+
65
+ def recursive_asdict(o):
66
+ if isinstance(o, tuple) and hasattr(o, "_asdict"):
67
+ return recursive_asdict(o._asdict())
68
+
69
+ if isinstance(o, (tuple, list)):
70
+ L = []
71
+ for k in o:
72
+ L.append(recursive_asdict(k))
73
+ return L
74
+
75
+ if isinstance(o, dict):
76
+ D = {k: recursive_asdict(v) for k, v in o.items()}
77
+ return D
78
+
79
+ return o
80
+
81
+
82
+ def jsonify_asdict(o) -> str:
83
+ return json.dumps(dashboard_utils.to_google_style(recursive_asdict(o)))
84
+
85
+
86
+ # A list of gauges to record and export metrics.
87
+ METRICS_GAUGES = {
88
+ # CPU metrics
89
+ "node_cpu_utilization": Gauge(
90
+ "node_cpu_utilization",
91
+ "Total CPU usage on a ray node",
92
+ "percentage",
93
+ NODE_TAG_KEYS,
94
+ ),
95
+ "node_cpu_count": Gauge(
96
+ "node_cpu_count",
97
+ "Total CPUs available on a ray node",
98
+ "cores",
99
+ NODE_TAG_KEYS,
100
+ ),
101
+ # Memory metrics
102
+ "node_mem_used": Gauge(
103
+ "node_mem_used",
104
+ "Memory usage on a ray node",
105
+ "bytes",
106
+ NODE_TAG_KEYS,
107
+ ),
108
+ "node_mem_available": Gauge(
109
+ "node_mem_available",
110
+ "Memory available on a ray node",
111
+ "bytes",
112
+ NODE_TAG_KEYS,
113
+ ),
114
+ "node_mem_total": Gauge(
115
+ "node_mem_total",
116
+ "Total memory on a ray node",
117
+ "bytes",
118
+ NODE_TAG_KEYS,
119
+ ),
120
+ "node_mem_shared_bytes": Gauge(
121
+ "node_mem_shared_bytes",
122
+ "Total shared memory usage on a ray node",
123
+ "bytes",
124
+ NODE_TAG_KEYS,
125
+ ),
126
+ # GPU metrics
127
+ "node_gpus_available": Gauge(
128
+ "node_gpus_available",
129
+ "Total GPUs available on a ray node",
130
+ "percentage",
131
+ GPU_TAG_KEYS,
132
+ ),
133
+ "node_gpus_utilization": Gauge(
134
+ "node_gpus_utilization",
135
+ "Total GPUs usage on a ray node",
136
+ "percentage",
137
+ GPU_TAG_KEYS,
138
+ ),
139
+ "node_gram_used": Gauge(
140
+ "node_gram_used",
141
+ "Total GPU RAM usage on a ray node",
142
+ "bytes",
143
+ GPU_TAG_KEYS,
144
+ ),
145
+ "node_gram_available": Gauge(
146
+ "node_gram_available",
147
+ "Total GPU RAM available on a ray node",
148
+ "bytes",
149
+ GPU_TAG_KEYS,
150
+ ),
151
+ # Disk I/O metrics
152
+ "node_disk_io_read": Gauge(
153
+ "node_disk_io_read",
154
+ "Total read from disk",
155
+ "bytes",
156
+ NODE_TAG_KEYS,
157
+ ),
158
+ "node_disk_io_write": Gauge(
159
+ "node_disk_io_write",
160
+ "Total written to disk",
161
+ "bytes",
162
+ NODE_TAG_KEYS,
163
+ ),
164
+ "node_disk_io_read_count": Gauge(
165
+ "node_disk_io_read_count",
166
+ "Total read ops from disk",
167
+ "io",
168
+ NODE_TAG_KEYS,
169
+ ),
170
+ "node_disk_io_write_count": Gauge(
171
+ "node_disk_io_write_count",
172
+ "Total write ops to disk",
173
+ "io",
174
+ NODE_TAG_KEYS,
175
+ ),
176
+ "node_disk_io_read_speed": Gauge(
177
+ "node_disk_io_read_speed",
178
+ "Disk read speed",
179
+ "bytes/sec",
180
+ NODE_TAG_KEYS,
181
+ ),
182
+ "node_disk_io_write_speed": Gauge(
183
+ "node_disk_io_write_speed",
184
+ "Disk write speed",
185
+ "bytes/sec",
186
+ NODE_TAG_KEYS,
187
+ ),
188
+ "node_disk_read_iops": Gauge(
189
+ "node_disk_read_iops",
190
+ "Disk read iops",
191
+ "iops",
192
+ NODE_TAG_KEYS,
193
+ ),
194
+ "node_disk_write_iops": Gauge(
195
+ "node_disk_write_iops",
196
+ "Disk write iops",
197
+ "iops",
198
+ NODE_TAG_KEYS,
199
+ ),
200
+ # Disk usage metrics
201
+ "node_disk_usage": Gauge(
202
+ "node_disk_usage",
203
+ "Total disk usage (bytes) on a ray node",
204
+ "bytes",
205
+ NODE_TAG_KEYS,
206
+ ),
207
+ "node_disk_free": Gauge(
208
+ "node_disk_free",
209
+ "Total disk free (bytes) on a ray node",
210
+ "bytes",
211
+ NODE_TAG_KEYS,
212
+ ),
213
+ "node_disk_utilization_percentage": Gauge(
214
+ "node_disk_utilization_percentage",
215
+ "Total disk utilization (percentage) on a ray node",
216
+ "percentage",
217
+ NODE_TAG_KEYS,
218
+ ),
219
+ # Network metrics
220
+ "node_network_sent": Gauge(
221
+ "node_network_sent",
222
+ "Total network sent",
223
+ "bytes",
224
+ NODE_TAG_KEYS,
225
+ ),
226
+ "node_network_received": Gauge(
227
+ "node_network_received",
228
+ "Total network received",
229
+ "bytes",
230
+ NODE_TAG_KEYS,
231
+ ),
232
+ "node_network_send_speed": Gauge(
233
+ "node_network_send_speed",
234
+ "Network send speed",
235
+ "bytes/sec",
236
+ NODE_TAG_KEYS,
237
+ ),
238
+ "node_network_receive_speed": Gauge(
239
+ "node_network_receive_speed",
240
+ "Network receive speed",
241
+ "bytes/sec",
242
+ NODE_TAG_KEYS,
243
+ ),
244
+ # Component metrics
245
+ "component_cpu_percentage": Gauge(
246
+ "component_cpu_percentage",
247
+ "Total CPU usage of the components on a node.",
248
+ "percentage",
249
+ COMPONENT_METRICS_TAG_KEYS,
250
+ ),
251
+ "component_mem_shared_bytes": Gauge(
252
+ "component_mem_shared_bytes",
253
+ "SHM usage of all components of the node. "
254
+ "It is equivalent to the top command's SHR column.",
255
+ "bytes",
256
+ COMPONENT_METRICS_TAG_KEYS,
257
+ ),
258
+ "component_rss_mb": Gauge(
259
+ "component_rss_mb",
260
+ "RSS usage of all components on the node.",
261
+ "MB",
262
+ COMPONENT_METRICS_TAG_KEYS,
263
+ ),
264
+ "component_uss_mb": Gauge(
265
+ "component_uss_mb",
266
+ "USS usage of all components on the node.",
267
+ "MB",
268
+ COMPONENT_METRICS_TAG_KEYS,
269
+ ),
270
+ "component_num_fds": Gauge(
271
+ "component_num_fds",
272
+ "Number of open fds of all components on the node (Not available on Windows).",
273
+ "count",
274
+ COMPONENT_METRICS_TAG_KEYS,
275
+ ),
276
+ # Cluster metrics
277
+ "cluster_active_nodes": Gauge(
278
+ "cluster_active_nodes",
279
+ "Active nodes on the cluster",
280
+ "count",
281
+ CLUSTER_TAG_KEYS,
282
+ ),
283
+ "cluster_failed_nodes": Gauge(
284
+ "cluster_failed_nodes",
285
+ "Failed nodes on the cluster",
286
+ "count",
287
+ CLUSTER_TAG_KEYS,
288
+ ),
289
+ "cluster_pending_nodes": Gauge(
290
+ "cluster_pending_nodes",
291
+ "Pending nodes on the cluster",
292
+ "count",
293
+ CLUSTER_TAG_KEYS,
294
+ ),
295
+ }
296
+
297
+ PSUTIL_PROCESS_ATTRS = (
298
+ [
299
+ "pid",
300
+ "create_time",
301
+ "cpu_percent",
302
+ "cpu_times",
303
+ "cmdline",
304
+ "memory_info",
305
+ "memory_full_info",
306
+ ]
307
+ + ["num_fds"]
308
+ if sys.platform != "win32"
309
+ else []
310
+ )
311
+
312
+ MB = 1024 * 1024
313
+
314
+ # Types
315
+ Percentage = int
316
+ Megabytes = int
317
+
318
+
319
+ # gpu utilization for nvidia gpu from a single process
320
+ class ProcessGPUInfo(TypedDict):
321
+ pid: int
322
+ gpu_memory_usage: Megabytes
323
+
324
+
325
+ # gpu utilization for nvidia gpu
326
+ class GpuUtilizationInfo(TypedDict):
327
+ index: int
328
+ name: str
329
+ uuid: str
330
+ utilization_gpu: Optional[Percentage]
331
+ memory_used: Megabytes
332
+ memory_total: Megabytes
333
+ processes_pids: Optional[List[ProcessGPUInfo]]
334
+
335
+
336
+ class ReporterAgent(
337
+ dashboard_utils.DashboardAgentModule, reporter_pb2_grpc.ReporterServiceServicer
338
+ ):
339
+ """A monitor process for monitoring Ray nodes.
340
+
341
+ Attributes:
342
+ dashboard_agent: The DashboardAgent object contains global config
343
+ """
344
+
345
+ def __init__(self, dashboard_agent):
346
+ """Initialize the reporter object."""
347
+ super().__init__(dashboard_agent)
348
+
349
+ if IN_KUBERNETES_POD or IN_CONTAINER:
350
+ # psutil does not give a meaningful logical cpu count when in a K8s pod, or
351
+ # in a container in general.
352
+ # Use ray._private.utils for this instead.
353
+ logical_cpu_count = ray._private.utils.get_num_cpus(
354
+ override_docker_cpu_warning=True
355
+ )
356
+ # (Override the docker warning to avoid dashboard log spam.)
357
+
358
+ # The dashboard expects a physical CPU count as well.
359
+ # This is not always meaningful in a container, but we will go ahead
360
+ # and give the dashboard what it wants using psutil.
361
+ physical_cpu_count = psutil.cpu_count(logical=False)
362
+ else:
363
+ logical_cpu_count = psutil.cpu_count()
364
+ physical_cpu_count = psutil.cpu_count(logical=False)
365
+ self._cpu_counts = (logical_cpu_count, physical_cpu_count)
366
+ self._gcs_aio_client = dashboard_agent.gcs_aio_client
367
+ self._ip = dashboard_agent.ip
368
+ self._log_dir = dashboard_agent.log_dir
369
+ self._is_head_node = self._ip == dashboard_agent.gcs_address.split(":")[0]
370
+ self._hostname = socket.gethostname()
371
+ # (pid, created_time) -> psutil.Process
372
+ self._workers = {}
373
+ # psutil.Process of the parent.
374
+ self._raylet_proc = None
375
+ # psutil.Process of the current process.
376
+ self._agent_proc = None
377
+ # The last reported worker proc names (e.g., ray::*).
378
+ self._latest_worker_proc_names = set()
379
+ self._network_stats_hist = [(0, (0.0, 0.0))] # time, (sent, recv)
380
+ self._disk_io_stats_hist = [
381
+ (0, (0.0, 0.0, 0, 0))
382
+ ] # time, (bytes read, bytes written, read ops, write ops)
383
+ self._metrics_collection_disabled = dashboard_agent.metrics_collection_disabled
384
+ self._metrics_agent = None
385
+ self._session_name = dashboard_agent.session_name
386
+ if not self._metrics_collection_disabled:
387
+ try:
388
+ stats_exporter = prometheus_exporter.new_stats_exporter(
389
+ prometheus_exporter.Options(
390
+ namespace="ray",
391
+ port=dashboard_agent.metrics_export_port,
392
+ address="127.0.0.1" if self._ip == "127.0.0.1" else "",
393
+ )
394
+ )
395
+ except Exception:
396
+ # TODO(SongGuyang): Catch the exception here because there is
397
+ # port conflict issue which brought from static port. We should
398
+ # remove this after we find better port resolution.
399
+ logger.exception(
400
+ "Failed to start prometheus stats exporter. Agent will stay "
401
+ "alive but disable the stats."
402
+ )
403
+ stats_exporter = None
404
+
405
+ self._metrics_agent = MetricsAgent(
406
+ stats_module.stats.view_manager,
407
+ stats_module.stats.stats_recorder,
408
+ stats_exporter,
409
+ )
410
+ if self._metrics_agent.proxy_exporter_collector:
411
+ # proxy_exporter_collector is None
412
+ # if Prometheus server is not started.
413
+ REGISTRY.register(self._metrics_agent.proxy_exporter_collector)
414
+ self._key = (
415
+ f"{reporter_consts.REPORTER_PREFIX}" f"{self._dashboard_agent.node_id}"
416
+ )
417
+
418
+ self._executor = ThreadPoolExecutor(
419
+ max_workers=RAY_DASHBOARD_REPORTER_AGENT_TPE_MAX_WORKERS,
420
+ thread_name_prefix="reporter_agent_executor",
421
+ )
422
+
423
+ async def GetTraceback(self, request, context):
424
+ pid = request.pid
425
+ native = request.native
426
+ p = CpuProfilingManager(self._log_dir)
427
+ success, output = await p.trace_dump(pid, native=native)
428
+ return reporter_pb2.GetTracebackReply(output=output, success=success)
429
+
430
+ async def CpuProfiling(self, request, context):
431
+ pid = request.pid
432
+ duration = request.duration
433
+ format = request.format
434
+ native = request.native
435
+ p = CpuProfilingManager(self._log_dir)
436
+ success, output = await p.cpu_profile(
437
+ pid, format=format, duration=duration, native=native
438
+ )
439
+ return reporter_pb2.CpuProfilingReply(output=output, success=success)
440
+
441
+ async def MemoryProfiling(self, request, context):
442
+ pid = request.pid
443
+ format = request.format
444
+ leaks = request.leaks
445
+ duration = request.duration
446
+ native = request.native
447
+ trace_python_allocators = request.trace_python_allocators
448
+ p = MemoryProfilingManager(self._log_dir)
449
+ success, profiler_filename, output = await p.attach_profiler(
450
+ pid, native=native, trace_python_allocators=trace_python_allocators
451
+ )
452
+ if not success:
453
+ return reporter_pb2.MemoryProfilingReply(output=output, success=success)
454
+
455
+ # add 1 second sleep for memray overhead
456
+ await asyncio.sleep(duration + 1)
457
+ success, output = await p.detach_profiler(pid)
458
+ warning = None if success else output
459
+ success, output = await p.get_profile_result(
460
+ pid, profiler_filename=profiler_filename, format=format, leaks=leaks
461
+ )
462
+ return reporter_pb2.MemoryProfilingReply(
463
+ output=output, success=success, warning=warning
464
+ )
465
+
466
+ async def ReportOCMetrics(self, request, context):
467
+ # Do nothing if metrics collection is disabled.
468
+ if self._metrics_collection_disabled:
469
+ return reporter_pb2.ReportOCMetricsReply()
470
+
471
+ # This function receives a GRPC containing OpenCensus (OC) metrics
472
+ # from a Ray process, then exposes those metrics to Prometheus.
473
+ try:
474
+ worker_id = WorkerID(request.worker_id)
475
+ worker_id = None if worker_id.is_nil() else worker_id.hex()
476
+ self._metrics_agent.proxy_export_metrics(request.metrics, worker_id)
477
+ except Exception:
478
+ logger.error(traceback.format_exc())
479
+ return reporter_pb2.ReportOCMetricsReply()
480
+
481
+ @staticmethod
482
+ def _get_cpu_percent(in_k8s: bool):
483
+ if in_k8s:
484
+ return k8s_utils.cpu_percent()
485
+ else:
486
+ return psutil.cpu_percent()
487
+
488
+ @staticmethod
489
+ def _get_gpu_usage():
490
+ import ray._private.thirdparty.pynvml as pynvml
491
+
492
+ global enable_gpu_usage_check
493
+ if not enable_gpu_usage_check:
494
+ return []
495
+ gpu_utilizations = []
496
+
497
+ def decode(b: Union[str, bytes]) -> str:
498
+ if isinstance(b, bytes):
499
+ return b.decode("utf-8") # for python3, to unicode
500
+ return b
501
+
502
+ try:
503
+ pynvml.nvmlInit()
504
+ except Exception as e:
505
+ logger.debug(f"pynvml failed to retrieve GPU information: {e}")
506
+
507
+ # On machines without GPUs, pynvml.nvmlInit() can run subprocesses that
508
+ # spew to stderr. Then with log_to_driver=True, we get log spew from every
509
+ # single raylet. To avoid this, disable the GPU usage check on
510
+ # certain errors.
511
+ # https://github.com/ray-project/ray/issues/14305
512
+ # https://github.com/ray-project/ray/pull/21686
513
+ if type(e).__name__ == "NVMLError_DriverNotLoaded":
514
+ enable_gpu_usage_check = False
515
+ return gpu_utilizations
516
+
517
+ num_gpus = pynvml.nvmlDeviceGetCount()
518
+ for i in range(num_gpus):
519
+ gpu_handle = pynvml.nvmlDeviceGetHandleByIndex(i)
520
+ memory_info = pynvml.nvmlDeviceGetMemoryInfo(gpu_handle)
521
+ utilization = None
522
+ try:
523
+ utilization_info = pynvml.nvmlDeviceGetUtilizationRates(gpu_handle)
524
+ utilization = int(utilization_info.gpu)
525
+ except pynvml.NVMLError as e:
526
+ logger.debug(f"pynvml failed to retrieve GPU utilization: {e}")
527
+
528
+ # processes pids
529
+ processes_pids = None
530
+ try:
531
+ nv_comp_processes = pynvml.nvmlDeviceGetComputeRunningProcesses(
532
+ gpu_handle
533
+ )
534
+ nv_graphics_processes = pynvml.nvmlDeviceGetGraphicsRunningProcesses(
535
+ gpu_handle
536
+ )
537
+ processes_pids = [
538
+ ProcessGPUInfo(
539
+ pid=int(nv_process.pid),
540
+ gpu_memory_usage=int(nv_process.usedGpuMemory) // MB
541
+ if nv_process.usedGpuMemory
542
+ else 0,
543
+ )
544
+ for nv_process in (nv_comp_processes + nv_graphics_processes)
545
+ ]
546
+ except pynvml.NVMLError as e:
547
+ logger.debug(f"pynvml failed to retrieve GPU processes: {e}")
548
+
549
+ info = GpuUtilizationInfo(
550
+ index=i,
551
+ name=decode(pynvml.nvmlDeviceGetName(gpu_handle)),
552
+ uuid=decode(pynvml.nvmlDeviceGetUUID(gpu_handle)),
553
+ utilization_gpu=utilization,
554
+ memory_used=int(memory_info.used) // MB,
555
+ memory_total=int(memory_info.total) // MB,
556
+ processes_pids=processes_pids,
557
+ )
558
+ gpu_utilizations.append(info)
559
+ pynvml.nvmlShutdown()
560
+
561
+ return gpu_utilizations
562
+
563
+ @staticmethod
564
+ def _get_boot_time():
565
+ if IN_KUBERNETES_POD:
566
+ # Return start time of container entrypoint
567
+ return psutil.Process(pid=1).create_time()
568
+ else:
569
+ return psutil.boot_time()
570
+
571
+ @staticmethod
572
+ def _get_network_stats():
573
+ ifaces = [
574
+ v for k, v in psutil.net_io_counters(pernic=True).items() if k[0] == "e"
575
+ ]
576
+
577
+ sent = sum((iface.bytes_sent for iface in ifaces))
578
+ recv = sum((iface.bytes_recv for iface in ifaces))
579
+ return sent, recv
580
+
581
+ @staticmethod
582
+ def _get_mem_usage():
583
+ total = ray._private.utils.get_system_memory()
584
+ used = ray._private.utils.get_used_memory()
585
+ available = total - used
586
+ percent = round(used / total, 3) * 100
587
+ return total, available, percent, used
588
+
589
+ @staticmethod
590
+ def _get_disk_usage():
591
+ if IN_KUBERNETES_POD and not ENABLE_K8S_DISK_USAGE:
592
+ # If in a K8s pod, disable disk display by passing in dummy values.
593
+ return {
594
+ "/": psutil._common.sdiskusage(total=1, used=0, free=1, percent=0.0)
595
+ }
596
+ if sys.platform == "win32":
597
+ root = psutil.disk_partitions()[0].mountpoint
598
+ else:
599
+ root = os.sep
600
+ tmp = ray._private.utils.get_user_temp_dir()
601
+ return {
602
+ "/": psutil.disk_usage(root),
603
+ tmp: psutil.disk_usage(tmp),
604
+ }
605
+
606
+ @staticmethod
607
+ def _get_disk_io_stats():
608
+ stats = psutil.disk_io_counters()
609
+ # stats can be None or {} if the machine is diskless.
610
+ # https://psutil.readthedocs.io/en/latest/#psutil.disk_io_counters
611
+ if not stats:
612
+ return (0, 0, 0, 0)
613
+ else:
614
+ return (
615
+ stats.read_bytes,
616
+ stats.write_bytes,
617
+ stats.read_count,
618
+ stats.write_count,
619
+ )
620
+
621
+ def _get_agent_proc(self) -> psutil.Process:
622
+ # Agent is the current process.
623
+ # This method is not necessary, but we have it for mock testing.
624
+ return psutil.Process()
625
+
626
+ def _generate_worker_key(self, proc: psutil.Process) -> Tuple[int, float]:
627
+ return (proc.pid, proc.create_time())
628
+
629
+ def _get_workers(self):
630
+ raylet_proc = self._get_raylet_proc()
631
+
632
+ if raylet_proc is None:
633
+ return []
634
+ else:
635
+ workers = {}
636
+ if sys.platform == "win32":
637
+ # windows, get the child process not the runner
638
+ for child in raylet_proc.children():
639
+ if child.children():
640
+ child = child.children()[0]
641
+ workers[self._generate_worker_key(child)] = child
642
+ else:
643
+ workers = {
644
+ self._generate_worker_key(proc): proc
645
+ for proc in raylet_proc.children()
646
+ }
647
+
648
+ # We should keep `raylet_proc.children()` in `self` because
649
+ # when `cpu_percent` is first called, it returns the meaningless 0.
650
+ # See more: https://github.com/ray-project/ray/issues/29848
651
+ keys_to_pop = []
652
+ # Add all new workers.
653
+ for key, worker in workers.items():
654
+ if key not in self._workers:
655
+ self._workers[key] = worker
656
+
657
+ # Pop out stale workers.
658
+ for key in self._workers:
659
+ if key not in workers:
660
+ keys_to_pop.append(key)
661
+ for k in keys_to_pop:
662
+ self._workers.pop(k)
663
+
664
+ # Remove the current process (reporter agent), which is also a child of
665
+ # the Raylet.
666
+ self._workers.pop(self._generate_worker_key(self._get_agent_proc()))
667
+
668
+ result = []
669
+ for w in self._workers.values():
670
+ try:
671
+ if w.status() == psutil.STATUS_ZOMBIE:
672
+ continue
673
+ except psutil.NoSuchProcess:
674
+ # the process may have terminated due to race condition.
675
+ continue
676
+
677
+ result.append(w.as_dict(attrs=PSUTIL_PROCESS_ATTRS))
678
+ return result
679
+
680
+ def _get_raylet_proc(self):
681
+ try:
682
+ if not self._raylet_proc:
683
+ curr_proc = psutil.Process()
684
+ # The dashboard agent is a child of the raylet process.
685
+ # It is not necessarily the direct child (python-windows
686
+ # typically uses a py.exe runner to run python), so search
687
+ # up for a process named 'raylet'
688
+ candidate = curr_proc.parent()
689
+ while candidate:
690
+ if "raylet" in candidate.name():
691
+ break
692
+ candidate = candidate.parent()
693
+ self._raylet_proc = candidate
694
+
695
+ if self._raylet_proc is not None:
696
+ if self._raylet_proc.pid == 1:
697
+ return None
698
+ if self._raylet_proc.status() == psutil.STATUS_ZOMBIE:
699
+ return None
700
+ return self._raylet_proc
701
+ except (psutil.AccessDenied, ProcessLookupError):
702
+ pass
703
+ return None
704
+
705
+ def _get_raylet(self):
706
+ raylet_proc = self._get_raylet_proc()
707
+ if raylet_proc is None:
708
+ return {}
709
+ else:
710
+ return raylet_proc.as_dict(attrs=PSUTIL_PROCESS_ATTRS)
711
+
712
+ def _get_agent(self):
713
+ # Current proc == agent proc
714
+ if not self._agent_proc:
715
+ self._agent_proc = psutil.Process()
716
+ return self._agent_proc.as_dict(attrs=PSUTIL_PROCESS_ATTRS)
717
+
718
+ def _get_load_avg(self):
719
+ if sys.platform == "win32":
720
+ cpu_percent = psutil.cpu_percent()
721
+ load = (cpu_percent, cpu_percent, cpu_percent)
722
+ else:
723
+ load = os.getloadavg()
724
+ if self._cpu_counts[0] > 0:
725
+ per_cpu_load = tuple((round(x / self._cpu_counts[0], 2) for x in load))
726
+ else:
727
+ per_cpu_load = None
728
+ return load, per_cpu_load
729
+
730
+ @staticmethod
731
+ def _compute_speed_from_hist(hist):
732
+ while len(hist) > 7:
733
+ hist.pop(0)
734
+ then, prev_stats = hist[0]
735
+ now, now_stats = hist[-1]
736
+ time_delta = now - then
737
+ return tuple((y - x) / time_delta for x, y in zip(prev_stats, now_stats))
738
+
739
+ def _get_shm_usage(self):
740
+ """Return the shm usage.
741
+
742
+ If shm doesn't exist (e.g., MacOS), it returns None.
743
+ """
744
+ mem = psutil.virtual_memory()
745
+ if not hasattr(mem, "shared"):
746
+ return None
747
+ return mem.shared
748
+
749
+ def _collect_stats(self):
750
+ now = dashboard_utils.to_posix_time(datetime.datetime.utcnow())
751
+ network_stats = self._get_network_stats()
752
+ self._network_stats_hist.append((now, network_stats))
753
+ network_speed_stats = self._compute_speed_from_hist(self._network_stats_hist)
754
+
755
+ disk_stats = self._get_disk_io_stats()
756
+ self._disk_io_stats_hist.append((now, disk_stats))
757
+ disk_speed_stats = self._compute_speed_from_hist(self._disk_io_stats_hist)
758
+
759
+ return {
760
+ "now": now,
761
+ "hostname": self._hostname,
762
+ "ip": self._ip,
763
+ "cpu": self._get_cpu_percent(IN_KUBERNETES_POD),
764
+ "cpus": self._cpu_counts,
765
+ "mem": self._get_mem_usage(),
766
+ # Unit is in bytes. None if
767
+ "shm": self._get_shm_usage(),
768
+ "workers": self._get_workers(),
769
+ "raylet": self._get_raylet(),
770
+ "agent": self._get_agent(),
771
+ "bootTime": self._get_boot_time(),
772
+ "loadAvg": self._get_load_avg(),
773
+ "disk": self._get_disk_usage(),
774
+ "disk_io": disk_stats,
775
+ "disk_io_speed": disk_speed_stats,
776
+ "gpus": self._get_gpu_usage(),
777
+ "network": network_stats,
778
+ "network_speed": network_speed_stats,
779
+ # Deprecated field, should be removed with frontend.
780
+ "cmdline": self._get_raylet().get("cmdline", []),
781
+ }
782
+
783
+ def _generate_reseted_stats_record(self, component_name: str) -> List[Record]:
784
+ """Return a list of Record that will reset
785
+ the system metrics of a given component name.
786
+
787
+ Args:
788
+ component_name: a component name for a given stats.
789
+
790
+ Returns:
791
+ a list of Record instances of all values 0.
792
+ """
793
+ tags = {"ip": self._ip, "Component": component_name}
794
+
795
+ records = []
796
+ records.append(
797
+ Record(
798
+ gauge=METRICS_GAUGES["component_cpu_percentage"],
799
+ value=0.0,
800
+ tags=tags,
801
+ )
802
+ )
803
+ records.append(
804
+ Record(
805
+ gauge=METRICS_GAUGES["component_mem_shared_bytes"],
806
+ value=0.0,
807
+ tags=tags,
808
+ )
809
+ )
810
+ records.append(
811
+ Record(
812
+ gauge=METRICS_GAUGES["component_rss_mb"],
813
+ value=0.0,
814
+ tags=tags,
815
+ )
816
+ )
817
+ records.append(
818
+ Record(
819
+ gauge=METRICS_GAUGES["component_uss_mb"],
820
+ value=0.0,
821
+ tags=tags,
822
+ )
823
+ )
824
+ records.append(
825
+ Record(
826
+ gauge=METRICS_GAUGES["component_num_fds"],
827
+ value=0,
828
+ tags=tags,
829
+ )
830
+ )
831
+ return records
832
+
833
+ def _generate_system_stats_record(
834
+ self, stats: List[dict], component_name: str, pid: Optional[str] = None
835
+ ) -> List[Record]:
836
+ """Generate a list of Record class from a given component names.
837
+
838
+ Args:
839
+ stats: a list of stats dict generated by `psutil.as_dict`.
840
+ If empty, it will create the metrics of a given "component_name"
841
+ which has all 0 values.
842
+ component_name: a component name for a given stats.
843
+ pid: optionally provided pids.
844
+
845
+ Returns:
846
+ a list of Record class that will be exposed to Prometheus.
847
+ """
848
+ total_cpu_percentage = 0.0
849
+ total_rss = 0.0
850
+ total_uss = 0.0
851
+ total_shm = 0.0
852
+ total_num_fds = 0
853
+
854
+ for stat in stats:
855
+ total_cpu_percentage += float(stat.get("cpu_percent", 0.0)) # noqa
856
+ memory_info = stat.get("memory_info")
857
+ if memory_info:
858
+ mem = stat["memory_info"]
859
+ total_rss += float(mem.rss) / 1.0e6
860
+ if hasattr(mem, "shared"):
861
+ total_shm += float(mem.shared)
862
+ mem_full_info = stat.get("memory_full_info")
863
+ if mem_full_info is not None:
864
+ total_uss += float(mem_full_info.uss) / 1.0e6
865
+ total_num_fds += int(stat.get("num_fds", 0))
866
+
867
+ tags = {"ip": self._ip, "Component": component_name}
868
+ if pid:
869
+ tags["pid"] = pid
870
+
871
+ records = []
872
+ records.append(
873
+ Record(
874
+ gauge=METRICS_GAUGES["component_cpu_percentage"],
875
+ value=total_cpu_percentage,
876
+ tags=tags,
877
+ )
878
+ )
879
+ records.append(
880
+ Record(
881
+ gauge=METRICS_GAUGES["component_mem_shared_bytes"],
882
+ value=total_shm,
883
+ tags=tags,
884
+ )
885
+ )
886
+ records.append(
887
+ Record(
888
+ gauge=METRICS_GAUGES["component_rss_mb"],
889
+ value=total_rss,
890
+ tags=tags,
891
+ )
892
+ )
893
+ if total_uss > 0.0:
894
+ records.append(
895
+ Record(
896
+ gauge=METRICS_GAUGES["component_uss_mb"],
897
+ value=total_uss,
898
+ tags=tags,
899
+ )
900
+ )
901
+ records.append(
902
+ Record(
903
+ gauge=METRICS_GAUGES["component_num_fds"],
904
+ value=total_num_fds,
905
+ tags=tags,
906
+ )
907
+ )
908
+
909
+ return records
910
+
911
+ def generate_worker_stats_record(self, worker_stats: List[dict]) -> List[Record]:
912
+ """Generate a list of Record class for worker proceses.
913
+
914
+ This API automatically sets the component_name of record as
915
+ the name of worker processes. I.e., ray::* so that we can report
916
+ per task/actor (grouped by a func/class name) resource usages.
917
+
918
+ Args:
919
+ stats: a list of stats dict generated by `psutil.as_dict`
920
+ for worker processes.
921
+ """
922
+ # worekr cmd name (ray::*) -> stats dict.
923
+ proc_name_to_stats = defaultdict(list)
924
+ for stat in worker_stats:
925
+ cmdline = stat.get("cmdline")
926
+ # All ray processes start with ray::
927
+ if cmdline and len(cmdline) > 0 and cmdline[0].startswith("ray::"):
928
+ proc_name = cmdline[0]
929
+ proc_name_to_stats[proc_name].append(stat)
930
+ # We will lose worker stats that don't follow the ray worker proc
931
+ # naming convention. Theoretically, there should be no data loss here
932
+ # because all worker processes are renamed to ray::.
933
+
934
+ records = []
935
+ for proc_name, stats in proc_name_to_stats.items():
936
+ records.extend(self._generate_system_stats_record(stats, proc_name))
937
+
938
+ # Reset worker metrics that are from finished processes.
939
+ new_proc_names = set(proc_name_to_stats.keys())
940
+ stale_procs = self._latest_worker_proc_names - new_proc_names
941
+ self._latest_worker_proc_names = new_proc_names
942
+
943
+ for stale_proc_name in stale_procs:
944
+ records.extend(self._generate_reseted_stats_record(stale_proc_name))
945
+
946
+ return records
947
+
948
+ def _to_records(self, stats, cluster_stats) -> List[Record]:
949
+ records_reported = []
950
+ ip = stats["ip"]
951
+ is_head_node = str(self._is_head_node).lower()
952
+
953
+ # Common tags for node-level metrics
954
+ node_tags = {"ip": ip, "IsHeadNode": is_head_node}
955
+
956
+ # -- Instance count of cluster --
957
+ # Only report cluster stats on head node
958
+ if "autoscaler_report" in cluster_stats and self._is_head_node:
959
+ active_nodes = cluster_stats["autoscaler_report"]["active_nodes"]
960
+ for node_type, active_node_count in active_nodes.items():
961
+ records_reported.append(
962
+ Record(
963
+ gauge=METRICS_GAUGES["cluster_active_nodes"],
964
+ value=active_node_count,
965
+ tags={"node_type": node_type},
966
+ )
967
+ )
968
+
969
+ failed_nodes = cluster_stats["autoscaler_report"]["failed_nodes"]
970
+ failed_nodes_dict = {}
971
+ for node_ip, node_type in failed_nodes:
972
+ if node_type in failed_nodes_dict:
973
+ failed_nodes_dict[node_type] += 1
974
+ else:
975
+ failed_nodes_dict[node_type] = 1
976
+
977
+ for node_type, failed_node_count in failed_nodes_dict.items():
978
+ records_reported.append(
979
+ Record(
980
+ gauge=METRICS_GAUGES["cluster_failed_nodes"],
981
+ value=failed_node_count,
982
+ tags={"node_type": node_type},
983
+ )
984
+ )
985
+
986
+ pending_nodes = cluster_stats["autoscaler_report"]["pending_nodes"]
987
+ pending_nodes_dict = {}
988
+ for node_ip, node_type, status_message in pending_nodes:
989
+ if node_type in pending_nodes_dict:
990
+ pending_nodes_dict[node_type] += 1
991
+ else:
992
+ pending_nodes_dict[node_type] = 1
993
+
994
+ for node_type, pending_node_count in pending_nodes_dict.items():
995
+ records_reported.append(
996
+ Record(
997
+ gauge=METRICS_GAUGES["cluster_pending_nodes"],
998
+ value=pending_node_count,
999
+ tags={"node_type": node_type},
1000
+ )
1001
+ )
1002
+
1003
+ # -- CPU per node --
1004
+ cpu_usage = float(stats["cpu"])
1005
+ cpu_record = Record(
1006
+ gauge=METRICS_GAUGES["node_cpu_utilization"],
1007
+ value=cpu_usage,
1008
+ tags=node_tags,
1009
+ )
1010
+
1011
+ cpu_count, _ = stats["cpus"]
1012
+ cpu_count_record = Record(
1013
+ gauge=METRICS_GAUGES["node_cpu_count"], value=cpu_count, tags=node_tags
1014
+ )
1015
+
1016
+ # -- Mem per node --
1017
+ mem_total, mem_available, _, mem_used = stats["mem"]
1018
+ mem_used_record = Record(
1019
+ gauge=METRICS_GAUGES["node_mem_used"], value=mem_used, tags=node_tags
1020
+ )
1021
+ mem_available_record = Record(
1022
+ gauge=METRICS_GAUGES["node_mem_available"],
1023
+ value=mem_available,
1024
+ tags=node_tags,
1025
+ )
1026
+ mem_total_record = Record(
1027
+ gauge=METRICS_GAUGES["node_mem_total"], value=mem_total, tags=node_tags
1028
+ )
1029
+
1030
+ shm_used = stats["shm"]
1031
+ if shm_used:
1032
+ node_mem_shared = Record(
1033
+ gauge=METRICS_GAUGES["node_mem_shared_bytes"],
1034
+ value=shm_used,
1035
+ tags=node_tags,
1036
+ )
1037
+ records_reported.append(node_mem_shared)
1038
+
1039
+ # The output example of GpuUtilizationInfo.
1040
+ """
1041
+ {'index': 0,
1042
+ 'uuid': 'GPU-36e1567d-37ed-051e-f8ff-df807517b396',
1043
+ 'name': 'NVIDIA A10G',
1044
+ 'utilization_gpu': 1,
1045
+ 'memory_used': 0,
1046
+ 'memory_total': 22731}
1047
+ """
1048
+ # -- GPU per node --
1049
+ gpus = stats["gpus"]
1050
+ gpus_available = len(gpus)
1051
+
1052
+ if gpus_available:
1053
+ for gpu in gpus:
1054
+ gpus_utilization, gram_used, gram_total = 0, 0, 0
1055
+ # Consume GPU may not report its utilization.
1056
+ if gpu["utilization_gpu"] is not None:
1057
+ gpus_utilization += gpu["utilization_gpu"]
1058
+ gram_used += gpu["memory_used"]
1059
+ gram_total += gpu["memory_total"]
1060
+ gpu_index = gpu.get("index")
1061
+ gpu_name = gpu.get("name")
1062
+
1063
+ gram_available = gram_total - gram_used
1064
+
1065
+ if gpu_index is not None:
1066
+ gpu_tags = {**node_tags, "GpuIndex": str(gpu_index)}
1067
+ if gpu_name:
1068
+ gpu_tags["GpuDeviceName"] = gpu_name
1069
+
1070
+ # There's only 1 GPU per each index, so we record 1 here.
1071
+ gpus_available_record = Record(
1072
+ gauge=METRICS_GAUGES["node_gpus_available"],
1073
+ value=1,
1074
+ tags=gpu_tags,
1075
+ )
1076
+ gpus_utilization_record = Record(
1077
+ gauge=METRICS_GAUGES["node_gpus_utilization"],
1078
+ value=gpus_utilization,
1079
+ tags=gpu_tags,
1080
+ )
1081
+ gram_used_record = Record(
1082
+ gauge=METRICS_GAUGES["node_gram_used"],
1083
+ value=gram_used,
1084
+ tags=gpu_tags,
1085
+ )
1086
+ gram_available_record = Record(
1087
+ gauge=METRICS_GAUGES["node_gram_available"],
1088
+ value=gram_available,
1089
+ tags=gpu_tags,
1090
+ )
1091
+ records_reported.extend(
1092
+ [
1093
+ gpus_available_record,
1094
+ gpus_utilization_record,
1095
+ gram_used_record,
1096
+ gram_available_record,
1097
+ ]
1098
+ )
1099
+
1100
+ # -- Disk per node --
1101
+ disk_io_stats = stats["disk_io"]
1102
+ disk_read_record = Record(
1103
+ gauge=METRICS_GAUGES["node_disk_io_read"],
1104
+ value=disk_io_stats[0],
1105
+ tags=node_tags,
1106
+ )
1107
+ disk_write_record = Record(
1108
+ gauge=METRICS_GAUGES["node_disk_io_write"],
1109
+ value=disk_io_stats[1],
1110
+ tags=node_tags,
1111
+ )
1112
+ disk_read_count_record = Record(
1113
+ gauge=METRICS_GAUGES["node_disk_io_read_count"],
1114
+ value=disk_io_stats[2],
1115
+ tags=node_tags,
1116
+ )
1117
+ disk_write_count_record = Record(
1118
+ gauge=METRICS_GAUGES["node_disk_io_write_count"],
1119
+ value=disk_io_stats[3],
1120
+ tags=node_tags,
1121
+ )
1122
+ disk_io_speed_stats = stats["disk_io_speed"]
1123
+ disk_read_speed_record = Record(
1124
+ gauge=METRICS_GAUGES["node_disk_io_read_speed"],
1125
+ value=disk_io_speed_stats[0],
1126
+ tags=node_tags,
1127
+ )
1128
+ disk_write_speed_record = Record(
1129
+ gauge=METRICS_GAUGES["node_disk_io_write_speed"],
1130
+ value=disk_io_speed_stats[1],
1131
+ tags=node_tags,
1132
+ )
1133
+ disk_read_iops_record = Record(
1134
+ gauge=METRICS_GAUGES["node_disk_read_iops"],
1135
+ value=disk_io_speed_stats[2],
1136
+ tags=node_tags,
1137
+ )
1138
+ disk_write_iops_record = Record(
1139
+ gauge=METRICS_GAUGES["node_disk_write_iops"],
1140
+ value=disk_io_speed_stats[3],
1141
+ tags=node_tags,
1142
+ )
1143
+ used = stats["disk"]["/"].used
1144
+ free = stats["disk"]["/"].free
1145
+ disk_utilization = float(used / (used + free)) * 100
1146
+ disk_usage_record = Record(
1147
+ gauge=METRICS_GAUGES["node_disk_usage"], value=used, tags=node_tags
1148
+ )
1149
+ disk_free_record = Record(
1150
+ gauge=METRICS_GAUGES["node_disk_free"], value=free, tags=node_tags
1151
+ )
1152
+ disk_utilization_percentage_record = Record(
1153
+ gauge=METRICS_GAUGES["node_disk_utilization_percentage"],
1154
+ value=disk_utilization,
1155
+ tags=node_tags,
1156
+ )
1157
+
1158
+ # -- Network speed (send/receive) stats per node --
1159
+ network_stats = stats["network"]
1160
+ network_sent_record = Record(
1161
+ gauge=METRICS_GAUGES["node_network_sent"],
1162
+ value=network_stats[0],
1163
+ tags=node_tags,
1164
+ )
1165
+ network_received_record = Record(
1166
+ gauge=METRICS_GAUGES["node_network_received"],
1167
+ value=network_stats[1],
1168
+ tags=node_tags,
1169
+ )
1170
+
1171
+ # -- Network speed (send/receive) per node --
1172
+ network_speed_stats = stats["network_speed"]
1173
+ network_send_speed_record = Record(
1174
+ gauge=METRICS_GAUGES["node_network_send_speed"],
1175
+ value=network_speed_stats[0],
1176
+ tags=node_tags,
1177
+ )
1178
+ network_receive_speed_record = Record(
1179
+ gauge=METRICS_GAUGES["node_network_receive_speed"],
1180
+ value=network_speed_stats[1],
1181
+ tags=node_tags,
1182
+ )
1183
+
1184
+ """
1185
+ Record system stats.
1186
+ """
1187
+
1188
+ # Record component metrics.
1189
+ raylet_stats = stats["raylet"]
1190
+ if raylet_stats:
1191
+ raylet_pid = str(raylet_stats["pid"])
1192
+ records_reported.extend(
1193
+ self._generate_system_stats_record(
1194
+ [raylet_stats], "raylet", pid=raylet_pid
1195
+ )
1196
+ )
1197
+ workers_stats = stats["workers"]
1198
+ records_reported.extend(self.generate_worker_stats_record(workers_stats))
1199
+ agent_stats = stats["agent"]
1200
+ if agent_stats:
1201
+ agent_pid = str(agent_stats["pid"])
1202
+ records_reported.extend(
1203
+ self._generate_system_stats_record(
1204
+ [agent_stats], "agent", pid=agent_pid
1205
+ )
1206
+ )
1207
+
1208
+ # TODO(sang): Record GCS metrics.
1209
+ # NOTE: Dashboard metrics is recorded within the dashboard because
1210
+ # it can be deployed as a standalone instance. It shouldn't
1211
+ # depend on the agent.
1212
+
1213
+ records_reported.extend(
1214
+ [
1215
+ cpu_record,
1216
+ cpu_count_record,
1217
+ mem_used_record,
1218
+ mem_available_record,
1219
+ mem_total_record,
1220
+ disk_read_record,
1221
+ disk_write_record,
1222
+ disk_read_count_record,
1223
+ disk_write_count_record,
1224
+ disk_read_speed_record,
1225
+ disk_write_speed_record,
1226
+ disk_read_iops_record,
1227
+ disk_write_iops_record,
1228
+ disk_usage_record,
1229
+ disk_free_record,
1230
+ disk_utilization_percentage_record,
1231
+ network_sent_record,
1232
+ network_received_record,
1233
+ network_send_speed_record,
1234
+ network_receive_speed_record,
1235
+ ]
1236
+ )
1237
+
1238
+ return records_reported
1239
+
1240
+ async def _run_loop(self, publisher):
1241
+ """Get any changes to the log files and push updates to kv."""
1242
+ loop = utils.get_or_create_event_loop()
1243
+
1244
+ while True:
1245
+ try:
1246
+ # Fetch autoscaler debug status
1247
+ autoscaler_status_json_bytes: Optional[
1248
+ bytes
1249
+ ] = await self._gcs_aio_client.internal_kv_get(
1250
+ DEBUG_AUTOSCALING_STATUS.encode(),
1251
+ None,
1252
+ timeout=GCS_RPC_TIMEOUT_SECONDS,
1253
+ )
1254
+
1255
+ # NOTE: Stats collection is executed inside the thread-pool
1256
+ # executor (TPE) to avoid blocking the Agent's event-loop
1257
+ json_payload = await loop.run_in_executor(
1258
+ self._executor,
1259
+ self._compose_stats_payload,
1260
+ autoscaler_status_json_bytes,
1261
+ )
1262
+
1263
+ await publisher.publish_resource_usage(self._key, json_payload)
1264
+
1265
+ except Exception:
1266
+ logger.exception("Error publishing node physical stats.")
1267
+
1268
+ await asyncio.sleep(reporter_consts.REPORTER_UPDATE_INTERVAL_MS / 1000)
1269
+
1270
+ def _compose_stats_payload(
1271
+ self, cluster_autoscaling_stats_json: Optional[bytes]
1272
+ ) -> str:
1273
+ stats = self._collect_stats()
1274
+
1275
+ # Report stats only when metrics collection is enabled.
1276
+ if not self._metrics_collection_disabled:
1277
+ cluster_stats = (
1278
+ json.loads(cluster_autoscaling_stats_json.decode())
1279
+ if cluster_autoscaling_stats_json
1280
+ else {}
1281
+ )
1282
+
1283
+ records = self._to_records(stats, cluster_stats)
1284
+
1285
+ self._metrics_agent.record_and_export(
1286
+ records,
1287
+ global_tags={
1288
+ "Version": ray.__version__,
1289
+ "SessionName": self._session_name,
1290
+ },
1291
+ )
1292
+
1293
+ self._metrics_agent.clean_all_dead_worker_metrics()
1294
+
1295
+ return jsonify_asdict(stats)
1296
+
1297
+ async def run(self, server):
1298
+ if server:
1299
+ reporter_pb2_grpc.add_ReporterServiceServicer_to_server(self, server)
1300
+
1301
+ await self._run_loop(self._dashboard_agent.publisher)
1302
+
1303
+ @staticmethod
1304
+ def is_minimal_module():
1305
+ return False
vllm/lib/python3.10/site-packages/ray/dashboard/modules/reporter/reporter_consts.py ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ import ray._private.ray_constants as ray_constants
2
+
3
+ REPORTER_PREFIX = "RAY_REPORTER:"
4
+ # The reporter will report its statistics this often (milliseconds).
5
+ REPORTER_UPDATE_INTERVAL_MS = ray_constants.env_integer(
6
+ "REPORTER_UPDATE_INTERVAL_MS", 5000
7
+ )
vllm/lib/python3.10/site-packages/ray/dashboard/modules/reporter/reporter_head.py ADDED
@@ -0,0 +1,669 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import json
3
+ import logging
4
+ from concurrent.futures import ThreadPoolExecutor
5
+ from typing import List, Optional, Tuple
6
+
7
+ import aiohttp.web
8
+
9
+ import ray.dashboard.optional_utils as dashboard_optional_utils
10
+ import ray.dashboard.utils as dashboard_utils
11
+ from ray._private.gcs_pubsub import GcsAioResourceUsageSubscriber
12
+ from ray._private.metrics_agent import PrometheusServiceDiscoveryWriter
13
+ from ray._private.ray_constants import (
14
+ DEBUG_AUTOSCALING_ERROR,
15
+ DEBUG_AUTOSCALING_STATUS,
16
+ DEBUG_AUTOSCALING_STATUS_LEGACY,
17
+ GLOBAL_GRPC_OPTIONS,
18
+ KV_NAMESPACE_CLUSTER,
19
+ env_integer,
20
+ )
21
+ from ray._private.usage.usage_constants import CLUSTER_METADATA_KEY
22
+ from ray._private.utils import get_or_create_event_loop, init_grpc_channel
23
+ from ray.autoscaler._private.commands import debug_status
24
+ from ray.core.generated import reporter_pb2, reporter_pb2_grpc
25
+ from ray.dashboard.consts import GCS_RPC_TIMEOUT_SECONDS
26
+ from ray.dashboard.datacenter import DataSource
27
+ from ray.dashboard.state_aggregator import StateAPIManager
28
+ from ray.util.state.common import ListApiOptions
29
+ from ray.util.state.state_manager import StateDataSourceClient
30
+
31
+ logger = logging.getLogger(__name__)
32
+ routes = dashboard_optional_utils.DashboardHeadRouteTable
33
+
34
+ EMOJI_WARNING = "&#x26A0;&#xFE0F;"
35
+ WARNING_FOR_MULTI_TASK_IN_A_WORKER = (
36
+ "Warning: This task is running in a worker process that is running multiple tasks. "
37
+ "This can happen if you are profiling a task right as it finishes or if you"
38
+ "are using the Async Actor or Threaded Actors pattern. "
39
+ "The information that follows may come from any of these tasks:"
40
+ )
41
+ SVG_STYLE = """<style>
42
+ svg {
43
+ width: 100%;
44
+ height: 100%;
45
+ }
46
+ </style>\n"""
47
+
48
+ # NOTE: Executor in this head is intentionally constrained to just 1 thread by
49
+ # default to limit its concurrency, therefore reducing potential for
50
+ # GIL contention
51
+ RAY_DASHBOARD_REPORTER_HEAD_TPE_MAX_WORKERS = env_integer(
52
+ "RAY_DASHBOARD_REPORTER_HEAD_TPE_MAX_WORKERS", 1
53
+ )
54
+
55
+
56
+ class ReportHead(dashboard_utils.DashboardHeadModule):
57
+ def __init__(self, dashboard_head):
58
+ super().__init__(dashboard_head)
59
+ self._stubs = {}
60
+ self._ray_config = None
61
+ DataSource.agents.signal.append(self._update_stubs)
62
+ # TODO(fyrestone): Avoid using ray.state in dashboard, it's not
63
+ # asynchronous and will lead to low performance. ray disconnect()
64
+ # will be hang when the ray.state is connected and the GCS is exit.
65
+ # Please refer to: https://github.com/ray-project/ray/issues/16328
66
+ assert dashboard_head.gcs_address or dashboard_head.redis_address
67
+ self._gcs_address = dashboard_head.gcs_address
68
+ temp_dir = dashboard_head.temp_dir
69
+ self.service_discovery = PrometheusServiceDiscoveryWriter(
70
+ self._gcs_address, temp_dir
71
+ )
72
+ self._gcs_aio_client = dashboard_head.gcs_aio_client
73
+ self._state_api = None
74
+
75
+ self._executor = ThreadPoolExecutor(
76
+ max_workers=RAY_DASHBOARD_REPORTER_HEAD_TPE_MAX_WORKERS,
77
+ thread_name_prefix="reporter_head_executor",
78
+ )
79
+
80
+ async def _update_stubs(self, change):
81
+ if change.old:
82
+ node_id, port = change.old
83
+ ip = DataSource.nodes[node_id]["nodeManagerAddress"]
84
+ self._stubs.pop(ip, None)
85
+ if change.new:
86
+ node_id, ports = change.new
87
+ ip = DataSource.nodes[node_id]["nodeManagerAddress"]
88
+ options = GLOBAL_GRPC_OPTIONS
89
+ channel = init_grpc_channel(
90
+ f"{ip}:{ports[1]}", options=options, asynchronous=True
91
+ )
92
+ stub = reporter_pb2_grpc.ReporterServiceStub(channel)
93
+ self._stubs[ip] = stub
94
+
95
+ @routes.get("/api/v0/cluster_metadata")
96
+ async def get_cluster_metadata(self, req):
97
+ return dashboard_optional_utils.rest_response(
98
+ success=True, message="", **self.cluster_metadata
99
+ )
100
+
101
+ @routes.get("/api/cluster_status")
102
+ async def get_cluster_status(self, req):
103
+ """Returns status information about the cluster.
104
+
105
+ Currently contains two fields:
106
+ autoscaling_status (str)-- a status message from the autoscaler.
107
+ autoscaling_error (str)-- an error message from the autoscaler if
108
+ anything has gone wrong during autoscaling.
109
+
110
+ These fields are both read from the GCS, it's expected that the
111
+ autoscaler writes them there.
112
+ """
113
+ # TODO(rickyx): We should be able to get the cluster status from the
114
+ # autoscaler directly with V2. And we should be able to return structured data
115
+ # rather than a string.
116
+
117
+ return_formatted_output = req.query.get("format", "0") == "1"
118
+
119
+ (legacy_status, formatted_status_string, error) = await asyncio.gather(
120
+ *[
121
+ self._gcs_aio_client.internal_kv_get(
122
+ key.encode(), namespace=None, timeout=GCS_RPC_TIMEOUT_SECONDS
123
+ )
124
+ for key in [
125
+ DEBUG_AUTOSCALING_STATUS_LEGACY,
126
+ DEBUG_AUTOSCALING_STATUS,
127
+ DEBUG_AUTOSCALING_ERROR,
128
+ ]
129
+ ]
130
+ )
131
+
132
+ formatted_status = (
133
+ json.loads(formatted_status_string.decode())
134
+ if formatted_status_string
135
+ else {}
136
+ )
137
+
138
+ if not return_formatted_output:
139
+ return dashboard_optional_utils.rest_response(
140
+ success=True,
141
+ message="Got cluster status.",
142
+ autoscaling_status=legacy_status.decode() if legacy_status else None,
143
+ autoscaling_error=error.decode() if error else None,
144
+ cluster_status=formatted_status if formatted_status else None,
145
+ )
146
+ else:
147
+ return dashboard_optional_utils.rest_response(
148
+ success=True,
149
+ message="Got formatted cluster status.",
150
+ cluster_status=debug_status(
151
+ formatted_status_string, error, address=self._gcs_address
152
+ ),
153
+ )
154
+
155
+ async def get_task_ids_running_in_a_worker(self, worker_id: str) -> List[str]:
156
+ """
157
+ Retrieves the task IDs of running tasks associated with a specific worker.
158
+
159
+ Args:
160
+ worker_id: The ID of the worker.
161
+
162
+ Returns:
163
+ List[str]: A list containing the task IDs
164
+ of all the running tasks associated with the worker.
165
+ """
166
+ option = ListApiOptions(
167
+ filters=[("worker_id", "=", worker_id), ("state", "=", "RUNNING")],
168
+ detail=True,
169
+ timeout=10,
170
+ )
171
+ # Call the state API to get all tasks in a worker
172
+ tasks_in_a_worker_result = await self._state_api.list_tasks(option=option)
173
+ tasks_in_a_worker = tasks_in_a_worker_result.result
174
+
175
+ # Get task_id from each task in a worker
176
+ task_ids_in_a_worker = [
177
+ task.get("task_id")
178
+ for task in tasks_in_a_worker
179
+ if task and "task_id" in task
180
+ ]
181
+ return task_ids_in_a_worker
182
+
183
+ async def get_worker_details_for_running_task(
184
+ self, task_id: str, attempt_number: int
185
+ ) -> Tuple[Optional[int], Optional[str]]:
186
+ """
187
+ Retrieves worker details for a specific task and attempt number.
188
+
189
+ Args:
190
+ task_id: The ID of the task.
191
+ attempt_number: The attempt number of the task.
192
+
193
+ Returns:
194
+ Tuple[Optional[int], Optional[str]]: A tuple
195
+ containing the worker's PID (process ID),
196
+ and worker's ID.
197
+
198
+ Raises:
199
+ ValueError: If the task attempt is not running or
200
+ the state APi is not initialized.
201
+ """
202
+ if self._state_api is None:
203
+ raise ValueError("The state API is not initialized yet. Please retry.")
204
+ option = ListApiOptions(
205
+ filters=[
206
+ ("task_id", "=", task_id),
207
+ ("attempt_number", "=", attempt_number),
208
+ ],
209
+ detail=True,
210
+ timeout=10,
211
+ )
212
+
213
+ result = await self._state_api.list_tasks(option=option)
214
+ tasks = result.result
215
+ if not tasks:
216
+ return None, None
217
+
218
+ pid = tasks[0]["worker_pid"]
219
+ worker_id = tasks[0]["worker_id"]
220
+
221
+ state = tasks[0]["state"]
222
+ if state != "RUNNING":
223
+ raise ValueError(
224
+ f"The task attempt is not running: the current state is {state}."
225
+ )
226
+
227
+ return pid, worker_id
228
+
229
+ @routes.get("/task/traceback")
230
+ async def get_task_traceback(self, req) -> aiohttp.web.Response:
231
+ """
232
+ Retrieves the traceback information for a specific task.
233
+ Note that one worker process works on one task at a time
234
+ or one worker works on multiple async tasks.
235
+
236
+ Args:
237
+ req (aiohttp.web.Request): The HTTP request object.
238
+
239
+ Returns:
240
+ aiohttp.web.Response: The HTTP response containing
241
+ the traceback information.
242
+
243
+ Raises:
244
+ ValueError: If the "task_id" parameter
245
+ is missing in the request query.
246
+ ValueError: If the "attempt_number" parameter
247
+ is missing in the request query.
248
+ ValueError: If the worker begins working on
249
+ another task during the traceback retrieval.
250
+ aiohttp.web.HTTPInternalServerError: If there is
251
+ an internal server error during the traceback retrieval.
252
+ """
253
+
254
+ if "task_id" not in req.query:
255
+ raise ValueError("task_id is required")
256
+ if "attempt_number" not in req.query:
257
+ raise ValueError("task's attempt number is required")
258
+ if "node_id" not in req.query:
259
+ raise ValueError("node_id is required")
260
+
261
+ task_id = req.query.get("task_id")
262
+ attempt_number = req.query.get("attempt_number")
263
+ node_id = req.query.get("node_id")
264
+
265
+ ip = DataSource.nodes[node_id]["nodeManagerAddress"]
266
+
267
+ reporter_stub = self._stubs[ip]
268
+
269
+ # Default not using `--native` for profiling
270
+ native = req.query.get("native", False) == "1"
271
+
272
+ try:
273
+ (pid, _) = await self.get_worker_details_for_running_task(
274
+ task_id, attempt_number
275
+ )
276
+ except ValueError as e:
277
+ raise aiohttp.web.HTTPInternalServerError(text=str(e))
278
+
279
+ logger.info(
280
+ "Sending stack trace request to {}:{} with native={}".format(
281
+ ip, pid, native
282
+ )
283
+ )
284
+ reply = await reporter_stub.GetTraceback(
285
+ reporter_pb2.GetTracebackRequest(pid=pid, native=native)
286
+ )
287
+
288
+ """
289
+ In order to truly confirm whether there are any other tasks
290
+ running during the profiling, we need to retrieve all tasks
291
+ that are currently running or have finished, and then parse
292
+ the task events (i.e., their start and finish times) to check
293
+ for any potential overlap. However, this process can be
294
+ quite extensive, so here we will make our best efforts
295
+ to check for any overlapping tasks.
296
+ Therefore, we will check if the task is still running
297
+ """
298
+ try:
299
+ (_, worker_id) = await self.get_worker_details_for_running_task(
300
+ task_id, attempt_number
301
+ )
302
+
303
+ except ValueError as e:
304
+ raise aiohttp.web.HTTPInternalServerError(text=str(e))
305
+ if not reply.success:
306
+ return aiohttp.web.HTTPInternalServerError(text=reply.output)
307
+
308
+ logger.info("Returning stack trace, size {}".format(len(reply.output)))
309
+
310
+ task_ids_in_a_worker = await self.get_task_ids_running_in_a_worker(worker_id)
311
+ return aiohttp.web.Response(
312
+ text=WARNING_FOR_MULTI_TASK_IN_A_WORKER
313
+ + str(task_ids_in_a_worker)
314
+ + "\n"
315
+ + reply.output
316
+ if len(task_ids_in_a_worker) > 1
317
+ else reply.output
318
+ )
319
+
320
+ @routes.get("/task/cpu_profile")
321
+ async def get_task_cpu_profile(self, req) -> aiohttp.web.Response:
322
+ """
323
+ Retrieves the CPU profile for a specific task.
324
+ Note that one worker process works on one task at a time
325
+ or one worker works on multiple async tasks.
326
+
327
+ Args:
328
+ req (aiohttp.web.Request): The HTTP request object.
329
+
330
+ Returns:
331
+ aiohttp.web.Response: The HTTP response containing the CPU profile data.
332
+
333
+ Raises:
334
+ ValueError: If the "task_id" parameter is
335
+ missing in the request query.
336
+ ValueError: If the "attempt_number" parameter is
337
+ missing in the request query.
338
+ ValueError: If the maximum duration allowed is exceeded.
339
+ ValueError: If the worker begins working on
340
+ another task during the profile retrieval.
341
+ aiohttp.web.HTTPInternalServerError: If there is
342
+ an internal server error during the profile retrieval.
343
+ aiohttp.web.HTTPInternalServerError: If the CPU Flame
344
+ Graph information for the task is not found.
345
+ """
346
+ if "task_id" not in req.query:
347
+ raise ValueError("task_id is required")
348
+ if "attempt_number" not in req.query:
349
+ raise ValueError("task's attempt number is required")
350
+ if "node_id" not in req.query:
351
+ raise ValueError("node_id is required")
352
+
353
+ task_id = req.query.get("task_id")
354
+ attempt_number = req.query.get("attempt_number")
355
+ node_id = req.query.get("node_id")
356
+
357
+ ip = DataSource.nodes[node_id]["nodeManagerAddress"]
358
+
359
+ duration_s = int(req.query.get("duration", 5))
360
+ if duration_s > 60:
361
+ raise ValueError(f"The max duration allowed is 60 seconds: {duration_s}.")
362
+ format = req.query.get("format", "flamegraph")
363
+
364
+ # Default not using `--native` for profiling
365
+ native = req.query.get("native", False) == "1"
366
+ reporter_stub = self._stubs[ip]
367
+
368
+ try:
369
+ (pid, _) = await self.get_worker_details_for_running_task(
370
+ task_id, attempt_number
371
+ )
372
+ except ValueError as e:
373
+ raise aiohttp.web.HTTPInternalServerError(text=str(e))
374
+
375
+ logger.info(
376
+ "Sending CPU profiling request to {}:{} for {} with native={}".format(
377
+ ip, pid, task_id, native
378
+ )
379
+ )
380
+
381
+ reply = await reporter_stub.CpuProfiling(
382
+ reporter_pb2.CpuProfilingRequest(
383
+ pid=pid, duration=duration_s, format=format, native=native
384
+ )
385
+ )
386
+
387
+ """
388
+ In order to truly confirm whether there are any other tasks
389
+ running during the profiling, we need to retrieve all tasks
390
+ that are currently running or have finished, and then parse
391
+ the task events (i.e., their start and finish times) to check
392
+ for any potential overlap. However, this process can be quite
393
+ extensive, so here we will make our best efforts to check
394
+ for any overlapping tasks. Therefore, we will check if
395
+ the task is still running
396
+ """
397
+ try:
398
+ (_, worker_id) = await self.get_worker_details_for_running_task(
399
+ task_id, attempt_number
400
+ )
401
+ except ValueError as e:
402
+ raise aiohttp.web.HTTPInternalServerError(text=str(e))
403
+
404
+ if not reply.success:
405
+ return aiohttp.web.HTTPInternalServerError(text=reply.output)
406
+ logger.info("Returning profiling response, size {}".format(len(reply.output)))
407
+
408
+ task_ids_in_a_worker = await self.get_task_ids_running_in_a_worker(worker_id)
409
+ return aiohttp.web.Response(
410
+ body='<p style="color: #E37400;">{} {} </br> </p> </br>'.format(
411
+ EMOJI_WARNING,
412
+ WARNING_FOR_MULTI_TASK_IN_A_WORKER + str(task_ids_in_a_worker),
413
+ )
414
+ + SVG_STYLE
415
+ + (reply.output)
416
+ if len(task_ids_in_a_worker) > 1
417
+ else SVG_STYLE + reply.output,
418
+ headers={"Content-Type": "text/html"},
419
+ )
420
+
421
+ @routes.get("/worker/traceback")
422
+ async def get_traceback(self, req) -> aiohttp.web.Response:
423
+ if "ip" in req.query and req.query["ip"] in self._stubs:
424
+ reporter_stub = self._stubs[req.query["ip"]]
425
+ else:
426
+ reporter_stub = list(self._stubs.values())[0]
427
+ pid = int(req.query["pid"])
428
+ # Default not using `--native` for profiling
429
+ native = req.query.get("native", False) == "1"
430
+ logger.info(
431
+ "Sending stack trace request to {}:{} with native={}".format(
432
+ req.query.get("ip"), pid, native
433
+ )
434
+ )
435
+ reply = await reporter_stub.GetTraceback(
436
+ reporter_pb2.GetTracebackRequest(pid=pid, native=native)
437
+ )
438
+ if reply.success:
439
+ logger.info("Returning stack trace, size {}".format(len(reply.output)))
440
+ return aiohttp.web.Response(text=reply.output)
441
+ else:
442
+ return aiohttp.web.HTTPInternalServerError(text=reply.output)
443
+
444
+ @routes.get("/worker/cpu_profile")
445
+ async def cpu_profile(self, req) -> aiohttp.web.Response:
446
+ if "ip" in req.query and req.query["ip"] in self._stubs:
447
+ reporter_stub = self._stubs[req.query["ip"]]
448
+ else:
449
+ reporter_stub = list(self._stubs.values())[0]
450
+ pid = int(req.query["pid"])
451
+ duration_s = int(req.query.get("duration", 5))
452
+ if duration_s > 60:
453
+ raise ValueError(f"The max duration allowed is 60 seconds: {duration_s}.")
454
+ format = req.query.get("format", "flamegraph")
455
+
456
+ # Default not using `--native` for profiling
457
+ native = req.query.get("native", False) == "1"
458
+ logger.info(
459
+ "Sending CPU profiling request to {}:{} with native={}".format(
460
+ req.query.get("ip"), pid, native
461
+ )
462
+ )
463
+ reply = await reporter_stub.CpuProfiling(
464
+ reporter_pb2.CpuProfilingRequest(
465
+ pid=pid, duration=duration_s, format=format, native=native
466
+ )
467
+ )
468
+ if reply.success:
469
+ logger.info(
470
+ "Returning profiling response, size {}".format(len(reply.output))
471
+ )
472
+ return aiohttp.web.Response(
473
+ body=reply.output,
474
+ headers={
475
+ "Content-Type": "image/svg+xml"
476
+ if format == "flamegraph"
477
+ else "text/plain"
478
+ },
479
+ )
480
+ else:
481
+ return aiohttp.web.HTTPInternalServerError(text=reply.output)
482
+
483
+ @routes.get("/memory_profile")
484
+ async def memory_profile(self, req) -> aiohttp.web.Response:
485
+ """
486
+ Retrieves the memory profile for a specific worker or task.
487
+ Note that for tasks, one worker process works on one task at a time
488
+ or one worker works on multiple async tasks.
489
+
490
+ Args:
491
+ req (aiohttp.web.Request): The HTTP request object.
492
+
493
+ Returns:
494
+ aiohttp.web.Response: The HTTP response containing the memory profile data.
495
+
496
+ Raises:
497
+ aiohttp.web.HTTPInternalServerError: If no stub
498
+ found from the given IP value
499
+ aiohttp.web.HTTPInternalServerError: If the
500
+ "task_id" parameter exists but either "attempt_number"
501
+ or "node id" is missing in the request query.
502
+ aiohttp.web.HTTPInternalServerError: If the maximum
503
+ duration allowed is exceeded.
504
+ aiohttp.web.HTTPInternalServerError If requesting task
505
+ profiling for the worker begins working on another task
506
+ during the profile retrieval.
507
+ aiohttp.web.HTTPInternalServerError: If there is
508
+ an internal server error during the profile retrieval.
509
+ """
510
+ is_task = "task_id" in req.query
511
+
512
+ if is_task:
513
+ if "attempt_number" not in req.query:
514
+ return aiohttp.web.HTTPInternalServerError(
515
+ text=(
516
+ "Failed to execute task profiling: "
517
+ "task's attempt number is required"
518
+ )
519
+ )
520
+ if "node_id" not in req.query:
521
+ return aiohttp.web.HTTPInternalServerError(
522
+ text=(
523
+ "Failed to execute task profiling: "
524
+ "task's node id is required"
525
+ )
526
+ )
527
+
528
+ task_id = req.query.get("task_id")
529
+ attempt_number = req.query.get("attempt_number")
530
+ node_id = req.query.get("node_id")
531
+ ip = DataSource.nodes[node_id]["nodeManagerAddress"]
532
+ try:
533
+ (pid, _) = await self.get_worker_details_for_running_task(
534
+ task_id, attempt_number
535
+ )
536
+ except ValueError as e:
537
+ raise aiohttp.web.HTTPInternalServerError(text=str(e))
538
+ else:
539
+ pid = int(req.query["pid"])
540
+ ip = req.query.get("ip") or None
541
+
542
+ duration_s = int(req.query.get("duration", 10))
543
+
544
+ # Default not using `--native`, `--leaks` and `--format` for profiling
545
+ format = req.query.get("format", "flamegraph")
546
+ native = req.query.get("native", False) == "1"
547
+ leaks = req.query.get("leaks", False) == "1"
548
+ trace_python_allocators = req.query.get("trace_python_allocators", False) == "1"
549
+
550
+ if ip:
551
+ if ip not in self._stubs:
552
+ return aiohttp.web.HTTPInternalServerError(
553
+ text="Failed to execute: No stub with given ip value"
554
+ )
555
+ reporter_stub = self._stubs[ip]
556
+ else:
557
+ reporter_stub = list(self._stubs.values())[0]
558
+
559
+ logger.info(
560
+ "Retrieving memory profiling request to {}:{}{}".format(
561
+ ip, pid, (f" for {task_id}" if is_task else "")
562
+ )
563
+ )
564
+
565
+ reply = await reporter_stub.MemoryProfiling(
566
+ reporter_pb2.MemoryProfilingRequest(
567
+ pid=pid,
568
+ format=format,
569
+ leaks=leaks,
570
+ duration=duration_s,
571
+ native=native,
572
+ trace_python_allocators=trace_python_allocators,
573
+ )
574
+ )
575
+
576
+ task_ids_in_a_worker = None
577
+ warning = reply.warning if reply.warning else ""
578
+ if is_task:
579
+ """
580
+ In order to truly confirm whether there are any other tasks
581
+ running during the profiling, Ray needs to retrieve all tasks
582
+ that are currently running or have finished, and then parse
583
+ the task events (i.e., their start and finish times) to check
584
+ for any potential overlap. However, this process can be quite
585
+ extensive, so Ray makes our best efforts to check
586
+ for any overlapping tasks. Therefore, Ray checks if
587
+ the task is still running.
588
+ """
589
+ try:
590
+ (_, worker_id) = await self.get_worker_details_for_running_task(
591
+ task_id, attempt_number
592
+ )
593
+ except ValueError as e:
594
+ raise aiohttp.web.HTTPInternalServerError(text=str(e))
595
+
596
+ task_ids_in_a_worker = await self.get_task_ids_running_in_a_worker(
597
+ worker_id
598
+ )
599
+ if len(task_ids_in_a_worker) > 1:
600
+ warning += (
601
+ "\n"
602
+ + WARNING_FOR_MULTI_TASK_IN_A_WORKER
603
+ + str(task_ids_in_a_worker)
604
+ )
605
+
606
+ if not reply.success:
607
+ return aiohttp.web.HTTPInternalServerError(text=reply.output)
608
+ logger.info("Returning profiling response, size {}".format(len(reply.output)))
609
+
610
+ return aiohttp.web.Response(
611
+ body='<p style="color: #E37400;">{} {} </br> </p> </br>'.format(
612
+ EMOJI_WARNING, warning
613
+ )
614
+ + (reply.output)
615
+ if warning != ""
616
+ else reply.output,
617
+ headers={"Content-Type": "text/html"},
618
+ )
619
+
620
+ async def run(self, server):
621
+ gcs_channel = self._dashboard_head.aiogrpc_gcs_channel
622
+ self._state_api_data_source_client = StateDataSourceClient(
623
+ gcs_channel, self._dashboard_head.gcs_aio_client
624
+ )
625
+ # Set up the state API in order to fetch task information.
626
+ # TODO(ryw): unify the StateAPIManager in reporter_head and state_head.
627
+ self._state_api = StateAPIManager(
628
+ self._state_api_data_source_client,
629
+ self._executor,
630
+ )
631
+
632
+ # Need daemon True to avoid dashboard hangs at exit.
633
+ self.service_discovery.daemon = True
634
+ self.service_discovery.start()
635
+ gcs_addr = self._dashboard_head.gcs_address
636
+ subscriber = GcsAioResourceUsageSubscriber(address=gcs_addr)
637
+ await subscriber.subscribe()
638
+ cluster_metadata = await self._dashboard_head.gcs_aio_client.internal_kv_get(
639
+ CLUSTER_METADATA_KEY,
640
+ namespace=KV_NAMESPACE_CLUSTER,
641
+ )
642
+ self.cluster_metadata = json.loads(cluster_metadata.decode("utf-8"))
643
+
644
+ loop = get_or_create_event_loop()
645
+
646
+ while True:
647
+ try:
648
+ # The key is b'RAY_REPORTER:{node id hex}',
649
+ # e.g. b'RAY_REPORTER:2b4fbd...'
650
+ key, data = await subscriber.poll()
651
+ if key is None:
652
+ continue
653
+
654
+ # NOTE: Every iteration is executed inside the thread-pool executor
655
+ # (TPE) to avoid blocking the Dashboard's event-loop
656
+ parsed_data = await loop.run_in_executor(
657
+ self._executor, json.loads, data
658
+ )
659
+
660
+ node_id = key.split(":")[-1]
661
+ DataSource.node_physical_stats[node_id] = parsed_data
662
+ except Exception:
663
+ logger.exception(
664
+ "Error receiving node physical stats from reporter agent."
665
+ )
666
+
667
+ @staticmethod
668
+ def is_minimal_module():
669
+ return False
vllm/lib/python3.10/site-packages/ray/dashboard/modules/serve/__init__.py ADDED
File without changes
vllm/lib/python3.10/site-packages/ray/dashboard/modules/serve/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (177 Bytes). View file
 
vllm/lib/python3.10/site-packages/ray/dashboard/modules/serve/__pycache__/sdk.cpython-310.pyc ADDED
Binary file (2.78 kB). View file
 
vllm/lib/python3.10/site-packages/ray/dashboard/modules/serve/__pycache__/serve_agent.cpython-310.pyc ADDED
Binary file (618 Bytes). View file
 
vllm/lib/python3.10/site-packages/ray/dashboard/modules/serve/__pycache__/serve_head.cpython-310.pyc ADDED
Binary file (583 Bytes). View file
 
vllm/lib/python3.10/site-packages/ray/dashboard/modules/serve/__pycache__/serve_rest_api_impl.cpython-310.pyc ADDED
Binary file (8.14 kB). View file
 
vllm/lib/python3.10/site-packages/ray/dashboard/modules/serve/sdk.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, Dict, Optional
2
+
3
+ from ray._private.utils import split_address
4
+ from ray.dashboard.modules.dashboard_sdk import SubmissionClient
5
+
6
+ try:
7
+ import aiohttp
8
+ import requests
9
+ except ImportError:
10
+ aiohttp = None
11
+ requests = None
12
+
13
+
14
+ DEPLOY_PATH = "/api/serve/applications/"
15
+ DELETE_PATH = "/api/serve/applications/"
16
+ STATUS_PATH = "/api/serve/applications/"
17
+
18
+
19
+ class ServeSubmissionClient(SubmissionClient):
20
+ def __init__(
21
+ self,
22
+ dashboard_head_address: str,
23
+ create_cluster_if_needed=False,
24
+ cookies: Optional[Dict[str, Any]] = None,
25
+ metadata: Optional[Dict[str, Any]] = None,
26
+ headers: Optional[Dict[str, Any]] = None,
27
+ ):
28
+ if requests is None:
29
+ raise RuntimeError(
30
+ "The Serve CLI requires the ray[default] "
31
+ 'installation: `pip install "ray[default]"`'
32
+ )
33
+
34
+ invalid_address_message = (
35
+ "Got an unexpected address"
36
+ f'"{dashboard_head_address}" while trying '
37
+ "to connect to the Ray dashboard. The Serve SDK/CLI requires the "
38
+ "Ray dashboard's HTTP(S) address (which should start with "
39
+ '"http://" or "https://". If this address '
40
+ "wasn't passed explicitly, it may be set in the "
41
+ "RAY_DASHBOARD_ADDRESS environment variable."
42
+ )
43
+
44
+ if "://" not in dashboard_head_address:
45
+ raise ValueError(invalid_address_message)
46
+
47
+ module_string, _ = split_address(dashboard_head_address)
48
+
49
+ # If user passes in ray://, raise error. Serve submission should
50
+ # not use a Ray client address.
51
+ if module_string not in ["http", "https"]:
52
+ raise ValueError(invalid_address_message)
53
+
54
+ super().__init__(
55
+ address=dashboard_head_address,
56
+ create_cluster_if_needed=create_cluster_if_needed,
57
+ cookies=cookies,
58
+ metadata=metadata,
59
+ headers=headers,
60
+ )
61
+ self._check_connection_and_version_with_url(
62
+ min_version="1.12",
63
+ version_error_message="Serve CLI is not supported on the Ray "
64
+ "cluster. Please ensure the cluster is "
65
+ "running Ray 1.12 or higher.",
66
+ url="/api/ray/version",
67
+ )
68
+
69
+ def get_serve_details(self) -> Dict:
70
+ response = self._do_request("GET", STATUS_PATH)
71
+ if response.status_code != 200:
72
+ self._raise_error(response)
73
+
74
+ return response.json()
75
+
76
+ def deploy_applications(self, config: Dict):
77
+ """Deploy multiple applications."""
78
+ response = self._do_request("PUT", DEPLOY_PATH, json_data=config)
79
+ if response.status_code != 200:
80
+ self._raise_error(response)
81
+
82
+ def delete_applications(self):
83
+ response = self._do_request("DELETE", DELETE_PATH)
84
+ if response.status_code != 200:
85
+ self._raise_error(response)
vllm/lib/python3.10/site-packages/ray/dashboard/modules/serve/serve_agent.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import ray.dashboard.optional_utils as optional_utils
2
+ import ray.dashboard.utils as dashboard_utils
3
+ from ray.dashboard.modules.serve.serve_rest_api_impl import create_serve_rest_api
4
+
5
+ dashboard_agent_route_table = optional_utils.DashboardAgentRouteTable
6
+
7
+ ServeAgent = create_serve_rest_api(
8
+ dashboard_module_superclass=dashboard_utils.DashboardAgentModule,
9
+ dashboard_route_table=dashboard_agent_route_table,
10
+ log_deprecation_warning=True,
11
+ )
vllm/lib/python3.10/site-packages/ray/dashboard/modules/serve/serve_head.py ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ import ray.dashboard.optional_utils as optional_utils
2
+ import ray.dashboard.utils as dashboard_utils
3
+ from ray.dashboard.modules.serve.serve_rest_api_impl import create_serve_rest_api
4
+
5
+ dashboard_head_route_table = optional_utils.DashboardHeadRouteTable
6
+
7
+ ServeHead = create_serve_rest_api(
8
+ dashboard_module_superclass=dashboard_utils.DashboardHeadModule,
9
+ dashboard_route_table=dashboard_head_route_table,
10
+ )
vllm/lib/python3.10/site-packages/ray/dashboard/modules/serve/serve_rest_api_impl.py ADDED
@@ -0,0 +1,260 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """This file contains the implementation for the Serve REST API.
2
+
3
+ This implementation is in a class generated by a factory method. serve_head.py
4
+ and serve_agent.py run the factory method to generate versions of the class
5
+ that inherit from the DashboardHeadModule and DashboardAgentModule classes,
6
+ respectively.
7
+
8
+ This means the API will be accessible on both the dashboard head and the
9
+ dashboard agent. Any changes here will affect both the head and the agent.
10
+ """
11
+
12
+ import asyncio
13
+ import dataclasses
14
+ import json
15
+ import logging
16
+ from functools import wraps
17
+ from typing import Union
18
+
19
+ import aiohttp
20
+ from aiohttp.web import Request, Response
21
+
22
+ import ray
23
+ import ray.dashboard.optional_utils as optional_utils
24
+ import ray.dashboard.optional_utils as dashboard_optional_utils
25
+ import ray.dashboard.utils as dashboard_utils
26
+ from ray._private.pydantic_compat import ValidationError
27
+ from ray.dashboard.modules.version import CURRENT_VERSION, VersionResponse
28
+ from ray.exceptions import RayTaskError
29
+
30
+ logger = logging.getLogger(__name__)
31
+ logger.setLevel(logging.INFO)
32
+
33
+
34
+ def validate_endpoint(log_deprecation_warning: bool):
35
+ def decorator(func):
36
+ @wraps(func)
37
+ async def check(self, *args, **kwargs):
38
+ try:
39
+ from ray import serve # noqa: F401
40
+
41
+ if log_deprecation_warning:
42
+ logger.info(
43
+ "The Serve REST API on the dashboard agent is deprecated. "
44
+ "Send requests to the Serve REST API directly to the "
45
+ "dashboard instead. If you're using default ports, this "
46
+ "means you should send the request to the same route on "
47
+ "port 8265 instead of 52365."
48
+ )
49
+ except ImportError:
50
+ return Response(
51
+ status=501,
52
+ text=(
53
+ "Serve dependencies are not installed. Please run `pip "
54
+ 'install "ray[serve]"`.'
55
+ ),
56
+ )
57
+ return await func(self, *args, **kwargs)
58
+
59
+ return check
60
+
61
+ return decorator
62
+
63
+
64
+ def create_serve_rest_api(
65
+ dashboard_module_superclass: Union[
66
+ dashboard_utils.DashboardHeadModule, dashboard_utils.DashboardAgentModule
67
+ ],
68
+ dashboard_route_table: Union[
69
+ dashboard_optional_utils.DashboardHeadRouteTable,
70
+ dashboard_optional_utils.DashboardAgentRouteTable,
71
+ ],
72
+ log_deprecation_warning: bool = False,
73
+ ):
74
+ # NOTE (shrekris-anyscale): This class uses delayed imports for all
75
+ # Ray Serve-related modules. That way, users can use the Ray dashboard agent for
76
+ # non-Serve purposes without downloading Serve dependencies.
77
+ class ServeRestApiImpl(dashboard_module_superclass):
78
+ def __init__(self, dashboard_head_or_agent):
79
+ super().__init__(dashboard_head_or_agent)
80
+ self._controller = None
81
+ self._controller_lock = asyncio.Lock()
82
+
83
+ # serve_start_async is not thread-safe call. This lock
84
+ # will make sure there is only one call that starts the serve instance.
85
+ # If the lock is already acquired by another async task, the async task
86
+ # will asynchronously wait for the lock.
87
+ self._controller_start_lock = asyncio.Lock()
88
+ self._session_name = dashboard_head_or_agent.session_name
89
+
90
+ # TODO: It's better to use `/api/version`.
91
+ # It requires a refactor of ClassMethodRouteTable to differentiate the server.
92
+ @dashboard_route_table.get("/api/ray/version")
93
+ async def get_version(self, req: Request) -> Response:
94
+ # NOTE(edoakes): CURRENT_VERSION should be bumped and checked on the
95
+ # client when we have backwards-incompatible changes.
96
+ resp = VersionResponse(
97
+ version=CURRENT_VERSION,
98
+ ray_version=ray.__version__,
99
+ ray_commit=ray.__commit__,
100
+ session_name=self._session_name,
101
+ )
102
+ return Response(
103
+ text=json.dumps(dataclasses.asdict(resp)),
104
+ content_type="application/json",
105
+ status=aiohttp.web.HTTPOk.status_code,
106
+ )
107
+
108
+ @dashboard_route_table.get("/api/serve/applications/")
109
+ @optional_utils.init_ray_and_catch_exceptions()
110
+ @validate_endpoint(log_deprecation_warning=log_deprecation_warning)
111
+ async def get_serve_instance_details(self, req: Request) -> Response:
112
+ from ray.serve.schema import ServeInstanceDetails
113
+
114
+ controller = await self.get_serve_controller()
115
+
116
+ if controller is None:
117
+ # If no serve instance is running, return a dict that represents that.
118
+ details = ServeInstanceDetails.get_empty_schema_dict()
119
+ else:
120
+ try:
121
+ details = await controller.get_serve_instance_details.remote()
122
+ except ray.exceptions.RayTaskError as e:
123
+ # Task failure sometimes are due to GCS
124
+ # failure. When GCS failed, we expect a longer time
125
+ # to recover.
126
+ return Response(
127
+ status=503,
128
+ text=(
129
+ "Failed to get a response from the controller. "
130
+ f"The GCS may be down, please retry later: {e}"
131
+ ),
132
+ )
133
+
134
+ return Response(
135
+ text=json.dumps(details),
136
+ content_type="application/json",
137
+ )
138
+
139
+ @dashboard_route_table.delete("/api/serve/applications/")
140
+ @optional_utils.init_ray_and_catch_exceptions()
141
+ async def delete_serve_applications(self, req: Request) -> Response:
142
+ from ray import serve
143
+
144
+ if await self.get_serve_controller() is not None:
145
+ serve.shutdown()
146
+
147
+ return Response()
148
+
149
+ @dashboard_route_table.put("/api/serve/applications/")
150
+ @optional_utils.init_ray_and_catch_exceptions()
151
+ @validate_endpoint(log_deprecation_warning=log_deprecation_warning)
152
+ async def put_all_applications(self, req: Request) -> Response:
153
+ from ray._private.usage.usage_lib import TagKey, record_extra_usage_tag
154
+ from ray.serve._private.api import serve_start_async
155
+ from ray.serve.config import ProxyLocation
156
+ from ray.serve.schema import ServeDeploySchema
157
+
158
+ try:
159
+ config: ServeDeploySchema = ServeDeploySchema.parse_obj(
160
+ await req.json()
161
+ )
162
+ except ValidationError as e:
163
+ return Response(
164
+ status=400,
165
+ text=repr(e),
166
+ )
167
+
168
+ config_http_options = config.http_options.dict()
169
+ location = ProxyLocation._to_deployment_mode(config.proxy_location)
170
+ full_http_options = dict({"location": location}, **config_http_options)
171
+ grpc_options = config.grpc_options.dict()
172
+
173
+ async with self._controller_start_lock:
174
+ client = await serve_start_async(
175
+ http_options=full_http_options,
176
+ grpc_options=grpc_options,
177
+ global_logging_config=config.logging_config,
178
+ )
179
+
180
+ # Serve ignores HTTP options if it was already running when
181
+ # serve_start_async() is called. Therefore we validate that no
182
+ # existing HTTP options are updated and print warning in case they are
183
+ self.validate_http_options(client, full_http_options)
184
+
185
+ try:
186
+ if config.logging_config:
187
+ client.update_global_logging_config(config.logging_config)
188
+ client.deploy_apps(config)
189
+ record_extra_usage_tag(TagKey.SERVE_REST_API_VERSION, "v2")
190
+ except RayTaskError as e:
191
+ return Response(
192
+ status=400,
193
+ text=str(e),
194
+ )
195
+ else:
196
+ return Response()
197
+
198
+ def validate_http_options(self, client, http_options):
199
+ divergent_http_options = []
200
+
201
+ for option, new_value in http_options.items():
202
+ prev_value = getattr(client.http_config, option)
203
+ if prev_value != new_value:
204
+ divergent_http_options.append(option)
205
+
206
+ if divergent_http_options:
207
+ logger.warning(
208
+ "Serve is already running on this Ray cluster and "
209
+ "it's not possible to update its HTTP options without "
210
+ "restarting it. Following options are attempted to be "
211
+ f"updated: {divergent_http_options}."
212
+ )
213
+
214
+ async def get_serve_controller(self):
215
+ """Gets the ServeController to the this cluster's Serve app.
216
+
217
+ return: If Serve is running on this Ray cluster, returns a client to
218
+ the Serve controller. If Serve is not running, returns None.
219
+ """
220
+ async with self._controller_lock:
221
+ if self._controller is not None:
222
+ try:
223
+ await self._controller.check_alive.remote()
224
+ return self._controller
225
+ except ray.exceptions.RayActorError:
226
+ logger.info("Controller is dead")
227
+ self._controller = None
228
+
229
+ # Try to connect to serve even when we detect the actor is dead
230
+ # because the user might have started a new
231
+ # serve cluter.
232
+ from ray.serve._private.constants import (
233
+ SERVE_CONTROLLER_NAME,
234
+ SERVE_NAMESPACE,
235
+ )
236
+
237
+ try:
238
+ # get_actor is a sync call but it'll timeout after
239
+ # ray.dashboard.consts.GCS_RPC_TIMEOUT_SECONDS
240
+ self._controller = ray.get_actor(
241
+ SERVE_CONTROLLER_NAME, namespace=SERVE_NAMESPACE
242
+ )
243
+ except Exception as e:
244
+ logger.debug(
245
+ "There is no "
246
+ "instance running on this Ray cluster. Please "
247
+ "call `serve.start(detached=True) to start "
248
+ f"one: {e}"
249
+ )
250
+
251
+ return self._controller
252
+
253
+ async def run(self, server):
254
+ pass
255
+
256
+ @staticmethod
257
+ def is_minimal_module():
258
+ return False
259
+
260
+ return ServeRestApiImpl
vllm/lib/python3.10/site-packages/ray/dashboard/modules/snapshot/__init__.py ADDED
File without changes
vllm/lib/python3.10/site-packages/ray/dashboard/modules/snapshot/__pycache__/snapshot_head.cpython-310.pyc ADDED
Binary file (8.8 kB). View file
 
vllm/lib/python3.10/site-packages/ray/dashboard/modules/train/__init__.py ADDED
File without changes
vllm/lib/python3.10/site-packages/ray/dashboard/modules/version.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dataclasses import dataclass
2
+
3
+ # Version 0 -> 1: Added log streaming and changed behavior of job logs cli.
4
+ # Version 1 -> 2: - Renamed job_id to submission_id.
5
+ # - Changed list_jobs sdk/cli/api to return a list
6
+ # instead of a dictionary.
7
+ # Version 2 -> 3: - Added optional fields entrypoint_num_cpus, entrypoint_num_gpus
8
+ # and entrypoint_resources to submit_job sdk/cli/api.
9
+ # Version 3 -> 4: - Added DELETE endpoint for deleting jobs.
10
+ CURRENT_VERSION = "4"
11
+
12
+
13
+ @dataclass
14
+ class VersionResponse:
15
+ version: str
16
+ ray_version: str
17
+ ray_commit: str
18
+ session_name: str
vllm/lib/python3.10/site-packages/ray/dashboard/optional_deps.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # These imports determine whether or not a user has the required dependencies
2
+ # to launch the optional dashboard API server.
3
+ # If any of these imports fail, the dashboard API server will not be launched.
4
+ # Please add important dashboard-api dependencies to this list.
5
+
6
+ import aiohttp # noqa: F401
7
+ import aiohttp.web # noqa: F401
8
+ import aiohttp_cors # noqa: F401
9
+ import grpc # noqa: F401
10
+
11
+ # These checks have to come first because aiohttp looks
12
+ # for opencensus, too, and raises a different error otherwise.
13
+ import opencensus # noqa: F401
14
+ import prometheus_client # noqa: F401
15
+ import pydantic # noqa: F401
16
+ from aiohttp import hdrs # noqa: F401
17
+ from aiohttp.typedefs import PathLike # noqa: F401
18
+ from aiohttp.web import RouteDef # noqa: F401
19
+
20
+ # Adding new modules should also be reflected in the
21
+ # python/ray/tests/test_minimal_install.py