|
| 1 | +package lineagecontrollerwebhook |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "encoding/json" |
| 6 | + "errors" |
| 7 | + "fmt" |
| 8 | + |
| 9 | + "github.com/cozystack/cozystack/pkg/lineage" |
| 10 | + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" |
| 11 | + "k8s.io/apimachinery/pkg/runtime/schema" |
| 12 | + "k8s.io/client-go/discovery" |
| 13 | + "k8s.io/client-go/discovery/cached/memory" |
| 14 | + "k8s.io/client-go/dynamic" |
| 15 | + "k8s.io/client-go/rest" |
| 16 | + "k8s.io/client-go/restmapper" |
| 17 | + ctrl "sigs.k8s.io/controller-runtime" |
| 18 | + "sigs.k8s.io/controller-runtime/pkg/client" |
| 19 | + "sigs.k8s.io/controller-runtime/pkg/log" |
| 20 | + "sigs.k8s.io/controller-runtime/pkg/webhook/admission" |
| 21 | +) |
| 22 | + |
| 23 | +var ( |
| 24 | + NoAncestors = fmt.Errorf("no managed apps found in lineage") |
| 25 | + AncestryAmbiguous = fmt.Errorf("object ancestry is ambiguous") |
| 26 | +) |
| 27 | + |
| 28 | +// SetupWithManager registers the handler with the webhook server. |
| 29 | +func (h *LineageControllerWebhook) SetupWithManagerAsWebhook(mgr ctrl.Manager) error { |
| 30 | + cfg := rest.CopyConfig(mgr.GetConfig()) |
| 31 | + |
| 32 | + var err error |
| 33 | + h.dynClient, err = dynamic.NewForConfig(cfg) |
| 34 | + if err != nil { |
| 35 | + return err |
| 36 | + } |
| 37 | + |
| 38 | + discoClient, err := discovery.NewDiscoveryClientForConfig(cfg) |
| 39 | + if err != nil { |
| 40 | + return err |
| 41 | + } |
| 42 | + |
| 43 | + cachedDisco := memory.NewMemCacheClient(discoClient) |
| 44 | + h.mapper = restmapper.NewDeferredDiscoveryRESTMapper(cachedDisco) |
| 45 | + |
| 46 | + // Register HTTP path -> handler. |
| 47 | + mgr.GetWebhookServer().Register("/mutate-lineage", &admission.Webhook{Handler: h}) |
| 48 | + |
| 49 | + return nil |
| 50 | +} |
| 51 | + |
| 52 | +// InjectDecoder lets controller-runtime give us a decoder for AdmissionReview requests. |
| 53 | +func (h *LineageControllerWebhook) InjectDecoder(d admission.Decoder) error { |
| 54 | + h.decoder = d |
| 55 | + return nil |
| 56 | +} |
| 57 | + |
| 58 | +// Handle is called for each AdmissionReview that matches the webhook config. |
| 59 | +func (h *LineageControllerWebhook) Handle(ctx context.Context, req admission.Request) admission.Response { |
| 60 | + logger := log.FromContext(ctx).WithValues( |
| 61 | + "gvk", req.Kind.String(), |
| 62 | + "namespace", req.Namespace, |
| 63 | + "name", req.Name, |
| 64 | + "operation", req.Operation, |
| 65 | + ) |
| 66 | + warn := make(admission.Warnings, 0) |
| 67 | + |
| 68 | + obj := &unstructured.Unstructured{} |
| 69 | + if err := h.decodeUnstructured(req, obj); err != nil { |
| 70 | + return admission.Errored(400, fmt.Errorf("decode object: %w", err)) |
| 71 | + } |
| 72 | + |
| 73 | + labels, err := h.computeLabels(ctx, obj) |
| 74 | + for { |
| 75 | + if err != nil && errors.Is(err, NoAncestors) { |
| 76 | + return admission.Allowed("object not managed by app") |
| 77 | + } |
| 78 | + if err != nil && errors.Is(err, AncestryAmbiguous) { |
| 79 | + warn = append(warn, "object ancestry ambiguous, using first ancestor found") |
| 80 | + break |
| 81 | + } |
| 82 | + if err != nil { |
| 83 | + return admission.Errored(500, fmt.Errorf("error computing lineage labels: %w", err)) |
| 84 | + } |
| 85 | + if err == nil { |
| 86 | + break |
| 87 | + } |
| 88 | + } |
| 89 | + |
| 90 | + h.applyLabels(obj, labels) |
| 91 | + |
| 92 | + mutated, err := json.Marshal(obj) |
| 93 | + if err != nil { |
| 94 | + return admission.Errored(500, fmt.Errorf("marshal mutated pod: %w", err)) |
| 95 | + } |
| 96 | + logger.V(1).Info("mutated pod", "namespace", obj.GetNamespace(), "name", obj.GetName()) |
| 97 | + return admission.PatchResponseFromRaw(req.Object.Raw, mutated).WithWarnings(warn...) |
| 98 | +} |
| 99 | + |
| 100 | +func (h *LineageControllerWebhook) computeLabels(ctx context.Context, o *unstructured.Unstructured) (map[string]string, error) { |
| 101 | + var err error |
| 102 | + owners := lineage.WalkOwnershipGraph(ctx, h.dynClient, h.mapper, h, o) |
| 103 | + if len(owners) == 0 { |
| 104 | + return nil, NoAncestors |
| 105 | + } |
| 106 | + if len(owners) > 1 { |
| 107 | + err = AncestryAmbiguous |
| 108 | + } |
| 109 | + obj, err2 := owners[0].GetUnstructured(ctx, h.dynClient, h.mapper) |
| 110 | + if err2 != nil { |
| 111 | + return nil, err2 |
| 112 | + } |
| 113 | + gv, err := schema.ParseGroupVersion(obj.GetAPIVersion()) |
| 114 | + if err != nil { |
| 115 | + // should never happen, we got an APIVersion right from the API |
| 116 | + return nil, fmt.Errorf("could not parse APIVersion %s to a group and version: %w", obj.GetAPIVersion(), err) |
| 117 | + } |
| 118 | + return map[string]string{ |
| 119 | + // truncate apigroup to first 63 chars |
| 120 | + "apps.cozystack.io/application.group": func(s string) string { |
| 121 | + if len(s) < 63 { |
| 122 | + return s |
| 123 | + } |
| 124 | + return s[:63] |
| 125 | + }(gv.Group), |
| 126 | + "apps.cozystack.io/application.kind": obj.GetKind(), |
| 127 | + "apps.cozystack.io/application.name": obj.GetName(), |
| 128 | + }, err |
| 129 | +} |
| 130 | + |
| 131 | +func (h *LineageControllerWebhook) applyLabels(o client.Object, labels map[string]string) { |
| 132 | + existing := o.GetLabels() |
| 133 | + if existing == nil { |
| 134 | + existing = make(map[string]string) |
| 135 | + } |
| 136 | + for k, v := range labels { |
| 137 | + existing[k] = v |
| 138 | + } |
| 139 | + o.SetLabels(existing) |
| 140 | +} |
| 141 | + |
| 142 | +func (h *LineageControllerWebhook) decodeUnstructured(req admission.Request, out *unstructured.Unstructured) error { |
| 143 | + if h.decoder != nil { |
| 144 | + if err := h.decoder.Decode(req, out); err == nil { |
| 145 | + return nil |
| 146 | + } |
| 147 | + if req.Kind.Group != "" || req.Kind.Kind != "" || req.Kind.Version != "" { |
| 148 | + out.SetGroupVersionKind(schema.GroupVersionKind{ |
| 149 | + Group: req.Kind.Group, |
| 150 | + Version: req.Kind.Version, |
| 151 | + Kind: req.Kind.Kind, |
| 152 | + }) |
| 153 | + if err := h.decoder.Decode(req, out); err == nil { |
| 154 | + return nil |
| 155 | + } |
| 156 | + } |
| 157 | + } |
| 158 | + if len(req.Object.Raw) == 0 { |
| 159 | + return errors.New("empty admission object") |
| 160 | + } |
| 161 | + return json.Unmarshal(req.Object.Raw, &out.Object) |
| 162 | +} |
0 commit comments