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