diff --git a/.golangci.yml b/.golangci.yml index 9bf79536c81f..2a249a67b565 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -17,6 +17,7 @@ linters: - gofmt # Checks whether code was gofmt-ed - goheader # Checks is file headers matche a given pattern - intrange # Checking for loops that could use an integer range + - perfsprint # Checks for faster fmt.Sprintf alternatives - revive # Stricter drop-in replacement for golint - testifylint # Checks usage of github.com/stretchr/testify - unconvert # Checks for unnecessary type conversions diff --git a/cmd/airgap/listimages.go b/cmd/airgap/listimages.go index e28c60e3853c..1291de8a22e7 100644 --- a/cmd/airgap/listimages.go +++ b/cmd/airgap/listimages.go @@ -17,6 +17,7 @@ limitations under the License. package airgap import ( + "errors" "fmt" "github.com/k0sproject/k0s/pkg/airgap" @@ -39,7 +40,7 @@ func NewAirgapListImagesCmd() *cobra.Command { } if opts.EnableDynamicConfig { - return fmt.Errorf("dynamic config is not supported for airgap list-images") + return errors.New("dynamic config is not supported for airgap list-images") } clusterConfig, err := opts.K0sVars.NodeConfig() diff --git a/cmd/api/api.go b/cmd/api/api.go index 303a9ccd5256..d4e079e1cf8e 100644 --- a/cmd/api/api.go +++ b/cmd/api/api.go @@ -20,6 +20,7 @@ import ( "context" "crypto/tls" "encoding/json" + "errors" "fmt" "net/http" "os" @@ -221,7 +222,7 @@ func (c *command) isValidToken(ctx context.Context, token string, usage string) return false } - secretName := fmt.Sprintf("bootstrap-token-%s", parts[0]) + secretName := "bootstrap-token-" + parts[0] secret, err := c.client.CoreV1().Secrets("kube-system").Get(ctx, secretName, metav1.GetOptions{}) if err != nil { logrus.Errorf("failed to get bootstrap token: %s", err.Error()) @@ -241,10 +242,12 @@ func (c *command) isValidToken(ctx context.Context, token string, usage string) } func (c *command) authMiddleware(next http.Handler, usage string) http.Handler { + unauthorizedErr := errors.New("go away") + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { auth := r.Header.Get("Authorization") if auth == "" { - sendError(fmt.Errorf("go away"), w, http.StatusUnauthorized) + sendError(unauthorizedErr, w, http.StatusUnauthorized) return } @@ -252,11 +255,11 @@ func (c *command) authMiddleware(next http.Handler, usage string) http.Handler { if len(parts) == 2 { token := parts[1] if !c.isValidToken(r.Context(), token, usage) { - sendError(fmt.Errorf("go away"), w, http.StatusUnauthorized) + sendError(unauthorizedErr, w, http.StatusUnauthorized) return } } else { - sendError(fmt.Errorf("go away"), w, http.StatusUnauthorized) + sendError(unauthorizedErr, w, http.StatusUnauthorized) return } diff --git a/cmd/backup/backup_unix.go b/cmd/backup/backup_unix.go index c0447a701166..1db3fef39df5 100644 --- a/cmd/backup/backup_unix.go +++ b/cmd/backup/backup_unix.go @@ -19,6 +19,7 @@ limitations under the License. package backup import ( + "errors" "fmt" "io" "os" @@ -56,7 +57,7 @@ func NewBackupCmd() *cobra.Command { return err } if nodeConfig.Spec.Storage.Etcd.IsExternalClusterUsed() { - return fmt.Errorf("command 'k0s backup' does not support external etcd cluster") + return errors.New("command 'k0s backup' does not support external etcd cluster") } return c.backup(savePath, cmd.OutOrStdout()) }, diff --git a/cmd/controller/certificates.go b/cmd/controller/certificates.go index 84fe17be4717..5eb4cb4c7d61 100644 --- a/cmd/controller/certificates.go +++ b/cmd/controller/certificates.go @@ -20,16 +20,18 @@ import ( "context" "errors" "fmt" + "net" + "net/url" + "os" + "path/filepath" + "strconv" + "github.com/k0sproject/k0s/internal/pkg/file" "github.com/k0sproject/k0s/internal/pkg/users" "github.com/k0sproject/k0s/pkg/apis/k0s/v1beta1" "github.com/k0sproject/k0s/pkg/certificate" "github.com/k0sproject/k0s/pkg/config" "github.com/k0sproject/k0s/pkg/constant" - "net" - "os" - "path/filepath" - "strconv" "k8s.io/client-go/tools/clientcmd" clientcmdapi "k8s.io/client-go/tools/clientcmd/api" @@ -66,7 +68,7 @@ func (c *Certificates) Init(ctx context.Context) error { c.CACert = string(cert) // Changing the URL here also requires changes in the "k0s kubeconfig admin" subcommand. apiAddress := net.JoinHostPort(c.ClusterSpec.API.Address, strconv.Itoa(c.ClusterSpec.API.Port)) - kubeConfigAPIUrl := fmt.Sprintf("https://%s", apiAddress) + kubeConfigAPIUrl := (&url.URL{Scheme: "https", Host: apiAddress}).String() apiServerUID, err := users.LookupUID(constant.ApiserverUser) if err != nil { @@ -197,7 +199,7 @@ func (c *Certificates) Init(ctx context.Context) error { "kubernetes.default", "kubernetes.default.svc", "kubernetes.default.svc.cluster", - fmt.Sprintf("kubernetes.svc.%s", c.ClusterSpec.Network.ClusterDomain), + "kubernetes.svc." + c.ClusterSpec.Network.ClusterDomain, "localhost", "127.0.0.1", } diff --git a/cmd/controller/controller.go b/cmd/controller/controller.go index 84594f1b367f..96d8d5863053 100644 --- a/cmd/controller/controller.go +++ b/cmd/controller/controller.go @@ -24,6 +24,7 @@ import ( "net" "os" "os/signal" + "path" "path/filepath" "slices" "syscall" @@ -58,6 +59,7 @@ import ( "github.com/k0sproject/k0s/pkg/token" "github.com/sirupsen/logrus" "github.com/spf13/cobra" + "k8s.io/apimachinery/pkg/fields" "k8s.io/client-go/rest" ) @@ -94,7 +96,7 @@ func NewControllerCmd() *cobra.Command { c.TokenArg = args[0] } if c.TokenArg != "" && c.TokenFile != "" { - return fmt.Errorf("you can only pass one token argument either as a CLI argument 'k0s controller [join-token]' or as a flag 'k0s controller --token-file [path]'") + return errors.New("you can only pass one token argument either as a CLI argument 'k0s controller [join-token]' or as a flag 'k0s controller --token-file [path]'") } if err := c.ControllerOptions.Normalize(); err != nil { return err @@ -659,9 +661,11 @@ func (c *command) startWorker(ctx context.Context, profile string, nodeConfig *v wc := workercmd.Command(*(*config.CLIOptions)(c)) wc.TokenArg = bootstrapConfig wc.WorkerProfile = profile - wc.Labels = append(wc.Labels, fmt.Sprintf("%s=control-plane", constant.K0SNodeRoleLabel)) + wc.Labels = append(wc.Labels, fields.OneTermEqualSelector(constant.K0SNodeRoleLabel, "control-plane").String()) if !c.SingleNode && !c.NoTaints { - wc.Taints = append(wc.Taints, fmt.Sprintf("%s/master=:NoSchedule", constant.NodeRoleLabelNamespace)) + key := path.Join(constant.NodeRoleLabelNamespace, "master") + taint := fields.OneTermEqualSelector(key, ":NoSchedule") + wc.Taints = append(wc.Taints, taint.String()) } return wc.Start(ctx) } diff --git a/cmd/etcd/etcd.go b/cmd/etcd/etcd.go index cba0647c520d..7b14ae291216 100644 --- a/cmd/etcd/etcd.go +++ b/cmd/etcd/etcd.go @@ -17,6 +17,7 @@ limitations under the License. package etcd import ( + "errors" "fmt" "github.com/k0sproject/k0s/pkg/apis/k0s/v1beta1" @@ -46,7 +47,7 @@ func NewEtcdCmd() *cobra.Command { return fmt.Errorf("wrong storage type: %s", nodeConfig.Spec.Storage.Type) } if nodeConfig.Spec.Storage.Etcd.IsExternalClusterUsed() { - return fmt.Errorf("command 'k0s etcd' does not support external etcd cluster") + return errors.New("command 'k0s etcd' does not support external etcd cluster") } return nil }, diff --git a/cmd/etcd/leave.go b/cmd/etcd/leave.go index 45fea772232c..2985ee2adf8c 100644 --- a/cmd/etcd/leave.go +++ b/cmd/etcd/leave.go @@ -21,6 +21,7 @@ import ( "fmt" "net" "net/url" + "strconv" "github.com/k0sproject/k0s/pkg/config" "github.com/k0sproject/k0s/pkg/etcd" @@ -52,7 +53,7 @@ func etcdLeaveCmd() *cobra.Command { peerAddress := nodeConfig.Spec.Storage.Etcd.PeerAddress if peerAddressArg == "" { if peerAddress == "" { - return fmt.Errorf("can't leave etcd cluster: this node doesn't have an etcd peer address, check the k0s configuration or use --peer-address") + return errors.New("can't leave etcd cluster: this node doesn't have an etcd peer address, check the k0s configuration or use --peer-address") } } else { peerAddress = peerAddressArg @@ -73,13 +74,13 @@ func etcdLeaveCmd() *cobra.Command { if err := etcdClient.DeleteMember(ctx, peerID); err != nil { logrus. WithField("peerURL", peerURL). - WithField("peerID", fmt.Sprintf("%x", peerID)). + WithField("peerID", strconv.FormatUint(peerID, 16)). Errorf("Failed to delete node from cluster") return err } logrus. - WithField("peerID", fmt.Sprintf("%x", peerID)). + WithField("peerID", strconv.FormatUint(peerID, 16)). Info("Successfully deleted") return nil }, diff --git a/cmd/install/install.go b/cmd/install/install.go index 5c96ca9b5e3e..b9310f2a82e6 100644 --- a/cmd/install/install.go +++ b/cmd/install/install.go @@ -17,6 +17,7 @@ limitations under the License. package install import ( + "errors" "fmt" "os" @@ -54,7 +55,7 @@ func NewInstallCmd() *cobra.Command { // - Sets up startup and logging for k0s. func (c *command) setup(role string, args []string, installFlags *installFlags) error { if os.Geteuid() != 0 { - return fmt.Errorf("this command must be run as root") + return errors.New("this command must be run as root") } nodeConfig, err := c.K0sVars.NodeConfig() diff --git a/cmd/kubectl/kubectl.go b/cmd/kubectl/kubectl.go index d53fda6bc436..5fa636b5df66 100644 --- a/cmd/kubectl/kubectl.go +++ b/cmd/kubectl/kubectl.go @@ -17,6 +17,7 @@ limitations under the License. package kubectl import ( + "errors" "fmt" "os" "os/exec" @@ -171,7 +172,7 @@ func handleKubectlPlugins(kubectlCmd *cobra.Command) { func fallbackToK0sKubeconfig(cmd *cobra.Command) error { kubeconfigFlag := cmd.Flags().Lookup("kubeconfig") if kubeconfigFlag == nil { - return fmt.Errorf("kubeconfig flag not found") + return errors.New("kubeconfig flag not found") } if kubeconfigFlag.Changed { diff --git a/cmd/reset/reset.go b/cmd/reset/reset.go index 8215fc140142..9e40c220e392 100644 --- a/cmd/reset/reset.go +++ b/cmd/reset/reset.go @@ -19,7 +19,6 @@ package reset import ( "fmt" "os" - "runtime" "github.com/k0sproject/k0s/pkg/cleanup" "github.com/k0sproject/k0s/pkg/component/status" @@ -36,9 +35,6 @@ func NewResetCmd() *cobra.Command { Use: "reset", Short: "Uninstall k0s. Must be run as root (or with sudo)", RunE: func(cmd *cobra.Command, args []string) error { - if runtime.GOOS == "windows" { - return fmt.Errorf("currently not supported on windows") - } opts, err := config.GetCmdOpts(cmd) if err != nil { return err diff --git a/cmd/restore/restore_unix.go b/cmd/restore/restore_unix.go index eb8f5ac3b4bb..08845f726534 100644 --- a/cmd/restore/restore_unix.go +++ b/cmd/restore/restore_unix.go @@ -19,6 +19,7 @@ limitations under the License. package restore import ( + "errors" "fmt" "io" "os" @@ -74,7 +75,7 @@ func NewRestoreCmd() *cobra.Command { func (c *command) restore(path string, out io.Writer) error { if os.Geteuid() != 0 { - return fmt.Errorf("this command must be run as root") + return errors.New("this command must be run as root") } k0sStatus, _ := status.GetStatusInfo(c.K0sVars.StatusSocketPath) diff --git a/cmd/root.go b/cmd/root.go index dbd9a7bae6e6..25e207d9abb0 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -18,9 +18,9 @@ package cmd import ( "errors" - "fmt" "net/http" "os" + "runtime" "github.com/k0sproject/k0s/cmd/airgap" "github.com/k0sproject/k0s/cmd/api" @@ -91,10 +91,16 @@ func NewRootCmd() *cobra.Command { cmd.AddCommand(install.NewInstallCmd()) cmd.AddCommand(kubeconfig.NewKubeConfigCmd()) cmd.AddCommand(kubectl.NewK0sKubectlCmd()) - cmd.AddCommand(reset.NewResetCmd()) + if runtime.GOOS == "linux" { + // Currently only supported on Linux + cmd.AddCommand(reset.NewResetCmd()) + } cmd.AddCommand(restore.NewRestoreCmd()) cmd.AddCommand(start.NewStartCmd()) - cmd.AddCommand(status.NewStatusCmd()) + if runtime.GOOS == "linux" { + // Currently only supported on Linux + cmd.AddCommand(status.NewStatusCmd()) + } cmd.AddCommand(stop.NewStopCmd()) cmd.AddCommand(sysinfo.NewSysinfoCmd()) cmd.AddCommand(token.NewTokenCmd()) @@ -128,7 +134,7 @@ func newDocsCmd() *cobra.Command { case "man": return doc.GenManTree(NewRootCmd(), &doc.GenManHeader{Title: "k0s", Section: "1"}, "./man") } - return fmt.Errorf("invalid format") + return errors.New("invalid format") }, } } diff --git a/cmd/start/start.go b/cmd/start/start.go index c19d8b25d3f6..b07c5aca1bb9 100644 --- a/cmd/start/start.go +++ b/cmd/start/start.go @@ -17,7 +17,7 @@ limitations under the License. package start import ( - "fmt" + "errors" "os" "github.com/k0sproject/k0s/pkg/install" @@ -32,7 +32,7 @@ func NewStartCmd() *cobra.Command { Short: "Start the k0s service configured on this host. Must be run as root (or with sudo)", RunE: func(cmd *cobra.Command, args []string) error { if os.Geteuid() != 0 { - return fmt.Errorf("this command must be run as root") + return errors.New("this command must be run as root") } svc, err := install.InstalledService() if err != nil { @@ -40,7 +40,7 @@ func NewStartCmd() *cobra.Command { } status, _ := svc.Status() if status == service.StatusRunning { - return fmt.Errorf("already running") + return errors.New("already running") } return svc.Start() }, diff --git a/cmd/status/status.go b/cmd/status/status.go index eecf1a1cf73b..25c9aac9141c 100644 --- a/cmd/status/status.go +++ b/cmd/status/status.go @@ -21,7 +21,6 @@ import ( "fmt" "io" "path/filepath" - "runtime" "github.com/k0sproject/k0s/pkg/component/status" "github.com/k0sproject/k0s/pkg/config" @@ -41,9 +40,6 @@ func NewStatusCmd() *cobra.Command { if err != nil { return err } - if runtime.GOOS == "windows" { - return fmt.Errorf("currently not supported on windows") - } statusInfo, err := status.GetStatusInfo(opts.K0sVars.StatusSocketPath) if err != nil { @@ -75,9 +71,6 @@ func NewStatusSubCmdComponents() *cobra.Command { if err != nil { return err } - if runtime.GOOS == "windows" { - return fmt.Errorf("currently not supported on windows") - } fmt.Fprintln(cmd.ErrOrStderr(), "!!! per component status is not yet finally ready, information here might be not full yet") state, err := status.GetComponentStatus(opts.K0sVars.StatusSocketPath, maxCount) if err != nil { diff --git a/cmd/stop/stop.go b/cmd/stop/stop.go index bcb00fc3e988..57c51ff09a24 100644 --- a/cmd/stop/stop.go +++ b/cmd/stop/stop.go @@ -17,7 +17,7 @@ limitations under the License. package stop import ( - "fmt" + "errors" "os" "github.com/k0sproject/k0s/pkg/install" @@ -32,7 +32,7 @@ func NewStopCmd() *cobra.Command { Short: "Stop the k0s service configured on this host. Must be run as root (or with sudo)", RunE: func(cmd *cobra.Command, args []string) error { if os.Geteuid() != 0 { - return fmt.Errorf("this command must be run as root") + return errors.New("this command must be run as root") } svc, err := install.InstalledService() if err != nil { @@ -43,7 +43,7 @@ func NewStopCmd() *cobra.Command { return err } if status == service.StatusStopped { - return fmt.Errorf("already stopped") + return errors.New("already stopped") } return svc.Stop() }, diff --git a/cmd/token/preshared.go b/cmd/token/preshared.go index 4e25a534be0f..de1e2329abb6 100644 --- a/cmd/token/preshared.go +++ b/cmd/token/preshared.go @@ -19,6 +19,7 @@ package token import ( "bufio" "bytes" + "errors" "fmt" "io" "os" @@ -55,10 +56,10 @@ func preSharedCmd() *cobra.Command { return err } if certPath == "" { - return fmt.Errorf("please, provide --cert argument") + return errors.New("please, provide --cert argument") } if joinURL == "" { - return fmt.Errorf("please, provide --url argument") + return errors.New("please, provide --url argument") } return nil diff --git a/cmd/worker/worker.go b/cmd/worker/worker.go index 778f8a11f9e9..2f9be2410ea3 100644 --- a/cmd/worker/worker.go +++ b/cmd/worker/worker.go @@ -74,7 +74,7 @@ func NewWorkerCmd() *cobra.Command { } if c.TokenArg != "" && c.TokenFile != "" { - return fmt.Errorf("you can only pass one token argument either as a CLI argument 'k0s worker [token]' or as a flag 'k0s worker --token-file [path]'") + return errors.New("you can only pass one token argument either as a CLI argument 'k0s worker [token]' or as a flag 'k0s worker --token-file [path]'") } if err := (&sysinfo.K0sSysinfoSpec{ diff --git a/hack/tool/cmd/aws/provision/provision.go b/hack/tool/cmd/aws/provision/provision.go index 4eb55fadd319..5a9f1b51e424 100644 --- a/hack/tool/cmd/aws/provision/provision.go +++ b/hack/tool/cmd/aws/provision/provision.go @@ -17,6 +17,7 @@ package provision import ( "context" + "errors" "fmt" "os" "os/exec" @@ -100,7 +101,7 @@ func bugfixK0sctlNullImages(k0sctlConfigFile string) error { cmd.Stdout = os.Stdout if err := cmd.Run(); err != nil { - return fmt.Errorf("failed to post-process k0sctl.yaml") + return errors.New("failed to post-process k0sctl.yaml") } return nil diff --git a/hack/tool/cmd/root.go b/hack/tool/cmd/root.go index 0f2d3c60b799..329c397e1bbf 100644 --- a/hack/tool/cmd/root.go +++ b/hack/tool/cmd/root.go @@ -16,7 +16,7 @@ limitations under the License. package cmd import ( - "fmt" + "errors" "os" "tool/cmd/aws" @@ -29,7 +29,7 @@ func newCommandRoot() *cobra.Command { Use: "tool", Short: "tool is the tool", RunE: func(cmd *cobra.Command, args []string) error { - return fmt.Errorf("insufficient arguments") + return errors.New("insufficient arguments") }, } diff --git a/hack/tool/pkg/terraform/terraform.go b/hack/tool/pkg/terraform/terraform.go index 7b78c025b30a..d839bd15183e 100644 --- a/hack/tool/pkg/terraform/terraform.go +++ b/hack/tool/pkg/terraform/terraform.go @@ -56,7 +56,7 @@ func Output(ctx context.Context, modulePath string) (map[string]tfexec.OutputMet return nil, fmt.Errorf("unable to create 'terraform' instance: %w", err) } - if err := tf.Init(ctx, tfexec.BackendConfig(fmt.Sprintf("path=%s", constant.TerraformStateFile))); err != nil { + if err := tf.Init(ctx, tfexec.BackendConfig("path="+constant.TerraformStateFile)); err != nil { return nil, fmt.Errorf("unable to init terraform in '%s': %w", scriptDir, err) } @@ -75,7 +75,7 @@ func execute[OT any](ctx context.Context, workDir string, handler Handler[OT], o tf.SetStdout(os.Stdout) tf.SetLogger(log.Default()) - if err := tf.Init(ctx, tfexec.BackendConfig(fmt.Sprintf("path=%s", constant.TerraformStateFile))); err != nil { + if err := tf.Init(ctx, tfexec.BackendConfig("path="+constant.TerraformStateFile)); err != nil { return fmt.Errorf("unable to init terraform in '%s': %w", workDir, err) } diff --git a/internal/http/filename.go b/internal/http/filename.go index 562e17564153..0b60cbfd6868 100644 --- a/internal/http/filename.go +++ b/internal/http/filename.go @@ -105,17 +105,17 @@ func fileNameFromContentDisposition(contentDisposition string) (string, error) { return sanitizeFileName(fileName) } - return "", fmt.Errorf("no filename parameter") + return "", errors.New("no filename parameter") } func fileNameFromRequestPath(requestPath string) (string, error) { if requestPath == "" { - return "", fmt.Errorf("request path is empty") + return "", errors.New("request path is empty") } fileName := path.Base(requestPath) if fileName == "/" { - return "", fmt.Errorf("request path has no base") + return "", errors.New("request path has no base") } return sanitizeFileName(fileName) diff --git a/internal/oci/download.go b/internal/oci/download.go index 7a7be1fe0a72..e97933d0a233 100644 --- a/internal/oci/download.go +++ b/internal/oci/download.go @@ -144,7 +144,7 @@ func findArtifactDescriptor(all []ocispec.Descriptor, opts downloadOptions) (oci } } if opts.artifactName == "" { - return ocispec.Descriptor{}, fmt.Errorf("no artifact descriptors found") + return ocispec.Descriptor{}, errors.New("no artifact descriptors found") } return ocispec.Descriptor{}, fmt.Errorf("artifact %q not found", opts.artifactName) } diff --git a/internal/oci/download_test.go b/internal/oci/download_test.go index b860e5e104e2..673adb9f9b08 100644 --- a/internal/oci/download_test.go +++ b/internal/oci/download_test.go @@ -85,7 +85,7 @@ func TestDownload(t *testing.T) { opts = append(opts, oci.WithDockerAuth( oci.DockerConfig{ Auths: map[string]oci.DockerConfigEntry{ - addr: entry, + addr.Host: entry, }, }, )) @@ -100,7 +100,7 @@ func TestDownload(t *testing.T) { } buf := bytes.NewBuffer(nil) - url := fmt.Sprintf("%s/repository/artifact:latest", addr) + url := path.Join(addr.Host, "repository", "artifact:latest") err := oci.Download(context.TODO(), url, buf, opts...) if tt.Expected != "" { require.NoError(t, err) @@ -117,8 +117,8 @@ func TestDownload(t *testing.T) { // startOCIMockServer starts a mock server that will respond to the given test. // this mimics the behavior of the real OCI registry. This function returns the // address of the server. -func startOCIMockServer(t *testing.T, tname string, test testFile) string { - var serverAddr string +func startOCIMockServer(t *testing.T, tname string, test testFile) url.URL { + var serverURL *url.URL starter := httptest.NewTLSServer if test.PlainHTTP { @@ -157,7 +157,7 @@ func startOCIMockServer(t *testing.T, tname string, test testFile) string { proto = "http" } - header := fmt.Sprintf(`Bearer realm="%s://%s/token"`, proto, serverAddr) + header := fmt.Sprintf(`Bearer realm="%s://%s/token"`, proto, serverURL.Host) w.Header().Add("WWW-Authenticate", header) w.WriteHeader(http.StatusUnauthorized) return @@ -195,8 +195,7 @@ func startOCIMockServer(t *testing.T, tname string, test testFile) string { ) t.Cleanup(server.Close) - u, err := url.Parse(server.URL) + serverURL, err := url.Parse(server.URL) require.NoError(t, err) - serverAddr = u.Host - return serverAddr + return *serverURL } diff --git a/internal/pkg/net/hostport.go b/internal/pkg/net/hostport.go index 2606a7f0d494..4cf22750b9eb 100644 --- a/internal/pkg/net/hostport.go +++ b/internal/pkg/net/hostport.go @@ -37,7 +37,7 @@ func (h *HostPort) Port() uint16 { return h.port } func NewHostPort(host string, port uint16) (*HostPort, error) { if !govalidator.IsIP(host) && !govalidator.IsDNSName(host) { - return nil, fmt.Errorf("host is neither an IP address nor a DNS name") + return nil, errors.New("host is neither an IP address nor a DNS name") } if port == 0 { diff --git a/internal/pkg/sysinfo/probes/disk.go b/internal/pkg/sysinfo/probes/disk.go index 1986dbab6daf..4a654528b027 100644 --- a/internal/pkg/sysinfo/probes/disk.go +++ b/internal/pkg/sysinfo/probes/disk.go @@ -16,10 +16,6 @@ limitations under the License. package probes -import ( - "fmt" -) - // AssertDiskSpace asserts a minimum amount of free disk space. func AssertFreeDiskSpace(parent ParentProbe, fsPath string, minFree uint64) { parent.Set("disk:"+fsPath, func(path ProbePath, current Probe) Probe { @@ -44,9 +40,9 @@ type assertDiskSpace struct { func (a *assertDiskSpace) desc() ProbeDesc { var description string if a.isRelative { - description = fmt.Sprintf("Relative disk space available for %s", a.fsPath) + description = "Relative disk space available for " + a.fsPath } else { - description = fmt.Sprintf("Disk space available for %s", a.fsPath) + description = "Disk space available for " + a.fsPath } return NewProbeDesc(description, a.path) } diff --git a/internal/pkg/sysinfo/probes/executables.go b/internal/pkg/sysinfo/probes/executables.go index a3a72777cf0d..204fb24ca0c5 100644 --- a/internal/pkg/sysinfo/probes/executables.go +++ b/internal/pkg/sysinfo/probes/executables.go @@ -17,14 +17,13 @@ limitations under the License. package probes import ( - "fmt" "os/exec" ) func AssertExecutableInPath(p Probes, executable string) { - p.Set(fmt.Sprintf("executableInPath:%s", executable), func(path ProbePath, _ Probe) Probe { + p.Set("executableInPath:"+executable, func(path ProbePath, _ Probe) Probe { return ProbeFn(func(r Reporter) error { - desc := NewProbeDesc(fmt.Sprintf("Executable in PATH: %s", executable), path) + desc := NewProbeDesc("Executable in PATH: "+executable, path) path, err := exec.LookPath(executable) if err != nil { return r.Warn(desc, ErrorProp(err), "") diff --git a/internal/pkg/sysinfo/probes/filesystem.go b/internal/pkg/sysinfo/probes/filesystem.go index 9c7d0ac7aa16..5c5d101aafde 100644 --- a/internal/pkg/sysinfo/probes/filesystem.go +++ b/internal/pkg/sysinfo/probes/filesystem.go @@ -16,10 +16,6 @@ limitations under the License. package probes -import ( - "fmt" -) - // AssertFileSystem asserts a minimum amount of free disk space. func AssertFileSystem(parent ParentProbe, fsPath string) { parent.Set("filesystem:"+fsPath, func(path ProbePath, current Probe) Probe { @@ -33,5 +29,5 @@ type assertFileSystem struct { } func (a *assertFileSystem) desc() ProbeDesc { - return NewProbeDesc(fmt.Sprintf("File system of %s", a.fsPath), a.path) + return NewProbeDesc("File system of "+a.fsPath, a.path) } diff --git a/internal/pkg/sysinfo/probes/linux/cgroup_v2.go b/internal/pkg/sysinfo/probes/linux/cgroup_v2.go index 2b14eda45c5b..ce0b88ec9627 100644 --- a/internal/pkg/sysinfo/probes/linux/cgroup_v2.go +++ b/internal/pkg/sysinfo/probes/linux/cgroup_v2.go @@ -77,7 +77,7 @@ func (g *cgroupV2) detectDevicesController() (cgroupControllerAvailable, error) case errors.Is(err, os.ErrPermission) && os.Geteuid() != 0: return cgroupControllerAvailable{true, "unknown", "insufficient permissions, try with elevated permissions"}, nil case errors.Is(err, unix.EROFS): - return cgroupControllerAvailable{true, "unknown", fmt.Sprintf("read-only file system: %s", g.mountPoint)}, nil + return cgroupControllerAvailable{true, "unknown", "read-only file system: " + g.mountPoint}, nil case eBPFProgramUnsupported(err): return cgroupControllerAvailable{false, err.Error(), ""}, nil @@ -190,7 +190,7 @@ func (g *cgroupV2) detectFreezerController() (cgroupControllerAvailable, error) return cgroupControllerAvailable{true, "unknown", "insufficient permissions, try with elevated permissions"}, nil } if errors.Is(err, unix.EROFS) && os.Geteuid() != 0 { - return cgroupControllerAvailable{true, "unknown", fmt.Sprintf("read-only file system: %s", g.mountPoint)}, nil + return cgroupControllerAvailable{true, "unknown", "read-only file system: " + g.mountPoint}, nil } return cgroupControllerAvailable{}, fmt.Errorf("failed to create temporary cgroup: %w", err) diff --git a/internal/pkg/sysinfo/probes/linux/kernel.go b/internal/pkg/sysinfo/probes/linux/kernel.go index d9f7271b3dcb..232c58b5f929 100644 --- a/internal/pkg/sysinfo/probes/linux/kernel.go +++ b/internal/pkg/sysinfo/probes/linux/kernel.go @@ -180,7 +180,7 @@ func ensureKConfig(config string) kConfig { } func (c kConfig) String() string { - return fmt.Sprintf("CONFIG_%s", string(c)) + return "CONFIG_" + string(c) } type kConfigProbe struct { @@ -242,7 +242,7 @@ func (k *kConfigProbe) probe(reporter probes.Reporter, option kConfigOption) err msg := "" if len(k.alternativeKConfigs) > 0 { - msg = fmt.Sprintf("also tried %s", strings.Join(alsoTried, ", ")) + msg = "also tried " + strings.Join(alsoTried, ", ") } if k.require { diff --git a/internal/pkg/sysinfo/probes/linux/procfs.go b/internal/pkg/sysinfo/probes/linux/procfs.go index 74363bf11f02..a70267150289 100644 --- a/internal/pkg/sysinfo/probes/linux/procfs.go +++ b/internal/pkg/sysinfo/probes/linux/procfs.go @@ -32,7 +32,7 @@ func (l *LinuxProbes) RequireProcFS() { l.Set("procfs", func(path probes.ProbePath, _ probes.Probe) probes.Probe { return probes.ProbeFn(func(r probes.Reporter) error { mountPoint := "/proc" - desc := probes.NewProbeDesc(fmt.Sprintf("%s file system", mountPoint), path) + desc := probes.NewProbeDesc(mountPoint+" file system", path) var st syscall.Statfs_t if err := syscall.Statfs(mountPoint, &st); err != nil { diff --git a/internal/pkg/sysinfo/probes/network.go b/internal/pkg/sysinfo/probes/network.go index 74d851a47044..76122c02294e 100644 --- a/internal/pkg/sysinfo/probes/network.go +++ b/internal/pkg/sysinfo/probes/network.go @@ -23,9 +23,9 @@ import ( ) func RequireNameResolution(p Probes, lookupIP func(host string) ([]net.IP, error), host string) { - p.Set(fmt.Sprintf("nameResolution:%s", host), func(path ProbePath, _ Probe) Probe { + p.Set("nameResolution:"+host, func(path ProbePath, _ Probe) Probe { return ProbeFn(func(r Reporter) error { - desc := NewProbeDesc(fmt.Sprintf("Name resolution: %s", host), path) + desc := NewProbeDesc("Name resolution: "+host, path) ips, err := lookupIP(host) if err != nil { return r.Error(desc, err) diff --git a/inttest/addons/addons_test.go b/inttest/addons/addons_test.go index a74f96d9c411..0b1468d0b993 100644 --- a/inttest/addons/addons_test.go +++ b/inttest/addons/addons_test.go @@ -156,7 +156,7 @@ func (as *AddonsSuite) deleteRelease(chart *helmv1beta1.Chart) { as.Require().NoError(wait.PollUntilContextCancel(ctx, 1*time.Second, true, func(pollCtx context.Context) (done bool, err error) { as.T().Logf("Expecting have no secrets left for release %s/%s", chart.Status.Namespace, chart.Status.ReleaseName) items, err := k8sclient.CoreV1().Secrets(chart.Status.Namespace).List(pollCtx, metav1.ListOptions{ - LabelSelector: fmt.Sprintf("name=%s", chart.Status.ReleaseName), + LabelSelector: "name=" + chart.Status.ReleaseName, }) if err != nil { if ctxErr := context.Cause(ctx); ctxErr != nil { @@ -294,7 +294,7 @@ func (as *AddonsSuite) waitForTestRelease(addonName, appVersion string, namespac as.Require().NoError(wait.PollUntilContextCancel(ctx, 1*time.Second, true, func(pollCtx context.Context) (done bool, err error) { err = chartClient.Get(pollCtx, client.ObjectKey{ Namespace: "kube-system", - Name: fmt.Sprintf("k0s-addon-chart-%s", addonName), + Name: "k0s-addon-chart-" + addonName, }, &chart) if err != nil { if ctxErr := context.Cause(ctx); ctxErr != nil { @@ -347,7 +347,7 @@ func (as *AddonsSuite) checkCustomValues(releaseName string) error { return err } return wait.PollUntilContextCancel(ctx, 1*time.Second, true, func(pollCtx context.Context) (done bool, err error) { - serverDeployment := fmt.Sprintf("%s-echo-server", releaseName) + serverDeployment := releaseName + "-echo-server" d, err := kc.AppsV1().Deployments("default").Get(pollCtx, serverDeployment, metav1.GetOptions{}) if err != nil { if ctxErr := context.Cause(ctx); ctxErr != nil { diff --git a/inttest/ap-updater-periodic/updater_test.go b/inttest/ap-updater-periodic/updater_test.go index 65888a24b0cb..cfb5a57aebfd 100644 --- a/inttest/ap-updater-periodic/updater_test.go +++ b/inttest/ap-updater-periodic/updater_test.go @@ -16,6 +16,7 @@ package updater import ( "fmt" + "net/url" "testing" "time" @@ -56,7 +57,7 @@ func (s *plansSingleControllerSuite) SetupTest() { vars := struct { Address string }{ - Address: fmt.Sprintf("http://%s", s.GetUpdateServerIPAddress()), + Address: (&url.URL{Scheme: "http", Host: s.GetUpdateServerIPAddress()}).String(), } s.PutFileTemplate(s.ControllerNode(0), "/etc/conf.d/k0scontroller", envTemplate, vars) diff --git a/inttest/basic/basic_test.go b/inttest/basic/basic_test.go index bf248261e934..ce945026c405 100644 --- a/inttest/basic/basic_test.go +++ b/inttest/basic/basic_test.go @@ -19,6 +19,7 @@ package basic import ( "bytes" "context" + "errors" "fmt" "strings" "testing" @@ -58,12 +59,12 @@ func (s *BasicSuite) TestK0sGetsUp() { defer ssh.Disconnect() _, err = ssh.ExecWithOutput(ctx, fmt.Sprintf("mkdir -p %s/bin && touch -t 202201010000 %s/bin/kube-apiserver", customDataDir, customDataDir)) s.Require().NoError(err) - _, err = ssh.ExecWithOutput(ctx, fmt.Sprintf("touch -t 202201010000 %s", s.K0sFullPath)) + _, err = ssh.ExecWithOutput(ctx, "touch -t 202201010000 "+s.K0sFullPath) s.Require().NoError(err) _, err = ssh.ExecWithOutput(ctx, "mkdir -p /run/k0s/konnectivity-server/ && touch -t 202201010000 /run/k0s/konnectivity-server/konnectivity-server.sock") s.Require().NoError(err) - dataDirOpt := fmt.Sprintf("--data-dir=%s", customDataDir) + dataDirOpt := "--data-dir=" + customDataDir s.Require().NoError(s.InitController(0, dataDirOpt)) token, err := s.GetJoinToken("worker", dataDirOpt) @@ -165,7 +166,7 @@ func (s *BasicSuite) verifyKubeletAddressFlag(ctx context.Context, node string) return err } if output != "--address=0.0.0.0" { - return fmt.Errorf("kubelet does not have the address flag set") + return errors.New("kubelet does not have the address flag set") } return nil diff --git a/inttest/byocri/byocri_test.go b/inttest/byocri/byocri_test.go index 481162e684d7..5ad94768ba03 100644 --- a/inttest/byocri/byocri_test.go +++ b/inttest/byocri/byocri_test.go @@ -17,6 +17,7 @@ limitations under the License. package byocri import ( + "errors" "fmt" "strings" "testing" @@ -85,7 +86,7 @@ func (s *BYOCRISuite) runDockerWorker() error { return err } if token == "" { - return fmt.Errorf("got empty token for worker join") + return errors.New("got empty token for worker join") } sshWorker, err := s.SSH(s.Context(), s.WorkerNode(0)) if err != nil { diff --git a/inttest/calico/calico_test.go b/inttest/calico/calico_test.go index 1112cc6565ce..a663792b409a 100644 --- a/inttest/calico/calico_test.go +++ b/inttest/calico/calico_test.go @@ -18,7 +18,6 @@ package calico import ( "context" - "fmt" "os/exec" "path/filepath" "strings" @@ -104,7 +103,7 @@ func (s *CalicoSuite) TestK0sGetsUp() { s.NoError(common.WaitForPod(s.Context(), kc, "alpine", "default"), "alpine pod did not start") err = wait.PollImmediateWithContext(s.Context(), 100*time.Millisecond, time.Minute, func(ctx context.Context) (done bool, err error) { - out, err := common.PodExecCmdOutput(kc, restConfig, sourcePod.Name, sourcePod.Namespace, fmt.Sprintf("/usr/bin/wget -qO- %s", targetPod.Status.PodIP)) + out, err := common.PodExecCmdOutput(kc, restConfig, sourcePod.Name, sourcePod.Namespace, "/usr/bin/wget -qO- "+targetPod.Status.PodIP) if err != nil { return false, err } diff --git a/inttest/cli/cli_test.go b/inttest/cli/cli_test.go index 1d07d5e44e8f..adc431bafe0d 100644 --- a/inttest/cli/cli_test.go +++ b/inttest/cli/cli_test.go @@ -18,7 +18,6 @@ package cli import ( "encoding/json" - "fmt" "testing" "time" @@ -58,7 +57,7 @@ func (s *CliSuite) TestK0sCliKubectlAndResetCommand() { defer ssh.Disconnect() s.Run("sysinfoSmoketest", func() { - out, err := ssh.ExecWithOutput(s.Context(), fmt.Sprintf("%s sysinfo", s.K0sFullPath)) + out, err := ssh.ExecWithOutput(s.Context(), s.K0sFullPath+" sysinfo") s.NoError(err, "k0s sysinfo has non-zero exit code") s.T().Logf("%s", out) s.Regexp("\nOperating system: Linux \\(pass\\)\n", out) diff --git a/inttest/common/bootloosesuite.go b/inttest/common/bootloosesuite.go index fc7b1afcf48c..cfa5132a273d 100644 --- a/inttest/common/bootloosesuite.go +++ b/inttest/common/bootloosesuite.go @@ -432,8 +432,8 @@ func (s *BootlooseSuite) dumpNodeLogs(ctx context.Context, t *testing.T, node, d } defer ssh.Disconnect() - outPath := filepath.Join(dir, fmt.Sprintf("%s.out.log", node)) - errPath := filepath.Join(dir, fmt.Sprintf("%s.err.log", node)) + outPath := filepath.Join(dir, node+".out.log") + errPath := filepath.Join(dir, node+".err.log") err = func() (err error) { type log struct { @@ -673,7 +673,7 @@ func (s *BootlooseSuite) ImportK0smotronImages(ctx context.Context) error { } defer sshWorker.Disconnect() - _, err = sshWorker.ExecWithOutput(ctx, fmt.Sprintf("k0s ctr images import %s", s.K0smotronImageBundleMountPoints[0])) + _, err = sshWorker.ExecWithOutput(ctx, "k0s ctr images import "+s.K0smotronImageBundleMountPoints[0]) if err != nil { return fmt.Errorf("failed to import k0smotron images: %w", err) } diff --git a/inttest/common/filetools.go b/inttest/common/filetools.go index ed32bdb64085..2c473f10879d 100644 --- a/inttest/common/filetools.go +++ b/inttest/common/filetools.go @@ -30,7 +30,7 @@ func (s *BootlooseSuite) GetFileFromController(controllerIdx int, path string) s sshCon, err := s.SSH(s.Context(), s.ControllerNode(controllerIdx)) s.Require().NoError(err) defer sshCon.Disconnect() - content, err := sshCon.ExecWithOutput(s.Context(), fmt.Sprintf("cat %s", path)) + content, err := sshCon.ExecWithOutput(s.Context(), "cat "+path) s.Require().NoError(err) return content @@ -42,7 +42,7 @@ func (s *BootlooseSuite) WriteFile(node, path string, reader io.Reader) { ssh, err := s.SSH(s.Context(), node) s.Require().NoError(err) defer ssh.Disconnect() - s.Require().NoError(ssh.Exec(s.Context(), fmt.Sprintf("cat >%s", path), SSHStreams{In: reader})) + s.Require().NoError(ssh.Exec(s.Context(), "cat >"+path, SSHStreams{In: reader})) } // WriteFileContent writes content to a file at the given path on the given diff --git a/inttest/common/launchdelegate.go b/inttest/common/launchdelegate.go index f148d58dd97b..e1cd071aad05 100644 --- a/inttest/common/launchdelegate.go +++ b/inttest/common/launchdelegate.go @@ -94,7 +94,7 @@ func (s *standaloneLaunchDelegate) StopController(ctx context.Context, conn *SSH // executable is launched directly (vs. started via a service manager). func (s *standaloneLaunchDelegate) InitWorker(ctx context.Context, conn *SSHConnection, token string, k0sArgs ...string) error { if token == "" { - return fmt.Errorf("got empty token for worker join") + return errors.New("got empty token for worker join") } var script strings.Builder @@ -158,7 +158,7 @@ func (o *openRCLaunchDelegate) InitController(ctx context.Context, conn *SSHConn } // Configure k0s as a controller w/args - controllerArgs := fmt.Sprintf("controller --debug %s", strings.Join(k0sArgs, " ")) + controllerArgs := "controller --debug " + strings.Join(k0sArgs, " ") if err := configureK0sServiceArgs(ctx, conn, "controller", controllerArgs); err != nil { return fmt.Errorf("failed to configure k0s with '%s'", controllerArgs) } @@ -253,7 +253,7 @@ func (*openRCLaunchDelegate) ReadK0sLogs(ctx context.Context, conn *SSHConnectio // installK0sServiceOpenRC will install an OpenRC k0s-type service (controller/worker) // if it does not already exist. func (o *openRCLaunchDelegate) installK0sService(ctx context.Context, conn *SSHConnection, k0sType string) error { - existsCommand := fmt.Sprintf("/usr/bin/file /etc/init.d/k0s%s", k0sType) + existsCommand := "/usr/bin/file /etc/init.d/k0s" + k0sType if _, err := conn.ExecWithOutput(ctx, existsCommand); err != nil { cmd := fmt.Sprintf("%s install %s", o.k0sFullPath, k0sType) if err := conn.Exec(ctx, cmd, SSHStreams{}); err != nil { @@ -268,7 +268,7 @@ func (o *openRCLaunchDelegate) installK0sService(ctx context.Context, conn *SSHC // `/etc/init.d/k0s[controller|worker]` startup script to allow for different // configurations at test time, using the same base image. func configureK0sServiceArgs(ctx context.Context, conn *SSHConnection, k0sType string, args string) error { - k0sServiceFile := fmt.Sprintf("/etc/init.d/k0s%s", k0sType) + k0sServiceFile := "/etc/init.d/k0s" + k0sType cmd := fmt.Sprintf("sed -i 's#^command_args=.*$#command_args=\"%s\"#g' %s", args, k0sServiceFile) _, err := conn.ExecWithOutput(ctx, cmd) diff --git a/inttest/common/util.go b/inttest/common/util.go index d8b367908ea9..19c63672fe9a 100644 --- a/inttest/common/util.go +++ b/inttest/common/util.go @@ -376,7 +376,7 @@ func ResetNode(name string, suite *BootlooseSuite) error { return err } defer ssh.Disconnect() - _, err = ssh.ExecWithOutput(suite.Context(), fmt.Sprintf("%s reset --debug", suite.K0sFullPath)) + _, err = ssh.ExecWithOutput(suite.Context(), suite.K0sFullPath+" reset --debug") return err } diff --git a/inttest/configchange/config_test.go b/inttest/configchange/config_test.go index 58a6cf30c4a4..68adc52db63e 100644 --- a/inttest/configchange/config_test.go +++ b/inttest/configchange/config_test.go @@ -18,6 +18,7 @@ package configchange import ( "context" + "errors" "fmt" "testing" "time" @@ -203,7 +204,7 @@ func (s *ConfigSuite) waitForReconcileEvent(eventWatch watch.Interface) (*corev1 event := e.Object.(*corev1.Event) return event, nil case <-timeout: - return nil, fmt.Errorf("timeout waiting for reconcile event") + return nil, errors.New("timeout waiting for reconcile event") } } diff --git a/inttest/ctr/ctr_test.go b/inttest/ctr/ctr_test.go index 7da70a609e74..b982945222d5 100644 --- a/inttest/ctr/ctr_test.go +++ b/inttest/ctr/ctr_test.go @@ -17,7 +17,6 @@ limitations under the License. package ctr import ( - "fmt" "regexp" "strings" "testing" @@ -54,7 +53,7 @@ func (s *CtrSuite) TestK0sCtrCommand() { s.Require().NoError(err) flatOutput := removeRedundantSpaces(output) - errMsg := fmt.Sprintf("returned output of command 'k0s ctr namespaces list' is different than expected: %s", output) + errMsg := "returned output of command 'k0s ctr namespaces list' is different than expected: " + output s.Equal("NAME LABELS k8s.io", flatOutput, errMsg) output, err = ssh.ExecWithOutput(s.Context(), "/usr/local/bin/k0s ctr version") diff --git a/inttest/disabledcomponents/disabled_components_test.go b/inttest/disabledcomponents/disabled_components_test.go index 8cc2562c3158..41c2a7d310f5 100644 --- a/inttest/disabledcomponents/disabled_components_test.go +++ b/inttest/disabledcomponents/disabled_components_test.go @@ -17,7 +17,6 @@ limitations under the License. package disabledcomponents import ( - "fmt" "testing" "github.com/stretchr/testify/suite" @@ -53,7 +52,7 @@ func (s *DisabledComponentsSuite) TestK0sGetsUp() { } func (s *DisabledComponentsSuite) processExists(procName string, ssh *common.SSHConnection) bool { - _, err := ssh.ExecWithOutput(s.Context(), fmt.Sprintf("pidof %s", procName)) + _, err := ssh.ExecWithOutput(s.Context(), "pidof "+procName) return err == nil // `pidof xyz` return 1 if the process does not exist } diff --git a/inttest/embedded-binaries/embedded_binaries_test.go b/inttest/embedded-binaries/embedded_binaries_test.go index a0d498637a25..b69677c8dbc6 100644 --- a/inttest/embedded-binaries/embedded_binaries_test.go +++ b/inttest/embedded-binaries/embedded_binaries_test.go @@ -17,7 +17,7 @@ limitations under the License. package binaries import ( - "fmt" + "path" "testing" "github.com/k0sproject/k0s/inttest/common" @@ -71,7 +71,7 @@ func (s *EmbeddedBinariesSuite) TestK0sGetsUp() { for _, tc := range testCases { s.Run(tc.cmd, func() { - out, err := sshC0.ExecWithOutput(s.Context(), fmt.Sprintf("/var/lib/k0s/bin/%s", tc.cmd)) + out, err := sshC0.ExecWithOutput(s.Context(), path.Join("/var/lib/k0s/bin", tc.cmd)) if tc.checkError { s.Require().NoError(err, tc.cmd, out) } @@ -93,7 +93,7 @@ func (s *EmbeddedBinariesSuite) TestK0sGetsUp() { for _, tc := range testCases { s.Run("", func() { - out, err := sshC1.ExecWithOutput(s.Context(), fmt.Sprintf("/var/lib/k0s/bin/%s", tc.cmd)) + out, err := sshC1.ExecWithOutput(s.Context(), path.Join("/var/lib/k0s/bin", tc.cmd)) if tc.checkError { s.Require().NoError(err, tc.cmd, out) } diff --git a/inttest/extraargs/extraargs_test.go b/inttest/extraargs/extraargs_test.go index 7d2434df6a78..2f92ec84d952 100644 --- a/inttest/extraargs/extraargs_test.go +++ b/inttest/extraargs/extraargs_test.go @@ -62,7 +62,7 @@ func (s *ExtraArgsSuite) TestK0sGetsUp() { } func (s *ExtraArgsSuite) checkFlag(ssh *common.SSHConnection, processName string, flag string) { s.T().Logf("Checking flag %s in process %s", flag, processName) - pid, err := ssh.ExecWithOutput(s.Context(), fmt.Sprintf("/usr/bin/pgrep %s", processName)) + pid, err := ssh.ExecWithOutput(s.Context(), "/usr/bin/pgrep "+processName) s.NoError(err) flagCount, err := ssh.ExecWithOutput(s.Context(), fmt.Sprintf("/bin/grep -c -- %s /proc/%s/cmdline", flag, pid)) diff --git a/inttest/hacontrolplane/hacontrolplane_test.go b/inttest/hacontrolplane/hacontrolplane_test.go index 3930e438cf52..3adb6a3b11e6 100644 --- a/inttest/hacontrolplane/hacontrolplane_test.go +++ b/inttest/hacontrolplane/hacontrolplane_test.go @@ -18,7 +18,6 @@ package hacontrolplane import ( "encoding/json" - "fmt" "net" "net/url" "testing" @@ -55,7 +54,7 @@ func (s *HAControlplaneSuite) makeNodeLeave(executeOnControllerIdx int, peerAddr s.Require().NoError(err) defer sshCon.Disconnect() for range 20 { - _, err := sshCon.ExecWithOutput(s.Context(), fmt.Sprintf("/usr/local/bin/k0s etcd leave --peer-address %s", peerAddress)) + _, err := sshCon.ExecWithOutput(s.Context(), "/usr/local/bin/k0s etcd leave --peer-address "+peerAddress) if err == nil { break } diff --git a/inttest/kubectl/kubectl_test.go b/inttest/kubectl/kubectl_test.go index 2f3357270322..9a465b179d4b 100644 --- a/inttest/kubectl/kubectl_test.go +++ b/inttest/kubectl/kubectl_test.go @@ -156,7 +156,7 @@ func (s *KubectlSuite) TestEmbeddedKubectl() { } execTest := func(t *testing.T, cmdline string, check checkFunc) { - cmdline = fmt.Sprintf("PATH=/inttest/bin:/inttest/symlink %s", cmdline) + cmdline = "PATH=/inttest/bin:/inttest/symlink " + cmdline t.Log("Executing", cmdline) var stdoutBuf bytes.Buffer @@ -204,7 +204,7 @@ func checkClientVersion(t *testing.T, v map[string]any) { ) assert.Contains(t, requiredValue[string](t, v, "gitVersion"), - fmt.Sprintf("v%s", constant.KubernetesMajorMinorVersion), + "v"+constant.KubernetesMajorMinorVersion, ) assert.Equal(t, "not_available", requiredValue[string](t, v, "gitCommit")) assert.Empty(t, requiredValue[string](t, v, "gitTreeState")) @@ -221,7 +221,7 @@ func checkServerVersion(t *testing.T, v map[string]any) { ) assert.Contains(t, requiredValue[string](t, v, "gitVersion"), - fmt.Sprintf("v%s", constant.KubernetesMajorMinorVersion), + "v"+constant.KubernetesMajorMinorVersion, ) assert.Contains(t, requiredValue[string](t, v, "gitVersion"), "+k0s") assert.NotEmpty(t, requiredValue[string](t, v, "gitCommit")) diff --git a/inttest/nllb/nllb_test.go b/inttest/nllb/nllb_test.go index 4af7edc2c748..3f48ffdfbc16 100644 --- a/inttest/nllb/nllb_test.go +++ b/inttest/nllb/nllb_test.go @@ -250,7 +250,7 @@ func (s *suite) checkClusterReadiness(ctx context.Context, clients *kubernetes.C s.T().Logf("Node %s is ready", nodeName) - nllbPodName := fmt.Sprintf("nllb-%s", nodeName) + nllbPodName := "nllb-" + nodeName if err := common.WaitForPod(ctx, clients, nllbPodName, kubeSystem); err != nil { return fmt.Errorf("Pod %s/%s is not ready: %w", nllbPodName, kubeSystem, err) } diff --git a/inttest/psp/psp_test.go b/inttest/psp/psp_test.go index 50baad753bf5..f230abbca904 100644 --- a/inttest/psp/psp_test.go +++ b/inttest/psp/psp_test.go @@ -17,7 +17,6 @@ limitations under the License. package psp import ( - "fmt" "testing" "github.com/k0sproject/k0s/inttest/common" @@ -52,7 +51,7 @@ func (s *PSPSuite) TestK0sGetsUp() { s.Require().NoError(err) defer ssh.Disconnect() - _, err = ssh.ExecWithOutput(s.Context(), fmt.Sprintf("%s kubectl apply -f /tmp/role.yaml", s.K0sFullPath)) + _, err = ssh.ExecWithOutput(s.Context(), s.K0sFullPath+" kubectl apply -f /tmp/role.yaml") s.NoError(err) nonPrivelegedPodReq := &corev1.Pod{ diff --git a/pkg/apis/helm/v1beta1/chart_types.go b/pkg/apis/helm/v1beta1/chart_types.go index 6bb3c5e66fc4..9f41c9836de8 100644 --- a/pkg/apis/helm/v1beta1/chart_types.go +++ b/pkg/apis/helm/v1beta1/chart_types.go @@ -18,7 +18,7 @@ package v1beta1 import ( "crypto/sha256" - "fmt" + "encoding/hex" "github.com/sirupsen/logrus" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" @@ -54,7 +54,7 @@ func (cs ChartSpec) YamlValues() map[string]interface{} { func (cs ChartSpec) HashValues() string { h := sha256.New() h.Write([]byte(cs.ReleaseName + cs.Values)) - return fmt.Sprintf("%x", h.Sum(nil)) + return hex.EncodeToString(h.Sum(nil)) } // ShouldForceUpgrade returns true if the chart should be force upgraded diff --git a/pkg/apis/helm/v1beta1/generic_hash.go b/pkg/apis/helm/v1beta1/generic_hash.go index 622881185552..97cde93482c8 100644 --- a/pkg/apis/helm/v1beta1/generic_hash.go +++ b/pkg/apis/helm/v1beta1/generic_hash.go @@ -31,7 +31,7 @@ func cleanUpInterfaceArray(in []interface{}) []interface{} { func cleanUpInterfaceMap(in map[string]interface{}) map[string]interface{} { result := make(map[string]interface{}) for k, v := range in { - result[fmt.Sprintf("%v", k)] = cleanUpMapValue(v) + result[k] = cleanUpMapValue(v) } return result } @@ -65,7 +65,7 @@ func cleanUpMapValue(v interface{}) interface{} { func CleanUpGenericMap(in map[string]interface{}) map[string]interface{} { result := make(map[string]interface{}) for k, v := range in { - result[fmt.Sprintf("%v", k)] = cleanUpMapValue(v) + result[k] = cleanUpMapValue(v) } return result } diff --git a/pkg/apis/k0s/v1beta1/controltypes.go b/pkg/apis/k0s/v1beta1/controltypes.go index 86468c3ce07c..df393c5708cd 100644 --- a/pkg/apis/k0s/v1beta1/controltypes.go +++ b/pkg/apis/k0s/v1beta1/controltypes.go @@ -16,7 +16,9 @@ limitations under the License. package v1beta1 -import "fmt" +import ( + "errors" +) // CaResponse defines the response type for /ca control API type CaResponse struct { @@ -37,11 +39,11 @@ type EtcdRequest struct { // Validate validates the request func (e *EtcdRequest) Validate() error { if e.Node == "" { - return fmt.Errorf("node cannot be empty") + return errors.New("node cannot be empty") } if e.PeerAddress == "" { - return fmt.Errorf("peerAddress cannot be empty") + return errors.New("peerAddress cannot be empty") } return nil diff --git a/pkg/apis/k0s/v1beta1/feature_gates.go b/pkg/apis/k0s/v1beta1/feature_gates.go index d37208392423..2f76f262ad11 100644 --- a/pkg/apis/k0s/v1beta1/feature_gates.go +++ b/pkg/apis/k0s/v1beta1/feature_gates.go @@ -17,6 +17,7 @@ limitations under the License. package v1beta1 import ( + "errors" "fmt" "strings" @@ -121,7 +122,7 @@ func (fg *FeatureGate) EnabledFor(component string) (value bool, found bool) { // Validate given feature gate func (fg *FeatureGate) Validate() error { if fg.Name == "" { - return fmt.Errorf("feature gate must have name") + return errors.New("feature gate must have name") } return nil } diff --git a/pkg/apis/k0s/v1beta1/images_test.go b/pkg/apis/k0s/v1beta1/images_test.go index 3fbbb6acca25..ac60f4b65f91 100644 --- a/pkg/apis/k0s/v1beta1/images_test.go +++ b/pkg/apis/k0s/v1beta1/images_test.go @@ -17,7 +17,6 @@ limitations under the License. package v1beta1 import ( - "fmt" "testing" "github.com/k0sproject/k0s/pkg/constant" @@ -63,19 +62,19 @@ func TestImagesRepoOverrideInConfiguration(t *testing.T) { cfg.Spec.Images.Repository = "my.repo" var testingConfig *ClusterConfig require.NoError(t, yaml.Unmarshal(getConfigYAML(t, cfg), &testingConfig)) - require.Equal(t, fmt.Sprintf("my.repo/k0sproject/apiserver-network-proxy-agent:%s", constant.KonnectivityImageVersion), testingConfig.Spec.Images.Konnectivity.URI()) - require.Equal(t, fmt.Sprintf("my.repo/metrics-server/metrics-server:%s", constant.MetricsImageVersion), testingConfig.Spec.Images.MetricsServer.URI()) - require.Equal(t, fmt.Sprintf("my.repo/k0sproject/kube-proxy:%s", constant.KubeProxyImageVersion), testingConfig.Spec.Images.KubeProxy.URI()) - require.Equal(t, fmt.Sprintf("my.repo/k0sproject/coredns:%s", constant.CoreDNSImageVersion), testingConfig.Spec.Images.CoreDNS.URI()) - require.Equal(t, fmt.Sprintf("my.repo/k0sproject/calico-cni:%s", constant.CalicoComponentImagesVersion), testingConfig.Spec.Images.Calico.CNI.URI()) - require.Equal(t, fmt.Sprintf("my.repo/k0sproject/calico-node:%s", constant.CalicoComponentImagesVersion), testingConfig.Spec.Images.Calico.Node.URI()) - require.Equal(t, fmt.Sprintf("my.repo/k0sproject/calico-kube-controllers:%s", constant.CalicoComponentImagesVersion), testingConfig.Spec.Images.Calico.KubeControllers.URI()) - require.Equal(t, fmt.Sprintf("my.repo/k0sproject/calico-cni:%s", constant.CalicoComponentImagesVersion), testingConfig.Spec.Images.Calico.CNI.URI()) - require.Equal(t, fmt.Sprintf("my.repo/k0sproject/calico-node:%s", constant.CalicoComponentImagesVersion), testingConfig.Spec.Images.Calico.Node.URI()) - require.Equal(t, fmt.Sprintf("my.repo/k0sproject/calico-kube-controllers:%s", constant.CalicoComponentImagesVersion), testingConfig.Spec.Images.Calico.KubeControllers.URI()) - require.Equal(t, fmt.Sprintf("my.repo/k0sproject/kube-router:%s", constant.KubeRouterCNIImageVersion), testingConfig.Spec.Images.KubeRouter.CNI.URI()) - require.Equal(t, fmt.Sprintf("my.repo/k0sproject/cni-node:%s", constant.KubeRouterCNIInstallerImageVersion), testingConfig.Spec.Images.KubeRouter.CNIInstaller.URI()) - require.Equal(t, fmt.Sprintf("my.repo/pause:%s", constant.KubePauseContainerImageVersion), testingConfig.Spec.Images.Pause.URI()) + require.Equal(t, "my.repo/k0sproject/apiserver-network-proxy-agent:"+constant.KonnectivityImageVersion, testingConfig.Spec.Images.Konnectivity.URI()) + require.Equal(t, "my.repo/metrics-server/metrics-server:"+constant.MetricsImageVersion, testingConfig.Spec.Images.MetricsServer.URI()) + require.Equal(t, "my.repo/k0sproject/kube-proxy:"+constant.KubeProxyImageVersion, testingConfig.Spec.Images.KubeProxy.URI()) + require.Equal(t, "my.repo/k0sproject/coredns:"+constant.CoreDNSImageVersion, testingConfig.Spec.Images.CoreDNS.URI()) + require.Equal(t, "my.repo/k0sproject/calico-cni:"+constant.CalicoComponentImagesVersion, testingConfig.Spec.Images.Calico.CNI.URI()) + require.Equal(t, "my.repo/k0sproject/calico-node:"+constant.CalicoComponentImagesVersion, testingConfig.Spec.Images.Calico.Node.URI()) + require.Equal(t, "my.repo/k0sproject/calico-kube-controllers:"+constant.CalicoComponentImagesVersion, testingConfig.Spec.Images.Calico.KubeControllers.URI()) + require.Equal(t, "my.repo/k0sproject/calico-cni:"+constant.CalicoComponentImagesVersion, testingConfig.Spec.Images.Calico.CNI.URI()) + require.Equal(t, "my.repo/k0sproject/calico-node:"+constant.CalicoComponentImagesVersion, testingConfig.Spec.Images.Calico.Node.URI()) + require.Equal(t, "my.repo/k0sproject/calico-kube-controllers:"+constant.CalicoComponentImagesVersion, testingConfig.Spec.Images.Calico.KubeControllers.URI()) + require.Equal(t, "my.repo/k0sproject/kube-router:"+constant.KubeRouterCNIImageVersion, testingConfig.Spec.Images.KubeRouter.CNI.URI()) + require.Equal(t, "my.repo/k0sproject/cni-node:"+constant.KubeRouterCNIInstallerImageVersion, testingConfig.Spec.Images.KubeRouter.CNIInstaller.URI()) + require.Equal(t, "my.repo/pause:"+constant.KubePauseContainerImageVersion, testingConfig.Spec.Images.Pause.URI()) }) t.Run("config_with_custom_images", func(t *testing.T) { cfg := DefaultClusterConfig() @@ -83,13 +82,13 @@ func TestImagesRepoOverrideInConfiguration(t *testing.T) { cfg.Spec.Images.Repository = "my.repo" var testingConfig *ClusterConfig require.NoError(t, yaml.Unmarshal(getConfigYAML(t, cfg), &testingConfig)) - require.Equal(t, fmt.Sprintf("my.repo/my-custom-image:%s", constant.KonnectivityImageVersion), testingConfig.Spec.Images.Konnectivity.URI()) - require.Equal(t, fmt.Sprintf("my.repo/metrics-server/metrics-server:%s", constant.MetricsImageVersion), testingConfig.Spec.Images.MetricsServer.URI()) - require.Equal(t, fmt.Sprintf("my.repo/k0sproject/kube-proxy:%s", constant.KubeProxyImageVersion), testingConfig.Spec.Images.KubeProxy.URI()) - require.Equal(t, fmt.Sprintf("my.repo/k0sproject/coredns:%s", constant.CoreDNSImageVersion), testingConfig.Spec.Images.CoreDNS.URI()) - require.Equal(t, fmt.Sprintf("my.repo/k0sproject/calico-cni:%s", constant.CalicoComponentImagesVersion), testingConfig.Spec.Images.Calico.CNI.URI()) - require.Equal(t, fmt.Sprintf("my.repo/k0sproject/calico-node:%s", constant.CalicoComponentImagesVersion), testingConfig.Spec.Images.Calico.Node.URI()) - require.Equal(t, fmt.Sprintf("my.repo/k0sproject/calico-kube-controllers:%s", constant.CalicoComponentImagesVersion), testingConfig.Spec.Images.Calico.KubeControllers.URI()) + require.Equal(t, "my.repo/my-custom-image:"+constant.KonnectivityImageVersion, testingConfig.Spec.Images.Konnectivity.URI()) + require.Equal(t, "my.repo/metrics-server/metrics-server:"+constant.MetricsImageVersion, testingConfig.Spec.Images.MetricsServer.URI()) + require.Equal(t, "my.repo/k0sproject/kube-proxy:"+constant.KubeProxyImageVersion, testingConfig.Spec.Images.KubeProxy.URI()) + require.Equal(t, "my.repo/k0sproject/coredns:"+constant.CoreDNSImageVersion, testingConfig.Spec.Images.CoreDNS.URI()) + require.Equal(t, "my.repo/k0sproject/calico-cni:"+constant.CalicoComponentImagesVersion, testingConfig.Spec.Images.Calico.CNI.URI()) + require.Equal(t, "my.repo/k0sproject/calico-node:"+constant.CalicoComponentImagesVersion, testingConfig.Spec.Images.Calico.Node.URI()) + require.Equal(t, "my.repo/k0sproject/calico-kube-controllers:"+constant.CalicoComponentImagesVersion, testingConfig.Spec.Images.Calico.KubeControllers.URI()) }) }) } diff --git a/pkg/apis/k0s/v1beta1/storage.go b/pkg/apis/k0s/v1beta1/storage.go index 1018150bfb10..d52f7673799a 100644 --- a/pkg/apis/k0s/v1beta1/storage.go +++ b/pkg/apis/k0s/v1beta1/storage.go @@ -18,6 +18,7 @@ package v1beta1 import ( "encoding/json" + "errors" "fmt" "net" "net/url" @@ -281,19 +282,19 @@ func (e *EtcdConfig) GetKeyFilePath(certDir string) string { } func validateRequiredProperties(e *ExternalCluster) []error { - var errors []error + var errs []error if len(e.Endpoints) == 0 { - errors = append(errors, fmt.Errorf("spec.storage.etcd.externalCluster.endpoints cannot be null or empty")) + errs = append(errs, errors.New("spec.storage.etcd.externalCluster.endpoints cannot be null or empty")) } else if slices.Contains(e.Endpoints, "") { - errors = append(errors, fmt.Errorf("spec.storage.etcd.externalCluster.endpoints cannot contain empty strings")) + errs = append(errs, errors.New("spec.storage.etcd.externalCluster.endpoints cannot contain empty strings")) } if e.EtcdPrefix == "" { - errors = append(errors, fmt.Errorf("spec.storage.etcd.externalCluster.etcdPrefix cannot be empty")) + errs = append(errs, errors.New("spec.storage.etcd.externalCluster.etcdPrefix cannot be empty")) } - return errors + return errs } func validateOptionalTLSProperties(e *ExternalCluster) []error { @@ -302,7 +303,7 @@ func validateOptionalTLSProperties(e *ExternalCluster) []error { if noTLSPropertyDefined || e.hasAllTLSPropertiesDefined() { return nil } - return []error{fmt.Errorf("spec.storage.etcd.externalCluster is invalid: " + + return []error{errors.New("spec.storage.etcd.externalCluster is invalid: " + "all TLS properties [caFile,clientCertFile,clientKeyFile] must be defined or none of those")} } diff --git a/pkg/applier/applier_test.go b/pkg/applier/applier_test.go index f390ce02e52f..b7f1f95094ee 100644 --- a/pkg/applier/applier_test.go +++ b/pkg/applier/applier_test.go @@ -18,8 +18,8 @@ package applier_test import ( "context" - "fmt" "os" + "path/filepath" "testing" "github.com/stretchr/testify/assert" @@ -91,9 +91,9 @@ spec: ports: - containerPort: 80 ` - require.NoError(t, os.WriteFile(fmt.Sprintf("%s/test-ns.yaml", dir), []byte(templateNS), 0400)) - require.NoError(t, os.WriteFile(fmt.Sprintf("%s/test-list.yaml", dir), []byte(template), 0400)) - require.NoError(t, os.WriteFile(fmt.Sprintf("%s/test-deploy.yaml", dir), []byte(templateDeployment), 0400)) + require.NoError(t, os.WriteFile(filepath.Join(dir, "test-ns.yaml"), []byte(templateNS), 0400)) + require.NoError(t, os.WriteFile(filepath.Join(dir, "test-list.yaml"), []byte(template), 0400)) + require.NoError(t, os.WriteFile(filepath.Join(dir, "test-deploy.yaml"), []byte(templateDeployment), 0400)) fakes := kubeutil.NewFakeClientFactory() a := applier.NewApplier(dir, fakes) diff --git a/pkg/autopilot/channels/channelclient.go b/pkg/autopilot/channels/channelclient.go index 59f6fa0464d6..7a381c86a819 100644 --- a/pkg/autopilot/channels/channelclient.go +++ b/pkg/autopilot/channels/channelclient.go @@ -19,7 +19,7 @@ import ( "fmt" "io" "net/http" - "strings" + "net/url" "time" "sigs.k8s.io/yaml" @@ -36,19 +36,21 @@ func NewChannelClient(server string, channel string, token string) (*ChannelClie Timeout: 10 * time.Second, } - // If server is a full URL, use that. If not assume it's a hostname and use the default path - if strings.HasPrefix(server, "http") { - server = strings.TrimSuffix(server, "/") - } else { - server = fmt.Sprintf("https://%s", server) + // If server is a full URL, use that. If not, assume HTTPS. + serverURL, err := url.Parse(server) + if err != nil { + return nil, err + } + if serverURL.Scheme == "" { + serverURL.Scheme = "https" } - channelURL := fmt.Sprintf("%s/%s/index.yaml", server, channel) + channelURL := serverURL.JoinPath(channel, "index.yaml") return &ChannelClient{ httpClient: httpClient, token: token, - channelURL: channelURL, + channelURL: channelURL.String(), }, nil } @@ -66,7 +68,7 @@ func (c *ChannelClient) GetLatest(ctx context.Context, headers map[string]string } if c.token != "" { - req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", c.token)) + req.Header.Add("Authorization", "Bearer "+c.token) } resp, err := c.httpClient.Do(req) diff --git a/pkg/autopilot/controller/leases_test.go b/pkg/autopilot/controller/leases_test.go index 16a337bd1312..09583a16f744 100644 --- a/pkg/autopilot/controller/leases_test.go +++ b/pkg/autopilot/controller/leases_test.go @@ -16,7 +16,6 @@ package controller import ( "context" - "fmt" "testing" "time" @@ -40,7 +39,7 @@ func TestLeasesInitialPending(t *testing.T) { leaseWatcher, err := NewLeaseWatcher(logger, clientFactory) assert.NoError(t, err) - leaseEventStatusCh, errorCh := leaseWatcher.StartWatcher(ctx, constant.AutopilotNamespace, fmt.Sprintf("%s-lease", constant.AutopilotNamespace), t.Name()) + leaseEventStatusCh, errorCh := leaseWatcher.StartWatcher(ctx, constant.AutopilotNamespace, constant.AutopilotNamespace+"-lease", t.Name()) assert.NotNil(t, errorCh) assert.NotNil(t, leaseEventStatusCh) diff --git a/pkg/autopilot/controller/plans/core/initprovidershandler_test.go b/pkg/autopilot/controller/plans/core/initprovidershandler_test.go index 2e01c952fdb2..116f5ab1b4aa 100644 --- a/pkg/autopilot/controller/plans/core/initprovidershandler_test.go +++ b/pkg/autopilot/controller/plans/core/initprovidershandler_test.go @@ -16,7 +16,7 @@ package core import ( "context" - "fmt" + "errors" "testing" apv1beta2 "github.com/k0sproject/k0s/pkg/apis/autopilot/v1beta2" @@ -80,10 +80,10 @@ func TestInitProvidersHandle(t *testing.T) { return PlanSchedulableWait, false, nil }, handlerSchedulable: func(ctx context.Context, planID string, pc apv1beta2.PlanCommand, pcs *apv1beta2.PlanCommandStatus) (apv1beta2.PlanStateType, bool, error) { - return PlanSchedulableWait, false, fmt.Errorf("should not have reached schedulable") + return PlanSchedulableWait, false, errors.New("should not have reached schedulable") }, handlerSchedulableWait: func(ctx context.Context, planID string, pc apv1beta2.PlanCommand, pcs *apv1beta2.PlanCommandStatus) (apv1beta2.PlanStateType, bool, error) { - return PlanSchedulableWait, false, fmt.Errorf("should not have reached schedulablewait") + return PlanSchedulableWait, false, errors.New("should not have reached schedulablewait") }, }, ), @@ -177,7 +177,7 @@ func TestInitProvidersHandle(t *testing.T) { NewInitProvidersHandler( logger, func(ctx context.Context, provider PlanCommandProvider, planID string, cmd apv1beta2.PlanCommand, status *apv1beta2.PlanCommandStatus) (apv1beta2.PlanStateType, bool, error) { - return PlanSchedulableWait, false, fmt.Errorf("intentional error") + return PlanSchedulableWait, false, assert.AnError }, PlanSchedulableWait, fakePlanCommandProvider{ diff --git a/pkg/autopilot/controller/plans/core/planstatecontroller_test.go b/pkg/autopilot/controller/plans/core/planstatecontroller_test.go index 659bee23dff3..e2c13b223efd 100644 --- a/pkg/autopilot/controller/plans/core/planstatecontroller_test.go +++ b/pkg/autopilot/controller/plans/core/planstatecontroller_test.go @@ -16,7 +16,6 @@ package core import ( "context" - "fmt" "testing" apv1beta2 "github.com/k0sproject/k0s/pkg/apis/autopilot/v1beta2" @@ -69,7 +68,7 @@ func TestReconcile(t *testing.T) { "HandlerError", &fakePlanStateHandler{ func(ctx context.Context, plan *apv1beta2.Plan) (ProviderResult, error) { - return ProviderResultFailure, fmt.Errorf("intentional error") + return ProviderResultFailure, assert.AnError }, }, &apv1beta2.Plan{ diff --git a/pkg/autopilot/controller/plans/core/planstatehandler_test.go b/pkg/autopilot/controller/plans/core/planstatehandler_test.go index 390f9df20612..08420ef2a8ff 100644 --- a/pkg/autopilot/controller/plans/core/planstatehandler_test.go +++ b/pkg/autopilot/controller/plans/core/planstatehandler_test.go @@ -16,7 +16,7 @@ package core import ( "context" - "fmt" + "errors" "testing" apv1beta2 "github.com/k0sproject/k0s/pkg/apis/autopilot/v1beta2" @@ -70,7 +70,7 @@ func TestHandle(t *testing.T) { fakePlanCommandProvider{ commandID: "K0sUpdate", handlerNewPlan: func(ctx context.Context, pc apv1beta2.PlanCommand, pcs *apv1beta2.PlanCommandStatus) (apv1beta2.PlanStateType, bool, error) { - return PlanSchedulableWait, false, fmt.Errorf("should not have reached newplan") + return PlanSchedulableWait, false, errors.New("should not have reached newplan") }, handlerSchedulable: func(ctx context.Context, planID string, pc apv1beta2.PlanCommand, pcs *apv1beta2.PlanCommandStatus) (apv1beta2.PlanStateType, bool, error) { assert.Equal(t, "v1.2.3", pc.K0sUpdate.Version) @@ -79,7 +79,7 @@ func TestHandle(t *testing.T) { return PlanCompleted, false, nil }, handlerSchedulableWait: func(ctx context.Context, planID string, pc apv1beta2.PlanCommand, pcs *apv1beta2.PlanCommandStatus) (apv1beta2.PlanStateType, bool, error) { - return PlanSchedulableWait, false, fmt.Errorf("should not have reached schedulablewait") + return PlanSchedulableWait, false, errors.New("should not have reached schedulablewait") }, }, ), @@ -206,7 +206,7 @@ func TestHandle(t *testing.T) { NewPlanStateHandler( logger, func(ctx context.Context, provider PlanCommandProvider, planID string, cmd apv1beta2.PlanCommand, status *apv1beta2.PlanCommandStatus) (apv1beta2.PlanStateType, bool, error) { - return PlanSchedulableWait, false, fmt.Errorf("intentional error") + return PlanSchedulableWait, false, assert.AnError }, fakePlanCommandProvider{ commandID: "K0sUpdate", @@ -259,7 +259,7 @@ func TestHandle(t *testing.T) { fakePlanCommandProvider{ commandID: "K0sUpdate", handlerNewPlan: func(ctx context.Context, pc apv1beta2.PlanCommand, pcs *apv1beta2.PlanCommandStatus) (apv1beta2.PlanStateType, bool, error) { - return pcs.State, false, fmt.Errorf("should not have reached newplan") + return pcs.State, false, errors.New("should not have reached newplan") }, handlerSchedulable: func(ctx context.Context, planID string, pc apv1beta2.PlanCommand, pcs *apv1beta2.PlanCommandStatus) (apv1beta2.PlanStateType, bool, error) { // Ensures that only the second command makes it here @@ -270,7 +270,7 @@ func TestHandle(t *testing.T) { return PlanCompleted, false, nil }, handlerSchedulableWait: func(ctx context.Context, planID string, pc apv1beta2.PlanCommand, pcs *apv1beta2.PlanCommandStatus) (apv1beta2.PlanStateType, bool, error) { - return pcs.State, false, fmt.Errorf("should not have reached schedulablewait") + return pcs.State, false, errors.New("should not have reached schedulablewait") }, }, ), @@ -313,14 +313,14 @@ func TestHandle(t *testing.T) { fakePlanCommandProvider{ commandID: "K0sUpdate", handlerNewPlan: func(ctx context.Context, pc apv1beta2.PlanCommand, pcs *apv1beta2.PlanCommandStatus) (apv1beta2.PlanStateType, bool, error) { - return pcs.State, false, fmt.Errorf("should not have reached newplan") + return pcs.State, false, errors.New("should not have reached newplan") }, handlerSchedulable: func(ctx context.Context, planID string, pc apv1beta2.PlanCommand, pcs *apv1beta2.PlanCommandStatus) (apv1beta2.PlanStateType, bool, error) { pcs.K0sUpdate = &apv1beta2.PlanCommandK0sUpdateStatus{} return PlanCompleted, false, nil }, handlerSchedulableWait: func(ctx context.Context, planID string, pc apv1beta2.PlanCommand, pcs *apv1beta2.PlanCommandStatus) (apv1beta2.PlanStateType, bool, error) { - return pcs.State, false, fmt.Errorf("should not have reached schedulablewait") + return pcs.State, false, errors.New("should not have reached schedulablewait") }, }, ), @@ -364,14 +364,14 @@ func TestHandle(t *testing.T) { fakePlanCommandProvider{ commandID: "K0sUpdate", handlerNewPlan: func(ctx context.Context, pc apv1beta2.PlanCommand, pcs *apv1beta2.PlanCommandStatus) (apv1beta2.PlanStateType, bool, error) { - return pcs.State, false, fmt.Errorf("should not have reached newplan") + return pcs.State, false, errors.New("should not have reached newplan") }, handlerSchedulable: func(ctx context.Context, planID string, pc apv1beta2.PlanCommand, pcs *apv1beta2.PlanCommandStatus) (apv1beta2.PlanStateType, bool, error) { pcs.K0sUpdate = &apv1beta2.PlanCommandK0sUpdateStatus{} return PlanCompleted, false, nil }, handlerSchedulableWait: func(ctx context.Context, planID string, pc apv1beta2.PlanCommand, pcs *apv1beta2.PlanCommandStatus) (apv1beta2.PlanStateType, bool, error) { - return pcs.State, false, fmt.Errorf("should not have reached schedulablewait") + return pcs.State, false, errors.New("should not have reached schedulablewait") }, }, ), @@ -420,14 +420,14 @@ func TestHandle(t *testing.T) { fakePlanCommandProvider{ commandID: "K0sUpdate", handlerNewPlan: func(ctx context.Context, pc apv1beta2.PlanCommand, pcs *apv1beta2.PlanCommandStatus) (apv1beta2.PlanStateType, bool, error) { - return pcs.State, false, fmt.Errorf("should not have reached newplan") + return pcs.State, false, errors.New("should not have reached newplan") }, handlerSchedulable: func(ctx context.Context, planID string, pc apv1beta2.PlanCommand, pcs *apv1beta2.PlanCommandStatus) (apv1beta2.PlanStateType, bool, error) { pcs.K0sUpdate = &apv1beta2.PlanCommandK0sUpdateStatus{} return pcs.State, true, nil }, handlerSchedulableWait: func(ctx context.Context, planID string, pc apv1beta2.PlanCommand, pcs *apv1beta2.PlanCommandStatus) (apv1beta2.PlanStateType, bool, error) { - return pcs.State, false, fmt.Errorf("should not have reached schedulablewait") + return pcs.State, false, errors.New("should not have reached schedulablewait") }, }, ), diff --git a/pkg/autopilot/controller/root_controller.go b/pkg/autopilot/controller/root_controller.go index d0cfa167e9f7..41db827c6eb7 100644 --- a/pkg/autopilot/controller/root_controller.go +++ b/pkg/autopilot/controller/root_controller.go @@ -99,7 +99,7 @@ func (c *rootController) Run(ctx context.Context) error { return fmt.Errorf("unable to setup lease watcher: %w", err) } - leaseName := fmt.Sprintf("%s-controller", apconst.AutopilotNamespace) + leaseName := apconst.AutopilotNamespace + "-controller" leaseIdentity := c.cfg.InvocationID leaseEventStatusCh, errorCh := leaseWatcher.StartWatcher(ctx, apconst.AutopilotNamespace, leaseName, leaseIdentity) diff --git a/pkg/autopilot/controller/setup.go b/pkg/autopilot/controller/setup.go index 93e1d0a90a8f..d39075e0fe12 100644 --- a/pkg/autopilot/controller/setup.go +++ b/pkg/autopilot/controller/setup.go @@ -227,7 +227,7 @@ func (sc *setupController) waitForControlNodesCRD(ctx context.Context, cf apcli. ctx, cancel := context.WithTimeout(ctx, 2*time.Minute) defer cancel() return watch.CRDs(extClient.CustomResourceDefinitions()). - WithObjectName(fmt.Sprintf("controlnodes.%s", apv1beta2.GroupName)). + WithObjectName("controlnodes."+apv1beta2.GroupName). WithErrorCallback(func(err error) (time.Duration, error) { if retryDelay, e := watch.IsRetryable(err); e == nil { sc.log.WithError(err).Debugf( diff --git a/pkg/autopilot/controller/signal/k0s/cordon.go b/pkg/autopilot/controller/signal/k0s/cordon.go index 615d2a861092..0768ca62b82d 100644 --- a/pkg/autopilot/controller/signal/k0s/cordon.go +++ b/pkg/autopilot/controller/signal/k0s/cordon.go @@ -16,6 +16,7 @@ package k0s import ( "context" + "errors" "fmt" "time" @@ -156,7 +157,7 @@ func (r *cordoning) drainNode(ctx context.Context, signalNode crcli.Object) erro var ok bool node, ok = signalNode.(*corev1.Node) if !ok { - return fmt.Errorf("failed to cast signalNode to *corev1.Node") + return errors.New("failed to cast signalNode to *corev1.Node") } } else { nodeName := signalNode.GetName() diff --git a/pkg/autopilot/controller/signal/k0s/uncordon.go b/pkg/autopilot/controller/signal/k0s/uncordon.go index 6bdda9d3295b..878fcdd2f247 100644 --- a/pkg/autopilot/controller/signal/k0s/uncordon.go +++ b/pkg/autopilot/controller/signal/k0s/uncordon.go @@ -16,6 +16,7 @@ package k0s import ( "context" + "errors" "fmt" "time" @@ -156,7 +157,7 @@ func (r *uncordoning) unCordonNode(ctx context.Context, signalNode crcli.Object) var ok bool node, ok = signalNode.(*corev1.Node) if !ok { - return fmt.Errorf("failed to convert signalNode to Node") + return errors.New("failed to convert signalNode to Node") } } else { nodeName := signalNode.GetName() diff --git a/pkg/autopilot/controller/updates/clusterinfo.go b/pkg/autopilot/controller/updates/clusterinfo.go index 3c8b57d83ec3..5821af60a744 100644 --- a/pkg/autopilot/controller/updates/clusterinfo.go +++ b/pkg/autopilot/controller/updates/clusterinfo.go @@ -22,6 +22,7 @@ import ( "encoding/json" "fmt" "runtime" + "strconv" "github.com/k0sproject/k0s/pkg/apis/k0s/v1beta1" "github.com/k0sproject/k0s/pkg/build" @@ -58,7 +59,7 @@ func (ci *ClusterInfo) AsMap() map[string]string { return map[string]string{ "K0S_StorageType": string(ci.StorageType), "K0S_ClusterID": ci.ClusterID, - "K0S_ControlPlaneNodesCount": fmt.Sprintf("%d", ci.ControlPlaneNodesCount), + "K0S_ControlPlaneNodesCount": strconv.FormatUint(uint64(ci.ControlPlaneNodesCount), 10), "K0S_WorkerData": workerData, "K0S_Version": ci.K0sVersion, "K0S_CNIProvider": ci.CNIProvider, diff --git a/pkg/autopilot/updater/client.go b/pkg/autopilot/updater/client.go index ab80144471f5..08e2e94ba86f 100644 --- a/pkg/autopilot/updater/client.go +++ b/pkg/autopilot/updater/client.go @@ -68,7 +68,7 @@ func (c *client) GetUpdate(channel, clusterID, lastUpdateStatus, currentVersion } if c.authToken != "" { - req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", c.authToken)) + req.Header.Set("Authorization", "Bearer "+c.authToken) } resp, err := c.httpClient.Do(req) diff --git a/pkg/backup/manager_unix.go b/pkg/backup/manager_unix.go index bbe73219272f..e18604c76b53 100644 --- a/pkg/backup/manager_unix.go +++ b/pkg/backup/manager_unix.go @@ -168,7 +168,7 @@ func (bm *Manager) RunRestore(archivePath string, k0sVars *config.CfgVars, desir if err != nil { return fmt.Errorf("failed to parse backed-up configuration file, check the backup archive: %w", err) } - bm.discoverSteps(fmt.Sprintf("%s/k0s.yaml", bm.tmpDir), cfg.Spec, k0sVars, "restore", desiredRestoredConfigPath, out) + bm.discoverSteps(bm.tmpDir+"/k0s.yaml", cfg.Spec, k0sVars, "restore", desiredRestoredConfigPath, out) logrus.Info("Starting restore") for _, step := range bm.steps { diff --git a/pkg/backup/sqlitedb_unix.go b/pkg/backup/sqlitedb_unix.go index ca8fdc661d4e..7bc365a42da8 100644 --- a/pkg/backup/sqlitedb_unix.go +++ b/pkg/backup/sqlitedb_unix.go @@ -46,7 +46,7 @@ func newSqliteStep(tmpDir string, dbPath string) *sqliteStep { } func (s *sqliteStep) Name() string { - return fmt.Sprintf("sqlite db path %s", s.dbPath) + return "sqlite db path " + s.dbPath } func (s *sqliteStep) Backup() (StepResult, error) { diff --git a/pkg/certificate/manager.go b/pkg/certificate/manager.go index 8795503087ce..845cb0551ce9 100644 --- a/pkg/certificate/manager.go +++ b/pkg/certificate/manager.go @@ -65,8 +65,8 @@ type Manager struct { // EnsureCA makes sure the given CA certs and key is created. func (m *Manager) EnsureCA(name, cn string) error { - keyFile := filepath.Join(m.K0sVars.CertRootDir, fmt.Sprintf("%s.key", name)) - certFile := filepath.Join(m.K0sVars.CertRootDir, fmt.Sprintf("%s.crt", name)) + keyFile := filepath.Join(m.K0sVars.CertRootDir, name+".key") + certFile := filepath.Join(m.K0sVars.CertRootDir, name+".crt") if file.Exists(keyFile) && file.Exists(certFile) { return nil @@ -101,8 +101,8 @@ func (m *Manager) EnsureCA(name, cn string) error { // EnsureCertificate creates the specified certificate if it does not already exist func (m *Manager) EnsureCertificate(certReq Request, ownerID int) (Certificate, error) { - keyFile := filepath.Join(m.K0sVars.CertRootDir, fmt.Sprintf("%s.key", certReq.Name)) - certFile := filepath.Join(m.K0sVars.CertRootDir, fmt.Sprintf("%s.crt", certReq.Name)) + keyFile := filepath.Join(m.K0sVars.CertRootDir, certReq.Name+".key") + certFile := filepath.Join(m.K0sVars.CertRootDir, certReq.Name+".crt") // if regenerateCert returns true, it means we need to create the certs if m.regenerateCert(certReq, keyFile, certFile) { @@ -126,8 +126,8 @@ func (m *Manager) EnsureCertificate(certReq Request, ownerID int) (Certificate, return Certificate{}, err } config := cli.Config{ - CAFile: fmt.Sprintf("file:%s", certReq.CACert), - CAKeyFile: fmt.Sprintf("file:%s", certReq.CAKey), + CAFile: "file:" + certReq.CACert, + CAKeyFile: "file:" + certReq.CAKey, } s, err := sign.SignerFromConfig(config) if err != nil { @@ -228,8 +228,8 @@ func isManagedByK0s(cert *certinfo.Certificate) bool { } func (m *Manager) CreateKeyPair(name string, k0sVars *config.CfgVars, ownerID int) error { - keyFile := filepath.Join(k0sVars.CertRootDir, fmt.Sprintf("%s.key", name)) - pubFile := filepath.Join(k0sVars.CertRootDir, fmt.Sprintf("%s.pub", name)) + keyFile := filepath.Join(k0sVars.CertRootDir, name+".key") + pubFile := filepath.Join(k0sVars.CertRootDir, name+".pub") if file.Exists(keyFile) && file.Exists(pubFile) { return file.Chown(keyFile, ownerID, constant.CertSecureMode) diff --git a/pkg/cleanup/containers.go b/pkg/cleanup/containers.go index a3b063fcc896..f78d03200bd4 100644 --- a/pkg/cleanup/containers.go +++ b/pkg/cleanup/containers.go @@ -98,9 +98,9 @@ func (c *containers) isCustomCriUsed() bool { func (c *containers) startContainerd() error { logrus.Debugf("starting containerd") args := []string{ - fmt.Sprintf("--root=%s", filepath.Join(c.Config.dataDir, "containerd")), - fmt.Sprintf("--state=%s", filepath.Join(c.Config.runDir, "containerd")), - fmt.Sprintf("--address=%s", c.Config.containerd.socketPath), + "--root=" + filepath.Join(c.Config.dataDir, "containerd"), + "--state=" + filepath.Join(c.Config.runDir, "containerd"), + "--address=" + c.Config.containerd.socketPath, } if file.Exists("/etc/k0s/containerd.toml") { args = append(args, "--config=/etc/k0s/containerd.toml") diff --git a/pkg/component/controller/apiserver.go b/pkg/component/controller/apiserver.go index 7e3025978aef..65c9a5303b38 100644 --- a/pkg/component/controller/apiserver.go +++ b/pkg/component/controller/apiserver.go @@ -104,7 +104,7 @@ func (a *APIServer) Start(_ context.Context) error { logrus.Info("Starting kube-apiserver") args := stringmap.StringMap{ "advertise-address": a.ClusterConfig.Spec.API.Address, - "secure-port": fmt.Sprintf("%d", a.ClusterConfig.Spec.API.Port), + "secure-port": strconv.Itoa(a.ClusterConfig.Spec.API.Port), "authorization-mode": "Node,RBAC", "client-ca-file": path.Join(a.K0sVars.CertRootDir, "ca.crt"), "enable-bootstrap-token-auth": "true", @@ -263,17 +263,17 @@ func getEtcdArgs(storage *v1beta1.StorageSpec, k0sVars *config.CfgVars) ([]strin Scheme: "unix", OmitHost: true, Path: filepath.ToSlash(k0sVars.KineSocketPath), } // kine endpoint - args = append(args, fmt.Sprintf("--etcd-servers=%s", sockURL.String())) + args = append(args, "--etcd-servers="+sockURL.String()) case v1beta1.EtcdStorageType: - args = append(args, fmt.Sprintf("--etcd-servers=%s", storage.Etcd.GetEndpointsAsString())) + args = append(args, "--etcd-servers="+storage.Etcd.GetEndpointsAsString()) if storage.Etcd.IsTLSEnabled() { args = append(args, - fmt.Sprintf("--etcd-cafile=%s", storage.Etcd.GetCaFilePath(k0sVars.EtcdCertDir)), - fmt.Sprintf("--etcd-certfile=%s", storage.Etcd.GetCertFilePath(k0sVars.CertRootDir)), - fmt.Sprintf("--etcd-keyfile=%s", storage.Etcd.GetKeyFilePath(k0sVars.CertRootDir))) + "--etcd-cafile="+storage.Etcd.GetCaFilePath(k0sVars.EtcdCertDir), + "--etcd-certfile="+storage.Etcd.GetCertFilePath(k0sVars.CertRootDir), + "--etcd-keyfile="+storage.Etcd.GetKeyFilePath(k0sVars.CertRootDir)) } if storage.Etcd.IsExternalClusterUsed() { - args = append(args, fmt.Sprintf("--etcd-prefix=%s", storage.Etcd.ExternalCluster.EtcdPrefix)) + args = append(args, "--etcd-prefix="+storage.Etcd.ExternalCluster.EtcdPrefix) } default: return nil, fmt.Errorf("invalid storage type: %s", storage.Type) diff --git a/pkg/component/controller/calico.go b/pkg/component/controller/calico.go index 159caa5bbc04..6f37305c7036 100644 --- a/pkg/component/controller/calico.go +++ b/pkg/component/controller/calico.go @@ -120,7 +120,7 @@ func (c *Calico) dumpCRDs() error { for _, entry := range crds { filename := entry.Name() - manifestName := fmt.Sprintf("calico-crd-%s", filename) + manifestName := "calico-crd-" + filename output := bytes.NewBuffer([]byte{}) @@ -130,7 +130,7 @@ func (c *Calico) dumpCRDs() error { } tw := templatewriter.TemplateWriter{ - Name: fmt.Sprintf("calico-crd-%s", strings.TrimSuffix(filename, filepath.Ext(filename))), + Name: "calico-crd-" + strings.TrimSuffix(filename, filepath.Ext(filename)), Template: string(contents), Data: emptyStruct, } diff --git a/pkg/component/controller/controllersleasecounter.go b/pkg/component/controller/controllersleasecounter.go index 41f24c6365ad..639e755ded08 100644 --- a/pkg/component/controller/controllersleasecounter.go +++ b/pkg/component/controller/controllersleasecounter.go @@ -65,7 +65,7 @@ func (l *K0sControllersLeaseCounter) Start(context.Context) error { if err != nil { return nil } - leaseName := fmt.Sprintf("k0s-ctrl-%s", nodeName) + leaseName := "k0s-ctrl-" + nodeName leasePool, err := leaderelection.NewLeasePool(client, leaseName, l.InvocationID, leaderelection.WithLogger(log)) diff --git a/pkg/component/controller/csrapprover.go b/pkg/component/controller/csrapprover.go index bee2aa312649..2551836afb5f 100644 --- a/pkg/component/controller/csrapprover.go +++ b/pkg/component/controller/csrapprover.go @@ -20,6 +20,7 @@ import ( "context" "crypto/x509" "encoding/pem" + "errors" "fmt" "time" @@ -210,7 +211,7 @@ func parseCSR(obj *v1.CertificateSigningRequest) (*x509.CertificateRequest, erro pemBytes := obj.Spec.Request block, _ := pem.Decode(pemBytes) if block == nil || block.Type != "CERTIFICATE REQUEST" { - return nil, fmt.Errorf("PEM block type must be CERTIFICATE REQUEST") + return nil, errors.New("PEM block type must be CERTIFICATE REQUEST") } csr, err := x509.ParseCertificateRequest(block.Bytes) if err != nil { diff --git a/pkg/component/controller/etcd.go b/pkg/component/controller/etcd.go index 6c2cc79475cf..8a5657df68ff 100644 --- a/pkg/component/controller/etcd.go +++ b/pkg/component/controller/etcd.go @@ -217,7 +217,7 @@ func (e *Etcd) Start(ctx context.Context) error { } for name, value := range e.Config.ExtraArgs { - argName := fmt.Sprintf("--%s", name) + argName := "--" + name if _, ok := args[argName]; ok { logrus.Warnf("overriding etcd flag with user provided value: %s", argName) } diff --git a/pkg/component/controller/etcd_member_reconciler.go b/pkg/component/controller/etcd_member_reconciler.go index a9654c66c472..81a0eb38ed8d 100644 --- a/pkg/component/controller/etcd_member_reconciler.go +++ b/pkg/component/controller/etcd_member_reconciler.go @@ -182,7 +182,7 @@ func (e *EtcdMemberReconciler) createMemberObject(ctx context.Context) error { } // Convert the memberID to hex string - memberIDStr := fmt.Sprintf("%x", memberID) + memberIDStr := strconv.FormatUint(memberID, 16) name, err := e.etcdConfig.GetNodeName() if err != nil { diff --git a/pkg/component/controller/k0scontrolapi.go b/pkg/component/controller/k0scontrolapi.go index e8793998804a..64da68b51e76 100644 --- a/pkg/component/controller/k0scontrolapi.go +++ b/pkg/component/controller/k0scontrolapi.go @@ -18,7 +18,6 @@ package controller import ( "context" - "fmt" "os" "github.com/k0sproject/k0s/pkg/component/manager" @@ -56,7 +55,7 @@ func (m *K0SControlAPI) Start(_ context.Context) error { DataDir: m.K0sVars.DataDir, Args: []string{ "api", - fmt.Sprintf("--data-dir=%s", m.K0sVars.DataDir), + "--data-dir=" + m.K0sVars.DataDir, }, } diff --git a/pkg/component/controller/kine.go b/pkg/component/controller/kine.go index 6b1f30781d9a..8bf5de2b497a 100644 --- a/pkg/component/controller/kine.go +++ b/pkg/component/controller/kine.go @@ -119,11 +119,11 @@ func (k *Kine) Start(ctx context.Context) error { DataDir: k.K0sVars.DataDir, RunDir: k.K0sVars.RunDir, Args: []string{ - fmt.Sprintf("--endpoint=%s", k.Config.DataSource), + "--endpoint=" + k.Config.DataSource, // NB: kine doesn't parse URLs properly, so construct potentially // invalid URLs that are understood by kine. // https://github.com/k3s-io/kine/blob/v0.13.5/pkg/util/network.go#L5-L13 - fmt.Sprintf("--listen-address=unix://%s", k.K0sVars.KineSocketPath), + "--listen-address=unix://" + k.K0sVars.KineSocketPath, // Enable metrics on port 2380. The default is 8080, which clashes with kube-router. "--metrics-bind-address=:2380", }, diff --git a/pkg/component/controller/konnectivity.go b/pkg/component/controller/konnectivity.go index 9695d542526c..300b237df3ed 100644 --- a/pkg/component/controller/konnectivity.go +++ b/pkg/component/controller/konnectivity.go @@ -149,8 +149,8 @@ func (k *Konnectivity) serverArgs(count uint) []string { "--kubeconfig": k.K0sVars.KonnectivityKubeConfigPath, "--mode": "grpc", "--server-port": "0", - "--agent-port": fmt.Sprintf("%d", k.clusterConfig.Spec.Konnectivity.AgentPort), - "--admin-port": fmt.Sprintf("%d", k.clusterConfig.Spec.Konnectivity.AdminPort), + "--agent-port": strconv.FormatInt(int64(k.clusterConfig.Spec.Konnectivity.AgentPort), 10), + "--admin-port": strconv.FormatInt(int64(k.clusterConfig.Spec.Konnectivity.AdminPort), 10), "--health-bind-address": "localhost", "--health-port": "8092", "--agent-namespace": "kube-system", diff --git a/pkg/component/controller/kuberouter.go b/pkg/component/controller/kuberouter.go index 9f4bb43a9805..381443bc051e 100644 --- a/pkg/component/controller/kuberouter.go +++ b/pkg/component/controller/kuberouter.go @@ -21,6 +21,7 @@ import ( "context" "fmt" "reflect" + "strconv" "github.com/k0sproject/k0s/internal/pkg/stringmap" "github.com/k0sproject/k0s/internal/pkg/templatewriter" @@ -119,10 +120,10 @@ func (k *KubeRouter) Reconcile(_ context.Context, clusterConfig *v1beta1.Cluster "bgp-graceful-restart": "true", "enable-ipv4": "true", // Args from config values - "enable-ipv6": fmt.Sprintf("%t", clusterConfig.Spec.Network.DualStack.Enabled), - "auto-mtu": fmt.Sprintf("%t", clusterConfig.Spec.Network.KubeRouter.IsAutoMTU()), - "metrics-port": fmt.Sprintf("%d", clusterConfig.Spec.Network.KubeRouter.MetricsPort), - "hairpin-mode": fmt.Sprintf("%t", globalHairpin), + "enable-ipv6": strconv.FormatBool(clusterConfig.Spec.Network.DualStack.Enabled), + "auto-mtu": strconv.FormatBool(clusterConfig.Spec.Network.KubeRouter.IsAutoMTU()), + "metrics-port": strconv.Itoa(clusterConfig.Spec.Network.KubeRouter.MetricsPort), + "hairpin-mode": strconv.FormatBool(globalHairpin), } // We should not add peering flags if the values are empty diff --git a/pkg/component/controller/kuberouter_test.go b/pkg/component/controller/kuberouter_test.go index 85c943b63f62..e6e6e62030e0 100644 --- a/pkg/component/controller/kuberouter_test.go +++ b/pkg/component/controller/kuberouter_test.go @@ -19,6 +19,7 @@ package controller import ( "context" "encoding/json" + "errors" "fmt" "testing" @@ -238,7 +239,7 @@ func findConfig(resources []*unstructured.Unstructured) (corev1.ConfigMap, error } } - return cm, fmt.Errorf("kube-router cm not found in manifests") + return cm, errors.New("kube-router cm not found in manifests") } func getKubeRouterPlugin(cm corev1.ConfigMap, pluginType string) (dig.Mapping, error) { @@ -249,7 +250,7 @@ func getKubeRouterPlugin(cm corev1.ConfigMap, pluginType string) (dig.Mapping, e } plugins, ok := data.Dig("plugins").([]interface{}) if !ok { - return data, fmt.Errorf("failed to dig plugins") + return data, errors.New("failed to dig plugins") } for _, p := range plugins { plugin := dig.Mapping(p.(map[string]interface{})) @@ -274,5 +275,5 @@ func findDaemonset(resources []*unstructured.Unstructured) (v1.DaemonSet, error) } } - return ds, fmt.Errorf("kube-router ds not found in manifests") + return ds, errors.New("kube-router ds not found in manifests") } diff --git a/pkg/component/controller/metricserver.go b/pkg/component/controller/metricserver.go index 100bc83d3254..f08c4fede7fa 100644 --- a/pkg/component/controller/metricserver.go +++ b/pkg/component/controller/metricserver.go @@ -18,6 +18,7 @@ package controller import ( "context" + "errors" "fmt" "math" "path" @@ -346,7 +347,7 @@ func (m *MetricServer) Reconcile(_ context.Context, clusterConfig *v1beta1.Clust // So that's 10m CPU and 30MiB mem per 10 nodes func (m *MetricServer) getConfig(ctx context.Context) (metricsConfig, error) { if m.clusterConfig == nil { - return metricsConfig{}, fmt.Errorf("cluster config not available yet") + return metricsConfig{}, errors.New("cluster config not available yet") } cfg := metricsConfig{ Image: m.clusterConfig.Spec.Images.MetricsServer.URI(), diff --git a/pkg/component/controller/noderole.go b/pkg/component/controller/noderole.go index 999f5830e0f5..e0ccc4cc1120 100644 --- a/pkg/component/controller/noderole.go +++ b/pkg/component/controller/noderole.go @@ -19,6 +19,7 @@ package controller import ( "context" "fmt" + "path" "strings" "time" @@ -113,7 +114,7 @@ func (n *NodeRole) ensureNodeLabel(ctx context.Context, client kubernetes.Interf } func (n *NodeRole) addNodeLabel(ctx context.Context, client kubernetes.Interface, node, key, value string) (*corev1.Node, error) { - keyPath := fmt.Sprintf("/metadata/labels/%s", jsonpointer.Escape(key)) + keyPath := path.Join("/metadata/labels", jsonpointer.Escape(key)) patch := fmt.Sprintf(`[{"op":"add", "path":"%s", "value":"%s" }]`, keyPath, value) return client.CoreV1().Nodes().Patch(ctx, node, types.JSONPatchType, []byte(patch), metav1.PatchOptions{}) } diff --git a/pkg/component/controller/windowsstackcomponent.go b/pkg/component/controller/windowsstackcomponent.go index 927248a2f6fa..c4aab160f65f 100644 --- a/pkg/component/controller/windowsstackcomponent.go +++ b/pkg/component/controller/windowsstackcomponent.go @@ -24,6 +24,7 @@ import ( "path" "path/filepath" "reflect" + "strconv" "strings" "time" @@ -157,7 +158,7 @@ func (n *WindowsStackComponent) makeRenderingContext(cfg *v1beta1.ClusterConfig) CNIBin: "c:\\\\opt\\\\cni\\\\bin", CNIConf: "c:\\\\opt\\\\cni\\\\conf", KubeAPIHost: cfg.Spec.API.Address, - KubeAPIPort: fmt.Sprintf("%d", cfg.Spec.API.Port), + KubeAPIPort: strconv.Itoa(cfg.Spec.API.Port), IPv4ServiceCIDR: cfg.Spec.Network.ServiceCIDR, Nameserver: dns, NodeImage: "calico/windows:v3.23.5", diff --git a/pkg/component/manager/manager.go b/pkg/component/manager/manager.go index 379d443a554b..d7c9ee969b25 100644 --- a/pkg/component/manager/manager.go +++ b/pkg/component/manager/manager.go @@ -19,6 +19,7 @@ package manager import ( "container/list" "context" + "errors" "fmt" "reflect" "strings" @@ -88,7 +89,7 @@ func (m *Manager) Start(ctx context.Context) error { perfTimer := performance.NewTimer("component-start").Buffer().Start() for _, comp := range m.Components { compName := reflect.TypeOf(comp).Elem().Name() - perfTimer.Checkpoint(fmt.Sprintf("running-%s", compName)) + perfTimer.Checkpoint("running-" + compName) logrus.Infof("starting %v", compName) if err := comp.Start(ctx); err != nil { _ = m.Stop() @@ -118,7 +119,7 @@ func (m *Manager) Stop() error { if err := component.Stop(); err != nil { logrus.Errorf("failed to stop component %s: %s", name, err.Error()) if ret == nil { - ret = fmt.Errorf("failed to stop components") + ret = errors.New("failed to stop components") } } else { logrus.Infof("stopped component %s", name) diff --git a/pkg/component/manager/manager_test.go b/pkg/component/manager/manager_test.go index 33dc4946359b..fbc79c94c3b8 100644 --- a/pkg/component/manager/manager_test.go +++ b/pkg/component/manager/manager_test.go @@ -18,11 +18,11 @@ package manager import ( "context" - "fmt" "testing" "time" proberPackage "github.com/k0sproject/k0s/pkg/component/prober" + "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -89,7 +89,7 @@ func TestManagerInitFail(t *testing.T) { ctx := context.Background() f1 := &Fake{ - InitErr: fmt.Errorf("failed"), + InitErr: assert.AnError, } m.Add(ctx, f1) @@ -113,7 +113,7 @@ func TestManagerRunFail(t *testing.T) { m.Add(ctx, f1) f2 := &Fake{ - RunErr: fmt.Errorf("failed"), + RunErr: assert.AnError, } m.Add(ctx, f2) @@ -145,7 +145,7 @@ func TestManagerHealthyFail(t *testing.T) { m.Add(ctx, f1) f2 := &Fake{ - HealthyErr: fmt.Errorf("failed"), + HealthyErr: assert.AnError, } m.Add(ctx, f2) diff --git a/pkg/component/prober/prober_test.go b/pkg/component/prober/prober_test.go index e88306d5e285..fce7a5c7c5e4 100644 --- a/pkg/component/prober/prober_test.go +++ b/pkg/component/prober/prober_test.go @@ -20,7 +20,6 @@ import ( "context" "encoding/json" "errors" - "fmt" "testing" "time" @@ -46,15 +45,15 @@ func TestHealthChecks(t *testing.T) { prober := testProber(5) prober.Register("test", &mockComponent{ - errors: []error{nil, nil, fmt.Errorf("test1 error"), nil, nil}, + errors: []error{nil, nil, errors.New("test1 error"), nil, nil}, }) prober.Register("test2", &mockComponent{ - errors: []error{nil, fmt.Errorf("test2 error"), nil, nil, nil}, + errors: []error{nil, errors.New("test2 error"), nil, nil, nil}, }) prober.Register("test3", &mockComponent{ - errors: []error{nil, nil, nil, nil, fmt.Errorf("test3 error")}, + errors: []error{nil, nil, nil, nil, errors.New("test3 error")}, }) prober.Run(context.Background()) st := prober.State(maxEvents) @@ -74,15 +73,15 @@ func TestHealthChecks(t *testing.T) { prober := testProber(5) prober.Register("test", &mockComponent{ - errors: []error{nil, nil, fmt.Errorf("test1 error"), nil, nil}, + errors: []error{nil, nil, errors.New("test1 error"), nil, nil}, }) prober.Register("test2", &mockComponent{ - errors: []error{nil, fmt.Errorf("test2 error"), nil, nil, nil}, + errors: []error{nil, errors.New("test2 error"), nil, nil, nil}, }) prober.Register("test3", &mockComponent{ - errors: []error{nil, nil, nil, nil, fmt.Errorf("test3 error")}, + errors: []error{nil, nil, nil, nil, errors.New("test3 error")}, }) prober.Run(context.Background()) st := prober.State(1) diff --git a/pkg/component/status/status.go b/pkg/component/status/status.go index 161d82bdfa4f..888f42ce4326 100644 --- a/pkg/component/status/status.go +++ b/pkg/component/status/status.go @@ -153,7 +153,7 @@ func (sh *statusHandler) getCurrentStatus(ctx context.Context) K0sStatus { if sh.client == nil { kubeClient, err := sh.buildWorkerSideKubeAPIClient(ctx) if err != nil { - status.WorkerToAPIConnectionStatus.Message = fmt.Sprintf("failed to create kube-api client required for kube-api status reports, probably kubelet failed to init: %s", err.Error()) + status.WorkerToAPIConnectionStatus.Message = "failed to create kube-api client required for kube-api status reports, probably kubelet failed to init: " + err.Error() return status } sh.client = kubeClient diff --git a/pkg/component/worker/config/loader_test.go b/pkg/component/worker/config/loader_test.go index 22ea42aeee0f..1146011d44b7 100644 --- a/pkg/component/worker/config/loader_test.go +++ b/pkg/component/worker/config/loader_test.go @@ -59,7 +59,7 @@ data: Kind: "ConfigMap", }, ObjectMeta: metav1.ObjectMeta{ - Name: fmt.Sprintf("worker-config-fake-%s", constant.KubernetesMajorMinorVersion), + Name: "worker-config-fake-" + constant.KubernetesMajorMinorVersion, Namespace: "kube-system", }, Data: map[string]string{ diff --git a/pkg/component/worker/containerd/component.go b/pkg/component/worker/containerd/component.go index d20227c9fd7c..718704d7dd49 100644 --- a/pkg/component/worker/containerd/component.go +++ b/pkg/component/worker/containerd/component.go @@ -151,11 +151,11 @@ func (c *Component) Start(ctx context.Context) error { RunDir: c.K0sVars.RunDir, DataDir: c.K0sVars.DataDir, Args: []string{ - fmt.Sprintf("--root=%s", filepath.Join(c.K0sVars.DataDir, "containerd")), - fmt.Sprintf("--state=%s", filepath.Join(c.K0sVars.RunDir, "containerd")), - fmt.Sprintf("--address=%s", socketPath), - fmt.Sprintf("--log-level=%s", c.LogLevel), - fmt.Sprintf("--config=%s", c.confPath), + "--root=" + filepath.Join(c.K0sVars.DataDir, "containerd"), + "--state=" + filepath.Join(c.K0sVars.RunDir, "containerd"), + "--address=" + socketPath, + "--log-level=" + c.LogLevel, + "--config=" + c.confPath, }, } diff --git a/pkg/component/worker/kubelet.go b/pkg/component/worker/kubelet.go index 0d27ce2374b9..0248607ab031 100644 --- a/pkg/component/worker/kubelet.go +++ b/pkg/component/worker/kubelet.go @@ -233,10 +233,11 @@ func (k *Kubelet) Stop() error { func (k *Kubelet) writeKubeletConfig(path string) error { var staticPodURL string if k.StaticPods != nil { - var err error - if staticPodURL, err = k.StaticPods.ManifestURL(); err != nil { + url, err := k.StaticPods.ManifestURL() + if err != nil { return err } + staticPodURL = url.String() } containerRuntimeEndpoint, err := GetContainerRuntimeEndpoint(k.CRISocket, k.K0sVars.RunDir) diff --git a/pkg/component/worker/nllb/reconciler_test.go b/pkg/component/worker/nllb/reconciler_test.go index 764f22f196ae..2bff91fa0610 100644 --- a/pkg/component/worker/nllb/reconciler_test.go +++ b/pkg/component/worker/nllb/reconciler_test.go @@ -20,6 +20,7 @@ import ( "context" "errors" "io/fs" + "net/url" "os" "path/filepath" "runtime" @@ -533,9 +534,9 @@ func (m *backendMock) updateAPIServers(apiServers []net.HostPort) error { type staticPodsMock struct{ mock.Mock } -func (m *staticPodsMock) ManifestURL() (string, error) { +func (m *staticPodsMock) ManifestURL() (*url.URL, error) { args := m.Called() - return args.String(0), args.Error(1) + return args.Get(0).(*url.URL), args.Error(1) } func (m *staticPodsMock) ClaimStaticPod(namespace, name string) (worker.StaticPod, error) { diff --git a/pkg/component/worker/ocibundle.go b/pkg/component/worker/ocibundle.go index 630443de6004..7883623e7ea6 100644 --- a/pkg/component/worker/ocibundle.go +++ b/pkg/component/worker/ocibundle.go @@ -214,7 +214,7 @@ func (a *OCIBundleReconciler) unpinOne(ctx context.Context, image images.Image, if err := SetImageSources(&image, sources); err != nil { return fmt.Errorf("failed to reset image sources: %w", err) } - _, err := isvc.Update(ctx, image, fmt.Sprintf("labels.%s", ImageSourcePathsLabel)) + _, err := isvc.Update(ctx, image, "labels."+ImageSourcePathsLabel) return err } @@ -302,8 +302,8 @@ func (a *OCIBundleReconciler) unpackBundle(ctx context.Context, client *containe } fieldpaths := []string{ - fmt.Sprintf("labels.%s", ImagePinnedLabel), - fmt.Sprintf("labels.%s", ImageSourcePathsLabel), + "labels." + ImagePinnedLabel, + "labels." + ImageSourcePathsLabel, } isvc := client.ImageService() diff --git a/pkg/component/worker/static_pods.go b/pkg/component/worker/static_pods.go index 3a4d4115dc6e..dcb7610ac856 100644 --- a/pkg/component/worker/static_pods.go +++ b/pkg/component/worker/static_pods.go @@ -25,6 +25,7 @@ import ( "math" "net" "net/http" + "net/url" "strings" "sync" "sync/atomic" @@ -45,7 +46,7 @@ import ( type StaticPods interface { // ManifestURL returns the HTTP URL that can be used by the kubelet to // obtain static pod manifests managed by this StaticPods instance. - ManifestURL() (string, error) + ManifestURL() (*url.URL, error) // ClaimStaticPod returns a new, empty StaticPod associated with the given // namespace and name. Note that only one StaticPod for a given combination @@ -96,9 +97,9 @@ type staticPods struct { contentPtr atomic.Value // Store only when mu is locked, concurrent Load is okay claimedPods map[staticPodID]*staticPod - manifestURL string // guaranteed to be initialized when started, immutable afterwards - stopSignal context.CancelFunc - stopped sync.WaitGroup + hostAddr string // guaranteed to be initialized when started, immutable afterwards + stopSignal context.CancelFunc + stopped sync.WaitGroup } var _ manager.Ready = (*staticPods)(nil) @@ -116,14 +117,14 @@ func NewStaticPods() interface { return staticPods } -func (s *staticPods) ManifestURL() (string, error) { +func (s *staticPods) ManifestURL() (*url.URL, error) { if lifecycle := s.peekLifecycle(); lifecycle < staticPodsStarted { - return "", staticPodsNotYet(staticPodsStarted) + return nil, staticPodsNotYet(staticPodsStarted) } s.mu.Lock() defer s.mu.Unlock() - return s.manifestURL, nil + return &url.URL{Scheme: "http", Host: s.hostAddr, Path: "/manifests"}, nil } func (s *staticPods) ClaimStaticPod(namespace, name string) (StaticPod, error) { @@ -382,7 +383,7 @@ func (s *staticPods) Start(ctx context.Context) error { }() // Store the handles. - s.manifestURL = fmt.Sprintf("http://%s/manifests", addr) + s.hostAddr = addr s.stopSignal = cancelFunc // This instance started successfully, everything is setup and running. @@ -482,7 +483,7 @@ func (s *staticPods) Ready() error { return err } - req, err := http.NewRequest(http.MethodGet, fmt.Sprintf("%s/_healthz", url), nil) + req, err := http.NewRequest(http.MethodGet, url.JoinPath("_healthz").String(), nil) if err != nil { return err } diff --git a/pkg/component/worker/static_pods_test.go b/pkg/component/worker/static_pods_test.go index 6596874aa320..f8655b7c5c72 100644 --- a/pkg/component/worker/static_pods_test.go +++ b/pkg/component/worker/static_pods_test.go @@ -280,7 +280,7 @@ func TestStaticPods_Lifecycle(t *testing.T) { url, err := underTest.ManifestURL() require.NoError(t, err) - req, err := http.NewRequest(http.MethodGet, url, nil) + req, err := http.NewRequest(http.MethodGet, url.String(), nil) require.NoError(t, err) ctx, cancel := context.WithTimeout(ctx, 3*time.Second) @@ -328,7 +328,7 @@ func TestStaticPods_Lifecycle(t *testing.T) { url, err := underTest.ManifestURL() require.NoError(t, err) - req, err := http.NewRequest(http.MethodGet, url, nil) + req, err := http.NewRequest(http.MethodGet, url.String(), nil) require.NoError(t, err) ctx, cancel := context.WithTimeout(ctx, 3*time.Second) diff --git a/pkg/component/worker/utils.go b/pkg/component/worker/utils.go index b567247be33c..655105552995 100644 --- a/pkg/component/worker/utils.go +++ b/pkg/component/worker/utils.go @@ -126,7 +126,7 @@ func BootstrapKubeletKubeconfig(ctx context.Context, k0sVars *config.CfgVars, wo // 4: None of the above, bail out. default: - return fmt.Errorf("neither regular nor bootstrap kubelet kubeconfig files exist and no join token given; dunno how to make kubelet authenticate to API server") + return errors.New("neither regular nor bootstrap kubelet kubeconfig files exist and no join token given; dunno how to make kubelet authenticate to API server") } kubeletCAPath := path.Join(k0sVars.CertRootDir, "ca.crt") diff --git a/pkg/config/cfgvars.go b/pkg/config/cfgvars.go index d27bcc7ba873..947252c069cb 100644 --- a/pkg/config/cfgvars.go +++ b/pkg/config/cfgvars.go @@ -235,11 +235,11 @@ func (c *CfgVars) NodeConfig() (*v1beta1.ClusterConfig, error) { } if c.origin == CfgVarsOriginRuntime { - return nil, fmt.Errorf("runtime config is not available") + return nil, errors.New("runtime config is not available") } if c.StartupConfigPath == "" { - return nil, fmt.Errorf("config path is not set") + return nil, errors.New("config path is not set") } var nodeConfig *v1beta1.ClusterConfig diff --git a/pkg/container/runtime/cri.go b/pkg/container/runtime/cri.go index 2a82509a7fae..00d3e4e5cbbc 100644 --- a/pkg/container/runtime/cri.go +++ b/pkg/container/runtime/cri.go @@ -18,6 +18,7 @@ package runtime import ( "context" + "errors" "fmt" "github.com/sirupsen/logrus" @@ -73,7 +74,7 @@ func (cri *CRIRuntime) RemoveContainer(ctx context.Context, id string) error { return fmt.Errorf("failed to create CRI runtime client: %w", err) } if client == nil { - return fmt.Errorf("failed to create CRI runtime client") + return errors.New("failed to create CRI runtime client") } request := &pb.RemovePodSandboxRequest{PodSandboxId: id} logrus.Debugf("RemovePodSandboxRequest: %v", request) @@ -93,7 +94,7 @@ func (cri *CRIRuntime) StopContainer(ctx context.Context, id string) error { return fmt.Errorf("failed to create CRI runtime client: %w", err) } if client == nil { - return fmt.Errorf("failed to create CRI runtime client") + return errors.New("failed to create CRI runtime client") } request := &pb.StopPodSandboxRequest{PodSandboxId: id} logrus.Debugf("StopPodSandboxRequest: %v", request) diff --git a/pkg/install/service.go b/pkg/install/service.go index 42c4cf13e5ca..c7cccd5d4b1c 100644 --- a/pkg/install/service.go +++ b/pkg/install/service.go @@ -62,7 +62,7 @@ func InstalledService() (service.Service, error) { } var s service.Service - return s, fmt.Errorf("k0s has not been installed as a service") + return s, errors.New("k0s has not been installed as a service") } // EnsureService installs the k0s service, per the given arguments, and the detected platform diff --git a/pkg/leaderelection/client.go b/pkg/leaderelection/client.go index 70b71965e28c..3736c5da5f0d 100644 --- a/pkg/leaderelection/client.go +++ b/pkg/leaderelection/client.go @@ -19,7 +19,7 @@ package leaderelection import ( "cmp" "context" - "fmt" + "errors" "sync/atomic" "time" @@ -64,13 +64,13 @@ type LeaseConfig struct { // Implements [Config]. func (c *LeaseConfig) buildLock() (resourcelock.Interface, error) { if c.Namespace == "" { - return nil, fmt.Errorf("namespace may not be empty") + return nil, errors.New("namespace may not be empty") } if c.Name == "" { - return nil, fmt.Errorf("name may not be empty") + return nil, errors.New("name may not be empty") } if c.Client == nil { - return nil, fmt.Errorf("client may not be nil") + return nil, errors.New("client may not be nil") } return &resourcelock.LeaseLock{ diff --git a/pkg/supervisor/supervisor.go b/pkg/supervisor/supervisor.go index bcf4bc85f954..b4dd9568a289 100644 --- a/pkg/supervisor/supervisor.go +++ b/pkg/supervisor/supervisor.go @@ -357,7 +357,7 @@ func (s *Supervisor) shouldKillProcess(ph procHandle) (bool, error) { // - inject k0s embedded bins into path func getEnv(dataDir, component string, keepEnvPrefix bool) []string { env := os.Environ() - componentPrefix := fmt.Sprintf("%s_", strings.ToUpper(component)) + componentPrefix := strings.ToUpper(component) + "_" // put the component specific env vars in the front. sort.Slice(env, func(i, j int) bool { return strings.HasPrefix(env[i], componentPrefix) }) @@ -390,7 +390,7 @@ func getEnv(dataDir, component string, keepEnvPrefix bool) []string { } switch k { case "PATH": - env[i] = fmt.Sprintf("PATH=%s", dir.PathListJoin(path.Join(dataDir, "bin"), v)) + env[i] = "PATH=" + dir.PathListJoin(path.Join(dataDir, "bin"), v) default: env[i] = fmt.Sprintf("%s=%s", k, v) } diff --git a/pkg/telemetry/telemetry.go b/pkg/telemetry/telemetry.go index f3cb447c6bf6..ff4c986d4631 100644 --- a/pkg/telemetry/telemetry.go +++ b/pkg/telemetry/telemetry.go @@ -160,6 +160,6 @@ func addCustomData(ctx context.Context, analyticCtx *analytics.Context, clients return } for k, v := range cm.Data { - analyticCtx.Extra[fmt.Sprintf("custom.%s", k)] = v + analyticCtx.Extra["custom."+k] = v } } diff --git a/pkg/token/manager.go b/pkg/token/manager.go index c059e5ec1b13..194330040a5a 100644 --- a/pkg/token/manager.go +++ b/pkg/token/manager.go @@ -72,7 +72,7 @@ func RandomBootstrapSecret(role string, valid time.Duration) (*corev1.Secret, st s := corev1.Secret{ ObjectMeta: metav1.ObjectMeta{ - Name: fmt.Sprintf("bootstrap-token-%s", tokenID), + Name: "bootstrap-token-" + tokenID, Namespace: "kube-system", }, Type: corev1.SecretTypeBootstrapToken, @@ -144,7 +144,7 @@ func (m *Manager) List(ctx context.Context, role string) ([]Token, error) { } func (m *Manager) Remove(ctx context.Context, tokenID string) error { - err := m.client.CoreV1().Secrets("kube-system").Delete(ctx, fmt.Sprintf("bootstrap-token-%s", tokenID), metav1.DeleteOptions{}) + err := m.client.CoreV1().Secrets("kube-system").Delete(ctx, "bootstrap-token-"+tokenID, metav1.DeleteOptions{}) if errors.IsNotFound(err) { return nil }