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 62
/
execution_manager.go
1562 lines (1427 loc) · 63.9 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/flyteplugins/go/tasks/pluginmachinery/flytek8s"
"github.com/flyteorg/flyteadmin/auth"
"k8s.io/apimachinery/pkg/api/resource"
"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"
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"
"github.com/flyteorg/flyteadmin/pkg/repositories"
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 prometheus.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
}
type executionUserMetrics struct {
Scope promutils.Scope
ScheduledExecutionDelays projectDomainScopedStopWatchMap
WorkflowExecutionDurations projectDomainScopedStopWatchMap
WorkflowExecutionInputBytes prometheus.Summary
WorkflowExecutionOutputBytes prometheus.Summary
}
type ExecutionManager struct {
db repositories.RepositoryInterface
config runtimeInterfaces.Configuration
storageClient *storage.DataStore
workflowExecutor workflowengineInterfaces.Executor
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
dbEventWriter eventWriter.WorkflowExecutionEventWriter
}
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
}
// Labels and annotations defined in the execution spec are preferred over those defined in the
// reference launch plan spec.
func (m *ExecutionManager) addLabelsAndAnnotations(requestSpec *admin.ExecutionSpec,
partiallyPopulatedInputs *workflowengineInterfaces.ExecuteWorkflowInput) error {
var labels map[string]string
if requestSpec.Labels != nil && requestSpec.Labels.Values != nil {
labels = requestSpec.Labels.Values
} else if partiallyPopulatedInputs.Reference.Spec.Labels != nil &&
partiallyPopulatedInputs.Reference.Spec.Labels.Values != nil {
labels = partiallyPopulatedInputs.Reference.Spec.Labels.Values
}
var annotations map[string]string
if requestSpec.Annotations != nil && requestSpec.Annotations.Values != nil {
annotations = requestSpec.Annotations.Values
} else if partiallyPopulatedInputs.Reference.Spec.Annotations != nil &&
partiallyPopulatedInputs.Reference.Spec.Annotations.Values != nil {
annotations = partiallyPopulatedInputs.Reference.Spec.Annotations.Values
}
err := validateMapSize(m.config.RegistrationValidationConfiguration().GetMaxLabelEntries(), labels, "Labels")
if err != nil {
return err
}
err = validateMapSize(
m.config.RegistrationValidationConfiguration().GetMaxAnnotationEntries(), annotations, "Annotations")
if err != nil {
return err
}
partiallyPopulatedInputs.Labels = labels
partiallyPopulatedInputs.Annotations = annotations
return 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
}
func (m *ExecutionManager) offloadInputs(ctx context.Context, literalMap *core.LiteralMap, identifier *core.WorkflowExecutionIdentifier, key string) (storage.DataReference, error) {
if literalMap == nil {
literalMap = &core.LiteralMap{}
}
inputsURI, err := m.storageClient.ConstructReference(ctx, m.storageClient.GetBaseContainerFQN(ctx), shared.Metadata, identifier.Project, identifier.Domain, identifier.Name, key)
if err != nil {
return "", err
}
if err := m.storageClient.WriteProtobuf(ctx, inputsURI, storage.Options{}, literalMap); err != nil {
return "", err
}
return inputsURI, nil
}
type completeTaskResources struct {
Defaults runtimeInterfaces.TaskResourceSet
Limits runtimeInterfaces.TaskResourceSet
}
func getTaskResourcesAsSet(ctx context.Context, identifier *core.Identifier,
resourceEntries []*core.Resources_ResourceEntry, resourceName string) runtimeInterfaces.TaskResourceSet {
result := runtimeInterfaces.TaskResourceSet{}
for _, entry := range resourceEntries {
switch entry.Name {
case core.Resources_CPU:
result.CPU = parseQuantityNoError(ctx, identifier.String(), fmt.Sprintf("%v.cpu", resourceName), entry.Value)
case core.Resources_MEMORY:
result.Memory = parseQuantityNoError(ctx, identifier.String(), fmt.Sprintf("%v.memory", resourceName), entry.Value)
case core.Resources_EPHEMERAL_STORAGE:
result.EphemeralStorage = parseQuantityNoError(ctx, identifier.String(),
fmt.Sprintf("%v.ephemeral storage", resourceName), entry.Value)
case core.Resources_GPU:
result.GPU = parseQuantityNoError(ctx, identifier.String(), "gpu", entry.Value)
}
}
return result
}
func getCompleteTaskResourceRequirements(ctx context.Context, identifier *core.Identifier, task *core.CompiledTask) completeTaskResources {
return completeTaskResources{
Defaults: getTaskResourcesAsSet(ctx, identifier, task.GetTemplate().GetContainer().Resources.Requests, "requests"),
Limits: getTaskResourcesAsSet(ctx, identifier, task.GetTemplate().GetContainer().Resources.Limits, "limits"),
}
}
// 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 := 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,
}
}
func parseQuantityNoError(ctx context.Context, ownerID, name, value string) resource.Quantity {
q, err := resource.ParseQuantity(value)
if err != nil {
logger.Infof(ctx, "Failed to parse owner's [%s] resource [%s]'s value [%s] with err: %v", ownerID, name, value, err)
}
return q
}
func fromAdminProtoTaskResourceSpec(ctx context.Context, spec *admin.TaskResourceSpec) runtimeInterfaces.TaskResourceSet {
result := runtimeInterfaces.TaskResourceSet{}
if len(spec.Cpu) > 0 {
result.CPU = parseQuantityNoError(ctx, "project", "cpu", spec.Cpu)
}
if len(spec.Memory) > 0 {
result.Memory = parseQuantityNoError(ctx, "project", "memory", spec.Memory)
}
if len(spec.Storage) > 0 {
result.Storage = parseQuantityNoError(ctx, "project", "storage", spec.Storage)
}
if len(spec.EphemeralStorage) > 0 {
result.EphemeralStorage = parseQuantityNoError(ctx, "project", "ephemeral storage", spec.EphemeralStorage)
}
if len(spec.Gpu) > 0 {
result.GPU = parseQuantityNoError(ctx, "project", "gpu", spec.Gpu)
}
return result
}
func (m *ExecutionManager) getTaskResources(ctx context.Context, workflow *core.Identifier) workflowengineInterfaces.TaskResources {
resource, err := m.resourceManager.GetResource(ctx, interfaces.ResourceRequest{
Project: workflow.Project,
Domain: workflow.Domain,
Workflow: workflow.Name,
ResourceType: admin.MatchableResource_TASK_RESOURCE,
})
if err != nil {
logger.Warningf(ctx, "Failed to fetch override values when assigning task resource default values for [%+v]: %v",
workflow, err)
}
logger.Debugf(ctx, "Assigning task requested resources for [%+v]", workflow)
var taskResourceAttributes = workflowengineInterfaces.TaskResources{}
if resource != nil && resource.Attributes != nil && resource.Attributes.GetTaskResourceAttributes() != nil {
taskResourceAttributes.Defaults = fromAdminProtoTaskResourceSpec(ctx, resource.Attributes.GetTaskResourceAttributes().Defaults)
taskResourceAttributes.Limits = fromAdminProtoTaskResourceSpec(ctx, resource.Attributes.GetTaskResourceAttributes().Limits)
} else {
taskResourceAttributes = workflowengineInterfaces.TaskResources{
Defaults: m.config.TaskResourceConfiguration().GetDefaults(),
Limits: m.config.TaskResourceConfiguration().GetLimits(),
}
}
return taskResourceAttributes
}
// 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)
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) {
if request.Spec.MaxParallelism > 0 {
return &admin.WorkflowExecutionConfig{
MaxParallelism: request.Spec.MaxParallelism,
}, nil
}
if launchPlan != nil && launchPlan.Spec.MaxParallelism > 0 {
return &admin.WorkflowExecutionConfig{
MaxParallelism: launchPlan.Spec.MaxParallelism,
}, nil
}
resource, err := m.resourceManager.GetResource(ctx, interfaces.ResourceRequest{
Project: request.Project,
Domain: request.Domain,
ResourceType: admin.MatchableResource_WORKFLOW_EXECUTION_CONFIG,
})
if err != nil {
if flyteAdminError, ok := err.(errors.FlyteAdminError); !ok || flyteAdminError.Code() != codes.NotFound {
logger.Errorf(ctx, "Failed to get workflow execution config overrides with error: %v", err)
return nil, err
}
}
if resource != nil && resource.Attributes.GetWorkflowExecutionConfig() != nil {
return resource.Attributes.GetWorkflowExecutionConfig(), nil
}
// Defaults to one from the application config
return &admin.WorkflowExecutionConfig{
MaxParallelism: m.config.ApplicationConfiguration().GetTopLevelConfig().GetMaxParallelism(),
}, 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
}
name := util.GetExecutionName(request)
workflowExecutionID := core.WorkflowExecutionIdentifier{
Project: request.Project,
Domain: request.Domain,
Name: name,
}
ctx = getExecutionContext(ctx, &workflowExecutionID)
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 := m.getTaskResources(ctx, workflow.Id)
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 := m.offloadInputs(ctx, request.Inputs, &workflowExecutionID, shared.Inputs)
if err != nil {
return nil, nil, err
}
userInputsURI, err := m.offloadInputs(ctx, request.Inputs, &workflowExecutionID, shared.UserInputs)
if err != nil {
return nil, nil, err
}
qualityOfService, err := m.qualityOfServiceAllocator.GetQualityOfService(ctx, executions.GetQualityOfServiceInput{
Workflow: &workflow,
LaunchPlan: launchPlan,
ExecutionCreateRequest: &request,
})
if err != nil {
logger.Errorf(ctx, "Failed to get quality of service for [%+v] with error: %v", workflowExecutionID, err)
return nil, nil, err
}
executionConfig, err := m.getExecutionConfig(ctx, &request, nil)
if err != nil {
return nil, nil, err
}
executeTaskInputs := workflowengineInterfaces.ExecuteTaskInput{
ExecutionID: &workflowExecutionID,
WfClosure: *workflow.Closure.CompiledWorkflow,
Inputs: request.Inputs,
ReferenceName: taskIdentifier.Name,
AcceptedAt: requestedAt,
Auth: requestSpec.AuthRole,
QueueingBudget: qualityOfService.QueuingBudget,
ExecutionConfig: executionConfig,
TaskResources: &platformTaskResources,
}
if requestSpec.Labels != nil {
executeTaskInputs.Labels = requestSpec.Labels.Values
}
executeTaskInputs.Labels, err = m.addProjectLabels(ctx, request.Project, executeTaskInputs.Labels)
if err != nil {
return nil, nil, err
}
if requestSpec.Annotations != nil {
executeTaskInputs.Annotations = requestSpec.Annotations.Values
}
overrides, err := m.addPluginOverrides(ctx, &workflowExecutionID, workflowExecutionID.Name, "")
if err != nil {
return nil, nil, err
}
if overrides != nil {
executeTaskInputs.TaskPluginOverrides = overrides
}
execInfo, err := m.workflowExecutor.ExecuteTask(ctx, executeTaskInputs)
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,
})
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 resolvePermissions(request *admin.ExecutionCreateRequest, launchPlan *admin.LaunchPlan) *admin.AuthRole {
if request.Spec.AuthRole != nil {
return request.Spec.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 (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
}
workflow, err := util.GetWorkflow(ctx, m.db, m.storageClient, *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
}
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
}
platformTaskResources := m.getTaskResources(ctx, workflow.Id)
// Dynamically assign task resource defaults.
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 := m.offloadInputs(ctx, executionInputs, &workflowExecutionID, shared.Inputs)
if err != nil {
return nil, nil, err
}
userInputsURI, err := m.offloadInputs(ctx, request.Inputs, &workflowExecutionID, shared.UserInputs)
if err != nil {
return nil, nil, err
}
qualityOfService, err := m.qualityOfServiceAllocator.GetQualityOfService(ctx, executions.GetQualityOfServiceInput{
Workflow: workflow,
LaunchPlan: launchPlan,
ExecutionCreateRequest: &request,
})
if err != nil {
logger.Errorf(ctx, "Failed to get quality of service for [%+v] with error: %v", workflowExecutionID, err)
return nil, nil, err
}
executionConfig, err := m.getExecutionConfig(ctx, &request, launchPlan)
if err != nil {
return nil, nil, err
}
// TODO: Reduce CRD size and use offloaded input URI to blob store instead.
executeWorkflowInputs := workflowengineInterfaces.ExecuteWorkflowInput{
ExecutionID: &workflowExecutionID,
WfClosure: *workflow.Closure.CompiledWorkflow,
Inputs: executionInputs,
Reference: *launchPlan,
AcceptedAt: requestedAt,
QueueingBudget: qualityOfService.QueuingBudget,
ExecutionConfig: executionConfig,
Auth: resolvePermissions(&request, launchPlan),
TaskResources: &platformTaskResources,
}
err = m.addLabelsAndAnnotations(request.Spec, &executeWorkflowInputs)
if err != nil {
return nil, nil, err
}
executeWorkflowInputs.Labels, err = m.addProjectLabels(ctx, request.Project, executeWorkflowInputs.Labels)
if err != nil {
return nil, nil, err
}
overrides, err := m.addPluginOverrides(ctx, &workflowExecutionID, launchPlan.GetSpec().WorkflowId.Name, launchPlan.Id.Name)
if err != nil {
return nil, nil, err
}
if overrides != nil {
executeWorkflowInputs.TaskPluginOverrides = overrides
}
if request.Spec.Metadata != nil && request.Spec.Metadata.ReferenceExecution != nil &&
request.Spec.Metadata.Mode == admin.ExecutionMetadata_RECOVERED {
executeWorkflowInputs.RecoveryExecution = request.Spec.Metadata.ReferenceExecution
}
execInfo, err := m.workflowExecutor.ExecuteWorkflow(ctx, executeWorkflowInputs)
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,
})
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)
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
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(
ctx context.Context, request admin.ExecutionRecoverRequest, 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)
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
}
}
if request.Metadata != nil {
executionSpec.Metadata.ParentNodeExecution = request.Metadata.ParentNodeExecution
}
executionSpec.Metadata.Mode = admin.ExecutionMetadata_RECOVERED
executionSpec.Metadata.ReferenceExecution = existingExecution.Id
var executionModel *models.Execution
ctx, executionModel, err = m.launchExecutionAndPrepareModel(ctx, admin.ExecutionCreateRequest{