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

[v1.14] golangci: Enable errorlint #31793

Merged
merged 3 commits into from
Apr 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
1 change: 1 addition & 0 deletions .golangci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,7 @@ issues:
linters:
disable-all: true
enable:
- errorlint
- goerr113
- gofmt
- goimports
Expand Down
4 changes: 2 additions & 2 deletions Makefile.defs
Original file line number Diff line number Diff line change
Expand Up @@ -95,8 +95,8 @@ endif
endif

# renovate: datasource=docker depName=golangci/golangci-lint
GOLANGCILINT_WANT_VERSION = v1.53.3
GOLANGCILINT_IMAGE_SHA = sha256:1e0e2867b387bf68762427db499a963e43582b06819992db205fc31daa75ceea
GOLANGCILINT_WANT_VERSION = v1.55.2
GOLANGCILINT_IMAGE_SHA = sha256:e699df940be1810b08ba6ec050bfc34cc1931027283b5a7f607fb6a67b503876
GOLANGCILINT_VERSION = $(shell golangci-lint version 2>/dev/null)

VERSION = $(shell cat $(dir $(lastword $(MAKEFILE_LIST)))/VERSION)
Expand Down
8 changes: 4 additions & 4 deletions bugtool/cmd/configuration.go
Original file line number Diff line number Diff line change
Expand Up @@ -233,17 +233,17 @@ func defaultCommands(confDir string, cmdDir string, k8sPods []string) []string {
func save(c *BugtoolConfiguration, path string) error {
f, err := os.Create(path)
if err != nil {
return fmt.Errorf("Failed to open file %s for writing: %s", path, err)
return fmt.Errorf("Failed to open file %s for writing: %w", path, err)
}
defer f.Close()

data, err := json.MarshalIndent(c, "", "\t")
if err != nil {
return fmt.Errorf("Cannot marshal config %s", err)
return fmt.Errorf("Cannot marshal config: %w", err)
}
err = os.WriteFile(path, data, 0644)
if err != nil {
return fmt.Errorf("Cannot write config %s", err)
return fmt.Errorf("Cannot write config: %w", err)
}
return nil
}
Expand All @@ -267,7 +267,7 @@ func loadConfigFile(path string) (*BugtoolConfiguration, error) {
func tcInterfaceCommands() ([]string, error) {
ifaces, err := net.Interfaces()
if err != nil {
return nil, fmt.Errorf("could not list network interfaces: %v", err)
return nil, fmt.Errorf("could not list network interfaces: %w", err)
}
commands := []string{}
for _, iface := range ifaces {
Expand Down
16 changes: 8 additions & 8 deletions cilium-health/launch/endpoint.go
Original file line number Diff line number Diff line change
Expand Up @@ -277,16 +277,16 @@ func LaunchAsEndpoint(baseCtx context.Context,
bigTCPConfig.GetGROIPv6MaxSize(), bigTCPConfig.GetGSOIPv6MaxSize(),
bigTCPConfig.GetGROIPv4MaxSize(), bigTCPConfig.GetGSOIPv4MaxSize(), info)
if err != nil {
return nil, fmt.Errorf("Error while creating veth: %s", err)
return nil, fmt.Errorf("Error while creating veth: %w", err)
}

if err = netlink.LinkSetNsFd(epLink, int(netNS.Fd())); err != nil {
return nil, fmt.Errorf("failed to move device %q to health namespace: %s", epIfaceName, err)
return nil, fmt.Errorf("failed to move device %q to health namespace: %w", epIfaceName, err)
}
}

if err = configureHealthInterface(netNS, epIfaceName, ip4Address, ip6Address); err != nil {
return nil, fmt.Errorf("failed configure health interface %q: %s", epIfaceName, err)
return nil, fmt.Errorf("failed configure health interface %q: %w", epIfaceName, err)
}

pidfile := filepath.Join(option.Config.StateDir, PidfilePath)
Expand All @@ -302,7 +302,7 @@ func LaunchAsEndpoint(baseCtx context.Context,
// Create the endpoint
ep, err := endpoint.NewEndpointFromChangeModel(baseCtx, owner, policyGetter, ipcache, proxy, allocator, info)
if err != nil {
return nil, fmt.Errorf("Error while creating endpoint model: %s", err)
return nil, fmt.Errorf("Error while creating endpoint model: %w", err)
}

// Wait until the cilium-health endpoint is running before setting up routes
Expand All @@ -312,15 +312,15 @@ func LaunchAsEndpoint(baseCtx context.Context,
log.WithField("pidfile", pidfile).Debug("cilium-health agent running")
break
} else if time.Now().After(deadline) {
return nil, fmt.Errorf("Endpoint failed to run: %s", err)
return nil, fmt.Errorf("Endpoint failed to run: %w", err)
} else {
time.Sleep(1 * time.Second)
}
}

// Set up the endpoint routes.
if err = configureHealthRouting(info.ContainerName, epIfaceName, node.GetNodeAddressing(), mtuConfig); err != nil {
return nil, fmt.Errorf("Error while configuring routes: %s", err)
return nil, fmt.Errorf("Error while configuring routes: %w", err)
}

if option.Config.IPAM == ipamOption.IPAMENI || option.Config.IPAM == ipamOption.IPAMAlibabaCloud {
Expand All @@ -332,12 +332,12 @@ func LaunchAsEndpoint(baseCtx context.Context,
false,
); err != nil {

return nil, fmt.Errorf("Error while configuring health endpoint rules and routes: %s", err)
return nil, fmt.Errorf("Error while configuring health endpoint rules and routes: %w", err)
}
}

if err := epMgr.AddEndpoint(owner, ep, "Create cilium-health endpoint"); err != nil {
return nil, fmt.Errorf("Error while adding endpoint: %s", err)
return nil, fmt.Errorf("Error while adding endpoint: %w", err)
}

// Give the endpoint a security identity
Expand Down
4 changes: 2 additions & 2 deletions cilium-health/launch/launcher.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,12 +57,12 @@ func Launch(spec *healthApi.Spec) (*CiliumHealth, error) {

ch.server, err = server.NewServer(config)
if err != nil {
return nil, fmt.Errorf("failed to instantiate cilium-health server: %s", err)
return nil, fmt.Errorf("failed to instantiate cilium-health server: %w", err)
}

ch.client, err = client.NewDefaultClient()
if err != nil {
return nil, fmt.Errorf("failed to instantiate cilium-health client: %s", err)
return nil, fmt.Errorf("failed to instantiate cilium-health client: %w", err)
}

go ch.runServer()
Expand Down
2 changes: 1 addition & 1 deletion cilium/cmd/cleanup.go
Original file line number Diff line number Diff line change
Expand Up @@ -390,7 +390,7 @@ func unmountCgroup() error {

log.Info("Trying to unmount ", cgroupRoot)
if err := unix.Unmount(cgroupRoot, unix.MNT_FORCE); err != nil {
return fmt.Errorf("Failed to unmount %s: %s", cgroupRoot, err)
return fmt.Errorf("Failed to unmount %s: %w", cgroupRoot, err)
}
return nil
}
Expand Down
22 changes: 11 additions & 11 deletions cilium/cmd/encrypt_status.go
Original file line number Diff line number Diff line change
Expand Up @@ -80,26 +80,26 @@ func dumpIPsecStatus() (models.EncryptionStatus, error) {
}
xfrmStates, err := netlink.XfrmStateList(netlink.FAMILY_ALL)
if err != nil {
return models.EncryptionStatus{}, fmt.Errorf("cannot get xfrm state: %s", err)
return models.EncryptionStatus{}, fmt.Errorf("cannot get xfrm state: %w", err)
}
keys, err := ipsec.CountUniqueIPsecKeys(xfrmStates)
if err != nil {
return models.EncryptionStatus{}, fmt.Errorf("error counting IPsec keys: %s\n", err)
return models.EncryptionStatus{}, fmt.Errorf("error counting IPsec keys: %w", err)
}
status.Ipsec.KeysInUse = int64(keys)
decryptInts, err := getDecryptionInterfaces()
if err != nil {
return models.EncryptionStatus{}, fmt.Errorf("error getting IPsec decryption interfaces: %s\n", err)
return models.EncryptionStatus{}, fmt.Errorf("error getting IPsec decryption interfaces: %w", err)
}
status.Ipsec.DecryptInterfaces = decryptInts
seqNum, err := maxSequenceNumber()
if err != nil {
return models.EncryptionStatus{}, fmt.Errorf("error getting IPsec max sequence number: %s\n", err)
return models.EncryptionStatus{}, fmt.Errorf("error getting IPsec max sequence number: %w", err)
}
status.Ipsec.MaxSeqNumber = seqNum
errCount, errMap, err := getXfrmStats("")
if err != nil {
return models.EncryptionStatus{}, fmt.Errorf("error getting xfrm stats: %s\n", err)
return models.EncryptionStatus{}, fmt.Errorf("error getting xfrm stats: %w", err)
}
status.Ipsec.ErrorCount = errCount
status.Ipsec.XfrmErrors = errMap
Expand Down Expand Up @@ -129,11 +129,11 @@ func getXfrmStats(mountPoint string) (int64, map[string]int64, error) {
fs, err = procfs.NewFS(mountPoint)
}
if err != nil {
return 0, nil, fmt.Errorf("cannot get a new proc FS: %s", err)
return 0, nil, fmt.Errorf("cannot get a new proc FS: %w", err)
}
stats, err := fs.NewXfrmStat()
if err != nil {
return 0, nil, fmt.Errorf("failed to read xfrm statistics: %s", err)
return 0, nil, fmt.Errorf("failed to read xfrm statistics: %w", err)
}
v := reflect.ValueOf(stats)
countErrors := int64(0)
Expand All @@ -159,7 +159,7 @@ func extractMaxSequenceNumber(ipOutput string) (int64, error) {
if matched != nil {
oseq, err := strconv.ParseInt(line[matched[2]:matched[3]], 16, 64)
if err != nil {
return 0, fmt.Errorf("failed to parse sequence number '%s': %s",
return 0, fmt.Errorf("failed to parse sequence number '%s': %w",
line[matched[2]:matched[3]], err)
}
if oseq > maxSeqNum {
Expand All @@ -173,7 +173,7 @@ func extractMaxSequenceNumber(ipOutput string) (int64, error) {
func maxSequenceNumber() (string, error) {
out, err := exec.Command("ip", "xfrm", "state", "list", "reqid", ciliumReqId).Output()
if err != nil {
return "", fmt.Errorf("cannot get xfrm states: %s", err)
return "", fmt.Errorf("cannot get xfrm states: %w", err)
}
maxSeqNum, err := extractMaxSequenceNumber(string(out))
if err != nil {
Expand Down Expand Up @@ -206,13 +206,13 @@ func isDecryptionInterface(link netlink.Link) (bool, error) {
func getDecryptionInterfaces() ([]string, error) {
links, err := netlink.LinkList()
if err != nil {
return nil, fmt.Errorf("failed to list interfaces: %s", err)
return nil, fmt.Errorf("failed to list interfaces: %w", err)
}
decryptionIfaces := []string{}
for _, link := range links {
itIs, err := isDecryptionInterface(link)
if err != nil {
return nil, fmt.Errorf("failed to list BPF programs for %s: %s", link.Attrs().Name, err)
return nil, fmt.Errorf("failed to list BPF programs for %s: %w", link.Attrs().Name, err)
}
if itIs {
decryptionIfaces = append(decryptionIfaces, link.Attrs().Name)
Expand Down
13 changes: 5 additions & 8 deletions cilium/cmd/fqdn.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
package cmd

import (
"errors"
"fmt"
"os"
"strings"
Expand Down Expand Up @@ -117,10 +118,8 @@ func listFQDNCache() {
}
result, err := client.Policy.GetFqdnCacheID(params)
if err != nil {
switch err := err.(type) {
case *policy.GetFqdnCacheIDNotFound:
// print out empty lookups slice
default:
notFound := &policy.GetFqdnCacheIDNotFound{}
if !errors.As(err, &notFound) {
Fatalf("Error: %s\n", err)
}
} else {
Expand All @@ -139,10 +138,8 @@ func listFQDNCache() {

result, err := client.Policy.GetFqdnCache(params)
if err != nil {
switch err := err.(type) {
case *policy.GetFqdnCacheNotFound:
// print out empty lookups slice
default:
notFound := &policy.GetFqdnCacheNotFound{}
if !errors.As(err, &notFound) {
Fatalf("Error: %s\n", err)
}
} else {
Expand Down
10 changes: 5 additions & 5 deletions cilium/cmd/helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -173,11 +173,11 @@ func expandNestedJSON(result bytes.Buffer) (bytes.Buffer, error) {
m := make(map[string]interface{})
nested := bytes.NewBufferString(unquoted[nestedStart:nestedEnd])
if err := json.NewDecoder(nested).Decode(&m); err != nil {
return bytes.Buffer{}, fmt.Errorf("Failed to decode nested JSON: %s (\n%s\n)", err.Error(), unquoted[nestedStart:nestedEnd])
return bytes.Buffer{}, fmt.Errorf("Failed to decode nested JSON: %w (\n%s\n)", err, unquoted[nestedStart:nestedEnd])
}
decodedBytes, err := json.MarshalIndent(m, indent, " ")
if err != nil {
return bytes.Buffer{}, fmt.Errorf("Cannot marshal nested JSON: %s", err.Error())
return bytes.Buffer{}, fmt.Errorf("Cannot marshal nested JSON: %w", err)
}
decoded = string(decodedBytes)
}
Expand Down Expand Up @@ -274,7 +274,7 @@ func parsePolicyUpdateArgsHelper(args []string, isDeny bool) (*PolicyUpdateArgs,
trafficDirection := args[1]
parsedTd, err := parseTrafficString(trafficDirection)
if err != nil {
return nil, fmt.Errorf("Failed to convert %s to a valid traffic direction: %s", args[1], err)
return nil, fmt.Errorf("Failed to convert %s to a valid traffic direction: %w", args[1], err)
}

mapName, err := endpointToPolicyMapPath(args[0])
Expand All @@ -293,7 +293,7 @@ func parsePolicyUpdateArgsHelper(args []string, isDeny bool) (*PolicyUpdateArgs,
if len(args) > 3 {
pp, err := parseL4PortsSlice([]string{args[3]})
if err != nil {
return nil, fmt.Errorf("Failed to parse L4: %s", err)
return nil, fmt.Errorf("Failed to parse L4: %w", err)
}
port = pp[0].Port
if port != 0 {
Expand Down Expand Up @@ -467,7 +467,7 @@ func parseL4PortsSlice(slice []string) ([]*models.Port, error) {
if !iana.IsSvcName(portStr) {
portUint64, err := strconv.ParseUint(portStr, 10, 16)
if err != nil {
return nil, fmt.Errorf("invalid port %q: %s", portStr, err)
return nil, fmt.Errorf("invalid port %q: %w", portStr, err)
}
port = uint16(portUint64)
portStr = ""
Expand Down
18 changes: 10 additions & 8 deletions cilium/cmd/policy.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ package cmd
import (
"bufio"
"encoding/json"
"errors"
"fmt"
"io"
"os"
Expand Down Expand Up @@ -73,9 +74,9 @@ func getContext(content []byte, offset int64) (int, string, int) {
}

func handleUnmarshalError(f string, content []byte, err error) error {
switch e := err.(type) {
case *json.SyntaxError:
line, ctx, off := getContext(content, e.Offset)
syntaxError := &json.SyntaxError{}
if errors.As(err, &syntaxError) {
line, ctx, off := getContext(content, syntaxError.Offset)

if off <= 1 {
return fmt.Errorf("malformed policy, not JSON?")
Expand All @@ -92,13 +93,14 @@ func handleUnmarshalError(f string, content []byte, err error) error {

return fmt.Errorf("%s:%d: syntax error at offset %d:\n%s\n%s^",
path.Base(f), line, off, ctx, pre)
case *json.UnmarshalTypeError:
line, ctx, off := getContext(content, e.Offset)
}
unmarshalTypeError := &json.UnmarshalTypeError{}
if errors.As(err, &unmarshalTypeError) {
line, ctx, off := getContext(content, unmarshalTypeError.Offset)
return fmt.Errorf("%s:%d: unable to assign value '%s' to type '%v':\n%s\n%*c",
path.Base(f), line, e.Value, e.Type, ctx, off, '^')
default:
return fmt.Errorf("%s: unknown error:%s", path.Base(f), err)
path.Base(f), line, unmarshalTypeError.Value, unmarshalTypeError.Type, ctx, off, '^')
}
return fmt.Errorf("%s: unknown error: %w", path.Base(f), err)
}

func ignoredFile(name string) bool {
Expand Down
2 changes: 1 addition & 1 deletion clustermesh-apiserver/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ func registerHooks(lc cell.Lifecycle, params parameters) error {
func readMockFile(ctx context.Context, path string, backend kvstore.BackendOperations) error {
f, err := os.Open(path)
if err != nil {
return fmt.Errorf("unable to open file %s: %s", path, err)
return fmt.Errorf("unable to open file %s: %w", path, err)
}
defer f.Close()

Expand Down
2 changes: 1 addition & 1 deletion daemon/cmd/cni/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -332,7 +332,7 @@ func (c *cniConfigManager) renderCNIConf() (cniConfig []byte, err error) {
func (c *cniConfigManager) mergeExistingCNIConfig(pluginConfig []byte) ([]byte, error) {
contents, err := c.findCNINetwork(c.config.CNIChainingTarget)
if err != nil {
return nil, fmt.Errorf("could not find existing CNI config for chaining %w", err)
return nil, fmt.Errorf("could not find existing CNI config for chaining: %w", err)
}

// Check to see if we're already inserted; otherwise we should append
Expand Down
4 changes: 2 additions & 2 deletions daemon/cmd/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ func (h *patchConfig) configModify(params PatchConfigParams, resChan chan interf

om, err := option.Config.Opts.Library.ValidateConfigurationMap(cfgSpec.Options)
if err != nil {
msg := fmt.Errorf("Invalid configuration option %s", err)
msg := fmt.Errorf("Invalid configuration option: %w", err)
resChan <- api.Error(PatchConfigBadRequestCode, msg)
return
}
Expand Down Expand Up @@ -89,7 +89,7 @@ func (h *patchConfig) configModify(params PatchConfigParams, resChan chan interf
// Only recompile if configuration has changed.
log.Debug("daemon configuration has changed; recompiling base programs")
if err := d.Datapath().Loader().Reinitialize(d.ctx, d, d.mtuConfig.GetDeviceMTU(), d.Datapath(), d.l7Proxy); err != nil {
msg := fmt.Errorf("Unable to recompile base programs: %s", err)
msg := fmt.Errorf("Unable to recompile base programs: %w", err)
// Revert configuration changes
option.Config.ConfigPatchMutex.Lock()
if policyEnforcementChanged {
Expand Down
6 changes: 3 additions & 3 deletions daemon/cmd/daemon.go
Original file line number Diff line number Diff line change
Expand Up @@ -405,7 +405,7 @@ func newDaemon(ctx context.Context, cleaner *daemonCleanup, params *daemonParams

// Validate the daemon-specific global options.
if err := option.Config.Validate(Vp); err != nil {
return nil, nil, fmt.Errorf("invalid daemon configuration: %s", err)
return nil, nil, fmt.Errorf("invalid daemon configuration: %w", err)
}

// Validate configuration options that depend on other cells.
Expand Down Expand Up @@ -478,7 +478,7 @@ func newDaemon(ctx context.Context, cleaner *daemonCleanup, params *daemonParams

authKeySize, encryptKeyID, err := setupIPSec()
if err != nil {
return nil, nil, fmt.Errorf("unable to setup encryption: %s", err)
return nil, nil, fmt.Errorf("unable to setup encryption: %w", err)
}

var mtuConfig mtu.Configuration
Expand Down Expand Up @@ -1293,7 +1293,7 @@ func (d *Daemon) Close() {
func (d *Daemon) TriggerReloadWithoutCompile(reason string) (*sync.WaitGroup, error) {
log.Debugf("BPF reload triggered from %s", reason)
if err := d.Datapath().Loader().Reinitialize(d.ctx, d, d.mtuConfig.GetDeviceMTU(), d.Datapath(), d.l7Proxy); err != nil {
return nil, fmt.Errorf("unable to recompile base programs from %s: %s", reason, err)
return nil, fmt.Errorf("unable to recompile base programs from %s: %w", reason, err)
}

regenRequest := &regeneration.ExternalRegenerationMetadata{
Expand Down
Loading
Loading