説明なし

graph.go 28KB

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