Nav apraksta

graph.go 31KB

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