...

Source file src/github.com/chaos-mesh/chaos-mesh/pkg/webhook/affected_namespaces.go

Documentation: github.com/chaos-mesh/chaos-mesh/pkg/webhook

     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 webhook
    17  
    18  import (
    19  	"reflect"
    20  
    21  	"k8s.io/apimachinery/pkg/util/validation/field"
    22  
    23  	"github.com/chaos-mesh/chaos-mesh/api/genericwebhook"
    24  	"github.com/chaos-mesh/chaos-mesh/api/v1alpha1"
    25  )
    26  
    27  func affectedNamespaces(obj interface{}) (bool, map[string]struct{}) {
    28  	clusterScoped := false
    29  	namespaces := make(map[string]struct{})
    30  
    31  	walker := genericwebhook.NewFieldWalker(obj, func(path *field.Path, obj interface{}, field *reflect.StructField) bool {
    32  
    33  		// These are some trivial rules to cut a lot of edges.
    34  		if field != nil && (field.Name == "Status" || field.Name == "TypeMeta" || field.Name == "ObjectMeta") {
    35  			return false
    36  		}
    37  
    38  		if selector, ok := obj.(*v1alpha1.PodSelector); ok {
    39  			if selector == nil {
    40  				return false
    41  			}
    42  
    43  			for _, ns := range selector.Selector.Namespaces {
    44  				namespaces[ns] = struct{}{}
    45  			}
    46  			for namespace := range selector.Selector.Pods {
    47  				namespaces[namespace] = struct{}{}
    48  			}
    49  			if selector.Selector.ClusterScoped() {
    50  				clusterScoped = true
    51  			}
    52  
    53  			return true
    54  		}
    55  		return true
    56  	})
    57  	walker.Walk()
    58  
    59  	return clusterScoped, namespaces
    60  }
    61