diff --git a/.golangci.yml b/.golangci.yml new file mode 100644 index 000000000..e90d26d05 --- /dev/null +++ b/.golangci.yml @@ -0,0 +1,17 @@ +linters: + enable: + - errcheck + - gofmt + - govet + - ineffassign + - unconvert + - staticcheck + - gocyclo + enable-all: false +linters-settings: + gocyclo: + # Minimal code complexity to report. + # Default: 30 (but we recommend 10-20) + min-complexity: 100 +run: + timeout: 20m diff --git a/pkg/Makefile b/pkg/Makefile index 2af25b9a0..3b78e60ef 100644 --- a/pkg/Makefile +++ b/pkg/Makefile @@ -3,51 +3,21 @@ GOPATH := $(shell go env GOPATH) all: build -getdeps: - @echo "Installing golint" && go install github.com/golangci/golangci-lint/cmd/golangci-lint@v1.55.0 - @echo "Installing gocyclo" && go install github.com/fzipp/gocyclo/cmd/gocyclo@latest - @echo "Installing deadcode" && go install github.com/remyoudompheng/go-misc/deadcode@latest - @echo "Installing misspell" && go install github.com/client9/misspell/cmd/misspell@latest - @echo "Installing ineffassign" && go install github.com/gordonklaus/ineffassign@latest - @echo "Installing staticcheck" && go install honnef.co/go/tools/cmd/staticcheck@latest - -verifiers: vet fmt lint cyclo spelling static #deadcode - -vet: - @echo "Running $@" - @go vet -atomic -bool -copylocks -nilfunc -printf -rangeloops -unreachable -unsafeptr -unusedresult ./... +all: getdeps test -fmt: - @echo "Running $@" - @gofmt -d . +getdeps: + @echo "Installing golangci-lint" && go get github.com/golangci/golangci-lint/cmd/golangci-lint && go install github.com/golangci/golangci-lint/cmd/golangci-lint + go mod tidy lint: @echo "Running $@" - @${GOPATH}/bin/golangci-lint run - -ineffassign: - @echo "Running $@" - @${GOPATH}/bin/ineffassign . - -cyclo: - @echo "Running $@" - @${GOPATH}/bin/gocyclo -over 100 . - -deadcode: - @echo "Running $@" - @${GOPATH}/bin/deadcode -test $(shell go list ./...) || true - -spelling: - @${GOPATH}/bin/misspell -i "monitord,forumla,etherent" -error `find .` - -static: - @${GOPATH}/bin/staticcheck -- ./... + @${GOPATH}/bin/golangci-lint run -c ../.golangci.yml check: test -test: verifiers build +test: lint build go test -vet=off -v $(shell go list ./... | grep -Ev "stubs|network" ) -testrace: verifiers build +testrace: lint build go test -vet=off -v $(shell go list ./... | grep -Ev "stubs|network" ) generate: diff --git a/pkg/container/container.go b/pkg/container/container.go index 10130d7f6..8d7e547bd 100644 --- a/pkg/container/container.go +++ b/pkg/container/container.go @@ -426,7 +426,7 @@ func (c *Module) start(ns, id string) error { ctx := namespaces.WithNamespace(context.Background(), ns) - container, err := client.LoadContainer(ctx, string(id)) + container, err := client.LoadContainer(ctx, id) if err != nil { return err } @@ -615,7 +615,7 @@ func (c *Module) Delete(ns string, id pkg.ContainerID) error { _ = task.Kill(ctx, syscall.SIGTERM) select { case <-exitC: - case <-time.After(time.Duration(shutdownTimeout)): + case <-time.After(shutdownTimeout): log.Debug().Str("id", string(id)).Int("signal", int(syscall.SIGKILL)).Msg("sending signal") _ = task.Kill(ctx, syscall.SIGKILL) select { diff --git a/pkg/container/stats/stats.go b/pkg/container/stats/stats.go index 967e02f70..90e3e802d 100644 --- a/pkg/container/stats/stats.go +++ b/pkg/container/stats/stats.go @@ -46,7 +46,7 @@ func Monitor(addr string, ns string, id string, backend io.WriteCloser) error { ctx := namespaces.WithNamespace(context.Background(), ns) - container, err := client.LoadContainer(ctx, string(id)) + container, err := client.LoadContainer(ctx, id) if err != nil { log.Error().Err(err).Msg("metric container") return err diff --git a/pkg/crypto/crypto_test.go b/pkg/crypto/crypto_test.go index c6ac7c8d2..c0c21714a 100644 --- a/pkg/crypto/crypto_test.go +++ b/pkg/crypto/crypto_test.go @@ -77,7 +77,8 @@ func TestPyNACLCompatibilityEncryption(t *testing.T) { sk := ed25519.NewKeyFromSeed(seed) chiper := "" - fmt.Sscanf("0bfe9e3b9ce17fe6d570b165ea2a01034326b8c81d5f2c5384c8fe886552f074ec43017465598c4f5a857b495b445be46c3df48d14878bd0b1b907", "%x", &chiper) + _, err := fmt.Sscanf("0bfe9e3b9ce17fe6d570b165ea2a01034326b8c81d5f2c5384c8fe886552f074ec43017465598c4f5a857b495b445be46c3df48d14878bd0b1b907", "%x", &chiper) + require.NoError(t, err) decrypted, err := Decrypt([]byte(chiper), sk) require.NoError(t, err) diff --git a/pkg/flist/cleanup.go b/pkg/flist/cleanup.go index 1dc078d21..0c24ef8b4 100644 --- a/pkg/flist/cleanup.go +++ b/pkg/flist/cleanup.go @@ -59,7 +59,7 @@ func (f *flistModule) cleanCache(now time.Time, age time.Duration) error { if sys, ok := sys.(*syscall.Stat_t); ok { // int64 cast required for arm32 targets - atime := time.Unix(int64(sys.Atim.Sec), int64(sys.Atim.Nsec)) + atime := time.Unix(sys.Atim.Sec, sys.Atim.Nsec) if now.Sub(atime) > age { if err := os.Remove(path); err != nil { diff --git a/pkg/gateway/gateway.go b/pkg/gateway/gateway.go index 33136241b..b4a4aff53 100644 --- a/pkg/gateway/gateway.go +++ b/pkg/gateway/gateway.go @@ -532,7 +532,7 @@ func (g *gatewayModule) configPath(name string) string { func (g *gatewayModule) validateNameContract(name string, twinID uint32) error { - contractID, subErr := g.substrateGateway.GetContractIDByNameRegistration(context.Background(), string(name)) + contractID, subErr := g.substrateGateway.GetContractIDByNameRegistration(context.Background(), name) if subErr.IsCode(pkg.CodeNotFound) { return ErrContractNotReserved } @@ -633,7 +633,7 @@ func (g *gatewayModule) setupRouting(ctx context.Context, wlID string, fqdn stri backend := config.Backends[0] - if err := zos.Backend(backend).Valid(config.TLSPassthrough); err != nil { + if err := backend.Valid(config.TLSPassthrough); err != nil { return errors.Wrapf(err, "failed to validate backend '%s'", backend) } diff --git a/pkg/gridtypes/id.go b/pkg/gridtypes/id.go index d90917854..40c43db3e 100644 --- a/pkg/gridtypes/id.go +++ b/pkg/gridtypes/id.go @@ -71,7 +71,7 @@ func (i WorkloadID) Unique(n string) string { b = b[:13] } - return string(b) + return b } // IsValidName validates workload name diff --git a/pkg/gridtypes/workload_test.go b/pkg/gridtypes/workload_test.go index cf0f8d8c6..645fea3af 100644 --- a/pkg/gridtypes/workload_test.go +++ b/pkg/gridtypes/workload_test.go @@ -21,7 +21,7 @@ func TestTimestamp(t *testing.T) { exp, err := json.Marshal(n) require.NoError(err) - err = json.Unmarshal([]byte(exp), &v) + err = json.Unmarshal(exp, &v) require.NoError(err) require.Equal(Timestamp(n.Unix()), v) diff --git a/pkg/gridtypes/zos/network.go b/pkg/gridtypes/zos/network.go index 854cfbc41..972af84ea 100644 --- a/pkg/gridtypes/zos/network.go +++ b/pkg/gridtypes/zos/network.go @@ -32,7 +32,7 @@ func NetworkID(twin uint32, network gridtypes.Name) NetID { if len(b) > 13 { b = b[:13] } - return NetID(string(b)) + return NetID(b) } func NetworkIDFromWorkloadID(wl gridtypes.WorkloadID) (NetID, error) { diff --git a/pkg/network/mycelium/mycelium.go b/pkg/network/mycelium/mycelium.go index 482922029..4caff618a 100644 --- a/pkg/network/mycelium/mycelium.go +++ b/pkg/network/mycelium/mycelium.go @@ -183,7 +183,7 @@ func (s *MyceliumServer) InspectMycelium() (inspection MyceliumInspection, err e // IP return the address in the 400::/7 subnet allocated by mycelium func (m *MyceliumInspection) IP() net.IP { - return net.IP(m.Address) + return m.Address } // Subnet return the 400::/64 subnet allocated by mycelium diff --git a/pkg/network/network_test.go b/pkg/network/network_test.go index 1d6ac47fd..6c08d15e8 100644 --- a/pkg/network/network_test.go +++ b/pkg/network/network_test.go @@ -30,7 +30,8 @@ func TestKeys(t *testing.T) { strEncrypted := fmt.Sprintf("%x", encrypted) strDecrypted := "" - fmt.Sscanf(strEncrypted, "%x", &strDecrypted) + _, err = fmt.Sscanf(strEncrypted, "%x", &strDecrypted) + require.NoError(t, err) decrypted, err := crypto.Decrypt([]byte(strDecrypted), sk) require.NoError(t, err) diff --git a/pkg/network/networker.go b/pkg/network/networker.go index ccef4a6d0..34ba6bc20 100644 --- a/pkg/network/networker.go +++ b/pkg/network/networker.go @@ -360,7 +360,7 @@ func (n *networker) SetupPrivTap(networkID pkg.NetID, name string) (ifc string, } func (n *networker) TapExists(name string) (bool, error) { - log.Info().Str("tap-name", string(name)).Msg("Checking if tap interface exists") + log.Info().Str("tap-name", name).Msg("Checking if tap interface exists") tapIface, err := tapName(name) if err != nil { @@ -372,7 +372,7 @@ func (n *networker) TapExists(name string) (bool, error) { // RemoveTap in the network resource. func (n *networker) RemoveTap(name string) error { - log.Info().Str("tap-name", string(name)).Msg("Removing tap interface") + log.Info().Str("tap-name", name).Msg("Removing tap interface") tapIface, err := tapName(name) if err != nil { @@ -390,7 +390,7 @@ func (n *networker) PublicIPv4Support() bool { // reservation id. It is hooked to the public bridge. The name of the tap // interface is returned func (n *networker) SetupPubTap(name string) (string, error) { - log.Info().Str("pubtap-name", string(name)).Msg("Setting up public tap interface") + log.Info().Str("pubtap-name", name).Msg("Setting up public tap interface") if !n.ndmz.SupportsPubIPv4() { return "", errors.New("can't create public tap on this node") @@ -408,7 +408,7 @@ func (n *networker) SetupPubTap(name string) (string, error) { // SetupMyceliumTap creates a new mycelium tap device attached to this network resource with deterministic IP address func (n *networker) SetupMyceliumTap(name string, netID zos.NetID, config zos.MyceliumIP) (tap pkg.PlanetaryTap, err error) { - log.Info().Str("tap-name", string(name)).Msg("Setting up mycelium tap interface") + log.Info().Str("tap-name", name).Msg("Setting up mycelium tap interface") network, err := n.networkOf(netID) if err != nil { @@ -452,7 +452,7 @@ func (n *networker) SetupMyceliumTap(name string, netID zos.NetID, config zos.My // SetupYggTap sets up a tap device in the host namespace for the yggdrasil ip func (n *networker) SetupYggTap(name string) (tap pkg.PlanetaryTap, err error) { - log.Info().Str("tap-name", string(name)).Msg("Setting up yggdrasil tap interface") + log.Info().Str("tap-name", name).Msg("Setting up yggdrasil tap interface") tapIface, err := tapName(name) if err != nil { @@ -486,7 +486,7 @@ func (n *networker) SetupYggTap(name string) (tap pkg.PlanetaryTap, err error) { // PubTapExists checks if the tap device for the public network exists already func (n *networker) PubTapExists(name string) (bool, error) { - log.Info().Str("pubtap-name", string(name)).Msg("Checking if public tap interface exists") + log.Info().Str("pubtap-name", name).Msg("Checking if public tap interface exists") tapIface, err := pubTapName(name) if err != nil { @@ -499,7 +499,7 @@ func (n *networker) PubTapExists(name string) (bool, error) { // RemovePubTap removes the public tap device from the host namespace // of the networkID func (n *networker) RemovePubTap(name string) error { - log.Info().Str("pubtap-name", string(name)).Msg("Removing public tap interface") + log.Info().Str("pubtap-name", name).Msg("Removing public tap interface") tapIface, err := pubTapName(name) if err != nil { @@ -660,7 +660,7 @@ func (n *networker) RemovePubIPFilter(filterName string) error { // DisconnectPubTap disconnects the public tap from the network. The interface // itself is not removed and will need to be cleaned up later func (n *networker) DisconnectPubTap(name string) error { - log.Info().Str("pubtap-name", string(name)).Msg("Disconnecting public tap interface") + log.Info().Str("pubtap-name", name).Msg("Disconnecting public tap interface") tapIfaceName, err := pubTapName(name) if err != nil { return errors.Wrap(err, "could not get network namespace tap device name") diff --git a/pkg/network/nr/net_resource.go b/pkg/network/nr/net_resource.go index ac5088c84..43b126fa6 100644 --- a/pkg/network/nr/net_resource.go +++ b/pkg/network/nr/net_resource.go @@ -644,7 +644,7 @@ func (nr *NetResource) wgPeers() ([]*wireguard.Peer, error) { } wgPeer := &wireguard.Peer{ - PublicKey: string(peer.WGPublicKey), + PublicKey: peer.WGPublicKey, AllowedIPs: allowedIPs, Endpoint: peer.Endpoint, } diff --git a/pkg/perf/iperf/iperf_task.go b/pkg/perf/iperf/iperf_task.go index df4a7f80e..bc12ad1b2 100644 --- a/pkg/perf/iperf/iperf_task.go +++ b/pkg/perf/iperf/iperf_task.go @@ -154,7 +154,7 @@ func (t *IperfTest) runIperfTest(ctx context.Context, clientIP string, tcp bool) operation := func() error { res := runIperfCommand(ctx, opts) if res.Error == errServerBusy { - return fmt.Errorf(errServerBusy) + return errors.New(errServerBusy) } report = res diff --git a/pkg/perf/publicip/publicip_task.go b/pkg/perf/publicip/publicip_task.go index 9b8499e94..51595cecc 100644 --- a/pkg/perf/publicip/publicip_task.go +++ b/pkg/perf/publicip/publicip_task.go @@ -207,7 +207,7 @@ func isLeastValidNode(ctx context.Context, farmID uint32, substrateGateway *stub } for _, node := range nodes { - if node.NodeID >= uint32(nodeID) { + if node.NodeID >= nodeID { continue } n, err := substrateGateway.GetNode(ctx, node.NodeID) diff --git a/pkg/power/ethtool.go b/pkg/power/ethtool.go index 85a28a51f..6480ed8c6 100644 --- a/pkg/power/ethtool.go +++ b/pkg/power/ethtool.go @@ -57,7 +57,7 @@ func valueOfFlag(output []byte, flag Flag) (string, error) { if len(parts) != 2 { return "", fmt.Errorf("invalid ethtool output format (%s)", line) } - return strings.TrimSpace(string(parts[1])), nil + return strings.TrimSpace(parts[1]), nil } return "", ErrFlagNotFound diff --git a/pkg/provision/auth.go b/pkg/provision/auth.go index 6a6ae0ffd..80eca8669 100644 --- a/pkg/provision/auth.go +++ b/pkg/provision/auth.go @@ -40,7 +40,7 @@ func (s *substrateTwins) GetKey(id uint32) ([]byte, error) { key := user.Account.PublicKey() s.mem.Add(id, key) - return []byte(key), nil + return key, nil } type substrateAdmins struct { diff --git a/pkg/provision/engine.go b/pkg/provision/engine.go index 5880fa27e..42a4a2d36 100644 --- a/pkg/provision/engine.go +++ b/pkg/provision/engine.go @@ -572,7 +572,7 @@ func (e *NativeEngine) validate(ctx context.Context, dl *gridtypes.Deployment, n return ctx, fmt.Errorf("substrate is not configured in engine") } - contract, subErr := e.substrateGateway.GetContract(ctx, uint64(dl.ContractID)) + contract, subErr := e.substrateGateway.GetContract(ctx, dl.ContractID) if subErr.IsError() { return nil, errors.Wrap(subErr.Err, "failed to get deployment contract") } diff --git a/pkg/provision/storage.fs/storage.go b/pkg/provision/storage.fs/storage.go index ffb630fad..ee32085ac 100644 --- a/pkg/provision/storage.fs/storage.go +++ b/pkg/provision/storage.fs/storage.go @@ -283,7 +283,7 @@ func (s *Fs) byTwin(twin uint32) ([]uint64, error) { continue } - ids = append(ids, uint64(id)) + ids = append(ids, id) } return ids, nil diff --git a/pkg/qsfsd/cleanup.go b/pkg/qsfsd/cleanup.go index 2a8a7a140..4c7f16301 100644 --- a/pkg/qsfsd/cleanup.go +++ b/pkg/qsfsd/cleanup.go @@ -59,11 +59,11 @@ func (q *QSFS) checkDeadQSFSs(ctx context.Context, state *failedQSFSState) error } for _, path := range paths { wlID := filepath.Base(path) - metrics, err := q.qsfsMetrics(ctx, string(wlID)) + metrics, err := q.qsfsMetrics(ctx, wlID) if err != nil { - log.Err(err).Str("id", string(wlID)).Msg("couldn't get qsfs metrics") - state.metricsFailureCount[string(wlID)] += 1 - if state.metricsFailureCount[string(wlID)] >= 10 { + log.Err(err).Str("id", wlID).Msg("couldn't get qsfs metrics") + state.metricsFailureCount[wlID] += 1 + if state.metricsFailureCount[wlID] >= 10 { q.Unmount(wlID) state.delete(wlID) } diff --git a/pkg/qsfsd/qsfs.go b/pkg/qsfsd/qsfs.go index a77db2bc6..387fc1d49 100644 --- a/pkg/qsfsd/qsfs.go +++ b/pkg/qsfsd/qsfs.go @@ -169,7 +169,7 @@ func (q *QSFS) Mount(wlID string, cfg zos.QuantumSafeFS) (info pkg.QSFSInfo, err if containerErr != nil { log.Error().Err(containerErr).Msg("Failed to read container logs") } - err = errors.Wrapf(lerr, fmt.Sprintf("Container Logs:\n%s", logs)) + err = errors.Wrapf(lerr, "Container Logs:\n%s", logs) return } log.Debug().Str("duration", time.Since(t).String()).Msg("waiting for qsfs deployment took") diff --git a/pkg/storage/storage_test.go b/pkg/storage/storage_test.go index 91b3ba66d..30b6ddd31 100644 --- a/pkg/storage/storage_test.go +++ b/pkg/storage/storage_test.go @@ -416,7 +416,7 @@ func TestCacheResize(t *testing.T) { Excl: 1, }, } - vol.On("Limit", uint64(cacheSize)).Return(nil) + vol.On("Limit", cacheSize).Return(nil) err := m.checkAndResizeCache(&vol, cacheSize) require.NoError(t, err) @@ -444,7 +444,7 @@ func TestCacheResize(t *testing.T) { Excl: 0, // no files }, } - vol.On("Limit", uint64(cacheSize)).Return(nil) + vol.On("Limit", cacheSize).Return(nil) err = m.checkAndResizeCache(&vol, cacheSize) require.NoError(t, err) @@ -468,7 +468,7 @@ func TestCacheResize(t *testing.T) { Excl: 91, }, } - vol.On("Limit", uint64(100+cacheSize)).Return(nil) + vol.On("Limit", 100+cacheSize).Return(nil) err = m.checkAndResizeCache(&vol, cacheSize) require.NoError(t, err) diff --git a/pkg/vm/manager.go b/pkg/vm/manager.go index 42524dac2..8a9aa51f9 100644 --- a/pkg/vm/manager.go +++ b/pkg/vm/manager.go @@ -322,7 +322,7 @@ func (m *Module) withLogs(path string, err error) error { return errors.Wrapf(err, "failed to tail machine logs: %s", tailErr) } - return errors.Wrapf(err, string(logs)) + return errors.Wrap(err, logs) } func (m *Module) checkDevicesUsed(devices []string) error { diff --git a/pkg/zdb/admin.go b/pkg/zdb/admin.go index 3832bf274..84f3a4482 100644 --- a/pkg/zdb/admin.go +++ b/pkg/zdb/admin.go @@ -1,7 +1,7 @@ package zdb import ( - "fmt" + "errors" "strings" "github.com/gomodule/redigo/redis" @@ -18,7 +18,7 @@ func (c *clientImpl) CreateNamespace(name string) error { return err } if ok != "OK" { - return fmt.Errorf(ok) + return errors.New(ok) } return nil } @@ -49,7 +49,7 @@ func (c *clientImpl) DeleteNamespace(name string) error { return err } if ok != "OK" { - return fmt.Errorf(ok) + return errors.New(ok) } return nil } @@ -70,7 +70,7 @@ func (c *clientImpl) NamespaceSetSize(name string, size uint64) error { return err } if ok != "OK" { - return fmt.Errorf(ok) + return errors.New(ok) } return nil } @@ -84,7 +84,7 @@ func (c *clientImpl) NamespaceSetPassword(name, password string) error { return err } if ok != "OK" { - return fmt.Errorf(ok) + return errors.New(ok) } return nil } @@ -98,7 +98,7 @@ func (c *clientImpl) NamespaceSetMode(name, mode string) error { return err } if ok != "OK" { - return fmt.Errorf(ok) + return errors.New(ok) } return nil } @@ -116,7 +116,7 @@ func (c *clientImpl) NamespaceSetLock(name string, lock bool) error { return err } if ok != "OK" { - return fmt.Errorf(ok) + return errors.New(ok) } return nil } @@ -136,7 +136,7 @@ func (c *clientImpl) NamespaceSetPublic(name string, public bool) error { return err } if ok != "OK" { - return fmt.Errorf(ok) + return errors.New(ok) } return nil } diff --git a/tools/zos-update-worker/Makefile b/tools/zos-update-worker/Makefile index 70d5e2dbd..9714904a3 100644 --- a/tools/zos-update-worker/Makefile +++ b/tools/zos-update-worker/Makefile @@ -8,41 +8,14 @@ ldflags='-w -s -X $(version).Branch=$(branch) -X $(version).Revision=$(revision) all: getdeps test getdeps: - @echo "Installing staticcheck" && go get -u honnef.co/go/tools/cmd/staticcheck && go install honnef.co/go/tools/cmd/staticcheck - @echo "Installing gocyclo" && go get -u github.com/fzipp/gocyclo/cmd/gocyclo && go install github.com/fzipp/gocyclo/cmd/gocyclo - @echo "Installing deadcode" && go get -u github.com/remyoudompheng/go-misc/deadcode && go install github.com/remyoudompheng/go-misc/deadcode - @echo "Installing misspell" && go get -u github.com/client9/misspell/cmd/misspell && go install github.com/client9/misspell/cmd/misspell - @echo "Installing golangci-lint" && go install github.com/golangci/golangci-lint/cmd/golangci-lint@v1.54.2 + @echo "Installing golangci-lint" && go get github.com/golangci/golangci-lint/cmd/golangci-lint && go install github.com/golangci/golangci-lint/cmd/golangci-lint go mod tidy - -verifiers: fmt lint cyclo deadcode spelling staticcheck - -fmt: - @echo "Running $@" - @gofmt -d . - lint: @echo "Running $@" - @${GOPATH}/bin/golangci-lint run - -cyclo: - @echo "Running $@" - @${GOPATH}/bin/gocyclo -over 100 . - -deadcode: - @echo "Running $@" - @${GOPATH}/bin/deadcode -test $(shell go list ./...) || true - -spelling: - @echo "Running $@" - @${GOPATH}/bin/misspell -i monitord -error `find .` - -staticcheck: - @echo "Running $@" - @${GOPATH}/bin/staticcheck -- ./... + golangci-lint run -c ../../.golangci.yml -test: verifiers +test: lint go test -v -vet=off ./... benchmarks: @@ -53,7 +26,7 @@ coverage: clean go test -v -vet=off ./... -coverprofile=coverage/coverage.out go tool cover -html=coverage/coverage.out -o coverage/coverage.html -testrace: verifiers +testrace: lint go test -v -race -vet=off ./... run: