Repository navigation
Expand file tree
/
Copy pathinstance.go
More file actions
1511 lines (1403 loc) · 58.9 KB
/
Copy pathinstance.go
File metadata and controls
1511 lines (1403 loc) · 58.9 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 worker
import (
"context"
"fmt"
"maps"
"slices"
"strings"
"time"
core "k8s.io/api/core/v1"
node "k8s.io/api/node/v1"
kerrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/resource"
meta "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/intstr"
utilversion "k8s.io/apimachinery/pkg/util/version"
"k8s.io/utils/ptr"
ctrl "sigs.k8s.io/controller-runtime"
ctrlbuilder "sigs.k8s.io/controller-runtime/pkg/builder"
ctrlcli "sigs.k8s.io/controller-runtime/pkg/client"
ctrlevent "sigs.k8s.io/controller-runtime/pkg/event"
ctrllog "sigs.k8s.io/controller-runtime/pkg/log"
ctrlpredicate "sigs.k8s.io/controller-runtime/pkg/predicate"
ctrlreconcile "sigs.k8s.io/controller-runtime/pkg/reconcile"
kueue "sigs.k8s.io/kueue/apis/kueue/v1beta2"
kueuectrlconst "sigs.k8s.io/kueue/pkg/controller/constants"
worker "gpustack.ai/gpustack/api/worker/v1"
workercore "gpustack.ai/gpustack/api/worker/v1alpha1"
"gpustack.ai/gpustack/pkg/controller"
"gpustack.ai/gpustack/pkg/deviceplugin"
"gpustack.ai/gpustack/pkg/kubediscovery"
"gpustack.ai/gpustack/pkg/kubemeta"
"gpustack.ai/gpustack/pkg/nodefeature"
"gpustack.ai/gpustack/pkg/systemmeta"
"gpustack.ai/gpustack/pkg/utils/ctrlclix"
"gpustack.ai/gpustack/pkg/utils/ctrlhandlerx"
"gpustack.ai/gpustack/pkg/utils/quantityx"
"gpustack.ai/gpustack/pkg/utils/slicex"
"gpustack.ai/gpustack/pkg/utils/strconvx"
"gpustack.ai/gpustack/pkg/worker/apistatus"
"gpustack.ai/gpustack/pkg/worker/kuberequest"
"gpustack.ai/gpustack/pkg/worker/settings"
)
// InstanceReconciler reconciles v1alpha1.Instance objects to finish the following tasks:
// - Create/Update/Delete a Kubernetes Pod as the backing resource of the Instance based on the Instance spec.
// - Create a Kubernetes Service to expose the ports of the backing Pod if specified in the Instance spec. The Service
// belongs to the Instance rather than to the Pod, so it survives a stop and keeps its allocated node ports.
// - Update the Instance status based on the backing Pod status for better visibility and stability.
type InstanceReconciler struct {
Client ctrlcli.Client
APIReader ctrlcli.Reader
}
var _ ctrlreconcile.Reconciler = (*InstanceReconciler)(nil)
const (
// InstancePhaseStarting is the Instance status phase reported when the
// backing Pod is being created or updated to match the Instance spec.
InstancePhaseStarting = "Starting"
// InstancePhaseStopping is the Instance status phase reported when the
// backing Pod is being deleted to stop the Instance.
InstancePhaseStopping = "Stopping"
// InstancePhaseStopped is the Instance status phase reported when the
// backing Pod is deleted and the Instance is stopped.
InstancePhaseStopped = "Stopped"
// InstancePhaseReady is the Instance status phase reported when the
// backing Pod is running and ready.
InstancePhaseReady = "Ready"
// InstancePhaseDeleting is the Instance status phase reported when the
// Instance is marked as deleted and the backing Pod is being deleted.
InstancePhaseDeleting = "Deleting"
)
const (
// InstanceTypePhaseInactive is the InstanceType status phase reported when its backing Kueue
// ClusterQueue is held (Hold, an admin Inactive) or already fully drained (HoldAndDrain with no
// reservations left), mirroring the "Inactive" summary from apistatus.GetSummaryOfClusterQueue.
InstanceTypePhaseInactive = "Inactive"
// InstanceTypePhaseDraining is the InstanceType status phase reported while its backing Kueue
// ClusterQueue is actively evicting admitted workloads (HoldAndDrain with reservations still
// outstanding), mirroring the "Draining" summary from apistatus.GetSummaryOfClusterQueue.
InstanceTypePhaseDraining = "Draining"
)
const (
// _PodReasonUnexpectedAdmissionError is the Pod status reason kubelet sets when it rejects
// a Pod at admission — for an accelerator Pod, the device-plugin's Allocate returning an
// error (e.g. FailedPrecondition on a cross-mode card conflict).
_PodReasonUnexpectedAdmissionError = "UnexpectedAdmissionError"
// _InstanceAdmissionFailureRetryWindow bounds how long after Instance creation a backing
// Pod rejected at admission is still rebuilt. The gap between the Instance's and the
// backing Pod's creation timestamps starts near zero and grows monotonically with every
// rebuild, so it doubles as a stateless backoff and a hard retry deadline — no rebuild
// bookkeeping has to be persisted on the Instance.
_InstanceAdmissionFailureRetryWindow = 5 * time.Minute
)
func (r *InstanceReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
logger := ctrllog.FromContext(ctx)
// Fetch.
inst := new(workercore.Instance)
err := r.Client.Get(ctx, req.NamespacedName, inst)
if err != nil {
if !kerrors.IsNotFound(err) {
logger.Error(err, "fetch instance")
return ctrl.Result{}, err
}
return ctrl.Result{}, nil
}
// Clean up if the Instance is marked as deleted.
if inst.DeletionTimestamp != nil {
if systemmeta.Unlock(inst) {
logger.V(3).Info("skip deleted instance")
return ctrl.Result{}, nil
}
// Ensure the backing Pod and Service are deleted before unlocking and let other controllers or users to clean up the Instance.
pod := new(core.Pod)
err = r.Client.Get(ctx, ctrlcli.ObjectKeyFromObject(inst), pod,
ctrlclix.WithoutQuorum)
if err != nil {
if !kerrors.IsNotFound(err) {
logger.Error(err, "fetch pod")
return ctrl.Result{}, err
}
pod = nil
}
// The Service outlives a stopped Instance on purpose, so its lifetime ends here instead:
// leaving it behind would hold NodePort allocations for an Instance that no longer exists.
svc := new(core.Service)
err = r.Client.Get(ctx, ctrlcli.ObjectKeyFromObject(inst), svc,
ctrlclix.WithoutQuorum)
if err != nil {
if !kerrors.IsNotFound(err) {
logger.Error(err, "fetch service")
return ctrl.Result{}, err
}
svc = nil
}
// A Service that merely shares the name belongs to something else, so it is left alone and
// treated as absent: this Instance never owned it, and it must not hold the finalizer.
if svc != nil && !kubemeta.IsControlledBy(svc, inst) {
logger.V(2).Info("service of the same name belongs to something else; leaving it alone",
"service", ctrlcli.ObjectKeyFromObject(svc))
svc = nil
}
// Same rule for the Pod: one that merely shares the name belongs to something else, and
// deleting it would terminate a stranger's workload.
if pod != nil && !kubemeta.IsControlledBy(pod, inst) {
logger.V(2).Info("pod of the same name belongs to something else; leaving it alone",
"pod", ctrlcli.ObjectKeyFromObject(pod))
pod = nil
}
if pod == nil && svc == nil {
err = r.Client.Update(ctx, inst)
if err != nil {
logger.Error(err, "unlock instance")
}
return ctrl.Result{}, err
}
if inst.Status.Phase != InstancePhaseDeleting {
logger.Info("instance deleting")
inst.Status.Phase = InstancePhaseDeleting
err = r.Client.Status().Update(ctx, inst)
if err != nil {
// The predicate drops status-only and metadata-only updates, so the change behind a
// conflict may deliver no event: requeue rather than wait for one. The same holds for
// every write to the Instance below.
return objectWriteResult(logger, err, "update instance status to deleting", _requeueAfterConflict)
}
}
if pod != nil && pod.DeletionTimestamp == nil {
err = r.Client.Delete(ctx, pod,
ctrlclix.Terminated)
if err != nil {
if !kerrors.IsNotFound(err) {
logger.Error(err, "delete pod")
return ctrl.Result{}, err
}
}
}
if svc != nil && svc.DeletionTimestamp == nil {
err = r.Client.Delete(ctx, svc,
ctrlclix.Terminated)
if err != nil {
if !kerrors.IsNotFound(err) {
logger.Error(err, "delete service")
return ctrl.Result{}, err
}
}
}
logger.V(3).Info("pod and service deletion in progress; requeue in 2s")
return ctrl.Result{RequeueAfter: 2 * time.Second}, nil
}
// Lock.
if !systemmeta.Lock(inst) {
err = r.Client.Update(ctx, inst)
if err != nil {
logger.Error(err, "lock instance")
return ctrl.Result{}, err
}
}
// Fetch the backing Pod.
pod := new(core.Pod)
err = r.Client.Get(ctx, req.NamespacedName, pod,
ctrlclix.WithoutQuorum)
if err != nil {
if !kerrors.IsNotFound(err) {
logger.Error(err, "fetch pod")
return ctrl.Result{}, err
}
pod = nil
}
// A same-named Pod this Instance does not own belongs to something else: treat it as absent —
// this Instance never owned it, so it must not be patched, stopped, deleted, or status-synced
// as the backing Pod. Same rule as the Service in the deletion path above.
if pod != nil && !kubemeta.IsControlledBy(pod, inst) {
logger.V(2).Info("pod of the same name belongs to something else; leaving it alone",
"pod", ctrlcli.ObjectKeyFromObject(pod))
pod = nil
}
// Pods that predate the resource-type label — rendered by an earlier operator before the
// namespace-isolation policy existed — carry nothing for that policy to select them by.
// Labels are mutable metadata, so patch the drifted one in place; no restart involved.
if pod != nil && pod.Labels[systemmeta.ResourceTypeLabel] != "instances" {
if pod.Labels == nil {
pod.Labels = map[string]string{}
}
pod.Labels[systemmeta.ResourceTypeLabel] = "instances"
if err = r.Client.Update(ctx, pod); err != nil {
logger.Error(err, "patch instance resource-type label")
return ctrl.Result{}, err
}
}
// If the Instance is marked as stopped,
// ensure the backing Pod is deleted and update the Instance status to "Stopped".
// The Service is left in place: it is what holds the NodePort numbers a user connects to, and
// releasing it here would make every stop/start cycle hand out different ones. It is deleted
// with the Instance, or on the next start if spec.ports was cleared while stopped.
if inst.Spec.Stop {
// Pod already deleted, mark the Instance as stopped.
if pod == nil {
if inst.Status.Phase == InstancePhaseStopped {
logger.V(3).Info("instance already stopped")
return ctrl.Result{}, nil
}
inst.Status = workercore.InstanceStatus{
Phase: InstancePhaseStopped,
}
err = r.Client.Status().Update(ctx, inst)
if err != nil {
return objectWriteResult(logger, err, "update instance status to stopped", _requeueAfterConflict)
}
logger.Info("instance stopped")
return ctrl.Result{}, nil
}
// If instance is not marked as stopping,
// mark it as stopping first to avoid racing with other controllers or users to update the instance status.
if inst.Status.Phase != InstancePhaseStopping {
inst.Status.Phase = InstancePhaseStopping
err = r.Client.Status().Update(ctx, inst)
if err != nil {
return objectWriteResult(logger, err, "update instance status to stopping", _requeueAfterConflict)
}
}
// Pod still exists, delete it.
if pod.DeletionTimestamp == nil {
err = r.Client.Delete(ctx, pod,
ctrlclix.Terminated)
if err != nil {
if !kerrors.IsNotFound(err) {
logger.Error(err, "delete pod")
return ctrl.Result{}, err
}
}
}
// Pod deletion in progress, requeue and wait for it to be deleted.
logger.V(2).Info("pod deletion in progress; requeue in 2s")
return ctrl.Result{RequeueAfter: 2 * time.Second}, nil
}
// Fetch the InstanceType that backs the Instance. It both sizes a new Pod and reports,
// via its phase, whether the type is still usable.
instType := new(worker.InstanceType)
err = r.Client.Get(ctx, ctrlcli.ObjectKey{Name: inst.Spec.Type}, instType,
ctrlclix.WithoutQuorum)
if err != nil {
if !kerrors.IsNotFound(err) {
logger.Error(err, "fetch instance type")
return ctrl.Result{}, err
}
// Maybe the InstanceType is not cached yet,
// try to fetch directly from API server to avoid the cache staleness.
err = r.APIReader.Get(ctx, ctrlcli.ObjectKey{Name: inst.Spec.Type}, instType,
ctrlclix.WithoutQuorum)
if err != nil && !kerrors.IsNotFound(err) {
logger.Error(err, "fetch instance type")
return ctrl.Result{}, err
}
}
instTypeGone := kerrors.IsNotFound(err)
// Read the backing ClusterQueue's StopPolicy — the only signal that distinguishes an admin Hold
// (block new admission, keep running Pods) from a HoldAndDrain drain or teardown (evict admitted
// workloads). Both collapse to InstanceType phase Inactive once no reservation remains, and a fast
// drain skips a durable Draining phase entirely, so the phase cannot be relied on to stop a drained
// Instance. The ClusterQueue is named after the InstanceType.
var draining bool
if !instTypeGone {
cq := new(kueue.ClusterQueue)
cqErr := r.Client.Get(ctx, ctrlcli.ObjectKey{Name: inst.Spec.Type}, cq)
if cqErr != nil && !kerrors.IsNotFound(cqErr) {
logger.Error(cqErr, "fetch backing cluster queue")
return ctrl.Result{}, cqErr
}
draining = cqErr == nil && ptr.Deref(cq.Spec.StopPolicy, kueue.None) == kueue.HoldAndDrain
}
// Stop the Instance once its InstanceType is gone, being deleted, or its backing queue is
// HoldAndDrain (a pool drain or a teardown that evicts admitted workloads), regardless of whether
// a Pod exists. An admin Hold keeps running Pods, so a Hold-Inactive type does not stop the
// Instance; a new Instance under it simply stays pending. Keying off the InstanceType's own
// deletion timestamp (not only the queue) stops the Instance the moment teardown begins, without
// waiting for the queue to drain the Pod. The InstanceType and ClusterQueue watches re-enqueue here
// on a phase transition, StopPolicy change, or deletion, so the stop stays level-based even when no
// Pod event fires.
if instTypeGone || instType.DeletionTimestamp != nil || draining {
// Persist the stop intent in the spec, so the Instance stays stopped after the signal it was
// taken on clears; the stop branch above then deletes the Pod and marks the Instance Stopped.
inst.Spec.Stop = true
err = r.Client.Update(ctx, inst)
if err != nil {
return objectWriteResult(logger, err, "stop instance with unschedulable instance type",
_requeueAfterConflict)
}
logger.Info("stop instance as its instance type is gone, deleting, or draining", "type", inst.Spec.Type)
return ctrl.Result{}, nil
}
// Rebuild a Pod kubelet rejected at admission — reason UnexpectedAdmissionError, which for
// an accelerator Pod is the device-plugin's Allocate failing (e.g. the cross-mode
// FailedPrecondition when kubelet's ListAndWatch snapshot raced a fresh reservation).
// Admission rejection happens before any container starts and leaves no allocation
// behind, so deleting and recreating the Pod is safe.
//
// The retry budget is stateless: the gap between the Instance's and the Pod's creation
// timestamps starts near zero and grows with every rebuild, so it doubles as the backoff
// (each attempt waits roughly the running gap) and the deadline — a gap beyond the window
// means the rejection is persistent, and the failed Pod stays as the visible error
// instead of hot-looping.
if pod != nil && pod.DeletionTimestamp == nil &&
pod.Status.Phase == core.PodFailed && pod.Status.Reason == _PodReasonUnexpectedAdmissionError {
gap := max(pod.CreationTimestamp.Sub(inst.CreationTimestamp.Time), 0)
if gap < _InstanceAdmissionFailureRetryWindow {
err = r.Client.Delete(ctx, pod,
ctrlclix.Terminated)
if err != nil && !kerrors.IsNotFound(err) {
logger.Error(err, "delete admission-rejected pod")
return ctrl.Result{}, err
}
backoff := max(gap, 2*time.Second)
logger.Info("rebuild admission-rejected pod",
"gap", gap, "backoff", backoff, "message", pod.Status.Message)
return ctrl.Result{RequeueAfter: backoff}, nil
}
logger.Info("admission-rejected pod past the retry window; leaving it as the visible error",
"gap", gap, "message", pod.Status.Message)
}
// Create the Pod if not exists.
if pod == nil {
// An accelerated type sizes its Pod (accelerator resource names, RuntimeClass, and the
// sliced-vs-whole-card shape) from Status.Detail. Creating a Pod before the reconciler has
// computed Detail would stamp a missing RuntimeClass and bogus resource names, so requeue
// until it is ready — the periodic requeue re-checks as the InstanceType status populates.
if instType.Spec.Acceleratable && !instType.Status.Detail.AcceleratorReady() {
logger.V(2).Info("instance type accelerator detail not ready; requeue in 2s")
return ctrl.Result{RequeueAfter: 2 * time.Second}, nil
}
// The queue-name label is READ from the type's published entrance rather than recomputed from
// its name, so a type that has not published one yet has no Pod built against it. A Pod
// carrying no queue-name label is not queued by Kueue at all -- the kubelet runs it directly,
// charging no quota and passing none of the gates the chain applies -- and one carrying a
// guessed name is routed at a LocalQueue that may not exist.
//
// WAITED FOR RATHER THAN FAILED, which is this path's own idiom and not the ModelDeployment
// one. That render returns an error because it has several ways to be unable to build a Pod;
// this one returns no error at all, and expresses "the type's status has not caught up" as the
// guard directly above does. The periodic requeue is also what stands in for a watch here:
// this controller watches ClusterQueue StopPolicy transitions, deliberately ignoring status
// churn, so nothing would wake it when the entrance is published.
if instType.Status.Entrance == "" {
logger.V(2).Info("instance type publishes no queue entrance yet; requeue in 2s")
return ctrl.Result{RequeueAfter: 2 * time.Second}, nil
}
// If the instance is marked as stopping/stopped/ready, mark it as starting first
// to avoid racing with other controllers or users to update the instance status.
if inst.Status.Phase == InstancePhaseStopping ||
inst.Status.Phase == InstancePhaseStopped ||
inst.Status.Phase == InstancePhaseReady {
inst.Status = workercore.InstanceStatus{
Phase: InstancePhaseStarting,
}
err = r.Client.Status().Update(ctx, inst)
if err != nil {
return objectWriteResult(logger, err, "update instance status to starting", _requeueAfterConflict)
}
logger.Info("instance starting")
}
// A model volume's artifact decides whether the Pod can be built at all, and for a claim
// where it may run; so does every persistent volume's claim. Waited for like the type's
// status above: the Pod is rendered once and never re-diffed, so building it early would
// fix the wait into it for good.
models, wait, err := r.resolveInstanceModelVolumes(ctx, inst)
if err != nil {
logger.Error(err, "resolve model volumes")
return ctrl.Result{}, err
}
var claimAffinities []*core.NodeSelector
if wait == "" {
claimAffinities, wait, err = r.resolveInstancePersistentVolumes(ctx, inst)
if err != nil {
logger.Error(err, "resolve persistent volumes")
return ctrl.Result{}, err
}
}
if wait != "" {
if inst.Status.Phase != InstancePhaseStarting || inst.Status.PhaseMessage != wait {
inst.Status = workercore.InstanceStatus{Phase: InstancePhaseStarting, PhaseMessage: wait}
if err = r.Client.Status().Update(ctx, inst); err != nil {
return ctrl.Result{}, ctrlcli.IgnoreNotFound(err)
}
}
logger.V(2).Info("volume not available; requeue in 10s", "reason", wait)
return ctrl.Result{RequeueAfter: 10 * time.Second}, nil
}
pod = r.convertPodFromInstance(ctx, inst, instType, models)
for _, required := range claimAffinities {
injectModelArtifactAffinity(pod, required)
}
err = r.Client.Create(ctx, pod)
if err != nil {
logger.Error(err, "create pod")
return ctrl.Result{}, err
}
} else if pod.DeletionTimestamp != nil {
logger.V(3).Info("previous pod deletion in progress; requeue in 2s")
return ctrl.Result{RequeueAfter: 2 * time.Second}, nil
}
// Fetch the backing Service.
svc := new(core.Service)
err = r.Client.Get(ctx, req.NamespacedName, svc,
ctrlclix.WithoutQuorum)
if err != nil {
if !kerrors.IsNotFound(err) {
logger.Error(err, "fetch service")
return ctrl.Result{}, err
}
svc = nil
}
// The Service is reconciled rather than recreated, because it survives a stop: reusing it is
// what keeps the NodePort numbers a user connects to across a stop and start.
//
// A portless NodePort Service is rejected by the API, which would fail every reconcile before
// the status is written, so an Instance that asks for no port also gives up the one it kept.
if len(inst.Spec.Ports) == 0 {
// Only a Service this Instance owns is this Instance's to delete. One that merely shares the
// name belongs to something else, and is left serving whatever already points at it.
if svc != nil && !kubemeta.IsControlledBy(svc, inst) {
logger.V(2).Info("service of the same name belongs to something else; leaving it alone",
"service", ctrlcli.ObjectKeyFromObject(svc))
svc = nil
}
if svc != nil {
if svc.DeletionTimestamp == nil {
err = r.Client.Delete(ctx, svc,
ctrlclix.Terminated)
if err != nil && !kerrors.IsNotFound(err) {
logger.Error(err, "delete service")
return ctrl.Result{}, err
}
}
logger.V(3).Info("service deletion in progress; requeue in 2s")
return ctrl.Result{RequeueAfter: 2 * time.Second}, nil
}
} else {
desired := r.convertServiceFromInstance(inst)
switch {
case svc == nil:
err = r.Client.Create(ctx, desired)
if err != nil {
logger.Error(err, "create service")
return ctrl.Result{}, err
}
svc = desired
case !kubemeta.IsControlledBy(svc, inst):
// Redirecting or deleting a Service this Instance does not own would take over whatever
// already points at it, and nothing in this operator's logs would name the victim. Report
// the collision and let a human resolve it, as a deployment does with a name clash.
//
// TESTED BEFORE THE DELETION BELOW, because a Service of someone else's that happens to be
// terminating is still not this Instance's to wait on: ordering the arms the other way
// requeues every 2s and the collision is never reported at all.
return ctrl.Result{}, fmt.Errorf("service %s/%s is not owned by this instance",
svc.Namespace, svc.Name)
case svc.DeletionTimestamp != nil:
logger.V(3).Info("previous service deletion in progress; requeue in 2s")
return ctrl.Result{RequeueAfter: 2 * time.Second}, nil
default:
if alignServiceToInstance(svc, desired) {
err = r.Client.Update(ctx, svc)
if err != nil {
logger.Error(err, "update service")
return ctrl.Result{}, err
}
}
}
}
instStatus := inst.Status.DeepCopy()
// Update the Phase in the Instance status.
instStatus.Phase, instStatus.PhaseMessage = apistatus.GetSummaryOfPod(&pod.Status)
if pod.Status.Phase == core.PodRunning {
// Surface the node ports once ready; cleared for a portless Instance (svc nil).
if svc == nil {
instStatus.Ports = nil
} else {
allReady := true
portsMap := make(map[string]int32)
for i := range svc.Spec.Ports {
if svc.Spec.Ports[i].NodePort == 0 {
allReady = false
break
}
portsMap[svc.Spec.Ports[i].Name] = svc.Spec.Ports[i].NodePort
}
if allReady {
instStatus.Ports = make([]workercore.InstanceServicePort, 0, len(inst.Spec.Ports))
for i := range inst.Spec.Ports {
portKey := getPortName(inst.Spec.Ports[i])
instStatus.Ports = append(instStatus.Ports, workercore.InstanceServicePort{
InstancePort: inst.Spec.Ports[i],
NodePort: portsMap[portKey],
})
}
} else {
logger.V(2).Info("instance ports not ready; requeue in 2s")
return ctrl.Result{RequeueAfter: 2 * time.Second}, nil
}
}
// Update the NodeName and HostIPs in the Instance status.
if instStatus.NodeName != pod.Spec.NodeName {
// Fetch the backing Node.
nd := new(core.Node)
err = r.Client.Get(ctx, ctrlcli.ObjectKey{Name: pod.Spec.NodeName}, nd,
ctrlclix.WithoutQuorum)
if err != nil {
logger.Error(err, "fetch node")
return ctrl.Result{}, err
}
instStatus.NodeName = nd.Name
for i := range nd.Status.Addresses {
if nd.Status.Addresses[i].Type == core.NodeExternalIP {
instStatus.HostIPs = append(instStatus.HostIPs, core.HostIP{
IP: nd.Status.Addresses[i].Address,
})
}
}
for i := range nd.Status.Addresses {
if nd.Status.Addresses[i].Type == core.NodeInternalIP {
instStatus.HostIPs = append(instStatus.HostIPs, core.HostIP{
IP: nd.Status.Addresses[i].Address,
})
}
}
}
// Update the PodIPs in the Instance status if not exists.
if len(instStatus.PodIPs) == 0 {
instStatus.PodIPs = pod.Status.PodIPs
if len(instStatus.PodIPs) == 0 && pod.Status.PodIP != "" {
instStatus.PodIPs = append(instStatus.PodIPs, core.PodIP{
IP: pod.Status.PodIP,
})
}
}
// Update the Allocations in the Instance status if not exists.
if len(instStatus.Allocations) == 0 {
instStatus.Allocations = deviceplugin.AllocatedAcceleratorGroupsOf(pod)
}
}
if kubemeta.DeepEqual(&inst.Status, instStatus) {
logger.V(3).Info("instance status up to date")
return ctrl.Result{}, nil
}
currentPhase, lastPhase := inst.Status.Phase, instStatus.Phase
inst.Status = *instStatus
err = r.Client.Status().Update(ctx, inst)
if err != nil {
return objectWriteResult(logger, err, "update instance status to ready", _requeueAfterConflict)
}
if currentPhase != lastPhase && lastPhase == InstancePhaseReady {
logger.Info("instance started")
} else {
logger.V(3).Info("updated instance status")
}
return ctrl.Result{}, nil
}
func (r *InstanceReconciler) convertPodFromInstance(
ctx context.Context,
inst *workercore.Instance,
instType *worker.InstanceType,
models map[int]*modelArtifactWeights,
) *core.Pod {
needSSHD := inst.Spec.SSHPublicKey != nil && inst.Spec.SSHPublicKey.Name != ""
overcommit := settings.InstanceGeneralResourcesOvercommit.ShouldValueBool(ctx)
additionalVols, additionalMounts := convertAdditionalVolumes(inst.Spec.AdditionalVolumes, models)
// Construct containers.
// Main container.
mainC := core.Container{
Name: "main",
Image: inst.Spec.Image,
ImagePullPolicy: inst.Spec.ImagePullPolicy,
Command: inst.Spec.Command,
SecurityContext: func() *core.SecurityContext {
sc := &core.SecurityContext{
RunAsUser: ptr.To[int64](0),
}
if inst.Spec.Privileged {
sc.Privileged = ptr.To(true)
}
return sc
}(),
Resources: getResourceRequirements(inst.Spec.Resources, instType, true, overcommit, true, false),
Ports: slicex.Transform(inst.Spec.Ports, func(p workercore.InstancePort) core.ContainerPort {
return core.ContainerPort{
Name: getPortName(p),
Protocol: p.Protocol,
ContainerPort: p.Port,
}
}),
Env: slicex.Transform(inst.Spec.Env, func(e workercore.InstanceEnvVar) core.EnvVar {
return core.EnvVar{
Name: e.Name,
Value: e.Value,
}
}),
// Additional volumes are mounted into the workload container only; the sshd sidecar
// nsenters into this container's mount namespace, so they are reachable over SSH anyway.
VolumeMounts: append([]core.VolumeMount{{
Name: "workspace",
MountPath: inst.Spec.VolumeMount,
}}, additionalMounts...),
}
containers := []core.Container{mainC}
if needSSHD {
// SSHD container.
sshdC := core.Container{
Name: "sshd",
Image: redirectedImage(ctx, settings.InstanceSSHServerImage.ShouldValue(ctx)),
ImagePullPolicy: inst.Spec.ImagePullPolicy,
Stdin: true,
TTY: true,
SecurityContext: &core.SecurityContext{
Capabilities: &core.Capabilities{
Add: []core.Capability{
"SYS_ADMIN",
"SYS_PTRACE",
},
},
},
Resources: getResourceRequirements(inst.Spec.Resources, instType, false, false, false, true),
Env: []core.EnvVar{
{
Name: "VOLUME_MOUNT_PATH",
Value: inst.Spec.VolumeMount,
},
},
VolumeMounts: func() []core.VolumeMount {
if inst.Spec.SSHPublicKey == nil {
return nil
}
return []core.VolumeMount{{
Name: "sshd-authorized-keys",
MountPath: "/var/run/sshd-authorized-keys",
ReadOnly: true,
}}
}(),
}
containers = append(containers, sshdC)
}
// Construct pod.
pod := &core.Pod{
ObjectMeta: meta.ObjectMeta{
Name: inst.Name,
Namespace: inst.Namespace,
Labels: map[string]string{
// The LocalQueue that fronts this type's pool, taken from what the type PUBLISHES
// rather than derived from its name. The two agree only while the ClusterQueue is
// created under the InstanceType's own name and both sides spell the result with
// FormatLocalQueueName -- neither of which this package states or owns. The caller
// guarantees it is non-empty; see the entrance guard in Reconcile.
kueuectrlconst.QueueLabel: instType.Status.Entrance, // Scheduling.
deviceplugin.InstancePartOfLabelKey: string(inst.UID), // Accessing.
// The value rides the operator's own resource-type vocabulary, stable across
// Instances — not a generic recommended label a third-party workload could
// carry too — so one policy selects every Instance Pod and nothing else.
systemmeta.ResourceTypeLabel: "instances", // Isolating.
},
},
Spec: core.PodSpec{
HostIPC: true,
ShareProcessNamespace: ptr.To(true),
AutomountServiceAccountToken: ptr.To(false),
EnableServiceLinks: ptr.To(false),
ImagePullSecrets: func() []core.LocalObjectReference {
if inst.Spec.ImagePullSecret == nil {
return nil
}
return []core.LocalObjectReference{
*inst.Spec.ImagePullSecret,
}
}(),
// Pin a node-pinned Instance through a nodeSelector, never through the Pod's own
// nodeName: nodeName skips the scheduler entirely, so Kueue's admission gating and
// the node's predicate checks would never run.
NodeSelector: func() map[string]string {
if inst.Spec.NodeName == "" {
return nil
}
return map[string]string{
core.LabelHostname: r.getNodeHostname(ctx, inst.Spec.NodeName),
}
}(),
Volumes: func() (vols []core.Volume) {
if inst.Spec.SSHPublicKey != nil {
vols = append(vols, core.Volume{
Name: "sshd-authorized-keys",
VolumeSource: core.VolumeSource{
Secret: &core.SecretVolumeSource{
SecretName: inst.Spec.SSHPublicKey.Name,
DefaultMode: ptr.To[int32](0o600),
},
},
})
}
if inst.Spec.Volume.Ephemeral != nil {
vols = append(vols, core.Volume{
Name: "workspace",
VolumeSource: core.VolumeSource{
EmptyDir: &core.EmptyDirVolumeSource{
SizeLimit: &inst.Spec.Volume.Ephemeral.Capacity,
},
},
})
return append(vols, additionalVols...)
}
vols = append(vols, core.Volume{
Name: "workspace",
VolumeSource: core.VolumeSource{
PersistentVolumeClaim: &core.PersistentVolumeClaimVolumeSource{
ClaimName: inst.Spec.Volume.Persistent.Name,
},
},
})
return append(vols, additionalVols...)
}(),
Containers: containers,
},
}
// Ensure runtime class.
if instType.Spec.Acceleratable {
rn := nodefeature.GetAcceleratableRuntimeName(instType.Status.Detail.Manufacturer)
if rn != "" {
rc := new(node.RuntimeClass)
err := r.Client.Get(ctx, ctrlcli.ObjectKey{Name: rn}, rc,
ctrlclix.WithoutQuorum)
if err == nil {
pod.Spec.RuntimeClassName = ptr.To(rn)
}
}
}
// A claim bound to a PV with node affinity is placed where that PV is; Kueue's topology-aware
// scheduling reads the Pod's affinity and not its volumes. A node-delivered artifact adds its
// preference for the nodes holding it, once per digest and in volume order, so a node holding
// more of the Instance's weights scores higher and the same Instance renders the same terms.
preferred := map[string]bool{}
for _, i := range slices.Sorted(maps.Keys(models)) {
w := models[i]
injectModelArtifactAffinity(pod, w.Affinity)
if w.Render == nil || preferred[w.Render.ManifestDigest] {
continue
}
if term := w.placementPreference(ctx, r.Client); term != nil {
preferred[w.Render.ManifestDigest] = true
injectModelPlacementPreference(pod, term)
}
}
systemmeta.NoteResource(pod, "instances", nil)
kubemeta.ControlOnWithoutBlock(pod, inst, workercore.SchemeGroupVersionKind("Instance"))
return pod
}
// convertAdditionalVolumes renders the Instance's additional volumes as Pod volumes paired with the
// mounts that place them in the workload container. Both are returned together so the volume name —
// derived from the entry's index, never from user input, so it can collide with neither "workspace"
// nor "sshd-authorized-keys" — is decided in one place.
//
// An entry with no source is skipped rather than rendered: admission rejects one, and a volume with
// an empty source would make the API server refuse the whole Pod on every reconcile.
func convertAdditionalVolumes(
avs []workercore.InstanceAdditionalVolume, models map[int]*modelArtifactWeights,
) (vols []core.Volume, mounts []core.VolumeMount) {
if len(avs) == 0 {
return nil, nil
}
vols = make([]core.Volume, 0, len(avs))
mounts = make([]core.VolumeMount, 0, len(avs))
for i := range avs {
av := &avs[i]
var vs core.VolumeSource
readOnly, subPath := av.ReadOnly, av.SubPath
switch {
case av.Model != nil:
// Always read-only whatever the entry says: a claim with the artifact's own path as
// the sub-path, a hub artifact through the node's plugin. An entry the reconciler
// resolved nothing for is skipped like one naming no source: the reconciler waits
// rather than build a Pod without it.
w := models[i]
switch {
case w == nil || w.Render == nil:
continue
case w.Render.Delivery == workercore.ModelDeploymentModelDeliveryPVC:
vs.PersistentVolumeClaim = &core.PersistentVolumeClaimVolumeSource{
ClaimName: w.Render.ClaimName, ReadOnly: true,
}
readOnly, subPath = true, w.Render.Path
case w.Render.Delivery == workercore.ModelDeploymentModelDeliveryNode:
vs = w.Render.nodeVolumeSource()
readOnly, subPath = true, ""
case w.Render.Delivery == workercore.ModelDeploymentModelDeliveryImage:
vs.Image = &core.ImageVolumeSource{Reference: w.Render.ImageReference}
readOnly, subPath = true, ""
default:
continue
}
case av.Persistent != nil:
vs.PersistentVolumeClaim = &core.PersistentVolumeClaimVolumeSource{
ClaimName: av.Persistent.Name,
}
case av.ConfigMap != nil:
vs.ConfigMap = &core.ConfigMapVolumeSource{
LocalObjectReference: *av.ConfigMap,
}
case av.Secret != nil:
vs.Secret = &core.SecretVolumeSource{
SecretName: av.Secret.Name,
}
case av.HostPath != nil:
vs.HostPath = av.HostPath.DeepCopy()
default:
continue
}
name := additionalVolumeName(i)
vols = append(vols, core.Volume{
Name: name,
VolumeSource: vs,
})
mounts = append(mounts, core.VolumeMount{
Name: name,
MountPath: av.MountPath,
ReadOnly: readOnly,
SubPath: subPath,
})
}
return vols, mounts
}
// resolveInstanceModelVolumes resolves every model volume's artifact, keyed by the entry's index,
// and returns why the Pod cannot be built yet, or "" once it can.
func (r *InstanceReconciler) resolveInstanceModelVolumes(
ctx context.Context, inst *workercore.Instance,
) (map[int]*modelArtifactWeights, string, error) {
models := map[int]*modelArtifactWeights{}
for i := range inst.Spec.AdditionalVolumes {
av := &inst.Spec.AdditionalVolumes[i]
if av.Model == nil {
continue
}
// One Pod mounts it, so a claim that cannot be shared still serves.
// An Instance has no engine to download a hub artifact, so the node delivers it.
w, err := resolveModelArtifactWeights(ctx, r.Client, inst.Namespace, av.Model.ArtifactRef.Name, 1, true)
if err != nil {
return nil, "", err
}
if w.Blocked {
return nil, w.Message, nil
}
// An image volume runs on kubelet and containerd, so a pinned Instance checks its node
// before rendering: a Pod whose volume the node cannot run would fail late, in a kubelet
// event the Instance status never surfaces. An Instance pinned to no node cannot know, and
// waits for the Pod's own fate like a ModelDeployment does.
if w.Render.Delivery == workercore.ModelDeploymentModelDeliveryImage && inst.Spec.NodeName != "" {
nd := new(core.Node)
if err := r.Client.Get(ctx, ctrlcli.ObjectKey{Name: inst.Spec.NodeName}, nd, ctrlclix.WithoutQuorum); err != nil {
if kerrors.IsNotFound(err) {
return nil, fmt.Sprintf("the node %q this Instance pins does not exist", inst.Spec.NodeName), nil
}
return nil, "", fmt.Errorf("read node %q: %w", inst.Spec.NodeName, err)
}
if unsupported := modelImageRuntimeUnsupported(
nd.Status.NodeInfo.KubeletVersion, nd.Status.NodeInfo.ContainerRuntimeVersion,
); unsupported != "" {
return nil, fmt.Sprintf("ModelArtifact %q is delivered as an image volume, and node %q cannot run one: "+
"%s; pin another node or upgrade it", av.Model.ArtifactRef.Name, inst.Spec.NodeName, unsupported), nil
}
}
models[i] = w
}
return models, "", nil
}
// instanceModelImageContainerdFloor is the containerd version that mounts image volumes from.
var instanceModelImageContainerdFloor = utilversion.MustParseGeneric("2.1")
// modelImageRuntimeUnsupported reports the first floor a node misses for an image volume, or ""
// when it meets them both: kubelet runs the ImageVolume feature, on by default from 1.35, and
// containerd mounts image volumes from 2.1. An unreadable version reports unsupported — the same
// fail-closed answer the apiserver's gate gives.
func modelImageRuntimeUnsupported(kubeletVersion, containerRuntimeVersion string) string {
if !kubediscovery.SupportsFeature(&kubediscovery.Version{GitVersion: kubeletVersion}, kubediscovery.FeatureImageVolume) {
return fmt.Sprintf("kubelet %q is below the 1.35 the ImageVolume feature turns on at", kubeletVersion)
}
runtime, runtimeVersion, found := strings.Cut(containerRuntimeVersion, "://")
if !found || runtime != "containerd" {
return fmt.Sprintf("the container runtime %q is not containerd, which is what mounts image volumes",
containerRuntimeVersion)
}
if v, err := utilversion.ParseGeneric(runtimeVersion); err != nil || v.LessThan(instanceModelImageContainerdFloor) {
return fmt.Sprintf("containerd %q is below the 2.1 that mounts image volumes from", runtimeVersion)
}
return ""