diff --git a/.golangci.yml b/.golangci.yml index 4c617d20d0..4f1cd530f0 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -35,6 +35,7 @@ linters: - nakedret - nilerr - nosprintfhostport + - perfsprint - prealloc - predeclared - promlinter @@ -94,7 +95,6 @@ linters: # - nolintlint # - nonamedreturns # - paralleltest - # - perfsprint # - revive # - rowserrcheck # - sqlclosecheck diff --git a/cmd/crictl/attach.go b/cmd/crictl/attach.go index dd83fad542..ca0806dc8a 100644 --- a/cmd/crictl/attach.go +++ b/cmd/crictl/attach.go @@ -18,6 +18,7 @@ package main import ( "context" + "errors" "fmt" "net/url" @@ -53,7 +54,7 @@ var runtimeAttachCommand = &cli.Command{ Action: func(c *cli.Context) error { id := c.Args().First() if id == "" { - return fmt.Errorf("ID cannot be empty") + return errors.New("ID cannot be empty") } if c.NArg() != 1 { @@ -84,7 +85,7 @@ var runtimeAttachCommand = &cli.Command{ // Attach sends an AttachRequest to server, and parses the returned AttachResponse func Attach(ctx context.Context, client internalapi.RuntimeService, opts attachOptions) error { if opts.id == "" { - return fmt.Errorf("ID cannot be empty") + return errors.New("ID cannot be empty") } request := &pb.AttachRequest{ diff --git a/cmd/crictl/completion.go b/cmd/crictl/completion.go index 23ed485561..ebc5c2f5a1 100644 --- a/cmd/crictl/completion.go +++ b/cmd/crictl/completion.go @@ -17,6 +17,7 @@ limitations under the License. package main import ( + "errors" "fmt" "strings" @@ -136,7 +137,7 @@ Examples: case "zsh": return zshCompletion(c) default: - return fmt.Errorf("only bash, zsh or fish are supported") + return errors.New("only bash, zsh or fish are supported") } }, } diff --git a/cmd/crictl/container.go b/cmd/crictl/container.go index b438a20f1c..ca722dc1bf 100644 --- a/cmd/crictl/container.go +++ b/cmd/crictl/container.go @@ -26,6 +26,7 @@ import ( "path/filepath" goruntime "runtime" "sort" + "strconv" "strings" "time" @@ -201,7 +202,7 @@ var startContainerCommand = &cli.Command{ ArgsUsage: "CONTAINER-ID [CONTAINER-ID...]", Action: func(c *cli.Context) error { if c.NArg() == 0 { - return fmt.Errorf("ID cannot be empty") + return errors.New("ID cannot be empty") } runtimeClient, err := getRuntimeService(c, 0) if err != nil { @@ -258,7 +259,7 @@ var updateContainerCommand = &cli.Command{ }, Action: func(c *cli.Context) error { if c.NArg() == 0 { - return fmt.Errorf("ID cannot be empty") + return errors.New("ID cannot be empty") } runtimeClient, err := getRuntimeService(c, 0) if err != nil { @@ -300,7 +301,7 @@ var stopContainerCommand = &cli.Command{ }, Action: func(c *cli.Context) error { if c.NArg() == 0 { - return fmt.Errorf("ID cannot be empty") + return errors.New("ID cannot be empty") } runtimeClient, err := getRuntimeService(c, 0) if err != nil { @@ -412,7 +413,7 @@ var removeContainerCommand = &cli.Command{ } if errored { - return fmt.Errorf("unable to remove container(s)") + return errors.New("unable to remove container(s)") } return nil }, @@ -440,7 +441,7 @@ var containerStatusCommand = &cli.Command{ }, Action: func(c *cli.Context) error { if c.NArg() == 0 { - return fmt.Errorf("ID cannot be empty") + return errors.New("ID cannot be empty") } runtimeClient, err := getRuntimeService(c, 0) if err != nil { @@ -646,10 +647,10 @@ var checkpointContainerCommand = &cli.Command{ }, Action: func(c *cli.Context) error { if c.NArg() == 0 { - return fmt.Errorf("ID cannot be empty") + return errors.New("ID cannot be empty") } if c.String("export") == "" { - return fmt.Errorf( + return errors.New( "Cannot checkpoint a container without specifying the checkpoint destination. " + "Use --export=/path/to/checkpoint.tar", ) @@ -769,7 +770,7 @@ func CreateContainer( // the returned StartContainerResponse. func StartContainer(client internalapi.RuntimeService, id string) error { if id == "" { - return fmt.Errorf("ID cannot be empty") + return errors.New("ID cannot be empty") } if err := client.StartContainer(context.TODO(), id); err != nil { return err @@ -803,7 +804,7 @@ type updateOptions struct { // the returned UpdateContainerResourcesResponse. func UpdateContainerResources(client internalapi.RuntimeService, id string, opts updateOptions) error { if id == "" { - return fmt.Errorf("ID cannot be empty") + return errors.New("ID cannot be empty") } request := &pb.UpdateContainerResourcesRequest{ ContainerId: id, @@ -839,7 +840,7 @@ func UpdateContainerResources(client internalapi.RuntimeService, id string, opts // the returned StopContainerResponse. func StopContainer(client internalapi.RuntimeService, id string, timeout int64) error { if id == "" { - return fmt.Errorf("ID cannot be empty") + return errors.New("ID cannot be empty") } if err := client.StopContainer(context.TODO(), id, timeout); err != nil { return err @@ -874,7 +875,7 @@ func CheckpointContainer( // the returned RemoveContainerResponse. func RemoveContainer(client internalapi.RuntimeService, id string) error { if id == "" { - return fmt.Errorf("ID cannot be empty") + return errors.New("ID cannot be empty") } if err := client.RemoveContainer(context.TODO(), id); err != nil { return err @@ -922,7 +923,7 @@ func ContainerStatus(client internalapi.RuntimeService, id, output string, tmplS output = "json" } if id == "" { - return fmt.Errorf("ID cannot be empty") + return errors.New("ID cannot be empty") } request := &pb.ContainerStatusRequest{ ContainerId: id, @@ -1088,7 +1089,7 @@ func ListContainers(runtimeClient internalapi.RuntimeService, imageClient intern } podName := getPodNameFromLabels(c.Labels) display.AddRow([]string{id, image, ctm, convertContainerState(c.State), c.Metadata.Name, - fmt.Sprintf("%d", c.Metadata.Attempt), podID, podName}) + strconv.FormatUint(uint64(c.Metadata.Attempt), 10), podID, podName}) continue } diff --git a/cmd/crictl/container_stats.go b/cmd/crictl/container_stats.go index 23cbec307d..bd7f4af2c7 100644 --- a/cmd/crictl/container_stats.go +++ b/cmd/crictl/container_stats.go @@ -18,8 +18,10 @@ package main import ( "context" + "errors" "fmt" "sort" + "strconv" "time" "github.com/docker/go-units" @@ -207,12 +209,12 @@ func (d containerStatsDisplayer) displayStats(ctx context.Context, client intern // Only generate cpuPerc for running container duration := s.GetCpu().GetTimestamp() - old.GetCpu().GetTimestamp() if duration == 0 { - return fmt.Errorf("cpu stat is not updated during sample") + return errors.New("cpu stat is not updated during sample") } cpuPerc = float64(cpu-old.GetCpu().GetUsageCoreNanoSeconds().GetValue()) / float64(duration) * 100 } d.display.AddRow([]string{id, name, fmt.Sprintf("%.2f", cpuPerc), units.HumanSize(float64(mem)), - units.HumanSize(float64(disk)), fmt.Sprintf("%d", inodes)}) + units.HumanSize(float64(disk)), strconv.FormatUint(inodes, 10)}) } d.display.ClearScreen() diff --git a/cmd/crictl/exec.go b/cmd/crictl/exec.go index 1ba9523389..6311c85bfc 100644 --- a/cmd/crictl/exec.go +++ b/cmd/crictl/exec.go @@ -202,7 +202,7 @@ func stream(ctx context.Context, in, tty bool, transport string, url *url.URL) e streamOptions.Stdin = pr } if !in { - return fmt.Errorf("tty=true must be specified with interactive=true") + return errors.New("tty=true must be specified with interactive=true") } t := term.TTY{ In: stdin, @@ -210,7 +210,7 @@ func stream(ctx context.Context, in, tty bool, transport string, url *url.URL) e Raw: true, } if !t.IsTerminalIn() { - return fmt.Errorf("input is not a terminal") + return errors.New("input is not a terminal") } streamOptions.TerminalSizeQueue = t.MonitorSize(t.GetSize()) return t.Safe(func() error { return executor.StreamWithContext(ctx, streamOptions) }) diff --git a/cmd/crictl/image.go b/cmd/crictl/image.go index 68841c001f..67287991a3 100644 --- a/cmd/crictl/image.go +++ b/cmd/crictl/image.go @@ -23,6 +23,7 @@ import ( "regexp" "slices" "sort" + "strconv" "strings" "syscall" @@ -87,7 +88,7 @@ var pullImageCommand = &cli.Command{ Action: func(c *cli.Context) error { imageName := c.Args().First() if imageName == "" { - return fmt.Errorf("Image name cannot be empty") + return errors.New("Image name cannot be empty") } if c.NArg() > 1 { @@ -237,7 +238,7 @@ var listImageCommand = &cli.Command{ } row = append(row, id, size) if showPinned { - row = append(row, fmt.Sprintf("%v", image.Pinned)) + row = append(row, strconv.FormatBool(image.Pinned)) } display.AddRow(row) } @@ -476,7 +477,7 @@ var removeImageCommand = &cli.Command{ } if errored { - return fmt.Errorf("unable to remove the image(s)") + return errors.New("unable to remove the image(s)") } return nil @@ -779,7 +780,7 @@ func ImageStatus(client internalapi.ImageManagerService, image string, verbose b // the returned RemoveImageResponse. func RemoveImage(client internalapi.ImageManagerService, image string) error { if image == "" { - return fmt.Errorf("ImageID cannot be empty") + return errors.New("ImageID cannot be empty") } request := &pb.RemoveImageRequest{Image: &pb.ImageSpec{Image: image}} logrus.Debugf("RemoveImageRequest: %v", request) diff --git a/cmd/crictl/logs.go b/cmd/crictl/logs.go index 58a386e88f..6e64715cd0 100644 --- a/cmd/crictl/logs.go +++ b/cmd/crictl/logs.go @@ -18,8 +18,10 @@ package main import ( "context" + "errors" "fmt" "os" + "strconv" "strings" "time" @@ -70,7 +72,7 @@ var logsCommand = &cli.Command{ Action: func(c *cli.Context) (retErr error) { containerID := c.Args().First() if containerID == "" { - return fmt.Errorf("ID cannot be empty") + return errors.New("ID cannot be empty") } if c.NArg() > 1 { @@ -103,14 +105,14 @@ var logsCommand = &cli.Command{ } logPath := status.GetStatus().GetLogPath() if logPath == "" { - return fmt.Errorf("The container has not set log path") + return errors.New("The container has not set log path") } if previous { containerAttempt := status.GetStatus().GetMetadata().Attempt if containerAttempt == uint32(0) { return fmt.Errorf("Previous terminated container %s not found", status.GetStatus().GetMetadata().Name) } - logPath = fmt.Sprintf("%s%s%s", logPath[:strings.LastIndex(logPath, "/")+1], fmt.Sprint(containerAttempt-1), + logPath = fmt.Sprintf("%s%s%s", logPath[:strings.LastIndex(logPath, "/")+1], strconv.FormatUint(uint64(containerAttempt-1), 10), logPath[strings.LastIndex(logPath, "."):]) } // build a WithCancel context based on cli.context diff --git a/cmd/crictl/main.go b/cmd/crictl/main.go index 2baa244dff..1c68d35017 100644 --- a/cmd/crictl/main.go +++ b/cmd/crictl/main.go @@ -18,6 +18,7 @@ package main import ( "context" + "errors" "fmt" "os" "runtime" @@ -64,7 +65,7 @@ var ( func getRuntimeService(_ *cli.Context, timeout time.Duration) (res internalapi.RuntimeService, err error) { if RuntimeEndpointIsSet && RuntimeEndpoint == "" { - return nil, fmt.Errorf("--runtime-endpoint is not set") + return nil, errors.New("--runtime-endpoint is not set") } logrus.Debug("get runtime connection") @@ -110,7 +111,7 @@ func getRuntimeService(_ *cli.Context, timeout time.Duration) (res internalapi.R func getImageService(*cli.Context) (res internalapi.ImageManagerService, err error) { if ImageEndpoint == "" { if RuntimeEndpointIsSet && RuntimeEndpoint == "" { - return nil, fmt.Errorf("--image-endpoint is not set") + return nil, errors.New("--image-endpoint is not set") } ImageEndpoint = RuntimeEndpoint ImageEndpointIsSet = RuntimeEndpointIsSet diff --git a/cmd/crictl/portforward.go b/cmd/crictl/portforward.go index 8990d7bcee..e508387fa7 100644 --- a/cmd/crictl/portforward.go +++ b/cmd/crictl/portforward.go @@ -18,6 +18,7 @@ package main import ( "context" + "errors" "fmt" "net/http" "net/url" @@ -70,7 +71,7 @@ var runtimePortForwardCommand = &cli.Command{ // PortForward sends an PortForwardRequest to server, and parses the returned PortForwardResponse func PortForward(client internalapi.RuntimeService, opts portforwardOptions) error { if opts.id == "" { - return fmt.Errorf("ID cannot be empty") + return errors.New("ID cannot be empty") } request := &pb.PortForwardRequest{ diff --git a/cmd/crictl/sandbox.go b/cmd/crictl/sandbox.go index 144312a288..31eece6c6d 100644 --- a/cmd/crictl/sandbox.go +++ b/cmd/crictl/sandbox.go @@ -19,9 +19,11 @@ package main import ( "context" "encoding/json" + "errors" "fmt" "log" "sort" + "strconv" "strings" "time" @@ -337,7 +339,7 @@ func RunPodSandbox(client internalapi.RuntimeService, config *pb.PodSandboxConfi // the returned StopPodSandboxResponse. func StopPodSandbox(client internalapi.RuntimeService, id string) error { if id == "" { - return fmt.Errorf("ID cannot be empty") + return errors.New("ID cannot be empty") } if err := client.StopPodSandbox(context.TODO(), id); err != nil { return err @@ -351,7 +353,7 @@ func StopPodSandbox(client internalapi.RuntimeService, id string) error { // the returned RemovePodSandboxResponse. func RemovePodSandbox(client internalapi.RuntimeService, id string) error { if id == "" { - return fmt.Errorf("ID cannot be empty") + return errors.New("ID cannot be empty") } if err := client.RemovePodSandbox(context.TODO(), id); err != nil { return err @@ -384,7 +386,7 @@ func PodSandboxStatus(client internalapi.RuntimeService, id, output string, quie output = "json" } if id == "" { - return fmt.Errorf("ID cannot be empty") + return errors.New("ID cannot be empty") } request := &pb.PodSandboxStatusRequest{ @@ -530,7 +532,7 @@ func ListPodSandboxes(client internalapi.RuntimeService, opts listOptions) error convertPodState(pod.State), pod.Metadata.Name, pod.Metadata.Namespace, - fmt.Sprintf("%d", pod.Metadata.Attempt), + strconv.FormatUint(uint64(pod.Metadata.Attempt), 10), getSandboxesRuntimeHandler(pod), }) continue diff --git a/pkg/benchmark/util.go b/pkg/benchmark/util.go index 947d8c1080..c2a823f293 100644 --- a/pkg/benchmark/util.go +++ b/pkg/benchmark/util.go @@ -18,6 +18,7 @@ package benchmark import ( "encoding/json" + "errors" "fmt" "os" "time" @@ -160,7 +161,7 @@ func (lbrm *LifecycleBenchmarksResultsManager) AwaitAllResults(timeoutSeconds in // Saves the results gathered so far as JSON under the given filepath. func (lbrm *LifecycleBenchmarksResultsManager) WriteResultsFile(filepath string) error { if lbrm.resultsConsumerRunning { - return fmt.Errorf("Results consumer is still running and expecting results.") + return errors.New("Results consumer is still running and expecting results.") } data, err := json.MarshalIndent(lbrm.resultsSet, "", " ") diff --git a/pkg/validate/container.go b/pkg/validate/container.go index 871d1b7005..81a752e40b 100644 --- a/pkg/validate/container.go +++ b/pkg/validate/container.go @@ -20,7 +20,7 @@ import ( "bufio" "context" "errors" - "fmt" + "os" "path/filepath" "regexp" @@ -532,7 +532,7 @@ func createVolumeContainer(rc internalapi.RuntimeService, ic internalapi.ImageMa func createLogContainer(rc internalapi.RuntimeService, ic internalapi.ImageManagerService, prefix string, podID string, podConfig *runtimeapi.PodSandboxConfig) (string, string) { By("create a container with log and name") containerName := prefix + framework.NewUUID() - path := fmt.Sprintf("%s.log", containerName) + path := containerName + ".log" containerConfig := &runtimeapi.ContainerConfig{ Metadata: framework.BuildContainerMetadata(containerName, framework.DefaultAttempt), Image: &runtimeapi.ImageSpec{Image: framework.TestContext.TestImageList.DefaultTestContainerImage}, @@ -546,7 +546,7 @@ func createLogContainer(rc internalapi.RuntimeService, ic internalapi.ImageManag func createKeepLoggingContainer(rc internalapi.RuntimeService, ic internalapi.ImageManagerService, prefix string, podID string, podConfig *runtimeapi.PodSandboxConfig) (string, string) { By("create a container with log and name") containerName := prefix + framework.NewUUID() - path := fmt.Sprintf("%s.log", containerName) + path := containerName + ".log" containerConfig := &runtimeapi.ContainerConfig{ Metadata: framework.BuildContainerMetadata(containerName, framework.DefaultAttempt), Image: &runtimeapi.ImageSpec{Image: framework.TestContext.TestImageList.DefaultTestContainerImage}, diff --git a/pkg/validate/multi_container_linux.go b/pkg/validate/multi_container_linux.go index 149678ca0b..671e630695 100644 --- a/pkg/validate/multi_container_linux.go +++ b/pkg/validate/multi_container_linux.go @@ -18,7 +18,7 @@ package validate import ( "context" - "fmt" + "os" "strings" "time" @@ -138,7 +138,7 @@ func createMultiContainerTestHttpdContainer(rc internalapi.RuntimeService, ic in Metadata: framework.BuildContainerMetadata(containerName, framework.DefaultAttempt), Image: &runtimeapi.ImageSpec{Image: httpdImage}, Linux: &runtimeapi.LinuxContainerConfig{}, - LogPath: fmt.Sprintf("%s.log", containerName), + LogPath: containerName + ".log", } return framework.CreateContainer(rc, ic, containerConfig, podID, podConfig) } @@ -151,7 +151,7 @@ func createMultiContainerTestBusyboxContainer(rc internalapi.RuntimeService, ic Metadata: framework.BuildContainerMetadata(containerName, framework.DefaultAttempt), Image: &runtimeapi.ImageSpec{Image: framework.TestContext.TestImageList.DefaultTestContainerImage}, Command: []string{"sh", "-c", "echo " + defaultLog + "; sleep 1000"}, - LogPath: fmt.Sprintf("%s.log", containerName), + LogPath: containerName + ".log", } return framework.CreateContainer(rc, ic, containerConfig, podID, podConfig) } diff --git a/pkg/validate/security_context_linux.go b/pkg/validate/security_context_linux.go index a3ff64b563..b46387d02c 100644 --- a/pkg/validate/security_context_linux.go +++ b/pkg/validate/security_context_linux.go @@ -307,7 +307,7 @@ var _ = framework.KubeDescribe("Security Context", func() { By("create container for security context SupplementalGroups") supplementalGroup := int64(1234) containerName := "container-with-SupplementalGroups-and-predefined-group-image-test-" + framework.NewUUID() - logPath := fmt.Sprintf("%s.log", containerName) + logPath := containerName + ".log" containerConfig := &runtimeapi.ContainerConfig{ Metadata: framework.BuildContainerMetadata(containerName, framework.DefaultAttempt), Image: &runtimeapi.ImageSpec{Image: testImagePreDefinedGroup}, @@ -806,7 +806,7 @@ var _ = framework.KubeDescribe("Security Context", func() { }) createContainerWithNoNewPrivs := func(name string, noNewPrivs bool, uid int64) string { - By(fmt.Sprintf("create container %s", name)) + By("create container " + name) containerConfig := &runtimeapi.ContainerConfig{ Metadata: framework.BuildContainerMetadata(name, framework.DefaultAttempt), Image: &runtimeapi.ImageSpec{Image: noNewPrivsImage}, @@ -818,7 +818,7 @@ var _ = framework.KubeDescribe("Security Context", func() { }, }, }, - LogPath: fmt.Sprintf("%s.log", name), + LogPath: name + ".log", } containerID := framework.CreateContainer(rc, ic, containerConfig, podID, podConfig) @@ -962,13 +962,13 @@ var _ = framework.KubeDescribe("Security Context", func() { // matchContainerOutput matches log line in container logs. func matchContainerOutput(podConfig *runtimeapi.PodSandboxConfig, name, output string) { By("check container output") - verifyLogContents(podConfig, fmt.Sprintf("%s.log", name), output, stdoutType) + verifyLogContents(podConfig, name+".log", output, stdoutType) } // matchContainerOutputRe matches log line in container logs using the provided regular expression pattern. func matchContainerOutputRe(podConfig *runtimeapi.PodSandboxConfig, name, pattern string) { By("check container output") - verifyLogContentsRe(podConfig, fmt.Sprintf("%s.log", name), pattern, stdoutType) + verifyLogContentsRe(podConfig, name+".log", pattern, stdoutType) } // createRunAsUserContainer creates the container with specified RunAsUser in ContainerConfig. @@ -1034,7 +1034,7 @@ func createRunAsGroupContainer(rc internalapi.RuntimeService, ic internalapi.Ima RunAsGroup: &gidV, }, }, - LogPath: fmt.Sprintf("%s.log", containerName), + LogPath: containerName + ".log", } return framework.CreateContainer(rc, ic, containerConfig, podID, podConfig), expectedLogMessage } @@ -1105,7 +1105,7 @@ func createNamespaceContainer(rc internalapi.RuntimeService, ic internalapi.Imag func createReadOnlyRootfsContainer(rc internalapi.RuntimeService, ic internalapi.ImageManagerService, podID string, podConfig *runtimeapi.PodSandboxConfig, prefix string, readonly bool) (string, string) { By("create ReadOnlyRootfs container") containerName := prefix + framework.NewUUID() - path := fmt.Sprintf("%s.log", containerName) + path := containerName + ".log" containerConfig := &runtimeapi.ContainerConfig{ Metadata: framework.BuildContainerMetadata(containerName, framework.DefaultAttempt), Image: &runtimeapi.ImageSpec{Image: framework.TestContext.TestImageList.DefaultTestContainerImage}, @@ -1224,7 +1224,7 @@ func createAndCheckHostNetwork(rc internalapi.RuntimeService, ic internalapi.Ima By("create a container in the sandbox") command := []string{"sh", "-c", "netstat -ln"} containerName := "container-with-HostNetwork-test-" + framework.NewUUID() - path := fmt.Sprintf("%s.log", containerName) + path := containerName + ".log" containerID, _, logPath := createNamespaceContainer(rc, ic, podID, podConfig, containerName, framework.TestContext.TestImageList.DefaultTestContainerImage, namespaceOptions, command, path) By("start container") @@ -1234,7 +1234,7 @@ func createAndCheckHostNetwork(rc internalapi.RuntimeService, ic internalapi.Ima Eventually(func() error { log := parseLogLine(podConfig, logPath) for _, msg := range log { - if strings.Contains(string(msg.log), fmt.Sprintf(":%s", hostNetworkPort)) { + if strings.Contains(string(msg.log), ":"+hostNetworkPort) { if hostNetwork { return nil } @@ -1419,7 +1419,7 @@ func runUserNamespaceContainer( UserSpecifiedImage: framework.TestContext.TestImageList.DefaultTestContainerImage, }, Command: []string{"cat", "/proc/self/uid_map"}, - LogPath: fmt.Sprintf("%s.log", containerName), + LogPath: containerName + ".log", Linux: &runtimeapi.LinuxContainerConfig{ SecurityContext: &runtimeapi.LinuxContainerSecurityContext{ NamespaceOptions: podConfig.Linux.SecurityContext.NamespaceOptions,