func (cm *ConfigManager) parseFlags() { pflag.StringVarP(&cm.Flags.ConfigFile, "configfile", "c", DefaultConfigFile, "Path to config") pflag.StringVarP(&cm.Flags.DestHost, "dest-host", "d", "", "Destination syslog hostname or IP") pflag.IntVarP(&cm.Flags.DestPort, "dest-port", "p", 0, "Destination syslog port") if utils.CanDaemonize { pflag.BoolVarP(&cm.Flags.NoDaemonize, "no-detach", "D", false, "Don't daemonize and detach from the terminal") } else { cm.Flags.NoDaemonize = true } pflag.StringVarP(&cm.Flags.Facility, "facility", "f", "user", "Facility") pflag.StringVar(&cm.Flags.Hostname, "hostname", "", "Local hostname to send from") pflag.StringVar(&cm.Flags.PidFile, "pid-file", "", "Location of the PID file") // --parse-syslog pflag.StringVarP(&cm.Flags.Severity, "severity", "s", "notice", "Severity") // --strip-color pflag.BoolVar(&cm.Flags.UseTCP, "tcp", false, "Connect via TCP (no TLS)") pflag.BoolVar(&cm.Flags.UseTLS, "tls", false, "Connect via TCP with TLS") pflag.BoolVar(&cm.Flags.Poll, "poll", false, "Detect changes by polling instead of inotify") pflag.Var(&cm.Flags.RefreshInterval, "new-file-check-interval", "How often to check for new files") _ = pflag.Bool("no-eventmachine-tail", false, "No action, provided for backwards compatibility") _ = pflag.Bool("eventmachine-tail", false, "No action, provided for backwards compatibility") pflag.StringVar(&cm.Flags.DebugLogFile, "debug-log-cfg", "", "the debug log file") pflag.StringVar(&cm.Flags.LogLevels, "log", "<root>=INFO", "\"logging configuration <root>=INFO;first=TRACE\"") pflag.Parse() cm.FlagFiles = pflag.Args() }
func main() { adaptflag.AdaptWithFunc(func(info adaptflag.Info) { flag.Var(info.Value, info.Name, info.Usage) }) flag.Parse() }
func main() { color := color.New() pflag.Var(color, "color", "when to use color (always|auto|never)") pflag.Parse() wd, err := os.Getwd() mustNot(err) gr, err := FindGithubInfo(wd) mustNot(err) err = GetReleaseInfo(gr) mustNot(err) t := template.Must(template.New("output").Parse(color.Sprint(outputTmpl))) t.Execute(os.Stdout, gr) }
func main() { tgt := &Config{} c := cstruct.MustNew(tgt, "example") configurable.Register(c) adaptflag.AdaptWithFunc(func(info adaptflag.Info) { flag.Var(info.Value, info.Name, info.Usage) }) flag.Parse() err := adaptconf.Load("exampleapp2") if err != nil { fmt.Printf("%v\n", err) } fmt.Printf("%#v\n", tgt) }
// Adapt registers all registered configurables as flags with the flag and // ogier/pflag packages. Note that Adapt will not do anything with // Configurables which it has already adapted once, thus it is safe to call // this function multiple times. func Adapt() { AdaptWithFunc(func(info Info) { dpn := DottedPath(info.Path) if len(dpn) > 0 { dpn += "." } dpn += info.Name flag.Var(info.Value, dpn, info.Usage) pflag.Var(info.Value, dpn, info.Usage) fl := kingpin.Flag(dpn, info.Usage) if info.DefaultValueString != "" { fl = fl.PlaceHolder(info.DefaultValueString) } else { fl = fl.PlaceHolder("\"\"") } if r, ok := shortFlags[dpn]; ok { fl = fl.Short(byte(r)) } fl.SetValue(info.Value) }) }
func readConfig(parse bool) { var err error // Set defaults ConfigYAML.UDPServiceAddress = defaultUDPServiceAddress ConfigYAML.TCPServiceAddress = defaultTCPServiceAddress ConfigYAML.MaxUDPPacketSize = maxUDPPacket ConfigYAML.BackendType = defaultBackendType ConfigYAML.PostFlushCmd = "stdout" ConfigYAML.GraphiteAddress = defaultGraphiteAddress ConfigYAML.OpenTSDBAddress = defaultOpenTSDBAddress ConfigYAML.FlushInterval = flushInterval ConfigYAML.LogLevel = "error" ConfigYAML.ShowVersion = false ConfigYAML.DeleteGauges = true ConfigYAML.ResetCounters = true ConfigYAML.PersistCountKeys = 0 ConfigYAML.StatsPrefix = statsPrefixName ConfigYAML.StoreDb = dbPath ConfigYAML.Prefix = "" ConfigYAML.ExtraTags = "" ConfigYAML.PercentThreshold = Percentiles{} // Percentiles{{Float: 50.0, Str: "50"}, {Float: 80.0, Str: "80"}, {Float: 90.0, Str: "90"}, {Float: 95.0, Str: "95"}} ConfigYAML.PrintConfig = false ConfigYAML.LogName = "stdout" ConfigYAML.LogToSyslog = true ConfigYAML.SyslogUDPAddress = "localhost:514" Config = ConfigYAML os.Setenv("CONFIGOR_ENV_PREFIX", "SD") configFile = flag.String("config", "", "Configuration file name (warning not error if not exists). Standard: "+configPath) flag.StringVar(&Config.UDPServiceAddress, "udp-addr", ConfigYAML.UDPServiceAddress, "UDP listen service address") flag.StringVar(&Config.TCPServiceAddress, "tcp-addr", ConfigYAML.TCPServiceAddress, "TCP listen service address, if set") flag.Int64Var(&Config.MaxUDPPacketSize, "max-udp-packet-size", ConfigYAML.MaxUDPPacketSize, "Maximum UDP packet size") flag.StringVar(&Config.BackendType, "backend-type", ConfigYAML.BackendType, "MANDATORY: Backend to use: graphite, opentsdb, external, dummy") flag.StringVar(&Config.PostFlushCmd, "post-flush-cmd", ConfigYAML.PostFlushCmd, "Command to run on each flush") flag.StringVar(&Config.GraphiteAddress, "graphite", ConfigYAML.GraphiteAddress, "Graphite service address") flag.StringVar(&Config.OpenTSDBAddress, "opentsdb", ConfigYAML.OpenTSDBAddress, "OpenTSDB service address") flag.Int64Var(&Config.FlushInterval, "flush-interval", ConfigYAML.FlushInterval, "Flush interval (seconds)") flag.StringVar(&Config.LogLevel, "log-level", ConfigYAML.LogLevel, "Set log level (debug,info,warn,error,fatal)") flag.BoolVar(&Config.ShowVersion, "version", ConfigYAML.ShowVersion, "Print version string") flag.BoolVar(&Config.DeleteGauges, "delete-gauges", ConfigYAML.DeleteGauges, "Don't send values to graphite for inactive gauges, as opposed to sending the previous value") flag.BoolVar(&Config.ResetCounters, "reset-counters", ConfigYAML.ResetCounters, "Reset counters after sending value to backend (send rate) or send cumulated value (artificial counter - eg. for OpenTSDB & Grafana)") flag.Int64Var(&Config.PersistCountKeys, "persist-count-keys", ConfigYAML.PersistCountKeys, "Number of flush-intervals to persist count keys") flag.StringVar(&Config.StatsPrefix, "stats-prefix", ConfigYAML.StatsPrefix, "Name for internal application metrics (no prefix prepended)") flag.StringVar(&Config.StoreDb, "store-db", ConfigYAML.StoreDb, "Name of database for permanent counters storage (for conversion from rate to counter)") flag.StringVar(&Config.Prefix, "prefix", ConfigYAML.Prefix, "Prefix for all stats") flag.StringVar(&Config.ExtraTags, "extra-tags", ConfigYAML.ExtraTags, "Default tags added to all measures in format: tag1=value1 tag2=value2") flag.Var(&Config.PercentThreshold, "percent-threshold", "Percentile calculation for timers (0-100, may be given multiple times)") flag.BoolVar(&Config.PrintConfig, "print-config", ConfigYAML.PrintConfig, "Print config in YAML format") flag.StringVar(&Config.LogName, "log-name", ConfigYAML.LogName, "Name of file to log into. If \"stdout\" than logs to stdout.If empty logs go to /dev/null") flag.BoolVar(&Config.LogToSyslog, "log-to-syslopg", ConfigYAML.LogToSyslog, "Log to syslog") flag.StringVar(&Config.SyslogUDPAddress, "syslog-udp-address", ConfigYAML.SyslogUDPAddress, "Syslog address with port number eg. localhost:514. If empty log to unix socket") if parse { flag.Parse() } if len(*configFile) > 0 { if _, err = os.Stat(*configFile); os.IsNotExist(err) { fmt.Printf("# Warning: No config file: %s\n", *configFile) *configFile = "" } if len(*configFile) > 0 { err = configor.Load(&ConfigYAML, *configFile) if err != nil { fmt.Printf("Error loading config file: %s\n", err) } else { // set configs read form YAML file // save 2 flags tmpConfig := Config // Overwites flags Config = ConfigYAML // restore 2 flags Config.ShowVersion = tmpConfig.ShowVersion Config.PrintConfig = tmpConfig.PrintConfig } } // visitor := func(a *flag.Flag) { // fmt.Println(">", a.Name, "value=", a.Value) // switch a.Name { // case "print-config", "version": // break // case "udp-addr": // ConfigYAML.UDPServiceAddress = a.Value.(string) // default: // fmt.Printf("Internal Config Error - unknown variable: %s\n", a.Name) // os.Exit(1) // } // // } // flag.Visit(visitor) } // Normalize prefix Config.Prefix = normalizeDot(Config.Prefix, true) // Normalize internal metrics name Config.StatsPrefix = normalizeDot(Config.StatsPrefix, true) // calculate extraFlags hash Config.ExtraTagsHash, err = parseExtraTags(Config.ExtraTags) if err != nil { fmt.Printf("Extra Tags: \"%s\" - %s\n", Config.ExtraTags, err) os.Exit(1) } // Set InternalLogLevel Config.InternalLogLevel, err = log.ParseLevel(Config.LogLevel) if err != nil { fmt.Printf("Invalid log level: \"%s\"\n", Config.LogLevel) os.Exit(1) } }
func init() { // Tie the command-line flag to the intervalFlag variable and // set a usage message. flag.Var(&intervalFlag, "deltaT", "comma-separated list of intervals to use between events") }
// Read configuration from both profile and flags. Flags override profile. func config() error { var err error if B2D.Dir, err = getCfgDir(".boot2docker"); err != nil { return fmt.Errorf("failed to get current directory: %s", err) } filename := os.Getenv("BOOT2DOCKER_PROFILE") if filename == "" { filename = filepath.Join(B2D.Dir, "profile") } profile, err := getProfile(filename) if err != nil && !os.IsNotExist(err) { // undefined/empty profile works return err } if p := os.Getenv("VBOX_INSTALL_PATH"); p != "" && runtime.GOOS == "windows" { B2D.VBM = profile.Get("", "vbm", filepath.Join(p, "VBoxManage.exe")) } else { B2D.VBM = profile.Get("", "vbm", "VBoxManage") } B2D.SSH = profile.Get("", "ssh", "ssh") B2D.VM = profile.Get("", "vm", "boot2docker-vm") B2D.ISO = profile.Get("", "iso", filepath.Join(B2D.Dir, "boot2docker.iso")) if diskSize, err := strconv.ParseUint(profile.Get("", "disksize", "20000"), 10, 32); err != nil { return fmt.Errorf("invalid disk image size: %s", err) } else { B2D.DiskSize = uint(diskSize) } if memory, err := strconv.ParseUint(profile.Get("", "memory", "1024"), 10, 32); err != nil { return fmt.Errorf("invalid memory size: %s", err) } else { B2D.Memory = uint(memory) } if sshPort, err := strconv.ParseUint(profile.Get("", "sshport", "2022"), 10, 16); err != nil { return fmt.Errorf("invalid SSH port: %s", err) } else { B2D.SSHPort = uint16(sshPort) } if dockerPort, err := strconv.ParseUint(profile.Get("", "dockerport", "4243"), 10, 16); err != nil { return fmt.Errorf("invalid DockerPort: %s", err) } else { B2D.DockerPort = uint16(dockerPort) } // Host only networking settings B2D.HostIP = profile.Get("", "hostiP", "192.168.59.3") B2D.DHCPIP = profile.Get("", "dhcpip", "192.168.59.99") B2D.NetworkMask = profile.Get("", "netmask", "255.255.255.0") B2D.LowerIPAddress = profile.Get("", "lowerip", "192.168.59.103") B2D.UpperIPAddress = profile.Get("", "upperip", "192.168.59.254") B2D.DHCPEnabled = profile.Get("", "dhcp", "Yes") // Commandline flags override profile settings. flag.StringVar(&B2D.VBM, "vbm", B2D.VBM, "Path to VirtualBox management utility") flag.StringVar(&B2D.SSH, "ssh", B2D.SSH, "Path to SSH client utility") flag.StringVarP(&B2D.Dir, "dir", "d", B2D.Dir, "boot2docker config directory") flag.StringVar(&B2D.ISO, "iso", B2D.ISO, "Path to boot2docker ISO image") flag.UintVarP(&B2D.DiskSize, "disksize", "s", B2D.DiskSize, "boot2docker disk image size (in MB)") flag.UintVarP(&B2D.Memory, "memory", "m", B2D.Memory, "Virtual machine memory size (in MB)") flag.Var(newUint16Value(B2D.SSHPort, &B2D.SSHPort), "sshport", "Host SSH port (forward to port 22 in VM)") flag.Var(newUint16Value(B2D.DockerPort, &B2D.DockerPort), "dockerport", "Host Docker port (forward to port 4243 in VM)") flag.StringVar(&B2D.HostIP, "hostip", B2D.HostIP, "VirtualBox host-only network IP address") flag.StringVar(&B2D.NetworkMask, "netmask", B2D.NetworkMask, "VirtualBox host-only network mask") flag.StringVar(&B2D.DHCPEnabled, "dhcp", B2D.DHCPEnabled, "Enable VirtualBox host-only network DHCP") flag.StringVar(&B2D.DHCPIP, "dhcpip", B2D.DHCPIP, "VirtualBox host-only network DHCP server address") flag.StringVar(&B2D.LowerIPAddress, "lowerip", B2D.LowerIPAddress, "VirtualBox host-only network DHCP lower bound") flag.StringVar(&B2D.UpperIPAddress, "upperip", B2D.UpperIPAddress, "VirtualBox host-only network DHCP upper bound") flag.Parse() // Name of VM is the second argument. if vm := flag.Arg(1); vm != "" { B2D.VM = vm } return nil }