/
main.go
172 lines (141 loc) · 4.05 KB
/
main.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
package main
import (
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"os"
"path/filepath"
"strings"
v1 "k8s.io/api/admission/v1"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
var (
port = GetEnvDefault("WEBHOOK_PORT", "8443")
skippableNamespaces = func() []string {
def := []string{metav1.NamespacePublic, metav1.NamespaceSystem}
v := os.Getenv("SKIP_NAMESPACE")
if v == "" {
return def
}
return append(def, strings.Split(v, ",")...)
}()
tlsDir = os.Getenv("TLS_DIR")
allowScheduling = GetEnvDefault("ALLOW_SCHEDULING", "false") == "true"
)
const (
jsonContentType = "application/json"
)
func main() {
certFile := filepath.Join(tlsDir, "tls.crt")
keyFile := filepath.Join(tlsDir, "tls.key")
mux := http.NewServeMux()
mux.Handle("/validate", validateHandler())
server := &http.Server{
Handler: mux,
Addr: ":" + port,
}
log.Println("webhook server is listening")
log.Fatal(server.ListenAndServeTLS(certFile, keyFile))
}
func validateHandler() http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Println("incoming request...")
// only POST method is supported
if r.Method != http.MethodPost {
w.WriteHeader(http.StatusMethodNotAllowed)
w.Write(responseBody("invalid method %s, only POST requests are allowed", r.Method))
return
}
body, err := io.ReadAll(r.Body)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
w.Write(responseBody("could not ready body %v", err))
return
}
if contentType := r.Header.Get("Content-Type"); contentType != jsonContentType {
w.WriteHeader(http.StatusBadRequest)
w.Write(
responseBody(
"unsupported content type %s, only %s is supported",
contentType,
jsonContentType,
),
)
return
}
var review v1.AdmissionReview
err = json.Unmarshal(body, &review)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
w.Write(responseBody("could not deserialize request: %v", err))
return
}
// Step 3: Construct the AdmissionReview response.
admissionReviewResponse := v1.AdmissionReview{
// Since the admission webhook now supports multiple API versions, we need
// to explicitly include the API version in the response.
// This API version needs to match the version from the request exactly, otherwise
// the API server will be unable to process the response.
// Note: a v1beta1 AdmissionReview is JSON-compatible with the v1 version, that's why
// we do not need to differentiate during unmarshaling or in the actual logic.
TypeMeta: review.TypeMeta,
Response: &v1.AdmissionResponse{
UID: review.Request.UID,
Allowed: true,
},
}
if !skipNamespace(review.Request.Namespace) {
raw := review.Request.Object.Raw
pod := corev1.Pod{}
err := json.Unmarshal(raw, &pod)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write(responseBody("could not unmarshal pod spec: %v", err))
return
}
if _, exists := pod.Labels["team"]; !exists {
admissionReviewResponse.Response.Allowed = allowScheduling
if allowScheduling {
admissionReviewResponse.Response.Warnings = []string{
"Team label not set on pod",
}
}
admissionReviewResponse.Response.Result = &metav1.Status{
Status: "Failure",
Message: "Team label not set on pod",
}
log.Printf("Team label not set on pod: %s\n", pod.Name)
}
}
response, err := json.Marshal(admissionReviewResponse)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write(responseBody("could not marshal JSON response: %v", err))
return
}
w.WriteHeader(http.StatusOK)
w.Write(response)
})
}
func responseBody(format string, args ...interface{}) []byte {
msg := fmt.Sprintf(format, args...)
log.Println("[ERROR]: " + msg)
return []byte(msg)
}
func GetEnvDefault(key, def string) string {
if v := os.Getenv(key); v != "" {
return v
}
return def
}
func skipNamespace(ns string) bool {
for _, n := range skippableNamespaces {
if n == ns {
return true
}
}
return false
}