-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathcontroller.py
More file actions
2541 lines (2262 loc) · 116 KB
/
Copy pathcontroller.py
File metadata and controls
2541 lines (2262 loc) · 116 KB
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
"""Controller: handles scheduling and the life cycle of a managed job.
"""
import asyncio
import io
import json
import os
import pathlib
import resource
import shutil
import sys
import threading
import time
import traceback
import typing
from typing import Any, Dict, List, Optional, Set, Tuple
import dotenv
import filelock
import sky
from sky import core
from sky import exceptions
from sky import global_user_state
from sky import sky_logging
from sky import skypilot_config
from sky.adaptors import common as adaptors_common
from sky.backends import backend_utils
from sky.backends import cloud_vm_ray_backend
from sky.batch import coordinator as batch_coordinator
from sky.data import data_utils
from sky.jobs import constants as jobs_constants
from sky.jobs import file_content_utils
from sky.jobs import job_group_networking
from sky.jobs import log_gc
from sky.jobs import recovery_strategy
from sky.jobs import runtime as managed_job_runtime
from sky.jobs import scheduler
from sky.jobs import state as managed_job_state
from sky.jobs import utils as managed_job_utils
from sky.metrics import utils as metrics_lib
from sky.server import plugins
from sky.skylet import constants
from sky.skylet import job_lib
from sky.usage import usage_lib
from sky.utils import annotations
from sky.utils import common
from sky.utils import common_utils
from sky.utils import context
from sky.utils import context_utils
from sky.utils import controller_utils
from sky.utils import dag_utils
from sky.utils import status_lib
from sky.utils import ux_utils
from sky.utils.plugin_extensions import ExternalClusterFailure
from sky.utils.plugin_extensions import ExternalFailureSource
if typing.TYPE_CHECKING:
import psutil
from sky import task as task_lib
from sky.schemas.generated import jobsv1_pb2
else:
psutil = adaptors_common.LazyImport('psutil')
jobsv1_pb2 = adaptors_common.LazyImport('sky.schemas.generated.jobsv1_pb2')
logger = sky_logging.init_logger('sky.jobs.controller')
_background_tasks: Set[asyncio.Task] = set()
_background_tasks_lock: asyncio.Lock = asyncio.Lock()
async def create_background_task(coro: typing.Coroutine) -> None:
"""Create a background task and add it to the set of background tasks.
Main reason we do this is since tasks are only held as a weak reference in
the executor, we need to keep a strong reference to the task to avoid it
being garbage collected.
Args:
coro: The coroutine to create a task for.
"""
async with _background_tasks_lock:
task = asyncio.create_task(coro)
_background_tasks.add(task)
# TODO(cooperc): Discard needs a lock?
task.add_done_callback(_background_tasks.discard)
# Make sure to limit the size as we don't want to cache too many DAGs in memory.
@annotations.lru_cache(scope='global', maxsize=50)
def _get_dag(job_id: int) -> 'sky.Dag':
dag_content = file_content_utils.get_job_dag_content(job_id)
if dag_content is None:
raise RuntimeError('Managed job DAG YAML content is unavailable for '
f'job {job_id}. This can happen if the job was '
'submitted before file migration completed or if '
'the submission failed to persist the DAG. Please '
're-submit the job.')
# Auto-detect YAML type (JobGroup or chain DAG) and parse accordingly
dag = dag_utils.load_dag_from_yaml_str(dag_content)
assert dag.name is not None, dag
return dag
def _add_k8s_annotations(task: 'sky.Task', job_id: int) -> None:
"""Adds Kubernetes pod config annotations to the task resources.
This function is a NOP for non-Kubernetes resources, as
the kubernetes specific config is not used when launching
a cluster on other clouds.
"""
original_resources = task.resources
new_resources_list: List['sky.Resources'] = []
for original_resource in original_resources:
# Get existing config overrides or create new dict
config_overrides = original_resource.cluster_config_overrides.copy()
# Initialize nested structure and add annotations
pod_annotations = config_overrides.setdefault(
'kubernetes',
{}).setdefault('pod_config',
{}).setdefault('metadata',
{}).setdefault('annotations', {})
pod_annotations['skypilot-managed-job-id'] = str(job_id)
pod_annotations['skypilot-managed-job-name'] = str(task.name)
# Create new resource with updated config
new_resource = original_resource.copy(
_cluster_config_overrides=config_overrides)
new_resources_list.append(new_resource)
# Set the new resources back to the task
task.set_resources(new_resources_list)
def _build_task_specs(
executor: 'recovery_strategy.StrategyExecutor',) -> Dict[str, Any]:
"""Merge base and strategy-specific task specs with collision detection."""
base_specs: Dict[str, Any] = {
'max_restarts_on_errors': executor.max_restarts_on_errors,
'recover_on_exit_codes': executor.recover_on_exit_codes,
}
strategy_specs = executor.task_specs()
overlap = set(base_specs) & set(strategy_specs)
if overlap:
raise ValueError(f'Strategy task_specs() conflicts with base spec '
f'keys: {overlap}')
base_specs.update(strategy_specs)
return base_specs
class JobController:
"""Controls the lifecycle of a single managed job.
This controller executes the chain DAG recorded for the job by:
- Loading the DAG and preparing per-task environment variables so each task
has a stable global job identifier across recoveries.
- Launching the task on the configured backend (``CloudVmRayBackend``),
optionally via a pool.
- Persisting state transitions to the managed jobs state store
(e.g., STARTING → RUNNING → SUCCEEDED/FAILED/CANCELLED).
- Monitoring execution, downloading/streaming logs, detecting failures or
preemptions, and invoking recovery through
``recovery_strategy.StrategyExecutor``.
- Cleaning up clusters and ephemeral resources when tasks finish.
Concurrency and coordination:
- Runs inside an ``asyncio`` event loop.
- Shares a ``starting`` set, guarded by ``starting_lock`` and signaled via
``starting_signal``, to throttle concurrent launches across jobs that the
top-level ``Controller`` manages.
Key attributes:
- ``_job_id``: Integer identifier of this managed job.
- ``_dag`` / ``_dag_name``: The job definition and metadata loaded from the
database-backed job YAML.
- ``_backend``: Backend used to launch and manage clusters.
- ``_pool``: Optional pool name if using a pool.
- ``starting`` / ``starting_lock`` / ``starting_signal``: Shared scheduler
coordination primitives. ``starting_lock`` must be used for accessing
``starting_signal`` and ``starting``
- ``_strategy_executor``: Recovery/launch strategy executor (created per
task).
"""
def __init__(
self,
job_id: int,
starting: Set[int],
starting_lock: asyncio.Lock,
starting_signal: asyncio.Condition,
pool: Optional[str] = None,
rank: Optional[int] = None,
) -> None:
"""Initialize a ``JobsController``.
Args:
job_id: Integer ID of the managed job.
starting: Shared set of job IDs currently in the STARTING phase,
used to limit concurrent launches.
starting_lock: ``asyncio.Lock`` guarding access to the shared
scheduler state (e.g., the ``starting`` set).
starting_signal: ``asyncio.Condition`` used to notify when a job
exits STARTING so more jobs can be admitted.
pool: Optional pool name. When provided, the job is
submitted to the pool rather than launching a dedicated
cluster.
rank: Optional rank of the job that can be used to partition
workloads.
"""
self.starting = starting
self.starting_lock = starting_lock
self.starting_signal = starting_signal
logger.info('Initializing JobsController for job_id=%s', job_id)
self._job_id = job_id
self._dag = _get_dag(job_id)
self._dag_name = self._dag.name
logger.info(f'Loaded DAG: {self._dag}')
self._backend = cloud_vm_ray_backend.CloudVmRayBackend()
self._pool = pool
self._rank = rank
logger.info(f'Rank for job {self._job_id}: {self._rank}')
# pylint: disable=line-too-long
# Add a unique identifier to the task environment variables, so that
# the user can have the same id for multiple recoveries.
# Example value: sky-2022-10-04-22-46-52-467694_my-spot-name_spot_id-17-0
job_id_env_vars = []
for i, task in enumerate(self._dag.tasks):
if len(self._dag.tasks) <= 1:
task_name = self._dag_name
else:
assert task.name is not None, task
task_name = task.name
# This is guaranteed by the jobs.launch API, where we fill in
# the task.name with
# dag_utils.maybe_infer_and_fill_dag_and_task_names.
assert task_name is not None, self._dag
task_name = f'{self._dag_name}_{task_name}'
job_id_env_var = common_utils.get_global_job_id(
self._backend.run_timestamp,
f'{task_name}',
str(self._job_id),
task_id=i,
is_managed_job=True)
job_id_env_vars.append(job_id_env_var)
for i, task in enumerate(self._dag.tasks):
task_envs = task.envs or {}
task_envs[constants.TASK_ID_ENV_VAR] = job_id_env_vars[i]
task_envs[constants.TASK_ID_LIST_ENV_VAR] = '\n'.join(
job_id_env_vars)
task_envs[constants.MANAGED_JOB_ID_ENV_VAR] = str(self._job_id)
# Add SKYPILOT_JOB_RANK if it's set in the context or os.environ
# (os.environ may be hijacked to use ContextualEnviron which includes context overrides)
if self._rank is not None:
task_envs['SKYPILOT_JOB_RANK'] = str(self._rank)
else:
task_envs['SKYPILOT_JOB_RANK'] = '0'
task.update_envs(task_envs)
def download_log_and_stream(
self,
task_id: Optional[int],
handle: Optional['cloud_vm_ray_backend.CloudVmRayResourceHandle'],
job_id_on_pool_cluster: Optional[int],
) -> None:
"""Downloads and streams the logs of the current job with given task ID.
We do not stream the logs from the cluster directly, as the
download and stream should be faster, and more robust against
preemptions or ssh disconnection during the streaming.
"""
if handle is None:
logger.info(f'Cluster for job {self._job_id} is not found. '
'Skipping downloading and streaming the logs.')
return
managed_job_logs_dir = os.path.join(constants.SKY_LOGS_DIRECTORY,
'managed_jobs',
f'job-id-{self._job_id}')
def _persist_local_log_file(local_log_file: str) -> None:
# Persist the log path for the current task so it can be accessed
# after the job finishes. Do this as early as possible -- right
# after the log is synced down, before the (potentially minutes-
# long for multi-GB logs) re-stream into the controller log --
# so the dashboard can serve the job's logs immediately instead
# of showing "already in terminal state" until the re-stream
# completes.
managed_job_state.set_local_log_file(self._job_id, task_id,
local_log_file)
log_file = None
if managed_job_runtime.is_registered():
log_file = managed_job_runtime.download_logs(
handle, self._job_id, task_id)
if log_file is not None:
_persist_local_log_file(log_file)
if log_file is None:
log_file = controller_utils.download_and_stream_job_log(
self._backend,
handle,
managed_job_logs_dir,
job_ids=[str(job_id_on_pool_cluster)]
if job_id_on_pool_cluster is not None else None,
on_downloaded=_persist_local_log_file)
if log_file is None:
logger.warning(
f'No log file was downloaded for job {self._job_id}, '
f'task {task_id}')
logger.info(f'\n== End of logs (ID: {self._job_id}) ==')
async def _cleanup_cluster(self, cluster_name: Optional[str]) -> None:
if cluster_name is None:
return
if self._pool is None:
await asyncio.to_thread(managed_job_utils.terminate_cluster,
cluster_name)
async def _get_cluster_job_exit_codes(
self, job_id: Optional[int],
handle: 'cloud_vm_ray_backend.CloudVmRayResourceHandle'
) -> Optional[list]:
"""Retrieve exit codes from the remote cluster.
Args:
job_id: The job ID on the remote cluster.
handle: The handle to the cluster.
Returns:
List of exit codes, or None if not available.
"""
if managed_job_runtime.is_registered():
exit_codes = managed_job_runtime.get_exit_codes(handle)
if exit_codes is not None:
return exit_codes
try:
# Try gRPC first if enabled
if handle.is_grpc_enabled_with_flag:
try:
request = jobsv1_pb2.GetJobExitCodesRequest()
if job_id is not None:
request.job_id = job_id
response = await asyncio.to_thread(
backend_utils.invoke_skylet_with_retries,
lambda: cloud_vm_ray_backend.SkyletClient(
handle.get_grpc_channel()).get_job_exit_codes(
request))
return list(
response.exit_codes) if response.exit_codes else None
except exceptions.SkyletMethodNotImplementedError:
pass # Fall back to legacy SSH-based method
# Legacy SSH-based method
code = job_lib.JobLibCodeGen.get_job_exit_codes(job_id)
returncode, stdout, stderr = await asyncio.to_thread(
self._backend.run_on_head,
handle,
code,
stream_logs=False,
require_outputs=True,
separate_stderr=True)
if returncode != 0:
logger.debug(f'Failed to retrieve exit codes: {stderr}')
return None
return json.loads(stdout.strip())
except Exception as e: # pylint: disable=broad-except
logger.debug(f'Failed to retrieve job exit codes: {e}')
return None
async def _run_one_task(self, task_id: int, task: 'sky.Task') -> bool:
"""Busy loop monitoring cluster status and handling recovery.
When the task is successfully completed, this function returns True,
and will terminate the cluster before returning.
If the user program fails, i.e. the task is set to FAILED or
FAILED_SETUP, this function will return False.
In other cases, the function will raise exceptions.
All the failure cases will rely on the caller to clean up the spot
cluster(s) and storages.
Returns:
True if the job is successfully completed; False otherwise.
Raises:
exceptions.ProvisionPrechecksError: This will be raised when the
underlying `sky.launch` fails due to precheck errors only.
I.e., none of the failover exceptions, if
any, is due to resources unavailability. This exception
includes the following cases:
1. The optimizer cannot find a feasible solution.
2. Precheck errors: invalid cluster name, failure in getting
cloud user identity, or unsupported feature.
exceptions.ManagedJobReachedMaxRetriesError: This will be raised
when all prechecks passed but the maximum number of retries is
reached for `sky.launch`. The failure of `sky.launch` can be
due to:
1. Any of the underlying failover exceptions is due to resources
unavailability.
2. The cluster is preempted or failed before the job is
submitted.
3. Any unexpected error happens during the `sky.launch`.
Other exceptions may be raised depending on the backend.
"""
_add_k8s_annotations(task, self._job_id)
logger.info(
f'Starting task {task_id} ({task.name}) for job {self._job_id}')
latest_task_id, last_task_prev_status = (
await
managed_job_state.get_latest_task_id_status_async(self._job_id))
is_resume = False
if (latest_task_id is not None and last_task_prev_status !=
managed_job_state.ManagedJobStatus.PENDING):
assert latest_task_id >= task_id, (latest_task_id, task_id)
if latest_task_id > task_id:
logger.info(f'Task {task_id} ({task.name}) has already '
'been executed. Skipping...')
return True
if latest_task_id == task_id:
# Start recovery.
is_resume = True
logger.info(f'Resuming task {task_id} from previous execution')
callback_func = managed_job_utils.event_callback_func(
job_id=self._job_id, task_id=task_id, task=task)
if task.metadata.get('batch_coordinator'):
return await self._run_batch_coordinator_task(task_id,
task,
callback_func,
is_resume=is_resume)
if task.run is None:
logger.info(f'Skip running task {task_id} ({task.name}) due to its '
'run commands being empty.')
# Note: `submitted_at` is recorded once when the task row is first
# inserted at PENDING (see `set_pending`), so this no-op task --
# which short-circuits straight to RUNNING/SUCCEEDED without going
# through STARTING -- still has a real submission time.
# Call set_started first to initialize columns in the state table,
# including start_at and last_recovery_at to avoid issues for
# uninitialized columns.
await managed_job_state.set_started_async(
job_id=self._job_id,
task_id=task_id,
start_time=time.time(),
callback_func=callback_func)
await managed_job_state.set_succeeded_async(
job_id=self._job_id,
task_id=task_id,
end_time=time.time(),
callback_func=callback_func)
logger.info(f'Empty task {task_id} marked as succeeded immediately')
return True
usage_lib.messages.usage.update_task_id(task_id)
task_id_env_var = task.envs[constants.TASK_ID_ENV_VAR]
assert task.name is not None, task
# Set the cluster name to None if the job is submitted
# to a pool. This will be updated when we later calls the `launch`
# or `recover` function from the strategy executor.
cluster_name = managed_job_utils.generate_managed_job_cluster_name(
task.name, self._job_id) if self._pool is None else None
self._strategy_executor = recovery_strategy.StrategyExecutor.make(
cluster_name,
self._backend,
task,
self._job_id,
task_id,
self._pool,
self.starting,
self.starting_lock,
self.starting_signal,
file_mounts_blob_id=managed_job_state.get_file_mounts_blob_id(
self._job_id))
if not is_resume:
submitted_at = time.time()
if task_id == 0:
submitted_at = backend_utils.get_timestamp_from_run_timestamp(
self._backend.run_timestamp)
resources_str = backend_utils.get_task_resources_str(
task, is_managed_job=True)
# Get full_resources_json using get_resource_config which handles
# heterogeneous resource configurations (any_of/ordered).
full_resources_json = None
if task.resources:
full_resources_json = task.get_resource_config()
await managed_job_state.set_starting_async(
self._job_id,
task_id,
self._backend.run_timestamp,
submitted_at,
resources_str=resources_str,
specs=_build_task_specs(self._strategy_executor),
callback_func=callback_func,
full_resources_json=full_resources_json)
logger.info(f'Submitted managed job {self._job_id} '
f'(task: {task_id}, name: {task.name!r}); '
f'{constants.TASK_ID_ENV_VAR}: {task_id_env_var}')
logger.info('Started monitoring.')
# Only do the initial cluster launch if not resuming from a controller
# failure. Otherwise, we will transit to recovering immediately.
remote_job_submitted_at = time.time()
if not is_resume:
launch_start = time.time()
# Run the launch in a separate thread to avoid blocking the event
# loop. The scheduler functions used internally already have their
# own file locks.
remote_job_submitted_at = await self._strategy_executor.launch()
launch_time = time.time() - launch_start
logger.info(f'Cluster launch completed in {launch_time:.2f}s')
assert remote_job_submitted_at is not None, remote_job_submitted_at
job_id_on_pool_cluster: Optional[int] = None
if self._pool:
# Update the cluster name when using pool.
cluster_name, job_id_on_pool_cluster = (
await
managed_job_state.get_pool_submit_info_async(self._job_id))
if cluster_name is None:
# Check if we have been cancelled here, in the case where a user
# quickly cancels the job we want to gracefully handle it here,
# otherwise we will end up in the FAILED_CONTROLLER state.
logger.info(f'Cluster name is None for job {self._job_id}, '
f'task {task_id}. Checking if we have been '
'cancelled.')
status = await (managed_job_state.get_job_status_with_task_id_async(
job_id=self._job_id, task_id=task_id))
logger.debug(f'Status for job {self._job_id}, task {task_id}:'
f'{status}')
if status == managed_job_state.ManagedJobStatus.CANCELLED:
logger.info(f'Job {self._job_id}, task {task_id} has '
'been quickly cancelled.')
raise asyncio.CancelledError()
assert cluster_name is not None, (cluster_name, job_id_on_pool_cluster)
if not is_resume:
await managed_job_state.set_started_async(
job_id=self._job_id,
task_id=task_id,
start_time=remote_job_submitted_at,
callback_func=callback_func)
async with self.starting_lock:
try:
self.starting.remove(self._job_id)
# its fine if we notify again, better to wake someone up
# and have them go to sleep again, then have some stuck
# sleeping.
# ps. this shouldn't actually happen because if its been
# removed from the set then we would get a key error.
self.starting_signal.notify()
except KeyError:
pass
# NOTE: if we are resuming from a controller failure, we only keep
# monitoring if the job is in RUNNING state. For all other cases,
# we will directly transit to recovering since we have no idea what
# the cluster status is.
# Handle resume logic before starting the monitoring loop.
# If resuming from a controller failure, check the previous state
# and determine if we need to force recovery.
force_transit_to_recovering = False
if is_resume:
prev_status = await (
managed_job_state.get_job_status_with_task_id_async(
job_id=self._job_id, task_id=task_id))
if prev_status is not None:
if prev_status.is_terminal():
logger.info(f'Task {task_id} already in terminal state: '
f'{prev_status}')
return (prev_status ==
managed_job_state.ManagedJobStatus.SUCCEEDED)
if prev_status == managed_job_state.ManagedJobStatus.CANCELLING:
# If the controller is down when cancelling the job,
# we re-raise the error to run the `_cleanup` function
# again to clean up any remaining resources.
logger.info(f'Task {task_id} was being cancelled, '
're-raising cancellation')
raise asyncio.CancelledError()
if prev_status != managed_job_state.ManagedJobStatus.RUNNING:
force_transit_to_recovering = True
await self._strategy_executor.on_resume(cluster_name)
logger.info('Started monitoring.')
# TODO(kevin): If StrategyExecutor grew pluggable detection methods
# (check_status, get_recovery_targets), this two-path dispatch could
# become a single generic monitor loop on the controller. See the
# TODO on StrategyExecutor.monitor_task().
result = await self._strategy_executor.monitor_task(
task_id=task_id,
task=task,
cluster_name=cluster_name,
job_id_on_pool_cluster=job_id_on_pool_cluster,
callback_func=callback_func,
cleanup_cluster_on_success=True,
force_transit_to_recovering=force_transit_to_recovering,
)
if result is not None:
return result
return await self._monitor_one_task(
task_id=task_id,
task=task,
cluster_name=cluster_name,
executor=self._strategy_executor,
job_id_on_pool_cluster=job_id_on_pool_cluster,
callback_func=callback_func,
cleanup_cluster_on_success=True,
force_transit_to_recovering=force_transit_to_recovering,
)
async def _run_batch_coordinator_task(
self,
task_id: int,
task: 'sky.Task',
callback_func: typing.Callable,
is_resume: bool = False,
) -> bool:
"""Run the BatchCoordinator inline on the controller.
The coordinator is lightweight orchestration (count items, split
batches, dispatch via ``sdk.exec()``). Running it here avoids
provisioning a separate CPU cluster.
When ``is_resume=True``, the coordinator reloads persisted batch
state from the DB and resumes dispatch from where it left off.
"""
if is_resume:
# Check if the previous run already reached a terminal status.
_, prev_status = (await
managed_job_state.get_latest_task_id_status_async(
self._job_id))
if (prev_status is not None and prev_status.is_terminal()):
logger.info(f'Batch task {task_id} already in terminal status '
f'{prev_status.value}, skipping.')
return prev_status == (
managed_job_state.ManagedJobStatus.SUCCEEDED)
if prev_status == managed_job_state.ManagedJobStatus.CANCELLING:
raise asyncio.CancelledError(
'Batch coordinator resuming into CANCELLING state')
metadata = task.metadata
coordinator = batch_coordinator.BatchCoordinator(
dataset_path=metadata['batch_dataset_path'],
output_path=metadata['batch_output_path'],
batch_size=metadata['batch_size'],
pool_name=metadata['batch_pool_name'],
serialized_fn=metadata['batch_serialized_fn'],
activate_env=metadata.get('batch_activate_env', ''),
job_id=self._job_id,
is_resume=is_resume,
input_format_dict=metadata['batch_input_format'],
output_formats_dict=metadata['batch_output_formats'],
)
if not is_resume:
submitted_at = backend_utils.get_timestamp_from_run_timestamp(
self._backend.run_timestamp) if task_id == 0 else time.time()
await managed_job_state.set_starting_async(
self._job_id,
task_id,
self._backend.run_timestamp,
submitted_at,
resources_str='-',
specs={
'max_restarts_on_errors': 0,
'recover_on_exit_codes': []
},
callback_func=callback_func)
await managed_job_state.set_started_async(
job_id=self._job_id,
task_id=task_id,
start_time=time.time(),
callback_func=callback_func)
try:
await asyncio.to_thread(coordinator.run)
await managed_job_state.set_succeeded_async(
job_id=self._job_id,
task_id=task_id,
end_time=time.time(),
callback_func=callback_func)
return True
except asyncio.CancelledError:
coordinator.cancel()
raise
except Exception as e: # pylint: disable=broad-except
logger.error(f'Batch coordinator failed: {e}', exc_info=True)
await managed_job_state.set_failed_async(
job_id=self._job_id,
task_id=task_id,
failure_type=managed_job_state.ManagedJobStatus.FAILED,
failure_reason=str(e),
callback_func=callback_func)
return False
async def _monitor_one_task(
self,
task_id: int,
task: 'sky.Task',
cluster_name: str,
executor: 'recovery_strategy.StrategyExecutor',
job_id_on_pool_cluster: Optional[int] = None,
callback_func: Optional[typing.Callable] = None,
cleanup_cluster_on_success: bool = True,
force_transit_to_recovering: bool = False,
on_recovery: Optional[typing.Callable[[], typing.Coroutine]] = None,
) -> bool:
"""Monitor a single task until completion with recovery support.
This is the core monitoring loop shared by both single-task execution
and JobGroup parallel execution. It handles:
- Periodic job status checks with transient error handling
- Success/failure detection with exit code-based restart logic
- External failure detection
- Preemption detection and recovery
Args:
task_id: Task ID.
task: The task to monitor.
cluster_name: Name of the cluster running the task.
executor: Recovery strategy executor for handling preemptions.
job_id_on_pool_cluster: Job ID on the cluster (for pools).
callback_func: Callback function for state updates.
cleanup_cluster_on_success: Whether to clean up cluster on success.
force_transit_to_recovering: If True, force recovery on first
iteration (used when resuming from controller failure).
on_recovery: Optional async callback called after recovery.
Used by JobGroups to re-setup networking.
Returns:
True if the task succeeded, False otherwise.
"""
if callback_func is None:
callback_func = managed_job_utils.event_callback_func(
job_id=self._job_id, task_id=task_id, task=task)
transient_job_check_error_start_time = None
job_check_backoff = None
while True:
# Get job status (skip on first iteration if forcing recovery)
job_status = None
transient_job_check_error_reason = None
if not force_transit_to_recovering:
await asyncio.sleep(
managed_job_utils.JOB_STATUS_CHECK_GAP_SECONDS)
# Check the network connection to avoid false alarm for job
# failure. Network glitch was observed even in the VM.
try:
await backend_utils.async_check_network_connection()
except exceptions.NetworkError:
logger.info(
'Network is not available. Retrying again in '
f'{managed_job_utils.JOB_STATUS_CHECK_GAP_SECONDS} '
'seconds.')
continue
# NOTE: we do not check cluster status first because race
# condition can occur, i.e. cluster can be down during the job
# status check.
# NOTE: If fetching the job status fails or we force to transit
# to recovering, we will set the job status to None, which will
# force enter the recovering logic.
try:
job_status, transient_job_check_error_reason = (
await managed_job_utils.get_job_status(
self._backend,
cluster_name,
job_id=job_id_on_pool_cluster,
))
except exceptions.FetchClusterInfoError as fetch_e:
logger.info(
'Failed to fetch the job status. Start recovery.\n'
f'Exception: {common_utils.format_exception(fetch_e)}\n'
f'Traceback: {traceback.format_exc()}')
# Fall through to recovery logic below
# When job status check fails, we need to retry to avoid false alarm
# for job failure, as it could be a transient error for
# communication issue.
if transient_job_check_error_reason is not None:
logger.info(
'Potential transient error when fetching the job '
f'status. Reason: {transient_job_check_error_reason}.\n'
'Check cluster status to determine if the job is '
'preempted or failed.')
if transient_job_check_error_start_time is None:
transient_job_check_error_start_time = time.time()
job_check_backoff = common_utils.Backoff(
initial_backoff=1, max_backoff_factor=5)
else:
transient_job_check_error_start_time = None
job_check_backoff = None
# Handle success
if job_status == job_lib.JobStatus.SUCCEEDED:
logger.info(f'Task {task_id} succeeded! '
'Getting end time and cleaning up')
try:
success_end_time = await asyncio.to_thread(
managed_job_utils.try_to_get_job_end_time,
self._backend, cluster_name, job_id_on_pool_cluster)
except Exception as e: # pylint: disable=broad-except
logger.warning(
f'Failed to get job end time: '
f'{common_utils.format_exception(e)}',
exc_info=True)
success_end_time = 0
# The job is done. Set the job to SUCCEEDED first before start
# downloading and streaming the logs to make it more responsive.
await managed_job_state.set_succeeded_async(
self._job_id,
task_id,
end_time=success_end_time,
callback_func=callback_func)
logger.info(
f'Managed job {self._job_id} (task: {task_id}) SUCCEEDED. '
f'Cleaning up the cluster {cluster_name}.')
try:
logger.info(f'Downloading logs on cluster {cluster_name} '
f'and job id {job_id_on_pool_cluster}.')
clusters = await asyncio.to_thread(
backend_utils.get_clusters,
cluster_names=[cluster_name],
refresh=common.StatusRefreshMode.NONE,
all_users=True,
_include_is_managed=True)
if clusters:
assert len(clusters) == 1, (clusters, cluster_name)
handle = clusters[0].get('handle')
# Best effort to download and stream the logs.
await asyncio.to_thread(self.download_log_and_stream,
task_id, handle,
job_id_on_pool_cluster)
except Exception as e: # pylint: disable=broad-except
# We don't want to crash here, so just log and continue.
logger.warning(
f'Failed to download and stream logs: '
f'{common_utils.format_exception(e)}',
exc_info=True)
if cleanup_cluster_on_success:
# Only clean up the cluster, not the storages, because tasks
# may share storages.
await self._cleanup_cluster(cluster_name)
return True
# For single-node jobs, non-terminated job_status indicates a
# healthy cluster. We can safely continue monitoring.
# For multi-node jobs, since the job may not be set to FAILED
# immediately (depending on user program) when only some of the
# nodes are preempted or failed, need to check the actual cluster
# status.
if (job_status is not None and not job_status.is_terminal() and
task.num_nodes == 1):
continue
if job_status in job_lib.JobStatus.user_code_failure_states():
# Add a grace period before the check of preemption to avoid
# false alarm for job failure.
await asyncio.sleep(5)
# Pull the actual cluster status from the cloud provider to
# determine whether the cluster is preempted or failed.
# NOTE: Some failures may not be reflected in the cluster status
# depending on the cloud, which can also cause failure of the job.
# Plugins can report such failures via ExternalFailureSource.
# TODO(cooperc): do we need to add this to asyncio thread?
(cluster_status, handle) = await asyncio.to_thread(
backend_utils.refresh_cluster_status_handle,
cluster_name,
force_refresh_statuses=set(status_lib.ClusterStatus))
external_failures: Optional[List[ExternalClusterFailure]] = None
cluster_event_reason = None
if cluster_status != status_lib.ClusterStatus.UP:
# The cluster is (partially) preempted or failed. It can be
# down, INIT or STOPPED, based on the interruption behavior of
# the cloud. Spot recovery is needed (will be done later in the
# code).
cluster_status_str = ('' if cluster_status is None else
f' (status: {cluster_status.value})')
logger.info(
f'Cluster is preempted or failed{cluster_status_str}. '
'Recovering...')
# Fetch and log cluster events to provide context on why the
# cluster entered INIT/non-UP state.
try:
events = await asyncio.to_thread(
global_user_state.get_cluster_events,
cluster_name=cluster_name,
cluster_hash=None,
event_type=global_user_state.ClusterEventType.
STATUS_CHANGE,
include_timestamps=True,
limit=5)
if events:
event_strs = []
for event in events:
# Need cast due to dictionary semantics
transitioned_at = int(event['transitioned_at'])
timestamp = time.strftime(
'%Y-%m-%d %H:%M:%S',
time.localtime(transitioned_at))
event_strs.append(
f' {timestamp}: {event["reason"]}')
events_str = '\n'.join(event_strs)
logger.info(f'Recent cluster events:\n{events_str}')
cluster_event_reason = str(events[-1]['reason'])
except Exception as e: # pylint: disable=broad-except
logger.debug('Failed to fetch cluster events: '
f'{common_utils.format_exception(e)}')
if ExternalFailureSource.is_registered():
cluster_failures = await asyncio.to_thread(
ExternalFailureSource.get, cluster_name=cluster_name)
if cluster_failures:
logger.info(
f'Detected cluster failures: {cluster_failures}')
external_failures = (
ExternalClusterFailure.from_failure_list(
cluster_failures))
else:
# Cluster is UP
if job_status is not None and not job_status.is_terminal():
# The multi-node job is still running, continue monitoring.
continue
elif (job_status
in job_lib.JobStatus.user_code_failure_states() or
job_status == job_lib.JobStatus.FAILED_DRIVER):
# The user code has probably crashed, fail immediately.
logger.info(
f'Task {task_id} failed with status: {job_status}')
end_time = await asyncio.to_thread(
managed_job_utils.try_to_get_job_end_time,
self._backend, cluster_name, job_id_on_pool_cluster)
logger.info(
f'The user job failed ({job_status}). Please check the '
'logs below.\n'
f'== Logs of the user job (ID: {self._job_id}) ==\n')
await asyncio.to_thread(self.download_log_and_stream,
task_id, handle,
job_id_on_pool_cluster)
failure_reason = (
'To see the details, run: '
f'sky jobs logs --controller {self._job_id}')
managed_job_status = (
managed_job_state.ManagedJobStatus.FAILED)
if job_status == job_lib.JobStatus.FAILED_SETUP:
managed_job_status = (
managed_job_state.ManagedJobStatus.FAILED_SETUP)
elif job_status == job_lib.JobStatus.FAILED_DRIVER:
# FAILED_DRIVER is kind of an internal error, so we mark
# this as FAILED_CONTROLLER, even though the failure is
# not strictly within the controller.
managed_job_status = (
managed_job_state.ManagedJobStatus.FAILED_CONTROLLER
)
failure_reason = (
'The job driver on the remote cluster failed. This '
'can be caused by the job taking too much memory '
'or other resources. Try adding more memory, CPU, '
f'or disk in your job definition. {failure_reason}')
# Retrieve exit codes from the failed job
assert handle is not None, (
'Handle should not be None when cluster is UP', handle)