-
Notifications
You must be signed in to change notification settings - Fork 541
/
cloud_vm_ray_backend.py
3670 lines (3340 loc) · 170 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 ast
import copy
import enum
import getpass
import inspect
import math
import json
import os
import pathlib
import re
import signal
import subprocess
import sys
import tempfile
import textwrap
import time
import typing
from typing import Dict, Iterable, List, Optional, Tuple, Union, Set
import colorama
import filelock
import sky
from sky import backends
from sky import clouds
from sky import cloud_stores
from sky import exceptions
from sky import global_user_state
from sky import resources as resources_lib
from sky import sky_logging
from sky import optimizer
from sky import skypilot_config
from sky import spot as spot_lib
from sky import task as task_lib
from sky.data import data_utils
from sky.data import storage as storage_lib
from sky.backends import backend_utils
from sky.backends import onprem_utils
from sky.backends import wheel_utils
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 common_utils
from sky.utils import command_runner
from sky.utils import log_utils
from sky.utils import subprocess_utils
from sky.utils import timeline
from sky.utils import tpu_utils
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 = 90
# 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 = 60
# The maximum retry count for fetching IP address.
_FETCH_IP_MAX_ATTEMPTS = 3
_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.'
f'{colorama.Style.RESET_ALL}')
_TPU_NOT_FOUND_ERROR = 'ERROR: (gcloud.compute.tpus.delete) NOT_FOUND'
_CTRL_C_TIP_MESSAGE = ('INFO: Tip: use Ctrl-C to exit log streaming '
'(task will not be killed).')
_MAX_RAY_UP_RETRY = 5
_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')
def _get_cluster_config_template(cloud):
cloud_to_template = {
clouds.AWS: 'aws-ray.yml.j2',
clouds.Azure: 'azure-ray.yml.j2',
clouds.GCP: 'gcp-ray.yml.j2',
clouds.Lambda: 'lambda-ray.yml.j2',
clouds.Local: 'local-ray.yml.j2',
}
return cloud_to_template[type(cloud)]
def write_ray_up_script_with_patched_launch_hash_fn(
cluster_config_path: 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') 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,
spot_task: Optional['task_lib.Task'] = None,
setup_cmd: Optional[str] = None,
envs: Optional[Dict[str, str]] = None,
setup_log_path: Optional[str] = None,
is_local: bool = False) -> 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, it will a bug of ray job failed to get the placement group
# in ray <= 2.0.1.
# TODO(mluo): Check why 'auto' not working with on-prem cluster and
# whether the placement group issue also occurs in on-prem cluster.
ray_address = 'ray://localhost:10001' if is_local else 'auto'
self._code = [
textwrap.dedent(f"""\
import getpass
import hashlib
import io
import os
import pathlib
import sys
import selectors
import subprocess
import tempfile
import textwrap
import time
from typing import Dict, List, Optional, Tuple, Union
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
SKY_REMOTE_WORKDIR = {constants.SKY_REMOTE_WORKDIR!r}
ray.init(address={ray_address!r}, namespace='__sky__{job_id}__', log_to_driver=True)
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.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)',
f'setup_cmd = {setup_cmd!r}',
]
# 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()
"""))
if setup_cmd is not None:
self._code += [
textwrap.dedent(f"""\
_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)
print({_CTRL_C_TIP_MESSAGE!r}, file=sys.stderr, flush=True)
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')
ray.get(setup_pg.ready())
setup_workers = [run_bash_command_with_log \\
.options(name='setup', num_cpus=_SETUP_CPUS, placement_group=setup_pg, placement_group_bundle_index=i) \\
.remote(
setup_cmd,
os.path.expanduser({setup_log_path!r}),
getpass.getuser(),
job_id={self.job_id},
env_vars={envs!r},
stream_logs=True,
with_ray=True,
use_sudo={is_local},
) for i in range(total_num_nodes)]
setup_returncodes = ray.get(setup_workers)
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,
file=sys.stderr,
flush=True)
# Need this to set the job status in ray job to be FAILED.
sys.exit(1)
""")
]
self._code += [
f'job_lib.set_status({job_id!r}, job_lib.JobStatus.PENDING)',
]
if spot_task is not None:
# Add the spot job to spot queue table.
resources_str = backend_utils.get_task_resources_str(spot_task)
self._code += [
'from sky.spot import spot_state',
f'spot_state.set_pending('
f'{job_id}, {spot_task.name!r}, {resources_str!r})',
]
def add_gang_scheduling_placement_group(
self,
num_nodes: int,
accelerator_dict: Optional[Dict[str, float]],
stable_cluster_internal_ips: List[str],
) -> 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().')
self._has_gang_scheduling = True
self._num_nodes = num_nodes
# Set CPU to avoid ray hanging the resources allocation
# for remote functions, since the task will request 1 CPU
# by default.
bundles = [{
'CPU': backend_utils.DEFAULT_TASK_CPU_DEMAND
} for _ in range(num_nodes)]
if accelerator_dict is not None:
acc_name = list(accelerator_dict.keys())[0]
acc_count = list(accelerator_dict.values())[0]
gpu_dict = {'GPU': acc_count}
# gpu_dict should be empty when the accelerator is not GPU.
# FIXME: This is a hack to make sure that we do not reserve
# GPU when requesting TPU.
if 'tpu' in acc_name.lower():
gpu_dict = {}
for bundle in bundles:
bundle.update({
**accelerator_dict,
# Set the GPU to avoid ray hanging the resources allocation
**gpu_dict,
})
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 = '' if setup_cmd is not None else {_CTRL_C_TIP_MESSAGE!r} + '\\n'
message += f'INFO: Waiting for task resources on {{node_str}}. This will block if the cluster is full.'
print(message,
file=sys.stderr,
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('INFO: All task resources reserved.',
file=sys.stderr,
flush=True)
job_lib.set_job_started({self.job_id!r})
""")
]
# 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={backend_utils.DEFAULT_TASK_CPU_DEMAND},
placement_group=pg,
placement_group_bundle_index=i).remote()
for i in range(pg.bundle_count)
])
print('INFO: Reserved IPs:', gang_scheduling_id_to_ip)
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() '
'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],
job_run_id: Optional[str],
ray_resources_dict: Optional[Dict[str, float]],
log_dir: str,
env_vars: Optional[Dict[str, str]] = None,
gang_scheduling_id: int = 0,
use_sudo: bool = False) -> None:
"""Generates code for a ray remote task that runs a bash command."""
assert self._has_gang_scheduling, (
'Call add_gang_scheduling_placement_group() 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.')
# Build remote_task.options(...)
# resources=...
# num_gpus=...
cpu_str = f', num_cpus={backend_utils.DEFAULT_TASK_CPU_DEMAND}'
resources_str = ''
num_gpus = 0.0
num_gpus_str = ''
if ray_resources_dict is not None:
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]
resources_str = f', resources={json.dumps(ray_resources_dict)}'
# 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.
num_gpus_str = f', num_gpus={num_gpus}'
# `num_gpus` should be empty when the accelerator is not GPU.
# FIXME: use a set of GPU types.
resources_key = list(ray_resources_dict.keys())[0]
if 'tpu' in resources_key.lower():
num_gpus_str = ''
resources_str += ', placement_group=pg'
resources_str += f', placement_group_bundle_index={gang_scheduling_id}'
sky_env_vars_dict_str = [
textwrap.dedent("""\
sky_env_vars_dict = {}
sky_env_vars_dict['SKYPILOT_NODE_IPS'] = job_ip_list_str
# Environment starting with `SKY_` is deprecated.
sky_env_vars_dict['SKY_NODE_IPS'] = job_ip_list_str
""")
]
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())
if job_run_id is not None:
sky_env_vars_dict_str += [
f'sky_env_vars_dict[{constants.JOB_ID_ENV_VAR!r}]'
f' = {job_run_id!r}'
]
sky_env_vars_dict_str = '\n'.join(sky_env_vars_dict_str)
logger.debug('Added Task with options: '
f'{cpu_str}{resources_str}{num_gpus_str}')
self._code += [
sky_env_vars_dict_str,
textwrap.dedent(f"""\
script = {bash_script!r}
if run_fn is not None:
script = run_fn({gang_scheduling_id}, gang_scheduling_id_to_ip)
if script is not None:
sky_env_vars_dict['SKYPILOT_NUM_GPUS_PER_NODE'] = {int(math.ceil(num_gpus))!r}
# Environment starting with `SKY_` is deprecated.
sky_env_vars_dict['SKY_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['SKYPILOT_NODE_RANK'] = rank
# Environment starting with `SKY_` is deprecated.
sky_env_vars_dict['SKY_NODE_RANK'] = rank
sky_env_vars_dict['SKYPILOT_INTERNAL_JOB_ID'] = {self.job_id}
# Environment starting with `SKY_` is deprecated.
sky_env_vars_dict['SKY_INTERNAL_JOB_ID'] = {self.job_id}
futures.append(run_bash_command_with_log \\
.options(name=name_str{cpu_str}{resources_str}{num_gpus_str}) \\
.remote(
script,
log_path,
getpass.getuser(),
job_id={self.job_id},
env_vars=sky_env_vars_dict,
stream_logs=True,
with_ray=True,
use_sudo={use_sudo},
))""")
]
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 = ray.get(futures)
if sum(returncodes) != 0:
job_lib.set_status({self.job_id!r}, job_lib.JobStatus.FAILED)
# This waits for all streaming logs to finish.
time.sleep(1)
print('ERROR: {colorama.Fore.RED}Job {self.job_id} failed with '
'return code list:{colorama.Style.RESET_ALL}',
returncodes,
file=sys.stderr,
flush=True)
# Need this to set the job status in ray job to be FAILED.
sys.exit(1)
else:
sys.stdout.flush()
sys.stderr.flush()
job_lib.set_status({self.job_id!r}, job_lib.JobStatus.SUCCEEDED)
# This waits for all streaming logs to finish.
time.sleep(1)
""")
]
def build(self) -> str:
"""Returns the entire generated program."""
assert self._has_epilogue, 'Call add_epilogue() before build().'
return '\n'.join(self._code)
class RetryingVmProvisioner(object):
"""A provisioner that retries different cloud/regions/zones."""
class ToProvisionConfig:
"""Resources to be provisioned."""
def __init__(
self, cluster_name: str, resources: resources_lib.Resources,
num_nodes: int,
prev_cluster_status: Optional[global_user_state.ClusterStatus]
) -> None:
assert cluster_name is not None, 'cluster_name must be specified.'
self.cluster_name = cluster_name
self.resources = resources
self.num_nodes = num_nodes
self.prev_cluster_status = prev_cluster_status
class GangSchedulingStatus(enum.Enum):
"""Enum for gang scheduling status."""
CLUSTER_READY = 0
GANG_FAILED = 1
HEAD_FAILED = 2
def __init__(self, log_dir: str, dag: 'dag.Dag',
optimize_target: 'optimizer.OptimizeTarget',
requested_features: Set[clouds.CloudImplementationFeatures],
local_wheel_path: pathlib.Path, wheel_hash: str):
self._blocked_resources: Set[resources_lib.Resources] = set()
self.log_dir = os.path.expanduser(log_dir)
self._dag = dag
self._optimize_target = optimize_target
self._requested_features = requested_features
self._local_wheel_path = local_wheel_path
self._wheel_hash = wheel_hash
def _update_blocklist_on_gcp_error(
self, launchable_resources: 'resources_lib.Resources',
region: 'clouds.Region', zones: Optional[List['clouds.Zone']],
stdout: str, stderr: str):
del region # unused
style = colorama.Style
assert zones and len(zones) == 1, zones
zone = zones[0]
splits = stderr.split('\n')
exception_list = [s for s in splits if s.startswith('Exception: ')]
httperror_str = [
s for s in splits
if s.startswith('googleapiclient.errors.HttpError: ')
]
if len(exception_list) == 1:
# Parse structured response {'errors': [...]}.
exception_str = exception_list[0][len('Exception: '):]
try:
exception_dict = ast.literal_eval(exception_str)
except Exception as e:
raise RuntimeError(
f'Failed to parse exception: {exception_str}') from e
# TPU VM returns a different structured response.
if 'errors' not in exception_dict:
exception_dict = {'errors': [exception_dict]}
for error in exception_dict['errors']:
code = error['code']
message = error['message']
logger.warning(f'Got return code {code} in {zone.name} '
f'{style.DIM}(message: {message})'
f'{style.RESET_ALL}')
if code == 'QUOTA_EXCEEDED':
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.
self._blocked_resources.add(
launchable_resources.copy(region=None, zone=None))
else:
# Per region. Ex: Quota 'CPUS' exceeded. Limit: 24.0
# in region us-west1.
self._blocked_resources.add(
launchable_resources.copy(zone=None))
elif code in [
'ZONE_RESOURCE_POOL_EXHAUSTED',
'ZONE_RESOURCE_POOL_EXHAUSTED_WITH_DETAILS',
'UNSUPPORTED_OPERATION'
]: # 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.
self._blocked_resources.add(
launchable_resources.copy(zone=zone.name))
elif code in ['RESOURCE_NOT_READY']:
# This code is returned when the VM is still STOPPING.
self._blocked_resources.add(
launchable_resources.copy(zone=zone.name))
elif code == 8:
# 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
self._blocked_resources.add(
launchable_resources.copy(zone=zone.name))
else:
assert False, error
elif len(httperror_str) >= 1:
logger.info(f'Got {httperror_str[0]}')
if ('Requested disk size cannot be smaller than the image size'
in httperror_str[0]):
logger.info('Skipping all regions due to disk size issue.')
self._blocked_resources.add(
launchable_resources.copy(region=None, zone=None))
else:
# Parse HttpError for unauthorized regions. Example:
# googleapiclient.errors.HttpError: <HttpError 403 when requesting ... returned "Location us-east1-d is not found or access is unauthorized.". # pylint: disable=line-too-long
# Details: "Location us-east1-d is not found or access is
# unauthorized.">
self._blocked_resources.add(
launchable_resources.copy(zone=zone.name))
else:
# No such structured error response found.
assert not exception_list, stderr
if 'was not found' in stderr:
# Example: The resource
# 'projects/<id>/zones/zone/acceleratorTypes/nvidia-tesla-v100'
# was not found.
logger.warning(f'Got \'resource not found\' in {zone.name}.')
self._blocked_resources.add(
launchable_resources.copy(zone=zone.name))
else:
logger.info('====== stdout ======')
for s in stdout.split('\n'):
print(s)
logger.info('====== stderr ======')
for s in splits:
print(s)
with ux_utils.print_exception_no_traceback():
raise RuntimeError('Errors occurred during provision; '
'check logs above.')
def _update_blocklist_on_aws_error(
self, launchable_resources: 'resources_lib.Resources',
region: 'clouds.Region', zones: Optional[List['clouds.Zone']],
stdout: str, stderr: str):
assert launchable_resources.is_launchable()
assert zones is not None, 'AWS should always have zones.'
style = colorama.Style
stdout_splits = stdout.split('\n')
stderr_splits = stderr.split('\n')
errors = [
s.strip()
for s in stdout_splits + stderr_splits
# 'An error occurred': boto3 errors
# 'SKYPILOT_ERROR_NO_NODES_LAUNCHED': skypilot's changes to the AWS
# node provider; for errors prior to provisioning like VPC
# setup.
if 'An error occurred' in s or
'SKYPILOT_ERROR_NO_NODES_LAUNCHED: ' in s
]
# Need to handle boto3 printing error but its retry succeeded:
# error occurred (Unsupported) .. not supported in your requested
# Availability Zone (us-west-2d)...retrying
# --> it automatically succeeded in another zone
# --> failed in [4/7] Running initialization commands due to user cmd
# In this case, we should error out.
head_node_up = any(
line.startswith('<1/1> Setting up head node')
for line in stdout_splits + stderr_splits)
if not errors or head_node_up:
# TODO: Got transient 'Failed to create security group' that goes
# away after a few minutes. Should we auto retry other regions, or
# let the user retry.
logger.info('====== stdout ======')
for s in stdout_splits:
print(s)
logger.info('====== stderr ======')
for s in stderr_splits:
print(s)
with ux_utils.print_exception_no_traceback():
raise RuntimeError('Errors occurred during provision; '
'check logs above.')
# Fill in the zones field in the Region.
region_with_zones_list = clouds.AWS.regions_with_offering(
launchable_resources.instance_type,
launchable_resources.accelerators,
launchable_resources.use_spot,
region.name,
zone=None)
assert len(region_with_zones_list) == 1, region_with_zones_list
region_with_zones = region_with_zones_list[0]
assert region_with_zones.zones is not None, region_with_zones
if set(zones) == set(region_with_zones.zones):
# The underlying AWS NodeProvider will try all specified zones of a
# region. (Each boto3 request takes one zone.)
logger.warning(f'Got error(s) in all zones of {region.name}:')
else:
zones_str = ', '.join(z.name for z in zones)
logger.warning(f'Got error(s) in {zones_str}:')
messages = '\n\t'.join(errors)
logger.warning(f'{style.DIM}\t{messages}{style.RESET_ALL}')
for zone in zones:
self._blocked_resources.add(
launchable_resources.copy(zone=zone.name))
def _update_blocklist_on_azure_error(
self, launchable_resources: 'resources_lib.Resources',
region: 'clouds.Region', zones: Optional[List['clouds.Zone']],
stdout: str, stderr: str):
del zones # Unused.
# The underlying ray autoscaler will try all zones of a region at once.
style = colorama.Style
stdout_splits = stdout.split('\n')
stderr_splits = stderr.split('\n')
errors = [
s.strip()
for s in stdout_splits + stderr_splits
if ('Exception Details:' in s.strip() or 'InvalidTemplateDeployment'
in s.strip() or '(ReadOnlyDisabledSubscription)' in s.strip())
]
if not errors:
logger.info('====== stdout ======')
for s in stdout_splits:
print(s)
logger.info('====== stderr ======')
for s in stderr_splits:
print(s)
with ux_utils.print_exception_no_traceback():
raise RuntimeError('Errors occurred during provision; '
'check logs above.')
logger.warning(f'Got error(s) in {region.name}:')
messages = '\n\t'.join(errors)
logger.warning(f'{style.DIM}\t{messages}{style.RESET_ALL}')
if any('(ReadOnlyDisabledSubscription)' in s for s in errors):
self._blocked_resources.add(
resources_lib.Resources(cloud=clouds.Azure()))
else:
self._blocked_resources.add(launchable_resources.copy(zone=None))
def _update_blocklist_on_lambda_error(
self, launchable_resources: 'resources_lib.Resources',
region: 'clouds.Region', zones: Optional[List['clouds.Zone']],
stdout: str, stderr: str):
del zones # Unused.
style = colorama.Style
stdout_splits = stdout.split('\n')
stderr_splits = stderr.split('\n')
errors = [
s.strip()
for s in stdout_splits + stderr_splits
if 'LambdaCloudError:' in s.strip()
]
if not errors:
logger.info('====== stdout ======')
for s in stdout_splits:
print(s)
logger.info('====== stderr ======')
for s in stderr_splits:
print(s)
with ux_utils.print_exception_no_traceback():
raise RuntimeError('Errors occurred during provision; '
'check logs above.')
logger.warning(f'Got error(s) in {region.name}:')
messages = '\n\t'.join(errors)
logger.warning(f'{style.DIM}\t{messages}{style.RESET_ALL}')
self._blocked_resources.add(launchable_resources.copy(zone=None))
# Sometimes, LambdaCloudError will list available regions.
for e in errors:
if e.find('Regions with capacity available:') != -1:
for r in clouds.Lambda.regions():
if e.find(r.name) == -1:
self._blocked_resources.add(
launchable_resources.copy(region=r.name, zone=None))
def _update_blocklist_on_local_error(
self, launchable_resources: 'resources_lib.Resources',
region: 'clouds.Region', zones: Optional[List['clouds.Zone']],
stdout: str, stderr: str):
del zones # Unused.
style = colorama.Style
stdout_splits = stdout.split('\n')
stderr_splits = stderr.split('\n')
errors = [
s.strip()
for s in stdout_splits + stderr_splits
if 'ERR' in s.strip() or 'PANIC' in s.strip()
]
if not errors:
logger.info('====== stdout ======')
for s in stdout_splits:
print(s)
logger.info('====== stderr ======')
for s in stderr_splits:
print(s)
with ux_utils.print_exception_no_traceback():
raise RuntimeError(
'Errors occurred during launching of cluster services; '
'check logs above.')
logger.warning('Got error(s) on local cluster:')
messages = '\n\t'.join(errors)
logger.warning(f'{style.DIM}\t{messages}{style.RESET_ALL}')
self._blocked_resources.add(
launchable_resources.copy(region=region.name, zone=None))
def _update_blocklist_on_error(
self, 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:
self._blocked_resources.add(
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?
handlers = {
clouds.AWS: self._update_blocklist_on_aws_error,
clouds.Azure: self._update_blocklist_on_azure_error,
clouds.GCP: self._update_blocklist_on_gcp_error,
clouds.Lambda: self._update_blocklist_on_lambda_error,
clouds.Local: self._update_blocklist_on_local_error,
}
cloud = launchable_resources.cloud
cloud_type = type(cloud)
if cloud_type not in handlers:
raise NotImplementedError(
f'Cloud {cloud} unknown, or has not added '
'support for parsing and handling provision failures.')
handler = handlers[cloud_type]
handler(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
def _yield_zones(
self, to_provision: resources_lib.Resources, num_nodes: int,
cluster_name: str,
prev_cluster_status: Optional[global_user_state.ClusterStatus]
) -> Iterable[Optional[List[clouds.Zone]]]:
"""Yield zones within the given region to try for provisioning.
Yields:
Zones to try for provisioning within the given to_provision.region.
- None means the cloud does not support zones, but the region does
offer the requested resources (so the outer loop should issue a
request to that region).
- Non-empty list means the cloud supports zones, and the zones
do offer the requested resources. If a list is yielded, it is
guaranteed to be non-empty.
- Nothing yielded means the region does not offer the requested
resources.
"""
assert (to_provision.cloud is not None and
to_provision.region is not None and to_provision.instance_type
is not None), (to_provision,
'cloud, region and instance_type must have been '
'set by optimizer')
cloud = to_provision.cloud
region = clouds.Region(to_provision.region)
zones = None
def _get_previously_launched_zones() -> Optional[List[clouds.Zone]]:
# When the cluster exists, the to_provision should have been set
# to the previous cluster's resources.
zones = [clouds.Zone(name=to_provision.zone)
] if to_provision.zone is not None else None
if zones is None:
# Reuse the zone field in the ray yaml as the
# prev_resources.zone field may not be set before the previous
# cluster is launched.
handle = global_user_state.get_handle_from_cluster_name(
cluster_name)
assert handle is not None, (
f'handle should not be None {cluster_name!r}')
config = common_utils.read_yaml(handle.cluster_yaml)
# This is for the case when the zone field is not set in the
# launched resources in a previous launch (e.g., ctrl-c during
# launch and multi-node cluster before PR #1700).
zones_str = config.get('provider', {}).get('availability_zone')
if zones_str is not None:
zones = [
clouds.Zone(name=zone) for zone in zones_str.split(',')
]
return zones
if prev_cluster_status is not None:
# If the cluster is previously launched, we should relaunch in the
# same region and zone.
zones = _get_previously_launched_zones()
if prev_cluster_status != global_user_state.ClusterStatus.UP:
logger.info(
f'Cluster {cluster_name!r} (status: '
f'{prev_cluster_status.value}) was previously launched '
f'in {cloud} {region.name}. Relaunching in that region.')
# TODO(zhwu): The cluster being killed by cloud provider should
# be tested whether re-launching a cluster killed spot instance
# will recover the data.
yield zones
# TODO(zhwu): update the following logics, since we have added
# the support for refreshing the cluster status from the cloud
# provider.
# If it reaches here: the cluster status in the database gets
# set to INIT, since a launch request was issued but failed.
#
# Cluster with status UP can reach here, if it was killed by the
# cloud provider and no available resources in that region to
# relaunch, which can happen to spot instance.
if prev_cluster_status == global_user_state.ClusterStatus.UP: