暫無描述

graph.go 29KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134
  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 isRedundantEdge(e) {
  771. delete(e.Src.Out, e.Dest)
  772. delete(e.Dest.In, e.Src)
  773. }
  774. }
  775. }
  776. }
  777. // isRedundantEdge determines if there is a path that allows e.Src
  778. // to reach e.Dest after removing e.
  779. func isRedundantEdge(e *Edge) bool {
  780. src, n := e.Src, e.Dest
  781. seen := map[*Node]bool{n: true}
  782. queue := Nodes{n}
  783. for len(queue) > 0 {
  784. n := queue[0]
  785. queue = queue[1:]
  786. for _, ie := range n.In {
  787. if e == ie || seen[ie.Src] {
  788. continue
  789. }
  790. if ie.Src == src {
  791. return true
  792. }
  793. seen[ie.Src] = true
  794. queue = append(queue, ie.Src)
  795. }
  796. }
  797. return false
  798. }
  799. // nodeSorter is a mechanism used to allow a report to be sorted
  800. // in different ways.
  801. type nodeSorter struct {
  802. rs Nodes
  803. less func(l, r *Node) bool
  804. }
  805. func (s nodeSorter) Len() int { return len(s.rs) }
  806. func (s nodeSorter) Swap(i, j int) { s.rs[i], s.rs[j] = s.rs[j], s.rs[i] }
  807. func (s nodeSorter) Less(i, j int) bool { return s.less(s.rs[i], s.rs[j]) }
  808. // Sort reorders a slice of nodes based on the specified ordering
  809. // criteria. The result is sorted in decreasing order for (absolute)
  810. // numeric quantities, alphabetically for text, and increasing for
  811. // addresses.
  812. func (ns Nodes) Sort(o NodeOrder) error {
  813. var s nodeSorter
  814. switch o {
  815. case FlatNameOrder:
  816. s = nodeSorter{ns,
  817. func(l, r *Node) bool {
  818. if iv, jv := abs64(l.Flat), abs64(r.Flat); iv != jv {
  819. return iv > jv
  820. }
  821. if iv, jv := l.Info.PrintableName(), r.Info.PrintableName(); iv != jv {
  822. return iv < jv
  823. }
  824. if iv, jv := abs64(l.Cum), abs64(r.Cum); iv != jv {
  825. return iv > jv
  826. }
  827. return compareNodes(l, r)
  828. },
  829. }
  830. case FlatCumNameOrder:
  831. s = nodeSorter{ns,
  832. func(l, r *Node) bool {
  833. if iv, jv := abs64(l.Flat), abs64(r.Flat); iv != jv {
  834. return iv > jv
  835. }
  836. if iv, jv := abs64(l.Cum), abs64(r.Cum); iv != jv {
  837. return iv > jv
  838. }
  839. if iv, jv := l.Info.PrintableName(), r.Info.PrintableName(); iv != jv {
  840. return iv < jv
  841. }
  842. return compareNodes(l, r)
  843. },
  844. }
  845. case NameOrder:
  846. s = nodeSorter{ns,
  847. func(l, r *Node) bool {
  848. if iv, jv := l.Info.Name, r.Info.Name; iv != jv {
  849. return iv < jv
  850. }
  851. return compareNodes(l, r)
  852. },
  853. }
  854. case FileOrder:
  855. s = nodeSorter{ns,
  856. func(l, r *Node) bool {
  857. if iv, jv := l.Info.File, r.Info.File; iv != jv {
  858. return iv < jv
  859. }
  860. if iv, jv := l.Info.StartLine, r.Info.StartLine; iv != jv {
  861. return iv < jv
  862. }
  863. return compareNodes(l, r)
  864. },
  865. }
  866. case AddressOrder:
  867. s = nodeSorter{ns,
  868. func(l, r *Node) bool {
  869. if iv, jv := l.Info.Address, r.Info.Address; iv != jv {
  870. return iv < jv
  871. }
  872. return compareNodes(l, r)
  873. },
  874. }
  875. case CumNameOrder, EntropyOrder:
  876. // Hold scoring for score-based ordering
  877. var score map[*Node]int64
  878. scoreOrder := func(l, r *Node) bool {
  879. if iv, jv := abs64(score[l]), abs64(score[r]); iv != jv {
  880. return iv > jv
  881. }
  882. if iv, jv := l.Info.PrintableName(), r.Info.PrintableName(); iv != jv {
  883. return iv < jv
  884. }
  885. if iv, jv := abs64(l.Flat), abs64(r.Flat); iv != jv {
  886. return iv > jv
  887. }
  888. return compareNodes(l, r)
  889. }
  890. switch o {
  891. case CumNameOrder:
  892. score = make(map[*Node]int64, len(ns))
  893. for _, n := range ns {
  894. score[n] = n.Cum
  895. }
  896. s = nodeSorter{ns, scoreOrder}
  897. case EntropyOrder:
  898. score = make(map[*Node]int64, len(ns))
  899. for _, n := range ns {
  900. score[n] = entropyScore(n)
  901. }
  902. s = nodeSorter{ns, scoreOrder}
  903. }
  904. default:
  905. return fmt.Errorf("report: unrecognized sort ordering: %d", o)
  906. }
  907. sort.Sort(s)
  908. return nil
  909. }
  910. // compareNodes compares two nodes to provide a deterministic ordering
  911. // between them. Two nodes cannot have the same Node.Info value.
  912. func compareNodes(l, r *Node) bool {
  913. return fmt.Sprint(l.Info) < fmt.Sprint(r.Info)
  914. }
  915. // entropyScore computes a score for a node representing how important
  916. // it is to include this node on a graph visualization. It is used to
  917. // sort the nodes and select which ones to display if we have more
  918. // nodes than desired in the graph. This number is computed by looking
  919. // at the flat and cum weights of the node and the incoming/outgoing
  920. // edges. The fundamental idea is to penalize nodes that have a simple
  921. // fallthrough from their incoming to the outgoing edge.
  922. func entropyScore(n *Node) int64 {
  923. score := float64(0)
  924. if len(n.In) == 0 {
  925. score++ // Favor entry nodes
  926. } else {
  927. score += edgeEntropyScore(n, n.In, 0)
  928. }
  929. if len(n.Out) == 0 {
  930. score++ // Favor leaf nodes
  931. } else {
  932. score += edgeEntropyScore(n, n.Out, n.Flat)
  933. }
  934. return int64(score*float64(n.Cum)) + n.Flat
  935. }
  936. // edgeEntropyScore computes the entropy value for a set of edges
  937. // coming in or out of a node. Entropy (as defined in information
  938. // theory) refers to the amount of information encoded by the set of
  939. // edges. A set of edges that have a more interesting distribution of
  940. // samples gets a higher score.
  941. func edgeEntropyScore(n *Node, edges EdgeMap, self int64) float64 {
  942. score := float64(0)
  943. total := self
  944. for _, e := range edges {
  945. if e.Weight > 0 {
  946. total += abs64(e.Weight)
  947. }
  948. }
  949. if total != 0 {
  950. for _, e := range edges {
  951. frac := float64(abs64(e.Weight)) / float64(total)
  952. score += -frac * math.Log2(frac)
  953. }
  954. if self > 0 {
  955. frac := float64(abs64(self)) / float64(total)
  956. score += -frac * math.Log2(frac)
  957. }
  958. }
  959. return score
  960. }
  961. // NodeOrder sets the ordering for a Sort operation
  962. type NodeOrder int
  963. // Sorting options for node sort.
  964. const (
  965. FlatNameOrder NodeOrder = iota
  966. FlatCumNameOrder
  967. CumNameOrder
  968. NameOrder
  969. FileOrder
  970. AddressOrder
  971. EntropyOrder
  972. )
  973. // Sort returns a slice of the edges in the map, in a consistent
  974. // order. The sort order is first based on the edge weight
  975. // (higher-to-lower) and then by the node names to avoid flakiness.
  976. func (e EdgeMap) Sort() []*Edge {
  977. el := make(edgeList, 0, len(e))
  978. for _, w := range e {
  979. el = append(el, w)
  980. }
  981. sort.Sort(el)
  982. return el
  983. }
  984. // Sum returns the total weight for a set of nodes.
  985. func (e EdgeMap) Sum() int64 {
  986. var ret int64
  987. for _, edge := range e {
  988. ret += edge.Weight
  989. }
  990. return ret
  991. }
  992. type edgeList []*Edge
  993. func (el edgeList) Len() int {
  994. return len(el)
  995. }
  996. func (el edgeList) Less(i, j int) bool {
  997. if el[i].Weight != el[j].Weight {
  998. return abs64(el[i].Weight) > abs64(el[j].Weight)
  999. }
  1000. from1 := el[i].Src.Info.PrintableName()
  1001. from2 := el[j].Src.Info.PrintableName()
  1002. if from1 != from2 {
  1003. return from1 < from2
  1004. }
  1005. to1 := el[i].Dest.Info.PrintableName()
  1006. to2 := el[j].Dest.Info.PrintableName()
  1007. return to1 < to2
  1008. }
  1009. func (el edgeList) Swap(i, j int) {
  1010. el[i], el[j] = el[j], el[i]
  1011. }
  1012. func abs64(i int64) int64 {
  1013. if i < 0 {
  1014. return -i
  1015. }
  1016. return i
  1017. }