Beispiel #1
1
func sshCreate(ctx *cli.Context) {
	if len(ctx.Args()) != 2 {
		log.Fatal("Must provide name and public key file.")
	}

	tokenSource := &TokenSource{
		AccessToken: APIKey,
	}
	oauthClient := oauth2.NewClient(oauth2.NoContext, tokenSource)
	client := godo.NewClient(oauthClient)

	file, err := os.Open(ctx.Args()[1])
	if err != nil {
		log.Fatalf("Error opening key file: %s.", err)
	}

	keyData, err := ioutil.ReadAll(file)
	if err != nil {
		log.Fatalf("Error reading key file: %s.", err)
	}

	createRequest := &godo.KeyCreateRequest{
		Name:      ctx.Args().First(),
		PublicKey: string(keyData),
	}
	key, _, err := client.Keys.Create(createRequest)
	if err != nil {
		log.Fatal(err)
	}

	WriteOutput(key)
}
Beispiel #2
1
Datei: util.go Projekt: sreis/go
func startProfile() {
	if cpuprofile != "" {
		f, err := os.Create(cpuprofile)
		if err != nil {
			log.Fatalf("%v", err)
		}
		if err := pprof.StartCPUProfile(f); err != nil {
			log.Fatalf("%v", err)
		}
		AtExit(pprof.StopCPUProfile)
	}
	if memprofile != "" {
		if memprofilerate != 0 {
			runtime.MemProfileRate = int(memprofilerate)
		}
		f, err := os.Create(memprofile)
		if err != nil {
			log.Fatalf("%v", err)
		}
		AtExit(func() {
			runtime.GC() // profile all outstanding allocations
			if err := pprof.WriteHeapProfile(f); err != nil {
				log.Fatalf("%v", err)
			}
		})
	}
}
Beispiel #3
1
func urlShortenerMain(client *http.Client, argv []string) {
	if len(argv) != 1 {
		fmt.Fprintf(os.Stderr, "Usage: urlshortener http://goo.gl/xxxxx     (to look up details)\n")
		fmt.Fprintf(os.Stderr, "       urlshortener http://example.com/long (to shorten)\n")
		return
	}

	svc, _ := urlshortener.New(client)
	urlstr := argv[0]

	// short -> long
	if strings.HasPrefix(urlstr, "http://goo.gl/") || strings.HasPrefix(urlstr, "https://goo.gl/") {
		url, err := svc.Url.Get(urlstr).Do()
		if err != nil {
			log.Fatalf("URL Get: %v", err)
		}
		fmt.Printf("Lookup of %s: %s\n", urlstr, url.LongUrl)
		return
	}

	// long -> short
	url, err := svc.Url.Insert(&urlshortener.Url{
		Kind:    "urlshortener#url", // Not really needed
		LongUrl: urlstr,
	}).Do()
	if err != nil {
		log.Fatalf("URL Insert: %v", err)
	}
	fmt.Printf("Shortened %s => %s\n", urlstr, url.Id)
}
func Example_buildBinaryDeb() {

	pkg := deb.NewControlDefault("testpkg", "me", "me@a", "Dummy package for doing nothing", "testpkg is package ", true)
	exesMap := map[string][]string{
		"amd64": []string{filepath.Join(deb.TempDirDefault, "/a.amd64")},
		"i386":  []string{filepath.Join(deb.TempDirDefault, "/a.i386")},
		"armhf": []string{filepath.Join(deb.TempDirDefault, "/a.armhf")}}
	err := createExes(exesMap)
	if err != nil {
		log.Fatalf("%v", err)
	}
	artifacts, err := deb.NewWriters(pkg)
	if err != nil {
		log.Fatalf("Error building binary: %v", err)
	}
	artifacts[deb.ArchAmd64].MappedFiles = map[string]string{"/usr/bin/a": filepath.Join(deb.TempDirDefault, "/a.amd64")}
	artifacts[deb.ArchI386].MappedFiles = map[string]string{"/usr/bin/a": filepath.Join(deb.TempDirDefault, "/a.i386")}
	artifacts[deb.ArchArmhf].MappedFiles = map[string]string{"/usr/bin/a": filepath.Join(deb.TempDirDefault, "/a.armhf")}
	buildDeb := func(art *deb.Writer) error {
		//generate artifact here ...
		return nil
	}
	for arch, artifact := range artifacts {
		//build binary deb here ...
		err = buildDeb(artifact)
		if err != nil {
			log.Fatalf("Error building for '%s': %v", arch, err)
		}
	}
}
Beispiel #5
1
func translate(typedJson interface{}) interface{} {
	switch v := typedJson.(type) {
	case map[string]interface{}:
		if len(v) == 2 && in("type", v) && in("value", v) {
			return untag(v)
		}
		m := make(map[string]interface{}, len(v))
		for k, v2 := range v {
			m[k] = translate(v2)
		}
		return m
	case []interface{}:
		tabArray := make([]map[string]interface{}, len(v))
		for i := range v {
			if m, ok := translate(v[i]).(map[string]interface{}); ok {
				tabArray[i] = m
			} else {
				log.Fatalf("JSON arrays may only contain objects. This " +
					"corresponds to only tables being allowed in " +
					"TOML table arrays.")
			}
		}
		return tabArray
	}
	log.Fatalf("Unrecognized JSON format '%T'.", typedJson)
	panic("unreachable")
}
Beispiel #6
1
func ExampleClient_Listen() {
	config := &ClientConfig{
		User: "******",
		Auth: []AuthMethod{
			Password("password"),
		},
	}
	// Dial your ssh server.
	conn, err := Dial("tcp", "localhost:22", config)
	if err != nil {
		log.Fatalf("unable to connect: %s", err)
	}
	defer conn.Close()

	// Request the remote side to open port 8080 on all interfaces.
	l, err := conn.Listen("tcp", "0.0.0.0:8080")
	if err != nil {
		log.Fatalf("unable to register tcp forward: %v", err)
	}
	defer l.Close()

	// Serve HTTP with your SSH server acting as a reverse proxy.
	http.Serve(l, http.HandlerFunc(func(resp http.ResponseWriter, req *http.Request) {
		fmt.Fprintf(resp, "Hello world!\n")
	}))
}
Beispiel #7
1
func Load() Config {
	file, err := os.Open(Path())

	var wConfig Config

	if err != nil {
		log.Printf("Config file not found. Creating new...")
		err = CreateNewConfigFile()

		if err != nil {
			log.Fatalf("Unable to create new config file. Error: %v", err)
			os.Exit(1)
		}

		file, err = os.Open(Path())
		if err != nil {
			log.Fatalf("Unable to read new config file. Error: %v", err)
			os.Exit(1)
		}
	}

	defer file.Close()

	toml.DecodeReader(file, &wConfig)

	return wConfig
}
Beispiel #8
0
// Takes care of dropping privileges to the desired user
func changeUser(u string) {
	if u == "" {
		return
	}
	userent, err := utils.UserLookup(u)
	if err != nil {
		log.Fatalf("Unable to find user %v: %v", u, err)
	}

	uid, err := strconv.Atoi(userent.Uid)
	if err != nil {
		log.Fatalf("Invalid uid: %v", userent.Uid)
	}
	gid, err := strconv.Atoi(userent.Gid)
	if err != nil {
		log.Fatalf("Invalid gid: %v", userent.Gid)
	}

	if err := syscall.Setgid(gid); err != nil {
		log.Fatalf("setgid failed: %v", err)
	}
	if err := syscall.Setuid(uid); err != nil {
		log.Fatalf("setuid failed: %v", err)
	}
}
Beispiel #9
0
func main() {
	var statsdHost = flag.String("statsd_host", "127.0.0.1", "Statsd host")
	var statsdPort = flag.Int("statsd_port", 8125, "Statsd host")
	var nodename = flag.String("nodename", "riak", "Riak node name")
	var riakHost = flag.String("riak_host", "127.0.0.1", "Riak host")
	var riakHttpPort = flag.Int("riak_http_port", 8098, "Riak HTTP port")
	flag.Parse()

	// First ping to node to make sure it works
	err := pingRiak(*riakHost, *riakHttpPort)
	if err != nil {
		log.Fatalf("Error: %v", err)
		os.Exit(1)
	}
	statsd := fmt.Sprintf("%s:%d", *statsdHost, *statsdPort)
	addr, err := net.ResolveUDPAddr("udp", statsd)
	if err != nil {
		log.Fatalf("Couldn't resolve UDP addr: %v", err)
		os.Exit(1)
	}
	conn, err := net.DialUDP("udp", nil, addr)
	if err != nil {
		log.Fatalf("Couldn't connect to statsd at %s", statsd)
		os.Exit(1)
	}

	// every 60s run hit the stats endpoint and then send to statsd
	interval := time.NewTicker(time.Second * 60)
	for _ = range interval.C {
		go getAndSendRiakMetrics(conn, *nodename, *riakHost, *riakHttpPort)
	}
}
Beispiel #10
0
func main() {
	flag.Parse()

	if *flagVersion {
		fmt.Fprintf(os.Stderr, "hello version: %s\nGo version: %s (%s/%s)\n",
			buildinfo.Version(), runtime.Version(), runtime.GOOS, runtime.GOARCH)
		return
	}

	log.Printf("Starting hello version %s; Go %s (%s/%s)", buildinfo.Version(), runtime.Version(),
		runtime.GOOS, runtime.GOARCH)

	listenAddr, err := app.ListenAddress()
	if err != nil {
		log.Fatalf("Listen address: %v", err)
	}
	conf := appConfig()
	ws := webserver.New()
	ws.Handle("/", &helloHandler{who: conf.Word})
	// TODO(mpl): handle status requests too. Camlistore will send an auth
	// token in the extra config that should be used as the "password" for
	// subsequent status requests.
	if err := ws.Listen(listenAddr); err != nil {
		log.Fatalf("Listen: %v", err)
	}

	ws.Serve()
}
Beispiel #11
0
// Authorize is for remote authorization of headless machines.
//
// It expects 1 or 3 arguments
//
//   rclone authorize "fs name"
//   rclone authorize "fs name" "client id" "client secret"
func Authorize(args []string) {
	switch len(args) {
	case 1, 3:
	default:
		log.Fatalf("Invalid number of arguments: %d", len(args))
	}
	newType := args[0]
	fs, err := Find(newType)
	if err != nil {
		log.Fatalf("Failed to find fs: %v", err)
	}

	if fs.Config == nil {
		log.Fatalf("Can't authorize fs %q", newType)
	}
	// Name used for temporary fs
	name := "**temp-fs**"

	// Make sure we delete it
	defer DeleteRemote(name)

	// Indicate that we want fully automatic configuration.
	ConfigFile.SetValue(name, ConfigAutomatic, "yes")
	if len(args) == 3 {
		ConfigFile.SetValue(name, ConfigClientID, args[1])
		ConfigFile.SetValue(name, ConfigClientSecret, args[2])
	}
	fs.Config(name)
}
Beispiel #12
0
// Find all sibling pods in the service and post to their /write handler.
func contactOthers(state *State) {
	const waitTimeout = 2 * time.Minute
	defer state.doneContactingPeers()
	client, err := client.NewInCluster()
	if err != nil {
		log.Fatalf("Unable to create client; error: %v\n", err)
	}
	// Double check that that worked by getting the server version.
	if v, err := client.Discovery().ServerVersion(); err != nil {
		log.Fatalf("Unable to get server version: %v\n", err)
	} else {
		log.Printf("Server version: %#v\n", v)
	}

	for start := time.Now(); time.Since(start) < waitTimeout; time.Sleep(5 * time.Second) {
		eps := getWebserverEndpoints(client)
		if eps.Len() >= *peerCount {
			break
		}
		state.Logf("%v/%v has %v endpoints, which is less than %v as expected. Waiting for all endpoints to come up.", *namespace, *service, len(eps), *peerCount)
	}

	// Do this repeatedly, in case there's some propagation delay with getting
	// newly started pods into the endpoints list.
	for i := 0; i < 15; i++ {
		eps := getWebserverEndpoints(client)
		for ep := range eps {
			state.Logf("Attempting to contact %s", ep)
			contactSingle(ep, state)
		}
		time.Sleep(5 * time.Second)
	}
}
Beispiel #13
0
func main() {
	db, err := sql.Open("sqlite3", ":memory:")
	if err != nil {
		log.Fatalf("cannot open an SQLite memory database: %v", err)
	}
	defer db.Close()

	// sqlite> select strftime('%J', '2015-04-13T19:22:19.773Z'), strftime('%J', '2015-04-13T19:22:19');
	_, err = db.Exec("CREATE TABLE unix_time (time datetime)")
	if err != nil {
		log.Fatalf("cannot create schema: %v", err)
	}

	_, err = db.Exec("INSERT INTO unix_time (time) VALUES (strftime('%Y-%m-%dT%H:%MZ','now'))")
	if err != nil {
		log.Fatalf("cannot insert: %v", err)
	}

	row := db.QueryRow("SELECT time FROM unix_time")
	fmt.Printf("Rec: %v\nScan: ", *row)

	var t time.Time
	err = row.Scan(TimeStamp{&t})
	if err != nil {
		log.Fatalf("cannot scan time: %v", err)
	}
	fmt.Println(t)
}
Beispiel #14
0
func main() {
	flag.Parse()

	rpc.Register(new(Worker))
	l, e := net.Listen("tcp", ":"+strconv.Itoa(*port))
	if e != nil {
		log.Fatal("listen error:", e)
	}
	log.Print("listening for connections on ", l.Addr())

	if *connect != "" {
		log.Printf("calling %s\n", *connect)
		conn, err := net.Dial("tcp", *connect)
		if err != nil {
			log.Fatalf("failed to connect to %s: %s", *connect, err)
		}
		addr, _, err := net.SplitHostPort(conn.LocalAddr().String())
		if err != nil {
			log.Fatalf("failed to get the local address: %s", err)
		}
		laddr := net.JoinHostPort(addr, strconv.Itoa(*port))
		client := rpc.NewClient(conn)
		var res struct{}
		client.Call("WorkerList.Add", laddr, &res)
		client.Close()
	}

	rpc.Accept(l)
}
Beispiel #15
0
func main() {

	var x int32
	var y int32
	flag.Parse()
	conn, err := openTLSClient("127.0.0.1:8000")
	sum := addservice.NewAddServiceClient(conn)
	if err != nil {
		log.Fatalf("dial: %s", err)
	}

	for {
		fmt.Printf("Enter 2 numbers> ")
		fmt.Scan(&x)
		fmt.Scan(&y)
		fmt.Printf("Sending %d and %d\n", x, y)
		in := &addservice.AddMessage{X: &x, Y: &y}
		out := &addservice.SumMessage{}
		if err := sum.Add(in, out); err != nil {
			log.Fatalf("Add failed with: %s", err)
		}
		if out.Z == nil {
			log.Fatalf("Sum failed with no message returned")
		}
		fmt.Printf("Received %d\n\n", *out.Z)
	}
}
Beispiel #16
0
// NewTwitchLogger ...
func NewTwitchLogger(f func(m <-chan *common.Message)) *TwitchLogger {
	t := &TwitchLogger{
		chats:      make(map[int]*common.Twitch, 0),
		admins:     make(map[string]struct{}),
		logHandler: f,
	}

	admins := common.GetConfig().Twitch.Admins
	for _, a := range admins {
		t.admins[a] = struct{}{}
	}

	d, err := ioutil.ReadFile(common.GetConfig().Twitch.ChannelListPath)
	if err != nil {
		log.Fatalf("unable to read channels %s", err)
	}

	if err := json.Unmarshal(d, &t.channels); err != nil {
		log.Fatalf("unable to read channels %s", err)
	}

	t.commandChannel = common.GetConfig().Twitch.CommandChannel

	return t
}
Beispiel #17
0
func Init(conf map[string]interface{}) bl.Output {
	hosts := bl.GArrString("hosts", conf)
	if len(hosts) == 0 {
		log.Fatalf("[ERROR] [%s] There is no valid hosts", module)
	} else {
		timeout := int64(bl.GInt("timeout", conf))
		if timeout <= 0 {
			log.Fatalf("[ERROR] [%s] You must specify right timeout (%v)", module, timeout)
		} else {
			SSLCertificate := bl.GString("ssl_cert", conf)
			SSLKey := bl.GString("ssl_key", conf)
			SSLCA := bl.GString("ssl_ca", conf)
			tag := bl.GString("tag", conf)
			res := Out_logear_forwarder{
				tag:            tag,
				c:              make(chan *bl.Message),
				conn:           nil,
				hosts:          hosts,
				SSLCertificate: SSLCertificate,
				SSLKey:         SSLKey,
				SSLCA:          SSLCA,
				timeout:        time.Second * time.Duration(timeout)}
			res.loadCerts()
			return &res
		}
	}
	return nil
}
func main() {

	usage := `Couchbase-Fleet.

Usage:
  couchbase-fleet launch-cbs --version=<cb-version> --num-nodes=<num_nodes> --userpass=<user:pass> [--edition=<edition>] [--etcd-servers=<server-list>] [--docker-tag=<dt>] [--skip-clean-slate-check]
  couchbase-fleet stop [--all-units] [--etcd-servers=<server-list>]
  couchbase-fleet destroy [--all-units] [--etcd-servers=<server-list>]
  couchbase-fleet generate-units --version=<cb-version> --num-nodes=<num_nodes> --userpass=<user:pass> [--etcd-servers=<server-list>] [--docker-tag=<dt>] --output-dir=<output_dir>
  couchbase-fleet -h | --help

Options:
  -h --help     Show this screen.
  --version=<cb-version> Couchbase Server version (examples: latest, 3.0.3, 2.2).  The list of supported version corresponds to available tags on dockerhub: https://hub.docker.com/u/couchbase/server 
  --num-nodes=<num_nodes> number of couchbase nodes to start
  --userpass=<user:pass> the username and password as a single string, delimited by a colon (:)
  --edition=<edition> the edition to use, either "enterprise" or "community".  Defaults to "community" edition. 
  --etcd-servers=<server-list>  Comma separated list of etcd servers, or omit to connect to etcd running on localhost
  --docker-tag=<dt>  if present, use this docker tag for spawned containers, otherwise, default to "latest"
  --skip-clean-slate-check  if present, will skip the check that we are starting from clean state
  --output-dir=<output_dir>

`

	arguments, err := docopt.Parse(usage, nil, true, "Couchbase-Fleet", false)
	if err != nil {
		log.Fatalf("Failed to parse args: %v", err)
	}

	if cbcluster.IsCommandEnabled(arguments, "launch-cbs") {
		if err := launchCouchbaseServer(arguments); err != nil {
			log.Fatalf("Failed: %v", err)
		}
		return
	}

	if cbcluster.IsCommandEnabled(arguments, "generate-units") {
		if err := generateUnits(arguments); err != nil {
			log.Fatalf("Failed: %v", err)
		}
		return
	}

	if cbcluster.IsCommandEnabled(arguments, "stop") {
		if err := stopUnits(arguments); err != nil {
			log.Fatalf("Failed: %v", err)
		}
		return
	}

	if cbcluster.IsCommandEnabled(arguments, "destroy") {
		if err := destroyUnits(arguments); err != nil {
			log.Fatalf("Failed: %v", err)
		}
		return
	}

	log.Printf("Nothing to do!")

}
Beispiel #19
0
func ExampleSession_RequestPty() {
	// Create client config
	config := &ClientConfig{
		User: "******",
		Auth: []AuthMethod{
			Password("password"),
		},
	}
	// Connect to ssh server
	conn, err := Dial("tcp", "localhost:22", config)
	if err != nil {
		log.Fatalf("unable to connect: %s", err)
	}
	defer conn.Close()
	// Create a session
	session, err := conn.NewSession()
	if err != nil {
		log.Fatalf("unable to create session: %s", err)
	}
	defer session.Close()
	// Set up terminal modes
	modes := TerminalModes{
		ECHO:          0,     // disable echoing
		TTY_OP_ISPEED: 14400, // input speed = 14.4kbaud
		TTY_OP_OSPEED: 14400, // output speed = 14.4kbaud
	}
	// Request pseudo terminal
	if err := session.RequestPty("xterm", 80, 40, modes); err != nil {
		log.Fatalf("request for pseudo terminal failed: %s", err)
	}
	// Start remote shell
	if err := session.Shell(); err != nil {
		log.Fatalf("failed to start shell: %s", err)
	}
}
Beispiel #20
0
func setupBaseImage() {
	config := &DaemonConfig{
		Root:        unitTestStoreBase,
		AutoRestart: false,
		BridgeIface: unitTestNetworkBridge,
	}
	runtime, err := NewRuntimeFromDirectory(config)
	if err != nil {
		log.Fatalf("Unable to create a runtime for tests:", err)
	}

	// Create the "Server"
	srv := &Server{
		runtime:     runtime,
		pullingPool: make(map[string]struct{}),
		pushingPool: make(map[string]struct{}),
	}

	// If the unit test is not found, try to download it.
	if img, err := runtime.repositories.LookupImage(unitTestImageName); err != nil || img.ID != unitTestImageID {
		// Retrieve the Image
		if err := srv.ImagePull(unitTestImageName, "", os.Stdout, utils.NewStreamFormatter(false), nil, nil, true); err != nil {
			log.Fatalf("Unable to pull the test image:", err)
		}
	}
}
Beispiel #21
0
func (w *Walker) walkVar(vs *ast.ValueSpec) {
	for i, ident := range vs.Names {
		if !ast.IsExported(ident.Name) {
			continue
		}

		typ := ""
		if vs.Type != nil {
			typ = w.nodeString(vs.Type)
		} else {
			if len(vs.Values) == 0 {
				log.Fatalf("no values for var %q", ident.Name)
			}
			if len(vs.Values) > 1 {
				log.Fatalf("more than 1 values in ValueSpec not handled, var %q", ident.Name)
			}
			var err error
			typ, err = w.varValueType(vs.Values[i])
			if err != nil {
				log.Fatalf("unknown type of variable %q, type %T, error = %v\ncode: %s",
					ident.Name, vs.Values[i], err, w.nodeString(vs.Values[i]))
			}
		}
		w.emitFeature(fmt.Sprintf("var %s %s", ident, typ))
	}
}
Beispiel #22
0
func startNode(cfg *ServerConfig, ids []types.ID) (id types.ID, n raft.Node, s *raft.MemoryStorage, w *wal.WAL) {
	var err error
	member := cfg.Cluster.MemberByName(cfg.Name)
	metadata := pbutil.MustMarshal(
		&pb.Metadata{
			NodeID:    uint64(member.ID),
			ClusterID: uint64(cfg.Cluster.ID()),
		},
	)
	if err := os.MkdirAll(cfg.SnapDir(), privateDirMode); err != nil {
		log.Fatalf("etcdserver create snapshot directory error: %v", err)
	}
	if w, err = wal.Create(cfg.WALDir(), metadata); err != nil {
		log.Fatalf("etcdserver: create wal error: %v", err)
	}
	peers := make([]raft.Peer, len(ids))
	for i, id := range ids {
		ctx, err := json.Marshal((*cfg.Cluster).Member(id))
		if err != nil {
			log.Panicf("marshal member should never fail: %v", err)
		}
		peers[i] = raft.Peer{ID: uint64(id), Context: ctx}
	}
	id = member.ID
	log.Printf("etcdserver: start member %s in cluster %s", id, cfg.Cluster.ID())
	s = raft.NewMemoryStorage()
	n = raft.StartNode(uint64(id), peers, 10, 1, s)
	return
}
Beispiel #23
0
func main() {
	help := fmt.Sprintf("%s link|unlink elb1 elb2 ...", os.Args[0])
	args := os.Args[1:]
	if len(args) < 2 {
		log.Fatalf("Too few arguments: %s", help)
	}
	cmd := args[0]
	elbs := args[1:]
	announcer, err := NewAnnouncer()
	if err != nil {
		log.Fatal(err)
	}
	switch cmd {
	case "link":
		err = announcer.LinkELB(elbs...)
		if err != nil {
			log.Fatal(err)
		}
	case "unlink":
		err = announcer.UnlinkELB(elbs...)
		if err != nil {
			log.Fatal(err)
		}
	default:
		log.Fatalf("Command not recognized: %s, %s", cmd, help)
	}
}
Beispiel #24
0
// Main entry point for running fixr subcommand.
func runFixr(cmd *cobra.Command, args []string) {
	if len(args) < 1 {
		log.Fatalf("Must provide at least one directory argument to fixr.")
	}

	var files []fileInfo
	for _, dir := range args {
		fl, err := ioutil.ReadDir(dir)
		if err != nil {
			log.Fatalf("Failed to read directory '%v' with error %v\n", dir, err)
		}

		for _, f := range fl {
			if match, _ := regexp.MatchString("\\.json$", f.Name()); match && !f.IsDir() {
				files = append(files, fileInfo{d: dir, f: f})
			}
		}
	}

	if cmd.Flags().Lookup("prompt").Changed {
		runFixrInteractive(cmd, files)
	} else {
		runFixrBatch(cmd, files)
	}
}
Beispiel #25
0
func main() {
	// Inputs
	var (
		versionFilePathParam = flag.String("file", "", `Version file path`)
	)

	flag.Parse()

	if versionFilePathParam == nil || *versionFilePathParam == "" {
		log.Fatalf(" [!] No version file parameter specified")
	}
	versionFilePath := *versionFilePathParam

	// Main
	versionFileBytes, err := ioutil.ReadFile(versionFilePath)
	if err != nil {
		log.Fatalf("Failed to read version file: %s", err)
	}
	versionFileContent := string(versionFileBytes)

	re := regexp.MustCompile(`const VERSION = "(?P<version>[0-9]+\.[0-9-]+\.[0-9-]+)"`)
	results := re.FindAllStringSubmatch(versionFileContent, -1)
	versionStr := ""
	for _, v := range results {
		versionStr = v[1]
	}
	if versionStr == "" {
		log.Fatalf("Failed to determine version")
	}

	fmt.Println(versionStr)
}
Beispiel #26
0
func main() {
	var bindAddress string
	var port int

	flag.IntVar(&port, "port", 9125, "Port to listen on")
	flag.IntVar(&port, "p", 9125, "Port to listen on")

	flag.StringVar(&bindAddress, "bind", "0.0.0.0", "IP Address to listen on")
	flag.StringVar(&bindAddress, "b", "0.0.0.0", "IP Address to listen on")

	flag.StringVar(&prefix, "prefix", "statsrelay", "The prefix to use with self generated stats")

	flag.BoolVar(&verbose, "verbose", false, "Verbose output")
	flag.BoolVar(&verbose, "v", false, "Verbose output")

	flag.Parse()

	if len(flag.Args()) == 0 {
		log.Fatalf("One or most host specifications are needed to locate statsd daemons.\n")
	}

	hashRing = consistent.New()
	hashRing.NumberOfReplicas = 1

	for _, v := range flag.Args() {
		var addr *net.UDPAddr
		var err error
		host := strings.Split(v, ":")

		switch len(host) {
		case 1:
			log.Printf("Invalid statsd location: %s\n", v)
			log.Fatalf("Must be of the form HOST:PORT or HOST:PORT:INSTANCE\n")
		case 2:
			addr, err = net.ResolveUDPAddr("udp", v)
			if err != nil {
				log.Printf("Error parsing HOST:PORT \"%s\"\n", v)
				log.Fatalf("%s\n", err.Error())
			}
		case 3:
			addr, err = net.ResolveUDPAddr("udp", host[0]+":"+host[1])
			if err != nil {
				log.Printf("Error parsing HOST:PORT:INSTANCE \"%s\"\n", v)
				log.Fatalf("%s\n", err.Error())
			}
		default:
			log.Fatalf("Unrecongnized host specification: %s\n", v)
		}

		if addr != nil {
			udpAddr[v] = addr
			hashRing.Add(v)
		}
	}

	epochTime = time.Now().Unix()
	runServer(bindAddress, port)

	log.Printf("Normal shutdown.\n")
}
Beispiel #27
0
func init() {

	// find sqlite3 command
	sqlite3, err := exec.LookPath("sqlite3")
	if err != nil {
		log.Fatalf("error finding sqlite3 in system: %#v", err.Error())
	}
	log.Printf("sqlite3 path: %#v", sqlite3)

	// open the schema file
	file, err := os.Open("_test/schema.sqlite3.sql")
	if err != nil {
		log.Fatalf("error opening test schema: %#v", err.Error())
	}

	// initialize test database with sql file
	cmd := exec.Command(sqlite3, dbpath)
	var outstd bytes.Buffer
	var outerr bytes.Buffer

	cmd.Stdin = file
	cmd.Stdout = &outstd
	cmd.Stderr = &outerr

	if err := cmd.Run(); err != nil {
		log.Printf("output: %#v", outstd.String())
		log.Printf("error:  %#v", outerr.String())

		log.Fatalf("Failed to run sqlite command")
	}
}
Beispiel #28
0
func openTLSClient(ipPort string) (*tls.Conn, error) {

	// Note this loads standard x509 certificates, test keys can be
	// generated with makecert.sh

	log.Printf("Loading certificates from directory: %s\n", *certDir)
	cert, err := tls.LoadX509KeyPair(*certDir+"/server.pem", *certDir+"/server.key")
	if err != nil {
		log.Fatalf("server: loadkeys: %s", err)
	}
	// InsecureSkipVerify required for unsigned certs with Go1 and later.
	config := tls.Config{Certificates: []tls.Certificate{cert}, InsecureSkipVerify: true}
	conn, err := tls.Dial("tcp", ipPort, &config)
	if err != nil {
		log.Fatalf("client: dial: %s", err)
	}
	log.Println("client: connected to: ", conn.RemoteAddr())
	// This shows the public key of the server, we will accept any key, but
	// we could terminate the connection based on the public key if desired.
	state := conn.ConnectionState()
	for _, v := range state.PeerCertificates {
		log.Printf("Client: Server public key is:\n%x\n", v.PublicKey.(*rsa.PublicKey).N)

	}
	// Lets verify behind the doubt that both ends of the connection
	// have completed the handshake and negotiated a SSL connection
	log.Println("client: handshake: ", state.HandshakeComplete)
	log.Println("client: mutual: ", state.NegotiatedProtocolIsMutual)
	// All TLS handling has completed, now to pass the connection off to
	// go-rpcgen/protobuf/AddService
	return conn, err
}
Beispiel #29
0
// parsePackage analyzes the single package constructed from the named files.
// If text is non-nil, it is a string to be used instead of the content of the file,
// to be used for testing. parsePackage exits if there is an error.
func (g *Generator) parsePackage(directory string, names []string, text interface{}) {
	var files []*File
	var astFiles []*ast.File
	g.pkg = new(Package)
	fs := token.NewFileSet()
	for _, name := range names {
		if !strings.HasSuffix(name, ".go") {
			continue
		}
		parsedFile, err := parser.ParseFile(fs, name, text, 0)
		if err != nil {
			log.Fatalf("parsing package: %s: %s", name, err)
		}
		astFiles = append(astFiles, parsedFile)
		files = append(files, &File{
			file: parsedFile,
			pkg:  g.pkg,
		})
	}
	if len(astFiles) == 0 {
		log.Fatalf("%s: no buildable Go files", directory)
	}
	g.pkg.name = astFiles[0].Name.Name
	g.pkg.files = files
	g.pkg.dir = directory
	// Type check the package.
	g.pkg.check(fs, astFiles)
}
Beispiel #30
0
func init() {
	pr = func(string, string, bool, int) (string, bool, error) { return "passphrase", false, nil }
	keyStore := trustmanager.NewKeyMemoryStore(pr)
	cryptoService := cryptoservice.NewCryptoService("", keyStore)
	cryptoServices := signer.CryptoServiceIndex{data.ED25519Key: cryptoService, data.RSAKey: cryptoService, data.ECDSAKey: cryptoService}
	void = &pb.Void{}

	fakeHealth := func() map[string]string {
		return health
	}

	//server setup
	kms := &api.KeyManagementServer{CryptoServices: cryptoServices,
		HealthChecker: fakeHealth}
	ss := &api.SignerServer{CryptoServices: cryptoServices,
		HealthChecker: fakeHealth}
	grpcServer = grpc.NewServer()
	pb.RegisterKeyManagementServer(grpcServer, kms)
	pb.RegisterSignerServer(grpcServer, ss)
	lis, err := net.Listen("tcp", "127.0.0.1:7899")
	if err != nil {
		log.Fatalf("failed to listen %v", err)
	}

	go grpcServer.Serve(lis)

	//client setup
	conn, err := grpc.Dial("127.0.0.1:7899", grpc.WithInsecure())
	if err != nil {
		log.Fatalf("fail to dial: %v", err)
	}

	kmClient = pb.NewKeyManagementClient(conn)
	sClient = pb.NewSignerClient(conn)
}