// Run starts the kubelet reacting to config updates
548619
func (kl *Kubelet) Run(updates <-chan kubetypes.PodUpdate) {
	if kl.logServer == nil {
		kl.logServer = http.StripPrefix("/logs/", http.FileServer(http.Dir("/var/log/")))
	}
	if kl.kubeClient == nil {
		klog.Warning("No api server defined - no node status update will be sent.")
	}

	// Start the cloud provider sync manager
	if kl.cloudResourceSyncManager != nil {
		go kl.cloudResourceSyncManager.Run(wait.NeverStop)
	}

	if err := kl.initializeModules(); err != nil {
		kl.recorder.Eventf(kl.nodeRef, v1.EventTypeWarning, events.KubeletSetupFailed, err.Error())
		klog.Fatal(err)
	}

	// Start volume manager
	go kl.volumeManager.Run(kl.sourcesReady, wait.NeverStop)

	if kl.kubeClient != nil {
		// Start syncing node status immediately, this may set up things the runtime needs to run.
		go wait.Until(kl.syncNodeStatus, kl.nodeStatusUpdateFrequency, wait.NeverStop)
		go kl.fastStatusUpdateOnce()

		// start syncing lease
		if utilfeature.DefaultFeatureGate.Enabled(features.NodeLease) {
			go kl.nodeLeaseController.Run(wait.NeverStop)
		}
	}
	go wait.Until(kl.updateRuntimeUp, 5*time.Second, wait.NeverStop)

	// Start loop to sync iptables util rules
	if kl.makeIPTablesUtilChains {
		go wait.Until(kl.syncNetworkUtil, 1*time.Minute, wait.NeverStop)
	}

	// Start a goroutine responsible for killing pods (that are not properly
	// handled by pod workers).
	go wait.Until(kl.podKiller, 1*time.Second, wait.NeverStop)

	// Start component sync loops.
	kl.statusManager.Start()
	kl.probeManager.Start()

	// Start syncing RuntimeClasses if enabled.
	if kl.runtimeClassManager != nil {
		kl.runtimeClassManager.Start(wait.NeverStop)
	}

	// Start the pod lifecycle event generator.
	kl.pleg.Start()
	kl.syncLoop(updates, kl)
}
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)
}
773753
func (d *DevList) Run(m libkb.MetaContext) (err error) {
	defer m.Trace("DevList#Run", func() error { return err })()

	var devs libkb.DeviceKeyMap
	var ss *libkb.SecretSyncer

	ss, err = m.ActiveDevice().SyncSecretsForce(m)
	if err != nil {
		return err
	}
	devs, err = ss.ActiveDevices(libkb.AllDeviceTypes)
	if err != nil {
		return err
	}

	var pdevs []keybase1.Device
	for k, v := range devs {
		pdevs = append(pdevs, keybase1.Device{
			Type:         v.Type,
			Name:         v.Display(),
			DeviceID:     k,
			CTime:        keybase1.TimeFromSeconds(v.CTime),
			MTime:        keybase1.TimeFromSeconds(v.MTime),
			LastUsedTime: keybase1.TimeFromSeconds(v.LastUsedTime),
		})
	}
	sort.Sort(dname(pdevs))
	d.devices = pdevs

	return nil
}
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
}
1062481
func (cli *CLI) Run(args []string) {
	configFile = cli.app.Flag("configFile", "Specifies the config file to load the configuration from").String()
	persist := cli.app.Command(saveConfigCommand, fmt.Sprintf("Save the config passed by flags into the file specified by --configFile"))
	configureFlags(cli.app)

	command := kingpin.MustParse(cli.app.Parse(args))
	if command == persist.FullCommand() {
		if *configFile == "" {
			out("--configFile must be used to specify the configuration file")
			return
		}
		persistConfig(parseFlagsToConfig(), *configFile)
		return
	}

	var conf Config
	if *configFile == "" {
		conf = parseFlagsToConfig()
	} else {
		conf = loadConfig(*configFile)
	}

	f, exists := cli.dispatchers[command]
	if !exists {
		out("Unknown command:", command)
		terminate(1)
		return
	}
	err := f(conf)
	if err != nil {
		out(err)
		terminate(1)
		return
	}
}
428507
func (c *EditMachineCmd) 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.UpdateMachineRequest{
		Machine: &c.machine,
		UpdateMask: getUpdateMask(&c.Flags, map[string]string{
			"plat":     "platform",
			"rack":     "rack",
			"state":    "state",
			"desc":     "description",
			"atag":     "asset_tag",
			"stag":     "service_tag",
			"tick":     "deployment_ticket",
			"dracpass": "drac_password",
		}),
	}
	client := getClient(ctx)
	resp, err := client.UpdateMachine(ctx, req)
	if err != nil {
		errors.Log(ctx, err)
		return 1
	}
	printMachines(c.f.tsv, resp)
	return 0
}
806956
func Run(ctx context.Context, cfg Config, newTeleport NewProcess) error {
	if newTeleport == nil {
		newTeleport = newTeleportProcess
	}
	copyCfg := cfg
	srv, err := newTeleport(&copyCfg)
	if err != nil {
		return trace.Wrap(err, "initialization failed")
	}
	if srv == nil {
		return trace.BadParameter("process has returned nil server")
	}
	if err := srv.Start(); err != nil {
		return trace.Wrap(err, "startup failed")
	}
	// Wait and reload until called exit.
	for {
		srv, err = waitAndReload(ctx, cfg, srv, newTeleport)
		if err != nil {
			// This error means that was a clean shutdown
			// and no reload is necessary.
			if err == ErrTeleportExited {
				return nil
			}
			return trace.Wrap(err)
		}
	}
}
73500
func (o *CreateSubcommandOptions) Run() error {
	obj, err := o.StructuredGenerator.StructuredGenerate()
	if err != nil {
		return err
	}
	if !o.DryRun {
		// create subcommands have compiled knowledge of things they create, so type them directly
		gvks, _, err := scheme.Scheme.ObjectKinds(obj)
		if err != nil {
			return err
		}
		gvk := gvks[0]
		mapping, err := o.Mapper.RESTMapping(schema.GroupKind{Group: gvk.Group, Kind: gvk.Kind}, gvk.Version)
		if err != nil {
			return err
		}

		if err := kubectl.CreateOrUpdateAnnotation(o.CreateAnnotation, obj, scheme.DefaultJSONEncoder()); err != nil {
			return err
		}

		asUnstructured := &unstructured.Unstructured{}

		if err := scheme.Scheme.Convert(obj, asUnstructured, nil); err != nil {
			return err
		}
		if mapping.Scope.Name() == meta.RESTScopeNameRoot {
			o.Namespace = ""
		}
		actualObject, err := o.DynamicClient.Resource(mapping.Resource).Namespace(o.Namespace).Create(asUnstructured, metav1.CreateOptions{})
		if err != nil {
			return err
		}

		// ensure we pass a versioned object to the printer
		obj = actualObject
	} else {
		if meta, err := meta.Accessor(obj); err == nil && o.EnforceNamespace {
			meta.SetNamespace(o.Namespace)
		}
	}

	return o.PrintObj(obj, o.Out)
}
495291
func (s *Config) Run(ctx context.Context) error {

	s.Lock()
	defer s.Unlock()

	if err := s.impl.Run(ctx); err != nil {
		return fmt.Errorf("unable to start the implementer: %s", err)
	}

	if err := s.impl.SetTargetNetworks(s.cfg); err != nil {
		return err
	}

	if s.service != nil {
		s.service.Initialize(s.filterQueue, s.impl.ACLProvider())
	}

	return nil
}
980116
func (e *MirrorSecrets) Run(c *fi.Context) error {
	return fi.DefaultDeltaRunMethod(e, c)
}
580955
func (e *SaltpackSign) Run(m libkb.MetaContext) error {
	if err := e.loadKey(m); err != nil {
		return err
	}

	saltpackVersion, err := libkb.SaltpackVersionFromArg(e.arg.Opts.SaltpackVersion)
	if err != nil {
		return err
	}

	if e.arg.Opts.Detached {
		return libkb.SaltpackSignDetached(e.G(), e.arg.Source, e.arg.Sink, e.key, e.arg.Opts.Binary, saltpackVersion)
	}

	return libkb.SaltpackSign(e.G(), e.arg.Source, e.arg.Sink, e.key, e.arg.Opts.Binary, saltpackVersion)
}
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()
			}
		}

	}
}
132335
func (c *Container) Run(ctx context.Context, configOverride *config.ServiceConfig) (int, error) {
	var (
		errCh       chan error
		out, stderr io.Writer
		in          io.ReadCloser
		inFd        uintptr
	)

	if configOverride.StdinOpen {
		in = os.Stdin
	}
	if configOverride.Tty {
		out = os.Stdout
		stderr = os.Stderr
	}

	options := types.ContainerAttachOptions{
		Stream: true,
		Stdin:  configOverride.StdinOpen,
		Stdout: configOverride.Tty,
		Stderr: configOverride.Tty,
	}

	resp, err := c.client.ContainerAttach(ctx, c.container.ID, options)
	if err != nil {
		return -1, err
	}

	if configOverride.StdinOpen {
		// set raw terminal
		inFd, _ = term.GetFdInfo(in)
		state, err := term.SetRawTerminal(inFd)
		if err != nil {
			return -1, err
		}
		// restore raw terminal
		defer term.RestoreTerminal(inFd, state)
	}

	// holdHijackedConnection (in goroutine)
	errCh = make(chan error, 1)
	go func() {
		errCh <- holdHijackedConnection(configOverride.Tty, in, out, stderr, resp)
	}()

	if err := c.client.ContainerStart(ctx, c.container.ID, types.ContainerStartOptions{}); err != nil {
		return -1, err
	}

	if configOverride.Tty {
		ws, err := term.GetWinsize(inFd)
		if err != nil {
			return -1, err
		}

		resizeOpts := types.ResizeOptions{
			Height: uint(ws.Height),
			Width:  uint(ws.Width),
		}

		if err := c.client.ContainerResize(ctx, c.container.ID, resizeOpts); err != nil {
			return -1, err
		}
	}

	if err := <-errCh; err != nil {
		logrus.Debugf("Error hijack: %s", err)
		return -1, err
	}

	exitedContainer, err := c.client.ContainerInspect(ctx, c.container.ID)
	if err != nil {
		return -1, err
	}

	return exitedContainer.State.ExitCode, nil
}
871666
func (cmd *ConfigCommand) Run(_ context.Context) error {
	buf, err := toml.Marshal(*cmd.Config)
	if err != nil {
		return err
	}
	fmt.Fprintln(cmd.Stdout, string(buf))
	return nil
}
1174906
func (m *cloudResourceSyncManager) Run(stopCh <-chan struct{}) {
	wait.Until(m.syncNodeAddresses, m.syncPeriod, stopCh)
}
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)
}
349349
func (c *Client) run() {
	// Watch for changes in allocations
	allocUpdates := make(chan *allocUpdates, 8)
	go c.watchAllocations(allocUpdates)

	for {
		select {
		case update := <-allocUpdates:
			// Don't apply updates while shutting down.
			c.shutdownLock.Lock()
			if c.shutdown {
				c.shutdownLock.Unlock()
				return
			}

			// Apply updates inside lock to prevent a concurrent
			// shutdown.
			c.runAllocs(update)
			c.shutdownLock.Unlock()

		case <-c.shutdownCh:
			return
		}
	}
}