Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

HorizontalPortrait: Introduce fully functional k8s HPA reactive scaling #54

Merged
merged 1 commit into from
Sep 18, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ require (
k8s.io/apimachinery v0.25.0
k8s.io/client-go v0.25.0
k8s.io/klog/v2 v2.70.1
k8s.io/kubernetes v1.25.0
k8s.io/metrics v0.25.0
k8s.io/utils v0.0.0-20220728103510-ee6ede2d64ed
sigs.k8s.io/controller-runtime v0.13.0
Expand All @@ -28,10 +29,34 @@ require (

replace (
k8s.io/api => k8s.io/api v0.25.0
k8s.io/apiextensions-apiserver => k8s.io/apiextensions-apiserver v0.25.0
k8s.io/apimachinery => k8s.io/apimachinery v0.25.0
k8s.io/apiserver => k8s.io/apiserver v0.25.0
k8s.io/cli-runtime => k8s.io/cli-runtime v0.25.0
k8s.io/client-go => k8s.io/client-go v0.25.0
k8s.io/cloud-provider => k8s.io/cloud-provider v0.25.0
k8s.io/cluster-bootstrap => k8s.io/cluster-bootstrap v0.25.0
k8s.io/code-generator => k8s.io/code-generator v0.25.0
k8s.io/component-base => k8s.io/component-base v0.25.0
k8s.io/component-helpers => k8s.io/component-helpers v0.25.0
k8s.io/controller-manager => k8s.io/controller-manager v0.25.0
k8s.io/cri-api => k8s.io/cri-api v0.25.0
k8s.io/csi-translation-lib => k8s.io/csi-translation-lib v0.25.0
k8s.io/klog/v2 => k8s.io/klog/v2 v2.70.1
k8s.io/kube-aggregator => k8s.io/kube-aggregator v0.25.0
k8s.io/kube-controller-manager => k8s.io/kube-controller-manager v0.25.0
k8s.io/kube-proxy => k8s.io/kube-proxy v0.25.0
k8s.io/kube-scheduler => k8s.io/kube-scheduler v0.25.0
k8s.io/kubectl => k8s.io/kubectl v0.25.0
k8s.io/kubelet => k8s.io/kubelet v0.25.0
k8s.io/kubernetes => k8s.io/kubernetes v1.25.0
k8s.io/legacy-cloud-providers => k8s.io/legacy-cloud-providers v0.25.0
k8s.io/metrics => k8s.io/metrics v0.25.0
k8s.io/mount-utils => k8s.io/mount-utils v0.25.0
k8s.io/pod-security-admission => k8s.io/pod-security-admission v0.25.0
k8s.io/sample-apiserver => k8s.io/sample-apiserver v0.25.0
k8s.io/sample-cli-plugin => k8s.io/sample-cli-plugin v0.25.0
k8s.io/sample-controller => k8s.io/sample-controller v0.25.0
)

require (
Expand All @@ -48,6 +73,7 @@ require (
github.com/blang/semver/v4 v4.0.0 // indirect
github.com/cespare/xxhash/v2 v2.1.2 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/docker/distribution v2.8.1+incompatible // indirect
github.com/emicklei/go-restful/v3 v3.8.0 // indirect
github.com/evanphx/json-patch v4.12.0+incompatible // indirect
github.com/evanphx/json-patch/v5 v5.6.0 // indirect
Expand All @@ -74,6 +100,7 @@ require (
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
github.com/opencontainers/go-digest v1.0.0 // indirect
github.com/pkg/errors v0.9.1 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/prometheus/client_model v0.2.0 // indirect
Expand All @@ -96,6 +123,7 @@ require (
k8s.io/apiextensions-apiserver v0.25.0 // indirect
k8s.io/apiserver v0.25.0 // indirect
k8s.io/component-base v0.25.0 // indirect
k8s.io/component-helpers v0.0.0 // indirect
k8s.io/kube-openapi v0.0.0-20220803162953-67bda5d908f1 // indirect
sigs.k8s.io/json v0.0.0-20220713155537-f223a00ba0e2 // indirect
sigs.k8s.io/structured-merge-diff/v4 v4.2.3 // indirect
Expand Down
8 changes: 8 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,8 @@ github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ3
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/docker/distribution v2.8.1+incompatible h1:Q50tZOPR6T/hjNsyc9g8/syEs6bk8XXApsHjKukMl68=
github.com/docker/distribution v2.8.1+incompatible/go.mod h1:J2gT2udsDAN96Uj4KfcMRqY0/ypR+oyYUYmja8H+y+w=
github.com/docopt/docopt-go v0.0.0-20180111231733-ee0de3bc6815/go.mod h1:WwZ+bS3ebgob9U8Nd0kOddGdZWjyMGR8Wziv+TBNwSE=
github.com/emicklei/go-restful/v3 v3.8.0 h1:eCZ8ulSerjdAiaNpF7GxXIE7ZCMo1moN1qX+S609eVw=
github.com/emicklei/go-restful/v3 v3.8.0/go.mod h1:6n3XBCmQQb25CM2LCACGz8ukIrRry+4bhvbpWn3mrbc=
Expand Down Expand Up @@ -302,6 +304,8 @@ github.com/onsi/ginkgo/v2 v2.1.4 h1:GNapqRSid3zijZ9H77KrgVG4/8KqiyRsxcSxe+7ApXY=
github.com/onsi/ginkgo/v2 v2.1.4/go.mod h1:um6tUpWM/cxCK3/FK8BXqEiUMUwRgSM4JXG47RKZmLU=
github.com/onsi/gomega v1.20.0 h1:8W0cWlwFkflGPLltQvLRB7ZVD5HuP6ng320w2IS245Q=
github.com/onsi/gomega v1.20.0/go.mod h1:DtrZpjmvpn2mPm4YWQa0/ALMDj9v4YxLgojwPeREyVo=
github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U=
github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM=
github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
Expand Down Expand Up @@ -814,10 +818,14 @@ k8s.io/client-go v0.25.0 h1:CVWIaCETLMBNiTUta3d5nzRbXvY5Hy9Dpl+VvREpu5E=
k8s.io/client-go v0.25.0/go.mod h1:lxykvypVfKilxhTklov0wz1FoaUZ8X4EwbhS6rpRfN8=
k8s.io/component-base v0.25.0 h1:haVKlLkPCFZhkcqB6WCvpVxftrg6+FK5x1ZuaIDaQ5Y=
k8s.io/component-base v0.25.0/go.mod h1:F2Sumv9CnbBlqrpdf7rKZTmmd2meJq0HizeyY/yAFxk=
k8s.io/component-helpers v0.25.0 h1:vNzYfqnVXj7f+CPksduKVv2Z9kC+IDsOs9yaOyxZrj0=
k8s.io/component-helpers v0.25.0/go.mod h1:auaFj2bvb5Zmy0mLk4WJNmwP0w4e7Zk+/Tu9FFBGA20=
k8s.io/klog/v2 v2.70.1 h1:7aaoSdahviPmR+XkS7FyxlkkXs6tHISSG03RxleQAVQ=
k8s.io/klog/v2 v2.70.1/go.mod h1:y1WjHnz7Dj687irZUWR/WLkLc5N1YHtjLdmgWjndZn0=
k8s.io/kube-openapi v0.0.0-20220803162953-67bda5d908f1 h1:MQ8BAZPZlWk3S9K4a9NCkIFQtZShWqoha7snGixVgEA=
k8s.io/kube-openapi v0.0.0-20220803162953-67bda5d908f1/go.mod h1:C/N6wCaBHeBHkHUesQOQy2/MZqGgMAFPqGsGQLdbZBU=
k8s.io/kubernetes v1.25.0 h1:NwTRyLrdXTORd5V7DLlUltxDbl/KZjYDiRgwI+pBYGE=
k8s.io/kubernetes v1.25.0/go.mod h1:UdtILd5Zg1vGZvShiO1EYOqmjzM2kZOG1hzwQnM5JxY=
k8s.io/metrics v0.25.0 h1:z/tyqXUCxvmFsKIO7GH6ulvogYvGp+pDmlz5ANSQVPE=
k8s.io/metrics v0.25.0/go.mod h1:HZZrbhuRX+fsDcRc3u59o2FbrKhqD67IGnoFECNmovc=
k8s.io/utils v0.0.0-20220728103510-ee6ede2d64ed h1:jAne/RjBTyawwAy0utX5eqigAwz/lQhTmy+Hr/Cpue4=
Expand Down
2 changes: 1 addition & 1 deletion main.go
Original file line number Diff line number Diff line change
Expand Up @@ -378,7 +378,7 @@ func initHorizontalPortraitProviders(client client.Client, eventTrigger chan eve

func initPortraitGenerators(client client.Client, metricProvider metricprovider.Interface, scaler *scale.Scaler) map[autoscalingv1alpha1.PortraitType]portraitgenerator.Interface {
generators := make(map[autoscalingv1alpha1.PortraitType]portraitgenerator.Interface)
generators[autoscalingv1alpha1.ReactivePortraitType] = reactive.NewPortraitGenerator(client, metricProvider, scaler)
generators[autoscalingv1alpha1.ReactivePortraitType] = reactive.NewPortraitGenerator(metricProvider, util.NewCtrlPodLister(client), scaler)
return generators
}

Expand Down
133 changes: 115 additions & 18 deletions pkg/portrait/generator/reactive/generator.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
/*
Copyright 2023 The Kapacity Authors.
Copyright 2016 The Kubernetes Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
Expand All @@ -23,7 +24,12 @@ import (
"time"

k8sautoscalingv2 "k8s.io/api/autoscaling/v2"
"sigs.k8s.io/controller-runtime/pkg/client"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
corev1listers "k8s.io/client-go/listers/core/v1"
"k8s.io/kubernetes/pkg/controller/podautoscaler"
podautoscalermetrics "k8s.io/kubernetes/pkg/controller/podautoscaler/metrics"
"sigs.k8s.io/controller-runtime/pkg/log"

autoscalingv1alpha1 "github.com/traas-stack/kapacity/apis/autoscaling/v1alpha1"
Expand All @@ -42,17 +48,17 @@ const (

// PortraitGenerator generates portraits reactively based on latest metrics.
type PortraitGenerator struct {
client client.Client
metricProvider metricprovider.Interface
scaler *pkgscale.Scaler
metricsClient podautoscalermetrics.MetricsClient
podLister corev1listers.PodLister
scaler *pkgscale.Scaler
}

// NewPortraitGenerator creates a new PortraitGenerator with the given Kubernetes client, metrics provider and scaler.
func NewPortraitGenerator(client client.Client, metricProvider metricprovider.Interface, scaler *pkgscale.Scaler) portraitgenerator.Interface {
func NewPortraitGenerator(metricProvider metricprovider.Interface, podLister corev1listers.PodLister, scaler *pkgscale.Scaler) portraitgenerator.Interface {
return &PortraitGenerator{
client: client,
metricProvider: metricProvider,
scaler: scaler,
metricsClient: NewMetricsClient(metricProvider),
podLister: podLister,
scaler: scaler,
}
}

Expand Down Expand Up @@ -86,27 +92,20 @@ func (g *PortraitGenerator) GenerateHorizontal(ctx context.Context, namespace st
return nil, 0, fmt.Errorf("failed to get the target's current scale: %v", err)
}
specReplicas := scale.Spec.Replicas
statusReplicas := scale.Status.Replicas
selector, err := util.ParseScaleSelector(scale.Status.Selector)
if err != nil {
return nil, 0, fmt.Errorf("failed to parse label selector %q of target's current scale: %v", scale.Status.Selector, err)
}
replicaCalc := &replicaCalculator{
Client: g.client,
MetricsClient: metricsClient{
MetricProvider: g.metricProvider,
},
Tolerance: tolerance,
CPUInitializationPeriod: cpuInitializationPeriod,
DelayOfInitialReadinessStatus: delayOfInitialReadinessStatus,
}
replicaCalc := podautoscaler.NewReplicaCalculator(g.metricsClient, g.podLister, tolerance, cpuInitializationPeriod, delayOfInitialReadinessStatus)

var (
replicas int32 = 1
invalidMetricsCount int
invalidMetricError error
)
for _, metric := range metrics {
replicasProposal, err := replicaCalc.ComputeReplicasForMetric(ctx, specReplicas, metric, namespace, selector)
replicasProposal, err := computeReplicasForMetric(ctx, replicaCalc, specReplicas, statusReplicas, metric, namespace, selector)
if err != nil {
l.Error(err, "failed to compute replicas for metric")
if invalidMetricsCount == 0 {
Expand All @@ -130,3 +129,101 @@ func (g *PortraitGenerator) GenerateHorizontal(ctx context.Context, namespace st
},
}, syncPeriod, nil
}

// computeReplicasForMetric computes the desired number of replicas for the specified metric.
func computeReplicasForMetric(ctx context.Context, replicaCalc *podautoscaler.ReplicaCalculator, specReplicas, statusReplicas int32, metric autoscalingv1alpha1.MetricSpec, namespace string, selector labels.Selector) (int32, error) {
switch metric.Type {
case k8sautoscalingv2.ResourceMetricSourceType:
return computeReplicasForResourceMetric(ctx, replicaCalc, specReplicas, metric.Resource.Target, metric.Resource.Name, namespace, "", selector)
case k8sautoscalingv2.ContainerResourceMetricSourceType:
return computeReplicasForResourceMetric(ctx, replicaCalc, specReplicas, metric.ContainerResource.Target, metric.ContainerResource.Name, namespace, metric.ContainerResource.Container, selector)
case k8sautoscalingv2.PodsMetricSourceType:
return computeReplicasForPodsMetric(replicaCalc, specReplicas, metric.Pods.Target, metric.Pods.Metric, namespace, selector)
case k8sautoscalingv2.ObjectMetricSourceType:
return computeReplicasForObjectMetric(replicaCalc, specReplicas, statusReplicas, metric.Object.Target, metric.Object.Metric, metric.Object.DescribedObject, namespace, selector)
case k8sautoscalingv2.ExternalMetricSourceType:
return computeReplicasForExternalMetric(replicaCalc, specReplicas, statusReplicas, metric.External.Target, metric.External.Metric, namespace, selector)
default:
return 0, fmt.Errorf("unsupported metric source type %q", metric.Type)
}
}

// computeReplicasForResourceMetric computes the desired number of replicas for the specified metric of type (Container)ResourceMetricSourceType.
func computeReplicasForResourceMetric(ctx context.Context, replicaCalc *podautoscaler.ReplicaCalculator, currentReplicas int32, target k8sautoscalingv2.MetricTarget,
resourceName corev1.ResourceName, namespace string, container string, selector labels.Selector) (int32, error) {
if target.AverageValue != nil {
replicaCountProposal, _, _, err := replicaCalc.GetRawResourceReplicas(ctx, currentReplicas, target.AverageValue.MilliValue(), resourceName, namespace, selector, container)
if err != nil {
return 0, fmt.Errorf("failed to get %s usage: %v", resourceName, err)
}
return replicaCountProposal, nil
}

if target.AverageUtilization == nil {
return 0, fmt.Errorf("invalid resource metric source: neither an average utilization target nor an average value (usage) target was set")
}

targetUtilization := *target.AverageUtilization
replicaCountProposal, _, _, _, err := replicaCalc.GetResourceReplicas(ctx, currentReplicas, targetUtilization, resourceName, namespace, selector, container)
if err != nil {
return 0, fmt.Errorf("failed to get %s utilization: %v", resourceName, err)
}
return replicaCountProposal, nil
}

// computeReplicasForPodsMetric computes the desired number of replicas for the specified metric of type PodsMetricSourceType.
func computeReplicasForPodsMetric(replicaCalc *podautoscaler.ReplicaCalculator, currentReplicas int32, target k8sautoscalingv2.MetricTarget,
metric k8sautoscalingv2.MetricIdentifier, namespace string, selector labels.Selector) (int32, error) {
metricSelector, err := metav1.LabelSelectorAsSelector(metric.Selector)
if err != nil {
return 0, fmt.Errorf("failed to parse metric selector as label selector: %v", err)
}

replicaCountProposal, _, _, err := replicaCalc.GetMetricReplicas(currentReplicas, target.AverageValue.MilliValue(), metric.Name, namespace, selector, metricSelector)
if err != nil {
return 0, fmt.Errorf("failed to get pods metric: %v", err)
}
return replicaCountProposal, nil
}

// computeReplicasForObjectMetric computes the desired number of replicas for the specified metric of type ObjectMetricSourceType.
func computeReplicasForObjectMetric(replicaCalc *podautoscaler.ReplicaCalculator, specReplicas, statusReplicas int32, target k8sautoscalingv2.MetricTarget,
metric k8sautoscalingv2.MetricIdentifier, describedObject k8sautoscalingv2.CrossVersionObjectReference, namespace string, selector labels.Selector) (int32, error) {
metricSelector, err := metav1.LabelSelectorAsSelector(metric.Selector)
if err != nil {
return 0, fmt.Errorf("failed to parse metric selector as label selector: %v", err)
}

var replicaCountProposal int32
if target.Type == k8sautoscalingv2.ValueMetricType {
replicaCountProposal, _, _, err = replicaCalc.GetObjectMetricReplicas(specReplicas, target.Value.MilliValue(), metric.Name, namespace, &describedObject, selector, metricSelector)
} else if target.Type == k8sautoscalingv2.AverageValueMetricType {
replicaCountProposal, _, _, err = replicaCalc.GetObjectPerPodMetricReplicas(statusReplicas, target.AverageValue.MilliValue(), metric.Name, namespace, &describedObject, metricSelector)
} else {
return 0, fmt.Errorf("invalid object metric source: neither a value target nor an average value target was set")
}
if err != nil {
return 0, fmt.Errorf("failed to get object metric: %v", err)
}
return replicaCountProposal, nil
}

// computeReplicasForExternalMetric computes the desired number of replicas for the specified metric of type ExternalMetricSourceType.
func computeReplicasForExternalMetric(replicaCalc *podautoscaler.ReplicaCalculator, specReplicas, statusReplicas int32, target k8sautoscalingv2.MetricTarget,
metric k8sautoscalingv2.MetricIdentifier, namespace string, selector labels.Selector) (int32, error) {
var (
replicaCountProposal int32
err error
)
if target.AverageValue != nil {
replicaCountProposal, _, _, err = replicaCalc.GetExternalPerPodMetricReplicas(statusReplicas, target.AverageValue.MilliValue(), metric.Name, namespace, metric.Selector)
} else if target.Value != nil {
replicaCountProposal, _, _, err = replicaCalc.GetExternalMetricReplicas(specReplicas, target.Value.MilliValue(), metric.Name, namespace, metric.Selector, selector)
} else {
return 0, fmt.Errorf("invalid external metric source: neither a value target nor an average value target was set")
}
if err != nil {
return 0, fmt.Errorf("failed to get external metric: %v", err)
}
return replicaCountProposal, nil
}
4 changes: 3 additions & 1 deletion pkg/portrait/generator/reactive/generator_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ import (
autoscalingv1alpha1 "github.com/traas-stack/kapacity/apis/autoscaling/v1alpha1"
"github.com/traas-stack/kapacity/pkg/metric/provider/metricsapi"
pkgscale "github.com/traas-stack/kapacity/pkg/scale"
"github.com/traas-stack/kapacity/pkg/util"
)

var (
Expand All @@ -72,6 +73,7 @@ func TestGenerateHorizontal(t *testing.T) {
}
scaleTargetRef := k8sautoscalingv2.CrossVersionObjectReference{Kind: "Deployment", APIVersion: "apps/v1beta2", Name: "foo"}
fakeClient := fake.NewClientBuilder().WithObjects(preparePod(1)).Build()
fakePodLister := util.NewCtrlPodLister(fakeClient)
algorithm := autoscalingv1alpha1.PortraitAlgorithm{Type: autoscalingv1alpha1.KubeHPAPortraitAlgorithmType}
metricSpecs := prepareMetricSpec(corev1.ResourceCPU, 30)
fakeScaler := prepareScaleClient(t)
Expand All @@ -81,7 +83,7 @@ func TestGenerateHorizontal(t *testing.T) {
prepareFakeMetricsClient(testCase.resourceName, testCase.podMetricsMap, testCase.timestamp).MetricsV1beta1(),
)

portraitGenerator := NewPortraitGenerator(fakeClient, fakeMetricProvider, fakeScaler)
portraitGenerator := NewPortraitGenerator(fakeMetricProvider, fakePodLister, fakeScaler)
assert.NotNil(t, portraitGenerator)

portraitData, _, _ := portraitGenerator.GenerateHorizontal(context.Background(), testNamespace, scaleTargetRef, metricSpecs, algorithm)
Expand Down
Loading