/
router.go
173 lines (145 loc) · 4.88 KB
/
router.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
// Package webhook holds shared code related to routing for webhook admission.
package webhook
import (
"context"
"encoding/json"
"fmt"
"net/http"
jsonpatch "github.com/evanphx/json-patch"
"github.com/sirupsen/logrus"
v1 "k8s.io/api/admission/v1"
"k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
)
var (
defObjType = &unstructured.Unstructured{}
jsonPatchType = v1.PatchTypeJSONPatch
)
// NewRouter returns a newly allocated Router.
func NewRouter() *Router {
return &Router{}
}
// Router manages request and the calling of matching handlers.
type Router struct {
matches []*RouteMatch
}
func (r *Router) sendError(rw http.ResponseWriter, review *v1.AdmissionReview, err error) {
logrus.Error(err)
if review == nil || review.Request == nil {
http.Error(rw, err.Error(), http.StatusInternalServerError)
return
}
review.Response.Result = &errors.NewInternalError(err).ErrStatus
writeResponse(rw, review)
}
func writeResponse(rw http.ResponseWriter, review *v1.AdmissionReview) {
rw.Header().Set("Content-Type", "application/json")
err := json.NewEncoder(rw).Encode(review)
if err != nil {
logrus.Errorf("Failed to write response: %s", err)
}
}
// ServeHTTP inspects the http.Request and calls the Admit function on all matching handlers.
func (r *Router) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
review := &v1.AdmissionReview{}
err := json.NewDecoder(req.Body).Decode(review)
if err != nil {
r.sendError(rw, review, err)
return
}
if review.Request == nil {
r.sendError(rw, review, fmt.Errorf("request is not set"))
return
}
response := &Response{
AdmissionResponse: v1.AdmissionResponse{
UID: review.Request.UID,
},
}
review.Response = &response.AdmissionResponse
if err := r.admit(response, review.Request, req); err != nil {
r.sendError(rw, review, err)
return
}
writeResponse(rw, review)
}
func (r *Router) admit(response *Response, request *v1.AdmissionRequest, req *http.Request) error {
for _, m := range r.matches {
if m.matches(request) {
err := m.admit(response, &Request{
AdmissionRequest: *request,
Context: req.Context(),
ObjTemplate: m.getObjType(),
})
logrus.Debugf("admit result: %s %s %s user=%s allowed=%v err=%v", request.Operation, request.Kind.String(), resourceString(request.Namespace, request.Name), request.UserInfo.Username, response.Allowed, err)
return err
}
}
return fmt.Errorf("no route match found for %s %s %s", request.Operation, request.Kind.String(), resourceString(request.Namespace, request.Name))
}
func (r *Router) next() *RouteMatch {
match := &RouteMatch{}
r.matches = append(r.matches, match)
return match
}
// Request wrapper for an AdmissionRequest.
type Request struct {
v1.AdmissionRequest
Context context.Context
ObjTemplate runtime.Object
}
// DecodeOldObject decodes the OldObject in the request into a new runtime.Object of type specified by Type().
// If Type() was not set the runtime.Object will be of type *unstructured.Unstructured.
func (r *Request) DecodeOldObject() (runtime.Object, error) {
obj := r.ObjTemplate.DeepCopyObject()
err := json.Unmarshal(r.OldObject.Raw, obj)
return obj, err
}
// DecodeObject decodes the Object in the request into a new runtime.Object of type specified by Type().
// If Type() was not set the runtime.Object will be of type *unstructured.Unstructured.
func (r *Request) DecodeObject() (runtime.Object, error) {
obj := r.ObjTemplate.DeepCopyObject()
err := json.Unmarshal(r.Object.Raw, obj)
return obj, err
}
// Response a wrapper for AdmissionResponses object
type Response struct {
v1.AdmissionResponse
}
// CreatePatch will patch the Object in the request with the given object.
// An error will be returned if on subsequent calls to the same request.
func (r *Response) CreatePatch(request *Request, newObj runtime.Object) error {
if len(r.Patch) > 0 {
return fmt.Errorf("response patch has already been already been assigned")
}
newBytes, err := json.Marshal(newObj)
if err != nil {
return err
}
patch, err := jsonpatch.CreateMergePatch(request.Object.Raw, newBytes)
if err != nil {
return err
}
r.Patch = patch
r.PatchType = &jsonPatchType
return nil
}
// The Handler type is an adapter to allow admission checking on a given request.
// Handlers should update the response to control admission.
type Handler interface {
Admit(resp *Response, req *Request) error
}
// HandlerFunc type is used to add regular functions as Handler.
type HandlerFunc func(resp *Response, req *Request) error
// Admit calls the handler function so that the function conforms to the Handler interface.
func (h HandlerFunc) Admit(resp *Response, req *Request) error {
return h(resp, req)
}
// resourceString returns the resource formatted as a string.
func resourceString(ns, name string) string {
if ns == "" {
return name
}
return fmt.Sprintf("%s/%s", ns, name)
}