// Run implements Command.Run.
425178
func (c *MetricsCommand) Run(ctx *cmd.Context) error {
	client, err := newClient(c.ModelCommandBase)
	if err != nil {
		return errors.Trace(err)
	}
	var metrics []params.MetricResult
	if c.All {
		metrics, err = client.GetMetrics()
	} else {
		metrics, err = client.GetMetrics(c.Tags...)
	}
	if err != nil {
		return errors.Trace(err)
	}
	defer client.Close()
	if len(metrics) == 0 {
		return nil
	}
	results := make([]metric, len(metrics))
	for i, m := range metrics {
		results[i] = metric{
			Unit:      m.Unit,
			Timestamp: m.Time,
			Metric:    m.Key,
			Value:     m.Value,
			Labels:    m.Labels,
		}
	}
	sortedResults := metricSlice(results)
	sort.Sort(sortedResults)

	return errors.Trace(c.out.Write(ctx, results))
}
1320246
func (c *runner) Run(name string, arg ...string) error {
	return c.RunWithOptions(CommandOpts{}, name, arg...)
}
240602
func (c *showCommand) Run(ctx *cmd.Context) (err error) {
	api, err := c.newAPIFunc()
	if err != nil {
		return err
	}
	defer api.Close()

	tags, err := c.getStorageTags()
	if err != nil {
		return err
	}

	results, err := api.StorageDetails(tags)
	if err != nil {
		return err
	}

	var errs params.ErrorResults
	var valid []params.StorageDetails
	for _, result := range results {
		if result.Error != nil {
			errs.Results = append(errs.Results, params.ErrorResult{result.Error})
			continue
		}
		valid = append(valid, *result.Result)
	}
	if len(errs.Results) > 0 {
		return errs.Combine()
	}

	output, err := formatStorageDetails(valid)
	if err != nil {
		return err
	}
	return c.out.Write(ctx, output)
}
796579
func (c *listCommand) 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()

	result, err := client.List()
	if err != nil {
		return errors.Trace(err)
	}

	if len(result.List) == 0 {
		ctx.Infof("No backups to display.")
		return nil
	}

	verbose := c.Log != nil && c.Log.Verbose
	if verbose {
		c.dumpMetadata(ctx, &result.List[0])
	} else {
		fmt.Fprintln(ctx.Stdout, result.List[0].ID)
	}
	for _, resultItem := range result.List[1:] {
		if verbose {
			fmt.Fprintln(ctx.Stdout)
			c.dumpMetadata(ctx, &resultItem)
		} else {
			fmt.Fprintln(ctx.Stdout, resultItem.ID)
		}
	}
	return nil
}
1139065
func Run(argv interface{}, fn CommandFunc, descs ...string) int {
	return RunWithArgs(argv, os.Args, fn, descs...)
}
1167217
func (c *ActionSetCommand) Run(ctx *cmd.Context) error {
	for _, argSlice := range c.args {
		valueIndex := len(argSlice) - 1
		keys := argSlice[:valueIndex]
		value := argSlice[valueIndex]
		err := c.ctx.UpdateActionResults(keys, value)
		if err != nil {
			return err
		}
	}

	return nil
}
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)
}
672984
func (p *Proxy) Run(command string, args ...string) error {
	log.WithFields(log.Fields{
		"command": command,
		"args":    args,
	}).Debug("exec")

	cmd := exec.Command(command, args...)
	cmd.Env = append(os.Environ(), p.functionEnvVars()...)
	cmd.Stdin = os.Stdin
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	cmd.Dir = p.Dir

	return cmd.Run()
}
692712
func (c *showModelCommand) Run(ctx *cmd.Context) error {
	controllerName, err := c.ControllerName()
	if err != nil {
		return errors.Trace(err)
	}
	_, modelDetails, err := c.ModelDetails()
	if err != nil {
		return errors.Trace(err)
	}
	modelTag := names.NewModelTag(modelDetails.ModelUUID)

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

	results, err := api.ModelInfo([]names.ModelTag{modelTag})
	if err != nil {
		return err
	}
	if results[0].Error != nil {
		return results[0].Error
	}
	infoMap, err := c.apiModelInfoToModelInfoMap([]params.ModelInfo{*results[0].Result}, controllerName)
	if err != nil {
		return errors.Trace(err)
	}
	return c.out.Write(ctx, infoMap)
}
865538
func (c *BootstrapCommand) Run(_ *cmd.Context) error {

	bootstrapParamsData, err := ioutil.ReadFile(c.BootstrapParamsFile)
	if err != nil {
		return errors.Annotate(err, "reading bootstrap params file")
	}
	var args instancecfg.StateInitializationParams
	if err := args.Unmarshal(bootstrapParamsData); err != nil {
		return errors.Trace(err)
	}

	isCAAS := args.ControllerCloud.Type == caasprovider.CAASProviderType

	if isCAAS {
		if err := c.ensureConfigFilesForCaas(); err != nil {
			return errors.Trace(err)
		}
	}

	if err := c.ReadConfig(c.Tag().String()); err != nil {
		return errors.Annotate(err, "cannot read config")
	}
	agentConfig := c.CurrentConfig()

	// agent.Jobs is an optional field in the agent config, and was
	// introduced after 1.17.2. We default to allowing units on
	// machine-0 if missing.
	jobs := agentConfig.Jobs()
	if len(jobs) == 0 {
		jobs = []multiwatcher.MachineJob{
			multiwatcher.JobManageModel,
			multiwatcher.JobHostUnits,
		}
	}

	// Get the bootstrap machine's addresses from the provider.
	cloudSpec, err := environs.MakeCloudSpec(
		args.ControllerCloud,
		args.ControllerCloudRegion,
		args.ControllerCloudCredential,
	)
	if err != nil {
		return errors.Trace(err)
	}

	openParams := environs.OpenParams{
		ControllerUUID: args.ControllerConfig.ControllerUUID(),
		Cloud:          cloudSpec,
		Config:         args.ControllerModelConfig,
	}
	var env environs.BootstrapEnviron
	if isCAAS {
		env, err = environsNewCAAS(openParams)
	} else {
		env, err = environsNewIAAS(openParams)
	}
	if err != nil {
		return errors.Trace(err)
	}

	newConfigAttrs := make(map[string]interface{})

	// Check to see if a newer agent version has been requested
	// by the bootstrap client.
	desiredVersion, ok := args.ControllerModelConfig.AgentVersion()
	if ok && desiredVersion != jujuversion.Current {
		if isCAAS {
			// For CAAS, the agent-version in controller config should
			// always equals to current juju version.
			return errors.NotSupportedf(
				"desired juju version %q, current version %q for k8s controllers",
				desiredVersion, jujuversion.Current,
			)
		}

		// If we have been asked for a newer version, ensure the newer
		// tools can actually be found, or else bootstrap won't complete.
		streams := envtools.PreferredStreams(&desiredVersion, args.ControllerModelConfig.Development(), args.ControllerModelConfig.AgentStream())
		logger.Infof("newer agent binaries requested, looking for %v in streams: %v", desiredVersion, strings.Join(streams, ","))
		hostSeries, err := series.HostSeries()
		if err != nil {
			return errors.Trace(err)
		}
		filter := tools.Filter{
			Number: desiredVersion,
			Arch:   arch.HostArch(),
			Series: hostSeries,
		}
		_, toolsErr := envtools.FindTools(env, -1, -1, streams, filter)
		if toolsErr == nil {
			logger.Infof("agent binaries are available, upgrade will occur after bootstrap")
		}
		if errors.IsNotFound(toolsErr) {
			// Newer tools not available, so revert to using the tools
			// matching the current agent version.
			logger.Warningf("newer agent binaries for %q not available, sticking with version %q", desiredVersion, jujuversion.Current)
			newConfigAttrs["agent-version"] = jujuversion.Current.String()
		} else if toolsErr != nil {
			logger.Errorf("cannot find newer agent binaries: %v", toolsErr)
			return toolsErr
		}
	}

	callCtx := context.NewCloudCallContext()
	// At this stage, cloud credential has not yet been stored server-side
	// as there is no server-side. If these cloud calls will fail with
	// invalid credential, just log it.
	callCtx.InvalidateCredentialFunc = func(reason string) error {
		logger.Errorf("Cloud credential %q is not accepted by cloud provider: %v", args.ControllerCloudCredentialName, reason)
		return nil
	}

	info, ok := agentConfig.StateServingInfo()
	if !ok {
		return fmt.Errorf("bootstrap machine config has no state serving info")
	}
	if err := ensureKeys(isCAAS, args, &info, newConfigAttrs); err != nil {
		return errors.Trace(err)
	}
	addrs, err := getAddressesForMongo(isCAAS, env, callCtx, args)
	if err != nil {
		return errors.Trace(err)
	}

	if err = c.ChangeConfig(func(agentConfig agent.ConfigSetter) error {
		agentConfig.SetStateServingInfo(info)
		mmprof, err := mongo.NewMemoryProfile(args.ControllerConfig.MongoMemoryProfile())
		if err != nil {
			logger.Errorf("could not set requested memory profile: %v", err)
		} else {
			agentConfig.SetMongoMemoryProfile(mmprof)
		}
		return nil
	}); err != nil {
		return fmt.Errorf("cannot write agent config: %v", err)
	}

	agentConfig = c.CurrentConfig()

	// Create system-identity file
	if err := agent.WriteSystemIdentityFile(agentConfig); err != nil {
		return errors.Trace(err)
	}

	if err := c.startMongo(isCAAS, addrs, agentConfig); err != nil {
		return errors.Annotate(err, "failed to start mongo")
	}

	controllerModelCfg, err := env.Config().Apply(newConfigAttrs)
	if err != nil {
		return errors.Annotate(err, "failed to update model config")
	}
	args.ControllerModelConfig = controllerModelCfg

	// Initialise state, and store any agent config (e.g. password) changes.
	var controller *state.Controller
	var m *state.Machine
	err = c.ChangeConfig(func(agentConfig agent.ConfigSetter) error {
		var stateErr error
		dialOpts := mongo.DefaultDialOpts()

		// Set a longer socket timeout than usual, as the machine
		// will be starting up and disk I/O slower than usual. This
		// has been known to cause timeouts in queries.
		dialOpts.SocketTimeout = c.Timeout
		if dialOpts.SocketTimeout < minSocketTimeout {
			dialOpts.SocketTimeout = minSocketTimeout
		}

		// We shouldn't attempt to dial peers until we have some.
		dialOpts.Direct = true

		adminTag := names.NewLocalUserTag(adminUserName)
		controller, m, stateErr = agentInitializeState(
			adminTag,
			agentConfig,
			agentbootstrap.InitializeStateParams{
				StateInitializationParams: args,
				BootstrapMachineAddresses: addrs,
				BootstrapMachineJobs:      jobs,
				SharedSecret:              info.SharedSecret,
				Provider:                  environs.Provider,
				StorageProviderRegistry:   stateenvirons.NewStorageProviderRegistry(env),
			},
			dialOpts,
			stateenvirons.GetNewPolicyFunc(),
		)
		return stateErr
	})
	if err != nil {
		return err
	}
	defer controller.Close()
	st := controller.SystemState()

	// Set up default container networking mode
	model, err := st.Model()
	if err != nil {
		return err
	}
	if err = model.AutoConfigureContainerNetworking(env); err != nil {
		if errors.IsNotSupported(err) {
			logger.Debugf("Not performing container networking autoconfiguration on a non-networking environment")
		} else {
			return err
		}
	}

	// Fetch spaces from substrate
	if err = st.ReloadSpaces(env); err != nil {
		if errors.IsNotSupported(err) {
			logger.Debugf("Not performing spaces load on a non-networking environment")
		} else {
			return err
		}
	}

	if !isCAAS {
		// Populate the tools catalogue.
		if err := c.populateTools(st, env); err != nil {
			return errors.Trace(err)
		}
		// Add custom image metadata to environment storage.
		if len(args.CustomImageMetadata) > 0 {
			if err := c.saveCustomImageMetadata(st, env, args.CustomImageMetadata); err != nil {
				return err
			}
		}
	}

	// Populate the GUI archive catalogue.
	if err := c.populateGUIArchive(st, env); err != nil {
		// Do not stop the bootstrapping process for Juju GUI archive errors.
		logger.Warningf("cannot set up Juju GUI: %s", err)
	} else {
		logger.Debugf("Juju GUI successfully set up")
	}

	// bootstrap machine always gets the vote
	return m.SetHasVote(true)
}
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
}
972687
func Run(run func(args []string) error) func(*cobra.Command, []string) {
	return func(_ *cobra.Command, args []string) {
		Check(run(args))
	}
}
975209
func (cmd AppCmd) Run() {
	utils.Logger.Info("Exec app:", "path", cmd.Path, "args", cmd.Args)
	if err := cmd.Cmd.Run(); err != nil {
		utils.Logger.Fatal("Error running:", "error", err)
	}
}
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)
}
72551
func (i *initCmd) run() error {
	if err := i.tlsOptions(); err != nil {
		return err
	}
	i.opts.Namespace = i.namespace
	i.opts.UseCanary = i.canary
	i.opts.ImageSpec = i.image
	i.opts.ForceUpgrade = i.forceUpgrade
	i.opts.ServiceAccount = i.serviceAccount
	i.opts.MaxHistory = i.maxHistory
	i.opts.Replicas = i.replicas

	writeYAMLManifests := func(manifests []string) error {
		w := i.out
		for _, manifest := range manifests {
			if _, err := fmt.Fprintln(w, "---"); err != nil {
				return err
			}

			if _, err := fmt.Fprintln(w, manifest); err != nil {
				return err
			}
		}

		// YAML ending document boundary marker
		_, err := fmt.Fprintln(w, "...")
		return err
	}
	if len(i.opts.Output) > 0 {
		var manifests []string
		var err error
		if manifests, err = installer.TillerManifests(&i.opts); err != nil {
			return err
		}
		switch i.opts.Output.String() {
		case "json":
			for _, manifest := range manifests {
				var out bytes.Buffer
				jsonb, err := yaml.ToJSON([]byte(manifest))
				if err != nil {
					return err
				}
				buf := bytes.NewBuffer(jsonb)
				if err := json.Indent(&out, buf.Bytes(), "", "    "); err != nil {
					return err
				}
				if _, err = i.out.Write(out.Bytes()); err != nil {
					return err
				}
				fmt.Fprint(i.out, "\n")
			}
			return nil
		case "yaml":
			return writeYAMLManifests(manifests)
		default:
			return fmt.Errorf("unknown output format: %q", i.opts.Output)
		}
	}
	if settings.Debug {
		var manifests []string
		var err error

		// write Tiller manifests
		if manifests, err = installer.TillerManifests(&i.opts); err != nil {
			return err
		}

		if err = writeYAMLManifests(manifests); err != nil {
			return err
		}
	}

	if i.dryRun {
		return nil
	}

	if err := installer.Initialize(i.home, i.out, i.skipRefresh, settings, stableRepositoryURL, localRepositoryURL); err != nil {
		return fmt.Errorf("error initializing: %s", err)
	}
	fmt.Fprintf(i.out, "$HELM_HOME has been configured at %s.\n", settings.Home)

	if !i.clientOnly {
		if i.kubeClient == nil {
			_, c, err := getKubeClient(settings.KubeContext, settings.KubeConfig)
			if err != nil {
				return fmt.Errorf("could not get kubernetes client: %s", err)
			}
			i.kubeClient = c
		}
		if err := installer.Install(i.kubeClient, &i.opts); err != nil {
			if !apierrors.IsAlreadyExists(err) {
				return fmt.Errorf("error installing: %s", err)
			}
			if i.upgrade {
				if err := installer.Upgrade(i.kubeClient, &i.opts); err != nil {
					return fmt.Errorf("error when upgrading: %s", err)
				}
				if err := i.ping(i.opts.SelectImage()); err != nil {
					return err
				}
				fmt.Fprintln(i.out, "\nTiller (the Helm server-side component) has been upgraded to the current version.")
			} else {
				fmt.Fprintln(i.out, "Warning: Tiller is already installed in the cluster.\n"+
					"(Use --client-only to suppress this message, or --upgrade to upgrade Tiller to the current version.)")
			}
		} else {
			fmt.Fprintln(i.out, "\nTiller (the Helm server-side component) has been installed into your Kubernetes Cluster.")
			if !tlsVerify {
				fmt.Fprintln(i.out, "\nPlease note: by default, Tiller is deployed with an insecure 'allow unauthenticated users' policy.\n"+
					"To prevent this, run `helm init` with the --tiller-tls-verify flag.\n"+
					"For more information on securing your installation see: https://docs.helm.sh/using_helm/#securing-your-helm-installation")
			}
		}
		if err := i.ping(i.opts.SelectImage()); err != nil {
			return err
		}
	} else {
		fmt.Fprintln(i.out, "Not installing Tiller due to 'client-only' flag having been set")
	}

	needsDefaultImage := !i.clientOnly && !i.opts.UseCanary && len(i.opts.ImageSpec) == 0 && version.BuildMetadata == "unreleased"
	if needsDefaultImage {
		fmt.Fprintf(i.out, "\nWarning: You appear to be using an unreleased version of Helm. Please either use the\n"+
			"--canary-image flag, or specify your desired tiller version with --tiller-image.\n\n"+
			"Ex:\n"+
			"$ helm init --tiller-image gcr.io/kubernetes-helm/tiller:v2.8.2\n\n")
	}

	return nil
}
901558
func (c *CmdSimpleFSKill) Run() error {
	cli, err := GetSimpleFSClient(c.G())
	if err != nil {
		return err
	}

	err = cli.SimpleFSClose(context.TODO(), c.opid)

	return err
}
798808
func (c *addImageMetadataCommand) Run(ctx *cmd.Context) (err error) {
	api, err := getImageMetadataAddAPI(c)
	if err != nil {
		return err
	}
	defer api.Close()

	m := c.constructMetadataParam()
	if err := api.Save([]params.CloudImageMetadata{m}); err != nil {
		return errors.Trace(err)
	}
	return nil
}