This repository has been archived by the owner on Oct 9, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 63
/
execution_manager.go
1689 lines (1536 loc) · 71.3 KB
/
execution_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
package impl
import (
"context"
"fmt"
"strconv"
"time"
"github.com/flyteorg/flytestdlib/promutils/labeled"
"github.com/flyteorg/flyteadmin/plugins"
"github.com/flyteorg/flyteplugins/go/tasks/pluginmachinery/flytek8s"
"github.com/flyteorg/flyteadmin/auth"
"github.com/flyteorg/flyteadmin/pkg/manager/impl/resources"
dataInterfaces "github.com/flyteorg/flyteadmin/pkg/data/interfaces"
"github.com/flyteorg/flytestdlib/contextutils"
"github.com/flyteorg/flytestdlib/promutils"
"github.com/golang/protobuf/ptypes"
"github.com/golang/protobuf/ptypes/timestamp"
"github.com/prometheus/client_golang/prometheus"
"github.com/flyteorg/flyteadmin/pkg/common"
"github.com/flyteorg/flytestdlib/logger"
"github.com/flyteorg/flytestdlib/storage"
cloudeventInterfaces "github.com/flyteorg/flyteadmin/pkg/async/cloudevent/interfaces"
eventWriter "github.com/flyteorg/flyteadmin/pkg/async/events/interfaces"
"github.com/flyteorg/flyteadmin/pkg/async/notifications"
notificationInterfaces "github.com/flyteorg/flyteadmin/pkg/async/notifications/interfaces"
"github.com/flyteorg/flyteadmin/pkg/errors"
"github.com/flyteorg/flyteadmin/pkg/manager/impl/executions"
"github.com/flyteorg/flyteadmin/pkg/manager/impl/util"
"github.com/flyteorg/flyteadmin/pkg/manager/impl/validation"
"github.com/flyteorg/flyteadmin/pkg/manager/interfaces"
repositoryInterfaces "github.com/flyteorg/flyteadmin/pkg/repositories/interfaces"
"github.com/flyteorg/flyteadmin/pkg/repositories/models"
"github.com/flyteorg/flyteadmin/pkg/repositories/transformers"
runtimeInterfaces "github.com/flyteorg/flyteadmin/pkg/runtime/interfaces"
workflowengineInterfaces "github.com/flyteorg/flyteadmin/pkg/workflowengine/interfaces"
"github.com/flyteorg/flyteidl/gen/pb-go/flyteidl/admin"
"github.com/flyteorg/flyteidl/gen/pb-go/flyteidl/core"
"google.golang.org/grpc/codes"
"github.com/benbjohnson/clock"
"github.com/flyteorg/flyteadmin/pkg/manager/impl/shared"
"github.com/golang/protobuf/proto"
)
const childContainerQueueKey = "child_queue"
// Map of [project] -> map of [domain] -> stop watch
type projectDomainScopedStopWatchMap = map[string]map[string]*promutils.StopWatch
type executionSystemMetrics struct {
Scope promutils.Scope
ActiveExecutions prometheus.Gauge
ExecutionsCreated prometheus.Counter
ExecutionsTerminated labeled.Counter
ExecutionEventsCreated prometheus.Counter
PropellerFailures prometheus.Counter
PublishNotificationError prometheus.Counter
TransformerError prometheus.Counter
UnexpectedDataError prometheus.Counter
SpecSizeBytes prometheus.Summary
ClosureSizeBytes prometheus.Summary
AcceptanceDelay prometheus.Summary
PublishEventError prometheus.Counter
TerminateExecutionFailures prometheus.Counter
}
type executionUserMetrics struct {
Scope promutils.Scope
ScheduledExecutionDelays projectDomainScopedStopWatchMap
WorkflowExecutionDurations projectDomainScopedStopWatchMap
WorkflowExecutionInputBytes prometheus.Summary
WorkflowExecutionOutputBytes prometheus.Summary
}
type ExecutionManager struct {
db repositoryInterfaces.Repository
config runtimeInterfaces.Configuration
storageClient *storage.DataStore
queueAllocator executions.QueueAllocator
_clock clock.Clock
systemMetrics executionSystemMetrics
userMetrics executionUserMetrics
notificationClient notificationInterfaces.Publisher
urlData dataInterfaces.RemoteURLInterface
workflowManager interfaces.WorkflowInterface
namedEntityManager interfaces.NamedEntityInterface
resourceManager interfaces.ResourceInterface
qualityOfServiceAllocator executions.QualityOfServiceAllocator
eventPublisher notificationInterfaces.Publisher
cloudEventPublisher notificationInterfaces.Publisher
dbEventWriter eventWriter.WorkflowExecutionEventWriter
pluginRegistry *plugins.Registry
}
func getExecutionContext(ctx context.Context, id *core.WorkflowExecutionIdentifier) context.Context {
ctx = contextutils.WithExecutionID(ctx, id.Name)
return contextutils.WithProjectDomain(ctx, id.Project, id.Domain)
}
// Returns the unique string which identifies the authenticated end user (if any).
func getUser(ctx context.Context) string {
identityContext := auth.IdentityContextFromContext(ctx)
return identityContext.UserID()
}
func (m *ExecutionManager) populateExecutionQueue(
ctx context.Context, identifier core.Identifier, compiledWorkflow *core.CompiledWorkflowClosure) {
queueConfig := m.queueAllocator.GetQueue(ctx, identifier)
for _, task := range compiledWorkflow.Tasks {
container := task.Template.GetContainer()
if container == nil {
// Unrecognized target type, nothing to do
continue
}
if queueConfig.DynamicQueue != "" {
logger.Debugf(ctx, "Assigning %s as child queue for task %+v", queueConfig.DynamicQueue, task.Template.Id)
container.Config = append(container.Config, &core.KeyValuePair{
Key: childContainerQueueKey,
Value: queueConfig.DynamicQueue,
})
}
}
}
func validateMapSize(maxEntries int, candidate map[string]string, candidateName string) error {
if maxEntries == 0 {
// Treat the max as unset
return nil
}
if len(candidate) > maxEntries {
return errors.NewFlyteAdminErrorf(codes.InvalidArgument, "%s has too many entries [%v > %v]",
candidateName, len(candidate), maxEntries)
}
return nil
}
type mapWithValues interface {
GetValues() map[string]string
}
func resolveStringMap(preferredValues, defaultValues mapWithValues, valueName string, maxEntries int) (map[string]string, error) {
var response = make(map[string]string)
if preferredValues != nil && preferredValues.GetValues() != nil {
response = preferredValues.GetValues()
} else if defaultValues != nil && defaultValues.GetValues() != nil {
response = defaultValues.GetValues()
}
err := validateMapSize(maxEntries, response, valueName)
if err != nil {
return nil, err
}
return response, nil
}
func (m *ExecutionManager) addPluginOverrides(ctx context.Context, executionID *core.WorkflowExecutionIdentifier,
workflowName, launchPlanName string) ([]*admin.PluginOverride, error) {
override, err := m.resourceManager.GetResource(ctx, interfaces.ResourceRequest{
Project: executionID.Project,
Domain: executionID.Domain,
Workflow: workflowName,
LaunchPlan: launchPlanName,
ResourceType: admin.MatchableResource_PLUGIN_OVERRIDE,
})
if err != nil {
ec, ok := err.(errors.FlyteAdminError)
if !ok || ec.Code() != codes.NotFound {
return nil, err
}
}
if override != nil && override.Attributes != nil && override.Attributes.GetPluginOverrides() != nil {
return override.Attributes.GetPluginOverrides().Overrides, nil
}
return nil, nil
}
// TODO: Delete this code usage after the flyte v0.17.0 release
// Assumes input contains a compiled task with a valid container resource execConfig.
//
// Note: The system will assign a system-default value for request but for limit it will deduce it from the request
// itself => Limit := Min([Some-Multiplier X Request], System-Max). For now we are using a multiplier of 1. In
// general we recommend the users to set limits close to requests for more predictability in the system.
func (m *ExecutionManager) setCompiledTaskDefaults(ctx context.Context, task *core.CompiledTask,
platformTaskResources workflowengineInterfaces.TaskResources) {
if task == nil {
logger.Warningf(ctx, "Can't set default resources for nil task.")
return
}
if task.Template == nil || task.Template.GetContainer() == nil {
// Nothing to do
logger.Debugf(ctx, "Not setting default resources for task [%+v], no container resources found to check", task)
return
}
if task.Template.GetContainer().Resources == nil {
// In case of no resources on the container, create empty requests and limits
// so the container will still have resources configure properly
task.Template.GetContainer().Resources = &core.Resources{
Requests: []*core.Resources_ResourceEntry{},
Limits: []*core.Resources_ResourceEntry{},
}
}
var finalizedResourceRequests = make([]*core.Resources_ResourceEntry, 0)
var finalizedResourceLimits = make([]*core.Resources_ResourceEntry, 0)
// The IDL representation for container-type tasks represents resources as a list with string quantities.
// In order to easily reason about them we convert them to a set where we can O(1) fetch specific resources (e.g. CPU)
// and represent them as comparable quantities rather than strings.
taskResourceRequirements := util.GetCompleteTaskResourceRequirements(ctx, task.Template.Id, task)
cpu := flytek8s.AdjustOrDefaultResource(taskResourceRequirements.Defaults.CPU, taskResourceRequirements.Limits.CPU,
platformTaskResources.Defaults.CPU, platformTaskResources.Limits.CPU)
finalizedResourceRequests = append(finalizedResourceRequests, &core.Resources_ResourceEntry{
Name: core.Resources_CPU,
Value: cpu.Request.String(),
})
finalizedResourceLimits = append(finalizedResourceLimits, &core.Resources_ResourceEntry{
Name: core.Resources_CPU,
Value: cpu.Limit.String(),
})
memory := flytek8s.AdjustOrDefaultResource(taskResourceRequirements.Defaults.Memory, taskResourceRequirements.Limits.Memory,
platformTaskResources.Defaults.Memory, platformTaskResources.Limits.Memory)
finalizedResourceRequests = append(finalizedResourceRequests, &core.Resources_ResourceEntry{
Name: core.Resources_MEMORY,
Value: memory.Request.String(),
})
finalizedResourceLimits = append(finalizedResourceLimits, &core.Resources_ResourceEntry{
Name: core.Resources_MEMORY,
Value: memory.Limit.String(),
})
// Only assign ephemeral storage when it is either requested or limited in the task definition, or a platform
// default exists.
if !taskResourceRequirements.Defaults.EphemeralStorage.IsZero() ||
!taskResourceRequirements.Limits.EphemeralStorage.IsZero() ||
!platformTaskResources.Defaults.EphemeralStorage.IsZero() {
ephemeralStorage := flytek8s.AdjustOrDefaultResource(taskResourceRequirements.Defaults.EphemeralStorage, taskResourceRequirements.Limits.EphemeralStorage,
platformTaskResources.Defaults.EphemeralStorage, platformTaskResources.Limits.EphemeralStorage)
finalizedResourceRequests = append(finalizedResourceRequests, &core.Resources_ResourceEntry{
Name: core.Resources_EPHEMERAL_STORAGE,
Value: ephemeralStorage.Request.String(),
})
finalizedResourceLimits = append(finalizedResourceLimits, &core.Resources_ResourceEntry{
Name: core.Resources_EPHEMERAL_STORAGE,
Value: ephemeralStorage.Limit.String(),
})
}
// Only assign storage when it is either requested or limited in the task definition, or a platform
// default exists.
if !taskResourceRequirements.Defaults.Storage.IsZero() ||
!taskResourceRequirements.Limits.Storage.IsZero() ||
!platformTaskResources.Defaults.Storage.IsZero() {
storageResource := flytek8s.AdjustOrDefaultResource(taskResourceRequirements.Defaults.Storage, taskResourceRequirements.Limits.Storage,
platformTaskResources.Defaults.Storage, platformTaskResources.Limits.Storage)
finalizedResourceRequests = append(finalizedResourceRequests, &core.Resources_ResourceEntry{
Name: core.Resources_STORAGE,
Value: storageResource.Request.String(),
})
finalizedResourceLimits = append(finalizedResourceLimits, &core.Resources_ResourceEntry{
Name: core.Resources_STORAGE,
Value: storageResource.Limit.String(),
})
}
// Only assign gpu when it is either requested or limited in the task definition, or a platform default exists.
if !taskResourceRequirements.Defaults.GPU.IsZero() ||
!taskResourceRequirements.Limits.GPU.IsZero() ||
!platformTaskResources.Defaults.GPU.IsZero() {
gpu := flytek8s.AdjustOrDefaultResource(taskResourceRequirements.Defaults.GPU, taskResourceRequirements.Limits.GPU,
platformTaskResources.Defaults.GPU, platformTaskResources.Limits.GPU)
finalizedResourceRequests = append(finalizedResourceRequests, &core.Resources_ResourceEntry{
Name: core.Resources_GPU,
Value: gpu.Request.String(),
})
finalizedResourceLimits = append(finalizedResourceLimits, &core.Resources_ResourceEntry{
Name: core.Resources_GPU,
Value: gpu.Limit.String(),
})
}
task.Template.GetContainer().Resources = &core.Resources{
Requests: finalizedResourceRequests,
Limits: finalizedResourceLimits,
}
}
// Fetches inherited execution metadata including the parent node execution db model id and the source execution model id
// as well as sets request spec metadata with the inherited principal and adjusted nesting data.
func (m *ExecutionManager) getInheritedExecMetadata(ctx context.Context, requestSpec *admin.ExecutionSpec,
workflowExecutionID *core.WorkflowExecutionIdentifier) (parentNodeExecutionID uint, sourceExecutionID uint, err error) {
if requestSpec.Metadata == nil || requestSpec.Metadata.ParentNodeExecution == nil {
return parentNodeExecutionID, sourceExecutionID, nil
}
parentNodeExecutionModel, err := util.GetNodeExecutionModel(ctx, m.db, requestSpec.Metadata.ParentNodeExecution)
if err != nil {
logger.Errorf(ctx, "Failed to get node execution [%+v] that launched this execution [%+v] with error %v",
requestSpec.Metadata.ParentNodeExecution, workflowExecutionID, err)
return parentNodeExecutionID, sourceExecutionID, err
}
parentNodeExecutionID = parentNodeExecutionModel.ID
sourceExecutionModel, err := util.GetExecutionModel(ctx, m.db, *requestSpec.Metadata.ParentNodeExecution.ExecutionId)
if err != nil {
logger.Errorf(ctx, "Failed to get workflow execution [%+v] that launched this execution [%+v] with error %v",
requestSpec.Metadata.ParentNodeExecution, workflowExecutionID, err)
return parentNodeExecutionID, sourceExecutionID, err
}
sourceExecutionID = sourceExecutionModel.ID
requestSpec.Metadata.Principal = sourceExecutionModel.User
sourceExecution, err := transformers.FromExecutionModel(*sourceExecutionModel, transformers.DefaultExecutionTransformerOptions)
if err != nil {
logger.Errorf(ctx, "Failed transform parent execution model for child execution [%+v] with err: %v", workflowExecutionID, err)
return parentNodeExecutionID, sourceExecutionID, err
}
if sourceExecution.Spec.Metadata != nil {
requestSpec.Metadata.Nesting = sourceExecution.Spec.Metadata.Nesting + 1
} else {
requestSpec.Metadata.Nesting = 1
}
return parentNodeExecutionID, sourceExecutionID, nil
}
// Produces execution-time attributes for workflow execution.
// Defaults to overridable execution values set in the execution create request, then looks at the launch plan values
// (if any) before defaulting to values set in the matchable resource db and further if matchable resources don't
// exist then defaults to one set in application configuration
func (m *ExecutionManager) getExecutionConfig(ctx context.Context, request *admin.ExecutionCreateRequest,
launchPlan *admin.LaunchPlan) (*admin.WorkflowExecutionConfig, error) {
workflowExecConfig := admin.WorkflowExecutionConfig{}
// Merge the request spec into workflowExecConfig
workflowExecConfig = util.MergeIntoExecConfig(workflowExecConfig, request.Spec)
var workflowName string
if launchPlan != nil && launchPlan.Spec != nil {
// Merge the launch plan spec into workflowExecConfig
workflowExecConfig = util.MergeIntoExecConfig(workflowExecConfig, launchPlan.Spec)
if launchPlan.Spec.WorkflowId != nil {
workflowName = launchPlan.Spec.WorkflowId.Name
}
}
// This will get the most specific Workflow Execution Config.
matchableResource, err := util.GetMatchableResource(ctx, m.resourceManager,
admin.MatchableResource_WORKFLOW_EXECUTION_CONFIG, request.Project, request.Domain, workflowName)
if err != nil {
return nil, err
}
if matchableResource != nil && matchableResource.Attributes.GetWorkflowExecutionConfig() != nil {
// merge the matchable resource workflow execution config into workflowExecConfig
workflowExecConfig = util.MergeIntoExecConfig(workflowExecConfig,
matchableResource.Attributes.GetWorkflowExecutionConfig())
}
// To match what the front-end will display to the user, we need to do the project level query too.
// This searches only for a direct match, and will not merge in system config level defaults like the
// GetProjectAttributes call does, since that's done below.
// The reason we need to do the project level query is for the case where some configs (say max parallelism)
// is set on the project level, but other items (say service account) is set on the project-domain level.
// In this case you want to use the project-domain service account, the project-level max parallelism, and
// system level defaults for the rest.
// See FLYTE-2322 for more background information.
projectMatchableResource, err := util.GetMatchableResource(ctx, m.resourceManager,
admin.MatchableResource_WORKFLOW_EXECUTION_CONFIG, request.Project, "", "")
if err != nil {
return nil, err
}
if projectMatchableResource != nil && projectMatchableResource.Attributes.GetWorkflowExecutionConfig() != nil {
// merge the matchable resource workflow execution config into workflowExecConfig
workflowExecConfig = util.MergeIntoExecConfig(workflowExecConfig,
projectMatchableResource.Attributes.GetWorkflowExecutionConfig())
}
// Backward compatibility changes to get security context from auth role.
// Older authRole or auth fields in the launchplan spec or execution request need to be used over application defaults.
// This portion of the code makes sure if newer way of setting security context is empty i.e
// K8sServiceAccount and IamRole is empty then get the values from the deprecated fields.
resolvedAuthRole := resolveAuthRole(request, launchPlan)
resolvedSecurityCtx := resolveSecurityCtx(ctx, workflowExecConfig.GetSecurityContext(), resolvedAuthRole)
workflowExecConfig.SecurityContext = resolvedSecurityCtx
// Merge the application config into workflowExecConfig. If even the deprecated fields are not set
workflowExecConfig = util.MergeIntoExecConfig(workflowExecConfig, m.config.ApplicationConfiguration().GetTopLevelConfig())
// Explicitly set the security context if its nil since downstream we expect this settings to be available
if workflowExecConfig.GetSecurityContext() == nil {
workflowExecConfig.SecurityContext = &core.SecurityContext{
RunAs: &core.Identity{},
}
}
logger.Infof(ctx, "getting the workflow execution config from application configuration")
// Defaults to one from the application config
return &workflowExecConfig, nil
}
func (m *ExecutionManager) getClusterAssignment(ctx context.Context, request *admin.ExecutionCreateRequest) (
*admin.ClusterAssignment, error) {
if request.Spec.ClusterAssignment != nil {
return request.Spec.ClusterAssignment, nil
}
resource, err := m.resourceManager.GetResource(ctx, interfaces.ResourceRequest{
Project: request.Project,
Domain: request.Domain,
ResourceType: admin.MatchableResource_CLUSTER_ASSIGNMENT,
})
if err != nil {
if flyteAdminError, ok := err.(errors.FlyteAdminError); !ok || flyteAdminError.Code() != codes.NotFound {
logger.Errorf(ctx, "Failed to get cluster assignment overrides with error: %v", err)
return nil, err
}
}
if resource != nil && resource.Attributes.GetClusterAssignment() != nil {
return resource.Attributes.GetClusterAssignment(), nil
}
// Defaults to empty assignment with no selectors
return &admin.ClusterAssignment{}, nil
}
func (m *ExecutionManager) launchSingleTaskExecution(
ctx context.Context, request admin.ExecutionCreateRequest, requestedAt time.Time) (
context.Context, *models.Execution, error) {
taskModel, err := m.db.TaskRepo().Get(ctx, repositoryInterfaces.Identifier{
Project: request.Spec.LaunchPlan.Project,
Domain: request.Spec.LaunchPlan.Domain,
Name: request.Spec.LaunchPlan.Name,
Version: request.Spec.LaunchPlan.Version,
})
if err != nil {
return nil, nil, err
}
task, err := transformers.FromTaskModel(taskModel)
if err != nil {
return nil, nil, err
}
// Prepare a skeleton workflow
taskIdentifier := request.Spec.LaunchPlan
workflowModel, err :=
util.CreateOrGetWorkflowModel(ctx, request, m.db, m.workflowManager, m.namedEntityManager, taskIdentifier, &task)
if err != nil {
logger.Debugf(ctx, "Failed to created skeleton workflow for [%+v] with err: %v", taskIdentifier, err)
return nil, nil, err
}
workflow, err := transformers.FromWorkflowModel(*workflowModel)
if err != nil {
return nil, nil, err
}
closure, err := util.FetchAndGetWorkflowClosure(ctx, m.storageClient, workflowModel.RemoteClosureIdentifier)
if err != nil {
return nil, nil, err
}
closure.CreatedAt = workflow.Closure.CreatedAt
workflow.Closure = closure
// Also prepare a skeleton launch plan.
launchPlan, err := util.CreateOrGetLaunchPlan(ctx, m.db, m.config, taskIdentifier,
workflow.Closure.CompiledWorkflow.Primary.Template.Interface, workflowModel.ID, request.Spec)
if err != nil {
return nil, nil, err
}
executionInputs, err := validation.CheckAndFetchInputsForExecution(
request.Inputs,
launchPlan.Spec.FixedInputs,
launchPlan.Closure.ExpectedInputs,
)
if err != nil {
logger.Debugf(ctx, "Failed to CheckAndFetchInputsForExecution with request.Inputs: %+v"+
"fixed inputs: %+v and expected inputs: %+v with err %v",
request.Inputs, launchPlan.Spec.FixedInputs, launchPlan.Closure.ExpectedInputs, err)
return nil, nil, err
}
name := util.GetExecutionName(request)
workflowExecutionID := core.WorkflowExecutionIdentifier{
Project: request.Project,
Domain: request.Domain,
Name: name,
}
ctx = getExecutionContext(ctx, &workflowExecutionID)
namespace := common.GetNamespaceName(
m.config.NamespaceMappingConfiguration().GetNamespaceTemplate(), workflowExecutionID.Project, workflowExecutionID.Domain)
requestSpec := request.Spec
if requestSpec.Metadata == nil {
requestSpec.Metadata = &admin.ExecutionMetadata{}
}
requestSpec.Metadata.Principal = getUser(ctx)
// Get the node execution (if any) that launched this execution
var parentNodeExecutionID uint
var sourceExecutionID uint
parentNodeExecutionID, sourceExecutionID, err = m.getInheritedExecMetadata(ctx, requestSpec, &workflowExecutionID)
if err != nil {
return nil, nil, err
}
// Dynamically assign task resource defaults.
platformTaskResources := util.GetTaskResources(ctx, workflow.Id, m.resourceManager, m.config.TaskResourceConfiguration())
for _, t := range workflow.Closure.CompiledWorkflow.Tasks {
m.setCompiledTaskDefaults(ctx, t, platformTaskResources)
}
// Dynamically assign execution queues.
m.populateExecutionQueue(ctx, *workflow.Id, workflow.Closure.CompiledWorkflow)
inputsURI, err := common.OffloadLiteralMap(ctx, m.storageClient, request.Inputs, workflowExecutionID.Project, workflowExecutionID.Domain, workflowExecutionID.Name, shared.Inputs)
if err != nil {
return nil, nil, err
}
userInputsURI, err := common.OffloadLiteralMap(ctx, m.storageClient, request.Inputs, workflowExecutionID.Project, workflowExecutionID.Domain, workflowExecutionID.Name, shared.UserInputs)
if err != nil {
return nil, nil, err
}
executionConfig, err := m.getExecutionConfig(ctx, &request, nil)
if err != nil {
return nil, nil, err
}
var labels map[string]string
if executionConfig.Labels != nil {
labels = executionConfig.Labels.Values
}
labels, err = m.addProjectLabels(ctx, request.Project, labels)
if err != nil {
return nil, nil, err
}
var annotations map[string]string
if executionConfig.Annotations != nil {
annotations = executionConfig.Annotations.Values
}
var rawOutputDataConfig *admin.RawOutputDataConfig
if executionConfig.RawOutputDataConfig != nil {
rawOutputDataConfig = executionConfig.RawOutputDataConfig
}
clusterAssignment, err := m.getClusterAssignment(ctx, &request)
if err != nil {
return nil, nil, err
}
executionParameters := workflowengineInterfaces.ExecutionParameters{
Inputs: executionInputs,
AcceptedAt: requestedAt,
Labels: labels,
Annotations: annotations,
ExecutionConfig: executionConfig,
TaskResources: &platformTaskResources,
EventVersion: m.config.ApplicationConfiguration().GetTopLevelConfig().EventVersion,
RoleNameKey: m.config.ApplicationConfiguration().GetTopLevelConfig().RoleNameKey,
RawOutputDataConfig: rawOutputDataConfig,
ClusterAssignment: clusterAssignment,
}
overrides, err := m.addPluginOverrides(ctx, &workflowExecutionID, workflowExecutionID.Name, "")
if err != nil {
return nil, nil, err
}
if overrides != nil {
executionParameters.TaskPluginOverrides = overrides
}
if request.Spec.Metadata != nil && request.Spec.Metadata.ReferenceExecution != nil &&
request.Spec.Metadata.Mode == admin.ExecutionMetadata_RECOVERED {
executionParameters.RecoveryExecution = request.Spec.Metadata.ReferenceExecution
}
workflowExecutor := plugins.Get[workflowengineInterfaces.WorkflowExecutor](m.pluginRegistry, plugins.PluginIDWorkflowExecutor)
execInfo, err := workflowExecutor.Execute(ctx, workflowengineInterfaces.ExecutionData{
Namespace: namespace,
ExecutionID: &workflowExecutionID,
ReferenceWorkflowName: workflow.Id.Name,
ReferenceLaunchPlanName: launchPlan.Id.Name,
WorkflowClosure: workflow.Closure.CompiledWorkflow,
WorkflowClosureReference: storage.DataReference(workflowModel.RemoteClosureIdentifier),
ExecutionParameters: executionParameters,
})
if err != nil {
m.systemMetrics.PropellerFailures.Inc()
logger.Infof(ctx, "Failed to execute workflow %+v with execution id %+v and inputs %+v with err %v",
request, workflowExecutionID, request.Inputs, err)
return nil, nil, err
}
executionCreatedAt := time.Now()
acceptanceDelay := executionCreatedAt.Sub(requestedAt)
m.systemMetrics.AcceptanceDelay.Observe(acceptanceDelay.Seconds())
// Request notification settings takes precedence over the launch plan settings.
// If there is no notification in the request and DisableAll is not true, use the settings from the launch plan.
var notificationsSettings []*admin.Notification
if launchPlan.Spec.GetEntityMetadata() != nil {
notificationsSettings = launchPlan.Spec.EntityMetadata.GetNotifications()
}
if request.Spec.GetNotifications() != nil && request.Spec.GetNotifications().Notifications != nil &&
len(request.Spec.GetNotifications().Notifications) > 0 {
notificationsSettings = request.Spec.GetNotifications().Notifications
} else if request.Spec.GetDisableAll() {
notificationsSettings = make([]*admin.Notification, 0)
}
executionModel, err := transformers.CreateExecutionModel(transformers.CreateExecutionModelInput{
WorkflowExecutionID: workflowExecutionID,
RequestSpec: requestSpec,
TaskID: taskModel.ID,
WorkflowID: workflowModel.ID,
// The execution is not considered running until the propeller sends a specific event saying so.
Phase: core.WorkflowExecution_UNDEFINED,
CreatedAt: m._clock.Now(),
Notifications: notificationsSettings,
WorkflowIdentifier: workflow.Id,
ParentNodeExecutionID: parentNodeExecutionID,
SourceExecutionID: sourceExecutionID,
Cluster: execInfo.Cluster,
InputsURI: inputsURI,
UserInputsURI: userInputsURI,
SecurityContext: executionConfig.SecurityContext,
LaunchEntity: taskIdentifier.ResourceType,
})
if err != nil {
logger.Infof(ctx, "Failed to create execution model in transformer for id: [%+v] with err: %v",
workflowExecutionID, err)
return nil, nil, err
}
m.userMetrics.WorkflowExecutionInputBytes.Observe(float64(proto.Size(request.Inputs)))
return ctx, executionModel, nil
}
func resolveAuthRole(request *admin.ExecutionCreateRequest, launchPlan *admin.LaunchPlan) *admin.AuthRole {
if request.Spec.AuthRole != nil {
return request.Spec.AuthRole
}
if launchPlan == nil || launchPlan.Spec == nil {
return &admin.AuthRole{}
}
// Set role permissions based on launch plan Auth values.
// The branched-ness of this check is due to the presence numerous deprecated fields
if launchPlan.Spec.GetAuthRole() != nil {
return launchPlan.Spec.GetAuthRole()
} else if launchPlan.GetSpec().GetAuth() != nil {
return &admin.AuthRole{
AssumableIamRole: launchPlan.GetSpec().GetAuth().AssumableIamRole,
KubernetesServiceAccount: launchPlan.GetSpec().GetAuth().KubernetesServiceAccount,
}
} else if len(launchPlan.GetSpec().GetRole()) > 0 {
return &admin.AuthRole{
AssumableIamRole: launchPlan.GetSpec().GetRole(),
}
}
return &admin.AuthRole{}
}
func resolveSecurityCtx(ctx context.Context, executionConfigSecurityCtx *core.SecurityContext,
resolvedAuthRole *admin.AuthRole) *core.SecurityContext {
// Use security context from the executionConfigSecurityCtx if its set and non empty or else resolve from authRole
if executionConfigSecurityCtx != nil && executionConfigSecurityCtx.RunAs != nil &&
(len(executionConfigSecurityCtx.RunAs.K8SServiceAccount) > 0 ||
len(executionConfigSecurityCtx.RunAs.IamRole) > 0) {
return executionConfigSecurityCtx
}
logger.Warn(ctx, "Setting security context from auth Role")
return &core.SecurityContext{
RunAs: &core.Identity{
IamRole: resolvedAuthRole.AssumableIamRole,
K8SServiceAccount: resolvedAuthRole.KubernetesServiceAccount,
},
}
}
func (m *ExecutionManager) launchExecutionAndPrepareModel(
ctx context.Context, request admin.ExecutionCreateRequest, requestedAt time.Time) (
context.Context, *models.Execution, error) {
err := validation.ValidateExecutionRequest(ctx, request, m.db, m.config.ApplicationConfiguration())
if err != nil {
logger.Debugf(ctx, "Failed to validate ExecutionCreateRequest %+v with err %v", request, err)
return nil, nil, err
}
if request.Spec.LaunchPlan.ResourceType == core.ResourceType_TASK {
logger.Debugf(ctx, "Launching single task execution with [%+v]", request.Spec.LaunchPlan)
return m.launchSingleTaskExecution(ctx, request, requestedAt)
}
launchPlanModel, err := util.GetLaunchPlanModel(ctx, m.db, *request.Spec.LaunchPlan)
if err != nil {
logger.Debugf(ctx, "Failed to get launch plan model for ExecutionCreateRequest %+v with err %v", request, err)
return nil, nil, err
}
launchPlan, err := transformers.FromLaunchPlanModel(launchPlanModel)
if err != nil {
logger.Debugf(ctx, "Failed to transform launch plan model %+v with err %v", launchPlanModel, err)
return nil, nil, err
}
executionInputs, err := validation.CheckAndFetchInputsForExecution(
request.Inputs,
launchPlan.Spec.FixedInputs,
launchPlan.Closure.ExpectedInputs,
)
if err != nil {
logger.Debugf(ctx, "Failed to CheckAndFetchInputsForExecution with request.Inputs: %+v"+
"fixed inputs: %+v and expected inputs: %+v with err %v",
request.Inputs, launchPlan.Spec.FixedInputs, launchPlan.Closure.ExpectedInputs, err)
return nil, nil, err
}
workflowModel, err := util.GetWorkflowModel(ctx, m.db, *launchPlan.Spec.WorkflowId)
if err != nil {
logger.Debugf(ctx, "Failed to get workflow with id %+v with err %v", launchPlan.Spec.WorkflowId, err)
return nil, nil, err
}
workflow, err := transformers.FromWorkflowModel(workflowModel)
if err != nil {
logger.Debugf(ctx, "Failed to get workflow with id %+v with err %v", launchPlan.Spec.WorkflowId, err)
return nil, nil, err
}
closure, err := util.FetchAndGetWorkflowClosure(ctx, m.storageClient, workflowModel.RemoteClosureIdentifier)
if err != nil {
logger.Debugf(ctx, "Failed to get workflow with id %+v with err %v", launchPlan.Spec.WorkflowId, err)
return nil, nil, err
}
closure.CreatedAt = workflow.Closure.CreatedAt
workflow.Closure = closure
name := util.GetExecutionName(request)
workflowExecutionID := core.WorkflowExecutionIdentifier{
Project: request.Project,
Domain: request.Domain,
Name: name,
}
ctx = getExecutionContext(ctx, &workflowExecutionID)
var requestSpec = request.Spec
if requestSpec.Metadata == nil {
requestSpec.Metadata = &admin.ExecutionMetadata{}
}
requestSpec.Metadata.Principal = getUser(ctx)
// Get the node and parent execution (if any) that launched this execution
var parentNodeExecutionID uint
var sourceExecutionID uint
parentNodeExecutionID, sourceExecutionID, err = m.getInheritedExecMetadata(ctx, requestSpec, &workflowExecutionID)
if err != nil {
return nil, nil, err
}
// Dynamically assign task resource defaults.
platformTaskResources := util.GetTaskResources(ctx, workflow.Id, m.resourceManager, m.config.TaskResourceConfiguration())
for _, task := range workflow.Closure.CompiledWorkflow.Tasks {
m.setCompiledTaskDefaults(ctx, task, platformTaskResources)
}
// Dynamically assign execution queues.
m.populateExecutionQueue(ctx, *workflow.Id, workflow.Closure.CompiledWorkflow)
inputsURI, err := common.OffloadLiteralMap(ctx, m.storageClient, executionInputs, workflowExecutionID.Project, workflowExecutionID.Domain, workflowExecutionID.Name, shared.Inputs)
if err != nil {
return nil, nil, err
}
userInputsURI, err := common.OffloadLiteralMap(ctx, m.storageClient, request.Inputs, workflowExecutionID.Project, workflowExecutionID.Domain, workflowExecutionID.Name, shared.UserInputs)
if err != nil {
return nil, nil, err
}
executionConfig, err := m.getExecutionConfig(ctx, &request, launchPlan)
if err != nil {
return nil, nil, err
}
namespace := common.GetNamespaceName(
m.config.NamespaceMappingConfiguration().GetNamespaceTemplate(), workflowExecutionID.Project, workflowExecutionID.Domain)
labels, err := resolveStringMap(executionConfig.GetLabels(), launchPlan.Spec.Labels, "labels", m.config.RegistrationValidationConfiguration().GetMaxLabelEntries())
if err != nil {
return nil, nil, err
}
labels, err = m.addProjectLabels(ctx, request.Project, labels)
if err != nil {
return nil, nil, err
}
annotations, err := resolveStringMap(executionConfig.GetAnnotations(), launchPlan.Spec.Annotations, "annotations", m.config.RegistrationValidationConfiguration().GetMaxAnnotationEntries())
if err != nil {
return nil, nil, err
}
var rawOutputDataConfig *admin.RawOutputDataConfig
if executionConfig.RawOutputDataConfig != nil {
rawOutputDataConfig = executionConfig.RawOutputDataConfig
}
clusterAssignment, err := m.getClusterAssignment(ctx, &request)
if err != nil {
return nil, nil, err
}
executionParameters := workflowengineInterfaces.ExecutionParameters{
Inputs: executionInputs,
AcceptedAt: requestedAt,
Labels: labels,
Annotations: annotations,
ExecutionConfig: executionConfig,
TaskResources: &platformTaskResources,
EventVersion: m.config.ApplicationConfiguration().GetTopLevelConfig().EventVersion,
RoleNameKey: m.config.ApplicationConfiguration().GetTopLevelConfig().RoleNameKey,
RawOutputDataConfig: rawOutputDataConfig,
ClusterAssignment: clusterAssignment,
}
overrides, err := m.addPluginOverrides(ctx, &workflowExecutionID, launchPlan.GetSpec().WorkflowId.Name, launchPlan.Id.Name)
if err != nil {
return nil, nil, err
}
if overrides != nil {
executionParameters.TaskPluginOverrides = overrides
}
if request.Spec.Metadata != nil && request.Spec.Metadata.ReferenceExecution != nil &&
request.Spec.Metadata.Mode == admin.ExecutionMetadata_RECOVERED {
executionParameters.RecoveryExecution = request.Spec.Metadata.ReferenceExecution
}
workflowExecutor := plugins.Get[workflowengineInterfaces.WorkflowExecutor](m.pluginRegistry, plugins.PluginIDWorkflowExecutor)
execInfo, err := workflowExecutor.Execute(ctx, workflowengineInterfaces.ExecutionData{
Namespace: namespace,
ExecutionID: &workflowExecutionID,
ReferenceWorkflowName: workflow.Id.Name,
ReferenceLaunchPlanName: launchPlan.Id.Name,
WorkflowClosure: workflow.Closure.CompiledWorkflow,
WorkflowClosureReference: storage.DataReference(workflowModel.RemoteClosureIdentifier),
ExecutionParameters: executionParameters,
})
if err != nil {
m.systemMetrics.PropellerFailures.Inc()
logger.Infof(ctx, "Failed to execute workflow %+v with execution id %+v and inputs %+v with err %v",
request, workflowExecutionID, executionInputs, err)
return nil, nil, err
}
executionCreatedAt := time.Now()
acceptanceDelay := executionCreatedAt.Sub(requestedAt)
m.systemMetrics.AcceptanceDelay.Observe(acceptanceDelay.Seconds())
// Request notification settings takes precedence over the launch plan settings.
// If there is no notification in the request and DisableAll is not true, use the settings from the launch plan.
var notificationsSettings []*admin.Notification
if launchPlan.Spec.GetEntityMetadata() != nil {
notificationsSettings = launchPlan.Spec.EntityMetadata.GetNotifications()
}
if requestSpec.GetNotifications() != nil && requestSpec.GetNotifications().Notifications != nil &&
len(requestSpec.GetNotifications().Notifications) > 0 {
notificationsSettings = requestSpec.GetNotifications().Notifications
} else if requestSpec.GetDisableAll() {
notificationsSettings = make([]*admin.Notification, 0)
}
executionModel, err := transformers.CreateExecutionModel(transformers.CreateExecutionModelInput{
WorkflowExecutionID: workflowExecutionID,
RequestSpec: requestSpec,
LaunchPlanID: launchPlanModel.ID,
WorkflowID: launchPlanModel.WorkflowID,
// The execution is not considered running until the propeller sends a specific event saying so.
Phase: core.WorkflowExecution_UNDEFINED,
CreatedAt: m._clock.Now(),
Notifications: notificationsSettings,
WorkflowIdentifier: workflow.Id,
ParentNodeExecutionID: parentNodeExecutionID,
SourceExecutionID: sourceExecutionID,
Cluster: execInfo.Cluster,
InputsURI: inputsURI,
UserInputsURI: userInputsURI,
SecurityContext: executionConfig.SecurityContext,
LaunchEntity: launchPlan.Id.ResourceType,
})
if err != nil {
logger.Infof(ctx, "Failed to create execution model in transformer for id: [%+v] with err: %v",
workflowExecutionID, err)
return nil, nil, err
}
return ctx, executionModel, nil
}
// Inserts an execution model into the database store and emits platform metrics.
func (m *ExecutionManager) createExecutionModel(
ctx context.Context, executionModel *models.Execution) (*core.WorkflowExecutionIdentifier, error) {
workflowExecutionIdentifier := core.WorkflowExecutionIdentifier{
Project: executionModel.ExecutionKey.Project,
Domain: executionModel.ExecutionKey.Domain,
Name: executionModel.ExecutionKey.Name,
}
err := m.db.ExecutionRepo().Create(ctx, *executionModel)
if err != nil {
logger.Debugf(ctx, "failed to save newly created execution [%+v] with id %+v to db with err %v",
workflowExecutionIdentifier, workflowExecutionIdentifier, err)
return nil, err
}
m.systemMetrics.ActiveExecutions.Inc()
m.systemMetrics.ExecutionsCreated.Inc()
m.systemMetrics.SpecSizeBytes.Observe(float64(len(executionModel.Spec)))
m.systemMetrics.ClosureSizeBytes.Observe(float64(len(executionModel.Closure)))
return &workflowExecutionIdentifier, nil
}
func (m *ExecutionManager) CreateExecution(
ctx context.Context, request admin.ExecutionCreateRequest, requestedAt time.Time) (
*admin.ExecutionCreateResponse, error) {
// Prior to flyteidl v0.15.0, Inputs was held in ExecutionSpec. Ensure older clients continue to work.
if request.Inputs == nil || len(request.Inputs.Literals) == 0 {
request.Inputs = request.GetSpec().GetInputs()
}
var executionModel *models.Execution
var err error
ctx, executionModel, err = m.launchExecutionAndPrepareModel(ctx, request, requestedAt)
if err != nil {
return nil, err
}
workflowExecutionIdentifier, err := m.createExecutionModel(ctx, executionModel)
if err != nil {
return nil, err
}
return &admin.ExecutionCreateResponse{
Id: workflowExecutionIdentifier,
}, nil
}
func (m *ExecutionManager) RelaunchExecution(
ctx context.Context, request admin.ExecutionRelaunchRequest, requestedAt time.Time) (
*admin.ExecutionCreateResponse, error) {
existingExecutionModel, err := util.GetExecutionModel(ctx, m.db, *request.Id)
if err != nil {
logger.Debugf(ctx, "Failed to get execution model for request [%+v] with err %v", request, err)
return nil, err
}
existingExecution, err := transformers.FromExecutionModel(*existingExecutionModel, transformers.DefaultExecutionTransformerOptions)
if err != nil {
return nil, err
}
executionSpec := existingExecution.Spec
if executionSpec.Metadata == nil {
executionSpec.Metadata = &admin.ExecutionMetadata{}
}
var inputs *core.LiteralMap
if len(existingExecutionModel.UserInputsURI) > 0 {
inputs = &core.LiteralMap{}
if err := m.storageClient.ReadProtobuf(ctx, existingExecutionModel.UserInputsURI, inputs); err != nil {
return nil, err
}
} else {
// For old data, inputs are held in the spec
var spec admin.ExecutionSpec
err = proto.Unmarshal(existingExecutionModel.Spec, &spec)
if err != nil {
return nil, errors.NewFlyteAdminErrorf(codes.Internal, "failed to unmarshal spec")
}
inputs = spec.Inputs
}
executionSpec.Metadata.Mode = admin.ExecutionMetadata_RELAUNCH
executionSpec.Metadata.ReferenceExecution = existingExecution.Id
executionSpec.OverwriteCache = request.GetOverwriteCache()
var executionModel *models.Execution
ctx, executionModel, err = m.launchExecutionAndPrepareModel(ctx, admin.ExecutionCreateRequest{
Project: request.Id.Project,
Domain: request.Id.Domain,
Name: request.Name,
Spec: executionSpec,
Inputs: inputs,
}, requestedAt)
if err != nil {
return nil, err
}
executionModel.SourceExecutionID = existingExecutionModel.ID
workflowExecutionIdentifier, err := m.createExecutionModel(ctx, executionModel)
if err != nil {
return nil, err
}
logger.Debugf(ctx, "Successfully relaunched [%+v] as [%+v]", request.Id, workflowExecutionIdentifier)
return &admin.ExecutionCreateResponse{
Id: workflowExecutionIdentifier,
}, nil
}
func (m *ExecutionManager) RecoverExecution(