Fix golangci-lint errors (#10196)

* Fix golangci-lint errors

Signed-off-by: z1cheng <imchench@gmail.com>

* Fix dupl errors

Signed-off-by: z1cheng <imchench@gmail.com>

* Fix comments

Signed-off-by: z1cheng <imchench@gmail.com>

* Fix errcheck lint errors

Signed-off-by: z1cheng <imchench@gmail.com>

* Fix assert in e2e test

Signed-off-by: z1cheng <imchench@gmail.com>

* Not interrupt the waitForPodsReady

Signed-off-by: z1cheng <imchench@gmail.com>

* Replace string with constant

Signed-off-by: z1cheng <imchench@gmail.com>

* Fix comments

Signed-off-by: z1cheng <imchench@gmail.com>

* Revert write file permision

Signed-off-by: z1cheng <imchench@gmail.com>

---------

Signed-off-by: z1cheng <imchench@gmail.com>
This commit is contained in:
Chen Chen 2023-08-31 15:36:48 +08:00 committed by GitHub
parent 46d87d3462
commit b3060bfbd0
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
253 changed files with 2434 additions and 2113 deletions

View file

@ -63,13 +63,14 @@ func CreateCommand(flags *genericclioptions.ConfigFlags) *cobra.Command {
return cmd
}
func backends(flags *genericclioptions.ConfigFlags, podName string, deployment string, selector string, container string, backend string, onlyList bool) error {
func backends(flags *genericclioptions.ConfigFlags, podName, deployment, selector, container, backend string, onlyList bool) error {
var command []string
if onlyList {
switch {
case onlyList:
command = []string{"/dbg", "backends", "list"}
} else if backend != "" {
case backend != "":
command = []string{"/dbg", "backends", "get", backend}
} else {
default:
command = []string{"/dbg", "backends", "all"}
}

View file

@ -59,7 +59,7 @@ func CreateCommand(flags *genericclioptions.ConfigFlags) *cobra.Command {
return cmd
}
func certs(flags *genericclioptions.ConfigFlags, podName string, deployment string, selector string, container string, host string) error {
func certs(flags *genericclioptions.ConfigFlags, podName, deployment, selector, container, host string) error {
command := []string{"/dbg", "certs", "get", host}
pod, err := request.ChoosePod(flags, podName, deployment, selector)

View file

@ -55,7 +55,7 @@ func CreateCommand(flags *genericclioptions.ConfigFlags) *cobra.Command {
return cmd
}
func conf(flags *genericclioptions.ConfigFlags, host string, podName string, deployment string, selector string, container string) error {
func conf(flags *genericclioptions.ConfigFlags, host, podName, deployment, selector, container string) error {
pod, err := request.ChoosePod(flags, podName, deployment, selector)
if err != nil {
return err

View file

@ -55,7 +55,7 @@ type execFlags struct {
Stdin bool
}
func exec(flags *genericclioptions.ConfigFlags, podName string, deployment string, selector string, container string, cmd []string, opts execFlags) error {
func exec(flags *genericclioptions.ConfigFlags, podName, deployment, selector, container string, cmd []string, opts execFlags) error {
pod, err := request.ChoosePod(flags, podName, deployment, selector)
if err != nil {
return err

View file

@ -47,7 +47,7 @@ func CreateCommand(flags *genericclioptions.ConfigFlags) *cobra.Command {
return cmd
}
func general(flags *genericclioptions.ConfigFlags, podName string, deployment string, selector string, container string) error {
func general(flags *genericclioptions.ConfigFlags, podName, deployment, selector, container string) error {
pod, err := request.ChoosePod(flags, podName, deployment, selector)
if err != nil {
return err

View file

@ -74,9 +74,9 @@ func ingresses(flags *genericclioptions.ConfigFlags, host string, allNamespaces
if host != "" {
rowsWithHost := make([]ingressRow, 0)
for _, row := range rows {
if row.Host == host {
rowsWithHost = append(rowsWithHost, row)
for i := range rows {
if rows[i].Host == host {
rowsWithHost = append(rowsWithHost, rows[i])
}
}
rows = rowsWithHost
@ -91,7 +91,8 @@ func ingresses(flags *genericclioptions.ConfigFlags, host string, allNamespaces
fmt.Fprintln(printer, "INGRESS NAME\tHOST+PATH\tADDRESSES\tTLS\tSERVICE\tSERVICE PORT\tENDPOINTS")
}
for _, row := range rows {
for i := range rows {
row := &rows[i]
var tlsMsg string
if row.TLS {
tlsMsg = "YES"
@ -134,8 +135,8 @@ type ingressRow struct {
func getIngressRows(ingresses *[]networking.Ingress) []ingressRow {
rows := make([]ingressRow, 0)
for _, ing := range *ingresses {
for i := range *ingresses {
ing := &(*ingresses)[i]
address := ""
for _, lbIng := range ing.Status.LoadBalancer.Ingress {
if len(lbIng.IP) > 0 {
@ -182,7 +183,7 @@ func getIngressRows(ingresses *[]networking.Ingress) []ingressRow {
for _, rule := range ing.Spec.Rules {
_, hasTLS := tlsHosts[rule.Host]
//Handle ingress with no paths
// Handle ingress with no paths
if rule.HTTP == nil {
row := ingressRow{
Namespace: ing.Namespace,

View file

@ -24,7 +24,6 @@ import (
)
func TestGetIngressInformation(t *testing.T) {
testcases := map[string]struct {
ServiceBackend *networking.IngressServiceBackend
wantName string

View file

@ -111,11 +111,13 @@ type lintOptions struct {
}
func (opts *lintOptions) Validate() error {
//nolint:dogsled // Ignore 3 blank identifiers
_, _, _, err := util.ParseVersionString(opts.versionFrom)
if err != nil {
return err
}
//nolint:dogsled // Ignore 3 blank identifiers
_, _, _, err = util.ParseVersionString(opts.versionTo)
if err != nil {
return err
@ -131,9 +133,9 @@ type lint interface {
Version() string
}
func checkObjectArray(lints []lint, objects []kmeta.Object, opts lintOptions) {
func checkObjectArray(allLints []lint, objects []kmeta.Object, opts lintOptions) {
usedLints := make([]lint, 0)
for _, lint := range lints {
for _, lint := range allLints {
lintVersion := lint.Version()
if lint.Version() == "" {
lintVersion = "0.0.0"
@ -189,7 +191,7 @@ func ingresses(opts lintOptions) error {
return err
}
var iLints []lints.IngressLint = lints.GetIngressLints()
iLints := lints.GetIngressLints()
genericLints := make([]lint, len(iLints))
for i := range iLints {
genericLints[i] = iLints[i]
@ -216,7 +218,7 @@ func deployments(opts lintOptions) error {
return err
}
var iLints []lints.DeploymentLint = lints.GetDeploymentLints()
iLints := lints.GetDeploymentLints()
genericLints := make([]lint, len(iLints))
for i := range iLints {
genericLints[i] = iLints[i]

View file

@ -95,7 +95,7 @@ func (o *logsFlags) toStrings() []string {
return r
}
func logs(flags *genericclioptions.ConfigFlags, podName string, deployment string, selector string, container string, opts logsFlags) error {
func logs(flags *genericclioptions.ConfigFlags, podName, deployment, selector, container string, opts logsFlags) error {
pod, err := request.ChoosePod(flags, podName, deployment, selector)
if err != nil {
return err

View file

@ -45,7 +45,7 @@ func CreateCommand(flags *genericclioptions.ConfigFlags) *cobra.Command {
return cmd
}
func ssh(flags *genericclioptions.ConfigFlags, podName string, deployment string, selector string, container string) error {
func ssh(flags *genericclioptions.ConfigFlags, podName, deployment, selector, container string) error {
pod, err := request.ChoosePod(flags, podName, deployment, selector)
if err != nil {
return err

View file

@ -38,11 +38,11 @@ func PodExecString(flags *genericclioptions.ConfigFlags, pod *apiv1.Pod, contain
// ExecToString runs a kubectl subcommand and returns stdout as a string
func ExecToString(flags *genericclioptions.ConfigFlags, args []string) (string, error) {
kArgs := getKubectlConfigFlags(flags)
kArgs = append(kArgs, args...)
kubectlArgs := getKubectlConfigFlags(flags)
kubectlArgs = append(kubectlArgs, args...)
buf := bytes.NewBuffer(make([]byte, 0))
err := execToWriter(append([]string{"kubectl"}, kArgs...), buf)
err := execToWriter(append([]string{"kubectl"}, kubectlArgs...), buf)
if err != nil {
return "", err
}
@ -51,9 +51,9 @@ func ExecToString(flags *genericclioptions.ConfigFlags, args []string) (string,
// Exec replaces the current process with a kubectl invocation
func Exec(flags *genericclioptions.ConfigFlags, args []string) error {
kArgs := getKubectlConfigFlags(flags)
kArgs = append(kArgs, args...)
return execCommand(append([]string{"kubectl"}, kArgs...))
kubectlArgs := getKubectlConfigFlags(flags)
kubectlArgs = append(kubectlArgs, args...)
return execCommand(append([]string{"kubectl"}, kubectlArgs...))
}
// Replaces the currently running process with the given command
@ -70,6 +70,7 @@ func execCommand(args []string) error {
// Runs a command and returns stdout
func execToWriter(args []string, writer io.Writer) error {
//nolint:gosec // Ignore G204 error
cmd := exec.Command(args[0], args[1:]...)
op, err := cmd.StdoutPipe()
@ -78,7 +79,7 @@ func execToWriter(args []string, writer io.Writer) error {
}
go func() {
io.Copy(writer, op) //nolint:errcheck
io.Copy(writer, op) //nolint:errcheck // Ignore the error
}()
err = cmd.Run()
if err != nil {
@ -106,7 +107,6 @@ func getKubectlConfigFlags(flags *genericclioptions.ConfigFlags) []string {
appendStringFlag(o, flags.Password, "password")
appendStringFlag(o, flags.ClusterName, "cluster")
appendStringFlag(o, flags.AuthInfoName, "user")
//appendStringFlag(o, flags.Namespace, "namespace")
appendStringFlag(o, flags.Context, "context")
appendStringFlag(o, flags.APIServer, "server")
appendBoolFlag(o, flags.Insecure, "insecure-skip-tls-verify")
@ -128,7 +128,7 @@ func appendBoolFlag(out *[]string, in *bool, flag string) {
}
}
func appendStringArrayFlag(out *[]string, in *[]string, flag string) {
func appendStringArrayFlag(out, in *[]string, flag string) {
if in != nil && len(*in) > 0 {
*out = append(*out, fmt.Sprintf("--%v=%v'", flag, strings.Join(*in, ",")))
}

View file

@ -35,7 +35,10 @@ type DeploymentLint struct {
// Check returns true if the lint detects an issue
func (lint DeploymentLint) Check(obj kmeta.Object) bool {
cmp := obj.(*v1.Deployment)
cmp, ok := obj.(*v1.Deployment)
if !ok {
util.PrintError(fmt.Errorf("unexpected type: %T", obj))
}
return lint.f(*cmp)
}
@ -72,11 +75,11 @@ func removedFlag(flag string, issueNumber int, version string) DeploymentLint {
issue: issueNumber,
version: version,
f: func(dep v1.Deployment) bool {
if !isIngressNginxDeployment(dep) {
if !isIngressNginxDeployment(&dep) {
return false
}
args := getNginxArgs(dep)
args := getNginxArgs(&dep)
for _, arg := range args {
if strings.HasPrefix(arg, fmt.Sprintf("--%v", flag)) {
return true
@ -88,8 +91,9 @@ func removedFlag(flag string, issueNumber int, version string) DeploymentLint {
}
}
func getNginxArgs(dep v1.Deployment) []string {
for _, container := range dep.Spec.Template.Spec.Containers {
func getNginxArgs(dep *v1.Deployment) []string {
for i := range dep.Spec.Template.Spec.Containers {
container := &dep.Spec.Template.Spec.Containers[i]
if len(container.Args) > 0 && container.Args[0] == "/nginx-ingress-controller" {
return container.Args
}
@ -97,10 +101,10 @@ func getNginxArgs(dep v1.Deployment) []string {
return make([]string, 0)
}
func isIngressNginxDeployment(dep v1.Deployment) bool {
func isIngressNginxDeployment(dep *v1.Deployment) bool {
containers := dep.Spec.Template.Spec.Containers
for _, container := range containers {
if len(container.Args) > 0 && container.Args[0] == "/nginx-ingress-controller" {
for i := range containers {
if len(containers[i].Args) > 0 && containers[i].Args[0] == "/nginx-ingress-controller" {
return true
}
}

View file

@ -30,13 +30,16 @@ type IngressLint struct {
message string
issue int
version string
f func(ing networking.Ingress) bool
f func(ing *networking.Ingress) bool
}
// Check returns true if the lint detects an issue
func (lint IngressLint) Check(obj kmeta.Object) bool {
ing := obj.(*networking.Ingress)
return lint.f(*ing)
ing, ok := obj.(*networking.Ingress)
if !ok {
util.PrintError(fmt.Errorf("unexpected type: %T", obj))
}
return lint.f(ing)
}
// Message is a description of the lint
@ -94,7 +97,7 @@ func GetIngressLints() []IngressLint {
}
}
func xForwardedPrefixIsBool(ing networking.Ingress) bool {
func xForwardedPrefixIsBool(ing *networking.Ingress) bool {
for name, val := range ing.Annotations {
if strings.HasSuffix(name, "/x-forwarded-prefix") && (val == "true" || val == "false") {
return true
@ -103,7 +106,7 @@ func xForwardedPrefixIsBool(ing networking.Ingress) bool {
return false
}
func annotationPrefixIsNginxCom(ing networking.Ingress) bool {
func annotationPrefixIsNginxCom(ing *networking.Ingress) bool {
for name := range ing.Annotations {
if strings.HasPrefix(name, "nginx.com/") {
return true
@ -112,7 +115,7 @@ func annotationPrefixIsNginxCom(ing networking.Ingress) bool {
return false
}
func annotationPrefixIsNginxOrg(ing networking.Ingress) bool {
func annotationPrefixIsNginxOrg(ing *networking.Ingress) bool {
for name := range ing.Annotations {
if strings.HasPrefix(name, "nginx.org/") {
return true
@ -121,7 +124,7 @@ func annotationPrefixIsNginxOrg(ing networking.Ingress) bool {
return false
}
func rewriteTargetWithoutCaptureGroup(ing networking.Ingress) bool {
func rewriteTargetWithoutCaptureGroup(ing *networking.Ingress) bool {
for name, val := range ing.Annotations {
if strings.HasSuffix(name, "/rewrite-target") && !strings.Contains(val, "$1") {
return true
@ -135,7 +138,7 @@ func removedAnnotation(annotationName string, issueNumber int, version string) I
message: fmt.Sprintf("Contains the removed %v annotation.", annotationName),
issue: issueNumber,
version: version,
f: func(ing networking.Ingress) bool {
f: func(ing *networking.Ingress) bool {
for annotation := range ing.Annotations {
if strings.HasSuffix(annotation, "/"+annotationName) {
return true
@ -146,7 +149,7 @@ func removedAnnotation(annotationName string, issueNumber int, version string) I
}
}
func satisfyDirective(ing networking.Ingress) bool {
func satisfyDirective(ing *networking.Ingress) bool {
for name, val := range ing.Annotations {
if strings.HasSuffix(name, "/configuration-snippet") {
return strings.Contains(val, "satisfy")

View file

@ -24,7 +24,7 @@ import (
"k8s.io/cli-runtime/pkg/genericclioptions"
//Just importing this is supposed to allow cloud authentication
// Just importing this is supposed to allow cloud authentication
// eg GCP, AWS, Azure ...
_ "k8s.io/client-go/plugin/pkg/client/auth"

View file

@ -35,7 +35,7 @@ import (
)
// ChoosePod finds a pod either by deployment or by name
func ChoosePod(flags *genericclioptions.ConfigFlags, podName string, deployment string, selector string) (apiv1.Pod, error) {
func ChoosePod(flags *genericclioptions.ConfigFlags, podName, deployment, selector string) (apiv1.Pod, error) {
if podName != "" {
return GetNamedPod(flags, podName)
}
@ -54,9 +54,9 @@ func GetNamedPod(flags *genericclioptions.ConfigFlags, name string) (apiv1.Pod,
return apiv1.Pod{}, err
}
for _, pod := range allPods {
if pod.Name == name {
return pod, nil
for i := range allPods {
if allPods[i].Name == name {
return allPods[i], nil
}
}
@ -132,7 +132,7 @@ func GetIngressDefinitions(flags *genericclioptions.ConfigFlags, namespace strin
}
// GetNumEndpoints counts the number of endpointslices adresses for the service with the given name
func GetNumEndpoints(flags *genericclioptions.ConfigFlags, namespace string, serviceName string) (*int, error) {
func GetNumEndpoints(flags *genericclioptions.ConfigFlags, namespace, serviceName string) (*int, error) {
epss, err := GetEndpointSlicesByName(flags, namespace, serviceName)
if err != nil {
return nil, err
@ -143,25 +143,26 @@ func GetNumEndpoints(flags *genericclioptions.ConfigFlags, namespace string, ser
}
ret := 0
for _, eps := range epss {
for _, ep := range eps.Endpoints {
ret += len(ep.Addresses)
for i := range epss {
eps := &epss[i]
for j := range eps.Endpoints {
ret += len(eps.Endpoints[j].Addresses)
}
}
return &ret, nil
}
// GetEndpointSlicesByName returns the endpointSlices for the service with the given name
func GetEndpointSlicesByName(flags *genericclioptions.ConfigFlags, namespace string, name string) ([]discoveryv1.EndpointSlice, error) {
func GetEndpointSlicesByName(flags *genericclioptions.ConfigFlags, namespace, name string) ([]discoveryv1.EndpointSlice, error) {
allEndpointsSlices, err := getEndpointSlices(flags, namespace)
if err != nil {
return nil, err
}
var eps []discoveryv1.EndpointSlice
for _, slice := range allEndpointsSlices {
if svcName, ok := slice.ObjectMeta.GetLabels()[discoveryv1.LabelServiceName]; ok {
for i := range allEndpointsSlices {
if svcName, ok := allEndpointsSlices[i].ObjectMeta.GetLabels()[discoveryv1.LabelServiceName]; ok {
if svcName == name {
eps = append(eps, slice)
eps = append(eps, allEndpointsSlices[i])
}
}
}
@ -182,7 +183,7 @@ func getEndpointSlices(flags *genericclioptions.ConfigFlags, namespace string) (
tryAllNamespacesEndpointSlicesCache(flags)
}
cachedEndpointSlices = tryFilteringEndpointSlicesFromAllNamespacesCache(flags, namespace)
cachedEndpointSlices = tryFilteringEndpointSlicesFromAllNamespacesCache(namespace)
if cachedEndpointSlices != nil {
return *cachedEndpointSlices, nil
@ -217,13 +218,13 @@ func tryAllNamespacesEndpointSlicesCache(flags *genericclioptions.ConfigFlags) {
}
}
func tryFilteringEndpointSlicesFromAllNamespacesCache(flags *genericclioptions.ConfigFlags, namespace string) *[]discoveryv1.EndpointSlice {
func tryFilteringEndpointSlicesFromAllNamespacesCache(namespace string) *[]discoveryv1.EndpointSlice {
allEndpointSlices := endpointSlicesCache[""]
if allEndpointSlices != nil {
endpointSlices := make([]discoveryv1.EndpointSlice, 0)
for _, slice := range *allEndpointSlices {
if slice.Namespace == namespace {
endpointSlices = append(endpointSlices, slice)
for i := range *allEndpointSlices {
if (*allEndpointSlices)[i].Namespace == namespace {
endpointSlices = append(endpointSlices, (*allEndpointSlices)[i])
}
}
endpointSlicesCache[namespace] = &endpointSlices
@ -242,9 +243,9 @@ func GetServiceByName(flags *genericclioptions.ConfigFlags, name string, service
services = &servicesArray
}
for _, svc := range *services {
if svc.Name == name {
return svc, nil
for i := range *services {
if (*services)[i].Name == name {
return (*services)[i], nil
}
}
@ -288,7 +289,6 @@ func getLabeledPods(flags *genericclioptions.ConfigFlags, label string) ([]apiv1
pods, err := api.Pods(namespace).List(context.TODO(), metav1.ListOptions{
LabelSelector: label,
})
if err != nil {
return make([]apiv1.Pod, 0), err
}
@ -303,9 +303,9 @@ func getDeploymentPods(flags *genericclioptions.ConfigFlags, deployment string)
}
ingressPods := make([]apiv1.Pod, 0)
for _, pod := range pods {
if util.PodInDeployment(pod, deployment) {
ingressPods = append(ingressPods, pod)
for i := range pods {
if util.PodInDeployment(&pods[i], deployment) {
ingressPods = append(ingressPods, pods[i])
}
}
@ -331,5 +331,4 @@ func getServices(flags *genericclioptions.ConfigFlags) ([]apiv1.Service, error)
}
return services.Items, nil
}

View file

@ -47,17 +47,25 @@ func PrintError(e error) {
}
// ParseVersionString returns the major, minor, and patch numbers of a version string
func ParseVersionString(v string) (int, int, int, error) {
func ParseVersionString(v string) (major, minor, patch int, err error) {
parts := versionRegex.FindStringSubmatch(v)
if len(parts) != 4 {
return 0, 0, 0, fmt.Errorf("could not parse %v as a version string (like 0.20.3)", v)
}
major, _ := strconv.Atoi(parts[1])
minor, _ := strconv.Atoi(parts[2])
patch, _ := strconv.Atoi(parts[3])
major, err = strconv.Atoi(parts[1])
if err != nil {
return 0, 0, 0, err
}
minor, err = strconv.Atoi(parts[2])
if err != nil {
return 0, 0, 0, err
}
patch, err = strconv.Atoi(parts[3])
if err != nil {
return 0, 0, 0, err
}
return major, minor, patch, nil
}
@ -90,7 +98,7 @@ func isVersionLessThan(a, b string) bool {
// PodInDeployment returns whether a pod is part of a deployment with the given name
// a pod is considered to be in {deployment} if it is owned by a replicaset with a name of format {deployment}-otherchars
func PodInDeployment(pod apiv1.Pod, deployment string) bool {
func PodInDeployment(pod *apiv1.Pod, deployment string) bool {
for _, owner := range pod.OwnerReferences {
if owner.Controller == nil || !*owner.Controller || owner.Kind != "ReplicaSet" {
continue
@ -138,7 +146,7 @@ func AddContainerFlag(cmd *cobra.Command) *string {
// GetNamespace takes a set of kubectl flag values and returns the namespace we should be operating in
func GetNamespace(flags *genericclioptions.ConfigFlags) string {
namespace, _, err := flags.ToRawKubeConfigLoader().Namespace()
if err != nil || len(namespace) == 0 {
if err != nil || namespace == "" {
namespace = apiv1.NamespaceDefault
}
return namespace