Skip to content

Commit e24907f

Browse files
authoredJan 8, 2024
enable linters in workflow (#8)
Made linting changes to pass linters check
1 parent f5d1704 commit e24907f

17 files changed

+321
-139
lines changed
 

‎.checkmake

+2
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
[maxbodylength]
2+
disabled = true

‎.github/workflows/pre-main.yaml

+5-2
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,9 @@ on:
66
pull_request:
77
branches: [ main ]
88
workflow_dispatch:
9+
env:
10+
CM_BIN: /usr/local/bin/checkmake
11+
CM_URL_LINUX: https://github.com/mrtazz/checkmake/releases/download/0.2.2/checkmake-0.2.2.linux.amd64 # yamllint disable-line
912

1013
jobs:
1114
lint:
@@ -56,8 +59,8 @@ jobs:
5659
dockerfile: Dockerfile
5760
recursive: true
5861

59-
- name: Shfmt
60-
run: shfmt -d *.sh script
62+
# - name: Shfmt
63+
# run: shfmt -d *.sh script
6164

6265
- name: Markdownlint
6366
uses: nosborn/github-action-markdown-cli@v3.3.0

‎.golangci.yml

+128
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,128 @@
1+
linters-settings:
2+
dupl:
3+
threshold: 100
4+
funlen:
5+
lines: 60
6+
statements: 45
7+
gci:
8+
local-prefixes: github.com/golangci/golangci-lint
9+
goconst:
10+
min-len: 4
11+
min-occurrences: 2
12+
gocritic:
13+
enabled-tags:
14+
- diagnostic
15+
- experimental
16+
- opinionated
17+
- performance
18+
- style
19+
disabled-checks:
20+
- whyNoLint
21+
gocyclo:
22+
min-complexity: 20
23+
goimports:
24+
local-prefixes: github.com/golangci/golangci-lint
25+
gomnd:
26+
settings:
27+
mnd:
28+
# do not include the "operation" and "assign"
29+
checks: argument,case,condition,return
30+
govet:
31+
check-shadowing: true
32+
settings:
33+
printf:
34+
funcs:
35+
- (github.com/golangci/golangci-lint/pkg/logutils.Log).Infof
36+
- (github.com/golangci/golangci-lint/pkg/logutils.Log).Warnf
37+
- (github.com/golangci/golangci-lint/pkg/logutils.Log).Errorf
38+
- (github.com/golangci/golangci-lint/pkg/logutils.Log).Fatalf
39+
lll:
40+
line-length: 250
41+
maligned:
42+
suggest-new: true
43+
nolintlint:
44+
allow-leading-space: false # disallow leading spaces. A space means the //nolint comment shows in `godoc` output.
45+
allow-unused: false # report any unused nolint directives
46+
require-explanation: false # do not require an explanation for nolint directives
47+
require-specific: true # require nolint directives to be specific about which linter is being skipped
48+
exhaustive:
49+
default-signifies-exhaustive: true
50+
linters:
51+
# please, do not use `enable-all`: it's deprecated and will be removed soon.
52+
# inverted configuration with `enable-all` and `disable` is not scalable during updates of golangci-lint
53+
disable-all: true
54+
enable:
55+
- bodyclose
56+
- dogsled
57+
- errcheck
58+
- exhaustive
59+
- exportloopref
60+
- funlen
61+
- goconst
62+
- gocritic
63+
- gocyclo
64+
- gofmt
65+
- goimports
66+
- gomnd
67+
- goprintffuncname
68+
- gosec
69+
- gosimple
70+
- govet
71+
- ineffassign
72+
- lll
73+
- misspell
74+
- nolintlint
75+
- revive
76+
- rowserrcheck
77+
- staticcheck
78+
- stylecheck
79+
- typecheck
80+
- unconvert
81+
- unparam
82+
- unused
83+
- whitespace
84+
# do not enable:
85+
# - asciicheck
86+
# - depguard
87+
# - dupl
88+
# - gochecknoglobals
89+
# - gochecknoinits
90+
# - gocognit
91+
# - godot
92+
# - godox
93+
# - goerr113
94+
# - maligned
95+
# - nakedret
96+
# - nestif
97+
# - noctx
98+
# - prealloc
99+
# - exportloopref
100+
# - structcheck
101+
# - testpackage
102+
# - wsl
103+
issues:
104+
# Excluding configuration per-path, per-linter, per-text and per-source
105+
exclude-rules:
106+
# Ignore magic numbers, inline strings and function length in tests.
107+
- path: _test\.go
108+
linters:
109+
- gomnd
110+
- goconst
111+
- funlen
112+
# Ignore line length for string assignments (do not try and wrap regex definitions)
113+
- linters:
114+
- lll
115+
source: "^(.*= (\".*\"|`.*`))$"
116+
# https://github.com/go-critic/go-critic/issues/926
117+
- linters:
118+
- gocritic
119+
text: "unnecessaryDefer:"
120+
# Ignore static strings in tests
121+
122+
123+
# golangci.com configuration
124+
# https://github.com/golangci/golangci/wiki/Configuration
125+
service:
126+
golangci-lint-version: 1.55.x # use the fixed version to not introduce new linters unexpectedly
127+
prepare:
128+
- echo "here I can run custom commands, but no preparation needed for this repo"

‎.yamllint.yml

+2
Original file line numberDiff line numberDiff line change
@@ -10,3 +10,5 @@ rules:
1010
empty-lines:
1111
level: warning
1212
no_warnings: true
13+
ignore:
14+
- config

‎Makefile

+13-1
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
# - use the VERSION as arg of the bundle target (e.g make bundle VERSION=0.0.2)
55
# - use environment variables to overwrite this value (e.g export VERSION=0.0.2)
66
VERSION ?= 0.0.1
7+
BASH_SCRIPTS=$(shell find . -name "*.sh" -not -path "./.git/*")
78

89
# CHANNELS define the bundle channels used in the bundle.
910
# Add a new line here if you would like to change its default config. (E.g CHANNELS = "candidate,fast,stable")
@@ -63,7 +64,7 @@ endif
6364
SHELL = /usr/bin/env bash -o pipefail
6465
.SHELLFLAGS = -ec
6566

66-
.PHONY: all
67+
.PHONY: all clean
6768
all: build
6869

6970
##@ General
@@ -101,6 +102,17 @@ fmt: ## Run go fmt against code.
101102
vet: ## Run go vet against code.
102103
go vet ./...
103104

105+
.PHONY: lint
106+
lint: # Runs configured linters
107+
checkmake --config=.checkmake Makefile
108+
golangci-lint run --timeout 10m0s
109+
hadolint Dockerfile
110+
# shfmt -d *.sh script
111+
typos
112+
markdownlint '**/*.md'
113+
yamllint --no-warnings .
114+
shellcheck --format=gcc ${BASH_SCRIPTS}
115+
104116
.PHONY: test
105117
test: manifests generate fmt vet envtest ## Run tests.
106118
KUBEBUILDER_ASSETS="$(shell $(ENVTEST) use $(ENVTEST_K8S_VERSION) --bin-dir $(LOCALBIN) -p path)" go test ./... -coverprofile cover.out

‎README.md

+52-30
Original file line numberDiff line numberDiff line change
@@ -1,77 +1,98 @@
11
# tnf-op
2+
23
Red Hat's CNF Certification Suite Operator PoC
34

45
## Description
5-
Proof of Concept for a Kubernetes/Openshift Operator running the [CNF Certification Suite Container](https://github.com/test-network-function/cnf-certification-test).
6+
7+
Proof of Concept for a Kubernetes/Openshift Operator running the
8+
[CNF Certification Suite Container](https://github.com/test-network-function/cnf-certification-test).
69

710
## Getting Started
8-
You’ll need a Kubernetes cluster to run against. You can use [KIND](https://sigs.k8s.io/kind) to get a local cluster for testing, or run against a remote cluster.
9-
**Note:** Your controller will automatically use the current context in your kubeconfig file (i.e. whatever cluster `kubectl cluster-info` shows).
11+
12+
You’ll need a Kubernetes cluster to run against.
13+
You can use [KIND](https://sigs.k8s.io/kind) to get a local cluster for testing,
14+
or run against a remote cluster.
15+
**Note:** Your controller will automatically use the current context in your
16+
kubeconfig file (i.e. whatever cluster `kubectl cluster-info` shows).
1017

1118
### Running on the cluster
19+
1220
1. Install Instances of Custom Resources:
1321

14-
```sh
15-
kubectl apply -f config/samples/
16-
```
22+
```sh
23+
kubectl apply -f config/samples/
24+
```
1725

1826
2. Build and push your image to the location specified by `IMG`:
1927

20-
```sh
21-
make docker-build docker-push IMG=<some-registry>/tnf-op:tag
22-
```
28+
```sh
29+
make docker-build docker-push IMG=<some-registry>/tnf-op:tag
30+
```
2331

2432
3. Deploy the controller to the cluster with the image specified by `IMG`:
2533

26-
```sh
27-
make deploy IMG=<some-registry>/tnf-op:tag
28-
```
34+
```sh
35+
make deploy IMG=<some-registry>/tnf-op:tag
36+
```
2937

3038
### Uninstall CRDs
39+
3140
To delete the CRDs from the cluster:
3241

3342
```sh
3443
make uninstall
3544
```
3645

3746
### Undeploy controller
47+
3848
UnDeploy the controller from the cluster:
3949

4050
```sh
4151
make undeploy
4252
```
4353

4454
## Contributing
45-
// TODO(user): Add detailed information on how you would like others to contribute to this project
55+
56+
// TODO(user): Add detailed information on how you would
57+
like others to contribute to this project
4658

4759
### How it works
48-
This project aims to follow the Kubernetes [Operator pattern](https://kubernetes.io/docs/concepts/extend-kubernetes/operator/).
4960

50-
It uses [Controllers](https://kubernetes.io/docs/concepts/architecture/controller/),
51-
which provide a reconcile function responsible for synchronizing resources until the desired state is reached on the cluster.
61+
This project aims to follow the Kubernetes
62+
[Operator pattern](https://kubernetes.io/docs/concepts/extend-kubernetes/operator/).
63+
64+
It uses
65+
[Controllers](https://kubernetes.io/docs/concepts/architecture/controller/),
66+
which provide a reconcile function responsible for synchronizing resources until
67+
the desired state is reached on the cluster.
5268

5369
### Test It Out
70+
5471
1. Install the CRDs into the cluster:
5572

56-
```sh
57-
make install
58-
```
73+
```sh
74+
make install
75+
```
5976

60-
2. Run your controller (this will run in the foreground, so switch to a new terminal if you want to leave it running):
77+
2. Run your controller (this will run in the foreground,
78+
so switch to a new terminal if you want to leave it running):
6179

62-
```sh
63-
make run
64-
```
80+
```sh
81+
make run
82+
```
6583

66-
**NOTE:** You can also run this in one step by running: `make install run`
84+
**NOTE:** You can also run this in one step by running: `make install run`
6785

6886
3. Sample CnfCertificationSuiteRun CR:
69-
```
70-
oc apply -f cert-run.yaml
71-
```
87+
88+
```sh
89+
oc apply -f cert-run.yaml
90+
```
7291

7392
### Modifying the API definitions
74-
If you are editing the API definitions, generate the manifests such as CRs or CRDs using:
93+
94+
If you are editing the API definitions,
95+
generate the manifests such as CRs or CRDs using:
7596

7697
```sh
7798
make manifests
@@ -89,11 +110,12 @@ Licensed under the Apache License, Version 2.0 (the "License");
89110
you may not use this file except in compliance with the License.
90111
You may obtain a copy of the License at
91112

92-
http://www.apache.org/licenses/LICENSE-2.0
113+
```plaintext
114+
http://www.apache.org/licenses/LICENSE-2.0
115+
```
93116

94117
Unless required by applicable law or agreed to in writing, software
95118
distributed under the License is distributed on an "AS IS" BASIS,
96119
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
97120
See the License for the specific language governing permissions and
98121
limitations under the License.
99-

‎_typos.toml

+7
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
[default.extend-words]
2+
iif = "iif"
3+
ono = "ono"
4+
daa = "daa"
5+
6+
[files]
7+
extend-exclude = ["depends-on.json", "go.mod"]

‎cnf-cert-sidecar/Dockerfile

+6-4
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
FROM registry.access.redhat.com/ubi8/ubi:latest AS build
1+
FROM registry.access.redhat.com/ubi8/ubi:8.9-1028 AS build
22

33
# Install dependencies
44
# hadolint ignore=DL3041
@@ -21,19 +21,21 @@ ENV \
2121
ENV GO_BIN_URL_x86_64=${GO_DL_URL}/${GO_BIN_TAR}
2222
RUN \
2323
if [ "$(uname -m)" = x86_64 ]; then \
24-
wget --directory-prefix=${TEMP_DIR} ${GO_BIN_URL_x86_64} --quiet \
24+
wget --directory-prefix="${TEMP_DIR}" ${GO_BIN_URL_x86_64} --quiet \
2525
&& rm -rf /usr/local/go \
26-
&& tar -C /usr/local -xzf ${TEMP_DIR}/${GO_BIN_TAR}; \
26+
&& tar -C /usr/local -xzf "${TEMP_DIR}/${GO_BIN_TAR}"; \
2727
else \
2828
echo "CPU architecture is not supported." && exit 1; \
2929
fi
3030
ENV PATH=${PATH}:"/usr/local/go/bin":${GOPATH}/"bin"
3131

3232
# Build app and copy into a empty ubi-minimal image.
33+
WORKDIR /
3334
COPY . .
3435
RUN ls -la && go build -o app cnf-cert-sidecar/app/main.go
3536

36-
FROM registry.access.redhat.com/ubi8/ubi-minimal
37+
FROM registry.access.redhat.com/ubi8/ubi-minimal:8.9-1029
38+
WORKDIR /
3739
COPY --from=build app .
3840

3941
ENV SHELL=/bin/bash

‎cnf-cert-sidecar/app/claim/claim.go

-4
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,6 @@ import (
44
corev1 "k8s.io/api/core/v1"
55
)
66

7-
const (
8-
supportedClaimFormatVersion = "v0.1.0"
9-
)
10-
117
const (
128
TestCaseResultPassed = "passed"
139
TestCaseResultSkipped = "skipped"

‎cnf-cert-sidecar/app/cnf-cert-suite-report/cnfcertsuitereport.go

+10-8
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@ import (
44
"fmt"
55
"os"
66

7-
"github.com/greyerof/cnf-certification-operator/api/v1alpha1"
87
cnfcertificationsv1alpha1 "github.com/greyerof/cnf-certification-operator/api/v1alpha1"
98
"github.com/greyerof/cnf-certification-operator/cnf-cert-sidecar/app/claim"
109
corev1 "k8s.io/api/core/v1"
@@ -14,7 +13,7 @@ import (
1413
const (
1514
podNameEnvVar = "MY_POD_NAME"
1615
podNamespaceEnvVar = "MY_POD_NAMESPACE"
17-
runCrNameEnvVar = "RUN_CR_NAME"
16+
runCrNameEnvVar = "RUN_CR_NAME"
1817
)
1918

2019
type Config struct {
@@ -31,10 +30,12 @@ func addNamespacesToCnfSpecField(cnf *cnfcertificationsv1alpha1.Cnf, namespaces
3130
}
3231

3332
func addPodsToCnfSpecField(cnf *cnfcertificationsv1alpha1.Cnf, pods []corev1.Pod) {
34-
for _, pod := range pods {
33+
for podIdx := 0; podIdx < len(pods); podIdx++ {
34+
pod := &pods[podIdx]
35+
podsContainers := &pod.Spec.Containers
3536
var containers []string
36-
for _, container := range pod.Spec.Containers {
37-
containers = append(containers, container.Name)
37+
for containerIdx := 0; containerIdx < len(*podsContainers); containerIdx++ {
38+
containers = append(containers, (*podsContainers)[containerIdx].Name)
3839
}
3940
cnf.Pods = append(cnf.Pods, cnfcertificationsv1alpha1.CnfPod{
4041
Name: pod.Name,
@@ -119,7 +120,8 @@ func UpdateStatus(cnfCertSuiteReport *cnfcertificationsv1alpha1.CnfCertification
119120
testSuiteResults *claim.TestSuiteResults) {
120121
results := []cnfcertificationsv1alpha1.TestCaseResult{}
121122
totalTests, passedTests, skippedTests, failedTests, erroredTests := 0, 0, 0, 0, 0
122-
for tcName, tcResult := range *testSuiteResults {
123+
for tcName := range *testSuiteResults {
124+
tcResult := (*testSuiteResults)[tcName]
123125
reason := ""
124126
switch tcResult.State {
125127
case "passed":
@@ -130,7 +132,7 @@ func UpdateStatus(cnfCertSuiteReport *cnfcertificationsv1alpha1.CnfCertification
130132
case "failed":
131133
failedTests++
132134
reason = tcResult.FailureReason
133-
case "error":
135+
case "error": //nolint:goconst
134136
erroredTests++
135137
}
136138
totalTests++
@@ -142,7 +144,7 @@ func UpdateStatus(cnfCertSuiteReport *cnfcertificationsv1alpha1.CnfCertification
142144
})
143145
}
144146
cnfCertSuiteReport.Status.Results = results
145-
cnfCertSuiteReport.Status.Summary = v1alpha1.CnfCertificationSuiteReportStatusSummary{
147+
cnfCertSuiteReport.Status.Summary = cnfcertificationsv1alpha1.CnfCertificationSuiteReportStatusSummary{
146148
Total: totalTests,
147149
Passed: passedTests,
148150
Skipped: skippedTests,

‎cnf-cert-sidecar/app/main.go

+44-40
Original file line numberDiff line numberDiff line change
@@ -19,46 +19,10 @@ import (
1919
const (
2020
sideCarResultsFolderEnvVar = "TNF_RESULTS_FOLDER"
2121
claimFileName = "claim.json"
22+
multiplier = 5
2223
)
2324

24-
// This CNF Certification sidecar container expects to be running in the same
25-
// pod as the CNF Cert Suite container.
26-
//
27-
// The sidecar will wait for TNF_CNF_CERT_TIMEOUT secs until the claim.json output is present in a
28-
// shared volume folder. Then it will parse it to get the list of test cases
29-
// results, and creates the CR CnfCertificationSuiteReport
30-
func main() {
31-
scheme := runtime.NewScheme()
32-
err := clientgoscheme.AddToScheme(scheme)
33-
if err != nil {
34-
logrus.Fatalf("failed to add to scheme: %v", err)
35-
}
36-
37-
err = cnfcertificationsv1alpha1.AddToScheme(scheme)
38-
if err != nil {
39-
logrus.Fatalf("failed to add cnfcertificationsv1alpha1 to scheme: %v", err)
40-
}
41-
42-
// k8sRestConfig, err := rest.InClusterConfig()
43-
kubeConfigFile := os.Getenv("HOME") + "/.kube/config"
44-
_, err = os.Stat(kubeConfigFile)
45-
if err != nil {
46-
kubeConfigFile = ""
47-
}
48-
49-
k8sRestConfig, err := clientcmd.BuildConfigFromFlags("", kubeConfigFile)
50-
if err != nil {
51-
logrus.Fatalf("Failed to get incluster rest config: %v", err)
52-
}
53-
54-
DefaultTimeout := 10 * time.Second
55-
k8sRestConfig.Timeout = DefaultTimeout
56-
57-
k8sClient, err := client.New(k8sRestConfig, client.Options{Scheme: scheme})
58-
if err != nil {
59-
logrus.Fatalf("Failed to get k8s client: %v", err)
60-
}
61-
25+
func handleClaimFile(k8sClient client.Client) {
6226
claimFolder := os.Getenv(sideCarResultsFolderEnvVar)
6327
logrus.Infof("Claim file folder: %v", claimFolder)
6428

@@ -67,13 +31,13 @@ func main() {
6731
_, err := os.Stat(claimFilePath)
6832
if os.IsNotExist(err) {
6933
logrus.Warnf("Claim file not found yet. Waiting 5 secs...")
70-
time.Sleep(5 * time.Second)
34+
time.Sleep(multiplier * time.Second)
7135
continue
7236
}
7337

7438
// Wait extra 5 secs to give time to the writer to finish.
7539
// TODO: Use file locking mechanism between writer/reader of this file.
76-
time.Sleep(5 * time.Second)
40+
time.Sleep(multiplier * time.Second)
7741

7842
logrus.Infof("Claim file found at %v", claimFilePath)
7943
claimBytes, err := os.ReadFile(claimFilePath)
@@ -105,3 +69,43 @@ func main() {
10569
break
10670
}
10771
}
72+
73+
// This CNF Certification sidecar container expects to be running in the same
74+
// pod as the CNF Cert Suite container.
75+
//
76+
// The sidecar will wait for TNF_CNF_CERT_TIMEOUT secs until the claim.json output is present in a
77+
// shared volume folder. Then it will parse it to get the list of test cases
78+
// results, and creates the CR CnfCertificationSuiteReport
79+
func main() {
80+
scheme := runtime.NewScheme()
81+
err := clientgoscheme.AddToScheme(scheme)
82+
if err != nil {
83+
logrus.Fatalf("failed to add to scheme: %v", err)
84+
}
85+
86+
err = cnfcertificationsv1alpha1.AddToScheme(scheme)
87+
if err != nil {
88+
logrus.Fatalf("failed to add cnfcertificationsv1alpha1 to scheme: %v", err)
89+
}
90+
91+
kubeConfigFile := os.Getenv("HOME") + "/.kube/config"
92+
_, err = os.Stat(kubeConfigFile)
93+
if err != nil {
94+
kubeConfigFile = ""
95+
}
96+
97+
k8sRestConfig, err := clientcmd.BuildConfigFromFlags("", kubeConfigFile)
98+
if err != nil {
99+
logrus.Fatalf("Failed to get incluster rest config: %v", err)
100+
}
101+
102+
DefaultTimeout := 10 * time.Second
103+
k8sRestConfig.Timeout = DefaultTimeout
104+
105+
k8sClient, err := client.New(k8sRestConfig, client.Options{Scheme: scheme})
106+
if err != nil {
107+
logrus.Fatalf("Failed to get k8s client: %v", err)
108+
}
109+
110+
handleClaimFile(k8sClient)
111+
}

‎controllers/cnf-cert-job/cnfcertjob.go

+1
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ func NewConfig(podName, namespace, certSuiteConfigRunName, labelsFilter, logLeve
2929
}
3030
}
3131

32+
//nolint:funlen
3233
func New(config *Config) *corev1.Pod {
3334
return &corev1.Pod{
3435
TypeMeta: metav1.TypeMeta{},

‎controllers/cnfcertificationsuiterun_controller.go

+22-26
Original file line numberDiff line numberDiff line change
@@ -54,9 +54,11 @@ var (
5454
// certificationRuns maps a certificationRun to a pod name
5555
certificationRuns map[certificationRun]string
5656
// Holds an autoincremental CNF Cert Suite pod id
57-
cnfRunPodId int
57+
cnfRunPodID int
5858
)
5959

60+
const multiplier = 5
61+
6062
// +kubebuilder:rbac:groups="*",resources="*",verbs="*"
6163
// +kubebuilder:rbac:urls="*",verbs="*"
6264

@@ -69,10 +71,13 @@ func ignoreUpdatePredicate() predicate.Predicate {
6971
}
7072
}
7173

72-
// Updates CnfCertificationSuiteRun.Status.Phase correspomding to a given status
74+
// Updates CnfCertificationSuiteRun.Status.Phase corresponding to a given status
7375
func (r *CnfCertificationSuiteRunReconciler) updateJobStatus(cnfrun *cnfcertificationsv1alpha1.CnfCertificationSuiteRun, status string) {
7476
cnfrun.Status.Phase = status
75-
r.Status().Update(context.Background(), cnfrun)
77+
err := r.Status().Update(context.Background(), cnfrun)
78+
if err != nil {
79+
logrus.Errorf("Error found while updating CnfCertificationSuiteRun's status: %s", err)
80+
}
7681
}
7782

7883
func (r *CnfCertificationSuiteRunReconciler) waitForCnfCertJobPodToComplete(ctx context.Context, namespace string, cnfCertJobPod *corev1.Pod) {
@@ -91,7 +96,7 @@ func (r *CnfCertificationSuiteRunReconciler) waitForCnfCertJobPodToComplete(ctx
9196
return
9297
default:
9398
logrus.Info("Cnf job pod is running. Current status: ", cnfCertJobPod.Status.Phase)
94-
time.Sleep(5 * time.Second)
99+
time.Sleep(multiplier * time.Second)
95100
}
96101
err := r.Get(ctx, cnfCertJobNamespacedName, cnfCertJobPod)
97102
if err != nil {
@@ -101,7 +106,8 @@ func (r *CnfCertificationSuiteRunReconciler) waitForCnfCertJobPodToComplete(ctx
101106
}
102107

103108
func (r *CnfCertificationSuiteRunReconciler) getCertSuiteContainerExitStatus(cnfCertJobPod *corev1.Pod) int32 {
104-
for _, containerStatus := range cnfCertJobPod.Status.ContainerStatuses {
109+
for i := range cnfCertJobPod.Status.ContainerStatuses {
110+
containerStatus := &cnfCertJobPod.Status.ContainerStatuses[i]
105111
if containerStatus.Name == definitions.CnfCertSuiteContainerName {
106112
return containerStatus.State.Terminated.ExitCode
107113
}
@@ -119,9 +125,8 @@ func (r *CnfCertificationSuiteRunReconciler) verifyCnfCertSuiteOutput(ctx contex
119125
logrus.Info("CNF Cert job has finished running.")
120126
} else {
121127
r.updateJobStatus(cnfrun, "CertSuiteError")
122-
logrus.Info("CNF Cert job encoutered an error. Exit status: ", certSuiteExitStatus)
128+
logrus.Info("CNF Cert job encountered an error. Exit status: ", certSuiteExitStatus)
123129
}
124-
125130
}
126131

127132
// Reconcile is part of the main kubernetes reconciliation loop which aims to
@@ -135,30 +140,22 @@ func (r *CnfCertificationSuiteRunReconciler) verifyCnfCertSuiteOutput(ctx contex
135140
// - https://pkg.go.dev/sigs.k8s.io/controller-runtime@v0.14.1/pkg/reconcile
136141
func (r *CnfCertificationSuiteRunReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
137142
_ = log.FromContext(ctx)
138-
139143
logrus.Infof("Reconciling CnfCertificationSuiteRun CRD.")
140144

141-
reqCertificationRun := certificationRun{
142-
name: req.Name,
143-
namespace: req.Namespace,
144-
}
145+
reqCertificationRun := certificationRun{name: req.Name, namespace: req.Namespace}
145146

146147
var cnfrun cnfcertificationsv1alpha1.CnfCertificationSuiteRun
147-
if err := r.Get(ctx, req.NamespacedName, &cnfrun); err != nil {
148+
if getErr := r.Get(ctx, req.NamespacedName, &cnfrun); getErr != nil {
148149
logrus.Infof("CnfCertificationSuiteRun CR %s (ns %s) not found.", req.Name, req.NamespacedName)
149-
150150
if podName, exist := certificationRuns[reqCertificationRun]; exist {
151151
logrus.Infof("CnfCertificationSuiteRun has been deleted. Removing the associated CNF Cert job pod %v", podName)
152-
153-
err := r.Delete(context.TODO(), &corev1.Pod{ObjectMeta: metav1.ObjectMeta{Name: podName, Namespace: req.Namespace}})
154-
if err != nil {
155-
logrus.Errorf("Failed to remove CNF Cert Job pod %s in namespace %s: %v", req.Name, req.Namespace, err)
152+
deleteErr := r.Delete(context.TODO(), &corev1.Pod{ObjectMeta: metav1.ObjectMeta{Name: podName, Namespace: req.Namespace}})
153+
if deleteErr != nil {
154+
logrus.Errorf("Failed to remove CNF Cert Job pod %s in namespace %s: %v", req.Name, req.Namespace, deleteErr)
156155
}
157-
158156
delete(certificationRuns, reqCertificationRun)
159157
}
160-
161-
return ctrl.Result{}, client.IgnoreNotFound(err)
158+
return ctrl.Result{}, client.IgnoreNotFound(getErr)
162159
}
163160

164161
if podName, exist := certificationRuns[reqCertificationRun]; exist {
@@ -168,14 +165,14 @@ func (r *CnfCertificationSuiteRunReconciler) Reconcile(ctx context.Context, req
168165

169166
logrus.Infof("New CNF Certification Job run requested: %v", reqCertificationRun)
170167

171-
cnfRunPodId++
172-
podName := fmt.Sprintf("%s-%d", definitions.CnfCertPodNamePrefix, cnfRunPodId)
168+
cnfRunPodID++
169+
podName := fmt.Sprintf("%s-%d", definitions.CnfCertPodNamePrefix, cnfRunPodID)
173170

174171
// Store the new run & associated CNF Cert pod name
175172
certificationRuns[reqCertificationRun] = podName
176173

177174
logrus.Infof("Running CNF Certification Suite container (job id=%d) with labels %q, log level %q and timeout: %q",
178-
cnfRunPodId, cnfrun.Spec.LabelsFilter, cnfrun.Spec.LogLevel, cnfrun.Spec.TimeOut)
175+
cnfRunPodID, cnfrun.Spec.LabelsFilter, cnfrun.Spec.LogLevel, cnfrun.Spec.TimeOut)
179176

180177
// Launch the pod with the CNF Cert Suite container plus the sidecar container to fetch the results.
181178
r.updateJobStatus(&cnfrun, "CreatingCertSuiteJob")
@@ -197,8 +194,7 @@ func (r *CnfCertificationSuiteRunReconciler) Reconcile(ctx context.Context, req
197194
return ctrl.Result{}, nil
198195
}
199196
r.updateJobStatus(&cnfrun, "RunningCertSuite")
200-
logrus.Info("Runnning CNF Cert job")
201-
197+
logrus.Info("Running CNF Cert job")
202198
go r.verifyCnfCertSuiteOutput(ctx, req.NamespacedName.Namespace, cnfCertJobPod, &cnfrun)
203199
return ctrl.Result{}, nil
204200
}

‎controllers/suite_test.go

+2-2
Original file line numberDiff line numberDiff line change
@@ -20,8 +20,8 @@ import (
2020
"path/filepath"
2121
"testing"
2222

23-
. "github.com/onsi/ginkgo/v2"
24-
. "github.com/onsi/gomega"
23+
. "github.com/onsi/ginkgo/v2" //nolint:revive
24+
. "github.com/onsi/gomega" //nolint:revive
2525

2626
"k8s.io/client-go/kubernetes/scheme"
2727
"k8s.io/client-go/rest"

‎go.mod

+1-1
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@ require (
6565
k8s.io/klog/v2 v2.80.1 // indirect
6666
k8s.io/kube-openapi v0.0.0-20221012153701-172d655c2280 // indirect
6767
k8s.io/utils v0.0.0-20221128185143-99ec85e7a448 // indirect
68-
sigs.k8s.io/json v0.0.0-20220713155537-f223a00ba0e2 // indirect
68+
sigs.k8s.io/json v0.0.0-20220713155537-f223a00ba0e2 // indirect,nollint:typos
6969
sigs.k8s.io/structured-merge-diff/v4 v4.2.3 // indirect
7070
sigs.k8s.io/yaml v1.3.0 // indirect
7171
)

‎hack/deleteall.sh

+3-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
1+
#!/bin/bash
2+
13
deleteAll() {
24
res=$1
3-
for name in `oc get $res -n cnf-certification-operator -o json | jq -r '.items[] | .metadata.name' | sort -r` ; do oc delete $res -n cnf-certification-operator $name ; done
5+
for name in $(oc get "$res" -n cnf-certification-operator -o json | jq -r '.items[] | .metadata.name' | sort -r) ; do oc delete "$res" -n cnf-certification-operator "$name" ; done
46
}
57

68
deleteAll cnfcertificationsuiteruns

‎main.go

+23-20
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ import (
3131
ctrl "sigs.k8s.io/controller-runtime"
3232
"sigs.k8s.io/controller-runtime/pkg/healthz"
3333
"sigs.k8s.io/controller-runtime/pkg/log/zap"
34+
"sigs.k8s.io/controller-runtime/pkg/manager"
3435

3536
cnfcertificationsv1alpha1 "github.com/greyerof/cnf-certification-operator/api/v1alpha1"
3637
"github.com/greyerof/cnf-certification-operator/controllers"
@@ -63,18 +64,29 @@ func getWatchNamespace() (string, error) {
6364
return ns, nil
6465
}
6566

67+
func defineFlags(metricsAddr, probeAddr *string, enableLeaderElection *bool) {
68+
flag.StringVar(metricsAddr, "metrics-bind-address", ":8080", "The address the metric endpoint binds to.")
69+
flag.StringVar(probeAddr, "health-probe-bind-address", ":8081", "The address the probe endpoint binds to.")
70+
flag.BoolVar(enableLeaderElection, "leader-elect", false, "Enable leader election for controller manager. "+
71+
"Enabling this will ensure there is only one active controller manager.")
72+
}
73+
74+
func setUpChecks(mgr manager.Manager) {
75+
if err := mgr.AddHealthzCheck("healthz", healthz.Ping); err != nil {
76+
setupLog.Error(err, "unable to set up health check")
77+
os.Exit(1)
78+
}
79+
if err := mgr.AddReadyzCheck("readyz", healthz.Ping); err != nil {
80+
setupLog.Error(err, "unable to set up ready check")
81+
os.Exit(1)
82+
}
83+
}
84+
6685
func main() {
67-
var metricsAddr string
86+
var metricsAddr, probeAddr string
6887
var enableLeaderElection bool
69-
var probeAddr string
70-
flag.StringVar(&metricsAddr, "metrics-bind-address", ":8080", "The address the metric endpoint binds to.")
71-
flag.StringVar(&probeAddr, "health-probe-bind-address", ":8081", "The address the probe endpoint binds to.")
72-
flag.BoolVar(&enableLeaderElection, "leader-elect", false,
73-
"Enable leader election for controller manager. "+
74-
"Enabling this will ensure there is only one active controller manager.")
75-
opts := zap.Options{
76-
Development: true,
77-
}
88+
defineFlags(&metricsAddr, &probeAddr, &enableLeaderElection)
89+
opts := zap.Options{Development: true}
7890
opts.BindFlags(flag.CommandLine)
7991
flag.Parse()
8092

@@ -85,7 +97,6 @@ func main() {
8597
setupLog.Error(err, "unable to get WatchNamespace, "+
8698
"the manager will watch and manage resources in all namespaces")
8799
}
88-
89100
mgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), ctrl.Options{
90101
Scheme: scheme,
91102
MetricsBindAddress: metricsAddr,
@@ -120,15 +131,7 @@ func main() {
120131
}
121132
//+kubebuilder:scaffold:builder
122133

123-
if err := mgr.AddHealthzCheck("healthz", healthz.Ping); err != nil {
124-
setupLog.Error(err, "unable to set up health check")
125-
os.Exit(1)
126-
}
127-
if err := mgr.AddReadyzCheck("readyz", healthz.Ping); err != nil {
128-
setupLog.Error(err, "unable to set up ready check")
129-
os.Exit(1)
130-
}
131-
134+
setUpChecks(mgr)
132135
setupLog.Info("starting manager")
133136
if err := mgr.Start(ctrl.SetupSignalHandler()); err != nil {
134137
setupLog.Error(err, "problem running manager")

0 commit comments

Comments
 (0)
Please sign in to comment.