暂无描述

fetch_test.go 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  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(nil)
  263. o.Flagset = f
  264. src, _, err := parseFlags(o)
  265. if err != nil {
  266. t.Fatalf("%s: %v", tc.desc, err)
  267. }
  268. p, err := fetchProfiles(src, o)
  269. pprofVariables = baseVars
  270. if err != nil {
  271. t.Fatal(err)
  272. }
  273. if want, got := len(tc.expectedSamples), len(p.Sample); want != got {
  274. t.Fatalf("want %d samples got %d", want, got)
  275. }
  276. if len(p.Sample) > 0 {
  277. for i, sample := range p.Sample {
  278. if want, got := len(tc.expectedSamples[i]), len(sample.Value); want != got {
  279. t.Errorf("want %d values for sample %d, got %d", want, i, got)
  280. }
  281. for j, value := range sample.Value {
  282. if want, got := tc.expectedSamples[i][j], value; want != got {
  283. t.Errorf("want value of %d for value %d of sample %d, got %d", want, j, i, got)
  284. }
  285. }
  286. }
  287. }
  288. })
  289. }
  290. }
  291. // mappingSources creates MappingSources map with a single item.
  292. func mappingSources(key, source string, start uint64) plugin.MappingSources {
  293. return plugin.MappingSources{
  294. key: []struct {
  295. Source string
  296. Start uint64
  297. }{
  298. {Source: source, Start: start},
  299. },
  300. }
  301. }
  302. // stubHTTPGet intercepts a call to http.Get and rewrites it to use
  303. // "file://" to get the profile directly from a file.
  304. func stubHTTPGet(source string, _ time.Duration) (*http.Response, error) {
  305. url, err := url.Parse(source)
  306. if err != nil {
  307. return nil, err
  308. }
  309. values := url.Query()
  310. file := values.Get("file")
  311. if file == "" {
  312. return nil, fmt.Errorf("want .../file?profile, got %s", source)
  313. }
  314. t := &http.Transport{}
  315. t.RegisterProtocol("file", http.NewFileTransport(http.Dir("testdata/")))
  316. c := &http.Client{Transport: t}
  317. return c.Get("file:///" + file)
  318. }
  319. func TestHttpsInsecure(t *testing.T) {
  320. if runtime.GOOS == "nacl" {
  321. t.Skip("test assumes tcp available")
  322. }
  323. baseVars := pprofVariables
  324. pprofVariables = baseVars.makeCopy()
  325. defer func() { pprofVariables = baseVars }()
  326. tlsConfig := &tls.Config{Certificates: []tls.Certificate{selfSignedCert(t)}}
  327. l, err := tls.Listen("tcp", "localhost:0", tlsConfig)
  328. if err != nil {
  329. t.Fatalf("net.Listen: got error %v, want no error", err)
  330. }
  331. donec := make(chan error, 1)
  332. go func(donec chan<- error) {
  333. donec <- http.Serve(l, nil)
  334. }(donec)
  335. defer func() {
  336. if got, want := <-donec, "use of closed"; !strings.Contains(got.Error(), want) {
  337. t.Fatalf("Serve got error %v, want %q", got, want)
  338. }
  339. }()
  340. defer l.Close()
  341. go func() {
  342. deadline := time.Now().Add(5 * time.Second)
  343. for time.Now().Before(deadline) {
  344. // Simulate a hotspot function. Spin in the inner loop for 100M iterations
  345. // to ensure we get most of the samples landed here rather than in the
  346. // library calls. We assume Go compiler won't elide the empty loop.
  347. for i := 0; i < 1e8; i++ {
  348. }
  349. runtime.Gosched()
  350. }
  351. }()
  352. outputTempFile, err := ioutil.TempFile("", "profile_output")
  353. if err != nil {
  354. t.Fatalf("Failed to create tempfile: %v", err)
  355. }
  356. defer os.Remove(outputTempFile.Name())
  357. defer outputTempFile.Close()
  358. address := "https+insecure://" + l.Addr().String() + "/debug/pprof/profile"
  359. s := &source{
  360. Sources: []string{address},
  361. Seconds: 10,
  362. Timeout: 10,
  363. Symbolize: "remote",
  364. }
  365. o := &plugin.Options{
  366. Obj: &binutils.Binutils{},
  367. UI: &proftest.TestUI{T: t, AllowRx: "Saved profile in"},
  368. }
  369. o.Sym = &symbolizer.Symbolizer{Obj: o.Obj, UI: o.UI}
  370. p, err := fetchProfiles(s, o)
  371. if err != nil {
  372. t.Fatal(err)
  373. }
  374. if len(p.SampleType) == 0 {
  375. t.Fatalf("fetchProfiles(%s) got empty profile: len(p.SampleType)==0", address)
  376. }
  377. if len(p.Function) == 0 {
  378. t.Fatalf("fetchProfiles(%s) got non-symbolized profile: len(p.Function)==0", address)
  379. }
  380. if err := checkProfileHasFunction(p, "TestHttpsInsecure"); !badSigprofOS[runtime.GOOS] && err != nil {
  381. t.Fatalf("fetchProfiles(%s) %v", address, err)
  382. }
  383. }
  384. // Some operating systems don't trigger the profiling signal right.
  385. // See https://github.com/golang/go/issues/13841.
  386. var badSigprofOS = map[string]bool{
  387. "darwin": true,
  388. "netbsd": true,
  389. "plan9": true,
  390. }
  391. func checkProfileHasFunction(p *profile.Profile, fname string) error {
  392. for _, f := range p.Function {
  393. if strings.Contains(f.Name, fname) {
  394. return nil
  395. }
  396. }
  397. return fmt.Errorf("got %s, want function %q", p.String(), fname)
  398. }
  399. func selfSignedCert(t *testing.T) tls.Certificate {
  400. privKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  401. if err != nil {
  402. t.Fatalf("failed to generate private key: %v", err)
  403. }
  404. b, err := x509.MarshalECPrivateKey(privKey)
  405. if err != nil {
  406. t.Fatalf("failed to marshal private key: %v", err)
  407. }
  408. bk := pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: b})
  409. tmpl := x509.Certificate{
  410. SerialNumber: big.NewInt(1),
  411. NotBefore: time.Now(),
  412. NotAfter: time.Now().Add(10 * time.Minute),
  413. }
  414. b, err = x509.CreateCertificate(rand.Reader, &tmpl, &tmpl, privKey.Public(), privKey)
  415. if err != nil {
  416. t.Fatalf("failed to create cert: %v", err)
  417. }
  418. bc := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: b})
  419. cert, err := tls.X509KeyPair(bc, bk)
  420. if err != nil {
  421. t.Fatalf("failed to create TLS key pair: %v", err)
  422. }
  423. return cert
  424. }