설명 없음

graph.go 26KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017
  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. "strconv"
  23. "strings"
  24. "github.com/google/pprof/profile"
  25. )
  26. // Graph summarizes a performance profile into a format that is
  27. // suitable for visualization.
  28. type Graph struct {
  29. Nodes Nodes
  30. }
  31. // Options encodes the options for constructing a graph
  32. type Options struct {
  33. SampleValue func(s []int64) int64 // Function to compute the value of a sample
  34. FormatTag func(int64, string) string // Function to format a sample tag value into a string
  35. ObjNames bool // Always preserve obj filename
  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. // Information associated to this entry.
  46. Info NodeInfo
  47. // values associated to this node.
  48. // Flat is exclusive to this node, cum includes all descendents.
  49. Flat, Cum int64
  50. // in and out contains the nodes immediately reaching or reached by this nodes.
  51. In, Out EdgeMap
  52. // tags provide additional information about subsets of a sample.
  53. LabelTags TagMap
  54. // Numeric tags provide additional values for subsets of a sample.
  55. // Numeric tags are optionally associated to a label tag. The key
  56. // for NumericTags is the name of the LabelTag they are associated
  57. // to, or "" for numeric tags not associated to a label tag.
  58. NumericTags map[string]TagMap
  59. }
  60. // AddToEdge increases the weight of an edge between two nodes. If
  61. // there isn't such an edge one is created.
  62. func (n *Node) AddToEdge(to *Node, w int64, residual, inline bool) {
  63. if n.Out[to] != to.In[n] {
  64. panic(fmt.Errorf("asymmetric edges %v %v", *n, *to))
  65. }
  66. if e := n.Out[to]; e != nil {
  67. e.Weight += w
  68. if residual {
  69. e.Residual = true
  70. }
  71. if !inline {
  72. e.Inline = false
  73. }
  74. return
  75. }
  76. info := &Edge{Src: n, Dest: to, Weight: w, Residual: residual, Inline: inline}
  77. n.Out[to] = info
  78. to.In[n] = info
  79. }
  80. // NodeInfo contains the attributes for a node.
  81. type NodeInfo struct {
  82. Name string
  83. OrigName string
  84. Address uint64
  85. File string
  86. StartLine, Lineno int
  87. Objfile string
  88. }
  89. // PrintableName calls the Node's Formatter function with a single space separator.
  90. func (i *NodeInfo) PrintableName() string {
  91. return strings.Join(i.NameComponents(), " ")
  92. }
  93. // NameComponents returns the components of the printable name to be used for a node.
  94. func (i *NodeInfo) NameComponents() []string {
  95. var name []string
  96. if i.Address != 0 {
  97. name = append(name, fmt.Sprintf("%016x", i.Address))
  98. }
  99. if fun := i.Name; fun != "" {
  100. name = append(name, fun)
  101. }
  102. switch {
  103. case i.Lineno != 0:
  104. // User requested line numbers, provide what we have.
  105. name = append(name, fmt.Sprintf("%s:%d", i.File, i.Lineno))
  106. case i.File != "":
  107. // User requested file name, provide it.
  108. name = append(name, i.File)
  109. case i.Name != "":
  110. // User requested function name. It was already included.
  111. case i.Objfile != "":
  112. // Only binary name is available
  113. name = append(name, "["+i.Objfile+"]")
  114. default:
  115. // Do not leave it empty if there is no information at all.
  116. name = append(name, "<unknown>")
  117. }
  118. return name
  119. }
  120. // NodeMap maps from a node info struct to a node. It is used to merge
  121. // report entries with the same info.
  122. type NodeMap map[NodeInfo]*Node
  123. // NodeSet maps is a collection of node info structs.
  124. type NodeSet struct {
  125. Info map[NodeInfo]bool
  126. Ptr map[*Node]bool
  127. }
  128. // FindOrInsertNode takes the info for a node and either returns a matching node
  129. // from the node map if one exists, or adds one to the map if one does not.
  130. // If kept is non-nil, nodes are only added if they can be located on it.
  131. func (nm NodeMap) FindOrInsertNode(info NodeInfo, kept NodeSet) *Node {
  132. if kept.Info != nil {
  133. if _, ok := kept.Info[info]; !ok {
  134. return nil
  135. }
  136. }
  137. if n, ok := nm[info]; ok {
  138. return n
  139. }
  140. n := &Node{
  141. Info: info,
  142. In: make(EdgeMap),
  143. Out: make(EdgeMap),
  144. LabelTags: make(TagMap),
  145. NumericTags: make(map[string]TagMap),
  146. }
  147. nm[info] = n
  148. return n
  149. }
  150. // EdgeMap is used to represent the incoming/outgoing edges from a node.
  151. type EdgeMap map[*Node]*Edge
  152. // Edge contains any attributes to be represented about edges in a graph.
  153. type Edge struct {
  154. Src, Dest *Node
  155. // The summary weight of the edge
  156. Weight int64
  157. // residual edges connect nodes that were connected through a
  158. // separate node, which has been removed from the report.
  159. Residual bool
  160. // An inline edge represents a call that was inlined into the caller.
  161. Inline bool
  162. }
  163. // Tag represent sample annotations
  164. type Tag struct {
  165. Name string
  166. Unit string // Describe the value, "" for non-numeric tags
  167. Value int64
  168. Flat int64
  169. Cum int64
  170. }
  171. // TagMap is a collection of tags, classified by their name.
  172. type TagMap map[string]*Tag
  173. // SortTags sorts a slice of tags based on their weight.
  174. func SortTags(t []*Tag, flat bool) []*Tag {
  175. ts := tags{t, flat}
  176. sort.Sort(ts)
  177. return ts.t
  178. }
  179. // New summarizes performance data from a profile into a graph.
  180. func New(prof *profile.Profile, o *Options) *Graph {
  181. if o.CallTree {
  182. return newTree(prof, o)
  183. }
  184. g, _ := newGraph(prof, o)
  185. return g
  186. }
  187. // newGraph computes a graph from a profile. It returns the graph, and
  188. // a map from the profile location indices to the corresponding graph
  189. // nodes.
  190. func newGraph(prof *profile.Profile, o *Options) (*Graph, map[uint64]Nodes) {
  191. nodes, locationMap := CreateNodes(prof, o.ObjNames, o.KeptNodes)
  192. for _, sample := range prof.Sample {
  193. weight := o.SampleValue(sample.Value)
  194. if weight == 0 {
  195. continue
  196. }
  197. seenNode := make(map[*Node]bool, len(sample.Location))
  198. seenEdge := make(map[nodePair]bool, len(sample.Location))
  199. var parent *Node
  200. // A residual edge goes over one or more nodes that were not kept.
  201. residual := false
  202. labels := joinLabels(sample)
  203. // Group the sample frames, based on a global map.
  204. for i := len(sample.Location) - 1; i >= 0; i-- {
  205. l := sample.Location[i]
  206. locNodes := locationMap[l.ID]
  207. for ni := len(locNodes) - 1; ni >= 0; ni-- {
  208. n := locNodes[ni]
  209. if n == nil {
  210. residual = true
  211. continue
  212. }
  213. // Add cum weight to all nodes in stack, avoiding double counting.
  214. if _, ok := seenNode[n]; !ok {
  215. seenNode[n] = true
  216. n.addSample(weight, labels, sample.NumLabel, o.FormatTag, false)
  217. }
  218. // Update edge weights for all edges in stack, avoiding double counting.
  219. if _, ok := seenEdge[nodePair{n, parent}]; !ok && parent != nil && n != parent {
  220. seenEdge[nodePair{n, parent}] = true
  221. parent.AddToEdge(n, weight, residual, ni != len(locNodes)-1)
  222. }
  223. parent = n
  224. residual = false
  225. }
  226. }
  227. if parent != nil && !residual {
  228. // Add flat weight to leaf node.
  229. parent.addSample(weight, labels, sample.NumLabel, o.FormatTag, true)
  230. }
  231. }
  232. return selectNodesForGraph(nodes, o.DropNegative), locationMap
  233. }
  234. func selectNodesForGraph(nodes Nodes, dropNegative bool) *Graph {
  235. // Collect nodes into a graph.
  236. gNodes := make(Nodes, 0, len(nodes))
  237. for _, n := range nodes {
  238. if n == nil {
  239. continue
  240. }
  241. if n.Cum == 0 && n.Flat == 0 {
  242. continue
  243. }
  244. if dropNegative && isNegative(n) {
  245. continue
  246. }
  247. gNodes = append(gNodes, n)
  248. }
  249. return &Graph{gNodes}
  250. }
  251. type nodePair struct {
  252. src, dest *Node
  253. }
  254. func newTree(prof *profile.Profile, o *Options) (g *Graph) {
  255. kept := o.KeptNodes
  256. keepBinary := o.ObjNames
  257. parentNodeMap := make(map[*Node]NodeMap, len(prof.Sample))
  258. for _, sample := range prof.Sample {
  259. weight := o.SampleValue(sample.Value)
  260. if weight == 0 {
  261. continue
  262. }
  263. var parent *Node
  264. labels := joinLabels(sample)
  265. // Group the sample frames, based on a per-node map.
  266. for i := len(sample.Location) - 1; i >= 0; i-- {
  267. l := sample.Location[i]
  268. lines := l.Line
  269. if len(lines) == 0 {
  270. lines = []profile.Line{{}} // Create empty line to include location info.
  271. }
  272. for lidx := len(lines) - 1; lidx >= 0; lidx-- {
  273. nodeMap := parentNodeMap[parent]
  274. if nodeMap == nil {
  275. nodeMap = make(NodeMap)
  276. parentNodeMap[parent] = nodeMap
  277. }
  278. n := nodeMap.findOrInsertLine(l, lines[lidx], keepBinary, kept)
  279. if n == nil {
  280. continue
  281. }
  282. n.addSample(weight, labels, sample.NumLabel, o.FormatTag, false)
  283. if parent != nil {
  284. parent.AddToEdge(n, weight, false, lidx != len(lines)-1)
  285. }
  286. parent = n
  287. }
  288. }
  289. if parent != nil {
  290. parent.addSample(weight, labels, sample.NumLabel, o.FormatTag, true)
  291. }
  292. }
  293. nodes := make(Nodes, len(prof.Location))
  294. for _, nm := range parentNodeMap {
  295. nodes = append(nodes, nm.nodes()...)
  296. }
  297. return selectNodesForGraph(nodes, o.DropNegative)
  298. }
  299. // Trims a Graph that is in forest form to contain only the nodes in kept. This
  300. // will not work correctly in the case that a node has multiple parents.
  301. func (g *Graph) TrimTree(kept NodeSet) {
  302. // Creates a new list of nodes
  303. oldNodes := g.Nodes
  304. g.Nodes = make(Nodes, 0, len(kept.Ptr))
  305. for _, cur := range oldNodes {
  306. // A node may not have multiple parents
  307. if len(cur.In) > 1 {
  308. fmt.Fprintf(os.Stderr, "ERROR: TrimTree only works on trees.\n")
  309. }
  310. // If a node should be kept, add it to the next list of nodes
  311. if _, ok := kept.Ptr[cur]; ok {
  312. g.Nodes = append(g.Nodes, cur)
  313. continue
  314. }
  315. // Get the parent. Since cur.In may only be of size 0 or 1, parent will be
  316. // equal to either nil or the only node in cur.In
  317. var parent *Node
  318. for _, edge := range cur.In {
  319. parent = edge.Src
  320. }
  321. if parent != nil {
  322. // Remove the edge from the parent to this node
  323. delete(parent.Out, cur)
  324. // Reconfigure every edge from the current node to now begin at the parent.
  325. for _, outEdge := range cur.Out {
  326. child := outEdge.Dest
  327. delete(child.In, cur)
  328. child.In[parent] = outEdge
  329. parent.Out[child] = outEdge
  330. outEdge.Src = parent
  331. outEdge.Residual = true
  332. // Any reconfigured edge can no longer be Inline.
  333. outEdge.Inline = false
  334. }
  335. } else {
  336. // If a node has no parents, delete all the in edges of the children to make them
  337. // all roots of their own trees.
  338. for _, outEdge := range cur.Out {
  339. delete(outEdge.Dest.In, cur)
  340. }
  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. }