feat: add some generic reconcilers

This commit is contained in:
Hugo Renard 2025-01-10 18:21:30 +01:00
parent b6f0ec03e3
commit d2452df888
Signed by: hougo
GPG key ID: 3A285FD470209C59

View file

@ -0,0 +1,87 @@
// SPDX-FileCopyrightText: 2025 IndieHosters <contact@indiehosters.net>
//
// SPDX-License-Identifier: EUPL-1.2
package controllerruntime
import (
"context"
corev1 "k8s.io/api/core/v1"
netv1 "k8s.io/api/networking/v1"
"k8s.io/apimachinery/pkg/util/intstr"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/controller/controllerutil"
lshcore "libre.sh/api/core/v1alpha1"
lshmeta "libre.sh/api/meta/v1alpha1"
)
func ReconcileGenericService(ctx context.Context, r Reconciler, o client.Object) (*corev1.Service, error) {
var service corev1.Service
SetResourceNamespacedName(o, &service)
return &service, CreateOrPatch(ctx, r, &service, func() error {
ApplyLabels(o, &service, nil)
service.Spec.Selector = ExtractLabelSelector(&service)
service.Spec.Ports = []corev1.ServicePort{
{
Name: "http",
TargetPort: intstr.FromString("http"),
Port: 80,
},
}
return controllerutil.SetControllerReference(o, &service, r.Scheme())
})
}
func ReconcileGenericIngress(ctx context.Context, r Reconciler, o client.Object, host string, extraAnnotations map[string]string) (*netv1.Ingress, error) {
var ingress netv1.Ingress
SetResourceNamespacedName(o, &ingress)
return &ingress, CreateOrPatch(ctx, r, &ingress, func() error {
if ingress.Annotations[lshmeta.SuspendAnnotation] == "true" {
return nil
}
ApplyLabels(o, &ingress, nil)
ingress.Annotations["kubernetes.io/tls-acme"] = "true"
for k, v := range extraAnnotations {
ingress.Annotations[k] = v
}
pathType := netv1.PathTypePrefix
ingress.Spec.Rules = []netv1.IngressRule{{
Host: host,
IngressRuleValue: netv1.IngressRuleValue{
HTTP: &netv1.HTTPIngressRuleValue{
Paths: []netv1.HTTPIngressPath{
{
PathType: &pathType,
Path: "/",
Backend: netv1.IngressBackend{
Service: &netv1.IngressServiceBackend{
Name: GetResourceName(o),
Port: netv1.ServiceBackendPort{
Name: "http",
},
},
},
},
},
},
},
}}
ingress.Spec.TLS = []netv1.IngressTLS{{
SecretName: ingress.Name + "-tls",
Hosts: []string{host},
}}
return controllerutil.SetControllerReference(o, &ingress, r.Scheme())
})
}
func ReconcileGenericPostgres(ctx context.Context, r Reconciler, o client.Object, database string) (*lshcore.Postgres, error) {
var postgres lshcore.Postgres
SetResourceNamespacedName(o, &postgres)
return &postgres, CreateOrPatch(ctx, r, &postgres, func() error {
ApplyLabels(o, &postgres, nil)
postgres.Spec.Database = database
return controllerutil.SetControllerReference(o, &postgres, r.Scheme())
})
}