-
Notifications
You must be signed in to change notification settings - Fork 175
/
admissionhandler.go
305 lines (286 loc) · 10.1 KB
/
admissionhandler.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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
/*
Copyright 2020 The Kubernetes Authors.
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 admissionhandler
import (
"context"
"crypto/tls"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"github.com/fsnotify/fsnotify"
admissionv1 "k8s.io/api/admission/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/serializer"
cnstypes "github.com/vmware/govmomi/cns/types"
cnsconfig "sigs.k8s.io/vsphere-csi-driver/v3/pkg/common/config"
"sigs.k8s.io/vsphere-csi-driver/v3/pkg/csi/service/common"
"sigs.k8s.io/vsphere-csi-driver/v3/pkg/csi/service/common/commonco"
"sigs.k8s.io/vsphere-csi-driver/v3/pkg/csi/service/logger"
)
type (
parameterSet map[string]struct{}
)
// Has checks if specified paramName present in the paramSet.
func (paramSet parameterSet) Has(paramName string) bool {
_, ok := paramSet[paramName]
return ok
}
var (
server *http.Server
cfg *config
// COInitParams stores the input params required for initiating the
// CO agnostic orchestrator in the admission handler package.
COInitParams *interface{}
featureGateCsiMigrationEnabled bool
featureGateBlockVolumeSnapshotEnabled bool
featureGateTKGSHaEnabled bool
featureGateVolumeHealthEnabled bool
featureGateTopologyAwareFileVolumeEnabled bool
)
// watchConfigChange watches on the webhook configuration directory for changes
// like cert, key etc. This is required for certificate rotation.
func watchConfigChange() {
ctx, log := logger.GetNewContextWithLogger()
cfg, err := getWebHookConfig(ctx)
if err != nil {
log.Fatalf("failed to get webhook config. err: %v", err)
}
log.Debugf("Webhook config: %v", cfg)
watcher, err := fsnotify.NewWatcher()
if err != nil {
log.Fatalf("failed to create fsnotify watcher. err=%v", err)
}
go func() {
for {
var restartWebHookError error
log.Debugf("Waiting for event on fsnotify watcher")
select {
case event, ok := <-watcher.Events:
if !ok {
return
}
log.Debugf("fsnotify event: %q", event.String())
if event.Op&fsnotify.Remove == fsnotify.Remove {
log.Infof("Restarting webhook server with new config")
errChan := make(chan error)
go func() {
err := restartWebhookServer(ctx)
if err != nil {
errChan <- err
return
}
}()
restartWebHookError = <-errChan
if restartWebHookError != nil {
log.Errorf("failed to restart webhook server. err: %v", err)
}
}
case err, ok := <-watcher.Errors:
if !ok {
log.Errorf("fsnotify error: %+v", err)
return
}
}
log.Debugf("fsnotify event processed")
}
}()
webHookConfigPath := os.Getenv(envWebHookConfigPath)
if webHookConfigPath == "" {
webHookConfigPath = defaultWebHookConfigPath
}
err = watcher.Add(webHookConfigPath)
if err != nil {
log.Fatalf("failed to watch on path: %q. err=%v", webHookConfigPath, err)
}
}
// StartWebhookServer starts the webhook server.
func StartWebhookServer(ctx context.Context) error {
var stopCh = make(chan bool)
log := logger.GetLogger(ctx)
var err error
var clusterFlavor cnstypes.CnsClusterFlavor
var containerOrchestratorUtility commonco.COCommonInterface
clusterFlavor, err = cnsconfig.GetClusterFlavor(ctx)
if err != nil {
log.Errorf("Failed retrieving cluster flavor. Error: %v", err)
return err
}
containerOrchestratorUtility, err = commonco.GetContainerOrchestratorInterface(ctx,
common.Kubernetes, clusterFlavor, *COInitParams)
if err != nil {
log.Errorf("failed to get k8s interface. err: %v", err)
return err
}
if clusterFlavor == cnstypes.CnsClusterFlavorWorkload {
featureGateTKGSHaEnabled = containerOrchestratorUtility.IsFSSEnabled(ctx, common.TKGsHA)
featureGateVolumeHealthEnabled = containerOrchestratorUtility.IsFSSEnabled(ctx, common.VolumeHealth)
featureGateBlockVolumeSnapshotEnabled = containerOrchestratorUtility.IsFSSEnabled(ctx, common.BlockVolumeSnapshot)
startCNSCSIWebhookManager(ctx)
} else if clusterFlavor == cnstypes.CnsClusterFlavorGuest {
featureGateBlockVolumeSnapshotEnabled = containerOrchestratorUtility.IsFSSEnabled(ctx, common.BlockVolumeSnapshot)
startPVCSIWebhookManager(ctx)
} else if clusterFlavor == cnstypes.CnsClusterFlavorVanilla {
if cfg == nil {
cfg, err = getWebHookConfig(ctx)
if err != nil {
log.Errorf("failed to get webhook config. err: %v", err)
return err
}
log.Debugf("webhook config: %v", cfg)
}
featureGateCsiMigrationEnabled = containerOrchestratorUtility.IsFSSEnabled(ctx, common.CSIMigration)
featureGateBlockVolumeSnapshotEnabled = containerOrchestratorUtility.IsFSSEnabled(ctx, common.BlockVolumeSnapshot)
featureGateTopologyAwareFileVolumeEnabled = containerOrchestratorUtility.IsFSSEnabled(ctx,
common.TopologyAwareFileVolume)
if featureGateCsiMigrationEnabled || featureGateBlockVolumeSnapshotEnabled {
certs, err := tls.LoadX509KeyPair(cfg.WebHookConfig.CertFile, cfg.WebHookConfig.KeyFile)
if err != nil {
log.Errorf("failed to load key pair. certFile: %q, keyFile: %q err: %v",
cfg.WebHookConfig.CertFile, cfg.WebHookConfig.KeyFile, err)
return err
}
if cfg.WebHookConfig.Port == "" {
cfg.WebHookConfig.Port = defaultWebhookServerPort
}
server = &http.Server{
Addr: fmt.Sprintf(":%v", cfg.WebHookConfig.Port),
TLSConfig: &tls.Config{
Certificates: []tls.Certificate{certs},
CipherSuites: []uint16{
tls.TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
},
MinVersion: tls.VersionTLS12,
},
}
// Define http server and server handler.
mux := http.NewServeMux()
mux.HandleFunc("/validate", validationHandler)
server.Handler = mux
// Start webhook server.
log.Debugf("Starting webhook server on port: %v", cfg.WebHookConfig.Port)
go func() {
if err = server.ListenAndServeTLS(cfg.WebHookConfig.CertFile, cfg.WebHookConfig.KeyFile); err != nil {
if err == http.ErrServerClosed {
log.Info("Webhook server stopped")
} else {
log.Fatalf("failed to listen and serve webhook server. err: %v", err)
}
}
}()
log.Info("Webhook server started")
watchConfigChange()
<-stopCh
return nil
}
}
return logger.LogNewError(log, "can't start webhook. no features are enabled which requires webhook")
}
// restartWebhookServer stops the webhook server and start webhook using
// updated config.
func restartWebhookServer(ctx context.Context) error {
log := logger.GetLogger(ctx)
cfg, err := getWebHookConfig(ctx)
if err != nil {
log.Errorf("failed to get webhook config. err: %v", err)
}
log.Debugf("Webhook config: %v", cfg)
log.Info("Shutting down webhook server gracefully...")
err = server.Shutdown(context.Background())
if err != nil {
log.Errorf("failed to get shutdown webhook server. err: %v", err)
return err
}
log.Info("Restarting webhook server...")
return StartWebhookServer(ctx)
}
// validationHandler is the handler for webhook http multiplexer to help
// validate resources. Depending on the URL validation of AdmissionReview
// will be redirected to appropriate validation function.
func validationHandler(w http.ResponseWriter, r *http.Request) {
var body []byte
ctx, log := logger.GetNewContextWithLogger()
if r.Body != nil {
if data, err := io.ReadAll(r.Body); err == nil {
body = data
}
}
if len(body) == 0 {
log.Error("received empty request body")
http.Error(w, "received empty request body", http.StatusBadRequest)
return
}
log.Debugf("Received request")
// Verify the content type is accurate.
contentType := r.Header.Get("Content-Type")
if contentType != "application/json" {
log.Errorf("content-Type=%s, expect application/json", contentType)
http.Error(w, "invalid Content-Type, expect `application/json`", http.StatusUnsupportedMediaType)
return
}
var admissionResponse *admissionv1.AdmissionResponse
ar := admissionv1.AdmissionReview{}
codecs := serializer.NewCodecFactory(runtime.NewScheme())
deserializer := codecs.UniversalDeserializer()
if _, _, err := deserializer.Decode(body, nil, &ar); err != nil {
log.Errorf("Can't decode body: %v", err)
admissionResponse = &admissionv1.AdmissionResponse{
Result: &metav1.Status{
Message: err.Error(),
},
}
} else {
if r.URL.Path == "/validate" {
log.Debugf("request URL path is /validate")
log.Debugf("admissionReview: %+v", ar)
switch ar.Request.Kind.Kind {
case "StorageClass":
admissionResponse = validateStorageClass(ctx, &ar)
case "PersistentVolumeClaim":
admissionResponse = validatePVC(ctx, ar.Request)
case "PersistentVolume":
admissionResponse = validatePv(ctx, ar.Request)
default:
log.Infof("Skipping validation for resource type: %q", ar.Request.Kind.Kind)
admissionResponse = &admissionv1.AdmissionResponse{
Allowed: true,
}
}
log.Debugf("admissionResponse: %+v", admissionResponse)
}
}
admissionReview := admissionv1.AdmissionReview{}
admissionReview.APIVersion = "admission.k8s.io/v1"
admissionReview.Kind = "AdmissionReview"
if admissionResponse != nil {
admissionReview.Response = admissionResponse
if ar.Request != nil {
admissionReview.Response.UID = ar.Request.UID
}
}
resp, err := json.Marshal(admissionReview)
if err != nil {
log.Errorf("Can't encode response: %v", err)
http.Error(w, fmt.Sprintf("could not encode response: %v", err), http.StatusInternalServerError)
}
log.Debugf("Ready to write response")
if _, err := w.Write(resp); err != nil {
log.Errorf("Can't write response: %v", err)
http.Error(w, fmt.Sprintf("could not write response: %v", err), http.StatusInternalServerError)
}
}