Без опису

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