...

Source file src/github.com/chaos-mesh/chaos-mesh/pkg/selector/generic/label/selector.go

Documentation: github.com/chaos-mesh/chaos-mesh/pkg/selector/generic/label

     1  // Copyright 2021 Chaos Mesh Authors.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  // http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  //
    15  
    16  package label
    17  
    18  import (
    19  	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    20  	"k8s.io/apimachinery/pkg/labels"
    21  	"sigs.k8s.io/controller-runtime/pkg/client"
    22  
    23  	"github.com/chaos-mesh/chaos-mesh/api/v1alpha1"
    24  	"github.com/chaos-mesh/chaos-mesh/pkg/selector/generic"
    25  )
    26  
    27  const Name = "label"
    28  
    29  type labelSelector struct {
    30  	labels.Selector
    31  }
    32  
    33  var _ generic.Selector = &labelSelector{}
    34  
    35  func (s *labelSelector) ListOption() client.ListOption {
    36  	return client.MatchingLabelsSelector{Selector: s}
    37  }
    38  
    39  func (s *labelSelector) ListFunc(_ client.Reader) generic.ListFunc {
    40  	return nil
    41  }
    42  
    43  func (s *labelSelector) Match(obj client.Object) bool {
    44  	objLabels := labels.Set(obj.GetLabels())
    45  	return s.Matches(objLabels)
    46  }
    47  
    48  func New(spec v1alpha1.GenericSelectorSpec, _ generic.Option) (generic.Selector, error) {
    49  	metav1Ls := &metav1.LabelSelector{
    50  		MatchLabels:      spec.LabelSelectors,
    51  		MatchExpressions: spec.ExpressionSelectors,
    52  	}
    53  	ls, err := metav1.LabelSelectorAsSelector(metav1Ls)
    54  	if err != nil {
    55  		return nil, err
    56  	}
    57  	return &labelSelector{Selector: ls}, nil
    58  }
    59