stackdriver_metadata_agent.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  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. "encoding/json"
  17. "fmt"
  18. "io/ioutil"
  19. "reflect"
  20. "time"
  21. "github.com/onsi/ginkgo"
  22. "golang.org/x/oauth2/google"
  23. "k8s.io/api/core/v1"
  24. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  25. clientset "k8s.io/client-go/kubernetes"
  26. "k8s.io/kubernetes/test/e2e/framework"
  27. instrumentation "k8s.io/kubernetes/test/e2e/instrumentation/common"
  28. )
  29. const (
  30. // Time to wait after a pod creation for it's metadata to be exported
  31. metadataWaitTime = 120 * time.Second
  32. // MonitoringScope is the scope for Stackdriver Metadata API
  33. MonitoringScope = "https://www.googleapis.com/auth/monitoring"
  34. )
  35. var _ = instrumentation.SIGDescribe("Stackdriver Monitoring", func() {
  36. ginkgo.BeforeEach(func() {
  37. framework.SkipUnlessProviderIs("gce", "gke")
  38. })
  39. f := framework.NewDefaultFramework("stackdriver-monitoring")
  40. var kubeClient clientset.Interface
  41. ginkgo.It("should run Stackdriver Metadata Agent [Feature:StackdriverMetadataAgent]", func() {
  42. kubeClient = f.ClientSet
  43. testAgent(f, kubeClient)
  44. })
  45. })
  46. func testAgent(f *framework.Framework, kubeClient clientset.Interface) {
  47. projectID := framework.TestContext.CloudConfig.ProjectID
  48. resourceType := "k8s_container"
  49. uniqueContainerName := fmt.Sprintf("test-container-%v", time.Now().Unix())
  50. endpoint := fmt.Sprintf(
  51. "https://stackdriver.googleapis.com/v1beta2/projects/%v/resourceMetadata?filter=resource.type%%3D%v+AND+resource.label.container_name%%3D%v",
  52. projectID,
  53. resourceType,
  54. uniqueContainerName)
  55. oauthClient, err := google.DefaultClient(context.Background(), MonitoringScope)
  56. if err != nil {
  57. framework.Failf("Failed to create oauth client: %s", err)
  58. }
  59. // Create test pod with unique name.
  60. framework.CreateExecPodOrFail(kubeClient, f.Namespace.Name, uniqueContainerName, func(pod *v1.Pod) {
  61. pod.Spec.Containers[0].Name = uniqueContainerName
  62. })
  63. defer kubeClient.CoreV1().Pods(f.Namespace.Name).Delete(uniqueContainerName, &metav1.DeleteOptions{})
  64. // Wait a short amount of time for Metadata Agent to be created and metadata to be exported
  65. time.Sleep(metadataWaitTime)
  66. resp, err := oauthClient.Get(endpoint)
  67. if err != nil {
  68. framework.Failf("Failed to call Stackdriver Metadata API %s", err)
  69. }
  70. if resp.StatusCode != 200 {
  71. framework.Failf("Stackdriver Metadata API returned error status: %s", resp.Status)
  72. }
  73. metadataAPIResponse, err := ioutil.ReadAll(resp.Body)
  74. if err != nil {
  75. framework.Failf("Failed to read response from Stackdriver Metadata API: %s", err)
  76. }
  77. exists, err := verifyPodExists(metadataAPIResponse, uniqueContainerName)
  78. if err != nil {
  79. framework.Failf("Failed to process response from Stackdriver Metadata API: %s", err)
  80. }
  81. if !exists {
  82. framework.Failf("Missing Metadata for container %q", uniqueContainerName)
  83. }
  84. }
  85. // Metadata has the information fetched from Stackdriver metadata API.
  86. type Metadata struct {
  87. Results []map[string]interface{}
  88. }
  89. // Resource contains the resource type and labels from Stackdriver metadata API.
  90. type Resource struct {
  91. resourceType string
  92. resourceLabels map[string]string
  93. }
  94. func verifyPodExists(response []byte, containerName string) (bool, error) {
  95. var metadata Metadata
  96. err := json.Unmarshal(response, &metadata)
  97. if err != nil {
  98. return false, fmt.Errorf("Failed to unmarshall: %s", err)
  99. }
  100. for _, result := range metadata.Results {
  101. rawResource, ok := result["resource"]
  102. if !ok {
  103. return false, fmt.Errorf("No resource entry in response from Stackdriver Metadata API")
  104. }
  105. resource, err := parseResource(rawResource)
  106. if err != nil {
  107. return false, fmt.Errorf("No 'resource' label: %s", err)
  108. }
  109. if resource.resourceType == "k8s_container" &&
  110. resource.resourceLabels["container_name"] == containerName {
  111. return true, nil
  112. }
  113. }
  114. return false, nil
  115. }
  116. func parseResource(resource interface{}) (*Resource, error) {
  117. labels := map[string]string{}
  118. resourceMap, ok := resource.(map[string]interface{})
  119. if !ok {
  120. return nil, fmt.Errorf("Resource entry is of type %s, expected map[string]interface{}", reflect.TypeOf(resource))
  121. }
  122. resourceType, ok := resourceMap["type"]
  123. if !ok {
  124. return nil, fmt.Errorf("Resource entry doesn't have a type specified")
  125. }
  126. resourceTypeName, ok := resourceType.(string)
  127. if !ok {
  128. return nil, fmt.Errorf("Resource type is of type %s, expected string", reflect.TypeOf(resourceType))
  129. }
  130. resourceLabels, ok := resourceMap["labels"]
  131. if !ok {
  132. return nil, fmt.Errorf("Resource entry doesn't have any labels specified")
  133. }
  134. resourceLabelMap, ok := resourceLabels.(map[string]interface{})
  135. if !ok {
  136. return nil, fmt.Errorf("Resource labels entry is of type %s, expected map[string]interface{}", reflect.TypeOf(resourceLabels))
  137. }
  138. for label, val := range resourceLabelMap {
  139. labels[label], ok = val.(string)
  140. if !ok {
  141. return nil, fmt.Errorf("Resource label %q is of type %s, expected string", label, reflect.TypeOf(val))
  142. }
  143. }
  144. return &Resource{
  145. resourceType: resourceTypeName,
  146. resourceLabels: labels,
  147. }, nil
  148. }