func main() {
	kingpin.Version(fmt.Sprintf("%s %s", kingpin.CommandLine.Name, version))
	kingpin.Parse()

	level, err := oplogging.LogLevel(*loglevel)
	if err != nil {
		prefixedUserError("Bad loglevel: %s", loglevel)
		os.Exit(1)
	}
	logging.SetLevel(level)

	diffCmd, err := shellwords.NewParser().Parse(*diffCommand)
	if err != nil {
		userError("Error parsing diff command %q: %s", *diffCommand, err.Error())
		os.Exit(1)
	}

	tests, err := testcase.DiscoverTests(*testcasePath)
	if err != nil {
		userError(err.Error())
		os.Exit(1)
	}
	if err = runTests(*logstashPath, tests, *configPaths, diffCmd, *keptEnvVars); err != nil {
		userError(err.Error())
		os.Exit(1)
	}
	os.Exit(0)
}
Exemple #2
0
func main() {
	logger := log.New(os.Stdout, "logger: ", log.Lshortfile)
	kingpin.Parse()
	filechannel := make(chan string, 100)
	go pump.TailFile(filechannel, *filename)

	mainpage := &frontend.MainPage{HTTPSMode: false, BasicAuth: false, UserName: *user, UserPassword: *password}

	if *user != "" && *password != "" {
		mainpage.BasicAuth = true
	}
	if *cert != "" && *key != "" {
		mainpage.HTTPSMode = true
	}
	logger.Printf("Basic auth: %t", mainpage.BasicAuth)
	logger.Printf("HTTPS: %t", mainpage.HTTPSMode)

	handler := pump.WebHandler{Filechannel: filechannel, Buffer: make([]string, *number), BufferSize: *number}
	address := fmt.Sprintf("%s:%d", *host, *port)

	r := mux.NewRouter()
	r.Handle("/", mainpage)
	r.Handle("/socket", websocket.Handler(handler.Websocket))

	http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(assetFS())))
	http.Handle("/", r)
	logger.Printf("Listening on %s\n", address)
	if *cert != "" && *key != "" {
		http.ListenAndServeTLS(address, *cert, *key, nil)
	}
	http.ListenAndServe(address, nil)
}
Exemple #3
0
func main() {
	kingpin.Version(Version)
	kingpin.Parse()

	setupLoggo(*debug)

	//localRegistry := metrics.NewRegistry()
	//publisher := newPublisher(localRegistry)
	//publisher := newLitePublisher()

	mqttEngine, mqerr := newMqttEngine(*mqttURL)
	wbEngine, wberr := NewWebBrickDriver(mqttEngine)

	if mqerr != nil && wberr != nil {
		panic(err)
	}

	wbEngine.Start()

	//ws := newWsServer(localRegistry)

	//go ws.listenAndServ(*port, *path)

	// Set up channel on which to send signal notifications.
	sigc := make(chan os.Signal, 1)
	signal.Notify(sigc, os.Interrupt, os.Kill)

	// Wait for receiving a signal.
	<-sigc

	// Disconnect the Network Connection.
	if err := engine.disconnect(); err != nil {
		panic(err)
	}
}
func init() {
	//set logging
	logg.LogKeys[TagError] = true
	logg.LogKeys[TagDiff] = true

	if DEBUG == false {
		logg.LogKeys[TagLog] = true
	}

	kingpin.Parse()
	if *configFileName == "" {
		kingpin.Errorf("Config file name missing")
		return
	}
	configFile, err := os.Open(*configFileName)
	if err != nil {
		logg.LogPanic("Unable to open file: %v.  Err: %v", *configFileName, err.Error())
		return
	}
	defer configFile.Close()

	configReader := bufio.NewReader(configFile)

	err = parseConfigFile(configReader)
	if err != nil {
		logg.LogPanic("Erro parsing the config file: %v", err)
	}
}
Exemple #5
0
func main() {
	//Parse command line flags
	var (
		_host    = kingpin.Flag("host", "Hostname").Short('h').Required().String()
		_port    = kingpin.Flag("port", "Port number").Short('p').Required().Int()
		_threads = kingpin.Flag("threads", "Thread count").Short('t').Default("1").Int()
		_size    = kingpin.Flag("size", "Packet Size").Short('s').Default("65507").Int()
	)
	kingpin.Parse()

	fullAddr := fmt.Sprintf("%s:%v", *_host, *_port)
	//Create send buffer
	var buf []byte = make([]byte, *_size)

	//Establish udp
	conn, err := net.Dial("udp", fullAddr)
	if err != nil {
		fmt.Println(err)
	} else {
		fmt.Printf("Flooding %s\n", fullAddr)
		for i := 0; i < *_threads; i++ {
			go func() {
				for {
					conn.Write(buf)
				}
			}()
		}
	}

	//Sleep forever
	<-make(chan bool, 1)
}
Exemple #6
0
func main() {
	kingpin.Parse()
	if *train {
		println("START")
		start := time.Now().UnixNano()
		ptrain := NewHMMParser("training/training.set")
		println("Training set loaded")
		ptrain.fParseTrainer()
		println("Training set trained")
		ptrain.Save()
		stop := time.Now().UnixNano()
		println("training delta", (stop-start)/1000, "mics")
	} else {
		println("Loading model " + *model)
		hmmParser := NewHMMParser(*model)
		hmmParser.Load()
		hmm := NewHMM(hmmParser)
		println("Model " + *model + " loaded")

		start := time.Now().UnixNano()
		ws := strings.Split("<s> "+*text, " ")
		hmm.fViterbi(ws)
		println(hmm.String())
		stop := time.Now().UnixNano()
		println("test delta", (stop-start)/1000, "mics")
	}
}
Exemple #7
0
func main() {
	kingpin.Parse()

	u, err := user.Lookup(*cliChownUser)
	if err != nil {
		panic(err)
	}

	g, err := user.Lookup(*cliChownGroup)
	if err != nil {
		panic(err)
	}

	uid, err = strconv.Atoi(u.Uid)
	if err != nil {
		panic(err)
	}

	gid, err = strconv.Atoi(g.Gid)
	if err != nil {
		panic(err)
	}

	// Ensure all folders and files are currently set to the correct permissions.
	filepath.Walk(*cliDir, update)

	// Now we will wait for
	watch(*cliDir)
}
Exemple #8
0
func main() {
	var (
		bcontent []byte
		content  string
		err      error
	)
	kingpin.Parse()
	if strings.HasPrefix(*infile, "wikipedia:") {
		log.Println("Fetching from wikipedia:", strings.TrimPrefix(*infile, "wikiedia:"))
		content, err = scrapedia.GetMainText("https://en.wikipedia.org/wiki/" + strings.TrimPrefix(*infile, "wikipedia:"))
	} else {
		// Default: assume plaintext file and load contents.
		log.Println("Opening plaintext file: " + *infile)
		bcontent, err = ioutil.ReadFile(*infile)
		content = string(bcontent)
	}
	if err != nil {
		log.Fatal(err.Error())
	}
	log.Println("Beginning at", *wpm, "words per minute..")
	took_seconds, total_wds, final_wpm, err := spritzlib.RenderSpritzed(string(content), *wpm, *boldText, colourNameToCode(*pivotColour), colourNameToCode(*plainColour), colourNameToCode(*bgColour))
	if err != nil {
		log.Fatal(err.Error())
	}
	log.Println("Finished reading", total_wds, "words in", took_seconds, "seconds")
	log.Println("Final wpm:", final_wpm)
}
Exemple #9
0
func main() {
	var err error

	kingpin.Parse()

	parsed, err := parseFile(*inputFile)
	fatalError(err)

	writer := NewAgentWriter(*interfaceName, *packageName, parsed)

	var out io.Writer
	if *outputFile == "" {
		out = os.Stdout
	} else {
		out, err = os.Create(*outputFile)
		fatalError(err)
	}

	WriteCodeGenerationWarning(out)
	writer.WritePackageName(out)
	WriteLibImport(out)

	writer.WriteAgentType(out)
	writer.WriteAgentMethods(out)
	writer.WriteAgentControl(out)
	writer.WriteRunLoop(out)

	for _, constructor := range *constructors {
		writer.WriteConstructor(out, constructor)
	}
}
Exemple #10
0
func main() {
	// Setup context
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	// Define a CLI
	dcConfig := &DCConfig{ServiceIdentifier: "omnivore"}

	kingpin.Flag("n", "The index of this node in the pool, if IPFS_POOL_PATH is set").Default("-1").Short('n').IntVar(&dcConfig.PoolIndex)

	var args []string
	kingpin.Arg("args", "arguments").StringsVar(&args)
	kingpin.Parse()

	// Build a node
	ipfsNode, err := BuildNode(ctx, dcConfig)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	fmt.Printf("I am node %s\n", ipfsNode.Identity.Pretty())

	// Respond to incoming providerIDs and streams
	// providerIDsIn, err := StartServiceDiscovery(ctx, ipfsNode, dcConfig)
	// if err != nil {
	// 	fmt.Println(err)
	// 	os.Exit(1)
	// }
	//
	// streamIn, err := StartListening(ipfsNode, dcConfig)
	// if err != nil {
	// 	fmt.Println(err)
	// 	os.Exit(1)
	// }
	//
	// for {
	// 	select {
	// 	case providerIDs := <-providerIDsIn:
	// 		for _, providerID := range providerIDs {
	// 			fmt.Printf("Provider: %s\n", providerID.Pretty())
	//
	// 			stream, err := corenet.Dial(ipfsNode, providerID, dcConfig.ServiceIdentifier)
	// 			if err != nil {
	// 				fmt.Printf("Failed to dial provider %s (%s)\n", providerID.Pretty(), err)
	// 				continue
	// 			}
	//
	// 			fmt.Fprintf(stream, "Hello! I'm peer %s\n", ipfsNode.Identity.Pretty())
	// 			stream.Close()
	// 		}
	//
	// 	case stream := <-streamIn:
	// 		fmt.Printf("Peer %s called!\n", stream.Conn().RemotePeer().Pretty())
	// 	}
	// }
}
Exemple #11
0
func main() {
	kingpin.CommandLine.Help = "An example implementation of curl."
	switch kingpin.Parse() {
	case "get":
		kingpin.FatalIfError(apply("GET", (*getURL).String()), "GET failed")

	case "post":
		kingpin.FatalIfError(applyPOST(), "POST failed")
	}
}
Exemple #12
0
func main() {
	kingpin.UsageTemplate(kingpin.CompactUsageTemplate).Version("1.0").Author("Alec Thomas")
	kingpin.CommandLine.Help = "An example implementation of curl."
	switch kingpin.Parse() {
	case "get url":
		kingpin.FatalIfError(apply("GET", (*getURLURL).String()), "GET failed")

	case "post":
		kingpin.FatalIfError(applyPOST(), "POST failed")
	}
}
Exemple #13
0
func main() {
	kingpin.Parse()

	config, err := config.LoadConfiguration(*configurationPath)
	if err != nil {
		log.Fatal(err)
	}

	youppi := slackscot.NewSlackscot([]slackscot.ExtentionBundle{brain.NewKarma(), brain.NewImager()})

	slackscot.Run(*youppi, *config)
}
Exemple #14
0
func main() {
	kingpin.Version("0.2.1")
	kingpin.Parse()

	switch *format {
	case "html":
		openBrowser()
	case "json":
		fetchJSON()
	default:
		openBrowser()
	}
}
func main() {
	kingpin.CommandLine.Help = "Docker container EC2 metadata service."
	kingpin.Parse()

	defer log.Flush()
	configureLogging(*verboseOpt)

	auth, err := aws.GetAuth("", "", "", time.Time{})

	if err != nil {
		panic(err)
	}

	containerService := NewContainerService(dockerClient(), *defaultRole, auth)

	// Proxy non-credentials requests to primary metadata service
	http.HandleFunc("/", logHandler(func(w http.ResponseWriter, r *http.Request) {
		match := credsRegex.FindStringSubmatch(r.URL.Path)
		if match != nil {
			handleCredentials(match[1], match[2], containerService, w, r)
			return
		}

		proxyReq, err := http.NewRequest(r.Method, fmt.Sprintf("%s%s", baseUrl, r.URL.Path), r.Body)

		if err != nil {
			log.Error("Error creating proxy http request: ", err)
			http.Error(w, "An unexpected error occurred communicating with Amazon", http.StatusInternalServerError)
			return
		}

		copyHeaders(proxyReq.Header, r.Header)
		resp, err := instanceServiceClient.RoundTrip(proxyReq)

		if err != nil {
			log.Error("Error forwarding request to EC2 metadata service: ", err)
			http.Error(w, "An unexpected error occurred communicating with Amazon", http.StatusInternalServerError)
			return
		}

		defer resp.Body.Close()

		copyHeaders(w.Header(), resp.Header)
		w.WriteHeader(resp.StatusCode)
		if _, err := io.Copy(w, resp.Body); err != nil {
			log.Warn("Error copying response content from EC2 metadata service: ", err)
		}
	}))

	log.Critical(http.ListenAndServe(*serverAddr, nil))
}
Exemple #16
0
func main() {
	kingpin.Version("0.1")
	kingpin.Parse()

	f, err := os.OpenFile(*logfile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)
	if err != nil {
		panic(err)
	}
	defer f.Close()

	LogInit(f)
	GetClusterReport(*conf)

}
Exemple #17
0
func main() {
	kingpin.Version("0.1")
	kingpin.Parse()

	ttyPath := *device

	fmt.Println("Writing packets to: " + ttyPath)
	fmt.Println("Packets are formatted all lower case hex, [src] [dest] [message...]")
	fmt.Println("Quote ascii strings for text conversion")

	serialConfig := &serial.Config{Name: ttyPath, Baud: 9600, Parity: serial.PARITY_EVEN}
	port, err := serial.OpenPort(serialConfig)
	if err != nil {
		panic(err)
	}

	go func() {
		parser := ibus.NewIbusPacketParser()
		for {
			buffer := make([]byte, 1)
			_, err := port.Read(buffer)
			if err != nil {
				panic(err)
			}
			parser.Push(buffer)
			if parser.HasPacket() {
				pkt := parser.GetPacket()
				// echo received packets to simulate bus broadcast
				port.Write(pkt.AsBytes())
				fmt.Println("\n<== " + pkt.AsString())
				fmt.Print("Enter IBUS packet: ")
			}
		}
	}()

	for {
		reader := bufio.NewReader(os.Stdin)
		fmt.Print("Enter IBUS packet: ")
		text, _ := reader.ReadString('\n')
		text = strings.TrimSpace(text)
		hexChars := strings.Split(text, " ")
		packet := new(ibus.IbusPacket)
		packet.Src = hexChars[0]
		packet.Dest = hexChars[1]
		packet.Message = hexChars[2:len(hexChars)]
		fmt.Println("==> " + packet.AsString())
		bytes := packet.AsBytes()
		port.Write(bytes)
	}
}
Exemple #18
0
func main() {
	bsize := kingpin.Flag("blocksize", "blocksize to test with").Default("262144").Int64()
	kingpin.Parse()

	ipfsdir := getIpfsDir()
	r, err := fsrepo.Open(ipfsdir)
	if err != nil {
		fmt.Printf("Failed to open ipfs repo at: %s: %s\n", ipfsdir, err)
		fmt.Println("Please ensure ipfs has been initialized and that no daemon is running")
		return
	}

	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	nd, err := core.NewNode(ctx, &core.BuildCfg{
		Repo: r,
	})
	if err != nil {
		fmt.Printf("failed to create node: %s\n", err)
		return
	}

	cfg := &BenchCfg{
		Blocksize: *bsize,
	}

	fmt.Println(cfg)
	err = BenchmarkBlockRewrites(nd, cfg)
	if err != nil {
		panic(err)
	}

	err = BenchmarkRandomBlockWrites(nd, cfg)
	if err != nil {
		panic(err)
	}

	err = BenchmarkAdd(nd, cfg)
	if err != nil {
		panic(err)
	}

	err = BenchmarkDiskWrites(ipfsdir)
	if err != nil {
		panic(err)
	}
}
Exemple #19
0
func main() {

	kingpin.Version("0.1")
	kingpin.Parse()

	f, err := os.OpenFile(*logfile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)
	if err != nil {
		panic(err)
	}
	defer f.Close()

	LogInit(*verbose, f)
	osd_sockets, err := filepath.Glob(*osd_sockets)
	if err != nil {
		log.Error("No sockets found exiting")
	}
	log.Info("Found following sockets", osd_sockets)
	c := make(chan perf)
	perfcounters := make([]PerfCounter, len(osd_sockets))

	for _, osd_socket := range osd_sockets {
		go func() {
			result, err := QueryAdminSocket(osd_socket)
			if err != nil {
				log.Fatal("Querying Socket failed with ", err)
			}
			c <- perf{*result, err}
		}()
		query := <-c
		if query.error == nil {
			perfcounters = append(perfcounters, query.PerfCounter)
			// perf_json, err := json.Marshal(query.PerfCounter)
			// if err == nil {
			// 	fmt.Println(string(perf_json))
			// }
			token, err := get_token()
			if err == nil {
				PostPerfCeilometer(token, query.PerfCounter)
			}

		}

	}
	GetClusterStatus(*conf)
	GetClusterIOPs(*conf)

}
Exemple #20
0
func parseFlags() {
	kingpin.HelpFlag.Short('h')
	kingpin.Version(versionMessage())
	kingpin.Flag("root", "root directory").Short('r').Default("./").StringVar(&gcfg.Root)
	kingpin.Flag("addr", "listen address").Short('a').Default(":8000").StringVar(&gcfg.Addr)
	kingpin.Flag("cert", "tls cert.pem path").StringVar(&gcfg.Cert)
	kingpin.Flag("key", "tls key.pem path").StringVar(&gcfg.Key)
	kingpin.Flag("httpauth", "HTTP basic auth (ex: user:pass)").Default("").StringVar(&gcfg.HttpAuth)
	kingpin.Flag("theme", "web theme, one of <black|green>").Default("black").StringVar(&gcfg.Theme)
	kingpin.Flag("upload", "enable upload support").BoolVar(&gcfg.Upload)
	kingpin.Flag("xheaders", "used when behide nginx").BoolVar(&gcfg.XHeaders)
	kingpin.Flag("cors", "enable cross-site HTTP request").BoolVar(&gcfg.Cors)
	kingpin.Flag("plistproxy", "plist proxy when server is not https").Default(defaultPlistProxy).Short('p').URLVar(&gcfg.PlistProxy)
	kingpin.Flag("title", "server title").Default("Go HTTP File Server").StringVar(&gcfg.Title)

	kingpin.Parse()
}
Exemple #21
0
func main() {
	kingpin.UsageTemplate(kingpin.DefaultUsageTemplate).Author("Cathal Garvey")
	//kingpin.CommandLine.Help = "miniLock-cli: The miniLock encryption system for terminal/scripted use."
	switch kingpin.Parse() {
	case "encrypt":
		kingpin.FatalIfError(encryptFile(), "Failed to encrypt..")
	case "decrypt":
		{
			kingpin.FatalIfError(decryptFile(), "Failed to decrypt..")
		}
	default:
		{
			fmt.Println("No subcommand provided..")
		}
	}
	if userKey != nil {
		userKey.Wipe()
	}
}
Exemple #22
0
func main() {
	kingpin.Version("1.3")
	kingpin.Parse()

	api := slack.New(*token)

	for {

		users, _ := api.UsersList()

		svc := ec2.New(session.New(), &aws.Config{Region: aws.String(*region)})

		// Call the DescribeInstances Operation
		resp, err := svc.DescribeInstances(nil)
		if err != nil {
			panic(err)
		}

		usersInstances := findLongRunningInstances(resp, users)
		alreadyNotified := getAlreadyNotified()

		for user, instances := range usersInstances {
			msg := ""
			for _, inst := range instances {
				if !contains(alreadyNotified, *inst.InstanceId) {
					msg += fmt.Sprintf("`%v - %v` with id _%v_\n", getTagValue(inst.Tags, "Purpose"), getTagValue(inst.Tags, "Name"), *inst.InstanceId)
					alreadyNotified = append(alreadyNotified, *inst.InstanceId)
				}
			}
			if msg != "" {
				msg := "\nYou have the following instances running in amazon:\n\n" + msg
				msg += "They were all started more then two days ago, are they still needed ?"
				if user == "U02HSGZ3F" || *prod { // ME
					err = api.ChatPostMessage(user, msg, &slack.ChatPostMessageOpt{Username: "******"})
				}

			}

		}
		saveAlreadyNotified(alreadyNotified)
		time.Sleep(time.Duration(*timeout) * time.Minute)
	}
}
func init() {
	// parse config file
	kingpin.Parse()
	if *configFileName == "" {
		kingpin.Errorf("Config file name missing")
		return
	}
	configFile, err := os.Open(*configFileName)
	if err != nil {
		logg.LogPanic("Unable to open file: %v.  Err: %v", *configFileName, err.Error())
		return
	}
	defer configFile.Close()

	configReader := bufio.NewReader(configFile)
	parseConfigFile(configReader)

	//set logging
	logg.LogKeys[logTag] = true
}
Exemple #24
0
func main() {
	kingpin.Parse()
	initRouters()

	http.Handle("/", m)

	addr := ":" + strconv.Itoa(gcfg.port)
	p := strconv.Itoa(gcfg.port)
	//mesg := "; please visit http://127.0.0.1:" + p
	if gcfg.private {
		addr = "localhost" + addr
		log.Printf("listens on 127.0.0.1@" + p) // + mesg)
	} else {
		log.Printf("listens on 0.0.0.0@" + p) // + mesg)
	}

	/*
		if gcfg.ftp {
			//log.Println("Enable FTP")
			auths := strings.SplitN(gcfg.ftpAuth, ":", 2)
			if len(auths) != 2 {
				log.Fatal("ftp auth format error")
			}
			auth := FTPAuth{auths[0], auths[1]}
			ftpserv := goftp.NewServer(&goftp.ServerOpts{
				Port:    gcfg.ftpPort,
				Factory: posixfs.NewPosixFSFactory(gcfg.root),
				Auth:    &auth,
			})
			go ftpserv.ListenAndServe()
		}
	*/

	var err error
	if gcfg.key != "" && gcfg.cert != "" {
		err = http.ListenAndServeTLS(addr, gcfg.cert, gcfg.key, nil)
	} else {
		err = http.ListenAndServe(addr, nil)
	}
	log.Fatal(err)
}
Exemple #25
0
func main() {
	kingpin.Parse()

	// This is a scheduled set of tasks which will unmount old directories which
	// are not being used by container instances.
	gocron.Every(15).Seconds().Do(Cleanup, *cliRoot)
	go gocron.Start()

	// Discovery the region which this instance resides. This will ensure the
	// EFS Filesystem gets created in the same region as this instance.
	metadata := ec2metadata.New(&ec2metadata.Config{})
	region, err := metadata.Region()
	if err != nil {
		panic(err)
	}

	// We need to determine which region this host lives in. That will allow us to spin
	// up EFS Filesystem within this region.
	e := ec2.New(&aws.Config{Region: aws.String(region)})

	i, err := metadata.GetMetadata("instance-id")
	if err != nil {
		panic(err)
	}

	subnet, err := GetSubnet(e, i)
	if err != nil {
		panic(err)
	}

	d := DriverEFS{
		Root:   *cliRoot,
		Region: region,
		Subnet: subnet,
	}
	h := dkvolume.NewHandler(d)
	log.Printf("Listening: %s", socketAddress)
	log.Println(h.ServeUnix("root", socketAddress))
}
Exemple #26
0
func main() {
	kingpin.Parse()

	opt := &install.InstallOption{}
	if *owner != "" {
		opt.Owner = *owner
	}
	if *group != "" {
		opt.Group = *group
	}
	if *mode != "" {
		m, err := strconv.ParseInt(*mode, 8, 32)
		if err != nil {
			fmt.Printf("invalid mode: %s", err)
			os.Exit(-1)
		}
		mode := os.FileMode(m)
		opt.Mode = &mode
	}

	args := *_args
	if *dir {
		for _, name := range args {
			install.InstallDir(name, opt)
		}
		return
	}

	sources := args[:len(args)-1]
	dst := args[len(args)-1]
	if len(sources) > 1 {
		if err := checkDst(dst); err != nil {
			fmt.Println(err.Error())
			os.Exit(-1)
		}
	}
	installFile(sources, dst, opt)
}
Exemple #27
0
func main() {
	kingpin.CommandLine.Help = "Docket Registry"
	kingpin.Parse()

	loc := *location
	if _, err := os.Stat(loc); os.IsNotExist(err) {
		os.Mkdir(loc, 0644)
	}

	var storeErr error

	store, storeErr = openStore()
	if storeErr != nil {
		log.Fatal("Failed to open data store: %v", storeErr)
	}
	deferCloseStore(store)

	pString := ":" + *port

	if err := http.ListenAndServe(pString, m); err != nil {
		log.Fatal(err)
	}
}
Exemple #28
0
func main() {
	log.SetFormatter(&log.TextFormatter{})

	kingpin.CommandLine.DefaultEnvars()
	kingpin.Parse()

	var queue lifecycled.Queue

	// provide a simulated queue for testing
	if *sqsQueue == simulateQueue {
		queue = lifecycled.NewSimulatedQueue(*instanceID)
	} else {
		queue = lifecycled.NewSQSQueue(*sqsQueue)
	}

	if *debug {
		log.SetLevel(log.DebugLevel)
	}

	signals := make(chan os.Signal)
	// signal.Notify(signals, os.Interrupt, os.Kill)

	daemon := lifecycled.Daemon{
		Queue:       queue,
		AutoScaling: autoscaling.New(session.New()),
		Handler:     *handler,
		Signals:     signals,
		InstanceID:  *instanceID,
	}

	err := daemon.Start()
	if err != nil {
		log.Error(err.Error())
		os.Exit(1)
	}
}
Exemple #29
0
func main() {
	kingpin.Version("0.0.1")
	kingpin.Parse()
	fmt.Printf("Would ping: %s with timeout %s and count %d", *ip, *timeout, *count)
}
Exemple #30
0
func main() {
	kingpin.Parse()

	var oldBuf string

	// Create a client which we can use to connect to the remote Kubernetes cluster.
	config := &client.Config{
		Host: *cliMaster,
	}
	client, err := client.New(config)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	// This ensures we don't overwhelm the Kubernetes API.
	t, err := time.ParseDuration(*cliRefresh)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	// This is an ongoing process to pull in new services.
	limiter := time.Tick(t)
	for {
		<-limiter

		// Get the data from the Kubernetes service API.
		log.Println("Refreshing data...")

		// This is the object which we will populate with new data.
		haproxy := Config{
			Port: *cliPort,
		}

		// Get a list of all the services.
		svcs, err := client.Services("").List(api.ListOptions{})
		if err != nil {
			log.Warn(err)
			continue
		}

		// Filter the list down to only the services we need.
		for _, s := range svcs.Items {
			// Only register services which are being balanced internally.
			if s.Spec.Type != "LoadBalancer" {
				log.Printf("Skipped service: %s", s.ObjectMeta.Name)
				continue
			}

			// Ensure we have the "domain" label set.
			if val, ok := s.ObjectMeta.Labels["domain"]; ok {
				// Get a list of all the pods and there IPs to add to the HAProxy.
				pods, err := client.Pods(s.ObjectMeta.Namespace).List(api.ListOptions{LabelSelector: labels.SelectorFromSet(labels.Set(s.Spec.Selector))})
				if err != nil {
					log.Println(err)
					continue
				}

				// Start building the new listener object.
				l := Listener{
					Domain: val,
				}

				// Populate the list of pod IPs.
				for _, p := range pods.Items {
					if p.Status.Phase != api.PodRunning {
						continue
					}
					l.Servers = append(l.Servers, Server{Name: p.ObjectMeta.Name, Address: p.Status.PodIP + ":80"})
				}

				haproxy.Listeners = append(haproxy.Listeners, l)
				log.Printf("Added service: %s", s.ObjectMeta.Name)
			}
		}

		// Attempt to rebuild the HAProxy configuration.
		t := template.Must(template.New("haproxy").Parse(tpl))
		buf := new(bytes.Buffer)
		err = t.Execute(buf, haproxy)
		if err != nil {
			log.Warn(err)
			continue
		}

		// Compare buffs.

		fmt.Println("Current")
		fmt.Println(buf.String())

		fmt.Println("Old")
		fmt.Println(oldBuf)

		if buf.String() == oldBuf {
			log.Warn("Configuration has not changed")
			continue
		}

		// Determine the current running HAProxy process.
		pid, err := ioutil.ReadFile(*cliPid)
		if err != nil {
			log.Warn(err)
			continue
		}

		// Write out the configuration to a file.
		err = ioutil.WriteFile(*cliConf, buf.Bytes(), 0644)
		if err != nil {
			log.Warn(err)
			continue
		}

		// Trigger a reload of the HAProxy service.
		if err := exec.Command("haproxy", "-f", *cliConf, "-p", *cliPid, "-D", "-sF", string(pid)).Run(); err != nil {
			log.Warn(err)
			continue
		}
	}
}