-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
serversidepathhelper.go
301 lines (259 loc) · 11.1 KB
/
serversidepathhelper.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
/*
Copyright 2022 The Kubernetes Authors.
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 structuredmerge
import (
"encoding/json"
"strings"
jsonpatch "github.com/evanphx/json-patch/v5"
"github.com/pkg/errors"
"golang.org/x/net/context"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/types"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
clusterv1 "sigs.k8s.io/cluster-api/api/v1beta1"
"sigs.k8s.io/cluster-api/internal/contract"
)
const (
// TopologyManagerName is the manager name in managed fields for the topology controller.
TopologyManagerName = "capi-topology"
)
// allowedPaths defines the list of paths that the topology controller should express opinion on.
var allowedPaths = []contract.Path{
// apiVersion, kind, name and namespace are required field for a server side apply intent.
{"apiVersion"},
{"kind"},
{"metadata", "name"},
{"metadata", "namespace"},
// the topology controller controls/has an opinion for labels, annotation, ownerReferences and spec only.
{"metadata", "labels"},
{"metadata", "annotations"},
{"metadata", "ownerReferences"},
{"spec"},
}
type serverSidePatchHelper struct {
client client.Client
modified *unstructured.Unstructured
hasChanges bool
hasSpecChanges bool
originalUID types.UID
}
// NewServerSidePatchHelper returns a new PatchHelper using server side apply.
func NewServerSidePatchHelper(ctx context.Context, original, modified client.Object, c client.Client, opts ...HelperOption) (PatchHelper, error) {
helperOptions := &HelperOptions{}
helperOptions = helperOptions.ApplyOptions(opts)
helperOptions.allowedPaths = allowedPaths
// If required, convert the original and modified objects to unstructured and filter out all the information
// not relevant for the topology controller.
var originalUnstructured *unstructured.Unstructured
if !isNil(original) {
originalUnstructured = &unstructured.Unstructured{}
switch original.(type) {
case *unstructured.Unstructured:
originalUnstructured = original.DeepCopyObject().(*unstructured.Unstructured)
default:
if err := c.Scheme().Convert(original, originalUnstructured, nil); err != nil {
return nil, errors.Wrap(err, "failed to convert original object to Unstructured")
}
}
// If the object has been created with previous custom approach for tracking managed fields, cleanup the object.
if _, ok := original.GetAnnotations()[clusterv1.ClusterTopologyManagedFieldsAnnotation]; ok {
if err := cleanupLegacyManagedFields(ctx, originalUnstructured, c); err != nil {
return nil, errors.Wrap(err, "failed to cleanup legacy managed fields from original object")
}
}
}
modifiedUnstructured := &unstructured.Unstructured{}
switch modified.(type) {
case *unstructured.Unstructured:
modifiedUnstructured = modified.DeepCopyObject().(*unstructured.Unstructured)
default:
if err := c.Scheme().Convert(modified, modifiedUnstructured, nil); err != nil {
return nil, errors.Wrap(err, "failed to convert modified object to Unstructured")
}
}
filterObject(modifiedUnstructured, helperOptions)
// Determine if the intent defined in the modified object is going to trigger
// an actual change when running server side apply, and if this change might impact the object spec or not.
var hasChanges, hasSpecChanges bool
var originalUID types.UID
switch {
case isNil(original):
hasChanges, hasSpecChanges = true, true
default:
var err error
hasChanges, hasSpecChanges, err = dryRunSSAPatch(ctx, c,
originalUnstructured,
modifiedUnstructured,
opts...)
if err != nil {
return nil, errors.Wrap(err, "failed to determine changes via dryRunSSAPatch")
}
originalUID = originalUnstructured.GetUID()
}
return &serverSidePatchHelper{
client: c,
modified: modifiedUnstructured,
hasChanges: hasChanges,
hasSpecChanges: hasSpecChanges,
originalUID: originalUID,
}, nil
}
// HasSpecChanges return true if the patch has changes to the spec field.
func (h *serverSidePatchHelper) HasSpecChanges() bool {
return h.hasSpecChanges
}
// HasChanges return true if the patch has changes.
func (h *serverSidePatchHelper) HasChanges() bool {
return h.hasChanges
}
// Patch will server side apply the current intent (the modified object.
func (h *serverSidePatchHelper) Patch(ctx context.Context) error {
if !h.HasChanges() {
return nil
}
log := ctrl.LoggerFrom(ctx)
log.V(5).Info("Patching object", "Intent", h.modified)
h.modified.SetUID(h.originalUID)
options := []client.PatchOption{
client.FieldOwner(TopologyManagerName),
// NOTE: we are using force ownership so in case of conflicts the topology controller
// overwrite values and become sole manager.
client.ForceOwnership,
}
return h.client.Patch(ctx, h.modified, client.Apply, options...)
}
// dryRunSSAPatch uses server side apply dry run to determine if the operation is going to change the actual object.
func dryRunSSAPatch(ctx context.Context, c client.Client, originalUnstructured, modifiedUnstructured *unstructured.Unstructured, opts ...HelperOption) (bool, bool, error) {
// For dry run we use the same options as for the intent but with adding metadata.managedFields
// so we can ensure that changes to ownership are detected.
dryRunHelperOptions := &HelperOptions{}
dryRunHelperOptions = dryRunHelperOptions.ApplyOptions(opts)
dryRunHelperOptions.allowedPaths = append(allowedPaths, []string{"metadata", "managedFields"})
dryRunUnstructured := modifiedUnstructured.DeepCopy()
dryRunUnstructured.SetUID(originalUnstructured.GetUID())
err := c.Patch(ctx, dryRunUnstructured, client.Apply, client.DryRunAll, client.FieldOwner(TopologyManagerName), client.ForceOwnership)
if err != nil {
// If a webhook blocks due to immutability of spec fields the dryRun for sure
// has spec changes.
if isInvalidSpecChangesStatusError(err) {
return true, true, nil
}
// This catches errors like metadata.uid changes.
return false, false, errors.Wrap(err, "failed to request dry-run server side apply")
}
// Drop output of dry run all the fields that are not part of our intent.
filterObject(dryRunUnstructured, dryRunHelperOptions)
filterObject(originalUnstructured, dryRunHelperOptions)
// Compare the output of dry run to the original object.
originalJSON, err := json.Marshal(originalUnstructured)
if err != nil {
return false, false, errors.Wrap(err, "failed to marshal originalUnstructured")
}
dryRunJSON, err := json.Marshal(dryRunUnstructured)
if err != nil {
return false, false, errors.Wrap(err, "failed to marshal dryRunUnstructured")
}
rawDiff, err := jsonpatch.CreateMergePatch(originalJSON, dryRunJSON)
if err != nil {
return false, false, errors.Wrap(err, "failed to create MergePatch for original and dryRun JSON")
}
// Determine if there are changes to the spec and object.
diff := map[string]interface{}{}
if err := json.Unmarshal(rawDiff, &diff); err != nil {
return false, false, errors.Wrap(err, "failed to unmarshal diff")
}
hasChanges := len(diff) > 0
_, hasSpecChanges := diff["spec"]
return hasChanges, hasSpecChanges, nil
}
// cleanupLegacyManagedFields cleanups managed field management in place before introducing SSA.
// NOTE: this operation can trigger a machine rollout, but this is considered acceptable given that ClusterClass is still alpha
// and SSA adoption align the topology controller with K8s recommended solution for many controllers authoring the same object.
func cleanupLegacyManagedFields(ctx context.Context, obj *unstructured.Unstructured, c client.Client) error {
base := obj.DeepCopyObject().(*unstructured.Unstructured)
// Remove the topology.cluster.x-k8s.io/managed-field-paths annotation
annotations := obj.GetAnnotations()
delete(annotations, clusterv1.ClusterTopologyManagedFieldsAnnotation)
obj.SetAnnotations(annotations)
// Remove managedFieldEntry for manager=manager and operation=update to prevent having two managers holding values set by the topology controller.
originalManagedFields := obj.GetManagedFields()
managedFields := make([]metav1.ManagedFieldsEntry, 0, len(originalManagedFields))
for i := range originalManagedFields {
if originalManagedFields[i].Manager == "manager" &&
originalManagedFields[i].Operation == metav1.ManagedFieldsOperationUpdate {
continue
}
managedFields = append(managedFields, originalManagedFields[i])
}
// Add a seeding managedFieldEntry for SSA executed by the management controller, to prevent SSA to create/infer
// a default managedFieldEntry when the first SSA is applied.
// More specifically, if an existing object doesn't have managedFields when applying the first SSA the API server
// creates an entry with operation=Update (kind of guessing where the object comes from), but this entry ends up
// acting as a co-ownership and we want to prevent this.
// NOTE: fieldV1Map cannot be empty, so we add metadata.name which will be cleaned up at the first SSA patch.
fieldV1Map := map[string]interface{}{
"f:metadata": map[string]interface{}{
"f:name": map[string]interface{}{},
},
}
fieldV1, err := json.Marshal(fieldV1Map)
if err != nil {
return errors.Wrap(err, "failed to create seeding fieldV1Map for cleaning up legacy managed fields")
}
now := metav1.Now()
managedFields = append(managedFields, metav1.ManagedFieldsEntry{
Manager: TopologyManagerName,
Operation: metav1.ManagedFieldsOperationApply,
APIVersion: obj.GetAPIVersion(),
Time: &now,
FieldsType: "FieldsV1",
FieldsV1: &metav1.FieldsV1{Raw: fieldV1},
})
obj.SetManagedFields(managedFields)
return c.Patch(ctx, obj, client.MergeFrom(base))
}
// isInvalidSpecChangesStatusError identifies an error to be only caused by fields
// inside spec which have an invalid value. This is the case if e.g. a validating
// webhook blocks updating a field due to immutability.
func isInvalidSpecChangesStatusError(err error) bool {
if !apierrors.IsInvalid(err) {
return false
}
statusErr, ok := err.(*apierrors.StatusError)
if !ok {
return false
}
// It is expected to contain details about the fields causing the error.
if statusErr.Status().Details == nil {
return false
}
// It is expected to find at least a single cause
if len(statusErr.Status().Details.Causes) == 0 {
return false
}
for _, cause := range statusErr.Status().Details.Causes {
// If a cause is CauseTypeFieldValueInvalid it could be realated to other errors.
if cause.Type != metav1.CauseTypeFieldValueInvalid {
return false
}
// If a field is not below spec it could be related to invalid values which
// would not be solved through template rotation
if !strings.HasPrefix(cause.Field, "spec.") {
return false
}
}
return true
}