skypilot-nightly 1.0.0.dev20250216__py3-none-any.whl → 1.0.0.dev20250218__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (172) hide show
  1. sky/__init__.py +48 -22
  2. sky/adaptors/aws.py +2 -1
  3. sky/adaptors/azure.py +4 -4
  4. sky/adaptors/cloudflare.py +4 -4
  5. sky/adaptors/kubernetes.py +8 -8
  6. sky/authentication.py +42 -45
  7. sky/backends/backend.py +2 -2
  8. sky/backends/backend_utils.py +108 -221
  9. sky/backends/cloud_vm_ray_backend.py +283 -282
  10. sky/benchmark/benchmark_utils.py +6 -2
  11. sky/check.py +40 -28
  12. sky/cli.py +1213 -1116
  13. sky/client/__init__.py +1 -0
  14. sky/client/cli.py +5644 -0
  15. sky/client/common.py +345 -0
  16. sky/client/sdk.py +1757 -0
  17. sky/cloud_stores.py +12 -6
  18. sky/clouds/__init__.py +0 -2
  19. sky/clouds/aws.py +20 -13
  20. sky/clouds/azure.py +5 -3
  21. sky/clouds/cloud.py +1 -1
  22. sky/clouds/cudo.py +2 -1
  23. sky/clouds/do.py +7 -3
  24. sky/clouds/fluidstack.py +3 -2
  25. sky/clouds/gcp.py +10 -8
  26. sky/clouds/ibm.py +8 -7
  27. sky/clouds/kubernetes.py +7 -6
  28. sky/clouds/lambda_cloud.py +8 -7
  29. sky/clouds/oci.py +4 -3
  30. sky/clouds/paperspace.py +2 -1
  31. sky/clouds/runpod.py +2 -1
  32. sky/clouds/scp.py +8 -7
  33. sky/clouds/service_catalog/__init__.py +3 -3
  34. sky/clouds/service_catalog/aws_catalog.py +7 -1
  35. sky/clouds/service_catalog/common.py +4 -2
  36. sky/clouds/service_catalog/data_fetchers/fetch_gcp.py +2 -2
  37. sky/clouds/service_catalog/data_fetchers/fetch_lambda_cloud.py +1 -0
  38. sky/clouds/utils/oci_utils.py +1 -1
  39. sky/clouds/vast.py +2 -1
  40. sky/clouds/vsphere.py +2 -1
  41. sky/core.py +263 -99
  42. sky/dag.py +4 -0
  43. sky/data/mounting_utils.py +2 -1
  44. sky/data/storage.py +97 -35
  45. sky/data/storage_utils.py +69 -9
  46. sky/exceptions.py +138 -5
  47. sky/execution.py +47 -50
  48. sky/global_user_state.py +105 -22
  49. sky/jobs/__init__.py +12 -14
  50. sky/jobs/client/__init__.py +0 -0
  51. sky/jobs/client/sdk.py +296 -0
  52. sky/jobs/constants.py +30 -1
  53. sky/jobs/controller.py +12 -6
  54. sky/jobs/dashboard/dashboard.py +2 -6
  55. sky/jobs/recovery_strategy.py +22 -29
  56. sky/jobs/server/__init__.py +1 -0
  57. sky/jobs/{core.py → server/core.py} +101 -34
  58. sky/jobs/server/dashboard_utils.py +64 -0
  59. sky/jobs/server/server.py +182 -0
  60. sky/jobs/utils.py +32 -23
  61. sky/models.py +27 -0
  62. sky/optimizer.py +22 -22
  63. sky/provision/__init__.py +6 -3
  64. sky/provision/aws/config.py +2 -2
  65. sky/provision/aws/instance.py +1 -1
  66. sky/provision/azure/instance.py +1 -1
  67. sky/provision/cudo/instance.py +1 -1
  68. sky/provision/do/instance.py +1 -1
  69. sky/provision/do/utils.py +0 -5
  70. sky/provision/fluidstack/fluidstack_utils.py +4 -3
  71. sky/provision/fluidstack/instance.py +4 -2
  72. sky/provision/gcp/instance.py +1 -1
  73. sky/provision/instance_setup.py +2 -2
  74. sky/provision/kubernetes/constants.py +8 -0
  75. sky/provision/kubernetes/instance.py +1 -1
  76. sky/provision/kubernetes/utils.py +67 -76
  77. sky/provision/lambda_cloud/instance.py +3 -15
  78. sky/provision/logging.py +1 -1
  79. sky/provision/oci/instance.py +7 -4
  80. sky/provision/paperspace/instance.py +1 -1
  81. sky/provision/provisioner.py +3 -2
  82. sky/provision/runpod/instance.py +1 -1
  83. sky/provision/vast/instance.py +1 -1
  84. sky/provision/vsphere/instance.py +2 -11
  85. sky/resources.py +63 -47
  86. sky/serve/__init__.py +6 -10
  87. sky/serve/client/__init__.py +0 -0
  88. sky/serve/client/sdk.py +366 -0
  89. sky/serve/constants.py +3 -0
  90. sky/serve/replica_managers.py +10 -10
  91. sky/serve/serve_utils.py +56 -36
  92. sky/serve/server/__init__.py +0 -0
  93. sky/serve/{core.py → server/core.py} +37 -17
  94. sky/serve/server/server.py +117 -0
  95. sky/serve/service.py +8 -1
  96. sky/server/__init__.py +1 -0
  97. sky/server/common.py +442 -0
  98. sky/server/constants.py +21 -0
  99. sky/server/html/log.html +174 -0
  100. sky/server/requests/__init__.py +0 -0
  101. sky/server/requests/executor.py +462 -0
  102. sky/server/requests/payloads.py +481 -0
  103. sky/server/requests/queues/__init__.py +0 -0
  104. sky/server/requests/queues/mp_queue.py +76 -0
  105. sky/server/requests/requests.py +567 -0
  106. sky/server/requests/serializers/__init__.py +0 -0
  107. sky/server/requests/serializers/decoders.py +192 -0
  108. sky/server/requests/serializers/encoders.py +166 -0
  109. sky/server/server.py +1095 -0
  110. sky/server/stream_utils.py +144 -0
  111. sky/setup_files/MANIFEST.in +1 -0
  112. sky/setup_files/dependencies.py +12 -4
  113. sky/setup_files/setup.py +1 -1
  114. sky/sky_logging.py +9 -13
  115. sky/skylet/autostop_lib.py +2 -2
  116. sky/skylet/constants.py +46 -12
  117. sky/skylet/events.py +5 -6
  118. sky/skylet/job_lib.py +78 -66
  119. sky/skylet/log_lib.py +17 -11
  120. sky/skypilot_config.py +79 -94
  121. sky/task.py +119 -73
  122. sky/templates/aws-ray.yml.j2 +4 -4
  123. sky/templates/azure-ray.yml.j2 +3 -2
  124. sky/templates/cudo-ray.yml.j2 +3 -2
  125. sky/templates/fluidstack-ray.yml.j2 +3 -2
  126. sky/templates/gcp-ray.yml.j2 +3 -2
  127. sky/templates/ibm-ray.yml.j2 +3 -2
  128. sky/templates/jobs-controller.yaml.j2 +1 -12
  129. sky/templates/kubernetes-ray.yml.j2 +3 -2
  130. sky/templates/lambda-ray.yml.j2 +3 -2
  131. sky/templates/oci-ray.yml.j2 +3 -2
  132. sky/templates/paperspace-ray.yml.j2 +3 -2
  133. sky/templates/runpod-ray.yml.j2 +3 -2
  134. sky/templates/scp-ray.yml.j2 +3 -2
  135. sky/templates/skypilot-server-kubernetes-proxy.sh +36 -0
  136. sky/templates/vsphere-ray.yml.j2 +4 -2
  137. sky/templates/websocket_proxy.py +64 -0
  138. sky/usage/constants.py +8 -0
  139. sky/usage/usage_lib.py +45 -11
  140. sky/utils/accelerator_registry.py +33 -53
  141. sky/utils/admin_policy_utils.py +2 -1
  142. sky/utils/annotations.py +51 -0
  143. sky/utils/cli_utils/status_utils.py +33 -3
  144. sky/utils/cluster_utils.py +356 -0
  145. sky/utils/command_runner.py +69 -14
  146. sky/utils/common.py +74 -0
  147. sky/utils/common_utils.py +133 -93
  148. sky/utils/config_utils.py +204 -0
  149. sky/utils/control_master_utils.py +2 -3
  150. sky/utils/controller_utils.py +133 -147
  151. sky/utils/dag_utils.py +72 -24
  152. sky/utils/kubernetes/deploy_remote_cluster.sh +2 -2
  153. sky/utils/kubernetes/exec_kubeconfig_converter.py +73 -0
  154. sky/utils/kubernetes/kubernetes_deploy_utils.py +228 -0
  155. sky/utils/log_utils.py +83 -23
  156. sky/utils/message_utils.py +81 -0
  157. sky/utils/registry.py +127 -0
  158. sky/utils/resources_utils.py +2 -2
  159. sky/utils/rich_utils.py +213 -34
  160. sky/utils/schemas.py +19 -2
  161. sky/{status_lib.py → utils/status_lib.py} +12 -7
  162. sky/utils/subprocess_utils.py +51 -35
  163. sky/utils/timeline.py +7 -2
  164. sky/utils/ux_utils.py +95 -25
  165. {skypilot_nightly-1.0.0.dev20250216.dist-info → skypilot_nightly-1.0.0.dev20250218.dist-info}/METADATA +8 -3
  166. {skypilot_nightly-1.0.0.dev20250216.dist-info → skypilot_nightly-1.0.0.dev20250218.dist-info}/RECORD +170 -132
  167. sky/clouds/cloud_registry.py +0 -76
  168. sky/utils/cluster_yaml_utils.py +0 -24
  169. {skypilot_nightly-1.0.0.dev20250216.dist-info → skypilot_nightly-1.0.0.dev20250218.dist-info}/LICENSE +0 -0
  170. {skypilot_nightly-1.0.0.dev20250216.dist-info → skypilot_nightly-1.0.0.dev20250218.dist-info}/WHEEL +0 -0
  171. {skypilot_nightly-1.0.0.dev20250216.dist-info → skypilot_nightly-1.0.0.dev20250218.dist-info}/entry_points.txt +0 -0
  172. {skypilot_nightly-1.0.0.dev20250216.dist-info → skypilot_nightly-1.0.0.dev20250218.dist-info}/top_level.txt +0 -0
sky/client/sdk.py ADDED
@@ -0,0 +1,1757 @@
1
+ """Client-side Python SDK for SkyPilot.
2
+
3
+ All functions will return a future that can be awaited on with the `get` method.
4
+
5
+ Usage example:
6
+
7
+ .. code-block:: python
8
+
9
+ request_id = sky.status()
10
+ statuses = sky.get(request_id)
11
+
12
+ """
13
+ import getpass
14
+ import json
15
+ import logging
16
+ import os
17
+ import pathlib
18
+ import subprocess
19
+ import typing
20
+ from typing import Any, Dict, List, Optional, Tuple, Union
21
+
22
+ import click
23
+ import colorama
24
+ import filelock
25
+ import psutil
26
+ import requests
27
+
28
+ from sky import backends
29
+ from sky import exceptions
30
+ from sky import sky_logging
31
+ from sky import skypilot_config
32
+ from sky.client import common as client_common
33
+ from sky.server import common as server_common
34
+ from sky.server import constants as server_constants
35
+ from sky.server.requests import payloads
36
+ from sky.server.requests import requests as requests_lib
37
+ from sky.skylet import constants
38
+ from sky.usage import usage_lib
39
+ from sky.utils import annotations
40
+ from sky.utils import cluster_utils
41
+ from sky.utils import common
42
+ from sky.utils import common_utils
43
+ from sky.utils import dag_utils
44
+ from sky.utils import env_options
45
+ from sky.utils import rich_utils
46
+ from sky.utils import status_lib
47
+ from sky.utils import subprocess_utils
48
+ from sky.utils import ux_utils
49
+
50
+ if typing.TYPE_CHECKING:
51
+ import io
52
+
53
+ import sky
54
+
55
+ logger = sky_logging.init_logger(__name__)
56
+ logging.getLogger('httpx').setLevel(logging.CRITICAL)
57
+
58
+
59
+ def stream_response(request_id: Optional[str],
60
+ response: requests.Response,
61
+ output_stream: Optional['io.TextIOBase'] = None) -> Any:
62
+ """Streams the response to the console.
63
+
64
+ Args:
65
+ request_id: The request ID.
66
+ response: The HTTP response.
67
+ output_stream: The output stream to write to. If None, print to the
68
+ console.
69
+ """
70
+
71
+ try:
72
+ for line in rich_utils.decode_rich_status(response):
73
+ if line is not None:
74
+ print(line, flush=True, end='', file=output_stream)
75
+ return get(request_id)
76
+ except Exception: # pylint: disable=broad-except
77
+ logger.debug(f'To stream request logs: sky api logs {request_id}')
78
+ raise
79
+
80
+
81
+ @usage_lib.entrypoint
82
+ @server_common.check_server_healthy_or_start
83
+ @annotations.client_api
84
+ def check(clouds: Optional[Tuple[str]],
85
+ verbose: bool) -> server_common.RequestId:
86
+ """Checks the credentials to enable clouds.
87
+
88
+ Args:
89
+ clouds: The clouds to check.
90
+ verbose: Whether to show verbose output.
91
+
92
+ Returns:
93
+ The request ID of the check request.
94
+
95
+ Request Returns:
96
+ None
97
+ """
98
+ body = payloads.CheckBody(clouds=clouds, verbose=verbose)
99
+ response = requests.post(f'{server_common.get_server_url()}/check',
100
+ json=json.loads(body.model_dump_json()))
101
+ return server_common.get_request_id(response)
102
+
103
+
104
+ @usage_lib.entrypoint
105
+ @server_common.check_server_healthy_or_start
106
+ @annotations.client_api
107
+ def enabled_clouds() -> server_common.RequestId:
108
+ """Gets the enabled clouds.
109
+
110
+ Returns:
111
+ The request ID of the enabled clouds request.
112
+
113
+ Request Returns:
114
+ A list of enabled clouds in string format.
115
+ """
116
+ response = requests.get(f'{server_common.get_server_url()}/enabled_clouds')
117
+ return server_common.get_request_id(response)
118
+
119
+
120
+ @usage_lib.entrypoint
121
+ @server_common.check_server_healthy_or_start
122
+ @annotations.client_api
123
+ def list_accelerators(gpus_only: bool = True,
124
+ name_filter: Optional[str] = None,
125
+ region_filter: Optional[str] = None,
126
+ quantity_filter: Optional[int] = None,
127
+ clouds: Optional[Union[List[str], str]] = None,
128
+ all_regions: bool = False,
129
+ require_price: bool = True,
130
+ case_sensitive: bool = True) -> server_common.RequestId:
131
+ """Lists the names of all accelerators offered by Sky.
132
+
133
+ This will include all accelerators offered by Sky, including those
134
+ that may not be available in the user's account.
135
+
136
+ Args:
137
+ gpus_only: Whether to only list GPU accelerators.
138
+ name_filter: The name filter.
139
+ region_filter: The region filter.
140
+ quantity_filter: The quantity filter.
141
+ clouds: The clouds to list.
142
+ all_regions: Whether to list all regions.
143
+ require_price: Whether to require price.
144
+ case_sensitive: Whether to case sensitive.
145
+
146
+ Returns:
147
+ The request ID of the list accelerator counts request.
148
+
149
+ Request Returns:
150
+ acc_to_instance_type_dict (Dict[str, List[InstanceTypeInfo]]): A
151
+ dictionary of canonical accelerator names mapped to a list of
152
+ instance type offerings. See usage in cli.py.
153
+ """
154
+ body = payloads.ListAcceleratorsBody(
155
+ gpus_only=gpus_only,
156
+ name_filter=name_filter,
157
+ region_filter=region_filter,
158
+ quantity_filter=quantity_filter,
159
+ clouds=clouds,
160
+ all_regions=all_regions,
161
+ require_price=require_price,
162
+ case_sensitive=case_sensitive,
163
+ )
164
+ response = requests.post(
165
+ f'{server_common.get_server_url()}/list_accelerators',
166
+ json=json.loads(body.model_dump_json()))
167
+ return server_common.get_request_id(response)
168
+
169
+
170
+ @usage_lib.entrypoint
171
+ @server_common.check_server_healthy_or_start
172
+ @annotations.client_api
173
+ def list_accelerator_counts(
174
+ gpus_only: bool = True,
175
+ name_filter: Optional[str] = None,
176
+ region_filter: Optional[str] = None,
177
+ quantity_filter: Optional[int] = None,
178
+ clouds: Optional[Union[List[str],
179
+ str]] = None) -> server_common.RequestId:
180
+ """Lists all accelerators offered by Sky and available counts.
181
+
182
+ Args:
183
+ gpus_only: Whether to only list GPU accelerators.
184
+ name_filter: The name filter.
185
+ region_filter: The region filter.
186
+ quantity_filter: The quantity filter.
187
+ clouds: The clouds to list.
188
+
189
+ Returns:
190
+ The request ID of the list accelerator counts request.
191
+
192
+ Request Returns:
193
+ acc_to_acc_num_dict (Dict[str, List[int]]): A dictionary of canonical
194
+ accelerator names mapped to a list of available counts. See usage
195
+ in cli.py.
196
+ """
197
+ body = payloads.ListAcceleratorsBody(
198
+ gpus_only=gpus_only,
199
+ name_filter=name_filter,
200
+ region_filter=region_filter,
201
+ quantity_filter=quantity_filter,
202
+ clouds=clouds,
203
+ )
204
+ response = requests.post(
205
+ f'{server_common.get_server_url()}/list_accelerator_counts',
206
+ json=json.loads(body.model_dump_json()))
207
+ return server_common.get_request_id(response)
208
+
209
+
210
+ @usage_lib.entrypoint
211
+ @server_common.check_server_healthy_or_start
212
+ @annotations.client_api
213
+ def optimize(
214
+ dag: 'sky.Dag',
215
+ minimize: common.OptimizeTarget = common.OptimizeTarget.COST
216
+ ) -> server_common.RequestId:
217
+ """Finds the best execution plan for the given DAG.
218
+
219
+ Args:
220
+ dag: the DAG to optimize.
221
+ minimize: whether to minimize cost or time.
222
+
223
+ Returns:
224
+ The request ID of the optimize request.
225
+
226
+ Request Returns:
227
+ optimized_dag (str): The optimized DAG in YAML format.
228
+
229
+ Request Raises:
230
+ exceptions.ResourcesUnavailableError: if no resources are available
231
+ for a task.
232
+ exceptions.NoCloudAccessError: if no public clouds are enabled.
233
+ """
234
+ dag_str = dag_utils.dump_chain_dag_to_yaml_str(dag)
235
+
236
+ body = payloads.OptimizeBody(dag=dag_str, minimize=minimize)
237
+ response = requests.post(f'{server_common.get_server_url()}/optimize',
238
+ json=json.loads(body.model_dump_json()))
239
+ return server_common.get_request_id(response)
240
+
241
+
242
+ @usage_lib.entrypoint
243
+ @server_common.check_server_healthy_or_start
244
+ @annotations.client_api
245
+ def validate(dag: 'sky.Dag', workdir_only: bool = False) -> None:
246
+ """Validates the tasks.
247
+
248
+ The file paths (workdir and file_mounts) are validated on the client side
249
+ while the rest (e.g. resource) are validated on server side.
250
+
251
+ Raises exceptions if the DAG is invalid.
252
+
253
+ Args:
254
+ dag: the DAG to validate.
255
+ workdir_only: whether to only validate the workdir. This is used for
256
+ `exec` as it does not need other files/folders in file_mounts.
257
+ """
258
+ for task in dag.tasks:
259
+ task.expand_and_validate_workdir()
260
+ if not workdir_only:
261
+ task.expand_and_validate_file_mounts()
262
+ dag_str = dag_utils.dump_chain_dag_to_yaml_str(dag)
263
+ body = payloads.ValidateBody(dag=dag_str)
264
+ response = requests.post(f'{server_common.get_server_url()}/validate',
265
+ json=json.loads(body.model_dump_json()))
266
+ if response.status_code == 400:
267
+ with ux_utils.print_exception_no_traceback():
268
+ raise exceptions.deserialize_exception(
269
+ response.json().get('detail'))
270
+
271
+
272
+ @usage_lib.entrypoint
273
+ @server_common.check_server_healthy_or_start
274
+ @annotations.client_api
275
+ def launch(
276
+ task: Union['sky.Task', 'sky.Dag'],
277
+ cluster_name: Optional[str] = None,
278
+ retry_until_up: bool = False,
279
+ idle_minutes_to_autostop: Optional[int] = None,
280
+ dryrun: bool = False,
281
+ down: bool = False, # pylint: disable=redefined-outer-name
282
+ backend: Optional[backends.Backend] = None,
283
+ optimize_target: common.OptimizeTarget = common.OptimizeTarget.COST,
284
+ no_setup: bool = False,
285
+ clone_disk_from: Optional[str] = None,
286
+ fast: bool = False,
287
+ # Internal only:
288
+ # pylint: disable=invalid-name
289
+ _need_confirmation: bool = False,
290
+ _is_launched_by_jobs_controller: bool = False,
291
+ _is_launched_by_sky_serve_controller: bool = False,
292
+ _disable_controller_check: bool = False,
293
+ ) -> server_common.RequestId:
294
+ """Launches a cluster or task.
295
+
296
+ The task's setup and run commands are executed under the task's workdir
297
+ (when specified, it is synced to remote cluster). The task undergoes job
298
+ queue scheduling on the cluster.
299
+
300
+ Currently, the first argument must be a sky.Task, or (EXPERIMENTAL advanced
301
+ usage) a sky.Dag. In the latter case, currently it must contain a single
302
+ task; support for pipelines/general DAGs are in experimental branches.
303
+
304
+ Example:
305
+ .. code-block:: python
306
+
307
+ import sky
308
+ task = sky.Task(run='echo hello SkyPilot')
309
+ task.set_resources(
310
+ sky.Resources(cloud=sky.AWS(), accelerators='V100:4'))
311
+ sky.launch(task, cluster_name='my-cluster')
312
+
313
+
314
+ Args:
315
+ task: sky.Task, or sky.Dag (experimental; 1-task only) to launch.
316
+ cluster_name: name of the cluster to create/reuse. If None,
317
+ auto-generate a name.
318
+ retry_until_up: whether to retry launching the cluster until it is
319
+ up.
320
+ idle_minutes_to_autostop: automatically stop the cluster after this
321
+ many minute of idleness, i.e., no running or pending jobs in the
322
+ cluster's job queue. Idleness gets reset whenever setting-up/
323
+ running/pending jobs are found in the job queue. Setting this
324
+ flag is equivalent to running
325
+ ``sky.launch(..., detach_run=True, ...)`` and then
326
+ ``sky.autostop(idle_minutes=<minutes>)``. If not set, the cluster
327
+ will not be autostopped.
328
+ dryrun: if True, do not actually launch the cluster.
329
+ down: Tear down the cluster after all jobs finish (successfully or
330
+ abnormally). If --idle-minutes-to-autostop is also set, the
331
+ cluster will be torn down after the specified idle time.
332
+ Note that if errors occur during provisioning/data syncing/setting
333
+ up, the cluster will not be torn down for debugging purposes.
334
+ backend: backend to use. If None, use the default backend
335
+ (CloudVMRayBackend).
336
+ optimize_target: target to optimize for. Choices: OptimizeTarget.COST,
337
+ OptimizeTarget.TIME.
338
+ no_setup: if True, do not re-run setup commands.
339
+ clone_disk_from: [Experimental] if set, clone the disk from the
340
+ specified cluster. This is useful to migrate the cluster to a
341
+ different availability zone or region.
342
+ fast: [Experimental] If the cluster is already up and available,
343
+ skip provisioning and setup steps.
344
+ _need_confirmation: (Internal only) If True, show the confirmation
345
+ prompt.
346
+
347
+ Returns:
348
+ The request ID of the launch request.
349
+
350
+ Request Returns:
351
+ job_id (Optional[int]): the job ID of the submitted job. None if the
352
+ backend is not ``CloudVmRayBackend``, or no job is submitted to the
353
+ cluster.
354
+ handle (Optional[backends.ResourceHandle]): the handle to the cluster.
355
+ None if dryrun.
356
+
357
+ Request Raises:
358
+ exceptions.ClusterOwnerIdentityMismatchError: if the cluster is owned
359
+ by another user.
360
+ exceptions.InvalidClusterNameError: if the cluster name is invalid.
361
+ exceptions.ResourcesMismatchError: if the requested resources
362
+ do not match the existing cluster.
363
+ exceptions.NotSupportedError: if required features are not supported
364
+ by the backend/cloud/cluster.
365
+ exceptions.ResourcesUnavailableError: if the requested resources
366
+ cannot be satisfied. The failover_history of the exception will be set
367
+ as:
368
+
369
+ 1. Empty: iff the first-ever sky.optimize() fails to find a feasible
370
+ resource; no pre-check or actual launch is attempted.
371
+
372
+ 2. Non-empty: iff at least 1 exception from either our pre-checks
373
+ (e.g., cluster name invalid) or a region/zone throwing resource
374
+ unavailability.
375
+
376
+ exceptions.CommandError: any ssh command error.
377
+ exceptions.NoCloudAccessError: if all clouds are disabled.
378
+
379
+ Other exceptions may be raised depending on the backend.
380
+ """
381
+ if cluster_name is None:
382
+ cluster_name = cluster_utils.generate_cluster_name()
383
+
384
+ if clone_disk_from is not None:
385
+ with ux_utils.print_exception_no_traceback():
386
+ raise NotImplementedError('clone_disk_from is not implemented yet. '
387
+ 'Please contact the SkyPilot team if you '
388
+ 'need this feature at slack.skypilot.co.')
389
+ dag = dag_utils.convert_entrypoint_to_dag(task)
390
+ validate(dag)
391
+
392
+ confirm_shown = False
393
+ if _need_confirmation:
394
+ cluster_status = None
395
+ # TODO(SKY-998): we should reduce RTTs before launching the cluster.
396
+ request_id = status([cluster_name], all_users=True)
397
+ clusters = get(request_id)
398
+ cluster_user_hash = common_utils.get_user_hash()
399
+ cluster_user_hash_str = ''
400
+ cluster_user_name = getpass.getuser()
401
+ if not clusters:
402
+ # Show the optimize log before the prompt if the cluster does not
403
+ # exist.
404
+ request_id = optimize(dag)
405
+ stream_and_get(request_id)
406
+ else:
407
+ cluster_record = clusters[0]
408
+ cluster_status = cluster_record['status']
409
+ cluster_user_hash = cluster_record['user_hash']
410
+ cluster_user_name = cluster_record['user_name']
411
+ if cluster_user_name == getpass.getuser():
412
+ # Only show the hash if the username is the same as the local
413
+ # username, to avoid confusion.
414
+ cluster_user_hash_str = f' (hash: {cluster_user_hash})'
415
+
416
+ # Prompt if (1) --cluster is None, or (2) cluster doesn't exist, or (3)
417
+ # it exists but is STOPPED.
418
+ prompt = None
419
+ if cluster_status is None:
420
+ prompt = (
421
+ f'Launching a new cluster {cluster_name!r}. '
422
+ # '{clone_source_str}. '
423
+ 'Proceed?')
424
+ elif cluster_status == status_lib.ClusterStatus.STOPPED:
425
+ user_name_str = ''
426
+ if cluster_user_hash != common_utils.get_user_hash():
427
+ user_name_str = (' created by another user '
428
+ f'{cluster_user_name!r}'
429
+ f'{cluster_user_hash_str}')
430
+ prompt = (f'Restarting the stopped cluster {cluster_name!r}'
431
+ f'{user_name_str}. Proceed?')
432
+ elif cluster_user_hash != common_utils.get_user_hash():
433
+ # Prompt if the cluster was created by a different user.
434
+ prompt = (f'Cluster {cluster_name!r} was created by another user '
435
+ f'{cluster_user_name!r}{cluster_user_hash_str}. '
436
+ 'Reusing the cluster. Proceed?')
437
+ if prompt is not None:
438
+ confirm_shown = True
439
+ click.confirm(prompt, default=True, abort=True, show_default=True)
440
+
441
+ if not confirm_shown:
442
+ click.secho('Running on cluster: ', fg='cyan', nl=False)
443
+ click.secho(cluster_name)
444
+
445
+ dag = client_common.upload_mounts_to_api_server(dag)
446
+
447
+ dag_str = dag_utils.dump_chain_dag_to_yaml_str(dag)
448
+
449
+ body = payloads.LaunchBody(
450
+ task=dag_str,
451
+ cluster_name=cluster_name,
452
+ retry_until_up=retry_until_up,
453
+ idle_minutes_to_autostop=idle_minutes_to_autostop,
454
+ dryrun=dryrun,
455
+ down=down,
456
+ backend=backend.NAME if backend else None,
457
+ optimize_target=optimize_target,
458
+ no_setup=no_setup,
459
+ clone_disk_from=clone_disk_from,
460
+ fast=fast,
461
+ # For internal use
462
+ quiet_optimizer=_need_confirmation,
463
+ is_launched_by_jobs_controller=_is_launched_by_jobs_controller,
464
+ is_launched_by_sky_serve_controller=(
465
+ _is_launched_by_sky_serve_controller),
466
+ disable_controller_check=_disable_controller_check,
467
+ )
468
+ response = requests.post(
469
+ f'{server_common.get_server_url()}/launch',
470
+ json=json.loads(body.model_dump_json()),
471
+ timeout=5,
472
+ )
473
+ return server_common.get_request_id(response)
474
+
475
+
476
+ @usage_lib.entrypoint
477
+ @server_common.check_server_healthy_or_start
478
+ @annotations.client_api
479
+ def exec( # pylint: disable=redefined-builtin
480
+ task: Union['sky.Task', 'sky.Dag'],
481
+ cluster_name: Optional[str] = None,
482
+ dryrun: bool = False,
483
+ down: bool = False, # pylint: disable=redefined-outer-name
484
+ backend: Optional[backends.Backend] = None,
485
+ ) -> server_common.RequestId:
486
+ """Executes a task on an existing cluster.
487
+
488
+ This function performs two actions:
489
+
490
+ (1) workdir syncing, if the task has a workdir specified;
491
+ (2) executing the task's ``run`` commands.
492
+
493
+ All other steps (provisioning, setup commands, file mounts syncing) are
494
+ skipped. If any of those specifications changed in the task, this function
495
+ will not reflect those changes. To ensure a cluster's setup is up to date,
496
+ use ``sky.launch()`` instead.
497
+
498
+ Execution and scheduling behavior:
499
+
500
+ - The task will undergo job queue scheduling, respecting any specified
501
+ resource requirement. It can be executed on any node of the cluster with
502
+ enough resources.
503
+ - The task is run under the workdir (if specified).
504
+ - The task is run non-interactively (without a pseudo-terminal or
505
+ pty), so interactive commands such as ``htop`` do not work.
506
+ Use ``ssh my_cluster`` instead.
507
+
508
+ Args:
509
+ task: sky.Task, or sky.Dag (experimental; 1-task only) containing the
510
+ task to execute.
511
+ cluster_name: name of an existing cluster to execute the task.
512
+ dryrun: if True, do not actually execute the task.
513
+ down: Tear down the cluster after all jobs finish (successfully or
514
+ abnormally). If --idle-minutes-to-autostop is also set, the
515
+ cluster will be torn down after the specified idle time.
516
+ Note that if errors occur during provisioning/data syncing/setting
517
+ up, the cluster will not be torn down for debugging purposes.
518
+ backend: backend to use. If None, use the default backend
519
+ (CloudVMRayBackend).
520
+
521
+ Returns:
522
+ The request ID of the exec request.
523
+
524
+
525
+ Request Returns:
526
+ job_id (Optional[int]): the job ID of the submitted job. None if the
527
+ backend is not CloudVmRayBackend, or no job is submitted to
528
+ the cluster.
529
+ handle (Optional[backends.ResourceHandle]): the handle to the cluster.
530
+ None if dryrun.
531
+
532
+ Request Raises:
533
+ ValueError: if the specified cluster is not in UP status.
534
+ sky.exceptions.ClusterDoesNotExist: if the specified cluster does not
535
+ exist.
536
+ sky.exceptions.NotSupportedError: if the specified cluster is a
537
+ controller that does not support this operation.
538
+ """
539
+ dag = dag_utils.convert_entrypoint_to_dag(task)
540
+ validate(dag, workdir_only=True)
541
+ dag = client_common.upload_mounts_to_api_server(dag, workdir_only=True)
542
+ dag_str = dag_utils.dump_chain_dag_to_yaml_str(dag)
543
+ body = payloads.ExecBody(
544
+ task=dag_str,
545
+ cluster_name=cluster_name,
546
+ dryrun=dryrun,
547
+ down=down,
548
+ backend=backend.NAME if backend else None,
549
+ )
550
+
551
+ response = requests.post(
552
+ f'{server_common.get_server_url()}/exec',
553
+ json=json.loads(body.model_dump_json()),
554
+ timeout=5,
555
+ )
556
+ return server_common.get_request_id(response)
557
+
558
+
559
+ @usage_lib.entrypoint
560
+ @server_common.check_server_healthy_or_start
561
+ @annotations.client_api
562
+ def tail_logs(cluster_name: str,
563
+ job_id: Optional[int],
564
+ follow: bool,
565
+ tail: int = 0,
566
+ output_stream: Optional['io.TextIOBase'] = None) -> None:
567
+ """Tails the logs of a job.
568
+
569
+ Args:
570
+ cluster_name: name of the cluster.
571
+ job_id: job id.
572
+ follow: if True, follow the logs. Otherwise, return the logs
573
+ immediately.
574
+ tail: if > 0, tail the last N lines of the logs.
575
+ output_stream: the stream to write the logs to. If None, print to the
576
+ console.
577
+
578
+ Returns:
579
+ None
580
+
581
+ Request Raises:
582
+ ValueError: if arguments are invalid or the cluster is not supported.
583
+ sky.exceptions.ClusterDoesNotExist: if the cluster does not exist.
584
+ sky.exceptions.ClusterNotUpError: if the cluster is not UP.
585
+ sky.exceptions.NotSupportedError: if the cluster is not based on
586
+ CloudVmRayBackend.
587
+ sky.exceptions.ClusterOwnerIdentityMismatchError: if the current user is
588
+ not the same as the user who created the cluster.
589
+ sky.exceptions.CloudUserIdentityError: if we fail to get the current
590
+ user identity.
591
+ """
592
+ body = payloads.ClusterJobBody(
593
+ cluster_name=cluster_name,
594
+ job_id=job_id,
595
+ follow=follow,
596
+ tail=tail,
597
+ )
598
+ response = requests.post(
599
+ f'{server_common.get_server_url()}/logs',
600
+ json=json.loads(body.model_dump_json()),
601
+ stream=True,
602
+ timeout=(client_common.API_SERVER_REQUEST_CONNECTION_TIMEOUT_SECONDS,
603
+ None))
604
+ request_id = server_common.get_request_id(response)
605
+ stream_response(request_id, response, output_stream)
606
+
607
+
608
+ @usage_lib.entrypoint
609
+ @server_common.check_server_healthy_or_start
610
+ @annotations.client_api
611
+ def download_logs(cluster_name: str,
612
+ job_ids: Optional[List[str]]) -> Dict[str, str]:
613
+ """Downloads the logs of jobs.
614
+
615
+ Args:
616
+ cluster_name: (str) name of the cluster.
617
+ job_ids: (List[str]) job ids.
618
+
619
+ Returns:
620
+ The request ID of the download_logs request.
621
+
622
+ Request Returns:
623
+ job_log_paths (Dict[str, str]): a mapping of job_id to local log path.
624
+
625
+ Request Raises:
626
+ sky.exceptions.ClusterDoesNotExist: if the cluster does not exist.
627
+ sky.exceptions.ClusterNotUpError: if the cluster is not UP.
628
+ sky.exceptions.NotSupportedError: if the cluster is not based on
629
+ CloudVmRayBackend.
630
+ sky.exceptions.ClusterOwnerIdentityMismatchError: if the current user is
631
+ not the same as the user who created the cluster.
632
+ sky.exceptions.CloudUserIdentityError: if we fail to get the current
633
+ user identity.
634
+ """
635
+ body = payloads.ClusterJobsDownloadLogsBody(
636
+ cluster_name=cluster_name,
637
+ job_ids=job_ids,
638
+ )
639
+ response = requests.post(f'{server_common.get_server_url()}/download_logs',
640
+ json=json.loads(body.model_dump_json()))
641
+ job_id_remote_path_dict = stream_and_get(
642
+ server_common.get_request_id(response))
643
+ remote2local_path_dict = client_common.download_logs_from_api_server(
644
+ job_id_remote_path_dict.values())
645
+ return {
646
+ job_id: remote2local_path_dict[remote_path]
647
+ for job_id, remote_path in job_id_remote_path_dict.items()
648
+ }
649
+
650
+
651
+ @usage_lib.entrypoint
652
+ @server_common.check_server_healthy_or_start
653
+ @annotations.client_api
654
+ def start(
655
+ cluster_name: str,
656
+ idle_minutes_to_autostop: Optional[int] = None,
657
+ retry_until_up: bool = False,
658
+ down: bool = False, # pylint: disable=redefined-outer-name
659
+ force: bool = False,
660
+ ) -> server_common.RequestId:
661
+ """Restart a cluster.
662
+
663
+ If a cluster is previously stopped (status is STOPPED) or failed in
664
+ provisioning/runtime installation (status is INIT), this function will
665
+ attempt to start the cluster. In the latter case, provisioning and runtime
666
+ installation will be retried.
667
+
668
+ Auto-failover provisioning is not used when restarting a stopped
669
+ cluster. It will be started on the same cloud, region, and zone that were
670
+ chosen before.
671
+
672
+ If a cluster is already in the UP status, this function has no effect.
673
+
674
+ Args:
675
+ cluster_name: name of the cluster to start.
676
+ idle_minutes_to_autostop: automatically stop the cluster after this
677
+ many minute of idleness, i.e., no running or pending jobs in the
678
+ cluster's job queue. Idleness gets reset whenever setting-up/
679
+ running/pending jobs are found in the job queue. Setting this
680
+ flag is equivalent to running
681
+ ``sky.launch(..., detach_run=True, ...)`` and then
682
+ ``sky.autostop(idle_minutes=<minutes>)``. If not set, the
683
+ cluster will not be autostopped.
684
+ retry_until_up: whether to retry launching the cluster until it is
685
+ up.
686
+ down: Autodown the cluster: tear down the cluster after specified
687
+ minutes of idle time after all jobs finish (successfully or
688
+ abnormally). Requires ``idle_minutes_to_autostop`` to be set.
689
+ force: whether to force start the cluster even if it is already up.
690
+ Useful for upgrading SkyPilot runtime.
691
+
692
+ Returns:
693
+ The request ID of the start request.
694
+
695
+ Request Returns:
696
+ None
697
+
698
+ Request Raises:
699
+ ValueError: argument values are invalid: (1) if ``down`` is set to True
700
+ but ``idle_minutes_to_autostop`` is None; (2) if the specified
701
+ cluster is the managed jobs controller, and either
702
+ ``idle_minutes_to_autostop`` is not None or ``down`` is True (omit
703
+ them to use the default autostop settings).
704
+ sky.exceptions.ClusterDoesNotExist: the specified cluster does not
705
+ exist.
706
+ sky.exceptions.NotSupportedError: if the cluster to restart was
707
+ launched using a non-default backend that does not support this
708
+ operation.
709
+ sky.exceptions.ClusterOwnerIdentitiesMismatchError: if the cluster to
710
+ restart was launched by a different user.
711
+ """
712
+ body = payloads.StartBody(
713
+ cluster_name=cluster_name,
714
+ idle_minutes_to_autostop=idle_minutes_to_autostop,
715
+ retry_until_up=retry_until_up,
716
+ down=down,
717
+ force=force,
718
+ )
719
+ response = requests.post(
720
+ f'{server_common.get_server_url()}/start',
721
+ json=json.loads(body.model_dump_json()),
722
+ timeout=5,
723
+ )
724
+ return server_common.get_request_id(response)
725
+
726
+
727
+ @usage_lib.entrypoint
728
+ @server_common.check_server_healthy_or_start
729
+ @annotations.client_api
730
+ def down(cluster_name: str, purge: bool = False) -> server_common.RequestId:
731
+ """Tears down a cluster.
732
+
733
+ Tearing down a cluster will delete all associated resources (all billing
734
+ stops), and any data on the attached disks will be lost. Accelerators
735
+ (e.g., TPUs) that are part of the cluster will be deleted too.
736
+
737
+ Args:
738
+ cluster_name: name of the cluster to down.
739
+ purge: (Advanced) Forcefully remove the cluster from SkyPilot's cluster
740
+ table, even if the actual cluster termination failed on the cloud.
741
+ WARNING: This flag should only be set sparingly in certain manual
742
+ troubleshooting scenarios; with it set, it is the user's
743
+ responsibility to ensure there are no leaked instances and related
744
+ resources.
745
+
746
+ Returns:
747
+ The request ID of the down request.
748
+
749
+ Request Returns:
750
+ None
751
+
752
+ Request Raises:
753
+ sky.exceptions.ClusterDoesNotExist: the specified cluster does not
754
+ exist.
755
+ RuntimeError: failed to tear down the cluster.
756
+ sky.exceptions.NotSupportedError: the specified cluster is the managed
757
+ jobs controller.
758
+
759
+ """
760
+ body = payloads.StopOrDownBody(
761
+ cluster_name=cluster_name,
762
+ purge=purge,
763
+ )
764
+ response = requests.post(
765
+ f'{server_common.get_server_url()}/down',
766
+ json=json.loads(body.model_dump_json()),
767
+ timeout=5,
768
+ )
769
+ return server_common.get_request_id(response)
770
+
771
+
772
+ @usage_lib.entrypoint
773
+ @server_common.check_server_healthy_or_start
774
+ @annotations.client_api
775
+ def stop(cluster_name: str, purge: bool = False) -> server_common.RequestId:
776
+ """Stops a cluster.
777
+
778
+ Data on attached disks is not lost when a cluster is stopped. Billing for
779
+ the instances will stop, while the disks will still be charged. Those
780
+ disks will be reattached when restarting the cluster.
781
+
782
+ Currently, spot instance clusters cannot be stopped (except for GCP, which
783
+ does allow disk contents to be preserved when stopping spot VMs).
784
+
785
+ Args:
786
+ cluster_name: name of the cluster to stop.
787
+ purge: (Advanced) Forcefully mark the cluster as stopped in SkyPilot's
788
+ cluster table, even if the actual cluster stop operation failed on
789
+ the cloud. WARNING: This flag should only be set sparingly in
790
+ certain manual troubleshooting scenarios; with it set, it is the
791
+ user's responsibility to ensure there are no leaked instances and
792
+ related resources.
793
+
794
+ Returns:
795
+ The request ID of the stop request.
796
+
797
+ Request Returns:
798
+ None
799
+
800
+ Request Raises:
801
+ sky.exceptions.ClusterDoesNotExist: the specified cluster does not
802
+ exist.
803
+ RuntimeError: failed to stop the cluster.
804
+ sky.exceptions.NotSupportedError: if the specified cluster is a spot
805
+ cluster, or a TPU VM Pod cluster, or the managed jobs controller.
806
+
807
+ """
808
+ body = payloads.StopOrDownBody(
809
+ cluster_name=cluster_name,
810
+ purge=purge,
811
+ )
812
+ response = requests.post(
813
+ f'{server_common.get_server_url()}/stop',
814
+ json=json.loads(body.model_dump_json()),
815
+ timeout=5,
816
+ )
817
+ return server_common.get_request_id(response)
818
+
819
+
820
+ @usage_lib.entrypoint
821
+ @server_common.check_server_healthy_or_start
822
+ @annotations.client_api
823
+ def autostop(
824
+ cluster_name: str,
825
+ idle_minutes: int,
826
+ down: bool = False # pylint: disable=redefined-outer-name
827
+ ) -> server_common.RequestId:
828
+ """Schedules an autostop/autodown for a cluster.
829
+
830
+ Autostop/autodown will automatically stop or teardown a cluster when it
831
+ becomes idle for a specified duration. Idleness means there are no
832
+ in-progress (pending/running) jobs in a cluster's job queue.
833
+
834
+ Idleness time of a cluster is reset to zero, whenever:
835
+
836
+ - A job is submitted (``sky.launch()`` or ``sky.exec()``).
837
+
838
+ - The cluster has restarted.
839
+
840
+ - An autostop is set when there is no active setting. (Namely, either
841
+ there's never any autostop setting set, or the previous autostop setting
842
+ was canceled.) This is useful for restarting the autostop timer.
843
+
844
+ Example: say a cluster without any autostop set has been idle for 1 hour,
845
+ then an autostop of 30 minutes is set. The cluster will not be immediately
846
+ autostopped. Instead, the idleness timer only starts counting after the
847
+ autostop setting was set.
848
+
849
+ When multiple autostop settings are specified for the same cluster, the
850
+ last setting takes precedence.
851
+
852
+ Args:
853
+ cluster_name: name of the cluster.
854
+ idle_minutes: the number of minutes of idleness (no pending/running
855
+ jobs) after which the cluster will be stopped automatically. Setting
856
+ to a negative number cancels any autostop/autodown setting.
857
+ down: if true, use autodown (tear down the cluster; non-restartable),
858
+ rather than autostop (restartable).
859
+
860
+ Returns:
861
+ The request ID of the autostop request.
862
+
863
+ Request Returns:
864
+ None
865
+
866
+ Request Raises:
867
+ sky.exceptions.ClusterDoesNotExist: if the cluster does not exist.
868
+ sky.exceptions.ClusterNotUpError: if the cluster is not UP.
869
+ sky.exceptions.NotSupportedError: if the cluster is not based on
870
+ CloudVmRayBackend or the cluster is TPU VM Pod.
871
+ sky.exceptions.ClusterOwnerIdentityMismatchError: if the current user is
872
+ not the same as the user who created the cluster.
873
+ sky.exceptions.CloudUserIdentityError: if we fail to get the current
874
+ user identity.
875
+ """
876
+ body = payloads.AutostopBody(
877
+ cluster_name=cluster_name,
878
+ idle_minutes=idle_minutes,
879
+ down=down,
880
+ )
881
+ response = requests.post(
882
+ f'{server_common.get_server_url()}/autostop',
883
+ json=json.loads(body.model_dump_json()),
884
+ timeout=5,
885
+ )
886
+ return server_common.get_request_id(response)
887
+
888
+
889
+ @usage_lib.entrypoint
890
+ @server_common.check_server_healthy_or_start
891
+ @annotations.client_api
892
+ def queue(cluster_name: List[str],
893
+ skip_finished: bool = False,
894
+ all_users: bool = False) -> server_common.RequestId:
895
+ """Gets the job queue of a cluster.
896
+
897
+ Args:
898
+ cluster_name: name of the cluster.
899
+ skip_finished: if True, skip finished jobs.
900
+ all_users: if True, return jobs from all users.
901
+
902
+
903
+ Returns:
904
+ The request ID of the queue request.
905
+
906
+ Request Returns:
907
+ job_records (List[Dict[str, Any]]): A list of dicts for each job in the
908
+ queue.
909
+
910
+ .. code-block:: python
911
+
912
+ [
913
+ {
914
+ 'job_id': (int) job id,
915
+ 'job_name': (str) job name,
916
+ 'username': (str) username,
917
+ 'user_hash': (str) user hash,
918
+ 'submitted_at': (int) timestamp of submitted,
919
+ 'start_at': (int) timestamp of started,
920
+ 'end_at': (int) timestamp of ended,
921
+ 'resources': (str) resources,
922
+ 'status': (job_lib.JobStatus) job status,
923
+ 'log_path': (str) log path,
924
+ }
925
+ ]
926
+
927
+ Request Raises:
928
+ sky.exceptions.ClusterDoesNotExist: if the cluster does not exist.
929
+ sky.exceptions.ClusterNotUpError: if the cluster is not UP.
930
+ sky.exceptions.NotSupportedError: if the cluster is not based on
931
+ ``CloudVmRayBackend``.
932
+ sky.exceptions.ClusterOwnerIdentityMismatchError: if the current user is
933
+ not the same as the user who created the cluster.
934
+ sky.exceptions.CloudUserIdentityError: if we fail to get the current
935
+ user identity.
936
+ sky.exceptions.CommandError: if failed to get the job queue with ssh.
937
+ """
938
+ body = payloads.QueueBody(
939
+ cluster_name=cluster_name,
940
+ skip_finished=skip_finished,
941
+ all_users=all_users,
942
+ )
943
+ response = requests.post(f'{server_common.get_server_url()}/queue',
944
+ json=json.loads(body.model_dump_json()))
945
+ return server_common.get_request_id(response)
946
+
947
+
948
+ @usage_lib.entrypoint
949
+ @server_common.check_server_healthy_or_start
950
+ @annotations.client_api
951
+ def job_status(cluster_name: str,
952
+ job_ids: Optional[List[int]] = None) -> server_common.RequestId:
953
+ """Gets the status of jobs on a cluster.
954
+
955
+ Args:
956
+ cluster_name: name of the cluster.
957
+ job_ids: job ids. If None, get the status of the last job.
958
+
959
+ Returns:
960
+ The request ID of the job status request.
961
+
962
+ Request Returns:
963
+ job_statuses (Dict[Optional[int], Optional[job_lib.JobStatus]]): A
964
+ mapping of job_id to job statuses. The status will be None if the
965
+ job does not exist. If job_ids is None and there is no job on the
966
+ cluster, it will return {None: None}.
967
+
968
+ Request Raises:
969
+ sky.exceptions.ClusterDoesNotExist: if the cluster does not exist.
970
+ sky.exceptions.ClusterNotUpError: if the cluster is not UP.
971
+ sky.exceptions.NotSupportedError: if the cluster is not based on
972
+ ``CloudVmRayBackend``.
973
+ sky.exceptions.ClusterOwnerIdentityMismatchError: if the current user is
974
+ not the same as the user who created the cluster.
975
+ sky.exceptions.CloudUserIdentityError: if we fail to get the current
976
+ user identity.
977
+ """
978
+ # TODO: merge this into the queue endpoint, i.e., let the queue endpoint
979
+ # take job_ids to filter the returned jobs.
980
+ body = payloads.JobStatusBody(
981
+ cluster_name=cluster_name,
982
+ job_ids=job_ids,
983
+ )
984
+ response = requests.post(f'{server_common.get_server_url()}/job_status',
985
+ json=json.loads(body.model_dump_json()))
986
+ return server_common.get_request_id(response)
987
+
988
+
989
+ @usage_lib.entrypoint
990
+ @server_common.check_server_healthy_or_start
991
+ @annotations.client_api
992
+ def cancel(
993
+ cluster_name: str,
994
+ all: bool = False, # pylint: disable=redefined-builtin
995
+ all_users: bool = False,
996
+ job_ids: Optional[List[int]] = None,
997
+ # pylint: disable=invalid-name
998
+ _try_cancel_if_cluster_is_init: bool = False
999
+ ) -> server_common.RequestId:
1000
+ """Cancels jobs on a cluster.
1001
+
1002
+ Args:
1003
+ cluster_name: name of the cluster.
1004
+ all: if True, cancel all jobs.
1005
+ all_users: if True, cancel all jobs from all users.
1006
+ job_ids: a list of job IDs to cancel.
1007
+ _try_cancel_if_cluster_is_init: (bool) whether to try cancelling the job
1008
+ even if the cluster is not UP, but the head node is still alive.
1009
+ This is used by the jobs controller to cancel the job when the
1010
+ worker node is preempted in the spot cluster.
1011
+
1012
+ Returns:
1013
+ The request ID of the cancel request.
1014
+
1015
+ Request Returns:
1016
+ None
1017
+
1018
+ Request Raises:
1019
+ ValueError: if arguments are invalid.
1020
+ sky.exceptions.ClusterDoesNotExist: if the cluster does not exist.
1021
+ sky.exceptions.ClusterNotUpError: if the cluster is not UP.
1022
+ sky.exceptions.NotSupportedError: if the specified cluster is a
1023
+ controller that does not support this operation.
1024
+ sky.exceptions.ClusterOwnerIdentityMismatchError: if the current user is
1025
+ not the same as the user who created the cluster.
1026
+ sky.exceptions.CloudUserIdentityError: if we fail to get the current
1027
+ user identity.
1028
+
1029
+ """
1030
+ body = payloads.CancelBody(
1031
+ cluster_name=cluster_name,
1032
+ all=all,
1033
+ all_users=all_users,
1034
+ job_ids=job_ids,
1035
+ try_cancel_if_cluster_is_init=_try_cancel_if_cluster_is_init,
1036
+ )
1037
+ response = requests.post(f'{server_common.get_server_url()}/cancel',
1038
+ json=json.loads(body.model_dump_json()))
1039
+ return server_common.get_request_id(response)
1040
+
1041
+
1042
+ @usage_lib.entrypoint
1043
+ @server_common.check_server_healthy_or_start
1044
+ @annotations.client_api
1045
+ def status(
1046
+ cluster_names: Optional[List[str]] = None,
1047
+ refresh: common.StatusRefreshMode = common.StatusRefreshMode.NONE,
1048
+ all_users: bool = False,
1049
+ ) -> server_common.RequestId:
1050
+ """Gets cluster statuses.
1051
+
1052
+ If cluster_names is given, return those clusters. Otherwise, return all
1053
+ clusters.
1054
+
1055
+ Each cluster can have one of the following statuses:
1056
+
1057
+ - ``INIT``: The cluster may be live or down. It can happen in the following
1058
+ cases:
1059
+
1060
+ - Ongoing provisioning or runtime setup. (A ``sky.launch()`` has started
1061
+ but has not completed.)
1062
+ - Or, the cluster is in an abnormal state, e.g., some cluster nodes are
1063
+ down, or the SkyPilot runtime is unhealthy. (To recover the cluster,
1064
+ try ``sky launch`` again on it.)
1065
+
1066
+ - ``UP``: Provisioning and runtime setup have succeeded and the cluster is
1067
+ live. (The most recent ``sky.launch()`` has completed successfully.)
1068
+
1069
+ - ``STOPPED``: The cluster is stopped and the storage is persisted. Use
1070
+ ``sky.start()`` to restart the cluster.
1071
+
1072
+ Autostop column:
1073
+
1074
+ - The autostop column indicates how long the cluster will be autostopped
1075
+ after minutes of idling (no jobs running). If ``to_down`` is True, the
1076
+ cluster will be autodowned, rather than autostopped.
1077
+
1078
+ Getting up-to-date cluster statuses:
1079
+
1080
+ - In normal cases where clusters are entirely managed by SkyPilot (i.e., no
1081
+ manual operations in cloud consoles) and no autostopping is used, the
1082
+ table returned by this command will accurately reflect the cluster
1083
+ statuses.
1084
+
1085
+ - In cases where the clusters are changed outside of SkyPilot (e.g., manual
1086
+ operations in cloud consoles; unmanaged spot clusters getting preempted)
1087
+ or for autostop-enabled clusters, use ``refresh=True`` to query the
1088
+ latest cluster statuses from the cloud providers.
1089
+
1090
+ Args:
1091
+ cluster_names: a list of cluster names to query. If not
1092
+ provided, all clusters will be queried.
1093
+ refresh: whether to query the latest cluster statuses from the cloud
1094
+ provider(s).
1095
+ all_users: whether to include all users' clusters. By default, only
1096
+ the current user's clusters are included.
1097
+
1098
+ Returns:
1099
+ The request ID of the status request.
1100
+
1101
+ Request Returns:
1102
+ cluster_records (List[Dict[str, Any]]): A list of dicts, with each dict
1103
+ containing the information of a cluster. If a cluster is found to be
1104
+ terminated or not found, it will be omitted from the returned list.
1105
+
1106
+ .. code-block:: python
1107
+
1108
+ {
1109
+ 'name': (str) cluster name,
1110
+ 'launched_at': (int) timestamp of last launch on this cluster,
1111
+ 'handle': (ResourceHandle) an internal handle to the cluster,
1112
+ 'last_use': (str) the last command/entrypoint that affected this
1113
+ cluster,
1114
+ 'status': (sky.ClusterStatus) cluster status,
1115
+ 'autostop': (int) idle time before autostop,
1116
+ 'to_down': (bool) whether autodown is used instead of autostop,
1117
+ 'metadata': (dict) metadata of the cluster,
1118
+ 'user_hash': (str) user hash of the cluster owner,
1119
+ 'user_name': (str) user name of the cluster owner,
1120
+ 'resources_str': (str) the resource string representation of the
1121
+ cluster,
1122
+ }
1123
+
1124
+ """
1125
+ # TODO(zhwu): this does not stream the logs output by logger back to the
1126
+ # user, due to the rich progress implementation.
1127
+ body = payloads.StatusBody(
1128
+ cluster_names=cluster_names,
1129
+ refresh=refresh,
1130
+ all_users=all_users,
1131
+ )
1132
+ response = requests.post(f'{server_common.get_server_url()}/status',
1133
+ json=json.loads(body.model_dump_json()))
1134
+ return server_common.get_request_id(response)
1135
+
1136
+
1137
+ @usage_lib.entrypoint
1138
+ @server_common.check_server_healthy_or_start
1139
+ @annotations.client_api
1140
+ def endpoints(
1141
+ cluster: str,
1142
+ port: Optional[Union[int, str]] = None) -> server_common.RequestId:
1143
+ """Gets the endpoint for a given cluster and port number (endpoint).
1144
+
1145
+ Args:
1146
+ cluster: The name of the cluster.
1147
+ port: The port number to get the endpoint for. If None, endpoints
1148
+ for all ports are returned.
1149
+
1150
+ Returns:
1151
+ The request ID of the endpoints request.
1152
+
1153
+ Request Returns:
1154
+ A dictionary of port numbers to endpoints. If port is None,
1155
+ the dictionary will contain all ports:endpoints exposed on the cluster.
1156
+
1157
+ Request Raises:
1158
+ ValueError: if the cluster is not UP or the endpoint is not exposed.
1159
+ RuntimeError: if the cluster has no ports to be exposed or no endpoints
1160
+ are exposed yet.
1161
+ """
1162
+ body = payloads.EndpointsBody(
1163
+ cluster=cluster,
1164
+ port=port,
1165
+ )
1166
+ response = requests.post(f'{server_common.get_server_url()}/endpoints',
1167
+ json=json.loads(body.model_dump_json()))
1168
+ return server_common.get_request_id(response)
1169
+
1170
+
1171
+ @usage_lib.entrypoint
1172
+ @server_common.check_server_healthy_or_start
1173
+ @annotations.client_api
1174
+ def cost_report() -> server_common.RequestId: # pylint: disable=redefined-builtin
1175
+ """Gets all cluster cost reports, including those that have been downed.
1176
+
1177
+ The estimated cost column indicates price for the cluster based on the type
1178
+ of resources being used and the duration of use up until the call to
1179
+ status. This means if the cluster is UP, successive calls to report will
1180
+ show increasing price. The estimated cost is calculated based on the local
1181
+ cache of the cluster status, and may not be accurate for the cluster with
1182
+ autostop/use_spot set or terminated/stopped on the cloud console.
1183
+
1184
+ Returns:
1185
+ The request ID of the cost report request.
1186
+
1187
+ Request Returns:
1188
+ cluster_cost_records (List[Dict[str, Any]]): A list of dicts, with each
1189
+ dict containing the cost information of a cluster.
1190
+
1191
+ .. code-block:: python
1192
+
1193
+ {
1194
+ 'name': (str) cluster name,
1195
+ 'launched_at': (int) timestamp of last launch on this cluster,
1196
+ 'duration': (int) total seconds that cluster was up and running,
1197
+ 'last_use': (str) the last command/entrypoint that affected this
1198
+ 'num_nodes': (int) number of nodes launched for cluster,
1199
+ 'resources': (resources.Resources) type of resource launched,
1200
+ 'cluster_hash': (str) unique hash identifying cluster,
1201
+ 'usage_intervals': (List[Tuple[int, int]]) cluster usage times,
1202
+ 'total_cost': (float) cost given resources and usage intervals,
1203
+ }
1204
+ """
1205
+ response = requests.get(f'{server_common.get_server_url()}/cost_report')
1206
+ return server_common.get_request_id(response)
1207
+
1208
+
1209
+ # === Storage APIs ===
1210
+ @usage_lib.entrypoint
1211
+ @server_common.check_server_healthy_or_start
1212
+ @annotations.client_api
1213
+ def storage_ls() -> server_common.RequestId:
1214
+ """Gets the storages.
1215
+
1216
+ Returns:
1217
+ The request ID of the storage list request.
1218
+
1219
+ Request Returns:
1220
+ storage_records (List[Dict[str, Any]]): A list of dicts, with each dict
1221
+ containing the information of a storage.
1222
+
1223
+ .. code-block:: python
1224
+
1225
+ {
1226
+ 'name': (str) storage name,
1227
+ 'launched_at': (int) timestamp of creation,
1228
+ 'store': (List[sky.StoreType]) storage type,
1229
+ 'last_use': (int) timestamp of last use,
1230
+ 'status': (sky.StorageStatus) storage status,
1231
+ }
1232
+ ]
1233
+ """
1234
+ response = requests.get(f'{server_common.get_server_url()}/storage/ls')
1235
+ return server_common.get_request_id(response)
1236
+
1237
+
1238
+ @usage_lib.entrypoint
1239
+ @server_common.check_server_healthy_or_start
1240
+ @annotations.client_api
1241
+ def storage_delete(name: str) -> server_common.RequestId:
1242
+ """Deletes a storage.
1243
+
1244
+ Args:
1245
+ name: The name of the storage to delete.
1246
+
1247
+ Returns:
1248
+ The request ID of the storage delete request.
1249
+
1250
+ Request Returns:
1251
+ None
1252
+
1253
+ Request Raises:
1254
+ ValueError: If the storage does not exist.
1255
+ """
1256
+ body = payloads.StorageBody(name=name)
1257
+ response = requests.post(f'{server_common.get_server_url()}/storage/delete',
1258
+ json=json.loads(body.model_dump_json()))
1259
+ return server_common.get_request_id(response)
1260
+
1261
+
1262
+ # === Kubernetes ===
1263
+
1264
+
1265
+ @usage_lib.entrypoint
1266
+ @server_common.check_server_healthy_or_start
1267
+ @annotations.client_api
1268
+ def local_up(gpus: bool, ips: Optional[List[str]], ssh_user: Optional[str],
1269
+ ssh_key: Optional[str], cleanup: bool) -> server_common.RequestId:
1270
+ """Launches a Kubernetes cluster on local machines.
1271
+
1272
+ Returns:
1273
+ request_id: The request ID of the local up request.
1274
+ """
1275
+ # We do not allow local up when the API server is running remotely since it
1276
+ # will modify the kubeconfig.
1277
+ # TODO: move this check to server.
1278
+ if not server_common.is_api_server_local():
1279
+ with ux_utils.print_exception_no_traceback():
1280
+ raise ValueError(
1281
+ 'sky local up is only supported when running SkyPilot locally.')
1282
+
1283
+ body = payloads.LocalUpBody(gpus=gpus,
1284
+ ips=ips,
1285
+ ssh_user=ssh_user,
1286
+ ssh_key=ssh_key,
1287
+ cleanup=cleanup)
1288
+ response = requests.post(f'{server_common.get_server_url()}/local_up',
1289
+ json=json.loads(body.model_dump_json()))
1290
+ return server_common.get_request_id(response)
1291
+
1292
+
1293
+ @usage_lib.entrypoint
1294
+ @server_common.check_server_healthy_or_start
1295
+ @annotations.client_api
1296
+ def local_down() -> server_common.RequestId:
1297
+ """Tears down the Kubernetes cluster started by local_up."""
1298
+ # We do not allow local up when the API server is running remotely since it
1299
+ # will modify the kubeconfig.
1300
+ # TODO: move this check to remote server.
1301
+ if not server_common.is_api_server_local():
1302
+ with ux_utils.print_exception_no_traceback():
1303
+ raise ValueError('sky local down is only supported when running '
1304
+ 'SkyPilot locally.')
1305
+ response = requests.post(f'{server_common.get_server_url()}/local_down')
1306
+ return server_common.get_request_id(response)
1307
+
1308
+
1309
+ @usage_lib.entrypoint
1310
+ @server_common.check_server_healthy_or_start
1311
+ @annotations.client_api
1312
+ def realtime_kubernetes_gpu_availability(
1313
+ context: Optional[str] = None,
1314
+ name_filter: Optional[str] = None,
1315
+ quantity_filter: Optional[int] = None) -> server_common.RequestId:
1316
+ """Gets the real-time Kubernetes GPU availability.
1317
+
1318
+ Returns:
1319
+ The request ID of the real-time Kubernetes GPU availability request.
1320
+ """
1321
+ body = payloads.RealtimeGpuAvailabilityRequestBody(
1322
+ context=context,
1323
+ name_filter=name_filter,
1324
+ quantity_filter=quantity_filter,
1325
+ )
1326
+ response = requests.post(
1327
+ f'{server_common.get_server_url()}/'
1328
+ 'realtime_kubernetes_gpu_availability',
1329
+ json=json.loads(body.model_dump_json()))
1330
+ return server_common.get_request_id(response)
1331
+
1332
+
1333
+ @usage_lib.entrypoint
1334
+ @server_common.check_server_healthy_or_start
1335
+ @annotations.client_api
1336
+ def kubernetes_node_info(
1337
+ context: Optional[str] = None) -> server_common.RequestId:
1338
+ """Gets the resource information for all the nodes in the cluster.
1339
+
1340
+ Currently only GPU resources are supported. The function returns the total
1341
+ number of GPUs available on the node and the number of free GPUs on the
1342
+ node.
1343
+
1344
+ If the user does not have sufficient permissions to list pods in all
1345
+ namespaces, the function will return free GPUs as -1.
1346
+
1347
+ Args:
1348
+ context: The Kubernetes context. If None, the default context is used.
1349
+
1350
+ Returns:
1351
+ The request ID of the Kubernetes node info request.
1352
+
1353
+ Request Returns:
1354
+ Dict[str, KubernetesNodeInfo]: Dictionary containing the node name as
1355
+ key and the KubernetesNodeInfo object as value
1356
+ """
1357
+ body = payloads.KubernetesNodeInfoRequestBody(context=context)
1358
+ response = requests.post(
1359
+ f'{server_common.get_server_url()}/kubernetes_node_info',
1360
+ json=json.loads(body.model_dump_json()))
1361
+ return server_common.get_request_id(response)
1362
+
1363
+
1364
+ @usage_lib.entrypoint
1365
+ @server_common.check_server_healthy_or_start
1366
+ @annotations.client_api
1367
+ def status_kubernetes() -> server_common.RequestId:
1368
+ """Gets all SkyPilot clusters and jobs in the Kubernetes cluster.
1369
+
1370
+ Managed jobs and services are also included in the clusters returned.
1371
+ The caller must parse the controllers to identify which clusters are run
1372
+ as managed jobs or services.
1373
+
1374
+ Returns:
1375
+ The request ID of the status request.
1376
+
1377
+ Request Returns:
1378
+ A tuple containing:
1379
+ - all_clusters: List of KubernetesSkyPilotClusterInfoPayload with info
1380
+ for all clusters, including managed jobs, services and controllers.
1381
+ - unmanaged_clusters: List of KubernetesSkyPilotClusterInfoPayload with
1382
+ info for all clusters excluding managed jobs and services.
1383
+ Controllers are included.
1384
+ - all_jobs: List of managed jobs from all controllers. Each entry is a
1385
+ dictionary job info, see jobs.queue_from_kubernetes_pod for details.
1386
+ - context: Kubernetes context used to fetch the cluster information.
1387
+ """
1388
+ response = requests.get(
1389
+ f'{server_common.get_server_url()}/status_kubernetes')
1390
+ return server_common.get_request_id(response)
1391
+
1392
+
1393
+ # === API request APIs ===
1394
+ @usage_lib.entrypoint
1395
+ @server_common.check_server_healthy_or_start
1396
+ @annotations.client_api
1397
+ def get(request_id: str) -> Any:
1398
+ """Waits for and gets the result of a request.
1399
+
1400
+ Args:
1401
+ request_id: The request ID of the request to get.
1402
+
1403
+ Returns:
1404
+ The ``Request Returns`` of the specified request. See the documentation
1405
+ of the specific requests above for more details.
1406
+
1407
+ Raises:
1408
+ Exception: It raises the same exceptions as the specific requests,
1409
+ see ``Request Raises`` in the documentation of the specific requests
1410
+ above.
1411
+ """
1412
+ response = requests.get(
1413
+ f'{server_common.get_server_url()}/api/get?request_id={request_id}',
1414
+ timeout=(client_common.API_SERVER_REQUEST_CONNECTION_TIMEOUT_SECONDS,
1415
+ None))
1416
+ request_task = None
1417
+ if response.status_code == 200:
1418
+ request_task = requests_lib.Request.decode(
1419
+ requests_lib.RequestPayload(**response.json()))
1420
+ elif response.status_code == 500:
1421
+ try:
1422
+ request_task = requests_lib.Request.decode(
1423
+ requests_lib.RequestPayload(**response.json().get('detail')))
1424
+ logger.debug(f'Got request with error: {request_task.name}')
1425
+ except Exception: # pylint: disable=broad-except
1426
+ request_task = None
1427
+ if request_task is None:
1428
+ with ux_utils.print_exception_no_traceback():
1429
+ raise RuntimeError(f'Failed to get request {request_id}: '
1430
+ f'{response.status_code} {response.text}')
1431
+ error = request_task.get_error()
1432
+ if error is not None:
1433
+ error_obj = error['object']
1434
+ if env_options.Options.SHOW_DEBUG_INFO.get():
1435
+ stacktrace = getattr(error_obj, 'stacktrace', str(error_obj))
1436
+ logger.error('=== Traceback on SkyPilot API Server ===\n'
1437
+ f'{stacktrace}')
1438
+ with ux_utils.print_exception_no_traceback():
1439
+ raise error_obj
1440
+ if request_task.status == requests_lib.RequestStatus.CANCELLED:
1441
+ with ux_utils.print_exception_no_traceback():
1442
+ raise exceptions.RequestCancelled(
1443
+ f'{colorama.Fore.YELLOW}Current {request_task.name!r} request '
1444
+ f'({request_task.request_id}) is cancelled by another process.'
1445
+ f'{colorama.Style.RESET_ALL}')
1446
+ return request_task.get_return_value()
1447
+
1448
+
1449
+ @usage_lib.entrypoint
1450
+ @server_common.check_server_healthy_or_start
1451
+ @annotations.client_api
1452
+ def stream_and_get(
1453
+ request_id: Optional[str] = None,
1454
+ log_path: Optional[str] = None,
1455
+ tail: Optional[int] = None,
1456
+ follow: bool = True,
1457
+ output_stream: Optional['io.TextIOBase'] = None,
1458
+ ) -> Any:
1459
+ """Streams the logs of a request or a log file and gets the final result.
1460
+
1461
+ This will block until the request is finished. The request id can be a
1462
+ prefix of the full request id.
1463
+
1464
+ Args:
1465
+ request_id: The prefix of the request ID of the request to stream.
1466
+ log_path: The path to the log file to stream.
1467
+ tail: The number of lines to show from the end of the logs.
1468
+ If None, show all logs.
1469
+ follow: Whether to follow the logs.
1470
+ output_stream: The output stream to write to. If None, print to the
1471
+ console.
1472
+
1473
+ Returns:
1474
+ The ``Request Returns`` of the specified request. See the documentation
1475
+ of the specific requests above for more details.
1476
+
1477
+ Raises:
1478
+ Exception: It raises the same exceptions as the specific requests,
1479
+ see ``Request Raises`` in the documentation of the specific requests
1480
+ above.
1481
+ """
1482
+ params = {
1483
+ 'request_id': request_id,
1484
+ 'log_path': log_path,
1485
+ 'tail': str(tail) if tail is not None else None,
1486
+ 'follow': follow,
1487
+ 'format': 'console',
1488
+ }
1489
+ response = requests.get(
1490
+ f'{server_common.get_server_url()}/api/stream',
1491
+ params=params,
1492
+ timeout=(client_common.API_SERVER_REQUEST_CONNECTION_TIMEOUT_SECONDS,
1493
+ None),
1494
+ stream=True)
1495
+ if response.status_code in [404, 400]:
1496
+ detail = response.json().get('detail')
1497
+ with ux_utils.print_exception_no_traceback():
1498
+ raise RuntimeError(f'Failed to stream logs: {detail}')
1499
+ elif response.status_code != 200:
1500
+ return get(request_id)
1501
+ return stream_response(request_id, response, output_stream)
1502
+
1503
+
1504
+ @usage_lib.entrypoint
1505
+ @annotations.client_api
1506
+ def api_cancel(request_ids: Optional[List[str]] = None,
1507
+ all_users: bool = False,
1508
+ silent: bool = False) -> server_common.RequestId:
1509
+ """Aborts a request or all requests.
1510
+
1511
+ Args:
1512
+ request_id: The prefix of the request ID of the request to abort.
1513
+ all: Whether to abort all requests.
1514
+ all_users: Whether to abort all requests from all users.
1515
+ silent: Whether to suppress the output.
1516
+
1517
+ Returns:
1518
+ The request ID of the abort request itself.
1519
+
1520
+ Request Returns:
1521
+ A list of request IDs that were cancelled.
1522
+
1523
+ Raises:
1524
+ click.BadParameter: If no request ID is specified and not all or
1525
+ all_users is not set.
1526
+ """
1527
+ echo = logger.info if not silent else logger.debug
1528
+ user_id = None
1529
+ if not all_users:
1530
+ user_id = common_utils.get_user_hash()
1531
+ body = payloads.RequestCancelBody(request_ids=request_ids, user_id=user_id)
1532
+ if all_users:
1533
+ echo('Cancelling all users\' requests...')
1534
+ elif request_ids is None:
1535
+ echo(f'Cancelling all requests for user {user_id!r}...')
1536
+ else:
1537
+ request_id_str = ', '.join(
1538
+ repr(request_id) for request_id in request_ids)
1539
+ plural = 's' if len(request_ids) > 1 else ''
1540
+ echo(f'Cancelling {len(request_ids)} request{plural}: '
1541
+ f'{request_id_str}...')
1542
+
1543
+ response = requests.post(f'{server_common.get_server_url()}/api/cancel',
1544
+ json=json.loads(body.model_dump_json()),
1545
+ timeout=5)
1546
+ return server_common.get_request_id(response)
1547
+
1548
+
1549
+ @usage_lib.entrypoint
1550
+ @annotations.client_api
1551
+ def api_status(
1552
+ request_ids: Optional[List[str]] = None,
1553
+ # pylint: disable=redefined-builtin
1554
+ all_status: bool = False
1555
+ ) -> List[requests_lib.RequestPayload]:
1556
+ """Lists all requests.
1557
+
1558
+ Args:
1559
+ request_ids: The prefixes of the request IDs of the requests to query.
1560
+ If None, all requests are queried.
1561
+ all_status: Whether to list all finished requests as well. This argument
1562
+ is ignored if request_ids is not None.
1563
+
1564
+ Returns:
1565
+ A list of request payloads.
1566
+ """
1567
+ body = payloads.RequestStatusBody(request_ids=request_ids,
1568
+ all_status=all_status)
1569
+ response = requests.get(
1570
+ f'{server_common.get_server_url()}/api/status',
1571
+ params=server_common.request_body_to_params(body),
1572
+ timeout=(client_common.API_SERVER_REQUEST_CONNECTION_TIMEOUT_SECONDS,
1573
+ None))
1574
+ server_common.handle_request_error(response)
1575
+ return [
1576
+ requests_lib.RequestPayload(**request) for request in response.json()
1577
+ ]
1578
+
1579
+
1580
+ # === API server management APIs ===
1581
+ @usage_lib.entrypoint
1582
+ @server_common.check_server_healthy_or_start
1583
+ @annotations.client_api
1584
+ def api_info() -> Dict[str, str]:
1585
+ """Gets the server's status, commit and version.
1586
+
1587
+ Returns:
1588
+ A dictionary containing the server's status, commit and version.
1589
+
1590
+ .. code-block:: python
1591
+
1592
+ {
1593
+ 'status': 'healthy',
1594
+ 'api_version': '1',
1595
+ 'commit': 'abc1234567890',
1596
+ 'version': '1.0.0',
1597
+ }
1598
+
1599
+ """
1600
+ response = requests.get(f'{server_common.get_server_url()}/api/health')
1601
+ response.raise_for_status()
1602
+ return response.json()
1603
+
1604
+
1605
+ @usage_lib.entrypoint
1606
+ @annotations.client_api
1607
+ def api_start(
1608
+ *,
1609
+ deploy: bool = False,
1610
+ host: str = '127.0.0.1',
1611
+ ) -> None:
1612
+ """Starts the API server.
1613
+
1614
+ It checks the existence of the API server and starts it if it does not
1615
+ exist.
1616
+
1617
+ Args:
1618
+ deploy: Whether to deploy the API server, i.e. fully utilize the
1619
+ resources of the machine.
1620
+ host: The host to deploy the API server. It will be set to 0.0.0.0
1621
+ if deploy is True, to allow remote access.
1622
+
1623
+ Returns:
1624
+ None
1625
+ """
1626
+ if deploy:
1627
+ host = '0.0.0.0'
1628
+ if host not in server_common.AVAILBLE_LOCAL_API_SERVER_HOSTS:
1629
+ raise ValueError(f'Invalid host: {host}. Should be one of: '
1630
+ f'{server_common.AVAILBLE_LOCAL_API_SERVER_HOSTS}')
1631
+ is_local_api_server = server_common.is_api_server_local()
1632
+ if not is_local_api_server:
1633
+ server_url = server_common.get_server_url()
1634
+ with ux_utils.print_exception_no_traceback():
1635
+ raise ValueError(f'Unable to start local API server: '
1636
+ f'server endpoint is set to {server_url}. '
1637
+ 'To start a local API server, remove the endpoint '
1638
+ 'from the config file and/or unset the '
1639
+ 'SKYPILOT_API_SERVER_ENDPOINT environment '
1640
+ 'variable.')
1641
+ server_common.check_server_healthy_or_start_fn(deploy, host)
1642
+ logger.info(f'{ux_utils.INDENT_SYMBOL}SkyPilot API server: '
1643
+ f'{server_common.get_server_url(host)}\n'
1644
+ f'{ux_utils.INDENT_LAST_SYMBOL}'
1645
+ f'View API server logs at: {constants.API_SERVER_LOGS}')
1646
+
1647
+
1648
+ @usage_lib.entrypoint
1649
+ @annotations.client_api
1650
+ def api_stop() -> None:
1651
+ """Stops the API server.
1652
+
1653
+ It will do nothing if the API server is remotely hosted.
1654
+
1655
+ Returns:
1656
+ None
1657
+ """
1658
+ # Kill the uvicorn process by name: uvicorn sky.server.server:app
1659
+ server_url = server_common.get_server_url()
1660
+ if not server_common.is_api_server_local():
1661
+ with ux_utils.print_exception_no_traceback():
1662
+ raise RuntimeError(
1663
+ f'Cannot kill the API server at {server_url} because it is not '
1664
+ f'the default SkyPilot API server started locally.')
1665
+
1666
+ found = False
1667
+ for process in psutil.process_iter(attrs=['pid', 'cmdline']):
1668
+ cmdline = process.info['cmdline']
1669
+ if cmdline and server_common.API_SERVER_CMD in ' '.join(cmdline):
1670
+ subprocess_utils.kill_children_processes(parent_pids=[process.pid],
1671
+ force=True)
1672
+ found = True
1673
+
1674
+ # Remove the database for requests including any files starting with
1675
+ # api.constants.API_SERVER_REQUEST_DB_PATH
1676
+ db_path = os.path.expanduser(server_constants.API_SERVER_REQUEST_DB_PATH)
1677
+ for extension in ['', '-shm', '-wal']:
1678
+ try:
1679
+ os.remove(f'{db_path}{extension}')
1680
+ except FileNotFoundError:
1681
+ logger.debug(f'Database file {db_path}{extension} not found.')
1682
+
1683
+ if found:
1684
+ logger.info(f'{colorama.Fore.GREEN}SkyPilot API server stopped.'
1685
+ f'{colorama.Style.RESET_ALL}')
1686
+ else:
1687
+ logger.info('SkyPilot API server is not running.')
1688
+
1689
+
1690
+ # Use the same args as `docker logs`
1691
+ @usage_lib.entrypoint
1692
+ @annotations.client_api
1693
+ def api_server_logs(follow: bool = True, tail: Optional[int] = None) -> None:
1694
+ """Streams the API server logs.
1695
+
1696
+ Args:
1697
+ follow: Whether to follow the logs.
1698
+ tail: the number of lines to show from the end of the logs.
1699
+ If None, show all logs.
1700
+
1701
+ Returns:
1702
+ None
1703
+ """
1704
+ if server_common.is_api_server_local():
1705
+ tail_args = ['-f'] if follow else []
1706
+ if tail is None:
1707
+ tail_args.extend(['-n', '+1'])
1708
+ else:
1709
+ tail_args.extend(['-n', f'{tail}'])
1710
+ log_path = os.path.expanduser(constants.API_SERVER_LOGS)
1711
+ subprocess.run(['tail', *tail_args, f'{log_path}'], check=False)
1712
+ else:
1713
+ stream_and_get(log_path=constants.API_SERVER_LOGS, tail=tail)
1714
+
1715
+
1716
+ @usage_lib.entrypoint
1717
+ @annotations.client_api
1718
+ def api_login(endpoint: Optional[str] = None) -> None:
1719
+ """Logs into a SkyPilot API server.
1720
+
1721
+ This sets the endpoint globally, i.e., all SkyPilot CLI and SDK calls will
1722
+ use this endpoint.
1723
+
1724
+ To temporarily override the endpoint, use the environment variable
1725
+ `SKYPILOT_API_SERVER_ENDPOINT` instead.
1726
+
1727
+ Args:
1728
+ endpoint: The endpoint of the SkyPilot API server, e.g.,
1729
+ http://1.2.3.4:46580 or https://skypilot.mydomain.com.
1730
+
1731
+ Returns:
1732
+ None
1733
+ """
1734
+ # TODO(zhwu): this SDK sets global endpoint, which may not be the best
1735
+ # design as a user may expect this is only effective for the current
1736
+ # session. We should consider using env var for specifying endpoint.
1737
+ if endpoint is None:
1738
+ endpoint = click.prompt('Enter your SkyPilot API server endpoint')
1739
+ # Check endpoint is a valid URL
1740
+ if (endpoint is not None and not endpoint.startswith('http://') and
1741
+ not endpoint.startswith('https://')):
1742
+ raise click.BadParameter('Endpoint must be a valid URL.')
1743
+
1744
+ server_common.check_server_healthy(endpoint)
1745
+
1746
+ # Set the endpoint in the config file
1747
+ config_path = pathlib.Path(skypilot_config.CONFIG_PATH).expanduser()
1748
+ with filelock.FileLock(config_path.with_suffix('.lock')):
1749
+ if not skypilot_config.loaded():
1750
+ config_path.touch()
1751
+ config = {'api_server': {'endpoint': endpoint}}
1752
+ else:
1753
+ config = skypilot_config.set_nested(('api_server', 'endpoint'),
1754
+ endpoint)
1755
+ common_utils.dump_yaml(str(config_path), config)
1756
+ click.secho(f'Logged in to SkyPilot API server at {endpoint}',
1757
+ fg='green')