Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

🌱 Enable additional linters #72

Merged
merged 1 commit into from
Mar 6, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/golangci-lint.yml
Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,5 @@ jobs:
- name: golangci-lint
uses: golangci/golangci-lint-action@v3
with:
version: v1.50.1
version: v1.51.1
args: --timeout 15m
112 changes: 112 additions & 0 deletions .golangci.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@


linters:
disable-all: true
# Enable specific linter
# https://golangci-lint.run/usage/linters/#enabled-by-default-linters
enable:
# Default linters
- errcheck
- gosimple
- govet
- ineffassign
- staticcheck
- typecheck
- unused
# Additional linters
- asciicheck
- bidichk
- bodyclose
- contextcheck
# - cyclop
- dogsled
# - dupl
- durationcheck
- errname
# - errorlint
- exhaustive
# - exportloopref
- forcetypeassert
# - funlen
# - gochecknoglobals
# - gocognit
- goconst
- gocritic
- gocyclo
- godot
# - goerr113
- gofmt
- goheader
- goimports
- goprintffuncname
# - gosec
- importas
- makezero
- misspell
- nakedret
- nestif
- nilerr
- nilnil
- nlreturn
- noctx
- nolintlint
- prealloc
- predeclared
# - revive
- tagliatelle
- tenv
- unconvert
- unparam
- whitespace
# - wrapcheck
- wsl
linters-settings:
goheader:
values:
regexp:
license-year: (202[0-9]|20[3-9][0-9])
template: |-
Copyright {{license-year}} The Kubernetes Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
nlreturn:
block-size: 2
revive:
confidence: 0
rules:
- name: exported
severity: warning
disabled: false
arguments:
- "checkPrivateReceivers"
- "disableStutteringCheck"
stylecheck:
# https://staticcheck.io/docs/options#checks
checks: ["all", "-ST1000"]
dot-import-whitelist:
- "github.com/onsi/gomega"
issues:
exclude:
# Not all platforms are supported by this operator, those which aren't
# supported will be caught by the default case in the switches.
- "missing cases in switch of type v1.PlatformType: (\\.*)"
exclude-use-default: false
exclude-rules:
# Exclude some linters from running on tests files.
- path: _test\.go
linters:
- gocyclo
- dupl
- gosec
- gochecknoglobals
- goerr113
3 changes: 3 additions & 0 deletions controllers/alias.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
/*
Copyright 2023 The Kubernetes Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
Expand Down
6 changes: 6 additions & 0 deletions internal/controllers/client_proxy.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ func (k *controllerProxy) GetResourceNames(groupVersion, kind string, options []
}

var comps []string

for _, item := range objList.Items {
name := item.GetName()

Expand Down Expand Up @@ -93,6 +94,7 @@ func (k *controllerProxy) ListResources(labels map[string]string, namespaces ...
}

var ret []unstructured.Unstructured

for _, resourceGroup := range resourceList {
for _, resourceKind := range resourceGroup.APIResources {
if resourceKind.Namespaced {
Expand All @@ -101,7 +103,9 @@ func (k *controllerProxy) ListResources(labels map[string]string, namespaces ...
if err != nil {
return nil, err
}

klog.V(3).InfoS("listed", "kind", resourceKind.Kind, "count", len(objList.Items))

ret = append(ret, objList.Items...)
}
} else {
Expand All @@ -114,6 +118,7 @@ func (k *controllerProxy) ListResources(labels map[string]string, namespaces ...
}
}
}

return ret, nil
}

Expand All @@ -128,5 +133,6 @@ func listObjByGVK(c client.Client, groupVersion, kind string, options []client.L
return nil, errors.Wrapf(err, "failed to list objects for the %q GroupVersionKind", objList.GroupVersionKind())
}
}

return objList, nil
}
34 changes: 33 additions & 1 deletion internal/controllers/component_customizer.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ var (
func customizeObjectsFn(provider genericprovider.GenericProvider) func(objs []unstructured.Unstructured) ([]unstructured.Unstructured, error) {
return func(objs []unstructured.Unstructured) ([]unstructured.Unstructured, error) {
results := []unstructured.Unstructured{}

for i := range objs {
o := objs[i]

Expand All @@ -73,15 +74,19 @@ func customizeObjectsFn(provider genericprovider.GenericProvider) func(objs []un
if err := scheme.Scheme.Convert(&o, d, nil); err != nil {
return nil, err
}

if provider.GetSpec().Deployment != nil {
customizeDeployment(provider.GetSpec(), d)
}

if err := scheme.Scheme.Convert(d, &o, nil); err != nil {
return nil, err
}
}

results = append(results, o)
}

return results, nil
}
}
Expand All @@ -90,15 +95,19 @@ func customizeObjectsFn(provider genericprovider.GenericProvider) func(objs []un
func customizeDeployment(pSpec operatorv1.ProviderSpec, d *appsv1.Deployment) {
if pSpec.Deployment != nil {
dSpec := pSpec.Deployment

if dSpec.Replicas != nil {
d.Spec.Replicas = pointer.Int32Ptr(int32(*dSpec.Replicas))
}

if dSpec.Affinity != nil {
d.Spec.Template.Spec.Affinity = dSpec.Affinity
}

if dSpec.NodeSelector != nil {
d.Spec.Template.Spec.NodeSelector = dSpec.NodeSelector
}

if dSpec.Tolerations != nil {
d.Spec.Template.Spec.Tolerations = dSpec.Tolerations
}
Expand All @@ -107,6 +116,7 @@ func customizeDeployment(pSpec operatorv1.ProviderSpec, d *appsv1.Deployment) {
customizeContainer(pc, d)
}
}

// run the customizeManager last so it overrides anything in the deploymentSpec.
if pSpec.Manager != nil {
for ic, c := range d.Spec.Template.Spec.Containers {
Expand All @@ -126,6 +136,7 @@ func customizeManager(mSpec *operatorv1.ManagerSpec, c *corev1.Container) {
c.Args = setArgs(c.Args, "--"+strings.ToLower(k)+"-concurrency", fmt.Sprint(v))
}
}

if mSpec.MaxConcurrentReconciles != 0 {
c.Args = setArgs(c.Args, "--max-concurrent-reconciles", fmt.Sprint(mSpec.MaxConcurrentReconciles))
}
Expand All @@ -138,14 +149,16 @@ func customizeManager(mSpec *operatorv1.ManagerSpec, c *corev1.Container) {
c.Args = setArgs(c.Args, "--namespace", mSpec.CacheNamespace)
}

//TODO can't find an arg for GracefulShutdownTimeout
// TODO can't find an arg for GracefulShutdownTimeout

if mSpec.Health.HealthProbeBindAddress != "" {
c.Args = setArgs(c.Args, "--health-addr", mSpec.Health.HealthProbeBindAddress)
}

if mSpec.Health.LivenessEndpointName != "" && c.LivenessProbe != nil && c.LivenessProbe.HTTPGet != nil {
c.LivenessProbe.HTTPGet.Path = "/" + mSpec.Health.LivenessEndpointName
}

if mSpec.Health.ReadinessEndpointName != "" && c.ReadinessProbe != nil && c.ReadinessProbe.HTTPGet != nil {
c.ReadinessProbe.HTTPGet.Path = "/" + mSpec.Health.ReadinessEndpointName
}
Expand All @@ -163,9 +176,11 @@ func customizeManager(mSpec *operatorv1.ManagerSpec, c *corev1.Container) {
if mSpec.Webhook.Host != "" {
c.Args = setArgs(c.Args, "--webhook-host", mSpec.Webhook.Host)
}

if mSpec.Webhook.Port != nil {
c.Args = setArgs(c.Args, "--webhook-port", fmt.Sprint(*mSpec.Webhook.Port))
}

if mSpec.Webhook.CertDir != "" {
c.Args = setArgs(c.Args, "--webhook-cert-dir", mSpec.Webhook.CertDir)
}
Expand All @@ -188,9 +203,11 @@ func customizeManager(mSpec *operatorv1.ManagerSpec, c *corev1.Container) {

if len(mSpec.FeatureGates) > 0 {
fgValue := []string{}

for fg, val := range mSpec.FeatureGates {
fgValue = append(fgValue, fg+"="+bool2Str[val])
}

sort.Strings(fgValue)
c.Args = setArgs(c.Args, "--feature-gates", strings.Join(fgValue, ","))
}
Expand All @@ -208,20 +225,25 @@ func customizeContainer(cSpec operatorv1.ContainerSpec, d *appsv1.Deployment) {
c.Args = setArgs(c.Args, an, av)
}
}

for _, se := range cSpec.Env {
c.Env = removeEnv(c.Env, se.Name)
c.Env = append(c.Env, se)
}

if cSpec.Resources != nil {
c.Resources = *cSpec.Resources
}

if cSpec.Image != nil && cSpec.Image.Name != "" && cSpec.Image.Repository != "" {
c.Image = imageMetaToURL(cSpec.Image)
}

if cSpec.Command != nil {
c.Command = cSpec.Command
}
}

d.Spec.Template.Spec.Containers[j] = c
}
}
Expand All @@ -231,6 +253,7 @@ func setArgs(args []string, name, value string) []string {
for i, a := range args {
if strings.HasPrefix(a, name+"=") {
args[i] = name + "=" + value

return args
}
}
Expand All @@ -243,6 +266,7 @@ func removeEnv(envs []corev1.EnvVar, name string) []corev1.EnvVar {
for i, a := range envs {
if a.Name == name {
copy(envs[i:], envs[i+1:])

return envs[:len(envs)-1]
}
}
Expand All @@ -256,6 +280,7 @@ func imageMetaToURL(im *operatorv1.ImageMeta) string {
if im.Tag != "" {
tag = im.Tag
}

return strings.Join([]string{im.Repository, im.Name}, "/") + ":" + tag
}

Expand All @@ -267,18 +292,25 @@ func leaderElectionArgs(lec *configv1alpha1.LeaderElectionConfiguration, args []
if lec.ResourceName != "" && lec.ResourceNamespace != "" {
args = setArgs(args, "--leader-election-id", lec.ResourceNamespace+"/"+lec.ResourceName)
}

leaseDuration := int(lec.LeaseDuration.Duration.Round(time.Second).Seconds())

if leaseDuration > 0 {
args = setArgs(args, "--leader-elect-lease-duration", fmt.Sprintf("%ds", leaseDuration))
}

renewDuration := int(lec.RenewDeadline.Duration.Round(time.Second).Seconds())

if renewDuration > 0 {
args = setArgs(args, "--leader-elect-renew-deadline", fmt.Sprintf("%ds", renewDuration))
}

retryDuration := int(lec.RetryPeriod.Duration.Round(time.Second).Seconds())

if retryDuration > 0 {
args = setArgs(args, "--leader-elect-retry-period", fmt.Sprintf("%ds", retryDuration))
}
}

return args
}
Loading