Bez popisu

graph.go 26KB

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