暂无描述

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  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 driver
  15. import (
  16. "fmt"
  17. "os"
  18. "strings"
  19. "github.com/google/pprof/internal/binutils"
  20. "github.com/google/pprof/internal/plugin"
  21. )
  22. type source struct {
  23. Sources []string
  24. ExecName string
  25. BuildID string
  26. Base []string
  27. Normalize bool
  28. Seconds int
  29. Timeout int
  30. Symbolize string
  31. HTTPHostport string
  32. Comment string
  33. }
  34. // Parse parses the command lines through the specified flags package
  35. // and returns the source of the profile and optionally the command
  36. // for the kind of report to generate (nil for interactive use).
  37. func parseFlags(o *plugin.Options) (*source, []string, error) {
  38. flag := o.Flagset
  39. // Comparisons.
  40. flagBase := flag.StringList("base", "", "Source for base profile for comparison")
  41. // Source options.
  42. flagSymbolize := flag.String("symbolize", "", "Options for profile symbolization")
  43. flagBuildID := flag.String("buildid", "", "Override build id for first mapping")
  44. flagTimeout := flag.Int("timeout", -1, "Timeout in seconds for fetching a profile")
  45. flagAddComment := flag.String("add_comment", "", "Annotation string to record in the profile")
  46. // CPU profile options
  47. flagSeconds := flag.Int("seconds", -1, "Length of time for dynamic profiles")
  48. // Heap profile options
  49. flagInUseSpace := flag.Bool("inuse_space", false, "Display in-use memory size")
  50. flagInUseObjects := flag.Bool("inuse_objects", false, "Display in-use object counts")
  51. flagAllocSpace := flag.Bool("alloc_space", false, "Display allocated memory size")
  52. flagAllocObjects := flag.Bool("alloc_objects", false, "Display allocated object counts")
  53. // Contention profile options
  54. flagTotalDelay := flag.Bool("total_delay", false, "Display total delay at each region")
  55. flagContentions := flag.Bool("contentions", false, "Display number of delays at each region")
  56. flagMeanDelay := flag.Bool("mean_delay", false, "Display mean delay at each region")
  57. flagTools := flag.String("tools", os.Getenv("PPROF_TOOLS"), "Path for object tool pathnames")
  58. flagHTTP := flag.String("http", "", "Present interactive web based UI at the specified http host:port")
  59. // Flags used during command processing
  60. installedFlags := installFlags(flag)
  61. flagCommands := make(map[string]*bool)
  62. flagParamCommands := make(map[string]*string)
  63. for name, cmd := range pprofCommands {
  64. if cmd.hasParam {
  65. flagParamCommands[name] = flag.String(name, "", "Generate a report in "+name+" format, matching regexp")
  66. } else {
  67. flagCommands[name] = flag.Bool(name, false, "Generate a report in "+name+" format")
  68. }
  69. }
  70. args := flag.Parse(func() {
  71. o.UI.Print(usageMsgHdr +
  72. usage(true) +
  73. usageMsgSrc +
  74. flag.ExtraUsage() +
  75. usageMsgVars)
  76. })
  77. if len(args) == 0 {
  78. return nil, nil, fmt.Errorf("no profile source specified")
  79. }
  80. var execName string
  81. // Recognize first argument as an executable or buildid override.
  82. if len(args) > 1 {
  83. arg0 := args[0]
  84. if file, err := o.Obj.Open(arg0, 0, ^uint64(0), 0); err == nil {
  85. file.Close()
  86. execName = arg0
  87. args = args[1:]
  88. } else if *flagBuildID == "" && isBuildID(arg0) {
  89. *flagBuildID = arg0
  90. args = args[1:]
  91. }
  92. }
  93. // Report conflicting options
  94. if err := updateFlags(installedFlags); err != nil {
  95. return nil, nil, err
  96. }
  97. cmd, err := outputFormat(flagCommands, flagParamCommands)
  98. if err != nil {
  99. return nil, nil, err
  100. }
  101. if cmd != nil && *flagHTTP != "" {
  102. return nil, nil, fmt.Errorf("-http is not compatible with an output format on the command line")
  103. }
  104. si := pprofVariables["sample_index"].value
  105. si = sampleIndex(flagTotalDelay, si, "delay", "-total_delay", o.UI)
  106. si = sampleIndex(flagMeanDelay, si, "delay", "-mean_delay", o.UI)
  107. si = sampleIndex(flagContentions, si, "contentions", "-contentions", o.UI)
  108. si = sampleIndex(flagInUseSpace, si, "inuse_space", "-inuse_space", o.UI)
  109. si = sampleIndex(flagInUseObjects, si, "inuse_objects", "-inuse_objects", o.UI)
  110. si = sampleIndex(flagAllocSpace, si, "alloc_space", "-alloc_space", o.UI)
  111. si = sampleIndex(flagAllocObjects, si, "alloc_objects", "-alloc_objects", o.UI)
  112. pprofVariables.set("sample_index", si)
  113. if *flagMeanDelay {
  114. pprofVariables.set("mean", "true")
  115. }
  116. source := &source{
  117. Sources: args,
  118. ExecName: execName,
  119. BuildID: *flagBuildID,
  120. Seconds: *flagSeconds,
  121. Timeout: *flagTimeout,
  122. Symbolize: *flagSymbolize,
  123. HTTPHostport: *flagHTTP,
  124. Comment: *flagAddComment,
  125. }
  126. for _, s := range *flagBase {
  127. if *s != "" {
  128. source.Base = append(source.Base, *s)
  129. }
  130. }
  131. normalize := pprofVariables["normalize"].boolValue()
  132. if normalize && len(source.Base) == 0 {
  133. return nil, nil, fmt.Errorf("Must have base profile to normalize by")
  134. }
  135. source.Normalize = normalize
  136. if bu, ok := o.Obj.(*binutils.Binutils); ok {
  137. bu.SetTools(*flagTools)
  138. }
  139. return source, cmd, nil
  140. }
  141. // installFlags creates command line flags for pprof variables.
  142. func installFlags(flag plugin.FlagSet) flagsInstalled {
  143. f := flagsInstalled{
  144. ints: make(map[string]*int),
  145. bools: make(map[string]*bool),
  146. floats: make(map[string]*float64),
  147. strings: make(map[string]*string),
  148. }
  149. for n, v := range pprofVariables {
  150. switch v.kind {
  151. case boolKind:
  152. if v.group != "" {
  153. // Set all radio variables to false to identify conflicts.
  154. f.bools[n] = flag.Bool(n, false, v.help)
  155. } else {
  156. f.bools[n] = flag.Bool(n, v.boolValue(), v.help)
  157. }
  158. case intKind:
  159. f.ints[n] = flag.Int(n, v.intValue(), v.help)
  160. case floatKind:
  161. f.floats[n] = flag.Float64(n, v.floatValue(), v.help)
  162. case stringKind:
  163. f.strings[n] = flag.String(n, v.value, v.help)
  164. }
  165. }
  166. return f
  167. }
  168. // updateFlags updates the pprof variables according to the flags
  169. // parsed in the command line.
  170. func updateFlags(f flagsInstalled) error {
  171. vars := pprofVariables
  172. groups := map[string]string{}
  173. for n, v := range f.bools {
  174. vars.set(n, fmt.Sprint(*v))
  175. if *v {
  176. g := vars[n].group
  177. if g != "" && groups[g] != "" {
  178. return fmt.Errorf("conflicting options %q and %q set", n, groups[g])
  179. }
  180. groups[g] = n
  181. }
  182. }
  183. for n, v := range f.ints {
  184. vars.set(n, fmt.Sprint(*v))
  185. }
  186. for n, v := range f.floats {
  187. vars.set(n, fmt.Sprint(*v))
  188. }
  189. for n, v := range f.strings {
  190. vars.set(n, *v)
  191. }
  192. return nil
  193. }
  194. type flagsInstalled struct {
  195. ints map[string]*int
  196. bools map[string]*bool
  197. floats map[string]*float64
  198. strings map[string]*string
  199. }
  200. // isBuildID determines if the profile may contain a build ID, by
  201. // checking that it is a string of hex digits.
  202. func isBuildID(id string) bool {
  203. return strings.Trim(id, "0123456789abcdefABCDEF") == ""
  204. }
  205. func sampleIndex(flag *bool, si string, sampleType, option string, ui plugin.UI) string {
  206. if *flag {
  207. if si == "" {
  208. return sampleType
  209. }
  210. ui.PrintErr("Multiple value selections, ignoring ", option)
  211. }
  212. return si
  213. }
  214. func outputFormat(bcmd map[string]*bool, acmd map[string]*string) (cmd []string, err error) {
  215. for n, b := range bcmd {
  216. if *b {
  217. if cmd != nil {
  218. return nil, fmt.Errorf("must set at most one output format")
  219. }
  220. cmd = []string{n}
  221. }
  222. }
  223. for n, s := range acmd {
  224. if *s != "" {
  225. if cmd != nil {
  226. return nil, fmt.Errorf("must set at most one output format")
  227. }
  228. cmd = []string{n, *s}
  229. }
  230. }
  231. return cmd, nil
  232. }
  233. var usageMsgHdr = `usage:
  234. Produce output in the specified format.
  235. pprof <format> [options] [binary] <source> ...
  236. Omit the format to get an interactive shell whose commands can be used
  237. to generate various views of a profile
  238. pprof [options] [binary] <source> ...
  239. Omit the format and provide the "-http" flag to get an interactive web
  240. interface at the specified host:port that can be used to navigate through
  241. various views of a profile.
  242. pprof -http [host]:[port] [options] [binary] <source> ...
  243. Details:
  244. `
  245. var usageMsgSrc = "\n\n" +
  246. " Source options:\n" +
  247. " -seconds Duration for time-based profile collection\n" +
  248. " -timeout Timeout in seconds for profile collection\n" +
  249. " -buildid Override build id for main binary\n" +
  250. " -add_comment Free-form annotation to add to the profile\n" +
  251. " Displayed on some reports or with pprof -comments\n" +
  252. " -base source Source of profile to use as baseline\n" +
  253. " profile.pb.gz Profile in compressed protobuf format\n" +
  254. " legacy_profile Profile in legacy pprof format\n" +
  255. " http://host/profile URL for profile handler to retrieve\n" +
  256. " -symbolize= Controls source of symbol information\n" +
  257. " none Do not attempt symbolization\n" +
  258. " local Examine only local binaries\n" +
  259. " fastlocal Only get function names from local binaries\n" +
  260. " remote Do not examine local binaries\n" +
  261. " force Force re-symbolization\n" +
  262. " Binary Local path or build id of binary for symbolization\n"
  263. var usageMsgVars = "\n\n" +
  264. " Misc options:\n" +
  265. " -http Provide web based interface at host:port.\n" +
  266. " Host is optional and 'localhost' by default.\n" +
  267. " Port is optional and a randomly available port by default.\n" +
  268. " -tools Search path for object tools\n" +
  269. "\n" +
  270. " Legacy convenience options:\n" +
  271. " -inuse_space Same as -sample_index=inuse_space\n" +
  272. " -inuse_objects Same as -sample_index=inuse_objects\n" +
  273. " -alloc_space Same as -sample_index=alloc_space\n" +
  274. " -alloc_objects Same as -sample_index=alloc_objects\n" +
  275. " -total_delay Same as -sample_index=delay\n" +
  276. " -contentions Same as -sample_index=contentions\n" +
  277. " -mean_delay Same as -mean -sample_index=delay\n" +
  278. "\n" +
  279. " Environment Variables:\n" +
  280. " PPROF_TMPDIR Location for saved profiles (default $HOME/pprof)\n" +
  281. " PPROF_TOOLS Search path for object-level tools\n" +
  282. " PPROF_BINARY_PATH Search path for local binary files\n" +
  283. " default: $HOME/pprof/binaries\n" +
  284. " searches $name, $path, $buildid/$name, $path/$buildid\n" +
  285. " * On Windows, %USERPROFILE% is used instead of $HOME"