forked from vllm-project/production-stack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvllmruntime_controller.go
More file actions
1406 lines (1263 loc) · 39.8 KB
/
Copy pathvllmruntime_controller.go
File metadata and controls
1406 lines (1263 loc) · 39.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright 2024.
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 permissions and
limitations under the License.
*/
package controller
import (
"context"
"fmt"
"maps"
"reflect"
"strings"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/meta"
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/intstr"
"k8s.io/client-go/util/retry"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/log"
productionstackv1alpha1 "production-stack/api/v1alpha1"
)
// VLLMRuntimeReconciler reconciles a VLLMRuntime object
type VLLMRuntimeReconciler struct {
client.Client
Scheme *runtime.Scheme
}
// +kubebuilder:rbac:groups=production-stack.vllm.ai,resources=vllmruntimes,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=production-stack.vllm.ai,resources=vllmruntimes/status,verbs=get;update;patch
// +kubebuilder:rbac:groups=production-stack.vllm.ai,resources=vllmruntimes/finalizers,verbs=update
// +kubebuilder:rbac:groups=apps,resources=deployments,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=core,resources=configmaps,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=core,resources=services,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=core,resources=persistentvolumeclaims,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=keda.sh,resources=scaledobjects,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=production-stack.vllm.ai,resources=vllmruntimes/scale,verbs=get;update;patch
// Reconcile is part of the main kubernetes reconciliation loop which aims to
// move the current state of the cluster closer to the desired state.
func (r *VLLMRuntimeReconciler) Reconcile(
ctx context.Context,
req ctrl.Request,
) (ctrl.Result, error) {
log := log.FromContext(ctx)
// Fetch the VLLMRuntime instance
vllmRuntime := &productionstackv1alpha1.VLLMRuntime{}
err := r.Get(ctx, req.NamespacedName, vllmRuntime)
if err != nil {
if errors.IsNotFound(err) {
// Request object not found, could have been deleted after reconcile request.
// Return and don't requeue
log.Info("VLLMRuntime resource not found. Ignoring since object must be deleted")
return ctrl.Result{}, nil
}
// Error reading the object - requeue the request.
log.Error(err, "Failed to get VLLMRuntime")
return ctrl.Result{}, err
}
// Check if the service already exists, if not create a new one
foundService := &corev1.Service{}
err = r.Get(
ctx,
types.NamespacedName{Name: vllmRuntime.Name, Namespace: vllmRuntime.Namespace},
foundService,
)
if err != nil && errors.IsNotFound(err) {
// Define a new service
svc := r.serviceForVLLMRuntime(vllmRuntime)
log.Info(
"Creating a new Service",
"Service.Namespace",
svc.Namespace,
"Service.Name",
svc.Name,
)
err = r.Create(ctx, svc)
if err != nil {
log.Error(
err,
"Failed to create new Service",
"Service.Namespace",
svc.Namespace,
"Service.Name",
svc.Name,
)
return ctrl.Result{}, err
}
// Service created successfully - return and requeue
return ctrl.Result{Requeue: true}, nil
} else if err != nil {
log.Error(err, "Failed to get Service")
return ctrl.Result{}, err
}
// Update the service if needed
if r.serviceNeedsUpdate(foundService, vllmRuntime) {
log.Info(
"Updating Service",
"Service.Namespace",
foundService.Namespace,
"Service.Name",
foundService.Name,
)
// Create new service spec
newSvc := r.serviceForVLLMRuntime(vllmRuntime)
err = r.Update(ctx, newSvc)
if err != nil {
log.Error(
err,
"Failed to update Service",
"Service.Namespace",
foundService.Namespace,
"Service.Name",
foundService.Name,
)
return ctrl.Result{}, err
}
// Service updated successfully - return and requeue
return ctrl.Result{Requeue: true}, nil
}
// Handle PVC if storage is enabled
if vllmRuntime.Spec.StorageConfig.Enabled {
// Check if the PVC already exists, if not create a new one
foundPVC := &corev1.PersistentVolumeClaim{}
err = r.Get(
ctx,
types.NamespacedName{Name: vllmRuntime.Name, Namespace: vllmRuntime.Namespace},
foundPVC,
)
if err != nil && errors.IsNotFound(err) {
// Define a new PVC
pvc := r.pvcForVLLMRuntime(vllmRuntime)
log.Info("Creating a new PVC", "PVC.Namespace", pvc.Namespace, "PVC.Name", pvc.Name)
err = r.Create(ctx, pvc)
if err != nil {
log.Error(
err,
"Failed to create new PVC",
"PVC.Namespace",
pvc.Namespace,
"PVC.Name",
pvc.Name,
)
return ctrl.Result{}, err
}
// PVC created successfully - return and requeue
return ctrl.Result{Requeue: true}, nil
} else if err != nil {
log.Error(err, "Failed to get PVC")
return ctrl.Result{}, err
}
// Update the PVC if needed
if r.pvcNeedsUpdate(foundPVC, vllmRuntime) {
log.Info("Updating PVC", "PVC.Namespace", foundPVC.Namespace, "PVC.Name", foundPVC.Name)
// Create new PVC spec
newPVC := r.pvcForVLLMRuntime(vllmRuntime)
err = r.Update(ctx, newPVC)
if err != nil {
log.Error(
err,
"Failed to update PVC",
"PVC.Namespace",
foundPVC.Namespace,
"PVC.Name",
foundPVC.Name,
)
return ctrl.Result{}, err
}
// PVC updated successfully - return and requeue
return ctrl.Result{Requeue: true}, nil
}
}
if vllmRuntime.Spec.Model.ChatTemplate != "" {
foundCM := &corev1.ConfigMap{}
err := r.Get(ctx, types.NamespacedName{
Name: vllmRuntime.Name + "-chat-template",
Namespace: vllmRuntime.Namespace,
}, foundCM)
if err != nil {
if errors.IsNotFound(err) {
ct := r.configMapForVLLMRuntime(vllmRuntime)
log.Info(
"Creating a new ConfigMap",
"ConfigMap.Namespace",
ct.Namespace,
"ConfigMap.Name",
ct.Name,
)
if err := r.Create(ctx, ct); err != nil {
log.Error(
err,
"failed to create new ConfigMap",
"ConfigMap.Namespace",
ct.Namespace,
"ConfigMap.Name",
ct.Name,
)
return ctrl.Result{}, err
} else {
return ctrl.Result{Requeue: true}, nil
}
}
return ctrl.Result{}, err
}
if r.configMapNeedsUpdate(foundCM, vllmRuntime) {
log.Info(
"Updating ConfigMap",
"ConfigMap.Namespace",
foundCM.Namespace,
"ConfigMap.Name",
foundCM.Name,
)
newCT := r.configMapForVLLMRuntime(vllmRuntime)
if err := r.Update(ctx, newCT); err != nil {
log.Error(
err,
"failed to update ConfigMap",
"cm.Namespace",
foundCM.Namespace,
"cm.Name",
foundCM.Name,
)
return ctrl.Result{}, err
}
return ctrl.Result{Requeue: true}, nil
}
}
// Check if the deployment already exists, if not create a new one
found := &appsv1.Deployment{}
err = r.Get(
ctx,
types.NamespacedName{Name: vllmRuntime.Name, Namespace: vllmRuntime.Namespace},
found,
)
if err != nil && errors.IsNotFound(err) {
// Define a new deployment
dep := r.deploymentForVLLMRuntime(vllmRuntime)
log.Info(
"Creating a new Deployment",
"Deployment.Namespace",
dep.Namespace,
"Deployment.Name",
dep.Name,
)
err = r.Create(ctx, dep)
if err != nil {
log.Error(
err,
"Failed to create new Deployment",
"Deployment.Namespace",
dep.Namespace,
"Deployment.Name",
dep.Name,
)
return ctrl.Result{}, err
}
// Deployment created successfully - return and requeue
return ctrl.Result{Requeue: true}, nil
} else if err != nil {
log.Error(err, "Failed to get Deployment")
return ctrl.Result{}, err
}
// Update the deployment if needed
if r.deploymentNeedsUpdate(ctx, found, vllmRuntime) {
log.Info(
"Updating Deployment",
"Deployment.Namespace",
found.Namespace,
"Deployment.Name",
found.Name,
)
// Create new deployment spec
newDep := r.deploymentForVLLMRuntime(vllmRuntime)
err = r.Update(ctx, newDep)
if err != nil {
log.Error(
err,
"Failed to update Deployment",
"Deployment.Namespace",
found.Namespace,
"Deployment.Name",
found.Name,
)
return ctrl.Result{}, err
}
// Deployment updated successfully - return and requeue
return ctrl.Result{Requeue: true}, nil
}
// Create, update or delete KEDA ScaledObject
if vllmRuntime.Spec.AutoscalingConfig != nil && vllmRuntime.Spec.AutoscalingConfig.Enabled {
cfg := vllmRuntime.Spec.AutoscalingConfig
if *cfg.MinReplicas > cfg.MaxReplicas {
log.Error(nil, "Invalid autoscaling config: minReplicas must be <= maxReplicas",
"minReplicas", *cfg.MinReplicas, "maxReplicas", cfg.MaxReplicas)
return ctrl.Result{}, fmt.Errorf(
"minReplicas (%d) must be <= maxReplicas (%d)",
*cfg.MinReplicas,
cfg.MaxReplicas,
)
}
if cfg.MaxReplicas < vllmRuntime.Spec.DeploymentConfig.Replicas {
log.Error(
nil,
"Invalid autoscaling config: maxReplicas must be >= deploymentConfig.replicas",
"maxReplicas",
cfg.MaxReplicas,
"replicas",
vllmRuntime.Spec.DeploymentConfig.Replicas,
)
return ctrl.Result{}, fmt.Errorf(
"maxReplicas (%d) must be >= deploymentConfig.replicas (%d)",
cfg.MaxReplicas,
vllmRuntime.Spec.DeploymentConfig.Replicas,
)
}
if err := r.reconcileScaledObject(ctx, vllmRuntime); err != nil {
log.Error(err, "Failed to reconcile ScaledObject")
return ctrl.Result{}, err
}
} else {
scaledObject := &unstructured.Unstructured{}
scaledObject.SetAPIVersion("keda.sh/v1alpha1")
scaledObject.SetKind("ScaledObject")
scaledObject.SetName(vllmRuntime.Name + "-scaledobject")
scaledObject.SetNamespace(vllmRuntime.Namespace)
// Best-effort cleanup of a stale ScaledObject when autoscaling is
// disabled. Tolerate IsNoMatchError so the reconcile still succeeds on
// clusters where KEDA is not installed (the keda.sh API group is not
// registered): there is nothing to delete, and requiring KEDA here
// would make the operator unusable on non-autoscaling clusters.
if err := r.Delete(ctx, scaledObject); err != nil &&
!errors.IsNotFound(err) && !meta.IsNoMatchError(err) {
log.Error(err, "Failed to delete ScaledObject")
return ctrl.Result{}, err
}
}
// Update the status
if err := r.updateStatus(ctx, vllmRuntime, found); err != nil {
log.Error(err, "Failed to update VLLMRuntime status")
return ctrl.Result{}, err
}
return ctrl.Result{}, nil
}
// deploymentForVLLMRuntime returns a VLLMRuntime Deployment object
func (r *VLLMRuntimeReconciler) deploymentForVLLMRuntime(
vllmRuntime *productionstackv1alpha1.VLLMRuntime,
) *appsv1.Deployment {
labels := map[string]string{"app": vllmRuntime.Name}
maps.Copy(labels, vllmRuntime.Labels)
// Define probes
readinessProbe := &corev1.Probe{
ProbeHandler: corev1.ProbeHandler{
HTTPGet: &corev1.HTTPGetAction{
Path: "/health",
Port: intstr.FromInt(int(vllmRuntime.Spec.VLLMConfig.Port)),
Scheme: corev1.URISchemeHTTP,
},
},
InitialDelaySeconds: 10,
PeriodSeconds: 20,
TimeoutSeconds: 5,
SuccessThreshold: 1,
FailureThreshold: 10,
}
livenessProbe := &corev1.Probe{
ProbeHandler: corev1.ProbeHandler{
HTTPGet: &corev1.HTTPGetAction{
Path: "/health",
Port: intstr.FromInt(int(vllmRuntime.Spec.VLLMConfig.Port)),
Scheme: corev1.URISchemeHTTP,
},
},
InitialDelaySeconds: 10,
PeriodSeconds: 20,
TimeoutSeconds: 3,
SuccessThreshold: 1,
FailureThreshold: 10,
}
startupProbe := &corev1.Probe{
ProbeHandler: corev1.ProbeHandler{
HTTPGet: &corev1.HTTPGetAction{
Path: "/health",
Port: intstr.FromInt(int(vllmRuntime.Spec.VLLMConfig.Port)),
Scheme: corev1.URISchemeHTTP,
},
},
InitialDelaySeconds: 120,
PeriodSeconds: 20,
TimeoutSeconds: 3,
FailureThreshold: 100,
}
// Build command line arguments
args := []string{
vllmRuntime.Spec.Model.ModelURL,
"--host",
"0.0.0.0",
"--port",
fmt.Sprintf("%d", vllmRuntime.Spec.VLLMConfig.Port),
}
if vllmRuntime.Spec.Model.EnableLoRA {
args = append(args, "--enable-lora")
}
if vllmRuntime.Spec.Model.EnableTool {
args = append(args, "--enable-auto-tool-choice")
}
if vllmRuntime.Spec.Model.ToolCallParser != "" {
args = append(args, "--tool-call-parser", vllmRuntime.Spec.Model.ToolCallParser)
}
if vllmRuntime.Spec.VLLMConfig.EnableChunkedPrefill {
args = append(args, "--enable-chunked-prefill")
} else {
args = append(args, "--no-enable-chunked-prefill")
}
if vllmRuntime.Spec.VLLMConfig.EnablePrefixCaching {
args = append(args, "--enable-prefix-caching")
} else {
args = append(args, "--no-enable-prefix-caching")
}
if vllmRuntime.Spec.Model.MaxModelLen > 0 {
args = append(
args,
"--max-model-len",
fmt.Sprintf("%d", vllmRuntime.Spec.Model.MaxModelLen),
)
}
if vllmRuntime.Spec.Model.DType != "" {
args = append(args, "--dtype", vllmRuntime.Spec.Model.DType)
}
if vllmRuntime.Spec.VLLMConfig.TensorParallelSize > 0 {
args = append(
args,
"--tensor-parallel-size",
fmt.Sprintf("%d", vllmRuntime.Spec.VLLMConfig.TensorParallelSize),
)
}
if vllmRuntime.Spec.Model.MaxNumSeqs > 0 {
args = append(args, "--max-num-seqs", fmt.Sprintf("%d", vllmRuntime.Spec.Model.MaxNumSeqs))
}
if vllmRuntime.Spec.VLLMConfig.GpuMemoryUtilization != "" {
args = append(
args,
"--gpu_memory_utilization",
vllmRuntime.Spec.VLLMConfig.GpuMemoryUtilization,
)
}
if vllmRuntime.Spec.VLLMConfig.MaxLoras > 0 {
args = append(args, "--max_loras", fmt.Sprintf("%d", vllmRuntime.Spec.VLLMConfig.MaxLoras))
}
if vllmRuntime.Spec.VLLMConfig.ExtraArgs != nil {
args = append(args, vllmRuntime.Spec.VLLMConfig.ExtraArgs...)
}
if vllmRuntime.Spec.Model.ChatTemplate != "" {
args = append(args, "--chat-template", "/etc/chat-template.json")
}
// Build environment variables
env := []corev1.EnvVar{}
if vllmRuntime.Spec.VLLMConfig.V1 {
env = append(env, corev1.EnvVar{
Name: "VLLM_USE_V1",
Value: "1",
})
} else {
env = append(env, corev1.EnvVar{
Name: "VLLM_USE_V1",
Value: "0",
})
}
if vllmRuntime.Spec.Model.EnableLoRA {
env = append(env,
corev1.EnvVar{
Name: "VLLM_ALLOW_RUNTIME_LORA_UPDATING",
Value: "True",
},
)
}
// LM Cache configuration
if vllmRuntime.Spec.LMCacheConfig.Enabled {
env = append(env,
corev1.EnvVar{
Name: "LMCACHE_LOG_LEVEL",
Value: "DEBUG",
},
corev1.EnvVar{
Name: "LMCACHE_USE_EXPERIMENTAL",
Value: "True",
},
corev1.EnvVar{
Name: "VLLM_RPC_TIMEOUT",
Value: "1000000",
},
)
// Add KV transfer config based on V1 flag
var lmcache_config string
if vllmRuntime.Spec.VLLMConfig.V1 {
lmcache_config = `{"kv_connector":"LMCacheConnectorV1","kv_role":"kv_both"}`
} else {
lmcache_config = `{"kv_connector":"LMCacheConnector","kv_role":"kv_both"}`
}
args = append(args, "--kv-transfer-config", lmcache_config)
if vllmRuntime.Spec.LMCacheConfig.CPUOffloadingBufferSize != "" {
env = append(env,
corev1.EnvVar{
Name: "LMCACHE_LOCAL_CPU",
Value: "True",
},
corev1.EnvVar{
Name: "LMCACHE_MAX_LOCAL_CPU_SIZE",
Value: vllmRuntime.Spec.LMCacheConfig.CPUOffloadingBufferSize,
},
)
}
if vllmRuntime.Spec.LMCacheConfig.DiskOffloadingBufferSize != "" {
env = append(env,
corev1.EnvVar{
Name: "LMCACHE_LOCAL_DISK",
Value: "True",
},
corev1.EnvVar{
Name: "LMCACHE_MAX_LOCAL_DISK_SIZE",
Value: vllmRuntime.Spec.LMCacheConfig.DiskOffloadingBufferSize,
},
)
}
if vllmRuntime.Spec.LMCacheConfig.RemoteURL != "" {
env = append(env,
corev1.EnvVar{
Name: "LMCACHE_REMOTE_URL",
Value: vllmRuntime.Spec.LMCacheConfig.RemoteURL,
},
corev1.EnvVar{
Name: "LMCACHE_REMOTE_SERDE",
Value: vllmRuntime.Spec.LMCacheConfig.RemoteSerde,
},
)
}
}
// Add user-defined environment variables
if vllmRuntime.Spec.VLLMConfig.Env != nil {
for _, e := range vllmRuntime.Spec.VLLMConfig.Env {
env = append(env, corev1.EnvVar{
Name: e.Name,
Value: e.Value,
})
}
}
// Build resource requirements
resources := corev1.ResourceRequirements{
Requests: corev1.ResourceList{},
Limits: corev1.ResourceList{},
}
if vllmRuntime.Spec.DeploymentConfig.Resources.CPU != "" {
resources.Requests[corev1.ResourceCPU] = resource.MustParse(
vllmRuntime.Spec.DeploymentConfig.Resources.CPU,
)
resources.Limits[corev1.ResourceCPU] = resource.MustParse(
vllmRuntime.Spec.DeploymentConfig.Resources.CPU,
)
}
if vllmRuntime.Spec.DeploymentConfig.Resources.Memory != "" {
resources.Requests[corev1.ResourceMemory] = resource.MustParse(
vllmRuntime.Spec.DeploymentConfig.Resources.Memory,
)
resources.Limits[corev1.ResourceMemory] = resource.MustParse(
vllmRuntime.Spec.DeploymentConfig.Resources.Memory,
)
}
if vllmRuntime.Spec.DeploymentConfig.Resources.GPU != "" {
// Parse GPU resource as a decimal value
// Determine which GPU type to use (default nvidia.com/gpu)
gpuType := "nvidia.com/gpu"
if vllmRuntime.Spec.DeploymentConfig.Resources.GPUType != "" {
gpuType = vllmRuntime.Spec.DeploymentConfig.Resources.GPUType
}
gpuResource := resource.MustParse(vllmRuntime.Spec.DeploymentConfig.Resources.GPU)
resources.Requests[corev1.ResourceName(gpuType)] = gpuResource
resources.Limits[corev1.ResourceName(gpuType)] = gpuResource
}
// Get the image from Image spec or use default
image := vllmRuntime.Spec.DeploymentConfig.Image.Registry + "/" + vllmRuntime.Spec.DeploymentConfig.Image.Name
// Get the image pull policy
imagePullPolicy := corev1.PullIfNotPresent
if vllmRuntime.Spec.DeploymentConfig.Image.PullPolicy != "" {
imagePullPolicy = corev1.PullPolicy(vllmRuntime.Spec.DeploymentConfig.Image.PullPolicy)
}
// Build image pull secrets
var imagePullSecrets []corev1.LocalObjectReference
if vllmRuntime.Spec.DeploymentConfig.Image.PullSecretName != "" {
imagePullSecrets = append(imagePullSecrets, corev1.LocalObjectReference{
Name: vllmRuntime.Spec.DeploymentConfig.Image.PullSecretName,
})
}
if vllmRuntime.Spec.Model.HFTokenSecret.HFTokenSecretName != "" {
env = append(env, corev1.EnvVar{
Name: "HF_TOKEN",
ValueFrom: &corev1.EnvVarSource{
SecretKeyRef: &corev1.SecretKeySelector{
LocalObjectReference: corev1.LocalObjectReference{
Name: vllmRuntime.Spec.Model.HFTokenSecret.HFTokenSecretName,
},
Key: vllmRuntime.Spec.Model.HFTokenSecret.HFTokenKeyName,
},
},
})
}
// Build volumes and volume mounts if storage is enabled
var volumes []corev1.Volume
var volumeMounts []corev1.VolumeMount
if vllmRuntime.Spec.StorageConfig.Enabled {
volumeName := "pvc-storage"
if vllmRuntime.Spec.StorageConfig.VolumeName != "" {
volumeName = vllmRuntime.Spec.StorageConfig.VolumeName
}
mountPath := "/data"
if vllmRuntime.Spec.StorageConfig.MountPath != "" {
mountPath = vllmRuntime.Spec.StorageConfig.MountPath
}
volumes = append(volumes, corev1.Volume{
Name: volumeName,
VolumeSource: corev1.VolumeSource{
PersistentVolumeClaim: &corev1.PersistentVolumeClaimVolumeSource{
ClaimName: vllmRuntime.Name,
},
},
})
volumeMounts = append(volumeMounts, corev1.VolumeMount{
Name: volumeName,
MountPath: mountPath,
})
}
if vllmRuntime.Spec.Model.ChatTemplate != "" {
volumeName := "chat-template"
mountPath := "/etc/chat-template.json"
volumes = append(volumes, corev1.Volume{
Name: volumeName,
VolumeSource: corev1.VolumeSource{
ConfigMap: &corev1.ConfigMapVolumeSource{
LocalObjectReference: corev1.LocalObjectReference{
Name: vllmRuntime.Name + "-" + volumeName,
},
Items: []corev1.KeyToPath{
{
Key: "chatTemplate",
Path: "chat_template.json",
},
},
},
},
})
volumeMounts = append(volumeMounts, corev1.VolumeMount{
Name: volumeName,
MountPath: mountPath,
SubPath: "chat_template.json",
})
}
var affinity *corev1.Affinity
if vllmRuntime.Spec.DeploymentConfig.NodeSelectorTerms != nil {
affinity = &corev1.Affinity{
NodeAffinity: &corev1.NodeAffinity{
RequiredDuringSchedulingIgnoredDuringExecution: &corev1.NodeSelector{
NodeSelectorTerms: vllmRuntime.Spec.DeploymentConfig.NodeSelectorTerms,
},
},
}
}
containers := []corev1.Container{
{
Name: "vllm",
Image: image,
ImagePullPolicy: imagePullPolicy,
Command: []string{"/opt/venv/bin/vllm", "serve"},
Args: args,
Env: env,
Ports: []corev1.ContainerPort{
{
Name: "http",
ContainerPort: vllmRuntime.Spec.VLLMConfig.Port,
},
},
Resources: resources,
VolumeMounts: volumeMounts,
ReadinessProbe: readinessProbe,
StartupProbe: startupProbe,
LivenessProbe: livenessProbe,
},
}
if vllmRuntime.Spec.DeploymentConfig.SidecarConfig.Enabled {
containers = append(containers, r.buildSidecarContainer(vllmRuntime))
}
dep := &appsv1.Deployment{
ObjectMeta: metav1.ObjectMeta{
Name: vllmRuntime.Name,
Namespace: vllmRuntime.Namespace,
},
Spec: appsv1.DeploymentSpec{
Replicas: &vllmRuntime.Spec.DeploymentConfig.Replicas,
Strategy: appsv1.DeploymentStrategy{
Type: appsv1.DeploymentStrategyType(
vllmRuntime.Spec.DeploymentConfig.DeployStrategy,
),
},
Selector: &metav1.LabelSelector{
MatchLabels: labels,
},
Template: corev1.PodTemplateSpec{
ObjectMeta: metav1.ObjectMeta{
Labels: labels,
Annotations: vllmRuntime.Spec.DeploymentConfig.PodAnnotations,
},
Spec: corev1.PodSpec{
RuntimeClassName: &vllmRuntime.Spec.DeploymentConfig.RuntimeClass,
Affinity: affinity,
Tolerations: vllmRuntime.Spec.DeploymentConfig.Toleration,
ImagePullSecrets: imagePullSecrets,
Volumes: volumes,
Containers: containers,
},
},
},
}
// Set the owner reference
ctrl.SetControllerReference(vllmRuntime, dep, r.Scheme)
return dep
}
// buildSidecarContainer builds the sidecar container configuration
func (r *VLLMRuntimeReconciler) buildSidecarContainer(
vllmRuntime *productionstackv1alpha1.VLLMRuntime,
) corev1.Container {
sidecarConfig := vllmRuntime.Spec.DeploymentConfig.SidecarConfig
// Build sidecar volume mounts
var sidecarVolumeMounts []corev1.VolumeMount
mountPath := "/data"
// Add shared storage volume mount if storage is enabled
if vllmRuntime.Spec.StorageConfig.Enabled {
volumeName := "pvc-storage"
if vllmRuntime.Spec.StorageConfig.VolumeName != "" {
volumeName = vllmRuntime.Spec.StorageConfig.VolumeName
}
if sidecarConfig.MountPath != "" {
mountPath = sidecarConfig.MountPath
}
sidecarVolumeMounts = append(sidecarVolumeMounts, corev1.VolumeMount{
Name: volumeName,
MountPath: mountPath,
})
}
// Build sidecar environment variables
var sidecarEnv []corev1.EnvVar
sidecarEnv = append(sidecarEnv, corev1.EnvVar{
Name: "PORT",
Value: "30090",
})
sidecarEnv = append(sidecarEnv, corev1.EnvVar{
Name: "LORA_DOWNLOAD_BASE_DIR",
Value: mountPath + "/lora-adapters",
})
for _, envVar := range sidecarConfig.Env {
sidecarEnv = append(sidecarEnv, corev1.EnvVar{
Name: envVar.Name,
Value: envVar.Value,
})
}
// Build sidecar resources
sidecarResources := corev1.ResourceRequirements{
Requests: corev1.ResourceList{},
Limits: corev1.ResourceList{},
}
if sidecarConfig.Resources.CPU != "" {
sidecarResources.Requests[corev1.ResourceCPU] = resource.MustParse(
sidecarConfig.Resources.CPU,
)
sidecarResources.Limits[corev1.ResourceCPU] = resource.MustParse(
sidecarConfig.Resources.CPU,
)
} else {
sidecarResources.Requests[corev1.ResourceCPU] = resource.MustParse("0.5")
sidecarResources.Limits[corev1.ResourceCPU] = resource.MustParse("0.5")
}
if sidecarConfig.Resources.Memory != "" {
sidecarResources.Requests[corev1.ResourceMemory] = resource.MustParse(
sidecarConfig.Resources.Memory,
)
sidecarResources.Limits[corev1.ResourceMemory] = resource.MustParse(
sidecarConfig.Resources.Memory,
)
} else {
sidecarResources.Requests[corev1.ResourceMemory] = resource.MustParse("128Mi")
sidecarResources.Limits[corev1.ResourceMemory] = resource.MustParse("128Mi")
}
if sidecarConfig.Resources.GPU != "" {
gpuType := "nvidia.com/gpu"
if sidecarConfig.Resources.GPUType != "" {
gpuType = sidecarConfig.Resources.GPUType
}
gpuResource := resource.MustParse(sidecarConfig.Resources.GPU)
sidecarResources.Requests[corev1.ResourceName(gpuType)] = gpuResource
sidecarResources.Limits[corev1.ResourceName(gpuType)] = gpuResource
} else {
gpuType := "nvidia.com/gpu"
if sidecarConfig.Resources.GPUType != "" {
gpuType = sidecarConfig.Resources.GPUType
}
zeroQty := resource.MustParse("0")
sidecarResources.Requests[corev1.ResourceName(gpuType)] = zeroQty
sidecarResources.Limits[corev1.ResourceName(gpuType)] = zeroQty
}
// Get sidecar image
sidecarImage := sidecarConfig.Image.Registry + "/" + sidecarConfig.Image.Name
// Get sidecar image pull policy
sidecarImagePullPolicy := corev1.PullIfNotPresent
if sidecarConfig.Image.PullPolicy != "" {
sidecarImagePullPolicy = corev1.PullPolicy(sidecarConfig.Image.PullPolicy)
}
// Build sidecar container
sidecarContainer := corev1.Container{
Name: sidecarConfig.Name,
Image: sidecarImage,
ImagePullPolicy: sidecarImagePullPolicy,
Command: sidecarConfig.Command,
Args: sidecarConfig.Args,
Env: sidecarEnv,
Resources: sidecarResources,
VolumeMounts: sidecarVolumeMounts,
}
return sidecarContainer
}
// deploymentNeedsUpdate checks if the deployment needs to be updated
func (r *VLLMRuntimeReconciler) deploymentNeedsUpdate(
ctx context.Context,
dep *appsv1.Deployment,
vr *productionstackv1alpha1.VLLMRuntime,
) bool {
log := log.FromContext(ctx)
// Generate the expected deployment
expectedDep := r.deploymentForVLLMRuntime(vr)
// Compare replicas
if *dep.Spec.Replicas != vr.Spec.DeploymentConfig.Replicas {
return true
}
// Compare model URL
expectedModelURL := vr.Spec.Model.ModelURL
actualModelURL := ""
// For vllm serve, the model URL is the first argument after the command
if len(dep.Spec.Template.Spec.Containers[0].Args) > 0 {
actualModelURL = dep.Spec.Template.Spec.Containers[0].Args[0]
}
if expectedModelURL != actualModelURL {
log.Info("Model URL mismatch", "expected", expectedModelURL, "actual", actualModelURL)
return true
}
// Compare port
expectedPort := vr.Spec.VLLMConfig.Port
actualPort := dep.Spec.Template.Spec.Containers[0].Ports[0].ContainerPort
if expectedPort != actualPort {
log.Info("Port mismatch", "expected", expectedPort, "actual", actualPort)
return true
}
// Compare image
if expectedDep.Spec.Template.Spec.Containers[0].Image != dep.Spec.Template.Spec.Containers[0].Image {
log.Info(
"Image mismatch",
"expected",
expectedDep.Spec.Template.Spec.Containers[0].Image,
"actual",
dep.Spec.Template.Spec.Containers[0].Image,
)
return true
}
// Compare resources
expectedResources := expectedDep.Spec.Template.Spec.Containers[0].Resources
actualResources := dep.Spec.Template.Spec.Containers[0].Resources
if !reflect.DeepEqual(expectedResources, actualResources) {
log.Info("Resources mismatch", "expected", expectedResources, "actual", actualResources)
return true
}
// Compare LM Cache configuration
expectedLMCacheConfig := vr.Spec.LMCacheConfig
actualLMCacheConfig := dep.Spec.Template.Spec.Containers[0].Env
// Extract actual values from environment variables
actualEnabled := false
actualCPUOffloadingBufferSize := ""
actualDiskOffloadingBufferSize := ""
actualRemoteURL := ""
actualRemoteSerde := ""
for _, env := range actualLMCacheConfig {