/
validate_namespace_deletion.go
171 lines (146 loc) · 6.56 KB
/
validate_namespace_deletion.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
// Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved. This file is licensed under the Apache Software License, v. 2 except as noted otherwise in the LICENSE file
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package webhooks
import (
"context"
"fmt"
"io/ioutil"
"net/http"
gardencorelisters "github.com/gardener/gardener/pkg/client/core/listers/core/v1beta1"
"github.com/gardener/gardener/pkg/client/kubernetes"
"github.com/gardener/gardener/pkg/logger"
"github.com/gardener/gardener/pkg/operation/common"
admissionv1beta1 "k8s.io/api/admission/v1beta1"
admissionregistrationv1beta1 "k8s.io/api/admissionregistration/v1beta1"
corev1 "k8s.io/api/core/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/serializer"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
)
type namespaceDeletionHandler struct {
k8sGardenClient kubernetes.Interface
projectLister gardencorelisters.ProjectLister
shootLister gardencorelisters.ShootLister
scheme *runtime.Scheme
codecs serializer.CodecFactory
}
// NewValidateNamespaceDeletionHandler creates a new handler for validating namespace deletions.
func NewValidateNamespaceDeletionHandler(k8sGardenClient kubernetes.Interface, projectLister gardencorelisters.ProjectLister, shootLister gardencorelisters.ShootLister) func(http.ResponseWriter, *http.Request) {
scheme := runtime.NewScheme()
utilruntime.Must(corev1.AddToScheme(scheme))
utilruntime.Must(admissionregistrationv1beta1.AddToScheme(scheme))
h := &namespaceDeletionHandler{k8sGardenClient, projectLister, shootLister, scheme, serializer.NewCodecFactory(scheme)}
return h.ValidateNamespaceDeletion
}
// ValidateNamespaceDeletion is a HTTP handler for validating whether a namespace deletion is allowed or not.
func (h *namespaceDeletionHandler) ValidateNamespaceDeletion(w http.ResponseWriter, r *http.Request) {
var (
body []byte
deserializer = h.codecs.UniversalDeserializer()
receivedReview = admissionv1beta1.AdmissionReview{}
wantedContentType = "application/json"
wantedOperation = admissionv1beta1.Delete
)
// Read HTTP request body into variable.
if r.Body != nil {
if data, err := ioutil.ReadAll(r.Body); err == nil {
body = data
}
}
// Verify that the correct content-type header has been sent.
if contentType := r.Header.Get("Content-Type"); contentType != wantedContentType {
err := fmt.Errorf("contentType=%s, expect %s", contentType, wantedContentType)
logger.Logger.Errorf(err.Error())
respond(w, errToAdmissionResponse(err))
return
}
// Deserialize HTTP request body into admissionv1beta1.AdmissionReview object.
if _, _, err := deserializer.Decode(body, nil, &receivedReview); err != nil {
logger.Logger.Errorf(err.Error())
respond(w, errToAdmissionResponse(err))
return
}
// If the request field is empty then do not admit (invalid body).
if receivedReview.Request == nil {
err := fmt.Errorf("invalid request body (missing admission request)")
logger.Logger.Errorf(err.Error())
respond(w, errToAdmissionResponse(err))
return
}
// If the request does not indicate the correct operation (DELETE) we allow the review without further doing.
if receivedReview.Request.Operation != wantedOperation {
respond(w, admissionResponse(true, ""))
return
}
// Now that all checks have been passed we can actually validate the admission request.
reviewResponse := h.admitNamespaces(receivedReview.Request)
if !reviewResponse.Allowed && reviewResponse.Result != nil {
logger.Logger.Infof("Rejected 'DELETE namespace' request of user '%s': %v", receivedReview.Request.UserInfo.Username, reviewResponse.Result.Message)
}
respond(w, reviewResponse)
}
// admitNamespaces does only allow the request if no Shoots exist in this
// specific namespace anymore.
func (h *namespaceDeletionHandler) admitNamespaces(request *admissionv1beta1.AdmissionRequest) *admissionv1beta1.AdmissionResponse {
namespaceResource := metav1.GroupVersionResource{Group: "", Version: "v1", Resource: "namespaces"}
if request.Resource != namespaceResource {
return errToAdmissionResponse(fmt.Errorf("expect resource to be %s", namespaceResource))
}
// Determine project object for given namespace.
project, err := common.ProjectForNamespace(h.projectLister, request.Name)
if err != nil {
if apierrors.IsNotFound(err) {
// Namespace does not belong to a project. Deletion is allowed.
return admissionResponse(true, "")
}
return errToAdmissionResponse(err)
}
// We do not receive the namespace object in the `.object` field of the admission request. Hence, we need to get it ourselves.
namespace := &corev1.Namespace{}
err = h.k8sGardenClient.Client().Get(context.TODO(), client.ObjectKey{Name: request.Name}, namespace)
if err != nil {
if apierrors.IsNotFound(err) {
return admissionResponse(true, "")
}
return errToAdmissionResponse(err)
}
switch {
case namespace.DeletionTimestamp != nil:
// Namespace is already marked to be deleted so we can allow the request.
return admissionResponse(true, "")
case project.DeletionTimestamp != nil:
namespaceEmpty, err := h.isNamespaceEmpty(namespace.Name)
if err != nil {
return errToAdmissionResponse(err)
}
if namespaceEmpty {
return admissionResponse(true, "")
}
return admissionResponse(false, fmt.Sprintf("Deletion of namespace %q is not permitted (there are still Shoots).", namespace.Name))
}
// Namespace is not yet marked to be deleted and project is not marked as well. We do not admit and respond that namespace deletion is only
// allowed via project deletion.
return admissionResponse(false, fmt.Sprintf("Direct deletion of namespace %q is not permitted (you must delete the corresponding project %q).", namespace.Name, project.Name))
}
func (h *namespaceDeletionHandler) isNamespaceEmpty(namespace string) (bool, error) {
shootList, err := h.shootLister.Shoots(namespace).List(labels.Everything())
if err != nil {
return false, err
}
return len(shootList) == 0, nil
}