func positive(i int64) bool { if i < 0 { flag.Usage() return false } return true }
func main() { var config Config flag.BoolVar(&DEBUG, "debug", false, "enable debug logging") flag.BoolVar(&QUIET, "quiet", false, "disable output") flag.StringVar(&config.FieldSep, "csv-fields-terminated-by", "\t", "field separator") flag.StringVar(&config.RowSep, "csv-records-terminated-by", "\n", "row separator") flag.StringVar(&config.NullString, "csv-null-string", "\\N", "output string for NULL values") flag.BoolVar(&config.DateEpoch, "epoch", true, "output datetime as epoch instead of RFC3339") defaults_file := flag.String("defaults-file", "my.cnf", "defaults file") defaults_group_suffix := flag.String("defaults-group-suffix", "", "defaults group suffix") format := flag.String("format", "json", "output format 'json' or 'csv'") flag.Usage = func() { fmt.Fprintf(os.Stderr, "Usage: mysqlcsvdump [options] database table > output.json\n\n") fmt.Fprintf(os.Stderr, "Reads connection info from ./my.cnf. Use '-' for table to send query in stdin\n\n") flag.PrintDefaults() } flag.Parse() args := flag.Args() if len(args) < 2 { flag.Usage() os.Exit(1) } dsn := getDSN(*defaults_file, "client"+*defaults_group_suffix, args[0]) rows := getRows(dsn, args[1]) if *format == "json" { NewJsonWriter(&config).WriteRows(rows) } else { NewCsvWriter(&config).WriteRows(rows) } }
func main() { var widthstr string flag.StringVarP(&widthstr, "width", "w", "100%", "Output width. Supports column count, percentage and decimals.") flag.Usage = usage flag.Parse() if len(flag.Args()) == 0 { flag.Usage() os.Exit(1) } width := getColumns(widthstr) - 1 // -1 for the reset column for _, fpath := range flag.Args() { im := aimg.NewImage(width) handleErr(im.ParseFile(fpath)) if terminal.IsTerminal(os.Stdout) { fmt.Print(im.BlankReset()) } im.WriteTo(os.Stdout) w, h := im.ActualSize() fmt.Println("File:", filepath.Base(fpath), "size:", w, "x", h) } }
func identify_pipe() { stat, _ := os.Stdin.Stat() if (stat.Mode() & os.ModeCharDevice) == 0 { reader := bufio.NewReader(os.Stdin) printID(encode(reader)) } else { flag.Usage() } }
func main() { flag.Parse() if !valid() { flag.Usage() os.Exit(1) } if len(os.Args) < 2 { flag.Usage() os.Exit(1) } directory := os.Args[1] if generateTestFiles { if len(os.Args) < 4 { flag.Usage() os.Exit(1) } domainsFilename := os.Args[2] _, err := generation.GenerateTestData( directory, fileCount, rowCount, timeOrigin, timeFrame, uidCount, domainsFilename, util.GeoPoint(geo), distance, ) if err != nil { fmt.Fprint(os.Stderr, err) os.Exit(1) } return } err := search.OutputSearchResults( directory, timeOrigin, timeFrame, util.GeoPoint(geo), distance, ) if err != nil { fmt.Fprint(os.Stderr, err) os.Exit(1) } }
func main() { // Basic user configuration variables force := pflag.BoolP("force", "f", false, "Force output to terminal.") count := pflag.StringP("count", "n", "+Inf", "Number of random bytes to generate.") procs := pflag.IntP("procs", "p", runtime.NumCPU(), "Maximum number of concurrent workers.") pflag.Parse() if !(*force) && terminal.IsTerminal(int(os.Stdout.Fd())) { fmt.Fprintf(os.Stderr, "Random data not written to terminal.\n\n") pflag.Usage() os.Exit(1) } cnt, err := strconv.ParsePrefix(*count, strconv.AutoParse) if err != nil || math.IsNaN(cnt) { fmt.Fprintf(os.Stderr, "Number of bytes to generate is invalid.\n\n") pflag.Usage() os.Exit(1) } if (*procs) < 1 { fmt.Fprintf(os.Stderr, "Number of workers must be positive.\n\n") pflag.Usage() os.Exit(1) } runtime.GOMAXPROCS(*procs) rand.SetNumRoutines(*procs) // Copy random data to stdout if int64(cnt) < 0 || math.IsInf(cnt, 0) { _, err = io.Copy(os.Stdout, rand.Reader) } else { _, err = io.CopyN(os.Stdout, rand.Reader, int64(cnt)) } if perr, ok := err.(*os.PathError); ok && perr.Err == syscall.EPIPE { err = nil // Expected error is for the sink to close the pipe } else if err != nil { panic(err) } }
func main() { flag.Usage = func() { fmt.Fprint(os.Stderr, Usage) } flag.IntVarP(&options.Port, "port", "p", 8080, "") flag.StringVar(&options.CustomCSS, "custom-css", "", "") flag.Parse() options.Dir = flag.Arg(0) if options.Dir == "" { flag.Usage() os.Exit(1) } log.Println("Serving wiki from", options.Dir) // Parse base template var err error options.template, err = template.New("base").Parse(Template) if err != nil { log.Fatalln("Error parsing HTML template:", err) } // Trim trailing slash from root path if strings.HasSuffix(options.Dir, "/") { options.Dir = options.Dir[:len(options.Dir)-1] } // Verify that the wiki folder exists _, err = os.Stat(options.Dir) if os.IsNotExist(err) { log.Fatalln("Directory not found") } // Check if the wiki folder is a Git repository options.git = IsGitRepository(options.Dir) if options.git { log.Println("Git repository found in directory") } else { log.Println("No git repository found in directory") } http.Handle("/api/diff/", commonHandler(DiffHandler)) http.Handle("/", commonHandler(WikiHandler)) log.Println("Listening on:", options.Port) http.ListenAndServe(fmt.Sprintf(":%d", options.Port), nil) }
func main() { if len(os.Args) < 2 { flag.Usage() os.Exit(0) } switch os.Args[1] { case "-h", "--help": flag.Usage() os.Exit(0) case "-version": fmt.Fprintf(os.Stderr, versionString()) os.Exit(0) case "id": if err := id_flags.Parse(os.Args[2:]); err == nil { id_main(id_flags) } case "cp": if err := cp_flags.Parse(os.Args[2:]); err == nil { cp_main(cp_flags) } } }
func main() { pflag.Usage = func() { fmt.Fprintf(os.Stderr, USAGE) } var output = pflag.StringP("output", "o", ".", "output directory") pflag.Parse() if pflag.NArg() == 1 { genRoutes(pflag.Arg(0), *output) } else { pflag.Usage() } }
func main() { board, id, err := parseThreadId(flag.Arg(0)) if err != nil { fmt.Printf("Invalid input: %s\n", flag.Arg(0)) flag.Usage() os.Exit(1) } ticker := time.NewTicker(*refresh) for { log.Println("Loading thread") go loadThread(board, id) <-ticker.C } }
// Run the program and return exit code. func run() int { flag.Usage = usageLong // make "-h" work similarly to "help" if err := config(); err != nil { errf("%s\n", err) return 1 } switch cmd := flag.Arg(0); cmd { case "download": return cmdDownload() case "init": return cmdInit() case "up", "start", "boot", "resume": return cmdUp() case "save", "suspend": return cmdSave() case "down", "halt", "stop": return cmdStop() case "poweroff": return cmdPoweroff() case "restart": return cmdRestart() case "reset": return cmdReset() case "delete": return cmdDelete() case "info": return cmdInfo() case "status": return cmdStatus() case "ssh": return cmdSSH() case "version": outf("Client version: %s\nGit commit: %s\n", Version, GitSHA) return 0 case "help": flag.Usage() return 0 case "": usageShort() return 0 default: errf("Unknown command %q\n", cmd) usageShort() return 1 } }
func main() { pflag.Usage = func() { fmt.Fprintln(os.Stderr, "Usage: hipcat [-r room] [message]") } cfg := Config{} err := cfg.Load() if err != nil { log.Fatalf("Failed to load config: %v", err) } cfg.bindFlags() pflag.Parse() if cfg.Room == "" { log.Println("Could not find a Room in HIPCAT_ROOM, /etc/hipcat.conf, /.hipcat.conf, ./hipcat.conf or passed with -r") pflag.Usage() os.Exit(1) } // was there a message on the command line? If so use it. args := pflag.Args() if len(args) > 0 { msg := RoomMessage{ Message: strings.Join(args, " "), } err = msg.Post(&cfg) if err != nil { log.Fatalf("Post failed: %v", err) } return } // ...Otherwise scan stdin scanner := bufio.NewScanner(os.Stdin) for scanner.Scan() { msg := RoomMessage{ Message: scanner.Text(), } err = msg.Post(&cfg) if err != nil { log.Fatalf("Post failed: %v", err) } } if err = scanner.Err(); err != nil { log.Fatalf("Error reading: %v", err) } }
func helpHandle(args []string) { arg := args[0] var cmd *Command for _, c := range commands { if c.Str == arg { cmd = &c break } } if arg == "" || cmd == nil { pflag.Usage() return } cmd.PrintUsage() }
// Initial setup when the program starts. func setup() { // ensure that zpool/zfs commands do not use localized messages: os.Setenv("LC_ALL", "C") // command line flags: pflag.StringVarP(&cfgFile, "conf", "c", CFGFILE, "configuration file path") pflag.BoolVarP(&optDebug, "debug", "d", false, "print debug information to stdout") optHashPassword := pflag.BoolP("passwordhash", "P", false, "hash web password") optTest := pflag.BoolP("test", "t", false, "test configuration and exit") optVersion := pflag.BoolP("version", "v", false, "print version information and exit") pflag.Parse() if pflag.NArg() > 0 { pflag.Usage() os.Exit(2) } if *optVersion { version() os.Exit(0) } if *optHashPassword { wwwHashPassword() os.Exit(0) } // initialize logging & notification: if *optTest { optDebug = true } cfg = getCfg() if cfg == nil { os.Exit(2) } notify = setupLog(cfg) if *optTest { notifyCloseC := notify.Close() select { // wait max 1 second for loggers to finish case <-notifyCloseC: case <-time.After(time.Second): } os.Exit(0) } }
func init() { flag.Usage = func() { fmt.Fprintf(os.Stderr, "Usage: dockdash [options]\n\n") flag.PrintDefaults() } flag.Parse() if *helpFlag { flag.Usage() os.Exit(1) } if *versionFlag { fmt.Println(VERSION) os.Exit(0) } }
func main() { pflag.Usage = func() { fmt.Fprintf(os.Stderr, USAGE) } var output = pflag.StringP("output", "o", ".", "output directory") var version = pflag.BoolP("version", "", false, "version") pflag.Parse() if *version { fmt.Println(VERSION) } else if pflag.NArg() == 1 { genRoutes(pflag.Arg(0), *output) } else { pflag.Usage() } }
func main() { flag.Usage = func() { fmt.Fprintf(os.Stderr, "usage: jp [file]\n") flag.PrintDefaults() } isTerminal := terminal.IsTerminal(int(os.Stdout.Fd())) compact := flag.Bool("compact", false, "compact format") colors := flag.Bool("color", isTerminal, "colored format") flag.Parse() args := flag.Args() if len(args) < 1 { flag.Usage() os.Exit(2) } format := "pretty" if *compact { format = "compact" } if *colors { format += "16" } var fd *os.File var e error if args[0] == "-" { fd = os.Stdin } else { fd, e = os.Open(args[0]) if e != nil { fmt.Fprintln(os.Stderr, "Error:", e) os.Exit(1) } } e = jp.Expand(fd, os.Stdout, format) if e != nil { fmt.Fprintln(os.Stderr, "Error:", e) os.Exit(1) } }
func main() { dir, _ := os.Getwd() port := flag.IntP("port", "p", 8080, "help message for flagname") flag.Parse() if flag.NArg() > 1 { flag.Usage() os.Exit(1) } else if flag.NArg() == 1 { dir = flag.Args()[0] } bindTo := fmt.Sprintf(":%d", *port) fmt.Printf("Serving '%s' on %s...\n", dir, bindTo) panic(http.ListenAndServe(bindTo, http.FileServer(http.Dir(dir)))) }
func main() { flag.Parse() if len(flag.Args()) < 1 { flag.Usage() os.Exit(-1) } config = NewConfig(flag.Args()[0]) r := mux.NewRouter() r.HandleFunc("/lambda", lambdaHandler) r.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("OK")) }) loggedRouter := handlers.LoggingHandler(os.Stdout, r) log.Fatal(http.ListenAndServe(":8080", loggedRouter)) }
func init() { flag.Usage = func() { fmt.Fprintln(os.Stderr, "Usage: chanloader [options] /b/res/123456\nOptions:") flag.PrintDefaults() } flag.Parse() if *refresh < time.Second*30 { *refresh = time.Second * 30 } if *showVersion { fmt.Println(version) os.Exit(0) } if flag.NArg() < 1 { flag.Usage() os.Exit(1) } runtime.GOMAXPROCS(runtime.NumCPU()) }
func parseFlags(args []string) (cmd Command, arguments []string) { var options []string var err error cmd, options, arguments, err = findCommand(args) if err != nil { pflag.Usage() os.Exit(1) } optionsSet().Parse(options) if len(arguments) == 0 { arguments = append(arguments, "") } switch arguments[0] { case "--help", "-help", "help", "-h": cmd.PrintUsage() os.Exit(1) } return }
func main() { if flagVersion { printVersion() os.Exit(0) } // get the config data var configPath string if flagConfigPath != "" { configPath = flagConfigPath } else { configPath = computeDefaultConfigPath() } if verbose { fmt.Println("Attempting to load config file from path: ", configPath) } props, err := properties.LoadFile(configPath, properties.UTF8) var didLoadConfig = err == nil if didLoadConfig { if verbose { fmt.Printf("Successfully loaded config file with the following properties:\n%v\n", props) } username = props.GetString("rpcuser", "") password = props.GetString("rpcpassword", "") serverSSL = props.GetBool("rpcssl", defaultSSL) serverPort = props.GetInt("rpcport", defaultPort) serverAddress = defaultAddress } else { if verbose { fmt.Printf("Problem loading config: %v\n", err) } serverSSL = defaultSSL serverPort = defaultPort serverAddress = defaultAddress } // Command line argument over-rides the config file. // We only want values which have been set if flagSetMap["rpcuser"] == true { username = flagUsername } if flagSetMap["rpcpassword"] == true { password = flagPassword } if flagSetMap["ssl"] == true { serverSSL = flagSSL } if flagSetMap["port"] == true { serverPort = flagPort } if flagSetMap["host"] == true { serverAddress = flagAddress } if verbose { fmt.Println("Using the following parameters where command line > config > defaults") fmt.Printf("rpcuser: %s\n", username) fmt.Printf("rpcpassword: %s\n", password) fmt.Println("ssl:", serverSSL) fmt.Println("port:", serverPort) fmt.Println("host:", serverAddress) } // After options and flags, everything else is json method and parameters args := flag.Args() // fmt.Printf("JSON COMMAND: %+v\n", jsoncall) // for index, element := range jsoncall { // fmt.Printf("JSON COMMAND %d : %v\n", index, element) // } numArgs = len(args) numParams = numArgs - 1 if numArgs == 0 { flag.Usage() os.Exit(1) } method := args[0] params := args[1:] var buffer []byte protocol := "http" if serverSSL { protocol = "https" } connectionString := fmt.Sprintf("%s://%s:%s@%s:%d/api", protocol, username, password, serverAddress, serverPort) if verbose { fmt.Println("URL connection string to server is: ", connectionString) } // Set a global option on our patched version of barrister.go // to allow connecting to self-signed certs // If connecting to localhost, we don't require CA signed cert. // If the insecure flag was explicitly set, use that value, otherwise our defaults if flagSetMap["insecure"] == false { serverIP := net.ParseIP(serverAddress) if serverIP != nil || serverAddress == "127.0.0.1" || strings.ToLower(serverAddress) == "localhost" { flagInsecure = true } } barrister.Global_insecure_ssl = flagInsecure if verbose { fmt.Println("insecure ssl flag = ", flagInsecure) fmt.Print("\n") } sparkbit := NewSparkbitProxy(connectionString) var res interface{} /* command := strings.ToUpper(method[:1]) + strings.ToLower(method[1:]) fmt.Println("command = ", command) // Oct 2014, still cannot get arguments of method via introspection // https://groups.google.com/forum/#!topic/golang-nuts/nM_ZhL7fuGc // var foo Sparkbit{} fooType := reflect.TypeOf(sparkbit) var v reflect.Value v = fooType.MethodByName(command) if theMethod != nil { fmt.Println("FOUND THE METHOD") } for i := 0; i < fooType.NumMethod(); i++ { meth := fooType.Method(i) fmt.Println(meth.Name) } */ switch method { case "addasset": validateParams(2, method, "WALLETNAME ASSETREF") res, err = sparkbit.Addasset(params[0], params[1]) case "createaddresses": validateParams(2, method, "WALLETNAME QUANTITY") i64, perr := strconv.ParseInt(params[1], 10, 64) if perr != nil { fmt.Println("Quantity parameter must be a number") log.Fatal(perr) } res, err = sparkbit.Createaddresses(params[0], i64) case "createwallet": validateParams(1, method, "WALLETNAME") res, err = sparkbit.Createwallet(params[0]) case "deletewallet": validateParams(1, method, "WALLETNAME") res, err = sparkbit.Deletewallet(params[0]) case "getstatus": validateParams(0, method, "") res, err = sparkbit.Getstatus() case "listaddresses": validateParams(1, method, "WALLETNAME") res, err = sparkbit.Listaddresses(params[0]) case "listbalances": validateParams(2, method, "WALLETNAME ONLYVISIBLE") flag, perr := strconv.ParseBool(params[1]) if perr != nil { fmt.Println("Visible must be true or false") os.Exit(1) } res, err = sparkbit.Listbalances(params[0], flag) case "listtransactions": validateParams(2, method, "WALLETNAME NUMOFTRANSACTIONS") i64, perr := strconv.ParseInt(params[1], 10, 64) if perr != nil { fmt.Println("Number of transactions must be a valid number") os.Exit(1) } res, err = sparkbit.Listtransactions(params[0], i64) case "listunspent": validateParams(4, method, "WALLETNAME MINCONF MAXCONF ADDRESSES\n* Set MINCONF or MAXCONF to 0 if you want to include unconfirmed transactions.\n* Set ADDRESSES to \"\" or - if you want all UTXOs") minconf, perr := strconv.ParseInt(params[1], 10, 64) maxconf, perr2 := strconv.ParseInt(params[2], 10, 64) if perr != nil { fmt.Println("Minimum number of confirmations must be a valid number") } if perr2 != nil { fmt.Println("Maximum number of confirmations must be a valid number") } if perr != nil || perr2 != nil { os.Exit(1) } z := strings.TrimSpace(params[3]) var addresses []string if z == "-" { addresses = []string{} } else { addresses = strings.Split(z, ",") } res, err = sparkbit.Listunspent(params[0], minconf, maxconf, addresses) case "listwallets": validateParams(0, method, "") res, err = sparkbit.Listwallets() case "deleteasset": validateParams(2, method, "WALLETNAME ASSETREF") res, err = sparkbit.Deleteasset(params[0], params[1]) case "refreshasset": validateParams(2, method, "WALLETNAME ASSETREF") res, err = sparkbit.Refreshasset(params[0], params[1]) case "sendasset": validateParams(5, method, "WALLETNAME ADDRESS ASSETREF QUANTITY SENDERPAYS") f64, perr := strconv.ParseFloat(params[3], 64) if perr != nil { fmt.Println("Quantity must be a valid number") os.Exit(1) } flag, perr := strconv.ParseBool(params[4]) if perr != nil { fmt.Println("Sender pays flag must be true or false") os.Exit(1) } res, err = sparkbit.Sendasset(params[0], params[1], params[2], f64, flag) case "sendbitcoin": validateParams(3, method, "WALLETNAME ADDRESS AMOUNT") f64, perr := strconv.ParseFloat(params[2], 64) if perr != nil { fmt.Println("Amount is not a valid number") os.Exit(1) } res, err = sparkbit.Sendbitcoin(params[0], params[1], f64) case "sendbitcoinmessage": validateParams(4, method, "WALLETNAME ADDRESS AMOUNT MESSAGE") f64, perr := strconv.ParseFloat(params[2], 64) if perr != nil { fmt.Println("Amount is not a valid number") os.Exit(1) } res, err = sparkbit.Sendbitcoinmessage(params[0], params[1], f64, params[3]) case "sendassetmessage": validateParams(6, method, "WALLETNAME ADDRESS ASSETREF QUANTITY SENDERPAYS MESSAGE") f64, perr := strconv.ParseFloat(params[3], 64) if perr != nil { fmt.Println("Quantity must be a valid number") os.Exit(1) } flag, perr := strconv.ParseBool(params[4]) if perr != nil { fmt.Println("Sender pays flag must be true or false") os.Exit(1) } res, err = sparkbit.Sendassetmessage(params[0], params[1], params[2], f64, flag, params[5]) case "sendbitcoinasset": validateParams(6, method, "WALLETNAME ADDRESS BTCAMOUNT ASSETREF ASSETQTY SENDERPAYS") f64, perr := strconv.ParseFloat(params[2], 64) if perr != nil { fmt.Println("Amount is not a valid number") os.Exit(1) } f64_2, perr := strconv.ParseFloat(params[4], 64) if perr != nil { fmt.Println("Quantity must be a valid number") os.Exit(1) } flag, perr := strconv.ParseBool(params[5]) if perr != nil { fmt.Println("Sender pays flag must be true or false") os.Exit(1) } res, err = sparkbit.Sendbitcoinasset(params[0], params[1], f64, params[3], f64_2, flag) case "sendbitcoinassetmessage": validateParams(7, method, "WALLETNAME ADDRESS BTCAMOUNT ASSETREF ASSETQTY SENDERPAYS MESSAGE") f64, perr := strconv.ParseFloat(params[2], 64) if perr != nil { fmt.Println("Amount is not a valid number") os.Exit(1) } f64_2, perr := strconv.ParseFloat(params[4], 64) if perr != nil { fmt.Println("Quantity must be a valid number") os.Exit(1) } flag, perr := strconv.ParseBool(params[5]) if perr != nil { fmt.Println("Sender pays flag must be true or false") os.Exit(1) } res, err = sparkbit.Sendbitcoinassetmessage(params[0], params[1], f64, params[3], f64_2, flag, params[6]) case "sendassetusing": validateParams(7, method, "WALLETNAME TXID VOUT ADDRESS ASSETREF QUANTITY SENDERPAYS") vout, perr := strconv.ParseInt(params[2], 10, 64) if perr != nil { fmt.Println("Vout must be a valid number") os.Exit(1) } f64, perr := strconv.ParseFloat(params[5], 64) if perr != nil { fmt.Println("Quantity must be a valid number") os.Exit(1) } flag, perr := strconv.ParseBool(params[6]) if perr != nil { fmt.Println("Sender pays flag must be true or false") os.Exit(1) } res, err = sparkbit.Sendassetusing(params[0], params[1], vout, params[3], params[4], f64, flag) case "sendbitcoinusing": validateParams(5, method, "WALLETNAME TXID VOUT ADDRESS AMOUNT") vout, perr := strconv.ParseInt(params[2], 10, 64) if perr != nil { fmt.Println("Vout must be a valid number") os.Exit(1) } f64, perr := strconv.ParseFloat(params[4], 64) if perr != nil { fmt.Println("Amount is not a valid number") os.Exit(1) } res, err = sparkbit.Sendbitcoinusing(params[0], params[1], vout, params[3], f64) case "setaddresslabel": validateParams(3, method, "WALLETNAME ADDRESS LABEL") res, err = sparkbit.Setaddresslabel(params[0], params[1], params[2]) case "setassetvisible": validateParams(3, method, "WALLETNAME ASSETREF ISVISIBLE") flag, perr := strconv.ParseBool(params[2]) if perr != nil { fmt.Println("Visibility flag must be true or false") os.Exit(1) } res, err = sparkbit.Setassetvisible(params[0], params[1], flag) case "stop": validateParams(0, method, "") res, err = sparkbit.Stop() default: fmt.Println("ERROR: Unknown command: " + method) os.Exit(1) } if err != nil { fmt.Printf("ERROR: %v\n", err) os.Exit(1) } buffer, err = json.MarshalIndent(res, "", " ") if err != nil { fmt.Printf("ERROR: %v\n", err) os.Exit(1) } bufferString := string(buffer) if strings.HasPrefix(method, "send") { bufferString = strings.Trim(bufferString, "\"") } //os.Stdout.Write(buffer) os.Stdout.WriteString(bufferString) os.Stdout.WriteString("\n") }
func main() { var err error readConfig(true) err = validateConfig() if err != nil { fmt.Printf("\n%s\n\n", err) flag.Usage() os.Exit(1) } if Config.ShowVersion { fmt.Printf("statsdaemon v%s (built w/%s)\n", VERSION, runtime.Version()) os.Exit(0) } if Config.PrintConfig { out, _ := yaml.Marshal(Config) fmt.Printf("# Default config file in YAML based on config options\n%s", string(out)) os.Exit(0) } log.SetLevel(Config.InternalLogLevel) if Config.LogName == "stdout" { log.SetOutput(os.Stdout) } else { if len(Config.LogName) > 0 { logFile, err := os.OpenFile(Config.LogName, os.O_WRONLY|os.O_CREATE, 0640) if err != nil { fmt.Printf("Error opennig log file: %s\n", err) os.Exit(1) } log.SetFormatter(&log.TextFormatter{DisableColors: true}) log.SetOutput(logFile) defer logFile.Close() } } if Config.LogToSyslog { // set syslog syslogNetwork := "" if len(Config.SyslogUDPAddress) > 0 { syslogNetwork = "udp" } hook, err := logrus_syslog.NewSyslogHook(syslogNetwork, Config.SyslogUDPAddress, syslog.LOG_DEBUG|syslog.LOG_LOCAL3, "statsdaemon") if err != nil { fmt.Printf("Unable to connect to syslog daemon: %s\n", err) } else { log.AddHook(hook) log.SetFormatter(&log.JSONFormatter{}) } } if Config.LogName == "" { log.SetOutput(ioutil.Discard) } // if Config.LogLevel == "debug" { // go func() { // log.Println(http.ListenAndServe(":8082", nil)) // }() // } // Stat Stat.Interval = Config.FlushInterval signalchan = make(chan os.Signal, 1) signal.Notify(signalchan, syscall.SIGTERM, syscall.SIGQUIT) dbHandle, err = bolt.Open(Config.StoreDb, 0644, &bolt.Options{Timeout: 1 * time.Second}) if err != nil { log.WithFields(log.Fields{ "in": "main", "after": "Open", "ctx": "Bolt DB open", }).Fatalf("%s", err) } // dbHandle.NoSync = true defer dbHandle.Close() go udpListener() if Config.TCPServiceAddress != "" { go tcpListener() } monitor() }
func runHelp() int { pflag.Usage() return 0 }
func main() { flag.Parse() Args.data = []string(dataFlag) if Args.version { fmt.Printf("Nrcq version is %s\n", Version) os.Exit(0) } if Args.json { Args.encode = true } else { Args.encode = false } // Xfer the encode setting to the library nrc.SetEncode(Args.encode) // Args left after flag finishes url := flag.Arg(0) // Base URL, eg. "http://1.2.3.4/rest" ep := flag.Arg(1) // end point, eg. "show/hosts" if Args.list != "" { n := createObject(Args.list) if Args.json == true { fmt.Printf("%s\n", []byte(n.OptionsJson())) } else { DisplayArray(n.Options(), n.RequiredOptions()) } os.Exit(0) } if Args.listendpoints { n := endpointarr() if Args.json == true { fmt.Printf("%s\n", n) } else { DisplayArray(n, []string{}) } os.Exit(0) } if url == "" || ep == "" { fmt.Fprintf(os.Stderr, "ERROR: 2 non-option arguments expected.\n") flag.Usage() } if strings.HasPrefix(ep, "check/") { // GET REQUESTS n := createObject("check") err := n.Get(url, ep, Args.folder, Args.data) if err != nil { fmt.Printf("ERROR: %s\n", err.Error()) os.Exit(1) } if Args.json == true { n.ShowJson(Args.newline, false, "") } else { n.Show(false, "") } } else if strings.HasPrefix(ep, "show/") { // GET REQUESTS cmd := strings.Split(ep, "/") n := createObject(cmd[1]) err := n.Get(url, ep, Args.folder, Args.data) if err != nil { fmt.Printf("ERROR: %s\n", err.Error()) os.Exit(1) } if Args.json == true { n.ShowJson(Args.newline, Args.brief, Args.filter) } else { n.Show(Args.brief, Args.filter) } } else if strings.HasPrefix(ep, "add/") || strings.HasPrefix(ep, "modify/") || strings.HasPrefix(ep, "delete/") || strings.HasPrefix(ep, "restart/") || ep == "apply/nagioslastgoodconfig" { // POST REQUESTS cmd := strings.Split(ep, "/") n := createObject(cmd[1]) err := n.Post(url, ep, Args.folder, Args.data) if err != nil { fmt.Printf("ERROR: %s\n", err.Error()) os.Exit(1) } fmt.Printf("SUCCESS\n") } else if ep == "apply/nagiosconfig" { // This is the only Post request that produces output n := createObject("applynagiosconfig") err := n.Post(url, ep, Args.folder, Args.data) if err != nil { fmt.Printf("ERROR: %s\n", err.Error()) os.Exit(1) } if Args.json == true { n.ShowJson(Args.newline, Args.brief, Args.filter) } else { n.Show(Args.brief, Args.filter) } } }