Example #1
0
func decodeRefArg(name, typeName string) (interface{}, error) {
	switch strings.ToLower(typeName) {
	case "*bool":
		newValue := flag.Bool(name, app.DefaultBoolValue, name)
		return newValue, nil
	case "bool":
		newValue := flag.Bool(name, app.DefaultBoolValue, name)
		return *newValue, nil

	case "*string":
		newValue := flag.String(name, app.DefaultStringValue, name)
		return *newValue, nil
	case "string":
		newValue := flag.String(name, app.DefaultStringValue, name)
		return *newValue, nil

	case "*time.duration":
		newValue := flag.Duration(name, app.DefaultDurationValue, name)
		return *newValue, nil
	case "time.duration":
		newValue := flag.Duration(name, app.DefaultDurationValue, name)
		return *newValue, nil

	case "*float64":
		newValue := flag.Float64(name, app.DefaultFloat64Value, name)
		return *newValue, nil
	case "float64":
		newValue := flag.Float64(name, app.DefaultFloat64Value, name)
		return *newValue, nil

	case "*int":
		newValue := flag.Int(name, app.DefaultIntValue, name)
		return *newValue, nil
	case "int":
		newValue := flag.Int(name, app.DefaultIntValue, name)
		return *newValue, nil

	case "*int64":
		newValue := flag.Int64(name, app.DefaultInt64Value, name)
		return *newValue, nil
	case "int64":
		newValue := flag.Int64(name, app.DefaultInt64Value, name)
		return *newValue, nil

	case "*uint":
		newValue := flag.Uint(name, app.DefaultUIntValue, name)
		return *newValue, nil
	case "uint":
		newValue := flag.Uint(name, app.DefaultUIntValue, name)
		return *newValue, nil

	case "*uint64":
		newValue := flag.Uint64(name, app.DefaultUInt64Value, name)
		return *newValue, nil
	case "uint64":
		newValue := flag.Uint64(name, app.DefaultUInt64Value, name)
		return *newValue, nil
	}
	return nil, fmt.Errorf("unknow type %s for argument %s", typeName, name)
}
Example #2
0
func main() {
	maxPics := flag.Int64("max", -1, "Max count of pics to download (not implemented)")
	downloaders := flag.Uint64("dl", 1, "Number of simultaneous manga downloader")
	workers := flag.Uint64("worker", 3, "Number of simultaneous archive worker per downloader")
	fetchers := flag.Uint64("fetch", 4, "Number of simultaneous image fetcher per worker")
	flag.Parse()
	mangas := flag.Args()

	targets := make(chan uint64, len(mangas))

	logfile, err := os.OpenFile("log.txt", os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0666)
	if err != nil {
		return
	}
	defer logfile.Close()
	logfile.WriteString(fmt.Sprintf(`======================================================
Fetch started at %v
======================================================
Targets supplied: %v
`, time.Now(), mangas))
	log.SetOutput(io.MultiWriter(os.Stdout, logfile))

	for _, manga := range mangas {
		m, err := strconv.ParseUint(manga, 10, 64)
		if err != nil {
			log.Fatal(err)
		}
		log.Println("Adding download target:", m)
		targets <- m
	}

	if len(mangas) == 0 {
		fmt.Println("Please input space-seperated manga ID.")
		fmt.Println("Manga ID: http://marumaru.in/b/manga/{ID}")
		os.Exit(1)
	}

	if *fetchers == 0 || *workers == 0 || *maxPics == 0 || *downloaders == 0 {
		fmt.Println("Invalid argument supplied")
		os.Exit(1)
	}
	doc, err := goquery.NewDocument(MangaPrefix)
	if err == nil && doc.Find("title").First().Text()[:7] == "You are" {
		UpdateCookie(doc)
	}
	wg := new(sync.WaitGroup)
	wg.Add(int(*downloaders))
	for i := uint64(0); i < *downloaders; i++ {
		dl := new(Downloader)
		dl.Init(*workers, *fetchers, *maxPics)
		go dl.Start(targets, wg)
	}
	close(targets)
	wg.Wait()
	log.Print("All tasks were done.")
}
Example #3
0
func main() {
	duration := flag.Uint64("duration", 3600, "Time to sleep before exit")
	asn := flag.Uint64("ASN", 65101, "Our AS number")
	rid := flag.Uint64("RID", 1, "Our router's ID")
	cfg := flag.String("cfg", "./inj.cfg", "Our configuration file")
	flag.Parse()
	fmt.Println("starting to inject bgp routes")
	to := make(chan bgp2go.BGPProcessMsg)
	from := make(chan bgp2go.BGPProcessMsg)
	bgpContext := bgp2go.BGPContext{ASN: uint32(*asn), RouterID: uint32(*rid)}
	go bgp2go.StartBGPProcess(to, from, bgpContext)
	ReadFile(*cfg, to)
	time.Sleep(time.Duration(*duration) * time.Second)
	fmt.Println("i've slept enough. waking up...")
}
Example #4
0
func main() {
	// use [from/to/by] or [from/iterations]
	nFrom := flag.Uint64("from", 1e2, "start iterations from this number")
	nTo := flag.Uint64("to", 1e4, "run iterations until arriving at this number")
	nBy := flag.Uint64("by", 1, "increment each iteration by this number")
	nIncrements := flag.Uint64("iterations", 0, "number of iterations to execute")
	encodingType := flag.String("encoding", "string", "encode/decode as 'string', 'binary', 'binary-int', 'binary-varint'")
	flag.Parse()

	flag.Usage = func() {
		fmt.Printf("%s\n", os.Args[0])
		flag.PrintDefaults()
		return
	}

	t0 := time.Now()
	nBytes := uint64(0)
	nIterations := uint64(0)

	encoderDecoder := getEncoder(*encodingType)
	startingLoop := newBigFloat(*nFrom)

	var endLoop *big.Float
	var incrementer *big.Float

	if *nIncrements > 0 {
		// using from/iterations flags
		fmt.Printf("encoding: %v from: %v iterations: %v\n", *encodingType, *nFrom, *nIncrements)

		incrementer = newBigFloat(1)
		n := newBigFloat(*nIncrements)
		endLoop = n.Add(n, startingLoop)
	} else {
		// using from/to/by flags
		fmt.Printf("encoding: %v from: %v to: %v by: %v\n", *encodingType, *nFrom, *nTo, *nBy)
		incrementer = newBigFloat(*nBy)
		endLoop = newBigFloat(*nTo)
	}

	for i := startingLoop; i.Cmp(endLoop) < 0; i = i.Add(i, incrementer) {
		nIterations++
		nBytes += runTest(encoderDecoder, i)
	}

	t1 := time.Now()
	d := t1.Sub(t0)
	fmt.Printf("IO  %s (%v nums) in %s (%s/s)\n", humanize.Bytes(nBytes), humanize.Comma(int64(nIterations)), d, humanize.Bytes(uint64(float64(nBytes)/d.Seconds())))
}
Example #5
0
func main() {

	var v = flag.String("v", "", "specify the Spit ID you want to see details")
	var c = flag.String("c", "", "specify a long URL (or text) to short-spit it")
	var e = flag.Uint64("e", 86400, "specify expiry time in seconds")
	var t = flag.String("t", "url", "specify the type of the Spit (url or text)")
	flag.Parse()

	if len(*v) > 0 {
		resp, err := spito.View(*v)
		if err != nil {
			fmt.Fprintf(os.Stderr, "Error while fetching information for: %s\n\t%s", v, err.Error())
		} else {
			fmt.Fprintf(os.Stdout, "Spit-details: %s\n", resp)
		}
	} else {
		if len(*c) == 0 {
			fmt.Fprintf(os.Stderr, "Cannot create empty Spit!\n")
			return
		}
		resp, err := spito.Spit(*c, *t, *e, true)
		if err != nil {
			fmt.Fprintln(os.Stderr, "Error while shortening with Spi.to :: \n", err.Error())
		} else {
			fmt.Fprintf(os.Stdout, "Spit-link: %s\n", resp)
		}
	}
}
func main() {
	keyname := flag.String("keyname", "hosts", "Etcd keyname under which to record containers' hostnames/IP")
	ttl := flag.Uint64("ttl", 172800, "Time to live of the host entry")
	dockerAPIPort := flag.String("port", "4243", "Docker API Port")
	interval := flag.Duration("interval", 10, "Docker API to Etcd sync interval")
	//etcdHost := flag.String("etcd_host", "127.0.0.1", "Etcd host")
	//etcdPort := flag.String("etcd_port", "4001", "Etcd port")
	concurrency := flag.Int("concurrency", 1, "Number of worker threads")

	flag.Parse()

	//etcdCluster := []string{"http://" + *etcdHost + ":" + *etcdPort}
	etcdClient := etcd.NewClient()
	//etcdClient.SetCluster(etcdCluster)

	dockerClient, err := docker.NewClient("http://127.0.0.1:" + *dockerAPIPort)
	if err != nil {
		log.Fatal(err)
	}

	var c = make(chan string, *concurrency)

	for i := 0; i < *concurrency; i++ {
		go inspectAndSet(c, etcdClient, dockerClient, keyname, ttl)
	}

	loop(c, dockerClient, interval)

}
Example #7
0
func main() {
	log.SetFlags(log.Lshortfile)

	flagDelay := flag.Uint64("d", 0, "delay between keystrokes (milliseconds)")
	flag.Usage = func() {
		fmt.Fprintln(os.Stderr,
			"Send keys to the active X11 window\n"+
				"Usage:\n"+
				"  xtypekeys [ -d <num> ] \"<string>\" \"<string>\"\n\n"+
				"Example:\n"+
				"  xtypekeys -d 10 \"[Control]t\" \"[Control]k\" \\\n"+
				"                    \"search this\" \\\n"+
				"                    \"[Return]\"\n"+
				"Options:")
		flag.PrintDefaults()
	}
	flag.Parse()

	temporize = func() {
		time.Sleep(time.Duration(*flagDelay) * time.Millisecond)
	}

	if err := x.OpenDisplay(); err != nil {
		log.Fatal(err)
	}
	defer x.CloseDisplay()
	typeStrings(flag.Args())
}
Example #8
0
func main() {
	defaultSize := bucket.BucketSize * uint64(bucket.MaxOpen)

	path := flag.String("disk", "", "File path to setup as persistent storage")
	size := flag.Uint64("size", defaultSize, "Size of persistent storage")
	flag.Parse()

	f, err := os.Create(*path)
	if err != nil {
		panic(err)
	}
	defer f.Close()

	err = f.Truncate(int64(*size))
	if err != nil {
		panic(err)
	}

	err = bucket.Create("/cache-buckets", *size)
	if err != nil {
		panic(err)
	}

	// We expect values to be at least 1KB
	err = hashtable.Create("/cache-hashtable", *size/1024)
	if err != nil {
		panic(err)
	}
}
Example #9
0
File: main.go Project: vys/proxy
func main() {
	c := flag.Uint64("c", 1, "Concurrency")
	flag.Parse()
	log.Printf("Running... with concurrency: %v\n", *c)
	log.Fatal(http.Serve(throttle.NewListener("0:8080", *c),
		http.HandlerFunc(HelloHandler)))
}
Example #10
0
File: main.go Project: phzfi/RIC
func main() {

	cpath := flag.String("c", "config.ini", "Sets the configuration .ini file used.")
	flag.Parse()
	// CLI arguments

	conf := config.ReadConfig(*cpath)

	mem := flag.Uint64("m", conf.Server.Memory, "Sets the maximum memory to be used for caching images in bytes. Does not account for memory consumption of other things.")
	imagick.Initialize()
	defer imagick.Terminate()

	log.Println("Server starting...")
	logging.Debug("Debug enabled")

	server, handler, ln := NewServer(8005, *mem, conf)
	handler.started = time.Now()
	err := server.Serve(ln)
	end := time.Now()

	// Get number of requests
	requests := strconv.FormatUint((*handler).requests, 10)

	// Calculate the elapsed time
	duration := end.Sub(handler.started)
	log.Println("Server requests: " + requests)
	log.Println("Server uptime: " + duration.String())

	// Log errors
	if err != nil {
		log.Fatal(err)
	}
}
func main() {
	optHost := flag.String("host", "localhost", "Hostname")
	optPort := flag.String("port", "64738", "Port")
	optTimeout := flag.Uint64("timeout", 1000, "Timeout (ms)")
	optTempfile := flag.String("tempfile", "", "Temp file name")
	flag.Parse()

	var murmur MurmurPlugin

	murmur.Host = fmt.Sprintf("%s:%s", *optHost, *optPort)
	murmur.Timeout = *optTimeout
	helper := mp.NewMackerelPlugin(murmur)

	if *optTempfile != "" {
		helper.Tempfile = *optTempfile
	} else {
		helper.Tempfile = fmt.Sprintf("/tmp/mackerel-plugin-murmur-%s-%s", *optHost, *optPort)
	}

	if os.Getenv("MACKEREL_AGENT_PLUGIN_META") != "" {
		helper.OutputDefinitions()
	} else {
		helper.OutputValues()
	}
}
Example #12
0
func main() {
	var client = flag.String("c", "", "soundcloud client id")
	var uid = flag.Uint64("u", 0, "soundcloud user id")
	var debug = flag.Bool("d", false, "debug")

	flag.Parse()

	if *client == "" {
		error("client id required")
	}

	if *uid == 0 {
		error("user id required")
	}

	unauthenticatedAPI := &soundcloud.Api{
		ClientId: *client,
	}

	tracks, err := unauthenticatedAPI.User(*uid).AllFavorites()
	if err != nil {
		if *debug {
			panic(err)
		}
		os.Exit(1)
	}

	for _, track := range tracks {
		fmt.Println(track.PermalinkUrl)
	}
}
Example #13
0
func main() {
	var (
		listen  = flag.String("listen", ":7800", "Server listen address.")
		name    = flag.String("test.name", "unknown", "Name of the test to run.")
		path    = flag.String("test.path", "/", "Path to hit on the targets")
		rate    = flag.Uint64("test.rate", defaultRate, "Number of requests to send during test duration.")
		timeout = flag.Duration("test.timeout", defaultTimeout, "Time until a request is discarded")

		ts = targets{}
	)
	flag.Var(&ts, "test.target", `Target to hit by the test with the following format: -test.target="NAME:address/url"`)
	flag.Parse()

	if *listen == "" || len(ts) == 0 {
		flag.Usage()
		os.Exit(1)
	}

	var (
		test     = newTest(*name, *path, *rate, defaultInterval, *timeout, ts)
		registry = newRegistry(prometheus.Labels{"test": test.name})
		resultc  = make(chan result)
	)

	test.run(resultc)
	go registry.collect(resultc)

	http.Handle("/metrics", prometheus.Handler())

	log.Printf("Starting server on %s", *listen)
	log.Fatal(http.ListenAndServe(*listen, nil))
}
Example #14
0
func (runner *_Runner) Milliseconds(name string, fullname string, defaultVal uint64, description string) Runner {
	runner.checkName(name, fullname)

	runner.flagMilliseconds[name] = flag.Uint64(name, defaultVal, description)

	return runner
}
Example #15
0
func main() {
	nTotal := flag.Uint64("n", math.MaxUint64, "number of times to perform a read and write operation")
	initialProcess := flag.String("initial", "", "Process to ask for the initial view")
	retryProcess := flag.String("retry", "", "Process to ask for a newer view")
	flag.Parse()

	freestoreClient, err := client.New(getInitialViewFunc(*initialProcess), getFurtherViewsFunc(*retryProcess))
	if err != nil {
		log.Fatalln("FATAL:", err)
	}

	var finalValue interface{}
	for i := uint64(0); i < *nTotal; i++ {
		startRead := time.Now()
		finalValue, err = freestoreClient.Read()
		endRead := time.Now()
		if err != nil {
			log.Fatalln(err)
		}

		startWrite := time.Now()
		err = freestoreClient.Write(finalValue)
		endWrite := time.Now()
		if err != nil {
			log.Fatalln(err)
		}

		if i%1000 == 0 {
			fmt.Printf("%v: Read %v (%v)-> Write (%v)\n", i, finalValue, endRead.Sub(startRead), endWrite.Sub(startWrite))
		} else {
			fmt.Printf(".")
		}
	}
}
Example #16
0
func main() {
	var (
		wordsize  = flag.Uint64("wordsize", 32, "Word size of CPU")
		numCycles = flag.Uint64("cycles", 1000000, "Number of cycles to emulate")
		dumpStart = flag.Uint64("dumpStart", 0, "Start word of memory dump")
		dumpEnd   = flag.Uint64("dumpEnd", 0, "End word of memory dump")
	)
	flag.Parse()

	if flag.NArg() != 1 {
		flag.PrintDefaults()
		fmt.Println("\nExpected file to read ('-' for stdin)")
		return
	}
	if 64%*wordsize != 0 {
		flag.PrintDefaults()
		fmt.Println("\nWord size must be a multiple of 64")
		return
	}
	in := os.Stdin
	if f := flag.Arg(0); f != "-" {
		var err error
		in, err = os.Open(f)
		if err != nil {
			log.Fatalf("Error openening %s: %s", f, err)
		}
	}

	sbm, err := bitMemoryFromFile(in)
	if err != nil {
		log.Fatalf("Error reading input: %s", err)
	}
	sbm.WordSize = *wordsize
	sbm.AlignMemory()

	cpu := &libnandcpu.NandCPU{BitMemory: sbm}
	for i := uint64(0); i < *numCycles; i++ {
		cpu.Step()
	}
	// wordsize/4 = Number of hex digits per word
	pattern := fmt.Sprintf("%%%02dX\n", *wordsize/4)
	for i := *dumpStart; i < *dumpEnd; i++ {
		fmt.Printf(pattern, sbm.Word(i))
	}
}
func main() {
	var (
		n = flag.Uint64("n", 1000, "Upper limit: not included")
	)

	flag.Parse()

	fmt.Println(multipleSumBelow(*n))
}
Example #18
0
func main() {
	workers := flag.Uint64("workers", 0, "max integer to try")
	rng := flag.Uint64("range", 0, "max integer to try")
	flag.Parse()

	partialResults := make(chan float64, 1000000)
	quit := make(chan bool)

	go accumulateResult(*workers, partialResults, quit)

	for i := uint64(0); i < *workers; i++ {
		makeWorker((0 == ((i * *rng) % 2)),
			float64(i**rng),
			float64((i+1)**rng-1),
			partialResults)
	}
	<-quit
}
Example #19
0
func main() {
	udpAddr := flag.String("udpaddr", "127.0.0.1:5565", "UDP address string")
	udpFdInt := flag.Uint64("udpfd", 0, "UDP socket file descriptor")
	maxprocs := flag.Int("maxprocs", 1, "Go runtime MAXPROCS value")
	pprofName := flag.String("pprof", "", "pprof output file path")
	poolSize := flag.Int("poolsize", 1000, "Pipeline pool size")
	decoder := flag.String("decoder", "json", "Default decoder")
	flag.Parse()
	udpFdIntPtr := uintptr(*udpFdInt)

	runtime.GOMAXPROCS(*maxprocs)

	if *pprofName != "" {
		profFile, err := os.Create(*pprofName)
		if err != nil {
			log.Fatalln(err)
		}
		pprof.StartCPUProfile(profFile)
		defer pprof.StopCPUProfile()
	}

	config := pipeline.GraterConfig{}

	udpInput := pipeline.NewUdpInput(*udpAddr, &udpFdIntPtr)
	var inputs = map[string]pipeline.Input{
		"udp": udpInput,
	}
	config.Inputs = inputs

	jsonDecoder := pipeline.JsonDecoder{}
	gobDecoder := pipeline.GobDecoder{}
	var decoders = map[string]pipeline.Decoder{
		"json": &jsonDecoder,
		"gob":  &gobDecoder,
	}
	config.Decoders = decoders
	config.DefaultDecoder = *decoder

	outputNames := []string{"counter"}
	namedOutputFilter := pipeline.NewNamedOutputFilter(outputNames)
	config.FilterChains = map[string][]pipeline.Filter{
		"default": {namedOutputFilter},
	}
	config.DefaultFilterChain = "default"

	counterOutput := pipeline.NewCounterOutput()
	logOutput := pipeline.LogOutput{}
	var outputs = map[string]pipeline.Output{
		"counter": counterOutput,
		"log":     &logOutput,
	}
	config.Outputs = outputs
	config.DefaultOutputs = []string{}
	config.PoolSize = *poolSize

	pipeline.Run(&config)
}
Example #20
0
func main() {
	pname := flag.String("name", "unnamed", "The name of the colorscheme.")
	pw := flag.Uint64("w", 40, "Width of the pictures of the colorscheme.")
	ph := flag.Uint64("h", 1024, "Height (number of levels) of the colorscheme.")
	flag.Parse()

	if flag.NArg() < 2*2 || flag.NArg()%2 != 0 {
		flag.Usage()
		log.Fatal("Need at least two gradient keypoints!")
	}

	keypoints := GradientTable{}
	for i := 0; i < flag.NArg(); i += 2 {
		keypoints = append(keypoints, GradientTableEntry{MustParseHex(flag.Arg(i)), MustParseFloatZeroOne(flag.Arg(i + 1))})
	}

	CreateColorschemes(keypoints, *pname, int(*pw), int(*ph))
}
Example #21
0
// UInt64 creates a new entry in the flag set with UInt64 value.
// The environment value used as a default, if it exists
func UInt64(flagName, envName string, value uint64, usage string) *uint64 {
	verifyNames(flagName, envName)
	envValStr := lookupEnv(envName)
	if envValStr != "" {
		value, _ = strconv.ParseUint(envValStr, 10, 64)
	}

	flag.Uint64(flagName, value, usage)
	return pflag.Uint64(flagName, value, usage)
}
Example #22
0
func NewCTConfig() *CTConfig {
	ret := &CTConfig{
		LogUrl:         flag.String("log", "", "URL of the CT Log"),
		CensysPath:     flag.String("censysJson", "", "Path to a Censys.io certificate json dump"),
		CensysUrl:      flag.String("censysUrl", "", "URL to a Censys.io certificate json dump"),
		CensysStdin:    flag.Bool("censysStdin", false, "Read a Censys.io json dump from stdin"),
		DbConnect:      flag.String("dbConnect", "", "DB Connection String"),
		Verbose:        flag.Bool("v", false, "verbose output"),
		CertPath:       flag.String("certPath", "", "Path under which to store full DER-encoded certificates"),
		CertsPerFolder: flag.Uint64("certsPerFolder", 16384, "Certificates per folder, when stored"),
		Offset:         flag.Uint64("offset", 0, "offset from the beginning"),
		OffsetByte:     flag.Uint64("offsetByte", 0, "byte offset from the beginning, only for censysJson and not compatible with offset"),
		Limit:          flag.Uint64("limit", 0, "limit processing to this many entries"),
		GeoipDbPath:    flag.String("geoipDbPath", "", "Path to GeoIP2-City.mmdb"),
		NumThreads:     flag.Int("numThreads", 1, "Use this many threads per CPU"),
		HistoricalDays: flag.Int("histDays", 90, "Update this many days of historical data"),
	}

	iniflags.Parse()
	return ret
}
Example #23
0
func main() {
	runtime.GOMAXPROCS(2)
	oClass := flag.Uint64("c", 2, `factor "class" number`)
	oDuration := flag.Duration("d", time.Second, "duration to spend on one class")
	flag.Parse()
	class := *oClass
	for class&1 != 0 {
		class >>= 1
	}
	class = mathutil.MaxUint64(class, 2)

	for {
		c := time.After(*oDuration)
		factor := big.NewInt(0)
		factor.SetUint64(class)
		exp := big.NewInt(0)
	oneClass:
		for {
			select {
			case <-c:
				break oneClass
			default:
			}

			exp.Set(factor)
			factor.Lsh(factor, 1)
			factor.Add(factor, _1)
			if !factor.ProbablyPrime(pp) {
				continue
			}

			if !exp.ProbablyPrime(pp) {
				continue
			}

			if mathutil.ModPowBigInt(_2, exp, factor).Cmp(_1) != 0 {
				continue
			}

			if !factor.ProbablyPrime(pp2) {
				continue
			}

			if !exp.ProbablyPrime(pp2) {
				continue
			}

			fmt.Printf("%d: %s | M%s (%d bits)\n", class, factor, exp, factor.BitLen())
		}

		class += 2
	}
}
Example #24
0
func main() {
	ep := flag.String("endpoint", "http://127.0.0.1:2379", "comma separated endpoints of an etcd cluster")
	dir := flag.String("dir", "/", "first level directory to purge")
	timestampDir := flag.String("timestamp-dir", "/", "directory to store and retrive fuzzy timestamps")
	// default to purge nothing
	limit := flag.Uint64("limit", 0, "the min index of directory to purge")
	dry := flag.Bool("dry", true, "do not actually purge the directories")
	mday := flag.Duration("day", 24*time.Hour, "decresing this for testing purpose")
	auto := flag.Bool("auto", false, "auto purge mode")
	oldv2 := flag.Bool("old-v2cluster", false, "purge old v2 cluster")
	flag.Parse()

	day = *mday

	eps := strings.Split(*ep, ",")
	cfg := client.Config{
		Endpoints: eps,
	}

	hc, err := client.New(cfg)
	if err != nil {
		fmt.Fprintln(os.Stderr, err.Error())
		os.Exit(1)
	}

	kAPI := client.NewKeysAPI(hc)

	if *auto {
		go makeTimestamps(kAPI, *timestampDir, *dry)
	}

	for {
		var l uint64
		if *auto {
			l = findLimit(kAPI, *timestampDir)
			if l == 0 {
				fmt.Println("timestamp is not ready. retry after a day...")
				time.Sleep(day)
				continue
			}
		} else {
			l = *limit
		}

		fmt.Printf("start to purge with limit = %016s\n", strconv.FormatUint(l, 16))
		purge(kAPI, *dir, l, *dry, *oldv2)
		if !*auto {
			os.Exit(0)
		}
		fmt.Println("successfully finished purging! sleeping for a day to start another one")
		time.Sleep(day)
	}
}
Example #25
0
// Parse arguments and call main loop
func main() {
	service := flag.String("service", "", "Service name to announce")
	etcdAddr := flag.String("etcd", "http://127.0.0.1:4001",
		"etcd peer address. Defaults to http://127.0.0.1:4001")
	etcdPath := flag.String("path", "/service",
		"Path in etcd to place announcement in.")
	etcdTtl := flag.Uint64("ttl", 30, "Service announce TTL (default 30s)")
	announceType := flag.String("type", "msg",
		"Announce type. One of \"net\" or \"msg\"")
	announceMsg := flag.String("msg", "", "Message to announce")
	announceInterface := flag.String("if", "", "Interface to announce")

	flag.Parse()

	// Do some simple validation
	if *service == "" {
		fmt.Println("Must supply service name with -service")
		printUsageAndExit()
	}

	if (*announceType == "msg") && (*announceMsg == "") {
		fmt.Println("Must set message with -msg")
		printUsageAndExit()
	}

	if (*announceType == "net") && (*announceInterface == "") {
		fmt.Println("Must set interface with -if")
		printUsageAndExit()
	}

	// Set up announcer
	var announcer func()

	if *announceType == "msg" {
		announcer = func() {
			announce((*etcdPath + "/" + *service),
				*announceMsg, *etcdAddr, *etcdTtl)
		}
	} else if *announceType == "net" {
		announcer = func() {
			announce((*etcdPath + "/" + *service),
				getLocalIp(*announceInterface),
				*etcdAddr, *etcdTtl)
		}
	}

	// Announce once and start main loop
	announcer()

	go startAnnouncer(*etcdTtl, announcer)
	select {}
}
Example #26
0
func main() {
	defer trace("gperfect")()
	perPtr := flag.Uint64("number", 0, "Perfect number to find")
	coreCountPtr := flag.Uint("numCores", 8, "Number of cores to use when calculating random perfect numbers")
	numRandPtr := flag.Uint("numRandom", 100, "Number of random perfect numbers to look for.  Omit for continuous calculations")
	flag.Parse()

	if *perPtr > 0 {
		calcPerfect(*perPtr, *coreCountPtr)
	} else {
		calcRandPerfects(coreCountPtr, numRandPtr)
	}
}
Example #27
0
func InitConfig() {
	defaultPort, err := strconv.ParseUint(os.Getenv("PORT"), 0, 16)
	if err != nil {
		defaultPort = 5002
	}
	port := flag.Uint64("p", defaultPort, "Port to serve on")

	flag.Parse()

	config = Config{
		*port,
	}
}
Example #28
0
func main() {

	// Pass the configuration files as parameters:
	//
	//   bin/nim -ucbc=1.0 -chips=100
	//   bin/nim -h
	//
	var ucbC *float64 = flag.Float64("ucbc", 1.0, "the constant biasing exploitation vs exploration")
	var chips *uint64 = flag.Uint64("chips", 100, "the number of chips in the starting state")
	flag.Parse()

	// Report the files we are using.
	var experimentName string = os.Args[0]
	log.Printf("Experiment: '%s'\n", experimentName)

	// Our two intrepid players.
	var playerA uint64 = 1 // Goes first.
	var playerB uint64 = 2 // Goes second.
	var playerIds []uint64 = []uint64{playerA, playerB}

	// How many iterations do players take when considering moves?
	var iterations uint = 1000

	// How many simulations do players make when valuing the new moves?
	var simulations uint = 100

	// Create the initial game state.
	var state *nim.NimState = nim.NewNimState(*chips, playerIds)

	// Play until the game is over (no more available moves).
	for len(state.AvailableMoves()) > 0 {

		// Log the current game state.
		state.Log()

		// What is the next active player's move?
		var move mcts.Move = mcts.Uct(state, iterations, simulations, *ucbC, state.ActivePlayerId, scoreNim)
		state.MakeMove(move)

		// Report the action taken.
		var nimMove *nim.NimMove = move.(*nim.NimMove)
		nimMove.Log()
	}

	// Report winner.
	state.LogWinner()

	log.Println("Experiment Complete.")
	os.Exit(0)
}
Example #29
0
func main() {
	workers := flag.Uint64("workers", 0, "max integer to try")
	rng := flag.Uint64("range", 0, "max integer to try")
	flag.Parse()

	chans := make(chan float64, 1000000)
	quit := make(chan bool)

	go func() {
		var pi float64 = 0.0
		for i := uint64(0); i < *workers; i++ {
			pi += <-chans
		}
		fmt.Printf("Approximate Pi = %v\n", pi)
		quit <- true
	}()

	var i uint64 = 0
	for ; i < *workers; i++ {
		makeWorker((0 == ((i * *rng) % 2)), float64(i**rng), float64((i+1)**rng-1), chans)
	}
	<-quit
}
Example #30
0
func main() {
	var (
		brokerName    = flag.String("broker", brokers[0], brokerList())
		brokerPort    = flag.String("broker-port", defaultBrokerPort, "host machine broker port")
		dockerHost    = flag.String("docker-host", defaultHost, "host machine (or VM) running Docker")
		brokerdHost   = flag.String("host", defaultDaemonHost, "machine running broker daemon")
		peerHosts     = flag.String("peer-hosts", defaultDaemonHost, "comma-separated list of machines to run peers")
		producers     = flag.Uint("producers", defaultNumProducers, "number of producers per host")
		consumers     = flag.Uint("consumers", defaultNumConsumers, "number of consumers per host")
		numMessages   = flag.Uint("num-messages", defaultNumMessages, "number of messages to send from each producer")
		messageSize   = flag.Uint64("message-size", defaultMessageSize, "size of each message in bytes")
		startupSleep  = flag.Uint("startup-sleep", defaultStartupSleep, "seconds to wait after broker start before benchmarking")
		daemonTimeout = flag.Uint("daemon-timeout", defaultDaemonTimeout, "seconds to wait for daemon before timing out")
		dockerExtras  = flag.String("docker-extra", "", "extra args to pass to `docker run'")
	)
	flag.Parse()

	peers := strings.Split(*peerHosts, ",")

	client, err := broker.NewClient(&broker.Benchmark{
		BrokerdHost:   *brokerdHost,
		BrokerName:    *brokerName,
		BrokerHost:    *dockerHost,
		BrokerPort:    *brokerPort,
		PeerHosts:     peers,
		NumMessages:   *numMessages,
		MessageSize:   *messageSize,
		Publishers:    *producers,
		Subscribers:   *consumers,
		StartupSleep:  *startupSleep,
		DaemonTimeout: *daemonTimeout,
		DockerExtras:  *dockerExtras,
	})
	if err != nil {
		fmt.Println("Failed to connect to flotilla:", err)
		os.Exit(1)
	}

	start := time.Now()
	results, err := runBenchmark(client)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	elapsed := time.Since(start)

	printSummary(client.Benchmark, elapsed)
	printResults(results)
}