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