暂无描述

cli.go 9.3KB

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