k8s.io/apiserver@v0.31.1/pkg/admission/errors.go (about)

     1  /*
     2  Copyright 2015 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 admission
    18  
    19  import (
    20  	apierrors "k8s.io/apimachinery/pkg/api/errors"
    21  	"k8s.io/apimachinery/pkg/api/meta"
    22  	"k8s.io/apimachinery/pkg/runtime/schema"
    23  	utilerrors "k8s.io/apimachinery/pkg/util/errors"
    24  )
    25  
    26  func extractResourceName(a Attributes) (name string, resource schema.GroupResource, err error) {
    27  	resource = a.GetResource().GroupResource()
    28  
    29  	if len(a.GetName()) > 0 {
    30  		return a.GetName(), resource, nil
    31  	}
    32  
    33  	name = "Unknown"
    34  	obj := a.GetObject()
    35  	if obj != nil {
    36  		accessor, err := meta.Accessor(obj)
    37  		if err != nil {
    38  			// not all object have ObjectMeta.  If we don't, return a name with a slash (always illegal)
    39  			return "Unknown/errorGettingName", resource, nil
    40  		}
    41  
    42  		// this is necessary because name object name generation has not occurred yet
    43  		if len(accessor.GetName()) > 0 {
    44  			name = accessor.GetName()
    45  		} else if len(accessor.GetGenerateName()) > 0 {
    46  			name = accessor.GetGenerateName()
    47  		}
    48  	}
    49  	return name, resource, nil
    50  }
    51  
    52  // NewForbidden is a utility function to return a well-formatted admission control error response
    53  func NewForbidden(a Attributes, internalError error) error {
    54  	// do not double wrap an error of same type
    55  	if apierrors.IsForbidden(internalError) {
    56  		return internalError
    57  	}
    58  	name, resource, err := extractResourceName(a)
    59  	if err != nil {
    60  		return apierrors.NewInternalError(utilerrors.NewAggregate([]error{internalError, err}))
    61  	}
    62  	return apierrors.NewForbidden(resource, name, internalError)
    63  }
    64  
    65  // NewNotFound is a utility function to return a well-formatted admission control error response
    66  func NewNotFound(a Attributes) error {
    67  	name, resource, err := extractResourceName(a)
    68  	if err != nil {
    69  		return apierrors.NewInternalError(err)
    70  	}
    71  	return apierrors.NewNotFound(resource, name)
    72  }