forked from kubeflow/kfp-tekton
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcompiler.py
More file actions
1888 lines (1729 loc) · 89.3 KB
/
compiler.py
File metadata and controls
1888 lines (1729 loc) · 89.3 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
# Copyright 2019-2021 kubeflow.org.
#
# 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.
import ast
import inspect
import json
import os
import re
import tarfile
import textwrap
import uuid
import zipfile
import copy
from collections import defaultdict
from distutils.util import strtobool
import collections
from os import environ as env
from typing import Callable, List, Text, Dict, Any
import hashlib
import yaml
# Kubeflow Pipeline imports
from kfp import dsl
from kfp.compiler._default_transformers import add_pod_env
from kfp.compiler.compiler import Compiler
from kfp.components.structures import InputSpec
from kfp.dsl._for_loop import LoopArguments
from kfp.dsl._metadata import _extract_pipeline_metadata
# KFP-Tekton imports
from kfp_tekton.compiler import __tekton_api_version__ as tekton_api_version
from kfp_tekton.compiler._data_passing_rewriter import fix_big_data_passing, BIG_DATA_PATH_FORMAT
from kfp_tekton.compiler._k8s_helper import convert_k8s_obj_to_json, sanitize_k8s_name, sanitize_k8s_object
from kfp_tekton.compiler._op_to_template import _op_to_template
from kfp_tekton.compiler._tekton_handler import _handle_tekton_pipeline_variables, _handle_tekton_custom_task, _process_argo_vars
from kfp_tekton.compiler.pipeline_utils import TektonPipelineConf
from kfp_tekton.compiler.yaml_utils import dump_yaml
from kfp_tekton.tekton import TEKTON_CUSTOM_TASK_IMAGES, DEFAULT_CONDITION_OUTPUT_KEYWORD, \
LOOP_PIPELINE_NAME_LENGTH, LOOP_GROUP_NAME_LENGTH, AddOnGroup
DEFAULT_ARTIFACT_BUCKET = env.get('DEFAULT_ARTIFACT_BUCKET', 'mlpipeline')
DEFAULT_ARTIFACT_ENDPOINT = env.get('DEFAULT_ARTIFACT_ENDPOINT', 'minio-service.kubeflow:9000')
DEFAULT_ARTIFACT_ENDPOINT_SCHEME = env.get('DEFAULT_ARTIFACT_ENDPOINT_SCHEME', 'http://')
TEKTON_GLOBAL_DEFAULT_TIMEOUT = strtobool(env.get('TEKTON_GLOBAL_DEFAULT_TIMEOUT', 'false'))
# DISABLE_CEL_CONDITION should be True until CEL is officially merged into Tekton main API.
DISABLE_CEL_CONDITION = True
# Default timeout is one year
DEFAULT_TIMEOUT_MINUTES = "525600m"
def _get_super_condition_template():
python_script = textwrap.dedent('''\
'import sys
input1=str.rstrip(sys.argv[1])
input2=str.rstrip(sys.argv[2])
try:
input1=int(input1)
input2=int(input2)
except:
input1=str(input1)
%(s)s="true" if (input1 $(inputs.params.operator) input2) else "false"
f = open("/tekton/results/%(s)s", "w")
f.write(%(s)s)
f.close()' '''
% {'s': DEFAULT_CONDITION_OUTPUT_KEYWORD})
template = {
'results': [
{'name': DEFAULT_CONDITION_OUTPUT_KEYWORD,
'description': 'Conditional task %s' % DEFAULT_CONDITION_OUTPUT_KEYWORD
}
],
'params': [
{'name': 'operand1'},
{'name': 'operand2'},
{'name': 'operator'}
],
'steps': [{
'script': 'python -c ' + python_script + "'$(inputs.params.operand1)' '$(inputs.params.operand2)'",
'image': 'python:alpine3.6',
}]
}
return template
def _get_cel_condition_template():
template = {
"name": "cel_condition",
"apiVersion": "cel.tekton.dev/v1alpha1",
"kind": "CEL"
}
return template
class TektonCompiler(Compiler):
"""DSL Compiler to generate Tekton YAML.
It compiles DSL pipeline functions into workflow yaml. Example usage:
```python
@dsl.pipeline(
name='name',
description='description'
)
def my_pipeline(a: int = 1, b: str = "default value"):
...
TektonCompiler().compile(my_pipeline, 'path/to/workflow.yaml')
```
"""
def __init__(self, **kwargs):
# Input and output artifacts are hash maps for metadata tracking.
# artifact_items is the artifact dependency map
# loops_pipeline recorde the loop tasks information for each loops
# produce_taskspec Produces task spec as part of Tekton pipelineRuns
self.input_artifacts = {}
self.output_artifacts = {}
self.artifact_items = {}
self.loops_pipeline = {}
self.addon_groups = {}
self.recursive_tasks = []
self.custom_task_crs = []
self.uuid = self._get_unique_id_code()
self._group_names = []
self.pipeline_labels = {}
self.pipeline_annotations = {}
self.tekton_inline_spec = True
self.resource_in_separate_yaml = False
self.produce_taskspec = True
self.security_context = None
self.automount_service_account_token = None
super().__init__(**kwargs)
def _set_pipeline_conf(self, tekton_pipeline_conf: TektonPipelineConf):
self.pipeline_labels = tekton_pipeline_conf.pipeline_labels
self.pipeline_annotations = tekton_pipeline_conf.pipeline_annotations
self.tekton_inline_spec = tekton_pipeline_conf.tekton_inline_spec
self.resource_in_separate_yaml = tekton_pipeline_conf.resource_in_separate_yaml
self.security_context = tekton_pipeline_conf.security_context
self.automount_service_account_token = tekton_pipeline_conf.automount_service_account_token
def _resolve_value_or_reference(self, value_or_reference, potential_references):
"""_resolve_value_or_reference resolves values and PipelineParams, which could be task parameters or input parameters.
Args:
value_or_reference: value or reference to be resolved. It could be basic python types or PipelineParam
potential_references(dict{str->str}): a dictionary of parameter names to task names
"""
if isinstance(value_or_reference, dsl.PipelineParam):
parameter_name = value_or_reference.full_name
task_names = [task_name for param_name, task_name in potential_references if param_name == parameter_name]
if task_names:
task_name = task_names[0]
# When the task_name is None, the parameter comes directly from ancient ancesters
# instead of parents. Thus, it is resolved as the input parameter in the current group.
if task_name is None:
return '$(params.%s)' % parameter_name
else:
return '$(params.%s)' % task_name
else:
return '$(params.%s)' % parameter_name
else:
return str(value_or_reference)
def _get_groups(self, root_group):
"""Helper function to get all groups (not including ops) in a pipeline."""
def _get_groups_helper(group):
groups = {group.name: group}
for g in group.groups:
groups.update(_get_groups_helper(g))
return groups
return _get_groups_helper(root_group)
@staticmethod
def _get_unique_id_code():
return uuid.uuid4().hex[:5]
def _group_to_dag_template(self, group, inputs, outputs, dependencies, pipeline_name, group_type, opsgroups):
"""Generate template given an OpsGroup.
inputs, outputs, dependencies are all helper dicts.
"""
# Generate GroupOp template
sub_group = group
# For loop and recursion id appends 5 characters, so limit the loop/recusion pipeline_name to 44 char and group_name to 12
# Group_name is truncated reversely because it has an unique identifier at the end of the name.
pipeline_name_copy = sanitize_k8s_name(pipeline_name, max_length=LOOP_PIPELINE_NAME_LENGTH)
sub_group_name_copy = sanitize_k8s_name(sub_group.name, max_length=LOOP_GROUP_NAME_LENGTH, rev_truncate=True)
self._group_names = [pipeline_name_copy, sub_group_name_copy]
if self.uuid:
self._group_names.insert(1, self.uuid)
# pipeline name (max 40) + loop id (max 5) + group name (max 16) + two connecting dashes (2) = 63 (Max size for CRD names)
group_name = '-'.join(self._group_names) if group_type == "loop" or \
group_type == "graph" or group_type == 'addon' else sub_group.name
template = {
'metadata': {
'name': group_name,
},
'spec': {}
}
# Generates a pseudo-template unique to conditions due to the catalog condition approach
# where every condition is an extension of one super-condition
if isinstance(sub_group, dsl.OpsGroup) and sub_group.type == 'condition':
subgroup_inputs = inputs.get(group_name, [])
condition = sub_group.condition
operand1_value = self._resolve_value_or_reference(condition.operand1, subgroup_inputs)
operand2_value = self._resolve_value_or_reference(condition.operand2, subgroup_inputs)
template['kind'] = 'Condition'
template['spec']['params'] = [
{'name': 'operand1', 'value': operand1_value, 'type': type(condition.operand1),
'op_name': getattr(condition.operand1, 'op_name', ''), 'output_name': getattr(condition.operand1, 'name', '')},
{'name': 'operand2', 'value': operand2_value, 'type': type(condition.operand2),
'op_name': getattr(condition.operand2, 'op_name', ''), 'output_name': getattr(condition.operand2, 'name', '')},
{'name': 'operator', 'value': str(condition.operator), 'type': type(condition.operator)}
]
# dsl does not expose Graph so here use sub_group.type to check whether it's graph
if sub_group.type == "graph":
# for graph now we just support as a pipeline loop with just 1 iteration
loop_args_name = "just_one_iteration"
loop_args_value = ["1"]
# Special handling for recursive subgroup
if sub_group.recursive_ref:
# generate ref graph name
sub_group_recursive_name_copy = sanitize_k8s_name(sub_group.recursive_ref.name,
max_length=LOOP_GROUP_NAME_LENGTH, rev_truncate=True)
tmp_group_names = [pipeline_name_copy, sub_group_recursive_name_copy]
if self.uuid:
tmp_group_names.insert(1, self.uuid)
ref_group_name = '-'.join(tmp_group_names)
# generate params
params = [{
"name": loop_args_name,
"value": loop_args_value
}]
# get other input params, for recursion need rename the param name to the refrenced one
for i in range(len(sub_group.inputs)):
g_input = sub_group.inputs[i]
inputRef = sub_group.recursive_ref.inputs[i]
if g_input.op_name:
params.append({
'name': inputRef.full_name,
'value': '$(tasks.%s.results.%s)' % (g_input.op_name, g_input.name)
})
else:
params.append({
'name': inputRef.full_name, 'value': '$(params.%s)' % g_input.name
})
self.recursive_tasks.append({
'name': sub_group.name,
'taskRef': {
'apiVersion': 'custom.tekton.dev/v1alpha1',
'kind': 'PipelineLoop',
'name': ref_group_name
},
'params': params
})
# normal graph logic start from here
else:
self.loops_pipeline[group_name] = {
'kind': 'loops',
'loop_args': loop_args_name,
'loop_sub_args': [],
'task_list': [],
'spec': {},
'depends': []
}
# get the dependencies tasks rely on the loop task.
for depend in dependencies.keys():
if depend == sub_group.name:
self.loops_pipeline[group_name]['spec']['runAfter'] = [task for task in dependencies[depend]]
self.loops_pipeline[group_name]['spec']['runAfter'].sort()
# for items depend on the graph, it will be handled in custom task handler
if sub_group.name in dependencies[depend]:
dependencies[depend].remove(sub_group.name)
self.loops_pipeline[group_name]['depends'].append({'org': depend, 'runAfter': group_name})
for op in sub_group.groups + sub_group.ops:
self.loops_pipeline[group_name]['task_list'].append(sanitize_k8s_name(op.name))
if hasattr(op, 'type') and op.type == 'condition':
if op.ops:
for condition_op in op.ops:
self.loops_pipeline[group_name]['task_list'].append(sanitize_k8s_name(condition_op.name))
if op.groups:
for condition_op in op.groups:
self.loops_pipeline[group_name]['task_list'].append(sanitize_k8s_name(condition_op.name))
self.loops_pipeline[group_name]['spec']['name'] = group_name
self.loops_pipeline[group_name]['spec']['taskRef'] = {
"apiVersion": "custom.tekton.dev/v1alpha1",
"kind": "PipelineLoop",
"name": group_name
}
self.loops_pipeline[group_name]['spec']['params'] = [{
"name": loop_args_name,
"value": loop_args_value
}]
# get other input params
for input_ in inputs.keys():
if input_ == sub_group.name:
for param in inputs[input_]:
if param[1]:
replace_str = param[1] + '-'
self.loops_pipeline[group_name]['spec']['params'].append({
'name': param[0], 'value': '$(tasks.%s.results.%s)' % (
param[1], sanitize_k8s_name(param[0].replace(replace_str, '', 1))
)
})
if not param[1]:
self.loops_pipeline[group_name]['spec']['params'].append({
'name': param[0], 'value': '$(params.%s)' % param[0]
})
def dep_helper(custom_task, sub_group):
"""get the dependencies tasks rely on the custom_task."""
for depend in dependencies.keys():
if depend == sub_group.name:
custom_task['spec']['runAfter'] = [task for task in dependencies[depend]]
custom_task['spec']['runAfter'].sort()
if sub_group.name in dependencies[depend]:
custom_task['depends'].append({'org': depend, 'runAfter': group_name})
for op in sub_group.groups + sub_group.ops:
custom_task['task_list'].append(sanitize_k8s_name(op.name))
# Add all the condition nested ops into the pipeline loop sub-dag
nested_groups = []
if hasattr(op, 'type') and op.type == 'condition':
nested_groups.append(op.name)
if op.ops:
for condition_op in op.ops:
custom_task['task_list'].append(sanitize_k8s_name(condition_op.name))
# If the nested op is a condition, find all the ops groups that are under the condition block
# until it reaches the end of the graph.
while nested_groups:
nested_group = nested_groups.pop(0)
opsgroup = opsgroups.get(nested_group, None)
if opsgroup and isinstance(opsgroup, dsl.OpsGroup) and opsgroup.type == 'condition':
condi_sub_groups = opsgroup.groups + opsgroup.ops
for condi_sub_group in condi_sub_groups:
custom_task['task_list'].append(sanitize_k8s_name(condi_sub_group.name))
nested_groups.append(condi_sub_group.name)
def input_helper(custom_task, sub_group, param_list):
"""add param from inputs if input is not in param_list"""
if sub_group.name in inputs:
for param in inputs[sub_group.name]:
if param[1] and param[0] not in param_list:
replace_str = param[1] + '-'
custom_task['spec']['params'].append({
'name': param[0], 'value': '$(tasks.%s.results.%s)' % (
param[1], sanitize_k8s_name(param[0].replace(replace_str, '', 1))
)
})
if not param[1] and param[0] not in param_list:
custom_task['spec']['params'].append({
'name': param[0], 'value': '$(params.%s)' % param[0]
})
def process_pipelineparam(s):
if "{{pipelineparam" in s:
pipe_params = re.findall(r"{{pipelineparam:op=([^ \t\n,]*);name=([^ \t\n,]*)}}", s)
for pipe_param in pipe_params:
if pipe_param[0] == '':
s = s.replace("{{pipelineparam:op=%s;name=%s}}" % pipe_param, '$(params.%s)' % pipe_param[1])
else:
param_name = sanitize_k8s_name(pipe_param[1])
s = s.replace("{{pipelineparam:op=%s;name=%s}}" % pipe_param, '$(tasks.%s.results.%s)' % (
sanitize_k8s_name(pipe_param[0]),
param_name))
return s
if isinstance(sub_group, AddOnGroup):
params = []
for k, v in sub_group.params.items():
if isinstance(v, dsl.PipelineParam):
if v.op_name is None:
v = '$(params.%s)' % v.name
else:
param_name = sanitize_k8s_name(v.name)
v = '$(tasks.%s.results.%s)' % (
sanitize_k8s_name(v.op_name),
param_name)
else:
if isinstance(v, str):
v = process_pipelineparam(v)
else:
v = str(v)
params.append({'name': sanitize_k8s_name(k, True), 'value': v})
self.addon_groups[group_name] = {
'kind': 'addon',
'task_list': [],
'spec': {
'name': group_name,
'taskRef': {
'apiVersion': sub_group.api_version,
'kind': sub_group.kind,
'name': group_name,
},
'params': params,
},
'depends': [],
'_data': sub_group
}
dep_helper(self.addon_groups[group_name], sub_group)
input_helper(self.addon_groups[group_name], sub_group, sub_group.params)
if isinstance(sub_group, dsl.ParallelFor):
self.loops_pipeline[group_name] = {
'kind': 'loops',
'loop_args': sub_group.loop_args.full_name,
'loop_sub_args': [],
'task_list': [],
'spec': {},
'depends': []
}
if hasattr(sub_group, 'separator') and sub_group.separator is not None:
self.loops_pipeline[group_name]['separator'] = sub_group.separator.full_name
if hasattr(sub_group, 'start') and sub_group.start is not None:
self.loops_pipeline[group_name]['start'] = sub_group.start
self.loops_pipeline[group_name]['end'] = sub_group.end
self.loops_pipeline[group_name]['step'] = sub_group.step
if hasattr(sub_group, 'call_enumerate') and sub_group.call_enumerate and sub_group.iteration_number is not None:
self.loops_pipeline[group_name]['iteration_number'] = sub_group.iteration_number.full_name
for subvarName in sub_group.loop_args.referenced_subvar_names:
if subvarName != '__iter__':
self.loops_pipeline[group_name]['loop_sub_args'].append(sub_group.loop_args.full_name + '-subvar-' + subvarName)
if isinstance(sub_group.loop_args.items_or_pipeline_param, list) and isinstance(
sub_group.loop_args.items_or_pipeline_param[0], dict):
for key in sub_group.loop_args.items_or_pipeline_param[0]:
self.loops_pipeline[group_name]['loop_sub_args'].append(sub_group.loop_args.full_name + '-subvar-' + key)
# get the dependencies tasks rely on the loop task.
dep_helper(self.loops_pipeline[group_name], sub_group)
self.loops_pipeline[group_name]['spec']['name'] = group_name
self.loops_pipeline[group_name]['spec']['taskRef'] = {
"apiVersion": "custom.tekton.dev/v1alpha1",
"kind": "PipelineLoop",
"name": group_name
}
if sub_group.items_is_pipeline_param:
# these loop args are a 'dynamic param' rather than 'static param'.
# i.e., rather than a static list, they are either the output of another task or were input
# as global pipeline parameters
pipeline_param = sub_group.loop_args.items_or_pipeline_param
if pipeline_param.op_name is None:
withparam_value = '$(params.%s)' % pipeline_param.name
else:
param_name = sanitize_k8s_name(pipeline_param.name)
withparam_value = '$(tasks.%s.results.%s)' % (
sanitize_k8s_name(pipeline_param.op_name),
param_name)
self.loops_pipeline[group_name]['spec']['params'] = [{
"name": sub_group.loop_args.full_name,
"value": withparam_value
}]
elif hasattr(sub_group, 'items_is_string') and sub_group.items_is_string:
loop_args_str_value = sub_group.loop_args.to_str_for_task_yaml()
self.loops_pipeline[group_name]['spec']['params'] = [{
"name": sub_group.loop_args.full_name,
"value": loop_args_str_value
}]
else:
# Need to sanitize the dict keys for consistency.
loop_arg_value = sub_group.loop_args.to_list_for_task_yaml()
loop_args_str_value = ''
sanitized_tasks = []
if isinstance(loop_arg_value[0], dict):
for argument_set in loop_arg_value:
c_dict = {}
for k, v in argument_set.items():
if isinstance(v, dsl.PipelineParam):
if v.op_name is None:
v = '$(params.%s)' % v.name
else:
param_name = sanitize_k8s_name(v.name)
v = '$(tasks.%s.results.%s)' % (
sanitize_k8s_name(v.op_name),
param_name)
else:
if isinstance(v, str):
v = process_pipelineparam(v)
c_dict[sanitize_k8s_name(k, True)] = v
sanitized_tasks.append(c_dict)
loop_args_str_value = json.dumps(sanitized_tasks, sort_keys=True)
else:
for i, value in enumerate(loop_arg_value):
if isinstance(value, str):
loop_arg_value[i] = process_pipelineparam(value)
loop_args_str_value = json.dumps(loop_arg_value)
self.loops_pipeline[group_name]['spec']['params'] = [{
"name": sub_group.loop_args.full_name,
"value": loop_args_str_value
}]
# start, end, step params should be added as a parameter
# isinstance(sub_group.start, dsl.PipelineParam)
def process_parameter(parameter):
parameter_value = str(parameter)
if isinstance(parameter, dsl.PipelineParam):
if parameter.op_name:
parameter_value = '$(tasks.' + parameter.op_name + '.results.' + sanitize_k8s_name(parameter.name) + ')'
else:
parameter_value = '$(params.' + parameter.name + ')'
return parameter_value
if hasattr(sub_group, 'separator') and sub_group.separator is not None:
# separator should be added as a parameter
sep_param = {
"name": sub_group.separator.full_name,
"value": process_parameter(sub_group.separator.value)
}
self.loops_pipeline[group_name]['spec']['params'].append(sep_param)
if hasattr(sub_group, 'start') and sub_group.start is not None:
start_param = {
"name": 'from',
"value": process_parameter(sub_group.start)
}
self.loops_pipeline[group_name]['spec']['params'].append(start_param)
end_param = {
"name": 'to',
"value": process_parameter(sub_group.end)
}
self.loops_pipeline[group_name]['spec']['params'].append(end_param)
if sub_group.step is not None:
step_param = {
"name": 'step',
"value": process_parameter(sub_group.step)
}
self.loops_pipeline[group_name]['spec']['params'].append(step_param)
# get other input params
input_helper(self.loops_pipeline[group_name], sub_group,
self.loops_pipeline[group_name]['loop_sub_args'] + [sub_group.loop_args.full_name])
if sub_group.parallelism is not None:
self.loops_pipeline[group_name]['spec']['parallelism'] = sub_group.parallelism
return template
def _create_dag_templates(self, pipeline, op_transformers=None, params=None, op_to_templates_handler=None):
"""Create all groups and ops templates in the pipeline.
Args:
pipeline: Pipeline context object to get all the pipeline data from.
op_transformers: A list of functions that are applied to all ContainerOp instances that are being processed.
op_to_templates_handler: Handler which converts a base op into a list of argo templates.
"""
op_to_steps_handler = op_to_templates_handler or (lambda op: [_op_to_template(op,
self.output_artifacts,
self.artifact_items)])
root_group = pipeline.groups[0]
# Call the transformation functions before determining the inputs/outputs, otherwise
# the user would not be able to use pipeline parameters in the container definition
# (for example as pod labels) - the generated template is invalid.
for op in pipeline.ops.values():
for transformer in op_transformers or []:
transformer(op)
# Generate core data structures to prepare for argo yaml generation
# op_name_to_parent_groups: op name -> list of ancestor groups including the current op
# opsgroups: a dictionary of ospgroup.name -> opsgroup
# inputs, outputs: group/op names -> list of tuples (full_param_name, producing_op_name)
# condition_params: recursive_group/op names -> list of pipelineparam
# dependencies: group/op name -> list of dependent groups/ops.
# Special Handling for the recursive opsgroup
# op_name_to_parent_groups also contains the recursive opsgroups
# condition_params from _get_condition_params_for_ops also contains the recursive opsgroups
# groups does not include the recursive opsgroups
opsgroups = self._get_groups(root_group)
op_name_to_parent_groups = self._get_groups_for_ops(root_group)
opgroup_name_to_parent_groups = self._get_groups_for_opsgroups(root_group)
condition_params = self._get_condition_params_for_ops(root_group)
op_name_to_for_loop_op = self._get_for_loop_ops(root_group)
inputs, outputs = self._get_inputs_outputs(
pipeline,
root_group,
op_name_to_parent_groups,
opgroup_name_to_parent_groups,
condition_params,
op_name_to_for_loop_op,
opsgroups
)
dependencies = self._get_dependencies(
pipeline,
root_group,
op_name_to_parent_groups,
opgroup_name_to_parent_groups,
opsgroups,
condition_params,
)
templates = []
for opsgroup in opsgroups.keys():
# Conditions and loops will get templates in Tekton
if opsgroups[opsgroup].type == 'condition':
template = self._group_to_dag_template(opsgroups[opsgroup], inputs, outputs, dependencies, pipeline.name, "condition", opsgroups)
templates.append(template)
if opsgroups[opsgroup].type == 'addon_group':
self._group_to_dag_template(opsgroups[opsgroup], inputs, outputs, dependencies, pipeline.name, "addon", opsgroups)
if opsgroups[opsgroup].type == 'for_loop':
self._group_to_dag_template(opsgroups[opsgroup], inputs, outputs, dependencies, pipeline.name, "loop", opsgroups)
if opsgroups[opsgroup].type == 'graph':
self._group_to_dag_template(opsgroups[opsgroup], inputs, outputs, dependencies, pipeline.name, "graph", opsgroups)
for op in pipeline.ops.values():
templates.extend(op_to_steps_handler(op))
return templates
def _get_dependencies(self, pipeline, root_group, op_groups,
opsgroups_groups, opsgroups, condition_params):
"""Get dependent groups and ops for all ops and groups.
Returns:
A dict. Key is group/op name, value is a list of dependent groups/ops.
The dependencies are calculated in the following way: if op2 depends on op1,
and their ancestors are [root, G1, G2, op1] and [root, G1, G3, G4, op2],
then G3 is dependent on G2. Basically dependency only exists in the first uncommon
ancesters in their ancesters chain. Only sibling groups/ops can have dependencies.
"""
dependencies = defaultdict(set)
for op in pipeline.ops.values():
upstream_op_names = set()
for param in op.inputs + list(condition_params[op.name]):
if param.op_name:
upstream_op_names.add(param.op_name)
upstream_op_names |= set(op.dependent_names)
for upstream_op_name in upstream_op_names:
# the dependent op could be either a BaseOp or an opsgroup
if upstream_op_name in pipeline.ops:
upstream_op = pipeline.ops[upstream_op_name]
elif upstream_op_name in opsgroups:
upstream_op = opsgroups[upstream_op_name]
else:
raise ValueError('compiler cannot find the ' +
upstream_op_name)
upstream_groups, downstream_groups = self._get_uncommon_ancestors(
op_groups, opsgroups_groups, upstream_op, op)
# Convert Argo condition DAG dependency into Tekton condition task dependency
while len(upstream_groups) > 0 and 'condition-' in upstream_groups[0]:
upstream_groups.pop(0)
if len(upstream_groups) > 0:
dependencies[downstream_groups[0]].add(upstream_groups[0])
# Generate dependencies based on the recursive opsgroups
# TODO: refactor the following codes with the above
def _get_dependency_opsgroup(group, dependencies):
upstream_op_names = set(
[dependency.name for dependency in group.dependencies])
if group.recursive_ref:
for param in group.inputs + list(condition_params[group.name]):
if param.op_name:
upstream_op_names.add(param.op_name)
for op_name in upstream_op_names:
if op_name in pipeline.ops:
upstream_op = pipeline.ops[op_name]
elif op_name in opsgroups:
upstream_op = opsgroups[op_name]
else:
raise ValueError('compiler cannot find the ' + op_name)
upstream_groups, downstream_groups = \
self._get_uncommon_ancestors(op_groups, opsgroups_groups, upstream_op, group)
# Convert Argo condition DAG dependency into Tekton condition task dependency
while len(upstream_groups) > 0 and 'condition-' in upstream_groups[0]:
upstream_groups.pop(0)
if len(upstream_groups) > 0:
dependencies[downstream_groups[0]].add(upstream_groups[0])
for subgroup in group.groups:
_get_dependency_opsgroup(subgroup, dependencies)
_get_dependency_opsgroup(root_group, dependencies)
return dependencies
def _get_inputs_outputs(
self,
pipeline,
root_group,
op_groups,
opsgroup_groups,
condition_params,
op_name_to_for_loop_op: Dict[Text, dsl.ParallelFor],
opsgroups: Dict[str, dsl.OpsGroup]
):
"""Get inputs and outputs of each group and op.
Returns:
A tuple (inputs, outputs).
inputs and outputs are dicts with key being the group/op names and values being list of
tuples (param_name, producing_op_name). producing_op_name is the name of the op that
produces the param. If the param is a pipeline param (no producer op), then
producing_op_name is None.
"""
inputs = defaultdict(set)
outputs = defaultdict(set)
for op in pipeline.ops.values():
# op's inputs and all params used in conditions for that op are both considered.
for param in op.inputs + list(condition_params[op.name]):
# if the value is already provided (immediate value), then no need to expose
# it as input for its parent groups.
if param.value:
continue
if param.op_name:
upstream_op = pipeline.ops[param.op_name]
upstream_groups, downstream_groups = \
self._get_uncommon_ancestors(op_groups, opsgroup_groups, upstream_op, op)
for i, group_name in enumerate(downstream_groups):
# Important: Changes for Tekton custom tasks
# Custom task condition are not pods running in Tekton. Thus it should also
# be considered as the first uncommon downstream group.
def is_parent_custom_task(index):
for group_name in downstream_groups[:index]:
if 'condition-' in group_name:
return True
return False
if i == 0 or is_parent_custom_task(i):
# If it is the first uncommon downstream group, then the input comes from
# the first uncommon upstream group.
inputs[group_name].add((param.full_name, upstream_groups[0]))
else:
# If not the first downstream group, then the input is passed down from
# its ancestor groups so the upstream group is None.
inputs[group_name].add((param.full_name, None))
for i, group_name in enumerate(upstream_groups):
if i == len(upstream_groups) - 1:
# If last upstream group, it is an operator and output comes from container.
outputs[group_name].add((param.full_name, None))
else:
# If not last upstream group, output value comes from one of its child.
outputs[group_name].add((param.full_name, upstream_groups[i + 1]))
else:
if not op.is_exit_handler:
for group_name in op_groups[op.name][::-1]:
# if group is for loop group and param is that loop's param, then the param
# is created by that for loop ops_group and it shouldn't be an input to
# any of its parent groups.
inputs[group_name].add((param.full_name, None))
if group_name in op_name_to_for_loop_op:
# for example:
# loop_group.loop_args.name = 'loop-item-param-99ca152e'
# param.name = 'loop-item-param-99ca152e--a'
loop_group = op_name_to_for_loop_op[group_name]
if loop_group.loop_args.name in param.name:
break
# apply the same rule to iteration_number which is used by enumerate()
# helper function. it shoudn't be an input to any of its parent groups
if hasattr(loop_group, 'iteration_number') and loop_group.iteration_number and \
loop_group.iteration_number.full_name == param.name:
break
elif group_name in opsgroups and isinstance(opsgroups[group_name], AddOnGroup) and \
param.name in opsgroups[group_name].params:
# if group is AddOnGroup and the param is in its params list, then the param
# is created by that AddOnGroup and it shouldn't be an input to
# any of its parent groups.
break
# Generate the input/output for recursive opsgroups
# It propagates the recursive opsgroups IO to their ancester opsgroups
def _get_inputs_outputs_recursive_opsgroup(group):
# TODO: refactor the following codes with the above
if group.recursive_ref:
params = [(param, False) for param in group.inputs]
params.extend([(param, True) for param in list(condition_params[group.name])])
for param, is_condition_param in params:
if param.value:
continue
full_name = param.full_name
if param.op_name:
upstream_op = pipeline.ops[param.op_name]
upstream_groups, downstream_groups = \
self._get_uncommon_ancestors(op_groups, opsgroup_groups, upstream_op, group)
for i, g in enumerate(downstream_groups):
if i == 0:
inputs[g].add((full_name, upstream_groups[0]))
# There is no need to pass the condition param as argument to the downstream ops.
# TODO: this might also apply to ops. add a TODO here and think about it.
elif i == len(downstream_groups) - 1 and is_condition_param:
continue
else:
# For Tekton, do not append duplicated input parameters
duplicated_downstream_group = False
for group_name in inputs[g]:
if len(group_name) > 1 and group_name[0] == full_name:
duplicated_downstream_group = True
break
if not duplicated_downstream_group:
inputs[g].add((full_name, None))
for i, g in enumerate(upstream_groups):
if i == len(upstream_groups) - 1:
outputs[g].add((full_name, None))
else:
outputs[g].add((full_name, upstream_groups[i + 1]))
elif not is_condition_param:
for g in op_groups[group.name]:
inputs[g].add((full_name, None))
for subgroup in group.groups:
_get_inputs_outputs_recursive_opsgroup(subgroup)
_get_inputs_outputs_recursive_opsgroup(root_group)
# Generate the input for SubGraph along with parallelfor
for sub_graph in opsgroup_groups:
if sub_graph in op_name_to_for_loop_op:
# The opsgroup list is sorted with the farthest group as the first and
# the opsgroup itself as the last. To get the latest opsgroup which is
# not the opsgroup itself -2 is used.
parent = opsgroup_groups[sub_graph][-2]
if parent and parent.startswith('subgraph'):
# propagate only op's pipeline param from subgraph to parallelfor
loop_op = op_name_to_for_loop_op[sub_graph]
pipeline_param = loop_op.loop_args.items_or_pipeline_param
if loop_op.items_is_pipeline_param and pipeline_param.op_name:
param_name = '%s-%s' % (
sanitize_k8s_name(pipeline_param.op_name), pipeline_param.name)
inputs[parent].add((param_name, pipeline_param.op_name))
return inputs, outputs
def _process_resourceOp(self, task_refs, pipeline):
""" handle resourceOp cases in pipeline """
for task in task_refs:
op = pipeline.ops.get(task['name'])
if isinstance(op, dsl.ResourceOp):
action = op.resource.get('action')
merge_strategy = op.resource.get('merge_strategy')
success_condition = op.resource.get('successCondition')
failure_condition = op.resource.get('failureCondition')
set_owner_reference = op.resource.get('setOwnerReference')
task['params'] = [tp for tp in task.get('params', []) if tp.get('name') != "image"]
if not merge_strategy:
task['params'] = [tp for tp in task.get('params', []) if tp.get('name') != 'merge-strategy']
if not success_condition:
task['params'] = [tp for tp in task.get('params', []) if tp.get('name') != 'success-condition']
if not failure_condition:
task['params'] = [tp for tp in task.get('params', []) if tp.get('name') != "failure-condition"]
if not set_owner_reference:
task['params'] = [tp for tp in task.get('params', []) if tp.get('name') != "set-ownerreference"]
for tp in task.get('params', []):
if tp.get('name') == "action" and action:
tp['value'] = action
if tp.get('name') == "merge-strategy" and merge_strategy:
tp['value'] = merge_strategy
if tp.get('name') == "success-condition" and success_condition:
tp['value'] = success_condition
if tp.get('name') == "failure-condition" and failure_condition:
tp['value'] = failure_condition
if tp.get('name') == "set-ownerreference" and set_owner_reference:
tp['value'] = set_owner_reference
if tp.get('name') == "output":
output_values = ''
for value in sorted(list(op.attribute_outputs.items()), key=lambda x: x[0]):
output_value = textwrap.dedent("""\
- name: %s
valueFrom: '%s'
""" % (value[0], value[1]))
output_values += output_value
tp['value'] = output_values
def _create_pipeline_workflow(self, args, pipeline, op_transformers=None, pipeline_conf=None) \
-> Dict[Text, Any]:
"""Create workflow for the pipeline."""
# Input Parameters
params = []
for arg in args:
param = {'name': arg.name}
if arg.value is not None:
if isinstance(arg.value, (list, tuple, dict)):
param['default'] = json.dumps(arg.value, sort_keys=True)
else:
param['default'] = str(arg.value)
params.append(param)
# generate Tekton tasks from pipeline ops
raw_templates = self._create_dag_templates(pipeline, op_transformers, params)
# generate task and condition reference list for the Tekton Pipeline
condition_refs = {}
task_refs = []
cel_conditions = {}
condition_when_refs = {}
condition_task_refs = {}
string_condition_refs = {}
for template in raw_templates:
if template['kind'] == 'Condition':
if DISABLE_CEL_CONDITION:
condition_task_spec = _get_super_condition_template()
else:
condition_task_spec = _get_cel_condition_template()
condition_params = template['spec'].get('params', [])
if condition_params:
condition_task_ref = [{
'name': template['metadata']['name'],
'params': [{
'name': p['name'],
'value': p.get('value', '')
} for p in template['spec'].get('params', [])
],
'taskSpec' if DISABLE_CEL_CONDITION else 'taskRef': condition_task_spec
}]
condition_refs[template['metadata']['name']] = [
{
'input': '$(tasks.%s.results.%s)' % (template['metadata']['name'], DEFAULT_CONDITION_OUTPUT_KEYWORD),
'operator': 'in',
'values': ['true']
}
]
# Don't use additional task if it's only doing literal string == and !=
# with CEL custom task output.
condition_operator = condition_params[2]
condition_operand1 = condition_params[0]
condition_operand2 = condition_params[1]
conditionOp_mapping = {"==": "in", "!=": "notin"}
if condition_operator.get('value', '') in conditionOp_mapping.keys():
# Check whether the operand is an output from custom task
# If so, don't create a new task to verify the condition.
def is_custom_task_output(operand) -> bool:
if operand['type'] == dsl.PipelineParam:
for template in raw_templates:
if operand['op_name'] == template['metadata']['name']:
for step in template['spec']['steps']:
if step['name'] == 'main' and step['image'] in TEKTON_CUSTOM_TASK_IMAGES:
return True
return False
if is_custom_task_output(condition_operand1) or is_custom_task_output(condition_operand2):
def map_cel_vars(a):
if a.get('type', '') == dsl.PipelineParam:
op_name = sanitize_k8s_name(a['op_name'])
output_name = sanitize_k8s_name(a['output_name'])
return '$(tasks.%s.results.%s)' % (op_name, output_name)
else:
return a.get('value', '')
condition_refs[template['metadata']['name']] = [
{
'input': map_cel_vars(condition_operand1),
'operator': conditionOp_mapping[condition_operator['value']],
'values': [map_cel_vars(condition_operand2)]
}
]
string_condition_refs[template['metadata']['name']] = True
condition_task_refs[template['metadata']['name']] = condition_task_ref
condition_when_refs[template['metadata']['name']] = condition_refs[template['metadata']['name']]
else:
task_ref = {
'name': template['metadata']['name'],
'params': [{
'name': p['name'],
'value': p.get('default', '')
} for p in template['spec'].get('params', [])
],
'taskSpec': template['spec'],
}
for i in template['spec'].get('steps', []):
# TODO: change the below conditions to map with a label
# or a list of images with optimized actions
if i.get('image', '') in TEKTON_CUSTOM_TASK_IMAGES:
custom_task_args = {}
container_args = i.get('args', [])
for index, item in enumerate(container_args):
if item.startswith('--'):
custom_task_args[item[2:]] = container_args[index + 1]
non_param_keys = ['name', 'apiVersion', 'kind', 'taskSpec', 'taskRef']
task_params = []
for key, value in custom_task_args.items():
if key not in non_param_keys:
task_params.append({'name': key, 'value': value})
task_orig_params = task_ref['params']
task_ref = {
'name': template['metadata']['name'],
'params': task_params,
# For processing Tekton parameter mapping later on.
'orig_params': task_orig_params,