k3s/pkg/controller/podautoscaler/metrics/legacy_metrics_client_test.go

411 lines
14 KiB
Go
Raw Normal View History

/*
Copyright 2015 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.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package metrics
import (
"encoding/json"
"fmt"
2015-09-23 10:00:20 +00:00
"io"
"testing"
"time"
2017-06-22 18:24:23 +00:00
"k8s.io/api/core/v1"
2017-01-25 13:13:07 +00:00
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
2017-01-11 14:09:48 +00:00
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/client-go/kubernetes/fake"
2017-01-19 18:27:59 +00:00
restclient "k8s.io/client-go/rest"
2017-01-25 20:07:10 +00:00
core "k8s.io/client-go/testing"
heapster "k8s.io/heapster/metrics/api/v1/types"
metricsapi "k8s.io/metrics/pkg/apis/metrics/v1alpha1"
"github.com/stretchr/testify/assert"
)
var fixedTimestamp = time.Date(2015, time.November, 10, 12, 30, 0, 0, time.UTC)
2015-09-23 10:00:20 +00:00
func (w fakeResponseWrapper) DoRaw() ([]byte, error) {
return w.raw, nil
}
func (w fakeResponseWrapper) Stream() (io.ReadCloser, error) {
return nil, nil
}
func newFakeResponseWrapper(raw []byte) fakeResponseWrapper {
return fakeResponseWrapper{raw: raw}
}
2015-09-23 10:00:20 +00:00
type fakeResponseWrapper struct {
raw []byte
}
2015-09-23 10:00:20 +00:00
// timestamp is used for establishing order on metricPoints
type metricPoint struct {
level uint64
timestamp int
}
type testCase struct {
desiredMetricValues PodMetricsInfo
desiredError error
replicas int
targetTimestamp int
window time.Duration
2015-09-23 10:00:20 +00:00
reportedMetricsPoints [][]metricPoint
2016-05-17 19:31:31 +00:00
reportedPodMetrics [][]int64
namespace string
selector labels.Selector
metricSelector labels.Selector
resourceName v1.ResourceName
metricName string
2015-09-23 10:00:20 +00:00
}
func (tc *testCase) prepareTestClient(t *testing.T) *fake.Clientset {
2015-09-23 10:00:20 +00:00
namespace := "test-namespace"
tc.namespace = namespace
podNamePrefix := "test-pod"
Support for both map-based and set-based selectors in extensions/v1beta1.Scale Here are a list of changes along with an explanation of how they work: 1. Add a new string field called TargetSelector to the external version of extensions Scale type (extensions/v1beta1.Scale). This is a serialized version of either the map-based selector (in case of ReplicationControllers) or the unversioned.LabelSelector struct (in case of Deployments and ReplicaSets). 2. Change the selector field in the internal Scale type (extensions.Scale) to unversioned.LabelSelector. 3. Add conversion functions to convert from two external selector fields to a single internal selector field. The rules for conversion are as follows: i. If the target resource that this scale targets supports LabelSelector (Deployments and ReplicaSets), then serialize the LabelSelector and store the string in the TargetSelector field in the external version and leave the map-based Selector field as nil. ii. If the target resource only supports a map-based selector (ReplicationControllers), then still serialize that selector and store the serialized string in the TargetSelector field. Also, set the the Selector map field in the external Scale type. iii. When converting from external to internal version, parse the TargetSelector string into LabelSelector struct if the string isn't empty. If it is empty, then check if the Selector map is set and just assign that map to the MatchLabels component of the LabelSelector. iv. When converting from internal to external version, serialize the LabelSelector and store it in the TargetSelector field. If only the MatchLabel component is set, then also copy that value to the Selector map field in the external version. 4. HPA now just converts the LabelSelector field to a Selector interface type to list the pods. 5. Scale Get and Update etcd methods for Deployments and ReplicaSets now return extensions.Scale instead of autoscaling.Scale. 6. Consequently, SubresourceGroupVersion override and is "autoscaling" enabled check is now removed from pkg/master/master.go 7. Other small changes to labels package, fuzzer and LabelSelector helpers to piece this all together. 8. Add unit tests to HPA targeting Deployments and ReplicaSets. 9. Add an e2e test to HPA targeting ReplicaSets.
2016-03-09 00:27:13 +00:00
podLabels := map[string]string{"name": podNamePrefix}
tc.selector = labels.SelectorFromSet(podLabels)
2015-09-23 10:00:20 +00:00
// it's a resource test if we have a resource name
isResource := len(tc.resourceName) > 0
fakeClient := &fake.Clientset{}
fakeClient.AddReactor("list", "pods", func(action core.Action) (handled bool, ret runtime.Object, err error) {
2016-11-18 20:50:17 +00:00
obj := &v1.PodList{}
2015-09-23 10:00:20 +00:00
for i := 0; i < tc.replicas; i++ {
podName := fmt.Sprintf("%s-%d", podNamePrefix, i)
2016-11-18 20:50:17 +00:00
pod := buildPod(namespace, podName, podLabels, v1.PodRunning, "1024")
2015-09-23 10:00:20 +00:00
obj.Items = append(obj.Items, pod)
}
2015-09-23 10:00:20 +00:00
return true, obj, nil
})
if isResource {
2016-05-17 19:31:31 +00:00
fakeClient.AddProxyReactor("services", func(action core.Action) (handled bool, ret restclient.ResponseWrapper, err error) {
metrics := metricsapi.PodMetricsList{}
2016-05-17 19:31:31 +00:00
for i, containers := range tc.reportedPodMetrics {
metric := metricsapi.PodMetrics{
ObjectMeta: metav1.ObjectMeta{
2016-05-17 19:31:31 +00:00
Name: fmt.Sprintf("%s-%d", podNamePrefix, i),
Namespace: namespace,
},
Timestamp: metav1.Time{Time: offsetTimestampBy(tc.targetTimestamp)},
Window: metav1.Duration{Duration: tc.window},
Containers: []metricsapi.ContainerMetrics{},
2016-05-17 19:31:31 +00:00
}
for j, cpu := range containers {
cm := metricsapi.ContainerMetrics{
2016-05-17 19:31:31 +00:00
Name: fmt.Sprintf("%s-%d-container-%d", podNamePrefix, i, j),
Usage: v1.ResourceList{
v1.ResourceCPU: *resource.NewMilliQuantity(
2016-05-17 19:31:31 +00:00
cpu,
resource.DecimalSI),
v1.ResourceMemory: *resource.NewQuantity(
2016-05-17 19:31:31 +00:00
int64(1024*1024),
resource.BinarySI),
},
}
metric.Containers = append(metric.Containers, cm)
2015-09-23 10:00:20 +00:00
}
metrics.Items = append(metrics.Items, metric)
2015-09-23 10:00:20 +00:00
}
2016-05-17 19:31:31 +00:00
heapsterRawMemResponse, _ := json.Marshal(&metrics)
return true, newFakeResponseWrapper(heapsterRawMemResponse), nil
})
} else {
fakeClient.AddProxyReactor("services", func(action core.Action) (handled bool, ret restclient.ResponseWrapper, err error) {
metrics := heapster.MetricResultList{}
var latestTimestamp time.Time
for _, reportedMetricPoints := range tc.reportedMetricsPoints {
var heapsterMetricPoints []heapster.MetricPoint
for _, reportedMetricPoint := range reportedMetricPoints {
timestamp := offsetTimestampBy(reportedMetricPoint.timestamp)
2016-05-17 19:31:31 +00:00
if latestTimestamp.Before(timestamp) {
latestTimestamp = timestamp
}
heapsterMetricPoint := heapster.MetricPoint{Timestamp: timestamp, Value: reportedMetricPoint.level, FloatValue: nil}
heapsterMetricPoints = append(heapsterMetricPoints, heapsterMetricPoint)
}
metric := heapster.MetricResult{
Metrics: heapsterMetricPoints,
LatestTimestamp: latestTimestamp,
}
metrics.Items = append(metrics.Items, metric)
2015-09-23 10:00:20 +00:00
}
2016-05-17 19:31:31 +00:00
heapsterRawMemResponse, _ := json.Marshal(&metrics)
return true, newFakeResponseWrapper(heapsterRawMemResponse), nil
})
}
2015-09-23 10:00:20 +00:00
return fakeClient
}
2016-11-18 20:50:17 +00:00
func buildPod(namespace, podName string, podLabels map[string]string, phase v1.PodPhase, request string) v1.Pod {
return v1.Pod{
ObjectMeta: metav1.ObjectMeta{
Name: podName,
Namespace: namespace,
Support for both map-based and set-based selectors in extensions/v1beta1.Scale Here are a list of changes along with an explanation of how they work: 1. Add a new string field called TargetSelector to the external version of extensions Scale type (extensions/v1beta1.Scale). This is a serialized version of either the map-based selector (in case of ReplicationControllers) or the unversioned.LabelSelector struct (in case of Deployments and ReplicaSets). 2. Change the selector field in the internal Scale type (extensions.Scale) to unversioned.LabelSelector. 3. Add conversion functions to convert from two external selector fields to a single internal selector field. The rules for conversion are as follows: i. If the target resource that this scale targets supports LabelSelector (Deployments and ReplicaSets), then serialize the LabelSelector and store the string in the TargetSelector field in the external version and leave the map-based Selector field as nil. ii. If the target resource only supports a map-based selector (ReplicationControllers), then still serialize that selector and store the serialized string in the TargetSelector field. Also, set the the Selector map field in the external Scale type. iii. When converting from external to internal version, parse the TargetSelector string into LabelSelector struct if the string isn't empty. If it is empty, then check if the Selector map is set and just assign that map to the MatchLabels component of the LabelSelector. iv. When converting from internal to external version, serialize the LabelSelector and store it in the TargetSelector field. If only the MatchLabel component is set, then also copy that value to the Selector map field in the external version. 4. HPA now just converts the LabelSelector field to a Selector interface type to list the pods. 5. Scale Get and Update etcd methods for Deployments and ReplicaSets now return extensions.Scale instead of autoscaling.Scale. 6. Consequently, SubresourceGroupVersion override and is "autoscaling" enabled check is now removed from pkg/master/master.go 7. Other small changes to labels package, fuzzer and LabelSelector helpers to piece this all together. 8. Add unit tests to HPA targeting Deployments and ReplicaSets. 9. Add an e2e test to HPA targeting ReplicaSets.
2016-03-09 00:27:13 +00:00
Labels: podLabels,
},
2016-11-18 20:50:17 +00:00
Spec: v1.PodSpec{
Containers: []v1.Container{
{
2016-11-18 20:50:17 +00:00
Resources: v1.ResourceRequirements{
Requests: v1.ResourceList{
v1.ResourceCPU: resource.MustParse(request),
},
},
},
},
},
2016-11-18 20:50:17 +00:00
Status: v1.PodStatus{
Phase: phase,
2016-11-18 20:50:17 +00:00
Conditions: []v1.PodCondition{
{
2016-11-18 20:50:17 +00:00
Type: v1.PodReady,
Status: v1.ConditionTrue,
},
},
},
}
}
func (tc *testCase) verifyResults(t *testing.T, metrics PodMetricsInfo, timestamp time.Time, err error) {
2015-09-23 10:00:20 +00:00
if tc.desiredError != nil {
assert.Error(t, err, "there should be an error retrieving the metrics")
assert.Contains(t, fmt.Sprintf("%v", err), fmt.Sprintf("%v", tc.desiredError), "the error message should be eas expected")
2015-09-23 10:00:20 +00:00
return
}
assert.NoError(t, err, "there should be no error retrieving the metrics")
assert.NotNil(t, metrics, "there should be metrics returned")
if len(metrics) != len(tc.desiredMetricValues) {
t.Errorf("Not equal:\nexpected: %v\nactual: %v", tc.desiredMetricValues, metrics)
} else {
for k, m := range metrics {
if !m.Timestamp.Equal(tc.desiredMetricValues[k].Timestamp) ||
m.Window != tc.desiredMetricValues[k].Window ||
m.Value != tc.desiredMetricValues[k].Value {
t.Errorf("Not equal:\nexpected: %v\nactual: %v", tc.desiredMetricValues, metrics)
break
}
}
}
targetTimestamp := offsetTimestampBy(tc.targetTimestamp)
assert.True(t, targetTimestamp.Equal(timestamp), fmt.Sprintf("the timestamp should be as expected (%s) but was %s", targetTimestamp, timestamp))
2015-09-23 10:00:20 +00:00
}
2015-09-23 10:00:20 +00:00
func (tc *testCase) runTest(t *testing.T) {
testClient := tc.prepareTestClient(t)
metricsClient := NewHeapsterMetricsClient(testClient, DefaultHeapsterNamespace, DefaultHeapsterScheme, DefaultHeapsterService, DefaultHeapsterPort)
isResource := len(tc.resourceName) > 0
if isResource {
info, timestamp, err := metricsClient.GetResourceMetric(tc.resourceName, tc.namespace, tc.selector)
tc.verifyResults(t, info, timestamp, err)
2016-01-27 20:14:45 +00:00
} else {
info, timestamp, err := metricsClient.GetRawMetric(tc.metricName, tc.namespace, tc.selector, tc.metricSelector)
tc.verifyResults(t, info, timestamp, err)
2016-01-27 20:14:45 +00:00
}
2015-09-23 10:00:20 +00:00
}
func TestCPU(t *testing.T) {
targetTimestamp := 1
window := 30 * time.Second
2015-09-23 10:00:20 +00:00
tc := testCase{
replicas: 3,
desiredMetricValues: PodMetricsInfo{
"test-pod-0": PodMetric{Value: 5000, Timestamp: offsetTimestampBy(targetTimestamp), Window: window},
"test-pod-1": PodMetric{Value: 5000, Timestamp: offsetTimestampBy(targetTimestamp), Window: window},
"test-pod-2": PodMetric{Value: 5000, Timestamp: offsetTimestampBy(targetTimestamp), Window: window},
},
2016-11-18 20:50:17 +00:00
resourceName: v1.ResourceCPU,
targetTimestamp: targetTimestamp,
window: window,
2016-05-17 19:31:31 +00:00
reportedPodMetrics: [][]int64{{5000}, {5000}, {5000}},
}
tc.runTest(t)
}
2016-01-27 20:14:45 +00:00
func TestQPS(t *testing.T) {
targetTimestamp := 1
2015-09-23 10:00:20 +00:00
tc := testCase{
replicas: 3,
desiredMetricValues: PodMetricsInfo{
"test-pod-0": PodMetric{Value: 10000, Timestamp: offsetTimestampBy(targetTimestamp), Window: heapsterDefaultMetricWindow},
"test-pod-1": PodMetric{Value: 20000, Timestamp: offsetTimestampBy(targetTimestamp), Window: heapsterDefaultMetricWindow},
"test-pod-2": PodMetric{Value: 10000, Timestamp: offsetTimestampBy(targetTimestamp), Window: heapsterDefaultMetricWindow},
},
metricName: "qps",
targetTimestamp: targetTimestamp,
2016-01-27 20:14:45 +00:00
reportedMetricsPoints: [][]metricPoint{{{10, 1}}, {{20, 1}}, {{10, 1}}},
}
2015-09-23 10:00:20 +00:00
tc.runTest(t)
}
2016-01-27 20:14:45 +00:00
func TestQpsSumEqualZero(t *testing.T) {
targetTimestamp := 0
2015-09-23 10:00:20 +00:00
tc := testCase{
replicas: 3,
desiredMetricValues: PodMetricsInfo{
"test-pod-0": PodMetric{Value: 0, Timestamp: offsetTimestampBy(targetTimestamp), Window: heapsterDefaultMetricWindow},
"test-pod-1": PodMetric{Value: 0, Timestamp: offsetTimestampBy(targetTimestamp), Window: heapsterDefaultMetricWindow},
"test-pod-2": PodMetric{Value: 0, Timestamp: offsetTimestampBy(targetTimestamp), Window: heapsterDefaultMetricWindow},
},
metricName: "qps",
targetTimestamp: targetTimestamp,
2015-09-23 10:00:20 +00:00
reportedMetricsPoints: [][]metricPoint{{{0, 0}}, {{0, 0}}, {{0, 0}}},
}
tc.runTest(t)
}
2015-09-23 10:00:20 +00:00
func TestCPUMoreMetrics(t *testing.T) {
targetTimestamp := 10
window := 30 * time.Second
2015-09-23 10:00:20 +00:00
tc := testCase{
replicas: 5,
desiredMetricValues: PodMetricsInfo{
"test-pod-0": PodMetric{Value: 5000, Timestamp: offsetTimestampBy(targetTimestamp), Window: window},
"test-pod-1": PodMetric{Value: 5000, Timestamp: offsetTimestampBy(targetTimestamp), Window: window},
"test-pod-2": PodMetric{Value: 5000, Timestamp: offsetTimestampBy(targetTimestamp), Window: window},
"test-pod-3": PodMetric{Value: 5000, Timestamp: offsetTimestampBy(targetTimestamp), Window: window},
"test-pod-4": PodMetric{Value: 5000, Timestamp: offsetTimestampBy(targetTimestamp), Window: window},
},
2016-11-18 20:50:17 +00:00
resourceName: v1.ResourceCPU,
targetTimestamp: targetTimestamp,
window: window,
2016-05-17 19:31:31 +00:00
reportedPodMetrics: [][]int64{{1000, 2000, 2000}, {5000}, {1000, 1000, 1000, 2000}, {4000, 1000}, {5000}},
2015-09-23 10:00:20 +00:00
}
tc.runTest(t)
}
func TestCPUMissingMetrics(t *testing.T) {
targetTimestamp := 0
window := 30 * time.Second
2015-09-23 10:00:20 +00:00
tc := testCase{
replicas: 3,
desiredMetricValues: PodMetricsInfo{
"test-pod-0": PodMetric{Value: 4000, Timestamp: offsetTimestampBy(targetTimestamp), Window: window},
},
2016-11-18 20:50:17 +00:00
resourceName: v1.ResourceCPU,
targetTimestamp: targetTimestamp,
window: window,
2016-05-17 19:31:31 +00:00
reportedPodMetrics: [][]int64{{4000}},
2015-09-23 10:00:20 +00:00
}
tc.runTest(t)
}
2016-01-27 20:14:45 +00:00
func TestQpsMissingMetrics(t *testing.T) {
2015-09-23 10:00:20 +00:00
tc := testCase{
replicas: 3,
desiredError: fmt.Errorf("requested metrics for 3 pods, got metrics for 1"),
metricName: "qps",
targetTimestamp: 1,
2015-09-23 10:00:20 +00:00
reportedMetricsPoints: [][]metricPoint{{{4000, 4}}},
}
tc.runTest(t)
}
2016-01-27 20:14:45 +00:00
func TestQpsSuperfluousMetrics(t *testing.T) {
2015-09-23 10:00:20 +00:00
tc := testCase{
replicas: 3,
desiredError: fmt.Errorf("requested metrics for 3 pods, got metrics for 6"),
metricName: "qps",
2015-09-23 10:00:20 +00:00
reportedMetricsPoints: [][]metricPoint{{{1000, 1}}, {{2000, 4}}, {{2000, 1}}, {{4000, 5}}, {{2000, 1}}, {{4000, 4}}},
}
tc.runTest(t)
}
func TestCPUEmptyMetrics(t *testing.T) {
tc := testCase{
replicas: 3,
2016-11-18 20:50:17 +00:00
resourceName: v1.ResourceCPU,
desiredError: fmt.Errorf("no metrics returned from heapster"),
2015-09-23 10:00:20 +00:00
reportedMetricsPoints: [][]metricPoint{},
2016-05-17 19:31:31 +00:00
reportedPodMetrics: [][]int64{},
}
tc.runTest(t)
}
func TestQpsEmptyEntries(t *testing.T) {
targetTimestamp := 4
tc := testCase{
replicas: 3,
metricName: "qps",
desiredMetricValues: PodMetricsInfo{
"test-pod-0": PodMetric{Value: 4000000, Timestamp: offsetTimestampBy(targetTimestamp), Window: heapsterDefaultMetricWindow},
"test-pod-2": PodMetric{Value: 2000000, Timestamp: offsetTimestampBy(targetTimestamp), Window: heapsterDefaultMetricWindow},
},
targetTimestamp: targetTimestamp,
reportedMetricsPoints: [][]metricPoint{{{4000, 4}}, {}, {{2000, 4}}},
2015-09-23 10:00:20 +00:00
}
tc.runTest(t)
}
func TestCPUZeroReplicas(t *testing.T) {
tc := testCase{
2016-05-17 19:31:31 +00:00
replicas: 0,
2016-11-18 20:50:17 +00:00
resourceName: v1.ResourceCPU,
desiredError: fmt.Errorf("no metrics returned from heapster"),
2016-05-17 19:31:31 +00:00
reportedPodMetrics: [][]int64{},
2015-09-23 10:00:20 +00:00
}
tc.runTest(t)
}
func TestCPUEmptyMetricsForOnePod(t *testing.T) {
targetTimestamp := 0
window := 30 * time.Second
2015-09-23 10:00:20 +00:00
tc := testCase{
replicas: 3,
2016-11-18 20:50:17 +00:00
resourceName: v1.ResourceCPU,
desiredMetricValues: PodMetricsInfo{
"test-pod-0": PodMetric{Value: 100, Timestamp: offsetTimestampBy(targetTimestamp), Window: window},
"test-pod-1": PodMetric{Value: 700, Timestamp: offsetTimestampBy(targetTimestamp), Window: window},
},
targetTimestamp: targetTimestamp,
window: window,
reportedPodMetrics: [][]int64{{100}, {300, 400}, {}},
2015-09-23 10:00:20 +00:00
}
tc.runTest(t)
}
func testCollapseTimeSamples(t *testing.T) {
now := time.Now()
metrics := heapster.MetricResult{
Metrics: []heapster.MetricPoint{
{Timestamp: now, Value: 50, FloatValue: nil},
{Timestamp: now.Add(-15 * time.Second), Value: 100, FloatValue: nil},
{Timestamp: now.Add(-60 * time.Second), Value: 100000, FloatValue: nil}},
LatestTimestamp: now,
}
val, timestamp, hadMetrics := collapseTimeSamples(metrics, time.Minute)
assert.True(t, hadMetrics, "should report that it received a populated list of metrics")
assert.InEpsilon(t, float64(75), val, 0.1, "collapsed sample value should be as expected")
assert.True(t, timestamp.Equal(now), "timestamp should be the current time (the newest)")
}
func offsetTimestampBy(t int) time.Time {
return fixedTimestamp.Add(time.Duration(t) * time.Minute)
}