// Run implements Command.Run.
553728
func (c *RemoveCommand) Run(ctx *cmd.Context) error {
	return c.RunWithAPI(ctx, func(api SpaceAPI, ctx *cmd.Context) error {
		// Remove the space.
		err := api.RemoveSpace(c.name)
		if err != nil {
			return errors.Annotatef(err, "cannot remove space %q", c.name)
		}
		ctx.Infof("removed space %q", c.name)
		return nil
	})
}
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
}
1028522
func (c *command) run() []byte {
	cmd := exec.Command(c.program, c.args...)
	var stdout, stderr bytes.Buffer
	cmd.Stdout = &stdout
	cmd.Stderr = &stderr
	err := cmd.Run()
	out := stdout.Bytes()
	if err != nil {
		log.Fatalf("Could not run %v: %v: %v: %v", c, err, string(out), stderr.String())
	}
	return out
}
1009235
func (c *branchCommand) Run(ctx *cmd.Context) error {
	client, err := c.getAPI()
	if err != nil {
		return err
	}
	defer func() { _ = client.Close() }()

	if err = client.AddBranch(c.branchName); err != nil {
		return err
	}

	// Update the model store with the new active branch for this model.
	if err = c.SetActiveBranch(c.branchName); err != nil {
		return err
	}

	_, err = ctx.Stdout.Write([]byte(fmt.Sprintf("Active branch set to %q\n", c.branchName)))
	return err
}
637869
func (c *destroyCommand) 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")
	}

	store := c.ClientStore()
	controllerName, err := c.ControllerName()
	if err != nil {
		return errors.Trace(err)
	}

	controllerDetails, err := store.ControllerByName(controllerName)
	if err != nil {
		return errors.Annotate(err, "cannot read controller details")
	}
	modelName, modelDetails, err := c.ModelDetails()
	if err != nil {
		return errors.Trace(err)
	}

	if modelDetails.ModelUUID == controllerDetails.ControllerUUID {
		return errors.Errorf("%q is a controller; use 'juju destroy-controller' to destroy it", modelName)
	}

	if !c.assumeYes {
		modelType, err := c.ModelType()
		if err != nil {
			return errors.Trace(err)
		}
		msg := destroyIAASModelMsg
		if modelType == model.CAAS {
			msg = destroyCAASModelMsg
		}
		fmt.Fprintf(ctx.Stdout, msg, modelName)

		if err := jujucmd.UserConfirmYes(ctx); err != nil {
			return errors.Annotate(err, "model destruction")
		}
	}

	// Attempt to connect to the API.  If we can't, fail the destroy.
	api, err := c.getAPI()
	if err != nil {
		return errors.Annotate(err, "cannot connect to API")
	}
	defer api.Close()

	configAPI, err := c.getModelConfigAPI()
	if err != nil {
		return errors.Annotate(err, "cannot connect to API")
	}
	defer configAPI.Close()

	// Check if the model has an SLA set.
	slaIsSet := false
	slaLevel, err := configAPI.SLALevel()
	if err == nil {
		slaIsSet = slaLevel != "" && slaLevel != slaUnsupported
	} else {
		logger.Debugf("could not determine model SLA level: %v", err)
	}

	if api.BestAPIVersion() < 4 {
		// Versions before 4 support only destroying the storage,
		// and will not raise an error if there is storage in the
		// controller. Force the user to specify up-front.
		if c.releaseStorage {
			return errors.New("this juju controller only supports destroying storage")
		}
		if !c.destroyStorage {
			storageAPI, err := c.getStorageAPI()
			if err != nil {
				return errors.Trace(err)
			}
			defer storageAPI.Close()

			storageDetails, err := storageAPI.ListStorageDetails()
			if err != nil {
				return errors.Trace(err)
			}
			if len(storageDetails) > 0 {
				return errors.Errorf(`cannot destroy model %q

Destroying this model will destroy the storage, but you
have not indicated that you want to do that.

Please run the the command again with --destroy-storage
to confirm that you want to destroy the storage along
with the model.

If instead you want to keep the storage, you must first
upgrade the controller to version 2.3 or greater.

`, modelName)
			}
			c.destroyStorage = true
		}
	}

	// Attempt to destroy the model.
	ctx.Infof("Destroying model")
	var destroyStorage *bool
	if c.destroyStorage || c.releaseStorage {
		destroyStorage = &c.destroyStorage
	}
	var force *bool
	var maxWait *time.Duration
	if c.Force {
		force = &c.Force
		if c.NoWait {
			zeroSec := 0 * time.Second
			maxWait = &zeroSec
		}
	}
	modelTag := names.NewModelTag(modelDetails.ModelUUID)
	if err := api.DestroyModel(modelTag, destroyStorage, force, maxWait); err != nil {
		return c.handleError(
			modelTag, modelName, api,
			errors.Annotate(err, "cannot destroy model"),
		)
	}

	// Wait for model to be destroyed.
	if err := waitForModelDestroyed(
		ctx, api,
		names.NewModelTag(modelDetails.ModelUUID),
		c.timeout,
		c.clock,
	); err != nil {
		return err
	}

	// Check if the model has an sla auth.
	if slaIsSet {
		err = c.removeModelBudget(modelDetails.ModelUUID)
		if err != nil {
			ctx.Warningf("model allocation not removed: %v", err)
		}
	}

	c.RemoveModelFromClientStore(store, controllerName, modelName)
	return nil
}
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)
}
1094705
func (c *listCommand) Run(ctx *cmd.Context) (err error) {
	api, err := c.newAPIFunc()
	if err != nil {
		return err
	}
	defer api.Close()

	params := GetCombinedStorageInfoParams{
		Context: ctx, APIClient: api, Ids: c.ids,
	}
	switch {
	case c.filesystem:
		params.WantFilesystems = true
	case c.volume:
		params.WantVolumes = true
	default:
		params.WantStorage = true
		params.WantVolumes = true
		params.WantFilesystems = true
	}

	combined, err := GetCombinedStorageInfo(params)
	if err != nil {
		return err
	}
	if combined.Empty() {
		if c.out.Name() == "tabular" {
			ctx.Infof("No storage to display.")
		}
		return nil
	}
	return c.out.Write(ctx, *combined)
}
700551
func Run(args []string) error {
	opt := newOption(ErrorWriter, flag.ExitOnError)
	if e := opt.parse(args); e != nil {
		Usage()
		PrintDefaults(flag.ExitOnError)
		return fmt.Errorf("%v, %v", CommandName, e)
	}
	return command(opt)
}
663118
func (c *CharmResourcesCommand) Run(ctx *cmd.Context) error {
	return c.baseRun(ctx)
}
1173972
func (c *leaderGetCommand) Run(ctx *cmd.Context) error {
	settings, err := c.ctx.LeaderSettings()
	if err != nil {
		return errors.Annotatef(err, "cannot read leadership settings")
	}
	if c.key == "" {
		return c.out.Write(ctx, settings)
	}
	if value, ok := settings[c.key]; ok {
		return c.out.Write(ctx, value)
	}
	return c.out.Write(ctx, nil)
}
919925
func (c *DeprecatedCommand) Run(args []string) int {
	c.warn()
	return c.Command.Run(args)
}
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)
}
427307
func (c *upgradeJujuCommand) Run(ctx *cmd.Context) (err error) {
	modelType, err := c.ModelType()
	if err != nil {
		return errors.Trace(err)
	}
	if modelType == model.CAAS {
		return c.upgradeCAASModel(ctx)
	}
	return c.upgradeIAASModel(ctx)
}
1145770
func (c Command) Run(ctx *Context) error {

	if len(c.Subcommands) > 0 || c.Before != nil {
		return c.startApp(ctx)
	}

	if !c.HideHelp {
		// append help to flags
		c.Flags = append(
			c.Flags,
			HelpFlag,
		)
	}

	if ctx.App.EnableBashCompletion {
		c.Flags = append(c.Flags, BashCompletionFlag)
	}

	set := flagSet(c.Name, c.Flags)
	set.SetOutput(ioutil.Discard)

	firstFlagIndex := -1
	for index, arg := range ctx.Args() {
		if strings.HasPrefix(arg, "-") {
			firstFlagIndex = index
			break
		}
	}

	var err error
	if firstFlagIndex > -1 && !c.SkipFlagParsing {
		args := ctx.Args()
		regularArgs := args[1:firstFlagIndex]
		flagArgs := args[firstFlagIndex:]
		err = set.Parse(append(flagArgs, regularArgs...))
	} else {
		err = set.Parse(ctx.Args().Tail())
	}

	if err != nil {
		fmt.Printf("Incorrect Usage.\n\n")
		ShowCommandHelp(ctx, c.Name)
		fmt.Println("")
		return err
	}

	nerr := normalizeFlags(c.Flags, set)
	if nerr != nil {
		fmt.Println(nerr)
		fmt.Println("")
		ShowCommandHelp(ctx, c.Name)
		fmt.Println("")
		return nerr
	}
	context := NewContext(ctx.App, set, ctx.globalSet)

	if checkCommandCompletions(context, c.Name) {
		return nil
	}

	if checkCommandHelp(context, c.Name) {
		return nil
	}
	context.Command = c
	c.Action(context)
	return nil
}
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())
}
417316
func (c *uploadCommand) 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, err := c.NewAPIClient()
	if err != nil {
		return errors.Trace(err)
	}
	defer client.Close()

	archive, meta, err := getArchive(c.Filename)
	if err != nil {
		return errors.Trace(err)
	}
	defer archive.Close()

	if c.Log != nil && c.Log.Verbose {
		fmt.Fprintln(ctx.Stdout, "Uploaded metadata:")
		c.dumpMetadata(ctx, meta)
		fmt.Fprintln(ctx.Stdout)
	}

	// Upload the archive.
	id, err := client.Upload(archive, *meta)
	if err != nil {
		return errors.Trace(err)
	}

	if c.Log != nil && c.Log.Quiet {
		fmt.Fprintln(ctx.Stdout, id)
		return nil
	}

	// Pull the stored metadata.
	stored, err := c.getStoredMetadata(id)
	if err != nil {
		return errors.Trace(err)
	}

	c.dumpMetadata(ctx, stored)
	return nil
}
285948
func (c *listCommand) Run(ctx *cmd.Context) (err error) {
	if c.all {
		return c.listForController(ctx)
	}
	return c.listForModel(ctx)
}