// Run executes a validated remote execution against a pod.
346037
func (p *ExecOptions) Run() error {
	pod, err := p.Client.Pods(p.Namespace).Get(p.PodName)
	if err != nil {
		return err
	}

	if pod.Status.Phase != api.PodRunning {
		return fmt.Errorf("pod %s is not running and cannot execute commands; current phase is %s", p.PodName, pod.Status.Phase)
	}

	containerName := p.ContainerName
	if len(containerName) == 0 {
		glog.V(4).Infof("defaulting container name to %s", pod.Spec.Containers[0].Name)
		containerName = pod.Spec.Containers[0].Name
	}

	// TODO: refactor with terminal helpers from the edit utility once that is merged
	var stdin io.Reader
	tty := p.TTY
	if p.Stdin {
		stdin = p.In
		if tty {
			if file, ok := stdin.(*os.File); ok {
				inFd := file.Fd()
				if term.IsTerminal(inFd) {
					oldState, err := term.SetRawTerminal(inFd)
					if err != nil {
						glog.Fatal(err)
					}
					// this handles a clean exit, where the command finished
					defer term.RestoreTerminal(inFd, oldState)

					// SIGINT is handled by term.SetRawTerminal (it runs a goroutine that listens
					// for SIGINT and restores the terminal before exiting)

					// this handles SIGTERM
					sigChan := make(chan os.Signal, 1)
					signal.Notify(sigChan, syscall.SIGTERM)
					go func() {
						<-sigChan
						term.RestoreTerminal(inFd, oldState)
						os.Exit(0)
					}()
				} else {
					fmt.Fprintln(p.Err, "STDIN is not a terminal")
				}
			} else {
				tty = false
				fmt.Fprintln(p.Err, "Unable to use a TTY - input is not the right kind of file")
			}
		}
	}

	// TODO: consider abstracting into a client invocation or client helper
	req := p.Client.RESTClient.Post().
		Resource("pods").
		Name(pod.Name).
		Namespace(pod.Namespace).
		SubResource("exec").
		Param("container", containerName)
	req.VersionedParams(&api.PodExecOptions{
		Container: containerName,
		Command:   p.Command,
		Stdin:     stdin != nil,
		Stdout:    p.Out != nil,
		Stderr:    p.Err != nil,
		TTY:       tty,
	}, api.Scheme)

	return p.Executor.Execute("POST", req.URL(), p.Config, stdin, p.Out, p.Err, tty)
}
939355
func (u *UIDMonitor) Run(ctx context.Context) error {

	if err := u.proc.config.IsComplete(); err != nil {
		return fmt.Errorf("uid: %s", err)
	}

	return u.Resync(ctx)
}
369310
func (e *Editor) Run(logger func(format string, a ...interface{})) {
	if logger == nil {
		logger = NoOpLogger
	}

	e.log = logger
	if e.config.Hostname == "" {
		e.config.Hostname = "0.0.0.0"
	}

	if e.config.Port <= 0 {
		e.config.Port = DefaultPort
	}

	if s, err := filepath.Abs(e.config.WorkingDir); err == nil {
		e.config.WorkingDir = s
	}

	e.start()
}
706543
func (rsc *ReplicaSetController) Run(workers int, stopCh <-chan struct{}) {
	defer utilruntime.HandleCrash()
	defer rsc.queue.ShutDown()

	controllerName := strings.ToLower(rsc.Kind)
	klog.Infof("Starting %v controller", controllerName)
	defer klog.Infof("Shutting down %v controller", controllerName)

	if !controller.WaitForCacheSync(rsc.Kind, stopCh, rsc.podListerSynced, rsc.rsListerSynced) {
		return
	}

	for i := 0; i < workers; i++ {
		go wait.Until(rsc.worker, time.Second, stopCh)
	}

	<-stopCh
}
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
}
1318342
func (b *AdapterBase) Run(stopCh <-chan struct{}) error {
	server, err := b.Server()
	if err != nil {
		return err
	}

	return server.GenericAPIServer.PrepareRun().Run(stopCh)
}
541268
func (e *EmptyService) Run(ctx context.Context, commandParts []string, options options.Run) (int, error) {
	return 0, nil
}
1117417
func (tc *NoExecuteTaintManager) Run(stopCh <-chan struct{}) {
	klog.V(0).Infof("Starting NoExecuteTaintManager")

	for i := 0; i < UpdateWorkerSize; i++ {
		tc.nodeUpdateChannels = append(tc.nodeUpdateChannels, make(chan nodeUpdateItem, NodeUpdateChannelSize))
		tc.podUpdateChannels = append(tc.podUpdateChannels, make(chan podUpdateItem, podUpdateChannelSize))
	}

	// Functions that are responsible for taking work items out of the workqueues and putting them
	// into channels.
	go func(stopCh <-chan struct{}) {
		for {
			item, shutdown := tc.nodeUpdateQueue.Get()
			if shutdown {
				break
			}
			nodeUpdate := item.(nodeUpdateItem)
			hash := hash(nodeUpdate.nodeName, UpdateWorkerSize)
			select {
			case <-stopCh:
				tc.nodeUpdateQueue.Done(item)
				return
			case tc.nodeUpdateChannels[hash] <- nodeUpdate:
				// tc.nodeUpdateQueue.Done is called by the nodeUpdateChannels worker
			}
		}
	}(stopCh)

	go func(stopCh <-chan struct{}) {
		for {
			item, shutdown := tc.podUpdateQueue.Get()
			if shutdown {
				break
			}
			podUpdate := item.(podUpdateItem)
			hash := hash(podUpdate.nodeName, UpdateWorkerSize)
			select {
			case <-stopCh:
				tc.podUpdateQueue.Done(item)
				return
			case tc.podUpdateChannels[hash] <- podUpdate:
				// tc.podUpdateQueue.Done is called by the podUpdateChannels worker
			}
		}
	}(stopCh)

	wg := sync.WaitGroup{}
	wg.Add(UpdateWorkerSize)
	for i := 0; i < UpdateWorkerSize; i++ {
		go tc.worker(i, wg.Done, stopCh)
	}
	wg.Wait()
}
383639
func (c *registerCommand) Run(ctx *cmd.Context) error {
	err := c.run(ctx)
	if err != nil && c.onRunError != nil {
		c.onRunError()
	}
	return err
}
1373941
func (mod *PastebinBee) Run(eventChan chan bees.Event) {
	mod.client = pastebin.NewPastebin(mod.apiDevKey)
}
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
}
132266
func (o *SetImageOptions) Run() error {
	allErrs := []error{}

	patches := CalculatePatches(o.Infos, scheme.DefaultJSONEncoder(), func(obj runtime.Object) ([]byte, error) {
		_, err := o.UpdatePodSpecForObject(obj, func(spec *v1.PodSpec) error {
			for name, image := range o.ContainerImages {
				resolvedImageName, err := o.ResolveImage(image)
				if err != nil {
					allErrs = append(allErrs, fmt.Errorf("error: unable to resolve image %q for container %q: %v", image, name, err))
					if name == "*" {
						break
					}
					continue
				}

				initContainerFound := setImage(spec.InitContainers, name, resolvedImageName)
				containerFound := setImage(spec.Containers, name, resolvedImageName)
				if !containerFound && !initContainerFound {
					allErrs = append(allErrs, fmt.Errorf("error: unable to find container named %q", name))
				}
			}
			return nil
		})
		if err != nil {
			return nil, err
		}
		// 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
		if patch.Err != nil {
			name := info.ObjectName()
			allErrs = append(allErrs, fmt.Errorf("error: %s %v\n", name, patch.Err))
			continue
		}

		// no changes
		if string(patch.Patch) == "{}" || len(patch.Patch) == 0 {
			continue
		}

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

		// patch the change
		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 image update to pod template: %v", err))
			continue
		}

		if err := o.PrintObj(actual, o.Out); err != nil {
			allErrs = append(allErrs, err)
		}
	}
	return utilerrors.NewAggregate(allErrs)
}
421616
func (*ExecRunner) Run(cmd string) error {
	glog.Infoln("Run:", cmd)
	c := exec.Command("/bin/bash", "-c", cmd)
	if err := c.Run(); err != nil {
		return errors.Wrapf(err, "running command: %s", cmd)
	}
	return nil
}
1322170
func (c Command) Run(ctx *Context) (err error) {
	if len(c.Subcommands) > 0 {
		return c.startApp(ctx)
	}

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

	set, err := c.parseFlags(ctx.Args().Tail())

	context := NewContext(ctx.App, set, ctx)
	context.Command = c
	if checkCommandCompletions(context, c.Name) {
		return nil
	}

	if err != nil {
		if c.OnUsageError != nil {
			err := c.OnUsageError(context, err, false)
			context.App.handleExitCoder(context, err)
			return err
		}
		fmt.Fprintln(context.App.Writer, "Incorrect Usage:", err.Error())
		fmt.Fprintln(context.App.Writer)
		ShowCommandHelp(context, c.Name)
		return err
	}

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

	if c.After != nil {
		defer func() {
			afterErr := c.After(context)
			if afterErr != nil {
				context.App.handleExitCoder(context, err)
				if err != nil {
					err = NewMultiError(err, afterErr)
				} else {
					err = afterErr
				}
			}
		}()
	}

	if c.Before != nil {
		err = c.Before(context)
		if err != nil {
			ShowCommandHelp(context, c.Name)
			context.App.handleExitCoder(context, err)
			return err
		}
	}

	if c.Action == nil {
		c.Action = helpSubcommand.Action
	}

	err = HandleAction(c.Action, context)

	if err != nil {
		context.App.handleExitCoder(context, err)
	}
	return err
}
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)
}
448790
func (c *EditNICCmd) 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.UpdateNICRequest{
		Nic: &c.nic,
		UpdateMask: getUpdateMask(&c.Flags, map[string]string{
			"mac":    "mac_address",
			"switch": "switch",
			"port":   "switchport",
		}),
	}
	client := getClient(ctx)
	resp, err := client.UpdateNIC(ctx, req)
	if err != nil {
		errors.Log(ctx, err)
		return 1
	}
	printNICs(c.f.tsv, resp)
	return 0
}
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
}