blob: 9a069a2c9945a15787a8ed4d9bb72f42089cd09f [file] [log] [blame]
Matthias Andreas Benkard832a54e2019-01-29 09:27:38 +01001/*
2Copyright 2015 The Kubernetes Authors.
3
4Licensed under the Apache License, Version 2.0 (the "License");
5you may not use this file except in compliance with the License.
6You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10Unless required by applicable law or agreed to in writing, software
11distributed under the License is distributed on an "AS IS" BASIS,
12WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13See the License for the specific language governing permissions and
14limitations under the License.
15*/
16
17package admission
18
19import (
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
26func 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
53func 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
66func 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}