暂无描述

fetch_test.go 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  1. // Copyright 2014 Google Inc. All Rights Reserved.
  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 driver
  15. import (
  16. "crypto/ecdsa"
  17. "crypto/elliptic"
  18. "crypto/rand"
  19. "crypto/tls"
  20. "crypto/x509"
  21. "encoding/pem"
  22. "fmt"
  23. "io/ioutil"
  24. "math/big"
  25. "net/http"
  26. "net/url"
  27. "os"
  28. "path/filepath"
  29. "reflect"
  30. "regexp"
  31. "runtime"
  32. "strings"
  33. "testing"
  34. "time"
  35. "github.com/google/pprof/internal/binutils"
  36. "github.com/google/pprof/internal/plugin"
  37. "github.com/google/pprof/internal/proftest"
  38. "github.com/google/pprof/internal/symbolizer"
  39. "github.com/google/pprof/profile"
  40. )
  41. func TestSymbolizationPath(t *testing.T) {
  42. if runtime.GOOS == "windows" {
  43. t.Skip("test assumes Unix paths")
  44. }
  45. // Save environment variables to restore after test
  46. saveHome := os.Getenv(homeEnv())
  47. savePath := os.Getenv("PPROF_BINARY_PATH")
  48. tempdir, err := ioutil.TempDir("", "home")
  49. if err != nil {
  50. t.Fatal("creating temp dir: ", err)
  51. }
  52. defer os.RemoveAll(tempdir)
  53. os.MkdirAll(filepath.Join(tempdir, "pprof", "binaries", "abcde10001"), 0700)
  54. os.Create(filepath.Join(tempdir, "pprof", "binaries", "abcde10001", "binary"))
  55. obj := testObj{tempdir}
  56. os.Setenv(homeEnv(), tempdir)
  57. for _, tc := range []struct {
  58. env, file, buildID, want string
  59. msgCount int
  60. }{
  61. {"", "/usr/bin/binary", "", "/usr/bin/binary", 0},
  62. {"", "/usr/bin/binary", "fedcb10000", "/usr/bin/binary", 0},
  63. {"/usr", "/bin/binary", "", "/usr/bin/binary", 0},
  64. {"", "/prod/path/binary", "abcde10001", filepath.Join(tempdir, "pprof/binaries/abcde10001/binary"), 0},
  65. {"/alternate/architecture", "/usr/bin/binary", "", "/alternate/architecture/binary", 0},
  66. {"/alternate/architecture", "/usr/bin/binary", "abcde10001", "/alternate/architecture/binary", 0},
  67. {"/nowhere:/alternate/architecture", "/usr/bin/binary", "fedcb10000", "/usr/bin/binary", 1},
  68. {"/nowhere:/alternate/architecture", "/usr/bin/binary", "abcde10002", "/usr/bin/binary", 1},
  69. } {
  70. os.Setenv("PPROF_BINARY_PATH", tc.env)
  71. p := &profile.Profile{
  72. Mapping: []*profile.Mapping{
  73. {
  74. File: tc.file,
  75. BuildID: tc.buildID,
  76. },
  77. },
  78. }
  79. s := &source{}
  80. locateBinaries(p, s, obj, &proftest.TestUI{T: t, Ignore: tc.msgCount})
  81. if file := p.Mapping[0].File; file != tc.want {
  82. t.Errorf("%s:%s:%s, want %s, got %s", tc.env, tc.file, tc.buildID, tc.want, file)
  83. }
  84. }
  85. os.Setenv(homeEnv(), saveHome)
  86. os.Setenv("PPROF_BINARY_PATH", savePath)
  87. }
  88. func TestCollectMappingSources(t *testing.T) {
  89. const startAddress uint64 = 0x40000
  90. const url = "http://example.com"
  91. for _, tc := range []struct {
  92. file, buildID string
  93. want plugin.MappingSources
  94. }{
  95. {"/usr/bin/binary", "buildId", mappingSources("buildId", url, startAddress)},
  96. {"/usr/bin/binary", "", mappingSources("/usr/bin/binary", url, startAddress)},
  97. {"", "", mappingSources(url, url, startAddress)},
  98. } {
  99. p := &profile.Profile{
  100. Mapping: []*profile.Mapping{
  101. {
  102. File: tc.file,
  103. BuildID: tc.buildID,
  104. Start: startAddress,
  105. },
  106. },
  107. }
  108. got := collectMappingSources(p, url)
  109. if !reflect.DeepEqual(got, tc.want) {
  110. t.Errorf("%s:%s, want %v, got %v", tc.file, tc.buildID, tc.want, got)
  111. }
  112. }
  113. }
  114. func TestUnsourceMappings(t *testing.T) {
  115. for _, tc := range []struct {
  116. file, buildID, want string
  117. }{
  118. {"/usr/bin/binary", "buildId", "/usr/bin/binary"},
  119. {"http://example.com", "", ""},
  120. } {
  121. p := &profile.Profile{
  122. Mapping: []*profile.Mapping{
  123. {
  124. File: tc.file,
  125. BuildID: tc.buildID,
  126. },
  127. },
  128. }
  129. unsourceMappings(p)
  130. if got := p.Mapping[0].File; got != tc.want {
  131. t.Errorf("%s:%s, want %s, got %s", tc.file, tc.buildID, tc.want, got)
  132. }
  133. }
  134. }
  135. type testObj struct {
  136. home string
  137. }
  138. func (o testObj) Open(file string, start, limit, offset uint64) (plugin.ObjFile, error) {
  139. switch file {
  140. case "/alternate/architecture/binary":
  141. return testFile{file, "abcde10001"}, nil
  142. case "/usr/bin/binary":
  143. return testFile{file, "fedcb10000"}, nil
  144. case filepath.Join(o.home, "pprof/binaries/abcde10001/binary"):
  145. return testFile{file, "abcde10001"}, nil
  146. }
  147. return nil, fmt.Errorf("not found: %s", file)
  148. }
  149. func (testObj) Demangler(_ string) func(names []string) (map[string]string, error) {
  150. return func(names []string) (map[string]string, error) { return nil, nil }
  151. }
  152. func (testObj) Disasm(file string, start, end uint64) ([]plugin.Inst, error) { return nil, nil }
  153. type testFile struct{ name, buildID string }
  154. func (f testFile) Name() string { return f.name }
  155. func (testFile) Base() uint64 { return 0 }
  156. func (f testFile) BuildID() string { return f.buildID }
  157. func (testFile) SourceLine(addr uint64) ([]plugin.Frame, error) { return nil, nil }
  158. func (testFile) Symbols(r *regexp.Regexp, addr uint64) ([]*plugin.Sym, error) { return nil, nil }
  159. func (testFile) Close() error { return nil }
  160. func TestFetch(t *testing.T) {
  161. const path = "testdata/"
  162. // Intercept http.Get calls from HTTPFetcher.
  163. savedHTTPGet := httpGet
  164. defer func() { httpGet = savedHTTPGet }()
  165. httpGet = stubHTTPGet
  166. type testcase struct {
  167. source, execName string
  168. }
  169. for _, tc := range []testcase{
  170. {path + "go.crc32.cpu", ""},
  171. {path + "go.nomappings.crash", "/bin/gotest.exe"},
  172. {"http://localhost/profile?file=cppbench.cpu", ""},
  173. } {
  174. p, _, _, err := grabProfile(&source{ExecName: tc.execName}, tc.source, nil, testObj{}, &proftest.TestUI{T: t})
  175. if err != nil {
  176. t.Fatalf("%s: %s", tc.source, err)
  177. }
  178. if len(p.Sample) == 0 {
  179. t.Errorf("%s: want non-zero samples", tc.source)
  180. }
  181. if e := tc.execName; e != "" {
  182. switch {
  183. case len(p.Mapping) == 0 || p.Mapping[0] == nil:
  184. t.Errorf("%s: want mapping[0].execName == %s, got no mappings", tc.source, e)
  185. case p.Mapping[0].File != e:
  186. t.Errorf("%s: want mapping[0].execName == %s, got %s", tc.source, e, p.Mapping[0].File)
  187. }
  188. }
  189. }
  190. }
  191. func TestFetchWithBase(t *testing.T) {
  192. baseVars := pprofVariables
  193. defer func() { pprofVariables = baseVars }()
  194. const path = "testdata/"
  195. type testcase struct {
  196. desc string
  197. sources []string
  198. bases []string
  199. normalize bool
  200. expectedSamples [][]int64
  201. }
  202. testcases := []testcase{
  203. {
  204. "not normalized base is same as source",
  205. []string{path + "cppbench.contention"},
  206. []string{path + "cppbench.contention"},
  207. false,
  208. [][]int64{},
  209. },
  210. {
  211. "not normalized single source, multiple base (all profiles same)",
  212. []string{path + "cppbench.contention"},
  213. []string{path + "cppbench.contention", path + "cppbench.contention"},
  214. false,
  215. [][]int64{{-2700, -608881724}, {-100, -23992}, {-200, -179943}, {-100, -17778444}, {-100, -75976}, {-300, -63568134}},
  216. },
  217. {
  218. "not normalized, different base and source",
  219. []string{path + "cppbench.contention"},
  220. []string{path + "cppbench.small.contention"},
  221. false,
  222. [][]int64{{1700, 608878600}, {100, 23992}, {200, 179943}, {100, 17778444}, {100, 75976}, {300, 63568134}},
  223. },
  224. {
  225. "normalized base is same as source",
  226. []string{path + "cppbench.contention"},
  227. []string{path + "cppbench.contention"},
  228. true,
  229. [][]int64{},
  230. },
  231. {
  232. "normalized single source, multiple base (all profiles same)",
  233. []string{path + "cppbench.contention"},
  234. []string{path + "cppbench.contention", path + "cppbench.contention"},
  235. true,
  236. [][]int64{},
  237. },
  238. {
  239. "normalized different base and source",
  240. []string{path + "cppbench.contention"},
  241. []string{path + "cppbench.small.contention"},
  242. true,
  243. [][]int64{{-229, -370}, {28, 0}, {57, 0}, {28, 80}, {28, 0}, {85, 287}},
  244. },
  245. }
  246. for _, tc := range testcases {
  247. t.Run(tc.desc, func(t *testing.T) {
  248. pprofVariables = baseVars.makeCopy()
  249. base := make([]*string, len(tc.bases))
  250. for i, s := range tc.bases {
  251. base[i] = &s
  252. }
  253. f := testFlags{
  254. stringLists: map[string][]*string{
  255. "base": base,
  256. },
  257. bools: map[string]bool{
  258. "normalize": tc.normalize,
  259. },
  260. }
  261. f.args = tc.sources
  262. o := setDefaults(&plugin.Options{
  263. UI: &proftest.TestUI{T: t, AllowRx: "Local symbolization failed|Some binary filenames not available"},
  264. Flagset: f,
  265. })
  266. src, _, err := parseFlags(o)
  267. if err != nil {
  268. t.Fatalf("%s: %v", tc.desc, err)
  269. }
  270. p, err := fetchProfiles(src, o)
  271. pprofVariables = baseVars
  272. if err != nil {
  273. t.Fatal(err)
  274. }
  275. if want, got := len(tc.expectedSamples), len(p.Sample); want != got {
  276. t.Fatalf("want %d samples got %d", want, got)
  277. }
  278. if len(p.Sample) > 0 {
  279. for i, sample := range p.Sample {
  280. if want, got := len(tc.expectedSamples[i]), len(sample.Value); want != got {
  281. t.Errorf("want %d values for sample %d, got %d", want, i, got)
  282. }
  283. for j, value := range sample.Value {
  284. if want, got := tc.expectedSamples[i][j], value; want != got {
  285. t.Errorf("want value of %d for value %d of sample %d, got %d", want, j, i, got)
  286. }
  287. }
  288. }
  289. }
  290. })
  291. }
  292. }
  293. // mappingSources creates MappingSources map with a single item.
  294. func mappingSources(key, source string, start uint64) plugin.MappingSources {
  295. return plugin.MappingSources{
  296. key: []struct {
  297. Source string
  298. Start uint64
  299. }{
  300. {Source: source, Start: start},
  301. },
  302. }
  303. }
  304. // stubHTTPGet intercepts a call to http.Get and rewrites it to use
  305. // "file://" to get the profile directly from a file.
  306. func stubHTTPGet(source string, _ time.Duration) (*http.Response, error) {
  307. url, err := url.Parse(source)
  308. if err != nil {
  309. return nil, err
  310. }
  311. values := url.Query()
  312. file := values.Get("file")
  313. if file == "" {
  314. return nil, fmt.Errorf("want .../file?profile, got %s", source)
  315. }
  316. t := &http.Transport{}
  317. t.RegisterProtocol("file", http.NewFileTransport(http.Dir("testdata/")))
  318. c := &http.Client{Transport: t}
  319. return c.Get("file:///" + file)
  320. }
  321. func closedError() string {
  322. if runtime.GOOS == "plan9" {
  323. return "listen hungup"
  324. }
  325. return "use of closed"
  326. }
  327. func TestHttpsInsecure(t *testing.T) {
  328. if runtime.GOOS == "nacl" {
  329. t.Skip("test assumes tcp available")
  330. }
  331. saveHome := os.Getenv(homeEnv())
  332. tempdir, err := ioutil.TempDir("", "home")
  333. if err != nil {
  334. t.Fatal("creating temp dir: ", err)
  335. }
  336. defer os.RemoveAll(tempdir)
  337. // pprof writes to $HOME/pprof by default which is not necessarily
  338. // writeable (e.g. on a Debian buildd) so set $HOME to something we
  339. // know we can write to for the duration of the test.
  340. os.Setenv(homeEnv(), tempdir)
  341. defer os.Setenv(homeEnv(), saveHome)
  342. baseVars := pprofVariables
  343. pprofVariables = baseVars.makeCopy()
  344. defer func() { pprofVariables = baseVars }()
  345. tlsConfig := &tls.Config{Certificates: []tls.Certificate{selfSignedCert(t)}}
  346. l, err := tls.Listen("tcp", "localhost:0", tlsConfig)
  347. if err != nil {
  348. t.Fatalf("net.Listen: got error %v, want no error", err)
  349. }
  350. donec := make(chan error, 1)
  351. go func(donec chan<- error) {
  352. donec <- http.Serve(l, nil)
  353. }(donec)
  354. defer func() {
  355. if got, want := <-donec, closedError(); !strings.Contains(got.Error(), want) {
  356. t.Fatalf("Serve got error %v, want %q", got, want)
  357. }
  358. }()
  359. defer l.Close()
  360. go func() {
  361. deadline := time.Now().Add(5 * time.Second)
  362. for time.Now().Before(deadline) {
  363. // Simulate a hotspot function. Spin in the inner loop for 100M iterations
  364. // to ensure we get most of the samples landed here rather than in the
  365. // library calls. We assume Go compiler won't elide the empty loop.
  366. for i := 0; i < 1e8; i++ {
  367. }
  368. runtime.Gosched()
  369. }
  370. }()
  371. outputTempFile, err := ioutil.TempFile("", "profile_output")
  372. if err != nil {
  373. t.Fatalf("Failed to create tempfile: %v", err)
  374. }
  375. defer os.Remove(outputTempFile.Name())
  376. defer outputTempFile.Close()
  377. address := "https+insecure://" + l.Addr().String() + "/debug/pprof/profile"
  378. s := &source{
  379. Sources: []string{address},
  380. Seconds: 10,
  381. Timeout: 10,
  382. Symbolize: "remote",
  383. }
  384. o := &plugin.Options{
  385. Obj: &binutils.Binutils{},
  386. UI: &proftest.TestUI{T: t, AllowRx: "Saved profile in"},
  387. }
  388. o.Sym = &symbolizer.Symbolizer{Obj: o.Obj, UI: o.UI}
  389. p, err := fetchProfiles(s, o)
  390. if err != nil {
  391. t.Fatal(err)
  392. }
  393. if len(p.SampleType) == 0 {
  394. t.Fatalf("fetchProfiles(%s) got empty profile: len(p.SampleType)==0", address)
  395. }
  396. switch runtime.GOOS {
  397. case "plan9":
  398. // CPU profiling is not supported on Plan9; see golang.org/issues/22564.
  399. return
  400. case "darwin":
  401. if runtime.GOARCH == "arm" || runtime.GOARCH == "arm64" {
  402. // CPU profiling on iOS os not symbolized; see golang.org/issues/22612.
  403. return
  404. }
  405. }
  406. if len(p.Function) == 0 {
  407. t.Fatalf("fetchProfiles(%s) got non-symbolized profile: len(p.Function)==0", address)
  408. }
  409. if err := checkProfileHasFunction(p, "TestHttpsInsecure"); !badSigprofOS[runtime.GOOS] && err != nil {
  410. t.Fatalf("fetchProfiles(%s) %v", address, err)
  411. }
  412. }
  413. // Some operating systems don't trigger the profiling signal right.
  414. // See https://github.com/golang/go/issues/13841.
  415. var badSigprofOS = map[string]bool{
  416. "darwin": true,
  417. "netbsd": true,
  418. }
  419. func checkProfileHasFunction(p *profile.Profile, fname string) error {
  420. for _, f := range p.Function {
  421. if strings.Contains(f.Name, fname) {
  422. return nil
  423. }
  424. }
  425. return fmt.Errorf("got %s, want function %q", p.String(), fname)
  426. }
  427. func selfSignedCert(t *testing.T) tls.Certificate {
  428. privKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  429. if err != nil {
  430. t.Fatalf("failed to generate private key: %v", err)
  431. }
  432. b, err := x509.MarshalECPrivateKey(privKey)
  433. if err != nil {
  434. t.Fatalf("failed to marshal private key: %v", err)
  435. }
  436. bk := pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: b})
  437. tmpl := x509.Certificate{
  438. SerialNumber: big.NewInt(1),
  439. NotBefore: time.Now(),
  440. NotAfter: time.Now().Add(10 * time.Minute),
  441. }
  442. b, err = x509.CreateCertificate(rand.Reader, &tmpl, &tmpl, privKey.Public(), privKey)
  443. if err != nil {
  444. t.Fatalf("failed to create cert: %v", err)
  445. }
  446. bc := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: b})
  447. cert, err := tls.X509KeyPair(bc, bk)
  448. if err != nil {
  449. t.Fatalf("failed to create TLS key pair: %v", err)
  450. }
  451. return cert
  452. }