Keine Beschreibung

graph.go 29KB

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