forked from linkerd/linkerd2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandlers.go
397 lines (351 loc) · 10.6 KB
/
handlers.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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
package api
import (
"context"
"encoding/json"
"fmt"
"net/http"
"strings"
"github.com/go-openapi/spec"
"github.com/julienschmidt/httprouter"
"github.com/linkerd/linkerd2/controller/k8s"
pkgK8s "github.com/linkerd/linkerd2/pkg/k8s"
"github.com/linkerd/linkerd2/pkg/protohttp"
pb "github.com/linkerd/linkerd2/viz/tap/gen/tap"
"github.com/linkerd/linkerd2/viz/tap/pkg"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/sirupsen/logrus"
"google.golang.org/grpc/metadata"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/version"
)
type handler struct {
k8sAPI *k8s.API
usernameHeader string
groupHeader string
grpcTapServer pb.TapServer
log *logrus.Entry
}
// TODO: share with api_handlers.go
type jsonError struct {
Error string `json:"error"`
}
var (
gvk = &schema.GroupVersionKind{
Group: "tap.linkerd.io",
Version: "v1alpha1",
Kind: "Tap",
}
gvfd = metav1.GroupVersionForDiscovery{
GroupVersion: gvk.GroupVersion().String(),
Version: gvk.Version,
}
apiGroup = metav1.APIGroup{
Name: gvk.Group,
Versions: []metav1.GroupVersionForDiscovery{gvfd},
PreferredVersion: gvfd,
}
resources = []struct {
name string
shortname string
namespaced bool
}{
{"namespaces", "ns", false},
{"pods", "po", true},
{"replicationcontrollers", "rc", true},
{"services", "svc", true},
{"daemonsets", "ds", true},
{"deployments", "deploy", true},
{"replicasets", "rs", true},
{"statefulsets", "sts", true},
{"jobs", "", true},
{"cronjobs", "cj", true},
}
)
func initRouter(h *handler) *httprouter.Router {
router := &httprouter.Router{}
router.GET("/", handleRoot)
router.GET("/apis", handleAPIs)
router.GET("/apis/"+gvk.Group, handleAPIGroup)
router.GET("/apis/"+gvk.GroupVersion().String(), handleAPIResourceList)
router.GET("/healthz", handleHealthz)
router.GET("/healthz/log", handleHealthz)
router.GET("/healthz/ping", handleHealthz)
router.GET("/metrics", handleMetrics)
router.GET("/openapi/v2", handleOpenAPI)
router.GET("/version", handleVersion)
router.NotFound = handleNotFound()
for _, res := range resources {
route := ""
if !res.namespaced {
route = fmt.Sprintf("/apis/%s/watch/%s/:namespace", gvk.GroupVersion().String(), res.name)
} else {
route = fmt.Sprintf("/apis/%s/watch/namespaces/:namespace/%s/:name", gvk.GroupVersion().String(), res.name)
}
router.GET(route, handleRoot)
router.POST(route+"/tap", h.handleTap)
}
return router
}
// POST /apis/tap.linkerd.io/v1alpha1/watch/namespaces/:namespace/tap
// POST /apis/tap.linkerd.io/v1alpha1/watch/namespaces/:namespace/:resource/:name/tap
func (h *handler) handleTap(w http.ResponseWriter, req *http.Request, p httprouter.Params) {
namespace := p.ByName("namespace")
name := p.ByName("name")
resource := ""
path := strings.Split(req.URL.Path, "/")
if len(path) == 8 {
resource = path[5]
} else if len(path) == 10 {
resource = path[7]
} else {
err := fmt.Errorf("invalid path: %s", req.URL.Path)
h.log.Error(err)
renderJSONError(w, err, http.StatusBadRequest)
return
}
h.log.Debugf("SubjectAccessReview: namespace: %s, resource: %s, name: %s, user: <%s>, group: <%s>",
namespace, resource, name, h.usernameHeader, h.groupHeader,
)
// TODO: it's possible this SubjectAccessReview is redundant, consider
// removing, more info at https://github.com/linkerd/linkerd2/issues/3182
err := pkgK8s.ResourceAuthzForUser(
req.Context(),
h.k8sAPI.Client,
namespace,
"watch",
gvk.Group,
gvk.Version,
resource,
"tap",
name,
req.Header.Get(h.usernameHeader),
req.Header.Values(h.groupHeader),
)
if err != nil {
err = fmt.Errorf("tap authorization failed (%s), visit %s for more information", err, pkg.TapRbacURL)
h.log.Error(err)
renderJSONError(w, err, http.StatusForbidden)
return
}
tapReq := pb.TapByResourceRequest{}
err = protohttp.HTTPRequestToProto(req, &tapReq)
if err != nil {
err = fmt.Errorf("Error decoding Tap Request proto: %s", err)
h.log.Error(err)
protohttp.WriteErrorToHTTPResponse(w, err)
return
}
url := pkg.TapReqToURL(&tapReq)
if url != req.URL.Path {
err = fmt.Errorf("tap request body did not match APIServer URL: %+v != %+v", url, req.URL.Path)
h.log.Error(err)
protohttp.WriteErrorToHTTPResponse(w, err)
return
}
flushableWriter, err := protohttp.NewStreamingWriter(w)
if err != nil {
h.log.Error(err)
protohttp.WriteErrorToHTTPResponse(w, err)
return
}
serverStream := serverStream{w: flushableWriter, req: req, log: h.log}
err = h.grpcTapServer.TapByResource(&tapReq, &serverStream)
if err != nil {
h.log.Error(err)
protohttp.WriteErrorToHTTPResponse(flushableWriter, err)
return
}
}
// GET (not found)
func handleNotFound() http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
handlePaths(w, http.StatusNotFound)
})
}
// GET /
// GET /apis/tap.linkerd.io/v1alpha1/watch/namespaces/:namespace
// GET /apis/tap.linkerd.io/v1alpha1/watch/namespaces/:namespace/:resource/:name
func handleRoot(w http.ResponseWriter, _ *http.Request, _ httprouter.Params) {
handlePaths(w, http.StatusOK)
}
// GET /
// GET (not found)
func handlePaths(w http.ResponseWriter, status int) {
paths := map[string][]string{
"paths": {
"/apis",
"/apis/" + gvk.Group,
"/apis/" + gvk.GroupVersion().String(),
"/healthz",
"/healthz/log",
"/healthz/ping",
"/metrics",
"/openapi/v2",
"/version",
},
}
renderJSON(w, paths, status)
}
// GET /apis
func handleAPIs(w http.ResponseWriter, _ *http.Request, _ httprouter.Params) {
groupList := metav1.APIGroupList{
TypeMeta: metav1.TypeMeta{
Kind: "APIGroupList",
},
Groups: []metav1.APIGroup{
apiGroup,
},
}
renderJSON(w, groupList, http.StatusOK)
}
// GET /apis/tap.linkerd.io
func handleAPIGroup(w http.ResponseWriter, _ *http.Request, _ httprouter.Params) {
groupWithType := apiGroup
groupWithType.TypeMeta = metav1.TypeMeta{
Kind: "APIGroup",
APIVersion: "v1",
}
renderJSON(w, groupWithType, http.StatusOK)
}
// GET /apis/tap.linkerd.io/v1alpha1
// this is required for `kubectl api-resources` to work
func handleAPIResourceList(w http.ResponseWriter, _ *http.Request, _ httprouter.Params) {
resList := metav1.APIResourceList{
TypeMeta: metav1.TypeMeta{
Kind: "APIResourceList",
APIVersion: "v1",
},
GroupVersion: gvk.GroupVersion().String(),
APIResources: []metav1.APIResource{},
}
for _, res := range resources {
resList.APIResources = append(resList.APIResources,
metav1.APIResource{
Name: res.name,
ShortNames: []string{res.shortname},
Namespaced: res.namespaced,
Kind: gvk.Kind,
Verbs: metav1.Verbs{"watch"},
})
resList.APIResources = append(resList.APIResources,
metav1.APIResource{
Name: fmt.Sprintf("%s/tap", res.name),
Namespaced: res.namespaced,
Kind: gvk.Kind,
Verbs: metav1.Verbs{"watch"},
})
}
renderJSON(w, resList, http.StatusOK)
}
// GET /healthz
// GET /healthz/logs
// GET /healthz/ping
func handleHealthz(w http.ResponseWriter, _ *http.Request, _ httprouter.Params) {
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
w.Write([]byte("ok"))
}
// GET /metrics
func handleMetrics(w http.ResponseWriter, req *http.Request, _ httprouter.Params) {
promhttp.Handler().ServeHTTP(w, req)
}
// GET /openapi/v2
func handleOpenAPI(w http.ResponseWriter, _ *http.Request, _ httprouter.Params) {
swagger := spec.Swagger{
SwaggerProps: spec.SwaggerProps{
Swagger: "2.0",
Info: &spec.Info{
InfoProps: spec.InfoProps{
Title: "Api",
Version: "v0",
},
},
Paths: &spec.Paths{
Paths: map[string]spec.PathItem{
"/": mkPathItem("get all paths"),
"/apis": mkPathItem("get available API versions"),
"/apis/" + gvk.Group: mkPathItem("get information of a group"),
"/apis/" + gvk.GroupVersion().String(): mkPathItem("get available resources"),
},
},
},
}
renderJSON(w, swagger, http.StatusOK)
}
func mkPathItem(desc string) spec.PathItem {
return spec.PathItem{
PathItemProps: spec.PathItemProps{
Get: &spec.Operation{
OperationProps: spec.OperationProps{
Description: desc,
Consumes: []string{"application/json"},
Produces: []string{"application/json"},
Responses: &spec.Responses{
ResponsesProps: spec.ResponsesProps{
StatusCodeResponses: map[int]spec.Response{
200: spec.Response{
Refable: spec.Refable{Ref: spec.MustCreateRef("n/a")},
ResponseProps: spec.ResponseProps{
Description: "OK response",
},
},
},
},
},
ID: "tapResourceV0",
},
},
},
}
}
// GET /version
func handleVersion(w http.ResponseWriter, _ *http.Request, _ httprouter.Params) {
renderJSON(w, version.Info{}, http.StatusOK)
}
func renderJSON(w http.ResponseWriter, obj interface{}, status int) {
bytes, err := json.MarshalIndent(obj, "", " ")
if err != nil {
renderJSONError(w, err, http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
w.Write(bytes)
}
// TODO: share with api_handlers.go
func renderJSONError(w http.ResponseWriter, err error, status int) {
w.Header().Set("Content-Type", "application/json")
rsp, _ := json.Marshal(jsonError{Error: err.Error()})
w.WriteHeader(status)
w.Write(rsp)
}
// serverStream provides functionality that satisfies the
// tap.Tap_TapByResourceServer. This allows the tap APIServer to call
// GRPCTapServer.TapByResource() directly, rather than make the request to an
// actual gRPC over the network.
//
// TODO: Share this code with streamServer and destinationServer in
// http_server.go.
type serverStream struct {
w protohttp.FlushableResponseWriter
req *http.Request
log *logrus.Entry
}
// Satisfy the grpc.ServerStream interface
func (s serverStream) SetHeader(metadata.MD) error { return nil }
func (s serverStream) SendHeader(metadata.MD) error { return nil }
func (s serverStream) SetTrailer(metadata.MD) {}
func (s serverStream) Context() context.Context { return s.req.Context() }
func (s serverStream) SendMsg(interface{}) error { return nil }
func (s serverStream) RecvMsg(interface{}) error { return nil }
// Satisfy the tap.Tap_TapByResourceServer interface
func (s *serverStream) Send(m *pb.TapEvent) error {
err := protohttp.WriteProtoToHTTPResponse(s.w, m)
if err != nil {
s.log.Errorf("Error writing proto to HTTP Response: %s", err)
protohttp.WriteErrorToHTTPResponse(s.w, err)
return err
}
s.w.Flush()
return nil
}