-
Notifications
You must be signed in to change notification settings - Fork 882
Expand file tree
/
Copy pathpod_helper.go
More file actions
1801 lines (1589 loc) · 70.8 KB
/
Copy pathpod_helper.go
File metadata and controls
1801 lines (1589 loc) · 70.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package flytek8s
import (
"context"
"errors"
"fmt"
"regexp"
"strconv"
"strings"
"sync"
"time"
"github.com/golang/protobuf/proto" //nolint: staticcheck
"github.com/imdario/mergo"
"google.golang.org/protobuf/types/known/timestamppb"
v1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/sets"
"sigs.k8s.io/controller-runtime/pkg/client"
pluginserrors "github.com/flyteorg/flyte/v2/flyteplugins/go/tasks/errors"
pluginsCore "github.com/flyteorg/flyte/v2/flyteplugins/go/tasks/pluginmachinery/core"
"github.com/flyteorg/flyte/v2/flyteplugins/go/tasks/pluginmachinery/core/template"
"github.com/flyteorg/flyte/v2/flyteplugins/go/tasks/pluginmachinery/flytek8s/config"
"github.com/flyteorg/flyte/v2/flyteplugins/go/tasks/pluginmachinery/k8s"
"github.com/flyteorg/flyte/v2/flyteplugins/go/tasks/pluginmachinery/utils"
"github.com/flyteorg/flyte/v2/flytestdlib/logger"
"github.com/flyteorg/flyte/v2/gen/go/flyteidl2/core"
)
const PodKind = "pod"
const OOMKilled = "OOMKilled"
const Interrupted = "Interrupted"
const PrimaryContainerNotFound = "PrimaryContainerNotFound"
const SIGKILL = 137
// unsignedSIGKILL = 256 - 9
const unsignedSIGKILL = 247
// ContainerFailed is reported when the task's container exited with a non-zero status of its own
// accord and the container runtime gave no more specific reason.
const ContainerFailed = "ContainerFailed"
// maxUserExitCode is the highest exit status attributable to the application itself. A process
// killed by signal N is reported as 128+N, so the band above 127 means something terminated the
// process rather than the process choosing to fail. Graceful eviction, drain and preemption all
// send SIGTERM first, which surfaces as 143.
const maxUserExitCode = 127
const defaultContainerTemplateName = "default"
const defaultInitContainerTemplateName = "default-init"
const primaryContainerTemplateName = "primary"
const primaryInitContainerTemplateName = "primary-init"
const PrimaryContainerKey = "primary_container_name"
const FlyteEnableVscode = "_F_E_VS"
// GpuPartitionSlicesLabel is applied to pods that request a MIG GPU partition.
// The value is the number of compute slices consumed (out of 7 total), parsed from
// the "Xg.Ygb" partition size format. Downstream consumers (e.g. billing) use this
// to compute fractional GPU usage as slices/7.
const GpuPartitionSlicesLabel = "platform.union.ai/gpu-partition-slices"
// ManagedLabelKey and ManagedLabelValue mark the Pods the executor is responsible for.
// The executor's informer cache selects on this label so it does not have to hold every
// Pod in the cluster, so anything the executor needs to observe must carry it. It lives
// here rather than in the executor because the plugins that build Pod templates have to
// keep it intact.
const (
ManagedLabelKey = "flyte.org/managed"
ManagedLabelValue = "true"
)
var migPartitionRegexp = regexp.MustCompile(`^(\d+)g\.\d+gb$`)
// parseMigSlices extracts the compute slice count from a MIG partition size string
// (e.g. "1g.5gb" → "1", "3g.20gb" → "3"). Returns the slice count as a string,
// or empty string if the format doesn't match.
func parseMigSlices(partitionSize string) string {
matches := migPartitionRegexp.FindStringSubmatch(partitionSize)
if matches == nil {
return ""
}
return matches[1]
}
var retryableStatusReasons = sets.NewString(
// Reasons that indicate the node was preempted aggressively.
// Kubelet can miss deleting the pod prior to the node being shutdown.
"Shutdown",
"Terminated",
"NodeShutdown",
// kubelet admission rejects the pod before the node gets assigned appropriate labels.
"NodeAffinity",
)
// AddRequiredNodeSelectorRequirements adds the provided v1.NodeSelectorRequirement
// objects to an existing v1.Affinity object. If there are no existing required
// node selectors, the new v1.NodeSelectorRequirement will be added as-is.
// However, if there are existing required node selectors, we iterate over all existing
// node selector terms and append the node selector requirement. Note that multiple node
// selector terms are OR'd, and match expressions within a single node selector term
// are AND'd during scheduling.
// See: https://kubernetes.io/docs/concepts/scheduling-eviction/assign-pod-node/#node-affinity
func AddRequiredNodeSelectorRequirements(base *v1.Affinity, new ...v1.NodeSelectorRequirement) {
if base.NodeAffinity == nil {
base.NodeAffinity = &v1.NodeAffinity{}
}
if base.NodeAffinity.RequiredDuringSchedulingIgnoredDuringExecution == nil {
base.NodeAffinity.RequiredDuringSchedulingIgnoredDuringExecution = &v1.NodeSelector{}
}
if len(base.NodeAffinity.RequiredDuringSchedulingIgnoredDuringExecution.NodeSelectorTerms) > 0 {
nodeSelectorTerms := base.NodeAffinity.RequiredDuringSchedulingIgnoredDuringExecution.NodeSelectorTerms
for i := range nodeSelectorTerms {
nst := &nodeSelectorTerms[i]
for _, req := range new {
if !containsNodeSelectorRequirement(nst.MatchExpressions, req) {
nst.MatchExpressions = append(nst.MatchExpressions, req)
}
}
}
} else {
base.NodeAffinity.RequiredDuringSchedulingIgnoredDuringExecution.NodeSelectorTerms = []v1.NodeSelectorTerm{{MatchExpressions: new}}
}
}
// containsNodeSelectorRequirement reports whether reqs already holds an identical
// requirement, so callers (e.g. ApplyGPUNodeSelectors, which may run more than once
// on the same pod spec) stay idempotent instead of duplicating match expressions.
func containsNodeSelectorRequirement(reqs []v1.NodeSelectorRequirement, req v1.NodeSelectorRequirement) bool {
for i := range reqs {
if reqs[i].Key != req.Key || reqs[i].Operator != req.Operator || len(reqs[i].Values) != len(req.Values) {
continue
}
match := true
for j := range req.Values {
if reqs[i].Values[j] != req.Values[j] {
match = false
break
}
}
if match {
return true
}
}
return false
}
// AddPreferredNodeSelectorRequirements appends the provided v1.NodeSelectorRequirement
// objects to an existing v1.Affinity object's list of preferred scheduling terms.
// See: https://kubernetes.io/docs/concepts/scheduling-eviction/assign-pod-node/#node-affinity-weight
// for how weights are used during scheduling.
func AddPreferredNodeSelectorRequirements(base *v1.Affinity, weight int32, new ...v1.NodeSelectorRequirement) {
if base.NodeAffinity == nil {
base.NodeAffinity = &v1.NodeAffinity{}
}
base.NodeAffinity.PreferredDuringSchedulingIgnoredDuringExecution = append(
base.NodeAffinity.PreferredDuringSchedulingIgnoredDuringExecution,
v1.PreferredSchedulingTerm{
Weight: weight,
Preference: v1.NodeSelectorTerm{
MatchExpressions: new,
},
},
)
}
// ApplyInterruptibleNodeSelectorRequirement configures the node selector requirement of the node-affinity using the configuration specified.
func ApplyInterruptibleNodeSelectorRequirement(interruptible bool, affinity *v1.Affinity) {
// Determine node selector terms to add to node affinity
var nodeSelectorRequirement v1.NodeSelectorRequirement
if interruptible {
if config.GetK8sPluginConfig().InterruptibleNodeSelectorRequirement == nil {
return
}
nodeSelectorRequirement = *config.GetK8sPluginConfig().InterruptibleNodeSelectorRequirement
} else {
if config.GetK8sPluginConfig().NonInterruptibleNodeSelectorRequirement == nil {
return
}
nodeSelectorRequirement = *config.GetK8sPluginConfig().NonInterruptibleNodeSelectorRequirement
}
AddRequiredNodeSelectorRequirements(affinity, nodeSelectorRequirement)
}
// ApplyInterruptibleNodeAffinity configures the node-affinity for the pod using the configuration specified.
func ApplyInterruptibleNodeAffinity(interruptible bool, podSpec *v1.PodSpec) {
if podSpec.Affinity == nil {
podSpec.Affinity = &v1.Affinity{}
}
ApplyInterruptibleNodeSelectorRequirement(interruptible, podSpec.Affinity)
}
// ApplyPlatformSchedulingConstraints re-applies the platform-injected scheduling
// constraints that a custom pod-spec merge can dilute or drop, and MUST be called
// after MergeOverlayPodSpecOntoBase. mergo appends a custom pod's node selector terms
// as new OR'd alternatives, so any REQUIRED node-affinity requirement the base carried
// — the configured DefaultAffinity requirements and the (non)interruptible requirement
// — ends up only on the base term; a pod could then satisfy an appended custom term
// alone and escape the constraint. This re-adds those requirements to every term and
// re-applies the interruptible node selector and tolerations. All operations are
// idempotent (AddRequiredNodeSelectorRequirements / addTolerationInPodSpec skip
// entries already present), so re-applying to an unmerged base pod is a no-op.
//
// Note: DefaultAffinity requirements are AND'd onto every term, which is the intended
// semantics for the common single-term DefaultAffinity. A DefaultAffinity expressed as
// multiple OR'd terms would be tightened to AND across those requirements.
func ApplyPlatformSchedulingConstraints(interruptible bool, podSpec *v1.PodSpec) {
if podSpec.Affinity == nil {
podSpec.Affinity = &v1.Affinity{}
}
// Re-add the configured DefaultAffinity required requirements to every term.
if da := config.GetK8sPluginConfig().DefaultAffinity; da != nil && da.NodeAffinity != nil &&
da.NodeAffinity.RequiredDuringSchedulingIgnoredDuringExecution != nil {
for _, term := range da.NodeAffinity.RequiredDuringSchedulingIgnoredDuringExecution.NodeSelectorTerms {
AddRequiredNodeSelectorRequirements(podSpec.Affinity, term.MatchExpressions...)
}
}
// Re-add the (non)interruptible requirement to every term.
ApplyInterruptibleNodeSelectorRequirement(interruptible, podSpec.Affinity)
if !interruptible {
return
}
cfg := config.GetK8sPluginConfig()
if len(cfg.InterruptibleNodeSelector) > 0 {
podSpec.NodeSelector = utils.UnionMaps(podSpec.NodeSelector, cfg.InterruptibleNodeSelector)
}
// addTolerationInPodSpec is a no-op when the toleration is already present, so
// re-applying does not duplicate tolerations seeded earlier by UpdatePod.
for i := range cfg.InterruptibleTolerations {
addTolerationInPodSpec(podSpec, &cfg.InterruptibleTolerations[i])
}
}
// Specialized merging of overrides into a base *core.ExtendedResources object. Note
// that doing a nested merge may not be the intended behavior all the time, so we
// handle each field separately here.
func ApplyExtendedResourcesOverrides(base, overrides *core.ExtendedResources) *core.ExtendedResources {
// Handle case where base might be nil
var new *core.ExtendedResources
if base == nil {
new = &core.ExtendedResources{}
} else {
new = proto.Clone(base).(*core.ExtendedResources)
}
// No overrides found
if overrides == nil {
return new
}
// GPU Accelerator
if overrides.GetGpuAccelerator() != nil {
new.GpuAccelerator = overrides.GetGpuAccelerator()
}
if overrides.GetSharedMemory() != nil {
new.SharedMemory = overrides.GetSharedMemory()
}
return new
}
func ApplySharedMemory(podSpec *v1.PodSpec, primaryContainerName string, SharedMemory *core.SharedMemory) error {
sharedMountName := SharedMemory.GetMountName()
sharedMountPath := SharedMemory.GetMountPath()
if sharedMountName == "" {
return pluginserrors.Errorf(pluginserrors.BadTaskSpecification, "mount name is not set")
}
if sharedMountPath == "" {
return pluginserrors.Errorf(pluginserrors.BadTaskSpecification, "mount path is not set")
}
var primaryContainer *v1.Container
for index, container := range podSpec.Containers {
if container.Name == primaryContainerName {
primaryContainer = &podSpec.Containers[index]
}
}
if primaryContainer == nil {
return pluginserrors.Errorf(pluginserrors.BadTaskSpecification, "Unable to find primary container")
}
for _, volume := range podSpec.Volumes {
if volume.Name == sharedMountName {
return pluginserrors.Errorf(pluginserrors.BadTaskSpecification, "A volume is already named %v in pod spec", sharedMountName)
}
}
for _, volume_mount := range primaryContainer.VolumeMounts {
if volume_mount.Name == sharedMountName {
return pluginserrors.Errorf(pluginserrors.BadTaskSpecification, "A volume is already named %v in container", sharedMountName)
}
if volume_mount.MountPath == sharedMountPath {
return pluginserrors.Errorf(pluginserrors.BadTaskSpecification, "%s is already mounted in container", sharedMountPath)
}
}
var quantity resource.Quantity
var err error
if len(SharedMemory.GetSizeLimit()) != 0 {
quantity, err = resource.ParseQuantity(SharedMemory.GetSizeLimit())
if err != nil {
return pluginserrors.Errorf(pluginserrors.BadTaskSpecification, "Unable to parse size limit: %v", err.Error())
}
}
podSpec.Volumes = append(
podSpec.Volumes,
v1.Volume{
Name: sharedMountName,
VolumeSource: v1.VolumeSource{EmptyDir: &v1.EmptyDirVolumeSource{Medium: v1.StorageMediumMemory, SizeLimit: &quantity}},
},
)
primaryContainer.VolumeMounts = append(primaryContainer.VolumeMounts, v1.VolumeMount{Name: sharedMountName, MountPath: sharedMountPath})
return nil
}
// getAcceleratorConfig returns the configuration for the given accelerator device class.
// It first attempts to get device-class-specific configuration from AcceleratorDeviceClasses.
// If not found or incomplete, it falls back to the global GPU configuration fields for backward compatibility.
func getAcceleratorConfig(gpuAccelerator *core.GPUAccelerator) config.AcceleratorDeviceClassConfig {
cfg := config.GetK8sPluginConfig()
// Start with defaults from global GPU config
accelConfig := config.AcceleratorDeviceClassConfig{
ResourceName: cfg.GpuResourceName, //nolint: staticcheck
DeviceNodeLabel: cfg.GpuDeviceNodeLabel,
PartitionSizeNodeLabel: cfg.GpuPartitionSizeNodeLabel,
UnpartitionedNodeSelectorRequirement: cfg.GpuUnpartitionedNodeSelectorRequirement,
UnpartitionedToleration: cfg.GpuUnpartitionedToleration,
}
// Override with device-class-specific config if available
if gpuAccelerator != nil {
deviceClass := gpuAccelerator.GetDeviceClass().String()
if deviceClassConfig, ok := cfg.AcceleratorDeviceClasses[deviceClass]; ok {
logger.Debugf(context.TODO(), "Using device-class-specific configuration for accelerator class: %s", deviceClass)
// Override resource name if specified
if deviceClassConfig.ResourceName != "" {
accelConfig.ResourceName = deviceClassConfig.ResourceName
}
// Override device node label if specified
if deviceClassConfig.DeviceNodeLabel != "" {
accelConfig.DeviceNodeLabel = deviceClassConfig.DeviceNodeLabel
}
// Override partition size node label if specified
if deviceClassConfig.PartitionSizeNodeLabel != "" {
accelConfig.PartitionSizeNodeLabel = deviceClassConfig.PartitionSizeNodeLabel
}
// Override unpartitioned node selector requirement if specified
if deviceClassConfig.UnpartitionedNodeSelectorRequirement != nil {
accelConfig.UnpartitionedNodeSelectorRequirement = deviceClassConfig.UnpartitionedNodeSelectorRequirement
}
// Override unpartitioned toleration if specified
if deviceClassConfig.UnpartitionedToleration != nil {
accelConfig.UnpartitionedToleration = deviceClassConfig.UnpartitionedToleration
}
// Override PodTemplate if specified
if deviceClassConfig.PodTemplate != nil {
accelConfig.PodTemplate = deviceClassConfig.PodTemplate
}
} else {
logger.Warnf(context.TODO(), "Device class '%s' not found in AcceleratorDeviceClasses configuration, falling back to global GPU config. Available device classes: %v",
deviceClass, getConfiguredDeviceClasses(cfg.AcceleratorDeviceClasses))
}
}
return accelConfig
}
func ApplyGPUNodeSelectors(podSpec *v1.PodSpec, gpuAccelerator *core.GPUAccelerator) {
// Short circuit if pod spec does not contain any containers that use accelerators
if !podRequiresAccelerator(podSpec) {
return
}
if podSpec.Affinity == nil {
podSpec.Affinity = &v1.Affinity{}
}
// Get device-class-specific configuration
accelConfig := getAcceleratorConfig(gpuAccelerator)
// Apply changes for GPU device
if device := gpuAccelerator.GetDevice(); len(device) > 0 {
// Normalize the device name
normalizedDevice := GetNormalizedAcceleratorDevice(device)
// Add node selector requirement for GPU device
deviceNsr := v1.NodeSelectorRequirement{
Key: accelConfig.DeviceNodeLabel,
Operator: v1.NodeSelectorOpIn,
Values: []string{normalizedDevice},
}
AddRequiredNodeSelectorRequirements(podSpec.Affinity, deviceNsr)
// Add toleration for GPU device
deviceTol := v1.Toleration{
Key: accelConfig.DeviceNodeLabel,
Value: normalizedDevice,
Operator: v1.TolerationOpEqual,
Effect: v1.TaintEffectNoSchedule,
}
addTolerationInPodSpec(podSpec, &deviceTol)
}
// Short circuit if a partition size preference is not specified
partitionSizeValue := gpuAccelerator.GetPartitionSizeValue()
if partitionSizeValue == nil {
return
}
// Apply changes for GPU partition size, if applicable
var partitionSizeNsr *v1.NodeSelectorRequirement
var partitionSizeTol *v1.Toleration
switch p := partitionSizeValue.(type) {
case *core.GPUAccelerator_Unpartitioned:
if !p.Unpartitioned {
break
}
if accelConfig.UnpartitionedNodeSelectorRequirement != nil {
partitionSizeNsr = accelConfig.UnpartitionedNodeSelectorRequirement
} else {
partitionSizeNsr = &v1.NodeSelectorRequirement{
Key: accelConfig.PartitionSizeNodeLabel,
Operator: v1.NodeSelectorOpDoesNotExist,
}
}
if accelConfig.UnpartitionedToleration != nil {
partitionSizeTol = accelConfig.UnpartitionedToleration
}
case *core.GPUAccelerator_PartitionSize:
partitionSizeNsr = &v1.NodeSelectorRequirement{
Key: accelConfig.PartitionSizeNodeLabel,
Operator: v1.NodeSelectorOpIn,
Values: []string{p.PartitionSize},
}
partitionSizeTol = &v1.Toleration{
Key: accelConfig.PartitionSizeNodeLabel,
Value: p.PartitionSize,
Operator: v1.TolerationOpEqual,
Effect: v1.TaintEffectNoSchedule,
}
}
if partitionSizeNsr != nil {
AddRequiredNodeSelectorRequirements(podSpec.Affinity, *partitionSizeNsr)
}
if partitionSizeTol != nil {
addTolerationInPodSpec(podSpec, partitionSizeTol)
}
}
// UpdatePod updates the base pod spec used to execute tasks. This is configured with plugins and task metadata-specific options
func UpdatePod(taskExecutionMetadata pluginsCore.TaskExecutionMetadata,
resourceRequirements []v1.ResourceRequirements, podSpec *v1.PodSpec) {
if len(podSpec.RestartPolicy) == 0 {
podSpec.RestartPolicy = v1.RestartPolicyNever
}
podSpec.Tolerations = append(
GetPodTolerations(taskExecutionMetadata.IsInterruptible(), resourceRequirements...), podSpec.Tolerations...)
if len(podSpec.ServiceAccountName) == 0 {
podSpec.ServiceAccountName = taskExecutionMetadata.GetK8sServiceAccount()
}
if len(podSpec.SchedulerName) == 0 {
podSpec.SchedulerName = config.GetK8sPluginConfig().SchedulerName
}
podSpec.NodeSelector = utils.UnionMaps(config.GetK8sPluginConfig().DefaultNodeSelector, podSpec.NodeSelector)
if taskExecutionMetadata.IsInterruptible() {
podSpec.NodeSelector = utils.UnionMaps(podSpec.NodeSelector, config.GetK8sPluginConfig().InterruptibleNodeSelector)
}
if podSpec.Affinity == nil && config.GetK8sPluginConfig().DefaultAffinity != nil {
podSpec.Affinity = config.GetK8sPluginConfig().DefaultAffinity.DeepCopy()
}
if podSpec.SecurityContext == nil && config.GetK8sPluginConfig().DefaultPodSecurityContext != nil {
podSpec.SecurityContext = config.GetK8sPluginConfig().DefaultPodSecurityContext.DeepCopy()
}
if config.GetK8sPluginConfig().EnableHostNetworkingPod != nil {
podSpec.HostNetwork = *config.GetK8sPluginConfig().EnableHostNetworkingPod
}
if podSpec.DNSConfig == nil && config.GetK8sPluginConfig().DefaultPodDNSConfig != nil {
podSpec.DNSConfig = config.GetK8sPluginConfig().DefaultPodDNSConfig.DeepCopy()
}
ApplyInterruptibleNodeAffinity(taskExecutionMetadata.IsInterruptible(), podSpec)
}
func mergeMapInto(src map[string]string, dst map[string]string) {
for key, value := range src {
dst[key] = value
}
}
// BuildRawPod constructs a PodSpec and ObjectMeta based on the definition passed by the TaskExecutionContext. This
// definition does not include any configuration injected by Flyte.
func BuildRawPod(ctx context.Context, tCtx pluginsCore.TaskExecutionContext) (*v1.PodSpec, *metav1.ObjectMeta, string, error) {
taskTemplate, err := tCtx.TaskReader().Read(ctx)
if err != nil {
logger.Warnf(ctx, "failed to read task information when trying to construct Pod, err: %s", err.Error())
return nil, nil, "", err
}
var podSpec *v1.PodSpec
objectMeta := metav1.ObjectMeta{
Annotations: make(map[string]string),
Labels: make(map[string]string),
}
primaryContainerName := ""
switch target := taskTemplate.GetTarget().(type) {
case *core.TaskTemplate_Container:
// handles tasks defined by a single container
c, err := BuildRawContainer(ctx, tCtx)
if err != nil {
return nil, nil, "", err
}
primaryContainerName = c.Name
podSpec = &v1.PodSpec{
Containers: []v1.Container{
*c,
},
}
// handle pod template override
podTemplate := tCtx.TaskExecutionMetadata().GetOverrides().GetPodTemplate()
if podTemplate.GetPodSpec() != nil {
podSpec, objectMeta, err = ApplyPodTemplateOverride(objectMeta, podTemplate)
if err != nil {
return nil, nil, "", err
}
primaryContainerName = podTemplate.GetPrimaryContainerName()
}
case *core.TaskTemplate_K8SPod:
// handles pod tasks that marshal the pod spec to the k8s_pod task target.
if target.K8SPod.PodSpec == nil {
return nil, nil, "", pluginserrors.Errorf(pluginserrors.BadTaskSpecification,
"Pod tasks with task type version > 1 should specify their target as a K8sPod with a defined pod spec")
}
err := utils.UnmarshalStructToObj(target.K8SPod.PodSpec, &podSpec) //nolint: staticcheck
if err != nil {
return nil, nil, "", pluginserrors.Errorf(pluginserrors.BadTaskSpecification,
"Unable to unmarshal task k8s pod [%v], Err: [%v]", target.K8SPod.PodSpec, err.Error())
}
// get primary container name
var ok bool
if primaryContainerName, ok = taskTemplate.GetConfig()[PrimaryContainerKey]; !ok {
return nil, nil, "", pluginserrors.Errorf(pluginserrors.BadTaskSpecification,
"invalid TaskSpecification, config missing [%s] key in [%v]", PrimaryContainerKey, taskTemplate.GetConfig())
}
// update annotations and labels
if taskTemplate.GetK8SPod().Metadata != nil {
mergeMapInto(target.K8SPod.Metadata.Annotations, objectMeta.Annotations)
mergeMapInto(target.K8SPod.Metadata.Labels, objectMeta.Labels)
}
// handle pod template override
podTemplate := tCtx.TaskExecutionMetadata().GetOverrides().GetPodTemplate()
if podTemplate.GetPodSpec() != nil {
podSpec, objectMeta, err = ApplyPodTemplateOverride(objectMeta, podTemplate)
if err != nil {
return nil, nil, "", err
}
primaryContainerName = podTemplate.GetPrimaryContainerName()
}
default:
return nil, nil, "", pluginserrors.Errorf(pluginserrors.BadTaskSpecification,
"invalid TaskSpecification, unable to determine Pod configuration")
}
enableServiceLinks := false
podSpec.EnableServiceLinks = &enableServiceLinks
return podSpec, &objectMeta, primaryContainerName, nil
}
func hasExternalLinkType(taskTemplate *core.TaskTemplate) bool {
if taskTemplate == nil {
return false
}
config := taskTemplate.GetConfig()
if config == nil {
return false
}
// The presence of any "link_type" is sufficient to guarantee that the console URL should be included.
_, exists := config["link_type"]
return exists
}
// PodSpecMutator is a hook applied to every pod spec built through
// ApplyFlytePodConfiguration, after its own construction and template merging.
// Individual plugins may still adapt the returned spec afterward (e.g. translate
// it into CRD fields), which can drop mutator changes. Mutators let embedding
// applications extend pod construction without forking this package. A mutator
// must be idempotent: the same spec may pass through pod construction more than
// once.
type PodSpecMutator func(spec *v1.PodSpec, primaryContainerName string) error
var podSpecMutators struct {
m sync.Mutex
mutators []PodSpecMutator
}
// RegisterPodSpecMutator registers a mutator applied to every pod spec built by
// ApplyFlytePodConfiguration. Register at startup, before any pods are built.
func RegisterPodSpecMutator(mutator PodSpecMutator) {
podSpecMutators.m.Lock()
defer podSpecMutators.m.Unlock()
podSpecMutators.mutators = append(podSpecMutators.mutators, mutator)
}
func applyPodSpecMutators(spec *v1.PodSpec, primaryContainerName string) error {
podSpecMutators.m.Lock()
mutators := podSpecMutators.mutators
podSpecMutators.m.Unlock()
for _, mutate := range mutators {
if err := mutate(spec, primaryContainerName); err != nil {
return err
}
}
return nil
}
// ApplyFlytePodConfiguration updates the PodSpec and ObjectMeta with various Flyte configuration. This includes
// applying default k8s configuration, applying overrides (resources etc.), injecting copilot containers, and merging with the
// configuration PodTemplate (if exists).
func ApplyFlytePodConfiguration(ctx context.Context, tCtx pluginsCore.TaskExecutionContext, podSpec *v1.PodSpec, objectMeta *metav1.ObjectMeta, primaryContainerName string) (*v1.PodSpec, *metav1.ObjectMeta, error) {
taskTemplate, err := tCtx.TaskReader().Read(ctx)
if err != nil {
logger.Warnf(ctx, "failed to read task information when trying to construct Pod, err: %s", err.Error())
return nil, nil, err
}
// add flyte resource customizations to containers
templateParameters := template.Parameters{
Inputs: tCtx.InputReader(),
OutputPath: tCtx.OutputWriter(),
Task: tCtx.TaskReader(),
TaskExecMetadata: tCtx.TaskExecutionMetadata(),
IncludeConsoleURL: hasExternalLinkType(taskTemplate),
}
// Merge overrides with base extended resources
extendedResources := ApplyExtendedResourcesOverrides(
taskTemplate.GetExtendedResources(),
tCtx.TaskExecutionMetadata().GetOverrides().GetExtendedResources(),
)
// iterate over the initContainers first
for index := range podSpec.InitContainers {
var resourceMode = ResourceCustomizationModeEnsureExistingResourcesInRange
if err := AddFlyteCustomizationsToContainer(ctx, templateParameters, resourceMode, &podSpec.InitContainers[index], extendedResources); err != nil {
return nil, nil, err
}
}
resourceRequests := make([]v1.ResourceRequirements, 0, len(podSpec.Containers))
var primaryContainer *v1.Container
for index, container := range podSpec.Containers {
var resourceMode = ResourceCustomizationModeEnsureExistingResourcesInRange
if container.Name == primaryContainerName {
resourceMode = ResourceCustomizationModeMergeExistingResources
}
if err := AddFlyteCustomizationsToContainer(ctx, templateParameters, resourceMode, &podSpec.Containers[index], extendedResources); err != nil {
return nil, nil, err
}
resourceRequests = append(resourceRequests, podSpec.Containers[index].Resources)
if container.Name == primaryContainerName {
primaryContainer = &podSpec.Containers[index]
}
}
if primaryContainer == nil {
return nil, nil, pluginserrors.Errorf(pluginserrors.BadTaskSpecification, "invalid TaskSpecification, primary container [%s] not defined", primaryContainerName)
}
// add copilot configuration to primaryContainer and PodSpec (if necessary)
var dataLoadingConfig *core.DataLoadingConfig
if container := taskTemplate.GetContainer(); container != nil {
dataLoadingConfig = container.GetDataConfig()
} else if pod := taskTemplate.GetK8SPod(); pod != nil {
dataLoadingConfig = pod.GetDataConfig()
}
primaryInitContainerName := ""
if dataLoadingConfig != nil {
if err := AddCoPilotToContainer(ctx, config.GetK8sPluginConfig().CoPilot,
primaryContainer, taskTemplate.Interface, dataLoadingConfig); err != nil {
return nil, nil, err
}
if err := AddCoPilotToPod(ctx, config.GetK8sPluginConfig().CoPilot, podSpec, taskTemplate.GetInterface(),
tCtx.TaskExecutionMetadata(), tCtx.InputReader(), tCtx.OutputWriter(), dataLoadingConfig); err != nil {
return nil, nil, err
}
}
// update primaryContainer and PodSpec with k8s plugin configuration, etc
UpdatePod(tCtx.TaskExecutionMetadata(), resourceRequests, podSpec)
if primaryContainer.SecurityContext == nil && config.GetK8sPluginConfig().DefaultSecurityContext != nil {
primaryContainer.SecurityContext = config.GetK8sPluginConfig().DefaultSecurityContext.DeepCopy()
}
// Apply device-class-specific PodTemplate (if applicable)
// This provides device-specific defaults while allowing task configs to override
podSpec, err = applyAcceleratorDeviceClassPodTemplate(ctx, podSpec, extendedResources, primaryContainerName, primaryInitContainerName)
if err != nil {
return nil, nil, err
}
// merge PodSpec and ObjectMeta with configuration pod template (if exists)
podSpec, objectMeta, err = MergeWithBasePodTemplate(ctx, tCtx, podSpec, objectMeta, primaryContainerName, primaryInitContainerName)
if err != nil {
return nil, nil, err
}
// GPU accelerator
if extendedResources.GetGpuAccelerator() != nil {
ApplyGPUNodeSelectors(podSpec, extendedResources.GetGpuAccelerator())
if ps, ok := extendedResources.GetGpuAccelerator().GetPartitionSizeValue().(*core.GPUAccelerator_PartitionSize); ok {
if slices := parseMigSlices(ps.PartitionSize); slices != "" {
if objectMeta.Labels == nil {
objectMeta.Labels = make(map[string]string)
}
objectMeta.Labels[GpuPartitionSlicesLabel] = slices
}
}
}
// Shared memory volume
if extendedResources.GetSharedMemory() != nil {
err = ApplySharedMemory(podSpec, primaryContainerName, extendedResources.GetSharedMemory())
if err != nil {
return nil, nil, err
}
}
// Override container image if necessary
if len(tCtx.TaskExecutionMetadata().GetOverrides().GetContainerImage()) > 0 {
ApplyContainerImageOverride(podSpec, tCtx.TaskExecutionMetadata().GetOverrides().GetContainerImage(), primaryContainerName)
}
// apply registered pod spec mutators last so they observe the fully built spec
if err := applyPodSpecMutators(podSpec, primaryContainerName); err != nil {
return nil, nil, err
}
return podSpec, objectMeta, nil
}
func IsVscodeEnabled(ctx context.Context, envVar []v1.EnvVar) bool {
for _, env := range envVar {
if env.Name != FlyteEnableVscode {
continue
}
var err error
enableVscode, err := strconv.ParseBool(env.Value)
if err != nil {
logger.Errorf(ctx, "failed to parse %s env var: [%s]", FlyteEnableVscode, env.Value)
return false
}
return enableVscode
}
return false
}
func ApplyContainerImageOverride(podSpec *v1.PodSpec, containerImage string, primaryContainerName string) {
for i, c := range podSpec.Containers {
if c.Name == primaryContainerName {
podSpec.Containers[i].Image = containerImage
return
}
}
}
func ApplyPodTemplateOverride(objectMeta metav1.ObjectMeta, podTemplate *core.K8SPod) (*v1.PodSpec, metav1.ObjectMeta, error) {
if podTemplate.GetMetadata().GetAnnotations() != nil {
mergeMapInto(podTemplate.GetMetadata().GetAnnotations(), objectMeta.Annotations)
}
if podTemplate.GetMetadata().GetLabels() != nil {
mergeMapInto(podTemplate.GetMetadata().GetLabels(), objectMeta.Labels)
}
var podSpecOverride *v1.PodSpec
err := utils.UnmarshalStructToObj(podTemplate.GetPodSpec(), &podSpecOverride) //nolint: staticcheck
if err != nil {
return nil, objectMeta, err
}
return podSpecOverride, objectMeta, nil
}
func addTolerationInPodSpec(podSpec *v1.PodSpec, toleration *v1.Toleration) *v1.PodSpec {
podTolerations := podSpec.Tolerations
var newTolerations []v1.Toleration
for i := range podTolerations {
if toleration.MatchToleration(&podTolerations[i]) {
return podSpec
}
newTolerations = append(newTolerations, podTolerations[i])
}
newTolerations = append(newTolerations, *toleration)
podSpec.Tolerations = newTolerations
return podSpec
}
func AddTolerationsForExtendedResources(podSpec *v1.PodSpec) *v1.PodSpec {
if podSpec == nil {
podSpec = &v1.PodSpec{}
}
resources := sets.NewString()
for _, container := range podSpec.Containers {
for _, extendedResource := range config.GetK8sPluginConfig().AddTolerationsForExtendedResources {
if _, ok := container.Resources.Requests[v1.ResourceName(extendedResource)]; ok {
resources.Insert(extendedResource)
}
}
}
for _, container := range podSpec.InitContainers {
for _, extendedResource := range config.GetK8sPluginConfig().AddTolerationsForExtendedResources {
if _, ok := container.Resources.Requests[v1.ResourceName(extendedResource)]; ok {
resources.Insert(extendedResource)
}
}
}
for _, resource := range resources.List() {
addTolerationInPodSpec(podSpec, &v1.Toleration{
Key: resource,
Operator: v1.TolerationOpExists,
Effect: v1.TaintEffectNoSchedule,
})
}
return podSpec
}
// ToK8sPodSpec builds a PodSpec and ObjectMeta based on the definition passed by the TaskExecutionContext. This
// involves parsing the raw PodSpec definition and applying all Flyte configuration options.
func ToK8sPodSpec(ctx context.Context, tCtx pluginsCore.TaskExecutionContext) (*v1.PodSpec, *metav1.ObjectMeta, string, error) {
// build raw PodSpec and ObjectMeta
podSpec, objectMeta, primaryContainerName, err := BuildRawPod(ctx, tCtx)
if err != nil {
return nil, nil, "", err
}
// add flyte configuration
podSpec, objectMeta, err = ApplyFlytePodConfiguration(ctx, tCtx, podSpec, objectMeta, primaryContainerName)
if err != nil {
return nil, nil, "", err
}
podSpec = AddTolerationsForExtendedResources(podSpec)
return podSpec, objectMeta, primaryContainerName, nil
}
func GetContainer(podSpec *v1.PodSpec, name string) (*v1.Container, error) {
for _, container := range podSpec.Containers {
if container.Name == name {
return &container, nil
}
}
return nil, pluginserrors.Errorf(pluginserrors.BadTaskSpecification, "invalid TaskSpecification, container [%s] not defined", name)
}
// getBasePodTemplate attempts to retrieve the PodTemplate to use as the base for k8s Pod configuration. This value can
// come from one of the following:
// (1) PodTemplate name in the TaskMetadata: This name is then looked up in the PodTemplateStore.
// (2) Default PodTemplate name from configuration: This name is then looked up in the PodTemplateStore.
func getBasePodTemplate(ctx context.Context, tCtx pluginsCore.TaskExecutionContext, podTemplateStore PodTemplateStore) (*v1.PodTemplate, error) {
taskTemplate, err := tCtx.TaskReader().Read(ctx)
if err != nil {
return nil, pluginserrors.Errorf(pluginserrors.BadTaskSpecification, "TaskSpecification cannot be read, Err: [%v]", err.Error())
}
var podTemplate *v1.PodTemplate
if taskTemplate.Metadata != nil && len(taskTemplate.Metadata.PodTemplateName) > 0 {
// retrieve PodTemplate by name from PodTemplateStore
podTemplate = podTemplateStore.LoadOrDefault(tCtx.TaskExecutionMetadata().GetNamespace(), taskTemplate.Metadata.PodTemplateName)
if podTemplate == nil {
return nil, pluginserrors.Errorf(pluginserrors.BadTaskSpecification, "PodTemplate '%s' does not exist", taskTemplate.Metadata.PodTemplateName)
}
} else {
// check for default PodTemplate
podTemplate = podTemplateStore.LoadOrDefault(tCtx.TaskExecutionMetadata().GetNamespace(), config.GetK8sPluginConfig().DefaultPodTemplateName)
}
return podTemplate, nil
}
// MergeWithBasePodTemplate attempts to merge the provided PodSpec and ObjectMeta with the configuration PodTemplate for
// this task.
func MergeWithBasePodTemplate(ctx context.Context, tCtx pluginsCore.TaskExecutionContext,
podSpec *v1.PodSpec, objectMeta *metav1.ObjectMeta, primaryContainerName, primaryInitContainerName string) (*v1.PodSpec, *metav1.ObjectMeta, error) {
// attempt to retrieve base PodTemplate
podTemplate, err := getBasePodTemplate(ctx, tCtx, DefaultPodTemplateStore)
if err != nil {
return nil, nil, err
} else if podTemplate == nil {
// if no PodTemplate to merge as base -> return
return podSpec, objectMeta, nil
}
// merge podTemplate onto podSpec
templateSpec := &podTemplate.Template.Spec
mergedPodSpec, err := MergeBasePodSpecOntoTemplate(templateSpec, podSpec, primaryContainerName, primaryInitContainerName)
if err != nil {
return nil, nil, err
}
// merge PodTemplate PodSpec with podSpec
var mergedObjectMeta = podTemplate.Template.ObjectMeta.DeepCopy()
if err := mergo.Merge(mergedObjectMeta, objectMeta, mergo.WithOverride, mergo.WithAppendSlice); err != nil {
return nil, nil, err
}
return mergedPodSpec, mergedObjectMeta, nil
}
// MergeBasePodSpecOntoTemplate merges a base pod spec onto a template pod spec. The template pod spec has some
// magic values that allow users to specify templates that target all containers and primary containers. Aside from
// magic values this method will merge containers that have matching names.
func MergeBasePodSpecOntoTemplate(templatePodSpec *v1.PodSpec, basePodSpec *v1.PodSpec, primaryContainerName string, primaryInitContainerName string) (*v1.PodSpec, error) {
if templatePodSpec == nil || basePodSpec == nil {
return nil, errors.New("neither the templatePodSpec or the basePodSpec can be nil")
}
// extract primaryContainerTemplate. The base should always contain the primary container.
var defaultContainerTemplate, primaryContainerTemplate *v1.Container
// extract default container template
for i := 0; i < len(templatePodSpec.Containers); i++ {
switch templatePodSpec.Containers[i].Name {
case defaultContainerTemplateName:
defaultContainerTemplate = &templatePodSpec.Containers[i]
case primaryContainerTemplateName:
primaryContainerTemplate = &templatePodSpec.Containers[i]
}
}
// extract primaryInitContainerTemplate. The base should always contain the primary container.
var defaultInitContainerTemplate, primaryInitContainerTemplate *v1.Container
// extract defaultInitContainerTemplate
for i := 0; i < len(templatePodSpec.InitContainers); i++ {
switch templatePodSpec.InitContainers[i].Name {
case defaultInitContainerTemplateName:
defaultInitContainerTemplate = &templatePodSpec.InitContainers[i]
case primaryInitContainerTemplateName:
primaryInitContainerTemplate = &templatePodSpec.InitContainers[i]
}
}
// Merge base into template
mergedPodSpec := templatePodSpec.DeepCopy()
if err := mergo.Merge(mergedPodSpec, basePodSpec, mergo.WithOverride, mergo.WithAppendSlice); err != nil {
return nil, err
}
// merge PodTemplate containers
var mergedContainers []v1.Container
for _, container := range basePodSpec.Containers {
// if applicable start with defaultContainerTemplate
var mergedContainer *v1.Container
if defaultContainerTemplate != nil {
mergedContainer = defaultContainerTemplate.DeepCopy()
}
// If this is a primary container handle the template
if container.Name == primaryContainerName && primaryContainerTemplate != nil {
if mergedContainer == nil {
mergedContainer = primaryContainerTemplate.DeepCopy()
} else {
err := mergo.Merge(mergedContainer, primaryContainerTemplate, mergo.WithOverride, mergo.WithAppendSlice)
if err != nil {
return nil, err
}
}