/* Copyright 2026 LocoStack. 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" appsv1 "k8s.io/api/apps/v1" corev1 "k8s.io/api/core/v1" apierrors "k8s.io/apimachinery/pkg/api/errors" apimeta "k8s.io/apimachinery/pkg/api/meta" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/client/apiutil" "sigs.k8s.io/controller-runtime/pkg/handler" logf "sigs.k8s.io/controller-runtime/pkg/log" "sigs.k8s.io/controller-runtime/pkg/reconcile" "github.com/LocoStack/loco-operator/api/v1alpha1" "github.com/LocoStack/loco-operator/internal/reconciler" "github.com/LocoStack/loco-operator/pkg/templates" ) // ComponentReconciler reconciles a Component object type ComponentReconciler struct { client.Client Scheme *runtime.Scheme } // +kubebuilder:rbac:groups=locostack.com,resources=components,verbs=get;list;watch;create;update;patch;delete // +kubebuilder:rbac:groups=locostack.com,resources=components/status,verbs=get;update;patch // +kubebuilder:rbac:groups=locostack.com,resources=components/finalizers,verbs=update // +kubebuilder:rbac:groups=locostack.com,resources=*,verbs=get;list;watch // +kubebuilder:rbac:groups="",resources=configmaps,verbs=get;list;watch;create;update;patch // +kubebuilder:rbac:groups="",resources=persistentvolumes,verbs=get;list;watch;create;update;patch // +kubebuilder:rbac:groups="",resources=persistentvolumeclaims,verbs=get;list;watch;create;update;patch // +kubebuilder:rbac:groups="",resources=secrets,verbs=get;list;watch;create;update;patch // +kubebuilder:rbac:groups="",resources=services,verbs=get;list;watch;create;update;patch // +kubebuilder:rbac:groups="apps",resources=deployments,verbs=get;list;watch;create;update;patch func (r *ComponentReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { log := logf.FromContext(ctx) comp := &v1alpha1.Component{} if err := r.Get(ctx, req.NamespacedName, comp); err != nil { if apierrors.IsNotFound(err) { return ctrl.Result{}, nil } log.Error(err, "Failed to get Component", "namespace", req.NamespacedName.Namespace, "name", req.NamespacedName.Name) return ctrl.Result{}, err } patch := client.MergeFrom(comp.DeepCopy()) tmpl, err := templates.Manager.ResolveTemplate(comp.Spec.Template, "") if err != nil { apimeta.SetStatusCondition(&comp.Status.Conditions, metav1.Condition{ Type: "Reconciled", Status: metav1.ConditionFalse, Reason: "TemplateResolutionFailed", Message: fmt.Sprintf("Could not resolve template: %v", err), ObservedGeneration: comp.Generation, }) log.Error(err, "Failed to resolve template for Component", "namespace", req.NamespacedName.Namespace, "name", req.NamespacedName.Name) _ = r.Status().Patch(ctx, comp, patch) return ctrl.Result{}, nil } stack := &v1alpha1.Stack{} if comp.Spec.StackRef == nil || comp.Spec.StackRef.Name == "" { stack = nil } else if err := r.Get(ctx, client.ObjectKey{Namespace: comp.Namespace, Name: comp.Spec.StackRef.Name}, stack); err != nil { stack = nil } componentReconciler := r.getComponentReconciler(comp, stack) dependencies, err := componentReconciler.ReconcileComponent(ctx, &tmpl, make(map[string]string)) if err != nil { apimeta.SetStatusCondition(&comp.Status.Conditions, metav1.Condition{ Type: "Reconciled", Status: metav1.ConditionFalse, Reason: "ReconcileFailed", Message: fmt.Sprintf("Could not reconcile component: %v", err), ObservedGeneration: comp.Generation, }) log.Error(err, "Failed to reconcile Component", "namespace", req.NamespacedName.Namespace, "name", req.NamespacedName.Name) _ = r.Status().Patch(ctx, comp, patch) return ctrl.Result{}, err } comp.Status.Endpoint = fmt.Sprintf("http://%s.%s.svc.cluster.local:%d", componentReconciler.ResourceName(""), comp.Namespace, tmpl.Spec.Runtime.Port) comp.Status.ObservedGeneration = comp.Generation // rebuilt from scratch on every reconcile, including when there are no dependencies // left: dependencies that are gone have to drop out of the status too, since this is // what tells them whether the Component is still serving their current generation comp.Status.Dependencies = nil for _, dep := range dependencies { gvk, err := apiutil.GVKForObject(dep, r.Scheme) if err != nil { log.Error(err, "Failed to get GVK for dependency", "dependency", dep) continue } if gvk.Group != v1alpha1.GroupVersion.Group { continue } kind := gvk.Kind name := dep.GetName() generation := dep.GetGeneration() if comp.Status.Dependencies == nil { comp.Status.Dependencies = make(map[string]map[string]int64) } if _, exists := comp.Status.Dependencies[kind]; !exists { comp.Status.Dependencies[kind] = make(map[string]int64) } comp.Status.Dependencies[kind][name] = generation } apimeta.SetStatusCondition(&comp.Status.Conditions, metav1.Condition{ Type: "Reconciled", Status: metav1.ConditionTrue, Reason: "ReconcileSucceeded", Message: "Component reconciled", ObservedGeneration: comp.Generation, }) if available := componentReconciler.ComponentAvailable(ctx); !available { apimeta.SetStatusCondition(&comp.Status.Conditions, metav1.Condition{ Type: "Available", Status: metav1.ConditionFalse, Reason: "ServiceUnavailable", Message: "Component is not available", ObservedGeneration: comp.Generation, }) } else { apimeta.SetStatusCondition(&comp.Status.Conditions, metav1.Condition{ Type: "Available", Status: metav1.ConditionTrue, Reason: "ComponentReady", Message: "Component is available", ObservedGeneration: comp.Generation, }) } if err := r.Status().Patch(ctx, comp, patch); err != nil { return ctrl.Result{}, client.IgnoreNotFound(err) } log.Info("Reconciled Component", "namespace", comp.Namespace, "name", comp.Name) return ctrl.Result{}, nil } func (r *ComponentReconciler) getComponentReconciler(comp *v1alpha1.Component, stack *v1alpha1.Stack) reconciler.ComponentReconciler { switch comp.Spec.Template.Name { case "litellm": return reconciler.NewLiteLLMReconciler(r.Client, r.Scheme, stack, comp) case "qdrant": return reconciler.NewQdrantReconciler(r.Client, r.Scheme, stack, comp) case "neo4j": return reconciler.NewNeo4jReconciler(r.Client, r.Scheme, stack, comp) case "postgresql": return reconciler.NewPostgreSQLReconciler(r.Client, r.Scheme, stack, comp) case "phoenix": return reconciler.NewPhoenixReconciler(r.Client, r.Scheme, stack, comp) case "llama.cpp": return reconciler.NewLlamaCPPReconciler(r.Client, r.Scheme, stack, comp) case "loco-context": return reconciler.NewLocoContextReconciler(r.Client, r.Scheme, stack, comp) case "loco-agents": return reconciler.NewLocoAgentsReconciler(r.Client, r.Scheme, stack, comp) case "opencode": return reconciler.NewLocoOpenCodeAgentReconciler(r.Client, r.Scheme, stack, comp) default: return reconciler.NewDefaultComponentReconciler(r.Client, r.Scheme, stack, comp) } } // SetupWithManager sets up the controller with the Manager. func (r *ComponentReconciler) SetupWithManager(mgr ctrl.Manager) error { c := mgr.GetClient() builder := ctrl.NewControllerManagedBy(mgr). For(&v1alpha1.Component{}). Owns(&corev1.ConfigMap{}). Owns(&corev1.Secret{}). Owns(&corev1.PersistentVolumeClaim{}). Owns(&corev1.Service{}). Owns(&appsv1.Deployment{}). // a Component renders its config from the objects it depends on, so every one of // them has to be able to trigger a re-render - and with it a rollout Watches(&v1alpha1.Component{}, handler.EnqueueRequestsFromMapFunc(componentDependencyMapFunc(c))). Watches(&corev1.ConfigMap{}, SkillConfigMapEventHandler(c)). Watches(&corev1.Secret{}, AuthSecretEventHandler(c)) for _, dep := range componentDependencyKinds { builder = builder.Watches(dep.object, handler.EnqueueRequestsFromMapFunc(dependencyMapFunc(c, dep.kind))) } return builder. Named("component"). Complete(r) } var componentDependencyKinds = []struct { kind string object client.Object }{ {"ExternalModel", &v1alpha1.ExternalModel{}}, {"ManagedModel", &v1alpha1.ManagedModel{}}, {"ExternalTool", &v1alpha1.ExternalTool{}}, {"ManagedTool", &v1alpha1.ManagedTool{}}, {"Skill", &v1alpha1.Skill{}}, {"ExternalKnowledgeBase", &v1alpha1.ExternalKnowledgeBase{}}, {"ManagedKnowledgeBase", &v1alpha1.ManagedKnowledgeBase{}}, {"Agent", &v1alpha1.Agent{}}, } func componentDependencyMapFunc(c client.Client) handler.MapFunc { return func(ctx context.Context, obj client.Object) []reconcile.Request { comp, ok := obj.(*v1alpha1.Component) if !ok { return nil } stackName := "" if comp.Spec.StackRef != nil { stackName = comp.Spec.StackRef.Name } stackWide := stackName != "" && stackComponentCategories[comp.Spec.Category] return dependentComponentRequests(ctx, c, comp.GetNamespace(), func(other *v1alpha1.Component) bool { if other.GetName() == comp.GetName() { // the Component's own events already reach the controller through For() return false } if componentDependsOn(other, "Component", comp.GetName(), comp.GetNamespace()) { return true } return stackWide && other.Spec.StackRef != nil && other.Spec.StackRef.Name == stackName }) } } func dependencyMapFunc(c client.Client, kind string) handler.MapFunc { return func(ctx context.Context, obj client.Object) []reconcile.Request { return dependentComponentRequests(ctx, c, obj.GetNamespace(), func(comp *v1alpha1.Component) bool { return componentDependsOn(comp, kind, obj.GetName(), obj.GetNamespace()) }) } }