/
routing.go
544 lines (487 loc) · 15.5 KB
/
routing.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
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
/*
* Tencent is pleased to support the open source community by making TKEStack
* available.
*
* Copyright (C) 2012-2021 Tencent. All Rights Reserved.
*
* 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
*
* https://opensource.org/licenses/Apache-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 OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
*/
package meshes
import (
"bytes"
"compress/gzip"
gojson "encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"strconv"
"strings"
"github.com/emicklei/go-restful"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/labels"
meshconfig "tkestack.io/tke/pkg/mesh/apis/config"
"tkestack.io/tke/pkg/mesh/route"
"tkestack.io/tke/pkg/mesh/services"
"tkestack.io/tke/pkg/mesh/services/rest"
"tkestack.io/tke/pkg/mesh/util/json"
"tkestack.io/tke/pkg/mesh/util/proxy"
"tkestack.io/tke/pkg/mesh/util/web"
"tkestack.io/tke/pkg/util/log"
)
type meshClusterHandler struct {
meshService services.MeshClusterService
clusterService services.ClusterService
istioService services.IstioService
config meshconfig.MeshConfiguration
}
func New(config meshconfig.MeshConfiguration, clusterService services.ClusterService,
istioService services.IstioService, meshService services.MeshClusterService) route.MeshClusterHandler {
return meshClusterHandler{
meshService: meshService,
clusterService: clusterService,
istioService: istioService,
config: config,
}
}
func (h meshClusterHandler) AddToWebService(ws *restful.WebService) {
ws.Route(
ws.GET(
fmt.Sprintf("/%s/{%s}/%s/{%s}/%s",
web.MeshPrefix, web.MeshKey,
web.NamespacePrefix, web.NamespaceKey,
web.MicroServicePrefix,
)).
To(h.ListMeshServices).
Param(ws.PathParameter(web.MeshKey, "mesh name").
DataType("string").Required(true)).
Param(ws.PathParameter(web.NamespaceKey, "namespace name").
DataType("string").Required(true)).
Operation("listMeshServices").
Doc("List istio micro services").
Returns(http.StatusOK, "List", rest.Response{}).
Returns(http.StatusBadRequest, "Error", rest.Response{}).
Returns(http.StatusNotFound, "Not Found", rest.Response{}).
Produces(restful.MIME_JSON),
)
ws.Route(
ws.GET(
fmt.Sprintf("/%s/{%s}/%s/{%s}/%s/{%s}",
web.MeshPrefix, web.MeshKey,
web.NamespacePrefix, web.NamespaceKey,
web.MicroServicePrefix, web.MicroServiceKey,
)).
To(h.GetMeshService).
Param(ws.PathParameter(web.MeshKey, "mesh name").
DataType("string").Required(true)).
Param(ws.PathParameter(web.NamespaceKey, "namespace name").
DataType("string").Required(true)).
Param(ws.PathParameter(web.MicroServiceKey, "micro service name").
DataType("string").Required(true)).
Operation("getMeshService").
Doc("get istio micro services").
Returns(http.StatusOK, "Get", rest.Response{}).
Returns(http.StatusBadRequest, "Error", rest.Response{}).
Returns(http.StatusNotFound, "Not Found", rest.Response{}).
Produces(restful.MIME_JSON),
)
// create Istio resource
ws.Route(
ws.POST(
fmt.Sprintf("/%s/{%s}/%s/{%s}/{%s}",
web.MeshPrefix, web.MeshKey,
web.NamespacePrefix, web.NamespaceKey,
web.IstioResourceKind,
)).
To(h.CreateMeshResource).
Param(ws.PathParameter(web.MeshKey, "mesh name").DataType("string").Required(true)).
Param(ws.PathParameter(web.NamespaceKey, "namespace name").DataType("string").Required(true)).
Param(ws.PathParameter(web.IstioResourceKind, "istio resource kind").DataType("string").Required(true).
AllowableValues(map[string]string{
web.GatewayPrefix: web.GatewayPrefix,
web.VirtualservicePrefix: web.VirtualservicePrefix,
web.DestinationrulePrefix: web.DestinationrulePrefix,
web.ServiceentriePrefix: web.ServiceentriePrefix,
web.SidecarPrefix: web.SidecarPrefix,
web.EnvoyfilterPrefix: web.EnvoyfilterPrefix,
web.WorkloadentryPrefix: web.WorkloadentryPrefix,
})).
Operation("createMeshResource").
Doc("create mesh resource").
Returns(http.StatusOK, "Created", rest.Response{}).
Returns(http.StatusBadRequest, "Error", rest.Response{}).
Returns(http.StatusNotFound, "Not Found", rest.Response{}).
Produces(restful.MIME_JSON),
)
// create mesh
ws.Route(ws.POST("/meshes").
To(h.reverseProxy("/meshes")).
Operation("createMesh").
Returns(http.StatusOK, "Created", rest.Response{}).
Returns(http.StatusBadRequest, "Error", rest.Response{}).
Returns(http.StatusNotFound, "Not Found", rest.Response{}).
Produces(restful.MIME_JSON),
)
// list mesh
ws.Route(ws.GET("/meshes").
To(h.reverseProxy("/meshes")).
Operation("listMesh").
Returns(http.StatusOK, "Created", rest.Response{}).
Returns(http.StatusBadRequest, "Error", rest.Response{}).
Returns(http.StatusNotFound, "Not Found", rest.Response{}).
Produces(restful.MIME_JSON).
Param(ws.QueryParameter("type", "type").DataType("string").
AllowableValues(map[string]string{"simple": ""})),
)
// list mesh from cache
ws.Route(ws.GET("/meshes/simple").
To(h.reverseProxy("/meshes/simple")).
Operation("getMeshSimple").
Returns(http.StatusOK, "Created", rest.Response{}).
Returns(http.StatusBadRequest, "Error", rest.Response{}).
Returns(http.StatusNotFound, "Not Found", rest.Response{}).
Produces(restful.MIME_JSON),
)
// get mesh
ws.Route(ws.GET("/meshes/{mesh}").
To(h.reverseProxy("/meshes/{mesh}")).
Operation("getMesh").
Returns(http.StatusOK, "Created", rest.Response{}).
Returns(http.StatusBadRequest, "Error", rest.Response{}).
Returns(http.StatusNotFound, "Not Found", rest.Response{}).
Produces(restful.MIME_JSON).
Param(ws.PathParameter("mesh", "mesh name").DataType("string")),
)
// delete mesh
ws.Route(ws.DELETE("/meshes/{mesh}").
To(h.reverseProxy("/meshes/{mesh}")).
Operation("deleteMesh").
Param(ws.PathParameter("mesh", "mesh name").DataType("string")),
)
// upgrade mesh
ws.Route(ws.POST("/meshes/{mesh}").
To(h.reverseProxy("/meshes/{mesh}")).
Operation("patchMeshUpgrade").
Returns(http.StatusOK, "Created", rest.Response{}).
Returns(http.StatusBadRequest, "Error", rest.Response{}).
Returns(http.StatusNotFound, "Not Found", rest.Response{}).
Produces(restful.MIME_JSON).
Param(ws.PathParameter("mesh", "mesh name").DataType("string")),
)
// auto injection namespaces
ws.Route(ws.POST("/meshes/{mesh}/autoinjectionnamespaces").
To(h.reverseProxy("/meshes/{mesh}/autoinjectionnamespaces")).
Operation("replaceAutoInjectionNamespaces").
Returns(http.StatusOK, "Created", rest.Response{}).
Returns(http.StatusBadRequest, "Error", rest.Response{}).
Returns(http.StatusNotFound, "Not Found", rest.Response{}).
Produces(restful.MIME_JSON).
Param(ws.PathParameter("mesh", "mesh name").DataType("string")),
)
// list mesh clusters namespaces
ws.Route(ws.GET("/meshes/{mesh}/autoinjectionnamespaces").
To(h.reverseProxy("/meshes/{mesh}/autoinjectionnamespaces")).
Operation("getMeshAutoInjectionNamespaces").
Param(ws.PathParameter("mesh", "mesh name").DataType("string")),
)
// outbound traffic
ws.Route(ws.POST("/meshes/{mesh}/outbound-traffic").
To(h.reverseProxy("/meshes/{mesh}/outbound-traffic")).
Operation("replaceMeshOutboundTraffic").
Returns(http.StatusOK, "Created", rest.Response{}).
Returns(http.StatusBadRequest, "Error", rest.Response{}).
Returns(http.StatusNotFound, "Not Found", rest.Response{}).
Produces(restful.MIME_JSON).
Param(ws.PathParameter("mesh", "mesh name").DataType("string")),
)
// tracing sampling
ws.Route(ws.POST("/meshes/{mesh}/sampling").
To(h.reverseProxy("/meshes/{mesh}/sampling")).
Operation("replaceMeshSampling").
Returns(http.StatusOK, "Created", rest.Response{}).
Returns(http.StatusBadRequest, "Error", rest.Response{}).
Returns(http.StatusNotFound, "Not Found", rest.Response{}).
Produces(restful.MIME_JSON).
Param(ws.PathParameter("mesh", "mesh name").DataType("string")),
)
// canary upgrade confirm or rollback
ws.Route(ws.POST("/meshes/{mesh}/canary").
To(h.reverseProxy("/meshes/{mesh}/canary")).
Operation("patchMeshCanaryUpgrade").
Returns(http.StatusOK, "Created", rest.Response{}).
Returns(http.StatusBadRequest, "Error", rest.Response{}).
Returns(http.StatusNotFound, "Not Found", rest.Response{}).
Produces(restful.MIME_JSON).
Param(ws.PathParameter("mesh", "mesh name").DataType("string")).
Param(ws.PathParameter("operate", "mesh canary operates").DataType("string").
DefaultValue("confirm").AllowableValues(map[string]string{"confirm": "confirm", "rollback": "rollback"})),
)
}
// ListMeshServices list mesh services, which contains the Istio "app" label
func (h meshClusterHandler) ListMeshServices(req *restful.Request, resp *restful.Response) {
result := rest.NewResult(false, "")
status := http.StatusBadRequest
defer func() {
if result.Err != "" {
log.Debugf("%v", result.Err)
}
_ = resp.WriteHeaderAndEntity(status, result)
}()
mesh := req.PathParameter(web.MeshKey)
namespace := req.PathParameter(web.NamespaceKey)
ls := req.QueryParameter(web.LabelSelectorQuery)
if namespace == "*" {
namespace = ""
}
var selector labels.Selector
if ls != "" {
var err error
selector, err = labels.Parse(ls)
if err != nil {
result.Err = err.Error()
return
}
}
ctx := req.Request.Context()
// 2020-11-04 list mesh services from mesh main cluster
ret, errs := h.meshService.ListMicroServices(ctx, mesh, namespace, "", selector)
if errs != nil && !errs.Empty() {
result.Err = errs.Error()
}
status = http.StatusOK
result.Result = true
result.Data = ret
}
// GetMeshServices get mesh service, which contains the Istio "app" label
func (h meshClusterHandler) GetMeshService(req *restful.Request, resp *restful.Response) {
result := rest.NewResult(false, "")
status := http.StatusBadRequest
defer func() {
if result.Err != "" {
log.Debugf("%v", result.Err)
}
_ = resp.WriteHeaderAndEntity(status, result)
}()
mesh := req.PathParameter(web.MeshKey)
namespace := req.PathParameter(web.NamespaceKey)
microService := req.PathParameter(web.MicroServiceKey)
ls := req.QueryParameter(web.LabelSelectorQuery)
if namespace == "*" {
namespace = ""
}
var selector labels.Selector
if ls != "" {
var err error
selector, err = labels.Parse(ls)
if err != nil {
result.Err = err.Error()
return
}
}
ctx := req.Request.Context()
// 2020-11-04 get mesh microService from mesh main cluster
ret, errs := h.meshService.ListMicroServices(ctx, mesh, namespace, microService, selector)
if errs != nil && !errs.Empty() {
result.Err = errs.Error()
}
status = http.StatusOK
result.Result = true
result.Data = ret
}
func (h meshClusterHandler) CreateMeshResource(req *restful.Request, resp *restful.Response) {
result := rest.NewResult(false, "")
status := http.StatusBadRequest
defer func() {
if result.Err != "" {
log.Debugf("%v", result.Err)
}
_ = resp.WriteHeaderAndEntity(status, result)
}()
ctx := req.Request.Context()
mesh := req.PathParameter(web.MeshKey)
namespace := req.PathParameter(web.NamespaceKey)
kind := req.PathParameter(web.IstioResourceKind)
switch kind {
case web.GatewayPrefix:
case web.VirtualservicePrefix:
case web.DestinationrulePrefix:
case web.ServiceentriePrefix:
case web.SidecarPrefix:
case web.EnvoyfilterPrefix:
case web.WorkloadentryPrefix:
default:
result.Err = fmt.Sprintf("unsupported istio resource[%s]", kind)
return
}
entity := &unstructured.Unstructured{}
err := req.ReadEntity(entity)
if err != nil {
result.Err = err.Error()
return
}
entity.SetNamespace(namespace)
err = h.meshService.CreateMeshResource(ctx, mesh, entity)
if err != nil {
status = http.StatusInternalServerError
result.Err = err.Error()
return
}
status = http.StatusOK
result.Result = true
result.Data = entity
}
// reverse proxy to mesh
func (h meshClusterHandler) reverseProxy(reverseRestPath string, o ...proxy.Opt) restful.RouteFunction {
return func(r *restful.Request, w *restful.Response) {
result := rest.NewResult(false, "")
status := http.StatusBadRequest
defer func() {
if result.Err != "" {
log.Debugf("%v", result.Err)
}
_ = w.WriteHeaderAndEntity(status, result)
}()
rewritePathOpt, err := h.rewriteURL(r, reverseRestPath)
if err != nil {
status = http.StatusInternalServerError
result.Err = err.Error()
return
}
// proxy to remote mesh-manger api
opts := []proxy.Opt{
rewritePathOpt,
RewriteHeaderOnTCM(),
RewriteResponseOnTCM(),
}
if len(o) > 0 {
opts = append(opts, o...)
}
p := proxy.New(opts...)
p.Proxy(w, r.Request)
}
}
const (
meshManagerContextPath = "/api"
)
func (h meshClusterHandler) rewriteURL(req *restful.Request, subPath string) (proxy.Opt, error) {
params := req.PathParameters()
replaces := make([]string, 0)
for key, value := range params {
p := fmt.Sprintf("{%s}", key)
replaces = append(replaces, p, value)
}
if len(replaces) != 0 {
r := strings.NewReplacer(replaces...)
subPath = r.Replace(subPath)
}
tcmConfig := h.config.Components.MeshManager.Address
rawurl := tcmConfig + meshManagerContextPath + subPath
parse, err := url.Parse(rawurl)
if err != nil {
log.Errorf("TCM API base url invalid: %s", rawurl)
return nil, err
}
return func(p *proxy.Proxy) {
target := &url.URL{
Scheme: parse.Scheme,
Host: parse.Host,
Path: parse.Path,
RawQuery: req.Request.URL.RawQuery,
}
p.Request.URL = target
}, nil
}
func RewriteResponseOnTCM() proxy.Opt {
return func(p *proxy.Proxy) {
p.ModifyResponse = handleTCMResponse
}
}
// handleTCMResponse handle TCM API response data structure
// 0. success direct data
// [{
// "name": "mesh-adj129ojm"
// }]
// 1. success without data
// {
// "code": 200,
// "message": "OK"
// }
// 2. success with data
// {
// "code": 200,
// "data": [{"test": "name"}]
// }
// 3. failure plain text
// HTTP Status 404
// 404 Not Found
func handleTCMResponse(res *http.Response) error {
// finally return response data struct
rsp := proxy.Response{
ResultCode: res.StatusCode,
}
var reader io.ReadCloser
switch res.Header.Get("Content-Encoding") {
case "gzip":
var err error
reader, err = gzip.NewReader(res.Body)
if err != nil {
log.Errorf("%v", err)
return err
}
reader.Close()
default:
reader = res.Body
}
bs, _ := ioutil.ReadAll(reader)
success := res.StatusCode == http.StatusOK
msg := json.Get(bs, "message")
data := json.Get(bs, "data")
hasMsg := msg.LastError() == nil
hasData := data.LastError() == nil
if hasMsg {
rsp.Msg = msg.ToString()
} else {
log.Warnf("mesh-manager API response: %s", msg.LastError().Error())
}
if hasData {
rsp.Data = gojson.RawMessage([]byte(data.ToString()))
} else {
log.Warnf("mesh-manager API response: %s", data.LastError().Error())
}
if success && !hasData && !hasMsg {
rsp.Data = gojson.RawMessage(bs)
}
if !success && !hasMsg {
rsp.Msg = string(bs)
}
returnResponse(res, rsp)
return nil
}
func returnResponse(res *http.Response, body interface{}) {
rb, _ := json.Marshal(body)
length := len(rb)
reader := bytes.NewReader(rb)
res.Body = ioutil.NopCloser(reader)
res.Header.Del("Content-Encoding")
res.Header.Set("Content-Length", strconv.Itoa(length))
}
func RewriteHeaderOnTCM() proxy.Opt {
return func(p *proxy.Proxy) {
p.Request.Header = map[string][]string{
"X-Remote-TenantID": {"default"},
"Content-Type": {"application/json"},
"Accept": {"*/*"},
}
}
}