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 more linters #2545

Merged
merged 10 commits into from
Sep 17, 2024
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
7 changes: 7 additions & 0 deletions .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -53,14 +53,19 @@ linters:
enable:
- asasalint
- asciicheck
- bidichk
- copyloopvar
- dupword
- durationcheck
- errcheck
- errchkjson
- errname
- errorlint
- fatcontext
- ginkgolinter
- gocheckcompilerdirectives
- gochecksumtype
- gocritic
- gocyclo
- godot
- gofmt
Expand All @@ -76,6 +81,7 @@ linters:
- loggercheck
- makezero
- misspell
- musttag
- nilerr
- noctx
- nolintlint
Expand All @@ -86,6 +92,7 @@ linters:
- spancheck
- staticcheck
- stylecheck
- tagalign
- tenv
- thelper
- tparallel
Expand Down
2 changes: 1 addition & 1 deletion internal/mode/provisioner/manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@
statusUpdater,
mgr.GetClient(),
embeddedfiles.StaticModeDeploymentYAML,
func() metav1.Time { return metav1.Now() },
metav1.Now,

Check warning on line 136 in internal/mode/provisioner/manager.go

View check run for this annotation

Codecov / codecov/patch

internal/mode/provisioner/manager.go#L136

Added line #L136 was not covered by tests
)

eventLoop := events.NewEventLoop(
Expand Down
3 changes: 1 addition & 2 deletions internal/mode/static/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -471,8 +471,7 @@ func getGatewayAddresses(
}

var addresses, hostnames []string
switch gwSvc.Spec.Type {
case v1.ServiceTypeLoadBalancer:
if gwSvc.Spec.Type == v1.ServiceTypeLoadBalancer {
for _, ingress := range gwSvc.Status.LoadBalancer.Ingress {
if ingress.IP != "" {
addresses = append(addresses, ingress.IP)
Expand Down
16 changes: 9 additions & 7 deletions internal/mode/static/manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,8 @@
Namespace: cfg.GatewayPodConfig.Namespace,
Name: cfg.ConfigName,
}
if err := registerControllers(ctx, cfg, mgr, recorder, logLevelSetter, eventCh, controlConfigNSName); err != nil {
kate-osborn marked this conversation as resolved.
Show resolved Hide resolved
err = registerControllers(ctx, cfg, mgr, recorder, logLevelSetter, eventCh, controlConfigNSName)
if err != nil {

Check warning on line 111 in internal/mode/static/manager.go

View check run for this annotation

Codecov / codecov/patch

internal/mode/static/manager.go#L110-L111

Added lines #L110 - L111 were not covered by tests
return err
}

Expand Down Expand Up @@ -149,9 +150,11 @@
processHandler := ngxruntime.NewProcessHandlerImpl(os.ReadFile, os.Stat)

// Ensure NGINX is running before registering metrics & starting the manager.
if _, err := processHandler.FindMainProcess(ctx, ngxruntime.PidFileTimeout); err != nil {
p, err := processHandler.FindMainProcess(ctx, ngxruntime.PidFileTimeout)
if err != nil {

Check warning on line 154 in internal/mode/static/manager.go

View check run for this annotation

Codecov / codecov/patch

internal/mode/static/manager.go#L153-L154

Added lines #L153 - L154 were not covered by tests
return fmt.Errorf("NGINX is not running: %w", err)
}
cfg.Logger.V(1).Info("NGINX is running with PID", "pid", p)

Check warning on line 157 in internal/mode/static/manager.go

View check run for this annotation

Codecov / codecov/patch

internal/mode/static/manager.go#L157

Added line #L157 was not covered by tests

var (
ngxruntimeCollector ngxruntime.MetricsCollector = collectors.NewManagerNoopCollector()
Expand All @@ -162,11 +165,6 @@
var usageSecret *usage.Secret

if cfg.Plus {
ngxPlusClient, err = ngxruntime.CreatePlusClient()
if err != nil {
return fmt.Errorf("error creating NGINX plus client: %w", err)
}

if cfg.UsageReportConfig != nil {
usageSecret = usage.NewUsageSecret()
reporter, err := createUsageReporterJob(mgr.GetAPIReader(), cfg, usageSecret, nginxChecker.getReadyCh())
Expand All @@ -188,6 +186,10 @@
constLabels := map[string]string{"class": cfg.GatewayClassName}
var ngxCollector prometheus.Collector
if cfg.Plus {
ngxPlusClient, err = ngxruntime.CreatePlusClient()
if err != nil {
return fmt.Errorf("error creating NGINX plus client: %w", err)

Check warning on line 191 in internal/mode/static/manager.go

View check run for this annotation

Codecov / codecov/patch

internal/mode/static/manager.go#L189-L191

Added lines #L189 - L191 were not covered by tests
}
ngxCollector, err = collectors.NewNginxPlusMetricsCollector(ngxPlusClient, constLabels, promLogger)
} else {
ngxCollector = collectors.NewNginxMetricsCollector(constLabels, promLogger)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ func TestValidateEscapedStringNoVarExpansion(t *testing.T) {

func TestValidateValidHeaderName(t *testing.T) {
t.Parallel()
validator := func(value string) error { return validateHeaderName(value) }
validator := validateHeaderName

testValidValuesForSimpleValidator(
t,
Expand Down
8 changes: 4 additions & 4 deletions internal/mode/static/nginx/file/folders.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,12 @@ func ClearFolders(fileMgr ClearFoldersOSFileManager, paths []string) (removedFil
}

for _, entry := range entries {
path := filepath.Join(path, entry.Name())
if err := fileMgr.Remove(path); err != nil {
return removedFiles, fmt.Errorf("failed to remove %q: %w", path, err)
entryPath := filepath.Join(path, entry.Name())
if err := fileMgr.Remove(entryPath); err != nil {
return removedFiles, fmt.Errorf("failed to remove %q: %w", entryPath, err)
}

removedFiles = append(removedFiles, path)
removedFiles = append(removedFiles, entryPath)
}
}

Expand Down
4 changes: 2 additions & 2 deletions internal/mode/static/nginx/runtime/manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -121,9 +121,9 @@ func (m *ManagerImpl) Reload(ctx context.Context, configVersion int) error {

// send HUP signal to the NGINX main process reload configuration
// See https://nginx.org/en/docs/control.html
if err := m.processHandler.Kill(pid); err != nil {
if errP := m.processHandler.Kill(pid); errP != nil {
m.metricsCollector.IncReloadErrors()
return fmt.Errorf("failed to send the HUP signal to NGINX main: %w", err)
return fmt.Errorf("failed to send the HUP signal to NGINX main: %w", errP)
}

if err = m.verifyClient.WaitForCorrectVersion(
Expand Down
4 changes: 2 additions & 2 deletions internal/mode/static/state/dataplane/configuration.go
Original file line number Diff line number Diff line change
Expand Up @@ -279,12 +279,12 @@ func buildBackendGroups(servers []VirtualServer) []BackendGroup {
for _, mr := range pr.MatchRules {
group := mr.BackendGroup

key := key{
k := key{
nsname: group.Source,
ruleIdx: group.RuleIdx,
}

uniqueGroups[key] = group
uniqueGroups[k] = group
}
}
}
Expand Down
8 changes: 3 additions & 5 deletions internal/mode/static/state/graph/backend_refs.go
Original file line number Diff line number Diff line change
Expand Up @@ -238,12 +238,10 @@ func validateBackendTLSPolicyMatchingAllBackends(backendRefs []BackendRef) *cond
if referencePolicy == nil {
// First reference, store the policy as reference
referencePolicy = backendRef.BackendTLSPolicy
} else {
} else if checkPoliciesEqual(backendRef.BackendTLSPolicy.Source, referencePolicy.Source) {
// Check if the policies match
if checkPoliciesEqual(backendRef.BackendTLSPolicy.Source, referencePolicy.Source) {
mismatch = true
break
}
mismatch = true
break
}
}
if mismatch {
Expand Down
12 changes: 8 additions & 4 deletions internal/mode/static/state/graph/backend_tls_policy.go
Original file line number Diff line number Diff line change
Expand Up @@ -86,23 +86,27 @@ func validateBackendTLSPolicy(

caCertRefs := backendTLSPolicy.Spec.Validation.CACertificateRefs
wellKnownCerts := backendTLSPolicy.Spec.Validation.WellKnownCACertificates
if len(caCertRefs) > 0 && wellKnownCerts != nil {
switch {
case len(caCertRefs) > 0 && wellKnownCerts != nil:
valid = false
msg := "CACertificateRefs and WellKnownCACertificates are mutually exclusive"
conds = append(conds, staticConds.NewPolicyInvalid(msg))
} else if len(caCertRefs) > 0 {

case len(caCertRefs) > 0:
if err := validateBackendTLSCACertRef(backendTLSPolicy, configMapResolver); err != nil {
valid = false
conds = append(conds, staticConds.NewPolicyInvalid(
fmt.Sprintf("invalid CACertificateRef: %s", err.Error())))
}
} else if wellKnownCerts != nil {

case wellKnownCerts != nil:
if err := validateBackendTLSWellKnownCACerts(backendTLSPolicy); err != nil {
valid = false
conds = append(conds, staticConds.NewPolicyInvalid(
fmt.Sprintf("invalid WellKnownCACertificates: %s", err.Error())))
}
} else {

default:
valid = false
conds = append(conds, staticConds.NewPolicyInvalid("CACertRefs and WellKnownCACerts are both nil"))
}
Expand Down
13 changes: 12 additions & 1 deletion internal/mode/static/state/graph/backend_tls_policy_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,18 @@ func TestValidateBackendTLSPolicy(t *testing.T) {
},
}

localObjectRefTooManyCerts := append(localObjectRefNormalCase, localObjectRefInvalidName...)
localObjectRefTooManyCerts := []gatewayv1.LocalObjectReference{
{
Kind: "ConfigMap",
Name: "configmap",
Group: "",
},
{
Kind: "ConfigMap",
Name: "invalid",
Group: "",
},
}

getAncestorRef := func(ctlrName, parentName string) v1alpha2.PolicyAncestorStatus {
return v1alpha2.PolicyAncestorStatus{
Expand Down
4 changes: 2 additions & 2 deletions internal/mode/static/state/graph/gateway_listener.go
Original file line number Diff line number Diff line change
Expand Up @@ -563,7 +563,7 @@ func GetAllowedRouteLabelSelector(l v1.Listener) *metav1.LabelSelector {

// matchesWildcard checks if hostname2 matches the wildcard pattern of hostname1.
func matchesWildcard(hostname1, hostname2 string) bool {
matchesWildcard := func(h1, h2 string) bool {
mw := func(h1, h2 string) bool {
if strings.HasPrefix(h1, "*.") {
// Remove the "*." from h1
h1 = h1[2:]
Expand All @@ -572,7 +572,7 @@ func matchesWildcard(hostname1, hostname2 string) bool {
}
return false
}
return matchesWildcard(hostname1, hostname2) || matchesWildcard(hostname2, hostname1)
return mw(hostname1, hostname2) || mw(hostname2, hostname1)
}

// haveOverlap checks for overlap between two hostnames.
Expand Down
9 changes: 6 additions & 3 deletions internal/mode/static/state/graph/secret.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,11 +44,14 @@ func (r *secretResolver) resolve(nsname types.NamespacedName) error {

var validationErr error

if !exist {
switch {
case !exist:
validationErr = errors.New("secret does not exist")
} else if secret.Type != apiv1.SecretTypeTLS {

case secret.Type != apiv1.SecretTypeTLS:
validationErr = fmt.Errorf("secret type must be %q not %q", apiv1.SecretTypeTLS, secret.Type)
} else {

default:
// A TLS Secret is guaranteed to have these data fields.
_, err := tls.X509KeyPair(secret.Data[apiv1.TLSCertKey], secret.Data[apiv1.TLSPrivateKeyKey])
if err != nil {
Expand Down
7 changes: 2 additions & 5 deletions internal/mode/static/state/resolver/resolver.go
Original file line number Diff line number Diff line change
Expand Up @@ -155,11 +155,8 @@ func resolveEndpoints(
// If the ServicePort has a non-zero integer TargetPort, the TargetPort integer value is returned.
// Otherwise, the ServicePort port value is returned.
func getDefaultPort(svcPort v1.ServicePort) int32 {
switch svcPort.TargetPort.Type {
case intstr.Int:
if svcPort.TargetPort.IntVal != 0 {
return svcPort.TargetPort.IntVal
}
if svcPort.TargetPort.Type == intstr.Int && svcPort.TargetPort.IntVal != 0 {
return svcPort.TargetPort.IntVal
}

return svcPort.Port
Expand Down
9 changes: 6 additions & 3 deletions internal/mode/static/status/prepare_requests.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,8 @@
r.Source.GetGeneration(),
)

if r.RouteType == graph.RouteTypeHTTP {
switch r.RouteType {
case graph.RouteTypeHTTP:
status := v1.HTTPRouteStatus{
RouteStatus: routeStatus,
}
Expand All @@ -80,7 +81,8 @@
}

reqs = append(reqs, req)
} else if r.RouteType == graph.RouteTypeGRPC {

case graph.RouteTypeGRPC:
status := v1.GRPCRouteStatus{
RouteStatus: routeStatus,
}
Expand All @@ -92,7 +94,8 @@
}

reqs = append(reqs, req)
} else {

default:

Check warning on line 98 in internal/mode/static/status/prepare_requests.go

View check run for this annotation

Codecov / codecov/patch

internal/mode/static/status/prepare_requests.go#L98

Added line #L98 was not covered by tests
panic(fmt.Sprintf("Unknown route type: %s", r.RouteType))
}
}
Expand Down
4 changes: 2 additions & 2 deletions internal/mode/static/telemetry/collector.go
Original file line number Diff line number Diff line change
Expand Up @@ -245,10 +245,10 @@ func computeRouteCount(

for _, r := range routes {
if r.RouteType == graph.RouteTypeHTTP {
httpRouteCount = httpRouteCount + 1
httpRouteCount++
}
if r.RouteType == graph.RouteTypeGRPC {
grpcRouteCount = grpcRouteCount + 1
grpcRouteCount++
}
}

Expand Down
9 changes: 3 additions & 6 deletions internal/mode/static/usage/job_worker_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,8 +58,7 @@ func TestCreateUsageJobWorker(t *testing.T) {
return nil
},
getCalls: func(_ context.Context, _ types.NamespacedName, object client.Object, _ ...client.GetOption) error {
switch typedObject := object.(type) {
case *v1.Namespace:
if typedObject, ok := object.(*v1.Namespace); ok {
typedObject.Name = metav1.NamespaceSystem
typedObject.UID = "1234abcd"
return nil
Expand All @@ -83,8 +82,7 @@ func TestCreateUsageJobWorker(t *testing.T) {
{
name: "collect node count fails",
listCalls: func(_ context.Context, object client.ObjectList, _ ...client.ListOption) error {
switch object.(type) {
case *v1.NodeList:
if _, ok := object.(*v1.NodeList); ok {
return errors.New("failed to collect node list")
}
return nil
Expand Down Expand Up @@ -127,8 +125,7 @@ func TestCreateUsageJobWorker(t *testing.T) {
return nil
},
getCalls: func(_ context.Context, _ types.NamespacedName, object client.Object, _ ...client.GetOption) error {
switch object.(type) {
case *v1.Namespace:
if _, ok := object.(*v1.Namespace); ok {
return errors.New("failed to collect namespace")
}
return nil
Expand Down
4 changes: 2 additions & 2 deletions tests/framework/ngf.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ func InstallNGF(cfg InstallationConfig, extraArgs ...string) ([]byte, error) {
}

args = append(args, setImageArgs(cfg)...)
fullArgs := append(args, extraArgs...)
fullArgs := append(args, extraArgs...) //nolint:gocritic

GinkgoWriter.Printf("Installing NGF with command: helm %v\n", strings.Join(fullArgs, " "))

Expand Down Expand Up @@ -102,7 +102,7 @@ func UpgradeNGF(cfg InstallationConfig, extraArgs ...string) ([]byte, error) {
}

args = append(args, setImageArgs(cfg)...)
fullArgs := append(args, extraArgs...)
fullArgs := append(args, extraArgs...) //nolint:gocritic

GinkgoWriter.Printf("Upgrading NGF with command: helm %v\n", strings.Join(fullArgs, " "))

Expand Down
15 changes: 7 additions & 8 deletions tests/suite/system_suite_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -148,11 +148,12 @@ func setup(cfg setupConfig, extraInstallArgs ...string) {
Skip("Graceful Recovery test must be run on Kind")
}

if *versionUnderTest != "" {
switch {
case *versionUnderTest != "":
version = *versionUnderTest
} else if *imageTag != "" {
case *imageTag != "":
version = *imageTag
} else {
default:
version = "edge"
}

Expand Down Expand Up @@ -203,11 +204,9 @@ func createNGFInstallConfig(cfg setupConfig, extraInstallArgs ...string) framewo
}
installCfg.ImageTag = *imageTag
installCfg.ImagePullPolicy = *imagePullPolicy
} else {
if version == "edge" {
chartVersion = "0.0.0-edge"
installCfg.ChartVersion = chartVersion
}
} else if version == "edge" {
chartVersion = "0.0.0-edge"
installCfg.ChartVersion = chartVersion
}

output, err := framework.InstallGatewayAPI(cfg.gwAPIVersion)
Expand Down
Loading
Loading