暫無描述

graph.go 29KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135
  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 graph collects a set of samples into a directed graph.
  15. package graph
  16. import (
  17. "fmt"
  18. "math"
  19. "path/filepath"
  20. "sort"
  21. "strconv"
  22. "strings"
  23. "github.com/google/pprof/profile"
  24. )
  25. // Graph summarizes a performance profile into a format that is
  26. // suitable for visualization.
  27. type Graph struct {
  28. Nodes Nodes
  29. }
  30. // Options encodes the options for constructing a graph
  31. type Options struct {
  32. SampleValue func(s []int64) int64 // Function to compute the value of a sample
  33. SampleMeanDivisor func(s []int64) int64 // Function to compute the divisor for mean graphs, or nil
  34. FormatTag func(int64, string) string // Function to format a sample tag value into a string
  35. ObjNames bool // Always preserve obj filename
  36. OrigFnNames bool // Preserve original (eg mangled) function names
  37. CallTree bool // Build a tree instead of a graph
  38. DropNegative bool // Drop nodes with overall negative values
  39. KeptNodes NodeSet // If non-nil, only use nodes in this set
  40. }
  41. // Nodes is an ordered collection of graph nodes.
  42. type Nodes []*Node
  43. // Node is an entry on a profiling report. It represents a unique
  44. // program location.
  45. type Node struct {
  46. // Info describes the source location associated to this node.
  47. Info NodeInfo
  48. // Function represents the function that this node belongs to. On
  49. // graphs with sub-function resolution (eg line number or
  50. // addresses), two nodes in a NodeMap that are part of the same
  51. // function have the same value of Node.Function. If the Node
  52. // represents the whole function, it points back to itself.
  53. Function *Node
  54. // Values associated to this node. Flat is exclusive to this node,
  55. // Cum includes all descendents.
  56. Flat, FlatDiv, Cum, CumDiv int64
  57. // In and out Contains the nodes immediately reaching or reached by
  58. // this node.
  59. In, Out EdgeMap
  60. // LabelTags provide additional information about subsets of a sample.
  61. LabelTags TagMap
  62. // NumericTags provide additional values for subsets of a sample.
  63. // Numeric tags are optionally associated to a label tag. The key
  64. // for NumericTags is the name of the LabelTag they are associated
  65. // to, or "" for numeric tags not associated to a label tag.
  66. NumericTags map[string]TagMap
  67. }
  68. // FlatValue returns the exclusive value for this node, computing the
  69. // mean if a divisor is available.
  70. func (n *Node) FlatValue() int64 {
  71. if n.FlatDiv == 0 {
  72. return n.Flat
  73. }
  74. return n.Flat / n.FlatDiv
  75. }
  76. // CumValue returns the inclusive value for this node, computing the
  77. // mean if a divisor is available.
  78. func (n *Node) CumValue() int64 {
  79. if n.CumDiv == 0 {
  80. return n.Cum
  81. }
  82. return n.Cum / n.CumDiv
  83. }
  84. // AddToEdge increases the weight of an edge between two nodes. If
  85. // there isn't such an edge one is created.
  86. func (n *Node) AddToEdge(to *Node, v int64, residual, inline bool) {
  87. n.AddToEdgeDiv(to, 0, v, residual, inline)
  88. }
  89. // AddToEdgeDiv increases the weight of an edge between two nodes. If
  90. // there isn't such an edge one is created.
  91. func (n *Node) AddToEdgeDiv(to *Node, dv, v int64, residual, inline bool) {
  92. if n.Out[to] != to.In[n] {
  93. panic(fmt.Errorf("asymmetric edges %v %v", *n, *to))
  94. }
  95. if e := n.Out[to]; e != nil {
  96. e.WeightDiv += dv
  97. e.Weight += v
  98. if residual {
  99. e.Residual = true
  100. }
  101. if !inline {
  102. e.Inline = false
  103. }
  104. return
  105. }
  106. info := &Edge{Src: n, Dest: to, WeightDiv: dv, Weight: v, Residual: residual, Inline: inline}
  107. n.Out[to] = info
  108. to.In[n] = info
  109. }
  110. // NodeInfo contains the attributes for a node.
  111. type NodeInfo struct {
  112. Name string
  113. OrigName string
  114. Address uint64
  115. File string
  116. StartLine, Lineno int
  117. Objfile string
  118. }
  119. // PrintableName calls the Node's Formatter function with a single space separator.
  120. func (i *NodeInfo) PrintableName() string {
  121. return strings.Join(i.NameComponents(), " ")
  122. }
  123. // NameComponents returns the components of the printable name to be used for a node.
  124. func (i *NodeInfo) NameComponents() []string {
  125. var name []string
  126. if i.Address != 0 {
  127. name = append(name, fmt.Sprintf("%016x", i.Address))
  128. }
  129. if fun := i.Name; fun != "" {
  130. name = append(name, fun)
  131. }
  132. switch {
  133. case i.Lineno != 0:
  134. // User requested line numbers, provide what we have.
  135. name = append(name, fmt.Sprintf("%s:%d", i.File, i.Lineno))
  136. case i.File != "":
  137. // User requested file name, provide it.
  138. name = append(name, i.File)
  139. case i.Name != "":
  140. // User requested function name. It was already included.
  141. case i.Objfile != "":
  142. // Only binary name is available
  143. name = append(name, "["+filepath.Base(i.Objfile)+"]")
  144. default:
  145. // Do not leave it empty if there is no information at all.
  146. name = append(name, "<unknown>")
  147. }
  148. return name
  149. }
  150. // NodeMap maps from a node info struct to a node. It is used to merge
  151. // report entries with the same info.
  152. type NodeMap map[NodeInfo]*Node
  153. // NodeSet is a collection of node info structs.
  154. type NodeSet map[NodeInfo]bool
  155. // NodePtrSet is a collection of nodes. Trimming a graph or tree requires a set
  156. // of objects which uniquely identify the nodes to keep. In a graph, NodeInfo
  157. // works as a unique identifier; however, in a tree multiple nodes may share
  158. // identical NodeInfos. A *Node does uniquely identify a node so we can use that
  159. // instead. Though a *Node also uniquely identifies a node in a graph,
  160. // currently, during trimming, graphs are rebult from scratch using only the
  161. // NodeSet, so there would not be the required context of the initial graph to
  162. // allow for the use of *Node.
  163. type NodePtrSet map[*Node]bool
  164. // FindOrInsertNode takes the info for a node and either returns a matching node
  165. // from the node map if one exists, or adds one to the map if one does not.
  166. // If kept is non-nil, nodes are only added if they can be located on it.
  167. func (nm NodeMap) FindOrInsertNode(info NodeInfo, kept NodeSet) *Node {
  168. if kept != nil {
  169. if _, ok := kept[info]; !ok {
  170. return nil
  171. }
  172. }
  173. if n, ok := nm[info]; ok {
  174. return n
  175. }
  176. n := &Node{
  177. Info: info,
  178. In: make(EdgeMap),
  179. Out: make(EdgeMap),
  180. LabelTags: make(TagMap),
  181. NumericTags: make(map[string]TagMap),
  182. }
  183. nm[info] = n
  184. if info.Address == 0 && info.Lineno == 0 {
  185. // This node represents the whole function, so point Function
  186. // back to itself.
  187. n.Function = n
  188. return n
  189. }
  190. // Find a node that represents the whole function.
  191. info.Address = 0
  192. info.Lineno = 0
  193. n.Function = nm.FindOrInsertNode(info, nil)
  194. return n
  195. }
  196. // EdgeMap is used to represent the incoming/outgoing edges from a node.
  197. type EdgeMap map[*Node]*Edge
  198. // Edge contains any attributes to be represented about edges in a graph.
  199. type Edge struct {
  200. Src, Dest *Node
  201. // The summary weight of the edge
  202. Weight, WeightDiv int64
  203. // residual edges connect nodes that were connected through a
  204. // separate node, which has been removed from the report.
  205. Residual bool
  206. // An inline edge represents a call that was inlined into the caller.
  207. Inline bool
  208. }
  209. // WeightValue returns the weight value for this edge, normalizing if a
  210. // divisor is available.
  211. func (e *Edge) WeightValue() int64 {
  212. if e.WeightDiv == 0 {
  213. return e.Weight
  214. }
  215. return e.Weight / e.WeightDiv
  216. }
  217. // Tag represent sample annotations
  218. type Tag struct {
  219. Name string
  220. Unit string // Describe the value, "" for non-numeric tags
  221. Value int64
  222. Flat, FlatDiv int64
  223. Cum, CumDiv int64
  224. }
  225. // FlatValue returns the exclusive value for this tag, computing the
  226. // mean if a divisor is available.
  227. func (t *Tag) FlatValue() int64 {
  228. if t.FlatDiv == 0 {
  229. return t.Flat
  230. }
  231. return t.Flat / t.FlatDiv
  232. }
  233. // CumValue returns the inclusive value for this tag, computing the
  234. // mean if a divisor is available.
  235. func (t *Tag) CumValue() int64 {
  236. if t.CumDiv == 0 {
  237. return t.Cum
  238. }
  239. return t.Cum / t.CumDiv
  240. }
  241. // TagMap is a collection of tags, classified by their name.
  242. type TagMap map[string]*Tag
  243. // SortTags sorts a slice of tags based on their weight.
  244. func SortTags(t []*Tag, flat bool) []*Tag {
  245. ts := tags{t, flat}
  246. sort.Sort(ts)
  247. return ts.t
  248. }
  249. // New summarizes performance data from a profile into a graph.
  250. func New(prof *profile.Profile, o *Options) *Graph {
  251. if o.CallTree {
  252. return newTree(prof, o)
  253. }
  254. g, _ := newGraph(prof, o)
  255. return g
  256. }
  257. // newGraph computes a graph from a profile. It returns the graph, and
  258. // a map from the profile location indices to the corresponding graph
  259. // nodes.
  260. func newGraph(prof *profile.Profile, o *Options) (*Graph, map[uint64]Nodes) {
  261. nodes, locationMap := CreateNodes(prof, o)
  262. for _, sample := range prof.Sample {
  263. var w, dw int64
  264. w = o.SampleValue(sample.Value)
  265. if o.SampleMeanDivisor != nil {
  266. dw = o.SampleMeanDivisor(sample.Value)
  267. }
  268. if dw == 0 && w == 0 {
  269. continue
  270. }
  271. seenNode := make(map[*Node]bool, len(sample.Location))
  272. seenEdge := make(map[nodePair]bool, len(sample.Location))
  273. var parent *Node
  274. // A residual edge goes over one or more nodes that were not kept.
  275. residual := false
  276. labels := joinLabels(sample)
  277. // Group the sample frames, based on a global map.
  278. for i := len(sample.Location) - 1; i >= 0; i-- {
  279. l := sample.Location[i]
  280. locNodes := locationMap[l.ID]
  281. for ni := len(locNodes) - 1; ni >= 0; ni-- {
  282. n := locNodes[ni]
  283. if n == nil {
  284. residual = true
  285. continue
  286. }
  287. // Add cum weight to all nodes in stack, avoiding double counting.
  288. if _, ok := seenNode[n]; !ok {
  289. seenNode[n] = true
  290. n.addSample(dw, w, labels, sample.NumLabel, sample.NumUnit, o.FormatTag, false)
  291. }
  292. // Update edge weights for all edges in stack, avoiding double counting.
  293. if _, ok := seenEdge[nodePair{n, parent}]; !ok && parent != nil && n != parent {
  294. seenEdge[nodePair{n, parent}] = true
  295. parent.AddToEdgeDiv(n, dw, w, residual, ni != len(locNodes)-1)
  296. }
  297. parent = n
  298. residual = false
  299. }
  300. }
  301. if parent != nil && !residual {
  302. // Add flat weight to leaf node.
  303. parent.addSample(dw, w, labels, sample.NumLabel, sample.NumUnit, o.FormatTag, true)
  304. }
  305. }
  306. return selectNodesForGraph(nodes, o.DropNegative), locationMap
  307. }
  308. func selectNodesForGraph(nodes Nodes, dropNegative bool) *Graph {
  309. // Collect nodes into a graph.
  310. gNodes := make(Nodes, 0, len(nodes))
  311. for _, n := range nodes {
  312. if n == nil {
  313. continue
  314. }
  315. if n.Cum == 0 && n.Flat == 0 {
  316. continue
  317. }
  318. if dropNegative && isNegative(n) {
  319. continue
  320. }
  321. gNodes = append(gNodes, n)
  322. }
  323. return &Graph{gNodes}
  324. }
  325. type nodePair struct {
  326. src, dest *Node
  327. }
  328. func newTree(prof *profile.Profile, o *Options) (g *Graph) {
  329. parentNodeMap := make(map[*Node]NodeMap, len(prof.Sample))
  330. for _, sample := range prof.Sample {
  331. var w, dw int64
  332. w = o.SampleValue(sample.Value)
  333. if o.SampleMeanDivisor != nil {
  334. dw = o.SampleMeanDivisor(sample.Value)
  335. }
  336. if dw == 0 && w == 0 {
  337. continue
  338. }
  339. var parent *Node
  340. labels := joinLabels(sample)
  341. // Group the sample frames, based on a per-node map.
  342. for i := len(sample.Location) - 1; i >= 0; i-- {
  343. l := sample.Location[i]
  344. lines := l.Line
  345. if len(lines) == 0 {
  346. lines = []profile.Line{{}} // Create empty line to include location info.
  347. }
  348. for lidx := len(lines) - 1; lidx >= 0; lidx-- {
  349. nodeMap := parentNodeMap[parent]
  350. if nodeMap == nil {
  351. nodeMap = make(NodeMap)
  352. parentNodeMap[parent] = nodeMap
  353. }
  354. n := nodeMap.findOrInsertLine(l, lines[lidx], o)
  355. if n == nil {
  356. continue
  357. }
  358. n.addSample(dw, w, labels, sample.NumLabel, sample.NumUnit, o.FormatTag, false)
  359. if parent != nil {
  360. parent.AddToEdgeDiv(n, dw, w, false, lidx != len(lines)-1)
  361. }
  362. parent = n
  363. }
  364. }
  365. if parent != nil {
  366. parent.addSample(dw, w, labels, sample.NumLabel, sample.NumUnit, o.FormatTag, true)
  367. }
  368. }
  369. nodes := make(Nodes, len(prof.Location))
  370. for _, nm := range parentNodeMap {
  371. nodes = append(nodes, nm.nodes()...)
  372. }
  373. return selectNodesForGraph(nodes, o.DropNegative)
  374. }
  375. // TrimTree trims a Graph in forest form, keeping only the nodes in kept. This
  376. // will not work correctly if even a single node has multiple parents.
  377. func (g *Graph) TrimTree(kept NodePtrSet) {
  378. // Creates a new list of nodes
  379. oldNodes := g.Nodes
  380. g.Nodes = make(Nodes, 0, len(kept))
  381. for _, cur := range oldNodes {
  382. // A node may not have multiple parents
  383. if len(cur.In) > 1 {
  384. panic("TrimTree only works on trees")
  385. }
  386. // If a node should be kept, add it to the new list of nodes
  387. if _, ok := kept[cur]; ok {
  388. g.Nodes = append(g.Nodes, cur)
  389. continue
  390. }
  391. // If a node has no parents, then delete all of the in edges of its
  392. // children to make them each roots of their own trees.
  393. if len(cur.In) == 0 {
  394. for _, outEdge := range cur.Out {
  395. delete(outEdge.Dest.In, cur)
  396. }
  397. continue
  398. }
  399. // Get the parent. This works since at this point cur.In must contain only
  400. // one element.
  401. if len(cur.In) != 1 {
  402. panic("Get parent assertion failed. cur.In expected to be of length 1.")
  403. }
  404. var parent *Node
  405. for _, edge := range cur.In {
  406. parent = edge.Src
  407. }
  408. parentEdgeInline := parent.Out[cur].Inline
  409. // Remove the edge from the parent to this node
  410. delete(parent.Out, cur)
  411. // Reconfigure every edge from the current node to now begin at the parent.
  412. for _, outEdge := range cur.Out {
  413. child := outEdge.Dest
  414. delete(child.In, cur)
  415. child.In[parent] = outEdge
  416. parent.Out[child] = outEdge
  417. outEdge.Src = parent
  418. outEdge.Residual = true
  419. // If the edge from the parent to the current node and the edge from the
  420. // current node to the child are both inline, then this resulting residual
  421. // edge should also be inline
  422. outEdge.Inline = parentEdgeInline && outEdge.Inline
  423. }
  424. }
  425. g.RemoveRedundantEdges()
  426. }
  427. func joinLabels(s *profile.Sample) string {
  428. if len(s.Label) == 0 {
  429. return ""
  430. }
  431. var labels []string
  432. for key, vals := range s.Label {
  433. for _, v := range vals {
  434. labels = append(labels, key+":"+v)
  435. }
  436. }
  437. sort.Strings(labels)
  438. return strings.Join(labels, `\n`)
  439. }
  440. // isNegative returns true if the node is considered as "negative" for the
  441. // purposes of drop_negative.
  442. func isNegative(n *Node) bool {
  443. switch {
  444. case n.Flat < 0:
  445. return true
  446. case n.Flat == 0 && n.Cum < 0:
  447. return true
  448. default:
  449. return false
  450. }
  451. }
  452. // CreateNodes creates graph nodes for all locations in a profile. It
  453. // returns set of all nodes, plus a mapping of each location to the
  454. // set of corresponding nodes (one per location.Line). If kept is
  455. // non-nil, only nodes in that set are included; nodes that do not
  456. // match are represented as a nil.
  457. func CreateNodes(prof *profile.Profile, o *Options) (Nodes, map[uint64]Nodes) {
  458. locations := make(map[uint64]Nodes, len(prof.Location))
  459. nm := make(NodeMap, len(prof.Location))
  460. for _, l := range prof.Location {
  461. lines := l.Line
  462. if len(lines) == 0 {
  463. lines = []profile.Line{{}} // Create empty line to include location info.
  464. }
  465. nodes := make(Nodes, len(lines))
  466. for ln := range lines {
  467. nodes[ln] = nm.findOrInsertLine(l, lines[ln], o)
  468. }
  469. locations[l.ID] = nodes
  470. }
  471. return nm.nodes(), locations
  472. }
  473. func (nm NodeMap) nodes() Nodes {
  474. nodes := make(Nodes, 0, len(nm))
  475. for _, n := range nm {
  476. nodes = append(nodes, n)
  477. }
  478. return nodes
  479. }
  480. func (nm NodeMap) findOrInsertLine(l *profile.Location, li profile.Line, o *Options) *Node {
  481. var objfile string
  482. if m := l.Mapping; m != nil && m.File != "" {
  483. objfile = m.File
  484. }
  485. if ni := nodeInfo(l, li, objfile, o); ni != nil {
  486. return nm.FindOrInsertNode(*ni, o.KeptNodes)
  487. }
  488. return nil
  489. }
  490. func nodeInfo(l *profile.Location, line profile.Line, objfile string, o *Options) *NodeInfo {
  491. if line.Function == nil {
  492. return &NodeInfo{Address: l.Address, Objfile: objfile}
  493. }
  494. ni := &NodeInfo{
  495. Address: l.Address,
  496. Lineno: int(line.Line),
  497. Name: line.Function.Name,
  498. }
  499. if fname := line.Function.Filename; fname != "" {
  500. ni.File = filepath.Clean(fname)
  501. }
  502. if o.ObjNames {
  503. ni.Objfile = objfile
  504. ni.StartLine = int(line.Function.StartLine)
  505. }
  506. if o.OrigFnNames {
  507. ni.OrigName = line.Function.SystemName
  508. }
  509. return ni
  510. }
  511. type tags struct {
  512. t []*Tag
  513. flat bool
  514. }
  515. func (t tags) Len() int { return len(t.t) }
  516. func (t tags) Swap(i, j int) { t.t[i], t.t[j] = t.t[j], t.t[i] }
  517. func (t tags) Less(i, j int) bool {
  518. if !t.flat {
  519. if t.t[i].Cum != t.t[j].Cum {
  520. return abs64(t.t[i].Cum) > abs64(t.t[j].Cum)
  521. }
  522. }
  523. if t.t[i].Flat != t.t[j].Flat {
  524. return abs64(t.t[i].Flat) > abs64(t.t[j].Flat)
  525. }
  526. return t.t[i].Name < t.t[j].Name
  527. }
  528. // Sum adds the flat and cum values of a set of nodes.
  529. func (ns Nodes) Sum() (flat int64, cum int64) {
  530. for _, n := range ns {
  531. flat += n.Flat
  532. cum += n.Cum
  533. }
  534. return
  535. }
  536. func (n *Node) addSample(dw, w int64, labels string, numLabel map[string][]int64, numUnit map[string][]string, format func(int64, string) string, flat bool) {
  537. // Update sample value
  538. if flat {
  539. n.FlatDiv += dw
  540. n.Flat += w
  541. } else {
  542. n.CumDiv += dw
  543. n.Cum += w
  544. }
  545. // Add string tags
  546. if labels != "" {
  547. t := n.LabelTags.findOrAddTag(labels, "", 0)
  548. if flat {
  549. t.FlatDiv += dw
  550. t.Flat += w
  551. } else {
  552. t.CumDiv += dw
  553. t.Cum += w
  554. }
  555. }
  556. numericTags := n.NumericTags[labels]
  557. if numericTags == nil {
  558. numericTags = TagMap{}
  559. n.NumericTags[labels] = numericTags
  560. }
  561. // Add numeric tags
  562. if format == nil {
  563. format = defaultLabelFormat
  564. }
  565. for k, nvals := range numLabel {
  566. units := numUnit[k]
  567. for i, v := range nvals {
  568. var t *Tag
  569. if len(units) > 0 {
  570. t = numericTags.findOrAddTag(format(v, units[i]), units[i], v)
  571. } else {
  572. t = numericTags.findOrAddTag(format(v, k), k, v)
  573. }
  574. if flat {
  575. t.FlatDiv += dw
  576. t.Flat += w
  577. } else {
  578. t.CumDiv += dw
  579. t.Cum += w
  580. }
  581. }
  582. }
  583. }
  584. func defaultLabelFormat(v int64, key string) string {
  585. return strconv.FormatInt(v, 10)
  586. }
  587. func (m TagMap) findOrAddTag(label, unit string, value int64) *Tag {
  588. l := m[label]
  589. if l == nil {
  590. l = &Tag{
  591. Name: label,
  592. Unit: unit,
  593. Value: value,
  594. }
  595. m[label] = l
  596. }
  597. return l
  598. }
  599. // String returns a text representation of a graph, for debugging purposes.
  600. func (g *Graph) String() string {
  601. var s []string
  602. nodeIndex := make(map[*Node]int, len(g.Nodes))
  603. for i, n := range g.Nodes {
  604. nodeIndex[n] = i + 1
  605. }
  606. for i, n := range g.Nodes {
  607. name := n.Info.PrintableName()
  608. var in, out []int
  609. for _, from := range n.In {
  610. in = append(in, nodeIndex[from.Src])
  611. }
  612. for _, to := range n.Out {
  613. out = append(out, nodeIndex[to.Dest])
  614. }
  615. s = append(s, fmt.Sprintf("%d: %s[flat=%d cum=%d] %x -> %v ", i+1, name, n.Flat, n.Cum, in, out))
  616. }
  617. return strings.Join(s, "\n")
  618. }
  619. // DiscardLowFrequencyNodes returns a set of the nodes at or over a
  620. // specific cum value cutoff.
  621. func (g *Graph) DiscardLowFrequencyNodes(nodeCutoff int64) NodeSet {
  622. return makeNodeSet(g.Nodes, nodeCutoff)
  623. }
  624. // DiscardLowFrequencyNodePtrs returns a NodePtrSet of nodes at or over a
  625. // specific cum value cutoff.
  626. func (g *Graph) DiscardLowFrequencyNodePtrs(nodeCutoff int64) NodePtrSet {
  627. cutNodes := getNodesAboveCumCutoff(g.Nodes, nodeCutoff)
  628. kept := make(NodePtrSet, len(cutNodes))
  629. for _, n := range cutNodes {
  630. kept[n] = true
  631. }
  632. return kept
  633. }
  634. func makeNodeSet(nodes Nodes, nodeCutoff int64) NodeSet {
  635. cutNodes := getNodesAboveCumCutoff(nodes, nodeCutoff)
  636. kept := make(NodeSet, len(cutNodes))
  637. for _, n := range cutNodes {
  638. kept[n.Info] = true
  639. }
  640. return kept
  641. }
  642. // getNodesAboveCumCutoff returns all the nodes which have a Cum value greater
  643. // than or equal to cutoff.
  644. func getNodesAboveCumCutoff(nodes Nodes, nodeCutoff int64) Nodes {
  645. cutoffNodes := make(Nodes, 0, len(nodes))
  646. for _, n := range nodes {
  647. if abs64(n.Cum) < nodeCutoff {
  648. continue
  649. }
  650. cutoffNodes = append(cutoffNodes, n)
  651. }
  652. return cutoffNodes
  653. }
  654. // TrimLowFrequencyTags removes tags that have less than
  655. // the specified weight.
  656. func (g *Graph) TrimLowFrequencyTags(tagCutoff int64) {
  657. // Remove nodes with value <= total*nodeFraction
  658. for _, n := range g.Nodes {
  659. n.LabelTags = trimLowFreqTags(n.LabelTags, tagCutoff)
  660. for s, nt := range n.NumericTags {
  661. n.NumericTags[s] = trimLowFreqTags(nt, tagCutoff)
  662. }
  663. }
  664. }
  665. func trimLowFreqTags(tags TagMap, minValue int64) TagMap {
  666. kept := TagMap{}
  667. for s, t := range tags {
  668. if abs64(t.Flat) >= minValue || abs64(t.Cum) >= minValue {
  669. kept[s] = t
  670. }
  671. }
  672. return kept
  673. }
  674. // TrimLowFrequencyEdges removes edges that have less than
  675. // the specified weight. Returns the number of edges removed
  676. func (g *Graph) TrimLowFrequencyEdges(edgeCutoff int64) int {
  677. var droppedEdges int
  678. for _, n := range g.Nodes {
  679. for src, e := range n.In {
  680. if abs64(e.Weight) < edgeCutoff {
  681. delete(n.In, src)
  682. delete(src.Out, n)
  683. droppedEdges++
  684. }
  685. }
  686. }
  687. return droppedEdges
  688. }
  689. // SortNodes sorts the nodes in a graph based on a specific heuristic.
  690. func (g *Graph) SortNodes(cum bool, visualMode bool) {
  691. // Sort nodes based on requested mode
  692. switch {
  693. case visualMode:
  694. // Specialized sort to produce a more visually-interesting graph
  695. g.Nodes.Sort(EntropyOrder)
  696. case cum:
  697. g.Nodes.Sort(CumNameOrder)
  698. default:
  699. g.Nodes.Sort(FlatNameOrder)
  700. }
  701. }
  702. // SelectTopNodePtrs returns a set of the top maxNodes *Node in a graph.
  703. func (g *Graph) SelectTopNodePtrs(maxNodes int, visualMode bool) NodePtrSet {
  704. set := make(NodePtrSet)
  705. for _, node := range g.selectTopNodes(maxNodes, visualMode) {
  706. set[node] = true
  707. }
  708. return set
  709. }
  710. // SelectTopNodes returns a set of the top maxNodes nodes in a graph.
  711. func (g *Graph) SelectTopNodes(maxNodes int, visualMode bool) NodeSet {
  712. return makeNodeSet(g.selectTopNodes(maxNodes, visualMode), 0)
  713. }
  714. // selectTopNodes returns a slice of the top maxNodes nodes in a graph.
  715. func (g *Graph) selectTopNodes(maxNodes int, visualMode bool) Nodes {
  716. if maxNodes > 0 {
  717. if visualMode {
  718. var count int
  719. // If generating a visual graph, count tags as nodes. Update
  720. // maxNodes to account for them.
  721. for i, n := range g.Nodes {
  722. tags := countTags(n)
  723. if tags > maxNodelets {
  724. tags = maxNodelets
  725. }
  726. if count += tags + 1; count >= maxNodes {
  727. maxNodes = i + 1
  728. break
  729. }
  730. }
  731. }
  732. }
  733. if maxNodes > len(g.Nodes) {
  734. maxNodes = len(g.Nodes)
  735. }
  736. return g.Nodes[:maxNodes]
  737. }
  738. // countTags counts the tags with flat count. This underestimates the
  739. // number of tags being displayed, but in practice is close enough.
  740. func countTags(n *Node) int {
  741. count := 0
  742. for _, e := range n.LabelTags {
  743. if e.Flat != 0 {
  744. count++
  745. }
  746. }
  747. for _, t := range n.NumericTags {
  748. for _, e := range t {
  749. if e.Flat != 0 {
  750. count++
  751. }
  752. }
  753. }
  754. return count
  755. }
  756. // RemoveRedundantEdges removes residual edges if the destination can
  757. // be reached through another path. This is done to simplify the graph
  758. // while preserving connectivity.
  759. func (g *Graph) RemoveRedundantEdges() {
  760. // Walk the nodes and outgoing edges in reverse order to prefer
  761. // removing edges with the lowest weight.
  762. for i := len(g.Nodes); i > 0; i-- {
  763. n := g.Nodes[i-1]
  764. in := n.In.Sort()
  765. for j := len(in); j > 0; j-- {
  766. e := in[j-1]
  767. if !e.Residual {
  768. // Do not remove edges heavier than a non-residual edge, to
  769. // avoid potential confusion.
  770. break
  771. }
  772. if isRedundantEdge(e) {
  773. delete(e.Src.Out, e.Dest)
  774. delete(e.Dest.In, e.Src)
  775. }
  776. }
  777. }
  778. }
  779. // isRedundantEdge determines if there is a path that allows e.Src
  780. // to reach e.Dest after removing e.
  781. func isRedundantEdge(e *Edge) bool {
  782. src, n := e.Src, e.Dest
  783. seen := map[*Node]bool{n: true}
  784. queue := Nodes{n}
  785. for len(queue) > 0 {
  786. n := queue[0]
  787. queue = queue[1:]
  788. for _, ie := range n.In {
  789. if e == ie || seen[ie.Src] {
  790. continue
  791. }
  792. if ie.Src == src {
  793. return true
  794. }
  795. seen[ie.Src] = true
  796. queue = append(queue, ie.Src)
  797. }
  798. }
  799. return false
  800. }
  801. // nodeSorter is a mechanism used to allow a report to be sorted
  802. // in different ways.
  803. type nodeSorter struct {
  804. rs Nodes
  805. less func(l, r *Node) bool
  806. }
  807. func (s nodeSorter) Len() int { return len(s.rs) }
  808. func (s nodeSorter) Swap(i, j int) { s.rs[i], s.rs[j] = s.rs[j], s.rs[i] }
  809. func (s nodeSorter) Less(i, j int) bool { return s.less(s.rs[i], s.rs[j]) }
  810. // Sort reorders a slice of nodes based on the specified ordering
  811. // criteria. The result is sorted in decreasing order for (absolute)
  812. // numeric quantities, alphabetically for text, and increasing for
  813. // addresses.
  814. func (ns Nodes) Sort(o NodeOrder) error {
  815. var s nodeSorter
  816. switch o {
  817. case FlatNameOrder:
  818. s = nodeSorter{ns,
  819. func(l, r *Node) bool {
  820. if iv, jv := abs64(l.Flat), abs64(r.Flat); iv != jv {
  821. return iv > jv
  822. }
  823. if iv, jv := l.Info.PrintableName(), r.Info.PrintableName(); iv != jv {
  824. return iv < jv
  825. }
  826. if iv, jv := abs64(l.Cum), abs64(r.Cum); iv != jv {
  827. return iv > jv
  828. }
  829. return compareNodes(l, r)
  830. },
  831. }
  832. case FlatCumNameOrder:
  833. s = nodeSorter{ns,
  834. func(l, r *Node) bool {
  835. if iv, jv := abs64(l.Flat), abs64(r.Flat); iv != jv {
  836. return iv > jv
  837. }
  838. if iv, jv := abs64(l.Cum), abs64(r.Cum); iv != jv {
  839. return iv > jv
  840. }
  841. if iv, jv := l.Info.PrintableName(), r.Info.PrintableName(); iv != jv {
  842. return iv < jv
  843. }
  844. return compareNodes(l, r)
  845. },
  846. }
  847. case NameOrder:
  848. s = nodeSorter{ns,
  849. func(l, r *Node) bool {
  850. if iv, jv := l.Info.Name, r.Info.Name; iv != jv {
  851. return iv < jv
  852. }
  853. return compareNodes(l, r)
  854. },
  855. }
  856. case FileOrder:
  857. s = nodeSorter{ns,
  858. func(l, r *Node) bool {
  859. if iv, jv := l.Info.File, r.Info.File; iv != jv {
  860. return iv < jv
  861. }
  862. if iv, jv := l.Info.StartLine, r.Info.StartLine; iv != jv {
  863. return iv < jv
  864. }
  865. return compareNodes(l, r)
  866. },
  867. }
  868. case AddressOrder:
  869. s = nodeSorter{ns,
  870. func(l, r *Node) bool {
  871. if iv, jv := l.Info.Address, r.Info.Address; iv != jv {
  872. return iv < jv
  873. }
  874. return compareNodes(l, r)
  875. },
  876. }
  877. case CumNameOrder, EntropyOrder:
  878. // Hold scoring for score-based ordering
  879. var score map[*Node]int64
  880. scoreOrder := func(l, r *Node) bool {
  881. if iv, jv := abs64(score[l]), abs64(score[r]); iv != jv {
  882. return iv > jv
  883. }
  884. if iv, jv := l.Info.PrintableName(), r.Info.PrintableName(); iv != jv {
  885. return iv < jv
  886. }
  887. if iv, jv := abs64(l.Flat), abs64(r.Flat); iv != jv {
  888. return iv > jv
  889. }
  890. return compareNodes(l, r)
  891. }
  892. switch o {
  893. case CumNameOrder:
  894. score = make(map[*Node]int64, len(ns))
  895. for _, n := range ns {
  896. score[n] = n.Cum
  897. }
  898. s = nodeSorter{ns, scoreOrder}
  899. case EntropyOrder:
  900. score = make(map[*Node]int64, len(ns))
  901. for _, n := range ns {
  902. score[n] = entropyScore(n)
  903. }
  904. s = nodeSorter{ns, scoreOrder}
  905. }
  906. default:
  907. return fmt.Errorf("report: unrecognized sort ordering: %d", o)
  908. }
  909. sort.Sort(s)
  910. return nil
  911. }
  912. // compareNodes compares two nodes to provide a deterministic ordering
  913. // between them. Two nodes cannot have the same Node.Info value.
  914. func compareNodes(l, r *Node) bool {
  915. return fmt.Sprint(l.Info) < fmt.Sprint(r.Info)
  916. }
  917. // entropyScore computes a score for a node representing how important
  918. // it is to include this node on a graph visualization. It is used to
  919. // sort the nodes and select which ones to display if we have more
  920. // nodes than desired in the graph. This number is computed by looking
  921. // at the flat and cum weights of the node and the incoming/outgoing
  922. // edges. The fundamental idea is to penalize nodes that have a simple
  923. // fallthrough from their incoming to the outgoing edge.
  924. func entropyScore(n *Node) int64 {
  925. score := float64(0)
  926. if len(n.In) == 0 {
  927. score++ // Favor entry nodes
  928. } else {
  929. score += edgeEntropyScore(n, n.In, 0)
  930. }
  931. if len(n.Out) == 0 {
  932. score++ // Favor leaf nodes
  933. } else {
  934. score += edgeEntropyScore(n, n.Out, n.Flat)
  935. }
  936. return int64(score*float64(n.Cum)) + n.Flat
  937. }
  938. // edgeEntropyScore computes the entropy value for a set of edges
  939. // coming in or out of a node. Entropy (as defined in information
  940. // theory) refers to the amount of information encoded by the set of
  941. // edges. A set of edges that have a more interesting distribution of
  942. // samples gets a higher score.
  943. func edgeEntropyScore(n *Node, edges EdgeMap, self int64) float64 {
  944. score := float64(0)
  945. total := self
  946. for _, e := range edges {
  947. if e.Weight > 0 {
  948. total += abs64(e.Weight)
  949. }
  950. }
  951. if total != 0 {
  952. for _, e := range edges {
  953. frac := float64(abs64(e.Weight)) / float64(total)
  954. score += -frac * math.Log2(frac)
  955. }
  956. if self > 0 {
  957. frac := float64(abs64(self)) / float64(total)
  958. score += -frac * math.Log2(frac)
  959. }
  960. }
  961. return score
  962. }
  963. // NodeOrder sets the ordering for a Sort operation
  964. type NodeOrder int
  965. // Sorting options for node sort.
  966. const (
  967. FlatNameOrder NodeOrder = iota
  968. FlatCumNameOrder
  969. CumNameOrder
  970. NameOrder
  971. FileOrder
  972. AddressOrder
  973. EntropyOrder
  974. )
  975. // Sort returns a slice of the edges in the map, in a consistent
  976. // order. The sort order is first based on the edge weight
  977. // (higher-to-lower) and then by the node names to avoid flakiness.
  978. func (e EdgeMap) Sort() []*Edge {
  979. el := make(edgeList, 0, len(e))
  980. for _, w := range e {
  981. el = append(el, w)
  982. }
  983. sort.Sort(el)
  984. return el
  985. }
  986. // Sum returns the total weight for a set of nodes.
  987. func (e EdgeMap) Sum() int64 {
  988. var ret int64
  989. for _, edge := range e {
  990. ret += edge.Weight
  991. }
  992. return ret
  993. }
  994. type edgeList []*Edge
  995. func (el edgeList) Len() int {
  996. return len(el)
  997. }
  998. func (el edgeList) Less(i, j int) bool {
  999. if el[i].Weight != el[j].Weight {
  1000. return abs64(el[i].Weight) > abs64(el[j].Weight)
  1001. }
  1002. from1 := el[i].Src.Info.PrintableName()
  1003. from2 := el[j].Src.Info.PrintableName()
  1004. if from1 != from2 {
  1005. return from1 < from2
  1006. }
  1007. to1 := el[i].Dest.Info.PrintableName()
  1008. to2 := el[j].Dest.Info.PrintableName()
  1009. return to1 < to2
  1010. }
  1011. func (el edgeList) Swap(i, j int) {
  1012. el[i], el[j] = el[j], el[i]
  1013. }
  1014. func abs64(i int64) int64 {
  1015. if i < 0 {
  1016. return -i
  1017. }
  1018. return i
  1019. }