integration_test.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. // Copyright 2017 Google LLC
  2. //
  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. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package profiler
  15. import (
  16. "bytes"
  17. "context"
  18. "fmt"
  19. "os"
  20. "os/exec"
  21. "runtime"
  22. "strings"
  23. "testing"
  24. "text/template"
  25. "time"
  26. "cloud.google.com/go/profiler/proftest"
  27. "golang.org/x/oauth2/google"
  28. compute "google.golang.org/api/compute/v1"
  29. )
  30. const (
  31. cloudScope = "https://www.googleapis.com/auth/cloud-platform"
  32. benchFinishString = "busybench finished profiling"
  33. errorString = "failed to set up or run the benchmark"
  34. )
  35. const startupTemplate = `
  36. #! /bin/bash
  37. # Signal any unexpected error.
  38. trap 'echo "{{.ErrorString}}"' ERR
  39. (
  40. # Shut down the VM in 5 minutes after this script exits
  41. # to stop accounting the VM for billing and cores quota.
  42. trap "sleep 300 && poweroff" EXIT
  43. retry() {
  44. for i in {1..3}; do
  45. "${@}" && return 0
  46. done
  47. return 1
  48. }
  49. # Fail on any error.
  50. set -eo pipefail
  51. # Display commands being run.
  52. set -x
  53. # Install git
  54. retry apt-get update >/dev/null
  55. retry apt-get -y -q install git >/dev/null
  56. # Install desired Go version
  57. mkdir -p /tmp/bin
  58. retry curl -sL -o /tmp/bin/gimme https://raw.githubusercontent.com/travis-ci/gimme/master/gimme
  59. chmod +x /tmp/bin/gimme
  60. export PATH=$PATH:/tmp/bin
  61. retry eval "$(gimme {{.GoVersion}})"
  62. # Set $GOPATH
  63. export GOPATH="$HOME/go"
  64. export GOCLOUD_HOME=$GOPATH/src/cloud.google.com/go
  65. mkdir -p $GOCLOUD_HOME
  66. # Install agent
  67. retry git clone https://code.googlesource.com/gocloud $GOCLOUD_HOME >/dev/null
  68. cd $GOCLOUD_HOME
  69. retry git fetch origin {{.Commit}}
  70. git reset --hard {{.Commit}}
  71. cd $GOCLOUD_HOME/profiler/busybench
  72. retry go get >/dev/null
  73. # Run benchmark with agent
  74. go run busybench.go --service="{{.Service}}" --mutex_profiling="{{.MutexProfiling}}"
  75. # Write output to serial port 2 with timestamp.
  76. ) 2>&1 | while read line; do echo "$(date): ${line}"; done >/dev/ttyS1
  77. `
  78. type goGCETestCase struct {
  79. proftest.InstanceConfig
  80. name string
  81. goVersion string
  82. mutexProfiling bool
  83. wantProfileTypes []string
  84. }
  85. func (tc *goGCETestCase) initializeStartupScript(template *template.Template, commit string) error {
  86. var buf bytes.Buffer
  87. err := template.Execute(&buf,
  88. struct {
  89. Service string
  90. GoVersion string
  91. Commit string
  92. ErrorString string
  93. MutexProfiling bool
  94. }{
  95. Service: tc.name,
  96. GoVersion: tc.goVersion,
  97. Commit: commit,
  98. ErrorString: errorString,
  99. MutexProfiling: tc.mutexProfiling,
  100. })
  101. if err != nil {
  102. return fmt.Errorf("failed to render startup script for %s: %v", tc.name, err)
  103. }
  104. tc.StartupScript = buf.String()
  105. return nil
  106. }
  107. func TestAgentIntegration(t *testing.T) {
  108. if testing.Short() {
  109. t.Skip("skipping profiler integration test in short mode")
  110. }
  111. projectID := os.Getenv("GCLOUD_TESTS_GOLANG_PROJECT_ID")
  112. if projectID == "" {
  113. t.Skip("skipping profiler integration test when GCLOUD_TESTS_GOLANG_PROJECT_ID variable is not set")
  114. }
  115. zone := os.Getenv("GCLOUD_TESTS_GOLANG_PROFILER_ZONE")
  116. if zone == "" {
  117. t.Fatalf("GCLOUD_TESTS_GOLANG_PROFILER_ZONE environment variable must be set when integration test is requested")
  118. }
  119. // Figure out the Git commit of the current directory. The source checkout in
  120. // the test VM will run in the same commit. Note that any local changes to
  121. // the profiler agent won't be tested in the integration test. This flow only
  122. // works with code that has been committed and pushed to the public repo
  123. // (either to master or to a branch).
  124. output, err := exec.Command("git", "rev-parse", "HEAD").CombinedOutput()
  125. if err != nil {
  126. t.Fatalf("failed to gather the Git revision of the current source: %v", err)
  127. }
  128. commit := strings.Trim(string(output), "\n")
  129. t.Logf("using Git commit %q for the profiler integration test", commit)
  130. pst, err := time.LoadLocation("America/Los_Angeles")
  131. if err != nil {
  132. t.Fatalf("failed to initiate PST location: %v", err)
  133. }
  134. runID := strings.Replace(time.Now().In(pst).Format("2006-01-02-15-04-05.000000-0700"), ".", "-", -1)
  135. ctx := context.Background()
  136. client, err := google.DefaultClient(ctx, cloudScope)
  137. if err != nil {
  138. t.Fatalf("failed to get default client: %v", err)
  139. }
  140. computeService, err := compute.New(client)
  141. if err != nil {
  142. t.Fatalf("failed to initialize compute service: %v", err)
  143. }
  144. template, err := template.New("startupScript").Parse(startupTemplate)
  145. if err != nil {
  146. t.Fatalf("failed to parse startup script template: %v", err)
  147. }
  148. tr := proftest.TestRunner{
  149. Client: client,
  150. }
  151. gceTr := proftest.GCETestRunner{
  152. TestRunner: tr,
  153. ComputeService: computeService,
  154. }
  155. testcases := []goGCETestCase{
  156. {
  157. InstanceConfig: proftest.InstanceConfig{
  158. ProjectID: projectID,
  159. Zone: zone,
  160. Name: fmt.Sprintf("profiler-test-go111-%s", runID),
  161. MachineType: "n1-standard-1",
  162. },
  163. name: fmt.Sprintf("profiler-test-go111-%s-gce", runID),
  164. wantProfileTypes: []string{"CPU", "HEAP", "THREADS", "CONTENTION", "HEAP_ALLOC"},
  165. goVersion: "1.11",
  166. mutexProfiling: true,
  167. },
  168. {
  169. InstanceConfig: proftest.InstanceConfig{
  170. ProjectID: projectID,
  171. Zone: zone,
  172. Name: fmt.Sprintf("profiler-test-go110-%s", runID),
  173. MachineType: "n1-standard-1",
  174. },
  175. name: fmt.Sprintf("profiler-test-go110-%s-gce", runID),
  176. wantProfileTypes: []string{"CPU", "HEAP", "THREADS", "CONTENTION", "HEAP_ALLOC"},
  177. goVersion: "1.10",
  178. mutexProfiling: true,
  179. },
  180. {
  181. InstanceConfig: proftest.InstanceConfig{
  182. ProjectID: projectID,
  183. Zone: zone,
  184. Name: fmt.Sprintf("profiler-test-go19-%s", runID),
  185. MachineType: "n1-standard-1",
  186. },
  187. name: fmt.Sprintf("profiler-test-go19-%s-gce", runID),
  188. wantProfileTypes: []string{"CPU", "HEAP", "THREADS", "CONTENTION", "HEAP_ALLOC"},
  189. goVersion: "1.9",
  190. mutexProfiling: true,
  191. },
  192. }
  193. // The number of tests run in parallel is the current value of GOMAXPROCS.
  194. runtime.GOMAXPROCS(len(testcases))
  195. for _, tc := range testcases {
  196. tc := tc // capture range variable
  197. t.Run(tc.name, func(t *testing.T) {
  198. t.Parallel()
  199. if err := tc.initializeStartupScript(template, commit); err != nil {
  200. t.Fatalf("failed to initialize startup script")
  201. }
  202. if err := gceTr.StartInstance(ctx, &tc.InstanceConfig); err != nil {
  203. t.Fatal(err)
  204. }
  205. defer func() {
  206. if gceTr.DeleteInstance(ctx, &tc.InstanceConfig); err != nil {
  207. t.Fatal(err)
  208. }
  209. }()
  210. timeoutCtx, cancel := context.WithTimeout(ctx, time.Minute*25)
  211. defer cancel()
  212. if err := gceTr.PollForSerialOutput(timeoutCtx, &tc.InstanceConfig, benchFinishString, errorString); err != nil {
  213. t.Fatalf("PollForSerialOutput() got error: %v", err)
  214. }
  215. timeNow := time.Now()
  216. endTime := timeNow.Format(time.RFC3339)
  217. startTime := timeNow.Add(-1 * time.Hour).Format(time.RFC3339)
  218. for _, pType := range tc.wantProfileTypes {
  219. pr, err := tr.QueryProfiles(tc.ProjectID, tc.name, startTime, endTime, pType)
  220. if err != nil {
  221. t.Errorf("QueryProfiles(%s, %s, %s, %s, %s) got error: %v", tc.ProjectID, tc.name, startTime, endTime, pType, err)
  222. continue
  223. }
  224. if err := pr.HasFunction("busywork"); err != nil {
  225. t.Error(err)
  226. }
  227. }
  228. })
  229. }
  230. }