From 170d5ef9fa0741505e9fa514bd793c6083c9ed21 Mon Sep 17 00:00:00 2001 From: SataQiu Date: Wed, 26 Apr 2023 23:22:20 +0800 Subject: [PATCH] code cleanup for kubeadm --- .../app/apis/bootstraptoken/v1/utils.go | 2 +- .../app/apis/bootstraptoken/v1/utils_test.go | 5 +++-- cmd/kubeadm/app/cmd/config.go | 2 +- cmd/kubeadm/app/cmd/phases/init/addons.go | 2 +- cmd/kubeadm/app/cmd/phases/join/data_test.go | 10 ++++----- cmd/kubeadm/app/cmd/upgrade/diff_test.go | 2 +- cmd/kubeadm/app/cmd/upgrade/node.go | 2 +- cmd/kubeadm/app/constants/constants.go | 10 ++++----- cmd/kubeadm/app/features/features.go | 8 +++---- .../app/phases/controlplane/volumes_test.go | 2 +- cmd/kubeadm/app/phases/upgrade/health.go | 4 ++-- cmd/kubeadm/app/preflight/checks.go | 22 +++++++++---------- cmd/kubeadm/app/util/initsystem/initsystem.go | 2 +- .../app/util/pkiutil/testing/testing.go | 2 +- cmd/kubeadm/app/util/staticpod/utils.go | 2 +- cmd/kubeadm/app/util/version.go | 2 +- 16 files changed, 40 insertions(+), 39 deletions(-) diff --git a/cmd/kubeadm/app/apis/bootstraptoken/v1/utils.go b/cmd/kubeadm/app/apis/bootstraptoken/v1/utils.go index 19d6394b3d7d..fbc8c1f7611a 100644 --- a/cmd/kubeadm/app/apis/bootstraptoken/v1/utils.go +++ b/cmd/kubeadm/app/apis/bootstraptoken/v1/utils.go @@ -102,7 +102,7 @@ func BootstrapTokenToSecret(bt *BootstrapToken) *v1.Secret { Name: bootstraputil.BootstrapTokenSecretName(bt.Token.ID), Namespace: metav1.NamespaceSystem, }, - Type: v1.SecretType(bootstrapapi.SecretTypeBootstrapToken), + Type: bootstrapapi.SecretTypeBootstrapToken, Data: encodeTokenSecretData(bt, time.Now()), } } diff --git a/cmd/kubeadm/app/apis/bootstraptoken/v1/utils_test.go b/cmd/kubeadm/app/apis/bootstraptoken/v1/utils_test.go index 490869c91f08..d7e36065a699 100644 --- a/cmd/kubeadm/app/apis/bootstraptoken/v1/utils_test.go +++ b/cmd/kubeadm/app/apis/bootstraptoken/v1/utils_test.go @@ -26,6 +26,7 @@ import ( v1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + bootstrapapi "k8s.io/cluster-bootstrap/token/api" ) func TestMarshalJSON(t *testing.T) { @@ -275,7 +276,7 @@ func TestBootstrapTokenToSecret(t *testing.T) { Name: "bootstrap-token-abcdef", Namespace: "kube-system", }, - Type: v1.SecretType("bootstrap.kubernetes.io/token"), + Type: bootstrapapi.SecretTypeBootstrapToken, Data: map[string][]byte{ "token-id": []byte("abcdef"), "token-secret": []byte("abcdef0123456789"), @@ -648,7 +649,7 @@ func TestBootstrapTokenFromSecret(t *testing.T) { Name: rt.name, Namespace: "kube-system", }, - Type: v1.SecretType("bootstrap.kubernetes.io/token"), + Type: bootstrapapi.SecretTypeBootstrapToken, Data: rt.data, }) if (err != nil) != rt.expectedError { diff --git a/cmd/kubeadm/app/cmd/config.go b/cmd/kubeadm/app/cmd/config.go index c02f5806d45b..3881321dc616 100644 --- a/cmd/kubeadm/app/cmd/config.go +++ b/cmd/kubeadm/app/cmd/config.go @@ -173,7 +173,7 @@ var legacyKindToGroupMap = map[string]string{ func getSupportedComponentConfigKinds() []string { objects := []string{} for componentType := range legacyKindToGroupMap { - objects = append(objects, string(componentType)) + objects = append(objects, componentType) } sort.Strings(objects) return objects diff --git a/cmd/kubeadm/app/cmd/phases/init/addons.go b/cmd/kubeadm/app/cmd/phases/init/addons.go index e76a3bdff986..e8438080ebc0 100644 --- a/cmd/kubeadm/app/cmd/phases/init/addons.go +++ b/cmd/kubeadm/app/cmd/phases/init/addons.go @@ -42,7 +42,7 @@ var ( Install the kube-proxy addon components via the API server. `) - printManifest bool = false + printManifest = false ) // NewAddonPhase returns the addon Cobra command diff --git a/cmd/kubeadm/app/cmd/phases/join/data_test.go b/cmd/kubeadm/app/cmd/phases/join/data_test.go index 94762f5908f8..c03e06bea1b9 100644 --- a/cmd/kubeadm/app/cmd/phases/join/data_test.go +++ b/cmd/kubeadm/app/cmd/phases/join/data_test.go @@ -40,8 +40,8 @@ func (j *testJoinData) Client() (clientset.Interface, error) { return func (j *testJoinData) IgnorePreflightErrors() sets.Set[string] { return nil } func (j *testJoinData) OutputWriter() io.Writer { return nil } func (j *testJoinData) PatchesDir() string { return "" } -func (t *testJoinData) DryRun() bool { return false } -func (t *testJoinData) KubeConfigDir() string { return "" } -func (t *testJoinData) KubeletDir() string { return "" } -func (t *testJoinData) ManifestDir() string { return "" } -func (t *testJoinData) CertificateWriteDir() string { return "" } +func (j *testJoinData) DryRun() bool { return false } +func (j *testJoinData) KubeConfigDir() string { return "" } +func (j *testJoinData) KubeletDir() string { return "" } +func (j *testJoinData) ManifestDir() string { return "" } +func (j *testJoinData) CertificateWriteDir() string { return "" } diff --git a/cmd/kubeadm/app/cmd/upgrade/diff_test.go b/cmd/kubeadm/app/cmd/upgrade/diff_test.go index 63eace98a6fd..0e83b8a55fa1 100644 --- a/cmd/kubeadm/app/cmd/upgrade/diff_test.go +++ b/cmd/kubeadm/app/cmd/upgrade/diff_test.go @@ -33,7 +33,7 @@ func createTestRunDiffFile(contents []byte) (string, error) { if err != nil { return "", errors.Wrap(err, "failed to create temporary test file") } - if _, err := file.Write([]byte(contents)); err != nil { + if _, err := file.Write(contents); err != nil { return "", errors.Wrap(err, "failed to write to temporary test file") } if err := file.Close(); err != nil { diff --git a/cmd/kubeadm/app/cmd/upgrade/node.go b/cmd/kubeadm/app/cmd/upgrade/node.go index 2d4d59bf4c49..cd80528fa687 100644 --- a/cmd/kubeadm/app/cmd/upgrade/node.go +++ b/cmd/kubeadm/app/cmd/upgrade/node.go @@ -206,7 +206,7 @@ func (d *nodeData) IgnorePreflightErrors() sets.Set[string] { return d.ignorePreflightErrors } -// KubeconfigPath returns the path to the user kubeconfig file. +// KubeConfigPath returns the path to the user kubeconfig file. func (d *nodeData) KubeConfigPath() string { return d.kubeConfigPath } diff --git a/cmd/kubeadm/app/constants/constants.go b/cmd/kubeadm/app/constants/constants.go index 8dd7ae0b8499..6397747009d1 100644 --- a/cmd/kubeadm/app/constants/constants.go +++ b/cmd/kubeadm/app/constants/constants.go @@ -422,15 +422,15 @@ const ( // CgroupDriverSystemd holds the systemd driver type CgroupDriverSystemd = "systemd" - // The username of the user that kube-controller-manager runs as. + // KubeControllerManagerUserName is the username of the user that kube-controller-manager runs as. KubeControllerManagerUserName string = "kubeadm-kcm" - // The username of the user that kube-apiserver runs as. + // KubeAPIServerUserName is the username of the user that kube-apiserver runs as. KubeAPIServerUserName string = "kubeadm-kas" - // The username of the user that kube-scheduler runs as. + // KubeSchedulerUserName is the username of the user that kube-scheduler runs as. KubeSchedulerUserName string = "kubeadm-ks" - // The username of the user that etcd runs as. + // EtcdUserName is the username of the user that etcd runs as. EtcdUserName string = "kubeadm-etcd" - // The group of users that are allowed to read the service account private key. + // ServiceAccountKeyReadersGroupName is the group of users that are allowed to read the service account private key. ServiceAccountKeyReadersGroupName string = "kubeadm-sa-key-readers" ) diff --git a/cmd/kubeadm/app/features/features.go b/cmd/kubeadm/app/features/features.go index 154901da10a8..4f25912633ba 100644 --- a/cmd/kubeadm/app/features/features.go +++ b/cmd/kubeadm/app/features/features.go @@ -78,17 +78,17 @@ func ValidateVersion(allFeatures FeatureList, requestedFeatures map[string]bool, // Enabled indicates whether a feature name has been enabled func Enabled(featureList map[string]bool, featureName string) bool { - if enabled, ok := featureList[string(featureName)]; ok { + if enabled, ok := featureList[featureName]; ok { return enabled } - return InitFeatureGates[string(featureName)].Default + return InitFeatureGates[featureName].Default } // Supports indicates whether a feature name is supported on the given // feature set func Supports(featureList FeatureList, featureName string) bool { for k, v := range featureList { - if featureName == string(k) { + if featureName == k { return v.PreRelease != featuregate.Deprecated } } @@ -99,7 +99,7 @@ func Supports(featureList FeatureList, featureName string) bool { func Keys(featureList FeatureList) []string { var list []string for k := range featureList { - list = append(list, string(k)) + list = append(list, k) } return list } diff --git a/cmd/kubeadm/app/phases/controlplane/volumes_test.go b/cmd/kubeadm/app/phases/controlplane/volumes_test.go index c6e0d7337db7..9a481338b446 100644 --- a/cmd/kubeadm/app/phases/controlplane/volumes_test.go +++ b/cmd/kubeadm/app/phases/controlplane/volumes_test.go @@ -631,7 +631,7 @@ func TestAddExtraHostPathMounts(t *testing.T) { if _, ok := mounts.volumeMounts["component"][volumeName]; !ok { t.Errorf("Expected to find volume mount %q", volumeName) } - if *vol.HostPath.Type != v1.HostPathType(hostMount.PathType) { + if *vol.HostPath.Type != hostMount.PathType { t.Errorf("Expected to host path type %q", hostMount.PathType) } volMount := mounts.volumeMounts["component"][volumeName] diff --git a/cmd/kubeadm/app/phases/upgrade/health.go b/cmd/kubeadm/app/phases/upgrade/health.go index b9e47c1acdec..01df98258250 100644 --- a/cmd/kubeadm/app/phases/upgrade/health.go +++ b/cmd/kubeadm/app/phases/upgrade/health.go @@ -207,9 +207,9 @@ func deleteHealthCheckJob(client clientset.Interface, ns, jobName string) error // controlPlaneNodesReady checks whether all control-plane Nodes in the cluster are in the Running state func controlPlaneNodesReady(client clientset.Interface, _ *kubeadmapi.ClusterConfiguration) error { - selectorControlPlane := labels.SelectorFromSet(labels.Set(map[string]string{ + selectorControlPlane := labels.SelectorFromSet(map[string]string{ constants.LabelNodeRoleControlPlane: "", - })) + }) nodes, err := client.CoreV1().Nodes().List(context.TODO(), metav1.ListOptions{ LabelSelector: selectorControlPlane.String(), }) diff --git a/cmd/kubeadm/app/preflight/checks.go b/cmd/kubeadm/app/preflight/checks.go index 8382e4cadcac..1bff75aa87df 100644 --- a/cmd/kubeadm/app/preflight/checks.go +++ b/cmd/kubeadm/app/preflight/checks.go @@ -58,9 +58,9 @@ const ( bridgenf6 = "/proc/sys/net/bridge/bridge-nf-call-ip6tables" ipv4Forward = "/proc/sys/net/ipv4/ip_forward" ipv6DefaultForwarding = "/proc/sys/net/ipv6/conf/default/forwarding" - externalEtcdRequestTimeout = time.Duration(10 * time.Second) + externalEtcdRequestTimeout = 10 * time.Second externalEtcdRequestRetries = 3 - externalEtcdRequestInterval = time.Duration(5 * time.Second) + externalEtcdRequestInterval = 5 * time.Second ) var ( @@ -384,7 +384,7 @@ func (ipc InPathCheck) Check() (warnings, errs []error) { return nil, nil } -// HostnameCheck checks if hostname match dns sub domain regex. +// HostnameCheck checks if hostname match dns subdomain regex. // If hostname doesn't match this regex, kubelet will not launch static pods like kube-apiserver/kube-controller-manager and so on. type HostnameCheck struct { nodeName string @@ -395,7 +395,7 @@ func (HostnameCheck) Name() string { return "Hostname" } -// Check validates if hostname match dns sub domain regex. +// Check validates if hostname match dns subdomain regex. // Check hostname length and format func (hc HostnameCheck) Check() (warnings, errorList []error) { klog.V(1).Infoln("checking whether the given node name is valid and reachable using net.LookupHost") @@ -578,8 +578,8 @@ func (kubever KubernetesVersionCheck) Check() (warnings, errorList []error) { // Checks if k8sVersion greater or equal than the first unsupported versions by current version of kubeadm, // that is major.minor+1 (all patch and pre-releases versions included) - // NB. in semver patches number is a numeric, while prerelease is a string where numeric identifiers always have lower precedence than non-numeric identifiers. - // thus setting the value to x.y.0-0 we are defining the very first patch - prereleases within x.y minor release. + // NB. in semver patches number is a numeric, while pre-release is a string where numeric identifiers always have lower precedence than non-numeric identifiers. + // thus setting the value to x.y.0-0 we are defining the very first patch - pre-releases within x.y minor release. firstUnsupportedVersion := versionutil.MustParseSemantic(fmt.Sprintf("%d.%d.%s", kadmVersion.Major(), kadmVersion.Minor()+1, "0-0")) if k8sVersion.AtLeast(firstUnsupportedVersion) { return []error{errors.Errorf("Kubernetes version is greater than kubeadm version. Please consider to upgrade kubeadm. Kubernetes version: %s. Kubeadm version: %d.%d.x", k8sVersion, kadmVersion.Components()[0], kadmVersion.Components()[1])}, nil @@ -920,10 +920,10 @@ func InitNodeChecks(execer utilsexec.Interface, cfg *kubeadmapi.InitConfiguratio } // File content check for IPV4 and IPV6 are needed if it is: - // (dual stack) `--service-cidr` or `--pod-network-cidr` is set with an IPV4 and IPV6 CIDR, `--apiserver-advertise-address` is optional as it can be auto detected. + // (dual stack) `--service-cidr` or `--pod-network-cidr` is set with an IPV4 and IPV6 CIDR, `--apiserver-advertise-address` is optional as it can be auto-detected. // (single stack) which is decided by the `--apiserver-advertise-address`. // Note that for the case of dual stack, user might only give IPV6 CIDR for `--service-cidr` and leave the `--apiserver-advertise-address` a default value which will be - // auto detected and properly bound to an IPV4 address, this will make the cluster non-functional eventually. The case like this should be avoided by the validation instead, + // auto-detected and properly bound to an IPV4 address, this will make the cluster non-functional eventually. The case like this should be avoided by the validation instead, // i.e. We don't care whether the input values for those parameters are set correctly here but if it's an IPV4 scoped CIDR or address we will add the file content check for IPV4, // as does the IPV6. IPV4Check := false @@ -1105,7 +1105,7 @@ func RunPullImagesCheck(execer utilsexec.Interface, cfg *kubeadmapi.InitConfigur return RunChecks(checks, os.Stderr, ignorePreflightErrors) } -// RunChecks runs each check, displays it's warnings/errors, and once all +// RunChecks runs each check, displays its warnings/errors, and once all // are processed will exit if any errors occurred. func RunChecks(checks []Checker, ww io.Writer, ignorePreflightErrors sets.Set[string]) error { var errsBuffer bytes.Buffer @@ -1133,7 +1133,7 @@ func RunChecks(checks []Checker, ww io.Writer, ignorePreflightErrors sets.Set[st return nil } -// setHasItemOrAll is helper function that return true if item is present in the set (case insensitive) or special key 'all' is present +// setHasItemOrAll is helper function that return true if item is present in the set (case-insensitive) or special key 'all' is present func setHasItemOrAll(s sets.Set[string], item string) bool { if s.Has("all") || s.Has(strings.ToLower(item)) { return true @@ -1142,7 +1142,7 @@ func setHasItemOrAll(s sets.Set[string], item string) bool { } // normalizeURLString returns the normalized string, or an error if it can't be parsed into an URL object. -// It takes an URL string as input. +// It takes a URL string as input. func normalizeURLString(s string) (string, error) { u, err := url.Parse(s) if err != nil { diff --git a/cmd/kubeadm/app/util/initsystem/initsystem.go b/cmd/kubeadm/app/util/initsystem/initsystem.go index 48e152f0a9be..3c98ee8bb650 100644 --- a/cmd/kubeadm/app/util/initsystem/initsystem.go +++ b/cmd/kubeadm/app/util/initsystem/initsystem.go @@ -18,7 +18,7 @@ package initsystem // InitSystem is the interface that describe behaviors of an init system type InitSystem interface { - // return a string describing how to enable a service + // EnableCommand returns a string describing how to enable a service EnableCommand(service string) string // ServiceStart tries to start a specific service diff --git a/cmd/kubeadm/app/util/pkiutil/testing/testing.go b/cmd/kubeadm/app/util/pkiutil/testing/testing.go index 3e80f24a934c..6ddd94343231 100644 --- a/cmd/kubeadm/app/util/pkiutil/testing/testing.go +++ b/cmd/kubeadm/app/util/pkiutil/testing/testing.go @@ -39,7 +39,7 @@ func RunWithPrivateKeyFixtureDirectory(m *testing.M) { os.Exit(m.Run()) } -// Reset() indicates a new test is starting and previously returned private key fixtures may be reused. +// Reset indicates a new test is starting and previously returned private key fixtures may be reused. func Reset() { lock.Lock() defer lock.Unlock() diff --git a/cmd/kubeadm/app/util/staticpod/utils.go b/cmd/kubeadm/app/util/staticpod/utils.go index a5ff7cf4ccc0..0837c8705387 100644 --- a/cmd/kubeadm/app/util/staticpod/utils.go +++ b/cmd/kubeadm/app/util/staticpod/utils.go @@ -90,7 +90,7 @@ func ComponentPod(container v1.Container, volumes map[string]v1.Volume, annotati func ComponentResources(cpu string) v1.ResourceRequirements { return v1.ResourceRequirements{ Requests: v1.ResourceList{ - v1.ResourceName(v1.ResourceCPU): resource.MustParse(cpu), + v1.ResourceCPU: resource.MustParse(cpu), }, } } diff --git a/cmd/kubeadm/app/util/version.go b/cmd/kubeadm/app/util/version.go index fa5f137c79f3..297a9c81d001 100644 --- a/cmd/kubeadm/app/util/version.go +++ b/cmd/kubeadm/app/util/version.go @@ -35,7 +35,7 @@ import ( ) const ( - getReleaseVersionTimeout = time.Duration(10 * time.Second) + getReleaseVersionTimeout = 10 * time.Second ) var (