// buildPod is responsible for constructing the pod specification
173369
func (b *KubeSchedulerBuilder) buildPod() (*v1.Pod, error) {
	c := b.Cluster.Spec.KubeScheduler

	flags, err := flagbuilder.BuildFlagsList(c)
	if err != nil {
		return nil, fmt.Errorf("error building kube-scheduler flags: %v", err)
	}
	// Add kubeconfig flag
	flags = append(flags, "--kubeconfig="+"/var/lib/kube-scheduler/kubeconfig")

	if c.UsePolicyConfigMap != nil {
		flags = append(flags, "--policy-configmap=scheduler-policy --policy-configmap-namespace=kube-system")
	}

	pod := &v1.Pod{
		TypeMeta: metav1.TypeMeta{
			APIVersion: "v1",
			Kind:       "Pod",
		},
		ObjectMeta: metav1.ObjectMeta{
			Name:      "kube-scheduler",
			Namespace: "kube-system",
			Labels: map[string]string{
				"k8s-app": "kube-scheduler",
			},
		},
		Spec: v1.PodSpec{
			HostNetwork: true,
		},
	}

	container := &v1.Container{
		Name:  "kube-scheduler",
		Image: c.Image,
		Command: exec.WithTee(
			"/usr/local/bin/kube-scheduler",
			sortedStrings(flags),
			"/var/log/kube-scheduler.log"),
		Env: getProxyEnvVars(b.Cluster.Spec.EgressProxy),
		LivenessProbe: &v1.Probe{
			Handler: v1.Handler{
				HTTPGet: &v1.HTTPGetAction{
					Host: "127.0.0.1",
					Path: "/healthz",
					Port: intstr.FromInt(10251),
				},
			},
			InitialDelaySeconds: 15,
			TimeoutSeconds:      15,
		},
		Resources: v1.ResourceRequirements{
			Requests: v1.ResourceList{
				v1.ResourceCPU: resource.MustParse("100m"),
			},
		},
	}
	addHostPathMapping(pod, container, "varlibkubescheduler", "/var/lib/kube-scheduler")
	addHostPathMapping(pod, container, "logfile", "/var/log/kube-scheduler.log").ReadOnly = false

	pod.Spec.Containers = append(pod.Spec.Containers, *container)

	kubemanifest.MarkPodAsCritical(pod)

	return pod, nil
}
478703
func (r *marathonClient) UpdatePod(pod *Pod, force bool) (*Pod, error) {
	uri := fmt.Sprintf("%s?force=%v", buildPodURI(pod.ID), force)
	result := new(Pod)

	if err := r.apiPut(uri, pod, result); err != nil {
		return nil, err
	}

	return result, nil
}
1018445
func deletePod(p *pkgPod.Pod) bool {
	podState := p.State()
	if podState != pkgPod.ExitedGarbage && podState != pkgPod.Garbage && podState != pkgPod.ExitedDeleting {
		stderr.Errorf("non-garbage pod %q (status %q), skipped", p.UUID, p.State())
		return false
	}

	if podState == pkgPod.ExitedGarbage {
		s, err := imagestore.NewStore(storeDir())
		if err != nil {
			stderr.PrintE("cannot open store", err)
			return false
		}
		defer s.Close()

		ts, err := treestore.NewStore(treeStoreDir(), s)
		if err != nil {
			stderr.PrintE("cannot open store", err)
			return false
		}

		if globalFlags.Debug {
			stage0.InitDebug()
		}

		if newMount, err := mountPodStage1(ts, p); err == nil {
			if err = stage0.GC(p.Path(), p.UUID, globalFlags.LocalConfigDir); err != nil {
				stderr.PrintE(fmt.Sprintf("problem performing stage1 GC on %q", p.UUID), err)
			}
			// Linux <4.13 allows an overlay fs to be mounted over itself, so let's
			// unmount it here to avoid problems when running stage0.MountGC
			if p.UsesOverlay() && newMount {
				stage1Mnt := common.Stage1RootfsPath(p.Path())
				if err := syscall.Unmount(stage1Mnt, 0); err != nil && err != syscall.EBUSY {
					stderr.PrintE("error unmounting stage1", err)
				}
			}
		} else {
			stderr.PrintE("skipping stage1 GC", err)
		}

		// unmount all leftover mounts
		if err := stage0.MountGC(p.Path(), p.UUID.String()); err != nil {
			stderr.PrintE(fmt.Sprintf("GC of leftover mounts for pod %q failed", p.UUID), err)
			return false
		}
	}

	// remove the rootfs first; if this fails (eg. due to busy mountpoints), pod manifest
	// is left in place and clean-up can be re-tried later.
	rootfsPath, err := p.Stage1RootfsPath()
	if err == nil {
		if e := os.RemoveAll(rootfsPath); e != nil {
			stderr.PrintE(fmt.Sprintf("unable to remove pod rootfs %q", p.UUID), e)
			return false
		}
	}

	// finally remove all remaining pieces
	if err := os.RemoveAll(p.Path()); err != nil {
		stderr.PrintE(fmt.Sprintf("unable to remove pod %q", p.UUID), err)
		return false
	}

	return true
}
1263820
func (m *Client) UpdatePod(podName string, pod *client.Pod) (*client.Pod, error) {
	p, ok := m.Pods[podName]
	if !ok {
		return nil, api.ErrNotFound
	}

	updateMetadata(p.Metadata, pod.Metadata)

	pstr, _ := json.Marshal(p)

	m.events <- watch.Event{
		Type:   watch.Modified,
		Object: json.RawMessage(pstr),
	}

	return nil, nil
}
1367460
func (daemon *Daemon) CmdCreatePod(podArgs string) (*engine.Env, error) {
	var podSpec apitypes.UserPod
	err := json.Unmarshal([]byte(podArgs), &podSpec)
	if err != nil {
		return nil, err
	}

	p, err := daemon.CreatePod("", &podSpec)
	if err != nil {
		return nil, err
	}

	v := &engine.Env{}
	v.Set("ID", p.Id())
	v.SetInt("Code", 0)
	v.Set("Cause", "")

	return v, nil
}
167772
func NewPod() *Pod {
	return &Pod{
		Labels:     map[string]string{},
		Env:        map[string]string{},
		Containers: []*PodContainer{},
		Secrets:    map[string]Secret{},
		Volumes:    []*PodVolume{},
		Networks:   []*PodNetwork{},
	}
}
968965
func (meta *predicateMetadata) AddPod(addedPod *v1.Pod, nodeInfo *schedulernodeinfo.NodeInfo) error {
	addedPodFullName := schedutil.GetPodFullName(addedPod)
	if addedPodFullName == schedutil.GetPodFullName(meta.pod) {
		return fmt.Errorf("addedPod and meta.pod must not be the same")
	}
	if nodeInfo.Node() == nil {
		return fmt.Errorf("invalid node in nodeInfo")
	}
	// Add matching anti-affinity terms of the addedPod to the map.
	topologyPairsMaps, err := getMatchingAntiAffinityTopologyPairsOfPod(meta.pod, addedPod, nodeInfo.Node())
	if err != nil {
		return err
	}
	meta.topologyPairsAntiAffinityPodsMap.appendMaps(topologyPairsMaps)
	// Add the pod to nodeNameToMatchingAffinityPods and nodeNameToMatchingAntiAffinityPods if needed.
	affinity := meta.pod.Spec.Affinity
	podNodeName := addedPod.Spec.NodeName
	if affinity != nil && len(podNodeName) > 0 {
		podNode := nodeInfo.Node()
		// It is assumed that when the added pod matches affinity of the meta.pod, all the terms must match,
		// this should be changed when the implementation of targetPodMatchesAffinityOfPod/podMatchesAffinityTermProperties
		// is changed
		if targetPodMatchesAffinityOfPod(meta.pod, addedPod) {
			affinityTerms := GetPodAffinityTerms(affinity.PodAffinity)
			for _, term := range affinityTerms {
				if topologyValue, ok := podNode.Labels[term.TopologyKey]; ok {
					pair := topologyPair{key: term.TopologyKey, value: topologyValue}
					meta.topologyPairsPotentialAffinityPods.addTopologyPair(pair, addedPod)
				}
			}
		}
		if targetPodMatchesAntiAffinityOfPod(meta.pod, addedPod) {
			antiAffinityTerms := GetPodAntiAffinityTerms(affinity.PodAntiAffinity)
			for _, term := range antiAffinityTerms {
				if topologyValue, ok := podNode.Labels[term.TopologyKey]; ok {
					pair := topologyPair{key: term.TopologyKey, value: topologyValue}
					meta.topologyPairsPotentialAntiAffinityPods.addTopologyPair(pair, addedPod)
				}
			}
		}
	}
	// If addedPod is in the same namespace as the meta.pod, update the list
	// of matching pods if applicable.
	if meta.serviceAffinityInUse && addedPod.Namespace == meta.pod.Namespace {
		selector := CreateSelectorFromLabels(meta.pod.Labels)
		if selector.Matches(labels.Set(addedPod.Labels)) {
			meta.serviceAffinityMatchingPodList = append(meta.serviceAffinityMatchingPodList,
				addedPod)
		}
	}
	return nil
}
64834
func (bc *BuildController) createPodSpec(build *buildv1.Build, includeAdditionalCA bool) (*corev1.Pod, error) {
	if build.Spec.Output.To != nil {
		build.Status.OutputDockerImageReference = build.Spec.Output.To.Name
	}

	// ensure the build object the pod sees starts with a clean set of reasons/messages,
	// rather than inheriting the potential "invalidoutputreference" message from the current
	// build state.  Otherwise when the pod attempts to update the build (e.g. with the git
	// revision information), it will re-assert the stale reason/message.
	build.Status.Reason = ""
	build.Status.Message = ""

	// Invoke the strategy to create a build pod.
	podSpec, err := bc.createStrategy.CreateBuildPod(build, bc.additionalTrustedCAData, bc.internalRegistryHostname)
	if err != nil {
		if strategy.IsFatal(err) {
			return nil, &strategy.FatalError{Reason: fmt.Sprintf("failed to create a build pod spec for build %s/%s: %v", build.Namespace, build.Name, err)}
		}
		return nil, fmt.Errorf("failed to create a build pod spec for build %s/%s: %v", build.Namespace, build.Name, err)
	}
	if err := bc.buildDefaults.ApplyDefaults(podSpec); err != nil {
		return nil, fmt.Errorf("failed to apply build defaults for build %s/%s: %v", build.Namespace, build.Name, err)
	}
	if err := bc.buildOverrides.ApplyOverrides(podSpec); err != nil {
		return nil, fmt.Errorf("failed to apply build overrides for build %s/%s: %v", build.Namespace, build.Name, err)
	}

	// Handle resolving ValueFrom references in build environment variables
	if err := common.ResolveValueFrom(podSpec, bc.kubeClient); err != nil {
		return nil, err
	}
	return podSpec, nil
}
309435
func LoadPod(root string, uuid *types.UUID, rp *RuntimePod) (*Pod, error) {
	p := &Pod{
		Root:     root,
		UUID:     *uuid,
		Images:   make(map[string]*schema.ImageManifest),
		UidRange: *user.NewBlankUidRange(),
	}

	// Unserialize runtime parameters
	if rp != nil {
		p.RuntimePod = *rp
	} else {
		buf, err := ioutil.ReadFile(filepath.Join(p.Root, RuntimeConfigPath))
		if err != nil {
			return nil, errwrap.Wrap(errors.New("failed reading runtime params"), err)
		}
		if err := json.Unmarshal(buf, &p.RuntimePod); err != nil {
			return nil, errwrap.Wrap(errors.New("failed unmarshalling runtime params"), err)
		}
	}

	pm, err := LoadPodManifest(p.Root)
	if err != nil {
		return nil, err
	}
	p.Manifest = pm

	// ensure volumes names are unique
	volNames := make(map[types.ACName]bool, len(pm.Volumes))
	for _, vol := range pm.Volumes {
		if volNames[vol.Name] {
			return nil, fmt.Errorf("duplicate volume name %q", vol.Name)
		}
		volNames[vol.Name] = true
	}

	for i, app := range p.Manifest.Apps {
		impath := common.ImageManifestPath(p.Root, app.Name)
		buf, err := ioutil.ReadFile(impath)
		if err != nil {
			return nil, errwrap.Wrap(fmt.Errorf("failed reading image manifest %q", impath), err)
		}

		im := &schema.ImageManifest{}
		if err = json.Unmarshal(buf, im); err != nil {
			return nil, errwrap.Wrap(fmt.Errorf("failed unmarshalling image manifest %q", impath), err)
		}

		if _, ok := p.Images[app.Name.String()]; ok {
			return nil, fmt.Errorf("got multiple definitions for app: %v", app.Name)
		}
		if app.App == nil {
			p.Manifest.Apps[i].App = im.App
		}
		p.Images[app.Name.String()] = im
	}

	if err := p.UidRange.Deserialize([]byte(p.PrivateUsers)); err != nil {
		return nil, err
	}

	return p, 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
}
2990
func (c *HyperClient) PausePod(podID string) error {
	_, err := c.client.PodPause(c.ctx, &types.PodPauseRequest{
		PodID: podID,
	})
	if err != nil {
		return err
	}

	return nil
}
487303
func ValidatePod(pod *api.Pod) field.ErrorList {
	allErrs := ValidateObjectMeta(&pod.ObjectMeta, true, ValidatePodName, field.NewPath("metadata"))
	allErrs = append(allErrs, ValidatePodSpec(&pod.Spec, field.NewPath("spec"))...)
	return allErrs
}
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
}
1138593
func encodePods(pods []*v1.Pod) (data []byte, err error) {
	podList := new(v1.PodList)
	for _, pod := range pods {
		podList.Items = append(podList.Items, *pod)
	}
	// TODO: this needs to be parameterized to the kubelet, not hardcoded. Depends on Kubelet
	//   as API server refactor.
	// TODO: Locked to v1, needs to be made generic
	codec := legacyscheme.Codecs.LegacyCodec(schema.GroupVersion{Group: v1.GroupName, Version: "v1"})
	return runtime.Encode(codec, podList)
}
915644
func (r *marathonClient) CreatePod(pod *Pod) (*Pod, error) {
	result := new(Pod)
	if err := r.apiPost(marathonAPIPods, &pod, result); err != nil {
		return nil, err
	}

	return result, nil
}
1047092
func WritePod(cpm checkpointmanager.CheckpointManager, pod *v1.Pod) error {
	var err error
	if checkAnnotations(pod) {
		data := NewPodCheckpoint(pod)
		err = cpm.CreateCheckpoint(getPodKey(pod), data)
	} else {
		// This is to handle an edge where a pod update could remove
		// an annotation and the checkpoint should then be removed.
		err = cpm.RemoveCheckpoint(getPodKey(pod))
	}
	return err
}
1118829
func (p podAPIChecker) CheckPod() error {
	_, err := p.client.CoreV1().Pods(p.namespace).Get(p.podName, metav1.GetOptions{})
	return err
}