Skip to content

Commit

Permalink
chore(controller): fix linter issues
Browse files Browse the repository at this point in the history
Signed-off-by: Oliver Bähler <oliverbaehler@hotmail.com>
  • Loading branch information
oliverbaehler committed Feb 20, 2024
1 parent 65a7439 commit acd5eb3
Show file tree
Hide file tree
Showing 48 changed files with 129 additions and 82 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/diff.yml
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ jobs:
fetch-depth: 0
- uses: actions/setup-go@0c52d547c9bc32b1aa3301fd7a9cb496313a4491 # v5.0.0
with:
go-version: '1.20'
go-version: '1.21'
- run: make installer
- name: Checking if YAML installer file is not aligned
run: if [[ $(git diff | wc -l) -gt 0 ]]; then echo ">>> Untracked generated files have not been committed" && git --no-pager diff && exit 1; fi
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/e2e.yml
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ jobs:
fetch-depth: 0
- uses: actions/setup-go@0c52d547c9bc32b1aa3301fd7a9cb496313a4491 # v5.0.0
with:
go-version: '1.20'
go-version: '1.21'
- run: make manifests
- name: Checking if manifests are disaligned
run: test -z "$(git diff 2> /dev/null)"
Expand Down
5 changes: 4 additions & 1 deletion .github/workflows/lint.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,12 @@ jobs:
runs-on: ubuntu-20.04
steps:
- uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1
- uses: actions/setup-go@0c52d547c9bc32b1aa3301fd7a9cb496313a4491 # v5.0.0
with:
go-version: '1.21'
- name: Run golangci-lint
uses: golangci/golangci-lint-action@3cfe3a4abbb849e10058ce4af15d205b6da42804 # v4.0.0
with:
version: v1.51.2
version: v1.56.2
only-new-issues: false
args: --timeout 5m --config .golangci.yml
21 changes: 19 additions & 2 deletions .golangci.yml
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@

linters-settings:
govet:
check-shadowing: true
Expand All @@ -19,10 +20,21 @@ linters-settings:
template: |-
Copyright 2020-2023 Project Capsule Authors.
SPDX-License-Identifier: Apache-2.0
gofumpt:
module-path: github.com/projectcapsule/capsule
extra-rules: false
inamedparam:
# Skips check for interface methods with only a single parameter.
# Default: false
skip-single-param: true
nakedret:
# Make an issue if func has more lines of code than this setting, and it has naked returns.
max-func-lines: 50
linters:
enable-all: true
disable:
- depguard
- perfsprint
- funlen
- gochecknoinits
- lll
Expand All @@ -48,8 +60,13 @@ linters:
- nonamedreturns

service:
golangci-lint-version: 1.51.2
golangci-lint-version: 1.56.x

run:
timeout: 3m
go: '1.21'
skip-files:
- "zz_.*\\.go$"
- ".+\\.generated.go"
- ".+_test.go"
- ".+_test_.+.go"
5 changes: 3 additions & 2 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -242,7 +242,7 @@ apidocs-gen: ## Download crdoc locally if necessary.
$(call go-install-tool,$(APIDOCS_GEN),fybrik.io/crdoc@$(APIDOCS_GEN_VERSION))

GINKGO := $(shell pwd)/bin/ginkgo
GINGKO_VERSION := v2.13.2
GINGKO_VERSION := v2.15.0
ginkgo: ## Download ginkgo locally if necessary.
$(call go-install-tool,$(GINKGO),github.com/onsi/ginkgo/v2/ginkgo@$(GINGKO_VERSION))

Expand Down Expand Up @@ -304,8 +304,9 @@ goimports:
goimports -w -l -local "github.com/projectcapsule/capsule" .

GOLANGCI_LINT = $(shell pwd)/bin/golangci-lint
GOLANGCI_LINT_VERSION = v1.56.2
golangci-lint: ## Download golangci-lint locally if necessary.
$(call go-install-tool,$(GOLANGCI_LINT),github.com/golangci/golangci-lint/cmd/golangci-lint@v1.51.2)
$(call go-install-tool,$(GOLANGCI_LINT),github.com/golangci/golangci-lint/cmd/golangci-lint@$(GOLANGCI_LINT_VERSION))

# Linting code as PR is expecting
.PHONY: golint
Expand Down
1 change: 1 addition & 0 deletions controllers/rbac/manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ type Manager struct {
Configuration configuration.Configuration
}

//nolint:revive
func (r *Manager) SetupWithManager(ctx context.Context, mgr ctrl.Manager, configurationName string) (err error) {
namesPredicate := utils.NamesMatchingPredicate(ProvisionerRoleName, DeleterRoleName)

Expand Down
7 changes: 6 additions & 1 deletion controllers/resources/processor.go
Original file line number Diff line number Diff line change
Expand Up @@ -264,23 +264,28 @@ func (r *Processor) createOrUpdate(ctx context.Context, obj *unstructured.Unstru
_, err = controllerutil.CreateOrUpdate(ctx, r.client, actual, func() error {
UID := actual.GetUID()
rv := actual.GetResourceVersion()

actual.SetUnstructuredContent(desired.Object)

combinedLabels := obj.GetLabels()
if combinedLabels == nil {
combinedLabels = make(map[string]string)
}

for key, value := range labels {
combinedLabels[key] = value
}

actual.SetLabels(combinedLabels)

combinedAnnotations := obj.GetAnnotations()
if combinedAnnotations == nil {
combinedAnnotations = make(map[string]string)
}

for key, value := range annotations {
combinedAnnotations[key] = value
}

actual.SetAnnotations(combinedAnnotations)
actual.SetResourceVersion(rv)
actual.SetUID(UID)
Expand Down
1 change: 1 addition & 0 deletions controllers/tenant/limitranges.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ func (r *Manager) syncLimitRange(ctx context.Context, tenant *capsulev1beta2.Ten
if labels == nil {
labels = map[string]string{}
}

labels[tenantLabel] = tenant.Name
labels[limitRangeLabel] = strconv.Itoa(i)

Expand Down
1 change: 1 addition & 0 deletions controllers/tenant/manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ func (r *Manager) SetupWithManager(mgr ctrl.Manager) error {
Complete(r)
}

//nolint:nakedret
func (r Manager) Reconcile(ctx context.Context, request ctrl.Request) (result ctrl.Result, err error) {
r.Log = r.Log.WithValues("Request.Name", request.Name)
// Fetch the Tenant instance
Expand Down
7 changes: 5 additions & 2 deletions controllers/tenant/namespaces.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ func (r *Manager) syncNamespaces(ctx context.Context, tenant *capsulev1beta2.Ten
return
}

//nolint:gocognit
//nolint:gocognit,nakedret
func (r *Manager) syncNamespaceMetadata(ctx context.Context, namespace string, tnt *capsulev1beta2.Tenant) (err error) {
var res controllerutil.OperationResult

Expand Down Expand Up @@ -81,6 +81,7 @@ func (r *Manager) syncNamespaceMetadata(ctx context.Context, namespace string, t
if len(tnt.Spec.IngressOptions.AllowedClasses.Exact) > 0 {
annotations[AvailableIngressClassesAnnotation] = strings.Join(tnt.Spec.IngressOptions.AllowedClasses.Exact, ",")
}

if len(tnt.Spec.IngressOptions.AllowedClasses.Regex) > 0 {
annotations[AvailableIngressClassesRegexpAnnotation] = tnt.Spec.IngressOptions.AllowedClasses.Regex
}
Expand All @@ -90,6 +91,7 @@ func (r *Manager) syncNamespaceMetadata(ctx context.Context, namespace string, t
if len(tnt.Spec.StorageClasses.Exact) > 0 {
annotations[AvailableStorageClassesAnnotation] = strings.Join(tnt.Spec.StorageClasses.Exact, ",")
}

if len(tnt.Spec.StorageClasses.Regex) > 0 {
annotations[AvailableStorageClassesRegexpAnnotation] = tnt.Spec.StorageClasses.Regex
}
Expand All @@ -99,6 +101,7 @@ func (r *Manager) syncNamespaceMetadata(ctx context.Context, namespace string, t
if len(tnt.Spec.ContainerRegistries.Exact) > 0 {
annotations[AllowedRegistriesAnnotation] = strings.Join(tnt.Spec.ContainerRegistries.Exact, ",")
}

if len(tnt.Spec.ContainerRegistries.Regex) > 0 {
annotations[AllowedRegistriesRegexpAnnotation] = tnt.Spec.ContainerRegistries.Regex
}
Expand Down Expand Up @@ -165,10 +168,10 @@ func (r *Manager) ensureNamespaceCount(ctx context.Context, tenant *capsulev1bet
func (r *Manager) collectNamespaces(ctx context.Context, tenant *capsulev1beta2.Tenant) error {
return retry.RetryOnConflict(retry.DefaultBackoff, func() (err error) {
list := &corev1.NamespaceList{}

err = r.Client.List(ctx, list, client.MatchingFieldsSelector{
Selector: fields.OneTermEqualSelector(".metadata.ownerReferences[*].capsule", tenant.GetName()),
})

if err != nil {
return
}
Expand Down
12 changes: 11 additions & 1 deletion controllers/tenant/resourcequotas.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,8 @@ import (
// the mutateFn along with the CreateOrUpdate to don't perform the update since resources are identical.
//
// In case of Namespace-scoped Resource Budget, we're just replicating the resources across all registered Namespaces.

//nolint:nakedret
func (r *Manager) syncResourceQuotas(ctx context.Context, tenant *capsulev1beta2.Tenant) (err error) { //nolint:gocognit
// getting ResourceQuota labels for the mutateFn
var tenantLabel, typeLabel string
Expand Down Expand Up @@ -65,11 +67,13 @@ func (r *Manager) syncResourceQuotas(ctx context.Context, tenant *capsulev1beta2
// Calculating the Resource Budget at Tenant scope just if this is put in place.
// Requirement to list ResourceQuota of the current Tenant
var tntRequirement *labels.Requirement

if tntRequirement, scopeErr = labels.NewRequirement(tenantLabel, selection.Equals, []string{tenant.Name}); scopeErr != nil {
r.Log.Error(scopeErr, "Cannot build ResourceQuota Tenant requirement")
}
// Requirement to list ResourceQuota for the current index
var indexRequirement *labels.Requirement

if indexRequirement, scopeErr = labels.NewRequirement(typeLabel, selection.Equals, []string{strconv.Itoa(index)}); scopeErr != nil {
r.Log.Error(scopeErr, "Cannot build ResourceQuota index requirement")
}
Expand All @@ -80,7 +84,7 @@ func (r *Manager) syncResourceQuotas(ctx context.Context, tenant *capsulev1beta2
if scopeErr = r.List(ctx, list, &client.ListOptions{LabelSelector: labels.NewSelector().Add(*tntRequirement).Add(*indexRequirement)}); scopeErr != nil {
r.Log.Error(scopeErr, "Cannot list ResourceQuota", "tenantFilter", tntRequirement.String(), "indexFilter", indexRequirement.String())

return
return scopeErr
}
// Iterating over all the options declared for the ResourceQuota,
// summing all the used quota across different Namespaces to determinate
Expand All @@ -95,6 +99,7 @@ func (r *Manager) syncResourceQuotas(ctx context.Context, tenant *capsulev1beta2
for _, item := range list.Items {
quantity.Add(item.Status.Used[name])
}

r.Log.Info("Computed " + name.String() + " quota for the whole Tenant is " + quantity.String())

switch quantity.Cmp(resourceQuota.Hard[name]) {
Expand Down Expand Up @@ -124,6 +129,7 @@ func (r *Manager) syncResourceQuotas(ctx context.Context, tenant *capsulev1beta2
if list.Items[item].Spec.Hard == nil {
list.Items[item].Spec.Hard = map[corev1.ResourceName]resource.Quantity{}
}

list.Items[item].Spec.Hard[name] = resourceQuota.Hard[name]

for k := range list.Items[item].Spec.Hard {
Expand All @@ -133,6 +139,7 @@ func (r *Manager) syncResourceQuotas(ctx context.Context, tenant *capsulev1beta2
}
}
}

if scopeErr = r.resourceQuotasUpdate(ctx, name, quantity, toKeep, resourceQuota.Hard[name], list.Items...); scopeErr != nil {
r.Log.Error(scopeErr, "cannot proceed with outer ResourceQuota")

Expand Down Expand Up @@ -168,6 +175,7 @@ func (r *Manager) syncResourceQuotas(ctx context.Context, tenant *capsulev1beta2
return group.Wait()
}

//nolint:nakedret
func (r *Manager) syncResourceQuota(ctx context.Context, tenant *capsulev1beta2.Tenant, namespace string, keys []string) (err error) {
// getting ResourceQuota labels for the mutateFn
var tenantLabel, typeLabel string
Expand Down Expand Up @@ -207,6 +215,7 @@ func (r *Manager) syncResourceQuota(ctx context.Context, tenant *capsulev1beta2.
target.SetLabels(targetLabels)
target.Spec.Scopes = resQuota.Scopes
target.Spec.ScopeSelector = resQuota.ScopeSelector

// In case of Namespace scope for the ResourceQuota we can easily apply the bare specification
if tenant.Spec.ResourceQuota.Scope == api.ResourceQuotaScopeNamespace {
target.Spec.Hard = resQuota.Hard
Expand Down Expand Up @@ -278,6 +287,7 @@ func (r *Manager) resourceQuotasUpdate(ctx context.Context, resourceName corev1.
if actualKey, keyErr := capsulev1beta2.UsedQuotaFor(resourceName); keyErr == nil {
found.Annotations[actualKey] = actual.String()
}

if limitKey, keyErr := capsulev1beta2.HardQuotaFor(resourceName); keyErr == nil {
found.Annotations[limitKey] = limit.String()
}
Expand Down
1 change: 1 addition & 0 deletions controllers/tenant/rolebindings.go
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,7 @@ func (r *Manager) syncRoleBindings(ctx context.Context, tenant *capsulev1beta2.T
return group.Wait()
}

//nolint:nakedret
func (r *Manager) syncAdditionalRoleBinding(ctx context.Context, tenant *capsulev1beta2.Tenant, ns string, keys []string, hashFn func(binding api.AdditionalRoleBindingsSpec) string) (err error) {
var tenantLabel, roleBindingLabel string

Expand Down
5 changes: 5 additions & 0 deletions controllers/tls/manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -219,6 +219,7 @@ func (r Reconciler) shouldUpdateCertificate(secret *corev1.Secret) bool {
func (r *Reconciler) updateTenantCustomResourceDefinition(ctx context.Context, name string, caBundle []byte) error {
return retry.RetryOnConflict(retry.DefaultBackoff, func() (err error) {
crd := &apiextensionsv1.CustomResourceDefinition{}

err = r.Get(ctx, types.NamespacedName{Name: name}, crd)
if err != nil {
r.Log.Error(err, "cannot retrieve CustomResourceDefinition")
Expand Down Expand Up @@ -254,12 +255,14 @@ func (r *Reconciler) updateTenantCustomResourceDefinition(ctx context.Context, n
func (r Reconciler) updateValidatingWebhookConfiguration(ctx context.Context, caBundle []byte) error {
return retry.RetryOnConflict(retry.DefaultBackoff, func() (err error) {
vw := &admissionregistrationv1.ValidatingWebhookConfiguration{}

err = r.Get(ctx, types.NamespacedName{Name: r.Configuration.ValidatingWebhookConfigurationName()}, vw)
if err != nil {
r.Log.Error(err, "cannot retrieve ValidatingWebhookConfiguration")

return err
}

for i, w := range vw.Webhooks {
// Updating CABundle only in case of an internal service reference
if w.ClientConfig.Service != nil {
Expand All @@ -275,12 +278,14 @@ func (r Reconciler) updateValidatingWebhookConfiguration(ctx context.Context, ca
func (r Reconciler) updateMutatingWebhookConfiguration(ctx context.Context, caBundle []byte) error {
return retry.RetryOnConflict(retry.DefaultBackoff, func() (err error) {
mw := &admissionregistrationv1.MutatingWebhookConfiguration{}

err = r.Get(ctx, types.NamespacedName{Name: r.Configuration.MutatingWebhookConfigurationName()}, mw)
if err != nil {
r.Log.Error(err, "cannot retrieve MutatingWebhookConfiguration")

return err
}

for i, w := range mw.Webhooks {
// Updating CABundle only in case of an internal service reference
if w.ClientConfig.Service != nil {
Expand Down
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
module github.com/projectcapsule/capsule

go 1.20
go 1.21

require (
github.com/go-logr/logr v1.4.1
Expand Down
2 changes: 1 addition & 1 deletion pkg/api/forbidden_list.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ func NewForbiddenError(key string, forbiddenSpec ForbiddenListSpec) error {
}
}

//nolint:predeclared
//nolint:predeclared,revive
func (f *ForbiddenError) appendForbiddenError() (append string) {
append += "Forbidden are "
if len(f.spec.Exact) > 0 {
Expand Down
8 changes: 4 additions & 4 deletions pkg/cert/ca.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,8 @@ type CapsuleCA struct {

func (c CapsuleCA) CACertificatePem() (b *bytes.Buffer, err error) {
var crtBytes []byte
crtBytes, err = x509.CreateCertificate(rand.Reader, c.certificate, c.certificate, &c.key.PublicKey, c.key)

crtBytes, err = x509.CreateCertificate(rand.Reader, c.certificate, c.certificate, &c.key.PublicKey, c.key)
if err != nil {
return
}
Expand Down Expand Up @@ -147,8 +147,8 @@ func NewCertificateAuthorityFromBytes(certBytes, keyBytes []byte) (*CapsuleCA, e
//nolint:nakedret
func (c *CapsuleCA) GenerateCertificate(opts CertificateOptions) (certificatePem *bytes.Buffer, certificateKey *bytes.Buffer, err error) {
var certPrivKey *rsa.PrivateKey
certPrivKey, err = rsa.GenerateKey(rand.Reader, 4096)

certPrivKey, err = rsa.GenerateKey(rand.Reader, 4096)
if err != nil {
return nil, nil, err
}
Expand All @@ -172,18 +172,18 @@ func (c *CapsuleCA) GenerateCertificate(opts CertificateOptions) (certificatePem
}

var certBytes []byte
certBytes, err = x509.CreateCertificate(rand.Reader, cert, c.certificate, &certPrivKey.PublicKey, c.key)

certBytes, err = x509.CreateCertificate(rand.Reader, cert, c.certificate, &certPrivKey.PublicKey, c.key)
if err != nil {
return nil, nil, err
}

certificatePem = new(bytes.Buffer)

err = pem.Encode(certificatePem, &pem.Block{
Type: "CERTIFICATE",
Bytes: certBytes,
})

if err != nil {
return
}
Expand Down
4 changes: 2 additions & 2 deletions pkg/webhook/defaults/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,8 @@ func (h *handler) OnCreate(client client.Client, decoder *admission.Decoder, rec
}
}

func (h *handler) OnDelete(client client.Client, decoder *admission.Decoder, recorder record.EventRecorder) capsulewebhook.Func {
return func(ctx context.Context, req admission.Request) *admission.Response {
func (h *handler) OnDelete(client.Client, *admission.Decoder, record.EventRecorder) capsulewebhook.Func {
return func(context.Context, admission.Request) *admission.Response {
return nil
}
}
Expand Down
2 changes: 1 addition & 1 deletion pkg/webhook/ingress/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ func (i ingressClassNotValidError) Error() string {
return utils.DefaultAllowedValuesErrorMessage(i.spec, err)
}

//nolint:predeclared
//nolint:predeclared,revive
func appendHostnameError(spec api.AllowedListSpec) (append string) {
if len(spec.Exact) > 0 {
append = fmt.Sprintf(", specify one of the following (%s)", strings.Join(spec.Exact, ", "))
Expand Down
Loading

0 comments on commit acd5eb3

Please sign in to comment.