Exemple #1
0
func processGlobalFlags(c *cli.Context) time.Duration {
	var network string
	if c.GlobalBool("tcp") {
		network = "tcp"
	} else {
		network = "udp"
	}
	client, err := raidman.Dial(network, fmt.Sprintf("%s:%d", c.GlobalString("host"), c.GlobalInt("port")))
	if c.GlobalString("event-host") == "nil" {
		log.Panic("Failed to automatically get the hostname. Please specify it with --host")
	}
	if err != nil {
		log.Panicf("Failed to connect to the riemann host because %s", err)
	}
	attribute, err := processAttributes(c.GlobalStringSlice("attribute"))
	if err != nil {
		log.Panic(err)
	}
	eventTemplate := raidman.Event{
		Ttl:        float32(c.GlobalDuration("ttl").Seconds()),
		Tags:       c.GlobalStringSlice("tags"),
		Host:       c.GlobalString("event-host"),
		Attributes: attribute,
	}
	riemannSend = func(url, method string, duration float64) {
		event := eventTemplate
		event.Service = fmt.Sprintf("%s %s", url, method)
		event.Time = time.Now().Unix()
		event.Metric = duration
		client.Send(&event)
	}

	return c.GlobalDuration("interval")
}
Exemple #2
0
// MakeChain creates a chain manager from set command line flags.
func MakeChain(ctx *cli.Context) (chain *core.BlockChain, chainDb ethdb.Database) {
	datadir := MustMakeDataDir(ctx)
	cache := ctx.GlobalInt(CacheFlag.Name)
	handles := MakeDatabaseHandles()

	var err error
	if chainDb, err = ethdb.NewLDBDatabase(filepath.Join(datadir, "chaindata"), cache, handles); err != nil {
		Fatalf("Could not open database: %v", err)
	}
	if ctx.GlobalBool(OlympicFlag.Name) {
		_, err := core.WriteTestNetGenesisBlock(chainDb)
		if err != nil {
			glog.Fatalln(err)
		}
	}

	eventMux := new(event.TypeMux)
	pow := ethash.New()
	//genesis := core.GenesisBlock(uint64(ctx.GlobalInt(GenesisNonceFlag.Name)), blockDB)
	chain, err = core.NewBlockChain(chainDb, pow, eventMux)
	if err != nil {
		Fatalf("Could not start chainmanager: %v", err)
	}
	return chain, chainDb
}
Exemple #3
0
func cliStart(c *cli.Context) {
	config := nomadapi.DefaultConfig()
	config.Address = c.GlobalString("nomad-address")
	config.Region = c.GlobalString("nomad-region")
	config.WaitTime = time.Duration(c.GlobalInt("wait-time")) * time.Second
	client, err := nomadapi.NewClient(config)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	log := logrus.New()
	level, err := logrus.ParseLevel(c.GlobalString("log-level"))
	if err != nil {
		fmt.Println("incorrect log-level")
		os.Exit(2)
	}
	log.Out = os.Stderr
	log.Level = level

	usage := usage.NewUsage(client, time.Duration(c.GlobalInt("wait-time"))*time.Second, log)
	usage.Loop()

	context := api.NewContext(c.GlobalString("api-addr"), serviceVersion, usage, log, client)
	log.Fatal(api.ListenAndServe(context))

}
Exemple #4
0
// startNode boots up the system node and all registered protocols, after which
// it unlocks any requested accounts, and starts the RPC/IPC interfaces and the
// miner.
func startNode(ctx *cli.Context, stack *node.Node) {
	// Start up the node itself
	utils.StartNode(stack)

	// Unlock any account specifically requested
	var ethereum *eth.Ethereum
	if err := stack.Service(&ethereum); err != nil {
		utils.Fatalf("ethereum service not running: %v", err)
	}
	accman := ethereum.AccountManager()
	passwords := utils.MakePasswordList(ctx)

	accounts := strings.Split(ctx.GlobalString(utils.UnlockedAccountFlag.Name), ",")
	for i, account := range accounts {
		if trimmed := strings.TrimSpace(account); trimmed != "" {
			unlockAccount(ctx, accman, trimmed, i, passwords)
		}
	}
	// Start auxiliary services if enabled
	if ctx.GlobalBool(utils.MiningEnabledFlag.Name) {
		if err := ethereum.StartMining(ctx.GlobalInt(utils.MinerThreadsFlag.Name), ctx.GlobalString(utils.MiningGPUFlag.Name)); err != nil {
			utils.Fatalf("Failed to start mining: %v", err)
		}
	}
}
func storagepoolAgent(c *cli.Context) {
	healthCheckInterval := c.GlobalInt("healthcheck-interval")
	healthCheckBaseDir := c.GlobalString("healthcheck-basedir")
	healthCheckType := c.String("storagepool-healthcheck-type")

	cattleUrl := c.GlobalString("url")
	cattleAccessKey := c.GlobalString("access-key")
	cattleSecretKey := c.GlobalString("secret-key")
	if c.GlobalBool("debug") {
		log.SetLevel(log.DebugLevel)
	}

	storagepoolRootDir := c.GlobalString("storagepool-rootdir")
	driver := c.GlobalString("storagepool-driver")
	if driver == "" {
		log.Fatal("required field storagepool-driver has not been set")
	}

	cattleClient, err := cattle.NewCattleClient(cattleUrl, cattleAccessKey, cattleSecretKey)
	if err != nil {
		log.Fatal(err)
	}

	storagepoolAgent := NewStoragepoolAgent(healthCheckInterval, storagepoolRootDir, driver, healthCheckBaseDir, healthCheckType, cattleClient)

	metadataUrl := c.String("storagepool-metadata-url")

	if err := storagepoolAgent.Run(metadataUrl); err != nil {
		log.Fatal(err)
	}
}
Exemple #6
0
func startEth(ctx *cli.Context, eth *eth.Ethereum) {
	// Start Ethereum itself
	utils.StartEthereum(eth)

	am := eth.AccountManager()
	account := ctx.GlobalString(utils.UnlockedAccountFlag.Name)
	accounts := strings.Split(account, " ")
	for i, account := range accounts {
		if len(account) > 0 {
			if account == "primary" {
				utils.Fatalf("the 'primary' keyword is deprecated. You can use integer indexes, but the indexes are not permanent, they can change if you add external keys, export your keys or copy your keystore to another node.")
			}
			unlockAccount(ctx, am, account, i)
		}
	}
	// Start auxiliary services if enabled.
	if !ctx.GlobalBool(utils.IPCDisabledFlag.Name) {
		if err := utils.StartIPC(eth, ctx); err != nil {
			utils.Fatalf("Error string IPC: %v", err)
		}
	}
	if ctx.GlobalBool(utils.RPCEnabledFlag.Name) {
		if err := utils.StartRPC(eth, ctx); err != nil {
			utils.Fatalf("Error starting RPC: %v", err)
		}
	}
	if ctx.GlobalBool(utils.MiningEnabledFlag.Name) {
		if err := eth.StartMining(ctx.GlobalInt(utils.MinerThreadsFlag.Name)); err != nil {
			utils.Fatalf("%v", err)
		}
	}
}
Exemple #7
0
// fetch data for subreddits based on configuration provided
func load(configuration *Configuration, context *cli.Context) {

	timeout := time.Duration(context.GlobalInt("timeout"))
	jsonOut := context.GlobalBool("json")
	browserOut := context.GlobalBool("browser")
	port := context.GlobalString("port")

	if len(configuration.Subreddits) == 0 {
		log.Fatalln("No subreddits found")
	}

	results := make(chan *Subreddit, len(configuration.Subreddits))

	for _, subreddit := range configuration.Subreddits {
		go fetch(subreddit, results)
	}

	collect(results, configuration, timeout)

	if browserOut {
		browserOutput(configuration.Subreddits, port)
	} else if jsonOut {
		jsonOutput(configuration.Subreddits)
	} else {
		prettyOutput(configuration.Subreddits)
	}

}
Exemple #8
0
// As CheckCommonFlagsAndInit, but will return all parsed and verified common values, including an optional error
func CheckCommonFlags(c *cli.Context) (nr int, level api.Importance, filters []api.FileFilter, err error) {
	// Put parsed args in cmd and sanitize it
	nr = c.GlobalInt(StreamsPerInputDeviceFlagName)
	if nr < 1 {
		return 0, level, filters, fmt.Errorf("--%v must not be smaller than 1", StreamsPerInputDeviceFlagName)
	}

	level, err = api.ParseImportance(c.GlobalString(LogLevelFlagName))
	if err != nil {
		return
	}

	filterStr := c.GlobalString(FileExcludePatternFlagName)
	for _, fstr := range strings.Split(filterStr, ",") {
		if f, e := api.ParseFileFilter(fstr); e != nil {
			err = e
			return
		} else {
			filters = append(filters, f)
		}
	}

	err = parseAdditionalFlags(c)
	return
}
Exemple #9
0
// MakeChain creates a chain manager from set command line flags.
func MakeChain(ctx *cli.Context) (chain *core.ChainManager, chainDb common.Database) {
	datadir := ctx.GlobalString(DataDirFlag.Name)
	cache := ctx.GlobalInt(CacheFlag.Name)

	var err error
	if chainDb, err = ethdb.NewLDBDatabase(filepath.Join(datadir, "chaindata"), cache); err != nil {
		Fatalf("Could not open database: %v", err)
	}
	if ctx.GlobalBool(OlympicFlag.Name) {
		InitOlympic()
		_, err := core.WriteTestNetGenesisBlock(chainDb, 42)
		if err != nil {
			glog.Fatalln(err)
		}
	}

	eventMux := new(event.TypeMux)
	pow := ethash.New()
	//genesis := core.GenesisBlock(uint64(ctx.GlobalInt(GenesisNonceFlag.Name)), blockDB)
	chain, err = core.NewChainManager(chainDb, nil, pow, eventMux)
	if err != nil {
		Fatalf("Could not start chainmanager: %v", err)
	}

	proc := core.NewBlockProcessor(chainDb, pow, chain, eventMux)
	chain.SetProcessor(proc)
	return chain, chainDb
}
Exemple #10
0
func sftpSetup(c *cli.Context) (connector.Connection, error) {
	var (
		password           *string
		privateKeyFilepath *string
	)
	host := c.GlobalString("sftp-host")
	port := c.GlobalInt("sftp-port")
	remotePath := c.GlobalString("sftp-remote-path")
	username := c.GlobalString("sftp-username")
	passwordInput := os.Getenv("ARQ_SFTP_PASSWORD")
	if passwordInput != "" {
		password = &passwordInput
	} else {
		password = nil
	}
	if c.GlobalIsSet("sftp-private-key-filepath") {
		privateKey := c.GlobalString("sftp-private-key-filepath")
		privateKeyFilepath = &privateKey
	} else {
		privateKeyFilepath = nil
	}
	cacheDirectory := c.GlobalString("cache-directory")

	connection, err := connector.NewSFTPConnection(host, port, remotePath,
		username, password, privateKeyFilepath, cacheDirectory)
	if err != nil {
		log.Errorf("Error while establishing SFTP connection: %s", err)
		return connector.SFTPConnection{}, err
	}
	return *connection, nil
}
Exemple #11
0
// MakeChain creates a chain manager from set command line flags.
func MakeChain(ctx *cli.Context) (chain *core.ChainManager, blockDB, stateDB, extraDB common.Database) {
	dd := ctx.GlobalString(DataDirFlag.Name)
	var err error
	if blockDB, err = ethdb.NewLDBDatabase(filepath.Join(dd, "blockchain")); err != nil {
		Fatalf("Could not open database: %v", err)
	}
	if stateDB, err = ethdb.NewLDBDatabase(filepath.Join(dd, "state")); err != nil {
		Fatalf("Could not open database: %v", err)
	}
	if extraDB, err = ethdb.NewLDBDatabase(filepath.Join(dd, "extra")); err != nil {
		Fatalf("Could not open database: %v", err)
	}

	eventMux := new(event.TypeMux)
	pow := ethash.New()
	genesis := core.GenesisBlock(uint64(ctx.GlobalInt(GenesisNonceFlag.Name)), blockDB)
	chain, err = core.NewChainManager(genesis, blockDB, stateDB, pow, eventMux)
	if err != nil {
		Fatalf("Could not start chainmanager: %v", err)
	}

	proc := core.NewBlockProcessor(stateDB, extraDB, pow, chain, eventMux)
	chain.SetProcessor(proc)
	return chain, blockDB, stateDB, extraDB
}
Exemple #12
0
func (cli *CLI) init(ctx *cli.Context) error {
	if ctx.GlobalBool("prtg") {
		cli.Err, cli.Out = prtg.Err, prtg.Out
	}
	var err error
	if cli.cred, err = cli.Store.Load(); err == nil {
		cli.c, err = cli.Client(cli.cred.URL, cli.cred.User, cli.cred.Pass)
	}
	if err != nil {
		cli.cred = &Creds{ctx.GlobalString("addr"), ctx.GlobalString("user"), ctx.GlobalString("pass")}
		if cli.c, err = cli.Client(cli.cred.URL, cli.cred.User, cli.cred.Pass); err != nil {
			return err
		}
	}
	a, p, s, o := ctx.GlobalString("agent"), ctx.GlobalString("project"), ctx.GlobalString("stage"), ctx.GlobalString("output")
	if cli.a, err = regexp.Compile(a); err != nil {
		return err
	}
	if cli.p, err = regexp.Compile(p); err != nil {
		return err
	}
	if cli.s, err = regexp.Compile(s); err != nil {
		return err
	}
	if cli.o, err = regexp.Compile(o); err != nil {
		return err
	}
	if cli.d, err = time.ParseDuration(ctx.GlobalString("timeout")); err != nil {
		return err
	}
	cli.n, cli.rev = int64(ctx.GlobalInt("build")), ctx.GlobalString("revision")
	cli.c.SetTimeout(cli.d)
	return nil
}
Exemple #13
0
//Initialize the Siil API server
func StartAPIServer(c *cli.Context) {
	var (
		baseRouter *mux.Router
		port       int    = c.GlobalInt("port")
		tmplDir    string = fmt.Sprintf("%s/templates", c.GlobalString("wd"))
	)

	fmt.Printf("Starting API server on port %d...\n", port)
	if err := entity.CreateConnection(c.GlobalString("mysql")); err != nil {
		log.Fatal(err)
	}

	fmt.Println("Loading templates...")
	if t, err := ioutil.ReadDir(tmplDir); err != nil {
		log.Fatal(err)
	} else {
		for _, file := range t {
			name := fmt.Sprintf("%s/%s", tmplDir, file.Name())
			if template, err := raymond.ParseFile(name); err != nil {
				log.Panic(err)
			} else {
				templates[file.Name()] = template
			}
		}
	}

	site.SIIL_SITE_ID = c.GlobalString("sid")

	baseRouter = mux.NewRouter()

	//Root endpoint doesn't really do anything
	baseRouter.HandleFunc("/", handleRootRequest)
	baseRouter.HandleFunc("/success", handleSuccessRequest)
	baseRouter.HandleFunc("/fail", handleCancelRequest)

	//User primer & authentication handlers
	baseRouter.HandleFunc("/signin/{site:[a-zA-Z0-9]*}", handleSigninRequest)
	baseRouter.HandleFunc("/id/{site:[a-zA-Z0-9]*}", handleSessionCreation)

	//New site creation
	baseRouter.HandleFunc("/addsite", handleAddSiteForm)
	baseRouter.HandleFunc("/addsite/fail", handleAddSiteFormFailed)
	baseRouter.HandleFunc("/addsite/success", handleAddSiteSuccess)
	baseRouter.HandleFunc("/addsite/request", handleAddSiteRequest)

	//Edit site
	baseRouter.HandleFunc("/editsite/success", handleEditSiteSuccess)
	baseRouter.HandleFunc("/editsite/{site:[a-zA-Z0-9]*}", handleEditSiteForm)
	baseRouter.HandleFunc("/editsite/{site:[a-zA-Z0-9]*}/fail", handleEditSiteFormFailed)
	baseRouter.HandleFunc("/editsite/{site:[a-zA-Z0-9]*}/request", handleEditSiteRequest)

	//Invalidate sessions
	baseRouter.HandleFunc("/signout/{token:[a-zA-Z0-9]*}", handleSignoutRequest)

	baseRouter.HandleFunc("/api/session", handleAPISessionRequest)
	baseRouter.HandleFunc("/api/me", handleAPIMeRequest)

	http.ListenAndServe(fmt.Sprintf(":%d", port), baseRouter)
}
Exemple #14
0
// SetupVM configured the VM package's global settings
func SetupVM(ctx *cli.Context) {
	vm.EnableJit = ctx.GlobalBool(VMEnableJitFlag.Name)
	vm.ForceJit = ctx.GlobalBool(VMForceJitFlag.Name)
	vm.SetJITCacheSize(ctx.GlobalInt(VMJitCacheFlag.Name))
	if ctx.GlobalIsSet(VMDebugFlag.Name) {
		vm.Debug = ctx.GlobalBool(VMDebugFlag.Name)
	}
}
Exemple #15
0
func version(c *cli.Context) {
	fmt.Println(clientIdentifier)
	fmt.Println("Version:", verString)
	fmt.Println("Protocol Versions:", eth.ProtocolVersions)
	fmt.Println("Network Id:", c.GlobalInt(utils.NetworkIdFlag.Name))
	fmt.Println("Go Version:", runtime.Version())
	fmt.Println("OS:", runtime.GOOS)
	fmt.Printf("GOPATH=%s\n", os.Getenv("GOPATH"))
	fmt.Printf("GOROOT=%s\n", runtime.GOROOT())
}
Exemple #16
0
func StartRPC(eth *eth.Ethereum, ctx *cli.Context) error {
	config := rpc.RpcConfig{
		ListenAddress: ctx.GlobalString(RPCListenAddrFlag.Name),
		ListenPort:    uint(ctx.GlobalInt(RPCPortFlag.Name)),
		CorsDomain:    ctx.GlobalString(RPCCORSDomainFlag.Name),
	}

	xeth := xeth.New(eth, nil)
	return rpc.Start(xeth, config)
}
Exemple #17
0
// SetupEth configures the eth packages global settings
func SetupEth(ctx *cli.Context) {
	version := ctx.GlobalInt(EthVersionFlag.Name)
	for len(eth.ProtocolVersions) > 0 && eth.ProtocolVersions[0] > uint(version) {
		eth.ProtocolVersions = eth.ProtocolVersions[1:]
		eth.ProtocolLengths = eth.ProtocolLengths[1:]
	}
	if len(eth.ProtocolVersions) == 0 {
		Fatalf("No valid eth protocols remaining")
	}
}
Exemple #18
0
func ParseConfig(c *cli.Context) {
	config = Config{
		Source:    c.GlobalString("source"),
		Dest:      c.GlobalString("dest"),
		Workers:   c.GlobalInt("workers"),
		Batch:     c.GlobalInt("batch"),
		Prefix:    c.GlobalString("prefix"),
		ClearDest: c.GlobalBool("clear-dest"),
		DryRun:    c.GlobalBool("dry-run"),
	}
}
Exemple #19
0
func volumeAgent(c *cli.Context) {
	socket := c.String("socket")
	cattleUrl := c.GlobalString("url")
	cattleAccessKey := c.GlobalString("access-key")
	cattleSecretKey := c.GlobalString("secret-key")
	if c.GlobalBool("debug") {
		logrus.SetLevel(logrus.DebugLevel)
	}

	healthCheckInterval := c.GlobalInt("healthcheck-interval")
	healthCheckBaseDir := c.GlobalString("healthcheck-basedir")

	controlChan := make(chan bool, 1)

	storagepoolDir := c.GlobalString("storagepool-rootdir")

	storagepoolUuid := c.GlobalString("storagepool-uuid")
	var err error
	for {
		if storagepoolUuid != "" {
			break
		}
		spUuid, err := ioutil.ReadFile(filepath.Join(storagepoolDir, rootUuidFileName))
		if err != nil {
			logrus.Errorf("Error reading the storage pool uuid [%v]", err)
		} else {
			storagepoolUuid = string(spUuid)
			break
		}
		time.Sleep(5 * time.Second)
	}

	storagepoolName := c.GlobalString("storagepool-name")
	storagepoolDriver := c.GlobalString("storagepool-driver")
	if storagepoolDriver == "" {
		logrus.Fatal("required field storagepool-driver has not been set")
	}

	hostUuid := c.String("host-uuid")
	if hostUuid == "" {
		logrus.Fatal("required field host-uuid has not been set")
	}

	cattleClient, err := cattle.NewCattleClient(cattleUrl, cattleAccessKey, cattleSecretKey, storagepoolDriver, storagepoolName)
	if err != nil {
		logrus.Fatal(err)
	}

	volAgent := NewVolumeAgent(healthCheckBaseDir, socket, hostUuid, healthCheckInterval, cattleClient, storagepoolUuid)

	if err := volAgent.Run(controlChan); err != nil {
		logrus.Fatal(err)
	}
}
Exemple #20
0
func GetRedis(c *cli.Context) (*redis.Client, error) {
	redisOptions = &redis.Options{
		Addr:     c.GlobalString("redis"),
		Password: c.GlobalString("redis-password"),
		DB:       int64(c.GlobalInt("redis-db")),
	}

	client, err := GetRedisClient()

	logs.Trace.Printf("Connected to Redis Host %s/%d", c.GlobalString("redis"), c.GlobalInt("redis-db"))
	return client, err
}
Exemple #21
0
func common(c *cli.Context) error {
	if c.GlobalString("seed") == "" {
		cli.ShowAppHelp(c)
		os.Exit(1)
	}
	if c.GlobalInt("sequence") == 0 {
		cli.ShowAppHelp(c)
		os.Exit(1)
	}
	key = parseSeed(c.String("seed"))
	return nil
}
Exemple #22
0
func loadProfile(context *cli.Context, useEnvValues bool) (error, Profile) {
	location := fmt.Sprintf("%s/config/%s.json", baseDir, context.GlobalString("profile"))
	err, profile := loadProfileFromFile(location)
	if err != nil {
		return err, profile
	}

	profile.Name = trimSurroundingQuotes(context.GlobalString("profile"))

	if useEnvValues == false {
		return nil, profile
	}

	if region := trimSurroundingQuotes(context.GlobalString("region")); region != "" {
		profile.Region = region
	} else if profile.Region == "" {
		profile.Region = "eu-west-1"
	}

	if user := trimSurroundingQuotes(context.GlobalString("user")); user != "" {
		profile.User = user
	} else if profile.User == "" {
		profile.User = currentUsername
	}

	if cert := trimSurroundingQuotes(context.GlobalString("cert")); cert != "" {
		profile.CertLocation = cert
	}

	if maxCacheAge := context.GlobalInt("maxCacheAge"); maxCacheAge != -1 {
		profile.MaxCacheAge = maxCacheAge
	} else if profile.MaxCacheAge == 0 {
		profile.MaxCacheAge = 300
	}

	if prefix := trimSurroundingQuotes(context.String("prefix")); prefix != "" {
		profile.AliasPrefix = prefix
	}

	if awsProfile := trimSurroundingQuotes(context.GlobalString("awsProfile")); awsProfile != "" {
		profile.AWSProfile = awsProfile
	}

	if awsAccessKey := trimSurroundingQuotes(context.GlobalString("awsAccessKey")); awsAccessKey != "" {
		profile.AWSAccessKey = awsAccessKey
	}

	if awsSecretKey := trimSurroundingQuotes(context.GlobalString("awsSecretKey")); awsSecretKey != "" {
		profile.AWSSecretKey = awsSecretKey
	}

	return nil, profile
}
Exemple #23
0
func MainAction(c *cli.Context) {
	port := c.GlobalInt("port")
	appPort := strconv.Itoa(c.GlobalInt("appPort"))
	immediate = c.GlobalBool("immediate")

	// Bootstrap the environment
	envy.Bootstrap()

	// Set the PORT env
	os.Setenv("PORT", appPort)

	wd, err := os.Getwd()
	if err != nil {
		logger.Fatal(err)
	}

	builder := gin.NewBuilder(c.GlobalString("path"), c.GlobalString("bin"), c.GlobalBool("godep"))

	// fmt.Println(c.Args())
	runArgs := strings.Split(c.GlobalString("runArgs"), ",")
	fmt.Println(c.GlobalString("runArgs"))

	// runArgs = append([]string{}, "-env", "development")
	runner := gin.NewRunner(filepath.Join(wd, builder.Binary()), runArgs...)
	runner.SetWriter(os.Stdout)
	proxy := gin.NewProxy(builder, runner)
	excludeList := strings.Split(c.GlobalString("exclude"), ",")

	config := &gin.Config{
		Port:    port,
		ProxyTo: "http://localhost:" + appPort,
	}

	err = proxy.Run(config)
	if err != nil {
		logger.Fatal(err)
	}

	logger.Printf("listening on port %d\n", port)

	shutdown(runner)

	// build right now
	build(builder, runner, logger)

	// scan for changes

	scanChanges(c.GlobalString("path"), excludeList, func(path string) {
		runner.Kill()
		build(builder, runner, logger)
	})
}
Exemple #24
0
// MakeChainDatabase open an LevelDB using the flags passed to the client and will hard crash if it fails.
func MakeChainDatabase(ctx *cli.Context) ethdb.Database {
	var (
		datadir = MustMakeDataDir(ctx)
		cache   = ctx.GlobalInt(CacheFlag.Name)
		handles = MakeDatabaseHandles()
	)

	chainDb, err := ethdb.NewLDBDatabase(filepath.Join(datadir, "chaindata"), cache, handles)
	if err != nil {
		Fatalf("Could not open database: %v", err)
	}
	return chainDb
}
Exemple #25
0
func newClientFromContext(c *cli.Context) (*client.Client, error) {
	var (
		base      = c.GlobalString("host")
		dnsport   = c.GlobalInt("dnsport")
		dnsdomain = c.GlobalString("dnsdomain")
		secret    = c.GlobalString("secret")
	)
	s, e := client.NewClient(base, secret, dnsdomain, dnsport)
	if e == nil {
		s.DNS = c.Bool("d") // currently only defined when listing services
	}
	return s, e
}
Exemple #26
0
func version(c *cli.Context) {
	fmt.Println(ClientIdentifier)
	fmt.Println("Version:", Version)
	if gitCommit != "" {
		fmt.Println("Git Commit:", gitCommit)
	}
	fmt.Println("Protocol Versions:", exp.ProtocolVersions)
	fmt.Println("Network Id:", c.GlobalInt(utils.NetworkIdFlag.Name))
	fmt.Println("Go Version:", runtime.Version())
	fmt.Println("OS:", runtime.GOOS)
	fmt.Printf("GOPATH=%s\n", os.Getenv("GOPATH"))
	fmt.Printf("GOROOT=%s\n", runtime.GOROOT())
}
Exemple #27
0
func run(ctx *cli.Context) {
	vm.Debug = ctx.GlobalBool(DebugFlag.Name)
	vm.ForceJit = ctx.GlobalBool(ForceJitFlag.Name)
	vm.EnableJit = !ctx.GlobalBool(DisableJitFlag.Name)

	glog.SetToStderr(true)
	glog.SetV(ctx.GlobalInt(VerbosityFlag.Name))

	db, _ := ethdb.NewMemDatabase()
	statedb, _ := state.New(common.Hash{}, db)
	sender := statedb.CreateAccount(common.StringToAddress("sender"))
	receiver := statedb.CreateAccount(common.StringToAddress("receiver"))
	receiver.SetCode(common.Hex2Bytes(ctx.GlobalString(CodeFlag.Name)))

	vmenv := NewEnv(statedb, common.StringToAddress("evmuser"), common.Big(ctx.GlobalString(ValueFlag.Name)))

	tstart := time.Now()
	ret, e := vmenv.Call(
		sender,
		receiver.Address(),
		common.Hex2Bytes(ctx.GlobalString(InputFlag.Name)),
		common.Big(ctx.GlobalString(GasFlag.Name)),
		common.Big(ctx.GlobalString(PriceFlag.Name)),
		common.Big(ctx.GlobalString(ValueFlag.Name)),
	)
	vmdone := time.Since(tstart)

	if ctx.GlobalBool(DumpFlag.Name) {
		fmt.Println(string(statedb.Dump()))
	}
	vm.StdErrFormat(vmenv.StructLogs())

	if ctx.GlobalBool(SysStatFlag.Name) {
		var mem runtime.MemStats
		runtime.ReadMemStats(&mem)
		fmt.Printf("vm took %v\n", vmdone)
		fmt.Printf(`alloc:      %d
tot alloc:  %d
no. malloc: %d
heap alloc: %d
heap objs:  %d
num gc:     %d
`, mem.Alloc, mem.TotalAlloc, mem.Mallocs, mem.HeapAlloc, mem.HeapObjects, mem.NumGC)
	}

	fmt.Printf("OUT: 0x%x", ret)
	if e != nil {
		fmt.Printf(" error: %v", e)
	}
	fmt.Println()
}
Exemple #28
0
func MainAction(c *cli.Context) {
	laddr := c.GlobalString("laddr")
	port := c.GlobalInt("port")
	appPort := strconv.Itoa(c.GlobalInt("appPort"))
	immediate = c.GlobalBool("immediate")

	// Bootstrap the environment
	envy.Bootstrap()

	// Set the PORT env
	os.Setenv("PORT", appPort)

	wd, err := os.Getwd()
	if err != nil {
		logger.Fatal(err)
	}

	builder := gin.NewBuilder(c.GlobalString("path"), c.GlobalString("bin"), c.GlobalBool("godep"))
	runner := gin.NewRunner(filepath.Join(wd, builder.Binary()), c.Args()...)
	runner.SetWriter(os.Stdout)
	proxy := gin.NewProxy(builder, runner)

	config := &gin.Config{
		Laddr:   laddr,
		Port:    port,
		ProxyTo: "http://localhost:" + appPort,
	}

	err = proxy.Run(config)
	if err != nil {
		logger.Fatal(err)
	}

	if laddr != "" {
		logger.Printf("listening at %s:%d\n", laddr, port)
	} else {
		logger.Printf("listening on port %d\n", port)
	}

	shutdown(runner)

	// build right now
	build(builder, runner, logger)

	// scan for changes
	scanChanges(c.GlobalString("path"), func(path string) {
		runner.Kill()
		build(builder, runner, logger)
	})
}
Exemple #29
0
func sign(c *cli.Context, tx data.Transaction, sequence int32) {
	priv, err := key.GenerateAccountKey(sequence)
	checkErr(err)
	id, err := key.GenerateAccountId(sequence)
	checkErr(err)
	pub, err := priv.PublicAccountKey()
	checkErr(err)
	base := tx.GetBase()
	base.Sequence = uint32(c.GlobalInt("sequence"))
	base.SigningPubKey = new(data.PublicKey)
	if c.GlobalInt("lastledger") > 0 {
		base.LastLedgerSequence = new(uint32)
		*base.LastLedgerSequence = uint32(c.GlobalInt("lastledger"))
	}
	if base.Flags == nil {
		base.Flags = new(data.TransactionFlag)
	}
	copy(base.Account[:], id.Payload())
	copy(base.SigningPubKey[:], pub.Payload())
	if c.GlobalString("fee") != "" {
		fee, err := data.NewNativeValue(int64(c.GlobalInt("fee")))
		checkErr(err)
		base.Fee = *fee
	}
	tx.GetBase().TxnSignature = &data.VariableLength{}
	checkErr(data.Sign(tx, priv))
}
Exemple #30
0
func volumeAgent(c *cli.Context) {
	socket := c.String("socket")
	cattleUrl := c.GlobalString("url")
	cattleAccessKey := c.GlobalString("access-key")
	cattleSecretKey := c.GlobalString("secret-key")
	if c.GlobalBool("debug") {
		logrus.SetLevel(logrus.DebugLevel)
	}

	healthCheckInterval := c.GlobalInt("healthcheck-interval")
	healthCheckBaseDir := c.GlobalString("healthcheck-basedir")

	driver := c.GlobalString("storagepool-driver")
	if driver == "" {
		logrus.Fatal("required field storagepool-driver has not been set")
	}

	hostUuid := c.String("host-uuid")
	if hostUuid == "" {
		logrus.Fatal("required field host-uuid has not been set")
	}

	resultChan := make(chan error)

	go func(rc chan<- error) {
		cmdArgs := buildConvoyCmdArgs(c, socket)
		cmd := exec.Command("convoy", cmdArgs...)
		logrus.Infof("Launching convoy with args: %s", cmdArgs)
		cmd.Stdout = os.Stdout
		cmd.Stderr = os.Stderr
		err := cmd.Run()
		logrus.Infof("convoy exited with error: %v", err)
		rc <- err
	}(resultChan)

	go func(rc chan<- error) {
		controlChan := make(chan bool, 1)
		cattleClient, err := cattle.NewCattleClient(cattleUrl, cattleAccessKey, cattleSecretKey)
		if err != nil {
			rc <- fmt.Errorf("Error getting cattle client: %v", err)
		}
		volAgent := NewVolumeAgent(healthCheckBaseDir, socket, hostUuid, healthCheckInterval, cattleClient, driver)
		err = volAgent.Run(controlChan)
		logrus.Infof("volume-agent exited with error: %v", err)
		rc <- err
	}(resultChan)

	<-resultChan
	logrus.Info("Exiting.")
}