Skip to content

Commit 9f7f570

Browse files
Upgrade golangci-lint to 1.64.8
- All above these version: github.com/golangci/golangci-lint/cmd/golangci-lint@v1.55.1 github.com/daixiang0/gci@v0.11.2 sigs.k8s.io/kustomize/kustomize/v5@v5.2.1 gosec => 2.22.2 kustomize => 5.6. - Upgrade golang to 1.23 ref: https://issues.redhat.com/browse/ACM-8341 Signed-off-by: yiraeChristineKim <yikim@redhat.com>
1 parent a2769fe commit 9f7f570

32 files changed

+166
-158
lines changed

api/v1/policy_webhook.go

+2-2
Original file line numberDiff line numberDiff line change
@@ -100,7 +100,7 @@ func (r *Policy) validateName() error {
100100

101101
// 1 character for "."
102102
if (utf8.RuneCountInString(r.Name) + utf8.RuneCountInString(r.Namespace)) > 62 {
103-
log.Info(fmt.Sprintf("Invalid policy name/namespace: %s", errName.Error()))
103+
log.Info("Invalid policy name/namespace: " + errName.Error())
104104

105105
return errName
106106
}
@@ -126,7 +126,7 @@ func (r *Policy) validateRemediationAction() error {
126126
if objUnstruct.GroupVersionKind().Kind == "ConfigurationPolicy" {
127127
_, found, _ := unstructured.NestedString(objUnstruct.Object, "spec", "remediationAction")
128128
if !found {
129-
log.Info(fmt.Sprintf("Invalid remediationAction configuration: %s", errRemediation.Error()))
129+
log.Info("Invalid remediationAction configuration: " + errRemediation.Error())
130130

131131
return errRemediation
132132
}

api/v1beta1/policyautomation_types.go

+7-7
Original file line numberDiff line numberDiff line change
@@ -134,7 +134,7 @@ func init() {
134134
// ReplicatedComplianceHistory defines the replicated policy compliance details history.
135135
type ReplicatedComplianceHistory struct {
136136
LastTimestamp metav1.Time `json:"lastTimestamp,omitempty" protobuf:"bytes,7,opt,name=lastTimestamp"`
137-
Message string `json:"message,omitempty" protobuf:"bytes,4,opt,name=message"`
137+
Message string `json:"message,omitempty" protobuf:"bytes,4,opt,name=message"`
138138
}
139139

140140
// ReplicatedDetailsPerTemplate defines the replicated policy compliance details and history.
@@ -153,10 +153,10 @@ type ReplicatedPolicyStatus struct {
153153
// ViolationContext defines the noncompliant replicated policy information that is sent to the
154154
// AnsibleJob through the extra_vars parameter.
155155
type ViolationContext struct {
156-
TargetClusters []string `json:"targetClusters" ansibleJob:"target_clusters"`
157-
PolicyName string `json:"policyName" ansibleJob:"policy_name"`
158-
PolicyNamespace string `json:"policyNamespace" ansibleJob:"policy_namespace"`
159-
HubCluster string `json:"hubCluster" ansibleJob:"hub_cluster"`
160-
PolicySets []string `json:"policySets" ansibleJob:"policy_sets"`
161-
PolicyViolations map[string]ReplicatedPolicyStatus `json:"policyViolations" ansibleJob:"policy_violations"`
156+
TargetClusters []string `ansibleJob:"target_clusters" json:"targetClusters"`
157+
PolicyName string `ansibleJob:"policy_name" json:"policyName"`
158+
PolicyNamespace string `ansibleJob:"policy_namespace" json:"policyNamespace"`
159+
HubCluster string `ansibleJob:"hub_cluster" json:"hubCluster"`
160+
PolicySets []string `ansibleJob:"policy_sets" json:"policySets"`
161+
PolicyViolations map[string]ReplicatedPolicyStatus `ansibleJob:"policy_violations" json:"policyViolations"`
162162
}

build/common/Makefile.common.mk

+3-3
Original file line numberDiff line numberDiff line change
@@ -5,15 +5,15 @@
55
# https://github.com/kubernetes-sigs/controller-tools/releases/latest
66
CONTROLLER_GEN_VERSION := v0.16.3
77
# https://github.com/kubernetes-sigs/kustomize/releases/latest
8-
KUSTOMIZE_VERSION := v5.4.3
8+
KUSTOMIZE_VERSION := v5.6.0
99
# https://github.com/golangci/golangci-lint/releases/latest
10-
GOLANGCI_VERSION := v1.52.2
10+
GOLANGCI_VERSION := v1.64.8
1111
# https://github.com/mvdan/gofumpt/releases/latest
1212
GOFUMPT_VERSION := v0.7.0
1313
# https://github.com/daixiang0/gci/releases/latest
1414
GCI_VERSION := v0.13.5
1515
# https://github.com/securego/gosec/releases/latest
16-
GOSEC_VERSION := v2.21.3
16+
GOSEC_VERSION := v2.22.2
1717
# https://github.com/kubernetes-sigs/kubebuilder/releases/latest
1818
KBVERSION := 3.15.1
1919
# https://github.com/kubernetes/kubernetes/releases/latest

build/common/config/.golangci.yml

+1
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ run:
2424
linters:
2525
enable-all: true
2626
disable:
27+
- mnd # Disabled as tech debt: Magic number detection
2728
- bodyclose
2829
- contextcheck # New linter to consider
2930
- cyclop

controllers/automation/PolicyAutomationPredicate.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ var policyAuomtationPredicateFuncs = predicate.Funcs{
3434

3535
return policyAutomationNew.Spec.PolicyRef != ""
3636
},
37-
DeleteFunc: func(e event.DeleteEvent) bool {
37+
DeleteFunc: func(_ event.DeleteEvent) bool {
3838
return false
3939
},
4040
}

controllers/automation/ansible.go

+6-4
Original file line numberDiff line numberDiff line change
@@ -122,16 +122,18 @@ func CreateAnsibleJob(policyAutomation *policyv1beta1.PolicyAutomation,
122122
typesOf := values.Type()
123123
// add every violationContext fields into mapExtraVars as well as the empty values,
124124
// or when the whole violationContext is empty
125-
for i := 0; i < values.NumField(); i++ {
125+
for i := range values.NumField() {
126126
tag := typesOf.Field(i).Tag
127127
value := values.Field(i).Interface()
128128

129129
var fieldName string
130-
if tag.Get("ansibleJob") != "" {
130+
131+
switch {
132+
case tag.Get("ansibleJob") != "":
131133
fieldName = tag.Get("ansibleJob")
132-
} else if tag.Get("json") != "" {
134+
case tag.Get("json") != "":
133135
fieldName = strings.SplitN(tag.Get("json"), ",", 2)[0]
134-
} else {
136+
default:
135137
fieldName = typesOf.Field(i).Name
136138
}
137139

controllers/automation/policyPredicate.go

+2-2
Original file line numberDiff line numberDiff line change
@@ -24,10 +24,10 @@ var policyPredicateFuncs = predicate.Funcs{
2424

2525
return !cmp.Equal(plcObjNew.Status.Status, plcObjOld.Status.Status)
2626
},
27-
CreateFunc: func(e event.CreateEvent) bool {
27+
CreateFunc: func(_ event.CreateEvent) bool {
2828
return false
2929
},
30-
DeleteFunc: func(e event.DeleteEvent) bool {
30+
DeleteFunc: func(_ event.DeleteEvent) bool {
3131
return false
3232
},
3333
}

controllers/automation/policyautomation_controller.go

+56-61
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@ package automation
55

66
import (
77
"context"
8-
"fmt"
98
"strconv"
109
"time"
1110

@@ -83,7 +82,7 @@ func (r *PolicyAutomationReconciler) setOwnerReferences(
8382
}
8483

8584
if !policyOwnerRefFound {
86-
log.V(3).Info(fmt.Sprintf("Setting the owner reference on the PolicyAutomation %s", policyAutomation.GetName()))
85+
log.V(3).Info("Setting the owner reference on the PolicyAutomation " + policyAutomation.GetName())
8786
policyAutomation.SetOwnerReferences([]metav1.OwnerReference{
8887
*metav1.NewControllerRef(policy, policy.GroupVersionKind()),
8988
})
@@ -232,8 +231,8 @@ func (r *PolicyAutomationReconciler) getViolationContext(
232231
if contextLimit > 0 && len(violationContext.PolicyViolations) == contextLimit {
233232
log.V(2).Info(
234233
"PolicyViolationsLimit is %s so skipping %s remaining replicated policies violations.",
235-
fmt.Sprint(contextLimit),
236-
fmt.Sprint(len(replicatedPlcList.Items)-contextLimit),
234+
strconv.Itoa(contextLimit),
235+
strconv.Itoa(len(replicatedPlcList.Items)-contextLimit),
237236
)
238237

239238
break
@@ -301,9 +300,10 @@ func (r *PolicyAutomationReconciler) Reconcile(
301300
return reconcile.Result{}, err
302301
}
303302

304-
if policyAutomation.Annotations["policy.open-cluster-management.io/rerun"] == "true" {
305-
AjExist, err := MatchPAResouceV(policyAutomation,
306-
r.DynamicClient, policyAutomation.GetResourceVersion())
303+
switch {
304+
case policyAutomation.Annotations["policy.open-cluster-management.io/rerun"] == "true":
305+
// Rerun logic
306+
AjExist, err := MatchPAResouceV(policyAutomation, r.DynamicClient, policyAutomation.GetResourceVersion())
307307
if err != nil {
308308
log.Error(err, "Failed to compare Ansible job's resourceVersion")
309309

@@ -317,24 +317,18 @@ func (r *PolicyAutomationReconciler) Reconcile(
317317
}
318318

319319
targetList := common.FindNonCompliantClustersForPolicy(policy)
320-
log.Info(
321-
"Creating an Ansible job", "mode", "manual",
322-
"clusterCount", strconv.Itoa(len(targetList)))
320+
log.Info("Creating an Ansible job", "mode", "manual", "clusterCount", strconv.Itoa(len(targetList)))
323321

324322
violationContext, _ := r.getViolationContext(ctx, policy, targetList, policyAutomation)
325323

326-
err = CreateAnsibleJob(
327-
policyAutomation,
328-
r.DynamicClient,
329-
"manual",
330-
violationContext,
331-
)
324+
err = CreateAnsibleJob(policyAutomation, r.DynamicClient, "manual", violationContext)
332325
if err != nil {
333326
log.Error(err, "Failed to create the Ansible job", "mode", "manual")
334327

335328
return reconcile.Result{}, err
336329
}
337-
// manual run succeeded, remove annotation
330+
331+
// Manual run succeeded, remove annotation
338332
delete(policyAutomation.Annotations, "policy.open-cluster-management.io/rerun")
339333

340334
err = r.Update(ctx, policyAutomation, &client.UpdateOptions{})
@@ -345,19 +339,17 @@ func (r *PolicyAutomationReconciler) Reconcile(
345339
}
346340

347341
return reconcile.Result{}, nil
348-
} else if policyAutomation.Spec.Mode == policyv1beta1.Disabled {
349-
log.Info("Automation is disabled, doing nothing")
350342

351-
return reconcile.Result{}, nil
352-
} else {
353-
if policy.Spec.Disabled {
354-
log.Info("The policy is disabled. Doing nothing.")
343+
case policy.Spec.Disabled:
344+
log.Info("The policy is disabled. Doing nothing.")
355345

356-
return reconcile.Result{}, nil
357-
}
346+
return reconcile.Result{}, nil
358347

359-
if policyAutomation.Spec.Mode == "scan" {
348+
default:
349+
switch policyAutomation.Spec.Mode {
350+
case "scan":
360351
log := log.WithValues("mode", "scan")
352+
361353
log.V(2).Info("Triggering scan mode")
362354

363355
requeueAfter, err := time.ParseDuration(policyAutomation.Spec.RescanAfter)
@@ -373,45 +365,42 @@ func (r *PolicyAutomationReconciler) Reconcile(
373365
if len(targetList) > 0 {
374366
log.Info("Creating An Ansible job", "targetList", targetList)
375367
violationContext, _ := r.getViolationContext(ctx, policy, targetList, policyAutomation)
376-
err = CreateAnsibleJob(policyAutomation, r.DynamicClient, "scan",
377-
violationContext)
368+
369+
err = CreateAnsibleJob(policyAutomation, r.DynamicClient, "scan", violationContext)
378370
if err != nil {
379371
return reconcile.Result{RequeueAfter: requeueAfter}, err
380372
}
381373
} else {
382374
log.Info("All clusters are compliant. Doing nothing.")
383375
}
384-
385376
// no violations found, doing nothing
386377
r.counter++
387-
log.V(2).Info(
388-
"RequeueAfter.", "RequeueAfter", requeueAfter.String(), "Counter", fmt.Sprintf("%d", r.counter),
389-
)
378+
379+
log.V(2).Info("RequeueAfter.", "RequeueAfter", requeueAfter.String(), "Counter", strconv.Itoa(r.counter))
390380

391381
return reconcile.Result{RequeueAfter: requeueAfter}, nil
392-
} else if policyAutomation.Spec.Mode == policyv1beta1.Once {
382+
383+
case policyv1beta1.Once:
393384
log := log.WithValues("mode", string(policyv1beta1.Once))
394385
targetList := common.FindNonCompliantClustersForPolicy(policy)
386+
395387
if len(targetList) > 0 {
396388
log.Info("Creating an Ansible job", "targetList", targetList)
397389

398-
AjExist, err := MatchPAGeneration(policyAutomation,
399-
r.DynamicClient, policyAutomation.GetGeneration())
390+
AjExist, err := MatchPAGeneration(policyAutomation, r.DynamicClient, policyAutomation.GetGeneration())
400391
if err != nil {
401392
log.Error(err, "Failed to get Ansible job's generation")
402393

403394
return reconcile.Result{}, err
404395
}
396+
405397
if AjExist {
406398
return reconcile.Result{}, nil
407399
}
400+
408401
violationContext, _ := r.getViolationContext(ctx, policy, targetList, policyAutomation)
409-
err = CreateAnsibleJob(
410-
policyAutomation,
411-
r.DynamicClient,
412-
string(policyv1beta1.Once),
413-
violationContext,
414-
)
402+
403+
err = CreateAnsibleJob(policyAutomation, r.DynamicClient, string(policyv1beta1.Once), violationContext)
415404
if err != nil {
416405
log.Error(err, "Failed to create the Ansible job")
417406

@@ -429,7 +418,8 @@ func (r *PolicyAutomationReconciler) Reconcile(
429418
} else {
430419
log.Info("All clusters are compliant. Doing nothing.")
431420
}
432-
} else if policyAutomation.Spec.Mode == policyv1beta1.EveryEvent {
421+
422+
case policyv1beta1.EveryEvent:
433423
log := log.WithValues("mode", string(policyv1beta1.EveryEvent))
434424
targetList := common.FindNonCompliantClustersForPolicy(policy)
435425
targetListMap := getTargetListMap(targetList)
@@ -441,6 +431,7 @@ func (r *PolicyAutomationReconciler) Reconcile(
441431
requeueFlag := false
442432
// Automation event time grouped by the cluster name
443433
eventMap := map[string]policyv1beta1.ClusterEvent{}
434+
444435
if len(policyAutomation.Status.ClustersWithEvent) > 0 {
445436
eventMap = policyAutomation.Status.ClustersWithEvent
446437
}
@@ -460,7 +451,6 @@ func (r *PolicyAutomationReconciler) Reconcile(
460451
log.Error(err, "Failed to retrieve EventTime in ClustersWithEvent")
461452
delete(eventMap, clusterName)
462453
}
463-
464454
// The time that delayAfterRunSeconds setting expires
465455
delayUntil := originalStartTime.Add(time.Duration(delayAfterRunSeconds) * time.Second)
466456

@@ -479,22 +469,23 @@ func (r *PolicyAutomationReconciler) Reconcile(
479469
} else {
480470
requeueFlag = true
481471
// Within the delay period and use the earliest requeueDuration to requeue
482-
if (requeueDuration == 0) || (requeueDuration > int(delayUntil.Sub(now)+1)) {
472+
if requeueDuration == 0 || requeueDuration > int(delayUntil.Sub(now)+1) {
483473
requeueDuration = int(delayUntil.Sub(now) + 1)
484474
}
485475
// keep the event and update eventTime
486476
clusterEvent.EventTime = nowStr
487-
// new event from compliant to non-compliant
488477
eventMap[clusterName] = clusterEvent
489478
}
490-
} // Otherwise, the policy keeps non-compliant since originalStartTime, do nothing
491-
} else { // The policy is compliant with the target cluster
479+
}
480+
} else {
481+
// Otherwise, the policy keeps non-compliant since originalStartTime, do nothing
482+
// The policy is compliant with the target cluster
492483
if delayAfterRunSeconds > 0 && now.Before(delayUntil) {
493484
// Within the delay period, keep the event and update eventTime
494485
clusterEvent.EventTime = nowStr
495-
// new event from non-compliant to compliant
496486
eventMap[clusterName] = clusterEvent
497-
} else { // No delay period or it is expired, remove the event
487+
} else {
488+
// No delay period or it is expired, remove the event
498489
delete(eventMap, clusterName)
499490
}
500491
}
@@ -514,14 +505,12 @@ func (r *PolicyAutomationReconciler) Reconcile(
514505
for clusterName := range trimmedTargetMap {
515506
trimmedTargetList = append(trimmedTargetList, clusterName)
516507
}
508+
517509
log.Info("Creating An Ansible job", "trimmedTargetList", trimmedTargetList)
518510
violationContext, _ := r.getViolationContext(ctx, policy, trimmedTargetList, policyAutomation)
519-
err = CreateAnsibleJob(
520-
policyAutomation,
521-
r.DynamicClient,
522-
string(policyv1beta1.EveryEvent),
523-
violationContext,
524-
)
511+
512+
err = CreateAnsibleJob(policyAutomation, r.DynamicClient,
513+
string(policyv1beta1.EveryEvent), violationContext)
525514
if err != nil {
526515
log.Error(err, "Failed to create the Ansible job")
527516

@@ -542,22 +531,28 @@ func (r *PolicyAutomationReconciler) Reconcile(
542531

543532
policyAutomation.Status.ClustersWithEvent = eventMap
544533
// use StatusWriter to update status subresource of a Kubernetes object
545-
err = r.Status().Update(ctx, policyAutomation)
534+
err := r.Status().Update(ctx, policyAutomation)
546535
if err != nil {
547536
log.Error(err, "Failed to update ClustersWithEvent in policyAutomation status")
548537

549538
return reconcile.Result{}, err
550539
}
551540

552541
if requeueFlag {
553-
log.Info(
554-
"Requeue for the new non-compliant event during the delay period",
555-
"Delay in seconds", delayAfterRunSeconds,
556-
"Requeue After", requeueDuration,
557-
)
542+
log.Info("Requeue for the new non-compliant event during the delay period", "Delay in seconds",
543+
delayAfterRunSeconds, "Requeue After", requeueDuration)
558544

559545
return reconcile.Result{RequeueAfter: time.Duration(requeueDuration)}, nil
560546
}
547+
548+
case policyv1beta1.Disabled:
549+
log.Info("Automation is disabled, doing nothing")
550+
551+
return reconcile.Result{}, nil
552+
default:
553+
log.Info("Unknown mode. No action taken.")
554+
555+
return reconcile.Result{}, nil
561556
}
562557
}
563558

controllers/common/common_test.go

+2
Original file line numberDiff line numberDiff line change
@@ -30,9 +30,11 @@ func TestParseRootPolicyLabel(t *testing.T) {
3030
if (err != nil) != expected.shouldErr {
3131
t.Fatal("expected error, got nil")
3232
}
33+
3334
if name != expected.name {
3435
t.Fatalf("expected name '%v', got '%v'", expected.name, name)
3536
}
37+
3638
if namespace != expected.namespace {
3739
t.Fatalf("expected namespace '%v', got '%v'", expected.namespace, namespace)
3840
}

controllers/common/handler.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -59,4 +59,4 @@ func (e *EnqueueRequestsFromMapFunc) mapAndEnqueue(
5959
}
6060
}
6161

62-
var NeverEnqueue = predicate.NewPredicateFuncs(func(o client.Object) bool { return false })
62+
var NeverEnqueue = predicate.NewPredicateFuncs(func(_ client.Object) bool { return false })

0 commit comments

Comments
 (0)