Repository: kubernetes/kubernetes
File: test/e2e/framework/autoscaling/autoscaling_utils.go (Go)

Code before:

	if sidecarStatus == Enable {
		sidecarContainer := getSidecarContainer(name, cpuLimit, memLimit)
		additionalContainers = append(additionalContainers, sidecarContainer)
	}

	config, err := framework.LoadConfig()
	framework.ExpectNoError(err)
	apiExtensionClient, err := crdclientset.NewForConfig(config)
	framework.ExpectNoError(err)
	dynamicClient, err := dynamic.NewForConfig(config)
	framework.ExpectNoError(err)
	resourceClient := dynamicClient.Resource(schema.GroupVersionResource{Group: crdGroup, Version: crdVersion, Resource: crdNamePlural}).Namespace(nsName)

	runServiceAndWorkloadForResourceConsumer(ctx, clientset, resourceClient, apiExtensionClient, nsName, name, kind, replicas, cpuLimit, memLimit, podAnnotations, serviceAnnotations, additionalContainers, podResources)
	controllerName := name + "-ctrl"
	// If sidecar is enabled and busy, run service and consumer for sidecar
	if sidecarStatus == Enable && sidecarType == Busy {
		runServiceAndSidecarForResourceConsumer(ctx, clientset, nsName, name, kind, replicas, serviceAnnotations)
		controllerName = name + "-sidecar-ctrl"
	}

	rc := &ResourceConsumer{
		name:                     name,
		controllerName:           controllerName,
		kind:                     kind,
		nsName:                   nsName,
		clientSet:                clientset,
		apiExtensionClient:       apiExtensionClient,
		scaleClient:              scaleClient,
		resourceClient:           resourceClient,
		dynamicClient:            dynamicClient,
		customMetricName:         customMetricName,
		cpu:                      make(chan int),
		mem:                      make(chan int),
		customMetric:             make(chan int),
		stopCPU:                  make(chan int),
		stopMem:                  make(chan int),
		stopCustomMetric:         make(chan int),
		consumptionTimeInSeconds: consumptionTimeInSeconds,
		sleepTime:                time.Duration(consumptionTimeInSeconds) * time.Second,
		requestSizeInMillicores:  requestSizeInMillicores,
		requestSizeInMegabytes:   requestSizeInMegabytes,
		requestSizeCustomMetric:  requestSizeCustomMetric,
		sidecarType:              sidecarType,
		sidecarStatus:            sidecarStatus,
	}

	go rc.makeConsumeCPURequests(ctx)
	rc.ConsumeCPU(initCPUTotal)
	go rc.makeConsumeMemRequests(ctx)

Review comment (performance):
Suggestion: you could replace this entire port-forward logic with directly invoking `PortForwardOptions.RunPortForwardContext`. We've written those commands such that they should be easily embedable anywhere where needed. Also, we're slowly switching again from SPDY, which you're using below, towards WebSockets. So using port-forward's code directly will give you the benefit that you don't have to think about it 😉 

Code after:
	params.Set("value", strconv.FormatInt(value, 10))
	if len(labels) > 0 {
		params.Set("labels", formatLabels(labels))
	}
	return emc.sendMetricRequest(ctx, "set", metricName, params)
}

// SetMetricFail configures whether a metric should return errors
func (emc *ExternalMetricsController) SetMetricFail(ctx context.Context, metricName string, shouldFail bool, labels map[string]string) error {
	params := url.Values{}
	params.Set("fail", strconv.FormatBool(shouldFail))
	if len(labels) > 0 {
		params.Set("labels", formatLabels(labels))
	}
	return emc.sendMetricRequest(ctx, "fail", metricName, params)
}

func (emc *ExternalMetricsController) sendMetricRequest(ctx context.Context, action, metricName string, params url.Values) error {
	return framework.Gomega().Eventually(ctx, func(ctx context.Context) error {
		return emc.doRequestWithPortForward(ctx, action, metricName, params)
	}).WithTimeout(serviceInitializationTimeout).WithPolling(serviceInitializationInterval).Should(gomega.Succeed())
}

func (emc *ExternalMetricsController) doRequestWithPortForward(ctx context.Context, action, metricName string, params url.Values) error {
	// Find the pod
	pods, err := emc.clientSet.CoreV1().Pods(emc.namespace).List(ctx, metav1.ListOptions{
		LabelSelector: "name=" + emc.serviceName,
	})
	if err != nil {
		return fmt.Errorf("failed to list pods: %w", err)
	}
	if len(pods.Items) == 0 {
		return fmt.Errorf("no pods found for service %s", emc.serviceName)
	}
	podName := pods.Items[0].Name

	// Set up port-forward
	config, err := framework.LoadConfig()
	if err != nil {
		return fmt.Errorf("failed to load config: %w", err)
	}

	transport, upgrader, err := spdy.RoundTripperFor(config)
	if err != nil {
		return fmt.Errorf("failed to create round tripper: %w", err)
	}

	reqURL := emc.clientSet.CoreV1().RESTClient().Post().
		Resource("pods").
		Namespace(emc.namespace).
		Name(podName).