|
| 1 | +/* |
| 2 | +Copyright 2026 The Cozystack Authors. |
| 3 | +
|
| 4 | +Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | +you may not use this file except in compliance with the License. |
| 6 | +You may obtain a copy of the License at |
| 7 | +
|
| 8 | + http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +
|
| 10 | +Unless required by applicable law or agreed to in writing, software |
| 11 | +distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | +See the License for the specific language governing permissions and |
| 14 | +limitations under the License. |
| 15 | +*/ |
| 16 | + |
| 17 | +// Package tenantlogrouting keeps the node fluent-bit's tenant log routes in |
| 18 | +// step with the namespaces that declare them. |
| 19 | +// |
| 20 | +// The monitoring-agents chart builds its routes with a Helm lookup of every |
| 21 | +// Namespace's namespace.cozystack.io/monitoring label (see |
| 22 | +// packages/system/monitoring-agents/templates/_tenant-log-routes.tpl). |
| 23 | +// helm-controller only upgrades a release when its chart or values digest |
| 24 | +// changes, and lookup results are part of neither, so a tenant that turns |
| 25 | +// monitoring on would get no route, and a removed one would keep its route, |
| 26 | +// until some unrelated change upgraded the release. This reconciler closes |
| 27 | +// that gap: it digests the label across all namespaces and, when the digest |
| 28 | +// moves, requests a forced upgrade of the release, which re-runs the lookup. |
| 29 | +// |
| 30 | +// The digest covers every namespace carrying the label, whatever its value, |
| 31 | +// rather than repeating the chart's selection (non-empty and not |
| 32 | +// global.target). A superset can only cost an upgrade that renders the same |
| 33 | +// config, while a copy of the rule could drift from the chart and miss one. |
| 34 | +// For the same reason a release that carries no digest yet is forced once on |
| 35 | +// first sight: that also covers a namespace labelled between the install |
| 36 | +// render and the first sweep. |
| 37 | +package tenantlogrouting |
| 38 | + |
| 39 | +import ( |
| 40 | + "context" |
| 41 | + "crypto/sha256" |
| 42 | + "encoding/hex" |
| 43 | + "sort" |
| 44 | + "strings" |
| 45 | + |
| 46 | + helmv2 "github.com/fluxcd/helm-controller/api/v2" |
| 47 | + fluxmeta "github.com/fluxcd/pkg/apis/meta" |
| 48 | + corev1 "k8s.io/api/core/v1" |
| 49 | + "k8s.io/apimachinery/pkg/types" |
| 50 | + ctrl "sigs.k8s.io/controller-runtime" |
| 51 | + "sigs.k8s.io/controller-runtime/pkg/builder" |
| 52 | + "sigs.k8s.io/controller-runtime/pkg/client" |
| 53 | + "sigs.k8s.io/controller-runtime/pkg/event" |
| 54 | + "sigs.k8s.io/controller-runtime/pkg/handler" |
| 55 | + "sigs.k8s.io/controller-runtime/pkg/log" |
| 56 | + "sigs.k8s.io/controller-runtime/pkg/predicate" |
| 57 | + "sigs.k8s.io/controller-runtime/pkg/reconcile" |
| 58 | +) |
| 59 | + |
| 60 | +const ( |
| 61 | + // MonitoringLabel is written by the apps/tenant chart and names the tenant |
| 62 | + // whose monitoring stack a namespace reports to. |
| 63 | + MonitoringLabel = "namespace.cozystack.io/monitoring" |
| 64 | + |
| 65 | + // DigestAnnotation records, on the HelmRelease, the digest the last forced |
| 66 | + // upgrade was requested for. It is compared instead of requestedAt, which |
| 67 | + // anyone running `flux reconcile` overwrites, so that a manual reconcile |
| 68 | + // does not make the next sweep force one more upgrade. |
| 69 | + DigestAnnotation = "monitoring.cozystack.io/log-routing-digest" |
| 70 | +) |
| 71 | + |
| 72 | +// Release is the node-agent HelmRelease whose fluent-bit config carries the |
| 73 | +// routes (packages/core/platform/sources/monitoring-agents.yaml). |
| 74 | +var Release = types.NamespacedName{Namespace: "cozy-monitoring", Name: "monitoring-agents"} |
| 75 | + |
| 76 | +// Reconciler requests a forced upgrade of Release whenever the set of |
| 77 | +// namespace monitoring labels changes. |
| 78 | +type Reconciler struct { |
| 79 | + client.Client |
| 80 | +} |
| 81 | + |
| 82 | +// +kubebuilder:rbac:groups="",resources=namespaces,verbs=get;list;watch |
| 83 | +// +kubebuilder:rbac:groups=helm.toolkit.fluxcd.io,resources=helmreleases,verbs=get;list;watch;patch |
| 84 | + |
| 85 | +func (r *Reconciler) Reconcile(ctx context.Context, _ ctrl.Request) (ctrl.Result, error) { |
| 86 | + logger := log.FromContext(ctx) |
| 87 | + |
| 88 | + hr := &helmv2.HelmRelease{} |
| 89 | + if err := r.Get(ctx, Release, hr); err != nil { |
| 90 | + return ctrl.Result{}, client.IgnoreNotFound(err) |
| 91 | + } |
| 92 | + |
| 93 | + namespaces := &corev1.NamespaceList{} |
| 94 | + if err := r.List(ctx, namespaces); err != nil { |
| 95 | + return ctrl.Result{}, err |
| 96 | + } |
| 97 | + digest := Digest(namespaces.Items) |
| 98 | + if hr.GetAnnotations()[DigestAnnotation] == digest { |
| 99 | + return ctrl.Result{}, nil |
| 100 | + } |
| 101 | + |
| 102 | + patch := client.MergeFrom(hr.DeepCopy()) |
| 103 | + annotations := hr.GetAnnotations() |
| 104 | + if annotations == nil { |
| 105 | + annotations = map[string]string{} |
| 106 | + } |
| 107 | + // helm-controller runs a forced upgrade when forceAt equals requestedAt and |
| 108 | + // differs from the last one it handled; the digest serves as both tokens. |
| 109 | + annotations[DigestAnnotation] = digest |
| 110 | + annotations[fluxmeta.ReconcileRequestAnnotation] = digest |
| 111 | + annotations[fluxmeta.ForceRequestAnnotation] = digest |
| 112 | + hr.SetAnnotations(annotations) |
| 113 | + if err := r.Patch(ctx, hr, patch); err != nil { |
| 114 | + return ctrl.Result{}, err |
| 115 | + } |
| 116 | + logger.Info("namespace monitoring labels changed, forcing an upgrade of the node agents", "release", Release.String(), "digest", digest) |
| 117 | + return ctrl.Result{}, nil |
| 118 | +} |
| 119 | + |
| 120 | +// Digest hashes the monitoring label of every namespace that carries it, in |
| 121 | +// namespace order, so it moves exactly when a namespace gains the label, |
| 122 | +// loses it, changes its value, or is deleted. |
| 123 | +func Digest(namespaces []corev1.Namespace) string { |
| 124 | + pairs := make([]string, 0, len(namespaces)) |
| 125 | + for i := range namespaces { |
| 126 | + if target, ok := namespaces[i].Labels[MonitoringLabel]; ok { |
| 127 | + pairs = append(pairs, namespaces[i].Name+"="+target) |
| 128 | + } |
| 129 | + } |
| 130 | + sort.Strings(pairs) |
| 131 | + sum := sha256.Sum256([]byte(strings.Join(pairs, "\n"))) |
| 132 | + return hex.EncodeToString(sum[:8]) |
| 133 | +} |
| 134 | + |
| 135 | +// sweep coalesces every event into one reconcile: the digest spans all |
| 136 | +// namespaces, so there is nothing per-object to reconcile. |
| 137 | +var sweep = reconcile.Request{NamespacedName: Release} |
| 138 | + |
| 139 | +func (r *Reconciler) SetupWithManager(mgr ctrl.Manager) error { |
| 140 | + toSweep := handler.EnqueueRequestsFromMapFunc(func(context.Context, client.Object) []reconcile.Request { |
| 141 | + return []reconcile.Request{sweep} |
| 142 | + }) |
| 143 | + labelled := func(o client.Object) bool { |
| 144 | + _, ok := o.GetLabels()[MonitoringLabel] |
| 145 | + return ok |
| 146 | + } |
| 147 | + monitoringLabelChanged := predicate.Funcs{ |
| 148 | + CreateFunc: func(e event.CreateEvent) bool { return labelled(e.Object) }, |
| 149 | + DeleteFunc: func(e event.DeleteEvent) bool { return labelled(e.Object) }, |
| 150 | + UpdateFunc: func(e event.UpdateEvent) bool { |
| 151 | + oldValue, oldOK := e.ObjectOld.GetLabels()[MonitoringLabel] |
| 152 | + newValue, newOK := e.ObjectNew.GetLabels()[MonitoringLabel] |
| 153 | + return oldOK != newOK || oldValue != newValue |
| 154 | + }, |
| 155 | + GenericFunc: func(event.GenericEvent) bool { return false }, |
| 156 | + } |
| 157 | + isRelease := predicate.NewPredicateFuncs(func(o client.Object) bool { |
| 158 | + return o.GetNamespace() == Release.Namespace && o.GetName() == Release.Name |
| 159 | + }) |
| 160 | + return ctrl.NewControllerManagedBy(mgr). |
| 161 | + Named("tenantlogrouting-controller"). |
| 162 | + Watches(&corev1.Namespace{}, toSweep, builder.WithPredicates(monitoringLabelChanged)). |
| 163 | + Watches(&helmv2.HelmRelease{}, toSweep, builder.WithPredicates(isRelease)). |
| 164 | + Complete(r) |
| 165 | +} |
0 commit comments