暫無描述

cli.go 8.6KB

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