// RunSelector executes the command.
5611
func (o *SetSelectorOptions) RunSelector() error {
	r := o.ResourceFinder.Do()

	return r.Visit(func(info *resource.Info, err error) error {
		patch := &Patch{Info: info}
		CalculatePatch(patch, scheme.DefaultJSONEncoder(), func(obj runtime.Object) ([]byte, error) {
			selectErr := updateSelectorForObject(info.Object, *o.selector)
			if selectErr != nil {
				return nil, selectErr
			}

			// record this change (for rollout history)
			if err := o.Recorder.Record(patch.Info.Object); err != nil {
				klog.V(4).Infof("error recording current command: %v", err)
			}

			return runtime.Encode(scheme.DefaultJSONEncoder(), info.Object)
		})

		if patch.Err != nil {
			return patch.Err
		}
		if !o.WriteToServer {
			return o.PrintObj(info.Object, o.Out)
		}

		actual, err := resource.NewHelper(info.Client, info.Mapping).Patch(info.Namespace, info.Name, types.StrategicMergePatchType, patch.Patch, nil)
		if err != nil {
			return err
		}

		return o.PrintObj(actual, o.Out)
	})
}
980997
func (c ConfigSelector) Select(r *http.Request) (config HandlerConfig) {
	for i := range c {
		if !c[i].Match(r) {
			continue
		}
		if config == nil || len(c[i].BasePath()) > len(config.BasePath()) {
			config = c[i]
		}
	}
	return config
}
507045
func RunSource(cmd *exec.Cmd) error {
	cmd.Stdin = os.Stdin
	cmd.Stderr = os.Stderr
	cmd.Stdout = os.Stdout
	return cmd.Run()
}
934834
func RunCommand(cmd *exec.Cmd, silent bool) error {
	if !silent {
		logger.Log(cmd.Args[0], strings.Join(cmd.Args[1:], " "))
	}
	err := CommandRunner(cmd)
	if err != nil {
		if execErr, ok := err.(*exec.Error); ok {
			logger.Log("warning", fmt.Sprintf("%q: %s", execErr.Name, execErr.Err))
		}
		return &RunError{cmd, err}
	}

	return nil
}
307283
func generateSelector(obj *batch.Job) {
	if obj.Spec.Template.Labels == nil {
		obj.Spec.Template.Labels = make(map[string]string)
	}
	// The job-name label is unique except in cases that are expected to be
	// quite uncommon, and is more user friendly than uid.  So, we add it as
	// a label.
	_, found := obj.Spec.Template.Labels["job-name"]
	if found {
		// User asked us to not automatically generate a selector and labels,
		// but set a possibly conflicting value.  If there is a conflict,
		// we will reject in validation.
	} else {
		obj.Spec.Template.Labels["job-name"] = string(obj.ObjectMeta.Name)
	}
	// The controller-uid label makes the pods that belong to this job
	// only match this job.
	_, found = obj.Spec.Template.Labels["controller-uid"]
	if found {
		// User asked us to automatically generate a selector and labels,
		// but set a possibly conflicting value.  If there is a conflict,
		// we will reject in validation.
	} else {
		obj.Spec.Template.Labels["controller-uid"] = string(obj.ObjectMeta.UID)
	}
	// Select the controller-uid label.  This is sufficient for uniqueness.
	if obj.Spec.Selector == nil {
		obj.Spec.Selector = &metav1.LabelSelector{}
	}
	if obj.Spec.Selector.MatchLabels == nil {
		obj.Spec.Selector.MatchLabels = make(map[string]string)
	}
	if _, found := obj.Spec.Selector.MatchLabels["controller-uid"]; !found {
		obj.Spec.Selector.MatchLabels["controller-uid"] = string(obj.ObjectMeta.UID)
	}
	// If the user specified matchLabel controller-uid=$WRONGUID, then it should fail
	// in validation, either because the selector does not match the pod template
	// (controller-uid=$WRONGUID does not match controller-uid=$UID, which we applied
	// above, or we will reject in validation because the template has the wrong
	// labels.
}
1361984
func typeSelector(tag string) Selector {
	tag = toLowerASCII(tag)
	return func(n *html.Node) bool {
		return n.Type == html.ElementNode && n.Data == tag
	}
}
855578
func Run(ctx context.Context, command string, arg []string) (*CommandExecutor, error) {
	if ctx == nil {
		ctx = context.Background()
	}

	if runtime.GOOS == "windows" {
		// For powershell, if running a script we need to execute it with a -File option
		// otherwise the return code will get lost
		if len(arg) == 1 && strings.HasSuffix(arg[0], ".ps1") {
			arg = append([]string{"-File"}, arg...)
		}
	}
	// by default Cancel is spineless unless someone configures an option to enable it
	commandExecutor := &CommandExecutor{Done: make(chan error, 1), done: make(chan error, 1)}

	cmd := exec.CommandContext(ctx, command, arg...)
	go func() {
		var err error
		defer func() { commandExecutor.Done <- err }()

		select {
		case <-ctx.Done():
			err = ctx.Err()
		case err = <-commandExecutor.done:
		}
	}()

	// Create a new PIPE.
	// stdout and stderr will be both redirected to this pipe. When the command is executed / cancelled or timeout
	// reached the pipe will be closed, unblocking the reader.
	r, w := io.Pipe()
	cmd.Stdout = w
	cmd.Stderr = w
	commandExecutor.pipe = r

	// execute the command in the goroutine.
	go func() {
		defer w.Close()
		commandExecutor.done <- cmd.Run()
	}()

	return commandExecutor, nil
}
1050930
func (o *Organizer) Run() {
	if o.only != nil {
		o.runTest(o.only)
		return
	}

	for _, test := range o.tests {
		o.runTest(&test)
	}
}
202045
func (svc *AsyncService) Run() error {
	for {
		e, open := <-svc.c
		if open {
			// Call event handler
			svc.i.HandleEvent(e)
		} else {
			// Exit runner
			break
		}
	}
	return nil
}
448252
func DoLeaderElection(ctx context.Context, logger *zap.Logger, component string, config LeaderElectionOptions, configMapsGetter core_v1client.ConfigMapsGetter, recorder record.EventRecorder) (context.Context, error) {
	id, err := os.Hostname()
	if err != nil {
		return nil, err
	}
	ctxRet, cancel := context.WithCancel(ctx)
	startedLeading := make(chan struct{})
	le, err := leaderelection.NewLeaderElector(leaderelection.LeaderElectionConfig{
		Lock: &resourcelock.ConfigMapLock{
			ConfigMapMeta: meta_v1.ObjectMeta{
				Namespace: config.ConfigMapNamespace,
				Name:      config.ConfigMapName,
			},
			Client: configMapsGetter,
			LockConfig: resourcelock.ResourceLockConfig{
				Identity:      id + "-" + component,
				EventRecorder: recorder,
			},
		},
		LeaseDuration: config.LeaseDuration,
		RenewDeadline: config.RenewDeadline,
		RetryPeriod:   config.RetryPeriod,
		Callbacks: leaderelection.LeaderCallbacks{
			OnStartedLeading: func(ctx context.Context) {
				logger.Info("Started leading")
				close(startedLeading)
			},
			OnStoppedLeading: func() {
				logger.Info("Leader status lost")
				cancel()
			},
		},
	})
	if err != nil {
		cancel()
		return nil, err
	}
	go func() {
		// note: because le.Run() also adds a logging panic handler panics with be logged 3 times
		defer logz.LogStructuredPanic()
		le.Run(ctx)
	}()
	select {
	case <-ctx.Done():
		return nil, ctx.Err()
	case <-startedLeading:
		return ctxRet, nil
	}
}
728742
func (c *Client) RunScript(script string) *exec.Cmd {
	nodePath, err := filepath.Rel(c.RootPath, c.nodePath())
	if err != nil {
		panic(err)
	}
	cmd := exec.Command(nodePath, "-e", script)
	cmd.Dir = c.RootPath
	return cmd
}
839068
func ValidateNodeSelector(nodeSelector *core.NodeSelector, fldPath *field.Path) field.ErrorList {
	allErrs := field.ErrorList{}

	termFldPath := fldPath.Child("nodeSelectorTerms")
	if len(nodeSelector.NodeSelectorTerms) == 0 {
		return append(allErrs, field.Required(termFldPath, "must have at least one node selector term"))
	}

	for i, term := range nodeSelector.NodeSelectorTerms {
		allErrs = append(allErrs, ValidateNodeSelectorTerm(term, termFldPath.Index(i))...)
	}

	return allErrs
}
1270288
func (s *Parameter) SetSelector(v string) *Parameter {
	s.Selector = &v
	return s
}
271348
func NewSelector(client RESTClient, mapping *meta.RESTMapping, namespace string, selector labels.Selector, export bool) *Selector {
	return &Selector{
		Client:    client,
		Mapping:   mapping,
		Namespace: namespace,
		Selector:  selector,
		Export:    export,
	}
}
483567
func RunCommand(
	ctx types.Context,
	cmd *exec.Cmd,
	ignoreCodes ...int) ([]byte, int, error) {

	ctx.WithField("args", cmd.Args).Debug("running command")

	out, err := cmd.Output()
	if err == nil {
		return out, 0, nil
	}

	exitStatus := -1
	if exiterr, ok := err.(*exec.ExitError); ok {
		stderr := string(exiterr.Stderr)
		errRet := goof.Newf("Error running command: %s", stderr)
		supMsg := "ignoring error due to matched return code"
		fields := map[string]interface{}{
			"args":   cmd.Args,
			"stderr": stderr,
		}

		if ws, ok := exiterr.Sys().(syscall.WaitStatus); ok {
			exitStatus = ws.ExitStatus()
			if len(ignoreCodes) > 0 {
				for _, rc := range ignoreCodes {
					if exitStatus == rc {
						fields["exitcode"] = rc
						ctx.WithFields(
							fields).Debug(
							supMsg,
						)
						return nil,
							exitStatus,
							errRet
					}
				}
			}
		}

		ctx.WithError(
			exiterr,
		).WithFields(fields).Error("Error running command")

		return nil,
			exitStatus,
			errRet
	}
	return nil, exitStatus, goof.Newe(err)
}
459177
func runAsNewCommand(cmd CommandRunner, mode string) {
	execCmd, ok := cmd.(ExecRunner)
	if !ok {
		panic(fmt.Sprintf("%v does not implement ExecRunner", mode))
	}
	cmdPath, err := execCmd.LookPath()
	if err != nil {
		Errorf("Error: %v\n", err)
		Exit(2)
	}
	allArgs := shiftFlags(mode)
	if err := runExec(cmdPath, allArgs, newCopyEnv()); err != nil {
		panic(fmt.Sprintf("running %v should have ended with an os.Exit, and not leave us with that error: %v", cmdPath, err))
	}
}
883683
func (o *GetOptions) Run(f cmdutil.Factory, cmd *cobra.Command, args []string) error {
	if len(o.Raw) > 0 {
		return o.raw(f)
	}
	if o.Watch || o.WatchOnly {
		return o.watch(f, cmd, args)
	}

	chunkSize := o.ChunkSize
	if o.Sort {
		// TODO(juanvallejo): in the future, we could have the client use chunking
		// to gather all results, then sort them all at the end to reduce server load.
		chunkSize = 0
	}

	r := f.NewBuilder().
		Unstructured().
		NamespaceParam(o.Namespace).DefaultNamespace().AllNamespaces(o.AllNamespaces).
		FilenameParam(o.ExplicitNamespace, &o.FilenameOptions).
		LabelSelectorParam(o.LabelSelector).
		FieldSelectorParam(o.FieldSelector).
		ExportParam(o.Export).
		RequestChunksOf(chunkSize).
		ResourceTypeOrNameArgs(true, args...).
		ContinueOnError().
		Latest().
		Flatten().
		TransformRequests(o.transformRequests).
		Do()

	if o.IgnoreNotFound {
		r.IgnoreErrors(kapierrors.IsNotFound)
	}
	if err := r.Err(); err != nil {
		return err
	}

	if !o.IsHumanReadablePrinter {
		return o.printGeneric(r)
	}

	allErrs := []error{}
	errs := sets.NewString()
	infos, err := r.Infos()
	if err != nil {
		allErrs = append(allErrs, err)
	}
	printWithKind := multipleGVKsRequested(infos)

	objs := make([]runtime.Object, len(infos))
	for ix := range infos {
		objs[ix] = infos[ix].Object
	}

	sorting, err := cmd.Flags().GetString("sort-by")
	if err != nil {
		return err
	}

	var positioner OriginalPositioner
	if o.Sort {
		sorter := NewRuntimeSorter(objs, sorting)
		if err := sorter.Sort(); err != nil {
			return err
		}
		positioner = sorter
	}

	var printer printers.ResourcePrinter
	var lastMapping *meta.RESTMapping

	// track if we write any output
	trackingWriter := &trackingWriterWrapper{Delegate: o.Out}

	w := utilprinters.GetNewTabWriter(trackingWriter)
	for ix := range objs {
		var mapping *meta.RESTMapping
		var info *resource.Info
		if positioner != nil {
			info = infos[positioner.OriginalPosition(ix)]
			mapping = info.Mapping
		} else {
			info = infos[ix]
			mapping = info.Mapping
		}

		printWithNamespace := o.AllNamespaces

		if mapping != nil && mapping.Scope.Name() == meta.RESTScopeNameRoot {
			printWithNamespace = false
		}

		if shouldGetNewPrinterForMapping(printer, lastMapping, mapping) {
			w.Flush()
			w.SetRememberedWidths(nil)

			// TODO: this doesn't belong here
			// add linebreak between resource groups (if there is more than one)
			// skip linebreak above first resource group
			if lastMapping != nil && !o.NoHeaders {
				fmt.Fprintln(o.ErrOut)
			}

			printer, err = o.ToPrinter(mapping, printWithNamespace, printWithKind)
			if err != nil {
				if !errs.Has(err.Error()) {
					errs.Insert(err.Error())
					allErrs = append(allErrs, err)
				}
				continue
			}

			lastMapping = mapping
		}

		// ensure a versioned object is passed to the custom-columns printer
		// if we are using OpenAPI columns to print
		if o.PrintWithOpenAPICols {
			printer.PrintObj(info.Object, w)
			continue
		}

		internalObj, err := legacyscheme.Scheme.ConvertToVersion(info.Object, info.Mapping.GroupVersionKind.GroupKind().WithVersion(runtime.APIVersionInternal).GroupVersion())
		if err != nil {
			// if there's an error, try to print what you have (mirrors old behavior).
			klog.V(1).Info(err)
			printer.PrintObj(info.Object, w)
		} else {
			printer.PrintObj(internalObj, w)
		}
	}
	w.Flush()
	if trackingWriter.Written == 0 && !o.IgnoreNotFound && len(allErrs) == 0 {
		// if we wrote no output, and had no errors, and are not ignoring NotFound, be sure we output something
		fmt.Fprintln(o.ErrOut, "No resources found.")
	}
	return utilerrors.NewAggregate(allErrs)
}