Skip to content

Commit 5137030

Browse files
oktalzmjuraga
authored andcommitted
BUILD/MEDIUM: lint: apply stricter rules for linting
1 parent 49ba264 commit 5137030

23 files changed

+61
-69
lines changed

.golangci.yml

+7-1
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,9 @@ linters-settings:
44
golint:
55
min-confidence: 0
66
gocyclo:
7-
min-complexity: 25
7+
min-complexity: 42
8+
cyclop:
9+
max-complexity: 42
810
maligned:
911
suggest-new: true
1012
dupl:
@@ -72,6 +74,7 @@ linters:
7274
- tagalign
7375
- depguard
7476

77+
7578
issues:
7679
exclude:
7780
# bugs of typecheck linter
@@ -85,6 +88,9 @@ issues:
8588
- linters:
8689
- gosec
8790
text: "G[501]"
91+
- linters:
92+
- gosec
93+
text: "G[404]"
8894

8995
run:
9096
skip-dirs:

adapters/adapters.go

-1
Original file line numberDiff line numberDiff line change
@@ -103,7 +103,6 @@ func RecoverMiddleware(logger *log.Logger) func(h http.Handler) http.Handler {
103103
if strings.HasPrefix(ct, "application/json") {
104104
w.Header().Set("Content-Type", "application/json")
105105
}
106-
// nolint:errcheck
107106
w.Write(errMsg)
108107
}
109108
}()

client-native/cn.go

-1
Original file line numberDiff line numberDiff line change
@@ -148,7 +148,6 @@ func ConfigureRuntimeClient(ctx context.Context, confClient configuration.Config
148148
return runtimeClient
149149
}
150150
log.Warningf("Error setting up runtime client with sockets: %v : %s", sockets, err.Error())
151-
152151
}
153152
if err != nil {
154153
log.Warning("Runtime API not configured, not using it: " + err.Error())

cmd/dataplaneapi/main.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -235,7 +235,7 @@ func startServer(cfg *configuration.Configuration) (reload configuration.AtomicB
235235
log.Fatalf("Error running HAProxy Data Plane API: %s", err.Error())
236236
}
237237

238-
defer server.Shutdown() // nolint:errcheck
238+
defer server.Shutdown() //nolint:errcheck
239239

240240
return reload
241241
}

configuration/cluster_sync.go

+9-10
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ import (
2626
"encoding/asn1"
2727
"encoding/pem"
2828
"fmt"
29-
"io/ioutil"
29+
"io"
3030
"net/http"
3131
"path"
3232
"strconv"
@@ -146,7 +146,7 @@ func (c *ClusterSync) issueRefreshRequest(url, port, basePath string, nodesPath
146146
json := jsoniter.ConfigCompatibleWithStandardLibrary
147147
bytesRepresentation, _ := json.Marshal(nodeData)
148148

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

163-
body, err := ioutil.ReadAll(resp.Body)
163+
body, err := io.ReadAll(resp.Body)
164164
if err != nil {
165165
return err
166166
}
167-
if resp.StatusCode != 202 {
167+
if resp.StatusCode != http.StatusAccepted {
168168
return fmt.Errorf("status code not proper [%d] %s", resp.StatusCode, string(body))
169169
}
170170
var responseData Node
@@ -366,7 +366,7 @@ func (c *ClusterSync) issueJoinRequest(url, port, basePath string, registerPath
366366
}
367367
defer resp.Body.Close()
368368

369-
body, err := ioutil.ReadAll(resp.Body)
369+
body, err := io.ReadAll(resp.Body)
370370
if err != nil {
371371
return err
372372
}
@@ -385,7 +385,7 @@ func (c *ClusterSync) issueJoinRequest(url, port, basePath string, registerPath
385385
return errCfg
386386
}
387387
// write id to file
388-
errFID := ioutil.WriteFile(c.cfg.HAProxy.NodeIDFile, []byte(responseData.ID), 0o644) // nolint:gosec
388+
errFID := renameio.WriteFile(c.cfg.HAProxy.NodeIDFile, []byte(responseData.ID), 0o644)
389389
if errFID != nil {
390390
return errFID
391391
}
@@ -501,7 +501,7 @@ func (c *ClusterSync) fetchCert() {
501501
apiNodesPath := c.cfg.Cluster.APINodesPath.Load()
502502
id := c.cfg.Cluster.ID.Load()
503503
url = fmt.Sprintf("%s:%d/%s", url, port, strings.TrimLeft(path.Join(apiBasePath, apiNodesPath, id), "/"))
504-
req, err := http.NewRequest("GET", url, nil)
504+
req, err := http.NewRequest(http.MethodGet, url, nil)
505505
if err != nil {
506506
c.activateFetchCert(err)
507507
break
@@ -514,13 +514,13 @@ func (c *ClusterSync) fetchCert() {
514514
c.activateFetchCert(err)
515515
break
516516
}
517-
body, err := ioutil.ReadAll(resp.Body)
517+
body, err := io.ReadAll(resp.Body)
518518
resp.Body.Close()
519519
if err != nil {
520520
c.activateFetchCert(err)
521521
break
522522
}
523-
if resp.StatusCode != 200 {
523+
if resp.StatusCode != http.StatusOK {
524524
c.activateFetchCert(fmt.Errorf("status code not proper [%d] %s", resp.StatusCode, string(body)))
525525
break
526526
}
@@ -605,7 +605,6 @@ func createHTTPClient() *http.Client {
605605
Transport: &http.Transport{
606606
MaxIdleConnsPerHost: 20,
607607
TLSClientConfig: &tls.Config{
608-
//nolint
609608
InsecureSkipVerify: true, // this is deliberate, might only have self signed certificate
610609
},
611610
},

configuration/configuration_storage.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -169,7 +169,7 @@ type StorageDataplaneAPIConfiguration struct {
169169
LogTargets *dpapilog.Targets `yaml:"log_targets,omitempty" hcl:"log_targets,omitempty"`
170170
}
171171

172-
func copyToConfiguration(cfg *Configuration) {
172+
func copyToConfiguration(cfg *Configuration) { //nolint:cyclop,maintidx
173173
cfgStorage := cfg.storage.Get()
174174
if cfgStorage.Name != nil {
175175
cfg.Name.Store(*cfgStorage.Name)

configuration/file-storage-hcl.go

+4-3
Original file line numberDiff line numberDiff line change
@@ -18,9 +18,10 @@ package configuration
1818
import (
1919
"bytes"
2020
"encoding/gob"
21-
"io/ioutil"
21+
"os"
2222
"strings"
2323

24+
"github.com/google/renameio"
2425
"github.com/haproxytech/dataplaneapi/log"
2526
"github.com/hashicorp/hcl"
2627
"github.com/rodaine/hclencoder"
@@ -36,7 +37,7 @@ func (s *StorageHCL) Load(filename string) error {
3637
cfg := &StorageDataplaneAPIConfiguration{}
3738
var hclFile []byte
3839
var err error
39-
hclFile, err = ioutil.ReadFile(filename)
40+
hclFile, err = os.ReadFile(filename)
4041
if err != nil {
4142
return err
4243
}
@@ -102,7 +103,7 @@ func (s *StorageHCL) SaveAs(filename string) error {
102103
return err
103104
}
104105

105-
return ioutil.WriteFile(filename, hcl, 0o644) //nolint:gosec
106+
return renameio.WriteFile(filename, hcl, 0o644)
106107
}
107108

108109
func (s *StorageHCL) Save() error {

configuration/file-storage-yml.go

+2-2
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616
package configuration
1717

1818
import (
19-
"io/ioutil"
19+
"os"
2020

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

35-
yamlFile, err := ioutil.ReadFile(filename)
35+
yamlFile, err := os.ReadFile(filename)
3636
if err != nil {
3737
return err
3838
}

configuration/map_sync.go

+3-4
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,7 @@ func (ms *MapSync) SyncAll(client client_native.HAProxyClient) {
5050
haproxyOptions := Get().HAProxy
5151

5252
d := time.Duration(haproxyOptions.UpdateMapFilesPeriod)
53-
ticker := time.NewTicker(d * time.Second)
53+
ticker := time.NewTicker(d * time.Second) //nolint:durationcheck
5454

5555
for {
5656
select {
@@ -145,9 +145,8 @@ func equalSomeEntries(fEntries, rEntries models.MapEntries, index ...int) bool {
145145
}
146146

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

176175
// dumpRuntimeEntries dumps runtime entries into map file
177-
// Returns true,nil if succeed, otherwise retuns false,error
176+
// Returns true,nil if succeed, otherwise returns false,error
178177
func dumpRuntimeEntries(file string, me models.MapEntries) (bool, error) {
179178
f, err := os.OpenFile(file, os.O_APPEND|os.O_WRONLY|os.O_TRUNC, 0o600)
180179
if err != nil {

configuration/pid.go

+1-2
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,6 @@ package configuration
1717

1818
import (
1919
"fmt"
20-
"io/ioutil"
2120
"os"
2221
"strconv"
2322

@@ -31,7 +30,7 @@ func HandlePIDFile(haproxyOptions HAProxyConfiguration) {
3130
}
3231

3332
if fileExists(haproxyOptions.PIDFile) {
34-
data, err := ioutil.ReadFile(haproxyOptions.PIDFile)
33+
data, err := os.ReadFile(haproxyOptions.PIDFile)
3534
if err != nil {
3635
log.Fatalf("error while reading PID file content: %v", err)
3736
}

configuration/user.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -145,7 +145,7 @@ func (u *Users) getUsersFromUsersListSection(filename, userlistSection string) e
145145
}
146146
data, err := p.Get(parser.UserList, userlistSection, "user")
147147
if err != nil {
148-
return fmt.Errorf("no users configured in %v, error: %s", filename, err.Error())
148+
return fmt.Errorf("no users configured in %v, error: %w", filename, err)
149149
}
150150

151151
return u.setUser(data, cfg.HAProxy.UserListFile)

configuration/watcher.go

+2-3
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ import (
1919
"context"
2020
"crypto/md5"
2121
"fmt"
22-
"io/ioutil"
22+
"os"
2323
"path/filepath"
2424
"strings"
2525

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

9999
func (w *ConfigWatcher) invalidHash() bool {
100-
content, err := ioutil.ReadFile(w.configFile)
100+
content, err := os.ReadFile(w.configFile)
101101
if err != nil {
102102
log.Warningf("Watcher: error reading config file: %s", err.Error())
103103
return false
@@ -107,7 +107,6 @@ func (w *ConfigWatcher) invalidHash() bool {
107107
if len(parts) != 2 || parts[0] != "# _md5hash" {
108108
return true
109109
}
110-
//nolint:gosec
111110
bHash := md5.Sum([]byte(strings.Join(lines[1:], "\n")))
112111
hash := fmt.Sprintf("%x", bHash)
113112
return parts[1] != hash

configure_data_plane.go

+3-5
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@ import (
6565
_ "github.com/GehirnInc/crypt/sha512_crypt"
6666
)
6767

68-
// 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
68+
//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
6969

7070
var (
7171
Version string
@@ -109,7 +109,7 @@ func configureFlags(api *operations.DataPlaneAPI) {
109109
api.CommandLineOptionsGroups = append(api.CommandLineOptionsGroups, syslogOptionsGroup)
110110
}
111111

112-
func configureAPI(api *operations.DataPlaneAPI) http.Handler {
112+
func configureAPI(api *operations.DataPlaneAPI) http.Handler { //nolint:cyclop,maintidx
113113
clientMutex.Lock()
114114
defer clientMutex.Unlock()
115115

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

882881
ra, e := haproxy.NewReloadAgent(raParams)
883882
if e != nil {
884-
// nolint:gocritic
883+
//nolint:gocritic
885884
log.Fatalf("Cannot initialize reload agent: %v", e)
886885
}
887886
return ra
@@ -1015,7 +1014,6 @@ func configureNativeClient(cyx context.Context, haproxyOptions dataplaneapi_conf
10151014
}
10161015

10171016
func handleSignals(ctx context.Context, cancel context.CancelFunc, sigs chan os.Signal, client client_native.HAProxyClient, haproxyOptions dataplaneapi_config.HAProxyConfiguration, users *dataplaneapi_config.Users) {
1018-
//nolint:gosimple
10191017
for {
10201018
select {
10211019
case sig := <-sigs:

discovery/service_discovery.go

-1
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,6 @@ func NewServiceDiscoveries(params ServiceDiscoveriesParams) ServiceDiscoveries {
5858
sd := &serviceDiscoveryImpl{
5959
services: NewInstanceStore(),
6060
}
61-
//nolint
6261
sd.AddService("consul", NewConsulDiscoveryService(params))
6362
_ = sd.AddService("aws", NewAWSDiscoveryService(params))
6463
return sd

generate/go-generate.go

+1-2
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,6 @@ package main
1616
import (
1717
"errors"
1818
"fmt"
19-
"io/ioutil"
2019
"log"
2120
"os"
2221
"os/exec"
@@ -117,7 +116,7 @@ type ParseData struct {
117116

118117
func readServerData(filePath string, pd *ParseData, structName string, attName string, groupName string, isList bool) {
119118
typeStruct := fmt.Sprintf("type %s struct {", structName)
120-
dat, err := ioutil.ReadFile(filePath)
119+
dat, err := os.ReadFile(filePath)
121120
if err != nil {
122121
log.Panic(err)
123122
}

handlers/cluster.go

+5-5
Original file line numberDiff line numberDiff line change
@@ -290,17 +290,17 @@ func getClusterSettings(cfg *configuration.Configuration) *models.ClusterSetting
290290
return settings
291291
}
292292

293-
func clusterLogTargetsChanged(old []*models.ClusterLogTarget, new []*models.ClusterLogTarget) bool {
294-
if len(old) == len(new) {
293+
func clusterLogTargetsChanged(oldCLT []*models.ClusterLogTarget, newCLT []*models.ClusterLogTarget) bool {
294+
if len(oldCLT) == len(newCLT) {
295295
eqCtr := 0
296-
for _, oldT := range old {
297-
for _, newT := range new {
296+
for _, oldT := range oldCLT {
297+
for _, newT := range newCLT {
298298
if reflect.DeepEqual(oldT, newT) {
299299
eqCtr++
300300
}
301301
}
302302
}
303-
return !(eqCtr == len(old))
303+
return !(eqCtr == len(oldCLT))
304304
}
305305
return true
306306
}

handlers/runtime.go

+4-4
Original file line numberDiff line numberDiff line change
@@ -237,9 +237,9 @@ func compareObjects(data, ondisk interface{}) []string {
237237
return diff
238238
}
239239

240-
// this returns true if only changable fields have been changed
241-
func compareChanged(changed, changable []string) bool {
242-
if len(changed) > len(changable) {
240+
// this returns true if only changeable fields have been changed
241+
func compareChanged(changed, changeable []string) bool {
242+
if len(changed) > len(changeable) {
243243
return false
244244
}
245245

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

251-
for _, elem := range changable {
251+
for _, elem := range changeable {
252252
delete(diff, elem)
253253
}
254254

0 commit comments

Comments
 (0)