-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
resource_manager.go
1293 lines (1143 loc) · 47.1 KB
/
resource_manager.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 2018 Google LLC
//
// 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 resource
import (
"encoding/json"
"fmt"
"io"
"strconv"
workflowapi "github.com/argoproj/argo/pkg/apis/workflow/v1alpha1"
workflowclient "github.com/argoproj/argo/pkg/client/clientset/versioned/typed/workflow/v1alpha1"
"github.com/cenkalti/backoff"
"github.com/golang/glog"
api "github.com/kubeflow/pipelines/backend/api/go_client"
"github.com/kubeflow/pipelines/backend/src/apiserver/archive"
"github.com/kubeflow/pipelines/backend/src/apiserver/client"
"github.com/kubeflow/pipelines/backend/src/apiserver/common"
"github.com/kubeflow/pipelines/backend/src/apiserver/list"
"github.com/kubeflow/pipelines/backend/src/apiserver/model"
"github.com/kubeflow/pipelines/backend/src/apiserver/storage"
"github.com/kubeflow/pipelines/backend/src/common/util"
scheduledworkflow "github.com/kubeflow/pipelines/backend/src/crd/pkg/apis/scheduledworkflow/v1beta1"
scheduledworkflowclient "github.com/kubeflow/pipelines/backend/src/crd/pkg/client/clientset/versioned/typed/scheduledworkflow/v1beta1"
"github.com/pkg/errors"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promauto"
authorizationv1 "k8s.io/api/authorization/v1"
corev1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
)
const (
defaultPipelineRunnerServiceAccount = "pipeline-runner"
HasDefaultBucketEnvVar = "HAS_DEFAULT_BUCKET"
ProjectIDEnvVar = "PROJECT_ID"
DefaultBucketNameEnvVar = "BUCKET_NAME"
)
// Metric variables. Please prefix the metric names with resource_manager_.
var (
// Count the removed workflows due to garbage collection.
workflowGCCounter = promauto.NewCounter(prometheus.CounterOpts{
Name: "resource_manager_workflow_gc",
Help: "The number of gabarage-collected workflows",
})
)
type ClientManagerInterface interface {
ExperimentStore() storage.ExperimentStoreInterface
PipelineStore() storage.PipelineStoreInterface
JobStore() storage.JobStoreInterface
RunStore() storage.RunStoreInterface
ResourceReferenceStore() storage.ResourceReferenceStoreInterface
DBStatusStore() storage.DBStatusStoreInterface
DefaultExperimentStore() storage.DefaultExperimentStoreInterface
ObjectStore() storage.ObjectStoreInterface
ArgoClient() client.ArgoClientInterface
SwfClient() client.SwfClientInterface
KubernetesCoreClient() client.KubernetesCoreInterface
SubjectAccessReviewClient() client.SubjectAccessReviewInterface
LogArchive() archive.LogArchiveInterface
Time() util.TimeInterface
UUID() util.UUIDGeneratorInterface
}
type ResourceManager struct {
experimentStore storage.ExperimentStoreInterface
pipelineStore storage.PipelineStoreInterface
jobStore storage.JobStoreInterface
runStore storage.RunStoreInterface
resourceReferenceStore storage.ResourceReferenceStoreInterface
dBStatusStore storage.DBStatusStoreInterface
defaultExperimentStore storage.DefaultExperimentStoreInterface
objectStore storage.ObjectStoreInterface
argoClient client.ArgoClientInterface
swfClient client.SwfClientInterface
k8sCoreClient client.KubernetesCoreInterface
subjectAccessReviewClient client.SubjectAccessReviewInterface
logArchive archive.LogArchiveInterface
time util.TimeInterface
uuid util.UUIDGeneratorInterface
}
func NewResourceManager(clientManager ClientManagerInterface) *ResourceManager {
return &ResourceManager{
experimentStore: clientManager.ExperimentStore(),
pipelineStore: clientManager.PipelineStore(),
jobStore: clientManager.JobStore(),
runStore: clientManager.RunStore(),
resourceReferenceStore: clientManager.ResourceReferenceStore(),
dBStatusStore: clientManager.DBStatusStore(),
defaultExperimentStore: clientManager.DefaultExperimentStore(),
objectStore: clientManager.ObjectStore(),
argoClient: clientManager.ArgoClient(),
swfClient: clientManager.SwfClient(),
k8sCoreClient: clientManager.KubernetesCoreClient(),
subjectAccessReviewClient: clientManager.SubjectAccessReviewClient(),
logArchive: clientManager.LogArchive(),
time: clientManager.Time(),
uuid: clientManager.UUID(),
}
}
func (r *ResourceManager) getWorkflowClient(namespace string) workflowclient.WorkflowInterface {
return r.argoClient.Workflow(namespace)
}
func (r *ResourceManager) getScheduledWorkflowClient(namespace string) scheduledworkflowclient.ScheduledWorkflowInterface {
return r.swfClient.ScheduledWorkflow(namespace)
}
func (r *ResourceManager) GetTime() util.TimeInterface {
return r.time
}
func (r *ResourceManager) CreateExperiment(apiExperiment *api.Experiment) (*model.Experiment, error) {
experiment, err := r.ToModelExperiment(apiExperiment)
if err != nil {
return nil, util.Wrap(err, "Failed to convert experiment model")
}
return r.experimentStore.CreateExperiment(experiment)
}
func (r *ResourceManager) GetExperiment(experimentId string) (*model.Experiment, error) {
return r.experimentStore.GetExperiment(experimentId)
}
func (r *ResourceManager) ListExperiments(filterContext *common.FilterContext, opts *list.Options) (
experiments []*model.Experiment, total_size int, nextPageToken string, err error) {
return r.experimentStore.ListExperiments(filterContext, opts)
}
func (r *ResourceManager) DeleteExperiment(experimentID string) error {
_, err := r.experimentStore.GetExperiment(experimentID)
if err != nil {
return util.Wrap(err, "Delete experiment failed")
}
return r.experimentStore.DeleteExperiment(experimentID)
}
func (r *ResourceManager) ArchiveExperiment(experimentId string) error {
// To archive an experiment
// (1) update our persistent agent to disable CRDs of jobs in experiment
// (2) update database to
// (2.1) archive experiemnts
// (2.2) archive runs
// (2.3) disable jobs
opts, err := list.NewOptions(&model.Job{}, 50, "name", nil)
if err != nil {
return util.NewInternalServerError(err,
"Failed to create list jobs options when archiving experiment. ")
}
for {
jobs, _, newToken, err := r.jobStore.ListJobs(&common.FilterContext{
ReferenceKey: &common.ReferenceKey{Type: common.Experiment, ID: experimentId}}, opts)
if err != nil {
return util.NewInternalServerError(err,
"Failed to list jobs of to-be-archived experiment. expID: %v", experimentId)
}
for _, job := range jobs {
_, err = r.getScheduledWorkflowClient(job.Namespace).Patch(
job.Name,
types.MergePatchType,
[]byte(fmt.Sprintf(`{"spec":{"enabled":%s}}`, strconv.FormatBool(false))))
if err != nil {
return util.NewInternalServerError(err,
"Failed to disable job CR. jobID: %v", job.UUID)
}
}
if newToken == "" {
break
} else {
opts, err = list.NewOptionsFromToken(newToken, 50)
if err != nil {
return util.NewInternalServerError(err,
"Failed to create list jobs options from page token when archiving experiment. ")
}
}
}
return r.experimentStore.ArchiveExperiment(experimentId)
}
func (r *ResourceManager) UnarchiveExperiment(experimentId string) error {
return r.experimentStore.UnarchiveExperiment(experimentId)
}
func (r *ResourceManager) ListPipelines(opts *list.Options) (
pipelines []*model.Pipeline, total_size int, nextPageToken string, err error) {
return r.pipelineStore.ListPipelines(opts)
}
func (r *ResourceManager) GetPipeline(pipelineId string) (*model.Pipeline, error) {
return r.pipelineStore.GetPipeline(pipelineId)
}
func (r *ResourceManager) DeletePipeline(pipelineId string) error {
_, err := r.pipelineStore.GetPipeline(pipelineId)
if err != nil {
return util.Wrap(err, "Delete pipeline failed")
}
// Mark pipeline as deleting so it's not visible to user.
err = r.pipelineStore.UpdatePipelineStatus(pipelineId, model.PipelineDeleting)
if err != nil {
return util.Wrap(err, "Delete pipeline failed")
}
// Delete pipeline file and DB entry.
// Not fail the request if this step failed. A background run will do the cleanup.
// https://github.com/kubeflow/pipelines/issues/388
// TODO(jingzhang36): For now (before exposing version API), we have only 1
// file with both pipeline and version pointing to it; so it is ok to do
// the deletion as follows. After exposing version API, we can have multiple
// versions and hence multiple files, and we shall improve performance by
// either using async deletion in order for this method to be non-blocking
// or or exploring other performance optimization tools provided by gcs.
err = r.objectStore.DeleteFile(r.objectStore.GetPipelineKey(fmt.Sprint(pipelineId)))
if err != nil {
glog.Errorf("%v", errors.Wrapf(err, "Failed to delete pipeline file for pipeline %v", pipelineId))
return nil
}
err = r.pipelineStore.DeletePipeline(pipelineId)
if err != nil {
glog.Errorf("%v", errors.Wrapf(err, "Failed to delete pipeline DB entry for pipeline %v", pipelineId))
}
return nil
}
func (r *ResourceManager) UpdatePipelineDefaultVersion(pipelineId string, versionId string) error {
return r.pipelineStore.UpdatePipelineDefaultVersion(pipelineId, versionId)
}
func (r *ResourceManager) CreatePipeline(name string, description string, pipelineFile []byte) (*model.Pipeline, error) {
// Extract the parameter from the pipeline
params, err := util.GetParameters(pipelineFile)
if err != nil {
return nil, util.Wrap(err, "Create pipeline failed")
}
// Create an entry with status of creating the pipeline
pipeline := &model.Pipeline{
Name: name,
Description: description,
Parameters: params,
Status: model.PipelineCreating,
DefaultVersion: &model.PipelineVersion{
Name: name,
Parameters: params,
Status: model.PipelineVersionCreating}}
newPipeline, err := r.pipelineStore.CreatePipeline(pipeline)
if err != nil {
return nil, util.Wrap(err, "Create pipeline failed")
}
// Store the pipeline file to a path dependent on pipeline version
err = r.objectStore.AddFile(pipelineFile,
r.objectStore.GetPipelineKey(fmt.Sprint(newPipeline.DefaultVersion.UUID)))
if err != nil {
return nil, util.Wrap(err, "Create pipeline failed")
}
newPipeline.Status = model.PipelineReady
newPipeline.DefaultVersion.Status = model.PipelineVersionReady
err = r.pipelineStore.UpdatePipelineAndVersionsStatus(
newPipeline.UUID,
newPipeline.Status,
newPipeline.DefaultVersionId,
newPipeline.DefaultVersion.Status)
if err != nil {
return nil, util.Wrap(err, "Create pipeline failed")
}
return newPipeline, nil
}
func (r *ResourceManager) UpdatePipelineStatus(pipelineId string, status model.PipelineStatus) error {
return r.pipelineStore.UpdatePipelineStatus(pipelineId, status)
}
func (r *ResourceManager) UpdatePipelineVersionStatus(pipelineId string, status model.PipelineVersionStatus) error {
return r.pipelineStore.UpdatePipelineVersionStatus(pipelineId, status)
}
func (r *ResourceManager) GetPipelineTemplate(pipelineId string) ([]byte, error) {
// Verify pipeline exist
pipeline, err := r.pipelineStore.GetPipeline(pipelineId)
if err != nil {
return nil, util.Wrap(err, "Get pipeline template failed")
}
if pipeline.DefaultVersion == nil {
return nil, util.Wrap(err,
"Get pipeline template failed since no default version is defined")
}
template, err := r.objectStore.GetFile(r.objectStore.GetPipelineKey(fmt.Sprint(pipeline.DefaultVersion.UUID)))
if err != nil {
return nil, util.Wrap(err, "Get pipeline template failed")
}
return template, nil
}
func (r *ResourceManager) CreateRun(apiRun *api.Run) (*model.RunDetail, error) {
// Get workflow from either of the two places:
// (1) raw pipeline manifest in pipeline_spec
// (2) pipeline version in resource_references
// And the latter takes priority over the former
var workflowSpecManifestBytes []byte
err := ConvertPipelineIdToDefaultPipelineVersion(apiRun.PipelineSpec, &apiRun.ResourceReferences, r)
if err != nil {
return nil, util.Wrap(err, "Failed to find default version to create run with pipeline id.")
}
workflowSpecManifestBytes, err = r.getWorkflowSpecBytesFromPipelineVersion(apiRun.GetResourceReferences())
if err != nil {
workflowSpecManifestBytes, err = r.getWorkflowSpecBytesFromPipelineSpec(apiRun.GetPipelineSpec())
if err != nil {
return nil, util.Wrap(err, "Failed to fetch workflow spec.")
}
}
uuid, err := r.uuid.NewRandom()
if err != nil {
return nil, util.NewInternalServerError(err, "Failed to generate run ID.")
}
runId := uuid.String()
var workflow util.Workflow
if err = json.Unmarshal(workflowSpecManifestBytes, &workflow); err != nil {
return nil, util.NewInternalServerError(err,
"Failed to unmarshal workflow spec manifest. Workflow bytes: %s", string(workflowSpecManifestBytes))
}
if workflow.Workflow == nil {
return nil, util.Wrap(
util.NewResourceNotFoundError("WorkflowSpecManifest", apiRun.GetName()),
"Failed to fetch workflow spec manifest.")
}
parameters := toParametersMap(apiRun.GetPipelineSpec().GetParameters())
// Verify no additional parameter provided
if err = workflow.VerifyParameters(parameters); err != nil {
return nil, util.Wrap(err, "Failed to verify parameters.")
}
r.setDefaultServiceAccount(&workflow, apiRun.GetServiceAccount())
// Disable istio sidecar injection
workflow.SetAnnotationsToAllTemplates(util.AnnotationKeyIstioSidecarInject, util.AnnotationValueIstioSidecarInjectDisabled)
// Add a KFP specific label for cache service filtering. The cache_enabled flag here is a global control for whether cache server will
// receive targeting pods. Since cache server only receives pods in step level, the resource manager here will set this global label flag
// on every single step/pod so the cache server can understand.
// TODO: Add run_level flag with similar logic by reading flag value from create_run api.
workflow.SetLabelsToAllTemplates(util.LabelKeyCacheEnabled, common.IsCacheEnabled())
// Append provided parameter
workflow.OverrideParameters(parameters)
err = OverrideParameterWithSystemDefault(workflow, apiRun)
if err != nil {
return nil, err
}
// Add label to the workflow so it can be persisted by persistent agent later.
workflow.SetLabels(util.LabelKeyWorkflowRunId, runId)
// Add run name annotation to the workflow so that it can be logged by the Metadata Writer.
workflow.SetAnnotations(util.AnnotationKeyRunName, apiRun.Name)
// Replace {{workflow.uid}} with runId
err = workflow.ReplaceUID(runId)
if err != nil {
return nil, util.NewInternalServerError(err, "Failed to replace workflow ID")
}
// Marking auto-added artifacts as optional. Otherwise most older workflows will start failing after upgrade to Argo 2.3.
// TODO: Fix the components to explicitly declare the artifacts they really output.
for templateIdx, template := range workflow.Workflow.Spec.Templates {
for artIdx, artifact := range template.Outputs.Artifacts {
if artifact.Name == "mlpipeline-ui-metadata" || artifact.Name == "mlpipeline-metrics" {
workflow.Workflow.Spec.Templates[templateIdx].Outputs.Artifacts[artIdx].Optional = true
}
}
}
// Add a reference to the default experiment if run does not already have a containing experiment
ref, err := r.getDefaultExperimentIfNoExperiment(apiRun.GetResourceReferences())
if err != nil {
return nil, err
}
if ref != nil {
apiRun.ResourceReferences = append(apiRun.GetResourceReferences(), ref)
}
namespace, err := r.getNamespaceFromExperiment(apiRun.GetResourceReferences())
if err != nil {
return nil, err
}
// Create argo workflow CR resource
newWorkflow, err := r.getWorkflowClient(namespace).Create(workflow.Get())
if err != nil {
return nil, util.NewInternalServerError(err, "Failed to create a workflow for (%s)", workflow.Name)
}
// Store run metadata into database
runDetail, err := r.ToModelRunDetail(apiRun, runId, util.NewWorkflow(newWorkflow), string(workflowSpecManifestBytes))
if err != nil {
return nil, util.Wrap(err, "Failed to convert run model")
}
// Assign the create at time.
runDetail.CreatedAtInSec = r.time.Now().Unix()
return r.runStore.CreateRun(runDetail)
}
func (r *ResourceManager) GetRun(runId string) (*model.RunDetail, error) {
return r.runStore.GetRun(runId)
}
func (r *ResourceManager) ListRuns(filterContext *common.FilterContext,
opts *list.Options) (runs []*model.Run, total_size int, nextPageToken string, err error) {
return r.runStore.ListRuns(filterContext, opts)
}
func (r *ResourceManager) ArchiveRun(runId string) error {
return r.runStore.ArchiveRun(runId)
}
func (r *ResourceManager) UnarchiveRun(runId string) error {
return r.runStore.UnarchiveRun(runId)
}
func (r *ResourceManager) DeleteRun(runID string) error {
runDetail, err := r.checkRunExist(runID)
if err != nil {
return util.Wrap(err, "Delete run failed")
}
namespace, err := r.GetNamespaceFromRunID(runID)
if err != nil {
return util.Wrap(err, "Delete run failed")
}
err = r.getWorkflowClient(namespace).Delete(runDetail.Name, &v1.DeleteOptions{})
if err != nil {
// API won't need to delete the workflow CR
// once persistent agent sync the state to DB and set TTL for it.
glog.Warningf("Failed to delete run %v. Error: %v", runDetail.Name, err.Error())
}
err = r.runStore.DeleteRun(runID)
if err != nil {
return util.Wrap(err, "Delete run failed")
}
return nil
}
func (r *ResourceManager) ListJobs(filterContext *common.FilterContext,
opts *list.Options) (jobs []*model.Job, total_size int, nextPageToken string, err error) {
return r.jobStore.ListJobs(filterContext, opts)
}
// TerminateWorkflow terminates a workflow by setting its activeDeadlineSeconds to 0
func TerminateWorkflow(wfClient workflowclient.WorkflowInterface, name string) error {
patchObj := map[string]interface{}{
"spec": map[string]interface{}{
"activeDeadlineSeconds": 0,
},
}
patch, err := json.Marshal(patchObj)
if err != nil {
return util.NewInternalServerError(err, "Unexpected error while marshalling a patch object.")
}
var operation = func() error {
_, err = wfClient.Patch(name, types.MergePatchType, patch)
return err
}
var backoffPolicy = backoff.WithMaxRetries(backoff.NewConstantBackOff(100), 10)
err = backoff.Retry(operation, backoffPolicy)
return err
}
func (r *ResourceManager) TerminateRun(runId string) error {
runDetail, err := r.checkRunExist(runId)
if err != nil {
return util.Wrap(err, "Terminate run failed")
}
namespace, err := r.GetNamespaceFromRunID(runId)
if err != nil {
return util.Wrap(err, "Terminate run failed")
}
err = r.runStore.TerminateRun(runId)
if err != nil {
return util.Wrap(err, "Terminate run failed")
}
err = TerminateWorkflow(r.getWorkflowClient(namespace), runDetail.Run.Name)
if err != nil {
return util.NewInternalServerError(err, "Failed to terminate the run")
}
return nil
}
func (r *ResourceManager) RetryRun(runId string) error {
runDetail, err := r.checkRunExist(runId)
if err != nil {
return util.Wrap(err, "Retry run failed")
}
namespace, err := r.GetNamespaceFromRunID(runId)
if err != nil {
return util.Wrap(err, "Retry run failed")
}
if runDetail.WorkflowRuntimeManifest == "" {
return util.NewBadRequestError(errors.New("workflow cannot be retried"), "Workflow must be Failed/Error to retry")
}
var workflow util.Workflow
if err := json.Unmarshal([]byte(runDetail.WorkflowRuntimeManifest), &workflow); err != nil {
return util.NewInternalServerError(err, "Failed to retrieve the runtime pipeline spec from the run")
}
newWorkflow, podsToDelete, err := formulateRetryWorkflow(&workflow)
if err != nil {
return util.Wrap(err, "Retry run failed.")
}
if err = deletePods(r.k8sCoreClient, podsToDelete, namespace); err != nil {
return util.NewInternalServerError(err, "Retry run failed. Failed to clean up the failed pods from previous run.")
}
// First try to update workflow
updateError := r.updateWorkflow(newWorkflow, namespace)
if updateError != nil {
// Remove resource version
newWorkflow.ResourceVersion = ""
newCreatedWorkflow, createError := r.getWorkflowClient(namespace).Create(newWorkflow.Workflow)
if createError != nil {
return util.NewInternalServerError(createError,
"Retry run failed. Failed to create or update the run. Update Error: %s, Create Error: %s",
updateError.Error(), createError.Error())
}
newWorkflow = util.NewWorkflow(newCreatedWorkflow)
}
err = r.runStore.UpdateRun(runId, newWorkflow.Condition(), 0, newWorkflow.ToStringForStore())
if err != nil {
return util.NewInternalServerError(err, "Failed to update the database entry.")
}
return nil
}
func (r *ResourceManager) ReadLog(runId string, nodeId string, follow bool, dst io.Writer) error {
run, err := r.checkRunExist(runId)
if err != nil {
return util.NewBadRequestError(errors.New("log cannot be read"), "Run does not exist")
}
err = r.readRunLogFromPod(run, nodeId, follow, dst)
if err != nil && r.logArchive != nil {
err = r.readRunLogFromArchive(run, nodeId, dst)
}
return err
}
func (r *ResourceManager) readRunLogFromPod(run *model.RunDetail, nodeId string, follow bool, dst io.Writer) error {
logOptions := corev1.PodLogOptions{
Container: "main",
Timestamps: false,
Follow: follow,
}
req := r.k8sCoreClient.PodClient(run.Namespace).GetLogs(nodeId, &logOptions)
podLogs, err := req.Stream()
if err != nil {
if !apierrors.IsNotFound(err) {
glog.Errorf("Failed to access Pod log: %v", err)
}
return util.NewInternalServerError(err, "error in opening log stream")
}
defer podLogs.Close()
_, err = io.Copy(dst, podLogs)
if err != nil && err != io.EOF {
return util.NewInternalServerError(err, "error in streaming the log")
}
return nil
}
func (r *ResourceManager) readRunLogFromArchive(run *model.RunDetail, nodeId string, dst io.Writer) error {
workflow := new(util.Workflow)
if run.WorkflowRuntimeManifest == "" {
return util.NewBadRequestError(errors.New("archived log cannot be read"), "Failed to retrieve the runtime workflow from the run")
}
if err := json.Unmarshal([]byte(run.WorkflowRuntimeManifest), &workflow); err != nil {
return util.NewInternalServerError(err, "Failed to retrieve the runtime pipeline spec from the run")
}
logPath, err := r.logArchive.GetLogObjectKey(workflow, nodeId)
if err != nil {
return err
}
logContent, err := r.objectStore.GetFile(logPath)
if err != nil {
return util.NewInternalServerError(err, "Failed to retrieve the log file from archive")
}
err = r.logArchive.CopyLogFromArchive(logContent, dst, archive.ExtractLogOptions{LogFormat: archive.LogFormatText, Timestamps: false})
if err != nil {
return util.NewInternalServerError(err, "error in streaming the log")
}
return nil
}
func (r *ResourceManager) updateWorkflow(newWorkflow *util.Workflow, namespace string) error {
// If fail to get the workflow, return error.
latestWorkflow, err := r.getWorkflowClient(namespace).Get(newWorkflow.Name, v1.GetOptions{})
if err != nil {
return err
}
// Update the workflow's resource version to latest.
newWorkflow.ResourceVersion = latestWorkflow.ResourceVersion
_, err = r.getWorkflowClient(namespace).Update(newWorkflow.Workflow)
return err
}
func (r *ResourceManager) GetJob(id string) (*model.Job, error) {
return r.jobStore.GetJob(id)
}
func (r *ResourceManager) CreateJob(apiJob *api.Job) (*model.Job, error) {
// Get workflow from either of the two places:
// (1) raw pipeline manifest in pipeline_spec
// (2) pipeline version in resource_references
// And the latter takes priority over the former
var workflowSpecManifestBytes []byte
err := ConvertPipelineIdToDefaultPipelineVersion(apiJob.PipelineSpec, &apiJob.ResourceReferences, r)
if err != nil {
return nil, util.Wrap(err, "Failed to find default version to create job with pipeline id.")
}
workflowSpecManifestBytes, err = r.getWorkflowSpecBytesFromPipelineVersion(apiJob.GetResourceReferences())
if err != nil {
workflowSpecManifestBytes, err = r.getWorkflowSpecBytesFromPipelineSpec(apiJob.GetPipelineSpec())
if err != nil {
return nil, util.Wrap(err, "Failed to fetch workflow spec.")
}
}
var workflow util.Workflow
err = json.Unmarshal(workflowSpecManifestBytes, &workflow)
if err != nil {
return nil, util.NewInternalServerError(err,
"Failed to unmarshal workflow spec manifest. Workflow bytes: %s", string(workflowSpecManifestBytes))
}
if workflow.Workflow == nil {
return nil, util.Wrap(
util.NewResourceNotFoundError("WorkflowSpecManifest", apiJob.GetName()),
"Failed to fetch workflow spec manifest.")
}
// Verify no additional parameter provided
err = workflow.VerifyParameters(toParametersMap(apiJob.GetPipelineSpec().GetParameters()))
if err != nil {
return nil, util.Wrap(err, "Create job failed")
}
r.setDefaultServiceAccount(&workflow, apiJob.GetServiceAccount())
// Disable istio sidecar injection
workflow.SetAnnotationsToAllTemplates(util.AnnotationKeyIstioSidecarInject, util.AnnotationValueIstioSidecarInjectDisabled)
swfGeneratedName, err := toSWFCRDResourceGeneratedName(apiJob.Name)
if err != nil {
return nil, util.Wrap(err, "Create job failed")
}
scheduledWorkflow := &scheduledworkflow.ScheduledWorkflow{
ObjectMeta: v1.ObjectMeta{GenerateName: swfGeneratedName},
Spec: scheduledworkflow.ScheduledWorkflowSpec{
Enabled: apiJob.Enabled,
MaxConcurrency: &apiJob.MaxConcurrency,
Trigger: *toCRDTrigger(apiJob.Trigger),
Workflow: &scheduledworkflow.WorkflowResource{
Parameters: toCRDParameter(apiJob.GetPipelineSpec().GetParameters()),
Spec: workflow.Spec,
},
NoCatchup: util.BoolPointer(apiJob.NoCatchup),
},
}
// Marking auto-added artifacts as optional. Otherwise most older workflows will start failing after upgrade to Argo 2.3.
// TODO: Fix the components to explicitly declare the artifacts they really output.
for templateIdx, template := range scheduledWorkflow.Spec.Workflow.Spec.Templates {
for artIdx, artifact := range template.Outputs.Artifacts {
if artifact.Name == "mlpipeline-ui-metadata" || artifact.Name == "mlpipeline-metrics" {
scheduledWorkflow.Spec.Workflow.Spec.Templates[templateIdx].Outputs.Artifacts[artIdx].Optional = true
}
}
}
// Add a reference to the default experiment if run does not already have a containing experiment
ref, err := r.getDefaultExperimentIfNoExperiment(apiJob.GetResourceReferences())
if err != nil {
return nil, err
}
if ref != nil {
apiJob.ResourceReferences = append(apiJob.GetResourceReferences(), ref)
}
namespace, err := r.getNamespaceFromExperiment(apiJob.GetResourceReferences())
if err != nil {
return nil, err
}
newScheduledWorkflow, err := r.getScheduledWorkflowClient(namespace).Create(scheduledWorkflow)
if err != nil {
return nil, util.NewInternalServerError(err, "Failed to create a scheduled workflow for (%s)", scheduledWorkflow.Name)
}
job, err := r.ToModelJob(apiJob, util.NewScheduledWorkflow(newScheduledWorkflow), string(workflowSpecManifestBytes))
if err != nil {
return nil, util.Wrap(err, "Create job failed")
}
now := r.time.Now().Unix()
job.CreatedAtInSec = now
job.UpdatedAtInSec = now
return r.jobStore.CreateJob(job)
}
func (r *ResourceManager) EnableJob(jobID string, enabled bool) error {
var job *model.Job
var err error
if enabled {
job, err = r.checkJobExist(jobID)
} else {
// We can skip custom resource existence verification, because disabling
// the job do not need to care about it.
job, err = r.jobStore.GetJob(jobID)
}
if err != nil {
return util.Wrap(err, "Enable/Disable job failed")
}
_, err = r.getScheduledWorkflowClient(job.Namespace).Patch(
job.Name,
types.MergePatchType,
[]byte(fmt.Sprintf(`{"spec":{"enabled":%s}}`, strconv.FormatBool(enabled))))
if err != nil {
return util.NewInternalServerError(err,
"Failed to enable/disable job CR. Enabled: %v, jobID: %v",
enabled, jobID)
}
err = r.jobStore.EnableJob(jobID, enabled)
if err != nil {
return util.Wrapf(err, "Failed to enable/disable job. Enabled: %v, jobID: %v",
enabled, jobID)
}
return nil
}
func (r *ResourceManager) DeleteJob(jobID string) error {
job, err := r.jobStore.GetJob(jobID)
if err != nil {
return util.Wrap(err, "Delete job failed")
}
err = r.getScheduledWorkflowClient(job.Namespace).Delete(job.Name, &v1.DeleteOptions{})
if err != nil {
if !util.IsNotFound(err) {
// For any error other than NotFound
return util.NewInternalServerError(err, "Delete job CR failed")
}
// The ScheduledWorkflow was not found.
glog.Infof("Deleting job '%v', but skipped deleting ScheduledWorkflow '%v' in namespace '%v' because it was not found. jobID: %v", job.Name, job.Name, job.Namespace, jobID)
// Continue the execution, because we want to delete the
// ScheduledWorkflow. We can skip deleting the ScheduledWorkflow
// when it no longer exists.
}
err = r.jobStore.DeleteJob(jobID)
if err != nil {
return util.Wrap(err, "Delete job failed")
}
return nil
}
func (r *ResourceManager) ReportWorkflowResource(workflow *util.Workflow) error {
if _, ok := workflow.ObjectMeta.Labels[util.LabelKeyWorkflowRunId]; !ok {
// Skip reporting if the workflow doesn't have the run id label
return util.NewInvalidInputError("Workflow[%s] missing the Run ID label", workflow.Name)
}
runId := workflow.ObjectMeta.Labels[util.LabelKeyWorkflowRunId]
jobId := workflow.ScheduledWorkflowUUIDAsStringOrEmpty()
if len(workflow.Namespace) == 0 {
return util.NewInvalidInputError("Workflow missing namespace")
}
if workflow.PersistedFinalState() {
// If workflow's final state has being persisted, the workflow should be garbage collected.
err := r.getWorkflowClient(workflow.Namespace).Delete(workflow.Name, &v1.DeleteOptions{})
if err != nil {
// A fix for kubeflow/pipelines#4484, persistence agent might have an outdated item in its workqueue, so it will
// report workflows that no longer exist. It's important to return a not found error, so that persistence
// agent won't retry again.
if util.IsNotFound(err) {
return util.NewNotFoundError(err, "Failed to delete the completed workflow for run %s", runId)
} else {
return util.NewInternalServerError(err, "Failed to delete the completed workflow for run %s", runId)
}
}
// TODO(jingzhang36): find a proper way to pass collectMetricsFlag here.
workflowGCCounter.Inc()
}
if jobId == "" {
// If a run doesn't have job ID, it's a one-time run created by Pipeline API server.
// In this case the DB entry should already been created when argo workflow CR is created.
err := r.runStore.UpdateRun(runId, workflow.Condition(), workflow.FinishedAt(), workflow.ToStringForStore())
if err != nil {
return util.Wrap(err, "Failed to update the run.")
}
} else {
// Get the experiment resource reference for job.
experimentRef, err := r.resourceReferenceStore.GetResourceReference(jobId, common.Job, common.Experiment)
if err != nil {
return util.Wrap(err, "Failed to retrieve the experiment ID for the job that created the run.")
}
jobName, err := r.getResourceName(common.Job, jobId)
if err != nil {
return util.Wrap(err, "Failed to retrieve the job name for the job that created the run.")
}
runDetail := &model.RunDetail{
Run: model.Run{
UUID: runId,
ExperimentUUID: experimentRef.ReferenceUUID,
DisplayName: workflow.Name,
Name: workflow.Name,
StorageState: api.Run_STORAGESTATE_AVAILABLE.String(),
Namespace: workflow.Namespace,
CreatedAtInSec: workflow.CreationTimestamp.Unix(),
ScheduledAtInSec: workflow.ScheduledAtInSecOr0(),
FinishedAtInSec: workflow.FinishedAt(),
Conditions: workflow.Condition(),
PipelineSpec: model.PipelineSpec{
WorkflowSpecManifest: workflow.GetWorkflowSpec().ToStringForStore(),
},
ResourceReferences: []*model.ResourceReference{
{
ResourceUUID: runId,
ResourceType: common.Run,
ReferenceUUID: jobId,
ReferenceName: jobName,
ReferenceType: common.Job,
Relationship: common.Creator,
},
{
ResourceUUID: runId,
ResourceType: common.Run,
ReferenceUUID: experimentRef.ReferenceUUID,
ReferenceName: experimentRef.ReferenceName,
ReferenceType: common.Experiment,
Relationship: common.Owner,
},
},
},
PipelineRuntime: model.PipelineRuntime{
WorkflowRuntimeManifest: workflow.ToStringForStore(),
},
}
err = r.runStore.CreateOrUpdateRun(runDetail)
if err != nil {
return util.Wrap(err, "Failed to create or update the run.")
}
}
if workflow.IsInFinalState() {
err := AddWorkflowLabel(r.getWorkflowClient(workflow.Namespace), workflow.Name, util.LabelKeyWorkflowPersistedFinalState, "true")
if err != nil {
message := fmt.Sprintf("Failed to add PersistedFinalState label to workflow %s", workflow.GetName())
// A fix for kubeflow/pipelines#4484, persistence agent might have an outdated item in its workqueue, so it will
// report workflows that no longer exist. It's important to return a not found error, so that persistence
// agent won't retry again.
if util.IsNotFound(err) {
return util.NewNotFoundError(err, message)
} else {
return util.Wrapf(err, message)
}
}
}
return nil
}
// AddWorkflowLabel add label for a workflow
func AddWorkflowLabel(wfClient workflowclient.WorkflowInterface, name string, labelKey string, labelValue string) error {
patchObj := map[string]interface{}{
"metadata": map[string]interface{}{
"labels": map[string]interface{}{
labelKey: labelValue,
},
},
}
patch, err := json.Marshal(patchObj)
if err != nil {
return util.NewInternalServerError(err, "Unexpected error while marshalling a patch object.")
}
var operation = func() error {
_, err = wfClient.Patch(name, types.MergePatchType, patch)
return err
}
var backoffPolicy = backoff.WithMaxRetries(backoff.NewConstantBackOff(100), 10)
err = backoff.Retry(operation, backoffPolicy)
return err
}
func (r *ResourceManager) ReportScheduledWorkflowResource(swf *util.ScheduledWorkflow) error {
return r.jobStore.UpdateJob(swf)
}
// checkJobExist The Kubernetes API doesn't support CRUD by UID. This method
// retrieve the job metadata from the database, then retrieve the CR
// using the job name, and compare the given job id is same as the CR.
func (r *ResourceManager) checkJobExist(jobID string) (*model.Job, error) {
job, err := r.jobStore.GetJob(jobID)
if err != nil {
return nil, util.Wrap(err, "Check job exist failed")
}
scheduledWorkflow, err := r.getScheduledWorkflowClient(job.Namespace).Get(job.Name, v1.GetOptions{})
if err != nil {
return nil, util.NewInternalServerError(err, "Check job exist failed")
}
if scheduledWorkflow == nil || string(scheduledWorkflow.UID) != jobID {
return nil, util.NewResourceNotFoundError("job", job.Name)
}
return job, nil
}
// checkRunExist The Kubernetes API doesn't support CRUD by UID. This method
// retrieve the run metadata from the database, then retrieve the CR
// using the run name, and compare the given run id is same as the CR.
func (r *ResourceManager) checkRunExist(runID string) (*model.RunDetail, error) {
runDetail, err := r.runStore.GetRun(runID)
if err != nil {
return nil, util.Wrap(err, "Check run exist failed")
}
return runDetail, nil
}
func (r *ResourceManager) getWorkflowSpecBytesFromPipelineSpec(spec *api.PipelineSpec) ([]byte, error) {
if spec.GetWorkflowManifest() != "" {
return []byte(spec.GetWorkflowManifest()), nil
}
return nil, util.NewInvalidInputError("Please provide a valid pipeline spec")
}
func (r *ResourceManager) getWorkflowSpecBytesFromPipelineVersion(references []*api.ResourceReference) ([]byte, error) {
var pipelineVersionId = ""
for _, reference := range references {
if reference.Key.Type == api.ResourceType_PIPELINE_VERSION && reference.Relationship == api.Relationship_CREATOR {
pipelineVersionId = reference.Key.Id
}
}
if len(pipelineVersionId) == 0 {
return nil, util.NewInvalidInputError("No pipeline version.")
}
var workflow util.Workflow
err := r.objectStore.GetFromYamlFile(&workflow, r.objectStore.GetPipelineKey(pipelineVersionId))
if err != nil {
return nil, util.Wrap(err, "Get pipeline YAML failed.")
}
return []byte(workflow.ToStringForStore()), nil
}
// Used to initialize the Experiment database with a default to be used for runs
func (r *ResourceManager) CreateDefaultExperiment() (string, error) {
// First check that we don't already have a default experiment ID in the DB.
defaultExperimentId, err := r.GetDefaultExperimentId()
if err != nil {
return "", fmt.Errorf("Failed to check if default experiment exists. Err: %v", err)