stackdriver.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. /*
  2. Copyright 2017 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 monitoring
  14. import (
  15. "context"
  16. "fmt"
  17. "math"
  18. "os"
  19. "time"
  20. "k8s.io/apimachinery/pkg/util/wait"
  21. "k8s.io/kubernetes/test/e2e/framework"
  22. e2eautoscaling "k8s.io/kubernetes/test/e2e/framework/autoscaling"
  23. e2eskipper "k8s.io/kubernetes/test/e2e/framework/skipper"
  24. instrumentation "k8s.io/kubernetes/test/e2e/instrumentation/common"
  25. "github.com/onsi/ginkgo"
  26. "golang.org/x/oauth2/google"
  27. gcm "google.golang.org/api/monitoring/v3"
  28. "google.golang.org/api/option"
  29. )
  30. var (
  31. // Stackdriver container metrics, as described here:
  32. // https://cloud.google.com/monitoring/api/metrics#gcp-container
  33. stackdriverMetrics = []string{
  34. "uptime",
  35. "memory/bytes_total",
  36. "memory/bytes_used",
  37. "cpu/reserved_cores",
  38. "cpu/usage_time",
  39. "memory/page_fault_count",
  40. "disk/bytes_used",
  41. "disk/bytes_total",
  42. "cpu/utilization",
  43. }
  44. pollFrequency = time.Second * 5
  45. pollTimeout = time.Minute * 7
  46. rcName = "resource-consumer"
  47. memoryUsed = 64
  48. memoryLimit int64 = 200
  49. tolerance = 0.25
  50. )
  51. var _ = instrumentation.SIGDescribe("Stackdriver Monitoring", func() {
  52. ginkgo.BeforeEach(func() {
  53. e2eskipper.SkipUnlessProviderIs("gce", "gke")
  54. })
  55. f := framework.NewDefaultFramework("stackdriver-monitoring")
  56. ginkgo.It("should have cluster metrics [Feature:StackdriverMonitoring]", func() {
  57. testStackdriverMonitoring(f, 1, 100, 200)
  58. })
  59. })
  60. func testStackdriverMonitoring(f *framework.Framework, pods, allPodsCPU int, perPodCPU int64) {
  61. projectID := framework.TestContext.CloudConfig.ProjectID
  62. ctx := context.Background()
  63. client, err := google.DefaultClient(ctx, gcm.CloudPlatformScope)
  64. framework.ExpectNoError(err)
  65. // Hack for running tests locally
  66. // If this is your use case, create application default credentials:
  67. // $ gcloud auth application-default login
  68. // and uncomment following lines (comment out the two lines above): (DON'T set the env var below)
  69. /*
  70. ts, err := google.DefaultTokenSource(oauth2.NoContext)
  71. framework.Logf("Couldn't get application default credentials, %v", err)
  72. if err != nil {
  73. framework.Failf("Error accessing application default credentials, %v", err)
  74. }
  75. client := oauth2.NewClient(oauth2.NoContext, ts)
  76. */
  77. gcmService, err := gcm.NewService(ctx, option.WithHTTPClient(client))
  78. // set this env var if accessing Stackdriver test endpoint (default is prod):
  79. // $ export STACKDRIVER_API_ENDPOINT_OVERRIDE=https://test-monitoring.sandbox.googleapis.com/
  80. basePathOverride := os.Getenv("STACKDRIVER_API_ENDPOINT_OVERRIDE")
  81. if basePathOverride != "" {
  82. gcmService.BasePath = basePathOverride
  83. }
  84. framework.ExpectNoError(err)
  85. rc := e2eautoscaling.NewDynamicResourceConsumer(rcName, f.Namespace.Name, e2eautoscaling.KindDeployment, pods, allPodsCPU, memoryUsed, 0, perPodCPU, memoryLimit, f.ClientSet, f.ScalesGetter)
  86. defer rc.CleanUp()
  87. rc.WaitForReplicas(pods, 15*time.Minute)
  88. metricsMap := map[string]bool{}
  89. pollingFunction := checkForMetrics(projectID, gcmService, time.Now(), metricsMap, allPodsCPU, perPodCPU)
  90. err = wait.Poll(pollFrequency, pollTimeout, pollingFunction)
  91. if err != nil {
  92. framework.Logf("Missing metrics: %+v\n", metricsMap)
  93. }
  94. framework.ExpectNoError(err)
  95. }
  96. func checkForMetrics(projectID string, gcmService *gcm.Service, start time.Time, metricsMap map[string]bool, cpuUsed int, cpuLimit int64) func() (bool, error) {
  97. return func() (bool, error) {
  98. counter := 0
  99. correctUtilization := false
  100. for _, metric := range stackdriverMetrics {
  101. metricsMap[metric] = false
  102. }
  103. for _, metric := range stackdriverMetrics {
  104. // TODO: check only for metrics from this cluster
  105. ts, err := fetchTimeSeries(projectID, gcmService, metric, start, time.Now())
  106. framework.ExpectNoError(err)
  107. if len(ts) > 0 {
  108. counter = counter + 1
  109. metricsMap[metric] = true
  110. framework.Logf("Received %v timeseries for metric %v\n", len(ts), metric)
  111. } else {
  112. framework.Logf("No timeseries for metric %v\n", metric)
  113. }
  114. var sum float64
  115. switch metric {
  116. case "cpu/utilization":
  117. for _, t := range ts {
  118. max := t.Points[0]
  119. maxEnd, _ := time.Parse(time.RFC3339, max.Interval.EndTime)
  120. for _, p := range t.Points {
  121. pEnd, _ := time.Parse(time.RFC3339, p.Interval.EndTime)
  122. if pEnd.After(maxEnd) {
  123. max = p
  124. maxEnd, _ = time.Parse(time.RFC3339, max.Interval.EndTime)
  125. }
  126. }
  127. sum = sum + *max.Value.DoubleValue
  128. framework.Logf("Received %v points for metric %v\n",
  129. len(t.Points), metric)
  130. }
  131. framework.Logf("Most recent cpu/utilization sum*cpu/limit: %v\n", sum*float64(cpuLimit))
  132. if math.Abs(sum*float64(cpuLimit)-float64(cpuUsed)) > tolerance*float64(cpuUsed) {
  133. return false, nil
  134. }
  135. correctUtilization = true
  136. }
  137. }
  138. if counter < 9 || !correctUtilization {
  139. return false, nil
  140. }
  141. return true, nil
  142. }
  143. }
  144. func createMetricFilter(metric string, containerName string) string {
  145. return fmt.Sprintf(`metric.type="container.googleapis.com/container/%s" AND
  146. resource.label.container_name="%s"`, metric, containerName)
  147. }
  148. func fetchTimeSeries(projectID string, gcmService *gcm.Service, metric string, start time.Time, end time.Time) ([]*gcm.TimeSeries, error) {
  149. response, err := gcmService.Projects.TimeSeries.
  150. List(fullProjectName(projectID)).
  151. Filter(createMetricFilter(metric, rcName)).
  152. IntervalStartTime(start.Format(time.RFC3339)).
  153. IntervalEndTime(end.Format(time.RFC3339)).
  154. Do()
  155. if err != nil {
  156. return nil, err
  157. }
  158. return response.TimeSeries, nil
  159. }
  160. func fullProjectName(name string) string {
  161. return fmt.Sprintf("projects/%s", name)
  162. }