Ingen beskrivning

graph.go 27KB

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