k8s.io/kubernetes@v1.31.0-alpha.0.0.20240520171757-56147500dadc/plugin/pkg/admission/namespace/exists/admission.go (about)

     1  /*
     2  Copyright 2014 The Kubernetes Authors.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package exists
    18  
    19  import (
    20  	"context"
    21  	"fmt"
    22  	"io"
    23  
    24  	"k8s.io/apimachinery/pkg/api/errors"
    25  	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    26  	"k8s.io/apiserver/pkg/admission"
    27  	genericadmissioninitializer "k8s.io/apiserver/pkg/admission/initializer"
    28  	informers "k8s.io/client-go/informers"
    29  	"k8s.io/client-go/kubernetes"
    30  	corev1listers "k8s.io/client-go/listers/core/v1"
    31  	api "k8s.io/kubernetes/pkg/apis/core"
    32  )
    33  
    34  // PluginName indicates name of admission plugin.
    35  const PluginName = "NamespaceExists"
    36  
    37  // Register registers a plugin
    38  func Register(plugins *admission.Plugins) {
    39  	plugins.Register(PluginName, func(config io.Reader) (admission.Interface, error) {
    40  		return NewExists(), nil
    41  	})
    42  }
    43  
    44  // Exists is an implementation of admission.Interface.
    45  // It rejects all incoming requests in a namespace context if the namespace does not exist.
    46  // It is useful in deployments that want to enforce pre-declaration of a Namespace resource.
    47  type Exists struct {
    48  	*admission.Handler
    49  	client          kubernetes.Interface
    50  	namespaceLister corev1listers.NamespaceLister
    51  }
    52  
    53  var _ admission.ValidationInterface = &Exists{}
    54  var _ = genericadmissioninitializer.WantsExternalKubeInformerFactory(&Exists{})
    55  var _ = genericadmissioninitializer.WantsExternalKubeClientSet(&Exists{})
    56  
    57  // Validate makes an admission decision based on the request attributes
    58  func (e *Exists) Validate(ctx context.Context, a admission.Attributes, o admission.ObjectInterfaces) error {
    59  	// if we're here, then we've already passed authentication, so we're allowed to do what we're trying to do
    60  	// if we're here, then the API server has found a route, which means that if we have a non-empty namespace
    61  	// its a namespaced resource.
    62  	if len(a.GetNamespace()) == 0 || a.GetKind().GroupKind() == api.Kind("Namespace") {
    63  		return nil
    64  	}
    65  
    66  	// we need to wait for our caches to warm
    67  	if !e.WaitForReady() {
    68  		return admission.NewForbidden(a, fmt.Errorf("not yet ready to handle request"))
    69  	}
    70  	_, err := e.namespaceLister.Get(a.GetNamespace())
    71  	if err == nil {
    72  		return nil
    73  	}
    74  	if !errors.IsNotFound(err) {
    75  		return errors.NewInternalError(err)
    76  	}
    77  
    78  	// in case of latency in our caches, make a call direct to storage to verify that it truly exists or not
    79  	_, err = e.client.CoreV1().Namespaces().Get(context.TODO(), a.GetNamespace(), metav1.GetOptions{})
    80  	if err != nil {
    81  		if errors.IsNotFound(err) {
    82  			return err
    83  		}
    84  		return errors.NewInternalError(err)
    85  	}
    86  
    87  	return nil
    88  }
    89  
    90  // NewExists creates a new namespace exists admission control handler
    91  func NewExists() *Exists {
    92  	return &Exists{
    93  		Handler: admission.NewHandler(admission.Create, admission.Update, admission.Delete),
    94  	}
    95  }
    96  
    97  // SetExternalKubeClientSet implements the WantsExternalKubeClientSet interface.
    98  func (e *Exists) SetExternalKubeClientSet(client kubernetes.Interface) {
    99  	e.client = client
   100  }
   101  
   102  // SetExternalKubeInformerFactory implements the WantsExternalKubeInformerFactory interface.
   103  func (e *Exists) SetExternalKubeInformerFactory(f informers.SharedInformerFactory) {
   104  	namespaceInformer := f.Core().V1().Namespaces()
   105  	e.namespaceLister = namespaceInformer.Lister()
   106  	e.SetReadyFunc(namespaceInformer.Informer().HasSynced)
   107  }
   108  
   109  // ValidateInitialization implements the InitializationValidator interface.
   110  func (e *Exists) ValidateInitialization() error {
   111  	if e.namespaceLister == nil {
   112  		return fmt.Errorf("missing namespaceLister")
   113  	}
   114  	if e.client == nil {
   115  		return fmt.Errorf("missing client")
   116  	}
   117  	return nil
   118  }