// Run changes the version proposed for the juju envtools.
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)
}
386639
func (g *Graceful) Run() {
	env := g.Env
	if env == nil {
		env = defaultEnv
	}

	// prepare listener files
	listeners, err := g.Listen()
	if err != nil {
		env.Cancel(err)
		return
	}
	g.Serve(listeners)
}
556101
func (c *EditDRACCmd) 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.UpdateDRACRequest{
		Drac: &c.drac,
		UpdateMask: getUpdateMask(&c.Flags, map[string]string{
			"machine": "machine",
			"mac":     "mac_address",
			"switch":  "switch",
			"port":    "switchport",
		}),
	}
	client := getClient(ctx)
	resp, err := client.UpdateDRAC(ctx, req)
	if err != nil {
		errors.Log(ctx, err)
		return 1
	}
	printDRACs(c.f.tsv, resp)
	return 0
}
68435
func (o PruneDeploymentsOptions) Run() error {
	deploymentConfigList, err := o.AppsClient.DeploymentConfigs(o.Namespace).List(metav1.ListOptions{})
	if err != nil {
		return err
	}
	deploymentConfigs := []*appsv1.DeploymentConfig{}
	for i := range deploymentConfigList.Items {
		deploymentConfigs = append(deploymentConfigs, &deploymentConfigList.Items[i])
	}

	deploymentList, err := o.KubeClient.ReplicationControllers(o.Namespace).List(metav1.ListOptions{})
	if err != nil {
		return err
	}
	deployments := []*corev1.ReplicationController{}
	for i := range deploymentList.Items {
		deployments = append(deployments, &deploymentList.Items[i])
	}

	options := PrunerOptions{
		KeepYoungerThan:   o.KeepYoungerThan,
		Orphans:           o.Orphans,
		KeepComplete:      o.KeepComplete,
		KeepFailed:        o.KeepFailed,
		DeploymentConfigs: deploymentConfigs,
		Deployments:       deployments,
	}
	pruner := NewPruner(options)

	w := tabwriter.NewWriter(o.Out, 10, 4, 3, ' ', 0)
	defer w.Flush()

	deploymentDeleter := &describingDeploymentDeleter{w: w}

	if o.Confirm {
		deploymentDeleter.delegate = NewDeploymentDeleter(o.KubeClient)
	} else {
		fmt.Fprintln(os.Stderr, "Dry run enabled - no modifications will be made. Add --confirm to remove deployments")
	}

	return pruner.Prune(deploymentDeleter)
}
798879
func (c *EditVMCmd) 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.UpdateVMRequest{
		Vm: &c.vm,
		UpdateMask: getUpdateMask(&c.Flags, map[string]string{
			"host":  "host",
			"os":    "os",
			"state": "state",
			"desc":  "description",
			"tick":  "deployment_ticket",
		}),
	}
	client := getClient(ctx)
	resp, err := client.UpdateVM(ctx, req)
	if err != nil {
		errors.Log(ctx, err)
		return 1
	}
	printVMs(c.f.tsv, resp)
	return 0
}
371131
func (config *Config) Run(cmd string) (string, error) {
	if config.DisplayOutput == true {
		fmt.Printf("run: %s\n", cmd)
	}
	return config.doRun(cmd, false)
}
1103836
func (r *wrappedCmdRun) Run(a subcommands.Application, args []string, env subcommands.Env) int {
	ctx := GetContext(a, r, env)
	r.prof.Logger = logging.Get(ctx)
	r.prof.Clock = clock.Get(ctx)

	if err := r.prof.Start(); err != nil {
		logging.WithError(err).Errorf(ctx, "Failed to start profiling")
		return 1
	}
	defer r.prof.Stop()

	return r.CommandRun.Run(a, args, env)
}
371450
func (s *ServerImpl) Run() error {
	var err error

	if s.config.APIVersion < 2 {
		s.config.APIVersion = 1
	}
	if s.config.APIVersion > 2 {
		return fmt.Errorf("unknown API version")
	}

	// Create and start the debugger
	if s.debugger, err = debugger.New(&debugger.Config{
		AttachPid:            s.config.AttachPid,
		WorkingDir:           s.config.WorkingDir,
		CoreFile:             s.config.CoreFile,
		Backend:              s.config.Backend,
		Foreground:           s.config.Foreground,
		DebugInfoDirectories: s.config.DebugInfoDirectories,
		CheckGoVersion:       s.config.CheckGoVersion,
	},
		s.config.ProcessArgs); err != nil {
		return err
	}

	s.s1 = rpc1.NewServer(s.config, s.debugger)
	s.s2 = rpc2.NewServer(s.config, s.debugger)

	rpcServer := &RPCServer{s}

	s.methodMaps = make([]map[string]*methodType, 2)

	s.methodMaps[0] = map[string]*methodType{}
	s.methodMaps[1] = map[string]*methodType{}
	suitableMethods(s.s1, s.methodMaps[0], s.log)
	suitableMethods(rpcServer, s.methodMaps[0], s.log)
	suitableMethods(s.s2, s.methodMaps[1], s.log)
	suitableMethods(rpcServer, s.methodMaps[1], s.log)

	go func() {
		defer s.listener.Close()
		for {
			c, err := s.listener.Accept()
			if err != nil {
				select {
				case <-s.stopChan:
					// We were supposed to exit, do nothing and return
					return
				default:
					panic(err)
				}
			}
			go s.serveJSONCodec(c)
			if !s.config.AcceptMulti {
				break
			}
		}
	}()
	return nil
}
895050
func (s *StepUploadVersion) Run(ctx context.Context, state multistep.StateBag) multistep.StepAction {
	comm := state.Get("communicator").(packer.Communicator)
	driver := state.Get("driver").(Driver)
	ui := state.Get("ui").(packer.Ui)

	if s.Path == "" {
		log.Println("ParallelsVersionFile is empty. Not uploading.")
		return multistep.ActionContinue
	}

	version, err := driver.Version()
	if err != nil {
		state.Put("error", fmt.Errorf("Error reading version for metadata upload: %s", err))
		return multistep.ActionHalt
	}

	ui.Say(fmt.Sprintf("Uploading Parallels version info (%s)", version))
	var data bytes.Buffer
	data.WriteString(version)
	if err := comm.Upload(s.Path, &data, nil); err != nil {
		state.Put("error", fmt.Errorf("Error uploading Parallels version: %s", err))
		return multistep.ActionHalt
	}

	return multistep.ActionContinue
}
1241946
func (o PruneImagesOptions) Run() error {
	allPods, err := o.KubeClient.CoreV1().Pods(o.Namespace).List(metav1.ListOptions{})
	if err != nil {
		return err
	}

	allRCs, err := o.KubeClient.CoreV1().ReplicationControllers(o.Namespace).List(metav1.ListOptions{})
	if err != nil {
		return err
	}

	allBCs, err := o.BuildClient.BuildConfigs(o.Namespace).List(metav1.ListOptions{})
	// We need to tolerate 'not found' errors for buildConfigs since they may be disabled in Atomic
	err = oserrors.TolerateNotFoundError(err)
	if err != nil {
		return err
	}

	allBuilds, err := o.BuildClient.Builds(o.Namespace).List(metav1.ListOptions{})
	// We need to tolerate 'not found' errors for builds since they may be disabled in Atomic
	err = oserrors.TolerateNotFoundError(err)
	if err != nil {
		return err
	}

	allDSs, err := o.KubeClient.AppsV1().DaemonSets(o.Namespace).List(metav1.ListOptions{})
	if err != nil {
		// TODO: remove in future (3.9) release
		if !kerrors.IsForbidden(err) {
			return err
		}
		fmt.Fprintf(o.ErrOut, "Failed to list daemonsets: %v\n - * Make sure to update clusterRoleBindings.\n", err)
	}

	allDeployments, err := o.KubeClient.AppsV1().Deployments(o.Namespace).List(metav1.ListOptions{})
	if err != nil {
		// TODO: remove in future (3.9) release
		if !kerrors.IsForbidden(err) {
			return err
		}
		fmt.Fprintf(o.ErrOut, "Failed to list deployments: %v\n - * Make sure to update clusterRoleBindings.\n", err)
	}

	allDCs, err := o.AppsClient.DeploymentConfigs(o.Namespace).List(metav1.ListOptions{})
	if err != nil {
		return err
	}

	allRSs, err := o.KubeClient.AppsV1().ReplicaSets(o.Namespace).List(metav1.ListOptions{})
	if err != nil {
		// TODO: remove in future (3.9) release
		if !kerrors.IsForbidden(err) {
			return err
		}
		fmt.Fprintf(o.ErrOut, "Failed to list replicasets: %v\n - * Make sure to update clusterRoleBindings.\n", err)
	}

	limitRangesList, err := o.KubeClient.CoreV1().LimitRanges(o.Namespace).List(metav1.ListOptions{})
	if err != nil {
		return err
	}
	limitRangesMap := make(map[string][]*corev1.LimitRange)
	for i := range limitRangesList.Items {
		limit := limitRangesList.Items[i]
		limits, ok := limitRangesMap[limit.Namespace]
		if !ok {
			limits = []*corev1.LimitRange{}
		}
		limits = append(limits, &limit)
		limitRangesMap[limit.Namespace] = limits
	}

	allImages, err := o.ImageClient.Images().List(metav1.ListOptions{})
	if err != nil {
		return err
	}
	imageWatcher, err := o.ImageClient.Images().Watch(metav1.ListOptions{})
	if err != nil {
		utilruntime.HandleError(fmt.Errorf("internal error: failed to watch for images: %v"+
			"\n - image changes will not be detected", err))
		imageWatcher = watch.NewFake()
	}

	imageStreamWatcher, err := o.ImageClient.ImageStreams(o.Namespace).Watch(metav1.ListOptions{})
	if err != nil {
		utilruntime.HandleError(fmt.Errorf("internal error: failed to watch for image streams: %v"+
			"\n - image stream changes will not be detected", err))
		imageStreamWatcher = watch.NewFake()
	}
	defer imageStreamWatcher.Stop()

	allStreams, err := o.ImageClient.ImageStreams(o.Namespace).List(metav1.ListOptions{})
	if err != nil {
		return err
	}

	var (
		registryHost          = o.RegistryUrlOverride
		registryClientFactory imageprune.RegistryClientFactoryFunc
		registryClient        *http.Client
		registryPinger        imageprune.RegistryPinger
	)

	if o.Confirm {
		if len(registryHost) == 0 {
			registryHost, err = imageprune.DetermineRegistryHost(allImages, allStreams)
			if err != nil {
				return fmt.Errorf("unable to determine registry: %v", err)
			}
		}

		insecure := o.ForceInsecure
		if !insecure && len(o.CABundle) == 0 {
			insecure = o.ClientConfig.TLSClientConfig.Insecure || netutils.IsPrivateAddress(registryHost) ||
				strings.HasPrefix(registryHost, "http://")
		}

		registryClientFactory = func() (*http.Client, error) {
			return getRegistryClient(o.ClientConfig, o.CABundle, insecure)
		}
		registryClient, err = registryClientFactory()
		if err != nil {
			return err
		}

		registryPinger = &imageprune.DefaultRegistryPinger{
			Client:   registryClient,
			Insecure: insecure,
		}
	} else {
		registryPinger = &imageprune.DryRunRegistryPinger{}
		registryClientFactory = imageprune.FakeRegistryClientFactory
	}

	// verify the registy connection now to avoid future surprises
	registryURL, err := registryPinger.Ping(registryHost)
	if err != nil {
		if len(o.RegistryUrlOverride) == 0 && regexp.MustCompile(registryURLNotReachable).MatchString(err.Error()) {
			err = fmt.Errorf("%s\n* Please provide a reachable route to the integrated registry using --registry-url.", err.Error())
		}
		return fmt.Errorf("failed to ping registry %s: %v", registryHost, err)
	}

	options := imageprune.PrunerOptions{
		KeepYoungerThan:       o.KeepYoungerThan,
		KeepTagRevisions:      o.KeepTagRevisions,
		PruneOverSizeLimit:    o.PruneOverSizeLimit,
		AllImages:             o.AllImages,
		Images:                allImages,
		ImageWatcher:          imageWatcher,
		Streams:               allStreams,
		StreamWatcher:         imageStreamWatcher,
		Pods:                  allPods,
		RCs:                   allRCs,
		BCs:                   allBCs,
		Builds:                allBuilds,
		DSs:                   allDSs,
		Deployments:           allDeployments,
		DCs:                   allDCs,
		RSs:                   allRSs,
		LimitRanges:           limitRangesMap,
		DryRun:                o.Confirm == false,
		RegistryClientFactory: registryClientFactory,
		RegistryURL:           registryURL,
		PruneRegistry:         o.PruneRegistry,
		IgnoreInvalidRefs:     o.IgnoreInvalidRefs,
	}
	if o.Namespace != metav1.NamespaceAll {
		options.Namespace = o.Namespace
	}
	pruner, errs := imageprune.NewPruner(options)
	if errs != nil {
		o.printGraphBuildErrors(errs)
		return fmt.Errorf("failed to build graph - no changes made")
	}

	imagePrunerFactory := func() (imageprune.ImageDeleter, error) {
		return &describingImageDeleter{w: o.Out, errOut: o.ErrOut}, nil
	}
	imageStreamDeleter := &describingImageStreamDeleter{w: o.Out, errOut: o.ErrOut}
	layerLinkDeleter := &describingLayerLinkDeleter{w: o.Out, errOut: o.ErrOut}
	blobDeleter := &describingBlobDeleter{w: o.Out, errOut: o.ErrOut}
	manifestDeleter := &describingManifestDeleter{w: o.Out, errOut: o.ErrOut}

	if o.Confirm {
		imageStreamDeleter.delegate = imageprune.NewImageStreamDeleter(o.ImageClient)
		layerLinkDeleter.delegate = imageprune.NewLayerLinkDeleter()
		blobDeleter.delegate = imageprune.NewBlobDeleter()
		manifestDeleter.delegate = imageprune.NewManifestDeleter()

		imagePrunerFactory = func() (imageprune.ImageDeleter, error) {
			imageClient, err := o.ImageClientFactory()
			if err != nil {
				return nil, err
			}
			return imageprune.NewImageDeleter(imageClient), nil
		}
	} else {
		fmt.Fprintln(o.ErrOut, "Dry run enabled - no modifications will be made. Add --confirm to remove images")
	}

	if o.PruneRegistry != nil && !*o.PruneRegistry {
		fmt.Fprintln(o.Out, "Only API objects will be removed.  No modifications to the image registry will be made.")
	}

	deletions, failures := pruner.Prune(
		imagePrunerFactory,
		imageStreamDeleter,
		layerLinkDeleter,
		blobDeleter,
		manifestDeleter,
	)
	printSummary(o.Out, deletions, failures)
	if len(failures) == 1 {
		return &failures[0]
	}
	if len(failures) > 0 {
		return fmt.Errorf("failed")
	}
	return nil
}
702744
func (mr *ModRunner) Run() error {
	for {
		modchan := make(chan *moddwatch.Mod, 1024)
		err := mr.runOnChan(modchan, func() {})
		if err != nil {
			return err
		}
	}
}
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
}
254038
func (o *SetResourcesOptions) Run() error {
	allErrs := []error{}
	patches := CalculatePatches(o.Infos, scheme.DefaultJSONEncoder(), func(obj runtime.Object) ([]byte, error) {
		transformed := false
		_, err := o.UpdatePodSpecForObject(obj, func(spec *v1.PodSpec) error {
			containers, _ := selectContainers(spec.Containers, o.ContainerSelector)
			if len(containers) != 0 {
				for i := range containers {
					if len(o.Limits) != 0 && len(containers[i].Resources.Limits) == 0 {
						containers[i].Resources.Limits = make(v1.ResourceList)
					}
					for key, value := range o.ResourceRequirements.Limits {
						containers[i].Resources.Limits[key] = value
					}

					if len(o.Requests) != 0 && len(containers[i].Resources.Requests) == 0 {
						containers[i].Resources.Requests = make(v1.ResourceList)
					}
					for key, value := range o.ResourceRequirements.Requests {
						containers[i].Resources.Requests[key] = value
					}
					transformed = true
				}
			} else {
				allErrs = append(allErrs, fmt.Errorf("error: unable to find container named %s", o.ContainerSelector))
			}
			return nil
		})
		if err != nil {
			return nil, err
		}
		if !transformed {
			return nil, nil
		}
		// record this change (for rollout history)
		if err := o.Recorder.Record(obj); err != nil {
			klog.V(4).Infof("error recording current command: %v", err)
		}

		return runtime.Encode(scheme.DefaultJSONEncoder(), obj)
	})

	for _, patch := range patches {
		info := patch.Info
		name := info.ObjectName()
		if patch.Err != nil {
			allErrs = append(allErrs, fmt.Errorf("error: %s %v\n", name, patch.Err))
			continue
		}

		//no changes
		if string(patch.Patch) == "{}" || len(patch.Patch) == 0 {
			allErrs = append(allErrs, fmt.Errorf("info: %s was not changed\n", name))
			continue
		}

		if o.Local || o.DryRun {
			if err := o.PrintObj(info.Object, o.Out); err != nil {
				allErrs = append(allErrs, err)
			}
			continue
		}

		actual, err := resource.NewHelper(info.Client, info.Mapping).Patch(info.Namespace, info.Name, types.StrategicMergePatchType, patch.Patch, nil)
		if err != nil {
			allErrs = append(allErrs, fmt.Errorf("failed to patch limit update to pod template %v", err))
			continue
		}

		if err := o.PrintObj(actual, o.Out); err != nil {
			allErrs = append(allErrs, err)
		}
	}
	return utilerrors.NewAggregate(allErrs)
}
1050752
func (step commonDeploymentUpgradeStep) Run(ctx context.ProviderCallContext) error {
	env := step.env
	isControllerEnviron, err := isControllerEnviron(env, ctx)
	if err != nil {
		return errors.Trace(err)
	}
	if isControllerEnviron {
		// We only need to create the deployment for
		// non-controller Environs.
		return nil
	}

	// Identify the network security rules that exist already.
	// We will add these, excluding the SSH/API rules, to the
	// network security group template created in the deployment
	// below.
	nsgClient := network.SecurityGroupsClient{
		BaseClient: env.network,
	}
	allRules, err := networkSecurityRules(nsgClient, env.resourceGroup)
	if errors.IsNotFound(err) {
		allRules = nil
	} else if err != nil {
		return errors.Trace(err)
	}
	rules := make([]network.SecurityRule, 0, len(allRules))
	for _, rule := range allRules {
		name := to.String(rule.Name)
		if name == sshSecurityRuleName || strings.HasPrefix(name, apiSecurityRulePrefix) {
			continue
		}
		rules = append(rules, rule)
	}

	env.mu.Lock()
	storageAccountType := env.config.storageAccountType
	env.mu.Unlock()
	return env.createCommonResourceDeployment(ctx, nil, rules, storageAccountTemplateResource(
		env.location, nil,
		env.storageAccountName,
		storageAccountType,
	))
}
1001192
func (m *Menu) Run() (map[flux.ResourceID][]ContainerUpdate, error) {
	specs := make(map[flux.ResourceID][]ContainerUpdate)
	if m.selectable == 0 {
		return specs, errors.New("No changes found.")
	}

	m.printInteractive()
	m.wr.hideCursor()
	defer m.wr.showCursor()

	for {
		ascii, keyCode, err := getChar()
		if err != nil {
			return specs, err
		}

		switch ascii {
		case 3, 27, 'q':
			return specs, errors.New("Aborted.")
		case ' ':
			m.toggleSelected()
		case 13:
			for _, item := range m.items {
				if item.checked {
					specs[item.id] = append(specs[item.id], item.update)
				}
			}
			m.wr.writeln("")
			return specs, nil
		case 9, 'j':
			m.cursorDown()
		case 'k':
			m.cursorUp()
		default:
			switch keyCode {
			case 40:
				m.cursorDown()
			case 38:
				m.cursorUp()
			}
		}

	}
}
743928
func (c *GetKVMsCmd) Run(app subcommands.Application, args []string, env subcommands.Env) int {
	ctx := cli.GetContext(app, c, env)
	client := getClient(ctx)
	resp, err := client.ListKVMs(ctx, &c.req)
	if err != nil {
		errors.Log(ctx, err)
		return 1
	}
	printKVMs(c.f.tsv, resp.Kvms...)
	return 0
}
126734
func (f *FakeCommandRunner) Run(cmd string) error {
	_, err := f.CombinedOutput(cmd)
	return err
}