stackdriver.go 5.8 KB

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