fix code inspection errors

Signed-off-by: whitewindmills <jayfantasyhjh@gmail.com>
This commit is contained in:
whitewindmills 2024-06-12 17:01:14 +08:00
parent 2ed4d77a06
commit 58c15c8ed9
8 changed files with 33 additions and 34 deletions

View File

@ -111,15 +111,15 @@ func main() {
// Set environment variables used by karmadactl so the output is consistent, // Set environment variables used by karmadactl so the output is consistent,
// regardless of where we run. // regardless of where we run.
os.Setenv("HOME", "/home/username") os.Setenv("HOME", "/home/username")
karmadactl := karmadactl.NewKarmadaCtlCommand("karmadactl", "karmadactl") karmadactlCmd := karmadactl.NewKarmadaCtlCommand("karmadactl", "karmadactl")
karmadactl.DisableAutoGenTag = true karmadactlCmd.DisableAutoGenTag = true
err = doc.GenMarkdownTree(karmadactl, outDir) err = doc.GenMarkdownTree(karmadactlCmd, outDir)
if err != nil { if err != nil {
fmt.Fprintf(os.Stderr, "failed to generate docs: %v\n", err) fmt.Fprintf(os.Stderr, "failed to generate docs: %v\n", err)
os.Exit(1) os.Exit(1)
} }
err = GenMarkdownTreeForIndex(karmadactl, outDir) err = GenMarkdownTreeForIndex(karmadactlCmd, outDir)
if err != nil { if err != nil {
fmt.Fprintf(os.Stderr, "failed to generate index docs: %v\n", err) fmt.Fprintf(os.Stderr, "failed to generate index docs: %v\n", err)
os.Exit(1) os.Exit(1)
@ -153,8 +153,8 @@ func main() {
newlines := []string{"---", "title: " + title} newlines := []string{"---", "title: " + title}
newlines = append(newlines, lines...) newlines = append(newlines, lines...)
newcontent := strings.Join(newlines, "\n") newContent := strings.Join(newlines, "\n")
return os.WriteFile(path, []byte(newcontent), info.Mode()) return os.WriteFile(path, []byte(newContent), info.Mode())
}) })
if err != nil { if err != nil {
fmt.Fprintf(os.Stderr, "failed to process docs: %v\n", err) fmt.Fprintf(os.Stderr, "failed to process docs: %v\n", err)

View File

@ -72,24 +72,24 @@ func (c *resourceMetricsClient) GetResourceMetric(ctx context.Context, resource
startTime := time.Now() startTime := time.Now()
defer metrics.ObserveFederatedHPAPullMetricsLatency(err, "ResourceMetric", startTime) defer metrics.ObserveFederatedHPAPullMetricsLatency(err, "ResourceMetric", startTime)
metrics, err := c.client.PodMetricses(namespace).List(ctx, metav1.ListOptions{LabelSelector: selector.String()}) podMetrics, err := c.client.PodMetricses(namespace).List(ctx, metav1.ListOptions{LabelSelector: selector.String()})
if err != nil { if err != nil {
return nil, time.Time{}, fmt.Errorf("unable to fetch metrics from resource metrics API: %v", err) return nil, time.Time{}, fmt.Errorf("unable to fetch metrics from resource metrics API: %v", err)
} }
if len(metrics.Items) == 0 { if len(podMetrics.Items) == 0 {
return nil, time.Time{}, fmt.Errorf("no metrics returned from resource metrics API") return nil, time.Time{}, fmt.Errorf("no metrics returned from resource metrics API")
} }
var res PodMetricsInfo var res PodMetricsInfo
if container != "" { if container != "" {
res, err = getContainerMetrics(metrics.Items, resource, container) res, err = getContainerMetrics(podMetrics.Items, resource, container)
if err != nil { if err != nil {
return nil, time.Time{}, fmt.Errorf("failed to get container metrics: %v", err) return nil, time.Time{}, fmt.Errorf("failed to get container metrics: %v", err)
} }
} else { } else {
res = getPodMetrics(metrics.Items, resource) res = getPodMetrics(podMetrics.Items, resource)
} }
timestamp := metrics.Items[0].Timestamp.Time timestamp := podMetrics.Items[0].Timestamp.Time
return res, timestamp, nil return res, timestamp, nil
} }
@ -156,17 +156,17 @@ func (c *customMetricsClient) GetRawMetric(metricName string, namespace string,
startTime := time.Now() startTime := time.Now()
defer metrics.ObserveFederatedHPAPullMetricsLatency(err, "RawMetric", startTime) defer metrics.ObserveFederatedHPAPullMetricsLatency(err, "RawMetric", startTime)
metrics, err := c.client.NamespacedMetrics(namespace).GetForObjects(schema.GroupKind{Kind: "Pod"}, selector, metricName, metricSelector) metricList, err := c.client.NamespacedMetrics(namespace).GetForObjects(schema.GroupKind{Kind: "Pod"}, selector, metricName, metricSelector)
if err != nil { if err != nil {
return nil, time.Time{}, fmt.Errorf("unable to fetch metrics from custom metrics API: %v", err) return nil, time.Time{}, fmt.Errorf("unable to fetch metrics from custom metrics API: %v", err)
} }
if len(metrics.Items) == 0 { if len(metricList.Items) == 0 {
return nil, time.Time{}, fmt.Errorf("no metrics returned from custom metrics API") return nil, time.Time{}, fmt.Errorf("no metrics returned from custom metrics API")
} }
res := make(PodMetricsInfo, len(metrics.Items)) res := make(PodMetricsInfo, len(metricList.Items))
for _, m := range metrics.Items { for _, m := range metricList.Items {
window := metricServerDefaultMetricWindow window := metricServerDefaultMetricWindow
if m.WindowSeconds != nil { if m.WindowSeconds != nil {
window = time.Duration(*m.WindowSeconds) * time.Second window = time.Duration(*m.WindowSeconds) * time.Second
@ -174,13 +174,13 @@ func (c *customMetricsClient) GetRawMetric(metricName string, namespace string,
res[m.DescribedObject.Name] = PodMetric{ res[m.DescribedObject.Name] = PodMetric{
Timestamp: m.Timestamp.Time, Timestamp: m.Timestamp.Time,
Window: window, Window: window,
Value: int64(m.Value.MilliValue()), Value: m.Value.MilliValue(),
} }
m.Value.MilliValue() m.Value.MilliValue()
} }
timestamp := metrics.Items[0].Timestamp.Time timestamp := metricList.Items[0].Timestamp.Time
return res, timestamp, nil return res, timestamp, nil
} }
@ -225,19 +225,19 @@ func (c *externalMetricsClient) GetExternalMetric(metricName, namespace string,
startTime := time.Now() startTime := time.Now()
defer metrics.ObserveFederatedHPAPullMetricsLatency(err, "ExternalMetric", startTime) defer metrics.ObserveFederatedHPAPullMetricsLatency(err, "ExternalMetric", startTime)
metrics, err := c.client.NamespacedMetrics(namespace).List(metricName, selector) externalMetrics, err := c.client.NamespacedMetrics(namespace).List(metricName, selector)
if err != nil { if err != nil {
return []int64{}, time.Time{}, fmt.Errorf("unable to fetch metrics from external metrics API: %v", err) return []int64{}, time.Time{}, fmt.Errorf("unable to fetch metrics from external metrics API: %v", err)
} }
if len(metrics.Items) == 0 { if len(externalMetrics.Items) == 0 {
return nil, time.Time{}, fmt.Errorf("no metrics returned from external metrics API") return nil, time.Time{}, fmt.Errorf("no metrics returned from external metrics API")
} }
res := make([]int64, 0) res := make([]int64, 0)
for _, m := range metrics.Items { for _, m := range externalMetrics.Items {
res = append(res, m.Value.MilliValue()) res = append(res, m.Value.MilliValue())
} }
timestamp := metrics.Items[0].Timestamp.Time timestamp := externalMetrics.Items[0].Timestamp.Time
return res, timestamp, nil return res, timestamp, nil
} }

View File

@ -402,7 +402,7 @@ func getEndpointSliceWorkMeta(c client.Client, ns string, workName string, endpo
return metav1.ObjectMeta{}, err return metav1.ObjectMeta{}, err
} }
labels := map[string]string{ ls := map[string]string{
util.MultiClusterServiceNamespaceLabel: endpointSlice.GetNamespace(), util.MultiClusterServiceNamespaceLabel: endpointSlice.GetNamespace(),
util.MultiClusterServiceNameLabel: endpointSlice.GetLabels()[discoveryv1.LabelServiceName], util.MultiClusterServiceNameLabel: endpointSlice.GetLabels()[discoveryv1.LabelServiceName],
// indicate the Work should be not propagated since it's collected resource. // indicate the Work should be not propagated since it's collected resource.
@ -410,18 +410,18 @@ func getEndpointSliceWorkMeta(c client.Client, ns string, workName string, endpo
util.EndpointSliceWorkManagedByLabel: util.MultiClusterServiceKind, util.EndpointSliceWorkManagedByLabel: util.MultiClusterServiceKind,
} }
if existWork.Labels == nil || (err != nil && apierrors.IsNotFound(err)) { if existWork.Labels == nil || (err != nil && apierrors.IsNotFound(err)) {
workMeta := metav1.ObjectMeta{Name: workName, Namespace: ns, Labels: labels} workMeta := metav1.ObjectMeta{Name: workName, Namespace: ns, Labels: ls}
return workMeta, nil return workMeta, nil
} }
labels = util.DedupeAndMergeLabels(labels, existWork.Labels) ls = util.DedupeAndMergeLabels(ls, existWork.Labels)
if value, ok := existWork.Labels[util.EndpointSliceWorkManagedByLabel]; ok { if value, ok := existWork.Labels[util.EndpointSliceWorkManagedByLabel]; ok {
controllerSet := sets.New[string]() controllerSet := sets.New[string]()
controllerSet.Insert(strings.Split(value, ".")...) controllerSet.Insert(strings.Split(value, ".")...)
controllerSet.Insert(util.MultiClusterServiceKind) controllerSet.Insert(util.MultiClusterServiceKind)
labels[util.EndpointSliceWorkManagedByLabel] = strings.Join(controllerSet.UnsortedList(), ".") ls[util.EndpointSliceWorkManagedByLabel] = strings.Join(controllerSet.UnsortedList(), ".")
} }
workMeta := metav1.ObjectMeta{Name: workName, Namespace: ns, Labels: labels} workMeta := metav1.ObjectMeta{Name: workName, Namespace: ns, Labels: ls}
return workMeta, nil return workMeta, nil
} }

View File

@ -150,8 +150,7 @@ func modifyRequest(req *http.Request, cluster string) error {
return nil return nil
} }
changed := false changed := store.RemoveCacheSourceAnnotation(obj)
changed = store.RemoveCacheSourceAnnotation(obj) || changed
changed = store.RecoverClusterResourceVersion(obj, cluster) || changed changed = store.RecoverClusterResourceVersion(obj, cluster) || changed
if changed { if changed {

View File

@ -27,5 +27,5 @@ import (
// ensuring the hash does not change when a pointer changes. // ensuring the hash does not change when a pointer changes.
func DeepHashObject(hasher hash.Hash, objectToWrite interface{}) { func DeepHashObject(hasher hash.Hash, objectToWrite interface{}) {
hasher.Reset() hasher.Reset()
pretty.Fprintf(hasher, "%# v", objectToWrite) pretty.Fprintf(hasher, "%v", objectToWrite)
} }

View File

@ -22,7 +22,7 @@ package lifted
import ( import (
corev1 "k8s.io/api/core/v1" corev1 "k8s.io/api/core/v1"
validation "k8s.io/apimachinery/pkg/util/validation" "k8s.io/apimachinery/pkg/util/validation"
"k8s.io/apimachinery/pkg/util/validation/field" "k8s.io/apimachinery/pkg/util/validation/field"
netutils "k8s.io/utils/net" netutils "k8s.io/utils/net"
) )

View File

@ -292,7 +292,7 @@ func (h *UpgradeAwareHandler) tryUpgrade(w http.ResponseWriter, req *http.Reques
if len(rawResponse) > 0 { if len(rawResponse) > 0 {
klog.V(6).Infof("Writing %d bytes to hijacked connection", len(rawResponse)) klog.V(6).Infof("Writing %d bytes to hijacked connection", len(rawResponse))
if _, err = requestHijackedConn.Write(rawResponse); err != nil { if _, err = requestHijackedConn.Write(rawResponse); err != nil {
utilruntime.HandleError(fmt.Errorf("Error proxying response from backend to client: %v", err)) utilruntime.HandleError(fmt.Errorf("error proxying response from backend to client: %v", err))
} }
} }

View File

@ -64,7 +64,7 @@ func NewTestKubeconfig(kubeConfig, karmadaContext, karmadactlpath, namespace str
// KarmadactlCmd runs the karmadactl executable through the wrapper script. // KarmadactlCmd runs the karmadactl executable through the wrapper script.
func (tk *TestKubeconfig) KarmadactlCmd(args ...string) *exec.Cmd { func (tk *TestKubeconfig) KarmadactlCmd(args ...string) *exec.Cmd {
defaultArgs := []string{} var defaultArgs []string
if tk.KubeConfig != "" { if tk.KubeConfig != "" {
defaultArgs = append(defaultArgs, "--"+clientcmd.RecommendedConfigPathFlag+"="+tk.KubeConfig) defaultArgs = append(defaultArgs, "--"+clientcmd.RecommendedConfigPathFlag+"="+tk.KubeConfig)
@ -116,7 +116,7 @@ func (k *KarmadactlBuilder) exec() (string, error) {
} }
// execWithFullOutput runs the karmadactl executable, and returns the stdout and stderr. // execWithFullOutput runs the karmadactl executable, and returns the stdout and stderr.
func (k KarmadactlBuilder) execWithFullOutput() (string, string, error) { func (k *KarmadactlBuilder) execWithFullOutput() (string, string, error) {
var stdout, stderr bytes.Buffer var stdout, stderr bytes.Buffer
cmd := k.cmd cmd := k.cmd
cmd.Stdout, cmd.Stderr = &stdout, &stderr cmd.Stdout, cmd.Stderr = &stdout, &stderr
@ -133,7 +133,7 @@ func (k KarmadactlBuilder) execWithFullOutput() (string, string, error) {
if err != nil { if err != nil {
var rc = 127 var rc = 127
if ee, ok := err.(*exec.ExitError); ok { if ee, ok := err.(*exec.ExitError); ok {
rc = int(ee.Sys().(syscall.WaitStatus).ExitStatus()) rc = ee.Sys().(syscall.WaitStatus).ExitStatus()
} }
return stdout.String(), stderr.String(), uexec.CodeExitError{ return stdout.String(), stderr.String(), uexec.CodeExitError{
Err: fmt.Errorf("error running %v:\nCommand stdout:\n%v\nstderr:\n%v\nerror:\n%v", cmd, cmd.Stdout, cmd.Stderr, err), Err: fmt.Errorf("error running %v:\nCommand stdout:\n%v\nstderr:\n%v\nerror:\n%v", cmd, cmd.Stdout, cmd.Stderr, err),