// GetPodPetSets returns a list of PetSets managing a pod. Returns an error only if no matching PetSets are found. func (s *StoreToPetSetLister) GetPodPetSets(pod *api.Pod) (psList []apps.PetSet, err error) { var selector labels.Selector var ps apps.PetSet if len(pod.Labels) == 0 { err = fmt.Errorf("no PetSets found for pod %v because it has no labels", pod.Name) return } for _, m := range s.Store.List() { ps = *m.(*apps.PetSet) if ps.Namespace != pod.Namespace { continue } selector, err = unversioned.LabelSelectorAsSelector(ps.Spec.Selector) if err != nil { err = fmt.Errorf("invalid selector: %v", err) return } // If a PetSet with a nil or empty selector creeps in, it should match nothing, not everything. if selector.Empty() || !selector.Matches(labels.Set(pod.Labels)) { continue } psList = append(psList, ps) } if len(psList) == 0 { err = fmt.Errorf("could not find PetSet for pod %s in namespace %s with labels: %v", pod.Name, pod.Namespace, pod.Labels) } return }
// GetPodDaemonSets returns a list of daemon sets managing a pod. // Returns an error if and only if no matching daemon sets are found. func (s *StoreToDaemonSetLister) GetPodDaemonSets(pod *api.Pod) (daemonSets []extensions.DaemonSet, err error) { var selector labels.Selector var daemonSet extensions.DaemonSet if len(pod.Labels) == 0 { err = fmt.Errorf("no daemon sets found for pod %v because it has no labels", pod.Name) return } for _, m := range s.Store.List() { daemonSet = *m.(*extensions.DaemonSet) if daemonSet.Namespace != pod.Namespace { continue } selector, err = unversioned.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 { err = fmt.Errorf("could not find daemon set for pod %s in namespace %s with labels: %v", pod.Name, pod.Namespace, pod.Labels) } return }
// GetDeploymentsForRC returns a list of deployments managing a replication controller. Returns an error only if no matching deployments are found. func (s *StoreToDeploymentLister) GetDeploymentsForRC(rc *api.ReplicationController) (deployments []extensions.Deployment, err error) { var selector labels.Selector var d extensions.Deployment if len(rc.Labels) == 0 { err = fmt.Errorf("no deployments found for replication controller %v because it has no labels", rc.Name) return } // TODO: MODIFY THIS METHOD so that it checks for the podTemplateSpecHash label for _, m := range s.Store.List() { d = *m.(*extensions.Deployment) if d.Namespace != rc.Namespace { continue } labelSet := labels.Set(d.Spec.Selector) selector = labels.Set(d.Spec.Selector).AsSelector() // If a deployment with a nil or empty selector creeps in, it should match nothing, not everything. if labelSet.AsSelector().Empty() || !selector.Matches(labels.Set(rc.Labels)) { continue } deployments = append(deployments, d) } if len(deployments) == 0 { err = fmt.Errorf("could not find deployments set for replication controller %s in namespace %s with labels: %v", rc.Name, rc.Namespace, rc.Labels) } return }
// TODO: Move this back to scheduler as a helper function that takes a Store, // rather than a method of StoreToServiceLister. func (s *StoreToServiceLister) GetPodServices(pod *api.Pod) (services []api.Service, err error) { var selector labels.Selector var service api.Service for _, m := range s.Store.List() { service = *m.(*api.Service) // consider only services that are in the same namespace as the pod if service.Namespace != pod.Namespace { continue } if service.Spec.Selector == nil { // services with nil selectors match nothing, not everything. continue } selector = labels.Set(service.Spec.Selector).AsSelector() if selector.Matches(labels.Set(pod.Labels)) { services = append(services, service) } } if len(services) == 0 { err = fmt.Errorf("could not find service for pod %s in namespace %s with labels: %v", pod.Name, pod.Namespace, pod.Labels) } return }
// GetPodReplicaSets returns a list of ReplicaSets managing a pod. Returns an error only if no matching ReplicaSets are found. func (s *StoreToReplicaSetLister) GetPodReplicaSets(pod *api.Pod) (rss []extensions.ReplicaSet, err error) { var selector labels.Selector var rs extensions.ReplicaSet if len(pod.Labels) == 0 { err = fmt.Errorf("no ReplicaSets found for pod %v because it has no labels", pod.Name) return } for _, m := range s.Store.List() { rs = *m.(*extensions.ReplicaSet) if rs.Namespace != pod.Namespace { continue } selector, err = unversioned.LabelSelectorAsSelector(rs.Spec.Selector) if err != nil { err = fmt.Errorf("failed to convert pod selector to selector: %v", err) return } // If a ReplicaSet with a nil or empty selector creeps in, it should match nothing, not everything. if selector.Empty() || !selector.Matches(labels.Set(pod.Labels)) { continue } rss = append(rss, rs) } if len(rss) == 0 { err = fmt.Errorf("could not find ReplicaSet for pod %s in namespace %s with labels: %v", pod.Name, pod.Namespace, pod.Labels) } return }
// GetPodJobs returns a list of jobs managing a pod. Returns an error only if no matching jobs are found. func (s *StoreToJobLister) GetPodJobs(pod *api.Pod) (jobs []extensions.Job, err error) { var selector labels.Selector var job extensions.Job if len(pod.Labels) == 0 { err = fmt.Errorf("no jobs found for pod %v because it has no labels", pod.Name) return } for _, m := range s.Store.List() { job = *m.(*extensions.Job) if job.Namespace != pod.Namespace { continue } selector, _ = unversioned.LabelSelectorAsSelector(job.Spec.Selector) if !selector.Matches(labels.Set(pod.Labels)) { continue } jobs = append(jobs, job) } if len(jobs) == 0 { err = fmt.Errorf("could not find jobs for pod %s in namespace %s with labels: %v", pod.Name, pod.Namespace, pod.Labels) } return }
// GetPodDaemonSets returns a list of daemon sets managing a pod. Returns an error iff no matching daemon sets are found. func (s *StoreToDaemonSetLister) GetPodDaemonSets(pod *api.Pod) (daemonSets []experimental.DaemonSet, err error) { var selector labels.Selector var daemonSet experimental.DaemonSet if len(pod.Labels) == 0 { err = fmt.Errorf("No daemon sets found for pod %v because it has no labels", pod.Name) return } for _, m := range s.Store.List() { daemonSet = *m.(*experimental.DaemonSet) if daemonSet.Namespace != pod.Namespace { continue } selector = labels.Set(daemonSet.Spec.Selector).AsSelector() // 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 { err = fmt.Errorf("Could not find daemon set for pod %s in namespace %s with labels: %v", pod.Name, pod.Namespace, pod.Labels) } return }
// Match parses the selectors and adds the target as a parent if the selector matches. func match(selector labels.Selector, topology, id string) func(labelledChild) { return func(c labelledChild) { if selector.Matches(labels.Set(c.Labels())) { c.AddParent(topology, id) } } }
// List all the deploymentconfigs that match the provided selector using a namespace index. // If the indexed list fails then we will fallback to listing from all namespaces and filter // by the namespace we want. func (s storeDeploymentConfigsNamespacer) List(selector labels.Selector) ([]*deployapi.DeploymentConfig, error) { configs := []*deployapi.DeploymentConfig{} if s.namespace == kapi.NamespaceAll { for _, obj := range s.indexer.List() { dc := obj.(*deployapi.DeploymentConfig) if selector.Matches(labels.Set(dc.Labels)) { configs = append(configs, dc) } } return configs, nil } items, err := s.indexer.ByIndex(cache.NamespaceIndex, s.namespace) if err != nil { return nil, err } for _, obj := range items { dc := obj.(*deployapi.DeploymentConfig) if selector.Matches(labels.Set(dc.Labels)) { configs = append(configs, dc) } } return configs, nil }
// Add a new selector to the aggregator. New values on the output channel may not appear // right away. func (c *consulAggregator) Watch(selector labels.Selector, quitCh <-chan struct{}) chan []Labeled { resCh := make(chan []Labeled, 1) // this buffer is useful in sendMatches(), below select { case <-c.aggregatorQuit: c.logger.WithField("selector", selector.String()).Warnln("New selector added after aggregator was closed") close(resCh) return resCh default: } c.watcherLock.Lock() defer c.watcherLock.Unlock() watch := &selectorWatch{ selector: selector, resultCh: resCh, } if c.watchers == nil { c.watchers = watch } else { c.watchers.append(watch) } if c.labeledCache != nil { c.sendMatches(watch) } go func() { select { case <-quitCh: case <-c.aggregatorQuit: } c.removeWatch(watch) }() c.metWatchCount.Update(int64(c.watchers.len())) return watch.resultCh }
// List all the image streams that match the provided selector using a namespace index. // If the indexed list fails then we will fallback to listing from all namespaces and filter // by the namespace we want. func (s storeImageStreamsNamespacer) List(selector labels.Selector) ([]*imageapi.ImageStream, error) { streams := []*imageapi.ImageStream{} if s.namespace == kapi.NamespaceAll { for _, obj := range s.indexer.List() { stream := obj.(*imageapi.ImageStream) if selector.Matches(labels.Set(stream.Labels)) { streams = append(streams, stream) } } return streams, nil } items, err := s.indexer.ByIndex(cache.NamespaceIndex, s.namespace) if err != nil { return nil, err } for _, obj := range items { stream := obj.(*imageapi.ImageStream) if selector.Matches(labels.Set(stream.Labels)) { streams = append(streams, stream) } } return streams, nil }
// GetPodControllers returns a list of jobs managing a pod. Returns an error only if no matching jobs are found. func (s *StoreToJobLister) GetPodJobs(pod *api.Pod) (jobs []extensions.Job, err error) { var selector labels.Selector var job extensions.Job if len(pod.Labels) == 0 { err = fmt.Errorf("No jobs found for pod %v because it has no labels", pod.Name) return } for _, m := range s.Store.List() { job = *m.(*extensions.Job) if job.Namespace != pod.Namespace { continue } labelSet := labels.Set(job.Spec.Selector) selector = labels.Set(job.Spec.Selector).AsSelector() // Job with a nil or empty selector match nothing if labelSet.AsSelector().Empty() || !selector.Matches(labels.Set(pod.Labels)) { continue } jobs = append(jobs, job) } if len(jobs) == 0 { err = fmt.Errorf("Could not find jobs for pod %s in namespace %s with labels: %v", pod.Name, pod.Namespace, pod.Labels) } return }
// List all the ServiceAccounts that match the provided selector using a namespace index. // If the indexed list fails then we will fallback to listing from all namespaces and filter // by the namespace we want. func (s storeServiceAccountsNamespacer) List(selector labels.Selector) ([]*kapi.ServiceAccount, error) { serviceAccounts := []*kapi.ServiceAccount{} if s.namespace == kapi.NamespaceAll { for _, obj := range s.indexer.List() { bc := obj.(*kapi.ServiceAccount) if selector.Matches(labels.Set(bc.Labels)) { serviceAccounts = append(serviceAccounts, bc) } } return serviceAccounts, nil } items, err := s.indexer.ByIndex(cache.NamespaceIndex, s.namespace) if err != nil { return nil, err } for _, obj := range items { bc := obj.(*kapi.ServiceAccount) if selector.Matches(labels.Set(bc.Labels)) { serviceAccounts = append(serviceAccounts, bc) } } return serviceAccounts, nil }
func (c *consulApplicator) GetMatches(selector labels.Selector, labelType Type, cachedMatch bool) ([]Labeled, error) { var allLabeled []Labeled if cachedMatch { aggregator := c.initAggregator(labelType) cache, err := aggregator.getCache() if err == nil { allLabeled = cache } else { c.logger.Warnln("Cache was empty on query, falling back to direct Consul query") } } var err error if len(allLabeled) == 0 { allLabeled, err = c.ListLabels(labelType) if err != nil { return nil, err } } res := []Labeled{} for _, l := range allLabeled { if selector.Matches(l.Labels) { res = append(res, l) } } return res, nil }
func (cli *HeapsterMetricsClient) GetPodMetrics(namespace string, podName string, allNamespaces bool, selector labels.Selector) ([]metrics_api.PodMetrics, error) { if allNamespaces { namespace = api.NamespaceAll } path, err := podMetricsUrl(namespace, podName) if err != nil { return []metrics_api.PodMetrics{}, err } params := map[string]string{"labelSelector": selector.String()} allMetrics := make([]metrics_api.PodMetrics, 0) resultRaw, err := GetHeapsterMetrics(cli, path, params) if err != nil { return []metrics_api.PodMetrics{}, err } if len(podName) == 0 { metrics := metrics_api.PodMetricsList{} err = json.Unmarshal(resultRaw, &metrics) if err != nil { return []metrics_api.PodMetrics{}, fmt.Errorf("failed to unmarshall heapster response: %v", err) } allMetrics = append(allMetrics, metrics.Items...) } else { var singleMetric metrics_api.PodMetrics err = json.Unmarshal(resultRaw, &singleMetric) if err != nil { return []metrics_api.PodMetrics{}, fmt.Errorf("failed to unmarshall heapster response: %v", err) } allMetrics = append(allMetrics, singleMetric) } return allMetrics, nil }
func parseNodeSelectorWithPrompt( oldSelector klabels.Selector, newSelectorString string, applicator labels.Applicator, ) (klabels.Selector, error) { newSelector, err := parseNodeSelector(newSelectorString) if err != nil { return newSelector, err } if oldSelector.String() == newSelector.String() { return newSelector, nil } newNodeLabels, err := applicator.GetMatches(newSelector, labels.NODE, false) if err != nil { return newSelector, util.Errorf("Error getting matching labels: %v", err) } oldNodeLabels, err := applicator.GetMatches(oldSelector, labels.NODE, false) if err != nil { return newSelector, util.Errorf("Error getting matching labels: %v", err) } toRemove, toAdd := makeNodeChanges(oldNodeLabels, newNodeLabels) fmt.Printf("Changing deployment from '%v' to '%v':\n", oldSelector.String(), newSelectorString) fmt.Printf("Removing:%9s hosts %s\n", fmt.Sprintf("-%v", len(toRemove)), toRemove) fmt.Printf("Adding: %9s hosts %s\n", fmt.Sprintf("+%v", len(toAdd)), toAdd) fmt.Println("Continue?") if !confirm() { return newSelector, util.Errorf("User cancelled") } return newSelector, nil }
func (cli *HeapsterMetricsClient) GetNodeMetrics(nodeName string, selector labels.Selector) ([]metrics_api.NodeMetrics, error) { params := map[string]string{"labelSelector": selector.String()} path, err := nodeMetricsUrl(nodeName) if err != nil { return []metrics_api.NodeMetrics{}, err } resultRaw, err := GetHeapsterMetrics(cli, path, params) if err != nil { return []metrics_api.NodeMetrics{}, err } metrics := make([]metrics_api.NodeMetrics, 0) if len(nodeName) == 0 { metricsList := metrics_api.NodeMetricsList{} err = json.Unmarshal(resultRaw, &metricsList) if err != nil { return []metrics_api.NodeMetrics{}, fmt.Errorf("failed to unmarshall heapster response: %v", err) } metrics = append(metrics, metricsList.Items...) } else { var singleMetric metrics_api.NodeMetrics err = json.Unmarshal(resultRaw, &singleMetric) if err != nil { return []metrics_api.NodeMetrics{}, fmt.Errorf("failed to unmarshall heapster response: %v", err) } metrics = append(metrics, singleMetric) } return metrics, nil }
// MatchPod returns a generic matcher for a given label and field selector. func MatchPod(label labels.Selector, field fields.Selector) generic.Matcher { return &generic.SelectionPredicate{ Label: label, Field: field, GetAttrs: func(obj runtime.Object) (labels.Set, fields.Set, error) { pod, ok := obj.(*api.Pod) if !ok { return nil, nil, fmt.Errorf("not a pod") } // podLabels is already sitting there ready to be used. // podFields is not available directly and requires allocation of a map. // Only bother if the fields might be useful to determining the match. // One common case is for a replication controller to set up a watch // based on labels alone; in that case we can avoid allocating the field map. // This is especially important in the apiserver. podLabels := labels.Set(pod.ObjectMeta.Labels) var podFields fields.Set if !field.Empty() && label.Matches(podLabels) { podFields = PodToSelectableFields(pod) } return podLabels, podFields, nil }, IndexFields: []string{"spec.nodeName"}, } }
// GetPodControllers returns a list of replication controllers managing a pod. Returns an error only if no matching controllers are found. func (s *StoreToReplicationControllerLister) GetPodControllers(pod *api.Pod) (controllers []api.ReplicationController, err error) { var selector labels.Selector var rc api.ReplicationController if len(pod.Labels) == 0 { err = fmt.Errorf("no controllers found for pod %v because it has no labels", pod.Name) return } key := &api.ReplicationController{ObjectMeta: api.ObjectMeta{Namespace: pod.Namespace}} items, err := s.Indexer.Index(NamespaceIndex, key) if err != nil { return } for _, m := range items { rc = *m.(*api.ReplicationController) selector = labels.Set(rc.Spec.Selector).AsSelectorPreValidated() // If an rc with a nil or empty selector creeps in, it should match nothing, not everything. if selector.Empty() || !selector.Matches(labels.Set(pod.Labels)) { continue } controllers = append(controllers, rc) } if len(controllers) == 0 { err = fmt.Errorf("could not find controller for pod %s in namespace %s with labels: %v", pod.Name, pod.Namespace, pod.Labels) } return }
// GetPodControllers returns a list of replication controllers managing a pod. Returns an error only if no matching controllers are found. func (s *StoreToReplicationControllerLister) GetPodControllers(pod *api.Pod) (controllers []api.ReplicationController, err error) { var selector labels.Selector var rc api.ReplicationController if len(pod.Labels) == 0 { err = fmt.Errorf("no controllers found for pod %v because it has no labels", pod.Name) return } for _, m := range s.Store.List() { rc = *m.(*api.ReplicationController) if rc.Namespace != pod.Namespace { continue } labelSet := labels.Set(rc.Spec.Selector) selector = labels.Set(rc.Spec.Selector).AsSelector() // If an rc with a nil or empty selector creeps in, it should match nothing, not everything. if labelSet.AsSelector().Empty() || !selector.Matches(labels.Set(pod.Labels)) { continue } controllers = append(controllers, rc) } if len(controllers) == 0 { err = fmt.Errorf("could not find controller for pod %s in namespace %s with labels: %v", pod.Name, pod.Namespace, pod.Labels) } return }
// GetPodPodDisruptionBudgets returns a list of PodDisruptionBudgets matching a pod. Returns an error only if no matching PodDisruptionBudgets are found. func (s *StoreToPodDisruptionBudgetLister) GetPodPodDisruptionBudgets(pod *api.Pod) (pdbList []policy.PodDisruptionBudget, err error) { var selector labels.Selector if len(pod.Labels) == 0 { err = fmt.Errorf("no PodDisruptionBudgets found for pod %v because it has no labels", pod.Name) return } for _, m := range s.Store.List() { pdb, ok := m.(*policy.PodDisruptionBudget) if !ok { glog.Errorf("Unexpected: %v is not a PodDisruptionBudget", m) continue } if pdb.Namespace != pod.Namespace { continue } selector, err = unversioned.LabelSelectorAsSelector(pdb.Spec.Selector) if err != nil { glog.Warningf("invalid selector: %v", err) // TODO(mml): add an event to the PDB continue } // If a PDB with a nil or empty selector creeps in, it should match nothing, not everything. if selector.Empty() || !selector.Matches(labels.Set(pod.Labels)) { continue } pdbList = append(pdbList, *pdb) } if len(pdbList) == 0 { err = fmt.Errorf("could not find PodDisruptionBudget for pod %s in namespace %s with labels: %v", pod.Name, pod.Namespace, pod.Labels) } return }
// List returns []*api.Pod matching a query. func (f FakePodLister) List(s labels.Selector) (selected []*api.Pod, err error) { for _, pod := range f { if s.Matches(labels.Set(pod.Labels)) { selected = append(selected, pod) } } return selected, nil }
func (p PodsToCache) List(s labels.Selector) (selected []*api.Pod, err error) { for _, pod := range p { if s.Matches(labels.Set(pod.Labels)) { selected = append(selected, pod) } } return selected, nil }
// MatchAutoscaler returns a generic matcher for a given label and field selector. func MatchAutoscaler(label labels.Selector, field fields.Selector) generic.Matcher { return generic.MatcherFunc(func(obj runtime.Object) (bool, error) { autoscaler, ok := obj.(*expapi.HorizontalPodAutoscaler) if !ok { return false, fmt.Errorf("not a horizontal pod autoscaler") } return label.Matches(labels.Set(autoscaler.Labels)), nil }) }
// Matcher returns a generic matcher for a given label and field selector. func Matcher(label labels.Selector, field fields.Selector) generic.Matcher { return generic.MatcherFunc(func(obj runtime.Object) (bool, error) { subnet, ok := obj.(*api.HostSubnet) if !ok { return false, fmt.Errorf("not a HostSubnet") } return label.Matches(labels.Set(subnet.Labels)) && field.Matches(api.HostSubnetToSelectableFields(subnet)), nil }) }
// Matcher returns a generic matcher for a given label and field selector. func Matcher(label labels.Selector, field fields.Selector) generic.Matcher { return generic.MatcherFunc(func(obj runtime.Object) (bool, error) { ns, ok := obj.(*api.NetNamespace) if !ok { return false, fmt.Errorf("not a NetNamespace") } return label.Matches(labels.Set(ns.Labels)) && field.Matches(api.NetNamespaceToSelectableFields(ns)), nil }) }
// Please note that selector is filtering among the pods that have gotten into // the store; there may have been some filtering that already happened before // that. // We explicitly don't return api.PodList, to avoid expensive allocations, which // in most cases are unnecessary. func (s *StoreToPodLister) List(selector labels.Selector) (pods []*api.Pod, err error) { for _, m := range s.Indexer.List() { pod := m.(*api.Pod) if selector.Matches(labels.Set(pod.Labels)) { pods = append(pods, pod) } } return pods, nil }
// Matcher returns a generic matcher for a given label and field selector. func Matcher(label labels.Selector, field fields.Selector) generic.Matcher { return generic.MatcherFunc(func(obj runtime.Object) (bool, error) { o, ok := obj.(*api.Template) if !ok { return false, fmt.Errorf("not a pod") } return label.Matches(labels.Set(o.Labels)) && field.Matches(api.TemplateToSelectableFields(o)), nil }) }
// MatchPodTemplate returns a generic matcher for a given label and field selector. func MatchPodTemplate(label labels.Selector, field fields.Selector) generic.Matcher { return generic.MatcherFunc(func(obj runtime.Object) (bool, error) { podObj, ok := obj.(*api.PodTemplate) if !ok { return false, fmt.Errorf("not a pod template") } return label.Matches(labels.Set(podObj.Labels)), nil }) }
// Matcher returns a generic matcher for a given label and field selector. func Matcher(label labels.Selector, field fields.Selector) generic.Matcher { return generic.MatcherFunc(func(obj runtime.Object) (bool, error) { sa, ok := obj.(*certificates.CertificateSigningRequest) if !ok { return false, fmt.Errorf("not a CertificateSigningRequest") } fields := SelectableFields(sa) return label.Matches(labels.Set(sa.Labels)) && field.Matches(fields), nil }) }