legacy_metrics_client.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  1. /*
  2. Copyright 2015 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package metrics
  14. import (
  15. "encoding/json"
  16. "fmt"
  17. "strings"
  18. "time"
  19. heapster "k8s.io/heapster/metrics/api/v1/types"
  20. "k8s.io/klog"
  21. metricsapi "k8s.io/metrics/pkg/apis/metrics/v1alpha1"
  22. autoscaling "k8s.io/api/autoscaling/v2beta2"
  23. "k8s.io/api/core/v1"
  24. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  25. "k8s.io/apimachinery/pkg/labels"
  26. clientset "k8s.io/client-go/kubernetes"
  27. v1core "k8s.io/client-go/kubernetes/typed/core/v1"
  28. )
  29. const (
  30. DefaultHeapsterNamespace = "kube-system"
  31. DefaultHeapsterScheme = "http"
  32. DefaultHeapsterService = "heapster"
  33. DefaultHeapsterPort = "" // use the first exposed port on the service
  34. heapsterDefaultMetricWindow = time.Minute
  35. )
  36. var heapsterQueryStart = -5 * time.Minute
  37. type HeapsterMetricsClient struct {
  38. services v1core.ServiceInterface
  39. podsGetter v1core.PodsGetter
  40. heapsterScheme string
  41. heapsterService string
  42. heapsterPort string
  43. }
  44. func NewHeapsterMetricsClient(client clientset.Interface, namespace, scheme, service, port string) MetricsClient {
  45. return &HeapsterMetricsClient{
  46. services: client.CoreV1().Services(namespace),
  47. podsGetter: client.CoreV1(),
  48. heapsterScheme: scheme,
  49. heapsterService: service,
  50. heapsterPort: port,
  51. }
  52. }
  53. func (h *HeapsterMetricsClient) GetResourceMetric(resource v1.ResourceName, namespace string, selector labels.Selector) (PodMetricsInfo, time.Time, error) {
  54. metricPath := fmt.Sprintf("/apis/metrics/v1alpha1/namespaces/%s/pods", namespace)
  55. params := map[string]string{"labelSelector": selector.String()}
  56. resultRaw, err := h.services.
  57. ProxyGet(h.heapsterScheme, h.heapsterService, h.heapsterPort, metricPath, params).
  58. DoRaw()
  59. if err != nil {
  60. return nil, time.Time{}, fmt.Errorf("failed to get pod resource metrics: %v", err)
  61. }
  62. klog.V(8).Infof("Heapster metrics result: %s", string(resultRaw))
  63. metrics := metricsapi.PodMetricsList{}
  64. err = json.Unmarshal(resultRaw, &metrics)
  65. if err != nil {
  66. return nil, time.Time{}, fmt.Errorf("failed to unmarshal heapster response: %v", err)
  67. }
  68. if len(metrics.Items) == 0 {
  69. return nil, time.Time{}, fmt.Errorf("no metrics returned from heapster")
  70. }
  71. res := make(PodMetricsInfo, len(metrics.Items))
  72. for _, m := range metrics.Items {
  73. podSum := int64(0)
  74. missing := len(m.Containers) == 0
  75. for _, c := range m.Containers {
  76. resValue, found := c.Usage[v1.ResourceName(resource)]
  77. if !found {
  78. missing = true
  79. klog.V(2).Infof("missing resource metric %v for container %s in pod %s/%s", resource, c.Name, namespace, m.Name)
  80. continue
  81. }
  82. podSum += resValue.MilliValue()
  83. }
  84. if !missing {
  85. res[m.Name] = PodMetric{
  86. Timestamp: m.Timestamp.Time,
  87. Window: m.Window.Duration,
  88. Value: int64(podSum),
  89. }
  90. }
  91. }
  92. timestamp := metrics.Items[0].Timestamp.Time
  93. return res, timestamp, nil
  94. }
  95. func (h *HeapsterMetricsClient) GetRawMetric(metricName string, namespace string, selector labels.Selector, metricSelector labels.Selector) (PodMetricsInfo, time.Time, error) {
  96. podList, err := h.podsGetter.Pods(namespace).List(metav1.ListOptions{LabelSelector: selector.String()})
  97. if err != nil {
  98. return nil, time.Time{}, fmt.Errorf("failed to get pod list while fetching metrics: %v", err)
  99. }
  100. if len(podList.Items) == 0 {
  101. return nil, time.Time{}, fmt.Errorf("no pods matched the provided selector")
  102. }
  103. podNames := make([]string, len(podList.Items))
  104. for i, pod := range podList.Items {
  105. podNames[i] = pod.Name
  106. }
  107. now := time.Now()
  108. startTime := now.Add(heapsterQueryStart)
  109. metricPath := fmt.Sprintf("/api/v1/model/namespaces/%s/pod-list/%s/metrics/%s",
  110. namespace,
  111. strings.Join(podNames, ","),
  112. metricName)
  113. resultRaw, err := h.services.
  114. ProxyGet(h.heapsterScheme, h.heapsterService, h.heapsterPort, metricPath, map[string]string{"start": startTime.Format(time.RFC3339)}).
  115. DoRaw()
  116. if err != nil {
  117. return nil, time.Time{}, fmt.Errorf("failed to get pod metrics: %v", err)
  118. }
  119. var metrics heapster.MetricResultList
  120. err = json.Unmarshal(resultRaw, &metrics)
  121. if err != nil {
  122. return nil, time.Time{}, fmt.Errorf("failed to unmarshal heapster response: %v", err)
  123. }
  124. klog.V(4).Infof("Heapster metrics result: %s", string(resultRaw))
  125. if len(metrics.Items) != len(podNames) {
  126. // if we get too many metrics or two few metrics, we have no way of knowing which metric goes to which pod
  127. // (note that Heapster returns *empty* metric items when a pod does not exist or have that metric, so this
  128. // does not cover the "missing metric entry" case)
  129. return nil, time.Time{}, fmt.Errorf("requested metrics for %v pods, got metrics for %v", len(podNames), len(metrics.Items))
  130. }
  131. var timestamp *time.Time
  132. res := make(PodMetricsInfo, len(metrics.Items))
  133. for i, podMetrics := range metrics.Items {
  134. val, podTimestamp, hadMetrics := collapseTimeSamples(podMetrics, time.Minute)
  135. if hadMetrics {
  136. res[podNames[i]] = PodMetric{
  137. Timestamp: podTimestamp,
  138. Window: heapsterDefaultMetricWindow,
  139. Value: int64(val),
  140. }
  141. if timestamp == nil || podTimestamp.Before(*timestamp) {
  142. timestamp = &podTimestamp
  143. }
  144. }
  145. }
  146. if timestamp == nil {
  147. timestamp = &time.Time{}
  148. }
  149. return res, *timestamp, nil
  150. }
  151. func (h *HeapsterMetricsClient) GetObjectMetric(metricName string, namespace string, objectRef *autoscaling.CrossVersionObjectReference, metricSelector labels.Selector) (int64, time.Time, error) {
  152. return 0, time.Time{}, fmt.Errorf("object metrics are not yet supported")
  153. }
  154. func (h *HeapsterMetricsClient) GetExternalMetric(metricName, namespace string, selector labels.Selector) ([]int64, time.Time, error) {
  155. return nil, time.Time{}, fmt.Errorf("external metrics aren't supported")
  156. }
  157. func collapseTimeSamples(metrics heapster.MetricResult, duration time.Duration) (int64, time.Time, bool) {
  158. floatSum := float64(0)
  159. intSum := int64(0)
  160. intSumCount := 0
  161. floatSumCount := 0
  162. var newest *heapster.MetricPoint // creation time of the newest sample for this pod
  163. for i, metricPoint := range metrics.Metrics {
  164. if newest == nil || newest.Timestamp.Before(metricPoint.Timestamp) {
  165. newest = &metrics.Metrics[i]
  166. }
  167. }
  168. if newest != nil {
  169. for _, metricPoint := range metrics.Metrics {
  170. if metricPoint.Timestamp.Add(duration).After(newest.Timestamp) {
  171. intSum += int64(metricPoint.Value)
  172. intSumCount++
  173. if metricPoint.FloatValue != nil {
  174. floatSum += *metricPoint.FloatValue
  175. floatSumCount++
  176. }
  177. }
  178. }
  179. if newest.FloatValue != nil {
  180. return int64(floatSum / float64(floatSumCount) * 1000), newest.Timestamp, true
  181. } else {
  182. return (intSum * 1000) / int64(intSumCount), newest.Timestamp, true
  183. }
  184. }
  185. return 0, time.Time{}, false
  186. }