blob: b79134114b612b40c1b8ab3816f9f20f843b34cd [file] [log] [blame]
Serge Bazanskie6030f62020-06-03 17:52:59 +02001// Copyright 2020 The Monogon Project Authors.
2//
3// SPDX-License-Identifier: Apache-2.0
4//
5// Licensed under the Apache License, Version 2.0 (the "License");
6// you may not use this file except in compliance with the License.
7// You may obtain a copy of the License at
8//
9// http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing, software
12// distributed under the License is distributed on an "AS IS" BASIS,
13// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14// See the License for the specific language governing permissions and
15// limitations under the License.
16
Serge Bazanski662b5b32020-12-21 13:49:00 +010017// The reconciler ensures that a base set of K8s resources is always available
18// in the cluster. These are necessary to ensure correct out-of-the-box
19// functionality. All resources containing the
20// metropolis.monogon.dev/builtin=true label are assumed to be managed by the
21// reconciler.
22// It currently does not revert modifications made by admins, it is planned to
23// create an admission plugin prohibiting such modifications to resources with
24// the metropolis.monogon.dev/builtin label to deal with that problem. This
25// would also solve a potential issue where you could delete resources just by
26// adding the metropolis.monogon.dev/builtin=true label.
Serge Bazanskie6030f62020-06-03 17:52:59 +020027package reconciler
28
29import (
30 "context"
Jan Schär69f5f4e2024-05-15 10:32:07 +020031 "errors"
Serge Bazanskie6030f62020-06-03 17:52:59 +020032 "fmt"
Jan Schär69f5f4e2024-05-15 10:32:07 +020033 "strings"
Serge Bazanskie6030f62020-06-03 17:52:59 +020034
Jan Schär69f5f4e2024-05-15 10:32:07 +020035 apiequality "k8s.io/apimachinery/pkg/api/equality"
36 apierrors "k8s.io/apimachinery/pkg/api/errors"
37 apivalidation "k8s.io/apimachinery/pkg/api/validation"
Serge Bazanskie6030f62020-06-03 17:52:59 +020038 meta "k8s.io/apimachinery/pkg/apis/meta/v1"
Serge Bazanskie6030f62020-06-03 17:52:59 +020039 "k8s.io/client-go/kubernetes"
Jan Schär69f5f4e2024-05-15 10:32:07 +020040
Tim Windelschmidt9f21f532024-05-07 15:14:20 +020041 "source.monogon.dev/osbase/supervisor"
Serge Bazanskie6030f62020-06-03 17:52:59 +020042)
43
Serge Bazanskie6030f62020-06-03 17:52:59 +020044const (
Serge Bazanski216fe7b2021-05-21 18:36:16 +020045 // BuiltinLabelKey is used as a k8s label to mark built-in objects (ie.,
46 // managed by the reconciler)
Serge Bazanski662b5b32020-12-21 13:49:00 +010047 BuiltinLabelKey = "metropolis.monogon.dev/builtin"
Serge Bazanski216fe7b2021-05-21 18:36:16 +020048 // BuiltinLabelValue is used as a k8s label value, under the
49 // BuiltinLabelKey key.
Serge Bazanskie6030f62020-06-03 17:52:59 +020050 BuiltinLabelValue = "true"
Serge Bazanski216fe7b2021-05-21 18:36:16 +020051 // BuiltinRBACPrefix is used to prefix all built-in objects that are part
52 // of the rbac/v1 API (eg. {Cluster,}Role{Binding,} objects). This
53 // corresponds to the colon-separated 'namespaces' notation used by
Serge Bazanskie6030f62020-06-03 17:52:59 +020054 // Kubernetes system (system:) objects.
Serge Bazanski662b5b32020-12-21 13:49:00 +010055 BuiltinRBACPrefix = "metropolis:"
Serge Bazanskie6030f62020-06-03 17:52:59 +020056)
57
Serge Bazanski216fe7b2021-05-21 18:36:16 +020058// builtinLabels makes a kubernetes-compatible label dictionary (key->value)
59// that is used to mark objects that are built-in into Metropolis (ie., managed
60// by the reconciler). These are then subsequently retrieved by listBuiltins.
61// The extra argument specifies what other labels are to be merged into the the
62// labels dictionary, for convenience. If nil or empty, no extra labels will be
63// applied.
Serge Bazanskie6030f62020-06-03 17:52:59 +020064func builtinLabels(extra map[string]string) map[string]string {
65 l := map[string]string{
66 BuiltinLabelKey: BuiltinLabelValue,
67 }
Tim Windelschmidt24ce66f2024-04-18 23:59:24 +020068 for k, v := range extra {
69 l[k] = v
Serge Bazanskie6030f62020-06-03 17:52:59 +020070 }
71 return l
72}
73
Serge Bazanski216fe7b2021-05-21 18:36:16 +020074// listBuiltins returns a k8s client ListOptions structure that allows to
75// retrieve all objects that are built-in into Metropolis currently present in
76// the API server (ie., ones that are to be managed by the reconciler). These
77// are created by applying builtinLabels to their metadata labels.
Serge Bazanskie6030f62020-06-03 17:52:59 +020078var listBuiltins = meta.ListOptions{
79 LabelSelector: fmt.Sprintf("%s=%s", BuiltinLabelKey, BuiltinLabelValue),
80}
81
Serge Bazanski216fe7b2021-05-21 18:36:16 +020082// builtinRBACName returns a name that is compatible with colon-delimited
83// 'namespaced' objects, a la system:*.
84// These names are to be used by all builtins created as part of the rbac/v1
85// Kubernetes API.
Serge Bazanskie6030f62020-06-03 17:52:59 +020086func builtinRBACName(name string) string {
87 return BuiltinRBACPrefix + name
88}
89
Serge Bazanski216fe7b2021-05-21 18:36:16 +020090// resource is a type of resource to be managed by the reconciler. All
Jan Schär7f727482024-03-25 13:03:51 +010091// built-ins/reconciled objects must implement this interface to be managed
Serge Bazanski216fe7b2021-05-21 18:36:16 +020092// correctly by the reconciler.
Serge Bazanskie6030f62020-06-03 17:52:59 +020093type resource interface {
Jan Schär7f727482024-03-25 13:03:51 +010094 // List returns a list of objects currently present on the target
Serge Bazanski216fe7b2021-05-21 18:36:16 +020095 // (ie. k8s API server).
Jan Schär7f727482024-03-25 13:03:51 +010096 List(ctx context.Context) ([]meta.Object, error)
97 // Create creates an object on the target. The el argument is
98 // an object returned by the Expected() call.
99 Create(ctx context.Context, el meta.Object) error
Jan Schär69f5f4e2024-05-15 10:32:07 +0200100 // Update updates an existing object, by name, on the target.
101 // The el argument is an object returned by the Expected() call.
102 Update(ctx context.Context, el meta.Object) error
Jan Schär7f727482024-03-25 13:03:51 +0100103 // Delete deletes an object, by name, from the target.
Jan Schär69f5f4e2024-05-15 10:32:07 +0200104 Delete(ctx context.Context, name string, opts meta.DeleteOptions) error
Jan Schär7f727482024-03-25 13:03:51 +0100105 // Expected returns a list of all objects expected to be present on the
106 // target. Objects are identified by their name, as returned by GetName.
107 Expected() []meta.Object
Serge Bazanskie6030f62020-06-03 17:52:59 +0200108}
109
110func allResources(clientSet kubernetes.Interface) map[string]resource {
111 return map[string]resource{
Serge Bazanskie6030f62020-06-03 17:52:59 +0200112 "clusterroles": resourceClusterRoles{clientSet},
113 "clusterrolebindings": resourceClusterRoleBindings{clientSet},
114 "storageclasses": resourceStorageClasses{clientSet},
115 "csidrivers": resourceCSIDrivers{clientSet},
Lorenz Brun5e4fc2d2020-09-22 18:35:15 +0200116 "runtimeclasses": resourceRuntimeClasses{clientSet},
Serge Bazanskie6030f62020-06-03 17:52:59 +0200117 }
118}
119
Jan Schärd20ddcc2024-05-08 14:18:29 +0200120func reconcileAll(ctx context.Context, clientSet kubernetes.Interface) error {
Serge Bazanski356cbf32023-03-16 17:52:20 +0100121 resources := allResources(clientSet)
122 for name, resource := range resources {
Jan Schär69f5f4e2024-05-15 10:32:07 +0200123 err := reconcile(ctx, resource, name)
Serge Bazanski356cbf32023-03-16 17:52:20 +0100124 if err != nil {
125 return fmt.Errorf("resource %s: %w", name, err)
126 }
127 }
128 return nil
129}
130
Jan Schär69f5f4e2024-05-15 10:32:07 +0200131func reconcile(ctx context.Context, r resource, rname string) error {
132 log := supervisor.Logger(ctx)
Serge Bazanskie6030f62020-06-03 17:52:59 +0200133 present, err := r.List(ctx)
134 if err != nil {
135 return err
136 }
Jan Schär7f727482024-03-25 13:03:51 +0100137 presentMap := make(map[string]meta.Object)
Serge Bazanskie6030f62020-06-03 17:52:59 +0200138 for _, el := range present {
Jan Schär7f727482024-03-25 13:03:51 +0100139 presentMap[el.GetName()] = el
Serge Bazanskie6030f62020-06-03 17:52:59 +0200140 }
Jan Schär7f727482024-03-25 13:03:51 +0100141 expected := r.Expected()
142 expectedMap := make(map[string]meta.Object)
143 for _, el := range expected {
144 expectedMap[el.GetName()] = el
145 }
146 for name, expectedEl := range expectedMap {
Jan Schär69f5f4e2024-05-15 10:32:07 +0200147 if presentEl, ok := presentMap[name]; ok {
148 // The object already exists. Update it if it is different than expected.
149
150 // The server rejects updates which don't have an up to date ResourceVersion.
151 expectedEl.SetResourceVersion(presentEl.GetResourceVersion())
152
153 // Clear out fields set by the server, such that comparison succeeds if
154 // there are no other changes.
155 presentEl.SetUID("")
156 presentEl.SetGeneration(0)
157 presentEl.SetCreationTimestamp(meta.Time{})
158 presentEl.SetManagedFields(nil)
159
160 if !apiequality.Semantic.DeepEqual(presentEl, expectedEl) {
161 log.Infof("Updating %s object %q", rname, name)
162 if err := r.Update(ctx, expectedEl); err != nil {
163 if !isImmutableError(err) {
164 return err
165 }
166 log.Infof("Failed to update object due to immutable fields; deleting and recreating: %v", err)
167
168 // Only delete if the ResourceVersion has not changed. If it has
169 // changed, that means another reconciler was faster than us and
170 // has already recreated the object.
171 resourceVersion := presentEl.GetResourceVersion()
172 deleteOpts := meta.DeleteOptions{
173 Preconditions: &meta.Preconditions{
174 ResourceVersion: &resourceVersion,
175 },
176 }
177 // ResourceVersion must be cleared when creating.
178 expectedEl.SetResourceVersion("")
179
180 if err := r.Delete(ctx, name, deleteOpts); err != nil {
181 return err
182 }
183 if err := r.Create(ctx, expectedEl); err != nil {
184 return err
185 }
186 }
187 }
Jan Schär7f727482024-03-25 13:03:51 +0100188 } else {
Jan Schär69f5f4e2024-05-15 10:32:07 +0200189 log.Infof("Creating %s object %q", rname, name)
Jan Schär7f727482024-03-25 13:03:51 +0100190 if err := r.Create(ctx, expectedEl); err != nil {
Serge Bazanskie6030f62020-06-03 17:52:59 +0200191 return err
192 }
193 }
194 }
Tim Windelschmidt6b6428d2024-04-11 01:35:41 +0200195 for name := range presentMap {
Serge Bazanskie6030f62020-06-03 17:52:59 +0200196 if _, ok := expectedMap[name]; !ok {
Jan Schär69f5f4e2024-05-15 10:32:07 +0200197 log.Infof("Deleting %s object %q", rname, name)
198 if err := r.Delete(ctx, name, meta.DeleteOptions{}); err != nil {
Serge Bazanskie6030f62020-06-03 17:52:59 +0200199 return err
200 }
201 }
202 }
203 return nil
204}
Jan Schär69f5f4e2024-05-15 10:32:07 +0200205
206// isImmutableError returns true if err indicates that an update failed because
207// of an attempt to update one or more immutable fields.
208func isImmutableError(err error) bool {
209 if !apierrors.IsInvalid(err) {
210 return false
211 }
212 var status apierrors.APIStatus
213 if !errors.As(err, &status) {
214 return false
215 }
216 details := status.Status().Details
217 if details == nil || len(details.Causes) == 0 {
218 return false
219 }
220 for _, cause := range details.Causes {
221 if !strings.Contains(cause.Message, apivalidation.FieldImmutableErrorMsg) {
222 return false
223 }
224 }
225 return true
226}