暂无描述

graph.go 30KB

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