Skip to content

Commit

Permalink
BUILD/MEDIUM: lint: apply stricter rules for linting
Browse files Browse the repository at this point in the history
  • Loading branch information
oktalz authored and mjuraga committed Oct 11, 2023
1 parent 49ba264 commit 5137030
Show file tree
Hide file tree
Showing 23 changed files with 61 additions and 69 deletions.
8 changes: 7 additions & 1 deletion .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@ linters-settings:
golint:
min-confidence: 0
gocyclo:
min-complexity: 25
min-complexity: 42
cyclop:
max-complexity: 42
maligned:
suggest-new: true
dupl:
Expand Down Expand Up @@ -72,6 +74,7 @@ linters:
- tagalign
- depguard


issues:
exclude:
# bugs of typecheck linter
Expand All @@ -85,6 +88,9 @@ issues:
- linters:
- gosec
text: "G[501]"
- linters:
- gosec
text: "G[404]"

run:
skip-dirs:
Expand Down
1 change: 0 additions & 1 deletion adapters/adapters.go
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,6 @@ func RecoverMiddleware(logger *log.Logger) func(h http.Handler) http.Handler {
if strings.HasPrefix(ct, "application/json") {
w.Header().Set("Content-Type", "application/json")
}
// nolint:errcheck
w.Write(errMsg)
}
}()
Expand Down
1 change: 0 additions & 1 deletion client-native/cn.go
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,6 @@ func ConfigureRuntimeClient(ctx context.Context, confClient configuration.Config
return runtimeClient
}
log.Warningf("Error setting up runtime client with sockets: %v : %s", sockets, err.Error())

}
if err != nil {
log.Warning("Runtime API not configured, not using it: " + err.Error())
Expand Down
2 changes: 1 addition & 1 deletion cmd/dataplaneapi/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -235,7 +235,7 @@ func startServer(cfg *configuration.Configuration) (reload configuration.AtomicB
log.Fatalf("Error running HAProxy Data Plane API: %s", err.Error())
}

defer server.Shutdown() // nolint:errcheck
defer server.Shutdown() //nolint:errcheck

return reload
}
Expand Down
19 changes: 9 additions & 10 deletions configuration/cluster_sync.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ import (
"encoding/asn1"
"encoding/pem"
"fmt"
"io/ioutil"
"io"
"net/http"
"path"
"strconv"
Expand Down Expand Up @@ -146,7 +146,7 @@ func (c *ClusterSync) issueRefreshRequest(url, port, basePath string, nodesPath
json := jsoniter.ConfigCompatibleWithStandardLibrary
bytesRepresentation, _ := json.Marshal(nodeData)

req, err := http.NewRequest("PATCH", url, bytes.NewBuffer(bytesRepresentation))
req, err := http.NewRequest(http.MethodPatch, url, bytes.NewBuffer(bytesRepresentation))
if err != nil {
return fmt.Errorf("error creating new POST request for cluster comunication")
}
Expand All @@ -160,11 +160,11 @@ func (c *ClusterSync) issueRefreshRequest(url, port, basePath string, nodesPath
}
defer resp.Body.Close()

body, err := ioutil.ReadAll(resp.Body)
body, err := io.ReadAll(resp.Body)
if err != nil {
return err
}
if resp.StatusCode != 202 {
if resp.StatusCode != http.StatusAccepted {
return fmt.Errorf("status code not proper [%d] %s", resp.StatusCode, string(body))
}
var responseData Node
Expand Down Expand Up @@ -366,7 +366,7 @@ func (c *ClusterSync) issueJoinRequest(url, port, basePath string, registerPath
}
defer resp.Body.Close()

body, err := ioutil.ReadAll(resp.Body)
body, err := io.ReadAll(resp.Body)
if err != nil {
return err
}
Expand All @@ -385,7 +385,7 @@ func (c *ClusterSync) issueJoinRequest(url, port, basePath string, registerPath
return errCfg
}
// write id to file
errFID := ioutil.WriteFile(c.cfg.HAProxy.NodeIDFile, []byte(responseData.ID), 0o644) // nolint:gosec
errFID := renameio.WriteFile(c.cfg.HAProxy.NodeIDFile, []byte(responseData.ID), 0o644)
if errFID != nil {
return errFID
}
Expand Down Expand Up @@ -501,7 +501,7 @@ func (c *ClusterSync) fetchCert() {
apiNodesPath := c.cfg.Cluster.APINodesPath.Load()
id := c.cfg.Cluster.ID.Load()
url = fmt.Sprintf("%s:%d/%s", url, port, strings.TrimLeft(path.Join(apiBasePath, apiNodesPath, id), "/"))
req, err := http.NewRequest("GET", url, nil)
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
c.activateFetchCert(err)
break
Expand All @@ -514,13 +514,13 @@ func (c *ClusterSync) fetchCert() {
c.activateFetchCert(err)
break
}
body, err := ioutil.ReadAll(resp.Body)
body, err := io.ReadAll(resp.Body)
resp.Body.Close()
if err != nil {
c.activateFetchCert(err)
break
}
if resp.StatusCode != 200 {
if resp.StatusCode != http.StatusOK {
c.activateFetchCert(fmt.Errorf("status code not proper [%d] %s", resp.StatusCode, string(body)))
break
}
Expand Down Expand Up @@ -605,7 +605,6 @@ func createHTTPClient() *http.Client {
Transport: &http.Transport{
MaxIdleConnsPerHost: 20,
TLSClientConfig: &tls.Config{
//nolint
InsecureSkipVerify: true, // this is deliberate, might only have self signed certificate
},
},
Expand Down
2 changes: 1 addition & 1 deletion configuration/configuration_storage.go
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,7 @@ type StorageDataplaneAPIConfiguration struct {
LogTargets *dpapilog.Targets `yaml:"log_targets,omitempty" hcl:"log_targets,omitempty"`
}

func copyToConfiguration(cfg *Configuration) {
func copyToConfiguration(cfg *Configuration) { //nolint:cyclop,maintidx
cfgStorage := cfg.storage.Get()
if cfgStorage.Name != nil {
cfg.Name.Store(*cfgStorage.Name)
Expand Down
7 changes: 4 additions & 3 deletions configuration/file-storage-hcl.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,10 @@ package configuration
import (
"bytes"
"encoding/gob"
"io/ioutil"
"os"
"strings"

"github.com/google/renameio"
"github.com/haproxytech/dataplaneapi/log"
"github.com/hashicorp/hcl"
"github.com/rodaine/hclencoder"
Expand All @@ -36,7 +37,7 @@ func (s *StorageHCL) Load(filename string) error {
cfg := &StorageDataplaneAPIConfiguration{}
var hclFile []byte
var err error
hclFile, err = ioutil.ReadFile(filename)
hclFile, err = os.ReadFile(filename)
if err != nil {
return err
}
Expand Down Expand Up @@ -102,7 +103,7 @@ func (s *StorageHCL) SaveAs(filename string) error {
return err
}

return ioutil.WriteFile(filename, hcl, 0o644) //nolint:gosec
return renameio.WriteFile(filename, hcl, 0o644)
}

func (s *StorageHCL) Save() error {
Expand Down
4 changes: 2 additions & 2 deletions configuration/file-storage-yml.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
package configuration

import (
"io/ioutil"
"os"

"github.com/google/renameio"
"gopkg.in/yaml.v2"
Expand All @@ -32,7 +32,7 @@ func (s *StorageYML) Load(filename string) error {
cfg := &StorageDataplaneAPIConfiguration{}
var err error

yamlFile, err := ioutil.ReadFile(filename)
yamlFile, err := os.ReadFile(filename)
if err != nil {
return err
}
Expand Down
7 changes: 3 additions & 4 deletions configuration/map_sync.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ func (ms *MapSync) SyncAll(client client_native.HAProxyClient) {
haproxyOptions := Get().HAProxy

d := time.Duration(haproxyOptions.UpdateMapFilesPeriod)
ticker := time.NewTicker(d * time.Second)
ticker := time.NewTicker(d * time.Second) //nolint:durationcheck

for {
select {
Expand Down Expand Up @@ -145,9 +145,8 @@ func equalSomeEntries(fEntries, rEntries models.MapEntries, index ...int) bool {
}

for i := 0; i < maxRandom; i++ {
rand.Seed(time.Now().UTC().UnixNano())
// There's no need for strong number generation, here, just need for performance
r := rand.Intn(max) // nolint:gosec
r := rand.Intn(max)
if len(index) > 0 {
r = index[0]
}
Expand All @@ -174,7 +173,7 @@ func equal(a, b models.MapEntries) bool {
}

// dumpRuntimeEntries dumps runtime entries into map file
// Returns true,nil if succeed, otherwise retuns false,error
// Returns true,nil if succeed, otherwise returns false,error
func dumpRuntimeEntries(file string, me models.MapEntries) (bool, error) {
f, err := os.OpenFile(file, os.O_APPEND|os.O_WRONLY|os.O_TRUNC, 0o600)
if err != nil {
Expand Down
3 changes: 1 addition & 2 deletions configuration/pid.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ package configuration

import (
"fmt"
"io/ioutil"
"os"
"strconv"

Expand All @@ -31,7 +30,7 @@ func HandlePIDFile(haproxyOptions HAProxyConfiguration) {
}

if fileExists(haproxyOptions.PIDFile) {
data, err := ioutil.ReadFile(haproxyOptions.PIDFile)
data, err := os.ReadFile(haproxyOptions.PIDFile)
if err != nil {
log.Fatalf("error while reading PID file content: %v", err)
}
Expand Down
2 changes: 1 addition & 1 deletion configuration/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ func (u *Users) getUsersFromUsersListSection(filename, userlistSection string) e
}
data, err := p.Get(parser.UserList, userlistSection, "user")
if err != nil {
return fmt.Errorf("no users configured in %v, error: %s", filename, err.Error())
return fmt.Errorf("no users configured in %v, error: %w", filename, err)
}

return u.setUser(data, cfg.HAProxy.UserListFile)
Expand Down
5 changes: 2 additions & 3 deletions configuration/watcher.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import (
"context"
"crypto/md5"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"

Expand Down Expand Up @@ -97,7 +97,7 @@ func (w *ConfigWatcher) checkFlags(event fsnotify.Event) bool {
}

func (w *ConfigWatcher) invalidHash() bool {
content, err := ioutil.ReadFile(w.configFile)
content, err := os.ReadFile(w.configFile)
if err != nil {
log.Warningf("Watcher: error reading config file: %s", err.Error())
return false
Expand All @@ -107,7 +107,6 @@ func (w *ConfigWatcher) invalidHash() bool {
if len(parts) != 2 || parts[0] != "# _md5hash" {
return true
}
//nolint:gosec
bHash := md5.Sum([]byte(strings.Join(lines[1:], "\n")))
hash := fmt.Sprintf("%x", bHash)
return parts[1] != hash
Expand Down
8 changes: 3 additions & 5 deletions configure_data_plane.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ import (
_ "github.com/GehirnInc/crypt/sha512_crypt"
)

// go:generate swagger generate server --target ../../../../../../github.com/haproxytech --name controller --spec ../../../../../../../../haproxy-api/haproxy-open-api-spec/build/haproxy_spec.yaml --server-package controller --tags Stats --tags Information --tags Configuration --tags Discovery --tags Frontend --tags Backend --tags Bind --tags Server --tags TCPRequestRule --tags HTTPRequestRule --tags HTTPResponseRule --tags Acl --tags BackendSwitchingRule --tags ServerSwitchingRule --tags TCPResponseRule --skip-models --exclude-main
//go:generate swagger generate server --target ../../../../../../github.com/haproxytech --name controller --spec ../../../../../../../../haproxy-api/haproxy-open-api-spec/build/haproxy_spec.yaml --server-package controller --tags Stats --tags Information --tags Configuration --tags Discovery --tags Frontend --tags Backend --tags Bind --tags Server --tags TCPRequestRule --tags HTTPRequestRule --tags HTTPResponseRule --tags Acl --tags BackendSwitchingRule --tags ServerSwitchingRule --tags TCPResponseRule --skip-models --exclude-main

var (
Version string
Expand Down Expand Up @@ -109,7 +109,7 @@ func configureFlags(api *operations.DataPlaneAPI) {
api.CommandLineOptionsGroups = append(api.CommandLineOptionsGroups, syslogOptionsGroup)
}

func configureAPI(api *operations.DataPlaneAPI) http.Handler {
func configureAPI(api *operations.DataPlaneAPI) http.Handler { //nolint:cyclop,maintidx
clientMutex.Lock()
defer clientMutex.Unlock()

Expand Down Expand Up @@ -149,7 +149,6 @@ func configureAPI(api *operations.DataPlaneAPI) http.Handler {
}
for f, ok := range m {
if !ok {
// nolint:gocritic
log.Fatalf("The %s file is not declared in the HAPROXY_CFGFILES environment variable, cannot start.", f)
}
}
Expand Down Expand Up @@ -881,7 +880,7 @@ func configureReloadAgent(ctx context.Context, haproxyOptions dataplaneapi_confi

ra, e := haproxy.NewReloadAgent(raParams)
if e != nil {
// nolint:gocritic
//nolint:gocritic
log.Fatalf("Cannot initialize reload agent: %v", e)
}
return ra
Expand Down Expand Up @@ -1015,7 +1014,6 @@ func configureNativeClient(cyx context.Context, haproxyOptions dataplaneapi_conf
}

func handleSignals(ctx context.Context, cancel context.CancelFunc, sigs chan os.Signal, client client_native.HAProxyClient, haproxyOptions dataplaneapi_config.HAProxyConfiguration, users *dataplaneapi_config.Users) {
//nolint:gosimple
for {
select {
case sig := <-sigs:
Expand Down
1 change: 0 additions & 1 deletion discovery/service_discovery.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,6 @@ func NewServiceDiscoveries(params ServiceDiscoveriesParams) ServiceDiscoveries {
sd := &serviceDiscoveryImpl{
services: NewInstanceStore(),
}
//nolint
sd.AddService("consul", NewConsulDiscoveryService(params))
_ = sd.AddService("aws", NewAWSDiscoveryService(params))
return sd
Expand Down
3 changes: 1 addition & 2 deletions generate/go-generate.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ package main
import (
"errors"
"fmt"
"io/ioutil"
"log"
"os"
"os/exec"
Expand Down Expand Up @@ -117,7 +116,7 @@ type ParseData struct {

func readServerData(filePath string, pd *ParseData, structName string, attName string, groupName string, isList bool) {
typeStruct := fmt.Sprintf("type %s struct {", structName)
dat, err := ioutil.ReadFile(filePath)
dat, err := os.ReadFile(filePath)
if err != nil {
log.Panic(err)
}
Expand Down
10 changes: 5 additions & 5 deletions handlers/cluster.go
Original file line number Diff line number Diff line change
Expand Up @@ -290,17 +290,17 @@ func getClusterSettings(cfg *configuration.Configuration) *models.ClusterSetting
return settings
}

func clusterLogTargetsChanged(old []*models.ClusterLogTarget, new []*models.ClusterLogTarget) bool {
if len(old) == len(new) {
func clusterLogTargetsChanged(oldCLT []*models.ClusterLogTarget, newCLT []*models.ClusterLogTarget) bool {
if len(oldCLT) == len(newCLT) {
eqCtr := 0
for _, oldT := range old {
for _, newT := range new {
for _, oldT := range oldCLT {
for _, newT := range newCLT {
if reflect.DeepEqual(oldT, newT) {
eqCtr++
}
}
}
return !(eqCtr == len(old))
return !(eqCtr == len(oldCLT))
}
return true
}
Expand Down
8 changes: 4 additions & 4 deletions handlers/runtime.go
Original file line number Diff line number Diff line change
Expand Up @@ -237,9 +237,9 @@ func compareObjects(data, ondisk interface{}) []string {
return diff
}

// this returns true if only changable fields have been changed
func compareChanged(changed, changable []string) bool {
if len(changed) > len(changable) {
// this returns true if only changeable fields have been changed
func compareChanged(changed, changeable []string) bool {
if len(changed) > len(changeable) {
return false
}

Expand All @@ -248,7 +248,7 @@ func compareChanged(changed, changable []string) bool {
diff[elem] = true
}

for _, elem := range changable {
for _, elem := range changeable {
delete(diff, elem)
}

Expand Down
Loading

0 comments on commit 5137030

Please sign in to comment.