No Description

profile_test.go 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675
  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 profile
  15. import (
  16. "bytes"
  17. "fmt"
  18. "io/ioutil"
  19. "path/filepath"
  20. "regexp"
  21. "strings"
  22. "testing"
  23. "github.com/google/pprof/internal/proftest"
  24. )
  25. func TestParse(t *testing.T) {
  26. const path = "testdata/"
  27. for _, source := range []string{
  28. "go.crc32.cpu",
  29. "go.godoc.thread",
  30. "gobench.cpu",
  31. "gobench.heap",
  32. "cppbench.cpu",
  33. "cppbench.heap",
  34. "cppbench.contention",
  35. "cppbench.growth",
  36. "cppbench.thread",
  37. "cppbench.thread.all",
  38. "cppbench.thread.none",
  39. "java.cpu",
  40. "java.heap",
  41. "java.contention",
  42. } {
  43. inbytes, err := ioutil.ReadFile(filepath.Join(path, source))
  44. if err != nil {
  45. t.Fatal(err)
  46. }
  47. p, err := Parse(bytes.NewBuffer(inbytes))
  48. if err != nil {
  49. t.Fatalf("%s: %s", source, err)
  50. }
  51. js := p.String()
  52. goldFilename := path + source + ".string"
  53. gold, err := ioutil.ReadFile(goldFilename)
  54. if err != nil {
  55. t.Fatalf("%s: %v", source, err)
  56. }
  57. if js != string(gold) {
  58. t.Errorf("diff %s %s", source, goldFilename)
  59. d, err := proftest.Diff(gold, []byte(js))
  60. if err != nil {
  61. t.Fatalf("%s: %v", source, err)
  62. }
  63. t.Error(source + "\n" + string(d) + "\n" + "new profile at:\n" + leaveTempfile([]byte(js)))
  64. }
  65. // Reencode and decode.
  66. bw := bytes.NewBuffer(nil)
  67. if err := p.Write(bw); err != nil {
  68. t.Fatalf("%s: %v", source, err)
  69. }
  70. if p, err = Parse(bw); err != nil {
  71. t.Fatalf("%s: %v", source, err)
  72. }
  73. js2 := p.String()
  74. if js2 != string(gold) {
  75. d, err := proftest.Diff(gold, []byte(js2))
  76. if err != nil {
  77. t.Fatalf("%s: %v", source, err)
  78. }
  79. t.Error(source + "\n" + string(d) + "\n" + "gold:\n" + goldFilename +
  80. "\nnew profile at:\n" + leaveTempfile([]byte(js)))
  81. }
  82. }
  83. }
  84. func TestParseError(t *testing.T) {
  85. testcases := []string{
  86. "",
  87. "garbage text",
  88. "\x1f\x8b", // truncated gzip header
  89. "\x1f\x8b\x08\x08\xbe\xe9\x20\x58\x00\x03\x65\x6d\x70\x74\x79\x00\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00", // empty gzipped file
  90. }
  91. for i, input := range testcases {
  92. _, err := Parse(strings.NewReader(input))
  93. if err == nil {
  94. t.Errorf("got nil, want error for input #%d", i)
  95. }
  96. }
  97. }
  98. // leaveTempfile leaves |b| in a temporary file on disk and returns the
  99. // temp filename. This is useful to recover a profile when the test
  100. // fails.
  101. func leaveTempfile(b []byte) string {
  102. f1, err := ioutil.TempFile("", "profile_test")
  103. if err != nil {
  104. panic(err)
  105. }
  106. if _, err := f1.Write(b); err != nil {
  107. panic(err)
  108. }
  109. return f1.Name()
  110. }
  111. const mainBinary = "/bin/main"
  112. var cpuM = []*Mapping{
  113. {
  114. ID: 1,
  115. Start: 0x10000,
  116. Limit: 0x40000,
  117. File: mainBinary,
  118. HasFunctions: true,
  119. HasFilenames: true,
  120. HasLineNumbers: true,
  121. HasInlineFrames: true,
  122. },
  123. {
  124. ID: 2,
  125. Start: 0x1000,
  126. Limit: 0x4000,
  127. File: "/lib/lib.so",
  128. HasFunctions: true,
  129. HasFilenames: true,
  130. HasLineNumbers: true,
  131. HasInlineFrames: true,
  132. },
  133. {
  134. ID: 3,
  135. Start: 0x4000,
  136. Limit: 0x5000,
  137. File: "/lib/lib2_c.so.6",
  138. HasFunctions: true,
  139. HasFilenames: true,
  140. HasLineNumbers: true,
  141. HasInlineFrames: true,
  142. },
  143. {
  144. ID: 4,
  145. Start: 0x5000,
  146. Limit: 0x9000,
  147. File: "/lib/lib.so_6 (deleted)",
  148. HasFunctions: true,
  149. HasFilenames: true,
  150. HasLineNumbers: true,
  151. HasInlineFrames: true,
  152. },
  153. }
  154. var cpuF = []*Function{
  155. {ID: 1, Name: "main", SystemName: "main", Filename: "main.c"},
  156. {ID: 2, Name: "foo", SystemName: "foo", Filename: "foo.c"},
  157. {ID: 3, Name: "foo_caller", SystemName: "foo_caller", Filename: "foo.c"},
  158. }
  159. var cpuL = []*Location{
  160. {
  161. ID: 1000,
  162. Mapping: cpuM[1],
  163. Address: 0x1000,
  164. Line: []Line{
  165. {Function: cpuF[0], Line: 1},
  166. },
  167. },
  168. {
  169. ID: 2000,
  170. Mapping: cpuM[0],
  171. Address: 0x2000,
  172. Line: []Line{
  173. {Function: cpuF[1], Line: 2},
  174. {Function: cpuF[2], Line: 1},
  175. },
  176. },
  177. {
  178. ID: 3000,
  179. Mapping: cpuM[0],
  180. Address: 0x3000,
  181. Line: []Line{
  182. {Function: cpuF[1], Line: 2},
  183. {Function: cpuF[2], Line: 1},
  184. },
  185. },
  186. {
  187. ID: 3001,
  188. Mapping: cpuM[0],
  189. Address: 0x3001,
  190. Line: []Line{
  191. {Function: cpuF[2], Line: 2},
  192. },
  193. },
  194. {
  195. ID: 3002,
  196. Mapping: cpuM[0],
  197. Address: 0x3002,
  198. Line: []Line{
  199. {Function: cpuF[2], Line: 3},
  200. },
  201. },
  202. }
  203. var testProfile1 = &Profile{
  204. PeriodType: &ValueType{Type: "cpu", Unit: "milliseconds"},
  205. Period: 1,
  206. DurationNanos: 10e9,
  207. SampleType: []*ValueType{
  208. {Type: "samples", Unit: "count"},
  209. {Type: "cpu", Unit: "milliseconds"},
  210. },
  211. Sample: []*Sample{
  212. {
  213. Location: []*Location{cpuL[0]},
  214. Value: []int64{1000, 1000},
  215. Label: map[string][]string{
  216. "key1": {"tag1"},
  217. "key2": {"tag1"},
  218. },
  219. },
  220. {
  221. Location: []*Location{cpuL[1], cpuL[0]},
  222. Value: []int64{100, 100},
  223. Label: map[string][]string{
  224. "key1": {"tag2"},
  225. "key3": {"tag2"},
  226. },
  227. },
  228. {
  229. Location: []*Location{cpuL[2], cpuL[0]},
  230. Value: []int64{10, 10},
  231. Label: map[string][]string{
  232. "key1": {"tag3"},
  233. "key2": {"tag2"},
  234. },
  235. },
  236. {
  237. Location: []*Location{cpuL[3], cpuL[0]},
  238. Value: []int64{10000, 10000},
  239. Label: map[string][]string{
  240. "key1": {"tag4"},
  241. "key2": {"tag1"},
  242. },
  243. },
  244. {
  245. Location: []*Location{cpuL[4], cpuL[0]},
  246. Value: []int64{1, 1},
  247. Label: map[string][]string{
  248. "key1": {"tag4"},
  249. "key2": {"tag1"},
  250. },
  251. },
  252. },
  253. Location: cpuL,
  254. Function: cpuF,
  255. Mapping: cpuM,
  256. }
  257. var testProfile2 = &Profile{
  258. PeriodType: &ValueType{Type: "cpu", Unit: "milliseconds"},
  259. Period: 1,
  260. DurationNanos: 10e9,
  261. SampleType: []*ValueType{
  262. {Type: "samples", Unit: "count"},
  263. {Type: "cpu", Unit: "milliseconds"},
  264. },
  265. Sample: []*Sample{
  266. {
  267. Location: []*Location{cpuL[0]},
  268. Value: []int64{70, 1000},
  269. Label: map[string][]string{
  270. "key1": {"tag1"},
  271. "key2": {"tag1"},
  272. },
  273. },
  274. {
  275. Location: []*Location{cpuL[1], cpuL[0]},
  276. Value: []int64{60, 100},
  277. Label: map[string][]string{
  278. "key1": {"tag2"},
  279. "key3": {"tag2"},
  280. },
  281. },
  282. {
  283. Location: []*Location{cpuL[2], cpuL[0]},
  284. Value: []int64{50, 10},
  285. Label: map[string][]string{
  286. "key1": {"tag3"},
  287. "key2": {"tag2"},
  288. },
  289. },
  290. {
  291. Location: []*Location{cpuL[3], cpuL[0]},
  292. Value: []int64{40, 10000},
  293. Label: map[string][]string{
  294. "key1": {"tag4"},
  295. "key2": {"tag1"},
  296. },
  297. },
  298. {
  299. Location: []*Location{cpuL[4], cpuL[0]},
  300. Value: []int64{1, 1},
  301. Label: map[string][]string{
  302. "key1": {"tag4"},
  303. "key2": {"tag1"},
  304. },
  305. },
  306. },
  307. Location: cpuL,
  308. Function: cpuF,
  309. Mapping: cpuM,
  310. }
  311. var testProfile3 = &Profile{
  312. PeriodType: &ValueType{Type: "cpu", Unit: "milliseconds"},
  313. Period: 1,
  314. DurationNanos: 10e9,
  315. SampleType: []*ValueType{
  316. {Type: "samples", Unit: "count"},
  317. },
  318. Sample: []*Sample{
  319. {
  320. Location: []*Location{cpuL[0]},
  321. Value: []int64{1000},
  322. Label: map[string][]string{
  323. "key1": {"tag1"},
  324. "key2": {"tag1"},
  325. },
  326. },
  327. },
  328. Location: cpuL,
  329. Function: cpuF,
  330. Mapping: cpuM,
  331. }
  332. var aggTests = map[string]aggTest{
  333. "precise": {true, true, true, true, 5},
  334. "fileline": {false, true, true, true, 4},
  335. "inline_function": {false, true, false, true, 3},
  336. "function": {false, true, false, false, 2},
  337. }
  338. type aggTest struct {
  339. precise, function, fileline, inlineFrame bool
  340. rows int
  341. }
  342. const totalSamples = int64(11111)
  343. func TestAggregation(t *testing.T) {
  344. prof := testProfile1.Copy()
  345. for _, resolution := range []string{"precise", "fileline", "inline_function", "function"} {
  346. a := aggTests[resolution]
  347. if !a.precise {
  348. if err := prof.Aggregate(a.inlineFrame, a.function, a.fileline, a.fileline, false); err != nil {
  349. t.Error("aggregating to " + resolution + ":" + err.Error())
  350. }
  351. }
  352. if err := checkAggregation(prof, &a); err != nil {
  353. t.Error("failed aggregation to " + resolution + ": " + err.Error())
  354. }
  355. }
  356. }
  357. // checkAggregation verifies that the profile remained consistent
  358. // with its aggregation.
  359. func checkAggregation(prof *Profile, a *aggTest) error {
  360. // Check that the total number of samples for the rows was preserved.
  361. total := int64(0)
  362. samples := make(map[string]bool)
  363. for _, sample := range prof.Sample {
  364. tb := locationHash(sample)
  365. samples[tb] = true
  366. total += sample.Value[0]
  367. }
  368. if total != totalSamples {
  369. return fmt.Errorf("sample total %d, want %d", total, totalSamples)
  370. }
  371. // Check the number of unique sample locations
  372. if a.rows != len(samples) {
  373. return fmt.Errorf("number of samples %d, want %d", len(samples), a.rows)
  374. }
  375. // Check that all mappings have the right detail flags.
  376. for _, m := range prof.Mapping {
  377. if m.HasFunctions != a.function {
  378. return fmt.Errorf("unexpected mapping.HasFunctions %v, want %v", m.HasFunctions, a.function)
  379. }
  380. if m.HasFilenames != a.fileline {
  381. return fmt.Errorf("unexpected mapping.HasFilenames %v, want %v", m.HasFilenames, a.fileline)
  382. }
  383. if m.HasLineNumbers != a.fileline {
  384. return fmt.Errorf("unexpected mapping.HasLineNumbers %v, want %v", m.HasLineNumbers, a.fileline)
  385. }
  386. if m.HasInlineFrames != a.inlineFrame {
  387. return fmt.Errorf("unexpected mapping.HasInlineFrames %v, want %v", m.HasInlineFrames, a.inlineFrame)
  388. }
  389. }
  390. // Check that aggregation has removed finer resolution data.
  391. for _, l := range prof.Location {
  392. if !a.inlineFrame && len(l.Line) > 1 {
  393. return fmt.Errorf("found %d lines on location %d, want 1", len(l.Line), l.ID)
  394. }
  395. for _, ln := range l.Line {
  396. if !a.fileline && (ln.Function.Filename != "" || ln.Line != 0) {
  397. return fmt.Errorf("found line %s:%d on location %d, want :0",
  398. ln.Function.Filename, ln.Line, l.ID)
  399. }
  400. if !a.function && (ln.Function.Name != "") {
  401. return fmt.Errorf(`found file %s location %d, want ""`,
  402. ln.Function.Name, l.ID)
  403. }
  404. }
  405. }
  406. return nil
  407. }
  408. // Test merge leaves the main binary in place.
  409. func TestMergeMain(t *testing.T) {
  410. prof := testProfile1.Copy()
  411. p1, err := Merge([]*Profile{prof})
  412. if err != nil {
  413. t.Fatalf("merge error: %v", err)
  414. }
  415. if cpuM[0].File != p1.Mapping[0].File {
  416. t.Errorf("want Mapping[0]=%s got %s", cpuM[0].File, p1.Mapping[0].File)
  417. }
  418. }
  419. func TestMerge(t *testing.T) {
  420. // Aggregate a profile with itself and once again with a factor of
  421. // -2. Should end up with an empty profile (all samples for a
  422. // location should add up to 0).
  423. prof := testProfile1.Copy()
  424. p1, err := Merge([]*Profile{prof, prof})
  425. if err != nil {
  426. t.Errorf("merge error: %v", err)
  427. }
  428. prof.Scale(-2)
  429. prof, err = Merge([]*Profile{p1, prof})
  430. if err != nil {
  431. t.Errorf("merge error: %v", err)
  432. }
  433. // Use aggregation to merge locations at function granularity.
  434. if err := prof.Aggregate(false, true, false, false, false); err != nil {
  435. t.Errorf("aggregating after merge: %v", err)
  436. }
  437. samples := make(map[string]int64)
  438. for _, s := range prof.Sample {
  439. tb := locationHash(s)
  440. samples[tb] = samples[tb] + s.Value[0]
  441. }
  442. for s, v := range samples {
  443. if v != 0 {
  444. t.Errorf("nonzero value for sample %s: %d", s, v)
  445. }
  446. }
  447. }
  448. func TestMergeAll(t *testing.T) {
  449. // Aggregate 10 copies of the profile.
  450. profs := make([]*Profile, 10)
  451. for i := 0; i < 10; i++ {
  452. profs[i] = testProfile1.Copy()
  453. }
  454. prof, err := Merge(profs)
  455. if err != nil {
  456. t.Errorf("merge error: %v", err)
  457. }
  458. samples := make(map[string]int64)
  459. for _, s := range prof.Sample {
  460. tb := locationHash(s)
  461. samples[tb] = samples[tb] + s.Value[0]
  462. }
  463. for _, s := range testProfile1.Sample {
  464. tb := locationHash(s)
  465. if samples[tb] != s.Value[0]*10 {
  466. t.Errorf("merge got wrong value at %s : %d instead of %d", tb, samples[tb], s.Value[0]*10)
  467. }
  468. }
  469. }
  470. func TestNormalizeBySameProfile(t *testing.T) {
  471. pb := testProfile1.Copy()
  472. p := testProfile1.Copy()
  473. if err := p.Normalize(pb); err != nil {
  474. t.Fatal(err)
  475. }
  476. for i, s := range p.Sample {
  477. for j, v := range s.Value {
  478. expectedSampleValue := testProfile1.Sample[i].Value[j]
  479. if v != expectedSampleValue {
  480. t.Errorf("For sample %d, value %d want %d got %d", i, j, expectedSampleValue, v)
  481. }
  482. }
  483. }
  484. }
  485. func TestNormalizeByDifferentProfile(t *testing.T) {
  486. p := testProfile1.Copy()
  487. pb := testProfile2.Copy()
  488. if err := p.Normalize(pb); err != nil {
  489. t.Fatal(err)
  490. }
  491. expectedSampleValues := [][]int64{
  492. {19, 1000},
  493. {1, 100},
  494. {0, 10},
  495. {198, 10000},
  496. {0, 1},
  497. }
  498. for i, s := range p.Sample {
  499. for j, v := range s.Value {
  500. if v != expectedSampleValues[i][j] {
  501. t.Errorf("For sample %d, value %d want %d got %d", i, j, expectedSampleValues[i][j], v)
  502. }
  503. }
  504. }
  505. }
  506. func TestNormalizeByMultipleOfSameProfile(t *testing.T) {
  507. pb := testProfile1.Copy()
  508. for i, s := range pb.Sample {
  509. for j, v := range s.Value {
  510. pb.Sample[i].Value[j] = 10 * v
  511. }
  512. }
  513. p := testProfile1.Copy()
  514. err := p.Normalize(pb)
  515. if err != nil {
  516. t.Fatal(err)
  517. }
  518. for i, s := range p.Sample {
  519. for j, v := range s.Value {
  520. expectedSampleValue := 10 * testProfile1.Sample[i].Value[j]
  521. if v != expectedSampleValue {
  522. t.Errorf("For sample %d, value %d, want %d got %d", i, j, expectedSampleValue, v)
  523. }
  524. }
  525. }
  526. }
  527. func TestNormalizeIncompatibleProfiles(t *testing.T) {
  528. p := testProfile1.Copy()
  529. pb := testProfile3.Copy()
  530. if err := p.Normalize(pb); err == nil {
  531. t.Errorf("Expected an error")
  532. }
  533. }
  534. func TestFilter(t *testing.T) {
  535. // Perform several forms of filtering on the test profile.
  536. type filterTestcase struct {
  537. focus, ignore, hide, show *regexp.Regexp
  538. fm, im, hm, hnm bool
  539. }
  540. for tx, tc := range []filterTestcase{
  541. {nil, nil, nil, nil, true, false, false, false},
  542. {regexp.MustCompile("notfound"), nil, nil, nil, false, false, false, false},
  543. {nil, regexp.MustCompile("foo.c"), nil, nil, true, true, false, false},
  544. {nil, nil, regexp.MustCompile("lib.so"), nil, true, false, true, false},
  545. } {
  546. prof := *testProfile1.Copy()
  547. gf, gi, gh, gnh := prof.FilterSamplesByName(tc.focus, tc.ignore, tc.hide, tc.show)
  548. if gf != tc.fm {
  549. t.Errorf("Filter #%d, got fm=%v, want %v", tx, gf, tc.fm)
  550. }
  551. if gi != tc.im {
  552. t.Errorf("Filter #%d, got im=%v, want %v", tx, gi, tc.im)
  553. }
  554. if gh != tc.hm {
  555. t.Errorf("Filter #%d, got hm=%v, want %v", tx, gh, tc.hm)
  556. }
  557. if gnh != tc.hnm {
  558. t.Errorf("Filter #%d, got hnm=%v, want %v", tx, gnh, tc.hnm)
  559. }
  560. }
  561. }
  562. func TestTagFilter(t *testing.T) {
  563. // Perform several forms of tag filtering on the test profile.
  564. type filterTestcase struct {
  565. include, exclude *regexp.Regexp
  566. im, em bool
  567. count int
  568. }
  569. countTags := func(p *Profile) map[string]bool {
  570. tags := make(map[string]bool)
  571. for _, s := range p.Sample {
  572. for l := range s.Label {
  573. tags[l] = true
  574. }
  575. for l := range s.NumLabel {
  576. tags[l] = true
  577. }
  578. }
  579. return tags
  580. }
  581. for tx, tc := range []filterTestcase{
  582. {nil, nil, true, false, 3},
  583. {regexp.MustCompile("notfound"), nil, false, false, 0},
  584. {regexp.MustCompile("key1"), nil, true, false, 1},
  585. {nil, regexp.MustCompile("key[12]"), true, true, 1},
  586. } {
  587. prof := testProfile1.Copy()
  588. gim, gem := prof.FilterTagsByName(tc.include, tc.exclude)
  589. if gim != tc.im {
  590. t.Errorf("Filter #%d, got include match=%v, want %v", tx, gim, tc.im)
  591. }
  592. if gem != tc.em {
  593. t.Errorf("Filter #%d, got exclude match=%v, want %v", tx, gem, tc.em)
  594. }
  595. if tags := countTags(prof); len(tags) != tc.count {
  596. t.Errorf("Filter #%d, got %d tags[%v], want %d", tx, len(tags), tags, tc.count)
  597. }
  598. }
  599. }
  600. // locationHash constructs a string to use as a hashkey for a sample, based on its locations
  601. func locationHash(s *Sample) string {
  602. var tb string
  603. for _, l := range s.Location {
  604. for _, ln := range l.Line {
  605. tb = tb + fmt.Sprintf("%s:%d@%d ", ln.Function.Name, ln.Line, l.Address)
  606. }
  607. }
  608. return tb
  609. }
  610. func TestSetMain(t *testing.T) {
  611. testProfile1.massageMappings()
  612. if testProfile1.Mapping[0].File != mainBinary {
  613. t.Errorf("got %s for main", testProfile1.Mapping[0].File)
  614. }
  615. }