설명 없음

merge.go 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  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. "fmt"
  17. "reflect"
  18. "sort"
  19. "strconv"
  20. "strings"
  21. )
  22. // Merge merges all the profiles in profs into a single Profile.
  23. // Returns a new profile independent of the input profiles. The merged
  24. // profile is compacted to eliminate unused samples, locations,
  25. // functions and mappings. Profiles must have identical profile sample
  26. // and period types or the merge will fail. profile.Period of the
  27. // resulting profile will be the maximum of all profiles, and
  28. // profile.TimeNanos will be the earliest nonzero one.
  29. func Merge(srcs []*Profile) (*Profile, error) {
  30. if len(srcs) == 0 {
  31. return nil, fmt.Errorf("no profiles to merge")
  32. }
  33. p, err := combineHeaders(srcs)
  34. if err != nil {
  35. return nil, err
  36. }
  37. pm := &profileMerger{
  38. p: p,
  39. samples: make(map[sampleKey]*Sample, len(srcs[0].Sample)),
  40. locations: make(map[locationKey]*Location, len(srcs[0].Location)),
  41. functions: make(map[functionKey]*Function, len(srcs[0].Function)),
  42. mappings: make(map[mappingKey]*Mapping, len(srcs[0].Mapping)),
  43. }
  44. for _, src := range srcs {
  45. // Clear the profile-specific hash tables
  46. pm.locationsByID = make(map[uint64]*Location, len(src.Location))
  47. pm.functionsByID = make(map[uint64]*Function, len(src.Function))
  48. pm.mappingsByID = make(map[uint64]mapInfo, len(src.Mapping))
  49. if len(pm.mappings) == 0 && len(src.Mapping) > 0 {
  50. // The Mapping list has the property that the first mapping
  51. // represents the main binary. Take the first Mapping we see,
  52. // otherwise the operations below will add mappings in an
  53. // arbitrary order.
  54. pm.mapMapping(srcs[0].Mapping[0])
  55. }
  56. for _, s := range src.Sample {
  57. if !isZeroSample(s) {
  58. pm.mapSample(s)
  59. }
  60. }
  61. }
  62. for _, s := range p.Sample {
  63. if isZeroSample(s) {
  64. // If there are any zero samples, re-merge the profile to GC
  65. // them.
  66. return Merge([]*Profile{p})
  67. }
  68. }
  69. return p, nil
  70. }
  71. func isZeroSample(s *Sample) bool {
  72. for _, v := range s.Value {
  73. if v != 0 {
  74. return false
  75. }
  76. }
  77. return true
  78. }
  79. type profileMerger struct {
  80. p *Profile
  81. // Memoization tables within a profile.
  82. locationsByID map[uint64]*Location
  83. functionsByID map[uint64]*Function
  84. mappingsByID map[uint64]mapInfo
  85. // Memoization tables for profile entities.
  86. samples map[sampleKey]*Sample
  87. locations map[locationKey]*Location
  88. functions map[functionKey]*Function
  89. mappings map[mappingKey]*Mapping
  90. }
  91. type mapInfo struct {
  92. m *Mapping
  93. offset int64
  94. }
  95. func (pm *profileMerger) mapSample(src *Sample) *Sample {
  96. s := &Sample{
  97. Location: make([]*Location, len(src.Location)),
  98. Value: make([]int64, len(src.Value)),
  99. Label: make(map[string][]string, len(src.Label)),
  100. NumLabel: make(map[string][]int64, len(src.NumLabel)),
  101. }
  102. for i, l := range src.Location {
  103. s.Location[i] = pm.mapLocation(l)
  104. }
  105. for k, v := range src.Label {
  106. vv := make([]string, len(v))
  107. copy(vv, v)
  108. s.Label[k] = vv
  109. }
  110. for k, v := range src.NumLabel {
  111. vv := make([]int64, len(v))
  112. copy(vv, v)
  113. s.NumLabel[k] = vv
  114. }
  115. // Check memoization table. Must be done on the remapped location to
  116. // account for the remapped mapping. Add current values to the
  117. // existing sample.
  118. k := s.key()
  119. if ss, ok := pm.samples[k]; ok {
  120. for i, v := range src.Value {
  121. ss.Value[i] += v
  122. }
  123. return ss
  124. }
  125. copy(s.Value, src.Value)
  126. pm.samples[k] = s
  127. pm.p.Sample = append(pm.p.Sample, s)
  128. return s
  129. }
  130. // key generates sampleKey to be used as a key for maps.
  131. func (sample *Sample) key() sampleKey {
  132. ids := make([]string, len(sample.Location))
  133. for i, l := range sample.Location {
  134. ids[i] = strconv.FormatUint(l.ID, 16)
  135. }
  136. labels := make([]string, 0, len(sample.Label))
  137. for k, v := range sample.Label {
  138. labels = append(labels, fmt.Sprintf("%q%q", k, v))
  139. }
  140. sort.Strings(labels)
  141. numlabels := make([]string, 0, len(sample.NumLabel))
  142. for k, v := range sample.NumLabel {
  143. numlabels = append(numlabels, fmt.Sprintf("%q%x", k, v))
  144. }
  145. sort.Strings(numlabels)
  146. return sampleKey{
  147. strings.Join(ids, "|"),
  148. strings.Join(labels, ""),
  149. strings.Join(numlabels, ""),
  150. }
  151. }
  152. type sampleKey struct {
  153. locations string
  154. labels string
  155. numlabels string
  156. }
  157. func (pm *profileMerger) mapLocation(src *Location) *Location {
  158. if src == nil {
  159. return nil
  160. }
  161. if l, ok := pm.locationsByID[src.ID]; ok {
  162. pm.locationsByID[src.ID] = l
  163. return l
  164. }
  165. mi := pm.mapMapping(src.Mapping)
  166. l := &Location{
  167. ID: uint64(len(pm.p.Location) + 1),
  168. Mapping: mi.m,
  169. Address: uint64(int64(src.Address) + mi.offset),
  170. Line: make([]Line, len(src.Line)),
  171. }
  172. for i, ln := range src.Line {
  173. l.Line[i] = pm.mapLine(ln)
  174. }
  175. // Check memoization table. Must be done on the remapped location to
  176. // account for the remapped mapping ID.
  177. k := l.key()
  178. if ll, ok := pm.locations[k]; ok {
  179. pm.locationsByID[src.ID] = ll
  180. return ll
  181. }
  182. pm.locationsByID[src.ID] = l
  183. pm.locations[k] = l
  184. pm.p.Location = append(pm.p.Location, l)
  185. return l
  186. }
  187. // key generates locationKey to be used as a key for maps.
  188. func (l *Location) key() locationKey {
  189. key := locationKey{
  190. addr: l.Address,
  191. }
  192. if l.Mapping != nil {
  193. // Normalizes address to handle address space randomization.
  194. key.addr -= l.Mapping.Start
  195. key.mappingID = l.Mapping.ID
  196. }
  197. lines := make([]string, len(l.Line)*2)
  198. for i, line := range l.Line {
  199. lines[i*2] = strconv.FormatUint(line.Function.ID, 16)
  200. lines[i*2+1] = strconv.FormatInt(line.Line, 16)
  201. }
  202. key.lines = strings.Join(lines, "|")
  203. return key
  204. }
  205. type locationKey struct {
  206. addr, mappingID uint64
  207. lines string
  208. }
  209. func (pm *profileMerger) mapMapping(src *Mapping) mapInfo {
  210. if src == nil {
  211. return mapInfo{}
  212. }
  213. if mi, ok := pm.mappingsByID[src.ID]; ok {
  214. return mi
  215. }
  216. // Check memoization tables.
  217. bk, pk := src.key()
  218. if src.BuildID != "" {
  219. if m, ok := pm.mappings[bk]; ok {
  220. mi := mapInfo{m, int64(m.Start) - int64(src.Start)}
  221. pm.mappingsByID[src.ID] = mi
  222. return mi
  223. }
  224. }
  225. if src.File != "" {
  226. if m, ok := pm.mappings[pk]; ok {
  227. mi := mapInfo{m, int64(m.Start) - int64(src.Start)}
  228. pm.mappingsByID[src.ID] = mi
  229. return mi
  230. }
  231. }
  232. m := &Mapping{
  233. ID: uint64(len(pm.p.Mapping) + 1),
  234. Start: src.Start,
  235. Limit: src.Limit,
  236. Offset: src.Offset,
  237. File: src.File,
  238. BuildID: src.BuildID,
  239. HasFunctions: src.HasFunctions,
  240. HasFilenames: src.HasFilenames,
  241. HasLineNumbers: src.HasLineNumbers,
  242. HasInlineFrames: src.HasInlineFrames,
  243. }
  244. pm.p.Mapping = append(pm.p.Mapping, m)
  245. // Update memoization tables.
  246. if m.BuildID != "" {
  247. pm.mappings[bk] = m
  248. }
  249. if m.File != "" {
  250. pm.mappings[pk] = m
  251. }
  252. mi := mapInfo{m, 0}
  253. pm.mappingsByID[src.ID] = mi
  254. return mi
  255. }
  256. // key generates encoded strings of Mapping to be used as a key for
  257. // maps. The first key represents only the build id, while the second
  258. // represents only the file path.
  259. func (m *Mapping) key() (buildIDKey, pathKey mappingKey) {
  260. // Normalize addresses to handle address space randomization.
  261. // Round up to next 4K boundary to avoid minor discrepancies.
  262. const mapsizeRounding = 0x1000
  263. size := m.Limit - m.Start
  264. size = size + mapsizeRounding - 1
  265. size = size - (size % mapsizeRounding)
  266. buildIDKey = mappingKey{
  267. size,
  268. m.Offset,
  269. m.BuildID,
  270. }
  271. pathKey = mappingKey{
  272. size,
  273. m.Offset,
  274. m.File,
  275. }
  276. return
  277. }
  278. type mappingKey struct {
  279. size, offset uint64
  280. buildidIDOrFile string
  281. }
  282. func (pm *profileMerger) mapLine(src Line) Line {
  283. ln := Line{
  284. Function: pm.mapFunction(src.Function),
  285. Line: src.Line,
  286. }
  287. return ln
  288. }
  289. func (pm *profileMerger) mapFunction(src *Function) *Function {
  290. if src == nil {
  291. return nil
  292. }
  293. if f, ok := pm.functionsByID[src.ID]; ok {
  294. return f
  295. }
  296. k := src.key()
  297. if f, ok := pm.functions[k]; ok {
  298. pm.functionsByID[src.ID] = f
  299. return f
  300. }
  301. f := &Function{
  302. ID: uint64(len(pm.p.Function) + 1),
  303. Name: src.Name,
  304. SystemName: src.SystemName,
  305. Filename: src.Filename,
  306. StartLine: src.StartLine,
  307. }
  308. pm.functions[k] = f
  309. pm.functionsByID[src.ID] = f
  310. pm.p.Function = append(pm.p.Function, f)
  311. return f
  312. }
  313. // key generates a struct to be used as a key for maps.
  314. func (f *Function) key() functionKey {
  315. return functionKey{
  316. f.StartLine,
  317. f.Name,
  318. f.SystemName,
  319. f.Filename,
  320. }
  321. }
  322. type functionKey struct {
  323. startLine int64
  324. name, systemName, fileName string
  325. }
  326. // combineHeaders checks that all profiles can be merged and returns
  327. // their combined profile.
  328. func combineHeaders(srcs []*Profile) (*Profile, error) {
  329. for _, s := range srcs[1:] {
  330. if err := srcs[0].compatible(s); err != nil {
  331. return nil, err
  332. }
  333. }
  334. var timeNanos, durationNanos, period int64
  335. var comments []string
  336. var defaultSampleType string
  337. for _, s := range srcs {
  338. if timeNanos == 0 || s.TimeNanos < timeNanos {
  339. timeNanos = s.TimeNanos
  340. }
  341. durationNanos += s.DurationNanos
  342. if period == 0 || period < s.Period {
  343. period = s.Period
  344. }
  345. comments = append(comments, s.Comments...)
  346. if defaultSampleType == "" {
  347. defaultSampleType = s.DefaultSampleType
  348. }
  349. }
  350. p := &Profile{
  351. SampleType: make([]*ValueType, len(srcs[0].SampleType)),
  352. DropFrames: srcs[0].DropFrames,
  353. KeepFrames: srcs[0].KeepFrames,
  354. TimeNanos: timeNanos,
  355. DurationNanos: durationNanos,
  356. PeriodType: srcs[0].PeriodType,
  357. Period: period,
  358. Comments: comments,
  359. DefaultSampleType: defaultSampleType,
  360. }
  361. copy(p.SampleType, srcs[0].SampleType)
  362. return p, nil
  363. }
  364. // compatible determines if two profiles can be compared/merged.
  365. // returns nil if the profiles are compatible; otherwise an error with
  366. // details on the incompatibility.
  367. func (p *Profile) compatible(pb *Profile) error {
  368. if !reflect.DeepEqual(p.PeriodType, pb.PeriodType) {
  369. return fmt.Errorf("incompatible period types %v and %v", p.PeriodType, pb.PeriodType)
  370. }
  371. if len(p.SampleType) != len(pb.SampleType) {
  372. return fmt.Errorf("incompatible sample types %v and %v", p.SampleType, pb.SampleType)
  373. }
  374. for i := range p.SampleType {
  375. if !reflect.DeepEqual(p.SampleType[i], pb.SampleType[i]) {
  376. return fmt.Errorf("incompatible sample types %v and %v", p.SampleType, pb.SampleType)
  377. }
  378. }
  379. return nil
  380. }