diff --git a/.golangci.yml b/.golangci.yml index ab4a15f2..d39526b7 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -16,9 +16,9 @@ linters-settings: min-occurrences: 2 revive: rules: - - name: var-naming - severity: warning - disabled: true + - name: var-naming + severity: warning + disabled: true linters: enable-all: true disable: @@ -74,13 +74,12 @@ linters: - tagalign - depguard - issues: exclude: # bugs of typecheck linter - "undeclared name: `shellquote`" - - "github.com/kballard/go-shellquote\" imported but not used" - - "github.com/haproxytech/config-parser/v5/types\" imported but not used" + - 'github.com/kballard/go-shellquote" imported but not used' + - 'github.com/haproxytech/config-parser/v5/types" imported but not used' exclude-rules: - linters: - staticcheck @@ -91,7 +90,5 @@ issues: - linters: - gosec text: "G[404]" - -run: - skip-dirs: + exclude-dirs: - test diff --git a/Makefile b/Makefile index f22c99e1..66d238a5 100644 --- a/Makefile +++ b/Makefile @@ -9,7 +9,7 @@ GIT_MODIFIED=${GIT_MODIFIED1}${GIT_MODIFIED2} SWAGGER_VERSION=${shell curl -s https://raw.githubusercontent.com/haproxytech/client-native/master/Makefile | grep SWAGGER_VERSION -m 1 | awk -F"=" '{print $$2}'} BUILD_DATE=$(shell date -u '+%Y-%m-%dT%H:%M:%SZ') CGO_ENABLED?=0 -GOLANGCI_LINT_VERSION=1.54.2 +GOLANGCI_LINT_VERSION=1.57.1 all: update clean build diff --git a/configuration/cluster_sync.go b/configuration/cluster_sync.go index ebf080ba..1dcfd8d2 100644 --- a/configuration/cluster_sync.go +++ b/configuration/cluster_sync.go @@ -25,6 +25,7 @@ import ( "crypto/x509/pkix" "encoding/asn1" "encoding/pem" + "errors" "fmt" "io" "net/http" @@ -148,7 +149,7 @@ func (c *ClusterSync) issueRefreshRequest(url, port, basePath string, nodesPath req, err := http.NewRequest(http.MethodPatch, url, bytes.NewBuffer(bytesRepresentation)) if err != nil { - return fmt.Errorf("error creating new POST request for cluster comunication") + return errors.New("error creating new POST request for cluster comunication") } req.Header.Add("X-Node-Key", c.cfg.Cluster.Token.Load()) req.Header.Add("Content-Type", "application/json") diff --git a/configuration/map_sync.go b/configuration/map_sync.go index cf79108c..c380f6cb 100644 --- a/configuration/map_sync.go +++ b/configuration/map_sync.go @@ -96,7 +96,7 @@ func (ms *MapSync) Sync(mp *models.Map, client client_native.HAProxyClient) (boo sort.Slice(fileEntries, func(i, j int) bool { return fileEntries[i].Key < fileEntries[j].Key }) // runtime map entries - id := fmt.Sprintf("#%s", mp.ID) + id := "#" + mp.ID runtimeEntries, err := runtime.ShowMapEntries(id) if err != nil { return false, fmt.Errorf("getting runtime entries error: id: %s %s", id, err.Error()) @@ -144,7 +144,7 @@ func equalSomeEntries(fEntries, rEntries models.MapEntries, index ...int) bool { maxRandom = max } - for i := 0; i < maxRandom; i++ { + for range maxRandom { // There's no need for strong number generation, here, just need for performance r := rand.Intn(max) if len(index) > 0 { diff --git a/configuration/map_sync_test.go b/configuration/map_sync_test.go index 595eaab0..8cc4f9c5 100644 --- a/configuration/map_sync_test.go +++ b/configuration/map_sync_test.go @@ -23,7 +23,7 @@ import ( ) func data(differentAtIndex ...int) (fileEntries models.MapEntries, runtimeEntries models.MapEntries) { - for i := 0; i < 50; i++ { + for i := range 50 { fe := &models.MapEntry{Key: "k" + strconv.Itoa(i), Value: "v" + strconv.Itoa(i)} re := &models.MapEntry{Key: "k" + strconv.Itoa(i), Value: "v" + strconv.Itoa(i)} fileEntries = append(fileEntries, fe) diff --git a/configuration/pid.go b/configuration/pid.go index 2c6a3352..68764246 100644 --- a/configuration/pid.go +++ b/configuration/pid.go @@ -16,7 +16,6 @@ package configuration import ( - "fmt" "os" "strconv" @@ -47,7 +46,7 @@ func HandlePIDFile(haproxyOptions HAProxyConfiguration) { } } - err := renameio.WriteFile(haproxyOptions.PIDFile, []byte(fmt.Sprintf("%d", os.Getpid())), 0o644) + err := renameio.WriteFile(haproxyOptions.PIDFile, []byte(strconv.Itoa(os.Getpid())), 0o644) if err != nil { log.Fatalf("error while writing PID file: %s %s", haproxyOptions.PIDFile, err.Error()) } else { diff --git a/configuration/reload-strategy.go b/configuration/reload-strategy.go index 834d1f1a..6e1d3377 100644 --- a/configuration/reload-strategy.go +++ b/configuration/reload-strategy.go @@ -15,7 +15,10 @@ package configuration -import "fmt" +import ( + "errors" + "fmt" +) const ( ReloadStratCustom = "custom" @@ -53,7 +56,7 @@ func validateReloadConfiguration(c *HAProxyConfiguration) error { case ReloadStratCustom: // The custom commands need to be set. if c.ReloadCmd == "" || c.RestartCmd == "" { - return fmt.Errorf("the custom reload strategy requires these options to be set: " + + return errors.New("the custom reload strategy requires these options to be set: " + "ReloadCmd, RestartCmd") } case ReloadStratS6: diff --git a/configuration/watcher.go b/configuration/watcher.go index 8cd8e73c..39de16a3 100644 --- a/configuration/watcher.go +++ b/configuration/watcher.go @@ -18,7 +18,7 @@ package configuration import ( "context" "crypto/md5" - "fmt" + "encoding/hex" "os" "path/filepath" "strings" @@ -108,6 +108,6 @@ func (w *ConfigWatcher) invalidHash() bool { return true } bHash := md5.Sum([]byte(strings.Join(lines[1:], "\n"))) - hash := fmt.Sprintf("%x", bHash) + hash := hex.EncodeToString(bHash[:]) return parts[1] != hash } diff --git a/configure_data_plane.go b/configure_data_plane.go index b7e44957..4764f7c4 100644 --- a/configure_data_plane.go +++ b/configure_data_plane.go @@ -1032,6 +1032,7 @@ func handleSignals(ctx context.Context, cancel context.CancelFunc, sigs chan os. reloadConfigurationFile(client, haproxyOptions, users) } case <-ctx.Done(): + cancel() return } } diff --git a/discovery/aws_service_discovery_instance.go b/discovery/aws_service_discovery_instance.go index 87ecf0fe..94e970f6 100644 --- a/discovery/aws_service_discovery_instance.go +++ b/discovery/aws_service_discovery_instance.go @@ -127,10 +127,9 @@ func newAWSRegionInstance(ctx context.Context, params *models.AwsRegion, client func (a *awsInstance) filterConverter(in []*models.AwsFilters) (out []types.Filter) { out = make([]types.Filter, len(in)) for i, l := range in { - filter := l out[i] = types.Filter{ - Name: filter.Key, - Values: []string{aws.ToString(filter.Value)}, + Name: l.Key, + Values: []string{aws.ToString(l.Value)}, } } return diff --git a/discovery/store.go b/discovery/store.go index 4fdb2e51..9d052b3d 100644 --- a/discovery/store.go +++ b/discovery/store.go @@ -16,6 +16,7 @@ package discovery import ( + "errors" "fmt" "sync" ) @@ -72,7 +73,7 @@ func (s *instanceStore) Create(name string, service interface{}) error { defer s.mu.Unlock() if _, err := s.get(name); err == nil { - return fmt.Errorf("instance already exists") + return errors.New("instance already exists") } s.store[name] = service @@ -102,7 +103,7 @@ func (s *instanceStore) get(name string) (sd interface{}, err error) { var ok bool sd, ok = s.store[name] if !ok { - return nil, fmt.Errorf("instance not found") + return nil, errors.New("instance not found") } return } diff --git a/generate/go-generate.go b/generate/go-generate.go index d3ffb9a6..d1b5bb46 100644 --- a/generate/go-generate.go +++ b/generate/go-generate.go @@ -229,7 +229,7 @@ func getExample(att Attribute) string { if att.Example != "" { if att.Type == "int" { i, _ := strconv.ParseInt(att.Example, 10, 64) - return fmt.Sprintf("%d", i) + return strconv.FormatInt(i, 10) } return att.Example } @@ -250,7 +250,7 @@ func getExample(att Attribute) string { if v, ok := itemDefaults[att.FileName]; ok { switch t := v.(type) { case int: - return fmt.Sprintf("%d", v.(int)) + return strconv.Itoa(v.(int)) default: return t.(string) } diff --git a/handlers/bind.go b/handlers/bind.go index 3c724ea4..9f12bd12 100644 --- a/handlers/bind.go +++ b/handlers/bind.go @@ -16,7 +16,7 @@ package handlers import ( - "fmt" + "errors" "github.com/go-openapi/runtime/middleware" client_native "github.com/haproxytech/client-native/v4" @@ -60,10 +60,10 @@ func bindTypeParams(frontend *string, parentType *string, parentName *string) (p return "frontend", *frontend, nil } if parentType == nil || *parentType == "" { - return "", "", fmt.Errorf("parentType empty") + return "", "", errors.New("parentType empty") } if parentName == nil || *parentName == "" { - return "", "", fmt.Errorf("parentName empty") + return "", "", errors.New("parentName empty") } return *parentType, *parentName, nil } diff --git a/handlers/cluster.go b/handlers/cluster.go index 4ed6f167..ec4874d0 100644 --- a/handlers/cluster.go +++ b/handlers/cluster.go @@ -16,6 +16,7 @@ package handlers import ( + "errors" "fmt" "reflect" "strings" @@ -245,7 +246,7 @@ func (h *EditClusterHandlerImpl) Handle(params cluster.EditClusterParams, princi } return cluster.NewEditClusterOK().WithPayload(getClusterSettings(h.Config)) } - return h.err406(fmt.Errorf("dataplaneapi in single mode")) + return h.err406(errors.New("dataplaneapi in single mode")) } func (h *EditClusterHandlerImpl) err406(err error) middleware.Responder { diff --git a/handlers/frontend.go b/handlers/frontend.go index 8f4d7499..69c21944 100644 --- a/handlers/frontend.go +++ b/handlers/frontend.go @@ -228,7 +228,7 @@ func (h *ReplaceFrontendHandlerImpl) Handle(params frontend.ReplaceFrontendParam return frontend.NewReplaceFrontendDefault(int(*e.Code)).WithPayload(e) } if params.TransactionID == nil { - reload := changeThroughRuntimeAPI(*params.Data, *ondisk, "", "", h.Client) + reload := changeThroughRuntimeAPI(*params.Data, *ondisk, "", h.Client) if reload { if *params.ForceReload { err := h.ReloadAgent.ForceReload() diff --git a/handlers/runtime.go b/handlers/runtime.go index 4264966a..e8f5ba98 100644 --- a/handlers/runtime.go +++ b/handlers/runtime.go @@ -33,7 +33,7 @@ var RuntimeSupportedFields = map[string][]string{ // ChangeThroughRuntimeAPI checks if something can be changed through the runtime API, and // returns false if reload is not needed, or true if needed. -func changeThroughRuntimeAPI(data, ondisk interface{}, parentName, parentType string, client client_native.HAProxyClient) (reload bool) { +func changeThroughRuntimeAPI(data, ondisk interface{}, parentName string, client client_native.HAProxyClient) (reload bool) { // reflect kinds and values are loosely checked as they are bound strictly in // schema, but in case of any panic, we will log and reload to ensure // changes go through @@ -183,7 +183,7 @@ func compareObjects(data, ondisk interface{}) []string { diff := make([]string, 0) dataVal := reflect.ValueOf(data) ondiskVal := reflect.ValueOf(ondisk) - for i := 0; i < dataVal.NumField(); i++ { + for i := range dataVal.NumField() { fName := dataVal.Type().Field(i).Name dataField := dataVal.FieldByName(fName) ondiskField := ondiskVal.FieldByName(fName) diff --git a/handlers/server.go b/handlers/server.go index e70b56ab..b7747e93 100644 --- a/handlers/server.go +++ b/handlers/server.go @@ -16,7 +16,7 @@ package handlers import ( - "fmt" + "errors" "github.com/haproxytech/client-native/v4/runtime" @@ -63,10 +63,10 @@ func serverTypeParams(backend *string, parentType *string, parentName *string) ( return "backend", *backend, nil } if parentType == nil || *parentType == "" { - return "", "", fmt.Errorf("parentType empty") + return "", "", errors.New("parentType empty") } if parentName == nil || *parentName == "" { - return "", "", fmt.Errorf("parentName empty") + return "", "", errors.New("parentName empty") } return *parentType, *parentName, nil } @@ -314,7 +314,7 @@ func (h *ReplaceServerHandlerImpl) Handle(params server.ReplaceServerParams, pri return server.NewReplaceServerDefault(int(*e.Code)).WithPayload(e) } if params.TransactionID == nil { - reload := changeThroughRuntimeAPI(*params.Data, *ondisk, pType, "", h.Client) + reload := changeThroughRuntimeAPI(*params.Data, *ondisk, pName, h.Client) if reload { if *params.ForceReload { err := h.ReloadAgent.ForceReload() diff --git a/handlers/server_template.go b/handlers/server_template.go index 9f516ac0..c5a18458 100644 --- a/handlers/server_template.go +++ b/handlers/server_template.go @@ -232,7 +232,7 @@ func (h *ReplaceServerTemplateHandlerImpl) Handle(params server_template.Replace return server_template.NewReplaceServerTemplateDefault(int(*e.Code)).WithPayload(e) } if params.TransactionID == nil { - reload := changeThroughRuntimeAPI(*params.Data, *ondisk, params.Backend, "", h.Client) + reload := changeThroughRuntimeAPI(*params.Data, *ondisk, params.Backend, h.Client) if reload { if *params.ForceReload { err := h.ReloadAgent.ForceReload() diff --git a/haproxy/reload_agent.go b/haproxy/reload_agent.go index d44d730d..7c6ff25d 100644 --- a/haproxy/reload_agent.go +++ b/haproxy/reload_agent.go @@ -18,6 +18,7 @@ package haproxy import ( "bytes" "context" + "errors" "fmt" "io" "os" @@ -42,10 +43,10 @@ const ( type IReloadAgent interface { Reload() string - ReloadWithCallback(func()) string + ReloadWithCallback(callback func()) string Restart() error ForceReload() error - ForceReloadWithCallback(func()) error + ForceReloadWithCallback(callback func()) error Status() (bool, error) GetReloads() models.Reloads GetReload(id string) *models.Reload @@ -479,7 +480,7 @@ func (ra *ReloadAgent) Status() (bool, error) { func (ra *ReloadAgent) status() (bool, error) { if ra.statusCmd == "" { - return false, fmt.Errorf("status command not configured") + return false, errors.New("status command not configured") } resp, err := execCmd(ra.statusCmd) if err != nil { @@ -511,7 +512,7 @@ type ReloadError struct { // Error implementation for ConfError func (e *ReloadError) Error() string { - return fmt.Sprintf(e.msg) + return e.msg } // NewReloadError constructor for ReloadError diff --git a/haproxy/reload_agent_test.go b/haproxy/reload_agent_test.go index 04ca67d4..9dfd6c42 100644 --- a/haproxy/reload_agent_test.go +++ b/haproxy/reload_agent_test.go @@ -22,16 +22,17 @@ import ( "time" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestReloadAgentDoesntMissReloads(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) f, err := os.CreateTemp("", "config.cfg") - assert.Nil(t, err) + require.NoError(t, err) assert.NotNil(t, f) t.Cleanup(func() { cancel() - assert.Nil(t, os.Remove(f.Name())) + assert.NoError(t, os.Remove(f.Name())) }) reloadAgentParams := ReloadAgentParams{ @@ -45,7 +46,7 @@ func TestReloadAgentDoesntMissReloads(t *testing.T) { } ra, err := NewReloadAgent(reloadAgentParams) - assert.Nil(t, err) + require.NoError(t, err) assert.NotNil(t, ra) var reloadID, firstReloadID, secondReloadID string diff --git a/log/logger.go b/log/logger.go index 717d3718..ca5b8e57 100644 --- a/log/logger.go +++ b/log/logger.go @@ -18,119 +18,102 @@ type ACLLogger struct { func (l *Logger) Log(level logrus.Level, args ...interface{}) { for _, log := range l.loggers { - log := log go log.Log(level, args...) } } func (l *Logger) Logf(level logrus.Level, format string, args ...interface{}) { for _, log := range l.loggers { - log := log go log.Logf(level, format, args...) } } func (l *Logger) Print(args ...interface{}) { for _, log := range l.loggers { - log := log go log.Print(args...) } } func (l *Logger) Trace(args ...interface{}) { for _, log := range l.loggers { - log := log go log.Trace(args...) } } func (l *Logger) Debug(args ...interface{}) { for _, log := range l.loggers { - log := log go log.Debug(args...) } } func (l *Logger) Info(args ...interface{}) { for _, log := range l.loggers { - log := log go log.Info(args...) } } func (l *Logger) Warning(args ...interface{}) { for _, log := range l.loggers { - log := log go log.Warning(args...) } } func (l *Logger) Error(args ...interface{}) { for _, log := range l.loggers { - log := log go log.Error(args...) } } func (l *Logger) Panic(args ...interface{}) { for _, log := range l.loggers { - log := log go log.Panic(args...) } } func (l *Logger) Printf(format string, args ...interface{}) { for _, log := range l.loggers { - log := log go log.Printf(format, args...) } } func (l *Logger) Tracef(format string, args ...interface{}) { for _, log := range l.loggers { - log := log go log.Tracef(format, args...) } } func (l *Logger) Debugf(format string, args ...interface{}) { for _, log := range l.loggers { - log := log go log.Debugf(format, args...) } } func (l *Logger) Infof(format string, args ...interface{}) { for _, log := range l.loggers { - log := log go log.Infof(format, args...) } } func (l *Logger) Warningf(format string, args ...interface{}) { for _, log := range l.loggers { - log := log go log.Warningf(format, args...) } } func (l *Logger) Errorf(format string, args ...interface{}) { for _, log := range l.loggers { - log := log go log.Errorf(format, args...) } } func (l *Logger) Panicf(format string, args ...interface{}) { for _, log := range l.loggers { - log := log go log.Panicf(format, args...) } } func (l *Logger) Fatalln(args ...interface{}) { for _, log := range l.loggers { - log := log log.Logln(logrus.FatalLevel, args...) } os.Exit(1) @@ -138,7 +121,6 @@ func (l *Logger) Fatalln(args ...interface{}) { func (l *Logger) Fatal(args ...interface{}) { for _, log := range l.loggers { - log := log log.Log(logrus.FatalLevel, args...) } os.Exit(1) @@ -146,7 +128,6 @@ func (l *Logger) Fatal(args ...interface{}) { func (l *Logger) Fatalf(format string, args ...interface{}) { for _, log := range l.loggers { - log := log log.Logf(logrus.FatalLevel, format, args...) } os.Exit(1) @@ -154,14 +135,12 @@ func (l *Logger) Fatalf(format string, args ...interface{}) { func (l *Logger) WithFieldsf(fields map[string]interface{}, level logrus.Level, format string, args ...interface{}) { for _, log := range l.loggers { - log := log go log.WithFields(fields).Logf(level, format, args...) } } func (l *Logger) WithFields(fields map[string]interface{}, level logrus.Level, args ...interface{}) { for _, log := range l.loggers { - log := log go log.WithFields(fields).Log(level, args...) } } diff --git a/log/rfc5424.go b/log/rfc5424.go index d630aa6a..906009ab 100644 --- a/log/rfc5424.go +++ b/log/rfc5424.go @@ -16,6 +16,7 @@ package log import ( + "errors" "fmt" "strings" "time" @@ -77,7 +78,7 @@ func (r RFC5424Hook) Fire(entry *logrus.Entry) (err error) { func NewRFC5424Hook(opts Target) (logrus.Hook, error) { if len(opts.SyslogAddr) == 0 { - return nil, fmt.Errorf("no address has been declared") + return nil, errors.New("no address has been declared") } priority := strings.Join([]string{opts.SyslogFacility, opts.SyslogLevel}, ".") diff --git a/misc/misc.go b/misc/misc.go index de9c66e0..15935c6c 100644 --- a/misc/misc.go +++ b/misc/misc.go @@ -322,7 +322,7 @@ func CreateClusterUser() (types.User, string, error) { if err != nil { return types.User{}, "", err } - name = fmt.Sprintf("dpapi-c-%s", name) + name = "dpapi-c" + name log.Infof("Creating user %s for cluster connection", name) user := types.User{ Name: name, diff --git a/misc/misc_test.go b/misc/misc_test.go index f6c774bf..297c9522 100644 --- a/misc/misc_test.go +++ b/misc/misc_test.go @@ -21,7 +21,7 @@ import ( ) func TestRandomString(t *testing.T) { - for i := 0; i < 1024; i++ { + for range 1024 { size := rand.Intn(512) str, err := RandomString(size) if err != nil { diff --git a/rate/threshold_limit_test.go b/rate/threshold_limit_test.go index 508517a0..31e1dfe6 100644 --- a/rate/threshold_limit_test.go +++ b/rate/threshold_limit_test.go @@ -18,6 +18,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func Test_thresholdLimit_LimitReached(t *testing.T) { @@ -37,6 +38,6 @@ func Test_thresholdLimit_LimitReached(t *testing.T) { }, limit: 10, } - assert.Nil(t, tl.LimitReached()) + require.NoError(t, tl.LimitReached()) }) }