暂无描述

profile.go 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613
  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 provides a representation of profile.proto and
  15. // methods to encode/decode profiles in this format.
  16. package profile
  17. import (
  18. "bytes"
  19. "compress/gzip"
  20. "fmt"
  21. "io"
  22. "io/ioutil"
  23. "path/filepath"
  24. "regexp"
  25. "sort"
  26. "strings"
  27. "time"
  28. )
  29. // Profile is an in-memory representation of profile.proto.
  30. type Profile struct {
  31. SampleType []*ValueType
  32. DefaultSampleType string
  33. Sample []*Sample
  34. Mapping []*Mapping
  35. Location []*Location
  36. Function []*Function
  37. Comments []string
  38. DropFrames string
  39. KeepFrames string
  40. TimeNanos int64
  41. DurationNanos int64
  42. PeriodType *ValueType
  43. Period int64
  44. commentX []int64
  45. dropFramesX int64
  46. keepFramesX int64
  47. stringTable []string
  48. defaultSampleTypeX int64
  49. }
  50. // ValueType corresponds to Profile.ValueType
  51. type ValueType struct {
  52. Type string // cpu, wall, inuse_space, etc
  53. Unit string // seconds, nanoseconds, bytes, etc
  54. typeX int64
  55. unitX int64
  56. }
  57. // Sample corresponds to Profile.Sample
  58. type Sample struct {
  59. Location []*Location
  60. Value []int64
  61. Label map[string][]string
  62. NumLabel map[string][]int64
  63. locationIDX []uint64
  64. labelX []label
  65. }
  66. // label corresponds to Profile.Label
  67. type label struct {
  68. keyX int64
  69. // Exactly one of the two following values must be set
  70. strX int64
  71. numX int64 // Integer value for this label
  72. }
  73. // Mapping corresponds to Profile.Mapping
  74. type Mapping struct {
  75. ID uint64
  76. Start uint64
  77. Limit uint64
  78. Offset uint64
  79. File string
  80. BuildID string
  81. HasFunctions bool
  82. HasFilenames bool
  83. HasLineNumbers bool
  84. HasInlineFrames bool
  85. fileX int64
  86. buildIDX int64
  87. }
  88. // Location corresponds to Profile.Location
  89. type Location struct {
  90. ID uint64
  91. Mapping *Mapping
  92. Address uint64
  93. Line []Line
  94. mappingIDX uint64
  95. }
  96. // Line corresponds to Profile.Line
  97. type Line struct {
  98. Function *Function
  99. Line int64
  100. functionIDX uint64
  101. }
  102. // Function corresponds to Profile.Function
  103. type Function struct {
  104. ID uint64
  105. Name string
  106. SystemName string
  107. Filename string
  108. StartLine int64
  109. nameX int64
  110. systemNameX int64
  111. filenameX int64
  112. }
  113. // Parse parses a profile and checks for its validity. The input
  114. // may be a gzip-compressed encoded protobuf or one of many legacy
  115. // profile formats which may be unsupported in the future.
  116. func Parse(r io.Reader) (*Profile, error) {
  117. data, err := ioutil.ReadAll(r)
  118. if err != nil {
  119. return nil, err
  120. }
  121. return ParseData(data)
  122. }
  123. // ParseData parses a profile from a buffer and checks for its
  124. // validity.
  125. func ParseData(data []byte) (*Profile, error) {
  126. var p *Profile
  127. var err error
  128. if len(data) >= 2 && data[0] == 0x1f && data[1] == 0x8b {
  129. gz, err := gzip.NewReader(bytes.NewBuffer(data))
  130. if err == nil {
  131. data, err = ioutil.ReadAll(gz)
  132. }
  133. if err != nil {
  134. return nil, fmt.Errorf("decompressing profile: %v", err)
  135. }
  136. }
  137. if p, err = ParseUncompressed(data); err != nil {
  138. if p, err = parseLegacy(data); err != nil {
  139. return nil, fmt.Errorf("parsing profile: %v", err)
  140. }
  141. }
  142. if err := p.CheckValid(); err != nil {
  143. return nil, fmt.Errorf("malformed profile: %v", err)
  144. }
  145. return p, nil
  146. }
  147. var errUnrecognized = fmt.Errorf("unrecognized profile format")
  148. var errMalformed = fmt.Errorf("malformed profile format")
  149. func parseLegacy(data []byte) (*Profile, error) {
  150. parsers := []func([]byte) (*Profile, error){
  151. parseCPU,
  152. parseHeap,
  153. parseGoCount, // goroutine, threadcreate
  154. parseThread,
  155. parseContention,
  156. parseJavaProfile,
  157. }
  158. for _, parser := range parsers {
  159. p, err := parser(data)
  160. if err == nil {
  161. p.addLegacyFrameInfo()
  162. return p, nil
  163. }
  164. if err != errUnrecognized {
  165. return nil, err
  166. }
  167. }
  168. return nil, errUnrecognized
  169. }
  170. // ParseUncompressed parses an uncompressed protobuf into a profile.
  171. func ParseUncompressed(data []byte) (*Profile, error) {
  172. p := &Profile{}
  173. if err := unmarshal(data, p); err != nil {
  174. return nil, err
  175. }
  176. if err := p.postDecode(); err != nil {
  177. return nil, err
  178. }
  179. return p, nil
  180. }
  181. var libRx = regexp.MustCompile(`([.]so$|[.]so[._][0-9]+)`)
  182. // massageMappings applies heuristic-based changes to the profile
  183. // mappings to account for quirks of some environments.
  184. func (p *Profile) massageMappings() {
  185. // Merge adjacent regions with matching names, checking that the offsets match
  186. if len(p.Mapping) > 1 {
  187. mappings := []*Mapping{p.Mapping[0]}
  188. for _, m := range p.Mapping[1:] {
  189. lm := mappings[len(mappings)-1]
  190. if adjacent(lm, m) {
  191. lm.Limit = m.Limit
  192. if m.File != "" {
  193. lm.File = m.File
  194. }
  195. if m.BuildID != "" {
  196. lm.BuildID = m.BuildID
  197. }
  198. p.updateLocationMapping(m, lm)
  199. continue
  200. }
  201. mappings = append(mappings, m)
  202. }
  203. p.Mapping = mappings
  204. }
  205. // Use heuristics to identify main binary and move it to the top of the list of mappings
  206. for i, m := range p.Mapping {
  207. file := strings.TrimSpace(strings.Replace(m.File, "(deleted)", "", -1))
  208. if len(file) == 0 {
  209. continue
  210. }
  211. if len(libRx.FindStringSubmatch(file)) > 0 {
  212. continue
  213. }
  214. if file[0] == '[' {
  215. continue
  216. }
  217. // Swap what we guess is main to position 0.
  218. p.Mapping[0], p.Mapping[i] = p.Mapping[i], p.Mapping[0]
  219. break
  220. }
  221. // Keep the mapping IDs neatly sorted
  222. for i, m := range p.Mapping {
  223. m.ID = uint64(i + 1)
  224. }
  225. }
  226. // adjacent returns whether two mapping entries represent the same
  227. // mapping that has been split into two. Check that their addresses are adjacent,
  228. // and if the offsets match, if they are available.
  229. func adjacent(m1, m2 *Mapping) bool {
  230. if m1.File != "" && m2.File != "" {
  231. if m1.File != m2.File {
  232. return false
  233. }
  234. }
  235. if m1.BuildID != "" && m2.BuildID != "" {
  236. if m1.BuildID != m2.BuildID {
  237. return false
  238. }
  239. }
  240. if m1.Limit != m2.Start {
  241. return false
  242. }
  243. if m1.Offset != 0 && m2.Offset != 0 {
  244. offset := m1.Offset + (m1.Limit - m1.Start)
  245. if offset != m2.Offset {
  246. return false
  247. }
  248. }
  249. return true
  250. }
  251. func (p *Profile) updateLocationMapping(from, to *Mapping) {
  252. for _, l := range p.Location {
  253. if l.Mapping == from {
  254. l.Mapping = to
  255. }
  256. }
  257. }
  258. // Write writes the profile as a gzip-compressed marshaled protobuf.
  259. func (p *Profile) Write(w io.Writer) error {
  260. p.preEncode()
  261. b := marshal(p)
  262. zw := gzip.NewWriter(w)
  263. defer zw.Close()
  264. _, err := zw.Write(b)
  265. return err
  266. }
  267. // WriteUncompressed writes the profile as a marshaled protobuf.
  268. func (p *Profile) WriteUncompressed(w io.Writer) error {
  269. p.preEncode()
  270. b := marshal(p)
  271. _, err := w.Write(b)
  272. return err
  273. }
  274. // CheckValid tests whether the profile is valid. Checks include, but are
  275. // not limited to:
  276. // - len(Profile.Sample[n].value) == len(Profile.value_unit)
  277. // - Sample.id has a corresponding Profile.Location
  278. func (p *Profile) CheckValid() error {
  279. // Check that sample values are consistent
  280. sampleLen := len(p.SampleType)
  281. if sampleLen == 0 && len(p.Sample) != 0 {
  282. return fmt.Errorf("missing sample type information")
  283. }
  284. for _, s := range p.Sample {
  285. if len(s.Value) != sampleLen {
  286. return fmt.Errorf("mismatch: sample has: %d values vs. %d types", len(s.Value), len(p.SampleType))
  287. }
  288. for _, l := range s.Location {
  289. if l == nil {
  290. return fmt.Errorf("sample has nil location")
  291. }
  292. }
  293. }
  294. // Check that all mappings/locations/functions are in the tables
  295. // Check that there are no duplicate ids
  296. mappings := make(map[uint64]*Mapping, len(p.Mapping))
  297. for _, m := range p.Mapping {
  298. if m.ID == 0 {
  299. return fmt.Errorf("found mapping with reserved ID=0")
  300. }
  301. if mappings[m.ID] != nil {
  302. return fmt.Errorf("multiple mappings with same id: %d", m.ID)
  303. }
  304. mappings[m.ID] = m
  305. }
  306. functions := make(map[uint64]*Function, len(p.Function))
  307. for _, f := range p.Function {
  308. if f.ID == 0 {
  309. return fmt.Errorf("found function with reserved ID=0")
  310. }
  311. if functions[f.ID] != nil {
  312. return fmt.Errorf("multiple functions with same id: %d", f.ID)
  313. }
  314. functions[f.ID] = f
  315. }
  316. locations := make(map[uint64]*Location, len(p.Location))
  317. for _, l := range p.Location {
  318. if l.ID == 0 {
  319. return fmt.Errorf("found location with reserved id=0")
  320. }
  321. if locations[l.ID] != nil {
  322. return fmt.Errorf("multiple locations with same id: %d", l.ID)
  323. }
  324. locations[l.ID] = l
  325. if m := l.Mapping; m != nil {
  326. if m.ID == 0 || mappings[m.ID] != m {
  327. return fmt.Errorf("inconsistent mapping %p: %d", m, m.ID)
  328. }
  329. }
  330. for _, ln := range l.Line {
  331. if f := ln.Function; f != nil {
  332. if f.ID == 0 || functions[f.ID] != f {
  333. return fmt.Errorf("inconsistent function %p: %d", f, f.ID)
  334. }
  335. }
  336. }
  337. }
  338. return nil
  339. }
  340. // Aggregate merges the locations in the profile into equivalence
  341. // classes preserving the request attributes. It also updates the
  342. // samples to point to the merged locations.
  343. func (p *Profile) Aggregate(inlineFrame, function, filename, linenumber, address bool) error {
  344. for _, m := range p.Mapping {
  345. m.HasInlineFrames = m.HasInlineFrames && inlineFrame
  346. m.HasFunctions = m.HasFunctions && function
  347. m.HasFilenames = m.HasFilenames && filename
  348. m.HasLineNumbers = m.HasLineNumbers && linenumber
  349. }
  350. // Aggregate functions
  351. if !function || !filename {
  352. for _, f := range p.Function {
  353. if !function {
  354. f.Name = ""
  355. f.SystemName = ""
  356. }
  357. if !filename {
  358. f.Filename = ""
  359. }
  360. }
  361. }
  362. // Aggregate locations
  363. if !inlineFrame || !address || !linenumber {
  364. for _, l := range p.Location {
  365. if !inlineFrame && len(l.Line) > 1 {
  366. l.Line = l.Line[len(l.Line)-1:]
  367. }
  368. if !linenumber {
  369. for i := range l.Line {
  370. l.Line[i].Line = 0
  371. }
  372. }
  373. if !address {
  374. l.Address = 0
  375. }
  376. }
  377. }
  378. return p.CheckValid()
  379. }
  380. // String dumps a text representation of a profile. Intended mainly
  381. // for debugging purposes.
  382. func (p *Profile) String() string {
  383. ss := make([]string, 0, len(p.Comments)+len(p.Sample)+len(p.Mapping)+len(p.Location))
  384. for _, c := range p.Comments {
  385. ss = append(ss, "Comment: "+c)
  386. }
  387. if pt := p.PeriodType; pt != nil {
  388. ss = append(ss, fmt.Sprintf("PeriodType: %s %s", pt.Type, pt.Unit))
  389. }
  390. ss = append(ss, fmt.Sprintf("Period: %d", p.Period))
  391. if p.TimeNanos != 0 {
  392. ss = append(ss, fmt.Sprintf("Time: %v", time.Unix(0, p.TimeNanos)))
  393. }
  394. if p.DurationNanos != 0 {
  395. ss = append(ss, fmt.Sprintf("Duration: %.4v", time.Duration(p.DurationNanos)))
  396. }
  397. ss = append(ss, "Samples:")
  398. var sh1 string
  399. for _, s := range p.SampleType {
  400. dflt := ""
  401. if s.Type == p.DefaultSampleType {
  402. dflt = "[dflt]"
  403. }
  404. sh1 = sh1 + fmt.Sprintf("%s/%s%s ", s.Type, s.Unit, dflt)
  405. }
  406. ss = append(ss, strings.TrimSpace(sh1))
  407. for _, s := range p.Sample {
  408. var sv string
  409. for _, v := range s.Value {
  410. sv = fmt.Sprintf("%s %10d", sv, v)
  411. }
  412. sv = sv + ": "
  413. for _, l := range s.Location {
  414. sv = sv + fmt.Sprintf("%d ", l.ID)
  415. }
  416. ss = append(ss, sv)
  417. const labelHeader = " "
  418. if len(s.Label) > 0 {
  419. ls := []string{}
  420. for k, v := range s.Label {
  421. ls = append(ls, fmt.Sprintf("%s:%v", k, v))
  422. }
  423. sort.Strings(ls)
  424. ss = append(ss, labelHeader+strings.Join(ls, " "))
  425. }
  426. if len(s.NumLabel) > 0 {
  427. ls := []string{}
  428. for k, v := range s.NumLabel {
  429. ls = append(ls, fmt.Sprintf("%s:%v", k, v))
  430. }
  431. sort.Strings(ls)
  432. ss = append(ss, labelHeader+strings.Join(ls, " "))
  433. }
  434. }
  435. ss = append(ss, "Locations")
  436. for _, l := range p.Location {
  437. locStr := fmt.Sprintf("%6d: %#x ", l.ID, l.Address)
  438. if m := l.Mapping; m != nil {
  439. locStr = locStr + fmt.Sprintf("M=%d ", m.ID)
  440. }
  441. if len(l.Line) == 0 {
  442. ss = append(ss, locStr)
  443. }
  444. for li := range l.Line {
  445. lnStr := "??"
  446. if fn := l.Line[li].Function; fn != nil {
  447. lnStr = fmt.Sprintf("%s %s:%d s=%d",
  448. fn.Name,
  449. fn.Filename,
  450. l.Line[li].Line,
  451. fn.StartLine)
  452. if fn.Name != fn.SystemName {
  453. lnStr = lnStr + "(" + fn.SystemName + ")"
  454. }
  455. }
  456. ss = append(ss, locStr+lnStr)
  457. // Do not print location details past the first line
  458. locStr = " "
  459. }
  460. }
  461. ss = append(ss, "Mappings")
  462. for _, m := range p.Mapping {
  463. bits := ""
  464. if m.HasFunctions {
  465. bits = bits + "[FN]"
  466. }
  467. if m.HasFilenames {
  468. bits = bits + "[FL]"
  469. }
  470. if m.HasLineNumbers {
  471. bits = bits + "[LN]"
  472. }
  473. if m.HasInlineFrames {
  474. bits = bits + "[IN]"
  475. }
  476. ss = append(ss, fmt.Sprintf("%d: %#x/%#x/%#x %s %s %s",
  477. m.ID,
  478. m.Start, m.Limit, m.Offset,
  479. m.File,
  480. m.BuildID,
  481. bits))
  482. }
  483. return strings.Join(ss, "\n") + "\n"
  484. }
  485. // Scale multiplies all sample values in a profile by a constant.
  486. func (p *Profile) Scale(ratio float64) {
  487. if ratio == 1 {
  488. return
  489. }
  490. ratios := make([]float64, len(p.SampleType))
  491. for i := range p.SampleType {
  492. ratios[i] = ratio
  493. }
  494. p.ScaleN(ratios)
  495. }
  496. // ScaleN multiplies each sample values in a sample by a different amount.
  497. func (p *Profile) ScaleN(ratios []float64) error {
  498. if len(p.SampleType) != len(ratios) {
  499. return fmt.Errorf("mismatched scale ratios, got %d, want %d", len(ratios), len(p.SampleType))
  500. }
  501. allOnes := true
  502. for _, r := range ratios {
  503. if r != 1 {
  504. allOnes = false
  505. break
  506. }
  507. }
  508. if allOnes {
  509. return nil
  510. }
  511. for _, s := range p.Sample {
  512. for i, v := range s.Value {
  513. if ratios[i] != 1 {
  514. s.Value[i] = int64(float64(v) * ratios[i])
  515. }
  516. }
  517. }
  518. return nil
  519. }
  520. // HasFunctions determines if all locations in this profile have
  521. // symbolized function information.
  522. func (p *Profile) HasFunctions() bool {
  523. for _, l := range p.Location {
  524. if l.Mapping != nil && !l.Mapping.HasFunctions {
  525. return false
  526. }
  527. }
  528. return true
  529. }
  530. // HasFileLines determines if all locations in this profile have
  531. // symbolized file and line number information.
  532. func (p *Profile) HasFileLines() bool {
  533. for _, l := range p.Location {
  534. if l.Mapping != nil && (!l.Mapping.HasFilenames || !l.Mapping.HasLineNumbers) {
  535. return false
  536. }
  537. }
  538. return true
  539. }
  540. // Unsymbolizable returns true if a mapping points to a binary for which
  541. // locations can't be symbolized in principle, at least now.
  542. func (m *Mapping) Unsymbolizable() bool {
  543. name := filepath.Base(m.File)
  544. return name == "[vdso]" || strings.HasPrefix(name, "linux-vdso")
  545. }
  546. // Copy makes a fully independent copy of a profile.
  547. func (p *Profile) Copy() *Profile {
  548. p.preEncode()
  549. b := marshal(p)
  550. pp := &Profile{}
  551. if err := unmarshal(b, pp); err != nil {
  552. panic(err)
  553. }
  554. if err := pp.postDecode(); err != nil {
  555. panic(err)
  556. }
  557. return pp
  558. }