Skip to content

Commit

Permalink
Merge pull request k0sproject#5224 from twz123/perfsprint
Browse files Browse the repository at this point in the history
Enable perfsprint linter
  • Loading branch information
twz123 authored Nov 15, 2024
2 parents 15586ee + c0bc069 commit c4feec0
Show file tree
Hide file tree
Showing 106 changed files with 310 additions and 293 deletions.
1 change: 1 addition & 0 deletions .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
3 changes: 2 additions & 1 deletion cmd/airgap/listimages.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ limitations under the License.
package airgap

import (
"errors"
"fmt"

"github.com/k0sproject/k0s/pkg/airgap"
Expand All @@ -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()
Expand Down
11 changes: 7 additions & 4 deletions cmd/api/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import (
"context"
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"net/http"
"os"
Expand Down Expand Up @@ -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())
Expand All @@ -241,22 +242,24 @@ 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
}

parts := strings.Split(auth, "Bearer ")
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
}

Expand Down
3 changes: 2 additions & 1 deletion cmd/backup/backup_unix.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ limitations under the License.
package backup

import (
"errors"
"fmt"
"io"
"os"
Expand Down Expand Up @@ -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())
},
Expand Down
14 changes: 8 additions & 6 deletions cmd/controller/certificates.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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",
}
Expand Down
10 changes: 7 additions & 3 deletions cmd/controller/controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import (
"net"
"os"
"os/signal"
"path"
"path/filepath"
"slices"
"syscall"
Expand Down Expand Up @@ -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"
)

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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)
}
Expand Down
3 changes: 2 additions & 1 deletion cmd/etcd/etcd.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ limitations under the License.
package etcd

import (
"errors"
"fmt"

"github.com/k0sproject/k0s/pkg/apis/k0s/v1beta1"
Expand Down Expand Up @@ -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
},
Expand Down
7 changes: 4 additions & 3 deletions cmd/etcd/leave.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import (
"fmt"
"net"
"net/url"
"strconv"

"github.com/k0sproject/k0s/pkg/config"
"github.com/k0sproject/k0s/pkg/etcd"
Expand Down Expand Up @@ -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
Expand All @@ -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
},
Expand Down
3 changes: 2 additions & 1 deletion cmd/install/install.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ limitations under the License.
package install

import (
"errors"
"fmt"
"os"

Expand Down Expand Up @@ -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()
Expand Down
3 changes: 2 additions & 1 deletion cmd/kubectl/kubectl.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ limitations under the License.
package kubectl

import (
"errors"
"fmt"
"os"
"os/exec"
Expand Down Expand Up @@ -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 {
Expand Down
4 changes: 0 additions & 4 deletions cmd/reset/reset.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ package reset
import (
"fmt"
"os"
"runtime"

"github.com/k0sproject/k0s/pkg/cleanup"
"github.com/k0sproject/k0s/pkg/component/status"
Expand All @@ -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
Expand Down
3 changes: 2 additions & 1 deletion cmd/restore/restore_unix.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ limitations under the License.
package restore

import (
"errors"
"fmt"
"io"
"os"
Expand Down Expand Up @@ -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)
Expand Down
14 changes: 10 additions & 4 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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())
Expand Down Expand Up @@ -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")
},
}
}
Expand Down
6 changes: 3 additions & 3 deletions cmd/start/start.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ limitations under the License.
package start

import (
"fmt"
"errors"
"os"

"github.com/k0sproject/k0s/pkg/install"
Expand All @@ -32,15 +32,15 @@ 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 {
return err
}
status, _ := svc.Status()
if status == service.StatusRunning {
return fmt.Errorf("already running")
return errors.New("already running")
}
return svc.Start()
},
Expand Down
7 changes: 0 additions & 7 deletions cmd/status/status.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ import (
"fmt"
"io"
"path/filepath"
"runtime"

"github.com/k0sproject/k0s/pkg/component/status"
"github.com/k0sproject/k0s/pkg/config"
Expand All @@ -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 {
Expand Down Expand Up @@ -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 {
Expand Down
Loading

0 comments on commit c4feec0

Please sign in to comment.