-
Notifications
You must be signed in to change notification settings - Fork 638
/
Copy pathcloud_vm_ray_backend.py
5217 lines (4754 loc) · 247 KB
/
cloud_vm_ray_backend.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Backend: runs on cloud virtual machines, managed by Ray."""
import copy
import enum
import inspect
import json
import math
import os
import pathlib
import re
import shlex
import shutil
import signal
import subprocess
import sys
import tempfile
import textwrap
import threading
import time
import typing
from typing import (Any, Callable, Dict, Iterable, List, Optional, Set, Tuple,
Union)
import colorama
import filelock
import sky
from sky import backends
from sky import check as sky_check
from sky import cloud_stores
from sky import clouds
from sky import exceptions
from sky import global_user_state
from sky import jobs as managed_jobs
from sky import optimizer
from sky import provision as provision_lib
from sky import resources as resources_lib
from sky import sky_logging
from sky import skypilot_config
from sky import task as task_lib
from sky.backends import backend_utils
from sky.backends import wheel_utils
from sky.clouds import cloud as sky_cloud
from sky.clouds import service_catalog
from sky.clouds.utils import gcp_utils
from sky.data import data_utils
from sky.data import storage as storage_lib
from sky.provision import common as provision_common
from sky.provision import instance_setup
from sky.provision import metadata_utils
from sky.provision import provisioner
from sky.provision.kubernetes import utils as kubernetes_utils
from sky.server.requests import requests as requests_lib
from sky.skylet import autostop_lib
from sky.skylet import constants
from sky.skylet import job_lib
from sky.skylet import log_lib
from sky.usage import usage_lib
from sky.utils import accelerator_registry
from sky.utils import annotations
from sky.utils import cluster_utils
from sky.utils import command_runner
from sky.utils import common
from sky.utils import common_utils
from sky.utils import controller_utils
from sky.utils import env_options
from sky.utils import log_utils
from sky.utils import message_utils
from sky.utils import registry
from sky.utils import resources_utils
from sky.utils import rich_utils
from sky.utils import status_lib
from sky.utils import subprocess_utils
from sky.utils import timeline
from sky.utils import ux_utils
if typing.TYPE_CHECKING:
from sky import dag
Path = str
SKY_REMOTE_APP_DIR = backend_utils.SKY_REMOTE_APP_DIR
SKY_REMOTE_WORKDIR = constants.SKY_REMOTE_WORKDIR
logger = sky_logging.init_logger(__name__)
_PATH_SIZE_MEGABYTES_WARN_THRESHOLD = 256
# Timeout (seconds) for provision progress: if in this duration no new nodes
# are launched, abort and failover.
_NODES_LAUNCHING_PROGRESS_TIMEOUT = {
clouds.AWS: 90,
clouds.Azure: 90,
clouds.GCP: 240,
clouds.Lambda: 300,
clouds.IBM: 160,
clouds.OCI: 300,
clouds.Paperspace: 600,
clouds.Kubernetes: 300,
clouds.Vsphere: 240,
}
# Time gap between retries after failing to provision in all possible places.
# Used only if --retry-until-up is set.
_RETRY_UNTIL_UP_INIT_GAP_SECONDS = 30
# The maximum retry count for fetching IP address.
_FETCH_IP_MAX_ATTEMPTS = 3
# How many times to query the cloud provider to make sure instances are
# stopping/terminating, and how long to wait between each query.
_TEARDOWN_WAIT_MAX_ATTEMPTS = 10
_TEARDOWN_WAIT_BETWEEN_ATTEMPS_SECONDS = 1
_TEARDOWN_FAILURE_MESSAGE = (
f'\n{colorama.Fore.RED}Failed to terminate '
'{cluster_name}. {extra_reason}'
'If you want to ignore this error and remove the cluster '
'from the status table, use `sky down --purge`.'
f'{colorama.Style.RESET_ALL}\n'
'**** STDOUT ****\n'
'{stdout}\n'
'**** STDERR ****\n'
'{stderr}')
_TEARDOWN_PURGE_WARNING = (
f'{colorama.Fore.YELLOW}'
'WARNING: Received non-zero exit code from {reason}. '
'Make sure resources are manually deleted.\n'
'Details: {details}'
f'{colorama.Style.RESET_ALL}')
_RSYNC_NOT_FOUND_MESSAGE = (
'`rsync` command is not found in the specified image. '
'Please use an image with rsync installed.')
_TPU_NOT_FOUND_ERROR = 'ERROR: (gcloud.compute.tpus.delete) NOT_FOUND'
_MAX_RAY_UP_RETRY = 5
# Number of retries for getting zones.
_MAX_GET_ZONE_RETRY = 3
_JOB_ID_PATTERN = re.compile(r'Job ID: ([0-9]+)')
# Path to the monkey-patched ray up script.
# We don't do import then __file__ because that script needs to be filled in
# (so import would fail).
_RAY_UP_WITH_MONKEY_PATCHED_HASH_LAUNCH_CONF_PATH = (
pathlib.Path(sky.__file__).resolve().parent / 'backends' /
'monkey_patches' / 'monkey_patch_ray_up.py')
# The maximum size of a command line arguments is 128 KB, i.e. the command
# executed with /bin/sh should be less than 128KB.
# https://github.com/torvalds/linux/blob/master/include/uapi/linux/binfmts.h
#
# If a user have very long run or setup commands, the generated command may
# exceed the limit, as we directly include scripts in job submission commands.
# If the command is too long, we instead write it to a file, rsync and execute
# it.
#
# We use 100KB as a threshold to be safe for other arguments that
# might be added during ssh.
_MAX_INLINE_SCRIPT_LENGTH = 100 * 1024
_RESOURCES_UNAVAILABLE_LOG = (
'Reasons for provision failures (for details, please check the log above):')
def _is_command_length_over_limit(command: str) -> bool:
"""Check if the length of the command exceeds the limit.
We calculate the length of the command after quoting the command twice as
when it is executed by the CommandRunner, the command will be quoted twice
to ensure the correctness, which will add significant length to the command.
"""
quoted_length = len(shlex.quote(shlex.quote(command)))
return quoted_length > _MAX_INLINE_SCRIPT_LENGTH
def _get_cluster_config_template(cloud):
cloud_to_template = {
clouds.AWS: 'aws-ray.yml.j2',
clouds.Azure: 'azure-ray.yml.j2',
clouds.Cudo: 'cudo-ray.yml.j2',
clouds.GCP: 'gcp-ray.yml.j2',
clouds.Lambda: 'lambda-ray.yml.j2',
clouds.IBM: 'ibm-ray.yml.j2',
clouds.SCP: 'scp-ray.yml.j2',
clouds.OCI: 'oci-ray.yml.j2',
clouds.Paperspace: 'paperspace-ray.yml.j2',
clouds.DO: 'do-ray.yml.j2',
clouds.RunPod: 'runpod-ray.yml.j2',
clouds.Kubernetes: 'kubernetes-ray.yml.j2',
clouds.Vsphere: 'vsphere-ray.yml.j2',
clouds.Vast: 'vast-ray.yml.j2',
clouds.Fluidstack: 'fluidstack-ray.yml.j2',
clouds.Nebius: 'nebius-ray.yml.j2'
}
return cloud_to_template[type(cloud)]
def write_ray_up_script_with_patched_launch_hash_fn(
cluster_config_path: Optional[str],
ray_up_kwargs: Dict[str, bool],
) -> str:
"""Writes a Python script that runs `ray up` with our launch hash func.
Our patched launch hash has one difference from the non-patched version: it
does not include any `ssh_proxy_command` under `auth` as part of the hash
calculation.
"""
with open(_RAY_UP_WITH_MONKEY_PATCHED_HASH_LAUNCH_CONF_PATH,
'r',
encoding='utf-8') as f:
ray_up_no_restart_script = f.read().format(
ray_yaml_path=repr(cluster_config_path),
ray_up_kwargs=ray_up_kwargs)
with tempfile.NamedTemporaryFile('w',
prefix='skypilot_ray_up_',
suffix='.py',
delete=False) as f:
f.write(ray_up_no_restart_script)
logger.debug(f'`ray up` script: {f.name}')
return f.name
class RayCodeGen:
"""Code generator of a Ray program that executes a sky.Task.
Usage:
>> codegen = RayCodegen()
>> codegen.add_prologue()
>> codegen.add_ray_task(...)
>> codegen.add_ray_task(...)
>> codegen.add_epilogue()
>> code = codegen.build()
"""
def __init__(self):
# Code generated so far, to be joined via '\n'.
self._code = []
# Guard method calling order.
self._has_prologue = False
self._has_epilogue = False
# For n nodes gang scheduling.
self._has_gang_scheduling = False
self._num_nodes = 0
self._has_register_run_fn = False
# job_id
# Job ID is used to identify the job (also this generated code).
# It is a int automatically generated by the DB on the cluster
# and monotonically increasing starting from 1.
# To generate the job ID, we use the following logic:
# code = job_lib.JobLibCodeGen.add_job(username,
# run_timestamp)
# job_id = get_output(run_on_cluster(code))
self.job_id = None
def add_prologue(self, job_id: int) -> None:
assert not self._has_prologue, 'add_prologue() called twice?'
self._has_prologue = True
self.job_id = job_id
# Should use 'auto' or 'ray://<internal_head_ip>:10001' rather than
# 'ray://localhost:10001', or 'ray://127.0.0.1:10001', for public cloud.
# Otherwise, ray will fail to get the placement group because of a bug
# in ray job.
ray_address = 'auto'
self._code = [
textwrap.dedent(f"""\
import getpass
import hashlib
import io
import os
import pathlib
import selectors
import shlex
import subprocess
import sys
import tempfile
import textwrap
import time
from typing import Dict, List, Optional, Tuple, Union
# Set the environment variables to avoid deduplicating logs and
# scheduler events. This should be set in driver code, since we are
# not using `ray job submit` anymore, and the environment variables
# from the ray cluster is not inherited.
os.environ['RAY_DEDUP_LOGS'] = '0'
os.environ['RAY_SCHEDULER_EVENTS'] = '0'
import ray
import ray.util as ray_util
from sky.skylet import autostop_lib
from sky.skylet import constants
from sky.skylet import job_lib
from sky.utils import log_utils
from sky.utils import subprocess_utils
SKY_REMOTE_WORKDIR = {constants.SKY_REMOTE_WORKDIR!r}
kwargs = dict()
# Only set the `_temp_dir` to SkyPilot's ray cluster directory when
# the directory exists for backward compatibility for the VM
# launched before #1790.
if os.path.exists({constants.SKY_REMOTE_RAY_TEMPDIR!r}):
kwargs['_temp_dir'] = {constants.SKY_REMOTE_RAY_TEMPDIR!r}
ray.init(
address={ray_address!r},
namespace='__sky__{job_id}__',
log_to_driver=True,
**kwargs
)
def get_or_fail(futures, pg) -> List[int]:
\"\"\"Wait for tasks, if any fails, cancel all unready.\"\"\"
if not futures:
return []
returncodes = [1] * len(futures)
# Wait for 1 task to be ready.
ready = []
# Keep invoking ray.wait if ready is empty. This is because
# ray.wait with timeout=None will only wait for 10**6 seconds,
# which will cause tasks running for more than 12 days to return
# before becoming ready.
# (Such tasks are common in serving jobs.)
# Reference: https://github.com/ray-project/ray/blob/ray-2.9.3/python/ray/_private/worker.py#L2845-L2846
while not ready:
ready, unready = ray.wait(futures)
idx = futures.index(ready[0])
returncodes[idx] = ray.get(ready[0])
while unready:
if returncodes[idx] != 0:
for task in unready:
# ray.cancel without force fails to kill tasks.
# We use force=True to kill unready tasks.
ray.cancel(task, force=True)
# Use SIGKILL=128+9 to indicate the task is forcely
# killed.
idx = futures.index(task)
returncodes[idx] = 137
break
ready, unready = ray.wait(unready)
idx = futures.index(ready[0])
returncodes[idx] = ray.get(ready[0])
# Remove the placement group after all tasks are done, so that
# the next job can be scheduled on the released resources
# immediately.
ray_util.remove_placement_group(pg)
sys.stdout.flush()
return returncodes
run_fn = None
futures = []
"""),
# FIXME: This is a hack to make sure that the functions can be found
# by ray.remote. This should be removed once we have a better way to
# specify dependencies for ray.
inspect.getsource(log_lib._ProcessingArgs), # pylint: disable=protected-access
inspect.getsource(log_lib._handle_io_stream), # pylint: disable=protected-access
inspect.getsource(log_lib.process_subprocess_stream),
inspect.getsource(log_lib.run_with_log),
inspect.getsource(log_lib.make_task_bash_script),
inspect.getsource(log_lib.add_ray_env_vars),
inspect.getsource(log_lib.run_bash_command_with_log),
'run_bash_command_with_log = ray.remote(run_bash_command_with_log)',
]
# Currently, the codegen program is/can only be submitted to the head
# node, due to using job_lib for updating job statuses, and using
# autostop_lib here.
self._code.append(
# Use hasattr to handle backward compatibility.
# TODO(zongheng): remove in ~1-2 minor releases (currently 0.2.x).
textwrap.dedent("""\
if hasattr(autostop_lib, 'set_last_active_time_to_now'):
autostop_lib.set_last_active_time_to_now()
"""))
self._code += [
f'job_lib.set_status({job_id!r}, job_lib.JobStatus.PENDING)',
]
def add_gang_scheduling_placement_group_and_setup(
self,
num_nodes: int,
resources_dict: Dict[str, float],
stable_cluster_internal_ips: List[str],
env_vars: Dict[str, str],
setup_cmd: Optional[str] = None,
setup_log_path: Optional[str] = None,
) -> None:
"""Create the gang scheduling placement group for a Task.
cluster_ips_sorted is used to ensure that the SKY_NODE_RANK environment
variable is assigned in a deterministic order whenever a new task is
added.
"""
assert self._has_prologue, (
'Call add_prologue() before '
'add_gang_scheduling_placement_group_and_setup().')
self._has_gang_scheduling = True
self._num_nodes = num_nodes
bundles = [copy.copy(resources_dict) for _ in range(num_nodes)]
# Set CPU to avoid ray hanging the resources allocation
# for remote functions, since the task will request 1 CPU
# by default.
task_cpu_demand = resources_dict.pop('CPU')
if resources_dict:
assert len(resources_dict) == 1, (
'There can only be one type of accelerator per instance. '
f'Found: {resources_dict}.')
acc_name, acc_count = list(resources_dict.items())[0]
gpu_dict = {'GPU': acc_count}
# gpu_dict should be empty when the accelerator is not GPU.
# TODO(zongheng,zhanghao): an alternative is to start the remote
# cluster with custom resource 'GPU': <n> even if the accelerator(s)
# are not GPU. We opt for the current solution for now.
if accelerator_registry.is_schedulable_non_gpu_accelerator(
acc_name):
gpu_dict = {}
for bundle in bundles:
bundle.update({
# Set the GPU to avoid ray hanging the resources allocation
**gpu_dict,
})
streaming_message = (
f'{ux_utils.INDENT_LAST_SYMBOL}Job started. Streaming logs... '
f'{colorama.Style.DIM}(Ctrl-C to exit log streaming; job will not '
f'be killed){colorama.Style.RESET_ALL}')
self._code += [
textwrap.dedent(f"""\
pg = ray_util.placement_group({json.dumps(bundles)}, 'STRICT_SPREAD')
plural = 's' if {num_nodes} > 1 else ''
node_str = f'{num_nodes} node{{plural}}'
message = ('{ux_utils.INDENT_SYMBOL}{colorama.Style.DIM}'
'Waiting for task resources on '
f'{{node_str}}.{colorama.Style.RESET_ALL}')
print(message, flush=True)
# FIXME: This will print the error message from autoscaler if
# it is waiting for other task to finish. We should hide the
# error message.
ray.get(pg.ready())
print({streaming_message!r}, flush=True)
""")
]
job_id = self.job_id
if setup_cmd is not None:
setup_envs = env_vars.copy()
setup_envs[constants.SKYPILOT_NUM_NODES] = str(num_nodes)
self._code += [
textwrap.dedent(f"""\
setup_cmd = {setup_cmd!r}
_SETUP_CPUS = 0.0001
# The setup command will be run as a ray task with num_cpus=_SETUP_CPUS as the
# requirement; this means Ray will set CUDA_VISIBLE_DEVICES to an empty string.
# We unset it so that user setup command may properly use this env var.
setup_cmd = 'unset CUDA_VISIBLE_DEVICES; ' + setup_cmd
job_lib.set_status({job_id!r}, job_lib.JobStatus.SETTING_UP)
# The schedule_step should be called after the job status is set to non-PENDING,
# otherwise, the scheduler will think the current job is not submitted yet, and
# skip the scheduling step.
job_lib.scheduler.schedule_step()
total_num_nodes = len(ray.nodes())
setup_bundles = [{{"CPU": _SETUP_CPUS}} for _ in range(total_num_nodes)]
setup_pg = ray.util.placement_group(setup_bundles, strategy='STRICT_SPREAD')
setup_workers = [run_bash_command_with_log \\
.options(
name='setup',
num_cpus=_SETUP_CPUS,
scheduling_strategy=ray.util.scheduling_strategies.PlacementGroupSchedulingStrategy(
placement_group=setup_pg,
placement_group_bundle_index=i)
) \\
.remote(
setup_cmd,
os.path.expanduser({setup_log_path!r}),
env_vars={setup_envs!r},
stream_logs=True,
with_ray=True,
) for i in range(total_num_nodes)]
setup_returncodes = get_or_fail(setup_workers, setup_pg)
if sum(setup_returncodes) != 0:
job_lib.set_status({self.job_id!r}, job_lib.JobStatus.FAILED_SETUP)
# This waits for all streaming logs to finish.
time.sleep(1)
print('ERROR: {colorama.Fore.RED}Job {self.job_id}\\'s setup failed with '
'return code list:{colorama.Style.RESET_ALL}',
setup_returncodes,
flush=True)
# Need this to set the job status in ray job to be FAILED.
sys.exit(1)
""")
]
self._code.append(f'job_lib.set_job_started({self.job_id!r})')
if setup_cmd is None:
# Need to call schedule_step() to make sure the scheduler
# schedule the next pending job.
self._code.append('job_lib.scheduler.schedule_step()')
# Export IP and node rank to the environment variables.
self._code += [
textwrap.dedent(f"""\
@ray.remote
def check_ip():
return ray.util.get_node_ip_address()
gang_scheduling_id_to_ip = ray.get([
check_ip.options(
num_cpus={task_cpu_demand},
scheduling_strategy=ray.util.scheduling_strategies.PlacementGroupSchedulingStrategy(
placement_group=pg,
placement_group_bundle_index=i
)).remote()
for i in range(pg.bundle_count)
])
cluster_ips_to_node_id = {{ip: i for i, ip in enumerate({stable_cluster_internal_ips!r})}}
job_ip_rank_list = sorted(gang_scheduling_id_to_ip, key=cluster_ips_to_node_id.get)
job_ip_rank_map = {{ip: i for i, ip in enumerate(job_ip_rank_list)}}
job_ip_list_str = '\\n'.join(job_ip_rank_list)
"""),
]
def register_run_fn(self, run_fn: str, run_fn_name: str) -> None:
"""Register the run function to be run on the remote cluster.
Args:
run_fn: The run function to be run on the remote cluster.
"""
assert self._has_gang_scheduling, (
'Call add_gang_scheduling_placement_group_and_setup() '
'before register_run_fn().')
assert not self._has_register_run_fn, (
'register_run_fn() called twice?')
self._has_register_run_fn = True
self._code += [
run_fn,
f'run_fn = {run_fn_name}',
]
def add_ray_task(self,
bash_script: Optional[str],
task_name: Optional[str],
ray_resources_dict: Dict[str, float],
log_dir: str,
env_vars: Optional[Dict[str, str]] = None,
gang_scheduling_id: int = 0) -> None:
"""Generates code for a ray remote task that runs a bash command."""
assert self._has_gang_scheduling, (
'Call add_gang_scheduling_placement_group_and_setup() before '
'add_ray_task().')
assert (not self._has_register_run_fn or
bash_script is None), ('bash_script should '
'be None when run_fn is registered.')
task_cpu_demand = ray_resources_dict.pop('CPU')
# Build remote_task.options(...)
# resources=...
# num_gpus=...
options = []
options.append(f'num_cpus={task_cpu_demand}')
num_gpus = 0.0
if ray_resources_dict:
assert len(ray_resources_dict) == 1, (
'There can only be one type of accelerator per instance. '
f'Found: {ray_resources_dict}.')
num_gpus = list(ray_resources_dict.values())[0]
options.append(f'resources={json.dumps(ray_resources_dict)}')
resources_key = list(ray_resources_dict.keys())[0]
if not accelerator_registry.is_schedulable_non_gpu_accelerator(
resources_key):
# `num_gpus` should be empty when the accelerator is not GPU.
# FIXME: use a set of GPU types, instead of 'tpu' in the key.
# Passing this ensures that the Ray remote task gets
# CUDA_VISIBLE_DEVICES set correctly. If not passed, that flag
# would be force-set to empty by Ray.
options.append(f'num_gpus={num_gpus}')
options.append(
'scheduling_strategy=ray.util.scheduling_strategies.PlacementGroupSchedulingStrategy(' # pylint: disable=line-too-long
'placement_group=pg, '
f'placement_group_bundle_index={gang_scheduling_id})')
sky_env_vars_dict_str = [
textwrap.dedent(f"""\
sky_env_vars_dict = {{}}
sky_env_vars_dict['{constants.SKYPILOT_NODE_IPS}'] = job_ip_list_str
sky_env_vars_dict['{constants.SKYPILOT_NUM_NODES}'] = len(job_ip_rank_list)
""")
]
if env_vars is not None:
sky_env_vars_dict_str.extend(f'sky_env_vars_dict[{k!r}] = {v!r}'
for k, v in env_vars.items())
sky_env_vars_dict_str = '\n'.join(sky_env_vars_dict_str)
options_str = ', '.join(options)
logger.debug('Added Task with options: '
f'{options_str}')
# Script to block completion of a job until all storage mounted with
# CACHED_MOUNT mode is uploaded to remote.
rclone_flush_script = textwrap.dedent(f"""\
if [ $(findmnt -t fuse.rclone --noheading | wc -l) -gt 0 ]; then
flushed=0
# extra second on top of --vfs-cache-poll-interval to
# avoid race condition between rclone log line creation and this check.
sleep 1
while [ $flushed -eq 0 ]; do
# sleep for the same interval as --vfs-cache-poll-interval
sleep {constants.RCLONE_CACHE_REFRESH_INTERVAL}
flushed=1
for file in {constants.RCLONE_LOG_DIR}/*; do
exitcode=0
tac $file | grep "vfs cache: cleaned:" -m 1 | grep "in use 0, to upload 0, uploading 0" -q || exitcode=$?
if [ $exitcode -ne 0 ]; then
echo "skypilot: cached mount is still uploading to remote"
flushed=0
break
fi
done
done
echo "skypilot: cached mount uploaded complete"
fi""")
self._code += [
sky_env_vars_dict_str,
textwrap.dedent(f"""\
script = {bash_script!r}
rclone_flush_script = {rclone_flush_script!r}
if run_fn is not None:
script = run_fn({gang_scheduling_id}, gang_scheduling_id_to_ip)
if script is not None:
script += rclone_flush_script
sky_env_vars_dict['{constants.SKYPILOT_NUM_GPUS_PER_NODE}'] = {int(math.ceil(num_gpus))!r}
ip = gang_scheduling_id_to_ip[{gang_scheduling_id!r}]
rank = job_ip_rank_map[ip]
if len(cluster_ips_to_node_id) == 1: # Single-node task on single-node cluter
name_str = '{task_name},' if {task_name!r} != None else 'task,'
log_path = os.path.expanduser(os.path.join({log_dir!r}, 'run.log'))
else: # Single-node or multi-node task on multi-node cluster
idx_in_cluster = cluster_ips_to_node_id[ip]
if cluster_ips_to_node_id[ip] == 0:
node_name = 'head'
else:
node_name = f'worker{{idx_in_cluster}}'
name_str = f'{{node_name}}, rank={{rank}},'
log_path = os.path.expanduser(os.path.join({log_dir!r}, f'{{rank}}-{{node_name}}.log'))
sky_env_vars_dict['{constants.SKYPILOT_NODE_RANK}'] = rank
sky_env_vars_dict['SKYPILOT_INTERNAL_JOB_ID'] = {self.job_id}
futures.append(run_bash_command_with_log \\
.options(name=name_str, {options_str}) \\
.remote(
script,
log_path,
env_vars=sky_env_vars_dict,
stream_logs=True,
with_ray=True,
))""")
]
def add_epilogue(self) -> None:
"""Generates code that waits for all tasks, then exits."""
assert self._has_prologue, 'Call add_prologue() before add_epilogue().'
assert not self._has_epilogue, 'add_epilogue() called twice?'
self._has_epilogue = True
self._code += [
textwrap.dedent(f"""\
returncodes = get_or_fail(futures, pg)
if sum(returncodes) != 0:
job_lib.set_status({self.job_id!r}, job_lib.JobStatus.FAILED)
# Schedule the next pending job immediately to make the job
# scheduling more efficient.
job_lib.scheduler.schedule_step()
# This waits for all streaming logs to finish.
time.sleep(0.5)
reason = ''
# 139 is the return code of SIGSEGV, i.e. Segmentation Fault.
if any(r == 139 for r in returncodes):
reason = '(likely due to Segmentation Fault)'
print('ERROR: {colorama.Fore.RED}Job {self.job_id} failed with '
'return code list:{colorama.Style.RESET_ALL}',
returncodes,
reason,
flush=True)
# Need this to set the job status in ray job to be FAILED.
sys.exit(1)
else:
job_lib.set_status({self.job_id!r}, job_lib.JobStatus.SUCCEEDED)
# Schedule the next pending job immediately to make the job
# scheduling more efficient.
job_lib.scheduler.schedule_step()
# This waits for all streaming logs to finish.
time.sleep(0.5)
""")
]
def build(self) -> str:
"""Returns the entire generated program."""
assert self._has_epilogue, 'Call add_epilogue() before build().'
return '\n'.join(self._code)
class GangSchedulingStatus(enum.Enum):
"""Enum for gang scheduling status."""
CLUSTER_READY = 0
GANG_FAILED = 1
HEAD_FAILED = 2
def _add_to_blocked_resources(blocked_resources: Set['resources_lib.Resources'],
resources: 'resources_lib.Resources') -> None:
# If the resources is already blocked by blocked_resources, we don't need to
# add it again to avoid duplicated entries.
for r in blocked_resources:
if resources.should_be_blocked_by(r):
return
blocked_resources.add(resources)
class FailoverCloudErrorHandlerV1:
"""Handles errors during provisioning and updates the blocked_resources.
Deprecated: Newly added cloud should use the FailoverCloudErrorHandlerV2,
which is more robust by parsing the errors raised by the cloud's API in a
more structured way, instead of directly based on the stdout and stderr.
"""
@staticmethod
def _handle_errors(stdout: str, stderr: str,
is_error_str_known: Callable[[str], bool]) -> List[str]:
stdout_splits = stdout.split('\n')
stderr_splits = stderr.split('\n')
errors = [
s.strip()
for s in stdout_splits + stderr_splits
if is_error_str_known(s.strip())
]
if errors:
return errors
if 'rsync: command not found' in stderr:
with ux_utils.print_exception_no_traceback():
e = RuntimeError(_RSYNC_NOT_FOUND_MESSAGE)
setattr(e, 'detailed_reason',
f'stdout: {stdout}\nstderr: {stderr}')
raise e
detailed_reason = textwrap.dedent(f"""\
====== stdout ======
{stdout}
====== stderr ======
{stderr}
""")
logger.info('====== stdout ======')
print(stdout)
logger.info('====== stderr ======')
print(stderr)
with ux_utils.print_exception_no_traceback():
e = RuntimeError('Errors occurred during provision; '
'check logs above.')
setattr(e, 'detailed_reason', detailed_reason)
raise e
@staticmethod
def _scp_handler(blocked_resources: Set['resources_lib.Resources'],
launchable_resources: 'resources_lib.Resources',
region: 'clouds.Region',
zones: Optional[List['clouds.Zone']], stdout: str,
stderr: str):
del zones # Unused.
errors = FailoverCloudErrorHandlerV1._handle_errors(
stdout,
stderr,
is_error_str_known=lambda x: 'SCPError:' in x.strip())
logger.warning(f'Got error(s) in {region.name}:')
messages = '\n\t'.join(errors)
style = colorama.Style
logger.warning(f'{style.DIM}\t{messages}{style.RESET_ALL}')
_add_to_blocked_resources(blocked_resources,
launchable_resources.copy(zone=None))
# Sometimes, SCPError will list available regions.
for e in errors:
if e.find('Regions with capacity available:') != -1:
for r in service_catalog.regions('scp'):
if e.find(r.name) == -1:
_add_to_blocked_resources(
blocked_resources,
launchable_resources.copy(region=r.name, zone=None))
@staticmethod
def _ibm_handler(blocked_resources: Set['resources_lib.Resources'],
launchable_resources: 'resources_lib.Resources',
region: 'clouds.Region',
zones: Optional[List['clouds.Zone']], stdout: str,
stderr: str):
errors = FailoverCloudErrorHandlerV1._handle_errors(
stdout, stderr,
lambda x: 'ERR' in x.strip() or 'PANIC' in x.strip())
logger.warning(f'Got error(s) on IBM cluster, in {region.name}:')
messages = '\n\t'.join(errors)
style = colorama.Style
logger.warning(f'{style.DIM}\t{messages}{style.RESET_ALL}')
for zone in zones: # type: ignore[union-attr]
_add_to_blocked_resources(blocked_resources,
launchable_resources.copy(zone=zone.name))
@staticmethod
def update_blocklist_on_error(
blocked_resources: Set['resources_lib.Resources'],
launchable_resources: 'resources_lib.Resources',
region: 'clouds.Region', zones: Optional[List['clouds.Zone']],
stdout: Optional[str], stderr: Optional[str]) -> bool:
"""Handles cloud-specific errors and updates the block list.
This parses textual stdout/stderr because we don't directly use the
underlying clouds' SDKs. If we did that, we could catch proper
exceptions instead.
Returns:
definitely_no_nodes_launched: bool, True if definitely no nodes
launched (e.g., due to VPC errors we have never sent the provision
request), False otherwise.
"""
assert launchable_resources.region == region.name, (
launchable_resources, region)
if stdout is None:
# Gang scheduling failure (head node is definitely up, but some
# workers' provisioning failed). Simply block the zones.
assert stderr is None, stderr
if zones is not None:
for zone in zones:
_add_to_blocked_resources(
blocked_resources,
launchable_resources.copy(zone=zone.name))
return False # definitely_no_nodes_launched
assert stdout is not None and stderr is not None, (stdout, stderr)
# TODO(zongheng): refactor into Cloud interface?
cloud = launchable_resources.cloud
handler = getattr(FailoverCloudErrorHandlerV1,
f'_{str(cloud).lower()}_handler')
if handler is None:
raise NotImplementedError(
f'Cloud {cloud} unknown, or has not added '
'support for parsing and handling provision failures. '
'Please implement a handler in FailoverCloudErrorHandlerV1 when'
'ray-autoscaler-based provisioner is used for the cloud.')
handler(blocked_resources, launchable_resources, region, zones, stdout,
stderr)
stdout_splits = stdout.split('\n')
stderr_splits = stderr.split('\n')
# Determining whether head node launch *may* have been requested based
# on outputs is tricky. We are conservative here by choosing an "early
# enough" output line in the following:
# https://github.com/ray-project/ray/blob/03b6bc7b5a305877501110ec04710a9c57011479/python/ray/autoscaler/_private/commands.py#L704-L737 # pylint: disable=line-too-long
# This is okay, because we mainly want to use the return value of this
# func to skip cleaning up never-launched clusters that encountered VPC
# errors; their launch should not have printed any such outputs.
head_node_launch_may_have_been_requested = any(
'Acquiring an up-to-date head node' in line
for line in stdout_splits + stderr_splits)
# If head node request has definitely not been sent (this happens when
# there are errors during node provider "bootstrapping", e.g.,
# VPC-not-found errors), then definitely no nodes are launched.
definitely_no_nodes_launched = (
not head_node_launch_may_have_been_requested)
return definitely_no_nodes_launched
class FailoverCloudErrorHandlerV2:
"""Handles errors during provisioning and updates the blocked_resources.
This is a more robust version of FailoverCloudErrorHandlerV1. V2 parses
the errors raised by the cloud's API using the exception, instead of the
stdout and stderr.
"""
@staticmethod
def _azure_handler(blocked_resources: Set['resources_lib.Resources'],
launchable_resources: 'resources_lib.Resources',
region: 'clouds.Region', zones: List['clouds.Zone'],
err: Exception):
del region, zones # Unused.
if '(ReadOnlyDisabledSubscription)' in str(err):
logger.info(
f'{colorama.Style.DIM}Azure subscription is read-only. '
'Skip provisioning on Azure. Please check the subscription set '
'with az account set -s <subscription_id>.'
f'{colorama.Style.RESET_ALL}')
_add_to_blocked_resources(
blocked_resources,
resources_lib.Resources(cloud=clouds.Azure()))
elif 'ClientAuthenticationError' in str(err):
_add_to_blocked_resources(
blocked_resources,
resources_lib.Resources(cloud=clouds.Azure()))
else:
_add_to_blocked_resources(blocked_resources,
launchable_resources.copy(zone=None))
@staticmethod
def _gcp_handler(blocked_resources: Set['resources_lib.Resources'],
launchable_resources: 'resources_lib.Resources',
region: 'clouds.Region', zones: List['clouds.Zone'],
err: Exception):
assert zones and len(zones) == 1, zones
zone = zones[0]
if not isinstance(err, provision_common.ProvisionerError):
logger.warning(f'{colorama.Style.DIM}Got an unparsed error: {err}; '
f'blocking resources by its zone {zone.name}'
f'{colorama.Style.RESET_ALL}')
_add_to_blocked_resources(blocked_resources,
launchable_resources.copy(zone=zone.name))
return
errors = err.errors
for e in errors:
code = e['code']
message = e['message']
if code in ('QUOTA_EXCEEDED', 'quotaExceeded'):
if '\'GPUS_ALL_REGIONS\' exceeded' in message:
# Global quota. All regions in GCP will fail. Ex:
# Quota 'GPUS_ALL_REGIONS' exceeded. Limit: 1.0
# globally.
# This skip is only correct if we implement "first
# retry the region/zone of an existing cluster with the
# same name" correctly.
_add_to_blocked_resources(
blocked_resources,
launchable_resources.copy(region=None, zone=None))
else:
# Per region. Ex: Quota 'CPUS' exceeded. Limit: 24.0
# in region us-west1.
_add_to_blocked_resources(
blocked_resources, launchable_resources.copy(zone=None))
elif code in [
'ZONE_RESOURCE_POOL_EXHAUSTED',
'ZONE_RESOURCE_POOL_EXHAUSTED_WITH_DETAILS',
'UNSUPPORTED_OPERATION',
'insufficientCapacity',
]: # Per zone.
# Return codes can be found at https://cloud.google.com/compute/docs/troubleshooting/troubleshooting-vm-creation # pylint: disable=line-too-long
# However, UNSUPPORTED_OPERATION is observed empirically
# when VM is preempted during creation. This seems to be
# not documented by GCP.
_add_to_blocked_resources(
blocked_resources,
launchable_resources.copy(zone=zone.name))
elif code in ['RESOURCE_NOT_READY']:
# This code is returned when the VM is still STOPPING.
_add_to_blocked_resources(
blocked_resources,
launchable_resources.copy(zone=zone.name))
elif code in ['RESOURCE_OPERATION_RATE_EXCEEDED']:
# This code can happen when the VM is being created with a
# machine image, and the VM and the machine image are on
# different zones. We already have the retry when calling the
# insert API, but if it still fails, we should block the zone
# to avoid infinite retry.
_add_to_blocked_resources(
blocked_resources,
launchable_resources.copy(zone=zone.name))
elif code in [3, 8, 9]:
# Error code 3 means TPU is preempted during creation.
# Example:
# {'code': 3, 'message': 'Cloud TPU received a bad request. update is not supported while in state PREEMPTED [EID: 0x73013519f5b7feb2]'} # pylint: disable=line-too-long
# Error code 8 means TPU resources is out of
# capacity. Example:
# {'code': 8, 'message': 'There is no more capacity in the zone "europe-west4-a"; you can try in another zone where Cloud TPU Nodes are offered (see https://cloud.google.com/tpu/docs/regions) [EID: 0x1bc8f9d790be9142]'} # pylint: disable=line-too-long
# Error code 9 means TPU resources is insufficient reserved
# capacity. Example:
# {'code': 9, 'message': 'Insufficient reserved capacity. Contact customer support to increase your reservation. [EID: 0x2f8bc266e74261a]'} # pylint: disable=line-too-long
_add_to_blocked_resources(
blocked_resources,