// GetNamespacesFromPodAffinityTerm returns a set of names
// according to the namespaces indicated in podAffinityTerm.
// If namespaces is empty it considers the given pod's namespace.
504502
func GetNamespacesFromPodAffinityTerm(pod *v1.Pod, podAffinityTerm *v1.PodAffinityTerm) sets.String {
	names := sets.String{}
	if len(podAffinityTerm.Namespaces) == 0 {
		names.Insert(pod.Namespace)
	} else {
		names.Insert(podAffinityTerm.Namespaces...)
	}
	return names
}
305447
func (n *NodeInfo) PodsWithAffinity() []*v1.Pod {
	if n == nil {
		return nil
	}
	return n.podsWithAffinity
}
561767
func validatePodAffinity(podAffinity *core.PodAffinity, fldPath *field.Path) field.ErrorList {
	allErrs := field.ErrorList{}
	// TODO:Uncomment below code once RequiredDuringSchedulingRequiredDuringExecution is implemented.
	// if podAffinity.RequiredDuringSchedulingRequiredDuringExecution != nil {
	//	allErrs = append(allErrs, validatePodAffinityTerms(podAffinity.RequiredDuringSchedulingRequiredDuringExecution, false,
	//		fldPath.Child("requiredDuringSchedulingRequiredDuringExecution"))...)
	//}
	if podAffinity.RequiredDuringSchedulingIgnoredDuringExecution != nil {
		allErrs = append(allErrs, validatePodAffinityTerms(podAffinity.RequiredDuringSchedulingIgnoredDuringExecution,
			fldPath.Child("requiredDuringSchedulingIgnoredDuringExecution"))...)
	}
	if podAffinity.PreferredDuringSchedulingIgnoredDuringExecution != nil {
		allErrs = append(allErrs, validateWeightedPodAffinityTerms(podAffinity.PreferredDuringSchedulingIgnoredDuringExecution,
			fldPath.Child("preferredDuringSchedulingIgnoredDuringExecution"))...)
	}
	return allErrs
}
405705
func (c *Cache) GetNamespace(name string) (*services.Namespace, error) {
	return c.presenceCache.GetNamespace(name)
}
933249
func (sink *influxdbSink) GetPodsFromNamespace(namespace string) ([]string, error) {
	if !nameAllowedChars.MatchString(namespace) {
		return nil, fmt.Errorf("Invalid namespace name %q", namespace)
	}
	// This is a bit difficult for the influx query language, so we cheat a bit here --
	// we just get all series for the uptime measurement for pods which match our namespace
	// (any measurement should work here, though)
	q := fmt.Sprintf("SHOW SERIES FROM %q WHERE %s = '%s' AND type = '%s'", core.MetricUptime.MetricDescriptor.Name, core.LabelNamespaceName.Key, namespace, core.MetricSetTypePod)
	return sink.stringListQueryCol(q, core.LabelPodName.Key, fmt.Sprintf("Unable to list pods in namespace %q", namespace))
}
450409
func nsNameForPod(pod *v1.Pod) ktypes.NamespacedName {
	return ktypes.NamespacedName{
		Namespace: pod.Namespace,
		Name:      pod.Name,
	}
}
1218360
func allocNamespaceFilter(namespace string) func(interface{}) bool {
	return func(raw interface{}) bool {
		alloc, ok := raw.(*structs.Allocation)
		if !ok {
			return true
		}

		return alloc.Namespace != namespace
	}
}
855236
func ValidateNamespaceFinalizeUpdate(newNamespace, oldNamespace *api.Namespace) field.ErrorList {
	allErrs := ValidateObjectMetaUpdate(&newNamespace.ObjectMeta, &oldNamespace.ObjectMeta, field.NewPath("metadata"))

	fldPath := field.NewPath("spec", "finalizers")
	for i := range newNamespace.Spec.Finalizers {
		idxPath := fldPath.Index(i)
		allErrs = append(allErrs, validateFinalizerName(string(newNamespace.Spec.Finalizers[i]), idxPath)...)
	}
	newNamespace.Status = oldNamespace.Status
	return allErrs
}
1240398
func (this *NamespaceBasedEnricher) addNamespaceInfo(metricSet *core.MetricSet) {
	metricSetType, found := metricSet.Labels[core.LabelMetricSetType.Key]
	if !found {
		return
	}
	if metricSetType != core.MetricSetTypePodContainer &&
		metricSetType != core.MetricSetTypePod &&
		metricSetType != core.MetricSetTypeNamespace {
		return
	}

	namespaceName, found := metricSet.Labels[core.LabelNamespaceName.Key]
	if !found {
		return
	}

	nsObj, exists, err := this.store.GetByKey(namespaceName)
	if exists && err == nil {
		namespace, ok := nsObj.(*kube_api.Namespace)
		if ok {
			metricSet.Labels[core.LabelPodNamespaceUID.Key] = string(namespace.UID)
		} else {
			glog.Errorf("Wrong namespace store content")
		}
	} else if err != nil {
		glog.Warningf("Failed to get namespace %s: %v", namespaceName, err)
	} else if !exists {
		glog.Warningf("Namespace doesn't exist: %s", namespaceName)
	}
}
230485
func (s *daemonSetLister) GetPodDaemonSets(pod *v1.Pod) ([]*apps.DaemonSet, error) {
	var selector labels.Selector
	var daemonSet *apps.DaemonSet

	if len(pod.Labels) == 0 {
		return nil, fmt.Errorf("no daemon sets found for pod %v because it has no labels", pod.Name)
	}

	list, err := s.DaemonSets(pod.Namespace).List(labels.Everything())
	if err != nil {
		return nil, err
	}

	var daemonSets []*apps.DaemonSet
	for i := range list {
		daemonSet = list[i]
		if daemonSet.Namespace != pod.Namespace {
			continue
		}
		selector, err = metav1.LabelSelectorAsSelector(daemonSet.Spec.Selector)
		if err != nil {
			// this should not happen if the DaemonSet passed validation
			return nil, err
		}

		// If a daemonSet with a nil or empty selector creeps in, it should match nothing, not everything.
		if selector.Empty() || !selector.Matches(labels.Set(pod.Labels)) {
			continue
		}
		daemonSets = append(daemonSets, daemonSet)
	}

	if len(daemonSets) == 0 {
		return nil, fmt.Errorf("could not find daemon set for pod %s in namespace %s with labels: %v", pod.Name, pod.Namespace, pod.Labels)
	}

	return daemonSets, nil
}
1315015
func (c *PodAffinityChecker) satisfiesPodsAffinityAntiAffinity(pod *v1.Pod,
	meta PredicateMetadata, nodeInfo *schedulernodeinfo.NodeInfo,
	affinity *v1.Affinity) (PredicateFailureReason, error) {
	node := nodeInfo.Node()
	if node == nil {
		return ErrPodAffinityRulesNotMatch, fmt.Errorf("Node is nil")
	}
	if predicateMeta, ok := meta.(*predicateMetadata); ok {
		// Check all affinity terms.
		topologyPairsPotentialAffinityPods := predicateMeta.topologyPairsPotentialAffinityPods
		if affinityTerms := GetPodAffinityTerms(affinity.PodAffinity); len(affinityTerms) > 0 {
			matchExists := c.nodeMatchesAllTopologyTerms(pod, topologyPairsPotentialAffinityPods, nodeInfo, affinityTerms)
			if !matchExists {
				// This pod may the first pod in a series that have affinity to themselves. In order
				// to not leave such pods in pending state forever, we check that if no other pod
				// in the cluster matches the namespace and selector of this pod and the pod matches
				// its own terms, then we allow the pod to pass the affinity check.
				if !(len(topologyPairsPotentialAffinityPods.topologyPairToPods) == 0 && targetPodMatchesAffinityOfPod(pod, pod)) {
					klog.V(10).Infof("Cannot schedule pod %+v onto node %v, because of PodAffinity",
						podName(pod), node.Name)
					return ErrPodAffinityRulesNotMatch, nil
				}
			}
		}

		// Check all anti-affinity terms.
		topologyPairsPotentialAntiAffinityPods := predicateMeta.topologyPairsPotentialAntiAffinityPods
		if antiAffinityTerms := GetPodAntiAffinityTerms(affinity.PodAntiAffinity); len(antiAffinityTerms) > 0 {
			matchExists := c.nodeMatchesAnyTopologyTerm(pod, topologyPairsPotentialAntiAffinityPods, nodeInfo, antiAffinityTerms)
			if matchExists {
				klog.V(10).Infof("Cannot schedule pod %+v onto node %v, because of PodAntiAffinity",
					podName(pod), node.Name)
				return ErrPodAntiAffinityRulesNotMatch, nil
			}
		}
	} else { // We don't have precomputed metadata. We have to follow a slow path to check affinity terms.
		filteredPods, err := c.podLister.FilteredList(nodeInfo.Filter, labels.Everything())
		if err != nil {
			return ErrPodAffinityRulesNotMatch, err
		}

		affinityTerms := GetPodAffinityTerms(affinity.PodAffinity)
		antiAffinityTerms := GetPodAntiAffinityTerms(affinity.PodAntiAffinity)
		matchFound, termsSelectorMatchFound := false, false
		for _, targetPod := range filteredPods {
			// Check all affinity terms.
			if !matchFound && len(affinityTerms) > 0 {
				affTermsMatch, termsSelectorMatch, err := c.podMatchesPodAffinityTerms(pod, targetPod, nodeInfo, affinityTerms)
				if err != nil {
					errMessage := fmt.Sprintf("Cannot schedule pod %s onto node %s, because of PodAffinity: %v", podName(pod), node.Name, err)
					klog.Error(errMessage)
					return ErrPodAffinityRulesNotMatch, errors.New(errMessage)
				}
				if termsSelectorMatch {
					termsSelectorMatchFound = true
				}
				if affTermsMatch {
					matchFound = true
				}
			}

			// Check all anti-affinity terms.
			if len(antiAffinityTerms) > 0 {
				antiAffTermsMatch, _, err := c.podMatchesPodAffinityTerms(pod, targetPod, nodeInfo, antiAffinityTerms)
				if err != nil || antiAffTermsMatch {
					klog.V(10).Infof("Cannot schedule pod %+v onto node %v, because of PodAntiAffinityTerm, err: %v",
						podName(pod), node.Name, err)
					return ErrPodAntiAffinityRulesNotMatch, nil
				}
			}
		}

		if !matchFound && len(affinityTerms) > 0 {
			// We have not been able to find any matches for the pod's affinity terms.
			// This pod may be the first pod in a series that have affinity to themselves. In order
			// to not leave such pods in pending state forever, we check that if no other pod
			// in the cluster matches the namespace and selector of this pod and the pod matches
			// its own terms, then we allow the pod to pass the affinity check.
			if termsSelectorMatchFound {
				klog.V(10).Infof("Cannot schedule pod %+v onto node %v, because of PodAffinity",
					podName(pod), node.Name)
				return ErrPodAffinityRulesNotMatch, nil
			}
			// Check if pod matches its own affinity properties (namespace and label selector).
			if !targetPodMatchesAffinityOfPod(pod, pod) {
				klog.V(10).Infof("Cannot schedule pod %+v onto node %v, because of PodAffinity",
					podName(pod), node.Name)
				return ErrPodAffinityRulesNotMatch, nil
			}
		}
	}

	if klog.V(10) {
		// We explicitly don't do klog.V(10).Infof() to avoid computing all the parameters if this is
		// not logged. There is visible performance gain from it.
		klog.Infof("Schedule Pod %+v on Node %+v is allowed, pod affinity/anti-affinity constraints satisfied.",
			podName(pod), node.Name)
	}
	return nil, nil
}
693415
func ToCoreNamespace(n []*NamespaceElement) core.Namespace {
	var namespace core.Namespace
	for _, val := range n {
		ele := core.NamespaceElement{
			Value:       val.Value,
			Description: val.Description,
			Name:        val.Name,
		}
		namespace = append(namespace, ele)
	}
	return namespace
}
1113971
func GetNamespaceContainerIds(namespaceId string) ([]string, error) {
	namespace, err := GetNamespaceByID(namespaceId)
	if err != nil {
		return nil, err
	}
	var containerIds []string
	for _, resource := range namespace.Resources {
		if resource.Type == "Container" {
			var contaienrResource NamespaceResourceContainer
			if err := json.Unmarshal([]byte(resource.Data), &contaienrResource); err != nil {
				return nil, err
			}
			containerIds = append(containerIds, contaienrResource.Id)
		}
	}
	return containerIds, nil
}
84847
func GetNamespaceEngine(config map[string]string) TSDSDBEngine {
	db := golkeyval.GetDBEngine(config["DBEngine"])
	db.Configure(config)
	db.CreateDB()

	ns := golkeyvalNS.GetNSDBEngine(config["NSEngine"])
	ns.Configure(db)

	tsds := GetTSDSDBEngine("namespace")
	tsds.Configure(ns)
	return tsds
}
961365
func Namespace(name string, s func()) error {
	defer func() {
		namespace = ""
	}()

	namespace = applyNamespace(name)
	s()
	return nil
}
636851
func NamespacePredictor(factory ApiClientFactory, filter map[string]struct{}) complete.Predictor {
	return complete.PredictFunc(func(a complete.Args) []string {
		client, err := factory()
		if err != nil {
			return nil
		}

		resp, _, err := client.Search().PrefixSearch(a.Last, contexts.Namespaces, nil)
		if err != nil {
			return []string{}
		}

		// Filter the returned namespaces. We assign the unfiltered slice to the
		// filtered slice but with no elements. This causes the slices to share
		// the underlying array and makes the filtering allocation free.
		unfiltered := resp.Matches[contexts.Namespaces]
		filtered := unfiltered[:0]
		for _, ns := range unfiltered {
			if _, ok := filter[ns]; !ok {
				filtered = append(filtered, ns)
			}
		}

		return filtered
	})
}
1032532
func (me *Me) findPodInNamespaces(selector string) (*v1.Pod, string, error) {
	// Get the deis namespace. If it does not exist, get the default namespce.
	s, err := labels.Parse(selector)
	if err == nil {
		ns, err := me.c.CoreV1().Namespaces().List(metav1.ListOptions{LabelSelector: s.String()})
		if err != nil {
			return nil, "default", err
		}
		for _, n := range ns.Items {
			p, err := me.c.CoreV1().Pods(n.Name).Get(me.Name, metav1.GetOptions{})

			// If there is no error, we got a matching pod.
			if err == nil {
				return p, n.Name, nil
			}
		}
	}

	// If we get here, it's really the last ditch.
	p, err := me.c.CoreV1().Pods("default").Get(me.Name, metav1.GetOptions{})
	return p, "default", err
}