Brak opisu

fetch_test.go 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645
  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. type WantSample struct {
  195. values []int64
  196. labels map[string][]string
  197. }
  198. const path = "testdata/"
  199. type testcase struct {
  200. desc string
  201. sources []string
  202. bases []string
  203. diffBases []string
  204. normalize bool
  205. wantSamples []WantSample
  206. wantErrorMsg string
  207. }
  208. testcases := []testcase{
  209. {
  210. "not normalized base is same as source",
  211. []string{path + "cppbench.contention"},
  212. []string{path + "cppbench.contention"},
  213. nil,
  214. false,
  215. nil,
  216. "",
  217. },
  218. {
  219. "not normalized base is same as source",
  220. []string{path + "cppbench.contention"},
  221. []string{path + "cppbench.contention"},
  222. nil,
  223. false,
  224. nil,
  225. "",
  226. },
  227. {
  228. "not normalized single source, multiple base (all profiles same)",
  229. []string{path + "cppbench.contention"},
  230. []string{path + "cppbench.contention", path + "cppbench.contention"},
  231. nil,
  232. false,
  233. []WantSample{
  234. {
  235. values: []int64{-2700, -608881724},
  236. labels: map[string][]string{},
  237. },
  238. {
  239. values: []int64{-100, -23992},
  240. labels: map[string][]string{},
  241. },
  242. {
  243. values: []int64{-200, -179943},
  244. labels: map[string][]string{},
  245. },
  246. {
  247. values: []int64{-100, -17778444},
  248. labels: map[string][]string{},
  249. },
  250. {
  251. values: []int64{-100, -75976},
  252. labels: map[string][]string{},
  253. },
  254. {
  255. values: []int64{-300, -63568134},
  256. labels: map[string][]string{},
  257. },
  258. },
  259. "",
  260. },
  261. {
  262. "not normalized, different base and source",
  263. []string{path + "cppbench.contention"},
  264. []string{path + "cppbench.small.contention"},
  265. nil,
  266. false,
  267. []WantSample{
  268. {
  269. values: []int64{1700, 608878600},
  270. labels: map[string][]string{},
  271. },
  272. {
  273. values: []int64{100, 23992},
  274. labels: map[string][]string{},
  275. },
  276. {
  277. values: []int64{200, 179943},
  278. labels: map[string][]string{},
  279. },
  280. {
  281. values: []int64{100, 17778444},
  282. labels: map[string][]string{},
  283. },
  284. {
  285. values: []int64{100, 75976},
  286. labels: map[string][]string{},
  287. },
  288. {
  289. values: []int64{300, 63568134},
  290. labels: map[string][]string{},
  291. },
  292. },
  293. "",
  294. },
  295. {
  296. "normalized base is same as source",
  297. []string{path + "cppbench.contention"},
  298. []string{path + "cppbench.contention"},
  299. nil,
  300. true,
  301. nil,
  302. "",
  303. },
  304. {
  305. "normalized single source, multiple base (all profiles same)",
  306. []string{path + "cppbench.contention"},
  307. []string{path + "cppbench.contention", path + "cppbench.contention"},
  308. nil,
  309. true,
  310. nil,
  311. "",
  312. },
  313. {
  314. "normalized different base and source",
  315. []string{path + "cppbench.contention"},
  316. []string{path + "cppbench.small.contention"},
  317. nil,
  318. true,
  319. []WantSample{
  320. {
  321. values: []int64{-229, -370},
  322. labels: map[string][]string{},
  323. },
  324. {
  325. values: []int64{28, 0},
  326. labels: map[string][]string{},
  327. },
  328. {
  329. values: []int64{57, 0},
  330. labels: map[string][]string{},
  331. },
  332. {
  333. values: []int64{28, 80},
  334. labels: map[string][]string{},
  335. },
  336. {
  337. values: []int64{28, 0},
  338. labels: map[string][]string{},
  339. },
  340. {
  341. values: []int64{85, 287},
  342. labels: map[string][]string{},
  343. },
  344. },
  345. "",
  346. },
  347. {
  348. "not normalized diff base is same as source",
  349. []string{path + "cppbench.contention"},
  350. nil,
  351. []string{path + "cppbench.contention"},
  352. false,
  353. []WantSample{
  354. {
  355. values: []int64{2700, 608881724},
  356. labels: map[string][]string{},
  357. },
  358. {
  359. values: []int64{100, 23992},
  360. labels: map[string][]string{},
  361. },
  362. {
  363. values: []int64{200, 179943},
  364. labels: map[string][]string{},
  365. },
  366. {
  367. values: []int64{100, 17778444},
  368. labels: map[string][]string{},
  369. },
  370. {
  371. values: []int64{100, 75976},
  372. labels: map[string][]string{},
  373. },
  374. {
  375. values: []int64{300, 63568134},
  376. labels: map[string][]string{},
  377. },
  378. {
  379. values: []int64{-2700, -608881724},
  380. labels: map[string][]string{"pprof::base": {"true"}},
  381. },
  382. {
  383. values: []int64{-100, -23992},
  384. labels: map[string][]string{"pprof::base": {"true"}},
  385. },
  386. {
  387. values: []int64{-200, -179943},
  388. labels: map[string][]string{"pprof::base": {"true"}},
  389. },
  390. {
  391. values: []int64{-100, -17778444},
  392. labels: map[string][]string{"pprof::base": {"true"}},
  393. },
  394. {
  395. values: []int64{-100, -75976},
  396. labels: map[string][]string{"pprof::base": {"true"}},
  397. },
  398. {
  399. values: []int64{-300, -63568134},
  400. labels: map[string][]string{"pprof::base": {"true"}},
  401. },
  402. },
  403. "",
  404. },
  405. {
  406. "diff_base and base both specified",
  407. []string{path + "cppbench.contention"},
  408. []string{path + "cppbench.contention"},
  409. []string{path + "cppbench.contention"},
  410. false,
  411. nil,
  412. "-base and -diff_base flags cannot both be specified",
  413. },
  414. }
  415. for _, tc := range testcases {
  416. t.Run(tc.desc, func(t *testing.T) {
  417. pprofVariables = baseVars.makeCopy()
  418. f := testFlags{
  419. stringLists: map[string][]string{
  420. "base": tc.bases,
  421. "diff_base": tc.diffBases,
  422. },
  423. bools: map[string]bool{
  424. "normalize": tc.normalize,
  425. },
  426. }
  427. f.args = tc.sources
  428. o := setDefaults(&plugin.Options{
  429. UI: &proftest.TestUI{T: t, AllowRx: "Local symbolization failed|Some binary filenames not available"},
  430. Flagset: f,
  431. })
  432. src, _, err := parseFlags(o)
  433. if tc.wantErrorMsg != "" {
  434. if err == nil {
  435. t.Fatalf("got nil, want error %q", tc.wantErrorMsg)
  436. }
  437. if gotErrMsg := err.Error(); gotErrMsg != tc.wantErrorMsg {
  438. t.Fatalf("got error %q, want error %q", gotErrMsg, tc.wantErrorMsg)
  439. }
  440. return
  441. }
  442. if err != nil {
  443. t.Fatalf("got error %q, want no error", err)
  444. }
  445. p, err := fetchProfiles(src, o)
  446. if err != nil {
  447. t.Fatalf("got error %q, want no error", err)
  448. }
  449. if got, want := len(p.Sample), len(tc.wantSamples); got != want {
  450. t.Fatalf("got %d samples want %d", got, want)
  451. }
  452. for i, sample := range p.Sample {
  453. if !reflect.DeepEqual(tc.wantSamples[i].values, sample.Value) {
  454. t.Errorf("for sample %d got values %v, want %v", i, sample.Value, tc.wantSamples[i])
  455. }
  456. if !reflect.DeepEqual(tc.wantSamples[i].labels, sample.Label) {
  457. t.Errorf("for sample %d got labels %v, want %v", i, sample.Label, tc.wantSamples[i].labels)
  458. }
  459. }
  460. })
  461. }
  462. }
  463. // mappingSources creates MappingSources map with a single item.
  464. func mappingSources(key, source string, start uint64) plugin.MappingSources {
  465. return plugin.MappingSources{
  466. key: []struct {
  467. Source string
  468. Start uint64
  469. }{
  470. {Source: source, Start: start},
  471. },
  472. }
  473. }
  474. // stubHTTPGet intercepts a call to http.Get and rewrites it to use
  475. // "file://" to get the profile directly from a file.
  476. func stubHTTPGet(source string, _ time.Duration) (*http.Response, error) {
  477. url, err := url.Parse(source)
  478. if err != nil {
  479. return nil, err
  480. }
  481. values := url.Query()
  482. file := values.Get("file")
  483. if file == "" {
  484. return nil, fmt.Errorf("want .../file?profile, got %s", source)
  485. }
  486. t := &http.Transport{}
  487. t.RegisterProtocol("file", http.NewFileTransport(http.Dir("testdata/")))
  488. c := &http.Client{Transport: t}
  489. return c.Get("file:///" + file)
  490. }
  491. func closedError() string {
  492. if runtime.GOOS == "plan9" {
  493. return "listen hungup"
  494. }
  495. return "use of closed"
  496. }
  497. func TestHttpsInsecure(t *testing.T) {
  498. if runtime.GOOS == "nacl" || runtime.GOOS == "js" {
  499. t.Skip("test assumes tcp available")
  500. }
  501. saveHome := os.Getenv(homeEnv())
  502. tempdir, err := ioutil.TempDir("", "home")
  503. if err != nil {
  504. t.Fatal("creating temp dir: ", err)
  505. }
  506. defer os.RemoveAll(tempdir)
  507. // pprof writes to $HOME/pprof by default which is not necessarily
  508. // writeable (e.g. on a Debian buildd) so set $HOME to something we
  509. // know we can write to for the duration of the test.
  510. os.Setenv(homeEnv(), tempdir)
  511. defer os.Setenv(homeEnv(), saveHome)
  512. baseVars := pprofVariables
  513. pprofVariables = baseVars.makeCopy()
  514. defer func() { pprofVariables = baseVars }()
  515. tlsConfig := &tls.Config{Certificates: []tls.Certificate{selfSignedCert(t)}}
  516. l, err := tls.Listen("tcp", "localhost:0", tlsConfig)
  517. if err != nil {
  518. t.Fatalf("net.Listen: got error %v, want no error", err)
  519. }
  520. donec := make(chan error, 1)
  521. go func(donec chan<- error) {
  522. donec <- http.Serve(l, nil)
  523. }(donec)
  524. defer func() {
  525. if got, want := <-donec, closedError(); !strings.Contains(got.Error(), want) {
  526. t.Fatalf("Serve got error %v, want %q", got, want)
  527. }
  528. }()
  529. defer l.Close()
  530. outputTempFile, err := ioutil.TempFile("", "profile_output")
  531. if err != nil {
  532. t.Fatalf("Failed to create tempfile: %v", err)
  533. }
  534. defer os.Remove(outputTempFile.Name())
  535. defer outputTempFile.Close()
  536. address := "https+insecure://" + l.Addr().String() + "/debug/pprof/goroutine"
  537. s := &source{
  538. Sources: []string{address},
  539. Seconds: 10,
  540. Timeout: 10,
  541. Symbolize: "remote",
  542. }
  543. o := &plugin.Options{
  544. Obj: &binutils.Binutils{},
  545. UI: &proftest.TestUI{T: t, AllowRx: "Saved profile in"},
  546. }
  547. o.Sym = &symbolizer.Symbolizer{Obj: o.Obj, UI: o.UI}
  548. p, err := fetchProfiles(s, o)
  549. if err != nil {
  550. t.Fatal(err)
  551. }
  552. if len(p.SampleType) == 0 {
  553. t.Fatalf("fetchProfiles(%s) got empty profile: len(p.SampleType)==0", address)
  554. }
  555. if len(p.Function) == 0 {
  556. t.Fatalf("fetchProfiles(%s) got non-symbolized profile: len(p.Function)==0", address)
  557. }
  558. if err := checkProfileHasFunction(p, "TestHttpsInsecure"); err != nil {
  559. t.Fatalf("fetchProfiles(%s) %v", address, err)
  560. }
  561. }
  562. func checkProfileHasFunction(p *profile.Profile, fname string) error {
  563. for _, f := range p.Function {
  564. if strings.Contains(f.Name, fname) {
  565. return nil
  566. }
  567. }
  568. return fmt.Errorf("got %s, want function %q", p.String(), fname)
  569. }
  570. func selfSignedCert(t *testing.T) tls.Certificate {
  571. privKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  572. if err != nil {
  573. t.Fatalf("failed to generate private key: %v", err)
  574. }
  575. b, err := x509.MarshalECPrivateKey(privKey)
  576. if err != nil {
  577. t.Fatalf("failed to marshal private key: %v", err)
  578. }
  579. bk := pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: b})
  580. tmpl := x509.Certificate{
  581. SerialNumber: big.NewInt(1),
  582. NotBefore: time.Now(),
  583. NotAfter: time.Now().Add(10 * time.Minute),
  584. }
  585. b, err = x509.CreateCertificate(rand.Reader, &tmpl, &tmpl, privKey.Public(), privKey)
  586. if err != nil {
  587. t.Fatalf("failed to create cert: %v", err)
  588. }
  589. bc := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: b})
  590. cert, err := tls.X509KeyPair(bc, bk)
  591. if err != nil {
  592. t.Fatalf("failed to create TLS key pair: %v", err)
  593. }
  594. return cert
  595. }