-
Notifications
You must be signed in to change notification settings - Fork 209
Expand file tree
/
Copy pathvirtualmcpserver_controller.go
More file actions
2447 lines (2165 loc) · 90.7 KB
/
virtualmcpserver_controller.go
File metadata and controls
2447 lines (2165 loc) · 90.7 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 controllers contains the reconciliation logic for the VirtualMCPServer custom resource.
// It handles the creation, update, and deletion of Virtual MCP Servers in Kubernetes.
package controllers
import (
"context"
"encoding/json"
"fmt"
"maps"
"net/http"
"reflect"
"strings"
"sync"
"time"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
rbacv1 "k8s.io/api/rbac/v1"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
"k8s.io/client-go/tools/record"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/builder"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/event"
"sigs.k8s.io/controller-runtime/pkg/handler"
"sigs.k8s.io/controller-runtime/pkg/log"
"sigs.k8s.io/controller-runtime/pkg/predicate"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
mcpv1alpha1 "github.com/stacklok/toolhive/cmd/thv-operator/api/v1alpha1"
ctrlutil "github.com/stacklok/toolhive/cmd/thv-operator/pkg/controllerutil"
"github.com/stacklok/toolhive/cmd/thv-operator/pkg/runconfig/configmap/checksum"
"github.com/stacklok/toolhive/cmd/thv-operator/pkg/virtualmcpserverstatus"
"github.com/stacklok/toolhive/pkg/groups"
vmcptypes "github.com/stacklok/toolhive/pkg/vmcp"
"github.com/stacklok/toolhive/pkg/vmcp/aggregator"
"github.com/stacklok/toolhive/pkg/vmcp/auth/converters"
authtypes "github.com/stacklok/toolhive/pkg/vmcp/auth/types"
vmcpconfig "github.com/stacklok/toolhive/pkg/vmcp/config"
"github.com/stacklok/toolhive/pkg/vmcp/workloads"
)
const (
// OutgoingAuthSourceDiscovered indicates that auth configs should be automatically discovered from MCPServers
OutgoingAuthSourceDiscovered = "discovered"
// OutgoingAuthSourceInline indicates that auth configs should be explicitly specified
OutgoingAuthSourceInline = "inline"
// defaultHealthCheckTimeout is the default timeout for health check operations
// This matches the default timeout used by the vmcp health monitor
defaultHealthCheckTimeout = 10 * time.Second
// minHealthCheckQueryTimeout is the minimum timeout for querying the vmcp health endpoint
minHealthCheckQueryTimeout = 5 * time.Second
// healthCheckRequeueMultiplier determines how frequently the controller reconciles
// to fetch updated health status. Set to 2x the health check interval to balance
// freshness with reconciliation overhead.
healthCheckRequeueMultiplier = 2
// healthStatusCacheTTL is the time-to-live for cached health status responses
// Short TTL ensures relatively fresh data while reducing HTTP overhead from frequent reconciliations
healthStatusCacheTTL = 10 * time.Second
)
// VirtualMCPServerReconciler reconciles a VirtualMCPServer object
//
// Resource Cleanup Strategy:
// VirtualMCPServer does NOT use finalizers because all managed resources have owner references
// set via controllerutil.SetControllerReference. Kubernetes automatically cascade-deletes
// owned resources when the VirtualMCPServer is deleted. Managed resources include:
// - Deployment (owned)
// - Service (owned)
// - ConfigMap for vmcp config (owned)
// - ServiceAccount, Role, RoleBinding via ctrlutil.EnsureRBACResource (owned)
//
// This differs from MCPServer which uses finalizers to explicitly delete resources that
// may not have owner references (StatefulSet, headless Service, RunConfig ConfigMap).
type VirtualMCPServerReconciler struct {
client.Client
Scheme *runtime.Scheme
Recorder record.EventRecorder
PlatformDetector *ctrlutil.SharedPlatformDetector
// healthStatusCache caches vmcp health endpoint responses to reduce HTTP overhead
// Initialized in SetupWithManager before reconciliation starts (controller-runtime contract)
healthStatusCache map[string]*healthStatusCacheEntry
healthStatusCacheMutex sync.RWMutex
}
// healthStatusCacheEntry stores cached health status with expiration time
type healthStatusCacheEntry struct {
healthStatus map[string]*BackendHealthInfo
expiresAt time.Time
}
// +kubebuilder:rbac:groups=toolhive.stacklok.dev,resources=virtualmcpservers,verbs=get;list;watch;create;update;patch;delete
// +kubebuilder:rbac:groups=toolhive.stacklok.dev,resources=virtualmcpservers/status,verbs=get;update;patch
// +kubebuilder:rbac:groups=toolhive.stacklok.dev,resources=mcpgroups,verbs=get;list;watch
// +kubebuilder:rbac:groups=toolhive.stacklok.dev,resources=mcpservers,verbs=get;list;watch
// +kubebuilder:rbac:groups=toolhive.stacklok.dev,resources=mcpexternalauthconfigs,verbs=get;list;watch
// +kubebuilder:rbac:groups=toolhive.stacklok.dev,resources=mcptoolconfigs,verbs=get;list;watch
// +kubebuilder:rbac:groups=toolhive.stacklok.dev,resources=virtualmcpcompositetooldefinitions,verbs=get;list;watch
// +kubebuilder:rbac:groups="",resources=configmaps,verbs=create;delete;get;list;patch;update;watch
// +kubebuilder:rbac:groups="",resources=services,verbs=create;delete;get;list;patch;update;watch;apply
// +kubebuilder:rbac:groups="rbac.authorization.k8s.io",resources=roles,verbs=create;delete;get;list;patch;update;watch
// +kubebuilder:rbac:groups="rbac.authorization.k8s.io",resources=rolebindings,verbs=create;delete;get;list;patch;update;watch
// +kubebuilder:rbac:groups="",resources=events,verbs=create;patch
// +kubebuilder:rbac:groups="",resources=secrets,verbs=get;list;watch
// +kubebuilder:rbac:groups=apps,resources=deployments,verbs=create;delete;get;list;patch;update;watch
// +kubebuilder:rbac:groups="",resources=serviceaccounts,verbs=create;delete;get;list;patch;update;watch
// Reconcile is part of the main kubernetes reconciliation loop which aims to
// move the current state of the cluster closer to the desired state.
//
//nolint:gocyclo // Complexity is inherent to reconciliation logic
func (r *VirtualMCPServerReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
ctxLogger := log.FromContext(ctx)
// Fetch the VirtualMCPServer instance
vmcp := &mcpv1alpha1.VirtualMCPServer{}
err := r.Get(ctx, req.NamespacedName, vmcp)
if err != nil {
if errors.IsNotFound(err) {
ctxLogger.Info("VirtualMCPServer resource not found. Ignoring since object must be deleted")
return ctrl.Result{}, nil
}
ctxLogger.Error(err, "Failed to get VirtualMCPServer")
return ctrl.Result{}, err
}
// Create status manager for batched updates
statusManager := virtualmcpserverstatus.NewStatusManager(vmcp)
// Validate PodTemplateSpec early - before other validations
if !r.validateAndUpdatePodTemplateStatus(ctx, vmcp, statusManager) {
// Invalid PodTemplateSpec - apply status updates and return without error to avoid infinite retries
// The user must fix the spec and the next reconciliation will retry
if err := r.applyStatusUpdates(ctx, vmcp, statusManager); err != nil {
ctxLogger.Error(err, "Failed to apply status updates after PodTemplateSpec validation error")
}
return ctrl.Result{}, nil
}
// Validate GroupRef
if err := r.validateGroupRef(ctx, vmcp, statusManager); err != nil {
// Apply status changes before returning error
if err := r.applyStatusUpdates(ctx, vmcp, statusManager); err != nil {
ctxLogger.Error(err, "Failed to apply status updates after GroupRef validation error")
}
return ctrl.Result{}, err
}
// Validate CompositeToolRefs
if err := r.validateCompositeToolRefs(ctx, vmcp, statusManager); err != nil {
// Apply status changes before returning error
if err := r.applyStatusUpdates(ctx, vmcp, statusManager); err != nil {
ctxLogger.Error(err, "Failed to apply status updates after CompositeToolRefs validation error")
}
return ctrl.Result{}, err
}
// Ensure all resources
if err := r.ensureAllResources(ctx, vmcp, statusManager); err != nil {
// Apply status changes before returning error
if err := r.applyStatusUpdates(ctx, vmcp, statusManager); err != nil {
ctxLogger.Error(err, "Failed to apply status updates after resource reconciliation error")
}
return ctrl.Result{}, err
}
// Discover backends from the MCPGroup
discoveredBackends, err := r.discoverBackends(ctx, vmcp)
if err != nil {
ctxLogger.Error(err, "Failed to discover backends")
// Don't fail reconciliation if backend discovery fails, but log the error
statusManager.SetCondition(
mcpv1alpha1.ConditionTypeVirtualMCPServerBackendsDiscovered,
mcpv1alpha1.ConditionReasonVirtualMCPServerBackendDiscoveryFailed,
fmt.Sprintf("Failed to discover backends: %v", err),
metav1.ConditionFalse,
)
statusManager.SetObservedGeneration(vmcp.Generation)
} else {
statusManager.SetDiscoveredBackends(discoveredBackends)
statusManager.SetCondition(
mcpv1alpha1.ConditionTypeVirtualMCPServerBackendsDiscovered,
mcpv1alpha1.ConditionReasonVirtualMCPServerBackendsDiscoveredSuccessfully,
fmt.Sprintf("Discovered %d backends", len(discoveredBackends)),
metav1.ConditionTrue,
)
statusManager.SetObservedGeneration(vmcp.Generation)
ctxLogger.Info("Discovered backends", "count", len(discoveredBackends))
}
// Fetch the latest version before updating status to ensure we use the current Generation
latestVMCP := &mcpv1alpha1.VirtualMCPServer{}
if err := r.Get(ctx, types.NamespacedName{
Name: vmcp.Name,
Namespace: vmcp.Namespace,
}, latestVMCP); err != nil {
ctxLogger.Error(err, "Failed to get latest VirtualMCPServer before status update")
return ctrl.Result{}, err
}
// Update status based on pod health using the latest Generation
// Note: updateVirtualMCPServerStatus uses statusManager.GetDiscoveredBackends()
// for phase determination, so discovered backends don't need to be applied here
if err := r.updateVirtualMCPServerStatus(ctx, latestVMCP, statusManager); err != nil {
ctxLogger.Error(err, "Failed to update VirtualMCPServer status")
return ctrl.Result{}, err
}
// Apply all collected status changes in a single batch update
if err := r.applyStatusUpdates(ctx, latestVMCP, statusManager); err != nil {
ctxLogger.Error(err, "Failed to apply final status updates")
return ctrl.Result{}, err
}
// Reconciliation complete
// If health monitoring is enabled, requeue periodically to fetch updated health status
// Health checks run in vmcp pods, and we need to query the health endpoint regularly
// to update backend status in the VirtualMCPServer CRD
if vmcp.Spec.Operational != nil && vmcp.Spec.Operational.FailureHandling != nil &&
vmcp.Spec.Operational.FailureHandling.HealthCheckInterval != "" {
// Parse health check interval to determine requeue time
interval, err := time.ParseDuration(vmcp.Spec.Operational.FailureHandling.HealthCheckInterval)
if err != nil {
// Invalid duration format - log warning and fall through to event-driven reconciliation
// This should be caught by webhook validation, but we handle it gracefully here
ctxLogger.Error(err, "Invalid HealthCheckInterval format, falling back to event-driven reconciliation",
"health_check_interval", vmcp.Spec.Operational.FailureHandling.HealthCheckInterval)
// Continue with event-driven reconciliation instead of periodic polling
} else {
// Requeue at a multiple of the health check interval to ensure we catch updates
// without reconciling too frequently
requeueAfter := interval * healthCheckRequeueMultiplier
ctxLogger.Info("Periodic reconciliation enabled for health monitoring",
"health_check_interval", interval,
"requeue_after", requeueAfter)
return ctrl.Result{RequeueAfter: requeueAfter}, nil
}
}
// No health monitoring - rely on event-driven reconciliation
// Kubernetes will automatically trigger reconcile when:
// - VirtualMCPServer spec changes
// - Referenced resources (MCPGroup, Secrets) change
// - Owned resources (Deployment, Service) status changes
return ctrl.Result{}, nil
}
// applyStatusUpdates applies all collected status changes in a single batch update.
// This implements the StatusCollector pattern to reduce API calls and prevent update conflicts.
func (r *VirtualMCPServerReconciler) applyStatusUpdates(
ctx context.Context,
vmcp *mcpv1alpha1.VirtualMCPServer,
statusManager virtualmcpserverstatus.StatusManager,
) error {
ctxLogger := log.FromContext(ctx)
// Fetch the latest version to avoid conflicts
latest := &mcpv1alpha1.VirtualMCPServer{}
if err := r.Get(ctx, types.NamespacedName{
Name: vmcp.Name,
Namespace: vmcp.Namespace,
}, latest); err != nil {
return fmt.Errorf("failed to get latest VirtualMCPServer: %w", err)
}
// Apply collected changes to the latest status
hasUpdates := statusManager.UpdateStatus(ctx, &latest.Status)
// Only update if there are changes
if hasUpdates {
if err := r.Status().Update(ctx, latest); err != nil {
// Handle conflicts by returning error to trigger requeue
if errors.IsConflict(err) {
ctxLogger.V(1).Info("Conflict updating status, will requeue")
return err
}
return fmt.Errorf("failed to update VirtualMCPServer status: %w", err)
}
ctxLogger.V(1).Info("Successfully applied batched status updates")
}
return nil
}
// validateGroupRef validates that the referenced MCPGroup exists and is ready
func (r *VirtualMCPServerReconciler) validateGroupRef(
ctx context.Context,
vmcp *mcpv1alpha1.VirtualMCPServer,
statusManager virtualmcpserverstatus.StatusManager,
) error {
ctxLogger := log.FromContext(ctx)
// Validate GroupRef exists
mcpGroup := &mcpv1alpha1.MCPGroup{}
err := r.Get(ctx, types.NamespacedName{
Name: vmcp.Spec.GroupRef.Name,
Namespace: vmcp.Namespace,
}, mcpGroup)
if errors.IsNotFound(err) {
message := fmt.Sprintf("Referenced MCPGroup %s not found", vmcp.Spec.GroupRef.Name)
statusManager.SetPhase(mcpv1alpha1.VirtualMCPServerPhaseFailed)
statusManager.SetMessage(message)
statusManager.SetGroupRefValidatedCondition(
mcpv1alpha1.ConditionReasonVirtualMCPServerGroupRefNotFound,
message,
metav1.ConditionFalse,
)
statusManager.SetObservedGeneration(vmcp.Generation)
return err
} else if err != nil {
ctxLogger.Error(err, "Failed to get MCPGroup")
return err
}
// Check if MCPGroup is ready
if mcpGroup.Status.Phase != mcpv1alpha1.MCPGroupPhaseReady {
message := fmt.Sprintf("Referenced MCPGroup %s is not ready (phase: %s)",
vmcp.Spec.GroupRef.Name, mcpGroup.Status.Phase)
statusManager.SetPhase(mcpv1alpha1.VirtualMCPServerPhasePending)
statusManager.SetMessage(message)
statusManager.SetGroupRefValidatedCondition(
mcpv1alpha1.ConditionReasonVirtualMCPServerGroupRefNotReady,
message,
metav1.ConditionFalse,
)
statusManager.SetObservedGeneration(vmcp.Generation)
// Requeue to check again later
return fmt.Errorf("MCPGroup %s is not ready", vmcp.Spec.GroupRef.Name)
}
// GroupRef is valid and ready
statusManager.SetGroupRefValidatedCondition(
mcpv1alpha1.ConditionReasonVirtualMCPServerGroupRefValid,
fmt.Sprintf("MCPGroup %s is valid and ready", vmcp.Spec.GroupRef.Name),
metav1.ConditionTrue,
)
statusManager.SetObservedGeneration(vmcp.Generation)
return nil
}
// validateCompositeToolRefs validates that all referenced VirtualMCPCompositeToolDefinition resources exist
func (r *VirtualMCPServerReconciler) validateCompositeToolRefs(
ctx context.Context,
vmcp *mcpv1alpha1.VirtualMCPServer,
statusManager virtualmcpserverstatus.StatusManager,
) error {
ctxLogger := log.FromContext(ctx)
// If no composite tool refs, nothing to validate
if len(vmcp.Spec.CompositeToolRefs) == 0 {
// Set condition to indicate validation passed (no refs to validate)
statusManager.SetObservedGeneration(vmcp.Generation)
statusManager.SetCompositeToolRefsValidatedCondition(
mcpv1alpha1.ConditionReasonCompositeToolRefsValid,
"No composite tool references to validate",
metav1.ConditionTrue,
)
return nil
}
// Validate each referenced composite tool definition exists
for _, ref := range vmcp.Spec.CompositeToolRefs {
compositeToolDef := &mcpv1alpha1.VirtualMCPCompositeToolDefinition{}
err := r.Get(ctx, types.NamespacedName{
Name: ref.Name,
Namespace: vmcp.Namespace,
}, compositeToolDef)
if errors.IsNotFound(err) {
message := fmt.Sprintf("Referenced VirtualMCPCompositeToolDefinition %s not found", ref.Name)
statusManager.SetObservedGeneration(vmcp.Generation)
statusManager.SetPhase(mcpv1alpha1.VirtualMCPServerPhaseFailed)
statusManager.SetMessage(message)
statusManager.SetCompositeToolRefsValidatedCondition(
mcpv1alpha1.ConditionReasonCompositeToolRefNotFound,
message,
metav1.ConditionFalse,
)
return err
} else if err != nil {
ctxLogger.Error(err, "Failed to get VirtualMCPCompositeToolDefinition", "name", ref.Name)
return err
}
// Check that the composite tool definition is validated and valid
if compositeToolDef.Status.ValidationStatus == mcpv1alpha1.ValidationStatusInvalid {
message := fmt.Sprintf("Referenced VirtualMCPCompositeToolDefinition %s is invalid", ref.Name)
if len(compositeToolDef.Status.ValidationErrors) > 0 {
message = fmt.Sprintf("%s: %s", message, strings.Join(compositeToolDef.Status.ValidationErrors, "; "))
}
statusManager.SetObservedGeneration(vmcp.Generation)
statusManager.SetPhase(mcpv1alpha1.VirtualMCPServerPhaseFailed)
statusManager.SetMessage(message)
statusManager.SetCompositeToolRefsValidatedCondition(
mcpv1alpha1.ConditionReasonCompositeToolRefInvalid,
message,
metav1.ConditionFalse,
)
return fmt.Errorf("referenced VirtualMCPCompositeToolDefinition %s is invalid", ref.Name)
}
// If ValidationStatus is Unknown, we still allow it (validation might be in progress)
// but log a warning
if compositeToolDef.Status.ValidationStatus == mcpv1alpha1.ValidationStatusUnknown {
ctxLogger.V(1).Info("Referenced composite tool definition validation status is Unknown, proceeding",
"name", ref.Name, "namespace", vmcp.Namespace)
}
}
// All composite tool refs are valid
statusManager.SetObservedGeneration(vmcp.Generation)
statusManager.SetCompositeToolRefsValidatedCondition(
mcpv1alpha1.ConditionReasonCompositeToolRefsValid,
fmt.Sprintf("All %d composite tool references are valid", len(vmcp.Spec.CompositeToolRefs)),
metav1.ConditionTrue,
)
return nil
}
// validateAndUpdatePodTemplateStatus validates the PodTemplateSpec and uses StatusManager to collect
// status changes. Returns true if validation passes, false otherwise.
// The caller is responsible for applying status updates via applyStatusUpdates().
func (r *VirtualMCPServerReconciler) validateAndUpdatePodTemplateStatus(
ctx context.Context,
vmcp *mcpv1alpha1.VirtualMCPServer,
statusManager virtualmcpserverstatus.StatusManager,
) bool {
ctxLogger := log.FromContext(ctx)
// Only validate if PodTemplateSpec is provided
if vmcp.Spec.PodTemplateSpec == nil || vmcp.Spec.PodTemplateSpec.Raw == nil {
// No PodTemplateSpec provided, validation passes
return true
}
_, err := ctrlutil.NewPodTemplateSpecBuilder(vmcp.Spec.PodTemplateSpec, "vmcp")
if err != nil {
// Record event for invalid PodTemplateSpec
if r.Recorder != nil {
r.Recorder.Eventf(vmcp, corev1.EventTypeWarning, "InvalidPodTemplateSpec",
"Failed to parse PodTemplateSpec: %v. Deployment blocked until PodTemplateSpec is fixed.", err)
}
// Use StatusManager to collect status changes
statusManager.SetPhase(mcpv1alpha1.VirtualMCPServerPhaseFailed)
statusManager.SetMessage(fmt.Sprintf("Invalid PodTemplateSpec: %v", err))
statusManager.SetCondition(
mcpv1alpha1.ConditionTypeVirtualMCPServerPodTemplateSpecValid,
mcpv1alpha1.ConditionReasonVirtualMCPServerPodTemplateSpecInvalid,
fmt.Sprintf("Failed to parse PodTemplateSpec: %v. Deployment blocked until fixed.", err),
metav1.ConditionFalse,
)
statusManager.SetObservedGeneration(vmcp.Generation)
ctxLogger.Error(err, "PodTemplateSpec validation failed")
return false
}
// Use StatusManager to collect status changes for valid PodTemplateSpec
statusManager.SetCondition(
mcpv1alpha1.ConditionTypeVirtualMCPServerPodTemplateSpecValid,
mcpv1alpha1.ConditionReasonVirtualMCPServerPodTemplateSpecValid,
"PodTemplateSpec is valid",
metav1.ConditionTrue,
)
statusManager.SetObservedGeneration(vmcp.Generation)
return true
}
// ensureAllResources ensures all Kubernetes resources for the VirtualMCPServer
func (r *VirtualMCPServerReconciler) ensureAllResources(
ctx context.Context,
vmcp *mcpv1alpha1.VirtualMCPServer,
statusManager virtualmcpserverstatus.StatusManager,
) error {
ctxLogger := log.FromContext(ctx)
// Validate secret references before creating resources
// This catches configuration errors early, providing faster feedback than waiting for pod startup failures
if err := r.validateSecretReferences(ctx, vmcp); err != nil {
ctxLogger.Error(err, "Secret validation failed")
// Set AuthConfigured condition to False
statusManager.SetAuthConfiguredCondition(
mcpv1alpha1.ConditionReasonAuthInvalid,
fmt.Sprintf("Authentication configuration is invalid: %v", err),
metav1.ConditionFalse,
)
statusManager.SetObservedGeneration(vmcp.Generation)
// Record event for secret validation failure
if r.Recorder != nil {
r.Recorder.Eventf(vmcp, corev1.EventTypeWarning, "SecretValidationFailed",
"Secret validation failed: %v", err)
}
return err
}
// Authentication secrets validated successfully
statusManager.SetAuthConfiguredCondition(
mcpv1alpha1.ConditionReasonAuthValid,
"Authentication configuration is valid",
metav1.ConditionTrue,
)
statusManager.SetObservedGeneration(vmcp.Generation)
// List workloads once and pass to functions that need them
// This ensures consistency - all functions use the same workload list
// rather than listing at different times which could yield different results
workloadDiscoverer := workloads.NewK8SDiscovererWithClient(r.Client, vmcp.Namespace)
workloadNames, err := workloadDiscoverer.ListWorkloadsInGroup(ctx, vmcp.Spec.GroupRef.Name)
if err != nil {
ctxLogger.Error(err, "Failed to list workloads in group")
return fmt.Errorf("failed to list workloads in group: %w", err)
}
// Ensure RBAC resources
if err := r.ensureRBACResources(ctx, vmcp); err != nil {
ctxLogger.Error(err, "Failed to ensure RBAC resources")
return err
}
// Ensure vmcp Config ConfigMap
if err := r.ensureVmcpConfigConfigMap(ctx, vmcp, workloadNames); err != nil {
ctxLogger.Error(err, "Failed to ensure vmcp Config ConfigMap")
return err
}
// Ensure Deployment
if result, err := r.ensureDeployment(ctx, vmcp, workloadNames); err != nil {
return err
} else if result.RequeueAfter > 0 {
return nil
}
// Ensure Service
if result, err := r.ensureService(ctx, vmcp); err != nil {
return err
} else if result.RequeueAfter > 0 {
return nil
}
// Update service URL in status
r.ensureServiceURL(vmcp, statusManager)
return nil
}
// ensureRBACResources ensures that the RBAC resources are in place for the VirtualMCPServer
func (r *VirtualMCPServerReconciler) ensureRBACResources(
ctx context.Context,
vmcp *mcpv1alpha1.VirtualMCPServer,
) error {
serviceAccountName := vmcpServiceAccountName(vmcp.Name)
// Ensure Role with minimal permissions
if err := ctrlutil.EnsureRBACResource(ctx, r.Client, r.Scheme, vmcp, "Role", func() client.Object {
return &rbacv1.Role{
ObjectMeta: metav1.ObjectMeta{
Name: serviceAccountName,
Namespace: vmcp.Namespace,
},
Rules: vmcpRBACRules,
}
}); err != nil {
return err
}
// Ensure ServiceAccount
if err := ctrlutil.EnsureRBACResource(ctx, r.Client, r.Scheme, vmcp, "ServiceAccount", func() client.Object {
return &corev1.ServiceAccount{
ObjectMeta: metav1.ObjectMeta{
Name: serviceAccountName,
Namespace: vmcp.Namespace,
},
}
}); err != nil {
return err
}
// Ensure RoleBinding
return ctrlutil.EnsureRBACResource(ctx, r.Client, r.Scheme, vmcp, "RoleBinding", func() client.Object {
return &rbacv1.RoleBinding{
ObjectMeta: metav1.ObjectMeta{
Name: serviceAccountName,
Namespace: vmcp.Namespace,
},
RoleRef: rbacv1.RoleRef{
APIGroup: "rbac.authorization.k8s.io",
Kind: "Role",
Name: serviceAccountName,
},
Subjects: []rbacv1.Subject{
{
Kind: "ServiceAccount",
Name: serviceAccountName,
Namespace: vmcp.Namespace,
},
},
}
})
}
// getVmcpConfigChecksum fetches the vmcp Config ConfigMap checksum annotation.
// This is used to trigger deployment rollouts when the configuration changes.
//
// Note: VirtualMCPServer uses a custom ConfigMap naming pattern ("{name}-vmcp-config")
// instead of the standard "{name}-runconfig" pattern, so it cannot use the shared
// checksum.RunConfigChecksumFetcher. However, it follows the same validation logic
// and uses the same annotation constant for consistency.
func (r *VirtualMCPServerReconciler) getVmcpConfigChecksum(
ctx context.Context,
vmcp *mcpv1alpha1.VirtualMCPServer,
) (string, error) {
if vmcp == nil {
return "", fmt.Errorf("vmcp cannot be nil")
}
configMapName := vmcpConfigMapName(vmcp.Name)
configMap := &corev1.ConfigMap{}
err := r.Get(ctx, types.NamespacedName{
Name: configMapName,
Namespace: vmcp.Namespace,
}, configMap)
if err != nil {
// Preserve error type for IsNotFound checks
return "", fmt.Errorf("failed to get vmcp Config ConfigMap %s/%s: %w",
vmcp.Namespace, configMapName, err)
}
// Use the standard checksum annotation constant for consistency
checksumValue, ok := configMap.Annotations[checksum.ContentChecksumAnnotation]
if !ok {
return "", fmt.Errorf("vmcp Config ConfigMap %s/%s missing %s annotation",
vmcp.Namespace, configMapName, checksum.ContentChecksumAnnotation)
}
if checksumValue == "" {
return "", fmt.Errorf("vmcp Config ConfigMap %s/%s has empty %s annotation",
vmcp.Namespace, configMapName, checksum.ContentChecksumAnnotation)
}
return checksumValue, nil
}
// ensureDeployment ensures the Deployment exists and is up to date
//
//nolint:unparam // ctrl.Result needed for ConfigMap not found case (RequeueAfter)
func (r *VirtualMCPServerReconciler) ensureDeployment(
ctx context.Context,
vmcp *mcpv1alpha1.VirtualMCPServer,
typedWorkloads []workloads.TypedWorkload,
) (ctrl.Result, error) {
ctxLogger := log.FromContext(ctx)
// Fetch vmcp Config ConfigMap checksum to include in pod template annotations
vmcpConfigChecksum, err := r.getVmcpConfigChecksum(ctx, vmcp)
if err != nil {
if errors.IsNotFound(err) {
ctxLogger.Info("vmcp Config ConfigMap not found yet, will retry",
"vmcp", vmcp.Name, "namespace", vmcp.Namespace)
return ctrl.Result{RequeueAfter: 5 * time.Second}, nil
}
ctxLogger.Error(err, "Failed to get vmcp Config checksum")
return ctrl.Result{}, err
}
deployment := &appsv1.Deployment{}
err = r.Get(ctx, types.NamespacedName{Name: vmcp.Name, Namespace: vmcp.Namespace}, deployment)
if errors.IsNotFound(err) {
dep := r.deploymentForVirtualMCPServer(ctx, vmcp, vmcpConfigChecksum, typedWorkloads)
if dep == nil {
return ctrl.Result{}, fmt.Errorf("failed to create Deployment object")
}
ctxLogger.Info("Creating a new Deployment", "Deployment.Namespace", dep.Namespace, "Deployment.Name", dep.Name)
if err := r.Create(ctx, dep); err != nil {
ctxLogger.Error(err, "Failed to create new Deployment")
// Record event for deployment creation failure
if r.Recorder != nil {
r.Recorder.Eventf(vmcp, corev1.EventTypeWarning, "DeploymentCreationFailed",
"Failed to create Deployment: %v", err)
}
return ctrl.Result{}, err
}
// Record event for successful deployment creation
if r.Recorder != nil {
r.Recorder.Event(vmcp, corev1.EventTypeNormal, "DeploymentCreated",
"Deployment created successfully")
}
// Return empty result to continue with rest of reconciliation (Service, status update, etc.)
// Kubernetes will automatically requeue when Deployment status changes
return ctrl.Result{}, nil
} else if err != nil {
ctxLogger.Error(err, "Failed to get Deployment")
return ctrl.Result{}, err
}
// Deployment exists - check if it needs to be updated
// deploymentNeedsUpdate performs a detailed comparison to avoid unnecessary updates
if r.deploymentNeedsUpdate(ctx, deployment, vmcp, vmcpConfigChecksum, typedWorkloads) {
newDeployment := r.deploymentForVirtualMCPServer(ctx, vmcp, vmcpConfigChecksum, typedWorkloads)
if newDeployment == nil {
return ctrl.Result{}, fmt.Errorf("failed to create updated Deployment object")
}
// Selective field update strategy:
// - Update Spec.Template: Contains container spec, volumes, pod metadata (triggers rollout)
// - Update Labels: For label selectors and queries
// - Update Annotations: For metadata and tooling
// - Preserve Spec.Replicas: Allows HPA/VPA to manage scaling independently
// - Preserve ResourceVersion, UID: Required for optimistic concurrency control
//
// Note: If update conflicts occur due to concurrent modifications, the reconcile
// loop will retry automatically. Kubernetes' optimistic locking prevents data loss.
deployment.Spec.Template = newDeployment.Spec.Template
deployment.Labels = newDeployment.Labels
deployment.Annotations = newDeployment.Annotations
ctxLogger.Info("Updating Deployment", "Deployment.Namespace", deployment.Namespace, "Deployment.Name", deployment.Name)
if err := r.Update(ctx, deployment); err != nil {
ctxLogger.Error(err, "Failed to update Deployment")
// Record event for deployment update failure
if r.Recorder != nil {
r.Recorder.Eventf(vmcp, corev1.EventTypeWarning, "DeploymentUpdateFailed",
"Failed to update Deployment: %v", err)
}
// Return error to trigger reconcile retry (handles transient failures and conflicts)
return ctrl.Result{}, err
}
// Record event for successful deployment update (config change triggers rollout)
if r.Recorder != nil {
r.Recorder.Event(vmcp, corev1.EventTypeNormal, "DeploymentUpdated",
"Deployment updated, rolling out new configuration")
}
// Return empty result to continue with rest of reconciliation
// Deployment rollout will be monitored when Kubernetes triggers subsequent reconciles
return ctrl.Result{}, nil
}
return ctrl.Result{}, nil
}
// ensureService ensures the Service exists and is up to date
//
//nolint:unparam // ctrl.Result kept for consistency with ensureDeployment signature
func (r *VirtualMCPServerReconciler) ensureService(
ctx context.Context,
vmcp *mcpv1alpha1.VirtualMCPServer,
) (ctrl.Result, error) {
ctxLogger := log.FromContext(ctx)
serviceName := vmcpServiceName(vmcp.Name)
service := &corev1.Service{}
err := r.Get(ctx, types.NamespacedName{Name: serviceName, Namespace: vmcp.Namespace}, service)
if errors.IsNotFound(err) {
svc := r.serviceForVirtualMCPServer(ctx, vmcp)
if svc == nil {
return ctrl.Result{}, fmt.Errorf("failed to create Service object")
}
ctxLogger.Info("Creating a new Service", "Service.Namespace", svc.Namespace, "Service.Name", svc.Name)
if err := r.Create(ctx, svc); err != nil {
ctxLogger.Error(err, "Failed to create new Service")
// Record event for service creation failure
if r.Recorder != nil {
r.Recorder.Eventf(vmcp, corev1.EventTypeWarning, "ServiceCreationFailed",
"Failed to create Service: %v", err)
}
return ctrl.Result{}, err
}
// Record event for successful service creation
if r.Recorder != nil {
r.Recorder.Eventf(vmcp, corev1.EventTypeNormal, "ServiceCreated",
"Service %s created successfully", serviceName)
}
// Return empty result to continue with rest of reconciliation
return ctrl.Result{}, nil
} else if err != nil {
ctxLogger.Error(err, "Failed to get Service")
return ctrl.Result{}, err
}
// Service exists - check if it needs to be updated
// serviceNeedsUpdate compares ports, type, labels, and annotations
if r.serviceNeedsUpdate(service, vmcp) {
newService := r.serviceForVirtualMCPServer(ctx, vmcp)
if newService == nil {
return ctrl.Result{}, fmt.Errorf("failed to create updated Service object")
}
// Selective field update strategy for Service:
// - Update Spec.Ports: Modify exposed ports
// - Update Spec.Type: Change service type (ClusterIP, NodePort, LoadBalancer)
// - Update Labels: For selectors and queries
// - Update Annotations: For metadata and tooling
// - Preserve Spec.ClusterIP: Immutable field, cannot be changed
// - Preserve Spec.HealthCheckNodePort: Set by cloud provider for LoadBalancer
// - Preserve ResourceVersion, UID: Required for optimistic concurrency control
service.Spec.Ports = newService.Spec.Ports
service.Spec.Type = newService.Spec.Type
service.Labels = newService.Labels
service.Annotations = newService.Annotations
ctxLogger.Info("Updating Service", "Service.Namespace", service.Namespace, "Service.Name", service.Name)
if err := r.Update(ctx, service); err != nil {
ctxLogger.Error(err, "Failed to update Service")
return ctrl.Result{}, err
}
// Return empty result to continue with rest of reconciliation
return ctrl.Result{}, nil
}
return ctrl.Result{}, nil
}
// ensureServiceURL ensures the service URL is set in the status
func (*VirtualMCPServerReconciler) ensureServiceURL(
vmcp *mcpv1alpha1.VirtualMCPServer,
statusManager virtualmcpserverstatus.StatusManager,
) {
if vmcp.Status.URL == "" {
url := createVmcpServiceURL(vmcp.Name, vmcp.Namespace, vmcpDefaultPort)
statusManager.SetURL(url)
}
}
// deploymentNeedsUpdate checks if the deployment needs to be updated
func (r *VirtualMCPServerReconciler) deploymentNeedsUpdate(
ctx context.Context,
deployment *appsv1.Deployment,
vmcp *mcpv1alpha1.VirtualMCPServer,
vmcpConfigChecksum string,
typedWorkloads []workloads.TypedWorkload,
) bool {
if deployment == nil || vmcp == nil {
return true
}
if len(deployment.Spec.Template.Spec.Containers) == 0 {
return true
}
if r.containerNeedsUpdate(ctx, deployment, vmcp, typedWorkloads) {
return true
}
if r.deploymentMetadataNeedsUpdate(deployment, vmcp) {
return true
}
if r.podTemplateMetadataNeedsUpdate(deployment, vmcp, vmcpConfigChecksum) {
return true
}
if r.podTemplateSpecNeedsUpdate(ctx, deployment, vmcp, typedWorkloads) {
return true
}
return false
}
// containerNeedsUpdate checks if the container specification has changed
func (r *VirtualMCPServerReconciler) containerNeedsUpdate(
ctx context.Context,
deployment *appsv1.Deployment,
vmcp *mcpv1alpha1.VirtualMCPServer,
typedWorkloads []workloads.TypedWorkload,
) bool {
if deployment == nil || vmcp == nil || len(deployment.Spec.Template.Spec.Containers) == 0 {
return true
}
container := deployment.Spec.Template.Spec.Containers[0]
// Check if vmcp image has changed
expectedImage := getVmcpImage()
if container.Image != expectedImage {
return true
}
// Check if port has changed
if len(container.Ports) > 0 && container.Ports[0].ContainerPort != vmcpDefaultPort {
return true
}
// Check if container args have changed (includes --debug flag from logLevel)
expectedArgs := r.buildContainerArgsForVmcp(vmcp)
if !reflect.DeepEqual(container.Args, expectedArgs) {
return true
}
// Check if environment variables have changed
expectedEnv := r.buildEnvVarsForVmcp(ctx, vmcp, typedWorkloads)
if !reflect.DeepEqual(container.Env, expectedEnv) {
return true
}
// Check if service account has changed
expectedServiceAccountName := vmcpServiceAccountName(vmcp.Name)
currentServiceAccountName := deployment.Spec.Template.Spec.ServiceAccountName
if currentServiceAccountName != "" && currentServiceAccountName != expectedServiceAccountName {
return true
}
return false
}
// deploymentMetadataNeedsUpdate checks if deployment-level metadata has changed
func (*VirtualMCPServerReconciler) deploymentMetadataNeedsUpdate(
deployment *appsv1.Deployment,
vmcp *mcpv1alpha1.VirtualMCPServer,
) bool {
if deployment == nil || vmcp == nil {
return true
}
expectedLabels := labelsForVirtualMCPServer(vmcp.Name)
expectedAnnotations := make(map[string]string)
// TODO: Add support for ResourceOverrides if needed in the future
// Check that all expected labels are present with correct values
// (Allows Kubernetes-managed labels to exist without triggering updates)
for key, expectedValue := range expectedLabels {
if actualValue, exists := deployment.Labels[key]; !exists || actualValue != expectedValue {
return true
}
}
// Check that all expected annotations are present with correct values
// (Allows Kubernetes-managed annotations like deployment.kubernetes.io/revision to exist)
for key, expectedValue := range expectedAnnotations {
if actualValue, exists := deployment.Annotations[key]; !exists || actualValue != expectedValue {
return true
}
}
return false
}
// podTemplateMetadataNeedsUpdate checks if pod template metadata has changed
func (r *VirtualMCPServerReconciler) podTemplateMetadataNeedsUpdate(
deployment *appsv1.Deployment,
vmcp *mcpv1alpha1.VirtualMCPServer,
vmcpConfigChecksum string,
) bool {
if deployment == nil || vmcp == nil {
return true
}
expectedPodTemplateLabels, expectedPodTemplateAnnotations := r.buildPodTemplateMetadata(
labelsForVirtualMCPServer(vmcp.Name), vmcp, vmcpConfigChecksum,
)
if !maps.Equal(deployment.Spec.Template.Labels, expectedPodTemplateLabels) {
return true
}
if !maps.Equal(deployment.Spec.Template.Annotations, expectedPodTemplateAnnotations) {
return true
}
return false
}
// podTemplateSpecNeedsUpdate checks if the user-provided PodTemplateSpec has changed
// This method compares the current deployment against a freshly generated deployment
// that includes the PodTemplateSpec customizations.
func (r *VirtualMCPServerReconciler) podTemplateSpecNeedsUpdate(
ctx context.Context,
deployment *appsv1.Deployment,
vmcp *mcpv1alpha1.VirtualMCPServer,
typedWorkloads []workloads.TypedWorkload,
) bool {
if deployment == nil || vmcp == nil {
return true
}
// If no PodTemplateSpec is provided, no update needed
if vmcp.Spec.PodTemplateSpec == nil || vmcp.Spec.PodTemplateSpec.Raw == nil {
return false
}
// Get the vmcp config checksum
vmcpConfigChecksum, err := r.getVmcpConfigChecksum(ctx, vmcp)
if err != nil {
// If we can't get the checksum, assume update is needed
return true
}