WARNING: THIS SITE IS A MIRROR OF GITHUB.COM / IT CANNOT LOGIN OR REGISTER ACCOUNTS / THE CONTENTS ARE PROVIDED AS-IS / THIS SITE ASSUMES NO RESPONSIBILITY FOR ANY DISPLAYED CONTENT OR LINKS / IF YOU FOUND SOMETHING MAY NOT GOOD FOR EVERYONE, CONTACT ADMIN AT ilovescratch@foxmail.com
Skip to content

Commit 5ee4272

Browse files
committed
WIP ObjectNamespace template variable
Signed-off-by: mprahl <[email protected]>
1 parent 829b397 commit 5ee4272

File tree

8 files changed

+438
-367
lines changed

8 files changed

+438
-367
lines changed

controllers/configurationpolicy_controller.go

Lines changed: 397 additions & 300 deletions
Large diffs are not rendered by default.

controllers/configurationpolicy_controller_test.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -568,7 +568,7 @@ status:
568568
t.Error(err)
569569
}
570570

571-
desiredObj := unstructured.Unstructured{Object: policyObjDef}
571+
desiredObj := &unstructured.Unstructured{Object: policyObjDef}
572572
existingObjOrderOne := unstructured.Unstructured{Object: orderOneObj}
573573
existingObjOrderTwo := unstructured.Unstructured{Object: orderTwoObj}
574574

@@ -1057,7 +1057,7 @@ secrets:
10571057
compType := policyv1.MustOnlyHave
10581058
mdCompType := policyv1.MustOnlyHave
10591059

1060-
throwSpecViolation, _, updateNeeded, statusMismatch := handleKeys(desiredObj, &existingObj,
1060+
throwSpecViolation, _, updateNeeded, statusMismatch := handleKeys(&desiredObj, &existingObj,
10611061
&existingObjCopy, compType, mdCompType)
10621062

10631063
assert.False(t, throwSpecViolation)
@@ -1524,7 +1524,7 @@ func TestShouldHandleSingleKeyFalse(t *testing.T) {
15241524
unstruct.Object = test.input
15251525
unstructObj.Object = test.fromAPI
15261526
key := test.expectResult.key
1527-
_, update, _, skip = handleSingleKey(key, unstruct, &unstructObj, "musthave", true)
1527+
_, update, _, skip = handleSingleKey(key, &unstruct, &unstructObj, "musthave", true)
15281528
assert.Equal(t, update, test.expectResult.expect)
15291529
assert.False(t, skip)
15301530
}

controllers/configurationpolicy_utils.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -359,7 +359,7 @@ func filterUnwantedAnnotations(input map[string]interface{}) map[string]interfac
359359
}
360360

361361
// formatTemplate returns the value of the input key in a manner that the controller can use for comparisons.
362-
func formatTemplate(unstruct unstructured.Unstructured, key string) (obj interface{}) {
362+
func formatTemplate(unstruct *unstructured.Unstructured, key string) (obj interface{}) {
363363
if key == "metadata" {
364364
metadata, ok := unstruct.Object[key].(map[string]interface{})
365365
if !ok {

controllers/metric.go

Lines changed: 0 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -25,22 +25,6 @@ var (
2525
},
2626
[]string{"name"},
2727
)
28-
plcTempsProcessSecondsCounter = prometheus.NewCounterVec(
29-
prometheus.CounterOpts{
30-
Name: "config_policy_templates_process_seconds_total",
31-
Help: "The total seconds taken while processing the configuration policy templates. Use this alongside " +
32-
"config_policy_templates_process_total.",
33-
},
34-
[]string{"name"},
35-
)
36-
plcTempsProcessCounter = prometheus.NewCounterVec(
37-
prometheus.CounterOpts{
38-
Name: "config_policy_templates_process_total",
39-
Help: "The total number of processes of the configuration policy templates. Use this alongside " +
40-
"config_policy_templates_process_seconds_total.",
41-
},
42-
[]string{"name"},
43-
)
4428
compareObjSecondsCounter = prometheus.NewCounterVec(
4529
prometheus.CounterOpts{
4630
Name: "compare_objects_seconds_total",
@@ -85,8 +69,6 @@ func init() {
8569
// Register custom metrics with the global Prometheus registry
8670
metrics.Registry.MustRegister(policyEvalSecondsCounter)
8771
metrics.Registry.MustRegister(policyEvalCounter)
88-
metrics.Registry.MustRegister(plcTempsProcessSecondsCounter)
89-
metrics.Registry.MustRegister(plcTempsProcessCounter)
9072
metrics.Registry.MustRegister(compareObjSecondsCounter)
9173
metrics.Registry.MustRegister(compareObjEvalCounter)
9274
// Error metrics may already be registered by template sync
@@ -107,8 +89,6 @@ func removeConfigPolicyMetrics(request ctrl.Request) {
10789
// If a metric has an error while deleting, that means the policy was never evaluated so it can be ignored.
10890
_ = policyEvalSecondsCounter.DeleteLabelValues(request.Name)
10991
_ = policyEvalCounter.DeleteLabelValues(request.Name)
110-
_ = plcTempsProcessSecondsCounter.DeleteLabelValues(request.Name)
111-
_ = plcTempsProcessCounter.DeleteLabelValues(request.Name)
11292
_ = compareObjEvalCounter.DeletePartialMatch(prometheus.Labels{"config_policy_name": request.Name})
11393
_ = compareObjSecondsCounter.DeletePartialMatch(prometheus.Labels{"config_policy_name": request.Name})
11494
_ = policyUserErrorsCounter.DeletePartialMatch(prometheus.Labels{"template": request.Name})

controllers/operatorpolicy_controller.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2533,7 +2533,7 @@ func (r *OperatorPolicyReconciler) mergeObjects(
25332533
existing *unstructured.Unstructured,
25342534
complianceType policyv1.ComplianceType,
25352535
) (updateNeeded, updateIsForbidden bool, err error) {
2536-
desiredObj := unstructured.Unstructured{Object: desired}
2536+
desiredObj := &unstructured.Unstructured{Object: desired}
25372537

25382538
// Use a copy since some values can be directly assigned to mergedObj in handleSingleKey.
25392539
existingObjectCopy := existing.DeepCopy()

test/e2e/case13_templatization_test.go

Lines changed: 17 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -5,13 +5,12 @@ package e2e
55

66
import (
77
"context"
8-
"fmt"
9-
"strconv"
108

119
. "github.com/onsi/ginkgo/v2"
1210
. "github.com/onsi/gomega"
1311
corev1 "k8s.io/api/core/v1"
1412
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
13+
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
1514

1615
"open-cluster-management.io/config-policy-controller/test/utils"
1716
)
@@ -67,7 +66,7 @@ const (
6766
case13PruneTmpErrYaml string = "../resources/case13_templatization/case13_prune_template_error.yaml"
6867
)
6968

70-
var _ = Describe("Test templatization", Ordered, func() {
69+
var _ = FDescribe("Test templatization", Ordered, func() {
7170
Describe("Create a secret and pull data from it into a configurationPolicy", func() {
7271
It("should be created properly on the managed cluster", func() {
7372
By("Creating " + case13CfgPolCreateSecret + " and " + case13CfgPolCheckSecret + " on managed")
@@ -254,12 +253,26 @@ var _ = Describe("Test templatization", Ordered, func() {
254253
plc = utils.GetWithTimeout(clientManagedDynamic, gvrConfigPolicy,
255254
case13WrongArgs, testNamespace, true, defaultTimeoutSeconds)
256255
Expect(plc).NotTo(BeNil())
256+
257+
var managedPlc *unstructured.Unstructured
258+
257259
Eventually(func(g Gomega) {
258-
managedPlc := utils.GetWithTimeout(clientManagedDynamic, gvrConfigPolicy,
260+
managedPlc = utils.GetWithTimeout(clientManagedDynamic, gvrConfigPolicy,
259261
case13WrongArgs, testNamespace, true, defaultTimeoutSeconds)
260262

261263
utils.CheckComplianceStatus(g, managedPlc, "NonCompliant")
262264
}, defaultTimeoutSeconds, 1).Should(Succeed())
265+
266+
// Verify that the first object template failing template resolution doesn't prevent the other
267+
// object templates from being evaluated.
268+
compliancyDetails, _, _ := unstructured.NestedSlice(managedPlc.Object, "status", "compliancyDetails")
269+
Expect(compliancyDetails).To(HaveLen(2))
270+
271+
firstObjTemplate := compliancyDetails[0].(map[string]interface{})
272+
Expect(firstObjTemplate["Compliant"]).To(Equal("NonCompliant"))
273+
274+
secondObjTemplate := compliancyDetails[1].(map[string]interface{})
275+
Expect(secondObjTemplate["Compliant"]).To(Equal("Compliant"))
263276
})
264277
AfterAll(func() {
265278
deleteConfigPolicies([]string{case13Unterminated, case13WrongArgs})
@@ -311,41 +324,6 @@ var _ = Describe("Test templatization", Ordered, func() {
311324
Expect(err).ToNot(HaveOccurred())
312325
Expect(replConfigMap.Data["message"]).To(Equal("Hello Raleigh!\n"))
313326

314-
By("Checking metric endpoint for policy template counter for policy " + case13UpdateRefObject)
315-
Eventually(func() interface{} {
316-
return utils.GetMetrics(
317-
"config_policy_templates_process_total",
318-
fmt.Sprintf(`name=\"%s\"`, case13UpdateRefObject),
319-
)
320-
}, defaultTimeoutSeconds, 1).Should(Not(BeNil()))
321-
templatesTotalCounter := utils.GetMetrics(
322-
"config_policy_templates_process_total",
323-
fmt.Sprintf(`name=\"%s\"`, case13UpdateRefObject),
324-
)
325-
totalCounter, err := strconv.Atoi(templatesTotalCounter[0])
326-
Expect(err).ToNot(HaveOccurred())
327-
if err == nil {
328-
Expect(totalCounter).To(BeNumerically(">", 0))
329-
}
330-
By("Policy " + case13UpdateRefObject + " total template process counter : " + templatesTotalCounter[0])
331-
332-
Eventually(func() interface{} {
333-
return utils.GetMetrics(
334-
"config_policy_templates_process_seconds_total",
335-
fmt.Sprintf(`name=\"%s\"`, case13UpdateRefObject),
336-
)
337-
}, defaultTimeoutSeconds, 1).Should(Not(BeNil()))
338-
templatesTotalSeconds := utils.GetMetrics(
339-
"config_policy_templates_process_seconds_total",
340-
fmt.Sprintf(`name=\"%s\"`, case13UpdateRefObject),
341-
)
342-
templatesSeconds, err := strconv.ParseFloat(templatesTotalSeconds[0], 32)
343-
Expect(err).ToNot(HaveOccurred())
344-
if err == nil {
345-
Expect(templatesSeconds).To(BeNumerically(">", 0))
346-
}
347-
By("Policy " + case13UpdateRefObject + " total template process seconds : " + templatesTotalSeconds[0])
348-
349327
By("Updating the referenced ConfigMap")
350328
configMap.Data["message"] = "Hello world!"
351329
_, err = clientManaged.CoreV1().ConfigMaps("default").Update(

test/resources/case13_templatization/case13_wrong_args.yaml

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ kind: ConfigurationPolicy
33
metadata:
44
name: case13-policy-pod-create-wrong-args
55
spec:
6-
remediationAction: enforce
6+
remediationAction: inform
77
namespaceSelector:
88
exclude: ["kube-*"]
99
include: ["default"]
@@ -19,4 +19,10 @@ spec:
1919
- image: nginx:1.7.9
2020
name: nginx
2121
ports:
22-
- containerPort: 80
22+
- containerPort: 80
23+
- complianceType: musthave
24+
objectDefinition:
25+
apiVersion: v1
26+
kind: Namespace
27+
metadata:
28+
name: default

test/utils/utils.go

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -190,7 +190,17 @@ func GetComplianceState(managedPlc *unstructured.Unstructured) (result interface
190190
// GetStatusMessage parses status field to get message
191191
func GetStatusMessage(managedPlc *unstructured.Unstructured) (result interface{}) {
192192
if managedPlc.Object["status"] != nil {
193-
detail := managedPlc.Object["status"].(map[string]interface{})["compliancyDetails"].([]interface{})[0]
193+
status, ok := managedPlc.Object["status"].(map[string]interface{})
194+
if !ok {
195+
return nil
196+
}
197+
198+
complianceDetails, ok := status["compliancyDetails"].([]interface{})
199+
if !ok || len(complianceDetails) == 0 {
200+
return nil
201+
}
202+
203+
detail := complianceDetails[0]
194204

195205
return detail.(map[string]interface{})["conditions"].([]interface{})[0].(map[string]interface{})["message"]
196206
}

0 commit comments

Comments
 (0)