Nav apraksta

profile_test.go 28KB

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