コード例 #1
0
ファイル: main.go プロジェクト: joshie/lochness
func main() {
	interval := flag.IntP("interval", "i", 60, "update interval in seconds")
	ttl := flag.IntP("ttl", "t", 0, "heartbeat ttl in seconds")
	eaddr := flag.StringP("etcd", "e", "http://localhost:4001", "address of etcd machine")
	id := flag.StringP("id", "d", "", "hypervisor id")
	logLevel := flag.StringP("log-level", "l", "info", "log level")
	flag.Parse()

	if err := logx.DefaultSetup(*logLevel); err != nil {
		log.WithFields(log.Fields{
			"error": err,
			"func":  "logx.DefaultSetup",
			"level": logLevel,
		}).Fatal("failed to set up logging")
	}

	if *ttl == 0 {
		*ttl = 2 * (*interval)
	}

	e := etcd.NewClient([]string{*eaddr})
	c := lochness.NewContext(e)

	hn, err := lochness.SetHypervisorID(*id)
	if err != nil {
		log.WithFields(log.Fields{
			"error": err,
			"func":  "lochness.SetHypervisorID",
			"id":    id,
		}).Fatal("failed to set hypervisor id")
	}

	hv, err := c.Hypervisor(hn)
	if err != nil {
		log.WithFields(log.Fields{
			"error": err,
			"func":  "context.Hypervisor",
			"id":    hn,
		}).Fatal("failed to instantiate hypervisor")
	}

	for {
		if err = hv.UpdateResources(); err != nil {
			log.WithFields(log.Fields{
				"error": err,
				"func":  "hv.UpdateResources",
			}).Fatal("failed to update hypervisor resources")
		}
		if err = hv.Heartbeat(time.Duration(*ttl)); err != nil {
			log.WithFields(log.Fields{
				"error": err,
				"func":  "hv.Heartbeat",
				"ttl":   *ttl,
			}).Fatal("failed to beat heart")
		}
		time.Sleep(time.Duration(*interval) * time.Second)
	}
}
コード例 #2
0
ファイル: slackcat.go プロジェクト: pborreli/slackcat
func main() {

	cfg, err := ReadConfig()
	if err != nil {
		log.Fatalf("Coult not read config: %v", err)
	}

	pflag.Usage = func() {
		fmt.Fprintln(os.Stderr, "Usage: slackcat [-c #channel] [-n name] [message]")
	}

	channel := pflag.StringP("channel", "c", cfg.Channel, "channel")
	name := pflag.StringP("name", "n", username(), "name")
	pflag.Parse()

	// was there a message on the command line? If so use it.
	args := pflag.Args()
	if len(args) > 0 {
		msg := SlackMsg{
			Channel:  *channel,
			Username: *name,
			Parse:    "full",
			Text:     strings.Join(args, " "),
		}

		err = msg.Post(cfg.WebhookUrl)
		if err != nil {
			log.Fatalf("Post failed: %v", err)
		}
		os.Exit(0)
	}

	// ...Otherwise scan stdin
	scanner := bufio.NewScanner(os.Stdin)
	for scanner.Scan() {
		msg := SlackMsg{
			Channel:  *channel,
			Username: *name,
			Parse:    "full",
			Text:     scanner.Text(),
		}

		err = msg.Post(cfg.WebhookUrl)
		if err != nil {
			log.Fatalf("Post failed: %v", err)
		}
	}
	if err := scanner.Err(); err != nil {
		log.Fatalf("Error reading: %v", err)
	}
}
コード例 #3
0
ファイル: main.go プロジェクト: pyting/jsonpath-1
func main() {
	var pathStrings pathSlice
	filePtr := flag.StringP("file", "f", "", "Path to json file")
	jsonPtr := flag.StringP("json", "j", "", "JSON text")
	flag.VarP(&pathStrings, "path", "p", "One or more paths to target in JSON")
	showKeysPtr := flag.BoolP("keys", "k", false, "Print keys & indexes that lead to value")
	flag.Usage = func() {
		fmt.Fprintf(os.Stderr, "Usage of %s:\n", os.Args[0])
		flag.PrintDefaults()
		fmt.Fprintln(os.Stderr, "Pipe JSON to StdIn by not specifying --file or --json ")
	}
	flag.Parse()

	if len(pathStrings) == 0 {
		fmt.Println("Must specify one or more paths with the --path flag")
		os.Exit(1)
	}

	paths, err := jsonpath.ParsePaths(pathStrings...)
	if err != nil {
		fmt.Println(fmt.Errorf("Failed to parse paths: %q", err.Error()))
		os.Exit(1)
	}

	if filePtr != nil && *filePtr != "" {
		f, err := os.Open(*filePtr)
		if err != nil {
			fmt.Println(fmt.Errorf("Failed to open file: %q", err.Error()))
			os.Exit(1)
		}

		eval, err := jsonpath.EvalPathsInReader(f, paths)
		checkAndHandleError(err)
		run(eval, *showKeysPtr)
		checkAndHandleError(eval.Error)
		f.Close()

	} else if jsonPtr != nil && *jsonPtr != "" {
		eval, err := jsonpath.EvalPathsInBytes([]byte(*jsonPtr), paths)
		checkAndHandleError(err)
		run(eval, *showKeysPtr)
		checkAndHandleError(eval.Error)
	} else {
		reader := bufio.NewReader(os.Stdin)
		eval, err := jsonpath.EvalPathsInReader(reader, paths)
		checkAndHandleError(err)
		run(eval, *showKeysPtr)
		checkAndHandleError(eval.Error)
	}
}
コード例 #4
0
ファイル: pgrun.go プロジェクト: joncrlsn/pgrun
// Executes a file of SQL statements one statement at a time, stopping everything
// if one of them has an error
func main() {

	// -f (filename) is a required program argument
	var fileName = flag.StringP("file", "f", "", "path of the SQL file to run")
	dbInfo := pgutil.DbInfo{}
	verFlag, helpFlag := dbInfo.Populate()

	if verFlag {
		fmt.Fprintf(os.Stderr, "%s version %s\n", os.Args[0], version)
		fmt.Fprintln(os.Stderr, "Copyright (c) 2016 Jon Carlson.  All rights reserved.")
		fmt.Fprintln(os.Stderr, "Use of this source code is governed by the MIT license")
		fmt.Fprintln(os.Stderr, "that can be found here: http://opensource.org/licenses/MIT")
		os.Exit(1)
	}

	if helpFlag {
		usage()
	}

	if len(*fileName) == 0 {
		fmt.Fprintln(os.Stderr, "Missing required filename argument (-f)")
		usage()
	}

	exists, _ := fileutil.Exists(*fileName)
	if !exists {
		fmt.Fprintf(os.Stderr, "File does not exist: %s\n", *fileName)
		os.Exit(2)
	}

	runFile(*fileName, &dbInfo)
}
コード例 #5
0
ファイル: main.go プロジェクト: joock/influx-alert
func main() {
	var file *string = flag.StringP("config", "c", "", "Config file to use")
	flag.Parse()

	setupInflux()

	alerts := []Alert{}

	data, _ := ioutil.ReadFile(*file)
	err := yaml.Unmarshal(data, &alerts)
	if err != nil {
		panic(err)
	}

	if os.Getenv("DEBUG") == "true" {
		fmt.Printf("%+v\n", alerts)
	}

	setupSlack()
	setupHipchat()
	done := make(chan bool)
	for _, alert := range alerts {
		go func(alert Alert) {
			for {
				alert.Run()
				time.Sleep(time.Duration(alert.Interval) * time.Second)
			}
		}(alert)
	}
	<-done // wait
}
コード例 #6
0
ファイル: main.go プロジェクト: jonasi/project
func main() {
	var (
		// general options
		stateDir = pflag.String("statedir", "", "the server state directory")
		help     = pflag.BoolP("help", "h", false, "show this help")

		// server options
		server = pflag.BoolP("server", "s", false, "run the server in the foreground")
		port   = pflag.IntP("port", "p", 40000, "server port to listen on")

		// client options
		method  = pflag.StringP("method", "X", "GET", "client method")
		plugin  = pflag.String("plugin", "", "client plugin")
		data    = pflag.StringP("data", "d", "", "client body")
		headers = &repString{[]string{}}
		verbose = pflag.BoolP("verbose", "v", false, "show full http response")
	)

	pflag.VarP(headers, "header", "H", "client request header")

	pflag.Parse()

	if *help {
		os.Exit(runHelp())
	}

	if *server {
		os.Exit(runServer(*port, *stateDir))
	}

	if pflag.NArg() < 1 {
		fmt.Fprintln(os.Stderr, "must pass in path to make api call")
		runHelp()
		os.Exit(1)
	}

	os.Exit(runClient(*stateDir, *plugin, *method, pflag.Arg(0), *data, headers.strs, *verbose))
}
コード例 #7
0
ファイル: main.go プロジェクト: qyfbq123/freedom-routes
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()
	}
}
コード例 #8
0
ファイル: main.go プロジェクト: rainly/freedom-routes
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()
	}
}
コード例 #9
0
func main() {
	configFile := flag.StringP("config", "c", "accounting.yml", "configuration file")
	flag.Parse()

	app := types.Application{}
	ReadConfig(*configFile, &app)

	var store types.Storage
	if app.StorageType == "xml" {
		store = storage.XMLStorage{app.XMLFilepath}
	}

	printHeader(&app)
	err := cli.MainLoop(&app, &store)
	if err != nil {
		panic(err.Error())
	}
}
コード例 #10
0
ファイル: nl.go プロジェクト: patrickToca/go-coreutils
func main() {
	bFlag := flag.StringP("body-numbering", "b", "t", "style")
	flag.Parse()
	if len(flag.Args()) == 0 {
		bytes, _ := ioutil.ReadAll(os.Stdin)
		lines := strings.Split(string(bytes), "\n")
		linecount := 0
		for i := 0; i < len(lines)-1; i++ {
			if *bFlag == "t" {
				if len(strings.TrimSpace(lines[i])) > 0 {
					linecount++
					fmt.Printf("%6d  %s\n", linecount, lines[i])
				} else {
					fmt.Println(lines[i])
				}
			} else {
				linecount++
				fmt.Printf("%6d  %s\n", linecount, lines[i])
			}
		}
	} else if len(flag.Args()) > 0 {
		linecount := 0
		for j := 0; j < len(flag.Args()); j++ {
			bytes, _ := ioutil.ReadFile(flag.Arg(j))
			lines := strings.Split(string(bytes), "\n")
			for i := 0; i < len(lines)-1; i++ {
				if *bFlag == "t" {
					if len(strings.TrimSpace(lines[i])) > 0 {
						linecount++
						fmt.Printf("%6d  %s\n", linecount, lines[i])
					} else {
						fmt.Println(lines[i])
					}
				} else {
					linecount++
					fmt.Printf("%6d  %s\n", linecount, lines[i])
				}
			}
		}
	}
}
コード例 #11
0
ファイル: main.go プロジェクト: dsnet/crypto
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)
	}
}
コード例 #12
0
	gutenberg "gutenberg.org"
	"gutenberg.org/config"
	"gutenberg.org/plugins"
	"io/ioutil"
	"log"
	"os"
	"path/filepath"
	"strings"
	"text/template"
	"time"
)

var (
	cfgfile   = flag.String("config", "", "config file (default is path/config.json)")
	help      = flag.BoolP("help", "h", false, "show this help")
	source    = flag.StringP("source", "s", "", "filesystem path to read files relative from")
	watchMode = flag.BoolP("watch", "w", false, "watch filesystem for changes and recreate as needed")
	server    = flag.BoolP("server", "S", false, "run a (very) simple web server")
	port      = flag.String("port", "1313", "port to run web server on, default :1313")
	interval  = flag.Int64P("interval", "i", 1000, "pooling interval for watching")
	rebuild   = flag.BoolP("rebuild", "r", false, "rebuild entire book on restart")
)

type Process struct {
	// Process is done
	Done chan bool
	// Source directory for the book
	Source string
	// Started
	Started bool
コード例 #13
0
ファイル: slackcat.go プロジェクト: montanaflynn/slackcat
func main() {

	cfg, err := ReadConfig()
	if err != nil {
		log.Fatalf("Could not read config: %v", err)
	}

	// By default use "user@server", unless overridden by config. cfg.Username
	// can be "", implying Slack should use the default username, so we have
	// to check if the value was set, not just for a non-empty string.
	defaultName := username()
	if cfg.Username != nil {
		defaultName = *cfg.Username
	}

	pflag.Usage = func() {
		fmt.Fprintln(os.Stderr, "Usage: slackcat [-c #channel] [-n name] [-i icon] [message]")
	}

	channel := pflag.StringP("channel", "c", cfg.Channel, "channel")
	name := pflag.StringP("name", "n", defaultName, "name")
	icon := pflag.StringP("icon", "i", "", "icon")
	pflag.Parse()

	// was there a message on the command line? If so use it.
	args := pflag.Args()
	if len(args) > 0 {
		msg := SlackMsg{
			Channel:   *channel,
			Username:  *name,
			Parse:     "full",
			Text:      strings.Join(args, " "),
			IconEmoji: *icon,
		}

		err = msg.Post(cfg.WebhookUrl)
		if err != nil {
			log.Fatalf("Post failed: %v", err)
		}
		return
	}

	// ...Otherwise scan stdin
	scanner := bufio.NewScanner(os.Stdin)
	for scanner.Scan() {
		msg := SlackMsg{
			Channel:   *channel,
			Username:  *name,
			Parse:     "full",
			Text:      scanner.Text(),
			IconEmoji: *icon,
		}

		err = msg.Post(cfg.WebhookUrl)
		if err != nil {
			log.Fatalf("Post failed: %v", err)
		}
	}
	if err := scanner.Err(); err != nil {
		log.Fatalf("Error reading: %v", err)
	}
}
コード例 #14
0
ファイル: cp.go プロジェクト: patrickToca/go-coreutils
	noDereference     = flag.BoolP("no-dereference", "P", false, "")
	noPreserve        = flag.String("no-preserve", "", "")
	noTargetDir       = flag.BoolP("no-target-directory", "T", false, "")
	oneFS             = flag.BoolP("one-file-system", "x", false, "")
	parents           = flag.Bool("parents", false, "")
	path              = flag.Bool("path", false, "")
	pmot              = flag.Bool("p", false, "")
	preserve          = flag.String("preserve", "", "")
	recursive         = flag.BoolP("recursive", "R", false, "")
	recursive2        = flag.Bool("r", false, "")
	removeDestination = flag.Bool("remove-destination", false, "")
	sparse            = flag.String("sparse", "界", "")
	reflink           = flag.String("reflink", "世", "")
	selinux           = flag.Bool("Z", false, "")
	stripTrailSlash   = flag.Bool("strip-trailing-slashes", false, "")
	suffix            = flag.StringP("suffix", "S", "", "")
	symLink           = flag.BoolP("symbolic-link", "s", false, "")
	targetDir         = flag.StringP("target-directory", "t", "", "")
	update            = flag.BoolP("update", "u", false, "")
	verbose           = flag.BoolP("verbose", "v", false, "")
	version           = flag.Bool("version", false, "")
)

var (
	makeBackups      bool
	copyConts        bool
	parentsOpt       bool
	removeTrailSlash bool
	noTargDir        bool
	targDir          string
	versControl      string
コード例 #15
0
func main() {

	var name *string = flag.StringP("name", "n", "", "Only run the instruction with this name")
	var project *string = flag.StringP("project", "p", "", "Only run the instruction that are apart of this project")
	var force_deploy *bool = flag.BoolP("force", "f", false, "Force a redeploy of everything in the conductor.yml file")
	flag.Parse()

	cd := []ConductorDirections{}

	data, _ := ioutil.ReadFile("conductor.yml")
	err := yaml.Unmarshal(data, &cd)
	if err != nil {
		panic(err)
	}

	for _, instr := range cd {
		if *name != "" {
			if instr.Name != *name {
				continue
			}
		}
		if *project != "" {
			if instr.Project != *project {
				continue
			}
		}
		// fmt.Printf("--- m:\n%v\n\n", instr)
		for _, host := range instr.Hosts {

			docker_ctrl := conductor.New(host)
			container := docker_ctrl.FindContainer(instr.Container.Name)
			host_log := log.New("\t\t\t\t[host]", host, "[container]", instr.Container.Name)

			if instr.Healthcheck != "" {
				health := healthcheck.New(host_log, instr.Healthcheck, host)
				health.Check()
			}

			host_log.Info("[ ] pulling image")
			pulled_image, err := docker_ctrl.PullImage(instr.Container.Image + ":latest")
			if err != nil {
				host_log.Error("Error pulling image: " + err.Error())
			}
			host_log.Info("[x] finished pulling image")

			if container.Container != nil {
				if pulled_image == container.Container.Image && *force_deploy == false {
					host_log.Info("skipping, container running latest image : " + pulled_image)
					continue
				}

				if container.ID() != "" {
					if err := docker_ctrl.RemoveContainer(container.ID()); err != nil {
						host_log.Error(err.Error())
					}
				}
			}

			host_log.Info("[ ] creating container")
			docker_ctrl.CreateAndStartContainer(conductor.ConductorContainerConfig{
				Name:        instr.Container.Name,
				Image:       instr.Container.Image,
				PortMap:     instr.Container.Ports,
				Environment: instr.Container.Environment,
				Volumes:     instr.Container.Volumes,
				Dns:         instr.Container.Dns,
			})
			host_log.Info("[x] finished creating container")
		}

	}

}
コード例 #16
0
ファイル: fsping.go プロジェクト: imarko/fsping
import (
	"fmt"
	flag "github.com/ogier/pflag"
	"os"
	"strings"
	"syscall"
	"time"
)

var verbose = flag.BoolP("verbose", "v", false, "verbose")
var timeout = flag.DurationP("timeout", "T", 5*time.Second, "timeout (ex: 100ms or 3s)")
var printpath = flag.BoolP("path", "p", true, "show path")
var printdev = flag.BoolP("dev", "d", false, "show device")
var quiet = flag.BoolP("quiet", "q", false, "quiet mode, only set exit status")
var checktype = flag.StringP("type", "t", "nfs", "filesystem type to check")
var checkall = flag.BoolP("all", "a", false, "check all filesystems types")

type fs_t struct {
	path     string
	dev      string
	resptime time.Duration
	done     bool
	err      error
}

type fsmap_t map[string]fs_t

func (fs fs_t) String() (s string) {
	switch {
	case fs.err != nil:
コード例 #17
0
ファイル: xxd.go プロジェクト: HarryBird/go-coreutils
)

// cli flags
var (
	autoskip   = flag.BoolP("autoskip", "a", false, "toggle autoskip (* replaces nul lines")
	bars       = flag.BoolP("bars", "B", false, "print |ascii| instead of ascii")
	binary     = flag.BoolP("binary", "b", false, "binary dump, incompatible with -ps, -i, -r")
	columns    = flag.IntP("cols", "c", -1, "format <cols> octets per line")
	ebcdic     = flag.BoolP("ebcdic", "E", false, "use EBCDIC instead of ASCII")
	group      = flag.IntP("group", "g", -1, "num of octets per group")
	cfmt       = flag.BoolP("include", "i", false, "output in C include format")
	length     = flag.Int64P("len", "l", -1, "stop after len octets")
	postscript = flag.BoolP("ps", "p", false, "output in postscript plain hd style")
	reverse    = flag.BoolP("reverse", "r", false, "convert hex to binary")
	offset     = flag.Int("off", 0, "revert with offset")
	seek       = flag.StringP("seek", "s", "", "start at seek bytes abs")
	upper      = flag.BoolP("uppercase", "u", false, "use uppercase hex letters")
	version    = flag.BoolP("version", "v", false, "print version")
)

// constants used in xxd()
const (
	ebcdicOffset = 0x40
)

// dumpType enum
const (
	dumpHex = iota
	dumpBinary
	dumpCformat
	dumpPostscript
コード例 #18
0
ファイル: main.go プロジェクト: joshie/lochness
func main() {
	port := flag.UintP("port", "p", 8888, "address to listen")
	eaddr := flag.StringP("etcd", "e", "http://127.0.0.1:4001", "address of etcd machine")
	baseURL := flag.StringP("base", "b", "http://ipxe.mistify.local:8888", "base address of bits request")
	defaultVersion := flag.StringP("version", "v", "0.1.0", "If all else fails, what version to serve")
	imageDir := flag.StringP("images", "i", "/var/lib/images", "directory containing the images")
	addOpts := flag.StringP("options", "o", "", "additional options to add to boot kernel")
	statsd := flag.StringP("statsd", "s", "", "statsd address")

	flag.Parse()

	e := etcd.NewClient([]string{*eaddr})
	c := lochness.NewContext(e)

	router := mux.NewRouter()
	router.StrictSlash(true)

	s := &server{
		ctx:            c,
		t:              template.Must(template.New("ipxe").Parse(ipxeTemplate)),
		c:              template.Must(template.New("config").Parse(configTemplate)),
		r:              regexp.MustCompile(envRegex),
		defaultVersion: *defaultVersion,
		baseURL:        *baseURL,
		addOpts:        *addOpts,
		etcdAddr:       *eaddr,
	}

	chain := alice.New(
		func(h http.Handler) http.Handler {
			return recovery.Handler(os.Stderr, h, true)
		},
		func(h http.Handler) http.Handler {
			return handlers.CombinedLoggingHandler(os.Stdout, h)
		},
		handlers.CompressHandler,
	)

	sink := mapsink.New()
	fanout := metrics.FanoutSink{sink}

	if *statsd != "" {
		ss, _ := metrics.NewStatsdSink(*statsd)
		fanout = append(fanout, ss)
	}

	conf := metrics.DefaultConfig("cbootstrapd")
	conf.EnableHostname = false
	m, _ := metrics.New(conf, fanout)
	mw := mmw.New(m)

	router.PathPrefix("/debug/").Handler(chain.Append(mw.HandlerWrapper("debug")).Then(http.DefaultServeMux))
	router.PathPrefix("/images").Handler(chain.Append(mw.HandlerWrapper("images")).Then(http.StripPrefix("/images/", http.FileServer(http.Dir(*imageDir)))))
	router.Handle("/metrics", chain.Append(mw.HandlerWrapper("metrics")).ThenFunc(
		func(w http.ResponseWriter, r *http.Request) {
			w.Header().Set("Content-Type", "application/json; charset=utf-8")
			if err := json.NewEncoder(w).Encode(sink); err != nil {
				log.WithField("error", err).Error(err)
			}
		}))

	chain = chain.Append(func(h http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			context.Set(r, "_server_", s)
			h.ServeHTTP(w, r)
		})
	})
	router.Handle("/ipxe/{ip}", chain.Append(mw.HandlerWrapper("ipxe")).ThenFunc(ipxeHandler))
	router.Handle("/config/{ip}", chain.Append(mw.HandlerWrapper("config")).ThenFunc(configHandler))

	if err := http.ListenAndServe(fmt.Sprintf(":%d", *port), router); err != nil {
		log.WithFields(log.Fields{
			"error": err,
			"func":  "http.ListenAndServe",
		}).Fatal("ListenAndServe returned an error")
	}
}
コード例 #19
0
ファイル: main.go プロジェクト: G4m30v3r/drac-kvm
package main

import (
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"os/exec"
	"os/user"

	"github.com/Unknwon/goconfig"
	"github.com/ogier/pflag"
)

// CLI flags
var _host = pflag.StringP("host", "h", "some.hostname.com", "The DRAC host (or IP)")
var _username = pflag.StringP("username", "u", "", "The DRAC username")
var _password = pflag.BoolP("password", "p", false, "Prompt for password (optional, will use 'calvin' if not present)")
var javaws = pflag.StringP("javaws", "j", "/usr/bin/javaws", "The path to javaws binary")

func promptPassword() string {
	var pass string
	fmt.Print("Password: "******"Unable to read password from CLI")
	}
	return pass
}

func main() {
コード例 #20
0
)

// TODO implement the following flags
//       -x: extended hostnames view
//       -r src | dst | src-port | dst-port | state : sort connections
//       -N: display NAT box connection information (only valid with SNAT & DNAT)

var Version = "0.1.0"

var onlySNAT = flag.BoolP("snat", "S", false, "Display only SNAT connections")
var onlyDNAT = flag.BoolP("dnat", "D", false, "Display only DNAT connections")
var onlyLocal = flag.BoolP("local", "L", false, "Display only local connections (originating from or going to the router)")
var onlyRouted = flag.BoolP("routed", "R", false, "Display only connections routed through the router")
var noResolve = flag.BoolP("no-resolve", "n", false, "Do not resolve hostnames") // TODO resolve port names as well
var noHeader = flag.BoolP("no-header", "o", false, "Strip output header")
var protocol = flag.StringP("protocol", "p", "", "Filter connections by protocol")
var sourceHost = flag.StringP("source", "s", "", "Filter by source IP")
var destinationHost = flag.StringP("destination", "d", "", "Filter by destination IP")
var displayVersion = flag.BoolP("version", "v", false, "Print version")

func main() {
	flag.Parse()

	if *displayVersion {
		fmt.Println("Version " + Version)
		os.Exit(0)
	}

	which := conntrack.SNATFilter | conntrack.DNATFilter

	if *onlySNAT {
コード例 #21
0
ファイル: netstat-nat.go プロジェクト: postfix/netstat-nat
	return flows.FlowSlice[i].Original.DPort < flows.FlowSlice[j].Original.DPort
}

func (flows SortByState) Less(i, j int) bool {
	return flows.FlowSlice[i].State < flows.FlowSlice[j].State
}

var Version = "0.1.0"

var onlySNAT = flag.BoolP("snat", "S", false, "Display only SNAT connections")
var onlyDNAT = flag.BoolP("dnat", "D", false, "Display only DNAT connections")
var onlyLocal = flag.BoolP("local", "L", false, "Display only local connections (originating from or going to the router)")
var onlyRouted = flag.BoolP("routed", "R", false, "Display only connections routed through the router")
var noResolve = flag.BoolP("no-resolve", "n", false, "Do not resolve hostnames")
var noHeader = flag.BoolP("no-header", "o", false, "Strip output header")
var protocol = flag.StringP("protocol", "p", "", "Filter connections by protocol")
var sourceHost = flag.StringP("source", "s", "", "Filter by source IP")
var destinationHost = flag.StringP("destination", "d", "", "Filter by destination IP")
var displayVersion = flag.BoolP("version", "v", false, "Print version")
var sortBy = flag.StringP("sort", "r", "src", "Sort connections (src | dst | src-port | dst-port | state)")
var _ = flag.BoolP("extended-hostnames", "x", false, "This flag serves no purpose other than compatibility")

func main() {
	flag.Parse()

	if *displayVersion {
		fmt.Println("Version " + Version)
		os.Exit(0)
	}

	which := conntrack.SNATFilter | conntrack.DNATFilter
コード例 #22
0
	"maunium.net/go/mauimageserver/data"
	"maunium.net/go/mauimageserver/handlers"
	log "maunium.net/go/maulogger"
	"maunium.net/go/mauth"
	"net/http"
	"os"
	"os/signal"
	"path/filepath"
	"strconv"
	"syscall"
)

const version = "2.1.0"

var debug = flag.BoolP("debug", "d", false, "Enable to print debug messages to stdout")
var confPath = flag.StringP("config", "c", "/etc/mis/config.json", "The path of the mauImageServer configuration file.")
var logPath = flag.StringP("logs", "l", "/var/log/mis", "The path of the mauImageServer configuration file.")
var disableSafeShutdown = flag.Bool("no-safe-shutdown", false, "Disable Interrupt/SIGTERM catching and handling.")

var config *data.Configuration
var database data.MISDatabase
var auth mauth.System

func main() {
	flag.Parse()

	if !*disableSafeShutdown {
		c := make(chan os.Signal, 1)
		signal.Notify(c, os.Interrupt, syscall.SIGTERM)
		go func() {
			<-c
コード例 #23
0
ファイル: tool.go プロジェクト: jweslley/stats-tools
	"fmt"
	"io"
	"os"
	"strconv"
	"unicode/utf8"

	flag "github.com/ogier/pflag"
)

const programVersion = "0.0.1"

var (
	ignore = flag.BoolP("ignore", "i", false, "ignore invalid numbers")
	behead = flag.BoolP("behead", "b", false,
		"remove the first line (head) from calculations. Useful to ignore column names")
	separator = flag.StringP("separator", "s", " ",
		"define the SEPARATOR to use instead of whitespace for column separator")
	column  = flag.IntP("column", "c", 1, "calculate stats based on the specified COLUMN")
	version = flag.BoolP("version", "v", false, "print version information and exit")
)

func fail(format string, v ...interface{}) {
	fmt.Fprintf(os.Stderr, format, v...)
	os.Exit(1)
}

func calculate(s *Stats) {
	if len(flag.Args()) == 0 {
		parse("<stdin>", os.Stdin, s)
	}

	for _, filename := range flag.Args() {
コード例 #24
0
ファイル: wiith.go プロジェクト: WoLfh0UnD/hubbIT-sniffer
	"github.com/ogier/pflag"
	"io/ioutil"
	"net/http"
	"os"
	"os/signal"
	"os/user"
	"strconv"
	"strings"
	"syscall"
)

// The command line flags available
var (
	// Log related flags
	logToStderr  = pflag.BoolP("logtostderr", "e", true, "log to stderr instead of to files")
	logThreshold = pflag.StringP("logthreshold", "o", "INFO", "Log events at or above this severity are logged to standard error as well as to files. Possible values: INFO, WARNING, ERROR and FATAL")
	logdir       = pflag.StringP("logpath", "l", "./logs", "The log files will be written in this directory/path")

	flushInterval = pflag.Int64P("flushinterval", "f", 59, "The interval between the PUT of batches of mac-addresses")
	iface         = pflag.StringP("interface", "i", "mon0", "The capture interface to listen on")
	pcap          = pflag.StringP("pcap", "p", "", "Use a pcap file instead of live capturing")
	server        = pflag.StringP("server", "s", "http://localhost:3000/sessions.json", "Server to PUT macs to")
	authToken     = pflag.StringP("token", "t", "", "API-token. (Required)")
	printResponse = pflag.BoolP("printresponse", "r", false, "Print response from backend")
	hitCount      uint64
)

func init() {
	pflag.Parse()

	// glog Logging options
コード例 #25
0
ファイル: main.go プロジェクト: hcoyote/drac-kvm
import (
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"os/exec"
	"os/user"
	"time"

	"github.com/Unknwon/goconfig"
	"github.com/howeyc/gopass"
	"github.com/ogier/pflag"
)

// CLI flags
var _host = pflag.StringP("host", "h", "some.hostname.com", "The DRAC host (or IP)")
var _username = pflag.StringP("username", "u", "", "The DRAC username")
var _password = pflag.BoolP("password", "p", false, "Prompt for password (optional, will use 'calvin' if not present)")
var _version = pflag.IntP("version", "v", -1, "iDRAC version (6 or 7) (supermicro ikvm as 1)")
var _delay = pflag.IntP("delay", "d", 10, "Number of seconds to delay for javaws to start up & read jnlp before deleting it")
var _javaws = pflag.StringP("javaws", "j", DefaultJavaPath, "The path to javaws binary")

func promptPassword() string {
	fmt.Print("Password: "******"root"
	var password = "******"
コード例 #26
0
ファイル: basename.go プロジェクト: patrickToca/go-coreutils
  basename -a any/str1 any/str2   -> "str1" followed by "str2"

`
	Version = `
basename (Go coreutils) 0.1
Copyright (C) 2015 Robert Deusser
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>.
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

`
)

var (
	multiple = flag.BoolP("multiple", "a", false, "")
	suffix   = flag.StringP("suffix", "s", "", "")
	zero     = flag.BoolP("zero", "z", false, "")
	version  = flag.BoolP("version", "v", false, "")
)

func baseName(path, suffix string, null bool) string {
	dir := filepath.Base(path)

	if strings.HasSuffix(dir, suffix) {
		dir = dir[:len(dir)-len(suffix)]
	}

	if !null {
		dir += "\n"
	}
コード例 #27
0
ファイル: fs2s3.go プロジェクト: reedobrien/wpgo
	"path/filepath"
	"runtime"
	"strings"
	"sync"
	"time"
	"wp/sss"
)

const concurrency = 100
const sseKey string = "server-side-encryption"

var sseValue = []string{"AES256"}

var meta = map[string][]string{}
var node string
var bucket = flag.StringP("bucket", "b", "", "Use the named bucket")
var prefix = flag.StringP("prefix", "x", "", "Set upload path prefix. i.e., '-x location/'. NB: Add a slash if you want it!")
var public = flag.BoolP("public", "p", false, "Makes the uploaded files publicly visible")
var force = flag.BoolP("force", "f", false, "Force upload regardless of existance or mtime")
var sse = flag.BoolP("sse", "e", false, "Use server side encryption")
var mimetype = flag.StringP("mimetype", "m", "binary/octet-stream", "Set a fallback/default mimetype string.")

// XXX: Should this always be true? I think so.
var newer = flag.BoolP("newer", "n", false, "Upload if file time is newer than Last-modified")
var newermetamtime = flag.BoolP("newermetamtime", "N", false, "Upload if file is newer than x-amz-meta-last-modified")

// var recursive = flag.BoolP("recursive", "r", false, "Upload everything resursively from the path")
// verify sums?
// add a flag to use text/html as the default/fallback mime type instead of binary/octet-stream

type FileUpload struct {
コード例 #28
0
ファイル: maulu.go プロジェクト: tulir293/maulu
	"maunium.net/go/maulu/data"
	"net/http"
	"os"
	"strconv"
)

func getIP(r *http.Request) string {
	if config.TrustHeaders {
		return r.Header.Get("X-Forwarded-For")
	}
	return r.RemoteAddr
}

var debug = flag.BoolP("debug", "d", false, "Enable to print debug messages to stdout")
var stdin = flag.BoolP("stdin", "i", false, "Enable stdin listener")
var confPath = flag.StringP("config", "c", "/etc/maulu/config.json", "The path of the mau\\Lu configuration file.")
var logPath = flag.StringP("logs", "l", "/var/log/maulu", "The path to store log files in")

var config *data.Configuration

var templRedirect *template.Template

func init() {
	flag.Parse()
}

func main() {
	// Configure the logger
	log.PrintDebug = *debug
	log.Fileformat = func(date string, i int) string { return fmt.Sprintf("%[3]s/%[1]s-%02[2]d.log", date, i, *logPath) }
コード例 #29
0
ファイル: main.go プロジェクト: justinian/dodyndns
package main

import (
	"fmt"
	"net"
	"os"

	flag "github.com/ogier/pflag"
)

const (
	tokenEnvName = "DO_API_TOKEN"
)

var (
	token = flag.StringP("token", "t", tokenEnvName, "DigitialOcean APIv2 token")
	v4opt = flag.BoolP("v4", "4", false, "Update IPv4 A record")
	v6opt = flag.BoolP("v6", "6", false, "Update IPv6 AAAA record")
)

func errorOut(msg string, err error) {
	fmt.Fprintf(os.Stderr, "Error %s: %v\n", msg, err)
	os.Exit(1)
}

func main() {
	flag.Parse()

	if *token == tokenEnvName {
		*token = os.Getenv(tokenEnvName)
	}
コード例 #30
0
ファイル: main.go プロジェクト: nsabine/hugo
	"fmt"
	"github.com/howeyc/fsnotify"
	"github.com/mostafah/fsync"
	flag "github.com/ogier/pflag"
	"github.com/spf13/hugo/hugolib"
	"log"
	"net/http"
	"os"
	"path/filepath"
	"runtime/pprof"
	"sync"
	"time"
)

var (
	baseUrl     = flag.StringP("base-url", "b", "", "hostname (and path) to the root eg. http://spf13.com/")
	cfgfile     = flag.String("config", "", "config file (default is path/config.yaml|json|toml)")
	checkMode   = flag.Bool("check", false, "analyze content and provide feedback")
	draft       = flag.BoolP("build-drafts", "D", false, "include content marked as draft")
	help        = flag.BoolP("help", "h", false, "show this help")
	source      = flag.StringP("source", "s", "", "filesystem path to read files relative from")
	destination = flag.StringP("destination", "d", "", "filesystem path to write files to")
	verbose     = flag.BoolP("verbose", "v", false, "verbose output")
	version     = flag.Bool("version", false, "which version of hugo")
	cpuprofile  = flag.Int("profile", 0, "Number of times to create the site and profile it")
	watchMode   = flag.BoolP("watch", "w", false, "watch filesystem for changes and recreate as needed")
	server      = flag.BoolP("server", "S", false, "run a (very) simple web server")
	port        = flag.String("port", "1313", "port to run web server on, default :1313")
	uglyUrls    = flag.Bool("uglyurls", false, "use /filename.html instead of /filename/ ")
)