Ingen beskrivning

graph.go 29KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133
  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, sample.NumUnit, 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, sample.NumUnit, 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, sample.NumUnit, 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, sample.NumUnit, 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).
  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.OrigFnNames {
  501. ni.OrigName = line.Function.SystemName
  502. }
  503. if o.ObjNames || (ni.Name == "" && ni.OrigName == "") {
  504. ni.Objfile = objfile
  505. ni.StartLine = int(line.Function.StartLine)
  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, numUnit map[string][]string, 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 k, nvals := range numLabel {
  564. units := numUnit[k]
  565. for i, v := range nvals {
  566. var t *Tag
  567. if len(units) > 0 {
  568. t = numericTags.findOrAddTag(format(v, units[i]), units[i], v)
  569. } else {
  570. t = numericTags.findOrAddTag(format(v, k), k, v)
  571. }
  572. if flat {
  573. t.FlatDiv += dw
  574. t.Flat += w
  575. } else {
  576. t.CumDiv += dw
  577. t.Cum += w
  578. }
  579. }
  580. }
  581. }
  582. func defaultLabelFormat(v int64, key string) string {
  583. return strconv.FormatInt(v, 10)
  584. }
  585. func (m TagMap) findOrAddTag(label, unit string, value int64) *Tag {
  586. l := m[label]
  587. if l == nil {
  588. l = &Tag{
  589. Name: label,
  590. Unit: unit,
  591. Value: value,
  592. }
  593. m[label] = l
  594. }
  595. return l
  596. }
  597. // String returns a text representation of a graph, for debugging purposes.
  598. func (g *Graph) String() string {
  599. var s []string
  600. nodeIndex := make(map[*Node]int, len(g.Nodes))
  601. for i, n := range g.Nodes {
  602. nodeIndex[n] = i + 1
  603. }
  604. for i, n := range g.Nodes {
  605. name := n.Info.PrintableName()
  606. var in, out []int
  607. for _, from := range n.In {
  608. in = append(in, nodeIndex[from.Src])
  609. }
  610. for _, to := range n.Out {
  611. out = append(out, nodeIndex[to.Dest])
  612. }
  613. s = append(s, fmt.Sprintf("%d: %s[flat=%d cum=%d] %x -> %v ", i+1, name, n.Flat, n.Cum, in, out))
  614. }
  615. return strings.Join(s, "\n")
  616. }
  617. // DiscardLowFrequencyNodes returns a set of the nodes at or over a
  618. // specific cum value cutoff.
  619. func (g *Graph) DiscardLowFrequencyNodes(nodeCutoff int64) NodeSet {
  620. return makeNodeSet(g.Nodes, nodeCutoff)
  621. }
  622. // DiscardLowFrequencyNodePtrs returns a NodePtrSet of nodes at or over a
  623. // specific cum value cutoff.
  624. func (g *Graph) DiscardLowFrequencyNodePtrs(nodeCutoff int64) NodePtrSet {
  625. cutNodes := getNodesAboveCumCutoff(g.Nodes, nodeCutoff)
  626. kept := make(NodePtrSet, len(cutNodes))
  627. for _, n := range cutNodes {
  628. kept[n] = true
  629. }
  630. return kept
  631. }
  632. func makeNodeSet(nodes Nodes, nodeCutoff int64) NodeSet {
  633. cutNodes := getNodesAboveCumCutoff(nodes, nodeCutoff)
  634. kept := make(NodeSet, len(cutNodes))
  635. for _, n := range cutNodes {
  636. kept[n.Info] = true
  637. }
  638. return kept
  639. }
  640. // getNodesAboveCumCutoff returns all the nodes which have a Cum value greater
  641. // than or equal to cutoff.
  642. func getNodesAboveCumCutoff(nodes Nodes, nodeCutoff int64) Nodes {
  643. cutoffNodes := make(Nodes, 0, len(nodes))
  644. for _, n := range nodes {
  645. if abs64(n.Cum) < nodeCutoff {
  646. continue
  647. }
  648. cutoffNodes = append(cutoffNodes, n)
  649. }
  650. return cutoffNodes
  651. }
  652. // TrimLowFrequencyTags removes tags that have less than
  653. // the specified weight.
  654. func (g *Graph) TrimLowFrequencyTags(tagCutoff int64) {
  655. // Remove nodes with value <= total*nodeFraction
  656. for _, n := range g.Nodes {
  657. n.LabelTags = trimLowFreqTags(n.LabelTags, tagCutoff)
  658. for s, nt := range n.NumericTags {
  659. n.NumericTags[s] = trimLowFreqTags(nt, tagCutoff)
  660. }
  661. }
  662. }
  663. func trimLowFreqTags(tags TagMap, minValue int64) TagMap {
  664. kept := TagMap{}
  665. for s, t := range tags {
  666. if abs64(t.Flat) >= minValue || abs64(t.Cum) >= minValue {
  667. kept[s] = t
  668. }
  669. }
  670. return kept
  671. }
  672. // TrimLowFrequencyEdges removes edges that have less than
  673. // the specified weight. Returns the number of edges removed
  674. func (g *Graph) TrimLowFrequencyEdges(edgeCutoff int64) int {
  675. var droppedEdges int
  676. for _, n := range g.Nodes {
  677. for src, e := range n.In {
  678. if abs64(e.Weight) < edgeCutoff {
  679. delete(n.In, src)
  680. delete(src.Out, n)
  681. droppedEdges++
  682. }
  683. }
  684. }
  685. return droppedEdges
  686. }
  687. // SortNodes sorts the nodes in a graph based on a specific heuristic.
  688. func (g *Graph) SortNodes(cum bool, visualMode bool) {
  689. // Sort nodes based on requested mode
  690. switch {
  691. case visualMode:
  692. // Specialized sort to produce a more visually-interesting graph
  693. g.Nodes.Sort(EntropyOrder)
  694. case cum:
  695. g.Nodes.Sort(CumNameOrder)
  696. default:
  697. g.Nodes.Sort(FlatNameOrder)
  698. }
  699. }
  700. // SelectTopNodePtrs returns a set of the top maxNodes *Node in a graph.
  701. func (g *Graph) SelectTopNodePtrs(maxNodes int, visualMode bool) NodePtrSet {
  702. set := make(NodePtrSet)
  703. for _, node := range g.selectTopNodes(maxNodes, visualMode) {
  704. set[node] = true
  705. }
  706. return set
  707. }
  708. // SelectTopNodes returns a set of the top maxNodes nodes in a graph.
  709. func (g *Graph) SelectTopNodes(maxNodes int, visualMode bool) NodeSet {
  710. return makeNodeSet(g.selectTopNodes(maxNodes, visualMode), 0)
  711. }
  712. // selectTopNodes returns a slice of the top maxNodes nodes in a graph.
  713. func (g *Graph) selectTopNodes(maxNodes int, visualMode bool) Nodes {
  714. if maxNodes > 0 {
  715. if visualMode {
  716. var count int
  717. // If generating a visual graph, count tags as nodes. Update
  718. // maxNodes to account for them.
  719. for i, n := range g.Nodes {
  720. tags := countTags(n)
  721. if tags > maxNodelets {
  722. tags = maxNodelets
  723. }
  724. if count += tags + 1; count >= maxNodes {
  725. maxNodes = i + 1
  726. break
  727. }
  728. }
  729. }
  730. }
  731. if maxNodes > len(g.Nodes) {
  732. maxNodes = len(g.Nodes)
  733. }
  734. return g.Nodes[:maxNodes]
  735. }
  736. // countTags counts the tags with flat count. This underestimates the
  737. // number of tags being displayed, but in practice is close enough.
  738. func countTags(n *Node) int {
  739. count := 0
  740. for _, e := range n.LabelTags {
  741. if e.Flat != 0 {
  742. count++
  743. }
  744. }
  745. for _, t := range n.NumericTags {
  746. for _, e := range t {
  747. if e.Flat != 0 {
  748. count++
  749. }
  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. }