volcano.sh/volcano@v1.9.0/pkg/webhooks/router/server.go (about) 1 /* 2 Copyright 2019 The Volcano 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 router 18 19 import ( 20 "encoding/json" 21 "io" 22 "net/http" 23 24 admissionv1 "k8s.io/api/admission/v1" 25 "k8s.io/apimachinery/pkg/runtime" 26 "k8s.io/klog/v2" 27 28 "volcano.sh/volcano/pkg/webhooks/schema" 29 "volcano.sh/volcano/pkg/webhooks/util" 30 ) 31 32 // CONTENTTYPE http content-type. 33 var CONTENTTYPE = "Content-Type" 34 35 // APPLICATIONJSON json content. 36 var APPLICATIONJSON = "application/json" 37 38 // Serve the http request. 39 func Serve(w io.Writer, r *http.Request, admit AdmitFunc) { 40 var body []byte 41 if r.Body != nil { 42 if data, err := io.ReadAll(r.Body); err == nil { 43 body = data 44 } 45 } 46 47 // verify the content type is accurate 48 contentType := r.Header.Get(CONTENTTYPE) 49 if contentType != APPLICATIONJSON { 50 klog.Errorf("contentType is not application/json") 51 return 52 } 53 54 var reviewResponse *admissionv1.AdmissionResponse 55 ar := admissionv1.AdmissionReview{} 56 deserializer := schema.Codecs.UniversalDeserializer() 57 if _, _, err := deserializer.Decode(body, nil, &ar); err != nil { 58 reviewResponse = util.ToAdmissionResponse(err) 59 } else { 60 reviewResponse = admit(ar) 61 } 62 klog.V(5).Infof("sending response: %v", reviewResponse) 63 64 response := createResponse(reviewResponse, &ar) 65 resp, err := json.Marshal(response) 66 if err != nil { 67 klog.Error(err) 68 } 69 if _, err := w.Write(resp); err != nil { 70 klog.Error(err) 71 } 72 } 73 74 func createResponse(reviewResponse *admissionv1.AdmissionResponse, ar *admissionv1.AdmissionReview) admissionv1.AdmissionReview { 75 response := admissionv1.AdmissionReview{} 76 if reviewResponse != nil { 77 response.APIVersion = "admission.k8s.io/v1" 78 response.Kind = "AdmissionReview" 79 response.Response = reviewResponse 80 response.Response.UID = ar.Request.UID 81 } 82 // reset the Object and OldObject, they are not needed in a response. 83 ar.Request.Object = runtime.RawExtension{} 84 ar.Request.OldObject = runtime.RawExtension{} 85 86 return response 87 }