Beispiel #1
1
func GetChain(ctx *cli.Context) (*core.ChainManager, common.Database, common.Database) {
	dataDir := ctx.GlobalString(DataDirFlag.Name)

	blockDb, err := ethdb.NewLDBDatabase(path.Join(dataDir, "blockchain"))
	if err != nil {
		Fatalf("Could not open database: %v", err)
	}

	stateDb, err := ethdb.NewLDBDatabase(path.Join(dataDir, "state"))
	if err != nil {
		Fatalf("Could not open database: %v", err)
	}

	extraDb, err := ethdb.NewLDBDatabase(path.Join(dataDir, "extra"))
	if err != nil {
		Fatalf("Could not open database: %v", err)
	}

	eventMux := new(event.TypeMux)
	chainManager := core.NewChainManager(blockDb, stateDb, eventMux)
	pow := ethash.New()
	txPool := core.NewTxPool(eventMux, chainManager.State, chainManager.GasLimit)
	blockProcessor := core.NewBlockProcessor(stateDb, extraDb, pow, txPool, chainManager, eventMux)
	chainManager.SetProcessor(blockProcessor)

	return chainManager, blockDb, stateDb
}
Beispiel #2
0
func cmdInit(c *cli.Context) error {
	username := c.Args().First()
	if username == "" {
		cli.ShowCommandHelp(c, "init")
		return cli.NewExitError("", 0)
	}

	password := c.Args().Get(1)
	if password == "" {
		pwd, err := askPass()
		if err != nil {
			if err != gopass.ErrInterrupted {
				return cli.NewExitError(err.Error(), 2)
			}
			return cli.NewExitError("", 2)
		}
		password = pwd
	}

	s, err := NewStore(c.GlobalString("store"), c.GlobalString("do-upgrades"),
		c.GlobalString("policy-type"), c.GlobalString("policy-condition"), c.GlobalString("hooks-dir"))
	if err != nil {
		return cli.NewExitError(fmt.Sprintf("Error initializing whawty store: %s", err), 3)
	}
	if err := s.GetInterface().Init(username, password); err != nil {
		return cli.NewExitError(fmt.Sprintf("Error initializing whawty store: %s", err), 3)
	}
	return cli.NewExitError(fmt.Sprintf("whawty store successfully initialized!"), 0)
}
Beispiel #3
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
}
func createImageCommandFunc(c *cli.Context) {
	var image string
	if len(c.Args()) == 0 {
		log.Fatal("You need to specify a image")
	} else {
		image = c.Args()[0]
	}

	clnt := client.New(c.GlobalString("server"))
	if c.GlobalBool("debug") {
		clnt.SetDebug()
	}

	s := client.Image{
		Image:     image,
		Type:      prompt.String("Type", prompt.Prompt{Default: "docker", FuncPtr: prompt.Enum, FuncInp: "file,docker"}),
		BootTagID: *chooseTag(clnt, ""),
	}

	// Is this correct?
	fmt.Println(string(s.JSON()))
	if !prompt.Bool("Is this correct", true) {
		os.Exit(1)
	}

	// Create image
	clnt.Image.Create(&s)
}
Beispiel #5
0
func makedag(ctx *cli.Context) {
	utils.CheckLegalese(ctx.GlobalString(utils.DataDirFlag.Name))

	args := ctx.Args()
	wrongArgs := func() {
		utils.Fatalf(`Usage: geth makedag <block number> <outputdir>`)
	}
	switch {
	case len(args) == 2:
		blockNum, err := strconv.ParseUint(args[0], 0, 64)
		dir := args[1]
		if err != nil {
			wrongArgs()
		} else {
			dir = filepath.Clean(dir)
			// seems to require a trailing slash
			if !strings.HasSuffix(dir, "/") {
				dir = dir + "/"
			}
			_, err = ioutil.ReadDir(dir)
			if err != nil {
				utils.Fatalf("Can't find dir")
			}
			fmt.Println("making DAG, this could take awhile...")
			ethash.MakeDAG(blockNum, dir)
		}
	default:
		wrongArgs()
	}
}
Beispiel #6
0
func blockRecovery(ctx *cli.Context) {
	utils.CheckLegalese(ctx.GlobalString(utils.DataDirFlag.Name))

	arg := ctx.Args().First()
	if len(ctx.Args()) < 1 && len(arg) > 0 {
		glog.Fatal("recover requires block number or hash")
	}

	cfg := utils.MakeEthConfig(ClientIdentifier, nodeNameVersion, ctx)
	utils.CheckLegalese(cfg.DataDir)

	blockDb, err := ethdb.NewLDBDatabase(filepath.Join(cfg.DataDir, "blockchain"), cfg.DatabaseCache)
	if err != nil {
		glog.Fatalln("could not open db:", err)
	}

	var block *types.Block
	if arg[0] == '#' {
		block = core.GetBlockByNumber(blockDb, common.String2Big(arg[1:]).Uint64())
	} else {
		block = core.GetBlockByHash(blockDb, common.HexToHash(arg))
	}

	if block == nil {
		glog.Fatalln("block not found. Recovery failed")
	}

	err = core.WriteHead(blockDb, block)
	if err != nil {
		glog.Fatalln("block write err", err)
	}
	glog.Infof("Recovery succesful. New HEAD %x\n", block.Hash())
}
Beispiel #7
0
func attach(ctx *cli.Context) {
	utils.CheckLegalese(ctx.GlobalString(utils.DataDirFlag.Name))

	var client comms.EthereumClient
	var err error
	if ctx.Args().Present() {
		client, err = comms.ClientFromEndpoint(ctx.Args().First(), codec.JSON)
	} else {
		cfg := comms.IpcConfig{
			Endpoint: ctx.GlobalString(utils.IPCPathFlag.Name),
		}
		client, err = comms.NewIpcClient(cfg, codec.JSON)
	}

	if err != nil {
		utils.Fatalf("Unable to attach to geth node - %v", err)
	}

	repl := newLightweightJSRE(
		ctx.GlobalString(utils.JSpathFlag.Name),
		client,
		true,
	)

	if ctx.GlobalString(utils.ExecFlag.Name) != "" {
		repl.batch(ctx.GlobalString(utils.ExecFlag.Name))
	} else {
		repl.welcome()
		repl.interactive()
	}
}
Beispiel #8
0
func push(c *cli.Context) {
	wd := ensureHome(c)
	pkg := a1(c, "No package name given")
	ver := a2(c, "Version is required")
	h := NewClient(c.GlobalString("host"))

	// Grab the latest version of the package from the server
	p, err := h.Get(pkg)
	if err != nil {
		die(err)
	}

	// Build a release
	r := &model.Release{
		Version:   ver,
		Author:    p.Author,
		Date:      time.Now(),
		PackageId: p.ID,
		Manifests: makeManifests(path.Join(wd, pkg)),
	}

	// Add it
	p.Releases = append([]*model.Release{r}, p.Releases...)

	info("Pushing %s %s to K8sPlace", pkg, ver)
	//d, _ := json.Marshal(p)
	//fmt.Println(string(d))
	if err := h.Update(p); err != nil {
		die(err)
	}
	ftw("Updated %s", p.Name)
}
Beispiel #9
0
// RecordGenerator abstracts from the way the strings are specified, e.g. via
// stdin a file or directly on the command line
func RecordGenerator(c *cli.Context) chan *Record {
	columnSpec, err := ParseColumnSpec(c.GlobalString("f"))
	if err != nil {
		log.Fatal(err)
	}
	// stdin
	if len(c.Args()) == 0 || (len(c.Args()) == 1 && c.Args()[0] == "-") {
		return RecordGeneratorFileDelimiter(os.Stdin, columnSpec, c.GlobalString("delimiter"))
	}
	// from filename
	if len(c.Args()) == 1 {
		filename := c.Args()[0]
		if _, err := os.Stat(filename); err == nil {
			file, err := os.Open(filename)
			if err != nil {
				log.Fatal(err)
			}
			return RecordGeneratorFile(file, columnSpec)
		}
		log.Fatalf("no such file: %s\n", filename)

	}
	// direct
	if len(c.Args()) == 2 {
		records := make(chan *Record)
		go func() {
			records <- &Record{Fields: c.Args(), left: 0, right: 1}
			close(records)
		}()
		return records
	}
	return nil
}
func (this *App) setup(c *cli.Context) error {
	if this.client == nil {
		this.client = api.NewClient(c.GlobalString("server"))
	}

	if this.user == nil {
		// try load user from config
		if this.config != nil && this.config.CurrentUser != "" {
			this.user, _ = this.store.FindUserByKey(this.config.CurrentUser)
		}

		// still not found
		if this.user == nil {
			this.user = this.selectCurrentUser()
		}
	}

	if this.user == nil {
		return ErrNoUser
	}

	if err := this.client.Register(this.user); err != nil {
		return err
	}

	// save config
	if this.config == nil {
		this.config = &AppConfig{
			CurrentUser: this.user.Key,
		}
		this.saveConfig(this.config)
	}

	return nil
}
// getConfigFilename gets the absolute filename of the config file specified by
// the ConfigFilename flag, and whether it exists.
//
// If the ConfigFilename exists, then it is returned as an absolute path.
// If neither of those exist, the absolute ConfigFilename is returned.
func getConfigFilename(context *cli.Context) (string, bool) {
	cf := context.GlobalString("config-filename")

	if filepath.IsAbs(cf) {
		// Absolute path specified; user knows what they want.
		_, err := os.Stat(cf)
		return cf, err == nil
	}

	absCF, err := filepath.Abs(cf)
	if err != nil {
		// syscall failure; treat as if file doesn't exist.
		return cf, false
	}
	if _, err := os.Stat(absCF); err == nil {
		// File exists on relative path.
		return absCF, true
	}

	// Check for config file on path relative to executable.
	exeFile := os.Args[0]
	exeDir := filepath.Dir(exeFile)
	absCF = filepath.Join(exeDir, cf)
	if _, err := os.Stat(absCF); err == nil {
		return absCF, true
	}

	// This is probably what the user expects if it wasn't found anywhere else.
	return absCF, false
}
Beispiel #12
0
// getConfigFilename gets the absolute filename of the config file specified by
// the ConfigFilename flag, and whether it exists.
//
// If the (relative or absolute) ConfigFilename exists, then it is returned.
// If the ConfigFilename exists in a valid XDG path, then it is returned.
// If neither of those exist, the (relative or absolute) ConfigFilename is returned.
func getConfigFilename(context *cli.Context) (string, bool) {
	cf := context.GlobalString("config-filename")

	if filepath.IsAbs(cf) {
		// Absolute path specified; user knows what they want.
		_, err := os.Stat(cf)
		return cf, err == nil
	}

	absCF, err := filepath.Abs(cf)
	if err != nil {
		// syscall failure; treat as if file doesn't exist.
		return cf, false
	}
	if _, err := os.Stat(absCF); err == nil {
		// File exists on relative path.
		return absCF, true
	}

	if xdgCF, err := xdg.Config.Find(cf); err == nil {
		// File exists in an XDG directory.
		return xdgCF, true
	}

	// Default to relative path. This is probably what the user expects if
	// it wasn't found anywhere else.
	return absCF, false
}
Beispiel #13
0
func installAction(ctx *cli.Context) {
	server := ctx.GlobalString("server")
	ref := ctx.String("ref")
	if len(ctx.Args()) == 0 {
		log.Fatal("Need args")
	}
	repo := ctx.Args().Get(0)
	log.Println(repo)

	u := url.URL{
		Scheme: "http",
		Host:   server,
	}

	// guess repo
	if !strings.Contains(repo, "/") {
		luckyURL := u
		luckyURL.Path = "/lucky/" + repo
		var err error
		repo, err = httpGetString(luckyURL.String())
		if err != nil {
			log.Fatal(err)
		}
		if repo == "" {
			log.Fatal("Guess repo failed, require fullname <owner/reponame>")
		}
	}
	log.Println("use repo:", repo)
	binURL := u
	binURL.Path = fmt.Sprintf("%s/%s/%s/%s", repo, ref, runtime.GOOS, runtime.GOARCH)
	getBinary(binURL, figureBinName(repo))
}
Beispiel #14
0
// Fetch returns exercism problems.
func Fetch(ctx *cli.Context) {
	c, err := config.New(ctx.GlobalString("config"))
	if err != nil {
		log.Fatal(err)
	}
	client := api.NewClient(c)

	problems, err := client.Fetch(ctx.Args())
	if err != nil {
		log.Fatal(err)
	}

	submissionInfo, err := client.Submissions()
	if err != nil {
		log.Fatal(err)
	}

	if err := setSubmissionState(problems, submissionInfo); err != nil {
		log.Fatal(err)
	}

	hw := user.NewHomework(problems, c)
	if err := hw.Save(); err != nil {
		log.Fatal(err)
	}

	hw.Summarize(user.HWAll)
}
Beispiel #15
0
func statusCmd(c *cli.Context) {
	migrationsPath := c.GlobalString("migrations")
	targetPath := c.GlobalString("target")

	migrationsPath, err := migrations.AbsMigrationsPath(migrationsPath)
	if err != nil {
		fmt.Printf("Error determining the migrations path: %s\n", err.Error())
		os.Exit(1)
	}

	list, err := migrations.List(migrationsPath)
	if err != nil {
		fmt.Printf("Error listing the available migrations: %s\n", err.Error())
		os.Exit(1)
	}

	timestamp, err := migrations.CurrentTimestamp(targetPath)
	if err != nil {
		fmt.Printf("Error reading the current timestamp: %s\n", err.Error())
		os.Exit(1)
	}

	if last := migrations.Last(list, timestamp); last != nil {
		fmt.Printf("Last migration executed: %s\n", last.Name)
	} else {
		fmt.Printf("No migration executed yet!\n")
	}

	fmt.Printf("Pending migrations: %d\n", len(migrations.Pending(list, timestamp)))
}
Beispiel #16
0
func cmdActive(c *cli.Context) {
	if len(c.Args()) > 0 {
		log.Fatal("Error: Too many arguments given.")
	}

	certInfo := getCertPathInfo(c)
	defaultStore, err := getDefaultStore(
		c.GlobalString("storage-path"),
		certInfo.CaCertPath,
		certInfo.CaKeyPath,
	)
	if err != nil {
		log.Fatal(err)
	}

	mcn, err := newMcn(defaultStore)
	if err != nil {
		log.Fatal(err)
	}

	host, err := mcn.GetActive()
	if err != nil {
		log.Fatalf("Error getting active host: %s", err)
	}

	if host != nil {
		fmt.Println(host.Name)
	}
}
Beispiel #17
0
func loginAction(c *cli.Context) {
	api := getAPI(c)
	var url string
	var version string
	var username string
	var password string
	fmt.Printf("URL: ")
	_, urlErr := fmt.Scanln(&url)
	if urlErr != nil {
		panic(urlErr)
	}
	fmt.Printf("Username: "******"Version (default: 1): ")
	_, verErr := fmt.Scanln(&version)
	if verErr != nil {
		version = "1"
	}
	userData, loginErr := api.Login(url, username, password)
	if loginErr != nil {
		LogMessage("Error logging in.  Please check username/password.", "r")
		os.Exit(1)
	}
	saveConfig(username, userData.ApiKey, url, version, c.GlobalString("config"))
	LogMessage("Login successful", "g")
}
Beispiel #18
0
// MustDataDir retrieves the currently requested data directory, terminating if
// none (or the empty string) is specified.
func MustDataDir(ctx *cli.Context) string {
	if path := ctx.GlobalString(DataDirFlag.Name); path != "" {
		return path
	}
	Fatalf("Cannot determine default data directory, please set manually (--datadir)")
	return ""
}
Beispiel #19
0
func get(c *cli.Context) {
	wd := ensureHome(c)
	pkg := a1(c, "No package name given")
	info("Getting %s", pkg)

	h := NewClient(c.GlobalString("host"))
	p, err := h.Get(pkg)
	if err != nil {
		die(err)
	}

	pdir := path.Join(wd, p.Name)

	if err := os.MkdirAll(pdir, 0755); err != nil {
		die(err)
	}

	if len(p.Releases) == 0 {
		info("There are no releases of %q.", pkg)
		ftw("Installed empty package %s into %q", p.Name, path.Join(wd, pdir))
		return
	}

	rel := p.Releases[0]
	info("Newest Version: %s", rel.Version)

	ftw("Installed %s %s into %q", p.Name, rel.Version, pdir)
}
Beispiel #20
0
// CartRemove removes an item from the cart
func CartRemove(c *cli.Context) {
	api := api.Create(c.GlobalString("locale"))

	conf := config.GetConfig()
	defer conf.Flush()

	cartName := conf.CartNameFromCache(c.Args().Get(1))

	cartItemID, exists := conf.CartItemIDFromCache(cartName, c.Args().First())
	if !exists {
		fmt.Fprintln(os.Stderr, "Cannot look up CartItemId")
		os.Exit(1)
	}

	cart, exists := conf.Carts[cartName]
	if !exists {
		fmt.Fprintln(os.Stderr, "Cannot look up Cart")
		os.Exit(1)
	}

	response, err := api.CartModify(cart.CartID, cart.HMAC, map[string]int{
		cartItemID: 0,
	})

	if err != nil {
		panic(err)
	}

	conf.Carts[cartName].HMAC = response.Cart.HMAC

	fmt.Printf("Removed item from cart %s\n", cartName)
}
Beispiel #21
0
func console(ctx *cli.Context) {
	utils.CheckLegalese(ctx.GlobalString(utils.DataDirFlag.Name))

	cfg := utils.MakeEthConfig(ClientIdentifier, nodeNameVersion, ctx)
	ethereum, err := eth.New(cfg)
	if err != nil {
		utils.Fatalf("%v", err)
	}

	client := comms.NewInProcClient(codec.JSON)

	startEth(ctx, ethereum)
	repl := newJSRE(
		ethereum,
		ctx.GlobalString(utils.JSpathFlag.Name),
		ctx.GlobalString(utils.RPCCORSDomainFlag.Name),
		client,
		true,
		nil,
	)

	if ctx.GlobalString(utils.ExecFlag.Name) != "" {
		repl.batch(ctx.GlobalString(utils.ExecFlag.Name))
	} else {
		repl.welcome()
		repl.interactive()
	}

	ethereum.Stop()
	ethereum.WaitForShutdown()
}
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)
	}
}
Beispiel #23
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)
		}
	}
}
Beispiel #24
0
func preload(context *cli.Context) error {
	if context.GlobalBool("debug") {
		logger.Level = logrus.DebugLevel
	}
	config = loadConfig(context.GlobalString("config"))
	return nil
}
Beispiel #25
0
func runBot(c *cli.Context) {
	var (
		Sapi     *slack.Slack
		cfg      *config.Config
		cfg_path string
		err      error
		wg       sync.WaitGroup
	)
	cfg_path = c.GlobalString("config")
	Log.Info("Config '%s' will be loaded.", cfg_path)
	cfg, err = config.New(cfg_path)
	if err != nil {
		Log.Error("Config processing error: %s", err)
		return
	}

	Sapi = slack.New(&cfg.Janus)
	Sapi.Connect()
	// start Messsage loop
	wg.Add(1)
	go func() {
		defer wg.Done()
		Sapi.MessageLoop()
	}()
	// start Channel info loop
	wg.Add(1)
	go func() {
		defer wg.Done()
		Sapi.ChannelLoop()
	}()
	// all loops started
	wg.Wait()

}
Beispiel #26
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)
	}

}
Beispiel #27
0
// Status is a command that allows a user to view their progress in a given
// language track.
func Status(ctx *cli.Context) {
	c, err := config.New(ctx.GlobalString("config"))
	if err != nil {
		log.Fatal(err)
	}
	args := ctx.Args()

	if len(args) != 1 {
		fmt.Fprintf(os.Stderr, "Usage: exercism status TRACK_ID")
		os.Exit(1)
	}

	client := api.NewClient(c)
	trackID := args[0]
	status, err := client.Status(trackID)
	if err != nil {
		if err == api.ErrUnknownTrack {
			log.Fatalf("There is no track with ID '%s'.", trackID)
		} else {
			log.Fatal(err)
		}
	}

	fmt.Println(status)
}
Beispiel #28
0
func remove(c *cli.Context) {
	if l := len(c.Args()); l != 1 {
		oserrf("error: expected 1 argument, got %d", l)
		return
	}

	cfgPath, err := tenetCfgPath(c)
	if err != nil {
		oserrf("reading config file: %s", err.Error())
		return
	}
	cfg, err := buildConfig(cfgPath, CascadeNone)
	if err != nil {
		oserrf("reading config file: %s", err.Error())
		return
	}

	imageName := c.Args().First()

	if !cfg.HasTenet(imageName) {
		oserrf(`error: tenet "%s" not found in %q`, imageName, c.GlobalString(tenetCfgFlg.long))
		return
	}

	if err := cfg.RemoveTenet(imageName, c.String("group")); err != nil {
		oserrf(err.Error())
		return
	}

	if err := writeConfigFile(c, cfg); err != nil {
		oserrf(err.Error())
		return
	}
}
Beispiel #29
0
// MakeNAT creates a port mapper from set command line flags.
func MakeNAT(ctx *cli.Context) nat.Interface {
	natif, err := nat.Parse(ctx.GlobalString(NATFlag.Name))
	if err != nil {
		Fatalf("Option %s: %v", NATFlag.Name, err)
	}
	return natif
}
Beispiel #30
0
func cmdRun(c *cli.Context) error {
	s, err := openAndCheck(c)
	if err != nil {
		return cli.NewExitError(err.Error(), 3)
	}

	webAddr := c.String("web-addr")
	saslPaths := c.StringSlice("sock")

	var wg sync.WaitGroup
	if webAddr != "" {
		wg.Add(1)
		go func() {
			defer wg.Done()
			if err := runWebAddr(webAddr, s.GetInterface(), c.GlobalString("web-static-dir")); err != nil {
				fmt.Printf("warning running web interface failed: %s\n", err)
			}
		}()
	}
	for _, path := range saslPaths {
		p := path
		wg.Add(1)
		go func() {
			defer wg.Done()
			if err := runSaslAuthSocket(p, s.GetInterface()); err != nil {
				fmt.Printf("warning running auth agent(%s) failed: %s\n", p, err)
			}
		}()
	}
	wg.Wait()

	return cli.NewExitError(fmt.Sprintf("shutting down since all auth sockets have closed."), 0)
}