暫無描述

profile_test.go 32KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328
  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 label 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 TestHasLabel(t *testing.T) {
  849. var testcases = []struct {
  850. desc string
  851. labels map[string][]string
  852. key string
  853. value string
  854. wantHasLabel bool
  855. }{
  856. {
  857. desc: "empty label does not have label",
  858. labels: map[string][]string{},
  859. key: "key",
  860. value: "value",
  861. wantHasLabel: false,
  862. },
  863. {
  864. desc: "label with one key and value has label",
  865. labels: map[string][]string{"key": {"value"}},
  866. key: "key",
  867. value: "value",
  868. wantHasLabel: true,
  869. },
  870. {
  871. desc: "label with one key and value does not have label",
  872. labels: map[string][]string{"key": {"value"}},
  873. key: "key1",
  874. value: "value1",
  875. wantHasLabel: false,
  876. },
  877. {
  878. desc: "label with many keys and values has label",
  879. labels: map[string][]string{
  880. "key1": {"value2", "value1"},
  881. "key2": {"value1", "value2", "value2"},
  882. "key3": {"value1", "value2", "value2"},
  883. },
  884. key: "key1",
  885. value: "value1",
  886. wantHasLabel: true,
  887. },
  888. {
  889. desc: "label with many keys and values does not have label",
  890. labels: map[string][]string{
  891. "key1": {"value2", "value1"},
  892. "key2": {"value1", "value2", "value2"},
  893. "key3": {"value1", "value2", "value2"},
  894. },
  895. key: "key5",
  896. value: "value5",
  897. wantHasLabel: false,
  898. },
  899. }
  900. for _, tc := range testcases {
  901. t.Run(tc.desc, func(t *testing.T) {
  902. sample := &Sample{
  903. Label: tc.labels,
  904. }
  905. if gotHasLabel := sample.HasLabel(tc.key, tc.value); gotHasLabel != tc.wantHasLabel {
  906. t.Errorf("sample.HasLabel(%q, %q) got %v, want %v", tc.key, tc.value, gotHasLabel, tc.wantHasLabel)
  907. }
  908. })
  909. }
  910. }
  911. func TestRemove(t *testing.T) {
  912. var testcases = []struct {
  913. desc string
  914. samples []*Sample
  915. removeKey string
  916. wantLabels []map[string][]string
  917. }{
  918. {
  919. desc: "some samples have label already",
  920. samples: []*Sample{
  921. {
  922. Location: []*Location{cpuL[0]},
  923. Value: []int64{1000},
  924. },
  925. {
  926. Location: []*Location{cpuL[0]},
  927. Value: []int64{1000},
  928. Label: map[string][]string{
  929. "key1": {"value1", "value2", "value3"},
  930. "key2": {"value1"},
  931. },
  932. },
  933. {
  934. Location: []*Location{cpuL[0]},
  935. Value: []int64{1000},
  936. Label: map[string][]string{
  937. "key1": {"value2"},
  938. },
  939. },
  940. },
  941. removeKey: "key1",
  942. wantLabels: []map[string][]string{
  943. {},
  944. {"key2": {"value1"}},
  945. {},
  946. },
  947. },
  948. }
  949. for _, tc := range testcases {
  950. t.Run(tc.desc, func(t *testing.T) {
  951. profile := testProfile1.Copy()
  952. profile.Sample = tc.samples
  953. profile.RemoveLabel(tc.removeKey)
  954. if got, want := len(profile.Sample), len(tc.wantLabels); got != want {
  955. t.Fatalf("got %v samples, want %v samples", got, want)
  956. }
  957. for i, sample := range profile.Sample {
  958. wantLabels := tc.wantLabels[i]
  959. if got, want := len(sample.Label), len(wantLabels); got != want {
  960. t.Errorf("got %v label keys for sample %v, want %v", got, i, want)
  961. continue
  962. }
  963. for wantKey, wantValues := range wantLabels {
  964. if gotValues, ok := sample.Label[wantKey]; ok {
  965. if !reflect.DeepEqual(gotValues, wantValues) {
  966. t.Errorf("for key %s, got values %v, want values %v", wantKey, gotValues, wantValues)
  967. }
  968. } else {
  969. t.Errorf("for key %s got no values, want %v", wantKey, wantValues)
  970. }
  971. }
  972. }
  973. })
  974. }
  975. }
  976. func TestSetLabel(t *testing.T) {
  977. var testcases = []struct {
  978. desc string
  979. samples []*Sample
  980. setKey string
  981. setVal []string
  982. wantLabels []map[string][]string
  983. }{
  984. {
  985. desc: "some samples have label already",
  986. samples: []*Sample{
  987. {
  988. Location: []*Location{cpuL[0]},
  989. Value: []int64{1000},
  990. },
  991. {
  992. Location: []*Location{cpuL[0]},
  993. Value: []int64{1000},
  994. Label: map[string][]string{
  995. "key1": {"value1", "value2", "value3"},
  996. "key2": {"value1"},
  997. },
  998. },
  999. {
  1000. Location: []*Location{cpuL[0]},
  1001. Value: []int64{1000},
  1002. Label: map[string][]string{
  1003. "key1": {"value2"},
  1004. },
  1005. },
  1006. },
  1007. setKey: "key1",
  1008. setVal: []string{"value1"},
  1009. wantLabels: []map[string][]string{
  1010. {"key1": {"value1"}},
  1011. {"key1": {"value1"}, "key2": {"value1"}},
  1012. {"key1": {"value1"}},
  1013. },
  1014. },
  1015. {
  1016. desc: "no samples have labels",
  1017. samples: []*Sample{
  1018. {
  1019. Location: []*Location{cpuL[0]},
  1020. Value: []int64{1000},
  1021. },
  1022. },
  1023. setKey: "key1",
  1024. setVal: []string{"value1"},
  1025. wantLabels: []map[string][]string{
  1026. {"key1": {"value1"}},
  1027. },
  1028. },
  1029. {
  1030. desc: "all samples have some labels, but not key being added",
  1031. samples: []*Sample{
  1032. {
  1033. Location: []*Location{cpuL[0]},
  1034. Value: []int64{1000},
  1035. Label: map[string][]string{
  1036. "key2": {"value2"},
  1037. },
  1038. },
  1039. {
  1040. Location: []*Location{cpuL[0]},
  1041. Value: []int64{1000},
  1042. Label: map[string][]string{
  1043. "key3": {"value3"},
  1044. },
  1045. },
  1046. },
  1047. setKey: "key1",
  1048. setVal: []string{"value1"},
  1049. wantLabels: []map[string][]string{
  1050. {"key1": {"value1"}, "key2": {"value2"}},
  1051. {"key1": {"value1"}, "key3": {"value3"}},
  1052. },
  1053. },
  1054. {
  1055. desc: "all samples have key being added",
  1056. samples: []*Sample{
  1057. {
  1058. Location: []*Location{cpuL[0]},
  1059. Value: []int64{1000},
  1060. Label: map[string][]string{
  1061. "key1": {"value1"},
  1062. },
  1063. },
  1064. {
  1065. Location: []*Location{cpuL[0]},
  1066. Value: []int64{1000},
  1067. Label: map[string][]string{
  1068. "key1": {"value1"},
  1069. },
  1070. },
  1071. },
  1072. setKey: "key1",
  1073. setVal: []string{"value1"},
  1074. wantLabels: []map[string][]string{
  1075. {"key1": {"value1"}},
  1076. {"key1": {"value1"}},
  1077. },
  1078. },
  1079. }
  1080. for _, tc := range testcases {
  1081. t.Run(tc.desc, func(t *testing.T) {
  1082. profile := testProfile1.Copy()
  1083. profile.Sample = tc.samples
  1084. profile.SetLabel(tc.setKey, tc.setVal)
  1085. if got, want := len(profile.Sample), len(tc.wantLabels); got != want {
  1086. t.Fatalf("got %v samples, want %v samples", got, want)
  1087. }
  1088. for i, sample := range profile.Sample {
  1089. wantLabels := tc.wantLabels[i]
  1090. if got, want := len(sample.Label), len(wantLabels); got != want {
  1091. t.Errorf("got %v label keys for sample %v, want %v", got, i, want)
  1092. continue
  1093. }
  1094. for wantKey, wantValues := range wantLabels {
  1095. if gotValues, ok := sample.Label[wantKey]; ok {
  1096. if !reflect.DeepEqual(gotValues, wantValues) {
  1097. t.Errorf("for key %s, got values %v, want values %v", wantKey, gotValues, wantValues)
  1098. }
  1099. } else {
  1100. t.Errorf("for key %s got no values, want %v", wantKey, wantValues)
  1101. }
  1102. }
  1103. }
  1104. })
  1105. }
  1106. }
  1107. func TestNumLabelUnits(t *testing.T) {
  1108. var tagFilterTests = []struct {
  1109. desc string
  1110. tagVals []map[string][]int64
  1111. tagUnits []map[string][]string
  1112. wantUnits map[string]string
  1113. wantIgnoredUnits map[string][]string
  1114. }{
  1115. {
  1116. "One sample, multiple keys, different specified units",
  1117. []map[string][]int64{{"key1": {131072}, "key2": {128}}},
  1118. []map[string][]string{{"key1": {"bytes"}, "key2": {"kilobytes"}}},
  1119. map[string]string{"key1": "bytes", "key2": "kilobytes"},
  1120. map[string][]string{},
  1121. },
  1122. {
  1123. "One sample, one key with one value, unit specified",
  1124. []map[string][]int64{{"key1": {8}}},
  1125. []map[string][]string{{"key1": {"bytes"}}},
  1126. map[string]string{"key1": "bytes"},
  1127. map[string][]string{},
  1128. },
  1129. {
  1130. "One sample, one key with one value, empty unit specified",
  1131. []map[string][]int64{{"key1": {8}}},
  1132. []map[string][]string{{"key1": {""}}},
  1133. map[string]string{"key1": "key1"},
  1134. map[string][]string{},
  1135. },
  1136. {
  1137. "Key bytes, unit not specified",
  1138. []map[string][]int64{{"bytes": {8}}},
  1139. []map[string][]string{nil},
  1140. map[string]string{"bytes": "bytes"},
  1141. map[string][]string{},
  1142. },
  1143. {
  1144. "One sample, one key with one value, unit not specified",
  1145. []map[string][]int64{{"kilobytes": {8}}},
  1146. []map[string][]string{nil},
  1147. map[string]string{"kilobytes": "kilobytes"},
  1148. map[string][]string{},
  1149. },
  1150. {
  1151. "Key request, unit not specified",
  1152. []map[string][]int64{{"request": {8}}},
  1153. []map[string][]string{nil},
  1154. map[string]string{"request": "bytes"},
  1155. map[string][]string{},
  1156. },
  1157. {
  1158. "Key alignment, unit not specified",
  1159. []map[string][]int64{{"alignment": {8}}},
  1160. []map[string][]string{nil},
  1161. map[string]string{"alignment": "bytes"},
  1162. map[string][]string{},
  1163. },
  1164. {
  1165. "One sample, one key with multiple values and two different units",
  1166. []map[string][]int64{{"key1": {8, 8}}},
  1167. []map[string][]string{{"key1": {"bytes", "kilobytes"}}},
  1168. map[string]string{"key1": "bytes"},
  1169. map[string][]string{"key1": {"kilobytes"}},
  1170. },
  1171. {
  1172. "One sample, one key with multiple values and three different units",
  1173. []map[string][]int64{{"key1": {8, 8}}},
  1174. []map[string][]string{{"key1": {"bytes", "megabytes", "kilobytes"}}},
  1175. map[string]string{"key1": "bytes"},
  1176. map[string][]string{"key1": {"kilobytes", "megabytes"}},
  1177. },
  1178. {
  1179. "Two samples, one key, different units specified",
  1180. []map[string][]int64{{"key1": {8}}, {"key1": {8}}},
  1181. []map[string][]string{{"key1": {"bytes"}}, {"key1": {"kilobytes"}}},
  1182. map[string]string{"key1": "bytes"},
  1183. map[string][]string{"key1": {"kilobytes"}},
  1184. },
  1185. {
  1186. "Keys alignment, request, and bytes have units specified",
  1187. []map[string][]int64{{
  1188. "alignment": {8},
  1189. "request": {8},
  1190. "bytes": {8},
  1191. }},
  1192. []map[string][]string{{
  1193. "alignment": {"seconds"},
  1194. "request": {"minutes"},
  1195. "bytes": {"hours"},
  1196. }},
  1197. map[string]string{
  1198. "alignment": "seconds",
  1199. "request": "minutes",
  1200. "bytes": "hours",
  1201. },
  1202. map[string][]string{},
  1203. },
  1204. }
  1205. for _, test := range tagFilterTests {
  1206. p := &Profile{Sample: make([]*Sample, len(test.tagVals))}
  1207. for i, numLabel := range test.tagVals {
  1208. s := Sample{
  1209. NumLabel: numLabel,
  1210. NumUnit: test.tagUnits[i],
  1211. }
  1212. p.Sample[i] = &s
  1213. }
  1214. units, ignoredUnits := p.NumLabelUnits()
  1215. if !reflect.DeepEqual(test.wantUnits, units) {
  1216. t.Errorf("%s: got %v units, want %v", test.desc, units, test.wantUnits)
  1217. }
  1218. if !reflect.DeepEqual(test.wantIgnoredUnits, ignoredUnits) {
  1219. t.Errorf("%s: got %v ignored units, want %v", test.desc, ignoredUnits, test.wantIgnoredUnits)
  1220. }
  1221. }
  1222. }
  1223. func TestSetMain(t *testing.T) {
  1224. testProfile1.massageMappings()
  1225. if testProfile1.Mapping[0].File != mainBinary {
  1226. t.Errorf("got %s for main", testProfile1.Mapping[0].File)
  1227. }
  1228. }
  1229. // parallel runs n copies of fn in parallel.
  1230. func parallel(n int, fn func()) {
  1231. var wg sync.WaitGroup
  1232. wg.Add(n)
  1233. for i := 0; i < n; i++ {
  1234. go func() {
  1235. fn()
  1236. wg.Done()
  1237. }()
  1238. }
  1239. wg.Wait()
  1240. }
  1241. func TestThreadSafety(t *testing.T) {
  1242. src := testProfile1.Copy()
  1243. parallel(4, func() { src.Copy() })
  1244. parallel(4, func() {
  1245. var b bytes.Buffer
  1246. src.WriteUncompressed(&b)
  1247. })
  1248. parallel(4, func() {
  1249. var b bytes.Buffer
  1250. src.Write(&b)
  1251. })
  1252. }