-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathapi_server_sql.py
More file actions
1547 lines (1383 loc) · 59.9 KB
/
api_server_sql.py
File metadata and controls
1547 lines (1383 loc) · 59.9 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
import dataclasses
import datetime
import logging
import typing
from typing import Any, Final, Optional
import sqlalchemy as sql
from sqlalchemy import orm
from . import backend_types_sql as bts
from . import component_structures as structures
from . import errors
from . import filter_query_sql
if typing.TYPE_CHECKING:
from cloud_pipelines.orchestration.storage_providers import (
interfaces as storage_provider_interfaces,
)
from .launchers import interfaces as launcher_interfaces
_logger = logging.getLogger(__name__)
T = typing.TypeVar("T")
class ApiServiceError(RuntimeError):
pass
def _get_current_time() -> datetime.datetime:
return datetime.datetime.now(tz=datetime.timezone.utc)
# ==== PipelineJobService
@dataclasses.dataclass(kw_only=True)
class PipelineRunResponse:
id: bts.IdType
root_execution_id: bts.IdType
annotations: dict[str, Any] | None = None
# status: "PipelineJobStatus"
created_by: str | None = None
created_at: datetime.datetime | None = None
pipeline_name: str | None = None
execution_status_stats: dict[str, int] | None = None
@classmethod
def from_db(cls, pipeline_run: bts.PipelineRun) -> "PipelineRunResponse":
return PipelineRunResponse(
id=pipeline_run.id,
root_execution_id=pipeline_run.root_execution_id,
annotations=pipeline_run.annotations,
created_by=pipeline_run.created_by,
created_at=pipeline_run.created_at,
)
class GetPipelineRunResponse(PipelineRunResponse):
pass
@dataclasses.dataclass(kw_only=True)
class ListPipelineJobsResponse:
pipeline_runs: list[PipelineRunResponse]
next_page_token: str | None = None
class PipelineRunsApiService_Sql:
_PIPELINE_NAME_EXTRA_DATA_KEY = "pipeline_name"
_DEFAULT_PAGE_SIZE: Final[int] = 10
_SYSTEM_KEY_RESERVED_MSG = (
"Annotation keys starting with "
f"{filter_query_sql.SYSTEM_KEY_PREFIX!r} are reserved for system use."
)
def _fail_if_changing_system_annotation(self, *, key: str) -> None:
if key.startswith(filter_query_sql.SYSTEM_KEY_PREFIX):
raise errors.ApiValidationError(self._SYSTEM_KEY_RESERVED_MSG)
def create(
self,
session: orm.Session,
root_task: structures.TaskSpec,
# Component library to avoid repeating component specs inside task specs
components: Optional[list[structures.ComponentReference]] = None,
# Arbitrary metadata. Can be used to specify user.
annotations: Optional[dict[str, Any]] = None,
created_by: str | None = None,
) -> PipelineRunResponse:
# TODO: Validate the pipeline spec
# TODO: Load and validate all components
# TODO: Fetch missing components and populate component specs
pipeline_name = root_task.component_ref.spec.name
with session.begin():
root_execution_node = _recursively_create_all_executions_and_artifacts_root(
session=session,
root_task_spec=root_task,
)
# Store into DB.
current_time = _get_current_time()
pipeline_run = bts.PipelineRun(
root_execution=root_execution_node,
created_at=current_time,
updated_at=current_time,
annotations=annotations,
created_by=created_by,
extra_data={
self._PIPELINE_NAME_EXTRA_DATA_KEY: pipeline_name,
},
)
session.add(pipeline_run)
# Mirror created_by into the annotations table so it's searchable
# via filter_query like any other annotation.
if created_by is not None:
# Flush to populate pipeline_run.id (server-generated) before inserting the annotation FK.
# TODO: Use ORM relationship instead of explicit flush + manual FK assignment.
session.flush()
session.add(
bts.PipelineRunAnnotation(
pipeline_run_id=pipeline_run.id,
key=filter_query_sql.PipelineRunAnnotationSystemKey.CREATED_BY,
value=created_by,
)
)
session.commit()
session.refresh(pipeline_run)
return PipelineRunResponse.from_db(pipeline_run)
def get(self, session: orm.Session, id: bts.IdType) -> PipelineRunResponse:
pipeline_run = session.get(bts.PipelineRun, id)
if not pipeline_run:
raise errors.ItemNotFoundError(f"Pipeline run {id} not found.")
return PipelineRunResponse.from_db(pipeline_run)
def terminate(
self,
session: orm.Session,
id: bts.IdType,
terminated_by: str | None = None,
skip_user_check: bool = False,
):
pipeline_run = session.get(bts.PipelineRun, id)
if not pipeline_run:
raise errors.ItemNotFoundError(f"Pipeline run {id} not found.")
if not skip_user_check and (terminated_by != pipeline_run.created_by):
raise errors.PermissionError(
f"The pipeline run {id} was started by {pipeline_run.created_by} and cannot be terminated by {terminated_by}"
)
_logger.info(
f"{pipeline_run.id=} The pipeline run is being cancelled by {terminated_by}."
)
# Marking the pipeline run for termination
if pipeline_run.extra_data is None:
pipeline_run.extra_data = {}
pipeline_run.extra_data["desired_state"] = "TERMINATED"
pipeline_run.extra_data["terminated_by"] = terminated_by
# Marking all running executions belonging to the run for termination
running_execution_nodes = [
execution_node
for execution_node in pipeline_run.root_execution.descendants
if execution_node.container_execution_status
in (
bts.ContainerExecutionStatus.QUEUED,
bts.ContainerExecutionStatus.WAITING_FOR_UPSTREAM,
bts.ContainerExecutionStatus.PENDING,
bts.ContainerExecutionStatus.RUNNING,
)
]
for execution_node in running_execution_nodes:
if execution_node.extra_data is None:
execution_node.extra_data = {}
execution_node.extra_data["desired_state"] = "TERMINATED"
session.commit()
# Note: This method must be last to not shadow the "list" type
def list(
self,
*,
session: orm.Session,
page_token: str | None = None,
filter: str | None = None,
filter_query: str | None = None,
current_user: str | None = None,
include_pipeline_names: bool = False,
include_execution_stats: bool = False,
) -> ListPipelineJobsResponse:
where_clauses, offset, next_token = filter_query_sql.build_list_filters(
filter_value=filter,
filter_query_value=filter_query,
page_token_value=page_token,
current_user=current_user,
page_size=self._DEFAULT_PAGE_SIZE,
)
pipeline_runs = list(
session.scalars(
sql.select(bts.PipelineRun)
.where(*where_clauses)
.order_by(bts.PipelineRun.created_at.desc())
.offset(offset)
.limit(self._DEFAULT_PAGE_SIZE)
).all()
)
next_page_token = (
next_token if len(pipeline_runs) >= self._DEFAULT_PAGE_SIZE else None
)
return ListPipelineJobsResponse(
pipeline_runs=[
self._create_pipeline_run_response(
session=session,
pipeline_run=pipeline_run,
include_pipeline_names=include_pipeline_names,
include_execution_stats=include_execution_stats,
)
for pipeline_run in pipeline_runs
],
next_page_token=next_page_token,
)
def _create_pipeline_run_response(
self,
*,
session: orm.Session,
pipeline_run: bts.PipelineRun,
include_pipeline_names: bool,
include_execution_stats: bool,
) -> PipelineRunResponse:
response = PipelineRunResponse.from_db(pipeline_run)
if include_pipeline_names:
pipeline_name = None
extra_data = pipeline_run.extra_data or {}
if self._PIPELINE_NAME_EXTRA_DATA_KEY in extra_data:
pipeline_name = extra_data[self._PIPELINE_NAME_EXTRA_DATA_KEY]
else:
execution_node = session.get(
bts.ExecutionNode, pipeline_run.root_execution_id
)
if execution_node:
task_spec = structures.TaskSpec.from_json_dict(
execution_node.task_spec
)
component_spec = task_spec.component_ref.spec
if component_spec:
pipeline_name = component_spec.name
response.pipeline_name = pipeline_name
if include_execution_stats:
execution_status_stats = self._calculate_execution_status_stats(
session=session, root_execution_id=pipeline_run.root_execution_id
)
response.execution_status_stats = {
status.value: count for status, count in execution_status_stats.items()
}
return response
def _calculate_execution_status_stats(
self, session: orm.Session, root_execution_id: bts.IdType
) -> dict[bts.ContainerExecutionStatus, int]:
query = (
sql.select(
bts.ExecutionNode.container_execution_status,
sql.func.count().label("count"),
)
.join(
bts.ExecutionToAncestorExecutionLink,
bts.ExecutionToAncestorExecutionLink.execution_id
== bts.ExecutionNode.id,
)
.where(
bts.ExecutionToAncestorExecutionLink.ancestor_execution_id
== root_execution_id
)
.where(bts.ExecutionNode.container_execution_status != None)
.group_by(
bts.ExecutionNode.container_execution_status,
)
)
execution_status_stat_rows = session.execute(query).tuples().all()
execution_status_stats = dict(execution_status_stat_rows)
return execution_status_stats
def list_annotations(
self,
*,
session: orm.Session,
id: bts.IdType,
) -> dict[str, str | None]:
# pipeline_run = session.get(bts.PipelineRun, id)
# if not pipeline_run:
# raise ItemNotFoundError(f"Pipeline run {id} not found.")
annotations = {
ann.key: ann.value
for ann in session.scalars(
sql.select(bts.PipelineRunAnnotation).where(
bts.PipelineRunAnnotation.pipeline_run_id == id
)
)
}
return annotations
def set_annotation(
self,
*,
session: orm.Session,
id: bts.IdType,
key: str,
value: str | None = None,
user_name: str | None = None,
skip_user_check: bool = False,
):
self._fail_if_changing_system_annotation(key=key)
pipeline_run = session.get(bts.PipelineRun, id)
if not pipeline_run:
raise errors.ItemNotFoundError(f"Pipeline run {id} not found.")
if not skip_user_check and (user_name != pipeline_run.created_by):
raise errors.PermissionError(
f"The pipeline run {id} was started by {pipeline_run.created_by} and cannot be changed by {user_name}"
)
pipeline_run_annotation = bts.PipelineRunAnnotation(
pipeline_run_id=id, key=key, value=value
)
session.merge(pipeline_run_annotation)
session.commit()
def delete_annotation(
self,
*,
session: orm.Session,
id: bts.IdType,
key: str,
user_name: str | None = None,
skip_user_check: bool = False,
):
self._fail_if_changing_system_annotation(key=key)
pipeline_run = session.get(bts.PipelineRun, id)
if not pipeline_run:
raise errors.ItemNotFoundError(f"Pipeline run {id} not found.")
if not skip_user_check and (user_name != pipeline_run.created_by):
raise errors.PermissionError(
f"The pipeline run {id} was started by {pipeline_run.created_by} and cannot be changed by {user_name}"
)
existing_annotation = session.get(bts.PipelineRunAnnotation, (id, key))
session.delete(existing_annotation)
session.commit()
# ========== ExecutionNodeApiService_Sql
# TODO: Use _storage_provider.calculate_hash(path)
# Hashing of constant arguments should the use same algorithm as caching of the output artifacts.
def _calculate_hash(s: str) -> str:
import hashlib
return "md5=" + hashlib.md5(s.encode("utf-8")).hexdigest()
def _split_type_spec(
type_spec: structures.TypeSpecType | None,
) -> typing.Tuple[str | None, dict[str, Any] | None]:
if type_spec is None:
return None, None
if isinstance(type_spec, str):
return type_spec, None
if isinstance(type_spec, typing.Mapping):
kv_pairs = list(type_spec.items())
if len(kv_pairs) == 1:
type_name, type_properties = kv_pairs[1]
if isinstance(type_name, str) and isinstance(
type_properties, typing.Mapping
):
return type_name, dict(type_properties)
raise TypeError(f"Unsupported kind of type spec: {type_spec}")
# def _construct_constant_data_info(value: str) -> DataInfo:
# return DataInfo(
# total_size=len(value),
# is_dir=False,
# hash=_calculate_hash(value),
# )
def _construct_constant_artifact_data(value: str) -> bts.ArtifactData:
# FIX: !!!
# raise NotImplementedError("MUST insert into session. Need to de-duplicate")
artifact_data = bts.ArtifactData(
total_size=len(value),
is_dir=False,
hash=_calculate_hash(value),
value=value,
created_at=_get_current_time(),
)
return artifact_data
def _construct_constant_artifact_node(
value: str,
artifact_type: structures.TypeSpecType | None = None,
):
type_name, type_properties = _split_type_spec(artifact_type)
artifact_node = bts.ArtifactNode(
type_name=type_name,
type_properties=type_properties,
artifact_data=_construct_constant_artifact_data(value=value),
had_data_in_past=True,
)
return artifact_node
def _construct_constant_artifact_node_and_add_to_session(
session: orm.Session,
value: str,
artifact_type: structures.TypeSpecType | None = None,
):
# FIX: !!!
# raise NotImplementedError("MUST insert into session. Need to de-duplicate")
artifact_node = _construct_constant_artifact_node(
value=value, artifact_type=artifact_type
)
session.add(artifact_node.artifact_data)
session.add(artifact_node)
return artifact_node
# ? Do we need an association table between PipelineJob and ExecutionNode
# ============
@dataclasses.dataclass(kw_only=True)
class GetExecutionInfoResponse:
id: bts.IdType
task_spec: structures.TaskSpec
parent_execution_id: bts.IdType | None = None
child_task_execution_ids: dict[str, bts.IdType]
pipeline_run_id: bts.IdType | None = None
# ancestor_breadcrumbs: list[tuple[str, str]]
input_artifacts: dict[str, "ArtifactNodeIdResponse"] | None = None
output_artifacts: dict[str, "ArtifactNodeIdResponse"] | None = None
@dataclasses.dataclass
class ArtifactNodeIdResponse:
id: bts.IdType
@dataclasses.dataclass(kw_only=True)
class ExecutionStatusSummary:
total_executions: int = 0
ended_executions: int = 0
has_ended: bool = False
def count_execution_status(
self, *, status: bts.ContainerExecutionStatus, count: int
) -> None:
self.total_executions += count
if status in bts.CONTAINER_STATUSES_ENDED:
self.ended_executions += count
self.has_ended = self.ended_executions == self.total_executions
@dataclasses.dataclass
class GetGraphExecutionStateResponse:
child_execution_status_stats: dict[bts.IdType, dict[str, int]]
pass
@dataclasses.dataclass(kw_only=True)
class GetExecutionArtifactsResponse:
input_artifacts: dict[str, "ArtifactNodeResponse"] | None = None
output_artifacts: dict[str, "ArtifactNodeResponse"] | None = None
@dataclasses.dataclass
class GetContainerExecutionStateResponse:
status: bts.ContainerExecutionStatus
exit_code: int | None = None
started_at: datetime.datetime | None = None
ended_at: datetime.datetime | None = None
debug_info: dict | None = None
@dataclasses.dataclass(kw_only=True)
class GetContainerExecutionLogResponse:
log_text: str | None = None
system_error_exception_full: str | None = None
orchestration_error_message: str | None = None
class ExecutionNodesApiService_Sql:
def get(self, session: orm.Session, id: bts.IdType) -> GetExecutionInfoResponse:
execution_node = session.get(bts.ExecutionNode, id)
if execution_node is None:
raise errors.ItemNotFoundError(f"Execution with {id=} does not exist.")
parent_pipeline_run_id = session.scalar(
sql.select(bts.PipelineRun.id).where(
bts.PipelineRun.root_execution_id == id
)
)
ancestor_pipeline_run_id = session.scalar(
sql.select(bts.PipelineRun.id)
.join(
bts.ExecutionToAncestorExecutionLink,
bts.ExecutionToAncestorExecutionLink.ancestor_execution_id
== bts.PipelineRun.root_execution_id,
)
.where(bts.ExecutionToAncestorExecutionLink.execution_id == id)
)
pipeline_run_id = parent_pipeline_run_id or ancestor_pipeline_run_id
child_executions = execution_node.child_executions
child_task_execution_ids = {
child_execution.task_id_in_parent_execution
or "<missing>": child_execution.id
for child_execution in child_executions
}
input_artifacts = {
input_name: ArtifactNodeIdResponse(id=artifact_id)
for input_name, artifact_id in session.execute(
sql.select(
bts.InputArtifactLink.input_name, bts.InputArtifactLink.artifact_id
).where(bts.InputArtifactLink.execution_id == id)
).tuples()
}
output_artifacts = {
output_name: ArtifactNodeIdResponse(id=artifact_id)
for output_name, artifact_id in session.execute(
sql.select(
bts.OutputArtifactLink.output_name,
bts.OutputArtifactLink.artifact_id,
).where(bts.OutputArtifactLink.execution_id == id)
).tuples()
}
return GetExecutionInfoResponse(
id=execution_node.id,
task_spec=structures.TaskSpec.from_json_dict(execution_node.task_spec),
parent_execution_id=execution_node.parent_execution_id,
pipeline_run_id=pipeline_run_id,
child_task_execution_ids=child_task_execution_ids,
input_artifacts=input_artifacts,
output_artifacts=output_artifacts,
)
def get_graph_execution_state(
self, session: orm.Session, id: bts.IdType
) -> GetGraphExecutionStateResponse:
ExecutionNode_Child = orm.aliased(
bts.ExecutionNode, name="child_execution_node"
)
ExecutionNode_Descendant = orm.aliased(
bts.ExecutionNode, name="descendant_execution_node"
)
# # We cannot use this query since ContainerExecution do not exist
# # for not yet started container execution nodes.
# query = (
# sql.select(
# ExecutionNode_Child.id.label("child_execution_id"),
# bts.ContainerExecution.status,
# sql.func.count().label("count"),
# )
# .where(ExecutionNode_Child.parent_execution_id == id)
# .join(
# bts.ExecutionToAncestorExecutionLink,
# bts.ExecutionToAncestorExecutionLink.ancestor_execution_id
# == ExecutionNode_Child.id,
# )
# .join(
# ExecutionNode_Descendant,
# ExecutionNode_Descendant.id
# == bts.ExecutionToAncestorExecutionLink.execution_id,
# )
# .join(
# bts.ContainerExecution,
# bts.ContainerExecution.id
# == ExecutionNode_Descendant.container_execution_id,
# )
# .group_by(
# ExecutionNode_Child.id,
# bts.ContainerExecution.status,
# )
# )
child_descendants_query = (
sql.select(
ExecutionNode_Child.id.label("child_execution_id"),
ExecutionNode_Descendant.container_execution_status,
sql.func.count().label("count"),
)
.where(ExecutionNode_Child.parent_execution_id == id)
.join(
bts.ExecutionToAncestorExecutionLink,
bts.ExecutionToAncestorExecutionLink.ancestor_execution_id
== ExecutionNode_Child.id,
)
.join(
ExecutionNode_Descendant,
ExecutionNode_Descendant.id
== bts.ExecutionToAncestorExecutionLink.execution_id,
)
.where(ExecutionNode_Descendant.container_execution_status != None)
.group_by(
ExecutionNode_Child.id,
ExecutionNode_Descendant.container_execution_status,
)
)
direct_container_children_query = (
sql.select(
ExecutionNode_Child.id.label("child_execution_id"),
ExecutionNode_Child.container_execution_status,
sql.func.count().label("count"),
)
.where(ExecutionNode_Child.parent_execution_id == id)
.where(ExecutionNode_Child.container_execution_status != None)
.group_by(
ExecutionNode_Child.id,
ExecutionNode_Child.container_execution_status,
)
)
child_descendants_execution_stat_rows = session.execute(
child_descendants_query
).all()
child_container_execution_stat_rows = session.execute(
direct_container_children_query
).all()
child_execution_stat_rows = tuple(
child_descendants_execution_stat_rows
) + tuple(child_container_execution_stat_rows)
child_execution_status_stats: dict[bts.IdType, dict[str, int]] = {}
for row in child_execution_stat_rows:
child_execution_id, status, count = row.tuple()
status_stats = child_execution_status_stats.setdefault(
child_execution_id, {}
)
status_stats[status.value] = count
return GetGraphExecutionStateResponse(
child_execution_status_stats=child_execution_status_stats,
)
def get_container_execution_state(
self, session: orm.Session, id: bts.IdType
) -> GetContainerExecutionStateResponse:
execution = session.get(bts.ExecutionNode, id)
if not execution:
raise errors.ItemNotFoundError(f"Execution with {id=} does not exist.")
container_execution = execution.container_execution
if not container_execution:
raise RuntimeError(
f"Execution with {id=} does not have container execution information."
)
return GetContainerExecutionStateResponse(
status=container_execution.status,
exit_code=container_execution.exit_code,
started_at=container_execution.started_at,
ended_at=container_execution.ended_at,
debug_info=container_execution.launcher_data,
)
def get_artifacts(
self, session: orm.Session, id: bts.IdType
) -> GetExecutionArtifactsResponse:
if not session.scalar(
sql.select(sql.exists().where(bts.ExecutionNode.id == id))
):
raise errors.ItemNotFoundError(f"Execution with {id=} does not exist.")
input_artifact_links = session.scalars(
sql.select(bts.InputArtifactLink)
.where(bts.InputArtifactLink.execution_id == id)
.options(
orm.joinedload(bts.InputArtifactLink.artifact).joinedload(
bts.ArtifactNode.artifact_data
)
)
)
output_artifact_links = session.scalars(
sql.select(bts.OutputArtifactLink)
.where(bts.OutputArtifactLink.execution_id == id)
.options(
orm.joinedload(bts.OutputArtifactLink.artifact).joinedload(
bts.ArtifactNode.artifact_data
)
)
)
input_artifacts = {
input_artifact_link.input_name: ArtifactNodeResponse.from_db(
input_artifact_link.artifact
)
for input_artifact_link in input_artifact_links
}
output_artifacts = {
output_artifact_link.output_name: ArtifactNodeResponse.from_db(
output_artifact_link.artifact
)
for output_artifact_link in output_artifact_links
}
return GetExecutionArtifactsResponse(
input_artifacts=input_artifacts,
output_artifacts=output_artifacts,
)
def get_container_execution_log(
self,
session: orm.Session,
id: bts.IdType,
container_launcher: "launcher_interfaces.ContainerTaskLauncher[launcher_interfaces.LaunchedContainer] | None" = None,
) -> GetContainerExecutionLogResponse:
execution = session.get(bts.ExecutionNode, id)
if not execution:
raise errors.ItemNotFoundError(f"Execution with {id=} does not exist.")
container_execution = execution.container_execution
execution_extra_data = execution.extra_data or {}
system_error_exception_full = execution_extra_data.get(
bts.EXECUTION_NODE_EXTRA_DATA_SYSTEM_ERROR_EXCEPTION_FULL_KEY
)
orchestration_error_message = execution_extra_data.get(
bts.EXECUTION_NODE_EXTRA_DATA_ORCHESTRATION_ERROR_MESSAGE_KEY
)
# Temporarily putting the orchestration error into the system error field for compatibility.
system_error_exception_full = (
system_error_exception_full or orchestration_error_message
)
if not container_execution:
if (
execution.container_execution_status
== bts.ContainerExecutionStatus.SYSTEM_ERROR
):
return GetContainerExecutionLogResponse(
system_error_exception_full=system_error_exception_full,
orchestration_error_message=orchestration_error_message,
)
raise RuntimeError(
f"Execution with {id=} does not have container execution information."
)
log_text: str | None = None
if container_execution.status in (
bts.ContainerExecutionStatus.SUCCEEDED,
bts.ContainerExecutionStatus.FAILED,
bts.ContainerExecutionStatus.SYSTEM_ERROR,
):
try:
# Returning completed log
if not container_execution.log_uri:
raise RuntimeError(
f"Container execution {container_execution.id=} does not have log_uri. Impossible."
)
# TODO: Make the ContainerLauncher._storage_provider part of the public interface or create a better solution for log retrieval
# Try getting the configured storage provider from the launcher so that it has correct access credentials.
storage_provider = (
getattr(container_launcher, "_storage_provider", None)
if container_launcher
else None
)
log_text = _read_container_execution_log_from_uri(
log_uri=container_execution.log_uri,
storage_provider=storage_provider,
)
except:
# Do not raise exception if the execution is in SYSTEM_ERROR state
# We want to return the system error exception.
if (
container_execution.status
!= bts.ContainerExecutionStatus.SYSTEM_ERROR
):
raise
elif container_execution.status == bts.ContainerExecutionStatus.RUNNING:
if not container_launcher:
raise ApiServiceError(
f"Reading log of an unfinished container requires `container_launcher`."
)
if not container_execution.launcher_data:
raise ApiServiceError(
f"Execution does not have container launcher data."
)
launched_container = (
container_launcher.deserialize_launched_container_from_dict(
container_execution.launcher_data
)
)
log_text = launched_container.get_log()
return GetContainerExecutionLogResponse(
log_text=log_text,
system_error_exception_full=system_error_exception_full,
orchestration_error_message=orchestration_error_message,
)
def stream_container_execution_log(
self,
session: orm.Session,
container_launcher: "launcher_interfaces.ContainerTaskLauncher[launcher_interfaces.LaunchedContainer]",
execution_id: bts.IdType,
) -> typing.Iterator[str]:
execution = session.get(bts.ExecutionNode, execution_id)
if not execution:
raise errors.ItemNotFoundError(
f"Execution with {execution_id=} does not exist."
)
container_execution = execution.container_execution
if not container_execution:
raise ApiServiceError(
f"Execution does not have container execution information."
)
if not container_execution.launcher_data:
raise ApiServiceError(
f"Execution does not have container launcher information."
)
if container_execution.status == bts.ContainerExecutionStatus.RUNNING:
launched_container = (
container_launcher.deserialize_launched_container_from_dict(
container_execution.launcher_data
)
)
return launched_container.stream_log_lines()
else:
if not container_execution.log_uri:
raise RuntimeError(
f"Container execution {container_execution.id=} does not have log_uri. Impossible."
)
# TODO: Make the ContainerLauncher._storage_provider part of the public interface or create a better solution for log retrieval
# Try getting the configured storage provider from the launcher so that it has correct access credentials.
storage_provider = (
getattr(container_launcher, "_storage_provider", None)
if container_launcher
else None
)
log_text = _read_container_execution_log_from_uri(
log_uri=container_execution.log_uri,
storage_provider=storage_provider,
)
return (line + "\n" for line in log_text.split("\n"))
def _read_container_execution_log_from_uri(
log_uri: str,
storage_provider: "storage_provider_interfaces.StorageProvider | None" = None,
) -> str:
if ".." in log_uri:
raise ValueError(
f"_read_container_execution_log_from_uri: log_uri contains '..': {log_uri=}"
)
if storage_provider:
# TODO: Switch to storage_provider.parse_uri_get_accessor
uri_accessor = storage_provider.make_uri(log_uri)
log_text = uri_accessor.get_reader().download_as_text()
return log_text
if "://" not in log_uri:
# Consider the URL to be an absolute local path (`/path` or `C:\path` or `C:/path`)
with open(log_uri, "r") as reader:
return reader.read()
elif log_uri.startswith("gs://"):
# TODO: Switch to using storage providers.
from google.cloud import storage
gcs_client = storage.Client()
blob = storage.Blob.from_string(log_uri, client=gcs_client)
log_text = blob.download_as_text()
return log_text
elif log_uri.startswith("hf://"):
from cloud_pipelines_backend.storage_providers import huggingface_repo_storage
storage_provider = huggingface_repo_storage.HuggingFaceRepoStorageProvider()
uri_accessor = storage_provider.parse_uri_get_accessor(uri_string=log_uri)
log_text = uri_accessor.get_reader().download_as_text()
return log_text
else:
raise NotImplementedError(
f"Only logs in local storage or Google Cloud Storage are supported. But got {log_uri=}."
)
@dataclasses.dataclass(kw_only=True)
class ArtifactNodeResponse:
id: bts.IdType
# had_data_in_past: bool = False
# may_have_data_in_future: bool = True
type_name: str | None = None
type_properties: dict[str, Any] | None = None
producer_execution_id: bts.IdType | None = None
producer_output_name: str | None = None
# artifact_data_id: bts.IdType | None = None
artifact_data: "ArtifactDataResponse | None" = None
@classmethod
def from_db(cls, artifact_node: bts.ArtifactNode) -> "ArtifactNodeResponse":
result = ArtifactNodeResponse(
**{
field.name: getattr(artifact_node, field.name)
for field in dataclasses.fields(ArtifactNodeResponse)
}
)
if artifact_node.artifact_data:
result.artifact_data = ArtifactDataResponse.from_db(
artifact_data=artifact_node.artifact_data
)
return result
@dataclasses.dataclass(kw_only=True)
class ArtifactDataResponse:
total_size: int
is_dir: bool
# hash: str
# At least one of `uri` or `value` must be set
uri: str | None = None
# Small constant value
value: str | None = None
# created_at: datetime.datetime | None = None
# deleted_at: datetime.datetime | None = None
@classmethod
def from_db(cls, artifact_data: bts.ArtifactData) -> "ArtifactDataResponse":
return ArtifactDataResponse(
**{
field.name: getattr(artifact_data, field.name)
for field in dataclasses.fields(ArtifactDataResponse)
}
)
@dataclasses.dataclass(kw_only=True)
class GetArtifactInfoResponse:
id: bts.IdType
artifact_data: bts.ArtifactData | None = None
@dataclasses.dataclass(kw_only=True)
class GetArtifactSignedUrlResponse:
signed_url: str
class ArtifactNodesApiService_Sql:
def get(self, session: orm.Session, id: bts.IdType) -> GetArtifactInfoResponse:
artifact_node = session.get(bts.ArtifactNode, id)
if artifact_node is None:
raise errors.ItemNotFoundError(f"Artifact with {id=} does not exist.")
artifact_data = artifact_node.artifact_data
result = GetArtifactInfoResponse(id=artifact_node.id)
if artifact_data:
result.artifact_data = artifact_data
return result
def get_signed_artifact_url(
self, session: orm.Session, id: bts.IdType
) -> GetArtifactSignedUrlResponse:
artifact_data = session.scalar(
sql.select(bts.ArtifactData)
.join(bts.ArtifactNode)
.where(bts.ArtifactNode.id == id)
)
if not artifact_data:
raise errors.ItemNotFoundError(f"Artifact node with {id=} does not exist.")
if not artifact_data.uri:
raise ValueError(f"Artifact node with {id=} does not have artifact URI.")
if artifact_data.is_dir:
raise ValueError(f"Cannot generate signer URL for a directory artifact.")
if not artifact_data.uri.startswith("gs://"):
raise ValueError(
f"The get_signed_artifact_url method only supports Google Cloud Storage URIs, but got {artifact_data.uri=}."
)
from google.cloud import storage
from google import auth
# Avoiding error: "you need a private key to sign credentials."
# "the credentials you are currently using <class 'google.auth.compute_engine.credentials.Credentials'> just contains a token.
# "see https://googleapis.dev/python/google-api-core/latest/auth.html#setting-up-a-service-account for more details."
credentials = auth.default(
scopes=["https://www.googleapis.com/auth/cloud-platform.read-only"]
)[0]
storage_client = storage.Client(credentials=credentials)
blob = storage.Blob.from_string(uri=artifact_data.uri, client=storage_client)
signed_url = blob.generate_signed_url(
# Expiration is required. Max expiration value is 7 days.
expiration=datetime.timedelta(days=7)
)
return GetArtifactSignedUrlResponse(signed_url=signed_url)
# === Secrets Service
@dataclasses.dataclass(kw_only=True)