-
Notifications
You must be signed in to change notification settings - Fork 94
Expand file tree
/
Copy pathmodel_serving_controller.go
More file actions
2131 lines (1907 loc) · 84.2 KB
/
model_serving_controller.go
File metadata and controls
2131 lines (1907 loc) · 84.2 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
/*
Copyright The Volcano Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permsssions and
limstations under the License.
*/
package controller
import (
"cmp"
"context"
"errors"
"fmt"
"reflect"
"slices"
"sync"
"time"
corev1 "k8s.io/api/core/v1"
apiextClientSet "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/selection"
"k8s.io/apimachinery/pkg/types"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
"k8s.io/client-go/informers"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/kubernetes/scheme"
typedcorev1 "k8s.io/client-go/kubernetes/typed/core/v1"
listerv1 "k8s.io/client-go/listers/core/v1"
"k8s.io/client-go/tools/cache"
"k8s.io/client-go/tools/record"
"k8s.io/client-go/util/retry"
"k8s.io/client-go/util/workqueue"
"k8s.io/klog/v2"
schedulingv1beta1 "volcano.sh/apis/pkg/apis/scheduling/v1beta1"
volcano "volcano.sh/apis/pkg/client/clientset/versioned"
clientset "github.com/volcano-sh/kthena/client-go/clientset/versioned"
informersv1alpha1 "github.com/volcano-sh/kthena/client-go/informers/externalversions"
listerv1alpha1 "github.com/volcano-sh/kthena/client-go/listers/workload/v1alpha1"
workloadv1alpha1 "github.com/volcano-sh/kthena/pkg/apis/workload/v1alpha1"
"github.com/volcano-sh/kthena/pkg/model-serving-controller/datastore"
"github.com/volcano-sh/kthena/pkg/model-serving-controller/plugins"
"github.com/volcano-sh/kthena/pkg/model-serving-controller/podgroupmanager"
"github.com/volcano-sh/kthena/pkg/model-serving-controller/utils"
)
const (
// enqueueAfter is the time duration to wait to re-enqueue:
enqueueAfter = 1 * time.Second
GroupNameKey = "GroupName"
RoleIDKey = "RoleID"
)
type ModelServingController struct {
kubeClientSet kubernetes.Interface
modelServingClient clientset.Interface
syncHandler func(ctx context.Context, msKey string) error
podGroupManager *podgroupmanager.Manager
podsLister listerv1.PodLister
podsInformer cache.SharedIndexInformer
servicesLister listerv1.ServiceLister
servicesInformer cache.SharedIndexInformer
modelServingLister listerv1alpha1.ModelServingLister
modelServingsInformer cache.SharedIndexInformer
// nolint
workqueue workqueue.RateLimitingInterface
store datastore.Store
graceMap sync.Map // key: errorPod.namespace/errorPod.name, value:time
initialSync bool // indicates whether the initial sync has been completed
pluginsRegistry *plugins.Registry
recorder record.EventRecorder
}
func NewModelServingController(kubeClientSet kubernetes.Interface, modelServingClient clientset.Interface, volcanoClient volcano.Interface, apiextClient apiextClientSet.Interface) (*ModelServingController, error) {
selector, err := labels.NewRequirement(workloadv1alpha1.GroupNameLabelKey, selection.Exists, nil)
if err != nil {
return nil, fmt.Errorf("cannot create label selector, err: %v", err)
}
// Register ModelServing types in the global scheme for event recording.
if err := workloadv1alpha1.Install(scheme.Scheme); err != nil {
return nil, fmt.Errorf("failed to register ModelServing API scheme: %v", err)
}
kubeInformerFactory := informers.NewSharedInformerFactoryWithOptions(
kubeClientSet,
0,
informers.WithTweakListOptions(func(opts *metav1.ListOptions) {
opts.LabelSelector = selector.String()
}),
)
podsInformer := kubeInformerFactory.Core().V1().Pods()
servicesInformer := kubeInformerFactory.Core().V1().Services()
modelServingInformerFactory := informersv1alpha1.NewSharedInformerFactory(modelServingClient, 0)
modelServingInformer := modelServingInformerFactory.Workload().V1alpha1().ModelServings()
err = podsInformer.Informer().AddIndexers(cache.Indexers{
GroupNameKey: utils.GroupNameIndexFunc,
RoleIDKey: utils.RoleIDIndexFunc,
})
if err != nil {
return nil, fmt.Errorf("cannot create pod Informer Index, err: %v", err)
}
err = servicesInformer.Informer().AddIndexers(cache.Indexers{
GroupNameKey: utils.GroupNameIndexFunc,
RoleIDKey: utils.RoleIDIndexFunc,
})
if err != nil {
return nil, fmt.Errorf("cannot create service Informer Index, err: %v", err)
}
store := datastore.New()
// setup event broadcaster & recorder
eventBroadcaster := record.NewBroadcaster()
eventBroadcaster.StartStructuredLogging(0)
eventBroadcaster.StartRecordingToSink(&typedcorev1.EventSinkImpl{
Interface: kubeClientSet.CoreV1().Events(""),
})
recorder := eventBroadcaster.NewRecorder(
scheme.Scheme,
corev1.EventSource{Component: "modelserving-controller"},
)
c := &ModelServingController{
kubeClientSet: kubeClientSet,
modelServingClient: modelServingClient,
podGroupManager: nil,
podsLister: podsInformer.Lister(),
podsInformer: podsInformer.Informer(),
servicesLister: servicesInformer.Lister(),
servicesInformer: servicesInformer.Informer(),
modelServingLister: modelServingInformer.Lister(),
modelServingsInformer: modelServingInformer.Informer(),
// nolint
workqueue: workqueue.NewNamedRateLimitingQueue(workqueue.DefaultControllerRateLimiter(), "ModelServings"),
store: store,
pluginsRegistry: plugins.DefaultRegistry,
recorder: recorder,
}
registerPodGroupHandler := func(pgInformer cache.SharedIndexInformer) {
if c == nil || pgInformer == nil {
return
}
_, _ = pgInformer.AddEventHandler(cache.FilteringResourceEventHandler{
FilterFunc: func(obj interface{}) bool {
metaObj := getMetaObject(obj)
if metaObj == nil {
return false
}
return isOwnedByModelServing(metaObj)
},
Handler: cache.ResourceEventHandlerFuncs{
DeleteFunc: func(obj interface{}) {
c.deletePodGroup(obj)
},
},
})
}
c.podGroupManager = podgroupmanager.NewManager(kubeClientSet, volcanoClient, apiextClient, registerPodGroupHandler)
klog.Info("Set the ModelServing event handler")
_, _ = c.modelServingsInformer.AddEventHandler(cache.ResourceEventHandlerFuncs{
AddFunc: func(obj interface{}) {
c.addModelServing(obj)
},
UpdateFunc: func(oldObj, newObj interface{}) {
c.updateModelServing(oldObj, newObj)
},
DeleteFunc: func(obj interface{}) {
c.deleteModelServing(obj)
},
})
_, _ = c.podsInformer.AddEventHandler(cache.FilteringResourceEventHandler{
FilterFunc: func(obj interface{}) bool {
metaObj := getMetaObject(obj)
if metaObj == nil {
return false
}
return isOwnedByModelServing(metaObj)
},
Handler: cache.ResourceEventHandlerFuncs{
AddFunc: func(obj interface{}) {
c.addPod(obj)
},
UpdateFunc: func(oldObj, newObj interface{}) {
c.updatePod(oldObj, newObj)
},
DeleteFunc: func(obj interface{}) {
c.deletePod(obj)
},
},
})
_, _ = c.servicesInformer.AddEventHandler(cache.FilteringResourceEventHandler{
FilterFunc: func(obj interface{}) bool {
metaObj := getMetaObject(obj)
if metaObj == nil {
return false
}
return isOwnedByModelServing(metaObj)
},
Handler: cache.ResourceEventHandlerFuncs{
DeleteFunc: func(obj interface{}) {
c.deleteService(obj)
},
},
})
c.syncHandler = c.syncModelServing
return c, nil
}
func (c *ModelServingController) addModelServing(obj interface{}) {
ms, ok := obj.(*workloadv1alpha1.ModelServing)
if !ok {
klog.Errorf("failed to parse ModelServing %#v", obj)
return
}
klog.V(4).InfoS("Adding", "modelServing", klog.KObj(ms))
c.enqueueModelServing(ms)
}
func (c *ModelServingController) updateModelServing(old, cur interface{}) {
curms, ok := cur.(*workloadv1alpha1.ModelServing)
if !ok {
klog.Error("failed to parse ModelServing type when updatems")
return
}
oldms, ok := old.(*workloadv1alpha1.ModelServing)
if !ok {
klog.Error("failed to parse ModelServing type when updatems")
return
}
if reflect.DeepEqual(oldms.Spec, curms.Spec) {
// If the spec has not changed, we do not need to reconcile.
klog.V(4).InfoS("Spec has not changed, skipping update", "modelServing", klog.KObj(curms))
return
}
// If network topology is removed, we need to clean up the PodGroups.
// Because minRoleReplicas is not allowed to be updated, so we do not need to check it here.
if oldms.Spec.Template.NetworkTopology != nil && curms.Spec.Template.NetworkTopology == nil {
if curms.Spec.Template.GangPolicy == nil || len(curms.Spec.Template.GangPolicy.MinRoleReplicas) == 0 {
if err := c.podGroupManager.CleanupPodGroups(context.TODO(), curms); err != nil {
klog.Errorf("failed to clean up PodGroups for ModelServing %s/%s: %v", curms.Namespace, curms.Name, err)
}
}
}
c.enqueueModelServing(curms)
}
func (c *ModelServingController) deleteModelServing(obj interface{}) {
ms, ok := obj.(*workloadv1alpha1.ModelServing)
if !ok {
// If the object is not a ModelServing, it might be a tombstone object.
tombstone, ok := obj.(cache.DeletedFinalStateUnknown)
if !ok {
klog.Errorf("failed to parse ModelServing type when deletems %#v", obj)
return
}
ms, ok = tombstone.Obj.(*workloadv1alpha1.ModelServing)
if !ok {
klog.Errorf("failed to parse ModelServing from tombstone %#v", tombstone.Obj)
return
}
}
c.store.DeleteModelServing(types.NamespacedName{
Namespace: ms.Namespace,
Name: ms.Name,
})
// ControllerRevisions will be automatically deleted via OwnerReference when ModelServing is deleted
}
func (c *ModelServingController) addPod(obj interface{}) {
c.updatePod(nil, obj)
}
func (c *ModelServingController) updatePod(_, newObj interface{}) {
newPod, ok := newObj.(*corev1.Pod)
if !ok {
klog.Error("failed to parse newPod type when updatePod")
return
}
klog.V(4).Infof("updatePod: %s/%s, %v", newPod.Namespace, newPod.Name, newPod.Status.Phase)
if newPod.DeletionTimestamp != nil {
// If the pod is being deleted, we do not need to handle it.
// After deleted,following work will be done in deletePod.
return
}
ms, servingGroupName, err := c.getModelServingByChildResource(newPod)
if err != nil {
if apierrors.IsNotFound(err) {
klog.V(4).Infof("modelServing of pod %s has been deleted", newPod.Name)
} else {
klog.Errorf("get model Serving failed when update pod: %v", err)
}
return
}
if c.shouldSkipHandling(ms, servingGroupName, newPod) {
return
}
switch {
case utils.IsPodRunningAndReady(newPod):
klog.V(4).Infof("handleReadyPod: %s/%s", newPod.Namespace, newPod.Name)
// The pod is available, that is, the state is running, and the container is ready
err = c.handleReadyPod(ms, servingGroupName, newPod)
if err != nil {
klog.Errorf("handle running pod failed: %v", err)
}
case utils.IsPodFailed(newPod) || utils.ContainerRestarted(newPod):
klog.V(4).Infof("handleErrorPod: %s/%s", newPod.Namespace, newPod.Name)
err = c.handleErrorPod(ms, servingGroupName, newPod)
if err != nil {
klog.Errorf("handle error pod failed: %v", err)
}
default:
klog.V(4).Infof("handleDefault: %s/%s", newPod.Namespace, newPod.Name)
if !c.initialSync {
c.store.AddServingGroupAndRole(types.NamespacedName{
Namespace: ms.Namespace,
Name: ms.Name,
}, servingGroupName, utils.ObjectRevision(newPod), utils.GetRoleName(newPod), utils.GetRoleID(newPod))
}
}
}
func (c *ModelServingController) deletePod(obj interface{}) {
pod, ok := obj.(*corev1.Pod)
if !ok {
// If the object is not a Pod, it might be a tombstone object.
tombstone, ok := obj.(cache.DeletedFinalStateUnknown)
if !ok {
klog.Error("failed to parse pod type when deletePod")
return
}
pod, ok = tombstone.Obj.(*corev1.Pod)
if !ok {
klog.Errorf("failed to parse Pod from tombstone %#v", tombstone.Obj)
return
}
}
ms, servingGroupName, roleName, roleID := c.getModelServingAndResourceDetails(pod)
// ms is nil means the modelserving is deleted
// delete the pod
if ms == nil {
klog.Warningf("ModelServing of deleted pod: %s not found, might be already deleted", pod.Name)
return
}
// Remove the pod from running pods in the store
c.store.DeleteRunningPodFromServingGroup(utils.GetNamespaceName(ms), servingGroupName, pod.Name)
// skip handling if pod revision mismatches serving group revision or owner mismatch
if c.shouldSkipHandling(ms, servingGroupName, pod) {
return
}
if c.handleDeletionInProgress(ms, servingGroupName, roleName, roleID) {
return
}
err := c.handleDeletedPod(ms, servingGroupName, pod)
if err != nil {
klog.Errorf("handle deleted pod failed: %v", err)
}
}
func (c *ModelServingController) deleteService(obj interface{}) {
svc, ok := obj.(*corev1.Service)
if !ok {
// If the object is not a Service, it might be a tombstone object.
tombstone, ok := obj.(cache.DeletedFinalStateUnknown)
if !ok {
klog.Error("failed to parse service type when deleteService")
return
}
svc, ok = tombstone.Obj.(*corev1.Service)
if !ok {
klog.Errorf("failed to parse Service from tombstone %#v", tombstone.Obj)
return
}
}
ms, servingGroupName, roleName, roleID := c.getModelServingAndResourceDetails(svc)
// ms is nil means the modelserving is deleted
if ms == nil {
klog.Warningf("ModelServing of deleted service: %s not found, might be already deleted", svc.Name)
return
}
// skip handling if service revision mismatches serving group revision or owner mismatch
if c.shouldSkipHandling(ms, servingGroupName, svc) {
return
}
if c.handleDeletionInProgress(ms, servingGroupName, roleName, roleID) {
return
}
klog.V(4).Infof("Service %s/%s deleted, enqueuing ModelServing %s for reconcile", svc.GetNamespace(), svc.GetName(), ms.Name)
c.enqueueModelServing(ms)
}
func (c *ModelServingController) deletePodGroup(obj interface{}) {
pg, ok := obj.(*schedulingv1beta1.PodGroup)
if !ok {
// If the object is not a PodGroup, it might be a tombstone object.
tombstone, ok := obj.(cache.DeletedFinalStateUnknown)
if !ok {
klog.Error("failed to parse podgroup type when deletePodGroup")
return
}
pg, ok = tombstone.Obj.(*schedulingv1beta1.PodGroup)
if !ok {
klog.Errorf("failed to parse PodGroup from tombstone %#v", tombstone.Obj)
return
}
}
ms, servingGroupName, _, _ := c.getModelServingAndResourceDetails(pg)
// ms is nil means the modelserving is deleted
if ms == nil {
klog.Warningf("ModelServing of deleted podGroup: %s not found, might be already deleted", pg.Name)
return
}
// skip handling if podGroup revision mismatches serving group revision or owner mismatch
if c.shouldSkipHandling(ms, servingGroupName, pg) {
return
}
// If servingGroup is deleting, skip handling.
if c.handleDeletionInProgress(ms, servingGroupName, "", "") {
return
}
klog.V(4).Infof("podGroup %s/%s deleted, enqueuing ModelServing %s for reconcile", pg.GetNamespace(), pg.GetName(), ms.Name)
c.enqueueModelServing(ms)
}
func (c *ModelServingController) enqueueModelServing(ms *workloadv1alpha1.ModelServing) {
var key string
var err error
if key, err = cache.MetaNamespaceKeyFunc(ms); err != nil {
utilruntime.HandleError(err)
return
}
c.workqueue.Add(key)
}
func (c *ModelServingController) enqueueModelServingAfter(ms *workloadv1alpha1.ModelServing, duration time.Duration) {
var key string
var err error
if key, err = cache.MetaNamespaceKeyFunc(ms); err != nil {
utilruntime.HandleError(err)
return
}
c.workqueue.AddAfter(key, duration)
}
func (c *ModelServingController) worker(ctx context.Context) {
for c.processNextWorkItem(ctx) {
}
}
func (c *ModelServingController) processNextWorkItem(ctx context.Context) bool {
key, quit := c.workqueue.Get()
if quit {
return false
}
defer c.workqueue.Done(key)
err := c.syncHandler(ctx, key.(string))
if err == nil {
c.workqueue.Forget(key)
return true
}
utilruntime.HandleError(fmt.Errorf("sync %q failed with %v", key, err))
c.workqueue.AddRateLimited(key)
return true
}
func (c *ModelServingController) syncModelServing(ctx context.Context, key string) error {
klog.V(4).InfoS("Started syncing ModelServing", "key", key)
namespace, name, err := cache.SplitMetaNamespaceKey(key)
if err != nil {
return fmt.Errorf("invalid resource key: %s", err)
}
ms, err := c.modelServingLister.ModelServings(namespace).Get(name)
if apierrors.IsNotFound(err) {
klog.V(4).Infof("%v has been deleted", key)
return nil
}
if err != nil {
return err
}
// only fields in roles can be modified in rolling updates.
// and only modifying the role.replicas field will not affect the revision.
copy := utils.RemoveRoleReplicasForRevision(ms)
revision := utils.Revision(copy.Spec.Template.Roles)
if err := c.manageServingGroupReplicas(ctx, ms, revision); err != nil {
return fmt.Errorf("cannot manage ServingGroup replicas: %v", err)
}
if err := c.manageRole(ctx, ms, revision); err != nil {
return fmt.Errorf("cannot manage role replicas: %v", err)
}
if err := c.manageServingGroupRollingUpdate(ctx, ms, revision); err != nil {
return fmt.Errorf("cannot manage ServingGroup rollingUpdate: %v", err)
}
if err := c.manageHeadlessService(ctx, ms); err != nil {
return fmt.Errorf("cannot manage ModelServing: %v", err)
}
if err := c.UpdateModelServingStatus(ms, revision); err != nil {
return fmt.Errorf("failed to update status of ms %s/%s: %v", namespace, name, err)
}
return nil
}
func (c *ModelServingController) Run(ctx context.Context, workers int) {
defer utilruntime.HandleCrash()
defer c.workqueue.ShutDown()
// start informers
go c.podsInformer.RunWithContext(ctx)
go c.servicesInformer.RunWithContext(ctx)
go c.modelServingsInformer.RunWithContext(ctx)
if err := c.podGroupManager.Run(ctx); err != nil {
klog.Errorf("failed to start PodGroup informer: %v", err)
}
cache.WaitForCacheSync(ctx.Done(),
c.podsInformer.HasSynced,
c.servicesInformer.HasSynced,
c.modelServingsInformer.HasSynced,
)
// sync pods first
c.syncAll()
klog.Info("initial sync has been done")
klog.Info("start modelServing controller")
for i := 0; i < workers; i++ {
go c.worker(ctx)
}
<-ctx.Done()
klog.Info("shut down modelServing controller")
}
func (c *ModelServingController) syncAll() {
pods, err := c.podsLister.List(labels.Everything())
if err != nil {
klog.Errorf("failed to list pods: %v", err)
}
for _, pod := range pods {
c.addPod(pod)
}
modelServings, err := c.modelServingLister.List(labels.Everything())
if err != nil {
klog.Errorf("failed to list model servings: %v", err)
}
for _, ms := range modelServings {
c.addModelServing(ms)
}
c.initialSync = true
}
func (c *ModelServingController) manageServingGroupReplicas(ctx context.Context, ms *workloadv1alpha1.ModelServing, newRevision string) error {
servingGroupList, err := c.store.GetServingGroupByModelServing(utils.GetNamespaceName(ms))
if err != nil && !errors.Is(err, datastore.ErrServingGroupNotFound) {
return fmt.Errorf("cannot get servingGroup of modelServing: %s from map: %v", ms.GetName(), err)
}
expectedCount := int(*ms.Spec.Replicas)
curReplicas := len(servingGroupList)
// Determine whether it is a scale-up or scale-down scenario
if curReplicas < expectedCount {
klog.V(2).Infof("manageServingGroupReplicas: scaling up modelServing=%s (%d -> %d)", utils.GetNamespaceName(ms), curReplicas, expectedCount)
// update pod groups if needed
for _, servingGroup := range servingGroupList {
if err := c.createOrUpdatePodGroupByServingGroup(ctx, ms, servingGroup.Name); err != nil {
return fmt.Errorf("failed to update PodGroup for ServingGroup %s: %v", servingGroup.Name, err)
}
}
if err := c.scaleUpServingGroups(ctx, ms, servingGroupList, expectedCount, newRevision); err != nil {
return fmt.Errorf("failed to scale up ServingGroups: %v", err)
}
} else {
if curReplicas > expectedCount {
klog.V(2).Infof("manageServingGroupReplicas: scaling down modelServing=%s (%d -> %d)", utils.GetNamespaceName(ms), curReplicas, expectedCount)
if err := c.scaleDownServingGroups(ctx, ms, servingGroupList, expectedCount); err != nil {
return fmt.Errorf("failed to scale down ServingGroups: %v", err)
}
}
// Note: in case the role is updated, we need to update pod groups as well.
// update pod group after scaling down, so that we do not need to update pod group for deleting serving groups
// Moreover, it is also possible to reconstruct accidentally deleted podGroups here.
servingGroupList, err := c.store.GetServingGroupByModelServing(utils.GetNamespaceName(ms))
if err != nil && !errors.Is(err, datastore.ErrServingGroupNotFound) {
return fmt.Errorf("cannot get servingGroup of modelServing: %s from map: %v", ms.GetName(), err)
}
for _, servingGroup := range servingGroupList {
if servingGroup.Status != datastore.ServingGroupDeleting {
if err := c.createOrUpdatePodGroupByServingGroup(ctx, ms, servingGroup.Name); err != nil {
return fmt.Errorf("failed to update PodGroup for ServingGroup %s: %v", servingGroup.Name, err)
}
}
}
}
return nil
}
// scaleUpServingGroups scales up the ServingGroups to the expected count.
// When partition is set, it fills missing ordinals in [0, partition) using CurrentRevision.
// Otherwise, it creates new ServingGroups with increasing indices starting from the current max index + 1.
func (c *ModelServingController) scaleUpServingGroups(ctx context.Context, ms *workloadv1alpha1.ModelServing, servingGroupList []datastore.ServingGroup, expectedCount int, newRevision string) error {
partition := c.getPartition(ms)
klog.V(4).Infof("scaleUpServingGroups: start for modelServing=%s, existingGroups=%d, expectedCount=%d, partition=%d, newRevision=%s",
utils.GetNamespaceName(ms), len(servingGroupList), expectedCount, partition, newRevision)
// Find the maximum ordinal in existing servingGroups
// Since servingGroupList is already sorted in ascending order by ordinal,
// we can directly get the maxOrdinal from the last element
maxOrdinal := -1
existingOrdinals := make(map[int]bool)
for _, group := range servingGroupList {
_, ordinal := utils.GetParentNameAndOrdinal(group.Name)
existingOrdinals[ordinal] = true
}
// Get maxOrdinal from the last element (list is sorted in ascending order)
if len(servingGroupList) > 0 {
_, maxOrdinal = utils.GetParentNameAndOrdinal(servingGroupList[len(servingGroupList)-1].Name)
}
klog.V(4).Infof("scaleUpServingGroups: modelServing=%s, existingOrdinals=%v, maxOrdinal=%d",
utils.GetNamespaceName(ms), existingOrdinals, maxOrdinal)
// Helper function to create a ServingGroup
createServingGroup := func(ordinal int, revision string, roles []workloadv1alpha1.Role) error {
groupName := utils.GenerateServingGroupName(ms.Name, ordinal)
klog.V(4).Infof("scaleUpServingGroups: creating/updating PodGroup for ServingGroup=%s", groupName)
// Ensure a PodGroup exists for the new ServingGroup when gang scheduling is enabled.
if err := c.createOrUpdatePodGroupByServingGroup(ctx, ms, groupName); err != nil {
return err
}
klog.V(4).Infof("Creating ServingGroup %s at ordinal %d with revision %s", groupName, ordinal, revision)
// Create pods for ServingGroup using the provided roles template
if err := c.CreatePodsForServingGroup(ctx, ms, ordinal, revision, roles); err != nil {
return fmt.Errorf("create Serving group failed: %v", err)
}
// Insert new ServingGroup to global storage
c.store.AddServingGroup(utils.GetNamespaceName(ms), ordinal, revision)
klog.V(4).Infof("scaleUpServingGroups: ServingGroup=%s added to store (ordinal=%d, revision=%s)", groupName, ordinal, revision)
return nil
}
if partition > 0 {
klog.V(4).Infof("scaleUpServingGroups: partition=%d set, filling missing ordinals in [0, %d) for modelServing=%s",
partition, partition, utils.GetNamespaceName(ms))
// When partition is set, fill missing ordinals in [0, partition) using CurrentRevision
for ordinal := 0; ordinal < partition && ordinal < expectedCount; ordinal++ {
if existingOrdinals[ordinal] {
klog.V(4).Infof("scaleUpServingGroups: ordinal %d already exists, skipping", ordinal)
continue
}
// Use CurrentRevision for partition-protected ordinals
revisionToUse := newRevision
if ms.Status.CurrentRevision != "" {
revisionToUse = ms.Status.CurrentRevision
}
klog.V(4).Infof("scaleUpServingGroups: ordinal %d missing (partition-protected), revisionToUse=%s, currentRevision=%s",
ordinal, revisionToUse, ms.Status.CurrentRevision)
// For ordinal < partition, we should use the old template from the revision
// Two cases:
// 1. First startup: use ms.Spec.Template.Roles (which corresponds to CurrentRevision)
// 2. During recovery: use template from ControllerRevision retrieved by revision
var rolesToUse []workloadv1alpha1.Role
cr, _ := utils.GetControllerRevision(ctx, c.kubeClientSet, ms, revisionToUse)
if cr != nil {
// Case 2: Recovery scenario - use template from ControllerRevision
if roles, err := utils.GetRolesFromControllerRevision(cr); err != nil {
klog.Warningf("Failed to get roles from ControllerRevision for revision %s (ordinal %d): %v, falling back to ms.Spec.Template.Roles", revisionToUse, ordinal, err)
rolesToUse = ms.Spec.Template.Roles
} else {
rolesToUse = roles
klog.V(4).Infof("Recovering ServingGroup at ordinal %d with revision %s using template from ControllerRevision (partition=%d)", ordinal, revisionToUse, partition)
}
} else {
// Case 1: First startup - ControllerRevision not found, use ms.Spec.Template.Roles
rolesToUse = ms.Spec.Template.Roles
klog.V(4).Infof("Creating missing ServingGroup at ordinal %d with revision %s using ms.Spec.Template.Roles (partition=%d, first startup)", ordinal, revisionToUse, partition)
}
if err := createServingGroup(ordinal, revisionToUse, rolesToUse); err != nil {
return err
}
// Update existingOrdinals and maxOrdinal
existingOrdinals[ordinal] = true
if ordinal > maxOrdinal {
maxOrdinal = ordinal
}
}
}
// Create new ServingGroups with increasing indices starting from the current max index + 1
toCreate := expectedCount - len(existingOrdinals)
klog.V(4).Infof("scaleUpServingGroups: toCreate=%d (expectedCount=%d, existingOrdinals=%d), startingIndex=%d, modelServing=%s",
toCreate, expectedCount, len(existingOrdinals), maxOrdinal+1, utils.GetNamespaceName(ms))
if toCreate > 0 {
startingIndex := maxOrdinal + 1
// Create ControllerRevision when scaling up with a new revision
// This is done once before the loop since newRevision and templateData are the same for all new groups
templateData := ms.Spec.Template.Roles
klog.V(4).Infof("scaleUpServingGroups: creating ControllerRevision for newRevision=%s, modelServing=%s", newRevision, utils.GetNamespaceName(ms))
_, err := utils.CreateControllerRevision(ctx, c.kubeClientSet, ms, newRevision, templateData)
if err != nil {
klog.Warningf("Failed to create ControllerRevision for new revision %s: %v", newRevision, err)
}
// Create new ServingGroups with increasing indices
for i := startingIndex; i < startingIndex+toCreate; i++ {
klog.V(4).Infof("scaleUpServingGroups: creating new ServingGroup at ordinal=%d with newRevision=%s for modelServing=%s", i, newRevision, utils.GetNamespaceName(ms))
// For newly created ServingGroups (ordinal >= partition), always use current template
if err := createServingGroup(i, newRevision, ms.Spec.Template.Roles); err != nil {
return err
}
}
}
klog.V(4).Infof("scaleUpServingGroups: done for modelServing=%s", utils.GetNamespaceName(ms))
return nil
}
func (c *ModelServingController) manageRole(ctx context.Context, ms *workloadv1alpha1.ModelServing, newRevision string) error {
servingGroupList, err := c.store.GetServingGroupByModelServing(utils.GetNamespaceName(ms))
if err != nil && !errors.Is(err, datastore.ErrServingGroupNotFound) {
return fmt.Errorf("cannot get ServingGroup of modelServing: %s from map: %v", ms.GetName(), err)
}
for _, servingGroup := range servingGroupList {
if c.store.GetServingGroupStatus(utils.GetNamespaceName(ms), servingGroup.Name) == datastore.ServingGroupDeleting {
// Deleting ServingGroup will be recreated after the deletion is complete, so there is no need to scale the roles
continue
}
_, servingGroupOrdinal := utils.GetParentNameAndOrdinal(servingGroup.Name)
for _, targetRole := range ms.Spec.Template.Roles {
c.manageRoleReplicas(ctx, ms, servingGroup.Name, targetRole, servingGroupOrdinal, newRevision)
}
}
return nil
}
// scaleDownRoles handles Role scaling down with two-level priority-based selection:
// 1. Primary: Not-ready roles (Creating, NotFound) are deleted first
// 2. Secondary: Among roles with same status, lower deletion cost = delete first
func (c *ModelServingController) scaleDownRoles(ctx context.Context, ms *workloadv1alpha1.ModelServing, groupName string, targetRole workloadv1alpha1.Role, roleList []datastore.Role, expectedCount int) {
// Calculate priority information for all Roles
var roleScores []RoleWithScore
for _, role := range roleList {
scoreInfo := c.calculateRoleScore(ms, groupName, targetRole.Name, role.Name)
roleScores = append(roleScores, scoreInfo)
}
// Sort by priority tuple: (priority, deletionCost, index)
// Lower priority value = higher deletion priority (delete first)
// Lower deletion cost = higher deletion priority
// Higher index = higher deletion priority (backward compatibility)
slices.SortFunc(roleScores, func(a, b RoleWithScore) int {
// Primary: Sort by priority (not-ready first)
if a.Priority != b.Priority {
return cmp.Compare(a.Priority, b.Priority) // Ascending: lower priority (not-ready) first
}
// Secondary: Among roles with same priority, lower deletion cost comes first
if a.DeletionCost != b.DeletionCost {
return cmp.Compare(a.DeletionCost, b.DeletionCost) // Ascending: lower cost first
}
// Tertiary: Higher index comes first (backward compatibility)
return cmp.Compare(b.Index, a.Index) // Descending: higher indices first
})
// Role needs to scale down, and the ServingGroup status needs to be set to Scaling
err := c.store.UpdateServingGroupStatus(utils.GetNamespaceName(ms), groupName, datastore.ServingGroupScaling)
klog.V(4).Infof("Setting ServingGroup %s/%s status to Scaling for role %s scaling down", ms.Namespace+"/"+ms.Name, groupName, targetRole.Name)
if err != nil {
klog.Errorf("failed to set ServingGroup %s/%s status: %v", ms.Namespace+"/"+ms.Name, groupName, err)
return
}
// Delete from beginning (not-ready, low cost, high index first)
numToDelete := len(roleScores) - expectedCount
for i := 0; i < numToDelete; i++ {
targetName := roleScores[i].Name
klog.V(2).Infof("Scaling down role %s (priority: %d, deletion cost: %d, index: %d)",
targetName, roleScores[i].Priority, roleScores[i].DeletionCost, roleScores[i].Index)
c.DeleteRole(ctx, ms, groupName, targetRole.Name, targetName)
}
}
// scaleUpRoles handles Role scaling up.
// It creates new Roles with increasing indices starting from the current max index + 1.
func (c *ModelServingController) scaleUpRoles(ctx context.Context, ms *workloadv1alpha1.ModelServing, groupName string, targetRole workloadv1alpha1.Role, roleList []datastore.Role, expectedCount int, servingGroupOrdinal int, newRevision string) {
startingIndex := 0
if len(roleList) > 0 {
_, ordinal := utils.GetParentNameAndOrdinal(roleList[len(roleList)-1].Name)
// since roleList is already sorted in ascending order by index
startingIndex = ordinal + 1
}
// Calculate how many new Roles we need to create
toCreate := expectedCount - len(roleList)
// Role needs to scale up, and the ServingGroup status needs to be set to Scaling
err := c.store.UpdateServingGroupStatus(utils.GetNamespaceName(ms), groupName, datastore.ServingGroupScaling)
klog.V(4).Infof("Setting ServingGroup %s/%s status to Scaling for role %s scaling up", ms.Namespace+"/"+ms.Name, groupName, targetRole.Name)
if err != nil {
klog.Errorf("failed to set ServingGroup %s/%s status: %v", ms.Namespace+"/"+ms.Name, groupName, err)
return
}
klog.V(2).Infof("scaling up role %s in ServingGroup %s: creating %d new replicas", targetRole.Name, groupName, toCreate)
// Create new Roles with increasing indices
for i := 0; i < toCreate; i++ {
newIndex := startingIndex + i
// Create pods for role
err := c.CreatePodsByRole(ctx, *targetRole.DeepCopy(), ms, newIndex, servingGroupOrdinal, newRevision)
if err != nil {
klog.Errorf("create role %s for ServingGroup %s failed: %v", utils.GenerateRoleID(targetRole.Name, newIndex), groupName, err)
} else {
// Insert new Role to global storage
roleID := utils.GenerateRoleID(targetRole.Name, newIndex)
c.store.AddRole(utils.GetNamespaceName(ms), groupName, targetRole.Name, roleID, newRevision)
// Emit event for new role entering Creating state
message := fmt.Sprintf("Role %s/%s in ServingGroup %s is now Creating", targetRole.Name, roleID, groupName)
c.emitRoleStatusEvent(ms, corev1.EventTypeNormal, "RoleCreating", message)
}
}
}
// manageRoleReplicas manages the replicas of a specific role within an Serving group
// It handles both scale up and scale down operations for the role
func (c *ModelServingController) manageRoleReplicas(ctx context.Context, ms *workloadv1alpha1.ModelServing, groupName string, targetRole workloadv1alpha1.Role, servingGroupOrdinal int, newRevision string) {
// TODO: add podGroup update after gang scheduler finished
// Get all replicas of a role from storage, for example, prefill-0, prefill-1...
roleList, err := c.store.GetRoleList(utils.GetNamespaceName(ms), groupName, targetRole.Name)
if err != nil {
klog.Errorf("manageRoleReplicas: cannot get role %s in ServingGroup %s, err:%v", targetRole.Name, groupName, err)
return
}
// TODO: need to check the pod spec match the modelserving spec, if not, recreate the pod
expectedCount := int(*targetRole.Replicas)
expectedPods := 1 + int(targetRole.WorkerReplicas)
for _, roleObj := range roleList {
if roleObj.Status == datastore.RoleDeleting {
continue
}
roleIDValue := fmt.Sprintf("%s/%s/%s/%s", ms.Namespace, groupName, targetRole.Name, roleObj.Name)
pods, err := c.getPodsByIndex(RoleIDKey, roleIDValue)
if err != nil {
klog.Warningf("manageRoleReplicas: failed to list pods for role %s/%s in ServingGroup %s: %v", targetRole.Name, roleObj.Name, groupName, err)
continue
}
for _, pod := range pods {
if !utils.IsOwnedByModelServingWithUID(pod, ms.UID) {
// If the pod is not owned by the ModelServing, we do not need to handle it.
klog.Warningf("manageRoleReplicas: pod %s/%s may be left from previous same-named ModelServing %s/%s (expected UID=%s, got UID=%s), re-enqueuing",
pod.Namespace, pod.Name, ms.Namespace, ms.Name, ms.UID, pod.OwnerReferences[0].UID)
c.enqueueModelServingAfter(ms, 1*time.Second)
break
}
}
if len(pods) < expectedPods {
klog.V(2).Infof("manageRoleReplicas: role %s/%s in ServingGroup %s is missing pods (%d/%d), recreating", targetRole.Name, roleObj.Name, groupName, len(pods), expectedPods)
_, roleIndex := utils.GetParentNameAndOrdinal(roleObj.Name)
if err := c.CreatePodsByRole(ctx, *targetRole.DeepCopy(), ms, roleIndex, servingGroupOrdinal, newRevision); err != nil {
klog.Errorf("manageRoleReplicas: failed to recreate pods for role %s/%s in ServingGroup %s: %v", targetRole.Name, roleObj.Name, groupName, err)
}
}
}
// Determine whether it is a scale-up or scale-down scenario
if len(roleList) < expectedCount {
klog.V(2).Infof("manageRoleReplicas: scaling UP role %s in ServingGroup %s: current=%d, expected=%d", targetRole.Name, groupName, len(roleList), expectedCount)
c.scaleUpRoles(ctx, ms, groupName, targetRole, roleList, expectedCount, servingGroupOrdinal, newRevision)
} else if len(roleList) > expectedCount {
klog.V(2).Infof("manageRoleReplicas: scaling DOWN role %s in ServingGroup %s: current=%d, expected=%d", targetRole.Name, groupName, len(roleList), expectedCount)
c.scaleDownRoles(ctx, ms, groupName, targetRole, roleList, expectedCount)
}
}
// emitRoleStatusEvent emits a Kubernetes Event for a role-related status change.
// It is intentionally lightweight and no-op when recorder is not initialized.
func (c *ModelServingController) emitRoleStatusEvent(
ms *workloadv1alpha1.ModelServing,
eventType, reason, message string,
) {
if c == nil || c.recorder == nil || ms == nil {
return
}
c.recorder.Event(ms, eventType, reason, message)
}
func (c *ModelServingController) getModelServingAndResourceDetails(resource metav1.Object) (*workloadv1alpha1.ModelServing, string, string, string) {
ms, servingGroupName, err := c.getModelServingByChildResource(resource)
if err != nil {
if apierrors.IsNotFound(err) {
klog.V(4).Infof("modelServing of svc %s/%s has been deleted", resource.GetNamespace(), resource.GetName())
} else {
klog.Errorf("failed to get modelServing of pod %s/%s: %v", resource.GetNamespace(), resource.GetName(), err)
}
return nil, "", "", ""
}
roleName, roleID := utils.GetRoleName(resource), utils.GetRoleID(resource)
return ms, servingGroupName, roleName, roleID
}
func (c *ModelServingController) DeleteRole(ctx context.Context, ms *workloadv1alpha1.ModelServing, groupName, roleName, roleID string) {
selector := labels.SelectorFromSet(map[string]string{
workloadv1alpha1.GroupNameLabelKey: groupName,
workloadv1alpha1.RoleLabelKey: roleName,
workloadv1alpha1.RoleIDKey: roleID,
})
// If the role is already in the deletion process, no further processing will be done.
roleStatus := c.store.GetRoleStatus(utils.GetNamespaceName(ms), groupName, roleName, roleID)
if roleStatus == datastore.RoleDeleting {
return
}
err := c.store.UpdateRoleStatus(utils.GetNamespaceName(ms), groupName, roleName, roleID, datastore.RoleDeleting)
klog.V(4).Infof("Setting role %s/%s status to Deleting", ms.GetName(), roleID)
if err != nil {
klog.Errorf("failed to set role %s/%s status: %v", groupName, roleID, err)
return
}
// Emit event for role entering Deleting state.
message := fmt.Sprintf("Role %s/%s in ServingGroup %s is now Deleting", roleName, roleID, groupName)
c.emitRoleStatusEvent(ms, corev1.EventTypeNormal, "RoleDeleting", message)
var deleteErr error
defer func() {
if deleteErr == nil {
return
}
rollbackErr := c.store.UpdateRoleStatus(utils.GetNamespaceName(ms), groupName, roleName, roleID, roleStatus)
if rollbackErr != nil {
klog.ErrorS(rollbackErr, "Failed to rollback role status", "role", roleID, "group", groupName)
}
c.enqueueModelServing(ms)
}()
deleteErr = c.kubeClientSet.CoreV1().Pods(ms.Namespace).DeleteCollection(