/
extramanifest.go
502 lines (431 loc) · 18.4 KB
/
extramanifest.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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
/*
Copyright 2023.
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 extramanifest
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"strconv"
"github.com/coreos/go-semver/semver"
"github.com/go-logr/logr"
lcav1alpha1 "github.com/openshift-kni/lifecycle-agent/api/v1alpha1"
"github.com/openshift-kni/lifecycle-agent/internal/common"
"github.com/openshift-kni/lifecycle-agent/utils"
"github.com/samber/lo"
corev1 "k8s.io/api/core/v1"
apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
k8serrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/meta"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/yaml"
"k8s.io/client-go/discovery"
"k8s.io/client-go/dynamic"
policyv1 "open-cluster-management.io/config-policy-controller/api/v1"
"sigs.k8s.io/controller-runtime/pkg/client"
)
const (
ExtraManifestPath = "/opt/extra-manifests"
PolicyManifestPath = "/opt/policy-manifests"
WarnAnnotationUnknownCRDKey = "lca.openshift.io/warn-extramanifest-cm-unknown-crd"
)
type EManifestHandler interface {
ApplyExtraManifests(ctx context.Context, fromDir string) error
ExportExtraManifestToDir(ctx context.Context, extraManifestCMs []lcav1alpha1.ConfigMapRef, toDir string) error
ExtractAndExportManifestFromPoliciesToDir(ctx context.Context, policyLabels, objectLabels, validationAnns map[string]string, toDir string) error
ValidateAndExtractManifestFromPolicies(ctx context.Context, policyLabels, objectLabels, validationAnns map[string]string) ([][]*unstructured.Unstructured, error)
ValidateExtraManifestConfigmaps(ctx context.Context, extraManifestCMs []lcav1alpha1.ConfigMapRef, ibu *lcav1alpha1.ImageBasedUpgrade) error
}
// EMHandler handles the extra manifests
type EMHandler struct {
Client client.Client
DynamicClient dynamic.Interface
Log logr.Logger
}
// EMStatusError type
type EMStatusError struct {
Reason string
ErrMessage string
}
func (e *EMStatusError) Error() string {
return fmt.Sprintf(e.ErrMessage)
}
func NewEMFailedError(msg string) *EMStatusError {
return &EMStatusError{
Reason: "Failed",
ErrMessage: msg,
}
}
func NewEMFailedValidationError(msg string) *EMStatusError {
return &EMStatusError{
Reason: "FailedValidation",
ErrMessage: msg,
}
}
func NewEMUnknownCRDError(msg string) *EMStatusError {
return &EMStatusError{
Reason: "UnknownCRD",
ErrMessage: msg,
}
}
func IsEMFailedError(err error) bool {
var emErr *EMStatusError
if errors.As(err, &emErr) {
return emErr.Reason == "Failed"
}
return false
}
func ApplyExtraManifest(ctx context.Context, dc dynamic.Interface, restMapper meta.RESTMapper, manifest *unstructured.Unstructured, isDryRun bool) error {
// Mapping resource GVK to CVR
mapping, err := restMapper.RESTMapping(manifest.GroupVersionKind().GroupKind(), manifest.GroupVersionKind().Version)
if err != nil {
return fmt.Errorf("failed to get RESTMapping: %w", err)
}
// Check if the resource exists
existingManifest := &unstructured.Unstructured{}
existingManifest.SetGroupVersionKind(manifest.GroupVersionKind())
resource := dc.Resource(mapping.Resource).Namespace(manifest.GetNamespace())
existingManifest, err = resource.Get(ctx, manifest.GetName(), metav1.GetOptions{})
if err != nil {
if !k8serrors.IsNotFound(err) {
return fmt.Errorf("failed to get manifest %s called %s: %w", manifest.GetKind(), manifest.GetName(), err)
}
opts := metav1.CreateOptions{}
if isDryRun {
opts = metav1.CreateOptions{
DryRun: []string{metav1.DryRunAll},
}
}
manifest.SetResourceVersion("")
if _, err := resource.Create(ctx, manifest, opts); err != nil {
return fmt.Errorf("failed to create manifest %s called %s: %w", manifest.GetKind(), manifest.GetName(), err)
}
} else {
applyType := common.ApplyTypeReplace
if metadata, exists := manifest.Object["metadata"].(map[string]interface{}); exists {
if annotations, exists := metadata["annotations"].(map[string]interface{}); exists {
if at, exists := annotations[common.ApplyTypeAnnotation]; exists {
applyType = at.(string)
// Remove the annotation as it serves no purpose at runtime
delete(annotations, common.ApplyTypeAnnotation)
}
}
}
opts := metav1.UpdateOptions{}
if isDryRun {
opts = metav1.UpdateOptions{
DryRun: []string{metav1.DryRunAll},
}
}
switch applyType {
case common.ApplyTypeReplace:
manifest.SetResourceVersion(existingManifest.GetResourceVersion())
if _, err := resource.Update(ctx, manifest, opts); err != nil {
return fmt.Errorf("failed to replace manifest %s called %s: %w", manifest.GetKind(), manifest.GetName(), err)
}
case common.ApplyTypeMerge:
mergedObj, err := mergeSpecs(manifest.Object, existingManifest.Object, string(policyv1.MustHave), false)
if err != nil {
return fmt.Errorf("failed to merge manifest %s called %s: %w", manifest.GetKind(), manifest.GetName(), err)
}
merged := &unstructured.Unstructured{Object: mergedObj.(map[string]interface{})}
merged.SetResourceVersion(existingManifest.GetResourceVersion())
if _, err := resource.Update(ctx, merged, opts); err != nil {
return fmt.Errorf("failed to update manifest %s called %s: %w", manifest.GetKind(), manifest.GetName(), err)
}
}
}
return nil
}
func (h *EMHandler) ValidateExtraManifestConfigmaps(ctx context.Context, content []lcav1alpha1.ConfigMapRef, ibu *lcav1alpha1.ImageBasedUpgrade) error {
configmaps, err := common.GetConfigMaps(ctx, h.Client, content)
if err != nil {
if k8serrors.IsNotFound(err) {
h.Log.Error(err, "The extraManifests configMap is not found")
errMsg := fmt.Sprintf("the extraManifests configMap is not found, error: %v. Please create the configMap.", err)
return NewEMFailedValidationError(errMsg)
}
return fmt.Errorf("failed to get configMaps to export extraManifest to dir: %w", err)
}
manifests, err := h.extractManifestFromConfigmaps(configmaps)
if err != nil {
return fmt.Errorf("failed to extract manifests from configMap: %w", err)
}
// MachineConfig can trigger reboot and this will result in not meeting KPI downtime requirement
// so raise validation error if there is a MachineConfig in extramanifests
for _, manifest := range manifests {
if manifest.GetKind() == "MachineConfig" && manifest.GetAPIVersion() == "machineconfiguration.openshift.io/v1" {
return NewEMFailedValidationError("Using MachingConfigs in extramanifests is not allowed")
}
}
// a map to track all the unknown CRDs in one shot
unknownCRDs := make(map[string]string)
// Apply manifest with dryRun
dryRun := true
// Collect unknownCRDs errors and continue to treat them as part of warning.
// Any other error should be treated as real error and return early (which should be priority over warnings)
for _, manifest := range manifests {
if err := ApplyExtraManifest(ctx, h.DynamicClient, h.Client.RESTMapper(), manifest, dryRun); err != nil {
defaultErrMsg := fmt.Sprintf("failed to apply manifest with dryrun: %v", err.Error())
var groupDiscoveryErr *discovery.ErrGroupDiscoveryFailed
switch {
case errors.As(err, &groupDiscoveryErr) || meta.IsNoMatchError(err): // Capture unknown CRD issue
key := manifest.GroupVersionKind().String()
if _, exists := unknownCRDs[key]; !exists {
unknownCRDs[key] = manifest.GetName()
h.Log.Info("unknown CRD", "CRD", key)
}
case k8serrors.IsInvalid(err) || k8serrors.IsBadRequest(err): // Capture both invalid syntax and webhook validation errors
return NewEMFailedValidationError(defaultErrMsg)
default: // Capture unknown runtime error
return fmt.Errorf(defaultErrMsg)
}
}
}
// annotate with the unknown CRDs
if len(unknownCRDs) > 0 {
b, err := json.Marshal(unknownCRDs)
if err != nil {
return fmt.Errorf("failed to marshal unknownCRDs map: %w", err)
}
annotationValue := string(b)
h.Log.Info(fmt.Sprintf("Unknown CRDs detected, will annotate with: %s", annotationValue))
if err := AddAnnotationWarnUnknownCRD(h.Client, h.Log, ibu, annotationValue); err != nil {
return fmt.Errorf("could not add new annotations to IBU: %w", err)
}
}
h.Log.Info("ExtraManifests configmaps are validated", "configmaps", content)
return nil
}
func (h *EMHandler) extractManifestFromConfigmaps(configmaps []corev1.ConfigMap) ([]*unstructured.Unstructured, error) {
var manifests []*unstructured.Unstructured
for _, cm := range configmaps {
for _, value := range cm.Data {
decoder := yaml.NewYAMLOrJSONDecoder(bytes.NewBufferString(value), 4096)
for {
resource := unstructured.Unstructured{}
err := decoder.Decode(&resource)
if err != nil {
if errors.Is(err, io.EOF) {
// Reach the end of the data, exit the loop
break
}
h.Log.Error(err, "Failed to decode yaml in the configMap", "configmap", cm.Name)
errMsg := fmt.Sprintf("failed to decode yaml in the configMap %s: %v", cm.Name, err.Error())
return nil, NewEMFailedValidationError(errMsg)
}
// In case it contains the UID and ResourceVersion, remove them
resource.SetUID("")
resource.SetResourceVersion("")
manifests = append(manifests, &resource)
}
}
}
return manifests, nil
}
// ExportExtraManifestToDir extracts the extra manifests from configmaps
// and writes them to the given directory
func (h *EMHandler) ExportExtraManifestToDir(ctx context.Context, extraManifestCMs []lcav1alpha1.ConfigMapRef, toDir string) error {
if extraManifestCMs == nil {
h.Log.Info("No extra manifests configmap is provided")
return nil
}
configmaps, err := common.GetConfigMaps(ctx, h.Client, extraManifestCMs)
if err != nil {
if k8serrors.IsNotFound(err) {
h.Log.Error(err, "The extraManifests configMap is not found")
errMsg := fmt.Sprintf("the extraManifests configMap is not found, error: %v. Please create the configMap.", err)
return NewEMFailedError(errMsg)
}
return fmt.Errorf("failed to get configMaps to export extraManifest to dir: %w", err)
}
manifests, err := h.extractManifestFromConfigmaps(configmaps)
if err != nil {
return fmt.Errorf("failed to extract manifests from configMap: %w", err)
}
sortedManifests, err := common.SortAndGroupByApplyWave[*unstructured.Unstructured](manifests)
if err != nil {
return fmt.Errorf("failed to sort and group manifests: %w", err)
}
// Create the directory for the extra manifests
exMDirPath := filepath.Join(toDir, ExtraManifestPath)
if err := os.MkdirAll(exMDirPath, 0o700); err != nil {
return fmt.Errorf("failed to create directory for extra manifests in %s: %w", exMDirPath, err)
}
for i, manifestGroup := range sortedManifests {
group := filepath.Join(toDir, ExtraManifestPath, "group"+strconv.Itoa(i+1))
if err := os.MkdirAll(group, 0o700); err != nil {
return fmt.Errorf("failed make dir in %s: %w", group, err)
}
for j, manifest := range manifestGroup {
fileName := fmt.Sprintf("%d_%s_%s_%s.yaml", j+1, manifest.GetKind(), manifest.GetName(), manifest.GetNamespace())
filePath := filepath.Join(group, fileName)
if err := utils.MarshalToYamlFile(manifest, filePath); err != nil {
return fmt.Errorf("failed to marshal manifest %s to yaml: %w", manifest.GetName(), err)
}
h.Log.Info("Exported manifest to file", "path", filePath)
}
}
return nil
}
// ExtractAndExportManifestFromPoliciesToDir extracts CR specs from policies and writes to a given directory. It matches policies and/or CRs by labels.
func (h *EMHandler) ExtractAndExportManifestFromPoliciesToDir(ctx context.Context, policyLabels, objectLabels, validationAnns map[string]string, toDir string) error {
crd := &apiextensionsv1.CustomResourceDefinition{}
if err := h.Client.Get(ctx, types.NamespacedName{Name: "policies.policy.open-cluster-management.io"}, crd); err != nil {
if k8serrors.IsNotFound(err) {
h.Log.Info("Skipping extraction from policies as the policy CRD is not found. This is expected if the cluster is not managed by ACM")
return nil
} else {
return fmt.Errorf("error while check policy CRD: %w", err)
}
}
sortedObjects, err := h.ValidateAndExtractManifestFromPolicies(ctx, policyLabels, objectLabels, validationAnns)
if err != nil {
return fmt.Errorf("failed to validate and extract manifests from policies: %w", err)
}
for i, objects := range sortedObjects {
group := filepath.Join(toDir, PolicyManifestPath, "group"+strconv.Itoa(i+1))
if err := os.MkdirAll(group, 0o700); err != nil {
return fmt.Errorf("failed to create directory %s: %w", group, err)
}
for j, object := range objects {
gvk := object.GroupVersionKind()
manifestFilePath := filepath.Join(group, fmt.Sprintf(
"%d_%s_%s_%s.yaml", j+1, gvk.Kind, object.GetName(), object.GetNamespace()))
if err := utils.MarshalToYamlFile(&object, manifestFilePath); err != nil { //nolint:gosec
return fmt.Errorf("failed to save manifests to file %s: %w", manifestFilePath, err)
}
h.Log.Info("Extracted from policy and exported manifest to file", "path", manifestFilePath)
}
}
return nil
}
func (h *EMHandler) ValidateAndExtractManifestFromPolicies(ctx context.Context, policyLabels, objectLabels, validationAnns map[string]string) ([][]*unstructured.Unstructured, error) {
var manifestCount int
var sortedObjects = [][]*unstructured.Unstructured{}
sortedPolicies, err := h.GetPolicies(ctx, policyLabels)
if err != nil {
return sortedObjects, fmt.Errorf("failed to get policies: %w", err)
}
for _, policy := range sortedPolicies {
objects, err := getConfigurationObjects(&h.Log, policy, objectLabels)
if err != nil {
return sortedObjects, fmt.Errorf("failed to extract manifests from policies: %w", err)
}
if len(objects) > 0 {
manifestCount += len(objects)
sortedObjects = append(sortedObjects, objects)
}
}
// check the labeled manifests count
if expectedManifestCount, exists := validationAnns[TargetOcpVersionManifestCountAnnotation]; exists {
if expectedManifestCount != strconv.Itoa(manifestCount) {
errMsg := fmt.Sprintf("The labeled manifests count found in policies %s does not match the expected manifests count %s", strconv.Itoa(manifestCount), expectedManifestCount)
h.Log.Error(nil, errMsg)
return sortedObjects, NewEMFailedError(errMsg)
}
}
return sortedObjects, nil
}
// ApplyExtraManifests applies the extra manifests from the preserved extra manifests directory
func (h *EMHandler) ApplyExtraManifests(ctx context.Context, fromDir string) error {
manifests, err := utils.LoadGroupedManifestsFromPath(fromDir, &h.Log)
if err != nil {
return fmt.Errorf("failed to read extra manifests from path: %w", err)
}
if manifests == nil || len(manifests) == 0 {
h.Log.Info(fmt.Sprintf("No extra manifests to apply in path %s", fromDir))
return nil
}
for _, group := range manifests {
for _, manifest := range group {
h.Log.Info("Applying manifest", "kind", manifest.GetKind(), "name", manifest.GetName())
err = ApplyExtraManifest(ctx, h.DynamicClient, h.Client.RESTMapper(), manifest, false)
if err != nil {
h.Log.Error(err, "Failed to apply manifest")
errMsg := fmt.Sprintf("failed to apply manifest: %v", err.Error())
// Capture both invalid syntax and webhook validation errors
if k8serrors.IsInvalid(err) || k8serrors.IsBadRequest(err) {
return NewEMFailedError(errMsg)
}
// Capture unknown CRD issue
var groupDiscoveryErr *discovery.ErrGroupDiscoveryFailed
if errors.As(err, &groupDiscoveryErr) || meta.IsNoMatchError(err) {
return NewEMFailedError(errMsg)
}
return fmt.Errorf(errMsg)
}
h.Log.Info("Applied manifest", "name", manifest.GetName(), "namespace", manifest.GetNamespace())
}
}
// Remove the extra manifests directory
if err := os.RemoveAll(fromDir); err != nil {
return fmt.Errorf("failed to remove manifests from %s: %w", fromDir, err)
}
h.Log.Info("Extra manifests path removed", "path", fromDir)
return nil
}
// GetMatchingTargetOcpVersionLabelVersions generates a list of matching versions that
// be used for extracting manifests from the policy
// The matching versions include: [full release version, Major.Minor.Patch, Major.Minor]
func GetMatchingTargetOcpVersionLabelVersions(ocpVersion string) ([]string, error) {
var validVersions []string
semVersion, err := semver.NewVersion(ocpVersion)
if err != nil {
return nil, fmt.Errorf("failed to parse target ocp version %s: %w", ocpVersion, err)
}
validVersions = append(validVersions,
fmt.Sprintf("%d.%d.%d", semVersion.Major, semVersion.Minor, semVersion.Patch),
fmt.Sprintf("%d.%d", semVersion.Major, semVersion.Minor),
)
if !lo.Contains(validVersions, ocpVersion) {
// full release version
validVersions = append(validVersions, ocpVersion)
}
return validVersions, nil
}
// AddAnnotationWarnUnknownCRD add warning in annotation for when CRD is unknown
func AddAnnotationWarnUnknownCRD(c client.Client, log logr.Logger, ibu *lcav1alpha1.ImageBasedUpgrade, annotationValue string) error {
patch := client.MergeFrom(ibu.DeepCopy()) // a merge patch will preserve other fields modified at runtime.
ann := ibu.GetAnnotations()
if ann == nil {
ann = make(map[string]string)
}
ann[WarnAnnotationUnknownCRDKey] = annotationValue
ibu.SetAnnotations(ann)
if err := c.Patch(context.Background(), ibu, patch); err != nil {
return fmt.Errorf("failed to update annotations: %w", err)
}
log.Info("Successfully added annotation", "annotation", WarnAnnotationUnknownCRDKey)
return nil
}
// RemoveAnnotationWarnUnknownCRD remove the warning if present
func RemoveAnnotationWarnUnknownCRD(c client.Client, ibu *lcav1alpha1.ImageBasedUpgrade, log logr.Logger) error {
if _, exists := ibu.GetAnnotations()[WarnAnnotationUnknownCRDKey]; exists {
patch := client.MergeFrom(ibu.DeepCopy()) // a merge patch will preserve other fields modified at runtime.
ann := ibu.GetAnnotations()
delete(ann, WarnAnnotationUnknownCRDKey)
ibu.SetAnnotations(ann)
if err := c.Patch(context.Background(), ibu, patch); err != nil {
return fmt.Errorf("failed to update annotations: %w", err)
}
log.Info("Successfully removed annotation", "annotations", WarnAnnotationUnknownCRDKey)
}
return nil
}