Nenhuma descrição

graph.go 21KB

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