/
impl.go
2240 lines (2180 loc) · 63.3 KB
/
impl.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
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2021 Terminus, Inc.
//
// 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
//
// http://www.apache.org/licenses/LICENSE-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 OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package impl
import (
"context"
"encoding/json"
"fmt"
"strings"
"sync"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
"github.com/erda-project/erda-proto-go/core/hepa/pb"
"github.com/erda-project/erda/apistructs"
"github.com/erda-project/erda/modules/hepa/bundle"
"github.com/erda-project/erda/modules/hepa/common"
. "github.com/erda-project/erda/modules/hepa/common/vars"
"github.com/erda-project/erda/modules/hepa/config"
"github.com/erda-project/erda/modules/hepa/gateway/assembler"
gw "github.com/erda-project/erda/modules/hepa/gateway/dto"
"github.com/erda-project/erda/modules/hepa/kong"
kongDto "github.com/erda-project/erda/modules/hepa/kong/dto"
"github.com/erda-project/erda/modules/hepa/repository/orm"
db "github.com/erda-project/erda/modules/hepa/repository/service"
"github.com/erda-project/erda/modules/hepa/services/global"
"github.com/erda-project/erda/modules/hepa/services/micro_api"
)
type GatewayApiServiceImpl struct {
apiInPackageDb db.GatewayApiInPackageService
zoneInPackageDb db.GatewayZoneInPackageService
packageDb db.GatewayPackageService
packageApiDb db.GatewayPackageApiService
serviceDb db.GatewayServiceService
routeDb db.GatewayRouteService
policyDb db.GatewayPolicyService
consumerDb db.GatewayConsumerService
pluginDb db.GatewayPluginInstanceService
apiDb db.GatewayApiService
consumerApiDb db.GatewayConsumerApiService
azDb db.GatewayAzInfoService
kongDb db.GatewayKongInfoService
runtimeDb db.GatewayRuntimeServiceService
globalBiz *global.GatewayGlobalService
kongAssembler assembler.GatewayKongAssembler
dbAssembler assembler.GatewayDbAssembler
reqCtx context.Context
}
var once sync.Once
func NewGatewayApiServiceImpl() error {
once.Do(
func() {
apiInPackageDb, _ := db.NewGatewayApiInPackageServiceImpl()
serviceDb, _ := db.NewGatewayServiceServiceImpl()
routeDb, _ := db.NewGatewayRouteServiceImpl()
policyDb, _ := db.NewGatewayPolicyServiceImpl()
consumerDb, _ := db.NewGatewayConsumerServiceImpl()
pluginDb, _ := db.NewGatewayPluginInstanceServiceImpl()
apiDb, _ := db.NewGatewayApiServiceImpl()
kongDb, _ := db.NewGatewayKongInfoServiceImpl()
azDb, _ := db.NewGatewayAzInfoServiceImpl()
consumerApiDb, _ := db.NewGatewayConsumerApiServiceImpl()
packageApiDb, _ := db.NewGatewayPackageApiServiceImpl()
packageDb, _ := db.NewGatewayPackageServiceImpl()
zoneInPackageDb, _ := db.NewGatewayZoneInPackageServiceImpl()
runtimeDb, _ := db.NewGatewayRuntimeServiceServiceImpl()
micro_api.Service = &GatewayApiServiceImpl{
apiInPackageDb: apiInPackageDb,
serviceDb: serviceDb,
routeDb: routeDb,
policyDb: policyDb,
consumerDb: consumerDb,
pluginDb: pluginDb,
apiDb: apiDb,
consumerApiDb: consumerApiDb,
kongDb: kongDb,
azDb: azDb,
kongAssembler: assembler.GatewayKongAssemblerImpl{},
dbAssembler: assembler.GatewayDbAssemblerImpl{},
globalBiz: &global.Service,
packageApiDb: packageApiDb,
packageDb: packageDb,
zoneInPackageDb: zoneInPackageDb,
runtimeDb: runtimeDb,
}
})
return nil
}
func (impl GatewayApiServiceImpl) Clone(ctx context.Context) micro_api.GatewayApiService {
newService := impl
newService.reqCtx = ctx
return &newService
}
func (impl GatewayApiServiceImpl) verifyApiCreateParams(req *gw.ApiReqDto) *common.StandardResult {
res := &common.StandardResult{Success: false}
if req == nil || req.IsEmpty() {
log.Errorf("invalid req[%+v]", req.ApiDto)
return res.SetReturnCode(PARAMS_IS_NULL)
}
req.RegisterType = gw.RT_MANUAL
var consumer *orm.GatewayConsumer
var err error
if req.RuntimeId == "" {
if req.ConsumerId == "" {
log.Error("empty consumerId")
return res.SetReturnCode(PARAMS_IS_NULL)
}
consumer, err = impl.consumerDb.GetById(req.ConsumerId)
if err != nil {
log.Errorf("error happend:%+v", err)
return res.SetReturnCode(UNKNOW_ERROR)
}
if consumer == nil {
return res.SetReturnCode(CONSUMER_NOT_EXIST)
}
req.Env = consumer.Env
}
if req.RedirectType == gw.RT_URL {
req.RedirectAddr = req.RedirectAddr + "/" + strings.TrimPrefix(req.RedirectPath, "/")
} else if req.RuntimeId == "" || req.DiceApp == "" || req.DiceService == "" {
return res.SetErrorInfo(&common.ErrInfo{Msg: "未选择对应的部署分支"})
}
return res.SetSuccessAndData(consumer)
}
func (impl GatewayApiServiceImpl) acquirePolicies(apiPolices []string) map[string]orm.GatewayPolicy {
res := map[string]orm.GatewayPolicy{}
for _, policyId := range apiPolices {
policy, err := impl.policyDb.GetById(policyId)
if err != nil || policy == nil {
log.Errorf("get policy by id[%s] failed[%+v]", policyId, err)
continue
}
res[policy.PluginName] = *policy
}
return res
}
func (impl GatewayApiServiceImpl) CreateUnitiyPackageShadowApi(apiId, projectId, env, az string) error {
api, err := impl.apiDb.GetById(apiId)
if err != nil {
return err
}
pack, err := impl.packageDb.GetByAny(&orm.GatewayPackage{
Scene: orm.UNITY_SCENE,
DiceProjectId: projectId,
DiceEnv: env,
DiceClusterName: az,
})
if err != nil {
return err
}
if pack == nil {
log.Warnf("unity package not found, projectId:%s, env:%s, az:%s", projectId, env, az)
return nil
}
err = impl.packageApiDb.Insert(&orm.GatewayPackageApi{
PackageId: pack.Id,
ApiPath: api.ApiPath,
Method: api.Method,
RedirectAddr: api.RedirectAddr,
Description: api.Description,
DiceApp: api.DiceApp,
DiceService: api.DiceService,
Origin: string(gw.FROM_SHADOW),
DiceApiId: apiId,
RedirectType: gw.RT_URL,
})
if err != nil {
return err
}
err = impl.apiInPackageDb.Insert(&orm.GatewayApiInPackage{
DiceApiId: apiId,
PackageId: pack.Id,
})
if err != nil {
return err
}
return nil
}
func (impl GatewayApiServiceImpl) CreateUpstreamBindApi(consumer *orm.GatewayConsumer, appName, srvName, runtimeServiceId string, upstreamApi *orm.GatewayUpstreamApi, aliasPath string) (string, error) {
if upstreamApi == nil {
return "", errors.New(ERR_INVALID_ARG)
}
var apiId string
if runtimeServiceId == "" {
if consumer == nil {
return "", errors.New("consumer is nil")
}
kongInfo, err := impl.kongDb.GetKongInfo(&orm.GatewayKongInfo{
ProjectId: consumer.ProjectId,
Az: consumer.Az,
Env: consumer.Env,
})
if err != nil {
return "", err
}
path := strings.ToLower("/"+kongInfo.ProjectName) + aliasPath + upstreamApi.GatewayPath
apiId, retCode, err := impl.createApi(consumer, &gw.ApiDto{
Path: path,
Method: upstreamApi.Method,
RedirectAddr: upstreamApi.Address + upstreamApi.Path,
RedirectType: gw.RT_URL,
DiceApp: appName,
DiceService: srvName,
Env: consumer.Env,
ProjectId: consumer.ProjectId,
IsInner: upstreamApi.IsInner,
OuterNetEnable: true,
RegisterType: gw.RT_AUTO,
}, nil, upstreamApi.Id)
if retCode == API_EXIST {
log.Warnf("api already existed, err:%+v", err)
return apiId, nil
}
if err != nil {
return apiId, err
}
err = impl.CreateUnitiyPackageShadowApi(apiId, consumer.ProjectId, consumer.Env, consumer.Az)
if err != nil {
return apiId, err
}
return apiId, nil
}
apiId, _, err := impl.CreateRuntimeApi(&gw.ApiDto{
Path: upstreamApi.GatewayPath,
Method: upstreamApi.Method,
RedirectAddr: upstreamApi.Address + upstreamApi.Path,
RedirectType: gw.RT_URL,
DiceApp: appName,
DiceService: srvName,
RuntimeServiceId: runtimeServiceId,
IsInner: upstreamApi.IsInner,
OuterNetEnable: true,
UpstreamApiId: upstreamApi.Id,
RegisterType: gw.RT_AUTO,
})
if err != nil {
return apiId, err
}
return apiId, nil
}
func (impl GatewayApiServiceImpl) UpdateUpstreamBindApi(consumer *orm.GatewayConsumer, appName, serviceName string, upstreamApi *orm.GatewayUpstreamApi, aliasPath string) error {
if upstreamApi == nil || len(upstreamApi.ApiId) == 0 {
return errors.Errorf("invalid arg: upstreamApi:%+v", upstreamApi)
}
gatewayApi, err := impl.apiDb.GetById(upstreamApi.ApiId)
if err != nil {
return err
}
if gatewayApi == nil {
return errors.Errorf("gatewayApi [%s] not exists", upstreamApi.ApiId)
}
// update restriction
if gatewayApi.Method != upstreamApi.Method {
return errors.Errorf("can't change api method: from %s to %s", gatewayApi.Method, upstreamApi.Method)
}
outerNetEnable := true
if gatewayApi.NetType == gw.NT_IN {
outerNetEnable = false
}
if gatewayApi.RuntimeServiceId == "" {
if consumer == nil {
return errors.New("consumer is nil")
}
kongInfo, err := impl.kongDb.GetKongInfo(&orm.GatewayKongInfo{
ProjectId: consumer.ProjectId,
Az: consumer.Az,
Env: consumer.Env,
})
if err != nil {
return err
}
path := strings.ToLower("/"+kongInfo.ProjectName) + aliasPath + upstreamApi.GatewayPath
_, _, err = impl.updateApi(gatewayApi, consumer, &gw.ApiDto{
Path: path,
Env: consumer.Env,
Method: gatewayApi.Method,
RegisterType: gw.RT_AUTO,
RedirectAddr: upstreamApi.Address + upstreamApi.Path,
RedirectType: gw.RT_URL,
OuterNetEnable: outerNetEnable,
DiceApp: appName,
DiceService: serviceName,
ProjectId: consumer.ProjectId,
IsInner: upstreamApi.IsInner,
NeedAuth: gatewayApi.NeedAuth,
Description: gatewayApi.Description,
}, nil, upstreamApi.Id)
if err != nil {
return err
}
return nil
}
_, _, err = impl.updateRuntimeApi(gatewayApi, &gw.ApiDto{
Path: upstreamApi.GatewayPath,
Method: gatewayApi.Method,
RegisterType: gw.RT_AUTO,
RedirectAddr: upstreamApi.Address + upstreamApi.Path,
RedirectType: gw.RT_URL,
OuterNetEnable: outerNetEnable,
IsInner: upstreamApi.IsInner,
DiceApp: appName,
DiceService: serviceName,
Description: gatewayApi.Description,
})
if err != nil {
return err
}
return nil
}
func (impl GatewayApiServiceImpl) DeleteUpstreamBindApi(upstreamApi *orm.GatewayUpstreamApi) error {
if upstreamApi == nil || len(upstreamApi.ApiId) == 0 {
return errors.Errorf("invalid arg: upstreamApi[%+v]", upstreamApi)
}
_, err := impl.deleteApi(upstreamApi.ApiId)
if err != nil {
return err
}
return nil
}
func (impl GatewayApiServiceImpl) apiPathExist(consumer *orm.GatewayConsumer, path string, method string) (bool, string, error) {
cond := &orm.GatewayApi{
ApiPath: path,
Method: method,
}
if consumer != nil {
cond.ConsumerId = consumer.Id
cond.SetMustCondCols("consumer_id", "api_path", "method")
} else {
cond.SetMustCondCols("api_path", "method")
}
exist, err := impl.apiDb.GetByAny(cond)
if err != nil {
return false, "", err
}
if exist == nil {
return false, "", nil
}
// case sensitive
if exist.ApiPath == path {
return true, exist.Id, nil
}
return false, "", nil
}
const varSlot = ""
const (
processStrStatus = iota
processVarStatus
)
func (impl GatewayApiServiceImpl) pathVariableSplit(path string) ([]string, []string, error) {
status := processStrStatus
var rawPaths []string
var vars []string
var items []byte
for i := 0; i < len(path); i++ {
c := path[i]
if status == processStrStatus {
if c == '{' {
status = processVarStatus
if len(items) > 0 {
rawPaths = append(rawPaths, string(items))
items = nil
}
} else if c == '}' {
return nil, nil, errors.Errorf("invalid path:%s", path)
} else {
items = append(items, c)
}
} else if status == processVarStatus {
if c == '{' {
return nil, nil, errors.Errorf("invalid path:%s", path)
} else if c == '}' {
status = processStrStatus
if len(items) > 0 {
vars = append(vars, string(items))
rawPaths = append(rawPaths, varSlot)
items = nil
} else {
return nil, nil, errors.Errorf("invalid path:%s", path)
}
} else {
items = append(items, c)
}
}
}
if status != processStrStatus {
return nil, nil, errors.Errorf("invalid path:%s", path)
}
if len(items) > 0 {
rawPaths = append(rawPaths, string(items))
}
return rawPaths, vars, nil
}
func (impl GatewayApiServiceImpl) pathVariableReplace(rawPaths []string, vars *[]string) (string, error) {
if len(*vars) == 0 {
return "", errors.New("invalid vars")
}
varIndex := 0
varRegex := `[^/]+`
for i, item := range rawPaths {
if item == varSlot {
varValue := (*vars)[varIndex]
colonIndex := strings.Index(varValue, ":")
if colonIndex != -1 {
varRegex = varValue[colonIndex+1:]
varValue = varValue[:colonIndex]
}
(*vars)[varIndex] = varValue
rawPaths[i] = fmt.Sprintf(`(?<%s>%s)`, varValue, varRegex)
varIndex++
}
if varIndex > len(*vars) {
return "", errors.Errorf("invalid varIndex[%d] of vars[%+v]", varIndex, vars)
}
}
return strings.Join(rawPaths, ""), nil
}
func (impl GatewayApiServiceImpl) pathAdjust(dto *gw.ApiDto) (bool, gw.ApiDto, string, error) {
if strings.HasSuffix(dto.Path, "/") {
validPath := strings.TrimSuffix(dto.Path, "/")
dto.Path = validPath
}
dto.Path = strings.Replace(dto.Path, "//", "/", -1)
dbDto := *dto
if dbDto.Path == "" {
dbDto.Path = "/"
}
isRegexPath := false
findBegin := strings.Index(dto.RedirectAddr, "://")
if findBegin < 0 {
return isRegexPath, dbDto, "", errors.Errorf("invalid dto:%+v", dto)
}
firstSlash := strings.Index(dto.RedirectAddr[findBegin+3:], "/")
servicePath := ""
if firstSlash > -1 {
servicePath = dto.RedirectAddr[findBegin+3+firstSlash:]
} else {
firstSlash = 0
}
rawPaths, vars, err := impl.pathVariableSplit(dto.Path)
if err != nil {
return isRegexPath, dbDto, "", err
}
serviceRawPaths, serviceVars, err := impl.pathVariableSplit(servicePath)
if err != nil {
return isRegexPath, dbDto, "", err
}
if len(vars) > 0 {
isRegexPath = true
adjustPath, err := impl.pathVariableReplace(rawPaths, &vars)
if err != nil {
return isRegexPath, dbDto, "", err
}
dto.Path = adjustPath
}
if len(serviceVars) > 0 {
varIndex := 0
for i, item := range serviceRawPaths {
if item == varSlot {
varValue := serviceVars[varIndex]
colonIndex := strings.Index(varValue, ":")
if colonIndex != -1 {
varValue = varValue[:colonIndex]
}
serviceRawPaths[i] = fmt.Sprintf(`{%s}`, varValue)
serviceVars[varIndex] = varValue
varIndex++
}
if varIndex > len(serviceVars) {
return isRegexPath, dbDto, "", errors.Errorf("invalid servicePath[%s]", servicePath)
}
}
servicePath = strings.Join(serviceRawPaths, "")
for _, serviceVarItem := range serviceVars {
exist := false
for _, varItem := range vars {
if varItem == serviceVarItem {
exist = true
break
}
}
if !exist {
return isRegexPath, dbDto, "", errors.Errorf("service var[%s] not exists in vars[%+v] of path[%s]",
serviceVarItem, vars, dto.Path)
}
}
dto.RedirectAddr = dto.RedirectAddr[:findBegin+3+firstSlash]
dbDto.RedirectAddr = dto.RedirectAddr + servicePath
return isRegexPath, dbDto, servicePath, nil
}
return isRegexPath, dbDto, "", nil
}
func (impl GatewayApiServiceImpl) GetRuntimeApis(runtimeServiceId string, registerType ...string) ([]gw.ApiDto, error) {
cond := &orm.GatewayApi{
RuntimeServiceId: runtimeServiceId,
}
if len(registerType) > 0 {
cond.RegisterType = registerType[0]
}
daos, err := impl.apiDb.SelectByAny(cond)
if err != nil {
return nil, err
}
var res []gw.ApiDto
for _, dao := range daos {
dto := gw.ApiDto{
Method: dao.Method,
DaoId: dao.Id,
}
dto.Path = strings.TrimPrefix(dao.ApiPath, "/"+dao.RuntimeServiceId)
if dto.Path == "" {
dto.Path = "/"
}
res = append(res, dto)
}
return res, nil
}
func (impl GatewayApiServiceImpl) CreateRuntimeApi(dto *gw.ApiDto, session ...*db.SessionHelper) (string, StandardErrorCode, error) {
var err error
dto.OuterNetEnable = true
apiDb := impl.apiDb
routeDb := impl.routeDb
serviceDb := impl.serviceDb
pluginDb := impl.pluginDb
runtimeDb := impl.runtimeDb
if len(session) > 0 {
apiDb, err = impl.apiDb.NewSession(session[0])
if err != nil {
return "", PARAMS_IS_NULL, err
}
routeDb, err = impl.routeDb.NewSession(session[0])
if err != nil {
return "", PARAMS_IS_NULL, err
}
serviceDb, err = impl.serviceDb.NewSession(session[0])
if err != nil {
return "", PARAMS_IS_NULL, err
}
pluginDb, err = impl.pluginDb.NewSession(session[0])
if err != nil {
return "", PARAMS_IS_NULL, err
}
runtimeDb, err = impl.runtimeDb.NewSession(session[0])
if err != nil {
return "", PARAMS_IS_NULL, err
}
}
var runtimeService *orm.GatewayRuntimeService
if dto.RuntimeServiceId == "" {
runtimeService, err = impl.getRuntimeService(dto.RuntimeId, dto.DiceApp, dto.DiceService, runtimeDb)
} else {
runtimeService, err = runtimeDb.Get(dto.RuntimeServiceId)
}
if err != nil {
return "", PARAMS_IS_NULL, err
}
if runtimeService == nil {
return "", PARAMS_IS_NULL, errors.Errorf("find runtime service failed, id:%s", dto.RuntimeServiceId)
}
auditCtx := map[string]interface{}{}
defer func() {
method := dto.Method
if method == "" {
method = "all"
}
auditCtx["path"] = strings.Join(strings.Split(dto.Path, "/")[2:], "/")
auditCtx["method"] = method
audit := common.MakeAuditInfo(impl.reqCtx, common.ScopeInfo{
ProjectId: runtimeService.ProjectId,
Workspace: runtimeService.Workspace,
AppId: runtimeService.AppId,
ServiceName: runtimeService.ServiceName,
RuntimeName: runtimeService.RuntimeName,
}, apistructs.CreateServiceApiTemplate, nil, auditCtx)
if audit != nil {
if err == nil {
audit.Result = apistructs.SuccessfulResult
} else {
// audit.Result = apistructs.FailureResult
// audit.ErrorMsg = errors.Cause(err).Error()
return
}
err = bundle.Bundle.CreateAuditEvent(&apistructs.AuditCreateRequest{Audit: *audit})
if err != nil {
log.Errorf("create audit failed, err:%+v", err)
}
}
}()
dto.RuntimeServiceId = runtimeService.Id
dto.ProjectId = runtimeService.ProjectId
dto.Env = runtimeService.Workspace
kongInfo, err := impl.kongDb.GetKongInfo(&orm.GatewayKongInfo{
Az: runtimeService.ClusterName,
ProjectId: runtimeService.ProjectId,
Env: runtimeService.Workspace,
})
if err != nil {
return "", PARAMS_IS_NULL, err
}
kongAdapter := kong.NewKongAdapter(kongInfo.KongAddr)
dto.Hosts = append(dto.Hosts, kong.InnerHost)
if dto.RedirectType == gw.RT_SERVICE {
dto.RedirectAddr = runtimeService.InnerAddress + dto.RedirectPath
if !strings.HasPrefix(dto.RedirectAddr, "http://") {
dto.RedirectAddr = "http://" + dto.RedirectAddr
}
}
pathPrefix, err := (*impl.globalBiz).GetRuntimeServicePrefix(runtimeService)
if err != nil {
return "", PARAMS_IS_NULL, err
}
dto.Path = pathPrefix + dto.Path
isRegexPath, dbDto, serviceRewritePath, err := impl.pathAdjust(dto)
if err != nil {
return "", INVALID_PATH, err
}
exist, existId, err := impl.apiPathExist(nil, dto.Path, dto.Method)
if err != nil {
return "", PARAMS_IS_NULL, err
}
if exist {
return existId, API_EXIST, errors.Errorf("api path[%s] method[%s] confilct", dto.Path, dto.Method)
}
ret := UNKNOW_ERROR
var serviceResp *kongDto.KongServiceRespDto
var routeResp *kongDto.KongRouteRespDto
var gatewayApi *orm.GatewayApi
var gatewayService *orm.GatewayService
var gatewayRoute *orm.GatewayRoute
gatewayApi, err = impl.dbAssembler.BuildGatewayApi(dbDto, "", nil, "")
if err != nil {
goto errorHappened
}
err = apiDb.Insert(gatewayApi)
if err != nil {
goto errorHappened
}
{
ret = CREATE_API_SERVICE_FAIL
var serviceReq *kongDto.KongServiceReqDto
serviceReq, err = impl.kongAssembler.BuildKongServiceReq("", dto)
if err != nil {
goto errorHappened
}
serviceResp, err = kongAdapter.CreateOrUpdateService(serviceReq)
if err != nil {
goto errorHappened
}
gatewayService, err = impl.dbAssembler.Resp2GatewayServiceByApi(serviceResp, dbDto, gatewayApi.Id)
if err != nil {
goto errorHappened
}
err = serviceDb.Insert(gatewayService)
if err != nil {
goto errorHappened
}
}
{
ret = CREATE_API_ROUTE_FAIL
var routeReq *kongDto.KongRouteReqDto
routeReq, err = impl.kongAssembler.BuildKongRouteReq("", dto, serviceResp.Id, isRegexPath)
if err != nil {
goto errorHappened
}
routeResp, err = kongAdapter.CreateOrUpdateRoute(routeReq)
if err != nil {
goto errorHappened
}
gatewayRoute, err = impl.dbAssembler.Resp2GatewayRouteByAPi(routeResp, gatewayService.Id, gatewayApi.Id)
if err != nil {
goto errorHappened
}
err = routeDb.Insert(gatewayRoute)
if err != nil {
goto errorHappened
}
}
{
ret = CREATE_API_PLUGIN_FAIL
policies := []orm.GatewayPolicy{}
if len(serviceRewritePath) > 0 {
configJson, err := json.Marshal(gw.PathVariableConfig{
RequestRegex: dto.Path,
RewritePath: serviceRewritePath,
Carrier: "ROUTE",
})
if err != nil {
goto errorHappened
}
policies = append(policies, orm.GatewayPolicy{
PluginName: "path-variable",
Config: configJson,
})
}
if config.ServerConf.HasRouteInfo {
configJson, err := json.Marshal(gw.RouteInfoConfig{
ProjectId: dbDto.ProjectId,
Workspace: strings.ToLower(dbDto.Env),
App: strings.ToLower(dbDto.DiceApp),
Service: strings.ToLower(dbDto.DiceService),
ApiPath: dbDto.Path,
Carrier: "ROUTE",
})
if err != nil {
goto errorHappened
}
policies = append(policies, orm.GatewayPolicy{
PluginName: "set-route-info",
Config: configJson,
})
}
for _, policy := range policies {
var pluginReq *kongDto.KongPluginReqDto
var pluginResp *kongDto.KongPluginRespDto
var pluginInstance *orm.GatewayPluginInstance
pluginReq, err = impl.kongAssembler.BuildKongPluginReqDto("", &policy, serviceResp.Id, routeResp.Id, "")
if err != nil {
goto errorHappened
}
pluginResp, err = kongAdapter.AddPlugin(pluginReq)
if err != nil {
goto errorHappened
}
if pluginResp == nil {
continue
}
pluginResp.PolicyId = policy.Id
pluginParams := assembler.PluginParams{
PolicyId: pluginResp.PolicyId,
GroupId: "",
ServiceId: gatewayService.Id,
RouteId: gatewayRoute.Id,
ConsumerId: "",
ApiId: gatewayApi.Id,
}
pluginInstance, err = impl.dbAssembler.Resp2GatewayPluginInstance(pluginResp, pluginParams)
if err != nil {
goto errorHappened
}
err = pluginDb.Insert(pluginInstance)
if err != nil {
goto errorHappened
}
}
}
return gatewayApi.Id, ret, nil
errorHappened:
var kerr error
if gatewayApi.Id != "" {
kerr = apiDb.RealDeleteById(gatewayApi.Id)
}
if serviceResp != nil {
kerr = kongAdapter.DeleteService(serviceResp.Id)
}
if routeResp != nil {
kerr = kongAdapter.DeleteRoute(routeResp.Id)
}
if kerr != nil {
log.Errorf("delete failed, err:%+v", kerr)
}
log.Errorf("error Happend, %+v:", err)
return "", ret, err
}
func (impl GatewayApiServiceImpl) getRuntimeService(runtimeId, appName, serviceName string, runtimeSession db.GatewayRuntimeServiceService) (*orm.GatewayRuntimeService, error) {
dao, err := runtimeSession.GetByAny(&orm.GatewayRuntimeService{
RuntimeId: runtimeId,
AppName: appName,
ServiceName: serviceName,
})
if err != nil {
return nil, err
}
if dao == nil {
return nil, errors.New("this runtime's deployment is not yet ready, it may be deploying or cancelled")
}
return dao, nil
}
func (impl GatewayApiServiceImpl) createApi(consumer *orm.GatewayConsumer, dto *gw.ApiDto, optionDto *gw.ApiReqOptionDto, upstreamApiId ...string) (string, StandardErrorCode, error) {
if consumer == nil || dto == nil || len(dto.RedirectAddr) == 0 {
return "", PARAMS_IS_NULL, errors.Errorf("invalid consumer[%+v] or dto[%+v]",
consumer, dto)
}
ret := UNKNOW_ERROR
var err error
var serviceResp *kongDto.KongServiceRespDto
var routeResp *kongDto.KongRouteRespDto
gatewayPolicies := []orm.GatewayPolicy{}
pluginRespList := []kongDto.KongPluginRespDto{}
// all api OuterNetEnable
dto.OuterNetEnable = true
// create zone if not exist
var zoneId string
kongInfo, err := impl.kongDb.GetKongInfo(&orm.GatewayKongInfo{
Az: consumer.Az,
ProjectId: consumer.ProjectId,
Env: consumer.Env,
})
if err != nil {
return "", PARAMS_IS_NULL, err
}
kongAdapter := kong.NewKongAdapter(kongInfo.KongAddr)
dto.Hosts = append(dto.Hosts, kong.InnerHost)
if dto.OuterNetEnable {
dto.Hosts = append(dto.Hosts, kongInfo.Endpoint)
}
isRegexPath, dbDto, serviceRewritePath, err := impl.pathAdjust(dto)
if err != nil {
return "", INVALID_PATH, err
}
exist, existId, err := impl.apiPathExist(consumer, dto.Path, dto.Method)
if err != nil {
return "", PARAMS_IS_NULL, err
}
if exist {
return existId, API_EXIST, errors.Errorf("api path[%s] method[%s] conflict", dto.Path,
dto.Method)
}
// 1 创建service
{
serviceReq, err := impl.kongAssembler.BuildKongServiceReq("", dto)
if err != nil {
ret = CREATE_API_SERVICE_FAIL
goto errorHappened
}
serviceResp, err = kongAdapter.CreateOrUpdateService(serviceReq)
if err != nil {
ret = CREATE_API_SERVICE_FAIL
goto errorHappened
}
}
// 2 创建route
{
routeReq, err := impl.kongAssembler.BuildKongRouteReq("", dto, serviceResp.Id, isRegexPath)
if err != nil {
ret = CREATE_API_ROUTE_FAIL
goto errorHappened
}
routeResp, err = kongAdapter.CreateOrUpdateRoute(routeReq)
if err != nil {
ret = CREATE_API_ROUTE_FAIL
goto errorHappened
}
}
// 3 根据group信息+请求信息增加插件
{
needAuth := false
var policies []orm.GatewayPolicy
var basicPolicies []orm.GatewayPolicy
// 3.0 请求信息更新
if optionDto != nil {
apiPolices := optionDto.Policies
policyMap := impl.acquirePolicies(apiPolices)
for _, policy := range policyMap {
if policy.Category == "auth" {
// 只能有一种auth策略
if needAuth {
continue
}
needAuth = true
}
policies = append(policies, policy)
}
}
if needAuth {
dbDto.NeedAuth = 1
} else {
dbDto.NeedAuth = 0
}
// 3.1 获取基本策略
basicPolicies, err = impl.policyDb.SelectByCategory("basic")
// 3.2 基本策略添加,acl根据是否开启鉴权添加
for _, policy := range basicPolicies {
if !needAuth && (policy.PluginName == "acl") {
continue
}
if policy.PluginName == "acl" {
objMap := map[string]interface{}{}
err = json.Unmarshal([]byte(policy.Config), &objMap)
if err != nil {
goto errorHappened
}
objMap["whitelist"] = consumer.Id
var mapJson []byte
mapJson, err = json.Marshal(objMap)
if err != nil {
goto errorHappened
}
policy.Config = mapJson
}
policies = append(policies, policy)
}
if len(serviceRewritePath) > 0 {
configJson, err := json.Marshal(gw.PathVariableConfig{
RequestRegex: dto.Path,
RewritePath: serviceRewritePath,
Carrier: "ROUTE",
})
if err != nil {
goto errorHappened
}
policies = append(policies, orm.GatewayPolicy{
PluginName: "path-variable",
Config: configJson,
})
}
if config.ServerConf.HasRouteInfo {
configJson, err := json.Marshal(gw.RouteInfoConfig{
ProjectId: dbDto.ProjectId,
Workspace: strings.ToLower(dbDto.Env),
App: strings.ToLower(dbDto.DiceApp),
Service: strings.ToLower(dbDto.DiceService),
ApiPath: dbDto.Path,
Carrier: "ROUTE",
})
if err != nil {
goto errorHappened
}
policies = append(policies, orm.GatewayPolicy{
PluginName: "set-route-info",
Config: configJson,
})
}
// 3.3 增加插件
for _, policy := range policies {
if policy.PluginName == "oauth2" {
_ = kongAdapter.TouchRouteOAuthMethod(routeResp.Id)
}
var pluginReq *kongDto.KongPluginReqDto
var pluginResp *kongDto.KongPluginRespDto
pluginReq, err = impl.kongAssembler.BuildKongPluginReqDto("", &policy, serviceResp.Id, routeResp.Id, "")
if err != nil {
ret = CREATE_API_PLUGIN_FAIL
goto errorHappened
}
pluginResp, err = kongAdapter.AddPlugin(pluginReq)
if err != nil {
ret = CREATE_API_PLUGIN_FAIL
goto errorHappened
}
if pluginResp == nil {
continue
}
if optionDto != nil {
for _, reqPolicyId := range optionDto.Policies {
if reqPolicyId == policy.Id {
gatewayPolicies = append(gatewayPolicies, policy)
break
}
}
}
pluginResp.PolicyId = policy.Id
pluginRespList = append(pluginRespList, *pluginResp)
}
if dto.IsInner == 1 {
pluginReq := &kongDto.KongPluginReqDto{
Name: "host-check",
RouteId: routeResp.Id,
Config: map[string]interface{}{
"allow_host": gw.INNER_HOSTS,
},
}
_, err = kongAdapter.CreateOrUpdatePlugin(pluginReq)
if err != nil {
ret = CREATE_API_PLUGIN_FAIL