暂无描述

profile_test.go 27KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139
  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. p1, err := Merge([]*Profile{prof, prof})
  596. if err != nil {
  597. t.Errorf("merge error: %v", err)
  598. }
  599. prof.Scale(-2)
  600. prof, err = Merge([]*Profile{p1, prof})
  601. if err != nil {
  602. t.Errorf("merge error: %v", err)
  603. }
  604. // Use aggregation to merge locations at function granularity.
  605. if err := prof.Aggregate(false, true, false, false, false); err != nil {
  606. t.Errorf("aggregating after merge: %v", err)
  607. }
  608. samples := make(map[string]int64)
  609. for _, s := range prof.Sample {
  610. tb := locationHash(s)
  611. samples[tb] = samples[tb] + s.Value[0]
  612. }
  613. for s, v := range samples {
  614. if v != 0 {
  615. t.Errorf("nonzero value for sample %s: %d", s, v)
  616. }
  617. }
  618. }
  619. func TestMergeAll(t *testing.T) {
  620. // Aggregate 10 copies of the profile.
  621. profs := make([]*Profile, 10)
  622. for i := 0; i < 10; i++ {
  623. profs[i] = testProfile1.Copy()
  624. }
  625. prof, err := Merge(profs)
  626. if err != nil {
  627. t.Errorf("merge error: %v", err)
  628. }
  629. samples := make(map[string]int64)
  630. for _, s := range prof.Sample {
  631. tb := locationHash(s)
  632. samples[tb] = samples[tb] + s.Value[0]
  633. }
  634. for _, s := range testProfile1.Sample {
  635. tb := locationHash(s)
  636. if samples[tb] != s.Value[0]*10 {
  637. t.Errorf("merge got wrong value at %s : %d instead of %d", tb, samples[tb], s.Value[0]*10)
  638. }
  639. }
  640. }
  641. func TestIsFoldedMerge(t *testing.T) {
  642. testProfile1Folded := testProfile1.Copy()
  643. testProfile1Folded.Location[0].IsFolded = true
  644. testProfile1Folded.Location[1].IsFolded = true
  645. for _, tc := range []struct {
  646. name string
  647. profs []*Profile
  648. wantLocationLen int
  649. }{
  650. {
  651. name: "folded and non-folded locations not merged",
  652. profs: []*Profile{testProfile1.Copy(), testProfile1Folded.Copy()},
  653. wantLocationLen: 7,
  654. },
  655. {
  656. name: "identical folded locations are merged",
  657. profs: []*Profile{testProfile1Folded.Copy(), testProfile1Folded.Copy()},
  658. wantLocationLen: 5,
  659. },
  660. } {
  661. t.Run(tc.name, func(t *testing.T) {
  662. prof, err := Merge(tc.profs)
  663. if err != nil {
  664. t.Fatalf("merge error: %v", err)
  665. }
  666. if got, want := len(prof.Location), tc.wantLocationLen; got != want {
  667. t.Fatalf("got %d locations, want %d locations", got, want)
  668. }
  669. })
  670. }
  671. }
  672. func TestNumLabelMerge(t *testing.T) {
  673. for _, tc := range []struct {
  674. name string
  675. profs []*Profile
  676. wantNumLabels []map[string][]int64
  677. wantNumUnits []map[string][]string
  678. }{
  679. {
  680. name: "different tag units not merged",
  681. profs: []*Profile{testProfile4.Copy(), testProfile5.Copy()},
  682. wantNumLabels: []map[string][]int64{
  683. {
  684. "key1": {10},
  685. "key2": {30},
  686. },
  687. {
  688. "key1": {10},
  689. "key2": {30},
  690. },
  691. },
  692. wantNumUnits: []map[string][]string{
  693. {
  694. "key1": {"bytes"},
  695. "key2": {"bytes"},
  696. },
  697. {
  698. "key1": {"kilobytes"},
  699. "key2": {"kilobytes"},
  700. },
  701. },
  702. },
  703. } {
  704. t.Run(tc.name, func(t *testing.T) {
  705. prof, err := Merge(tc.profs)
  706. if err != nil {
  707. t.Errorf("merge error: %v", err)
  708. }
  709. if want, got := len(tc.wantNumLabels), len(prof.Sample); want != got {
  710. t.Fatalf("got %d samples, want %d samples", got, want)
  711. }
  712. for i, wantLabels := range tc.wantNumLabels {
  713. numLabels := prof.Sample[i].NumLabel
  714. if !reflect.DeepEqual(wantLabels, numLabels) {
  715. t.Errorf("got numeric labels %v, want %v", numLabels, wantLabels)
  716. }
  717. wantUnits := tc.wantNumUnits[i]
  718. numUnits := prof.Sample[i].NumUnit
  719. if !reflect.DeepEqual(wantUnits, numUnits) {
  720. t.Errorf("got numeric labels %v, want %v", numUnits, wantUnits)
  721. }
  722. }
  723. })
  724. }
  725. }
  726. func TestEmptyMappingMerge(t *testing.T) {
  727. // Aggregate a profile with itself and once again with a factor of
  728. // -2. Should end up with an empty profile (all samples for a
  729. // location should add up to 0).
  730. prof1 := testProfile1.Copy()
  731. prof2 := testProfile1NoMapping.Copy()
  732. p1, err := Merge([]*Profile{prof2, prof1})
  733. if err != nil {
  734. t.Errorf("merge error: %v", err)
  735. }
  736. prof2.Scale(-2)
  737. prof, err := Merge([]*Profile{p1, prof2})
  738. if err != nil {
  739. t.Errorf("merge error: %v", err)
  740. }
  741. // Use aggregation to merge locations at function granularity.
  742. if err := prof.Aggregate(false, true, false, false, false); err != nil {
  743. t.Errorf("aggregating after merge: %v", err)
  744. }
  745. samples := make(map[string]int64)
  746. for _, s := range prof.Sample {
  747. tb := locationHash(s)
  748. samples[tb] = samples[tb] + s.Value[0]
  749. }
  750. for s, v := range samples {
  751. if v != 0 {
  752. t.Errorf("nonzero value for sample %s: %d", s, v)
  753. }
  754. }
  755. }
  756. func TestNormalizeBySameProfile(t *testing.T) {
  757. pb := testProfile1.Copy()
  758. p := testProfile1.Copy()
  759. if err := p.Normalize(pb); err != nil {
  760. t.Fatal(err)
  761. }
  762. for i, s := range p.Sample {
  763. for j, v := range s.Value {
  764. expectedSampleValue := testProfile1.Sample[i].Value[j]
  765. if v != expectedSampleValue {
  766. t.Errorf("For sample %d, value %d want %d got %d", i, j, expectedSampleValue, v)
  767. }
  768. }
  769. }
  770. }
  771. func TestNormalizeByDifferentProfile(t *testing.T) {
  772. p := testProfile1.Copy()
  773. pb := testProfile2.Copy()
  774. if err := p.Normalize(pb); err != nil {
  775. t.Fatal(err)
  776. }
  777. expectedSampleValues := [][]int64{
  778. {19, 1000},
  779. {1, 100},
  780. {0, 10},
  781. {198, 10000},
  782. {0, 1},
  783. }
  784. for i, s := range p.Sample {
  785. for j, v := range s.Value {
  786. if v != expectedSampleValues[i][j] {
  787. t.Errorf("For sample %d, value %d want %d got %d", i, j, expectedSampleValues[i][j], v)
  788. }
  789. }
  790. }
  791. }
  792. func TestNormalizeByMultipleOfSameProfile(t *testing.T) {
  793. pb := testProfile1.Copy()
  794. for i, s := range pb.Sample {
  795. for j, v := range s.Value {
  796. pb.Sample[i].Value[j] = 10 * v
  797. }
  798. }
  799. p := testProfile1.Copy()
  800. err := p.Normalize(pb)
  801. if err != nil {
  802. t.Fatal(err)
  803. }
  804. for i, s := range p.Sample {
  805. for j, v := range s.Value {
  806. expectedSampleValue := 10 * testProfile1.Sample[i].Value[j]
  807. if v != expectedSampleValue {
  808. t.Errorf("For sample %d, value %d, want %d got %d", i, j, expectedSampleValue, v)
  809. }
  810. }
  811. }
  812. }
  813. func TestNormalizeIncompatibleProfiles(t *testing.T) {
  814. p := testProfile1.Copy()
  815. pb := testProfile3.Copy()
  816. if err := p.Normalize(pb); err == nil {
  817. t.Errorf("Expected an error")
  818. }
  819. }
  820. func TestFilter(t *testing.T) {
  821. // Perform several forms of filtering on the test profile.
  822. type filterTestcase struct {
  823. focus, ignore, hide, show *regexp.Regexp
  824. fm, im, hm, hnm bool
  825. }
  826. for tx, tc := range []filterTestcase{
  827. {
  828. fm: true, // nil focus matches every sample
  829. },
  830. {
  831. focus: regexp.MustCompile("notfound"),
  832. },
  833. {
  834. ignore: regexp.MustCompile("foo.c"),
  835. fm: true,
  836. im: true,
  837. },
  838. {
  839. hide: regexp.MustCompile("lib.so"),
  840. fm: true,
  841. hm: true,
  842. },
  843. {
  844. show: regexp.MustCompile("foo.c"),
  845. fm: true,
  846. hnm: true,
  847. },
  848. {
  849. show: regexp.MustCompile("notfound"),
  850. fm: true,
  851. },
  852. } {
  853. prof := *testProfile1.Copy()
  854. gf, gi, gh, gnh := prof.FilterSamplesByName(tc.focus, tc.ignore, tc.hide, tc.show)
  855. if gf != tc.fm {
  856. t.Errorf("Filter #%d, got fm=%v, want %v", tx, gf, tc.fm)
  857. }
  858. if gi != tc.im {
  859. t.Errorf("Filter #%d, got im=%v, want %v", tx, gi, tc.im)
  860. }
  861. if gh != tc.hm {
  862. t.Errorf("Filter #%d, got hm=%v, want %v", tx, gh, tc.hm)
  863. }
  864. if gnh != tc.hnm {
  865. t.Errorf("Filter #%d, got hnm=%v, want %v", tx, gnh, tc.hnm)
  866. }
  867. }
  868. }
  869. func TestTagFilter(t *testing.T) {
  870. // Perform several forms of tag filtering on the test profile.
  871. type filterTestcase struct {
  872. include, exclude *regexp.Regexp
  873. im, em bool
  874. count int
  875. }
  876. countTags := func(p *Profile) map[string]bool {
  877. tags := make(map[string]bool)
  878. for _, s := range p.Sample {
  879. for l := range s.Label {
  880. tags[l] = true
  881. }
  882. for l := range s.NumLabel {
  883. tags[l] = true
  884. }
  885. }
  886. return tags
  887. }
  888. for tx, tc := range []filterTestcase{
  889. {nil, nil, true, false, 3},
  890. {regexp.MustCompile("notfound"), nil, false, false, 0},
  891. {regexp.MustCompile("key1"), nil, true, false, 1},
  892. {nil, regexp.MustCompile("key[12]"), true, true, 1},
  893. } {
  894. prof := testProfile1.Copy()
  895. gim, gem := prof.FilterTagsByName(tc.include, tc.exclude)
  896. if gim != tc.im {
  897. t.Errorf("Filter #%d, got include match=%v, want %v", tx, gim, tc.im)
  898. }
  899. if gem != tc.em {
  900. t.Errorf("Filter #%d, got exclude match=%v, want %v", tx, gem, tc.em)
  901. }
  902. if tags := countTags(prof); len(tags) != tc.count {
  903. t.Errorf("Filter #%d, got %d tags[%v], want %d", tx, len(tags), tags, tc.count)
  904. }
  905. }
  906. }
  907. // locationHash constructs a string to use as a hashkey for a sample, based on its locations
  908. func locationHash(s *Sample) string {
  909. var tb string
  910. for _, l := range s.Location {
  911. for _, ln := range l.Line {
  912. tb = tb + fmt.Sprintf("%s:%d@%d ", ln.Function.Name, ln.Line, l.Address)
  913. }
  914. }
  915. return tb
  916. }
  917. func TestNumLabelUnits(t *testing.T) {
  918. var tagFilterTests = []struct {
  919. desc string
  920. tagVals []map[string][]int64
  921. tagUnits []map[string][]string
  922. wantUnits map[string]string
  923. wantIgnoredUnits map[string][]string
  924. }{
  925. {
  926. "One sample, multiple keys, different specified units",
  927. []map[string][]int64{{"key1": {131072}, "key2": {128}}},
  928. []map[string][]string{{"key1": {"bytes"}, "key2": {"kilobytes"}}},
  929. map[string]string{"key1": "bytes", "key2": "kilobytes"},
  930. map[string][]string{},
  931. },
  932. {
  933. "One sample, one key with one value, unit specified",
  934. []map[string][]int64{{"key1": {8}}},
  935. []map[string][]string{{"key1": {"bytes"}}},
  936. map[string]string{"key1": "bytes"},
  937. map[string][]string{},
  938. },
  939. {
  940. "One sample, one key with one value, empty unit specified",
  941. []map[string][]int64{{"key1": {8}}},
  942. []map[string][]string{{"key1": {""}}},
  943. map[string]string{"key1": "key1"},
  944. map[string][]string{},
  945. },
  946. {
  947. "Key bytes, unit not specified",
  948. []map[string][]int64{{"bytes": {8}}},
  949. []map[string][]string{nil},
  950. map[string]string{"bytes": "bytes"},
  951. map[string][]string{},
  952. },
  953. {
  954. "One sample, one key with one value, unit not specified",
  955. []map[string][]int64{{"kilobytes": {8}}},
  956. []map[string][]string{nil},
  957. map[string]string{"kilobytes": "kilobytes"},
  958. map[string][]string{},
  959. },
  960. {
  961. "Key request, unit not specified",
  962. []map[string][]int64{{"request": {8}}},
  963. []map[string][]string{nil},
  964. map[string]string{"request": "bytes"},
  965. map[string][]string{},
  966. },
  967. {
  968. "Key alignment, unit not specified",
  969. []map[string][]int64{{"alignment": {8}}},
  970. []map[string][]string{nil},
  971. map[string]string{"alignment": "bytes"},
  972. map[string][]string{},
  973. },
  974. {
  975. "One sample, one key with multiple values and two different units",
  976. []map[string][]int64{{"key1": {8, 8}}},
  977. []map[string][]string{{"key1": {"bytes", "kilobytes"}}},
  978. map[string]string{"key1": "bytes"},
  979. map[string][]string{"key1": {"kilobytes"}},
  980. },
  981. {
  982. "One sample, one key with multiple values and three different units",
  983. []map[string][]int64{{"key1": {8, 8}}},
  984. []map[string][]string{{"key1": {"bytes", "megabytes", "kilobytes"}}},
  985. map[string]string{"key1": "bytes"},
  986. map[string][]string{"key1": {"kilobytes", "megabytes"}},
  987. },
  988. {
  989. "Two samples, one key, different units specified",
  990. []map[string][]int64{{"key1": {8}}, {"key1": {8}}},
  991. []map[string][]string{{"key1": {"bytes"}}, {"key1": {"kilobytes"}}},
  992. map[string]string{"key1": "bytes"},
  993. map[string][]string{"key1": {"kilobytes"}},
  994. },
  995. {
  996. "Keys alignment, request, and bytes have units specified",
  997. []map[string][]int64{{
  998. "alignment": {8},
  999. "request": {8},
  1000. "bytes": {8},
  1001. }},
  1002. []map[string][]string{{
  1003. "alignment": {"seconds"},
  1004. "request": {"minutes"},
  1005. "bytes": {"hours"},
  1006. }},
  1007. map[string]string{
  1008. "alignment": "seconds",
  1009. "request": "minutes",
  1010. "bytes": "hours",
  1011. },
  1012. map[string][]string{},
  1013. },
  1014. }
  1015. for _, test := range tagFilterTests {
  1016. p := &Profile{Sample: make([]*Sample, len(test.tagVals))}
  1017. for i, numLabel := range test.tagVals {
  1018. s := Sample{
  1019. NumLabel: numLabel,
  1020. NumUnit: test.tagUnits[i],
  1021. }
  1022. p.Sample[i] = &s
  1023. }
  1024. units, ignoredUnits := p.NumLabelUnits()
  1025. if !reflect.DeepEqual(test.wantUnits, units) {
  1026. t.Errorf("%s: got %v units, want %v", test.desc, units, test.wantUnits)
  1027. }
  1028. if !reflect.DeepEqual(test.wantIgnoredUnits, ignoredUnits) {
  1029. t.Errorf("%s: got %v ignored units, want %v", test.desc, ignoredUnits, test.wantIgnoredUnits)
  1030. }
  1031. }
  1032. }
  1033. func TestSetMain(t *testing.T) {
  1034. testProfile1.massageMappings()
  1035. if testProfile1.Mapping[0].File != mainBinary {
  1036. t.Errorf("got %s for main", testProfile1.Mapping[0].File)
  1037. }
  1038. }
  1039. // parallel runs n copies of fn in parallel.
  1040. func parallel(n int, fn func()) {
  1041. var wg sync.WaitGroup
  1042. wg.Add(n)
  1043. for i := 0; i < n; i++ {
  1044. go func() {
  1045. fn()
  1046. wg.Done()
  1047. }()
  1048. }
  1049. wg.Wait()
  1050. }
  1051. func TestThreadSafety(t *testing.T) {
  1052. src := testProfile1.Copy()
  1053. parallel(4, func() { src.Copy() })
  1054. parallel(4, func() {
  1055. var b bytes.Buffer
  1056. src.WriteUncompressed(&b)
  1057. })
  1058. parallel(4, func() {
  1059. var b bytes.Buffer
  1060. src.Write(&b)
  1061. })
  1062. }