/* Copyright 2025. 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" dnsv1alpha1 "git.mayers.cloud/superflo22/split-horizon-operator/api/v1alpha1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "reflect" "sigs.k8s.io/controller-runtime/pkg/handler" gatewayv1 "sigs.k8s.io/gateway-api/apis/v1" "strings" "k8s.io/apimachinery/pkg/runtime" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/log" ) // ExternalDNSWatcherReconciler reconciles a ExternalDNSWatcher object type ExternalDNSWatcherReconciler struct { client.Client Scheme *runtime.Scheme } // +kubebuilder:rbac:groups=dns.mayers.cloud,resources=externaldnswatchers,verbs=get;list;watch;create;update;patch;delete // +kubebuilder:rbac:groups=dns.mayers.cloud,resources=externaldnswatchers/status,verbs=get;update;patch // +kubebuilder:rbac:groups=dns.mayers.cloud,resources=externaldnswatchers/finalizers,verbs=update // Reconcile is part of the main kubernetes reconciliation loop which aims to // move the current state of the cluster closer to the desired state. // TODO(user): Modify the Reconcile function to compare the state specified by // the ExternalDNSWatcher object against the actual cluster state, and then // perform operations to make the cluster state reflect the state specified by // the user. // // For more details, check Reconcile and its Result here: // - https://pkg.go.dev/sigs.k8s.io/controller-runtime@v0.19.0/pkg/reconcile func (r *ExternalDNSWatcherReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) { log := log.FromContext(ctx) // Step 1: Fetch the Gateway var gateway gatewayv1.Gateway if err := r.Get(ctx, req.NamespacedName, &gateway); err != nil { return ctrl.Result{}, client.IgnoreNotFound(err) } // Step 2: Check annotation annotations := gateway.GetAnnotations() authority := annotations["dns.mayers.cloud/authority"] if authority == "" { log.Info("Missing required authority annotation") return ctrl.Result{}, nil } network := annotations["dns.mayers.cloud/network"] if network == "" { log.Info("Missing network annotation assuming default network") network = "default" } // Step 3: Get Gateway IP (if available) var gatewayIPs []string for _, addr := range gateway.Status.Addresses { if addr.Type == nil || *addr.Type == gatewayv1.IPAddressType { gatewayIPs = append(gatewayIPs, addr.Value) } } // Step 4: List HTTPRoutes that reference this Gateway var routes gatewayv1.HTTPRouteList if err := r.List(ctx, &routes, client.InNamespace(req.Namespace)); err != nil { return ctrl.Result{}, err } for _, route := range routes.Items { // Step 5: Collect hostnames for _, hostname := range route.Spec.Hostnames { // Naming convention for TechnitiumRecord recordName := fmt.Sprintf("%s", strings.ReplaceAll(string(hostname), ".", "-")) // Bestehendes TechnitiumRecord abrufen var existingRecord dnsv1alpha1.TechnitiumRecord err := r.Client.Get(ctx, client.ObjectKey{ Namespace: route.Namespace, Name: recordName, }, &existingRecord) if err != nil { log.Info("Creating new Record", "recordName", recordName) record := &dnsv1alpha1.TechnitiumRecord{ TypeMeta: metav1.TypeMeta{ Kind: "TechnitiumRecord", APIVersion: "dns.mayers.cloud/v1alpha1", }, ObjectMeta: metav1.ObjectMeta{ Name: recordName, Namespace: route.Namespace, }, Spec: dnsv1alpha1.TechnitiumRecordSpec{ AuthorityRef: dnsv1alpha1.AuthorityReference{ Name: authority, }, Name: string(hostname), TTL: 300, ClassPath: "SimpleAddress", RecordData: map[string][]string{ network: gatewayIPs, }, }, } // Log the record yaml log.V(1).Info("TechnitiumRecord Manifest", "record", record) if err := r.Client.Patch(ctx, record, client.Apply, client.ForceOwnership, client.FieldOwner("external-dns-watcher")); err != nil { log.Error(err, "Failed to apply TechnitiumRecord") } else { log.Info("Created new Record", "name", record.Name) } } // Step 6: Update existing TechnitiumRecord if existingRecord.Spec.RecordData[network] != nil { // Check if the IPs are different if !reflect.DeepEqual(existingRecord.Spec.RecordData[network], gatewayIPs) { log.Info("Updating existing Record", "recordName", recordName) existingRecord.Spec.RecordData[network] = gatewayIPs if err := r.Update(ctx, &existingRecord); err != nil { log.Error(err, "Failed to update TechnitiumRecord") } else { log.Info("Updated IPs in existing Record", "name", recordName) } } } else { log.Info("Adding new network to existing Record", "recordName", recordName) // Add the new network and IPs existingRecord.Spec.RecordData[network] = gatewayIPs if err := r.Update(ctx, &existingRecord); err != nil { log.Error(err, "Failed to update TechnitiumRecord") } else { log.Info("Updated new network in existing Record", "name", recordName) } } } } return ctrl.Result{}, nil } // SetupWithManager sets up the controller with the Manager. func (r *ExternalDNSWatcherReconciler) SetupWithManager(mgr ctrl.Manager) error { return ctrl.NewControllerManagedBy(mgr). // Uncomment the following line adding a pointer to an instance of the controlled resource as an argument Named("external_dns_controller"). Watches( &gatewayv1.Gateway{}, &handler.EnqueueRequestForObject{}, ). Watches( &gatewayv1.HTTPRoute{}, &handler.EnqueueRequestForObject{}, ). Complete(r) }