Açıklama Yok

legacy_java_profile.go 8.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  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. // This file implements parsers to convert java legacy profiles into
  15. // the profile.proto format.
  16. package profile
  17. import (
  18. "bytes"
  19. "fmt"
  20. "io"
  21. "path/filepath"
  22. "regexp"
  23. "strconv"
  24. "strings"
  25. )
  26. var (
  27. attributeRx = regexp.MustCompile(`([\w ]+)=([\w ]+)`)
  28. javaSampleRx = regexp.MustCompile(` *(\d+) +(\d+) +@ +([ x0-9a-f]*)`)
  29. javaLocationRx = regexp.MustCompile(`^\s*0x([[:xdigit:]]+)\s+(.*)\s*$`)
  30. javaLocationFileLineRx = regexp.MustCompile(`^(.*)\s+\((.+):(-?[[:digit:]]+)\)$`)
  31. javaLocationPathRx = regexp.MustCompile(`^(.*)\s+\((.*)\)$`)
  32. )
  33. // javaCPUProfile returns a new Profile from profilez data.
  34. // b is the profile bytes after the header, period is the profiling
  35. // period, and parse is a function to parse 8-byte chunks from the
  36. // profile in its native endianness.
  37. func javaCPUProfile(b []byte, period int64, parse func(b []byte) (uint64, []byte)) (*Profile, error) {
  38. p := &Profile{
  39. Period: period * 1000,
  40. PeriodType: &ValueType{Type: "cpu", Unit: "nanoseconds"},
  41. SampleType: []*ValueType{{Type: "samples", Unit: "count"}, {Type: "cpu", Unit: "nanoseconds"}},
  42. }
  43. var err error
  44. var locs map[uint64]*Location
  45. if b, locs, err = parseCPUSamples(b, parse, false, p); err != nil {
  46. return nil, err
  47. }
  48. if err = parseJavaLocations(b, locs, p); err != nil {
  49. return nil, err
  50. }
  51. // Strip out addresses for better merge.
  52. if err = p.Aggregate(true, true, true, true, false); err != nil {
  53. return nil, err
  54. }
  55. return p, nil
  56. }
  57. // parseJavaProfile returns a new profile from heapz or contentionz
  58. // data. b is the profile bytes after the header.
  59. func parseJavaProfile(b []byte) (*Profile, error) {
  60. h := bytes.SplitAfterN(b, []byte("\n"), 2)
  61. if len(h) < 2 {
  62. return nil, errUnrecognized
  63. }
  64. p := &Profile{
  65. PeriodType: &ValueType{},
  66. }
  67. header := string(bytes.TrimSpace(h[0]))
  68. var err error
  69. var pType string
  70. switch header {
  71. case "--- heapz 1 ---":
  72. pType = "heap"
  73. case "--- contentionz 1 ---":
  74. pType = "contention"
  75. default:
  76. return nil, errUnrecognized
  77. }
  78. if b, err = parseJavaHeader(pType, h[1], p); err != nil {
  79. return nil, err
  80. }
  81. var locs map[uint64]*Location
  82. if b, locs, err = parseJavaSamples(pType, b, p); err != nil {
  83. return nil, err
  84. }
  85. if err = parseJavaLocations(b, locs, p); err != nil {
  86. return nil, err
  87. }
  88. // Strip out addresses for better merge.
  89. if err = p.Aggregate(true, true, true, true, false); err != nil {
  90. return nil, err
  91. }
  92. return p, nil
  93. }
  94. // parseJavaHeader parses the attribute section on a java profile and
  95. // populates a profile. Returns the remainder of the buffer after all
  96. // attributes.
  97. func parseJavaHeader(pType string, b []byte, p *Profile) ([]byte, error) {
  98. nextNewLine := bytes.IndexByte(b, byte('\n'))
  99. for nextNewLine != -1 {
  100. line := string(bytes.TrimSpace(b[0:nextNewLine]))
  101. if line != "" {
  102. h := attributeRx.FindStringSubmatch(line)
  103. if h == nil {
  104. // Not a valid attribute, exit.
  105. return b, nil
  106. }
  107. attribute, value := strings.TrimSpace(h[1]), strings.TrimSpace(h[2])
  108. var err error
  109. switch pType + "/" + attribute {
  110. case "heap/format", "cpu/format", "contention/format":
  111. if value != "java" {
  112. return nil, errUnrecognized
  113. }
  114. case "heap/resolution":
  115. p.SampleType = []*ValueType{
  116. {Type: "inuse_objects", Unit: "count"},
  117. {Type: "inuse_space", Unit: value},
  118. }
  119. case "contention/resolution":
  120. p.SampleType = []*ValueType{
  121. {Type: "contentions", Unit: value},
  122. {Type: "delay", Unit: value},
  123. }
  124. case "contention/sampling period":
  125. p.PeriodType = &ValueType{
  126. Type: "contentions", Unit: "count",
  127. }
  128. if p.Period, err = strconv.ParseInt(value, 0, 64); err != nil {
  129. return nil, fmt.Errorf("failed to parse attribute %s: %v", line, err)
  130. }
  131. case "contention/ms since reset":
  132. millis, err := strconv.ParseInt(value, 0, 64)
  133. if err != nil {
  134. return nil, fmt.Errorf("failed to parse attribute %s: %v", line, err)
  135. }
  136. p.DurationNanos = millis * 1000 * 1000
  137. default:
  138. return nil, errUnrecognized
  139. }
  140. }
  141. // Grab next line.
  142. b = b[nextNewLine+1:]
  143. nextNewLine = bytes.IndexByte(b, byte('\n'))
  144. }
  145. return b, nil
  146. }
  147. // parseJavaSamples parses the samples from a java profile and
  148. // populates the Samples in a profile. Returns the remainder of the
  149. // buffer after the samples.
  150. func parseJavaSamples(pType string, b []byte, p *Profile) ([]byte, map[uint64]*Location, error) {
  151. nextNewLine := bytes.IndexByte(b, byte('\n'))
  152. locs := make(map[uint64]*Location)
  153. for nextNewLine != -1 {
  154. line := string(bytes.TrimSpace(b[0:nextNewLine]))
  155. if line != "" {
  156. sample := javaSampleRx.FindStringSubmatch(line)
  157. if sample == nil {
  158. // Not a valid sample, exit.
  159. return b, locs, nil
  160. }
  161. // Java profiles have data/fields inverted compared to other
  162. // profile types.
  163. var err error
  164. value1, value2, value3 := sample[2], sample[1], sample[3]
  165. addrs, err := parseHexAddresses(value3)
  166. if err != nil {
  167. return nil, nil, fmt.Errorf("malformed sample: %s: %v", line, err)
  168. }
  169. var sloc []*Location
  170. for _, addr := range addrs {
  171. loc := locs[addr]
  172. if locs[addr] == nil {
  173. loc = &Location{
  174. Address: addr,
  175. }
  176. p.Location = append(p.Location, loc)
  177. locs[addr] = loc
  178. }
  179. sloc = append(sloc, loc)
  180. }
  181. s := &Sample{
  182. Value: make([]int64, 2),
  183. Location: sloc,
  184. }
  185. if s.Value[0], err = strconv.ParseInt(value1, 0, 64); err != nil {
  186. return nil, nil, fmt.Errorf("parsing sample %s: %v", line, err)
  187. }
  188. if s.Value[1], err = strconv.ParseInt(value2, 0, 64); err != nil {
  189. return nil, nil, fmt.Errorf("parsing sample %s: %v", line, err)
  190. }
  191. switch pType {
  192. case "heap":
  193. const javaHeapzSamplingRate = 524288 // 512K
  194. s.NumLabel = map[string][]int64{"bytes": []int64{s.Value[1] / s.Value[0]}}
  195. s.Value[0], s.Value[1] = scaleHeapSample(s.Value[0], s.Value[1], javaHeapzSamplingRate)
  196. case "contention":
  197. if period := p.Period; period != 0 {
  198. s.Value[0] = s.Value[0] * p.Period
  199. s.Value[1] = s.Value[1] * p.Period
  200. }
  201. }
  202. p.Sample = append(p.Sample, s)
  203. }
  204. // Grab next line.
  205. b = b[nextNewLine+1:]
  206. nextNewLine = bytes.IndexByte(b, byte('\n'))
  207. }
  208. return b, locs, nil
  209. }
  210. // parseJavaLocations parses the location information in a java
  211. // profile and populates the Locations in a profile. It uses the
  212. // location addresses from the profile as both the ID of each
  213. // location.
  214. func parseJavaLocations(b []byte, locs map[uint64]*Location, p *Profile) error {
  215. r := bytes.NewBuffer(b)
  216. fns := make(map[string]*Function)
  217. for {
  218. line, err := r.ReadString('\n')
  219. if err != nil {
  220. if err != io.EOF {
  221. return err
  222. }
  223. if line == "" {
  224. break
  225. }
  226. }
  227. if line = strings.TrimSpace(line); line == "" {
  228. continue
  229. }
  230. jloc := javaLocationRx.FindStringSubmatch(line)
  231. if len(jloc) != 3 {
  232. continue
  233. }
  234. addr, err := strconv.ParseUint(jloc[1], 16, 64)
  235. if err != nil {
  236. return fmt.Errorf("parsing sample %s: %v", line, err)
  237. }
  238. loc := locs[addr]
  239. if loc == nil {
  240. // Unused/unseen
  241. continue
  242. }
  243. var lineFunc, lineFile string
  244. var lineNo int64
  245. if fileLine := javaLocationFileLineRx.FindStringSubmatch(jloc[2]); len(fileLine) == 4 {
  246. // Found a line of the form: "function (file:line)"
  247. lineFunc, lineFile = fileLine[1], fileLine[2]
  248. if n, err := strconv.ParseInt(fileLine[3], 10, 64); err == nil && n > 0 {
  249. lineNo = n
  250. }
  251. } else if filePath := javaLocationPathRx.FindStringSubmatch(jloc[2]); len(filePath) == 3 {
  252. // If there's not a file:line, it's a shared library path.
  253. // The path isn't interesting, so just give the .so.
  254. lineFunc, lineFile = filePath[1], filepath.Base(filePath[2])
  255. } else if strings.Contains(jloc[2], "generated stub/JIT") {
  256. lineFunc = "STUB"
  257. } else {
  258. // Treat whole line as the function name. This is used by the
  259. // java agent for internal states such as "GC" or "VM".
  260. lineFunc = jloc[2]
  261. }
  262. fn := fns[lineFunc]
  263. if fn == nil {
  264. fn = &Function{
  265. Name: lineFunc,
  266. SystemName: lineFunc,
  267. Filename: lineFile,
  268. }
  269. fns[lineFunc] = fn
  270. p.Function = append(p.Function, fn)
  271. }
  272. loc.Line = []Line{
  273. {
  274. Function: fn,
  275. Line: lineNo,
  276. },
  277. }
  278. loc.Address = 0
  279. }
  280. p.remapLocationIDs()
  281. p.remapFunctionIDs()
  282. p.remapMappingIDs()
  283. return nil
  284. }