// ToRun transitions a pod from prepared -> run, leaves the pod locked in the run directory.
// the creator of the pod (via NewPod()) may also jump directly from preparing -> run
// This method refreshes the pod state.
10885
func (p *Pod) ToRun() error {
	if !p.createdByMe && !p.isPrepared {
		return fmt.Errorf("bug: only prepared pods may transition to run")
	}

	if p.createdByMe && !p.isPrepared && !p.isPreparing {
		return fmt.Errorf("bug: only prepared or preparing pods may transition to run")
	}

	if err := p.ExclusiveLock(); err != nil {
		return err
	}
	label.Relabel(p.Path(), p.MountLabel, false)
	if err := os.Rename(p.Path(), p.runPath()); err != nil {
		// TODO(vc): we could race here with a concurrent ToRun(), let caller deal with the error.
		return err
	}

	df, err := os.Open(runDir(p.dataDir))
	if err != nil {
		return err
	}
	defer df.Close()
	if err := df.Sync(); err != nil {
		return err
	}

	p.isPreparing = false
	p.isPrepared = false

	return nil
}
1094286
func (m *MockCoreV1Interface) Pods(arg0 string) v11.PodInterface {
	ret := m.ctrl.Call(m, "Pods", arg0)
	ret0, _ := ret[0].(v11.PodInterface)
	return ret0
}
979114
func (cache *schedulerCache) addPod(pod *v1.Pod) {
	n, ok := cache.nodes[pod.Spec.NodeName]
	if !ok {
		n = newNodeInfoListItem(schedulernodeinfo.NewNodeInfo())
		cache.nodes[pod.Spec.NodeName] = n
	}
	n.info.AddPod(pod)
	cache.moveNodeInfoToHead(pod.Spec.NodeName)
}
830951
func (c *Container) arrayToRun(numRuns int32) {
	statsHit("arrayToRun")
	array := c.array()
	c.typ = containerRun
	c.mapped = false
	// return early if empty
	if c.n == 0 {
		c.setRuns(nil)
		return
	}
	if numRuns == 0 {
		numRuns = arrayCountRuns(array)
	}

	runs := make([]interval16, 0, numRuns)
	start := array[0]
	for i, v := range array[1:] {
		if v-array[i] > 1 {
			// if current-previous > 1, one run ends and another begins
			runs = append(runs, interval16{start, array[i]})
			start = v
		}
	}
	// append final run
	runs = append(runs, interval16{start, array[c.n-1]})
	c.setRuns(runs)
}
1328874
func Start(toRun Funk) {
	flag.Parse()
	if PersistPID(*DaemonPIDFile) {
		LogDaemon("Started daemon.")
		toRun()
		LogDaemon("Daemon finished task.")
	} else {
		LogDaemon("Daemon seem to already run. Start failed.")
	}
}
482739
func Run(kv *staert.KvSource, traefikConfiguration *cmd.TraefikConfiguration) func() error {
	return func() error {
		if kv == nil {
			return fmt.Errorf("error using command storeconfig, no Key-value store defined")
		}

		fileConfig := traefikConfiguration.Providers.File
		if fileConfig != nil {
			traefikConfiguration.Providers.File = nil
			if len(fileConfig.Filename) == 0 && len(fileConfig.Directory) == 0 {
				fileConfig.Filename = traefikConfiguration.ConfigFile
			}
		}

		jsonConf, err := json.Marshal(traefikConfiguration.Configuration)
		if err != nil {
			return err
		}
		stdlog.Printf("Storing configuration: %s\n", jsonConf)

		err = kv.StoreConfig(traefikConfiguration.Configuration)
		if err != nil {
			return err
		}

		if fileConfig != nil {
			jsonConf, err = json.Marshal(fileConfig)
			if err != nil {
				return err
			}

			stdlog.Printf("Storing file configuration: %s\n", jsonConf)
			config, err := fileConfig.BuildConfiguration()
			if err != nil {
				return err
			}

			stdlog.Print("Writing config to KV")
			err = kv.StoreConfig(config)
			if err != nil {
				return err
			}
		}

		// if traefikConfiguration.Configuration.ACME != nil {
		// 	account := &acme.Account{}
		//
		// 	accountInitialized, err := keyExists(kv, traefikConfiguration.Configuration.ACME.Storage)
		// 	if err != nil && err != store.ErrKeyNotFound {
		// 		return err
		// 	}
		//
		// 	// Check to see if ACME account object is already in kv store
		// 	if traefikConfiguration.Configuration.ACME.OverrideCertificates || !accountInitialized {
		//
		// 		// Stores the ACME Account into the KV Store
		// 		// Certificates in KV Stores will be overridden
		// 		meta := cluster.NewMetadata(account)
		// 		err = meta.Marshall()
		// 		if err != nil {
		// 			return err
		// 		}
		//
		// 		source := staert.KvSource{
		// 			Store:  kv,
		// 			Prefix: traefikConfiguration.Configuration.ACME.Storage,
		// 		}
		//
		// 		err = source.StoreConfig(meta)
		// 		if err != nil {
		// 			return err
		// 		}
		// 	}
		// }
		return nil
	}
}
1262192
func (_m *Marathon) UpdatePod(pod *marathon.Pod, force bool) (*marathon.Pod, error) {
	ret := _m.Called(pod, force)

	var r0 *marathon.Pod
	if rf, ok := ret.Get(0).(func(*marathon.Pod, bool) *marathon.Pod); ok {
		r0 = rf(pod, force)
	} else {
		if ret.Get(0) != nil {
			r0 = ret.Get(0).(*marathon.Pod)
		}
	}

	var r1 error
	if rf, ok := ret.Get(1).(func(*marathon.Pod, bool) error); ok {
		r1 = rf(pod, force)
	} else {
		r1 = ret.Error(1)
	}

	return r0, r1
}
1137262
func (r *marathonClient) Pod(name string) (*Pod, error) {
	uri := buildPodURI(name)
	result := new(Pod)
	if err := r.apiGet(uri, nil, result); err != nil {
		return nil, err
	}

	return result, nil
}
241314
func (m *PodMonitor) Run(ctx context.Context) error {
	if m.kubeCfg == nil {
		return errors.New("pod: missing kubeconfig")
	}

	if err := m.handlers.IsComplete(); err != nil {
		return fmt.Errorf("pod: %s", err.Error())
	}

	mgr, err := manager.New(m.kubeCfg, manager.Options{})
	if err != nil {
		return fmt.Errorf("pod: %s", err.Error())
	}

	r := newReconciler(mgr, m.handlers, m.metadataExtractor, m.netclsProgrammer, m.localNode, m.enableHostPods)
	if err := addController(mgr, r, m.eventsCh); err != nil {
		return fmt.Errorf("pod: %s", err.Error())
	}

	controllerStarted := make(chan struct{})
	if err := mgr.Add(&runnable{ch: controllerStarted}); err != nil {
		return fmt.Errorf("pod: %s", err.Error())
	}

	// starting the manager is a bit awkward:
	// - it does not use contexts
	// - we pass in a fake signal handler channel
	// - we start another go routine which waits for the context to be cancelled
	//   and closes that channel if that is the case
	// -
	z := make(chan struct{})
	errCh := make(chan error, 2)
	go func() {
		<-ctx.Done()
		close(z)
		errCh <- ctx.Err()
	}()
	go func() {
		if err := mgr.Start(z); err != nil {
			errCh <- err
		}
	}()

	select {
	case err := <-errCh:
		return fmt.Errorf("pod: %s", err.Error())
	case <-time.After(5 * time.Second):
		// we give the controller 5 seconds to report back
		return errors.New("pod: controller did not start within 5s")
	case <-controllerStarted:
		m.kubeClient = mgr.GetClient()
		return nil
	}
}
303534
func (p *Pod) Path() string {
	switch {
	case p.isEmbryo:
		return p.embryoPath()
	case p.isPreparing || p.isAbortedPrepare:
		return p.preparePath()
	case p.isPrepared:
		return p.preparedPath()
	case p.isExitedGarbage:
		return p.exitedGarbagePath()
	case p.isGarbage:
		return p.garbagePath()
	case p.isGone:
		return "" // TODO(vc): anything better?
	}

	return p.runPath()
}
1198345
func (o *AttachOptions) Run() error {
	if o.Pod == nil {
		b := o.Builder().
			WithScheme(scheme.Scheme, scheme.Scheme.PrioritizedVersionsAllGroups()...).
			NamespaceParam(o.Namespace).DefaultNamespace()

		switch len(o.Resources) {
		case 1:
			b.ResourceNames("pods", o.Resources[0])
		case 2:
			b.ResourceNames(o.Resources[0], o.Resources[1])
		}

		obj, err := b.Do().Object()
		if err != nil {
			return err
		}

		o.Pod, err = o.findAttachablePod(obj)
		if err != nil {
			return err
		}

		if o.Pod.Status.Phase == corev1.PodSucceeded || o.Pod.Status.Phase == corev1.PodFailed {
			return fmt.Errorf("cannot attach a container in a completed pod; current phase is %s", o.Pod.Status.Phase)
		}
		// TODO: convert this to a clean "wait" behavior
	}

	// check for TTY
	containerToAttach, err := o.containerToAttachTo(o.Pod)
	if err != nil {
		return fmt.Errorf("cannot attach to the container: %v", err)
	}
	if o.TTY && !containerToAttach.TTY {
		o.TTY = false
		if o.ErrOut != nil {
			fmt.Fprintf(o.ErrOut, "Unable to use a TTY - container %s did not allocate one\n", containerToAttach.Name)
		}
	} else if !o.TTY && containerToAttach.TTY {
		// the container was launched with a TTY, so we have to force a TTY here, otherwise you'll get
		// an error "Unrecognized input header"
		o.TTY = true
	}

	// ensure we can recover the terminal while attached
	t := o.SetupTTY()

	var sizeQueue remotecommand.TerminalSizeQueue
	if t.Raw {
		if size := t.GetSize(); size != nil {
			// fake resizing +1 and then back to normal so that attach-detach-reattach will result in the
			// screen being redrawn
			sizePlusOne := *size
			sizePlusOne.Width++
			sizePlusOne.Height++

			// this call spawns a goroutine to monitor/update the terminal size
			sizeQueue = t.MonitorSize(&sizePlusOne, size)
		}

		o.DisableStderr = true
	}

	if !o.Quiet {
		fmt.Fprintln(o.ErrOut, "If you don't see a command prompt, try pressing enter.")
	}
	if err := t.Safe(o.AttachFunc(o, containerToAttach, t.Raw, sizeQueue)); err != nil {
		return err
	}

	if o.Stdin && t.Raw && o.Pod.Spec.RestartPolicy == corev1.RestartPolicyAlways {
		fmt.Fprintf(o.Out, "Session ended, resume using '%s %s -c %s -i -t' command when the pod is running\n", o.CommandName, o.Pod.Name, containerToAttach.Name)
	}
	return nil
}
976022
func (e *Runner) Run(args []string) error {
	e.prepareForExecution()

	// determine which phase should be run according to RunnerOptions
	phaseRunFlags, err := e.computePhaseRunFlags()
	if err != nil {
		return err
	}

	// builds the runner data
	var data RunData
	if data, err = e.InitData(args); err != nil {
		return err
	}

	err = e.visitAll(func(p *phaseRunner) error {
		// if the phase should not be run, skip the phase.
		if run, ok := phaseRunFlags[p.generatedName]; !run || !ok {
			return nil
		}

		// Errors if phases that are meant to create special subcommands only
		// are wrongly assigned Run Methods
		if p.RunAllSiblings && (p.RunIf != nil || p.Run != nil) {
			return errors.Wrapf(err, "phase marked as RunAllSiblings can not have Run functions %s", p.generatedName)
		}

		// If the phase defines a condition to be checked before executing the phase action.
		if p.RunIf != nil {
			// Check the condition and returns if the condition isn't satisfied (or fails)
			ok, err := p.RunIf(data)
			if err != nil {
				return errors.Wrapf(err, "error execution run condition for phase %s", p.generatedName)
			}

			if !ok {
				return nil
			}
		}

		// Runs the phase action (if defined)
		if p.Run != nil {
			if err := p.Run(data); err != nil {
				return errors.Wrapf(err, "error execution phase %s", p.generatedName)
			}
		}

		return nil
	})

	return err
}
1286796
func (p *ExecOptions) Run() error {
	var err error
	// we still need legacy pod getter when PodName in ExecOptions struct is provided,
	// since there are any other command run this function by providing Podname with PodsGetter
	// and without resource builder, eg: `kubectl cp`.
	if len(p.PodName) != 0 {
		p.Pod, err = p.PodClient.Pods(p.Namespace).Get(p.PodName, metav1.GetOptions{})
		if err != nil {
			return err
		}
	} else {
		builder := p.Builder().
			WithScheme(scheme.Scheme, scheme.Scheme.PrioritizedVersionsAllGroups()...).
			NamespaceParam(p.Namespace).DefaultNamespace().ResourceNames("pods", p.ResourceName)

		obj, err := builder.Do().Object()
		if err != nil {
			return err
		}

		p.Pod, err = p.ExecutablePodFn(p.restClientGetter, obj, p.GetPodTimeout)
		if err != nil {
			return err
		}
	}

	pod := p.Pod

	if pod.Status.Phase == corev1.PodSucceeded || pod.Status.Phase == corev1.PodFailed {
		return fmt.Errorf("cannot exec into a container in a completed pod; current phase is %s", pod.Status.Phase)
	}

	containerName := p.ContainerName
	if len(containerName) == 0 {
		if len(pod.Spec.Containers) > 1 {
			usageString := fmt.Sprintf("Defaulting container name to %s.", pod.Spec.Containers[0].Name)
			if len(p.SuggestedCmdUsage) > 0 {
				usageString = fmt.Sprintf("%s\n%s", usageString, p.SuggestedCmdUsage)
			}
			fmt.Fprintf(p.ErrOut, "%s\n", usageString)
		}
		containerName = pod.Spec.Containers[0].Name
	}

	// ensure we can recover the terminal while attached
	t := p.SetupTTY()

	var sizeQueue remotecommand.TerminalSizeQueue
	if t.Raw {
		// this call spawns a goroutine to monitor/update the terminal size
		sizeQueue = t.MonitorSize(t.GetSize())

		// unset p.Err if it was previously set because both stdout and stderr go over p.Out when tty is
		// true
		p.ErrOut = nil
	}

	fn := func() error {
		restClient, err := restclient.RESTClientFor(p.Config)
		if err != nil {
			return err
		}

		// TODO: consider abstracting into a client invocation or client helper
		req := restClient.Post().
			Resource("pods").
			Name(pod.Name).
			Namespace(pod.Namespace).
			SubResource("exec")
		req.VersionedParams(&corev1.PodExecOptions{
			Container: containerName,
			Command:   p.Command,
			Stdin:     p.Stdin,
			Stdout:    p.Out != nil,
			Stderr:    p.ErrOut != nil,
			TTY:       t.Raw,
		}, scheme.ParameterCodec)

		return p.Executor.Execute("POST", req.URL(), p.Config, p.In, p.Out, p.ErrOut, t.Raw, sizeQueue)
	}

	if err := t.Safe(fn); err != nil {
		return err
	}

	return nil
}
1024750
func canRunPod(pod *v1.Pod) error {
	if !capabilities.Get().AllowPrivileged {
		for _, container := range pod.Spec.Containers {
			if securitycontext.HasPrivilegedRequest(&container) {
				return fmt.Errorf("pod with UID %q specified privileged container, but is disallowed", pod.UID)
			}
		}
		for _, container := range pod.Spec.InitContainers {
			if securitycontext.HasPrivilegedRequest(&container) {
				return fmt.Errorf("pod with UID %q specified privileged init container, but is disallowed", pod.UID)
			}
		}
	}

	if pod.Spec.HostNetwork {
		allowed, err := allowHostNetwork(pod)
		if err != nil {
			return err
		}
		if !allowed {
			return fmt.Errorf("pod with UID %q specified host networking, but is disallowed", pod.UID)
		}
	}

	if pod.Spec.HostPID {
		allowed, err := allowHostPID(pod)
		if err != nil {
			return err
		}
		if !allowed {
			return fmt.Errorf("pod with UID %q specified host PID, but is disallowed", pod.UID)
		}
	}

	if pod.Spec.HostIPC {
		allowed, err := allowHostIPC(pod)
		if err != nil {
			return err
		}
		if !allowed {
			return fmt.Errorf("pod with UID %q specified host ipc, but is disallowed", pod.UID)
		}
	}

	return nil
}
704311
func (c *PodController) Run() {
	glog.Infof("starting pod controller")

	stopCh := c.StopChannel()
	go c.runWatcher(stopCh)

	<-stopCh
	glog.Infof("shutting down pod controller")
}
1039486
func (m *podManager) setup(req *cniserver.PodRequest) (cnitypes.Result, *runningPod, error) {
	defer PodOperationsLatency.WithLabelValues(PodOperationSetup).Observe(sinceInMicroseconds(time.Now()))

	// Release any IPAM allocations and hostports if the setup failed
	var success bool
	defer func() {
		if !success {
			m.ipamDel(req.SandboxID)
			if mappings := m.shouldSyncHostports(nil); mappings != nil {
				if err := m.hostportSyncer.SyncHostports(Tun0, mappings); err != nil {
					klog.Warningf("failed syncing hostports: %v", err)
				}
			}
		}
	}()

	v1Pod, err := m.kClient.CoreV1().Pods(req.PodNamespace).Get(req.PodName, metav1.GetOptions{})
	if err != nil {
		return nil, nil, err
	}

	var ipamResult cnitypes.Result
	podIP := net.ParseIP(req.AssignedIP)
	if podIP == nil {
		ipamResult, podIP, err = m.ipamAdd(req.Netns, req.SandboxID)
		if err != nil {
			return nil, nil, fmt.Errorf("failed to run IPAM for %v: %v", req.SandboxID, err)
		}
		if err := maybeAddMacvlan(v1Pod, req.Netns); err != nil {
			return nil, nil, err
		}
	}

	// Open any hostports the pod wants
	podPortMapping := constructPodPortMapping(v1Pod, podIP)
	if mappings := m.shouldSyncHostports(podPortMapping); mappings != nil {
		if err := m.hostportSyncer.OpenPodHostportsAndSync(podPortMapping, Tun0, mappings); err != nil {
			return nil, nil, err
		}
	}

	vnid, err := m.policy.GetVNID(req.PodNamespace)
	if err != nil {
		return nil, nil, err
	}

	ofport, err := m.ovs.SetUpPod(req.SandboxID, req.HostVeth, podIP, vnid)
	if err != nil {
		return nil, nil, err
	}
	if err := setupPodBandwidth(m.ovs, v1Pod, req.HostVeth, req.SandboxID); err != nil {
		return nil, nil, err
	}

	m.policy.EnsureVNIDRules(vnid)
	success = true
	return ipamResult, &runningPod{podPortMapping: podPortMapping, vnid: vnid, ofport: ofport}, nil
}
1148845
func (c *pods) Create(pod *v1.Pod) (result *v1.Pod, err error) {
	result = &v1.Pod{}
	err = c.client.Post().
		Namespace(c.ns).
		Resource("pods").
		Body(pod).
		Do().
		Into(result)
	return
}