Нема описа

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873
  1. // Copyright 2014 Google Inc. All Rights Reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. // Package graph collects a set of samples into a directed graph.
  15. package graph
  16. import (
  17. "fmt"
  18. "math"
  19. "path/filepath"
  20. "sort"
  21. "strconv"
  22. "strings"
  23. "github.com/google/pprof/profile"
  24. )
  25. // Graph summarizes a performance profile into a format that is
  26. // suitable for visualization.
  27. type Graph struct {
  28. Nodes Nodes
  29. }
  30. // Options encodes the options for constructing a graph
  31. type Options struct {
  32. SampleValue func(s []int64) int64 // Function to compute the value of a sample
  33. FormatTag func(int64, string) string // Function to format a sample tag value into a string
  34. ObjNames bool // Always preserve obj filename
  35. CallTree bool // Build a tree instead of a graph
  36. DropNegative bool // Drop nodes with overall negative values
  37. KeptNodes NodeSet // If non-nil, only use nodes in this set
  38. }
  39. // Nodes is an ordered collection of graph nodes.
  40. type Nodes []*Node
  41. // Node is an entry on a profiling report. It represents a unique
  42. // program location.
  43. type Node struct {
  44. // Information associated to this entry.
  45. Info NodeInfo
  46. // values associated to this node.
  47. // Flat is exclusive to this node, cum includes all descendents.
  48. Flat, Cum int64
  49. // in and out contains the nodes immediately reaching or reached by this nodes.
  50. In, Out EdgeMap
  51. // tags provide additional information about subsets of a sample.
  52. LabelTags TagMap
  53. // Numeric tags provide additional values for subsets of a sample.
  54. // Numeric tags are optionally associated to a label tag. The key
  55. // for NumericTags is the name of the LabelTag they are associated
  56. // to, or "" for numeric tags not associated to a label tag.
  57. NumericTags map[string]TagMap
  58. }
  59. // BumpWeight increases the weight of an edge between two nodes. If
  60. // there isn't such an edge one is created.
  61. func (n *Node) BumpWeight(to *Node, w int64, residual, inline bool) {
  62. if n.Out[to] != to.In[n] {
  63. panic(fmt.Errorf("asymmetric edges %v %v", *n, *to))
  64. }
  65. if e := n.Out[to]; e != nil {
  66. e.Weight += w
  67. if residual {
  68. e.Residual = true
  69. }
  70. if !inline {
  71. e.Inline = false
  72. }
  73. return
  74. }
  75. info := &Edge{Src: n, Dest: to, Weight: w, Residual: residual, Inline: inline}
  76. n.Out[to] = info
  77. to.In[n] = info
  78. }
  79. // NodeInfo contains the attributes for a node.
  80. type NodeInfo struct {
  81. Name string
  82. OrigName string
  83. Address uint64
  84. File string
  85. StartLine, Lineno int
  86. Objfile string
  87. }
  88. // PrintableName calls the Node's Formatter function with a single space separator.
  89. func (i *NodeInfo) PrintableName() string {
  90. return strings.Join(i.NameComponents(), " ")
  91. }
  92. // NameComponents returns the components of the printable name to be used for a node.
  93. func (i *NodeInfo) NameComponents() []string {
  94. var name []string
  95. if i.Address != 0 {
  96. name = append(name, fmt.Sprintf("%016x", i.Address))
  97. }
  98. if fun := i.Name; fun != "" {
  99. name = append(name, fun)
  100. }
  101. switch {
  102. case i.Lineno != 0:
  103. // User requested line numbers, provide what we have.
  104. name = append(name, fmt.Sprintf("%s:%d", i.File, i.Lineno))
  105. case i.File != "":
  106. // User requested file name, provide it.
  107. name = append(name, i.File)
  108. case i.Name != "":
  109. // User requested function name. It was already included.
  110. case i.Objfile != "":
  111. // Only binary name is available
  112. name = append(name, "["+i.Objfile+"]")
  113. default:
  114. // Do not leave it empty if there is no information at all.
  115. name = append(name, "<unknown>")
  116. }
  117. return name
  118. }
  119. // ExtendedNodeInfo extends the NodeInfo with a pointer to a parent node, to
  120. // identify nodes with identical information and different callers. This is
  121. // used when creating call trees.
  122. type ExtendedNodeInfo struct {
  123. NodeInfo
  124. parent *Node
  125. }
  126. // NodeMap maps from a node info struct to a node. It is used to merge
  127. // report entries with the same info.
  128. type NodeMap map[ExtendedNodeInfo]*Node
  129. // NodeSet maps is a collection of node info structs.
  130. type NodeSet map[NodeInfo]bool
  131. // FindOrInsertNode takes the info for a node and either returns a matching node
  132. // from the node map if one exists, or adds one to the map if one does not.
  133. // If parent is non-nil, return a match with the same parent.
  134. // If kept is non-nil, nodes are only added if they can be located on it.
  135. func (m NodeMap) FindOrInsertNode(info NodeInfo, parent *Node, kept NodeSet) *Node {
  136. if kept != nil {
  137. if _, ok := kept[info]; !ok {
  138. return nil
  139. }
  140. }
  141. extendedInfo := ExtendedNodeInfo{
  142. info,
  143. parent,
  144. }
  145. if n, ok := m[extendedInfo]; ok {
  146. return n
  147. }
  148. n := &Node{
  149. Info: info,
  150. In: make(EdgeMap),
  151. Out: make(EdgeMap),
  152. LabelTags: make(TagMap),
  153. NumericTags: make(map[string]TagMap),
  154. }
  155. m[extendedInfo] = n
  156. return n
  157. }
  158. // EdgeMap is used to represent the incoming/outgoing edges from a node.
  159. type EdgeMap map[*Node]*Edge
  160. // Edge contains any attributes to be represented about edges in a graph.
  161. type Edge struct {
  162. Src, Dest *Node
  163. // The summary weight of the edge
  164. Weight int64
  165. // residual edges connect nodes that were connected through a
  166. // separate node, which has been removed from the report.
  167. Residual bool
  168. // An inline edge represents a call that was inlined into the caller.
  169. Inline bool
  170. }
  171. // Tag represent sample annotations
  172. type Tag struct {
  173. Name string
  174. Unit string // Describe the value, "" for non-numeric tags
  175. Value int64
  176. Flat int64
  177. Cum int64
  178. }
  179. // TagMap is a collection of tags, classified by their name.
  180. type TagMap map[string]*Tag
  181. // SortTags sorts a slice of tags based on their weight.
  182. func SortTags(t []*Tag, flat bool) []*Tag {
  183. ts := tags{t, flat}
  184. sort.Sort(ts)
  185. return ts.t
  186. }
  187. // New summarizes performance data from a profile into a graph.
  188. func New(prof *profile.Profile, o *Options) (g *Graph) {
  189. const averageNodesPerLocation = 2
  190. locations := NewLocInfo(prof, o.ObjNames)
  191. nm := make(NodeMap, len(prof.Location)*averageNodesPerLocation)
  192. for _, sample := range prof.Sample {
  193. if sample.Location == nil {
  194. continue
  195. }
  196. // Construct list of node names for sample.
  197. // Keep track of the index on the Sample for each frame,
  198. // to determine inlining status.
  199. stack := make([]NodeInfo, 0, len(sample.Location))
  200. locIndex := make([]int, 0, len(sample.Location)*averageNodesPerLocation)
  201. for i, loc := range sample.Location {
  202. id := loc.ID
  203. stack = append(stack, locations[id]...)
  204. for _ = range locations[id] {
  205. locIndex = append(locIndex, i)
  206. }
  207. }
  208. weight := o.SampleValue(sample.Value)
  209. seenNode := make(map[*Node]bool, len(stack))
  210. seenEdge := make(map[nodePair]bool, len(stack))
  211. var nn *Node
  212. nlocIndex := -1
  213. residual := false
  214. // Walk top-down over the frames in a sample, keeping track
  215. // of the current parent if we're building a tree.
  216. for i := len(stack); i > 0; i-- {
  217. var parent *Node
  218. if o.CallTree {
  219. parent = nn
  220. }
  221. n := nm.FindOrInsertNode(stack[i-1], parent, o.KeptNodes)
  222. if n == nil {
  223. residual = true
  224. continue
  225. }
  226. // Add flat weight to leaf node.
  227. if i == 1 {
  228. n.addSample(sample, weight, o.FormatTag, true)
  229. }
  230. // Add cum weight to all nodes in stack, avoiding double counting.
  231. if _, ok := seenNode[n]; !ok {
  232. seenNode[n] = true
  233. n.addSample(sample, weight, o.FormatTag, false)
  234. }
  235. // Update edge weights for all edges in stack, avoiding double counting.
  236. if _, ok := seenEdge[nodePair{n, nn}]; !ok && nn != nil && n != nn {
  237. seenEdge[nodePair{n, nn}] = true
  238. // This is an inlined edge if the caller and the callee
  239. // correspond to the same entry in the sample.
  240. nn.BumpWeight(n, weight, residual, locIndex[i-1] == nlocIndex)
  241. }
  242. nn = n
  243. nlocIndex = locIndex[i-1]
  244. residual = false
  245. }
  246. }
  247. // Collect nodes into a graph.
  248. ns := make(Nodes, 0, len(nm))
  249. for _, n := range nm {
  250. if o.DropNegative && isNegative(n) {
  251. continue
  252. }
  253. ns = append(ns, n)
  254. }
  255. return &Graph{ns}
  256. }
  257. type nodePair struct {
  258. src, dest *Node
  259. }
  260. // isNegative returns true if the node is considered as "negative" for the
  261. // purposes of drop_negative.
  262. func isNegative(n *Node) bool {
  263. switch {
  264. case n.Flat < 0:
  265. return true
  266. case n.Flat == 0 && n.Cum < 0:
  267. return true
  268. default:
  269. return false
  270. }
  271. }
  272. // NewLocInfo creates a slice of formatted names for a location.
  273. func NewLocInfo(prof *profile.Profile, keepBinary bool) map[uint64][]NodeInfo {
  274. locations := make(map[uint64][]NodeInfo)
  275. for _, l := range prof.Location {
  276. var objfile string
  277. if m := l.Mapping; m != nil {
  278. objfile = filepath.Base(m.File)
  279. }
  280. if len(l.Line) == 0 {
  281. locations[l.ID] = []NodeInfo{
  282. {
  283. Address: l.Address,
  284. Objfile: objfile,
  285. },
  286. }
  287. continue
  288. }
  289. var info []NodeInfo
  290. for _, line := range l.Line {
  291. ni := NodeInfo{
  292. Address: l.Address,
  293. Lineno: int(line.Line),
  294. }
  295. if line.Function != nil {
  296. ni.Name = line.Function.Name
  297. ni.OrigName = line.Function.SystemName
  298. if fname := line.Function.Filename; fname != "" {
  299. ni.File = filepath.Clean(fname)
  300. }
  301. if keepBinary {
  302. ni.StartLine = int(line.Function.StartLine)
  303. }
  304. }
  305. if keepBinary || line.Function == nil {
  306. ni.Objfile = objfile
  307. }
  308. info = append(info, ni)
  309. }
  310. locations[l.ID] = info
  311. }
  312. return locations
  313. }
  314. type tags struct {
  315. t []*Tag
  316. flat bool
  317. }
  318. func (t tags) Len() int { return len(t.t) }
  319. func (t tags) Swap(i, j int) { t.t[i], t.t[j] = t.t[j], t.t[i] }
  320. func (t tags) Less(i, j int) bool {
  321. if !t.flat {
  322. if t.t[i].Cum != t.t[j].Cum {
  323. return abs64(t.t[i].Cum) > abs64(t.t[j].Cum)
  324. }
  325. }
  326. if t.t[i].Flat != t.t[j].Flat {
  327. return abs64(t.t[i].Flat) > abs64(t.t[j].Flat)
  328. }
  329. return t.t[i].Name < t.t[j].Name
  330. }
  331. // Sum adds the Flat and sum values on a report.
  332. func (ns Nodes) Sum() (flat int64, cum int64) {
  333. for _, n := range ns {
  334. flat += n.Flat
  335. cum += n.Cum
  336. }
  337. return
  338. }
  339. func (n *Node) addSample(s *profile.Sample, value int64, format func(int64, string) string, flat bool) {
  340. // Update sample value
  341. if flat {
  342. n.Flat += value
  343. } else {
  344. n.Cum += value
  345. }
  346. // Add string tags
  347. var labels []string
  348. for key, vals := range s.Label {
  349. for _, v := range vals {
  350. labels = append(labels, key+":"+v)
  351. }
  352. }
  353. var joinedLabels string
  354. if len(labels) > 0 {
  355. sort.Strings(labels)
  356. joinedLabels = strings.Join(labels, `\n`)
  357. t := n.LabelTags.findOrAddTag(joinedLabels, "", 0)
  358. if flat {
  359. t.Flat += value
  360. } else {
  361. t.Cum += value
  362. }
  363. }
  364. numericTags := n.NumericTags[joinedLabels]
  365. if numericTags == nil {
  366. numericTags = TagMap{}
  367. n.NumericTags[joinedLabels] = numericTags
  368. }
  369. // Add numeric tags
  370. if format == nil {
  371. format = defaultLabelFormat
  372. }
  373. for key, nvals := range s.NumLabel {
  374. for _, v := range nvals {
  375. t := numericTags.findOrAddTag(format(v, key), key, v)
  376. if flat {
  377. t.Flat += value
  378. } else {
  379. t.Cum += value
  380. }
  381. }
  382. }
  383. }
  384. func defaultLabelFormat(v int64, key string) string {
  385. return strconv.FormatInt(v, 10)
  386. }
  387. func (m TagMap) findOrAddTag(label, unit string, value int64) *Tag {
  388. l := m[label]
  389. if l == nil {
  390. l = &Tag{
  391. Name: label,
  392. Unit: unit,
  393. Value: value,
  394. }
  395. m[label] = l
  396. }
  397. return l
  398. }
  399. // String returns a text representation of a graph, for debugging purposes.
  400. func (g *Graph) String() string {
  401. var s []string
  402. nodeIndex := make(map[*Node]int, len(g.Nodes))
  403. for i, n := range g.Nodes {
  404. nodeIndex[n] = i + 1
  405. }
  406. for i, n := range g.Nodes {
  407. name := n.Info.PrintableName()
  408. var in, out []int
  409. for _, from := range n.In {
  410. in = append(in, nodeIndex[from.Src])
  411. }
  412. for _, to := range n.Out {
  413. out = append(out, nodeIndex[to.Dest])
  414. }
  415. s = append(s, fmt.Sprintf("%d: %s[flat=%d cum=%d] %x -> %v ", i+1, name, n.Flat, n.Cum, in, out))
  416. }
  417. return strings.Join(s, "\n")
  418. }
  419. // DiscardLowFrequencyNodes returns a set of the nodes at or over a
  420. // specific cum value cutoff.
  421. func (g *Graph) DiscardLowFrequencyNodes(nodeCutoff int64) NodeSet {
  422. return makeNodeSet(g.Nodes, nodeCutoff)
  423. }
  424. func makeNodeSet(nodes Nodes, nodeCutoff int64) NodeSet {
  425. kept := make(NodeSet, len(nodes))
  426. for _, n := range nodes {
  427. if abs64(n.Cum) < nodeCutoff {
  428. continue
  429. }
  430. kept[n.Info] = true
  431. }
  432. return kept
  433. }
  434. // TrimLowFrequencyTags removes tags that have less than
  435. // the specified weight.
  436. func (g *Graph) TrimLowFrequencyTags(tagCutoff int64) {
  437. // Remove nodes with value <= total*nodeFraction
  438. for _, n := range g.Nodes {
  439. n.LabelTags = trimLowFreqTags(n.LabelTags, tagCutoff)
  440. for s, nt := range n.NumericTags {
  441. n.NumericTags[s] = trimLowFreqTags(nt, tagCutoff)
  442. }
  443. }
  444. }
  445. func trimLowFreqTags(tags TagMap, minValue int64) TagMap {
  446. kept := TagMap{}
  447. for s, t := range tags {
  448. if abs64(t.Flat) >= minValue || abs64(t.Cum) >= minValue {
  449. kept[s] = t
  450. }
  451. }
  452. return kept
  453. }
  454. // TrimLowFrequencyEdges removes edges that have less than
  455. // the specified weight. Returns the number of edges removed
  456. func (g *Graph) TrimLowFrequencyEdges(edgeCutoff int64) int {
  457. var droppedEdges int
  458. for _, n := range g.Nodes {
  459. for src, e := range n.In {
  460. if abs64(e.Weight) < edgeCutoff {
  461. delete(n.In, src)
  462. delete(src.Out, n)
  463. droppedEdges++
  464. }
  465. }
  466. }
  467. return droppedEdges
  468. }
  469. // SortNodes sorts the nodes in a graph based on a specific heuristic.
  470. func (g *Graph) SortNodes(cum bool, visualMode bool) {
  471. // Sort nodes based on requested mode
  472. switch {
  473. case visualMode:
  474. // Specialized sort to produce a more visually-interesting graph
  475. g.Nodes.Sort(EntropyOrder)
  476. case cum:
  477. g.Nodes.Sort(CumNameOrder)
  478. default:
  479. g.Nodes.Sort(FlatNameOrder)
  480. }
  481. }
  482. // SelectTopNodes returns a set of the top maxNodes nodes in a graph.
  483. func (g *Graph) SelectTopNodes(maxNodes int, visualMode bool) NodeSet {
  484. if maxNodes > 0 {
  485. if visualMode {
  486. var count int
  487. // If generating a visual graph, count tags as nodes. Update
  488. // maxNodes to account for them.
  489. for i, n := range g.Nodes {
  490. if count += countTags(n) + 1; count >= maxNodes {
  491. maxNodes = i + 1
  492. break
  493. }
  494. }
  495. }
  496. }
  497. if maxNodes > len(g.Nodes) {
  498. maxNodes = len(g.Nodes)
  499. }
  500. return makeNodeSet(g.Nodes[:maxNodes], 0)
  501. }
  502. // countTags counts the tags with flat count. This underestimates the
  503. // number of tags being displayed, but in practice is close enough.
  504. func countTags(n *Node) int {
  505. count := 0
  506. for _, e := range n.LabelTags {
  507. if e.Flat != 0 {
  508. count++
  509. }
  510. }
  511. for _, t := range n.NumericTags {
  512. for _, e := range t {
  513. if e.Flat != 0 {
  514. count++
  515. }
  516. }
  517. }
  518. return count
  519. }
  520. // countEdges counts the number of edges below the specified cutoff.
  521. func countEdges(el EdgeMap, cutoff int64) int {
  522. count := 0
  523. for _, e := range el {
  524. if e.Weight > cutoff {
  525. count++
  526. }
  527. }
  528. return count
  529. }
  530. // RemoveRedundantEdges removes residual edges if the destination can
  531. // be reached through another path. This is done to simplify the graph
  532. // while preserving connectivity.
  533. func (g *Graph) RemoveRedundantEdges() {
  534. // Walk the nodes and outgoing edges in reverse order to prefer
  535. // removing edges with the lowest weight.
  536. for i := len(g.Nodes); i > 0; i-- {
  537. n := g.Nodes[i-1]
  538. in := n.In.Sort()
  539. for j := len(in); j > 0; j-- {
  540. e := in[j-1]
  541. if !e.Residual {
  542. // Do not remove edges heavier than a non-residual edge, to
  543. // avoid potential confusion.
  544. break
  545. }
  546. if isRedundant(e) {
  547. delete(e.Src.Out, e.Dest)
  548. delete(e.Dest.In, e.Src)
  549. }
  550. }
  551. }
  552. }
  553. // isRedundant determines if an edge can be removed without impacting
  554. // connectivity of the whole graph. This is implemented by checking if the
  555. // nodes have a common ancestor after removing the edge.
  556. func isRedundant(e *Edge) bool {
  557. destPred := predecessors(e, e.Dest)
  558. if len(destPred) == 1 {
  559. return false
  560. }
  561. srcPred := predecessors(e, e.Src)
  562. for n := range srcPred {
  563. if destPred[n] && n != e.Dest {
  564. return true
  565. }
  566. }
  567. return false
  568. }
  569. // predecessors collects all the predecessors to node n, excluding edge e.
  570. func predecessors(e *Edge, n *Node) map[*Node]bool {
  571. seen := map[*Node]bool{n: true}
  572. queue := []*Node{n}
  573. for len(queue) > 0 {
  574. n := queue[0]
  575. queue = queue[1:]
  576. for _, ie := range n.In {
  577. if e == ie || seen[ie.Src] {
  578. continue
  579. }
  580. seen[ie.Src] = true
  581. queue = append(queue, ie.Src)
  582. }
  583. }
  584. return seen
  585. }
  586. // nodeSorter is a mechanism used to allow a report to be sorted
  587. // in different ways.
  588. type nodeSorter struct {
  589. rs Nodes
  590. less func(l, r *Node) bool
  591. }
  592. func (s nodeSorter) Len() int { return len(s.rs) }
  593. func (s nodeSorter) Swap(i, j int) { s.rs[i], s.rs[j] = s.rs[j], s.rs[i] }
  594. func (s nodeSorter) Less(i, j int) bool { return s.less(s.rs[i], s.rs[j]) }
  595. // Sort reorders a slice of nodes based on the specified ordering
  596. // criteria. The result is sorted in decreasing order for (absolute)
  597. // numeric quantities, alphabetically for text, and increasing for
  598. // addresses.
  599. func (ns Nodes) Sort(o NodeOrder) error {
  600. var s nodeSorter
  601. switch o {
  602. case FlatNameOrder:
  603. s = nodeSorter{ns,
  604. func(l, r *Node) bool {
  605. if iv, jv := l.Flat, r.Flat; iv != jv {
  606. return abs64(iv) > abs64(jv)
  607. }
  608. if l.Info.PrintableName() != r.Info.PrintableName() {
  609. return l.Info.PrintableName() < r.Info.PrintableName()
  610. }
  611. iv, jv := l.Cum, r.Cum
  612. return abs64(iv) > abs64(jv)
  613. },
  614. }
  615. case FlatCumNameOrder:
  616. s = nodeSorter{ns,
  617. func(l, r *Node) bool {
  618. if iv, jv := l.Flat, r.Flat; iv != jv {
  619. return abs64(iv) > abs64(jv)
  620. }
  621. if iv, jv := l.Cum, r.Cum; iv != jv {
  622. return abs64(iv) > abs64(jv)
  623. }
  624. return l.Info.PrintableName() < r.Info.PrintableName()
  625. },
  626. }
  627. case NameOrder:
  628. s = nodeSorter{ns,
  629. func(l, r *Node) bool {
  630. return l.Info.Name < r.Info.Name
  631. },
  632. }
  633. case FileOrder:
  634. s = nodeSorter{ns,
  635. func(l, r *Node) bool {
  636. return l.Info.File < r.Info.File
  637. },
  638. }
  639. case AddressOrder:
  640. s = nodeSorter{ns,
  641. func(l, r *Node) bool {
  642. return l.Info.Address < r.Info.Address
  643. },
  644. }
  645. case CumNameOrder, EntropyOrder:
  646. // Hold scoring for score-based ordering
  647. var score map[*Node]int64
  648. scoreOrder := func(l, r *Node) bool {
  649. if is, js := score[l], score[r]; is != js {
  650. return abs64(is) > abs64(js)
  651. }
  652. if l.Info.PrintableName() != r.Info.PrintableName() {
  653. return l.Info.PrintableName() < r.Info.PrintableName()
  654. }
  655. return abs64(l.Flat) > abs64(r.Flat)
  656. }
  657. switch o {
  658. case CumNameOrder:
  659. score = make(map[*Node]int64, len(ns))
  660. for _, n := range ns {
  661. score[n] = n.Cum
  662. }
  663. s = nodeSorter{ns, scoreOrder}
  664. case EntropyOrder:
  665. score = make(map[*Node]int64, len(ns))
  666. for _, n := range ns {
  667. score[n] = entropyScore(n)
  668. }
  669. s = nodeSorter{ns, scoreOrder}
  670. }
  671. default:
  672. return fmt.Errorf("report: unrecognized sort ordering: %d", o)
  673. }
  674. sort.Sort(s)
  675. return nil
  676. }
  677. // entropyScore computes a score for a node representing how important
  678. // it is to include this node on a graph visualization. It is used to
  679. // sort the nodes and select which ones to display if we have more
  680. // nodes than desired in the graph. This number is computed by looking
  681. // at the flat and cum weights of the node and the incoming/outgoing
  682. // edges. The fundamental idea is to penalize nodes that have a simple
  683. // fallthrough from their incoming to the outgoing edge.
  684. func entropyScore(n *Node) int64 {
  685. score := float64(0)
  686. if len(n.In) == 0 {
  687. score++ // Favor entry nodes
  688. } else {
  689. score += edgeEntropyScore(n, n.In, 0)
  690. }
  691. if len(n.Out) == 0 {
  692. score++ // Favor leaf nodes
  693. } else {
  694. score += edgeEntropyScore(n, n.Out, n.Flat)
  695. }
  696. return int64(score*float64(n.Cum)) + n.Flat
  697. }
  698. // edgeEntropyScore computes the entropy value for a set of edges
  699. // coming in or out of a node. Entropy (as defined in information
  700. // theory) refers to the amount of information encoded by the set of
  701. // edges. A set of edges that have a more interesting distribution of
  702. // samples gets a higher score.
  703. func edgeEntropyScore(n *Node, edges EdgeMap, self int64) float64 {
  704. score := float64(0)
  705. total := self
  706. for _, e := range edges {
  707. if e.Weight > 0 {
  708. total += abs64(e.Weight)
  709. }
  710. }
  711. if total != 0 {
  712. for _, e := range edges {
  713. frac := float64(abs64(e.Weight)) / float64(total)
  714. score += -frac * math.Log2(frac)
  715. }
  716. if self > 0 {
  717. frac := float64(abs64(self)) / float64(total)
  718. score += -frac * math.Log2(frac)
  719. }
  720. }
  721. return score
  722. }
  723. // NodeOrder sets the ordering for a Sort operation
  724. type NodeOrder int
  725. // Sorting options for node sort.
  726. const (
  727. FlatNameOrder NodeOrder = iota
  728. FlatCumNameOrder
  729. CumNameOrder
  730. NameOrder
  731. FileOrder
  732. AddressOrder
  733. EntropyOrder
  734. )
  735. // Sort returns a slice of the edges in the map, in a consistent
  736. // order. The sort order is first based on the edge weight
  737. // (higher-to-lower) and then by the node names to avoid flakiness.
  738. func (e EdgeMap) Sort() []*Edge {
  739. el := make(edgeList, 0, len(e))
  740. for _, w := range e {
  741. el = append(el, w)
  742. }
  743. sort.Sort(el)
  744. return el
  745. }
  746. // Sum returns the total weight for a set of nodes.
  747. func (e EdgeMap) Sum() int64 {
  748. var ret int64
  749. for _, edge := range e {
  750. ret += edge.Weight
  751. }
  752. return ret
  753. }
  754. type edgeList []*Edge
  755. func (el edgeList) Len() int {
  756. return len(el)
  757. }
  758. func (el edgeList) Less(i, j int) bool {
  759. if el[i].Weight != el[j].Weight {
  760. return abs64(el[i].Weight) > abs64(el[j].Weight)
  761. }
  762. from1 := el[i].Src.Info.PrintableName()
  763. from2 := el[j].Src.Info.PrintableName()
  764. if from1 != from2 {
  765. return from1 < from2
  766. }
  767. to1 := el[i].Dest.Info.PrintableName()
  768. to2 := el[j].Dest.Info.PrintableName()
  769. return to1 < to2
  770. }
  771. func (el edgeList) Swap(i, j int) {
  772. el[i], el[j] = el[j], el[i]
  773. }
  774. func abs64(i int64) int64 {
  775. if i < 0 {
  776. return -i
  777. }
  778. return i
  779. }