forked from kubeflow/pipelines
-
Notifications
You must be signed in to change notification settings - Fork 0
/
driver.go
1748 lines (1641 loc) · 65 KB
/
driver.go
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 2021-2023 The Kubeflow Authors
//
// 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
//
// https://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.
package driver
import (
"context"
"encoding/json"
"fmt"
"github.com/kubeflow/pipelines/backend/src/v2/objectstore"
"strconv"
"time"
"github.com/golang/glog"
"github.com/golang/protobuf/ptypes/timestamp"
"github.com/google/uuid"
"github.com/kubeflow/pipelines/api/v2alpha1/go/pipelinespec"
api "github.com/kubeflow/pipelines/backend/api/v1beta1/go_client"
"github.com/kubeflow/pipelines/backend/src/v2/cacheutils"
"github.com/kubeflow/pipelines/backend/src/v2/component"
"github.com/kubeflow/pipelines/backend/src/v2/config"
"github.com/kubeflow/pipelines/backend/src/v2/expression"
"github.com/kubeflow/pipelines/backend/src/v2/metadata"
"github.com/kubeflow/pipelines/kubernetes_platform/go/kubernetesplatform"
pb "github.com/kubeflow/pipelines/third_party/ml-metadata/go/ml_metadata"
"google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/types/known/structpb"
k8score "k8s.io/api/core/v1"
k8sres "k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
)
var dummyImages = map[string]string{
"argostub/createpvc": "create PVC",
"argostub/deletepvc": "delete PVC",
}
// TODO(capri-xiyue): Move driver to component package
// Driver options
type Options struct {
// required, pipeline context name
PipelineName string
// required, KFP run ID
RunID string
// required, Component spec
Component *pipelinespec.ComponentSpec
// optional, iteration index. -1 means not an iteration.
IterationIndex int
// optional, required only by root DAG driver
RuntimeConfig *pipelinespec.PipelineJob_RuntimeConfig
Namespace string
// optional, required by non-root drivers
Task *pipelinespec.PipelineTaskSpec
DAGExecutionID int64
// optional, required only by container driver
Container *pipelinespec.PipelineDeploymentConfig_PipelineContainerSpec
// optional, allows to specify kubernetes-specific executor config
KubernetesExecutorConfig *kubernetesplatform.KubernetesExecutorConfig
}
// Identifying information used for error messages
func (o Options) info() string {
msg := fmt.Sprintf("pipelineName=%v, runID=%v", o.PipelineName, o.RunID)
if o.Task.GetTaskInfo().GetName() != "" {
msg = msg + fmt.Sprintf(", task=%q", o.Task.GetTaskInfo().GetName())
}
if o.Task.GetComponentRef().GetName() != "" {
msg = msg + fmt.Sprintf(", component=%q", o.Task.GetComponentRef().GetName())
}
if o.DAGExecutionID != 0 {
msg = msg + fmt.Sprintf(", dagExecutionID=%v", o.DAGExecutionID)
}
if o.IterationIndex >= 0 {
msg = msg + fmt.Sprintf(", iterationIndex=%v", o.IterationIndex)
}
if o.RuntimeConfig != nil {
msg = msg + ", runtimeConfig" // this only means runtimeConfig is not empty
}
if o.Component.GetImplementation() != nil {
msg = msg + ", componentSpec" // this only means componentSpec is not empty
}
if o.KubernetesExecutorConfig != nil {
msg = msg + ", KubernetesExecutorConfig" // this only means KubernetesExecutorConfig is not empty
}
return msg
}
type Execution struct {
ID int64
ExecutorInput *pipelinespec.ExecutorInput
IterationCount *int // number of iterations, -1 means not an iterator
Condition *bool // true -> trigger the task, false -> not trigger the task, nil -> the task is unconditional
// only specified when this is a Container execution
Cached *bool
PodSpecPatch string
}
func (e *Execution) WillTrigger() bool {
if e == nil || e.Condition == nil {
return true
}
return *e.Condition
}
func RootDAG(ctx context.Context, opts Options, mlmd *metadata.Client) (execution *Execution, err error) {
defer func() {
if err != nil {
err = fmt.Errorf("driver.RootDAG(%s) failed: %w", opts.info(), err)
}
}()
err = validateRootDAG(opts)
if err != nil {
return nil, err
}
// TODO(v2): in pipeline spec, rename GCS output directory to pipeline root.
pipelineRoot := opts.RuntimeConfig.GetGcsOutputDirectory()
restConfig, err := rest.InClusterConfig()
if err != nil {
return nil, fmt.Errorf("failed to initialize kubernetes client: %w", err)
}
k8sClient, err := kubernetes.NewForConfig(restConfig)
if err != nil {
return nil, fmt.Errorf("failed to initialize kubernetes client set: %w", err)
}
cfg, err := config.FromConfigMap(ctx, k8sClient, opts.Namespace)
if err != nil {
return nil, err
}
storeSessionInfo := objectstore.SessionInfo{}
if pipelineRoot != "" {
glog.Infof("PipelineRoot=%q", pipelineRoot)
} else {
pipelineRoot = cfg.DefaultPipelineRoot()
glog.Infof("PipelineRoot=%q from default config", pipelineRoot)
}
storeSessionInfo, err = cfg.GetStoreSessionInfo(pipelineRoot)
if err != nil {
return nil, err
}
storeSessionInfoJSON, err := json.Marshal(storeSessionInfo)
if err != nil {
return nil, err
}
storeSessionInfoStr := string(storeSessionInfoJSON)
// TODO(Bobgy): fill in run resource.
pipeline, err := mlmd.GetPipeline(ctx, opts.PipelineName, opts.RunID, opts.Namespace, "run-resource", pipelineRoot, storeSessionInfoStr)
if err != nil {
return nil, err
}
executorInput := &pipelinespec.ExecutorInput{
Inputs: &pipelinespec.ExecutorInput_Inputs{
ParameterValues: opts.RuntimeConfig.GetParameterValues(),
},
}
// TODO(Bobgy): validate executorInput matches component spec types
ecfg, err := metadata.GenerateExecutionConfig(executorInput)
if err != nil {
return nil, err
}
ecfg.ExecutionType = metadata.DagExecutionTypeName
ecfg.Name = fmt.Sprintf("run/%s", opts.RunID)
exec, err := mlmd.CreateExecution(ctx, pipeline, ecfg)
if err != nil {
return nil, err
}
glog.Infof("Created execution: %s", exec)
// No need to return ExecutorInput, because tasks in the DAG will resolve
// needed info from MLMD.
return &Execution{ID: exec.GetID()}, nil
}
func validateRootDAG(opts Options) (err error) {
defer func() {
if err != nil {
err = fmt.Errorf("invalid root DAG driver args: %w", err)
}
}()
if opts.PipelineName == "" {
return fmt.Errorf("pipeline name is required")
}
if opts.RunID == "" {
return fmt.Errorf("KFP run ID is required")
}
if opts.Component == nil {
return fmt.Errorf("component spec is required")
}
if opts.RuntimeConfig == nil {
return fmt.Errorf("runtime config is required")
}
if opts.Namespace == "" {
return fmt.Errorf("namespace is required")
}
if opts.Task.GetTaskInfo().GetName() != "" {
return fmt.Errorf("task spec is unnecessary")
}
if opts.DAGExecutionID != 0 {
return fmt.Errorf("DAG execution ID is unnecessary")
}
if opts.Container != nil {
return fmt.Errorf("container spec is unnecessary")
}
if opts.IterationIndex >= 0 {
return fmt.Errorf("iteration index is unnecessary")
}
return nil
}
func Container(ctx context.Context, opts Options, mlmd *metadata.Client, cacheClient *cacheutils.Client) (execution *Execution, err error) {
defer func() {
if err != nil {
err = fmt.Errorf("driver.Container(%s) failed: %w", opts.info(), err)
}
}()
err = validateContainer(opts)
if err != nil {
return nil, err
}
var iterationIndex *int
if opts.IterationIndex >= 0 {
index := opts.IterationIndex
iterationIndex = &index
}
// TODO(Bobgy): there's no need to pass any parameters, because pipeline
// and pipeline run context have been created by root DAG driver.
pipeline, err := mlmd.GetPipeline(ctx, opts.PipelineName, opts.RunID, "", "", "", "")
if err != nil {
return nil, err
}
dag, err := mlmd.GetDAG(ctx, opts.DAGExecutionID)
if err != nil {
return nil, err
}
glog.Infof("parent DAG: %+v", dag.Execution)
expr, err := expression.New()
if err != nil {
return nil, err
}
inputs, err := resolveInputs(ctx, dag, iterationIndex, pipeline, opts.Task, opts.Component.GetInputDefinitions(), mlmd, expr)
if err != nil {
return nil, err
}
executorInput := &pipelinespec.ExecutorInput{
Inputs: inputs,
}
execution = &Execution{ExecutorInput: executorInput}
condition := opts.Task.GetTriggerPolicy().GetCondition()
if condition != "" {
willTrigger, err := expr.Condition(executorInput, condition)
if err != nil {
return execution, err
}
execution.Condition = &willTrigger
}
if execution.WillTrigger() {
executorInput.Outputs = provisionOutputs(pipeline.GetPipelineRoot(), opts.Task.GetTaskInfo().GetName(), opts.Component.GetOutputDefinitions())
}
ecfg, err := metadata.GenerateExecutionConfig(executorInput)
if err != nil {
return execution, err
}
ecfg.TaskName = opts.Task.GetTaskInfo().GetName()
ecfg.ExecutionType = metadata.ContainerExecutionTypeName
ecfg.ParentDagID = dag.Execution.GetID()
ecfg.IterationIndex = iterationIndex
ecfg.NotTriggered = !execution.WillTrigger()
// When the container image is a dummy image, there is no launcher for this task.
// This happens when this task is created to implement a Kubernetes-specific configuration, i.e.,
// there is no user container to run.
// It publishes execution details to mlmd in driver and takes care of caching, which are usually done in launcher.
// We also skip creating the podspecpatch in these cases.
if _, ok := dummyImages[opts.Container.Image]; ok {
return execution, kubernetesPlatformOps(ctx, mlmd, cacheClient, execution, ecfg, &opts)
}
// Generate fingerprint and MLMD ID for cache
fingerPrint, cachedMLMDExecutionID, err := getFingerPrintsAndID(execution, &opts, cacheClient)
if err != nil {
return execution, err
}
ecfg.CachedMLMDExecutionID = cachedMLMDExecutionID
ecfg.FingerPrint = fingerPrint
// TODO(Bobgy): change execution state to pending, because this is driver, execution hasn't started.
createdExecution, err := mlmd.CreateExecution(ctx, pipeline, ecfg)
if err != nil {
return execution, err
}
glog.Infof("Created execution: %s", createdExecution)
execution.ID = createdExecution.GetID()
if !execution.WillTrigger() {
return execution, nil
}
// Use cache and skip launcher if all contions met:
// (1) Cache is enabled
// (2) CachedMLMDExecutionID is non-empty, which means a cache entry exists
cached := false
execution.Cached = &cached
if opts.Task.GetCachingOptions().GetEnableCache() && ecfg.CachedMLMDExecutionID != "" {
executorOutput, outputArtifacts, err := reuseCachedOutputs(ctx, execution.ExecutorInput, opts.Component.GetOutputDefinitions(), mlmd, ecfg.CachedMLMDExecutionID)
if err != nil {
return execution, err
}
// TODO(Bobgy): upload output artifacts.
// TODO(Bobgy): when adding artifacts, we will need execution.pipeline to be non-nil, because we need
// to publish output artifacts to the context too.
if err := mlmd.PublishExecution(ctx, createdExecution, executorOutput.GetParameterValues(), outputArtifacts, pb.Execution_CACHED); err != nil {
return execution, fmt.Errorf("failed to publish cached execution: %w", err)
}
glog.Infof("Use cache for task %s", opts.Task.GetTaskInfo().GetName())
*execution.Cached = true
return execution, nil
}
podSpec, err := initPodSpecPatch(opts.Container, opts.Component, executorInput, execution.ID, opts.PipelineName, opts.RunID)
if err != nil {
return execution, err
}
if opts.KubernetesExecutorConfig != nil {
dagTasks, err := mlmd.GetExecutionsInDAG(ctx, dag, pipeline)
if err != nil {
return execution, err
}
err = extendPodSpecPatch(podSpec, opts.KubernetesExecutorConfig, dag, dagTasks)
if err != nil {
return execution, err
}
}
podSpecPatchBytes, err := json.Marshal(podSpec)
if err != nil {
return execution, fmt.Errorf("JSON marshaling pod spec patch: %w", err)
}
execution.PodSpecPatch = string(podSpecPatchBytes)
return execution, nil
}
// initPodSpecPatch generates a strategic merge patch for pod spec, it is merged
// to container base template generated in compiler/container.go. Therefore, only
// dynamic values are patched here. The volume mounts / configmap mounts are
// defined in compiler, because they are static.
func initPodSpecPatch(
container *pipelinespec.PipelineDeploymentConfig_PipelineContainerSpec,
componentSpec *pipelinespec.ComponentSpec,
executorInput *pipelinespec.ExecutorInput,
executionID int64,
pipelineName string,
runID string,
) (*k8score.PodSpec, error) {
executorInputJSON, err := protojson.Marshal(executorInput)
if err != nil {
return nil, fmt.Errorf("failed to init podSpecPatch: %w", err)
}
componentJSON, err := protojson.Marshal(componentSpec)
if err != nil {
return nil, fmt.Errorf("failed to init podSpecPatch: %w", err)
}
// Convert environment variables
userEnvVar := make([]k8score.EnvVar, 0)
for _, envVar := range container.GetEnv() {
userEnvVar = append(userEnvVar, k8score.EnvVar{Name: envVar.GetName(), Value: envVar.GetValue()})
}
userCmdArgs := make([]string, 0, len(container.Command)+len(container.Args))
userCmdArgs = append(userCmdArgs, container.Command...)
userCmdArgs = append(userCmdArgs, container.Args...)
launcherCmd := []string{
// TODO(Bobgy): workaround argo emissary executor bug, after we upgrade to an argo version with the bug fix, we can remove the following line.
// Reference: https://github.com/argoproj/argo-workflows/issues/7406
"/var/run/argo/argoexec", "emissary", "--",
component.KFPLauncherPath,
// TODO(Bobgy): no need to pass pipeline_name and run_id, these info can be fetched via pipeline context and pipeline run context which have been created by root DAG driver.
"--pipeline_name", pipelineName,
"--run_id", runID,
"--execution_id", fmt.Sprintf("%v", executionID),
"--executor_input", string(executorInputJSON),
"--component_spec", string(componentJSON),
"--pod_name",
fmt.Sprintf("$(%s)", component.EnvPodName),
"--pod_uid",
fmt.Sprintf("$(%s)", component.EnvPodUID),
"--mlmd_server_address",
fmt.Sprintf("$(%s)", component.EnvMetadataHost),
"--mlmd_server_port",
fmt.Sprintf("$(%s)", component.EnvMetadataPort),
"--", // separater before user command and args
}
res := k8score.ResourceRequirements{
Limits: map[k8score.ResourceName]k8sres.Quantity{},
Requests: map[k8score.ResourceName]k8sres.Quantity{},
}
memoryLimit := container.GetResources().GetMemoryLimit()
if memoryLimit != 0 {
q, err := k8sres.ParseQuantity(fmt.Sprintf("%vG", memoryLimit))
if err != nil {
return nil, fmt.Errorf("failed to init podSpecPatch: %w", err)
}
res.Limits[k8score.ResourceMemory] = q
}
memoryRequest := container.GetResources().GetMemoryRequest()
if memoryRequest != 0 {
q, err := k8sres.ParseQuantity(fmt.Sprintf("%vG", memoryRequest))
if err != nil {
return nil, err
}
res.Requests[k8score.ResourceMemory] = q
}
cpuLimit := container.GetResources().GetCpuLimit()
if cpuLimit != 0 {
q, err := k8sres.ParseQuantity(fmt.Sprintf("%v", cpuLimit))
if err != nil {
return nil, fmt.Errorf("failed to init podSpecPatch: %w", err)
}
res.Limits[k8score.ResourceCPU] = q
}
cpuRequest := container.GetResources().GetCpuRequest()
if cpuRequest != 0 {
q, err := k8sres.ParseQuantity(fmt.Sprintf("%v", cpuRequest))
if err != nil {
return nil, err
}
res.Requests[k8score.ResourceCPU] = q
}
accelerator := container.GetResources().GetAccelerator()
if accelerator != nil {
if accelerator.GetType() != "" && accelerator.GetCount() > 0 {
q, err := k8sres.ParseQuantity(fmt.Sprintf("%v", accelerator.GetCount()))
if err != nil {
return nil, fmt.Errorf("failed to init podSpecPatch: %w", err)
}
res.Limits[k8score.ResourceName(accelerator.GetType())] = q
}
}
podSpec := &k8score.PodSpec{
Containers: []k8score.Container{{
Name: "main", // argo task user container is always called "main"
Command: launcherCmd,
Args: userCmdArgs,
Image: container.Image,
Resources: res,
Env: userEnvVar,
}},
}
return podSpec, nil
}
// Extends the PodSpec to include Kubernetes-specific executor config.
func extendPodSpecPatch(
podSpec *k8score.PodSpec,
kubernetesExecutorConfig *kubernetesplatform.KubernetesExecutorConfig,
dag *metadata.DAG,
dagTasks map[string]*metadata.Execution,
) error {
// Return an error if the podSpec has no user container.
if len(podSpec.Containers) == 0 {
return fmt.Errorf("failed to patch the pod with kubernetes-specific config due to missing user container: %v", podSpec)
}
// Get volume mount information
if kubernetesExecutorConfig.GetPvcMount() != nil {
volumeMounts, volumes, err := makeVolumeMountPatch(kubernetesExecutorConfig.GetPvcMount(), dag, dagTasks)
if err != nil {
return fmt.Errorf("failed to extract volume mount info: %w", err)
}
podSpec.Volumes = append(podSpec.Volumes, volumes...)
// We assume that the user container always gets executed first within a pod.
podSpec.Containers[0].VolumeMounts = append(podSpec.Containers[0].VolumeMounts, volumeMounts...)
}
// Get image pull policy
pullPolicy := kubernetesExecutorConfig.GetImagePullPolicy()
if pullPolicy != "" {
policies := []string{"Always", "Never", "IfNotPresent"}
found := false
for _, value := range policies {
if value == pullPolicy {
found = true
break
}
}
if !found {
return fmt.Errorf("unsupported value: %s. ImagePullPolicy should be one of 'Always', 'Never' or 'IfNotPresent'", pullPolicy)
}
// We assume that the user container always gets executed first within a pod.
podSpec.Containers[0].ImagePullPolicy = k8score.PullPolicy(pullPolicy)
}
// Get node selector information
if kubernetesExecutorConfig.GetNodeSelector() != nil {
podSpec.NodeSelector = kubernetesExecutorConfig.GetNodeSelector().GetLabels()
}
if tolerations := kubernetesExecutorConfig.GetTolerations(); tolerations != nil {
var k8sTolerations []k8score.Toleration
glog.Infof("Tolerations passed: %+v", tolerations)
for _, toleration := range tolerations {
if toleration != nil {
k8sToleration := k8score.Toleration{
Key: toleration.Key,
Operator: k8score.TolerationOperator(toleration.Operator),
Value: toleration.Value,
Effect: k8score.TaintEffect(toleration.Effect),
TolerationSeconds: toleration.TolerationSeconds,
}
k8sTolerations = append(k8sTolerations, k8sToleration)
}
}
podSpec.Tolerations = k8sTolerations
}
// Get secret mount information
for _, secretAsVolume := range kubernetesExecutorConfig.GetSecretAsVolume() {
optional := secretAsVolume.Optional != nil && *secretAsVolume.Optional
secretVolume := k8score.Volume{
Name: secretAsVolume.GetSecretName(),
VolumeSource: k8score.VolumeSource{
Secret: &k8score.SecretVolumeSource{SecretName: secretAsVolume.GetSecretName(), Optional: &optional},
},
}
secretVolumeMount := k8score.VolumeMount{
Name: secretAsVolume.GetSecretName(),
MountPath: secretAsVolume.GetMountPath(),
}
podSpec.Volumes = append(podSpec.Volumes, secretVolume)
podSpec.Containers[0].VolumeMounts = append(podSpec.Containers[0].VolumeMounts, secretVolumeMount)
}
// Get secret env information
for _, secretAsEnv := range kubernetesExecutorConfig.GetSecretAsEnv() {
for _, keyToEnv := range secretAsEnv.GetKeyToEnv() {
secretEnvVar := k8score.EnvVar{
Name: keyToEnv.GetEnvVar(),
ValueFrom: &k8score.EnvVarSource{
SecretKeyRef: &k8score.SecretKeySelector{
Key: keyToEnv.GetSecretKey(),
},
},
}
secretEnvVar.ValueFrom.SecretKeyRef.LocalObjectReference.Name = secretAsEnv.GetSecretName()
podSpec.Containers[0].Env = append(podSpec.Containers[0].Env, secretEnvVar)
}
}
// Get config map mount information
for _, configMapAsVolume := range kubernetesExecutorConfig.GetConfigMapAsVolume() {
optional := configMapAsVolume.Optional != nil && *configMapAsVolume.Optional
configMapVolume := k8score.Volume{
Name: configMapAsVolume.GetConfigMapName(),
VolumeSource: k8score.VolumeSource{
ConfigMap: &k8score.ConfigMapVolumeSource{
LocalObjectReference: k8score.LocalObjectReference{Name: configMapAsVolume.GetConfigMapName()}, Optional: &optional},
},
}
configMapVolumeMount := k8score.VolumeMount{
Name: configMapAsVolume.GetConfigMapName(),
MountPath: configMapAsVolume.GetMountPath(),
}
podSpec.Volumes = append(podSpec.Volumes, configMapVolume)
podSpec.Containers[0].VolumeMounts = append(podSpec.Containers[0].VolumeMounts, configMapVolumeMount)
}
// Get config map env information
for _, configMapAsEnv := range kubernetesExecutorConfig.GetConfigMapAsEnv() {
for _, keyToEnv := range configMapAsEnv.GetKeyToEnv() {
configMapEnvVar := k8score.EnvVar{
Name: keyToEnv.GetEnvVar(),
ValueFrom: &k8score.EnvVarSource{
ConfigMapKeyRef: &k8score.ConfigMapKeySelector{
Key: keyToEnv.GetConfigMapKey(),
},
},
}
configMapEnvVar.ValueFrom.ConfigMapKeyRef.LocalObjectReference.Name = configMapAsEnv.GetConfigMapName()
podSpec.Containers[0].Env = append(podSpec.Containers[0].Env, configMapEnvVar)
}
}
// Get image pull secret information
for _, imagePullSecret := range kubernetesExecutorConfig.GetImagePullSecret() {
podSpec.ImagePullSecrets = append(podSpec.ImagePullSecrets, k8score.LocalObjectReference{Name: imagePullSecret.GetSecretName()})
}
// Get Kubernetes FieldPath Env information
for _, fieldPathAsEnv := range kubernetesExecutorConfig.GetFieldPathAsEnv() {
fieldPathEnvVar := k8score.EnvVar{
Name: fieldPathAsEnv.GetName(),
ValueFrom: &k8score.EnvVarSource{
FieldRef: &k8score.ObjectFieldSelector{
FieldPath: fieldPathAsEnv.GetFieldPath(),
},
},
}
podSpec.Containers[0].Env = append(podSpec.Containers[0].Env, fieldPathEnvVar)
}
// Get container timeout information
timeout := kubernetesExecutorConfig.GetActiveDeadlineSeconds()
if timeout > 0 {
podSpec.ActiveDeadlineSeconds = &timeout
}
// Get Pod Generic Ephemeral volume information
for _, ephemeralVolumeSpec := range kubernetesExecutorConfig.GetGenericEphemeralVolume() {
var accessModes []k8score.PersistentVolumeAccessMode
for _, value := range ephemeralVolumeSpec.GetAccessModes() {
accessModes = append(accessModes, accessModeMap[value])
}
var storageClassName *string
storageClassName = nil
if !ephemeralVolumeSpec.GetDefaultStorageClass() {
_storageClassName := ephemeralVolumeSpec.GetStorageClassName()
storageClassName = &_storageClassName
}
ephemeralVolume := k8score.Volume{
Name: ephemeralVolumeSpec.GetVolumeName(),
VolumeSource: k8score.VolumeSource{
Ephemeral: &k8score.EphemeralVolumeSource{
VolumeClaimTemplate: &k8score.PersistentVolumeClaimTemplate{
ObjectMeta: metav1.ObjectMeta{
Labels: ephemeralVolumeSpec.GetMetadata().GetLabels(),
Annotations: ephemeralVolumeSpec.GetMetadata().GetAnnotations(),
},
Spec: k8score.PersistentVolumeClaimSpec{
AccessModes: accessModes,
Resources: k8score.ResourceRequirements{
Requests: k8score.ResourceList{
k8score.ResourceStorage: k8sres.MustParse(ephemeralVolumeSpec.GetSize()),
},
},
StorageClassName: storageClassName,
},
},
},
},
}
ephemeralVolumeMount := k8score.VolumeMount{
Name: ephemeralVolumeSpec.GetVolumeName(),
MountPath: ephemeralVolumeSpec.GetMountPath(),
}
podSpec.Volumes = append(podSpec.Volumes, ephemeralVolume)
podSpec.Containers[0].VolumeMounts = append(podSpec.Containers[0].VolumeMounts, ephemeralVolumeMount)
}
return nil
}
// TODO(Bobgy): merge DAG driver and container driver, because they are very similar.
func DAG(ctx context.Context, opts Options, mlmd *metadata.Client) (execution *Execution, err error) {
defer func() {
if err != nil {
err = fmt.Errorf("driver.DAG(%s) failed: %w", opts.info(), err)
}
}()
err = validateDAG(opts)
if err != nil {
return nil, err
}
var iterationIndex *int
if opts.IterationIndex >= 0 {
index := opts.IterationIndex
iterationIndex = &index
}
// TODO(Bobgy): there's no need to pass any parameters, because pipeline
// and pipeline run context have been created by root DAG driver.
pipeline, err := mlmd.GetPipeline(ctx, opts.PipelineName, opts.RunID, "", "", "", "")
if err != nil {
return nil, err
}
dag, err := mlmd.GetDAG(ctx, opts.DAGExecutionID)
if err != nil {
return nil, err
}
glog.Infof("parent DAG: %+v", dag.Execution)
expr, err := expression.New()
if err != nil {
return nil, err
}
inputs, err := resolveInputs(ctx, dag, iterationIndex, pipeline, opts.Task, opts.Component.GetInputDefinitions(), mlmd, expr)
if err != nil {
return nil, err
}
executorInput := &pipelinespec.ExecutorInput{
Inputs: inputs,
}
glog.Infof("executorInput value: %+v", executorInput)
execution = &Execution{ExecutorInput: executorInput}
condition := opts.Task.GetTriggerPolicy().GetCondition()
if condition != "" {
willTrigger, err := expr.Condition(executorInput, condition)
if err != nil {
return execution, err
}
execution.Condition = &willTrigger
}
ecfg, err := metadata.GenerateExecutionConfig(executorInput)
if err != nil {
return execution, err
}
ecfg.TaskName = opts.Task.GetTaskInfo().GetName()
ecfg.ExecutionType = metadata.DagExecutionTypeName
ecfg.ParentDagID = dag.Execution.GetID()
ecfg.IterationIndex = iterationIndex
ecfg.NotTriggered = !execution.WillTrigger()
if opts.Task.GetArtifactIterator() != nil {
return execution, fmt.Errorf("ArtifactIterator is not implemented")
}
isIterator := opts.Task.GetParameterIterator() != nil && opts.IterationIndex < 0
// Fan out iterations
if execution.WillTrigger() && isIterator {
iterator := opts.Task.GetParameterIterator()
report := func(err error) error {
return fmt.Errorf("iterating on item input %q failed: %w", iterator.GetItemInput(), err)
}
// Check the items type of parameterIterator:
// It can be "inputParameter" or "Raw"
var value *structpb.Value
switch iterator.GetItems().GetKind().(type) {
case *pipelinespec.ParameterIteratorSpec_ItemsSpec_InputParameter:
var ok bool
value, ok = executorInput.GetInputs().GetParameterValues()[iterator.GetItems().GetInputParameter()]
if !ok {
return execution, report(fmt.Errorf("cannot find input parameter"))
}
case *pipelinespec.ParameterIteratorSpec_ItemsSpec_Raw:
value_raw := iterator.GetItems().GetRaw()
var unmarshalled_raw interface{}
err = json.Unmarshal([]byte(value_raw), &unmarshalled_raw)
if err != nil {
return execution, fmt.Errorf("error unmarshall raw string: %q", err)
}
value, err = structpb.NewValue(unmarshalled_raw)
if err != nil {
return execution, fmt.Errorf("error converting unmarshalled raw string into protobuf Value type: %q", err)
}
// Add the raw input to the executor input
execution.ExecutorInput.Inputs.ParameterValues[iterator.GetItemInput()] = value
default:
return execution, fmt.Errorf("cannot find parameter iterator")
}
items, err := getItems(value)
if err != nil {
return execution, report(err)
}
count := len(items)
ecfg.IterationCount = &count
execution.IterationCount = &count
}
// TODO(Bobgy): change execution state to pending, because this is driver, execution hasn't started.
createdExecution, err := mlmd.CreateExecution(ctx, pipeline, ecfg)
if err != nil {
return execution, err
}
glog.Infof("Created execution: %s", createdExecution)
execution.ID = createdExecution.GetID()
return execution, nil
}
// Get iteration items from a structpb.Value.
// Return value may be
// * a list of JSON serializable structs
// * a list of structpb.Value
func getItems(value *structpb.Value) (items []*structpb.Value, err error) {
switch v := value.GetKind().(type) {
case *structpb.Value_ListValue:
return v.ListValue.GetValues(), nil
case *structpb.Value_StringValue:
listValue := structpb.Value{}
if err = listValue.UnmarshalJSON([]byte(v.StringValue)); err != nil {
return nil, err
}
return listValue.GetListValue().GetValues(), nil
default:
return nil, fmt.Errorf("value of type %T cannot be iterated", v)
}
}
func reuseCachedOutputs(ctx context.Context, executorInput *pipelinespec.ExecutorInput, outputDefinitions *pipelinespec.ComponentOutputsSpec, mlmd *metadata.Client, cachedMLMDExecutionID string) (*pipelinespec.ExecutorOutput, []*metadata.OutputArtifact, error) {
cachedMLMDExecutionIDInt64, err := strconv.ParseInt(cachedMLMDExecutionID, 10, 64)
if err != nil {
return nil, nil, fmt.Errorf("failure while transfering cachedMLMDExecutionID %s from string to int64: %w", cachedMLMDExecutionID, err)
}
execution, err := mlmd.GetExecution(ctx, cachedMLMDExecutionIDInt64)
if err != nil {
return nil, nil, fmt.Errorf("failure while getting execution of cachedMLMDExecutionID %v: %w", cachedMLMDExecutionIDInt64, err)
}
executorOutput := &pipelinespec.ExecutorOutput{
Artifacts: map[string]*pipelinespec.ArtifactList{},
}
_, outputs, err := execution.GetParameters()
if err != nil {
return nil, nil, fmt.Errorf("failed to collect output parameters from cache: %w", err)
}
executorOutput.ParameterValues = outputs
outputArtifacts, err := collectOutputArtifactMetadataFromCache(ctx, executorInput, cachedMLMDExecutionIDInt64, mlmd)
if err != nil {
return nil, nil, fmt.Errorf("failed collect output artifact metadata from cache: %w", err)
}
return executorOutput, outputArtifacts, nil
}
func collectOutputArtifactMetadataFromCache(ctx context.Context, executorInput *pipelinespec.ExecutorInput, cachedMLMDExecutionID int64, mlmd *metadata.Client) ([]*metadata.OutputArtifact, error) {
outputArtifacts, err := mlmd.GetOutputArtifactsByExecutionId(ctx, cachedMLMDExecutionID)
if err != nil {
return nil, fmt.Errorf("failed to get MLMDOutputArtifactsByName by executionId %v: %w", cachedMLMDExecutionID, err)
}
// Register artifacts with MLMD.
registeredMLMDArtifacts := make([]*metadata.OutputArtifact, 0, len(executorInput.GetOutputs().GetArtifacts()))
for name, artifactList := range executorInput.GetOutputs().GetArtifacts() {
if len(artifactList.Artifacts) == 0 {
continue
}
artifact := artifactList.Artifacts[0]
outputArtifact, ok := outputArtifacts[name]
if !ok {
return nil, fmt.Errorf("unable to find artifact with name %v in mlmd output artifacts", name)
}
outputArtifact.Schema = artifact.GetType().GetInstanceSchema()
registeredMLMDArtifacts = append(registeredMLMDArtifacts, outputArtifact)
}
return registeredMLMDArtifacts, nil
}
func getFingerPrint(opts Options, executorInput *pipelinespec.ExecutorInput) (string, error) {
outputParametersTypeMap := make(map[string]string)
for outputParamName, outputParamSpec := range opts.Component.GetOutputDefinitions().GetParameters() {
outputParametersTypeMap[outputParamName] = outputParamSpec.GetParameterType().String()
}
userCmdArgs := make([]string, 0, len(opts.Container.Command)+len(opts.Container.Args))
userCmdArgs = append(userCmdArgs, opts.Container.Command...)
userCmdArgs = append(userCmdArgs, opts.Container.Args...)
cacheKey, err := cacheutils.GenerateCacheKey(executorInput.GetInputs(), executorInput.GetOutputs(), outputParametersTypeMap, userCmdArgs, opts.Container.Image)
if err != nil {
return "", fmt.Errorf("failure while generating CacheKey: %w", err)
}
fingerPrint, err := cacheutils.GenerateFingerPrint(cacheKey)
return fingerPrint, err
}
func validateContainer(opts Options) (err error) {
defer func() {
if err != nil {
err = fmt.Errorf("invalid container driver args: %w", err)
}
}()
if opts.Container == nil {
return fmt.Errorf("container spec is required")
}
return validateNonRoot(opts)
}
func validateDAG(opts Options) (err error) {
defer func() {
if err != nil {
err = fmt.Errorf("invalid DAG driver args: %w", err)
}
}()
if opts.Container != nil {
return fmt.Errorf("container spec is unnecessary")
}
return validateNonRoot(opts)
}
func validateNonRoot(opts Options) error {
if opts.PipelineName == "" {
return fmt.Errorf("pipeline name is required")
}
if opts.RunID == "" {
return fmt.Errorf("KFP run ID is required")
}
if opts.Component == nil {
return fmt.Errorf("component spec is required")
}
if opts.Task.GetTaskInfo().GetName() == "" {
return fmt.Errorf("task spec is required")
}
if opts.RuntimeConfig != nil {
return fmt.Errorf("runtime config is unnecessary")
}
if opts.DAGExecutionID == 0 {
return fmt.Errorf("DAG execution ID is required")
}
return nil
}
func resolveInputs(ctx context.Context, dag *metadata.DAG, iterationIndex *int, pipeline *metadata.Pipeline, task *pipelinespec.PipelineTaskSpec, inputsSpec *pipelinespec.ComponentInputsSpec, mlmd *metadata.Client, expr *expression.Expr) (inputs *pipelinespec.ExecutorInput_Inputs, err error) {
defer func() {
if err != nil {
err = fmt.Errorf("failed to resolve inputs: %w", err)
}
}()
inputParams, _, err := dag.Execution.GetParameters()
if err != nil {
return nil, err
}
inputArtifacts, err := mlmd.GetInputArtifactsByExecutionID(ctx, dag.Execution.GetID())
if err != nil {
return nil, err
}
glog.Infof("parent DAG input parameters: %+v, artifacts: %+v", inputParams, inputArtifacts)
inputs = &pipelinespec.ExecutorInput_Inputs{
ParameterValues: make(map[string]*structpb.Value),
Artifacts: make(map[string]*pipelinespec.ArtifactList),
}
isIterationDriver := iterationIndex != nil
handleParameterExpressionSelector := func() error {
for name, paramSpec := range task.GetInputs().GetParameters() {
var selector string
if selector = paramSpec.GetParameterExpressionSelector(); selector == "" {
continue
}
wrap := func(e error) error {
return fmt.Errorf("resolving parameter %q: evaluation of parameter expression selector %q failed: %w", name, selector, e)
}
value, ok := inputs.ParameterValues[name]
if !ok {
return wrap(fmt.Errorf("value not found in inputs"))
}
selected, err := expr.Select(value, selector)
if err != nil {
return wrap(err)
}
inputs.ParameterValues[name] = selected
}
return nil
}
handleParamTypeValidationAndConversion := func() error {
// TODO(Bobgy): verify whether there are inputs not in the inputs spec.
for name, spec := range inputsSpec.GetParameters() {
if task.GetParameterIterator() != nil {
if !isIterationDriver && task.GetParameterIterator().GetItemInput() == name {
// It's expected that an iterator does not have iteration item input parameter,
// because only iterations get the item input parameter.
continue
}
if isIterationDriver && task.GetParameterIterator().GetItems().GetInputParameter() == name {
// It's expected that an iteration does not have iteration items input parameter,
// because only the iterator has it.
continue
}
}
value, hasValue := inputs.GetParameterValues()[name]
// Handle when parameter does not have input value
if !hasValue && !inputsSpec.GetParameters()[name].GetIsOptional() {
// When parameter is not optional and there is no input value, first check if there is a default value,
// if there is a default value, use it as the value of the parameter.
// if there is no default value, report error.
if inputsSpec.GetParameters()[name].GetDefaultValue() == nil {
return fmt.Errorf("neither value nor default value provided for non-optional parameter %q", name)
}
} else if !hasValue && inputsSpec.GetParameters()[name].GetIsOptional() {
// When parameter is optional and there is no input value, value comes from default value.
// But we don't pass the default value here. They are resolved internally within the component.
// Note: in the past the backend passed the default values into the component. This is a behavior change.
// See discussion: https://github.com/kubeflow/pipelines/pull/8765#discussion_r1119477085
continue
}
switch spec.GetParameterType() {
case pipelinespec.ParameterType_STRING:
_, isValueString := value.GetKind().(*structpb.Value_StringValue)
if !isValueString {
// TODO(Bobgy): discuss whether we want to allow auto type conversion
// all parameter types can be consumed as JSON string
text, err := metadata.PbValueToText(value)
if err != nil {
return fmt.Errorf("converting input parameter %q to string: %w", name, err)
}
inputs.GetParameterValues()[name] = structpb.NewStringValue(text)
}
default:
typeMismatch := func(actual string) error {