Nenhuma descrição

cli.go 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  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 that set configuration properties.
  65. cfg := currentConfig()
  66. configFlagSetter := installConfigFlags(flag, &cfg)
  67. flagCommands := make(map[string]*bool)
  68. flagParamCommands := make(map[string]*string)
  69. for name, cmd := range pprofCommands {
  70. if cmd.hasParam {
  71. flagParamCommands[name] = flag.String(name, "", "Generate a report in "+name+" format, matching regexp")
  72. } else {
  73. flagCommands[name] = flag.Bool(name, false, "Generate a report in "+name+" format")
  74. }
  75. }
  76. args := flag.Parse(func() {
  77. o.UI.Print(usageMsgHdr +
  78. usage(true) +
  79. usageMsgSrc +
  80. flag.ExtraUsage() +
  81. usageMsgVars)
  82. })
  83. if len(args) == 0 {
  84. return nil, nil, errors.New("no profile source specified")
  85. }
  86. var execName string
  87. // Recognize first argument as an executable or buildid override.
  88. if len(args) > 1 {
  89. arg0 := args[0]
  90. if file, err := o.Obj.Open(arg0, 0, ^uint64(0), 0); err == nil {
  91. file.Close()
  92. execName = arg0
  93. args = args[1:]
  94. } else if *flagBuildID == "" && isBuildID(arg0) {
  95. *flagBuildID = arg0
  96. args = args[1:]
  97. }
  98. }
  99. // Apply any specified flags to cfg.
  100. if err := configFlagSetter(); err != nil {
  101. return nil, nil, err
  102. }
  103. cmd, err := outputFormat(flagCommands, flagParamCommands)
  104. if err != nil {
  105. return nil, nil, err
  106. }
  107. if cmd != nil && *flagHTTP != "" {
  108. return nil, nil, errors.New("-http is not compatible with an output format on the command line")
  109. }
  110. if *flagNoBrowser && *flagHTTP == "" {
  111. return nil, nil, errors.New("-no_browser only makes sense with -http")
  112. }
  113. si := cfg.SampleIndex
  114. si = sampleIndex(flagTotalDelay, si, "delay", "-total_delay", o.UI)
  115. si = sampleIndex(flagMeanDelay, si, "delay", "-mean_delay", o.UI)
  116. si = sampleIndex(flagContentions, si, "contentions", "-contentions", o.UI)
  117. si = sampleIndex(flagInUseSpace, si, "inuse_space", "-inuse_space", o.UI)
  118. si = sampleIndex(flagInUseObjects, si, "inuse_objects", "-inuse_objects", o.UI)
  119. si = sampleIndex(flagAllocSpace, si, "alloc_space", "-alloc_space", o.UI)
  120. si = sampleIndex(flagAllocObjects, si, "alloc_objects", "-alloc_objects", o.UI)
  121. cfg.SampleIndex = si
  122. if *flagMeanDelay {
  123. cfg.Mean = true
  124. }
  125. source := &source{
  126. Sources: args,
  127. ExecName: execName,
  128. BuildID: *flagBuildID,
  129. Seconds: *flagSeconds,
  130. Timeout: *flagTimeout,
  131. Symbolize: *flagSymbolize,
  132. HTTPHostport: *flagHTTP,
  133. HTTPDisableBrowser: *flagNoBrowser,
  134. Comment: *flagAddComment,
  135. }
  136. if err := source.addBaseProfiles(*flagBase, *flagDiffBase); err != nil {
  137. return nil, nil, err
  138. }
  139. normalize := cfg.Normalize
  140. if normalize && len(source.Base) == 0 {
  141. return nil, nil, errors.New("must have base profile to normalize by")
  142. }
  143. source.Normalize = normalize
  144. if bu, ok := o.Obj.(*binutils.Binutils); ok {
  145. bu.SetTools(*flagTools)
  146. }
  147. setCurrentConfig(cfg)
  148. return source, cmd, nil
  149. }
  150. // addBaseProfiles adds the list of base profiles or diff base profiles to
  151. // the source. This function will return an error if both base and diff base
  152. // profiles are specified.
  153. func (source *source) addBaseProfiles(flagBase, flagDiffBase []*string) error {
  154. base, diffBase := dropEmpty(flagBase), dropEmpty(flagDiffBase)
  155. if len(base) > 0 && len(diffBase) > 0 {
  156. return errors.New("-base and -diff_base flags cannot both be specified")
  157. }
  158. source.Base = base
  159. if len(diffBase) > 0 {
  160. source.Base, source.DiffBase = diffBase, true
  161. }
  162. return nil
  163. }
  164. // dropEmpty list takes a slice of string pointers, and outputs a slice of
  165. // non-empty strings associated with the flag.
  166. func dropEmpty(list []*string) []string {
  167. var l []string
  168. for _, s := range list {
  169. if *s != "" {
  170. l = append(l, *s)
  171. }
  172. }
  173. return l
  174. }
  175. // installConfigFlags creates command line flags for configuration
  176. // fields and returns a function which can be called after flags have
  177. // been parsed to copy any flags specified on the command line to
  178. // *cfg.
  179. func installConfigFlags(flag plugin.FlagSet, cfg *config) func() error {
  180. // List of functions for setting the different parts of a config.
  181. var setters []func()
  182. var err error // Holds any errors encountered while running setters.
  183. for _, field := range configFields {
  184. n := field.name
  185. help := configHelp[n]
  186. var setter func()
  187. switch ptr := cfg.fieldPtr(field).(type) {
  188. case *bool:
  189. f := flag.Bool(n, *ptr, help)
  190. setter = func() { *ptr = *f }
  191. case *int:
  192. f := flag.Int(n, *ptr, help)
  193. setter = func() { *ptr = *f }
  194. case *float64:
  195. f := flag.Float64(n, *ptr, help)
  196. setter = func() { *ptr = *f }
  197. case *string:
  198. if len(field.choices) == 0 {
  199. f := flag.String(n, *ptr, help)
  200. setter = func() { *ptr = *f }
  201. } else {
  202. // Make a separate flag per possible choice.
  203. // Set all flags to initially false so we can
  204. // identify conflicts.
  205. bools := make(map[string]*bool)
  206. for _, choice := range field.choices {
  207. bools[choice] = flag.Bool(choice, false, configHelp[choice])
  208. }
  209. setter = func() {
  210. var set []string
  211. for k, v := range bools {
  212. if *v {
  213. set = append(set, k)
  214. }
  215. }
  216. switch len(set) {
  217. case 0:
  218. // Leave as default value.
  219. case 1:
  220. *ptr = set[0]
  221. default:
  222. err = fmt.Errorf("conflicting options set: %v", set)
  223. }
  224. }
  225. }
  226. }
  227. setters = append(setters, setter)
  228. }
  229. return func() error {
  230. // Apply the setter for every flag.
  231. for _, setter := range setters {
  232. setter()
  233. if err != nil {
  234. return err
  235. }
  236. }
  237. return nil
  238. }
  239. }
  240. // isBuildID determines if the profile may contain a build ID, by
  241. // checking that it is a string of hex digits.
  242. func isBuildID(id string) bool {
  243. return strings.Trim(id, "0123456789abcdefABCDEF") == ""
  244. }
  245. func sampleIndex(flag *bool, si string, sampleType, option string, ui plugin.UI) string {
  246. if *flag {
  247. if si == "" {
  248. return sampleType
  249. }
  250. ui.PrintErr("Multiple value selections, ignoring ", option)
  251. }
  252. return si
  253. }
  254. func outputFormat(bcmd map[string]*bool, acmd map[string]*string) (cmd []string, err error) {
  255. for n, b := range bcmd {
  256. if *b {
  257. if cmd != nil {
  258. return nil, errors.New("must set at most one output format")
  259. }
  260. cmd = []string{n}
  261. }
  262. }
  263. for n, s := range acmd {
  264. if *s != "" {
  265. if cmd != nil {
  266. return nil, errors.New("must set at most one output format")
  267. }
  268. cmd = []string{n, *s}
  269. }
  270. }
  271. return cmd, nil
  272. }
  273. var usageMsgHdr = `usage:
  274. Produce output in the specified format.
  275. pprof <format> [options] [binary] <source> ...
  276. Omit the format to get an interactive shell whose commands can be used
  277. to generate various views of a profile
  278. pprof [options] [binary] <source> ...
  279. Omit the format and provide the "-http" flag to get an interactive web
  280. interface at the specified host:port that can be used to navigate through
  281. various views of a profile.
  282. pprof -http [host]:[port] [options] [binary] <source> ...
  283. Details:
  284. `
  285. var usageMsgSrc = "\n\n" +
  286. " Source options:\n" +
  287. " -seconds Duration for time-based profile collection\n" +
  288. " -timeout Timeout in seconds for profile collection\n" +
  289. " -buildid Override build id for main binary\n" +
  290. " -add_comment Free-form annotation to add to the profile\n" +
  291. " Displayed on some reports or with pprof -comments\n" +
  292. " -diff_base source Source of base profile for comparison\n" +
  293. " -base source Source of base profile for profile subtraction\n" +
  294. " profile.pb.gz Profile in compressed protobuf format\n" +
  295. " legacy_profile Profile in legacy pprof format\n" +
  296. " http://host/profile URL for profile handler to retrieve\n" +
  297. " -symbolize= Controls source of symbol information\n" +
  298. " none Do not attempt symbolization\n" +
  299. " local Examine only local binaries\n" +
  300. " fastlocal Only get function names from local binaries\n" +
  301. " remote Do not examine local binaries\n" +
  302. " force Force re-symbolization\n" +
  303. " Binary Local path or build id of binary for symbolization\n"
  304. var usageMsgVars = "\n\n" +
  305. " Misc options:\n" +
  306. " -http Provide web interface at host:port.\n" +
  307. " Host is optional and 'localhost' by default.\n" +
  308. " Port is optional and a randomly available port by default.\n" +
  309. " -no_browser Skip opening a browser for the interactive web UI.\n" +
  310. " -tools Search path for object tools\n" +
  311. "\n" +
  312. " Legacy convenience options:\n" +
  313. " -inuse_space Same as -sample_index=inuse_space\n" +
  314. " -inuse_objects Same as -sample_index=inuse_objects\n" +
  315. " -alloc_space Same as -sample_index=alloc_space\n" +
  316. " -alloc_objects Same as -sample_index=alloc_objects\n" +
  317. " -total_delay Same as -sample_index=delay\n" +
  318. " -contentions Same as -sample_index=contentions\n" +
  319. " -mean_delay Same as -mean -sample_index=delay\n" +
  320. "\n" +
  321. " Environment Variables:\n" +
  322. " PPROF_TMPDIR Location for saved profiles (default $HOME/pprof)\n" +
  323. " PPROF_TOOLS Search path for object-level tools\n" +
  324. " PPROF_BINARY_PATH Search path for local binary files\n" +
  325. " default: $HOME/pprof/binaries\n" +
  326. " searches $name, $path, $buildid/$name, $path/$buildid\n" +
  327. " * On Windows, %USERPROFILE% is used instead of $HOME"