暂无描述

graph.go 21KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859
  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. "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. ni.File = line.Function.Filename
  291. ni.StartLine = int(line.Function.StartLine)
  292. }
  293. if keepBinary || line.Function == nil {
  294. ni.Objfile = objfile
  295. }
  296. info = append(info, ni)
  297. }
  298. locations[l.ID] = info
  299. }
  300. return locations
  301. }
  302. type tags struct {
  303. t []*Tag
  304. flat bool
  305. }
  306. func (t tags) Len() int { return len(t.t) }
  307. func (t tags) Swap(i, j int) { t.t[i], t.t[j] = t.t[j], t.t[i] }
  308. func (t tags) Less(i, j int) bool {
  309. if !t.flat {
  310. if t.t[i].Cum != t.t[j].Cum {
  311. return abs64(t.t[i].Cum) > abs64(t.t[j].Cum)
  312. }
  313. }
  314. if t.t[i].Flat != t.t[j].Flat {
  315. return abs64(t.t[i].Flat) > abs64(t.t[j].Flat)
  316. }
  317. return t.t[i].Name < t.t[j].Name
  318. }
  319. // Sum adds the Flat and sum values on a report.
  320. func (ns Nodes) Sum() (flat int64, cum int64) {
  321. for _, n := range ns {
  322. flat += n.Flat
  323. cum += n.Cum
  324. }
  325. return
  326. }
  327. func (n *Node) addSample(s *profile.Sample, value int64, format func(int64, string) string, flat bool) {
  328. // Update sample value
  329. if flat {
  330. n.Flat += value
  331. } else {
  332. n.Cum += value
  333. }
  334. // Add string tags
  335. var labels []string
  336. for key, vals := range s.Label {
  337. for _, v := range vals {
  338. labels = append(labels, key+":"+v)
  339. }
  340. }
  341. var joinedLabels string
  342. if len(labels) > 0 {
  343. sort.Strings(labels)
  344. joinedLabels = strings.Join(labels, `\n`)
  345. t := n.LabelTags.findOrAddTag(joinedLabels, "", 0)
  346. if flat {
  347. t.Flat += value
  348. } else {
  349. t.Cum += value
  350. }
  351. }
  352. numericTags := n.NumericTags[joinedLabels]
  353. if numericTags == nil {
  354. numericTags = TagMap{}
  355. n.NumericTags[joinedLabels] = numericTags
  356. }
  357. // Add numeric tags
  358. for key, nvals := range s.NumLabel {
  359. for _, v := range nvals {
  360. var label string
  361. if format != nil {
  362. label = format(v, key)
  363. } else {
  364. label = fmt.Sprintf("%d", v)
  365. }
  366. t := numericTags.findOrAddTag(label, key, v)
  367. if flat {
  368. t.Flat += value
  369. } else {
  370. t.Cum += value
  371. }
  372. }
  373. }
  374. }
  375. func (m TagMap) findOrAddTag(label, unit string, value int64) *Tag {
  376. l := m[label]
  377. if l == nil {
  378. l = &Tag{
  379. Name: label,
  380. Unit: unit,
  381. Value: value,
  382. }
  383. m[label] = l
  384. }
  385. return l
  386. }
  387. // String returns a text representation of a graph, for debugging purposes.
  388. func (g *Graph) String() string {
  389. var s []string
  390. nodeIndex := make(map[*Node]int, len(g.Nodes))
  391. for i, n := range g.Nodes {
  392. nodeIndex[n] = i + 1
  393. }
  394. for i, n := range g.Nodes {
  395. name := n.Info.PrintableName()
  396. var in, out []int
  397. for _, from := range n.In {
  398. in = append(in, nodeIndex[from.Src])
  399. }
  400. for _, to := range n.Out {
  401. out = append(out, nodeIndex[to.Dest])
  402. }
  403. s = append(s, fmt.Sprintf("%d: %s[flat=%d cum=%d] %x -> %v ", i+1, name, n.Flat, n.Cum, in, out))
  404. }
  405. return strings.Join(s, "\n")
  406. }
  407. // DiscardLowFrequencyNodes returns a set of the nodes at or over a
  408. // specific cum value cutoff.
  409. func (g *Graph) DiscardLowFrequencyNodes(nodeCutoff int64) NodeSet {
  410. return makeNodeSet(g.Nodes, nodeCutoff)
  411. }
  412. func makeNodeSet(nodes Nodes, nodeCutoff int64) NodeSet {
  413. kept := make(NodeSet, len(nodes))
  414. for _, n := range nodes {
  415. if abs64(n.Cum) < nodeCutoff {
  416. continue
  417. }
  418. kept[n.Info] = true
  419. }
  420. return kept
  421. }
  422. // TrimLowFrequencyTags removes tags that have less than
  423. // the specified weight.
  424. func (g *Graph) TrimLowFrequencyTags(tagCutoff int64) {
  425. // Remove nodes with value <= total*nodeFraction
  426. for _, n := range g.Nodes {
  427. n.LabelTags = trimLowFreqTags(n.LabelTags, tagCutoff)
  428. for s, nt := range n.NumericTags {
  429. n.NumericTags[s] = trimLowFreqTags(nt, tagCutoff)
  430. }
  431. }
  432. }
  433. func trimLowFreqTags(tags TagMap, minValue int64) TagMap {
  434. kept := TagMap{}
  435. for s, t := range tags {
  436. if abs64(t.Flat) >= minValue || abs64(t.Cum) >= minValue {
  437. kept[s] = t
  438. }
  439. }
  440. return kept
  441. }
  442. // TrimLowFrequencyEdges removes edges that have less than
  443. // the specified weight. Returns the number of edges removed
  444. func (g *Graph) TrimLowFrequencyEdges(edgeCutoff int64) int {
  445. var droppedEdges int
  446. for _, n := range g.Nodes {
  447. for src, e := range n.In {
  448. if abs64(e.Weight) < edgeCutoff {
  449. delete(n.In, src)
  450. delete(src.Out, n)
  451. droppedEdges++
  452. }
  453. }
  454. }
  455. return droppedEdges
  456. }
  457. // SortNodes sorts the nodes in a graph based on a specific heuristic.
  458. func (g *Graph) SortNodes(cum bool, visualMode bool) {
  459. // Sort nodes based on requested mode
  460. switch {
  461. case visualMode:
  462. // Specialized sort to produce a more visually-interesting graph
  463. g.Nodes.Sort(EntropyOrder)
  464. case cum:
  465. g.Nodes.Sort(CumNameOrder)
  466. default:
  467. g.Nodes.Sort(FlatNameOrder)
  468. }
  469. }
  470. // SelectTopNodes returns a set of the top maxNodes nodes in a graph.
  471. func (g *Graph) SelectTopNodes(maxNodes int, visualMode bool) NodeSet {
  472. if maxNodes > 0 {
  473. if visualMode {
  474. var count int
  475. // If generating a visual graph, count tags as nodes. Update
  476. // maxNodes to account for them.
  477. for i, n := range g.Nodes {
  478. if count += countTags(n) + 1; count >= maxNodes {
  479. maxNodes = i + 1
  480. break
  481. }
  482. }
  483. }
  484. }
  485. if maxNodes > len(g.Nodes) {
  486. maxNodes = len(g.Nodes)
  487. }
  488. return makeNodeSet(g.Nodes[:maxNodes], 0)
  489. }
  490. // countTags counts the tags with flat count. This underestimates the
  491. // number of tags being displayed, but in practice is close enough.
  492. func countTags(n *Node) int {
  493. count := 0
  494. for _, e := range n.LabelTags {
  495. if e.Flat != 0 {
  496. count++
  497. }
  498. }
  499. for _, t := range n.NumericTags {
  500. for _, e := range t {
  501. if e.Flat != 0 {
  502. count++
  503. }
  504. }
  505. }
  506. return count
  507. }
  508. // countEdges counts the number of edges below the specified cutoff.
  509. func countEdges(el EdgeMap, cutoff int64) int {
  510. count := 0
  511. for _, e := range el {
  512. if e.Weight > cutoff {
  513. count++
  514. }
  515. }
  516. return count
  517. }
  518. // RemoveRedundantEdges removes residual edges if the destination can
  519. // be reached through another path. This is done to simplify the graph
  520. // while preserving connectivity.
  521. func (g *Graph) RemoveRedundantEdges() {
  522. // Walk the nodes and outgoing edges in reverse order to prefer
  523. // removing edges with the lowest weight.
  524. for i := len(g.Nodes); i > 0; i-- {
  525. n := g.Nodes[i-1]
  526. in := n.In.Sort()
  527. for j := len(in); j > 0; j-- {
  528. e := in[j-1]
  529. if !e.Residual {
  530. // Do not remove edges heavier than a non-residual edge, to
  531. // avoid potential confusion.
  532. break
  533. }
  534. if isRedundant(e) {
  535. delete(e.Src.Out, e.Dest)
  536. delete(e.Dest.In, e.Src)
  537. }
  538. }
  539. }
  540. }
  541. // isRedundant determines if an edge can be removed without impacting
  542. // connectivity of the whole graph. This is implemented by checking if the
  543. // nodes have a common ancestor after removing the edge.
  544. func isRedundant(e *Edge) bool {
  545. destPred := predecessors(e, e.Dest)
  546. if len(destPred) == 1 {
  547. return false
  548. }
  549. srcPred := predecessors(e, e.Src)
  550. for n := range srcPred {
  551. if destPred[n] && n != e.Dest {
  552. return true
  553. }
  554. }
  555. return false
  556. }
  557. // predecessors collects all the predecessors to node n, excluding edge e.
  558. func predecessors(e *Edge, n *Node) map[*Node]bool {
  559. seen := map[*Node]bool{n: true}
  560. queue := []*Node{n}
  561. for len(queue) > 0 {
  562. n := queue[0]
  563. queue = queue[1:]
  564. for _, ie := range n.In {
  565. if e == ie || seen[ie.Src] {
  566. continue
  567. }
  568. seen[ie.Src] = true
  569. queue = append(queue, ie.Src)
  570. }
  571. }
  572. return seen
  573. }
  574. // nodeSorter is a mechanism used to allow a report to be sorted
  575. // in different ways.
  576. type nodeSorter struct {
  577. rs Nodes
  578. less func(l, r *Node) bool
  579. }
  580. func (s nodeSorter) Len() int { return len(s.rs) }
  581. func (s nodeSorter) Swap(i, j int) { s.rs[i], s.rs[j] = s.rs[j], s.rs[i] }
  582. func (s nodeSorter) Less(i, j int) bool { return s.less(s.rs[i], s.rs[j]) }
  583. // Sort reorders a slice of nodes based on the specified ordering
  584. // criteria. The result is sorted in decreasing order for (absolute)
  585. // numeric quantities, alphabetically for text, and increasing for
  586. // addresses.
  587. func (ns Nodes) Sort(o NodeOrder) error {
  588. var s nodeSorter
  589. switch o {
  590. case FlatNameOrder:
  591. s = nodeSorter{ns,
  592. func(l, r *Node) bool {
  593. if iv, jv := l.Flat, r.Flat; iv != jv {
  594. return abs64(iv) > abs64(jv)
  595. }
  596. if l.Info.PrintableName() != r.Info.PrintableName() {
  597. return l.Info.PrintableName() < r.Info.PrintableName()
  598. }
  599. iv, jv := l.Cum, r.Cum
  600. return abs64(iv) > abs64(jv)
  601. },
  602. }
  603. case FlatCumNameOrder:
  604. s = nodeSorter{ns,
  605. func(l, r *Node) bool {
  606. if iv, jv := l.Flat, r.Flat; iv != jv {
  607. return abs64(iv) > abs64(jv)
  608. }
  609. if iv, jv := l.Cum, r.Cum; iv != jv {
  610. return abs64(iv) > abs64(jv)
  611. }
  612. return l.Info.PrintableName() < r.Info.PrintableName()
  613. },
  614. }
  615. case NameOrder:
  616. s = nodeSorter{ns,
  617. func(l, r *Node) bool {
  618. return l.Info.Name < r.Info.Name
  619. },
  620. }
  621. case FileOrder:
  622. s = nodeSorter{ns,
  623. func(l, r *Node) bool {
  624. return l.Info.File < r.Info.File
  625. },
  626. }
  627. case AddressOrder:
  628. s = nodeSorter{ns,
  629. func(l, r *Node) bool {
  630. return l.Info.Address < r.Info.Address
  631. },
  632. }
  633. case CumNameOrder, EntropyOrder:
  634. // Hold scoring for score-based ordering
  635. var score map[*Node]int64
  636. scoreOrder := func(l, r *Node) bool {
  637. if is, js := score[l], score[r]; is != js {
  638. return abs64(is) > abs64(js)
  639. }
  640. if l.Info.PrintableName() != r.Info.PrintableName() {
  641. return l.Info.PrintableName() < r.Info.PrintableName()
  642. }
  643. return abs64(l.Flat) > abs64(r.Flat)
  644. }
  645. switch o {
  646. case CumNameOrder:
  647. score = make(map[*Node]int64, len(ns))
  648. for _, n := range ns {
  649. score[n] = n.Cum
  650. }
  651. s = nodeSorter{ns, scoreOrder}
  652. case EntropyOrder:
  653. score = make(map[*Node]int64, len(ns))
  654. for _, n := range ns {
  655. score[n] = entropyScore(n)
  656. }
  657. s = nodeSorter{ns, scoreOrder}
  658. }
  659. default:
  660. return fmt.Errorf("report: unrecognized sort ordering: %d", o)
  661. }
  662. sort.Sort(s)
  663. return nil
  664. }
  665. // entropyScore computes a score for a node representing how important
  666. // it is to include this node on a graph visualization. It is used to
  667. // sort the nodes and select which ones to display if we have more
  668. // nodes than desired in the graph. This number is computed by looking
  669. // at the flat and cum weights of the node and the incoming/outgoing
  670. // edges. The fundamental idea is to penalize nodes that have a simple
  671. // fallthrough from their incoming to the outgoing edge.
  672. func entropyScore(n *Node) int64 {
  673. score := float64(0)
  674. if len(n.In) == 0 {
  675. score++ // Favor entry nodes
  676. } else {
  677. score += edgeEntropyScore(n, n.In, 0)
  678. }
  679. if len(n.Out) == 0 {
  680. score++ // Favor leaf nodes
  681. } else {
  682. score += edgeEntropyScore(n, n.Out, n.Flat)
  683. }
  684. return int64(score*float64(n.Cum)) + n.Flat
  685. }
  686. // edgeEntropyScore computes the entropy value for a set of edges
  687. // coming in or out of a node. Entropy (as defined in information
  688. // theory) refers to the amount of information encoded by the set of
  689. // edges. A set of edges that have a more interesting distribution of
  690. // samples gets a higher score.
  691. func edgeEntropyScore(n *Node, edges EdgeMap, self int64) float64 {
  692. score := float64(0)
  693. total := self
  694. for _, e := range edges {
  695. if e.Weight > 0 {
  696. total += abs64(e.Weight)
  697. }
  698. }
  699. if total != 0 {
  700. for _, e := range edges {
  701. frac := float64(abs64(e.Weight)) / float64(total)
  702. score += -frac * math.Log2(frac)
  703. }
  704. if self > 0 {
  705. frac := float64(abs64(self)) / float64(total)
  706. score += -frac * math.Log2(frac)
  707. }
  708. }
  709. return score
  710. }
  711. // NodeOrder sets the ordering for a Sort operation
  712. type NodeOrder int
  713. // Sorting options for node sort.
  714. const (
  715. FlatNameOrder NodeOrder = iota
  716. FlatCumNameOrder
  717. CumNameOrder
  718. NameOrder
  719. FileOrder
  720. AddressOrder
  721. EntropyOrder
  722. )
  723. // Sort returns a slice of the edges in the map, in a consistent
  724. // order. The sort order is first based on the edge weight
  725. // (higher-to-lower) and then by the node names to avoid flakiness.
  726. func (e EdgeMap) Sort() []*Edge {
  727. el := make(edgeList, 0, len(e))
  728. for _, w := range e {
  729. el = append(el, w)
  730. }
  731. sort.Sort(el)
  732. return el
  733. }
  734. // Sum returns the total weight for a set of nodes.
  735. func (e EdgeMap) Sum() int64 {
  736. var ret int64
  737. for _, edge := range e {
  738. ret += edge.Weight
  739. }
  740. return ret
  741. }
  742. type edgeList []*Edge
  743. func (el edgeList) Len() int {
  744. return len(el)
  745. }
  746. func (el edgeList) Less(i, j int) bool {
  747. if el[i].Weight != el[j].Weight {
  748. return abs64(el[i].Weight) > abs64(el[j].Weight)
  749. }
  750. from1 := el[i].Src.Info.PrintableName()
  751. from2 := el[j].Src.Info.PrintableName()
  752. if from1 != from2 {
  753. return from1 < from2
  754. }
  755. to1 := el[i].Dest.Info.PrintableName()
  756. to2 := el[j].Dest.Info.PrintableName()
  757. return to1 < to2
  758. }
  759. func (el edgeList) Swap(i, j int) {
  760. el[i], el[j] = el[j], el[i]
  761. }
  762. func abs64(i int64) int64 {
  763. if i < 0 {
  764. return -i
  765. }
  766. return i
  767. }