Keine Beschreibung

graph.go 30KB

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