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

     1  /*
     2  Copyright 2017 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 errors
    18  
    19  import (
    20  	"fmt"
    21  	"net/http"
    22  
    23  	apierrors "k8s.io/apimachinery/pkg/api/errors"
    24  	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    25  )
    26  
    27  // ToStatusErr returns a StatusError with information about the webhook plugin
    28  func ToStatusErr(webhookName string, result *metav1.Status) *apierrors.StatusError {
    29  	deniedBy := fmt.Sprintf("admission webhook %q denied the request", webhookName)
    30  	const noExp = "without explanation"
    31  
    32  	if result == nil {
    33  		result = &metav1.Status{Status: metav1.StatusFailure}
    34  	}
    35  
    36  	// Make sure we don't return < 400 status codes along with a rejection
    37  	if result.Code < http.StatusBadRequest {
    38  		result.Code = http.StatusBadRequest
    39  	}
    40  	// Make sure we don't return "" or "Success" status along with a rejection
    41  	if result.Status == "" || result.Status == metav1.StatusSuccess {
    42  		result.Status = metav1.StatusFailure
    43  	}
    44  
    45  	switch {
    46  	case len(result.Message) > 0:
    47  		result.Message = fmt.Sprintf("%s: %s", deniedBy, result.Message)
    48  	case len(result.Reason) > 0:
    49  		result.Message = fmt.Sprintf("%s: %s", deniedBy, result.Reason)
    50  	default:
    51  		result.Message = fmt.Sprintf("%s %s", deniedBy, noExp)
    52  	}
    53  
    54  	return &apierrors.StatusError{
    55  		ErrStatus: *result,
    56  	}
    57  }
    58  
    59  // NewDryRunUnsupportedErr returns a StatusError with information about the webhook plugin
    60  func NewDryRunUnsupportedErr(webhookName string) *apierrors.StatusError {
    61  	reason := fmt.Sprintf("admission webhook %q does not support dry run", webhookName)
    62  	return apierrors.NewBadRequest(reason)
    63  }