utilization.go 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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. "fmt"
  16. )
  17. // GetResourceUtilizationRatio takes in a set of metrics, a set of matching requests,
  18. // and a target utilization percentage, and calculates the ratio of
  19. // desired to actual utilization (returning that, the actual utilization, and the raw average value)
  20. func GetResourceUtilizationRatio(metrics PodMetricsInfo, requests map[string]int64, targetUtilization int32) (utilizationRatio float64, currentUtilization int32, rawAverageValue int64, err error) {
  21. metricsTotal := int64(0)
  22. requestsTotal := int64(0)
  23. numEntries := 0
  24. for podName, metric := range metrics {
  25. request, hasRequest := requests[podName]
  26. if !hasRequest {
  27. // we check for missing requests elsewhere, so assuming missing requests == extraneous metrics
  28. continue
  29. }
  30. metricsTotal += metric.Value
  31. requestsTotal += request
  32. numEntries++
  33. }
  34. // if the set of requests is completely disjoint from the set of metrics,
  35. // then we could have an issue where the requests total is zero
  36. if requestsTotal == 0 {
  37. return 0, 0, 0, fmt.Errorf("no metrics returned matched known pods")
  38. }
  39. currentUtilization = int32((metricsTotal * 100) / requestsTotal)
  40. return float64(currentUtilization) / float64(targetUtilization), currentUtilization, metricsTotal / int64(numEntries), nil
  41. }
  42. // GetMetricUtilizationRatio takes in a set of metrics and a target utilization value,
  43. // and calcuates the ratio of desired to actual utilization
  44. // (returning that and the actual utilization)
  45. func GetMetricUtilizationRatio(metrics PodMetricsInfo, targetUtilization int64) (utilizationRatio float64, currentUtilization int64) {
  46. metricsTotal := int64(0)
  47. for _, metric := range metrics {
  48. metricsTotal += metric.Value
  49. }
  50. currentUtilization = metricsTotal / int64(len(metrics))
  51. return float64(currentUtilization) / float64(targetUtilization), currentUtilization
  52. }