-
Notifications
You must be signed in to change notification settings - Fork 19
/
configurationpolicy_controller.go
2938 lines (2404 loc) · 92.8 KB
/
configurationpolicy_controller.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
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2020 Red Hat, Inc.
// Copyright Contributors to the Open Cluster Management project
package controllers
import (
"context"
"errors"
"fmt"
"os"
"reflect"
"sort"
"strconv"
"strings"
"sync"
"time"
gocmp "github.com/google/go-cmp/cmp"
"github.com/prometheus/client_golang/prometheus"
templates "github.com/stolostron/go-template-utils/v3/pkg/templates"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
extensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1"
extensionsv1beta1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1"
k8serrors "k8s.io/apimachinery/pkg/api/errors"
meta "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/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/types"
apimachineryerrors "k8s.io/apimachinery/pkg/util/errors"
"k8s.io/apimachinery/pkg/util/json"
"k8s.io/client-go/dynamic"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/client-go/restmapper"
"k8s.io/client-go/tools/record"
kubeopenapivalidation "k8s.io/kube-openapi/pkg/util/proto/validation"
"k8s.io/kubectl/pkg/util/openapi"
openapivalidation "k8s.io/kubectl/pkg/util/openapi/validation"
"k8s.io/kubectl/pkg/validation"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
yaml "sigs.k8s.io/yaml"
policyv1 "open-cluster-management.io/config-policy-controller/api/v1"
common "open-cluster-management.io/config-policy-controller/pkg/common"
)
const (
ControllerName string = "configuration-policy-controller"
CRDName string = "configurationpolicies.policy.open-cluster-management.io"
pruneObjectFinalizer string = "policy.open-cluster-management.io/delete-related-objects"
)
var log = ctrl.Log.WithName(ControllerName)
// PlcChan a channel used to pass policies ready for update
var PlcChan chan *policyv1.ConfigurationPolicy
var (
eventNormal = "Normal"
eventWarning = "Warning"
eventFmtStr = "policy: %s/%s"
plcFmtStr = "policy: %s"
)
var (
reasonWantFoundExists = "Resource found as expected"
reasonWantFoundNoMatch = "Resource found but does not match"
reasonWantFoundDNE = "Resource not found but should exist"
reasonWantNotFoundExists = "Resource found but should not exist"
reasonWantNotFoundDNE = "Resource not found as expected"
reasonCleanupError = "Error cleaning up child objects"
)
// SetupWithManager sets up the controller with the Manager.
func (r *ConfigurationPolicyReconciler) SetupWithManager(mgr ctrl.Manager) error {
return ctrl.NewControllerManagedBy(mgr).
Named(ControllerName).
For(&policyv1.ConfigurationPolicy{}).
Complete(r)
}
// blank assignment to verify that ConfigurationPolicyReconciler implements reconcile.Reconciler
var _ reconcile.Reconciler = &ConfigurationPolicyReconciler{}
type cachedEncryptionKey struct {
key []byte
previousKey []byte
}
type discoveryInfo struct {
apiResourceList []*metav1.APIResourceList
apiGroups []*restmapper.APIGroupResources
discoveryLastRefreshed time.Time
}
// ConfigurationPolicyReconciler reconciles a ConfigurationPolicy object
type ConfigurationPolicyReconciler struct {
cachedEncryptionKey *cachedEncryptionKey
// This client, initialized using mgr.Client() above, is a split client
// that reads objects from the cache and writes to the apiserver
client.Client
DecryptionConcurrency uint8
// Determines the number of Go routines that can evaluate policies concurrently.
EvaluationConcurrency uint8
Scheme *runtime.Scheme
Recorder record.EventRecorder
InstanceName string
// The Kubernetes client to use when evaluating/enforcing policies. Most times, this will be the same cluster
// where the controller is running.
TargetK8sClient kubernetes.Interface
TargetK8sDynamicClient dynamic.Interface
TargetK8sConfig *rest.Config
// Whether custom metrics collection is enabled
EnableMetrics bool
discoveryInfo
// This is used to fetch and parse OpenAPI documents to perform client-side validation of object definitions.
openAPIParser *openapi.CachedOpenAPIParser
// A lock when performing actions that are not thread safe (i.e. reassigning object properties).
lock sync.RWMutex
}
//+kubebuilder:rbac:groups=*,resources=*,verbs=*
// Reconcile currently does nothing except that it removes a policy's metric when the policy is deleted. All the logic
// is handled in the PeriodicallyExecConfigPolicies method.
func (r *ConfigurationPolicyReconciler) Reconcile(ctx context.Context, request ctrl.Request) (ctrl.Result, error) {
policy := &policyv1.ConfigurationPolicy{}
err := r.Get(ctx, request.NamespacedName, policy)
if k8serrors.IsNotFound(err) {
// If the metric was not deleted, that means the policy was never evaluated so it can be ignored.
_ = policyEvalSecondsCounter.DeleteLabelValues(request.Name)
_ = policyEvalCounter.DeleteLabelValues(request.Name)
_ = plcTempsProcessSecondsCounter.DeleteLabelValues(request.Name)
_ = plcTempsProcessCounter.DeleteLabelValues(request.Name)
_ = compareObjEvalCounter.DeletePartialMatch(prometheus.Labels{"config_policy_name": request.Name})
_ = compareObjSecondsCounter.DeletePartialMatch(prometheus.Labels{"config_policy_name": request.Name})
_ = policyRelatedObjectGauge.DeletePartialMatch(
prometheus.Labels{"policy": fmt.Sprintf("%s/%s", request.Namespace, request.Name)})
_ = policyUserErrorsCounter.DeletePartialMatch(prometheus.Labels{"template": request.Name})
_ = policySystemErrorsCounter.DeletePartialMatch(prometheus.Labels{"template": request.Name})
}
return reconcile.Result{}, nil
}
// PeriodicallyExecConfigPolicies loops through all configurationpolicies in the target namespace and triggers
// template handling for each one. This function drives all the work the configuration policy controller does.
func (r *ConfigurationPolicyReconciler) PeriodicallyExecConfigPolicies(
ctx context.Context, freq uint, elected <-chan struct{},
) {
log.Info("Waiting for leader election before periodically evaluating configuration policies")
select {
case <-elected:
case <-ctx.Done():
return
}
const waiting = 10 * time.Minute
exiting := false
deploymentFinalizerRemoved := false
for !exiting {
if !deploymentFinalizerRemoved {
err := r.removeLegacyDeploymentFinalizer()
if err == nil {
deploymentFinalizerRemoved = true
} else {
log.Error(err, "Failed to remove the legacy Deployment finalizer. Will try again.")
}
}
start := time.Now()
policiesList := policyv1.ConfigurationPolicyList{}
var skipLoop bool
var discoveryErr error
if len(r.apiResourceList) == 0 || len(r.apiGroups) == 0 {
discoveryErr = r.refreshDiscoveryInfo()
}
// If it's been more than 10 minutes since the last refresh, then refresh the discovery info, but ignore
// any errors since the cache can still be used. If a policy encounters an API resource type not in the
// cache, the discovery info refresh will be handled there. This periodic refresh is to account for
// deleted CRDs or strange edits to the CRD (e.g. converted it from namespaced to not).
if time.Since(r.discoveryLastRefreshed) >= waiting {
_ = r.refreshDiscoveryInfo()
}
if discoveryErr == nil {
// This retrieves the policies from the controller-runtime cache populated by the watch.
err := r.List(context.TODO(), &policiesList)
if err != nil {
log.Error(err, "Failed to list the ConfigurationPolicy objects to evaluate")
skipLoop = true
}
} else {
skipLoop = true
}
cleanupImmediately, err := r.cleanupImmediately()
if err != nil {
log.Error(err, "Failed to determine if it's time to cleanup immediately")
skipLoop = true
}
// This is done every loop cycle since the channel needs to be variable in size to account for the number of
// policies changing.
policyQueue := make(chan *policyv1.ConfigurationPolicy, len(policiesList.Items))
var wg sync.WaitGroup
if !skipLoop {
log.Info("Processing the policies", "count", len(policiesList.Items))
// Initialize the related object map
policyRelatedObjectMap = sync.Map{}
for i := 0; i < int(r.EvaluationConcurrency); i++ {
wg.Add(1)
go r.handlePolicyWorker(policyQueue, &wg)
}
for i := range policiesList.Items {
policy := policiesList.Items[i]
if !shouldEvaluatePolicy(&policy, cleanupImmediately) {
continue
}
// handle each template in each policy
policyQueue <- &policy
}
}
close(policyQueue)
wg.Wait()
// Update the related object metric after policy processing
if r.EnableMetrics {
updateRelatedObjectMetric()
}
// Update the evaluation histogram with the elapsed time
elapsed := time.Since(start).Seconds()
evalLoopHistogram.Observe(elapsed)
// making sure that if processing is > freq we don't sleep
// if freq > processing we sleep for the remaining duration
if float64(freq) > elapsed {
remainingSleep := float64(freq) - elapsed
sleepTime := time.Duration(remainingSleep) * time.Second
log.V(2).Info("Sleeping before reprocessing the configuration policies", "seconds", sleepTime)
time.Sleep(sleepTime)
}
select {
case <-ctx.Done():
exiting = true
default:
}
}
}
// handlePolicyWorker is meant to be used as a Go routine that wraps handleObjectTemplates.
func (r *ConfigurationPolicyReconciler) handlePolicyWorker(
policyQueue <-chan *policyv1.ConfigurationPolicy, wg *sync.WaitGroup,
) {
defer wg.Done()
for policy := range policyQueue {
before := time.Now().UTC()
r.handleObjectTemplates(*policy)
duration := time.Now().UTC().Sub(before)
seconds := float64(duration) / float64(time.Second)
policyEvalSecondsCounter.WithLabelValues(policy.Name).Add(seconds)
policyEvalCounter.WithLabelValues(policy.Name).Inc()
}
}
func (r *ConfigurationPolicyReconciler) refreshDiscoveryInfo() error {
log.V(2).Info("Refreshing the discovery info")
r.lock.Lock()
defer func() { r.lock.Unlock() }()
dd := r.TargetK8sClient.Discovery()
_, apiResourceList, err := dd.ServerGroupsAndResources()
if err != nil {
log.Error(err, "Could not get the API resource list")
return err
}
r.apiResourceList = apiResourceList
apiGroups, err := restmapper.GetAPIGroupResources(dd)
if err != nil {
log.Error(err, "Could not get the API groups list")
return err
}
r.apiGroups = apiGroups
// Reset the OpenAPI cache in case the CRDs were updated since the last fetch.
r.openAPIParser = openapi.NewOpenAPIParser(dd)
r.discoveryLastRefreshed = time.Now().UTC()
return nil
}
// shouldEvaluatePolicy will determine if the policy is ready for evaluation by examining the
// status.lastEvaluated and status.lastEvaluatedGeneration fields. If a policy has been updated, it
// will always be triggered for evaluation. If the spec.evaluationInterval configuration has been
// met, then that will also trigger an evaluation. If cleanupImmediately is true, then only policies
// with finalizers will be ready for evaluation regardless of the last evaluation.
// cleanupImmediately should be set true when the controller is getting uninstalled.
func shouldEvaluatePolicy(policy *policyv1.ConfigurationPolicy, cleanupImmediately bool) bool {
log := log.WithValues("policy", policy.GetName())
// If it's time to clean up such as when the config-policy-controller is being uninstalled, only evaluate policies
// with a finalizer to remove the finalizer.
if cleanupImmediately {
return len(policy.Finalizers) != 0
}
if policy.ObjectMeta.DeletionTimestamp != nil {
log.V(2).Info("The policy has been deleted and is waiting for object cleanup. Will evaluate it now.")
return true
}
if policy.Status.LastEvaluatedGeneration != policy.Generation {
log.V(2).Info("The policy has been updated. Will evaluate it now.")
return true
}
if policy.Status.LastEvaluated == "" {
log.V(2).Info("The policy's status.lastEvaluated field is not set. Will evaluate it now.")
return true
}
lastEvaluated, err := time.Parse(time.RFC3339, policy.Status.LastEvaluated)
if err != nil {
log.Error(err, "The policy has an invalid status.lastEvaluated value. Will evaluate it now.")
return true
}
var interval time.Duration
if policy.Status.ComplianceState == policyv1.Compliant && policy.Spec != nil {
interval, err = policy.Spec.EvaluationInterval.GetCompliantInterval()
} else if policy.Status.ComplianceState == policyv1.NonCompliant && policy.Spec != nil {
interval, err = policy.Spec.EvaluationInterval.GetNonCompliantInterval()
} else {
log.V(2).Info("The policy has an unknown compliance. Will evaluate it now.")
return true
}
if errors.Is(err, policyv1.ErrIsNever) {
log.Info("Skipping the policy evaluation due to the spec.evaluationInterval value being set to never")
return false
} else if err != nil {
log.Error(
err,
"The policy has an invalid spec.evaluationInterval value. Will evaluate it now.",
"spec.evaluationInterval.compliant", policy.Spec.EvaluationInterval.Compliant,
"spec.evaluationInterval.noncompliant", policy.Spec.EvaluationInterval.NonCompliant,
)
return true
}
nextEvaluation := lastEvaluated.Add(interval)
if nextEvaluation.Sub(time.Now().UTC()) > 0 {
log.Info("Skipping the policy evaluation due to the policy not reaching the evaluation interval")
return false
}
return true
}
// getTemplateConfigErrorMsg converts a configuration error from `NewResolver` or `SetEncryptionConfig` to a message
// to be used as a policy noncompliant message.
func getTemplateConfigErrorMsg(err error) string {
if errors.Is(err, templates.ErrInvalidAESKey) || errors.Is(err, templates.ErrAESKeyNotSet) {
return `The "policy-encryption-key" Secret contains an invalid AES key`
} else if errors.Is(err, templates.ErrInvalidIV) {
return fmt.Sprintf(`The "%s" annotation value is not a valid initialization vector`, IVAnnotation)
}
// This should never happen unless go-template-utils is updated and this doesn't account for a new error
// type that can happen with the input configuration.
return fmt.Sprintf("An unexpected error occurred when configuring the template resolver: %v", err)
}
type objectTemplateDetails struct {
kind string
name string
namespace string
isNamespaced bool
}
// getObjectTemplateDetails retrieves values from the object templates and returns an array of
// objects containing the retrieved values.
// It also gathers namespaces for this policy if necessary:
//
// If a namespaceSelector is present AND objects are namespaced without a namespace specified
func (r *ConfigurationPolicyReconciler) getObjectTemplateDetails(
plc policyv1.ConfigurationPolicy,
) ([]objectTemplateDetails, []string, bool, error) {
templateObjs := make([]objectTemplateDetails, len(plc.Spec.ObjectTemplates))
selectedNamespaces := []string{}
queryNamespaces := false
for idx, objectT := range plc.Spec.ObjectTemplates {
unstruct, err := unmarshalFromJSON(objectT.ObjectDefinition.Raw)
if err != nil {
return templateObjs, selectedNamespaces, false, err
}
templateObjs[idx].isNamespaced = r.isObjectNamespaced(&unstruct, true)
// strings.TrimSpace() is needed here because a multi-line value will have '\n' in it
templateObjs[idx].kind = strings.TrimSpace(unstruct.GetKind())
templateObjs[idx].name = strings.TrimSpace(unstruct.GetName())
templateObjs[idx].namespace = strings.TrimSpace(unstruct.GetNamespace())
if templateObjs[idx].isNamespaced && templateObjs[idx].namespace == "" {
queryNamespaces = true
}
}
// If required, query for namespaces specified in NamespaceSelector for objects to use
if queryNamespaces {
// Retrieve the namespaces based on filters in NamespaceSelector
selector := plc.Spec.NamespaceSelector
// If MatchLabels/MatchExpressions/Include were not provided, return no namespaces
if selector.MatchLabels == nil && selector.MatchExpressions == nil && len(selector.Include) == 0 {
log.Info("namespaceSelector is empty. Skipping namespace retrieval.")
} else {
// If an error occurred in the NamespaceSelector, update the policy status and abort
var err error
selectedNamespaces, err = common.GetSelectedNamespaces(r.TargetK8sClient, selector)
if err != nil {
errMsg := "Error filtering namespaces with provided namespaceSelector"
log.Error(
err, errMsg,
"namespaceSelector", fmt.Sprintf("%+v", selector))
reason := "namespaceSelector error"
msg := fmt.Sprintf(
"%s: %s", errMsg, err.Error())
statusChanged := addConditionToStatus(&plc, 0, false, reason, msg)
if statusChanged {
r.Recorder.Event(
&plc,
eventWarning,
fmt.Sprintf(plcFmtStr, plc.GetName()),
convertPolicyStatusToString(&plc),
)
}
return templateObjs, selectedNamespaces, statusChanged, err
}
if len(selectedNamespaces) == 0 {
log.Info("Fetching namespaces with provided NamespaceSelector returned no namespaces.",
"namespaceSelector", fmt.Sprintf("%+v", selector))
}
}
}
return templateObjs, selectedNamespaces, false, nil
}
func (r *ConfigurationPolicyReconciler) cleanUpChildObjects(plc policyv1.ConfigurationPolicy) []string {
deletionFailures := []string{}
for _, object := range plc.Status.RelatedObjects {
// set up client for object deletion
gvk := schema.FromAPIVersionAndKind(object.Object.APIVersion, object.Object.Kind)
log := log.WithValues("policy", plc.GetName(), "groupVersionKind", gvk.String())
r.lock.RLock()
mapper := restmapper.NewDiscoveryRESTMapper(r.apiGroups)
r.lock.RUnlock()
mapping, err := mapper.RESTMapping(gvk.GroupKind(), gvk.Version)
if err != nil {
log.Error(err, "Could not get resource mapping for child object")
deletionFailures = append(deletionFailures, gvk.String()+fmt.Sprintf(` "%s" in namespace %s`,
object.Object.Metadata.Name, object.Object.Metadata.Namespace))
continue
}
namespaced := object.Object.Metadata.Namespace != ""
// determine whether object should be deleted
needsDelete := false
existing, err := getObject(
namespaced,
object.Object.Metadata.Namespace,
object.Object.Metadata.Name,
mapping.Resource,
r.TargetK8sDynamicClient,
)
if err != nil {
log.Error(err, "Failed to get child object")
deletionFailures = append(deletionFailures, gvk.String()+fmt.Sprintf(` "%s" in namespace %s`,
object.Object.Metadata.Name, object.Object.Metadata.Namespace))
continue
}
// object does not exist, no deletion logic needed
if existing == nil {
continue
}
if strings.EqualFold(string(plc.Spec.RemediationAction), "enforce") {
if string(plc.Spec.PruneObjectBehavior) == "DeleteAll" {
needsDelete = true
} else {
// if prune behavior is DeleteIfCreated, we need to check whether createdByPolicy
// is true and the UID is not stale
uid, uidFound, err := unstructured.NestedString(existing.Object, "metadata", "uid")
if !uidFound || err != nil {
log.Error(err, "Tried to pull UID from obj but the field did not exist or was not a string")
} else if object.Properties != nil &&
object.Properties.CreatedByPolicy != nil &&
*object.Properties.CreatedByPolicy &&
object.Properties.UID == uid {
needsDelete = true
}
}
}
// delete object if needed
if needsDelete {
// if object has already been deleted and is stuck, no need to redo delete request
_, deletionTimeFound, _ := unstructured.NestedString(existing.Object, "metadata", "deletionTimestamp")
if deletionTimeFound {
log.Error(fmt.Errorf("tried to delete object, but delete is hanging"), "Error")
deletionFailures = append(deletionFailures, gvk.String()+fmt.Sprintf(` "%s" in namespace %s`,
object.Object.Metadata.Name, object.Object.Metadata.Namespace))
continue
}
var res dynamic.ResourceInterface
if namespaced {
res = r.TargetK8sDynamicClient.Resource(mapping.Resource).Namespace(object.Object.Metadata.Namespace)
} else {
res = r.TargetK8sDynamicClient.Resource(mapping.Resource)
}
if completed, err := deleteObject(res, object.Object.Metadata.Name,
object.Object.Metadata.Namespace); !completed {
deletionFailures = append(deletionFailures, gvk.String()+fmt.Sprintf(` "%s" in namespace %s`,
object.Object.Metadata.Name, object.Object.Metadata.Namespace))
log.Error(err, "Error: Failed to delete object during child object pruning")
} else {
obj, _ := getObject(
namespaced,
object.Object.Metadata.Namespace,
object.Object.Metadata.Name,
mapping.Resource,
r.TargetK8sDynamicClient,
)
if obj != nil {
log.Error(err, "Error: tried to delete object, but delete is hanging")
deletionFailures = append(deletionFailures, gvk.String()+fmt.Sprintf(` "%s" in namespace %s`,
object.Object.Metadata.Name, object.Object.Metadata.Namespace))
continue
}
log.Info("Object successfully deleted as part of child object pruning")
}
}
}
return deletionFailures
}
// cleanupImmediately returns true when the cluster is in a state where configurationpolicies should
// be removed as soon as possible, ignoring the pruneObjectBehavior of the policies. This is the
// case when the controller is being uninstalled or the CRD is being deleted.
func (r *ConfigurationPolicyReconciler) cleanupImmediately() (bool, error) {
beingUninstalled, beingUninstalledErr := r.isBeingUninstalled()
if beingUninstalledErr == nil && beingUninstalled {
return true, nil
}
defDeleting, defErr := r.definitionIsDeleting()
if defErr == nil && defDeleting {
return true, nil
}
if beingUninstalledErr == nil && defErr == nil {
// if either was deleting, we would've already returned.
return false, nil
}
// At least one had an unexpected error, so the decision can't be made right now
//nolint:errorlint // we can't choose just one of the errors to "correctly" wrap
return false, fmt.Errorf(
"isBeingUninstalled error: '%v', definitionIsDeleting error: '%v'", beingUninstalledErr, defErr,
)
}
func (r *ConfigurationPolicyReconciler) definitionIsDeleting() (bool, error) {
key := types.NamespacedName{Name: CRDName}
v1def := extensionsv1.CustomResourceDefinition{}
v1err := r.Get(context.TODO(), key, &v1def)
if v1err == nil {
return (v1def.ObjectMeta.DeletionTimestamp != nil), nil
}
v1beta1def := extensionsv1beta1.CustomResourceDefinition{}
v1beta1err := r.Get(context.TODO(), key, &v1beta1def)
if v1beta1err == nil {
return (v1beta1def.DeletionTimestamp != nil), nil
}
// It might not be possible to get a not-found on the CRD while reconciling the CR...
// But in that case, it seems reasonable to still consider it "deleting"
if k8serrors.IsNotFound(v1err) || k8serrors.IsNotFound(v1beta1err) {
return true, nil
}
// Both had unexpected errors, return them and retry later
return false, fmt.Errorf("v1: %v, v1beta1: %v", v1err, v1beta1err) //nolint:errorlint
}
// handleObjectTemplates iterates through all policy templates in a given policy and processes them
func (r *ConfigurationPolicyReconciler) handleObjectTemplates(plc policyv1.ConfigurationPolicy) {
log := log.WithValues("policy", plc.GetName())
log.V(1).Info("Processing object templates")
// initialize the RelatedObjects for this Configuration Policy
oldRelated := append([]policyv1.RelatedObject{}, plc.Status.RelatedObjects...)
relatedObjects := []policyv1.RelatedObject{}
parentStatusUpdateNeeded := false
validationErr := ""
if plc.Spec == nil {
validationErr = "Policy does not have a Spec specified"
} else if plc.Spec.RemediationAction == "" {
validationErr = "Policy does not have a RemediationAction specified"
}
// error if no spec or remediationAction is specified
if validationErr != "" {
message := validationErr
log.Info(message)
statusChanged := addConditionToStatus(&plc, 0, false, "Invalid spec", message)
if statusChanged {
r.Recorder.Event(&plc, eventWarning,
fmt.Sprintf(plcFmtStr, plc.GetName()), convertPolicyStatusToString(&plc))
}
r.checkRelatedAndUpdate(plc, relatedObjects, oldRelated, statusChanged)
parent := ""
if len(plc.OwnerReferences) > 0 {
parent = plc.OwnerReferences[0].Name
}
policyUserErrorsCounter.WithLabelValues(parent, plc.GetName(), "invalid-template").Add(1)
return
}
// object handling for when configurationPolicy is deleted
if plc.Spec.PruneObjectBehavior == "DeleteIfCreated" || plc.Spec.PruneObjectBehavior == "DeleteAll" {
cleanupNow, err := r.cleanupImmediately()
if err != nil {
log.Error(err, "Error determining whether to cleanup immediately, requeueing policy")
return
}
if cleanupNow {
if objHasFinalizer(&plc, pruneObjectFinalizer) {
patch := removeObjFinalizerPatch(&plc, pruneObjectFinalizer)
err = r.Patch(context.TODO(), &plc, client.RawPatch(types.JSONPatchType, patch))
if err != nil {
log.V(1).Error(err, "Error removing finalizer for configuration policy")
return
}
}
return
}
// set finalizer if it hasn't been set
if !objHasFinalizer(&plc, pruneObjectFinalizer) {
var patch []byte
if plc.Finalizers == nil {
patch = []byte(
`[{"op":"add","path":"/metadata/finalizers","value":["` + pruneObjectFinalizer + `"]}]`,
)
} else {
patch = []byte(
`[{"op":"add","path":"/metadata/finalizers/-","value":"` + pruneObjectFinalizer + `"}]`,
)
}
err := r.Patch(context.TODO(), &plc, client.RawPatch(types.JSONPatchType, patch))
if err != nil {
log.V(1).Error(err, "Error setting finalizer for configuration policy")
return
}
}
// kick off object deletion if configurationPolicy has been deleted
if plc.ObjectMeta.DeletionTimestamp != nil {
log.V(1).Info("Config policy has been deleted, handling child objects")
failures := r.cleanUpChildObjects(plc)
if len(failures) == 0 {
log.V(1).Info("Objects have been successfully cleaned up, removing finalizer")
patch := removeObjFinalizerPatch(&plc, pruneObjectFinalizer)
err = r.Patch(context.TODO(), &plc, client.RawPatch(types.JSONPatchType, patch))
if err != nil {
log.V(1).Error(err, "Error removing finalizer for configuration policy")
return
}
} else {
log.V(1).Info("Object cleanup failed, some objects have not been deleted from the cluster")
statusChanged := addConditionToStatus(
&plc,
0,
false,
reasonCleanupError,
"Failed to delete objects: "+strings.Join(failures, ", "))
if statusChanged {
parentStatusUpdateNeeded = true
r.Recorder.Event(
&plc,
eventWarning,
fmt.Sprintf(plcFmtStr, plc.GetName()),
convertPolicyStatusToString(&plc),
)
}
// don't change related objects while deletion is in progress
r.checkRelatedAndUpdate(plc, oldRelated, oldRelated, parentStatusUpdateNeeded)
}
return
}
} else if objHasFinalizer(&plc, pruneObjectFinalizer) {
// if pruneObjectBehavior is none, no finalizer is needed
patch := removeObjFinalizerPatch(&plc, pruneObjectFinalizer)
err := r.Patch(context.TODO(), &plc, client.RawPatch(types.JSONPatchType, patch))
if err != nil {
log.V(1).Error(err, "Error removing finalizer for configuration policy")
return
}
}
addTemplateErrorViolation := func(reason, msg string) {
log.Info("Setting the policy to noncompliant due to a templating error", "error", msg)
if reason == "" {
reason = "Error processing template"
}
statusChanged := addConditionToStatus(&plc, 0, false, reason, msg)
if statusChanged {
parentStatusUpdateNeeded = true
r.Recorder.Event(
&plc,
eventWarning,
fmt.Sprintf(plcFmtStr, plc.GetName()),
convertPolicyStatusToString(&plc),
)
}
r.checkRelatedAndUpdate(plc, relatedObjects, oldRelated, parentStatusUpdateNeeded)
}
// initialize apiresources for template processing before starting objectTemplate processing
// this is optional but since apiresourcelist is already available,
// use this rather than re-discovering the list for generic-lookup
r.lock.RLock()
tmplResolverCfg := templates.Config{KubeAPIResourceList: r.apiResourceList}
r.lock.RUnlock()
usedKeyCache := false
if usesEncryption(plc) {
var encryptionConfig templates.EncryptionConfig
var err error
encryptionConfig, usedKeyCache, err = r.getEncryptionConfig(plc, false)
if err != nil {
addTemplateErrorViolation("", err.Error())
return
}
tmplResolverCfg.EncryptionConfig = encryptionConfig
}
annotations := plc.GetAnnotations()
disableTemplates := false
if disableAnnotation, ok := annotations["policy.open-cluster-management.io/disable-templates"]; ok {
log.V(2).Info("Found disable-templates annotation", "value", disableAnnotation)
parsedDisable, err := strconv.ParseBool(disableAnnotation)
if err != nil {
log.Error(err, "Could not parse value for disable-templates annotation", "value", disableAnnotation)
} else {
disableTemplates = parsedDisable
}
}
// set up raw data for template processing
var rawDataList [][]byte
var isRawObjTemplate bool
if plc.Spec.ObjectTemplatesRaw != "" {
rawDataList = [][]byte{[]byte(plc.Spec.ObjectTemplatesRaw)}
isRawObjTemplate = true
} else {
for _, objectT := range plc.Spec.ObjectTemplates {
rawDataList = append(rawDataList, objectT.ObjectDefinition.Raw)
}
isRawObjTemplate = false
}
tmplResolverCfg.InputIsYAML = isRawObjTemplate
tmplResolver, err := templates.NewResolver(&r.TargetK8sClient, r.TargetK8sConfig, tmplResolverCfg)
if err != nil {
// If the encryption key is invalid, clear the cache.
if errors.Is(err, templates.ErrInvalidAESKey) || errors.Is(err, templates.ErrAESKeyNotSet) {
r.cachedEncryptionKey = &cachedEncryptionKey{}
}
msg := getTemplateConfigErrorMsg(err)
addTemplateErrorViolation("", msg)
return
}
log.V(2).Info("Processing the object templates", "count", len(plc.Spec.ObjectTemplates))
if !disableTemplates {
startTime := time.Now().UTC()
var objTemps []*policyv1.ObjectTemplate
// process object templates for go template usage
for i, rawData := range rawDataList {
// first check to make sure there are no hub-templates with delimiter - {{hub
// if one exists, it means the template resolution on the hub did not succeed.
if templates.HasTemplate(rawData, "{{hub", false) {
// check to see there is an annotation set to the hub error msg,
// if not ,set a generic msg
hubTemplatesErrMsg, ok := annotations["policy.open-cluster-management.io/hub-templates-error"]
if !ok || hubTemplatesErrMsg == "" {
// set a generic msg
hubTemplatesErrMsg = "Error occurred while processing hub-templates, " +
"check the policy events for more details."
}
log.Info(
"An error occurred while processing hub-templates on the Hub cluster. Cannot process the policy.",
"message", hubTemplatesErrMsg,
)
addTemplateErrorViolation("Error processing hub templates", hubTemplatesErrMsg)
return
}
if templates.HasTemplate(rawData, "", true) {
log.V(1).Info("Processing policy templates")
resolvedTemplate, tplErr := tmplResolver.ResolveTemplate(rawData, nil)
if errors.Is(tplErr, templates.ErrMissingAPIResource) ||
errors.Is(tplErr, templates.ErrMissingAPIResourceInvalidTemplate) {
log.V(2).Info(
"A template encountered an API resource which was not in the API resource list. Refreshing " +
"it and trying again.",
)
discoveryErr := r.refreshDiscoveryInfo()
if discoveryErr == nil {
tmplResolver.SetKubeAPIResourceList(r.apiResourceList)
resolvedTemplate, tplErr = tmplResolver.ResolveTemplate(rawData, nil)
} else {
log.V(2).Info(
"Failed to refresh the API discovery information after a template encountered an unknown " +
"API resource type. Continuing with the assumption that the discovery information " +
"was correct.",
)
}
}
// If the error is because the padding is invalid, this either means the encrypted value was not
// generated by the "protect" template function or the AES key is incorrect. Control for a stale
// cached key.
if usedKeyCache && errors.Is(tplErr, templates.ErrInvalidPKCS7Padding) {
log.V(2).Info(
"The template decryption failed likely due to an invalid encryption key, will refresh " +
"the encryption key cache and try the decryption again",
)
var encryptionConfig templates.EncryptionConfig
encryptionConfig, usedKeyCache, err = r.getEncryptionConfig(plc, true)
if err != nil {
addTemplateErrorViolation("", err.Error())
return
}
tmplResolverCfg.EncryptionConfig = encryptionConfig
err := tmplResolver.SetEncryptionConfig(encryptionConfig)
if err != nil {
// If the encryption key is invalid, clear the cache.
if errors.Is(err, templates.ErrInvalidAESKey) || errors.Is(err, templates.ErrAESKeyNotSet) {
r.cachedEncryptionKey = &cachedEncryptionKey{}
}
msg := getTemplateConfigErrorMsg(err)
addTemplateErrorViolation("", msg)
return
}
resolvedTemplate, tplErr = tmplResolver.ResolveTemplate(rawData, nil)
}
if tplErr != nil {
addTemplateErrorViolation("", tplErr.Error())
return
}
// If raw data, only one passthrough is needed, since all the object templates are in it
if isRawObjTemplate {
err := json.Unmarshal(resolvedTemplate.ResolvedJSON, &objTemps)
if err != nil {
addTemplateErrorViolation("Error unmarshalling raw template", err.Error())
return
}
plc.Spec.ObjectTemplates = objTemps