metrics_test.go 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  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. "bufio"
  16. "fmt"
  17. "net/http"
  18. "net/http/httptest"
  19. "runtime"
  20. "testing"
  21. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  22. "k8s.io/apimachinery/pkg/runtime/schema"
  23. clientset "k8s.io/client-go/kubernetes"
  24. restclient "k8s.io/client-go/rest"
  25. "k8s.io/kubernetes/test/integration/framework"
  26. "github.com/golang/protobuf/proto"
  27. prometheuspb "github.com/prometheus/client_model/go"
  28. "k8s.io/klog"
  29. )
  30. const scrapeRequestHeader = "application/vnd.google.protobuf;proto=io.prometheus.client.MetricFamily;encoding=compact-text"
  31. func scrapeMetrics(s *httptest.Server) ([]*prometheuspb.MetricFamily, error) {
  32. req, err := http.NewRequest("GET", s.URL+"/metrics", nil)
  33. if err != nil {
  34. return nil, fmt.Errorf("Unable to create http request: %v", err)
  35. }
  36. // Ask the prometheus exporter for its text protocol buffer format, since it's
  37. // much easier to parse than its plain-text format. Don't use the serialized
  38. // proto representation since it uses a non-standard varint delimiter between
  39. // metric families.
  40. req.Header.Add("Accept", scrapeRequestHeader)
  41. client := &http.Client{}
  42. resp, err := client.Do(req)
  43. if err != nil {
  44. return nil, fmt.Errorf("Unable to contact metrics endpoint of master: %v", err)
  45. }
  46. defer resp.Body.Close()
  47. if resp.StatusCode != http.StatusOK {
  48. return nil, fmt.Errorf("Non-200 response trying to scrape metrics from master: %v", resp)
  49. }
  50. // Each line in the response body should contain all the data for a single metric.
  51. var metrics []*prometheuspb.MetricFamily
  52. scanner := bufio.NewScanner(resp.Body)
  53. // Increase buffer size, since default one is too small for reading
  54. // the /metrics contents.
  55. scanner.Buffer(make([]byte, 10), 131072)
  56. for scanner.Scan() {
  57. var metric prometheuspb.MetricFamily
  58. if err := proto.UnmarshalText(scanner.Text(), &metric); err != nil {
  59. return nil, fmt.Errorf("Failed to unmarshal line of metrics response: %v", err)
  60. }
  61. klog.V(4).Infof("Got metric %q", metric.GetName())
  62. metrics = append(metrics, &metric)
  63. }
  64. return metrics, nil
  65. }
  66. func checkForExpectedMetrics(t *testing.T, metrics []*prometheuspb.MetricFamily, expectedMetrics []string) {
  67. foundMetrics := make(map[string]bool)
  68. for _, metric := range metrics {
  69. foundMetrics[metric.GetName()] = true
  70. }
  71. for _, expected := range expectedMetrics {
  72. if _, found := foundMetrics[expected]; !found {
  73. t.Errorf("Master metrics did not include expected metric %q", expected)
  74. }
  75. }
  76. }
  77. func TestMasterProcessMetrics(t *testing.T) {
  78. if runtime.GOOS == "darwin" || runtime.GOOS == "windows" {
  79. t.Skipf("not supported on GOOS=%s", runtime.GOOS)
  80. }
  81. _, s, closeFn := framework.RunAMaster(nil)
  82. defer closeFn()
  83. metrics, err := scrapeMetrics(s)
  84. if err != nil {
  85. t.Fatal(err)
  86. }
  87. checkForExpectedMetrics(t, metrics, []string{
  88. "process_start_time_seconds",
  89. "process_cpu_seconds_total",
  90. "process_open_fds",
  91. "process_resident_memory_bytes",
  92. })
  93. }
  94. func TestApiserverMetrics(t *testing.T) {
  95. _, s, closeFn := framework.RunAMaster(nil)
  96. defer closeFn()
  97. // Make a request to the apiserver to ensure there's at least one data point
  98. // for the metrics we're expecting -- otherwise, they won't be exported.
  99. client := clientset.NewForConfigOrDie(&restclient.Config{Host: s.URL, ContentConfig: restclient.ContentConfig{GroupVersion: &schema.GroupVersion{Group: "", Version: "v1"}}})
  100. if _, err := client.CoreV1().Pods(metav1.NamespaceDefault).List(metav1.ListOptions{}); err != nil {
  101. t.Fatalf("unexpected error getting pods: %v", err)
  102. }
  103. metrics, err := scrapeMetrics(s)
  104. if err != nil {
  105. t.Fatal(err)
  106. }
  107. checkForExpectedMetrics(t, metrics, []string{
  108. "apiserver_request_total",
  109. "apiserver_request_duration_seconds",
  110. "etcd_request_duration_seconds",
  111. })
  112. }