暫無描述

profile_test.go 27KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143
  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. "reflect"
  21. "regexp"
  22. "strings"
  23. "sync"
  24. "testing"
  25. "github.com/google/pprof/internal/proftest"
  26. )
  27. func TestParse(t *testing.T) {
  28. const path = "testdata/"
  29. for _, source := range []string{
  30. "go.crc32.cpu",
  31. "go.godoc.thread",
  32. "gobench.cpu",
  33. "gobench.heap",
  34. "cppbench.cpu",
  35. "cppbench.heap",
  36. "cppbench.contention",
  37. "cppbench.growth",
  38. "cppbench.thread",
  39. "cppbench.thread.all",
  40. "cppbench.thread.none",
  41. "java.cpu",
  42. "java.heap",
  43. "java.contention",
  44. } {
  45. inbytes, err := ioutil.ReadFile(filepath.Join(path, source))
  46. if err != nil {
  47. t.Fatal(err)
  48. }
  49. p, err := Parse(bytes.NewBuffer(inbytes))
  50. if err != nil {
  51. t.Fatalf("%s: %s", source, err)
  52. }
  53. js := p.String()
  54. goldFilename := path + source + ".string"
  55. gold, err := ioutil.ReadFile(goldFilename)
  56. if err != nil {
  57. t.Fatalf("%s: %v", source, err)
  58. }
  59. if js != string(gold) {
  60. t.Errorf("diff %s %s", source, goldFilename)
  61. d, err := proftest.Diff(gold, []byte(js))
  62. if err != nil {
  63. t.Fatalf("%s: %v", source, err)
  64. }
  65. t.Error(source + "\n" + string(d) + "\n" + "new profile at:\n" + leaveTempfile([]byte(js)))
  66. }
  67. // Reencode and decode.
  68. bw := bytes.NewBuffer(nil)
  69. if err := p.Write(bw); err != nil {
  70. t.Fatalf("%s: %v", source, err)
  71. }
  72. if p, err = Parse(bw); err != nil {
  73. t.Fatalf("%s: %v", source, err)
  74. }
  75. js2 := p.String()
  76. if js2 != string(gold) {
  77. d, err := proftest.Diff(gold, []byte(js2))
  78. if err != nil {
  79. t.Fatalf("%s: %v", source, err)
  80. }
  81. t.Error(source + "\n" + string(d) + "\n" + "gold:\n" + goldFilename +
  82. "\nnew profile at:\n" + leaveTempfile([]byte(js)))
  83. }
  84. }
  85. }
  86. func TestParseError(t *testing.T) {
  87. testcases := []string{
  88. "",
  89. "garbage text",
  90. "\x1f\x8b", // truncated gzip header
  91. "\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
  92. }
  93. for i, input := range testcases {
  94. _, err := Parse(strings.NewReader(input))
  95. if err == nil {
  96. t.Errorf("got nil, want error for input #%d", i)
  97. }
  98. }
  99. }
  100. func TestCheckValid(t *testing.T) {
  101. const path = "testdata/java.cpu"
  102. inbytes, err := ioutil.ReadFile(path)
  103. if err != nil {
  104. t.Fatalf("failed to read profile file %q: %v", path, err)
  105. }
  106. p, err := Parse(bytes.NewBuffer(inbytes))
  107. if err != nil {
  108. t.Fatalf("failed to parse profile %q: %s", path, err)
  109. }
  110. for _, tc := range []struct {
  111. mutateFn func(*Profile)
  112. wantErr string
  113. }{
  114. {
  115. mutateFn: func(p *Profile) { p.SampleType = nil },
  116. wantErr: "missing sample type information",
  117. },
  118. {
  119. mutateFn: func(p *Profile) { p.Sample[0] = nil },
  120. wantErr: "profile has nil sample",
  121. },
  122. {
  123. mutateFn: func(p *Profile) { p.Sample[0].Value = append(p.Sample[0].Value, 0) },
  124. wantErr: "sample has 3 values vs. 2 types",
  125. },
  126. {
  127. mutateFn: func(p *Profile) { p.Sample[0].Location[0] = nil },
  128. wantErr: "sample has nil location",
  129. },
  130. {
  131. mutateFn: func(p *Profile) { p.Location[0] = nil },
  132. wantErr: "profile has nil location",
  133. },
  134. {
  135. mutateFn: func(p *Profile) { p.Mapping = append(p.Mapping, nil) },
  136. wantErr: "profile has nil mapping",
  137. },
  138. {
  139. mutateFn: func(p *Profile) { p.Function[0] = nil },
  140. wantErr: "profile has nil function",
  141. },
  142. } {
  143. t.Run(tc.wantErr, func(t *testing.T) {
  144. p := p.Copy()
  145. tc.mutateFn(p)
  146. if err := p.CheckValid(); err == nil {
  147. t.Errorf("CheckValid(): got no error, want error %q", tc.wantErr)
  148. } else if !strings.Contains(err.Error(), tc.wantErr) {
  149. t.Errorf("CheckValid(): got error %v, want error %q", err, tc.wantErr)
  150. }
  151. })
  152. }
  153. }
  154. // leaveTempfile leaves |b| in a temporary file on disk and returns the
  155. // temp filename. This is useful to recover a profile when the test
  156. // fails.
  157. func leaveTempfile(b []byte) string {
  158. f1, err := ioutil.TempFile("", "profile_test")
  159. if err != nil {
  160. panic(err)
  161. }
  162. if _, err := f1.Write(b); err != nil {
  163. panic(err)
  164. }
  165. return f1.Name()
  166. }
  167. const mainBinary = "/bin/main"
  168. var cpuM = []*Mapping{
  169. {
  170. ID: 1,
  171. Start: 0x10000,
  172. Limit: 0x40000,
  173. File: mainBinary,
  174. HasFunctions: true,
  175. HasFilenames: true,
  176. HasLineNumbers: true,
  177. HasInlineFrames: true,
  178. },
  179. {
  180. ID: 2,
  181. Start: 0x1000,
  182. Limit: 0x4000,
  183. File: "/lib/lib.so",
  184. HasFunctions: true,
  185. HasFilenames: true,
  186. HasLineNumbers: true,
  187. HasInlineFrames: true,
  188. },
  189. {
  190. ID: 3,
  191. Start: 0x4000,
  192. Limit: 0x5000,
  193. File: "/lib/lib2_c.so.6",
  194. HasFunctions: true,
  195. HasFilenames: true,
  196. HasLineNumbers: true,
  197. HasInlineFrames: true,
  198. },
  199. {
  200. ID: 4,
  201. Start: 0x5000,
  202. Limit: 0x9000,
  203. File: "/lib/lib.so_6 (deleted)",
  204. HasFunctions: true,
  205. HasFilenames: true,
  206. HasLineNumbers: true,
  207. HasInlineFrames: true,
  208. },
  209. }
  210. var cpuF = []*Function{
  211. {ID: 1, Name: "main", SystemName: "main", Filename: "main.c"},
  212. {ID: 2, Name: "foo", SystemName: "foo", Filename: "foo.c"},
  213. {ID: 3, Name: "foo_caller", SystemName: "foo_caller", Filename: "foo.c"},
  214. }
  215. var cpuL = []*Location{
  216. {
  217. ID: 1000,
  218. Mapping: cpuM[1],
  219. Address: 0x1000,
  220. Line: []Line{
  221. {Function: cpuF[0], Line: 1},
  222. },
  223. },
  224. {
  225. ID: 2000,
  226. Mapping: cpuM[0],
  227. Address: 0x2000,
  228. Line: []Line{
  229. {Function: cpuF[1], Line: 2},
  230. {Function: cpuF[2], Line: 1},
  231. },
  232. },
  233. {
  234. ID: 3000,
  235. Mapping: cpuM[0],
  236. Address: 0x3000,
  237. Line: []Line{
  238. {Function: cpuF[1], Line: 2},
  239. {Function: cpuF[2], Line: 1},
  240. },
  241. },
  242. {
  243. ID: 3001,
  244. Mapping: cpuM[0],
  245. Address: 0x3001,
  246. Line: []Line{
  247. {Function: cpuF[2], Line: 2},
  248. },
  249. },
  250. {
  251. ID: 3002,
  252. Mapping: cpuM[0],
  253. Address: 0x3002,
  254. Line: []Line{
  255. {Function: cpuF[2], Line: 3},
  256. },
  257. },
  258. }
  259. var testProfile1 = &Profile{
  260. PeriodType: &ValueType{Type: "cpu", Unit: "milliseconds"},
  261. Period: 1,
  262. DurationNanos: 10e9,
  263. SampleType: []*ValueType{
  264. {Type: "samples", Unit: "count"},
  265. {Type: "cpu", Unit: "milliseconds"},
  266. },
  267. Sample: []*Sample{
  268. {
  269. Location: []*Location{cpuL[0]},
  270. Value: []int64{1000, 1000},
  271. Label: map[string][]string{
  272. "key1": {"tag1"},
  273. "key2": {"tag1"},
  274. },
  275. },
  276. {
  277. Location: []*Location{cpuL[1], cpuL[0]},
  278. Value: []int64{100, 100},
  279. Label: map[string][]string{
  280. "key1": {"tag2"},
  281. "key3": {"tag2"},
  282. },
  283. },
  284. {
  285. Location: []*Location{cpuL[2], cpuL[0]},
  286. Value: []int64{10, 10},
  287. Label: map[string][]string{
  288. "key1": {"tag3"},
  289. "key2": {"tag2"},
  290. },
  291. },
  292. {
  293. Location: []*Location{cpuL[3], cpuL[0]},
  294. Value: []int64{10000, 10000},
  295. Label: map[string][]string{
  296. "key1": {"tag4"},
  297. "key2": {"tag1"},
  298. },
  299. },
  300. {
  301. Location: []*Location{cpuL[4], cpuL[0]},
  302. Value: []int64{1, 1},
  303. Label: map[string][]string{
  304. "key1": {"tag4"},
  305. "key2": {"tag1"},
  306. },
  307. },
  308. },
  309. Location: cpuL,
  310. Function: cpuF,
  311. Mapping: cpuM,
  312. }
  313. var testProfile1NoMapping = &Profile{
  314. PeriodType: &ValueType{Type: "cpu", Unit: "milliseconds"},
  315. Period: 1,
  316. DurationNanos: 10e9,
  317. SampleType: []*ValueType{
  318. {Type: "samples", Unit: "count"},
  319. {Type: "cpu", Unit: "milliseconds"},
  320. },
  321. Sample: []*Sample{
  322. {
  323. Location: []*Location{cpuL[0]},
  324. Value: []int64{1000, 1000},
  325. Label: map[string][]string{
  326. "key1": {"tag1"},
  327. "key2": {"tag1"},
  328. },
  329. },
  330. {
  331. Location: []*Location{cpuL[1], cpuL[0]},
  332. Value: []int64{100, 100},
  333. Label: map[string][]string{
  334. "key1": {"tag2"},
  335. "key3": {"tag2"},
  336. },
  337. },
  338. {
  339. Location: []*Location{cpuL[2], cpuL[0]},
  340. Value: []int64{10, 10},
  341. Label: map[string][]string{
  342. "key1": {"tag3"},
  343. "key2": {"tag2"},
  344. },
  345. },
  346. {
  347. Location: []*Location{cpuL[3], cpuL[0]},
  348. Value: []int64{10000, 10000},
  349. Label: map[string][]string{
  350. "key1": {"tag4"},
  351. "key2": {"tag1"},
  352. },
  353. },
  354. {
  355. Location: []*Location{cpuL[4], cpuL[0]},
  356. Value: []int64{1, 1},
  357. Label: map[string][]string{
  358. "key1": {"tag4"},
  359. "key2": {"tag1"},
  360. },
  361. },
  362. },
  363. Location: cpuL,
  364. Function: cpuF,
  365. }
  366. var testProfile2 = &Profile{
  367. PeriodType: &ValueType{Type: "cpu", Unit: "milliseconds"},
  368. Period: 1,
  369. DurationNanos: 10e9,
  370. SampleType: []*ValueType{
  371. {Type: "samples", Unit: "count"},
  372. {Type: "cpu", Unit: "milliseconds"},
  373. },
  374. Sample: []*Sample{
  375. {
  376. Location: []*Location{cpuL[0]},
  377. Value: []int64{70, 1000},
  378. Label: map[string][]string{
  379. "key1": {"tag1"},
  380. "key2": {"tag1"},
  381. },
  382. },
  383. {
  384. Location: []*Location{cpuL[1], cpuL[0]},
  385. Value: []int64{60, 100},
  386. Label: map[string][]string{
  387. "key1": {"tag2"},
  388. "key3": {"tag2"},
  389. },
  390. },
  391. {
  392. Location: []*Location{cpuL[2], cpuL[0]},
  393. Value: []int64{50, 10},
  394. Label: map[string][]string{
  395. "key1": {"tag3"},
  396. "key2": {"tag2"},
  397. },
  398. },
  399. {
  400. Location: []*Location{cpuL[3], cpuL[0]},
  401. Value: []int64{40, 10000},
  402. Label: map[string][]string{
  403. "key1": {"tag4"},
  404. "key2": {"tag1"},
  405. },
  406. },
  407. {
  408. Location: []*Location{cpuL[4], cpuL[0]},
  409. Value: []int64{1, 1},
  410. Label: map[string][]string{
  411. "key1": {"tag4"},
  412. "key2": {"tag1"},
  413. },
  414. },
  415. },
  416. Location: cpuL,
  417. Function: cpuF,
  418. Mapping: cpuM,
  419. }
  420. var testProfile3 = &Profile{
  421. PeriodType: &ValueType{Type: "cpu", Unit: "milliseconds"},
  422. Period: 1,
  423. DurationNanos: 10e9,
  424. SampleType: []*ValueType{
  425. {Type: "samples", Unit: "count"},
  426. },
  427. Sample: []*Sample{
  428. {
  429. Location: []*Location{cpuL[0]},
  430. Value: []int64{1000},
  431. Label: map[string][]string{
  432. "key1": {"tag1"},
  433. "key2": {"tag1"},
  434. },
  435. },
  436. },
  437. Location: cpuL,
  438. Function: cpuF,
  439. Mapping: cpuM,
  440. }
  441. var testProfile4 = &Profile{
  442. PeriodType: &ValueType{Type: "cpu", Unit: "milliseconds"},
  443. Period: 1,
  444. DurationNanos: 10e9,
  445. SampleType: []*ValueType{
  446. {Type: "samples", Unit: "count"},
  447. },
  448. Sample: []*Sample{
  449. {
  450. Location: []*Location{cpuL[0]},
  451. Value: []int64{1000},
  452. NumLabel: map[string][]int64{
  453. "key1": {10},
  454. "key2": {30},
  455. },
  456. NumUnit: map[string][]string{
  457. "key1": {"bytes"},
  458. "key2": {"bytes"},
  459. },
  460. },
  461. },
  462. Location: cpuL,
  463. Function: cpuF,
  464. Mapping: cpuM,
  465. }
  466. var testProfile5 = &Profile{
  467. PeriodType: &ValueType{Type: "cpu", Unit: "milliseconds"},
  468. Period: 1,
  469. DurationNanos: 10e9,
  470. SampleType: []*ValueType{
  471. {Type: "samples", Unit: "count"},
  472. },
  473. Sample: []*Sample{
  474. {
  475. Location: []*Location{cpuL[0]},
  476. Value: []int64{1000},
  477. NumLabel: map[string][]int64{
  478. "key1": {10},
  479. "key2": {30},
  480. },
  481. NumUnit: map[string][]string{
  482. "key1": {"bytes"},
  483. "key2": {"bytes"},
  484. },
  485. },
  486. {
  487. Location: []*Location{cpuL[0]},
  488. Value: []int64{1000},
  489. NumLabel: map[string][]int64{
  490. "key1": {10},
  491. "key2": {30},
  492. },
  493. NumUnit: map[string][]string{
  494. "key1": {"kilobytes"},
  495. "key2": {"kilobytes"},
  496. },
  497. },
  498. },
  499. Location: cpuL,
  500. Function: cpuF,
  501. Mapping: cpuM,
  502. }
  503. var aggTests = map[string]aggTest{
  504. "precise": {true, true, true, true, 5},
  505. "fileline": {false, true, true, true, 4},
  506. "inline_function": {false, true, false, true, 3},
  507. "function": {false, true, false, false, 2},
  508. }
  509. type aggTest struct {
  510. precise, function, fileline, inlineFrame bool
  511. rows int
  512. }
  513. const totalSamples = int64(11111)
  514. func TestAggregation(t *testing.T) {
  515. prof := testProfile1.Copy()
  516. for _, resolution := range []string{"precise", "fileline", "inline_function", "function"} {
  517. a := aggTests[resolution]
  518. if !a.precise {
  519. if err := prof.Aggregate(a.inlineFrame, a.function, a.fileline, a.fileline, false); err != nil {
  520. t.Error("aggregating to " + resolution + ":" + err.Error())
  521. }
  522. }
  523. if err := checkAggregation(prof, &a); err != nil {
  524. t.Error("failed aggregation to " + resolution + ": " + err.Error())
  525. }
  526. }
  527. }
  528. // checkAggregation verifies that the profile remained consistent
  529. // with its aggregation.
  530. func checkAggregation(prof *Profile, a *aggTest) error {
  531. // Check that the total number of samples for the rows was preserved.
  532. total := int64(0)
  533. samples := make(map[string]bool)
  534. for _, sample := range prof.Sample {
  535. tb := locationHash(sample)
  536. samples[tb] = true
  537. total += sample.Value[0]
  538. }
  539. if total != totalSamples {
  540. return fmt.Errorf("sample total %d, want %d", total, totalSamples)
  541. }
  542. // Check the number of unique sample locations
  543. if a.rows != len(samples) {
  544. return fmt.Errorf("number of samples %d, want %d", len(samples), a.rows)
  545. }
  546. // Check that all mappings have the right detail flags.
  547. for _, m := range prof.Mapping {
  548. if m.HasFunctions != a.function {
  549. return fmt.Errorf("unexpected mapping.HasFunctions %v, want %v", m.HasFunctions, a.function)
  550. }
  551. if m.HasFilenames != a.fileline {
  552. return fmt.Errorf("unexpected mapping.HasFilenames %v, want %v", m.HasFilenames, a.fileline)
  553. }
  554. if m.HasLineNumbers != a.fileline {
  555. return fmt.Errorf("unexpected mapping.HasLineNumbers %v, want %v", m.HasLineNumbers, a.fileline)
  556. }
  557. if m.HasInlineFrames != a.inlineFrame {
  558. return fmt.Errorf("unexpected mapping.HasInlineFrames %v, want %v", m.HasInlineFrames, a.inlineFrame)
  559. }
  560. }
  561. // Check that aggregation has removed finer resolution data.
  562. for _, l := range prof.Location {
  563. if !a.inlineFrame && len(l.Line) > 1 {
  564. return fmt.Errorf("found %d lines on location %d, want 1", len(l.Line), l.ID)
  565. }
  566. for _, ln := range l.Line {
  567. if !a.fileline && (ln.Function.Filename != "" || ln.Line != 0) {
  568. return fmt.Errorf("found line %s:%d on location %d, want :0",
  569. ln.Function.Filename, ln.Line, l.ID)
  570. }
  571. if !a.function && (ln.Function.Name != "") {
  572. return fmt.Errorf(`found file %s location %d, want ""`,
  573. ln.Function.Name, l.ID)
  574. }
  575. }
  576. }
  577. return nil
  578. }
  579. // Test merge leaves the main binary in place.
  580. func TestMergeMain(t *testing.T) {
  581. prof := testProfile1.Copy()
  582. p1, err := Merge([]*Profile{prof})
  583. if err != nil {
  584. t.Fatalf("merge error: %v", err)
  585. }
  586. if cpuM[0].File != p1.Mapping[0].File {
  587. t.Errorf("want Mapping[0]=%s got %s", cpuM[0].File, p1.Mapping[0].File)
  588. }
  589. }
  590. func TestMerge(t *testing.T) {
  591. // Aggregate a profile with itself and once again with a factor of
  592. // -2. Should end up with an empty profile (all samples for a
  593. // location should add up to 0).
  594. prof := testProfile1.Copy()
  595. prof.Comments = []string{"comment1"}
  596. p1, err := Merge([]*Profile{prof, prof})
  597. if err != nil {
  598. t.Errorf("merge error: %v", err)
  599. }
  600. prof.Scale(-2)
  601. prof, err = Merge([]*Profile{p1, prof})
  602. if err != nil {
  603. t.Errorf("merge error: %v", err)
  604. }
  605. if got, want := len(prof.Comments), 1; got != want {
  606. t.Errorf("len(prof.Comments) = %d, want %d", got, want)
  607. }
  608. // Use aggregation to merge locations at function granularity.
  609. if err := prof.Aggregate(false, true, false, false, false); err != nil {
  610. t.Errorf("aggregating after merge: %v", err)
  611. }
  612. samples := make(map[string]int64)
  613. for _, s := range prof.Sample {
  614. tb := locationHash(s)
  615. samples[tb] = samples[tb] + s.Value[0]
  616. }
  617. for s, v := range samples {
  618. if v != 0 {
  619. t.Errorf("nonzero value for sample %s: %d", s, v)
  620. }
  621. }
  622. }
  623. func TestMergeAll(t *testing.T) {
  624. // Aggregate 10 copies of the profile.
  625. profs := make([]*Profile, 10)
  626. for i := 0; i < 10; i++ {
  627. profs[i] = testProfile1.Copy()
  628. }
  629. prof, err := Merge(profs)
  630. if err != nil {
  631. t.Errorf("merge error: %v", err)
  632. }
  633. samples := make(map[string]int64)
  634. for _, s := range prof.Sample {
  635. tb := locationHash(s)
  636. samples[tb] = samples[tb] + s.Value[0]
  637. }
  638. for _, s := range testProfile1.Sample {
  639. tb := locationHash(s)
  640. if samples[tb] != s.Value[0]*10 {
  641. t.Errorf("merge got wrong value at %s : %d instead of %d", tb, samples[tb], s.Value[0]*10)
  642. }
  643. }
  644. }
  645. func TestIsFoldedMerge(t *testing.T) {
  646. testProfile1Folded := testProfile1.Copy()
  647. testProfile1Folded.Location[0].IsFolded = true
  648. testProfile1Folded.Location[1].IsFolded = true
  649. for _, tc := range []struct {
  650. name string
  651. profs []*Profile
  652. wantLocationLen int
  653. }{
  654. {
  655. name: "folded and non-folded locations not merged",
  656. profs: []*Profile{testProfile1.Copy(), testProfile1Folded.Copy()},
  657. wantLocationLen: 7,
  658. },
  659. {
  660. name: "identical folded locations are merged",
  661. profs: []*Profile{testProfile1Folded.Copy(), testProfile1Folded.Copy()},
  662. wantLocationLen: 5,
  663. },
  664. } {
  665. t.Run(tc.name, func(t *testing.T) {
  666. prof, err := Merge(tc.profs)
  667. if err != nil {
  668. t.Fatalf("merge error: %v", err)
  669. }
  670. if got, want := len(prof.Location), tc.wantLocationLen; got != want {
  671. t.Fatalf("got %d locations, want %d locations", got, want)
  672. }
  673. })
  674. }
  675. }
  676. func TestNumLabelMerge(t *testing.T) {
  677. for _, tc := range []struct {
  678. name string
  679. profs []*Profile
  680. wantNumLabels []map[string][]int64
  681. wantNumUnits []map[string][]string
  682. }{
  683. {
  684. name: "different tag units not merged",
  685. profs: []*Profile{testProfile4.Copy(), testProfile5.Copy()},
  686. wantNumLabels: []map[string][]int64{
  687. {
  688. "key1": {10},
  689. "key2": {30},
  690. },
  691. {
  692. "key1": {10},
  693. "key2": {30},
  694. },
  695. },
  696. wantNumUnits: []map[string][]string{
  697. {
  698. "key1": {"bytes"},
  699. "key2": {"bytes"},
  700. },
  701. {
  702. "key1": {"kilobytes"},
  703. "key2": {"kilobytes"},
  704. },
  705. },
  706. },
  707. } {
  708. t.Run(tc.name, func(t *testing.T) {
  709. prof, err := Merge(tc.profs)
  710. if err != nil {
  711. t.Errorf("merge error: %v", err)
  712. }
  713. if want, got := len(tc.wantNumLabels), len(prof.Sample); want != got {
  714. t.Fatalf("got %d samples, want %d samples", got, want)
  715. }
  716. for i, wantLabels := range tc.wantNumLabels {
  717. numLabels := prof.Sample[i].NumLabel
  718. if !reflect.DeepEqual(wantLabels, numLabels) {
  719. t.Errorf("got numeric labels %v, want %v", numLabels, wantLabels)
  720. }
  721. wantUnits := tc.wantNumUnits[i]
  722. numUnits := prof.Sample[i].NumUnit
  723. if !reflect.DeepEqual(wantUnits, numUnits) {
  724. t.Errorf("got numeric labels %v, want %v", numUnits, wantUnits)
  725. }
  726. }
  727. })
  728. }
  729. }
  730. func TestEmptyMappingMerge(t *testing.T) {
  731. // Aggregate a profile with itself and once again with a factor of
  732. // -2. Should end up with an empty profile (all samples for a
  733. // location should add up to 0).
  734. prof1 := testProfile1.Copy()
  735. prof2 := testProfile1NoMapping.Copy()
  736. p1, err := Merge([]*Profile{prof2, prof1})
  737. if err != nil {
  738. t.Errorf("merge error: %v", err)
  739. }
  740. prof2.Scale(-2)
  741. prof, err := Merge([]*Profile{p1, prof2})
  742. if err != nil {
  743. t.Errorf("merge error: %v", err)
  744. }
  745. // Use aggregation to merge locations at function granularity.
  746. if err := prof.Aggregate(false, true, false, false, false); err != nil {
  747. t.Errorf("aggregating after merge: %v", err)
  748. }
  749. samples := make(map[string]int64)
  750. for _, s := range prof.Sample {
  751. tb := locationHash(s)
  752. samples[tb] = samples[tb] + s.Value[0]
  753. }
  754. for s, v := range samples {
  755. if v != 0 {
  756. t.Errorf("nonzero value for sample %s: %d", s, v)
  757. }
  758. }
  759. }
  760. func TestNormalizeBySameProfile(t *testing.T) {
  761. pb := testProfile1.Copy()
  762. p := testProfile1.Copy()
  763. if err := p.Normalize(pb); err != nil {
  764. t.Fatal(err)
  765. }
  766. for i, s := range p.Sample {
  767. for j, v := range s.Value {
  768. expectedSampleValue := testProfile1.Sample[i].Value[j]
  769. if v != expectedSampleValue {
  770. t.Errorf("For sample %d, value %d want %d got %d", i, j, expectedSampleValue, v)
  771. }
  772. }
  773. }
  774. }
  775. func TestNormalizeByDifferentProfile(t *testing.T) {
  776. p := testProfile1.Copy()
  777. pb := testProfile2.Copy()
  778. if err := p.Normalize(pb); err != nil {
  779. t.Fatal(err)
  780. }
  781. expectedSampleValues := [][]int64{
  782. {19, 1000},
  783. {1, 100},
  784. {0, 10},
  785. {198, 10000},
  786. {0, 1},
  787. }
  788. for i, s := range p.Sample {
  789. for j, v := range s.Value {
  790. if v != expectedSampleValues[i][j] {
  791. t.Errorf("For sample %d, value %d want %d got %d", i, j, expectedSampleValues[i][j], v)
  792. }
  793. }
  794. }
  795. }
  796. func TestNormalizeByMultipleOfSameProfile(t *testing.T) {
  797. pb := testProfile1.Copy()
  798. for i, s := range pb.Sample {
  799. for j, v := range s.Value {
  800. pb.Sample[i].Value[j] = 10 * v
  801. }
  802. }
  803. p := testProfile1.Copy()
  804. err := p.Normalize(pb)
  805. if err != nil {
  806. t.Fatal(err)
  807. }
  808. for i, s := range p.Sample {
  809. for j, v := range s.Value {
  810. expectedSampleValue := 10 * testProfile1.Sample[i].Value[j]
  811. if v != expectedSampleValue {
  812. t.Errorf("For sample %d, value %d, want %d got %d", i, j, expectedSampleValue, v)
  813. }
  814. }
  815. }
  816. }
  817. func TestNormalizeIncompatibleProfiles(t *testing.T) {
  818. p := testProfile1.Copy()
  819. pb := testProfile3.Copy()
  820. if err := p.Normalize(pb); err == nil {
  821. t.Errorf("Expected an error")
  822. }
  823. }
  824. func TestFilter(t *testing.T) {
  825. // Perform several forms of filtering on the test profile.
  826. type filterTestcase struct {
  827. focus, ignore, hide, show *regexp.Regexp
  828. fm, im, hm, hnm bool
  829. }
  830. for tx, tc := range []filterTestcase{
  831. {
  832. fm: true, // nil focus matches every sample
  833. },
  834. {
  835. focus: regexp.MustCompile("notfound"),
  836. },
  837. {
  838. ignore: regexp.MustCompile("foo.c"),
  839. fm: true,
  840. im: true,
  841. },
  842. {
  843. hide: regexp.MustCompile("lib.so"),
  844. fm: true,
  845. hm: true,
  846. },
  847. {
  848. show: regexp.MustCompile("foo.c"),
  849. fm: true,
  850. hnm: true,
  851. },
  852. {
  853. show: regexp.MustCompile("notfound"),
  854. fm: true,
  855. },
  856. } {
  857. prof := *testProfile1.Copy()
  858. gf, gi, gh, gnh := prof.FilterSamplesByName(tc.focus, tc.ignore, tc.hide, tc.show)
  859. if gf != tc.fm {
  860. t.Errorf("Filter #%d, got fm=%v, want %v", tx, gf, tc.fm)
  861. }
  862. if gi != tc.im {
  863. t.Errorf("Filter #%d, got im=%v, want %v", tx, gi, tc.im)
  864. }
  865. if gh != tc.hm {
  866. t.Errorf("Filter #%d, got hm=%v, want %v", tx, gh, tc.hm)
  867. }
  868. if gnh != tc.hnm {
  869. t.Errorf("Filter #%d, got hnm=%v, want %v", tx, gnh, tc.hnm)
  870. }
  871. }
  872. }
  873. func TestTagFilter(t *testing.T) {
  874. // Perform several forms of tag filtering on the test profile.
  875. type filterTestcase struct {
  876. include, exclude *regexp.Regexp
  877. im, em bool
  878. count int
  879. }
  880. countTags := func(p *Profile) map[string]bool {
  881. tags := make(map[string]bool)
  882. for _, s := range p.Sample {
  883. for l := range s.Label {
  884. tags[l] = true
  885. }
  886. for l := range s.NumLabel {
  887. tags[l] = true
  888. }
  889. }
  890. return tags
  891. }
  892. for tx, tc := range []filterTestcase{
  893. {nil, nil, true, false, 3},
  894. {regexp.MustCompile("notfound"), nil, false, false, 0},
  895. {regexp.MustCompile("key1"), nil, true, false, 1},
  896. {nil, regexp.MustCompile("key[12]"), true, true, 1},
  897. } {
  898. prof := testProfile1.Copy()
  899. gim, gem := prof.FilterTagsByName(tc.include, tc.exclude)
  900. if gim != tc.im {
  901. t.Errorf("Filter #%d, got include match=%v, want %v", tx, gim, tc.im)
  902. }
  903. if gem != tc.em {
  904. t.Errorf("Filter #%d, got exclude match=%v, want %v", tx, gem, tc.em)
  905. }
  906. if tags := countTags(prof); len(tags) != tc.count {
  907. t.Errorf("Filter #%d, got %d tags[%v], want %d", tx, len(tags), tags, tc.count)
  908. }
  909. }
  910. }
  911. // locationHash constructs a string to use as a hashkey for a sample, based on its locations
  912. func locationHash(s *Sample) string {
  913. var tb string
  914. for _, l := range s.Location {
  915. for _, ln := range l.Line {
  916. tb = tb + fmt.Sprintf("%s:%d@%d ", ln.Function.Name, ln.Line, l.Address)
  917. }
  918. }
  919. return tb
  920. }
  921. func TestNumLabelUnits(t *testing.T) {
  922. var tagFilterTests = []struct {
  923. desc string
  924. tagVals []map[string][]int64
  925. tagUnits []map[string][]string
  926. wantUnits map[string]string
  927. wantIgnoredUnits map[string][]string
  928. }{
  929. {
  930. "One sample, multiple keys, different specified units",
  931. []map[string][]int64{{"key1": {131072}, "key2": {128}}},
  932. []map[string][]string{{"key1": {"bytes"}, "key2": {"kilobytes"}}},
  933. map[string]string{"key1": "bytes", "key2": "kilobytes"},
  934. map[string][]string{},
  935. },
  936. {
  937. "One sample, one key with one value, unit specified",
  938. []map[string][]int64{{"key1": {8}}},
  939. []map[string][]string{{"key1": {"bytes"}}},
  940. map[string]string{"key1": "bytes"},
  941. map[string][]string{},
  942. },
  943. {
  944. "One sample, one key with one value, empty unit specified",
  945. []map[string][]int64{{"key1": {8}}},
  946. []map[string][]string{{"key1": {""}}},
  947. map[string]string{"key1": "key1"},
  948. map[string][]string{},
  949. },
  950. {
  951. "Key bytes, unit not specified",
  952. []map[string][]int64{{"bytes": {8}}},
  953. []map[string][]string{nil},
  954. map[string]string{"bytes": "bytes"},
  955. map[string][]string{},
  956. },
  957. {
  958. "One sample, one key with one value, unit not specified",
  959. []map[string][]int64{{"kilobytes": {8}}},
  960. []map[string][]string{nil},
  961. map[string]string{"kilobytes": "kilobytes"},
  962. map[string][]string{},
  963. },
  964. {
  965. "Key request, unit not specified",
  966. []map[string][]int64{{"request": {8}}},
  967. []map[string][]string{nil},
  968. map[string]string{"request": "bytes"},
  969. map[string][]string{},
  970. },
  971. {
  972. "Key alignment, unit not specified",
  973. []map[string][]int64{{"alignment": {8}}},
  974. []map[string][]string{nil},
  975. map[string]string{"alignment": "bytes"},
  976. map[string][]string{},
  977. },
  978. {
  979. "One sample, one key with multiple values and two different units",
  980. []map[string][]int64{{"key1": {8, 8}}},
  981. []map[string][]string{{"key1": {"bytes", "kilobytes"}}},
  982. map[string]string{"key1": "bytes"},
  983. map[string][]string{"key1": {"kilobytes"}},
  984. },
  985. {
  986. "One sample, one key with multiple values and three different units",
  987. []map[string][]int64{{"key1": {8, 8}}},
  988. []map[string][]string{{"key1": {"bytes", "megabytes", "kilobytes"}}},
  989. map[string]string{"key1": "bytes"},
  990. map[string][]string{"key1": {"kilobytes", "megabytes"}},
  991. },
  992. {
  993. "Two samples, one key, different units specified",
  994. []map[string][]int64{{"key1": {8}}, {"key1": {8}}},
  995. []map[string][]string{{"key1": {"bytes"}}, {"key1": {"kilobytes"}}},
  996. map[string]string{"key1": "bytes"},
  997. map[string][]string{"key1": {"kilobytes"}},
  998. },
  999. {
  1000. "Keys alignment, request, and bytes have units specified",
  1001. []map[string][]int64{{
  1002. "alignment": {8},
  1003. "request": {8},
  1004. "bytes": {8},
  1005. }},
  1006. []map[string][]string{{
  1007. "alignment": {"seconds"},
  1008. "request": {"minutes"},
  1009. "bytes": {"hours"},
  1010. }},
  1011. map[string]string{
  1012. "alignment": "seconds",
  1013. "request": "minutes",
  1014. "bytes": "hours",
  1015. },
  1016. map[string][]string{},
  1017. },
  1018. }
  1019. for _, test := range tagFilterTests {
  1020. p := &Profile{Sample: make([]*Sample, len(test.tagVals))}
  1021. for i, numLabel := range test.tagVals {
  1022. s := Sample{
  1023. NumLabel: numLabel,
  1024. NumUnit: test.tagUnits[i],
  1025. }
  1026. p.Sample[i] = &s
  1027. }
  1028. units, ignoredUnits := p.NumLabelUnits()
  1029. if !reflect.DeepEqual(test.wantUnits, units) {
  1030. t.Errorf("%s: got %v units, want %v", test.desc, units, test.wantUnits)
  1031. }
  1032. if !reflect.DeepEqual(test.wantIgnoredUnits, ignoredUnits) {
  1033. t.Errorf("%s: got %v ignored units, want %v", test.desc, ignoredUnits, test.wantIgnoredUnits)
  1034. }
  1035. }
  1036. }
  1037. func TestSetMain(t *testing.T) {
  1038. testProfile1.massageMappings()
  1039. if testProfile1.Mapping[0].File != mainBinary {
  1040. t.Errorf("got %s for main", testProfile1.Mapping[0].File)
  1041. }
  1042. }
  1043. // parallel runs n copies of fn in parallel.
  1044. func parallel(n int, fn func()) {
  1045. var wg sync.WaitGroup
  1046. wg.Add(n)
  1047. for i := 0; i < n; i++ {
  1048. go func() {
  1049. fn()
  1050. wg.Done()
  1051. }()
  1052. }
  1053. wg.Wait()
  1054. }
  1055. func TestThreadSafety(t *testing.T) {
  1056. src := testProfile1.Copy()
  1057. parallel(4, func() { src.Copy() })
  1058. parallel(4, func() {
  1059. var b bytes.Buffer
  1060. src.WriteUncompressed(&b)
  1061. })
  1062. parallel(4, func() {
  1063. var b bytes.Buffer
  1064. src.Write(&b)
  1065. })
  1066. }