-
Notifications
You must be signed in to change notification settings - Fork 251
Expand file tree
/
Copy pathresource_reservation.go
More file actions
686 lines (611 loc) · 20.6 KB
/
Copy pathresource_reservation.go
File metadata and controls
686 lines (611 loc) · 20.6 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
// Copyright 2025 NVIDIA CORPORATION
// SPDX-License-Identifier: Apache-2.0
package resourcereservation
import (
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"maps"
"strings"
"time"
"golang.org/x/exp/slices"
v1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/watch"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/log"
karpenterv1 "sigs.k8s.io/karpenter/pkg/apis/v1"
schedulingv1alpha2 "github.com/kai-scheduler/KAI-scheduler/pkg/apis/scheduling/v1alpha2"
"github.com/kai-scheduler/KAI-scheduler/pkg/binder/binding/resourcereservation/group_mutex"
"github.com/kai-scheduler/KAI-scheduler/pkg/common/constants"
"github.com/kai-scheduler/KAI-scheduler/pkg/common/resources"
)
type Interface interface {
Sync(ctx context.Context) error
SyncForNode(ctx context.Context, nodeName string) error
SyncForGpuGroup(ctx context.Context, gpuGroup string) error
ReserveGpuDevice(ctx context.Context, pod *v1.Pod, nodeName string, gpuGroup string) (string, error)
RemovePodGpuGroupsConnection(ctx context.Context, pod *v1.Pod) error
}
const (
resourceReservation = "resource-reservation"
gpuReservationPodPrefix = "gpu-reservation"
gpuIndexAnnotationName = "run.ai/reserve_for_gpu_index"
numberOfGPUsToReserve = 1
unknownGpuIndicator = "-1"
)
type service struct {
fakeGPuNodes bool
kubeClient client.WithWatch
reservationPodImage string
allocationTimeout time.Duration
gpuGroupMutex *group_mutex.GroupMutex
namespace string
serviceAccountName string
appLabelValue string
scalingPodNamespace string
runtimeClassName string
podResources *v1.ResourceRequirements
reservationPodSecurityContext *v1.PodSecurityContext
reservationContainerSecurityContext *v1.SecurityContext
}
func NewService(
fakeGPuNodes bool,
kubeClient client.WithWatch,
reservationPodImage string,
allocationTimeout time.Duration,
namespace string,
serviceAccountName string,
appLabelValue string,
scalingPodNamespace string,
runtimeClassName string,
podResources *v1.ResourceRequirements,
reservationPodSecurityContext *v1.PodSecurityContext,
reservationContainerSecurityContext *v1.SecurityContext,
) *service {
return &service{
fakeGPuNodes: fakeGPuNodes,
kubeClient: kubeClient,
reservationPodImage: reservationPodImage,
allocationTimeout: allocationTimeout,
gpuGroupMutex: group_mutex.NewGroupMutex(),
namespace: namespace,
serviceAccountName: serviceAccountName,
appLabelValue: appLabelValue,
scalingPodNamespace: scalingPodNamespace,
runtimeClassName: runtimeClassName,
podResources: podResources,
reservationPodSecurityContext: reservationPodSecurityContext,
reservationContainerSecurityContext: reservationContainerSecurityContext,
}
}
func (rsc *service) Sync(ctx context.Context) error {
podsList := &v1.PodList{}
err := rsc.kubeClient.List(ctx, podsList,
client.HasLabels{constants.GPUGroup},
)
if err != nil {
return err
}
return rsc.SyncForPodsList(ctx, podsList)
}
func (rsc *service) SyncForNode(ctx context.Context, nodeName string) error {
podsList := &v1.PodList{}
err := rsc.kubeClient.List(ctx, podsList,
client.HasLabels{constants.GPUGroup},
client.MatchingFields{"spec.nodeName": nodeName},
)
if err != nil {
return err
}
return rsc.SyncForPodsList(ctx, podsList)
}
func (rsc *service) SyncForPodsList(ctx context.Context, podsList *v1.PodList) error {
gpuGroupsMap := map[string]bool{}
for _, pod := range podsList.Items {
gpuGroups := resources.GetGpuGroups(&pod)
for _, gpuGroup := range gpuGroups {
gpuGroupsMap[gpuGroup] = true
}
}
for gpuGroup := range gpuGroupsMap {
err := rsc.SyncForGpuGroup(ctx, gpuGroup)
if err != nil {
return err
}
}
return nil
}
func (rsc *service) SyncForGpuGroup(ctx context.Context, gpuGroup string) error {
rsc.gpuGroupMutex.LockMutexForGroup(gpuGroup)
defer rsc.gpuGroupMutex.ReleaseMutex(gpuGroup)
return rsc.syncForGpuGroupWithLock(ctx, gpuGroup)
}
func (rsc *service) syncForGpuGroupWithLock(ctx context.Context, gpuGroup string) error {
podsList := &v1.PodList{}
err := rsc.kubeClient.List(ctx, podsList,
client.MatchingLabels{constants.GPUGroup: gpuGroup},
)
if err != nil {
return err
}
multiFractionsPodsList := &v1.PodList{}
multiGroupKey, multiGroupValue := resources.GetMultiFractionGpuGroupLabel(gpuGroup)
err = rsc.kubeClient.List(ctx, multiFractionsPodsList,
client.MatchingLabels{multiGroupKey: multiGroupValue},
)
if err != nil {
return err
}
pods := []*v1.Pod{}
for index := range len(podsList.Items) {
pods = append(pods, &podsList.Items[index])
}
for index := range len(multiFractionsPodsList.Items) {
pods = append(pods, &multiFractionsPodsList.Items[index])
}
return rsc.syncForPods(ctx, pods, gpuGroup)
}
func (rsc *service) syncForPods(ctx context.Context, pods []*v1.Pod, gpuGroupToSync string) error {
logger := log.FromContext(ctx)
reservationPods := map[string]*v1.Pod{}
fractionPods := map[string][]*v1.Pod{}
for _, pod := range pods {
if pod.Namespace == rsc.namespace {
reservationPods[gpuGroupToSync] = pod
continue
}
if slices.Contains(
[]v1.PodPhase{v1.PodRunning, v1.PodPending},
pod.Status.Phase,
) {
fractionPods[gpuGroupToSync] = append(fractionPods[gpuGroupToSync], pod)
}
}
for gpuGroup, pods := range fractionPods {
if _, found := reservationPods[gpuGroup]; !found {
err := rsc.deleteNonReservedPods(ctx, gpuGroup, pods)
if err != nil {
return err
}
}
}
for gpuGroup, reservationPod := range reservationPods {
if _, found := fractionPods[gpuGroup]; !found {
hasActive, err := rsc.hasActiveBindRequestsForGpuGroup(ctx, gpuGroup)
if err != nil {
logger.Error(err, "Failed to check active BindRequests for gpu group",
"gpuGroup", gpuGroup)
return err
}
if hasActive {
logger.Info("Skipping reservation pod deletion, active BindRequests exist",
"gpuGroup", gpuGroup)
continue
}
logger.Info("Did not find fraction pod for gpu group, deleting reservation pod",
"gpuGroup", gpuGroup)
err = rsc.deleteReservationPod(ctx, reservationPod)
if err != nil {
return err
}
}
}
return nil
}
// hasActiveBindRequestsForGpuGroup checks if BindRequests still protect the GPU group.
// A succeeded BindRequest also protects the reservation while its pod is still alive:
// the pod label can lag behind the BindRequest status in the controller cache.
func (rsc *service) hasActiveBindRequestsForGpuGroup(ctx context.Context, gpuGroup string) (bool, error) {
bindRequestList := &schedulingv1alpha2.BindRequestList{}
if err := rsc.kubeClient.List(ctx, bindRequestList); err != nil {
return false, fmt.Errorf("failed to list BindRequests: %w", err)
}
for _, br := range bindRequestList.Items {
if !slices.Contains(br.Spec.SelectedGPUGroups, gpuGroup) {
continue
}
if br.Status.Phase == schedulingv1alpha2.BindRequestPhaseFailed {
continue
}
if br.Status.Phase == schedulingv1alpha2.BindRequestPhaseSucceeded {
hasLivePod, err := rsc.hasLivePodForBindRequest(ctx, &br)
if err != nil {
return false, err
}
if hasLivePod {
return true, nil
}
continue
}
return true, nil
}
return false, nil
}
func (rsc *service) hasLivePodForBindRequest(ctx context.Context, bindRequest *schedulingv1alpha2.BindRequest) (bool, error) {
pod := &v1.Pod{}
err := rsc.kubeClient.Get(ctx, client.ObjectKey{
Namespace: bindRequest.Namespace,
Name: bindRequest.Spec.PodName,
}, pod)
if apierrors.IsNotFound(err) {
return false, nil
}
if err != nil {
return false, fmt.Errorf("failed to get pod for BindRequest <%s/%s>: %w",
bindRequest.Namespace, bindRequest.Name, err)
}
if slices.Contains([]v1.PodPhase{v1.PodSucceeded, v1.PodFailed}, pod.Status.Phase) {
return false, nil
}
for _, gpuGroup := range bindRequest.Spec.SelectedGPUGroups {
if slices.Contains(resources.GetGpuGroups(pod), gpuGroup) {
return true, nil
}
}
return true, nil
}
func (rsc *service) ReserveGpuDevice(ctx context.Context, pod *v1.Pod, nodeName string, gpuGroup string) (string, error) {
logger := log.FromContext(ctx)
rsc.gpuGroupMutex.LockMutexForGroup(gpuGroup)
defer rsc.gpuGroupMutex.ReleaseMutex(gpuGroup)
gpuIndex, err := rsc.acquireGPUIndexByGroup(ctx, pod, nodeName, gpuGroup)
if err != nil {
return unknownGpuIndicator, err
}
err = rsc.updatePodGPUGroup(ctx, pod, nodeName, gpuGroup)
if err != nil {
logger.Error(err, "Failed to update GPU group annotation on pod",
"namespace", pod.Namespace, "name", pod.Name, "node", nodeName)
syncErr := rsc.syncForGpuGroupWithLock(ctx, gpuGroup)
if syncErr != nil {
logger.Error(err, "Failed to sync reservation for gpu group", "gpuGroup", gpuGroup)
}
return unknownGpuIndicator, err
}
return gpuIndex, nil
}
func (rsc *service) updatePodGPUGroup(
ctx context.Context, pod *v1.Pod, nodeName string, gpuGroup string) error {
logger := log.FromContext(ctx)
logger.Info("Updating GPU group annotation for pod",
"namespace", pod.Namespace, "name", pod.Name, "node", nodeName,
"gpu-group", gpuGroup)
originalPod := pod.DeepCopy()
if pod.Labels == nil {
pod.Labels = map[string]string{}
}
isMultiFraction, err := resources.IsMultiFraction(pod)
if err != nil {
return fmt.Errorf(
"failed to determine if pod <%s/%s> is a multi fractional pod while setting gpu group label. %w",
pod.Namespace, pod.Name, err)
}
if isMultiFraction {
labelKey, labelValue := resources.GetMultiFractionGpuGroupLabel(gpuGroup)
pod.Labels[labelKey] = labelValue
} else {
pod.Labels[constants.GPUGroup] = gpuGroup
}
err = rsc.kubeClient.Patch(ctx, pod, client.MergeFrom(originalPod))
if err != nil {
return fmt.Errorf("failed to patch pod <%s/%s> with GPU group label: %v", pod.Namespace, pod.Name, err)
}
return nil
}
func (rsc *service) RemovePodGpuGroupsConnection(ctx context.Context, pod *v1.Pod) error {
var patch []map[string]string
for labelKey := range pod.Labels {
if labelKey == constants.GPUGroup || strings.HasPrefix(labelKey, constants.MultiGpuGroupLabelPrefix) {
patch = append(patch, map[string]string{
"op": "remove",
"path": fmt.Sprintf("/metadata/labels/%s", escapeJSONPointer(labelKey)),
})
}
}
patchBytes, err := json.Marshal(patch)
if err != nil {
return fmt.Errorf("failed to generate a patch for pod gpu-group removal. %w", err)
}
if err := rsc.kubeClient.Patch(ctx, pod, client.RawPatch(types.JSONPatchType, patchBytes)); err != nil {
return err
}
return nil
}
// escapeJSONPointer escapes a string for use in a JSON Pointer path (RFC 6901).
// ~ must be escaped as ~0, and / must be escaped as ~1.
func escapeJSONPointer(s string) string {
s = strings.ReplaceAll(s, "~", "~0")
s = strings.ReplaceAll(s, "/", "~1")
return s
}
func (rsc *service) acquireGPUIndexByGroup(
ctx context.Context, sourcePod *v1.Pod, nodeName, gpuGroup string,
) (string, error) {
gpuIndex, err := rsc.findGPUIndexByGroup(gpuGroup)
if err != nil {
return "", err
}
if gpuIndex != "" {
return gpuIndex, err
}
return rsc.createGPUReservationPodAndGetIndex(ctx, sourcePod, nodeName, gpuGroup)
}
func (rsc *service) findGPUIndexByGroup(gpuGroup string) (
gpuIndex string, err error,
) {
pods := &v1.PodList{}
err = rsc.kubeClient.List(context.Background(), pods,
client.InNamespace(rsc.namespace),
client.MatchingLabels{constants.GPUGroup: gpuGroup})
if err != nil {
return "", err
}
if len(pods.Items) == 0 {
return "", nil
}
gpuIndex, found := pods.Items[0].Annotations[gpuIndexAnnotationName]
if !found {
return "", fmt.Errorf("failed to find annotation on reservation pod %s", pods.Items[0].Name)
}
return gpuIndex, nil
}
func (rsc *service) createGPUReservationPodAndGetIndex(
ctx context.Context, sourcePod *v1.Pod, nodeName, gpuGroup string,
) (
gpuIndex string, err error) {
logger := log.FromContext(ctx)
pod, err := rsc.createGPUReservationPod(ctx, sourcePod, nodeName, gpuGroup)
if err != nil {
return unknownGpuIndicator, err
}
gpuIndex = rsc.waitForGPUReservationPodAllocation(ctx, nodeName, pod.Name)
if gpuIndex == unknownGpuIndicator {
deleteErr := rsc.deleteReservationPod(ctx, pod)
if deleteErr != nil {
logger.Error(deleteErr, "failed to delete reservation pod", "name", pod.Name)
}
return unknownGpuIndicator, fmt.Errorf(
"failed waiting for GPU reservation pod to allocate: %v/%v", rsc.namespace, pod.Name)
}
return gpuIndex, err
}
func (rsc *service) deleteNonReservedPods(ctx context.Context, gpuGroup string, pods []*v1.Pod) error {
logger := log.FromContext(ctx)
for _, pod := range pods {
if pod.Status.Phase != v1.PodRunning {
continue
}
logger.Info("Warning: Found pod without reservation, deleting", "name", pod.Name,
"namespace", pod.Namespace, "gpuGroup", gpuGroup)
err := rsc.kubeClient.Delete(ctx, pod)
if err != nil {
logger.Error(err, "Failed to delete non-reserved pods", "name", pod.Name,
"namespace", pod.Namespace)
return err
}
}
return nil
}
func (rsc *service) deleteReservationPod(ctx context.Context, pod *v1.Pod) error {
logger := log.FromContext(ctx)
logger.Info("Deleting reservation pod", "name", pod.Name)
err := rsc.kubeClient.Delete(ctx,
pod,
client.GracePeriodSeconds(0),
)
if err != nil {
if !apierrors.IsNotFound(err) {
return fmt.Errorf("failed to delete reservation pod: %w", err)
}
logger.Info("Reservation pod not found, skipping deletion", "name", pod.Name)
}
return nil
}
func (rsc *service) createGPUReservationPod(
ctx context.Context, sourcePod *v1.Pod, nodeName, gpuGroup string,
) (*v1.Pod, error) {
logger := log.FromContext(ctx)
if rsc.isScalingUp(ctx) {
return nil, fmt.Errorf("cluster is scaling up, could not create reservation pod")
}
podName := reservationPodName(nodeName, gpuGroup)
// Build resource requirements starting with GPU resources
resources := v1.ResourceRequirements{
Limits: v1.ResourceList{
constants.NvidiaGpuResource: *resource.NewQuantity(numberOfGPUsToReserve, resource.DecimalSI),
},
Requests: v1.ResourceList{
constants.NvidiaGpuResource: *resource.NewQuantity(numberOfGPUsToReserve, resource.DecimalSI),
},
}
if rsc.podResources != nil {
if rsc.podResources.Limits != nil {
delete(rsc.podResources.Limits, constants.NvidiaGpuResource)
maps.Copy(resources.Limits, rsc.podResources.Limits)
}
if rsc.podResources.Requests != nil {
delete(rsc.podResources.Requests, constants.NvidiaGpuResource)
maps.Copy(resources.Requests, rsc.podResources.Requests)
}
}
pod, err := rsc.createResourceReservationPod(sourcePod, nodeName, gpuGroup, podName, resources)
if err != nil {
// The reservation pod name is deterministic per (node, gpu-group). AlreadyExists
// means another actor (a concurrent bind, a retry, or another binder replica)
// already created the reservation pod for this gpu-group, so reuse it rather than
// creating a duplicate on a different physical GPU.
if apierrors.IsAlreadyExists(err) {
logger.Info("GPU reservation pod already exists for gpu group, reusing",
"nodeName", nodeName, "namespace", rsc.namespace, "name", podName, "gpuGroup", gpuGroup)
return pod, nil
}
logger.Error(err, "Failed to create GPU reservation pod on node",
"nodeName", nodeName, "namespace", rsc.namespace, "name", podName)
return nil, err
}
logger.Info(
"Successfully created GPU resource reservation pod",
"nodeName", nodeName, "namespace", rsc.namespace, "name", podName)
return pod, nil
}
func (rsc *service) waitForGPUReservationPodAllocation(
ctx context.Context, nodeName, gpuReservationPodName string,
) string {
logger := log.FromContext(ctx)
pods := &v1.PodList{}
watcher, err := rsc.kubeClient.Watch(
ctx, pods,
client.InNamespace(rsc.namespace),
client.MatchingFields{"metadata.name": gpuReservationPodName},
)
if err != nil {
logger.Error(err, "Failed to watch for GPU reservation pod")
return unknownGpuIndicator
}
defer watcher.Stop()
timeout := time.After(rsc.allocationTimeout)
for {
select {
case <-ctx.Done():
logger.Error(ctx.Err(),
"Context done while waiting for GPU reservation pod to be allocated",
"nodeName", nodeName, "name", gpuReservationPodName)
return unknownGpuIndicator
case <-timeout:
logger.Error(fmt.Errorf("timeout"),
"Reached timeout while waiting for GPU reservation pod to be allocated",
"nodeName", nodeName, "name", gpuReservationPodName)
return unknownGpuIndicator
case event, ok := <-watcher.ResultChan():
if !ok {
logger.Error(nil,
"GPU reservation pod watch channel closed while waiting for allocation",
"nodeName", nodeName, "name", gpuReservationPodName)
return unknownGpuIndicator
}
if event.Type == watch.Error {
logger.Error(fmt.Errorf("watch error"),
"Error event received while waiting for GPU reservation pod allocation",
"nodeName", nodeName, "name", gpuReservationPodName, "event", fmt.Sprintf("%v", event.Object))
return unknownGpuIndicator
}
pod, ok := event.Object.(*v1.Pod)
if pod.Annotations != nil && pod.Annotations[gpuIndexAnnotationName] != "" {
return pod.Annotations[gpuIndexAnnotationName]
}
}
}
}
func (rsc *service) createResourceReservationPod(
sourcePod *v1.Pod, nodeName, gpuGroup, podName string, resources v1.ResourceRequirements,
) (*v1.Pod, error) {
var tolerations []v1.Toleration
if sourcePod != nil {
sourcePodSpec := sourcePod.Spec.DeepCopy()
tolerations = sourcePodSpec.Tolerations
}
podSpec := &v1.Pod{
ObjectMeta: metav1.ObjectMeta{
Name: podName,
Namespace: rsc.namespace,
Labels: map[string]string{
constants.AppLabelName: rsc.appLabelValue,
constants.GPUGroup: gpuGroup,
},
Annotations: map[string]string{
karpenterv1.DoNotDisruptAnnotationKey: "true",
},
},
Spec: v1.PodSpec{
NodeName: nodeName,
Tolerations: tolerations,
RuntimeClassName: func() *string {
if len(rsc.runtimeClassName) == 0 {
return nil
}
return &rsc.runtimeClassName
}(),
SecurityContext: rsc.reservationPodSecurityContext,
ServiceAccountName: rsc.serviceAccountName,
Containers: []v1.Container{
{
Name: resourceReservation,
Image: rsc.reservationPodImage,
ImagePullPolicy: v1.PullIfNotPresent,
Resources: resources,
SecurityContext: rsc.reservationContainerSecurityContext,
Env: []v1.EnvVar{
{
Name: "POD_NAME",
ValueFrom: &v1.EnvVarSource{
FieldRef: &v1.ObjectFieldSelector{
FieldPath: "metadata.name",
},
},
},
{
Name: "POD_NAMESPACE",
ValueFrom: &v1.EnvVarSource{
FieldRef: &v1.ObjectFieldSelector{
FieldPath: "metadata.namespace",
},
},
},
},
},
},
},
Status: v1.PodStatus{
Conditions: []v1.PodCondition{
{
Type: v1.PodScheduled,
Status: v1.ConditionTrue,
},
},
},
}
if rsc.fakeGPuNodes {
podSpec.Spec.Containers[0].Image = "ubuntu"
podSpec.Spec.Containers[0].Args = []string{"sleep", "infinity"}
}
return podSpec, rsc.kubeClient.Create(context.Background(), podSpec)
}
func (rsc *service) isScalingUp(ctx context.Context) bool {
logger := log.FromContext(ctx)
pods := &v1.PodList{}
err := rsc.kubeClient.List(ctx, pods,
client.InNamespace(rsc.scalingPodNamespace),
)
if err != nil {
logger.Error(err, "Could not list scaling pods")
return false
}
for _, pod := range pods.Items {
podStatus := pod.Status
for _, condition := range podStatus.Conditions {
if condition.Type == v1.PodScheduled && condition.Status != v1.ConditionTrue {
logger.Error(fmt.Errorf("not found"),
"Unscheduled scaling pod was found", "name", pod.Name)
return true
}
}
}
return false
}
func IsGPUReservationPod(pod *v1.Pod) bool {
return strings.HasPrefix(pod.Name, gpuReservationPodPrefix)
}
// reservationPodName derives a deterministic reservation pod name from the node and
// gpu-group, so concurrent or retried creates for the same gpu-group collide on a
// single API-server object (AlreadyExists) instead of producing duplicate reservation
// pods on different physical GPUs.
func reservationPodName(nodeName, gpuGroup string) string {
hash := sha256.Sum256([]byte(nodeName + "/" + gpuGroup))
return fmt.Sprintf("%s-%s", gpuReservationPodPrefix, hex.EncodeToString(hash[:8]))
}