No Description

profile_test.go 25KB

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