-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathjobs.py
More file actions
1824 lines (1576 loc) · 77.5 KB
/
jobs.py
File metadata and controls
1824 lines (1576 loc) · 77.5 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
"""
SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. # pylint: disable=line-too-long
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
SPDX-License-Identifier: Apache-2.0
"""
import abc
import asyncio
import collections
import copy
import dataclasses
import datetime
import hashlib
import json
import logging
import os
import tempfile
import time
from typing import List, Dict, Tuple, Type
import urllib.parse
import redis # type: ignore
import redis.asyncio # type: ignore
import pydantic
import yaml
from src.lib.data import storage
from src.lib.utils import common, osmo_errors, priority as wf_priority
from src.utils import connectors
from src.utils.job import app, backend_job_defs, common as task_common, kb_objects, task, workflow
from src.utils.job.jobs_base import Job, JobResult, JobStatus, update_progress_writer
from src.utils.progress_check import progress
# The name of the delayed job queue
DELAYED_JOB_QUEUE = 'delayed_job_queue'
PROGRESS_ITER_WRITE = 100
CONCURRENT_UPLOADS = 10
class JobExecutionContext(pydantic.BaseModel):
"""Context from the worker process, needed for executing jobs"""
postgres: connectors.PostgresConnector
redis: connectors.RedisConfig
class Config:
arbitrary_types_allowed = True
extra = 'forbid'
def cleanup_workflow_group(context: JobExecutionContext, workflow_id: str, workflow_uuid: str,
group_name: str):
"""
Cleans up a workflow group and enqueues a workflow cleanup job if all groups are cleaned up.
This function marks a workflow group as cleaned up in the database. If all groups in
the workflow are cleaned up, it enqueues a CleanupWorkflow job to perform final
workflow cleanup tasks.
Args:
context: The job execution context containing database and Redis connections
workflow_id: The ID of the workflow to clean up
workflow_uuid: The UUID of the workflow to clean up
group_name: The name of the group to mark as cleaned up
Returns:
None
"""
all_cleaned_up = task.TaskGroup.patch_cleaned_up(context.postgres,
workflow_id, group_name)
if all_cleaned_up:
cleanup_job = CleanupWorkflow(
workflow_id=workflow_id,
workflow_uuid=workflow_uuid
)
cleanup_job.send_job_to_queue()
class FrontendJob(Job):
""" Describes a job that can be run in the service worker """
super_type: str = 'frontend'
@abc.abstractmethod
def execute(self, context: JobExecutionContext,
progress_writer: progress.ProgressWriter,
progress_iter_freq: datetime.timedelta = \
datetime.timedelta(seconds=15)) -> JobResult:
"""
Executes the job. Returns info on whether the job completed successfully.
"""
pass
def prepare_execute(self, context: JobExecutionContext,
progress_writer: progress.ProgressWriter,
progress_iter_freq: datetime.timedelta = \
datetime.timedelta(seconds=15)) -> Tuple[bool, str]:
# pylint: disable=unused-argument
"""
Runs execute checks and prerequisites.
Returns whether execute is ready to run and error message if failed
"""
return True, ''
def handle_failure(self, context: JobExecutionContext, error: str):
"""
Handles job failure in the case that something goes wrong.
"""
pass
def get_redis_options(self):
return connectors.EXCHANGE, connectors.JOBS, connectors.TRANSPORT_OPTIONS
def send_delayed_job_to_queue(self, delay_duration: datetime.timedelta):
"""
Stores a serialized Job and the timestamp to a Redis Sorted Set (Zset).
The timestamp added represents the time step for the DelayedJobMonitor to add the
job into the job queue.
"""
redis_client = connectors.RedisConnector.get_instance().client
serialized_job = self.json()
timeout_time = time.time() + delay_duration.total_seconds()
redis_client.zadd(DELAYED_JOB_QUEUE, {serialized_job: timeout_time})
self.log_delayed_submission(delay_duration)
class WorkflowJob(FrontendJob):
"""
Represents some workflow task that needs to be executed by a worker.
"""
workflow_id: task_common.NamePattern
workflow_uuid: common.UuidPattern
def log_submission(self):
logging.info('Submitted new job %s to the job queue', self,
extra={'workflow_uuid': self.workflow_uuid})
def log_labels(self) -> Dict[str, str]:
return {'workflow_uuid': self.workflow_uuid}
class BackendJob(Job):
"""
Represents jobs that are sent to a backend worker.
"""
backend: str
def get_redis_options(self):
return connectors.EXCHANGE, connectors.BACKEND_JOBS,\
connectors.get_backend_transport_option(self.backend)
class SubmitWorkflow(WorkflowJob):
"""
Submit workflow job contains a workflow spec that has been submitted by the user.
When executed, it should do the following:
- Create an entry in the database for the overall workflow.
- Create entries in the database for each task in the job.
- Schedule "Submit Task" jobs for all tasks in the workflow that have no preconditions.
"""
user: str
spec: workflow.WorkflowSpec
original_spec: Dict
group_and_task_uuids: Dict[str, common.UuidPattern]
parent_workflow_id: task_common.NamePattern | None
app_uuid: str | None = None
app_version: int | None = None
task_db_keys: Dict[str, str] | None = None
priority: wf_priority.WorkflowPriority = wf_priority.WorkflowPriority.NORMAL
@classmethod
def _get_job_id(cls, values):
return f'{values["workflow_uuid"]}-submit'
@pydantic.validator('job_id')
@classmethod
def validate_job_id(cls, value: str) -> str:
"""
Validates job_id. Returns the value of job_id if valid.
"""
if not value.endswith('-submit'):
raise osmo_errors.OSMOServerError(
f'SubmitWorkflow job_id should end with \"-submit\": {value}.')
return value
def execute(self, context: JobExecutionContext,
progress_writer: progress.ProgressWriter,
progress_iter_freq: datetime.timedelta = \
datetime.timedelta(seconds=15)) -> JobResult:
"""
Executes the job. Returns true if the job was completed successful and can
be removed from the message queue, or false if the job failed.
"""
last_timestamp = datetime.datetime.now()
postgres = context.postgres
# Create workflow and groups in database
remaining_upstream_groups: Dict = collections.defaultdict(set)
downstream_groups: Dict = collections.defaultdict(set)
workflow_obj = workflow.Workflow.from_workflow_spec(context.postgres, self.workflow_id,
self.workflow_uuid, self.user, self.spec, context.redis.redis_url,
self.group_and_task_uuids, remaining_upstream_groups, downstream_groups,
parent_workflow_id=self.parent_workflow_id, task_db_keys=self.task_db_keys,
app_uuid=self.app_uuid, app_version=self.app_version,
priority=self.priority)
version = self.original_spec['version'] if 'version' in self.original_spec else '2'
workflow_obj.insert_to_db(version)
self.workflow_id = workflow_obj.workflow_id
for group_obj in workflow_obj.groups:
group_obj.workflow_id_internal = workflow_obj.workflow_id
group_obj.spec = \
group_obj.spec.parse(postgres, workflow_obj.workflow_id,
self.group_and_task_uuids)
group_obj.insert_to_db()
for task_obj, task_obj_spec in zip(group_obj.tasks, group_obj.spec.tasks):
task_obj.workflow_id_internal = workflow_obj.workflow_id
task_obj.insert_to_db(
gpu_count=task_obj_spec.resources.gpu or 0,
cpu_count=task_obj_spec.resources.cpu or 0,
disk_count=common.convert_resource_value_str(
task_obj_spec.resources.storage or '0', 'GiB'),
memory_count=common.convert_resource_value_str(
task_obj_spec.resources.memory or '0', 'GiB'))
current_timestamp = datetime.datetime.now()
time_elapsed = last_timestamp - current_timestamp
if time_elapsed > progress_iter_freq:
progress_writer.report_progress()
last_timestamp = current_timestamp
progress_writer.report_progress()
# Fetch workflow_obj to get latest info
workflow_obj = workflow.Workflow.fetch_from_db(context.postgres, workflow_obj.workflow_id)
# Enqueue a delayed job to check the queue timeout
if not workflow_obj.pool:
raise osmo_errors.OSMOUserError('No Pool Specified')
pool_info = connectors.Pool.fetch_from_db(context.postgres, workflow_obj.pool)
workflow_config = context.postgres.get_workflow_configs()
queue_timeout = workflow_obj.timeout.queue_timeout or \
common.to_timedelta(pool_info.default_queue_timeout
if pool_info.default_queue_timeout else
workflow_config.default_queue_timeout)
check_queue_timeout = CheckQueueTimeout(workflow_id=workflow_obj.workflow_id,
workflow_uuid=self.workflow_uuid)
check_queue_timeout.send_delayed_job_to_queue(queue_timeout)
# Check if workflow has been canceled.
# If it hasn't, mark all the groups as WAITING
# If this is false, the workflow has been canceled
if workflow_obj.mark_groups_as_waiting():
# Determine which groups don't have prerequisites and enqueue CreateGroup jobs
# for them
backend_config_cache = connectors.BackendConfigCache()
for group_obj in workflow_obj.groups:
group_obj.workflow_id_internal = workflow_obj.workflow_id
if not group_obj.remaining_upstream_groups:
backend_name = group_obj.spec.tasks[0].backend
backend = backend_config_cache.get(backend_name)
group_obj.set_tasks_to_processing()
group_obj.update_status_to_db(
common.current_time(),
task.TaskGroupStatus.PROCESSING,
scheduler_settings=backend.scheduler_settings)
submit_task = CreateGroup(
backend=workflow_obj.backend,
group_name=group_obj.name,
workflow_id=workflow_obj.workflow_id,
workflow_uuid=self.workflow_uuid,
user=self.user)
submit_task.send_job_to_queue()
return JobResult()
def handle_failure(self, context: JobExecutionContext, error: str):
"""
Update Workflow to FAILED_SERVER_ERROR
Set Failure Reason to log file
"""
try:
workflow_obj = workflow.Workflow.fetch_from_db(context.postgres, self.workflow_id)
except osmo_errors.OSMODatabaseError:
logging.info('Cannot find %s workflow during SubmitWorkflow handle failure',
self.workflow_id, extra={'workflow_uuid': self.workflow_uuid})
return
parsed_result = urllib.parse.urlparse(workflow_obj.logs)
if parsed_result.scheme in ('redis', 'rediss'):
redis_client = redis.from_url(workflow_obj.logs)
logs = connectors.redis.LogStreamBody(
time=common.current_time(), io_type=connectors.redis.IOType.OSMO_CTRL,
source='OSMO', retry_id=0, text='Failed SubmitWorkflow for workflow ' +
f'{workflow_obj.workflow_id} with error: {error}')
redis_client.xadd(f'{self.workflow_id}-logs', json.loads(logs.json()))
redis_client.expire(f'{self.workflow_id}-logs', connectors.MAX_LOG_TTL, nx=True)
for group_obj in workflow_obj.get_group_objs():
if group_obj.status.finished():
continue
# Update unfinished task statuses
message = f'Task is canceled due to Failed Infra: {self.user}, {error}'
canceled_task_status = task.TaskGroupStatus.FAILED_SERVER_ERROR
update_task = UpdateGroup(
workflow_id=self.workflow_id,
workflow_uuid=self.workflow_uuid,
group_name=group_obj.name,
status=canceled_task_status,
message=message,
user=self.user,
exit_code=task.ExitCode.FAILED_SERVER_ERROR.value
)
update_task.send_job_to_queue()
@dataclasses.dataclass
class File:
"""Stores a file to be uploaded to a workflow's outputs directory"""
path: str
content: str
class UploadWorkflowFiles(WorkflowJob):
"""
Uploads a list of workflow files to a workflow's outputs directory
"""
files: List[File]
@classmethod
def _get_job_id(cls, values):
# Generate unique id using sha256 of all file paths
# 16 bytes of the hash is enough to guarantee uniqueness
all_paths = '\n'.join(file.path for file in values['files'])
digest = hashlib.sha256(all_paths.encode('utf-8')).hexdigest()[:32]
return f'{values["workflow_uuid"]}-{digest}-upload-files'
@pydantic.validator('job_id')
@classmethod
def validate_job_id(cls, value: str) -> str:
"""
Validates job_id. Returns the value of job_id if valid.
"""
if not value.endswith('-upload-files'):
raise osmo_errors.OSMOServerError(
f'UploadFiles job_id should end with \"-upload-files\": {value}.')
return value
def execute(self, context: JobExecutionContext,
progress_writer: progress.ProgressWriter,
progress_iter_freq: datetime.timedelta = \
datetime.timedelta(seconds=15)) -> JobResult:
"""
Executes the job. Returns true if the job was completed successful and can
be removed from the message queue, or false if the job failed.
"""
workflow_config = context.postgres.get_workflow_configs()
if workflow_config.workflow_log.credential is None:
return JobResult(
success=False,
error='Workflow log credential is not set',
)
storage_client = storage.Client.create(
data_credential=workflow_config.workflow_log.credential,
)
with tempfile.TemporaryDirectory() as temp_dir:
for file in self.files:
file_path = os.path.join(temp_dir, file.path)
with open(file_path, 'w+', encoding='utf-8') as local_file:
local_file.write(file.content)
local_file.flush()
# Trigger progress update (if applicable) whenever a file is uploaded
last_timestamp = datetime.datetime.now()
def _upload_callback(upload_input, upload_resp) -> None:
# pylint: disable=unused-argument
nonlocal last_timestamp
current_timestamp = datetime.datetime.now()
time_elapsed = last_timestamp - current_timestamp
if time_elapsed > progress_iter_freq:
progress_writer.report_progress()
last_timestamp = current_timestamp
storage_client.upload_objects(
source=os.path.join(temp_dir, '*'), # upload contents only
destination_prefix=self.workflow_id,
callback=_upload_callback,
)
return JobResult()
class CreateGroup(BackendJob, WorkflowJob, backend_job_defs.BackendCreateGroupMixin):
""" This is the frontend implementation for the BackendCreateGroup job
that is put in backend queue and worked on by backend worker. It's execute function
will be called only if the backend's execute function succeeds """
user: str
k8s_resources: List[Dict] | None = None # type: ignore[assignment]
@classmethod
def _get_job_id(cls, values):
return f'{values["workflow_uuid"]}-{values["group_name"]}-submit'
@pydantic.validator('job_id', check_fields=False)
@classmethod
def validate_job_id(cls, value: str) -> str:
"""
Validates job_id. Returns the value of job_id if valid.
"""
if not value.endswith('-submit'):
raise osmo_errors.OSMOServerError(
f'CreateGroup job_id should end with \"-submit\": {value}.')
return value
def execute(self, context: JobExecutionContext,
progress_writer: progress.ProgressWriter,
progress_iter_freq: datetime.timedelta = \
datetime.timedelta(seconds=15)) -> JobResult:
# Status update is executed before sending the CreateGroup job to the queue
return JobResult()
def prepare_execute(self, context: JobExecutionContext,
progress_writer: progress.ProgressWriter,
progress_iter_freq: datetime.timedelta = \
datetime.timedelta(seconds=15)) -> Tuple[bool, str]:
"""
Runs execute checks and prerequisites.
Returns whether execute is ready to run and error message if failed
"""
group_obj = task.TaskGroup.fetch_from_db(context.postgres, self.workflow_id,
self.group_name)
if group_obj.status not in \
(task.TaskGroupStatus.WAITING, task.TaskGroupStatus.PROCESSING):
return False, f'Create Group Failed: Group {group_obj.name} has status: ' +\
f'{group_obj.status.value}.'
if not self.k8s_resources:
workflow_config = context.postgres.get_workflow_configs()
backend_config_cache = connectors.BackendConfigCache()
workflow_obj = workflow.Workflow.fetch_from_db(context.postgres, self.workflow_id)
resources, pod_specs = group_obj.get_kb_specs(
self.workflow_uuid,
self.user,
workflow_config,
backend_config_cache,
group_obj.spec.tasks[0].backend,
workflow_obj.pool or '', # pool is validated in SubmitWorkflow
progress_writer,
progress_iter_freq,
workflow_obj.plugins,
workflow_obj.priority,
)
self.k8s_resources = resources
group_obj.update_group_template_resource_types()
upload_task = UploadWorkflowFiles(
workflow_id=workflow_obj.workflow_id,
workflow_uuid=self.workflow_uuid,
files=[File(f'{task_name}.spec', yaml.dump(pod_spec))
for task_name, pod_spec in pod_specs.items()])
upload_task.send_job_to_queue()
return True, ''
def handle_failure(self, context: JobExecutionContext, error: str):
"""
Handles job failure in the case that something goes wrong.
"""
update_task = UpdateGroup(
workflow_id=self.workflow_id,
workflow_uuid=self.workflow_uuid,
status=task.TaskGroupStatus.FAILED_SERVER_ERROR,
group_name=self.group_name,
message=f'CreateGroup job failed: {error}',
user=self.user,
exit_code=task.ExitCode.FAILED_SERVER_ERROR.value)
update_task.send_job_to_queue()
class CleanupGroup(BackendJob, WorkflowJob, backend_job_defs.BackendCleanupGroupMixin):
""" This is the frontend implementation for the CleanupGroup job
that is put in backend queue and worked on by backend worker. It's execute function
will be called only if the backend's execute function succeeds """
@classmethod
def _get_job_id(cls, values):
return f'{values["workflow_uuid"]}-{values["group_name"]}-backend-cleanup'
@pydantic.validator('job_id', check_fields=False)
@classmethod
def validate_job_id(cls, value: str) -> str:
"""
Validates job_id. Returns the value of job_id if valid.
"""
if not value.endswith('-cleanup'):
raise osmo_errors.OSMOServerError(
f'CleanupGroup job_id should end with \"-cleanup\": {value}.')
return value
def execute(self, context: JobExecutionContext,
progress_writer: progress.ProgressWriter,
progress_iter_freq: datetime.timedelta = \
datetime.timedelta(seconds=15)) -> JobResult:
cleanup_workflow_group(context, self.workflow_id, self.workflow_uuid, self.group_name)
return JobResult()
def prepare_execute(self, context: JobExecutionContext,
progress_writer: progress.ProgressWriter,
progress_iter_freq: datetime.timedelta = \
datetime.timedelta(seconds=15)) -> Tuple[bool, str]:
# pylint: disable=unused-argument
"""
Runs execute checks and prerequisites.
Returns whether execute is ready to run and error message if failed
"""
# Clear the error-logs in case the job has already ran before
redis_client = connectors.RedisConnector.get_instance().client
group_obj = task.TaskGroup.fetch_from_db(context.postgres, self.workflow_id,
self.group_name)
for task_obj in group_obj.tasks:
redis_client.delete(
f'{self.workflow_id}-{task_obj.task_uuid}-{task_obj.retry_id}-error-logs')
return True, ''
class UpdateGroup(WorkflowJob):
"""
Update task job contains the id of a task, its container status and optional failure reason.
When executed, it should do the following:
- Update the task status and workflow status.
- Schedule BackendCleanupGroup if needed.
"""
group_name: task_common.NamePattern
task_name: task_common.NamePattern | None = None
retry_id: int | None = None
status: task.TaskGroupStatus
message: str = ''
user: str
exit_code: int | None = None
force_cancel: bool = False
lead_task: bool = True
@classmethod
def _get_job_id(cls, values):
status = values.get('status')
if isinstance(status, task.TaskGroupStatus):
status = status.name
name_list = [values['workflow_uuid'], values['group_name']]
if values.get('task_name'):
name_list.append(values['task_name'])
if values.get('retry_id') is not None:
name_list.append(str(values['retry_id']))
name_list += ['update', status]
return '-'.join(name_list)
@pydantic.root_validator
@classmethod
def validate_job_id(cls, values):
"""
Validates job_id. Returns the value of job_id if valid.
"""
job_id = values.get('job_id')
status = values.get('status')
if job_id is None or status is None:
return values
if isinstance(status, task.TaskGroupStatus):
status = status.name
suffix = f'-update-{status}'
if not job_id.endswith(suffix):
raise osmo_errors.OSMOServerError(
f'Job id for an UpdateGroup is in valid: {job_id} should ends with {suffix}.')
return values
@pydantic.root_validator
@classmethod
def validate_retry_id(cls, values):
"""
Validates that when task_name exists, retry id is not None. Returns values if valid.
"""
job_id = values.get('job_id')
task_name = values.get('task_name')
retry_id = values.get('retry_id')
if task_name and retry_id is None:
raise osmo_errors.OSMOServerError(f'UpdateGroup: {job_id} is missing retry_id.')
return values
def send_job_to_queue(self):
"""
Sends a Job to the job queue.
"""
redis_connector = connectors.RedisConnector.get_instance()
redis_client = redis_connector.client
key_name = f'dedupe:{self.job_id}'
if not self.status.canceled() and redis_client.get(key_name):
logging.info('Skipping enqueuing job %s because it is a duplicate', self,
extra={'workflow_uuid': self.workflow_uuid})
return
self.send_job(redis_client, redis_connector.config, key_name)
def _update_and_fetch_task_status(self, context: JobExecutionContext,
current_task: task.Task, update_time: datetime.datetime
) -> task.TaskGroupStatus:
current_task.update_status_to_db(update_time, self.status, self.message, self.exit_code)
if not self.task_name or self.retry_id is None:
raise osmo_errors.OSMOError('Task name and retry id are required to update task status')
updated_task = task.Task.fetch_from_db(
context.postgres,
self.workflow_id,
self.task_name,
self.retry_id,
)
return updated_task.status
def _update_all_tasks(
self,
context: JobExecutionContext,
progress_writer: progress.ProgressWriter,
progress_iter_freq: datetime.timedelta,
group_obj: task.TaskGroup,
pool: connectors.Pool,
update_time: datetime.datetime,
total_timeout: int,
redis_client: redis.Redis,
workflow_config: connectors.WorkflowConfig,
backend_config_cache: connectors.BackendConfigCache,
workflow_obj: workflow.Workflow,
current_task: task.Task,
) -> task.TaskGroupStatus:
# pylint: disable=unused-argument
"""
Update tasks if needed.
"""
if not self.status.finished():
return self._update_and_fetch_task_status(context, current_task, update_time)
backend_config = backend_config_cache.get(group_obj.spec.tasks[0].backend)
k8s_factory = group_obj.get_k8s_object_factory(backend_config)
max_retries = workflow_config.max_retry_per_task
if not k8s_factory.retry_allowed():
max_retries = 0
self._apply_exit_action(current_task, max_retries, pool)
if self.lead_task: # Lead task finished
if group_obj.spec.has_group_barrier():
self._remove_all_barrier(redis_client)
update_status = self._update_and_fetch_task_status(context, current_task, update_time)
if self.status != update_status:
return update_status
if self.status == task.TaskGroupStatus.RESCHEDULED:
self._retry_task(
current_task,
group_obj,
pool.name,
workflow_config,
backend_config,
context,
progress_writer,
workflow_obj,
k8s_factory
)
# If group leader reschedules, the other tasks should restart
for task_obj in group_obj.tasks:
if task_obj.name == self.task_name:
continue
else:
self._restart_task(redis_client, task_obj, total_timeout)
else:
for task_obj in group_obj.tasks:
if task_obj.name == self.task_name:
continue
# If group leader exits with a special failed status like
# FAILED_EVICTED, the other tasks should be labeled as FAILED
# (not FAILED_EVICTED)
status = task.TaskGroupStatus.FAILED if self.status.failed() else self.status
# TODO: Add a new status type for status caused by Lead Container finishing
task_obj.update_status_to_db(update_time, status, 'Lead task finished')
else: # Nonlead task finished
if group_obj.spec.has_group_barrier():
self._remove_barrier(redis_client)
update_status = self._update_and_fetch_task_status(context, current_task, update_time)
if group_obj.spec.has_group_barrier() and current_task.status != update_status:
self._notify_barrier(context.postgres, redis_client, total_timeout)
if self.status != update_status:
return update_status
if self.status == task.TaskGroupStatus.RESCHEDULED:
if not group_obj.spec.ignoreNonleadStatus:
if group_obj.spec.has_group_barrier():
self._remove_all_barrier(redis_client)
for task_obj in group_obj.tasks:
if task_obj.name == self.task_name:
continue
else:
self._restart_task(redis_client, task_obj, total_timeout)
self._retry_task(
current_task,
group_obj,
pool.name,
workflow_config,
backend_config,
context,
progress_writer,
workflow_obj,
k8s_factory
)
elif self.status.failed() and not group_obj.spec.ignoreNonleadStatus:
for task_obj in group_obj.tasks:
if task_obj.name == self.task_name:
continue
task_obj.update_status_to_db(update_time, task.TaskGroupStatus.FAILED,
f'Task {self.task_name} Failed.')
return update_status
def schedule_cleanup_job(self, context: JobExecutionContext, workflow_obj: workflow.Workflow,
group_obj: task.TaskGroup,
workflow_config: connectors.WorkflowConfig,
backend: connectors.Backend | None):
# Is the status being updated to finished? If so, enqueue BackendCleanup task
# Schedule BackendCleanupGroup if needed. We only schedule cleanup if the lead
# task has a completed status, OR if any task (including non-lead) has a failed
# status.
lead_finished = self.status.finished() and self.lead_task
nonlead_triggered_failed = self.status.failed() and not group_obj.spec.ignoreNonleadStatus
if not(lead_finished or nonlead_triggered_failed or self.force_cancel):
return
job_id = f'{self.workflow_uuid}-{self.group_name}-{common.generate_unique_id(6)}'\
'-backend-cleanup'
# TODO: Get labels from same place they are created
labels={
'osmo.workflow_uuid': self.workflow_uuid,
'osmo.group_uuid': group_obj.group_uuid
}
if backend is None:
logging.info('Backend %s not found for group %s. '
'Skipping CleanupGroup and checking CleanupWorkflow.',
workflow_obj.backend, group_obj.name,
extra={'workflow_uuid': self.workflow_uuid})
cleanup_workflow_group(context, workflow_obj.workflow_id,
workflow_obj.workflow_uuid,
group_obj.name)
else:
factory = group_obj.get_k8s_object_factory(backend)
cleanup_specs = [
backend_job_defs.BackendCleanupSpec(
generic_api=backend_job_defs.BackendGenericApi(
api_version='v1', kind='Secret'),
labels=labels),
backend_job_defs.BackendCleanupSpec(
generic_api=backend_job_defs.BackendGenericApi(
api_version='v1', kind='Service'),
labels=labels),
] + factory.get_group_cleanup_specs(labels)
for resource_type in group_obj.group_template_resource_types:
cleanup_specs.append(
backend_job_defs.BackendCleanupSpec(
generic_api=backend_job_defs.BackendGenericApi(
api_version=resource_type['apiVersion'],
kind=resource_type['kind'],
),
labels=labels,
)
)
force_job_id = f'{self.workflow_uuid}-{self.group_name}-'\
f'{common.generate_unique_id(6)}-force-backend-cleanup'
error_log_spec = None
if self.status.has_error_logs():
error_log_spec = factory.get_error_log_specs(labels)
cleanup_task = CleanupGroup(
backend=workflow_obj.backend,
job_id=job_id if not self.force_cancel else force_job_id,
group_name=group_obj.name,
workflow_id=self.workflow_id,
workflow_uuid=self.workflow_uuid,
force_delete=self.force_cancel,
cleanup_specs=cleanup_specs, error_log_spec=error_log_spec,
max_log_lines=workflow_config.max_error_log_lines)
cleanup_task.send_job_to_queue()
def execute(self, context: JobExecutionContext,
progress_writer: progress.ProgressWriter,
progress_iter_freq: datetime.timedelta = \
datetime.timedelta(seconds=15)) -> JobResult:
"""
Executes the job. Returns true if the job was completed successful and can
be removed from the message queue, or false if the job failed.
"""
# Read current status from db
group_obj = task.TaskGroup.fetch_from_db(context.postgres, self.workflow_id,
self.group_name)
update_time = common.current_time()
if self.status.canceled():
# If it is force cancel, bypass PROCESSING
if group_obj.status != task.TaskGroupStatus.PROCESSING or self.force_cancel:
# Try to change it to Canceled
group_obj.update_status_to_db(update_time,
self.status, self.message, self.force_cancel)
# Get the status again to see if Canceled was applied
group_obj.fetch_status()
# Need to check status here because the status could have changed due to fetch_status
if group_obj.status == task.TaskGroupStatus.PROCESSING:
delayed_job = copy.deepcopy(self)
delayed_job.job_id = \
f'{common.generate_unique_id(5)}-{UpdateGroup._get_job_id(delayed_job.dict())}'
delayed_job.send_delayed_job_to_queue(
datetime.timedelta(minutes=1))
# Put it back into the queue
return JobResult(
status=JobStatus.FAILED_NO_RETRY,
message=f'Group status is {group_obj.status}: Adding back into job queue.')
workflow_config = context.postgres.get_workflow_configs()
backend_config_cache = connectors.BackendConfigCache()
workflow_obj = workflow.Workflow.fetch_from_db(
context.postgres, self.workflow_id, fetch_groups=False)
total_timeout = task_common.calculate_total_timeout(
workflow_obj.workflow_id,
workflow_obj.timeout.queue_timeout, workflow_obj.timeout.exec_timeout)
redis_client = connectors.RedisConnector.get_instance().client
if not workflow_obj.pool:
raise osmo_errors.OSMOUserError('No Pool Specified')
if self.status.canceled() or \
self.status in [task.TaskGroupStatus.FAILED_UPSTREAM,
task.TaskGroupStatus.FAILED_SERVER_ERROR]:
for task_obj in group_obj.tasks:
task_obj.update_status_to_db(update_time, self.status,
self.message, self.exit_code)
else:
pool_info = connectors.Pool.fetch_from_db(context.postgres, workflow_obj.pool)
if self.task_name and self.retry_id is not None:
current_task = task.Task.fetch_from_db(
context.postgres, self.workflow_id, self.task_name, self.retry_id)
if (not current_task.status.prerunning()) and \
self.status == task.TaskGroupStatus.FAILED_START_TIMEOUT:
logging.info('Skipping updating task %s to FAILED_START_TIMEOUT '
'as it is in %s state.',
current_task.name, current_task.status,
extra={'workflow_uuid': self.workflow_uuid})
return JobResult()
update_status = self._update_all_tasks(
context,
progress_writer,
progress_iter_freq,
group_obj,
pool_info,
update_time,
total_timeout,
redis_client,
workflow_config,
backend_config_cache,
workflow_obj,
current_task
)
if self.status != update_status: # If no change occurs, don't update anything
return JobResult()
# Change self.status to group status
if self.status == task.TaskGroupStatus.RESCHEDULED:
self.status = task.TaskGroupStatus.RUNNING
# Is the status being updated to running? If so, schedule a CheckRunTimeout task
if group_obj.status.prerunning() and self.status == task.TaskGroupStatus.RUNNING:
exec_timeout = workflow_obj.timeout.exec_timeout or \
common.to_timedelta(pool_info.default_exec_timeout
if pool_info.default_exec_timeout else
workflow_config.default_exec_timeout)
check_run_timeout = CheckRunTimeout(workflow_id=self.workflow_id,
workflow_uuid=self.workflow_uuid)
check_run_timeout.send_delayed_job_to_queue(exec_timeout)
group_obj.update_status_to_db(update_time, self.status, self.message)
canceled_by = self.user if \
(self.status == task.TaskGroupStatus.FAILED_CANCELED) else ''
workflow_status = workflow_obj.update_status_to_db(update_time, canceled_by=canceled_by)
# Send notification only for the last lead task that ran, which excludes FAILED_UPSTREAM
if workflow_status.finished() and self.lead_task and \
self.status != task.TaskGroupStatus.FAILED_UPSTREAM \
and context.postgres.method != 'dev':
workflow_obj.send_notification(workflow_status)
backend: connectors.Backend | None = None
try:
backend = backend_config_cache.get(workflow_obj.backend)
except osmo_errors.OSMOBackendError:
pass
self.schedule_cleanup_job(context, workflow_obj, group_obj,
workflow_config, backend)
# Fetch the group obj in case of race-condition
group_obj.fetch_status()
if backend is None:
downstream_status = task.TaskGroupStatus.FAILED
for downstream_group in group_obj.downstream_groups:
downstream_update_task = UpdateGroup(
workflow_id=self.workflow_id,
workflow_uuid=self.workflow_uuid,
group_name=downstream_group,
status=downstream_status,
message='Backend not found.',
user=self.user,
exit_code=task.ExitCode.FAILED_UPSTREAM.value)
downstream_update_task.send_job_to_queue()
# Update downstream tasks' status to FAILED_UPSTREAM
elif group_obj.status.failed():
downstream_status = task.TaskGroupStatus.FAILED_UPSTREAM
for downstream_group in group_obj.downstream_groups:
downstream_update_task = UpdateGroup(
workflow_id=self.workflow_id,
workflow_uuid=self.workflow_uuid,
group_name=downstream_group,
status=downstream_status,
message='Upstream task failed.',
user=self.user,
exit_code=task.ExitCode.FAILED_UPSTREAM.value)
downstream_update_task.send_job_to_queue()
# If this group succeeded, remove this as a dependency for all downstream groups and
# launch downstream groups that can be launched
elif group_obj.status == task.TaskGroupStatus.COMPLETED:
downstream_groups = group_obj.update_downstream_groups_in_db()
for downstream_group_obj in downstream_groups:
if not workflow_obj.pool:
raise osmo_errors.OSMOUserError('No Pool Specified')
downstream_group_obj.set_tasks_to_processing()
downstream_group_obj.update_status_to_db(
common.current_time(),
task.TaskGroupStatus.PROCESSING,
scheduler_settings=backend.scheduler_settings)
submit_task = CreateGroup(
backend=workflow_obj.backend,
group_name=downstream_group_obj.name,
workflow_id=self.workflow_id,
workflow_uuid=self.workflow_uuid,
user=self.user)
submit_task.send_job_to_queue()
return JobResult()
def handle_failure(self, context: JobExecutionContext, error: str):
"""
Schedule cleanup in case UpdateGroup fails.
"""
workflow_obj = workflow.Workflow.fetch_from_db(context.postgres, self.workflow_id)
if not workflow_obj.status.finished():
return
workflow_config = context.postgres.get_workflow_configs()
backend_config_cache = connectors.BackendConfigCache()
group_obj = task.TaskGroup.fetch_from_db(context.postgres, self.workflow_id,
self.group_name)
backend: connectors.Backend | None = None
try: