// Run runs the command to delete a host.
559063
func (c *DeleteHostCmd) Run(app subcommands.Application, args []string, env subcommands.Env) int {
	ctx := cli.GetContext(app, c, env)
	// TODO(smut): Validate required fields client-side.
	client := getClient(ctx)
	_, err := client.DeleteHost(ctx, &c.req)
	if err != nil {
		errors.Log(ctx, err)
		return 1
	}
	return 0
}
111979
func (c *removeCommand) Run(ctx *cmd.Context) error {
	if err := c.validateIaasController(c.Info().Name); err != nil {
		return errors.Trace(err)
	}
	if c.Log != nil {
		if err := c.Log.Start(ctx); err != nil {
			return err
		}
	}

	client, apiVersion, err := c.NewGetAPI()
	if err != nil {
		return errors.Trace(err)
	}
	defer client.Close()

	if apiVersion < 2 && c.KeepLatest {
		return errors.New("--keep-latest is not supported by this controller")
	}
	//ctx.Infof("apiversion %d", apiVersion)

	ids := []string{}
	var keep string
	if c.KeepLatest {
		list, err := client.List()
		if err != nil {
			return errors.Trace(err)
		}

		ids, keep, err = parseList(list.List)
		switch {
		case err != nil:
			return errors.Trace(err)
		case len(ids) > 0:
			break
		case keep != "":
			ctx.Warningf("no backups to remove, %v most current", keep)
			return nil
		default:
			ctx.Warningf("no backups to remove")
			return nil
		}
	} else {
		ids = append(ids, c.ID)
	}
	//ctx.Infof("%s; %+v", keep, ids)

	results, err := client.Remove(ids...)
	if err != nil {
		return errors.Trace(err)
	}

	for i, err := range results {
		if err.Error != nil {
			// Some errors do not provide enough info, let's try to fix that here.
			err.Error.Message = fmt.Sprintf("failed to remove %v: %s", ids[i], err.Error.Message)
			continue
		}
		ctx.Infof("successfully removed: %v\n", ids[i])
	}
	if c.KeepLatest {
		ctx.Infof("kept: %v", keep)
	}
	return errors.Trace(params.ErrorResults{results}.Combine())
}
584783
func (c *container) Run(cmds []string, targeted bool, detachFlag bool) {
	adHoc := (len(cmds) > 0)
	if !adHoc {
		c.Rm(true, false)
	}
	msg := "Running container %s"
	if adHoc {
		msg += " (ad-hoc)"
	}
	fmt.Fprintf(c.CommandsOut(), msg+" ...\n", c.ActualName(adHoc))

	args := append([]string{"create"}, c.createArgs(cmds)...)
	// Hide output of container ID, the name of the container
	// is printed later anyway when it is started.
	executeCommand("docker", args, nil, c.CommandsErr())

	c.connectWithNetworks(adHoc)

	c.start(adHoc, targeted, detachFlag)
}
347648
func (c *enableCommand) Run(_ *cmd.Context) error {
	api, err := c.apiFunc(c)
	if err != nil {
		return errors.Annotate(err, "cannot connect to the API")
	}
	defer api.Close()

	return api.SwitchBlockOff(c.target)
}
903420
func (c *CmdSimpleFSDebug) Run() error {
	cli, err := GetSimpleFSClient(c.G())
	if err != nil {
		return err
	}

	return cli.SimpleFSDumpDebuggingInfo(context.TODO())
}
169351
func (cmd *Command) Run(args []string) {
	cmd.Flags.SetOutput(ioutil.Discard)

	err := cmd.Flags.Parse(args)
	if err != nil {
		cmd.Usage()
		fmt.Fprintf(os.Stderr, "\nError: %v\n", err)
		os.Exit(2)
	}
	subArgs := cmd.Flags.Args()

	if len(subArgs) == 0 {
		cmd.Action(cmd, subArgs)
		return
	}

	name := subArgs[0]
	for _, subcmd := range cmd.Subcmds {
		if subcmd.Name() == name {
			subcmd.Run(subArgs[1:])
			return
		}
	}

	cmd.Action(cmd, subArgs)
}
564707
func (c *configCommand) Run(ctx *cmd.Context) error {
	client, err := c.getAPI()
	if err != nil {
		return errors.Trace(err)
	}
	defer func() { _ = client.Close() }()

	if len(c.resetKeys) > 0 {
		if err := c.resetConfig(client, ctx); err != nil {
			// We return this error naked as it is almost certainly going to be
			// cmd.ErrSilent and the cmd.Command framework expects that back
			// from cmd.Run if the process is blocked.
			return err
		}
	}
	if c.action == nil {
		// If we are reset only, we end up here; we have already done that.
		return nil
	}

	return c.action(client, ctx)
}
436703
func (c *listKeysCommand) Run(context *cmd.Context) error {
	client, err := c.NewKeyManagerClient()
	if err != nil {
		return err
	}
	defer client.Close()

	mode := ssh.Fingerprints
	if c.showFullKey {
		mode = ssh.FullKeys
	}
	// TODO(alexisb) - currently keys are global which is not ideal.
	// keymanager needs to be updated to allow keys per user
	c.user = "admin"
	results, err := client.ListKeys(mode, c.user)
	if err != nil {
		return errors.Trace(err)
	}
	result := results[0]
	if result.Error != nil {
		return errors.Trace(result.Error)
	}
	if len(result.Result) == 0 {
		context.Infof("No keys to display.")
		return nil
	}
	modelName, err := c.ModelName()
	if err != nil {
		return errors.Trace(err)
	}
	fmt.Fprintf(context.Stdout, "Keys used in model: %s\n", modelName)
	fmt.Fprintln(context.Stdout, strings.Join(result.Result, "\n"))
	return nil
}
1329161
func (cmd *Command) Run(args ...string) error {
	fs := flag.NewFlagSet("buildtsi", flag.ExitOnError)
	dataDir := fs.String("datadir", "", "data directory")
	walDir := fs.String("waldir", "", "WAL directory")
	fs.IntVar(&cmd.concurrency, "concurrency", runtime.GOMAXPROCS(0), "Number of workers to dedicate to shard index building. Defaults to GOMAXPROCS")
	fs.StringVar(&cmd.databaseFilter, "database", "", "optional: database name")
	fs.StringVar(&cmd.retentionFilter, "retention", "", "optional: retention policy")
	fs.StringVar(&cmd.shardFilter, "shard", "", "optional: shard id")
	fs.Int64Var(&cmd.maxLogFileSize, "max-log-file-size", tsi1.DefaultMaxIndexLogFileSize, "optional: maximum log file size")
	fs.Uint64Var(&cmd.maxCacheSize, "max-cache-size", tsm1.DefaultCacheMaxMemorySize, "optional: maximum cache size")
	fs.IntVar(&cmd.batchSize, "batch-size", defaultBatchSize, "optional: set the size of the batches we write to the index. Setting this can have adverse affects on performance and heap requirements")
	fs.BoolVar(&cmd.Verbose, "v", false, "verbose")
	fs.SetOutput(cmd.Stdout)
	if err := fs.Parse(args); err != nil {
		return err
	} else if fs.NArg() > 0 || *dataDir == "" || *walDir == "" {
		fs.Usage()
		return nil
	}
	cmd.Logger = logger.New(cmd.Stderr)

	return cmd.run(*dataDir, *walDir)
}
453592
func (c *CmdSimpleFSClearConflicts) Run() error {
	cli, err := GetSimpleFSClient(c.G())
	if err != nil {
		return err
	}

	return cli.SimpleFSClearConflictState(context.TODO(), c.path)
}
528087
func (cmd *ExportCommand) Run(ctx context.Context) error {
	logger := log.New(cmd.Stderr, "", log.LstdFlags)

	// Validate arguments.
	if cmd.Index == "" {
		return pilosa.ErrIndexRequired
	} else if cmd.Field == "" {
		return pilosa.ErrFieldRequired
	}

	// Use output file, if specified.
	// Otherwise use STDOUT.
	var w io.Writer = cmd.Stdout
	if cmd.Path != "" {
		f, err := os.Create(cmd.Path)
		if err != nil {
			return errors.Wrap(err, "creating file")
		}
		defer f.Close()

		w = f
	}

	// Create a client to the server.
	client, err := commandClient(cmd)
	if err != nil {
		return errors.Wrap(err, "creating client")
	}

	// Determine shard count.
	maxShards, err := client.MaxShardByIndex(ctx)
	if err != nil {
		return errors.Wrap(err, "getting shard count")
	}

	// Export each shard.
	for shard := uint64(0); shard <= maxShards[cmd.Index]; shard++ {
		logger.Printf("exporting shard: %d", shard)
		if err := client.ExportCSV(ctx, cmd.Index, cmd.Field, shard, w); err != nil {
			return errors.Wrap(err, "exporting")
		}
	}

	// Close writer, if applicable.
	if w, ok := w.(io.Closer); ok {
		if err := w.Close(); err != nil {
			return errors.Wrap(err, "closing")
		}
	}

	return nil
}
541375
func (c *slaCommand) Run(ctx *cmd.Context) error {
	root, err := c.newAPIRoot()
	if err != nil {
		return errors.Trace(err)
	}
	client := c.newSLAClient(root)
	modelId := modelId(root)
	modelNameMap := modelNameMap()
	modelName := modelId
	if name, ok := modelNameMap[modelId]; ok {
		modelName = name
	}

	if c.Level == "" {
		return c.displayCurrentLevel(client, modelName, ctx)
	}
	owner, message, credentials, err := c.requestSupportCredentials(modelId)
	if err != nil {
		return errors.Trace(err)
	}
	if message != "" {
		err = c.out.Write(ctx, &slaLevel{
			Model:   modelName,
			SLA:     c.Level,
			Message: message,
		})
		if err != nil {
			return errors.Trace(err)
		}
	}
	err = client.SetSLALevel(c.Level, owner, credentials)
	if err != nil {
		return errors.Trace(err)
	}
	return nil
}
1142332
func (c *GetPhysicalHostsCmd) Run(app subcommands.Application, args []string, env subcommands.Env) int {
	ctx := cli.GetContext(app, c, env)
	client := getClient(ctx)
	resp, err := client.ListPhysicalHosts(ctx, &c.req)
	if err != nil {
		errors.Log(ctx, err)
		return 1
	}
	printPhysicalHosts(c.f.tsv, resp.Hosts...)
	return 0
}
673401
func (c *listCommand) Run(ctx *cmd.Context) (err error) {
	client, err := getListImagesAPI(&c.CachedImagesCommandBase)
	if err != nil {
		return err
	}
	defer client.Close()

	results, err := client.ListImages(c.Kind, c.Series, c.Arch)
	if err != nil {
		return err
	}
	imageInfo := c.imageMetadataToImageInfo(results)
	if len(imageInfo) == 0 {
		ctx.Infof("No images to display.")
		return nil
	}
	fmt.Fprintf(ctx.Stdout, "Cached images:\n")
	return c.out.Write(ctx, imageInfo)
}
891829
func (s *SSHRunner) Run(cmd string) error {
	glog.Infof("SSH: %s", cmd)
	sess, err := s.c.NewSession()
	if err != nil {
		return errors.Wrap(err, "NewSession")
	}

	defer func() {
		if err := sess.Close(); err != nil {
			if err != io.EOF {
				glog.Errorf("session close: %v", err)
			}
		}
	}()
	var outB bytes.Buffer
	var errB bytes.Buffer
	err = teeSSH(sess, cmd, &outB, &errB)
	if err != nil {
		return errors.Wrapf(err, "command failed: %s\nstdout: %s\nstderr: %s", cmd, outB.String(), errB.String())
	}
	return nil
}
929955
func (c *removeCommand) Run(ctx *cmd.Context) error {
	noWaitSet := false
	forceSet := false
	c.fs.Visit(func(flag *gnuflag.Flag) {
		if flag.Name == "no-wait" {
			noWaitSet = true
		} else if flag.Name == "force" {
			forceSet = true
		}
	})
	if !forceSet && noWaitSet {
		return errors.NotValidf("--no-wait without --force")
	}
	var maxWait *time.Duration
	if c.Force {
		if c.NoWait {
			zeroSec := 0 * time.Second
			maxWait = &zeroSec
		}
	}

	client, err := c.getRemoveMachineAPI()
	if err != nil {
		return err
	}
	defer client.Close()

	var results []params.DestroyMachineResult

	if c.KeepInstance || c.Force {
		results, err = client.DestroyMachinesWithParams(c.Force, c.KeepInstance, maxWait, c.MachineIds...)
	} else {
		results, err = client.DestroyMachines(c.MachineIds...)
	}
	if err := block.ProcessBlockedError(err, block.BlockRemove); err != nil {
		return err
	}

	anyFailed := false
	for i, id := range c.MachineIds {
		result := results[i]
		if result.Error != nil {
			anyFailed = true
			ctx.Infof("removing machine %s failed: %s", id, result.Error)
			continue
		}
		if c.KeepInstance {
			ctx.Infof("removing machine %s (but retaining cloud instance)", id)
		} else {
			ctx.Infof("removing machine %s", id)
		}
		for _, entity := range result.Info.DestroyedUnits {
			unitTag, err := names.ParseUnitTag(entity.Tag)
			if err != nil {
				logger.Warningf("%s", err)
				continue
			}
			ctx.Infof("- will remove %s", names.ReadableString(unitTag))
		}
		for _, entity := range result.Info.DestroyedStorage {
			storageTag, err := names.ParseStorageTag(entity.Tag)
			if err != nil {
				logger.Warningf("%s", err)
				continue
			}
			ctx.Infof("- will remove %s", names.ReadableString(storageTag))
		}
		for _, entity := range result.Info.DetachedStorage {
			storageTag, err := names.ParseStorageTag(entity.Tag)
			if err != nil {
				logger.Warningf("%s", err)
				continue
			}
			ctx.Infof("- will detach %s", names.ReadableString(storageTag))
		}
	}

	if anyFailed {
		return cmd.ErrSilent
	}
	return nil
}
1164276
func (c *AddPhysicalHostCmd) Run(app subcommands.Application, args []string, env subcommands.Env) int {
	ctx := cli.GetContext(app, c, env)
	// TODO(smut): Validate required fields client-side.
	req := &crimson.CreatePhysicalHostRequest{
		Host: &c.host,
	}
	client := getClient(ctx)
	resp, err := client.CreatePhysicalHost(ctx, req)
	if err != nil {
		errors.Log(ctx, err)
		return 1
	}
	printPhysicalHosts(c.f.tsv, resp)
	return 0
}