You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

359 lines
12 KiB

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