You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

295 lines
8.5 KiB

  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. # $GOCACHE is required from Go 1.12. See https://golang.org/doc/go1.11#gocache
  57. # $GOCACHE is explicitly set becasue $HOME is not set when this code runs
  58. mkdir -p /tmp/gocache
  59. export GOCACHE=/tmp/gocache
  60. # Install gcc, needed to install go master
  61. if [ "{{.GoVersion}}" = "master" ]
  62. then
  63. retry apt-get -y -q install gcc >/dev/null
  64. fi
  65. # Install desired Go version
  66. mkdir -p /tmp/bin
  67. retry curl -sL -o /tmp/bin/gimme https://raw.githubusercontent.com/travis-ci/gimme/master/gimme
  68. chmod +x /tmp/bin/gimme
  69. export PATH=$PATH:/tmp/bin
  70. retry eval "$(gimme {{.GoVersion}})"
  71. # Set $GOPATH
  72. export GOPATH="$HOME/go"
  73. export GOCLOUD_HOME=$GOPATH/src/cloud.google.com/go
  74. mkdir -p $GOCLOUD_HOME
  75. # Install agent
  76. retry git clone https://code.googlesource.com/gocloud $GOCLOUD_HOME >/dev/null
  77. cd $GOCLOUD_HOME
  78. retry git fetch origin {{.Commit}}
  79. git reset --hard {{.Commit}}
  80. cd $GOCLOUD_HOME/profiler/busybench
  81. retry go get >/dev/null
  82. # Run benchmark with agent
  83. go run busybench.go --service="{{.Service}}" --mutex_profiling="{{.MutexProfiling}}"
  84. # Write output to serial port 2 with timestamp.
  85. ) 2>&1 | while read line; do echo "$(date): ${line}"; done >/dev/ttyS1
  86. `
  87. type goGCETestCase struct {
  88. proftest.InstanceConfig
  89. name string
  90. goVersion string
  91. mutexProfiling bool
  92. wantProfileTypes []string
  93. }
  94. func (tc *goGCETestCase) initializeStartupScript(template *template.Template, commit string) error {
  95. var buf bytes.Buffer
  96. err := template.Execute(&buf,
  97. struct {
  98. Service string
  99. GoVersion string
  100. Commit string
  101. ErrorString string
  102. MutexProfiling bool
  103. }{
  104. Service: tc.name,
  105. GoVersion: tc.goVersion,
  106. Commit: commit,
  107. ErrorString: errorString,
  108. MutexProfiling: tc.mutexProfiling,
  109. })
  110. if err != nil {
  111. return fmt.Errorf("failed to render startup script for %s: %v", tc.name, err)
  112. }
  113. tc.StartupScript = buf.String()
  114. return nil
  115. }
  116. func TestAgentIntegration(t *testing.T) {
  117. t.Skip("https://github.com/googleapis/google-cloud-go/issues/1366")
  118. // Testing against master requires building go code and may take up to 10 minutes.
  119. // Allow this test to run in parallel with other top level tests to avoid timeouts.
  120. t.Parallel()
  121. if testing.Short() {
  122. t.Skip("skipping profiler integration test in short mode")
  123. }
  124. projectID := os.Getenv("GCLOUD_TESTS_GOLANG_PROJECT_ID")
  125. if projectID == "" {
  126. t.Skip("skipping profiler integration test when GCLOUD_TESTS_GOLANG_PROJECT_ID variable is not set")
  127. }
  128. zone := os.Getenv("GCLOUD_TESTS_GOLANG_PROFILER_ZONE")
  129. if zone == "" {
  130. t.Fatalf("GCLOUD_TESTS_GOLANG_PROFILER_ZONE environment variable must be set when integration test is requested")
  131. }
  132. // Figure out the Git commit of the current directory. The source checkout in
  133. // the test VM will run in the same commit. Note that any local changes to
  134. // the profiler agent won't be tested in the integration test. This flow only
  135. // works with code that has been committed and pushed to the public repo
  136. // (either to master or to a branch).
  137. output, err := exec.Command("git", "rev-parse", "HEAD").CombinedOutput()
  138. if err != nil {
  139. t.Fatalf("failed to gather the Git revision of the current source: %v", err)
  140. }
  141. commit := strings.Trim(string(output), "\n")
  142. t.Logf("using Git commit %q for the profiler integration test", commit)
  143. pst, err := time.LoadLocation("America/Los_Angeles")
  144. if err != nil {
  145. t.Fatalf("failed to initiate PST location: %v", err)
  146. }
  147. runID := strings.Replace(time.Now().In(pst).Format("2006-01-02-15-04-05.000000-0700"), ".", "-", -1)
  148. ctx := context.Background()
  149. client, err := google.DefaultClient(ctx, cloudScope)
  150. if err != nil {
  151. t.Fatalf("failed to get default client: %v", err)
  152. }
  153. computeService, err := compute.New(client)
  154. if err != nil {
  155. t.Fatalf("failed to initialize compute service: %v", err)
  156. }
  157. template, err := template.New("startupScript").Parse(startupTemplate)
  158. if err != nil {
  159. t.Fatalf("failed to parse startup script template: %v", err)
  160. }
  161. tr := proftest.TestRunner{
  162. Client: client,
  163. }
  164. gceTr := proftest.GCETestRunner{
  165. TestRunner: tr,
  166. ComputeService: computeService,
  167. }
  168. testcases := []goGCETestCase{
  169. {
  170. InstanceConfig: proftest.InstanceConfig{
  171. ProjectID: projectID,
  172. Zone: zone,
  173. Name: fmt.Sprintf("profiler-test-gomaster-%s", runID),
  174. MachineType: "n1-standard-1",
  175. },
  176. name: fmt.Sprintf("profiler-test-gomaster-%s-gce", runID),
  177. wantProfileTypes: []string{"CPU", "HEAP", "THREADS", "CONTENTION", "HEAP_ALLOC"},
  178. goVersion: "master",
  179. mutexProfiling: true,
  180. },
  181. {
  182. InstanceConfig: proftest.InstanceConfig{
  183. ProjectID: projectID,
  184. Zone: zone,
  185. Name: fmt.Sprintf("profiler-test-go111-%s", runID),
  186. MachineType: "n1-standard-1",
  187. },
  188. name: fmt.Sprintf("profiler-test-go111-%s-gce", runID),
  189. wantProfileTypes: []string{"CPU", "HEAP", "THREADS", "CONTENTION", "HEAP_ALLOC"},
  190. goVersion: "1.11",
  191. mutexProfiling: true,
  192. },
  193. {
  194. InstanceConfig: proftest.InstanceConfig{
  195. ProjectID: projectID,
  196. Zone: zone,
  197. Name: fmt.Sprintf("profiler-test-go110-%s", runID),
  198. MachineType: "n1-standard-1",
  199. },
  200. name: fmt.Sprintf("profiler-test-go110-%s-gce", runID),
  201. wantProfileTypes: []string{"CPU", "HEAP", "THREADS", "CONTENTION", "HEAP_ALLOC"},
  202. goVersion: "1.10",
  203. mutexProfiling: true,
  204. },
  205. {
  206. InstanceConfig: proftest.InstanceConfig{
  207. ProjectID: projectID,
  208. Zone: zone,
  209. Name: fmt.Sprintf("profiler-test-go19-%s", runID),
  210. MachineType: "n1-standard-1",
  211. },
  212. name: fmt.Sprintf("profiler-test-go19-%s-gce", runID),
  213. wantProfileTypes: []string{"CPU", "HEAP", "THREADS", "CONTENTION", "HEAP_ALLOC"},
  214. goVersion: "1.9",
  215. mutexProfiling: true,
  216. },
  217. }
  218. // The number of tests run in parallel is the current value of GOMAXPROCS.
  219. runtime.GOMAXPROCS(len(testcases))
  220. for _, tc := range testcases {
  221. tc := tc // capture range variable
  222. t.Run(tc.name, func(t *testing.T) {
  223. t.Parallel()
  224. if err := tc.initializeStartupScript(template, commit); err != nil {
  225. t.Fatalf("failed to initialize startup script")
  226. }
  227. if err := gceTr.StartInstance(ctx, &tc.InstanceConfig); err != nil {
  228. t.Fatal(err)
  229. }
  230. defer func() {
  231. if gceTr.DeleteInstance(ctx, &tc.InstanceConfig); err != nil {
  232. t.Fatal(err)
  233. }
  234. }()
  235. timeoutCtx, cancel := context.WithTimeout(ctx, time.Minute*25)
  236. defer cancel()
  237. if err := gceTr.PollForSerialOutput(timeoutCtx, &tc.InstanceConfig, benchFinishString, errorString); err != nil {
  238. t.Fatalf("PollForSerialOutput() got error: %v", err)
  239. }
  240. timeNow := time.Now()
  241. endTime := timeNow.Format(time.RFC3339)
  242. startTime := timeNow.Add(-1 * time.Hour).Format(time.RFC3339)
  243. for _, pType := range tc.wantProfileTypes {
  244. pr, err := tr.QueryProfiles(tc.ProjectID, tc.name, startTime, endTime, pType)
  245. if err != nil {
  246. t.Errorf("QueryProfiles(%s, %s, %s, %s, %s) got error: %v", tc.ProjectID, tc.name, startTime, endTime, pType, err)
  247. continue
  248. }
  249. if err := pr.HasFunction("busywork"); err != nil {
  250. t.Error(err)
  251. }
  252. }
  253. })
  254. }
  255. }