/
create.go
1451 lines (1305 loc) · 46.6 KB
/
create.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.
//
// This program is free software: you can use, redistribute, and/or modify
// it under the terms of the GNU Affero General Public License, version 3
// or later ("AGPL"), as published by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package assetsvc
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"strconv"
"strings"
"time"
"github.com/getkin/kin-openapi/openapi3"
"github.com/jinzhu/gorm"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"gopkg.in/yaml.v2"
"github.com/erda-project/erda/apistructs"
"github.com/erda-project/erda/bundle"
"github.com/erda-project/erda/modules/dop/bdl"
"github.com/erda-project/erda/modules/dop/dbclient"
"github.com/erda-project/erda/modules/dop/services/apidocsvc"
"github.com/erda-project/erda/modules/dop/services/apierrors"
"github.com/erda-project/erda/pkg/http/httpserver/errorresp"
"github.com/erda-project/erda/pkg/strutil"
"github.com/erda-project/erda/pkg/swagger/oas2"
"github.com/erda-project/erda/pkg/swagger/oas3"
"github.com/erda-project/erda/pkg/swagger/oasconv"
)
const (
InsTypeDice = "dice"
InsTypeExternal = "external"
)
func accessDetailPath(id uint64) string {
accessID := strconv.FormatUint(id, 10)
return fmt.Sprintf("/workBench/apiManage/access-manage/detail/%s", accessID)
}
func myClientsPath(clientPrimary uint64) string {
return "/workBench/apiManage/client/" + strconv.FormatUint(clientPrimary, 10)
}
// CreateAPIAsset 创建 API 资料
func (svc *Service) CreateAPIAsset(req apistructs.APIAssetCreateRequest) (apiAssetID string, err error) {
// 参数校验
if req.AssetID == "" {
return "", apierrors.CreateAPIAsset.MissingParameter("assetID")
}
if err := apistructs.ValidateAPIAssetID(req.AssetID); err != nil {
return "", apierrors.CreateAPIAsset.InvalidParameter(fmt.Errorf("assetID: %v", err))
}
if req.AssetName == "" {
req.AssetName = req.AssetID
}
if err := strutil.Validate(req.AssetName,
strutil.MinLenValidator(1),
strutil.MaxLenValidator(191),
); err != nil {
return "", apierrors.CreateAPIAsset.InvalidParameter(fmt.Errorf("assetName: %v", err))
}
if req.OrgID == 0 {
return "", apierrors.CreateAPIAsset.MissingParameter("orgID")
}
// 校验每个 version
for _, version := range req.Versions {
version.OrgID = req.OrgID
version.APIAssetID = req.AssetID
if err := svc.readSpec(&version); err != nil {
return "", apierrors.CreateAPIAsset.InvalidParameter(err)
}
if _, err := parseSpec(&version.SpecProtocol, version.Spec); err != nil {
logrus.Errorf("failed to parseSpec, err: %v", err)
return "", apierrors.CreateAPIAssetVersion.InvalidParameter(errors.Wrap(err, "swagger 文件不符合 OAS2/3 标准"))
}
// 校验每个 instance
for _, ins := range version.Instances {
if err := validateVersionInstanceRequest(ins); err != nil {
return "", err
}
}
}
// 获取额外参数
var (
timeNow = time.Now()
projectID, appID *uint64
projectName, appName *string
)
// 来自 action 或 design_center 的创建请求要查询 project 和 app 信息
if req.Source == apistructs.CreateAPIAssetSourceAction ||
req.Source == apistructs.CreateAPIAssetSourceDesignCenter {
project, err := bdl.Bdl.GetProject(req.ProjectID)
if err != nil {
return "", err
}
projectID = &project.ID
projectName = &project.Name
app, err := bdl.Bdl.GetApp(req.AppID)
if err != nil {
return "", err
}
appID = &app.ID
appName = &app.Name
}
var (
exAsset apistructs.APIAssetsModel
assetModel = dbclient.APIAssetsModel{
BaseModel: apistructs.BaseModel{
ID: 0,
CreatedAt: timeNow,
UpdatedAt: timeNow,
CreatorID: req.IdentityInfo.UserID,
UpdaterID: req.IdentityInfo.UserID,
},
OrgID: req.OrgID,
AssetID: req.AssetID,
AssetName: req.AssetName,
Desc: req.Desc,
Logo: req.Logo,
ProjectID: projectID,
ProjectName: projectName,
AppID: appID,
AppName: appName,
Public: false,
CurVersionID: 0,
CurMajor: 0,
CurMinor: 0,
CurPatch: 0,
}
)
// 检查是否已存在这个 asset
switch err := svc.FirstRecord(&exAsset, map[string]interface{}{
"org_id": req.OrgID,
"asset_id": req.AssetID,
}); {
case err == nil &&
(req.Source == apistructs.CreateAPIAssetSourceAction ||
req.Source == apistructs.CreateAPIAssetSourceDesignCenter):
// assetID 已存在 且 来自 action 的创建, 则跳过新建流程
case err == nil:
// assetID 已存在, 则不允许创建, 立即响应 err
return "", apierrors.CreateAPIAsset.InternalError(errors.New("assetID already exists"))
case gorm.IsRecordNotFoundError(err):
// 如果 assetID 不存在, 则正常创建
if err := dbclient.Sq().Create(&assetModel).Error; err != nil {
logrus.Errorf("failed to Create assetModel, err: %v", err)
return "", apierrors.CreateAPIAsset.InternalError(err)
}
default:
// 查询错误, 响应 err
logrus.Errorf("failed to FirstRecord exAsset, err: %v", err)
return "", apierrors.CreateAPIAsset.InternalError(err)
}
// 创建或更新 API Asset Versions
for _, version := range req.Versions {
version.APIAssetID = assetModel.AssetID
version.OrgID = assetModel.OrgID
version.IdentityInfo = req.IdentityInfo
if _, _, _, err := svc.CreateAPIAssetVersion(version); err != nil {
return "", err
}
}
return assetModel.AssetID, nil
}
// CreateAPIAssetVersion 创建 API 资料版本
func (svc *Service) CreateAPIAssetVersion(req apistructs.APIAssetVersionCreateRequest) (apiAsset *dbclient.APIAssetsModel,
version *apistructs.APIAssetVersionsModel, spec *dbclient.APIAssetVersionSpecsModel, err error) {
// 参数校验
if err := apistructs.ValidateAPIAssetID(req.APIAssetID); err != nil {
return nil, nil, nil, apierrors.CreateAPIAssetVersion.InvalidParameter(fmt.Errorf("apiAssetID: %v", err))
}
if req.OrgID == 0 {
return nil, nil, nil, apierrors.CreateAPIAssetVersion.MissingParameter("orgID")
}
if req.Source == "" {
req.Source = "local"
}
// 查询所属的 asset
var (
asset apistructs.APIAssetsModel
whereAsset = map[string]interface{}{
"org_id": req.OrgID,
"asset_id": req.APIAssetID,
}
)
if err := svc.FirstRecord(&asset, whereAsset); err != nil {
logrus.Errorf("failed to FirstRecord asset, err: %v", err)
return nil, nil, nil, err
}
// 鉴权 {asset 创建者, 企业管理人员, 关联项目管理人员, 关联应用管理人员} 才可以创建 version
rolesSet := bdl.FetchAssetRolesSet(req.OrgID, req.UserID)
if written := writePermission(rolesSet, &asset); !written {
return nil, nil, nil, apierrors.CreateAPIAssetVersion.AccessDenied()
}
if err := svc.readSpec(&req); err != nil {
return nil, nil, nil, apierrors.CreateAPIAssetVersion.InvalidParameter(err)
}
swagger, err := parseSpec(&req.SpecProtocol, req.Spec)
if err != nil {
logrus.Errorf("failed to parseSpec, err: %v", err)
return nil, nil, nil, apierrors.CreateAPIAssetVersion.InvalidParameter(errors.Wrap(err, "swagger 文件不符合 OAS2/3 标准"))
}
for i, instance := range req.Instances {
if err := validateVersionInstanceRequest(instance); err != nil {
return nil, nil, nil, err
}
handleVersionInstanceRequest(&req.Instances[i])
}
var (
timeNow = time.Now()
)
version = &apistructs.APIAssetVersionsModel{
BaseModel: apistructs.BaseModel{
ID: 0,
CreatedAt: timeNow,
UpdatedAt: timeNow,
CreatorID: req.IdentityInfo.UserID,
UpdaterID: req.IdentityInfo.UserID,
},
OrgID: req.OrgID,
AssetID: req.APIAssetID,
AssetName: asset.AssetName,
Major: req.Major,
Minor: req.Minor,
Patch: req.Patch,
Desc: req.Desc,
SpecProtocol: req.SpecProtocol,
SwaggerVersion: swagger.Info.Version,
Deprecated: false,
Source: req.Source,
AppID: req.AppID,
Branch: req.Branch,
ServiceName: req.ServiceName,
}
if err = dbclient.GenSemVer(req.OrgID, req.APIAssetID, swagger.Info.Version, &version.Major, &version.Minor, &version.Patch); err != nil {
return nil, nil, nil, apierrors.CreateAPIAssetVersion.InternalError(err)
}
if err := dbclient.Sq().Create(version).Error; err != nil {
return nil, nil, nil, apierrors.CreateAPIAssetVersion.InternalError(err)
}
// 创建或更新 API Asset Version Spec
spec = &dbclient.APIAssetVersionSpecsModel{
BaseModel: apistructs.BaseModel{
ID: 0,
CreatorID: req.IdentityInfo.UserID,
UpdaterID: req.IdentityInfo.UserID,
},
OrgID: req.OrgID,
AssetID: req.APIAssetID,
VersionID: version.ID,
SpecProtocol: string(req.SpecProtocol),
Spec: req.Spec,
}
if err := dbclient.CreateOrUpdateAPIAssetVersionSpec(spec); err != nil {
return nil, nil, nil, apierrors.CreateAPIAssetVersion.InternalError(err)
}
// 插入搜索用的索引和片段
go svc.createOAS3IndexFragments(swagger, req.APIAssetID, asset.AssetName, version.ID)
// 创建 API 实例
for _, instanceReq := range req.Instances {
services, err := bdl.Bdl.GetRuntimeServices(instanceReq.RuntimeID, req.OrgID, req.IdentityInfo.UserID)
if err != nil {
logrus.Errorf("failed to GetRuntimeServices, err: %v", err)
continue
}
if len(services.Services) == 0 {
logrus.Error("length of services.Services == 0")
continue
}
service, ok := services.Services[instanceReq.ServiceName]
if !ok {
logrus.Errorf("no this service which name is %s", instanceReq.ServiceName)
continue
}
if len(service.Addrs) == 0 {
logrus.Error("length of service.Addrs == 0")
continue
}
instanceAddr := service.Addrs[0]
var appID uint64
if services.Extra != nil {
appID = services.Extra.ApplicationId
} else {
appID = *asset.AppID
}
if _, apiError := svc.CreateInstantiation(&apistructs.CreateInstantiationReq{
OrgID: req.OrgID,
Identity: &req.IdentityInfo,
URIParams: &apistructs.CreateInstantiationURIParams{
AssetID: req.APIAssetID,
SwaggerVersion: swagger.Info.Version,
Minor: req.Minor,
},
Body: &apistructs.CreateInstantiationBody{
Type: "dice", // 仅 action 创建实例时会在此处创建实例化, 所以 Type 的值为 "dice"
URL: instanceAddr,
ProjectID: services.ProjectID,
AppID: appID,
RuntimeID: instanceReq.RuntimeID,
ServiceName: instanceReq.ServiceName,
Workspace: services.Extra.Workspace,
},
}); apiError != nil {
return nil, nil, nil, apiError
}
}
// 更新 APIAsset
latestVersion, err := dbclient.QueryAPILatestVersion(req.OrgID, req.APIAssetID)
if err != nil {
return nil, nil, nil, err
}
if err := dbclient.Sq().Model(new(apistructs.APIAssetsModel)).Where(map[string]interface{}{
"org_id": req.OrgID,
"asset_id": req.APIAssetID,
}).Updates(map[string]interface{}{
"updater_id": req.IdentityInfo.UserID,
"updated_at": time.Now(),
"cur_version_id": latestVersion.ID,
"cur_major": latestVersion.Major,
"cur_minor": latestVersion.Minor,
"cur_patch": latestVersion.Patch,
}).Error; err != nil {
return nil, nil, nil, err
}
// 查询更新后的 APIAsset
var updatedAsset dbclient.APIAssetsModel
if err := svc.FirstRecord(&updatedAsset, whereAsset); err != nil {
return nil, nil, nil, err
}
// 保留最新 10 条version
var (
versions []*apistructs.APIAssetVersionsModel
versionsIDs []uint64
where = map[string]interface{}{
"org_id": version.OrgID,
"asset_id": version.AssetID,
"major": version.Major,
"minor": version.Minor,
}
)
if err := dbclient.Sq().Where(where).Order("patch DESC").
Find(&versions); err != nil {
logrus.Errorf("failed to query newest ten versions: %v", err)
}
if len(versions) >= 10 {
for i := 10; i < len(versions); i++ {
versionsIDs = append(versionsIDs, versions[i].ID)
}
if err := dbclient.Sq().Where(where).
Where("id IN (?)", versionsIDs).
Delete(new(apistructs.APIAssetVersionsModel)).Error; err != nil {
logrus.Errorf("failed to delete old versions: %+v", err)
}
if err := dbclient.Sq().
Where(map[string]interface{}{
"org_id": req.OrgID,
"asset_id": req.APIAssetID,
}).
Where("version_id IN (?)", versionsIDs).
Delete(new(apistructs.APIAssetVersionSpecsModel)).Error; err != nil {
logrus.Errorf("failed to Delete SpecsModel, err: %v", err)
}
}
return &updatedAsset, version, spec, nil
}
func (svc *Service) CreateInstantiation(req *apistructs.CreateInstantiationReq) (*apistructs.InstantiationModel, *errorresp.APIError) {
// 参数校验
if req.Body == nil {
return nil, apierrors.CreateInstantiation.MissingParameter("missing body")
}
if req.Body.Type = strings.ToLower(req.Body.Type); req.Body.Type != InsTypeDice && req.Body.Type != InsTypeExternal {
return nil, apierrors.CreateInstantiation.MissingParameter("missing type")
}
if _, err := url.Parse(req.Body.URL); err != nil {
return nil, apierrors.CreateInstantiation.InvalidParameter("invalid url format")
}
var (
timeNow = time.Now()
asset apistructs.APIAssetsModel
version apistructs.APIAssetVersionsModel
)
// 查询 asset
if err := svc.FirstRecord(&asset, map[string]interface{}{
"org_id": req.OrgID,
"asset_id": req.URIParams.AssetID,
}); err != nil {
logrus.Errorf("failed to FirstRecord asset, err: %v", err)
return nil, apierrors.CreateInstantiation.InternalError(err)
}
// 查出 version
switch err := svc.FirstRecord(&version, map[string]interface{}{
"org_id": req.OrgID,
"asset_id": req.URIParams.AssetID,
"swagger_version": req.URIParams.SwaggerVersion,
}); {
case err == nil:
case gorm.IsRecordNotFoundError(err):
return nil, apierrors.CreateInstantiation.InternalError(
errors.Errorf("版本标签 %s 不存在", req.URIParams.SwaggerVersion))
default:
logrus.Errorf("failed to FirstRecord version, err: %v", err)
return nil, apierrors.CreateInstantiation.InternalError(err)
}
var instantiation = apistructs.InstantiationModel{
BaseModel: apistructs.BaseModel{
ID: 0,
CreatedAt: timeNow,
UpdatedAt: timeNow,
CreatorID: req.Identity.UserID,
UpdaterID: req.Identity.UserID,
},
OrgID: req.OrgID,
Name: "",
AssetID: req.URIParams.AssetID,
SwaggerVersion: req.URIParams.SwaggerVersion,
Major: version.Major,
Minor: req.URIParams.Minor,
Type: req.Body.Type,
URL: req.Body.URL,
ProjectID: req.Body.ProjectID,
AppID: req.Body.AppID,
ServiceName: req.Body.ServiceName,
RuntimeID: req.Body.RuntimeID,
Workspace: req.Body.Workspace,
}
if err := dbclient.FirstOrCreateInstantiation(&instantiation, map[string]interface{}{
"asset_id": req.URIParams.AssetID,
"swagger_version": req.URIParams.SwaggerVersion,
"minor": req.URIParams.Minor,
}); err != nil {
return nil, apierrors.CreateInstantiation.InternalError(err)
}
// 如果绑定实例前, asset 还没关联项目和应用, 则将实例的项目和应用关联到 asset (允许失败)
switch asset.ProjectID {
case nil:
project, err := bdl.Bdl.GetProject(instantiation.ProjectID)
if err != nil {
logrus.Errorf("failed to GetProject, err: %v", err)
break
}
app, err := bdl.Bdl.GetApp(instantiation.AppID)
if err != nil {
logrus.Errorf("failed to GetApp, err: %v", err)
break
}
if err := dbclient.Sq().Model(new(apistructs.APIAssetsModel)).
Where(map[string]interface{}{
"org_id": req.OrgID,
"asset_id": req.URIParams.AssetID,
}).
Updates(map[string]interface{}{
"project_id": instantiation.ProjectID,
"project_name": project.Name,
"app_id": instantiation.AppID,
"app_name": app.Name,
"updated_at": timeNow,
"updater_id": req.Identity.UserID,
},
).Error; err != nil {
logrus.Errorf("failed to Updates AssetModel, err: %v", err)
}
}
instantiations, ok, apiError := svc.GetInstantiation(&apistructs.GetInstantiationsReq{
OrgID: req.OrgID,
Identity: req.Identity,
URIParams: &apistructs.GetInstantiationsURIParams{
AssetID: req.URIParams.AssetID,
SwaggerVersion: req.URIParams.SwaggerVersion,
Minor: req.URIParams.Minor,
},
})
if apiError != nil {
return nil, apiError
}
if !ok {
return nil, apierrors.CreateInstantiation.InternalError(errors.New("failed to CreateInstantiation"))
}
return instantiations, nil
}
func (svc *Service) CreateClient(req *apistructs.CreateClientReq) (*apistructs.ClientModel, *errorresp.APIError) {
if req == nil || req.Body == nil {
return nil, apierrors.CreateClient.InvalidParameter("无效的参数")
}
if req.Body.Name == "" {
return nil, apierrors.CreateClient.InvalidParameter("无效的客户端标识")
}
if len(req.Body.DisplayName) == 0 || len(req.Body.DisplayName) > 50 {
return nil, apierrors.CreateClient.InvalidParameter("无效的客户端名称")
}
// 检查同名 client 是否已存在
if err := svc.FirstRecord(new(apistructs.ClientModel), map[string]interface{}{
"org_id": req.OrgID,
"name": req.Body.Name,
}); err == nil {
return nil, apierrors.CreateClient.InternalError(errors.New("客户端标识已存在"))
}
// 检查此用户下同 displayName 的 client 是否存在
if err := svc.FirstRecord(new(apistructs.ClientModel), map[string]interface{}{
"org_id": req.OrgID,
"display_name": req.Body.DisplayName,
"creator_id": req.Identity.UserID,
}); err == nil {
return nil, apierrors.CreateClient.InternalError(errors.New("用户名下已有同名客户端"))
}
consumer, err := bdl.Bdl.CreateClientConsumer(req.OrgID, req.Body.Name)
if err != nil {
return nil, apierrors.CreateClient.InternalError(err)
}
var (
timeNow = time.Now()
model = apistructs.ClientModel{
BaseModel: apistructs.BaseModel{
ID: 0,
CreatedAt: timeNow,
UpdatedAt: timeNow,
CreatorID: req.Identity.UserID,
UpdaterID: req.Identity.UserID,
},
OrgID: req.OrgID,
Name: req.Body.Name,
Desc: req.Body.Desc,
ClientID: consumer.ClientId,
DisplayName: req.Body.DisplayName,
}
)
if err = dbclient.Sq().Create(&model).Error; err != nil {
return nil, apierrors.CreateClient.InternalError(err)
}
return &model, nil
}
// 创建一个合约. 注意创建合约时, 需要查询客户端详情, 查询客户端详情时传入的 ClientID 是 dice_api_clients 的主键
func (svc *Service) CreateContract(req *apistructs.CreateContractReq) (*apistructs.ClientModel, *apistructs.SK, *apistructs.ContractModel, *errorresp.APIError) {
// 参数校验
if req.URIParams == nil {
return nil, nil, nil, apierrors.CreateContract.InvalidParameter("no URI parameter")
}
if req.Body == nil {
return nil, nil, nil, apierrors.CreateContract.InvalidParameter("no body")
}
if req.OrgID == 0 {
return nil, nil, nil, apierrors.CreateContract.InvalidParameter("orgID can not be 0")
}
// 参数初始化
var (
asset apistructs.APIAssetsModel
access apistructs.APIAccessesModel
)
// 查询 assetName
if err := svc.FirstRecord(&asset, map[string]interface{}{
"org_id": req.OrgID,
"asset_id": req.Body.AssetID,
}); err != nil {
logrus.Errorf("failed to FirstRecord asset, err: %v", err)
return nil, nil, nil, apierrors.CreateContract.InternalError(errors.New("查询 API 失败"))
}
// 查询客户端详情 (一般角色只能用自己的客户端, 企业管理员可以用所有客户端)
rolesSet := bdl.FetchAssetRolesSet(req.OrgID, req.Identity.UserID)
rolesMOrgs := rolesSet.RolesOrgs(bdl.OrgMRoles...)
client, err := dbclient.GetMyClient(&apistructs.GetClientReq{
OrgID: req.OrgID,
Identity: req.Identity,
URIParams: &apistructs.GetClientURIParams{ClientID: req.URIParams.ClientID},
}, inSlice(strconv.FormatUint(req.OrgID, 10), rolesMOrgs))
if err != nil {
logrus.Errorf("failed to GetMyClient, err: %v", err)
return nil, nil, nil, apierrors.CreateContract.InternalError(errors.New("客户端不存在或无权限"))
}
// 查询 SK
credentials, err := bdl.Bdl.GetClientCredentials(client.ClientID)
if err != nil {
logrus.Errorf("failed to GetClientCredentials, err: %v", err)
return nil, nil, nil, apierrors.CreateContract.InternalError(errors.New("查询客户端密钥失败"))
}
sk := apistructs.SK{
ClientID: credentials.ClientId,
ClientSecret: credentials.ClientSecret,
}
// 查询 access
if err = svc.FirstRecord(&access, map[string]interface{}{
"org_id": req.OrgID,
"asset_id": req.Body.AssetID,
"swagger_version": req.Body.SwaggerVersion,
}); err != nil {
logrus.Errorf("failed to FirstRecord access: %v", err)
return nil, nil, nil, apierrors.CreateContract.InternalError(errors.New("查询访问管理失败"))
}
// 查询 access 下的 SLA 列表
var slas []*apistructs.SLAModel
if _ = svc.ListRecords(&slas, map[string]interface{}{
"access_id": access.ID,
}); len(slas) > 0 && req.Body.SLAID == nil {
return nil, nil, nil, apierrors.CreateContract.InvalidParameter("未选择任何 SLA")
}
// 查询是否已经有这样的合约了, 如果有且不是撤销状态, 则不再创建了
var (
exContract apistructs.ContractModel
where = map[string]interface{}{
"asset_id": req.Body.AssetID,
"org_id": req.OrgID,
"client_id": req.URIParams.ClientID,
"swagger_version": req.Body.SwaggerVersion,
}
)
// 如果已存在这样的调用的申请
if err := dbclient.Sq().Where(where).Find(&exContract).Error; err == nil {
contract, err := svc.createContractIfExists(req, &asset, &access, client, &exContract)
if err != nil {
logrus.Errorf("failed to createContractIfExists, err: %v", err)
return nil, nil, nil, apierrors.CreateContract.InternalError(errors.New("调用申请失败"))
}
return client, &sk, contract, nil
}
// 如果没有这样的调用申请
contract, err := svc.createContractFirstTime(req, &asset, &access, client)
if err != nil {
logrus.Errorf("failed to createContractFirstTime, err: %v", err)
return nil, nil, nil, apierrors.CreateContract.InternalError(errors.New("调用申请失败"))
}
return client, &sk, contract, nil
}
// 创建合约时, 如果合约已存在, 进入此分支
func (svc *Service) createContractIfExists(req *apistructs.CreateContractReq, asset *apistructs.APIAssetsModel, access *apistructs.APIAccessesModel,
client *apistructs.ClientModel, exContract *apistructs.ContractModel) (*apistructs.ContractModel, error) {
var (
err error
timeNow = time.Now()
updates = make(map[string]interface{})
contract apistructs.ContractModel
record = apistructs.ContractRecordModel{
ID: 0,
OrgID: req.OrgID,
ContractID: exContract.ID,
Action: "重新发起了调用申请",
CreatorID: req.Identity.UserID,
CreatedAt: timeNow,
}
sla apistructs.SLAModel
)
// 如果合约处于 "等待授权" 和 "已授权" 以外的情形, 则修改为 "等待授权"
if exContract.Status.ToLower() != apistructs.ContractApproving &&
exContract.Status.ToLower() != apistructs.ContractApproved {
exContract.Status = apistructs.ContractApproving
updates["status"] = exContract.Status
}
// 如果合约处 "等待授权" 且 access 是自动授权的, 则修改为 "已授权"
if exContract.Status.ToLower() == apistructs.ContractApproving &&
access.Authorization.ToLower() == apistructs.AuthorizationAuto {
exContract.Status = apistructs.ContractApproved
updates["status"] = exContract.Status
}
// 库表操作和消息通知
defer func() {
tx := dbclient.Tx()
defer tx.RollbackUnlessCommitted()
updates["updated_at"] = timeNow
updates["updater_id"] = req.Identity.UserID
if err = tx.Model(&contract).
Where(map[string]interface{}{"id": exContract.ID}).
Updates(updates).
Error; err != nil {
err = errors.Wrap(err, "failed to Updates contract")
return
}
switch updatingStatus, ok := updates["status"]; {
case !ok:
// 如果没有修改 status, 则关注 SLA 状态
// 如果申请了新的 SLA 且处于待审批的状态, 则记录操作, 并通知管理员
if reqSLAID, ok := updates["request_sla_id"]; ok && reqSLAID != nil {
go svc.contractMsgToManager(req.OrgID, req.Identity.UserID, asset, access, RequestItemSLA(sla.Name), false)
record.Action = fmt.Sprintf("申请了名称为 %s 的 SLA", sla.Name)
break
}
// 如果通过了申请的 SLA, 则记录操作, 通知用户
if _, ok := updates["cur_sla_id"]; ok {
result := ApprovalResultSLAUpdated(sla.Name)
go svc.contractMsgToUser(req.OrgID, req.Identity.UserID, asset.AssetName, client, result)
record.Action = string(result)
}
case updatingStatus == apistructs.ContractApproving:
// 如果是更新后的状态是"等待授权", 向管理员发送通知
go svc.contractMsgToManager(req.OrgID, req.Identity.UserID, asset, access, RequestItemAPI(access.AssetName, access.SwaggerVersion), false)
record.Action += ", 等待审批中"
case updatingStatus == apistructs.ContractApproved:
// 如果更新后的状态是"已授权", 向用户发送通知; 调用网关测的授权
go svc.contractMsgToUser(req.OrgID, req.Identity.UserID, access.AssetName, client, ManagerProvedContract)
record.Action += ", 并自动通过了审批"
if err = bdl.Bdl.GrantEndpointToClient(client.ClientID, access.EndpointID); err != nil {
err = errors.Wrapf(err, "failed to GrantEndpointToClient, clientID: %s, endpointID: %s", client.ClientID, access.EndpointID)
return
}
}
if err = tx.Create(&record).Error; err != nil {
err = errors.Wrap(err, "failed to Create record")
}
tx.Commit()
go func() {
err := svc.createOrUpdateClientLimits(access.EndpointID, client.ClientID, contract.ID)
if err != nil {
logrus.Errorf("create or update client limits failed, err:%+v", err)
}
}()
}()
// 如果没有申请 SLA, 则结束业务流程
if req.Body.SLAID == nil {
return &contract, err
}
exContract.RequestSLAID = req.Body.SLAID
updates["request_sla_id"] = req.Body.SLAID
// 如果合约没有当前 SLA, 且 access 有默认 SLA, 则令当前 SLA 为默认 SLA
if exContract.CurSLAID == nil && access.DefaultSLAID != nil {
exContract.CurSLAID = access.DefaultSLAID
updates["cur_sla_id"] = exContract.CurSLAID
updates["sla_committed_at"] = timeNow
}
// 如果当前合约与申请的合约一致, 则相当于自动通过
if exContract.CurSLAID != nil && *exContract.CurSLAID == *req.Body.SLAID {
updates["request_sla_id"] = nil
}
// 如果 SLA 是自动审批的, 则将请求中的 SLA 转移到当前 SLA
if err := svc.FirstRecord(&sla, map[string]interface{}{"id": req.Body.SLAID}); err == nil && sla.Approval.ToLower() == apistructs.AuthorizationAuto {
updates["cur_sla_id"] = req.Body.SLAID
updates["sla_committed_at"] = timeNow
updates["request_sla_id"] = nil
}
return &contract, err
}
// 创建合约时, 如果合约不存在, 进入此分支
func (svc *Service) createContractFirstTime(req *apistructs.CreateContractReq, asset *apistructs.APIAssetsModel, access *apistructs.APIAccessesModel,
client *apistructs.ClientModel) (*apistructs.ContractModel, error) {
var (
timeNow = time.Now()
contract = apistructs.ContractModel{
BaseModel: apistructs.BaseModel{
ID: 0,
CreatedAt: timeNow,
UpdatedAt: timeNow,
CreatorID: req.Identity.UserID,
UpdaterID: req.Identity.UserID,
},
OrgID: req.OrgID,
AssetID: access.AssetID,
AssetName: access.AssetName,
SwaggerVersion: access.SwaggerVersion,
ClientID: client.ID,
Status: apistructs.ContractApproving,
CurSLAID: nil,
RequestSLAID: nil,
SLACommittedAt: nil,
}
)
// 如果 access 下有 sla, 但没有申请 SLA, 则不允许申请
var count uint64
dbclient.Sq().Model(new(apistructs.SLAModel)).Where(map[string]interface{}{"access_id": access.ID}).Count(&count)
if count > 0 && (req.Body.SLAID == nil || *req.Body.SLAID == 0) {
return nil, apierrors.CreateContract.InvalidParameter("必须申请一个 SLA")
}
// 如果 access 是自动授权的, 令 contract.Status 为 "已授权"
if access.Authorization.ToLower() == apistructs.AuthorizationAuto {
contract.Status = apistructs.ContractApproved
}
// 如果 access 有默认 SLA, 则令 contract 当前 SLA 为其默认 SLA
if access.DefaultSLAID != nil && *access.DefaultSLAID != 0 {
contract.CurSLAID = access.DefaultSLAID
contract.SLACommittedAt = &timeNow
}
if req.Body.SLAID == nil {
var id uint64 = 0
req.Body.SLAID = &id
}
sla, err := svc.querySLAByID(*req.Body.SLAID, access)
switch {
case err != nil:
// 查询不到申请的 SLA
return nil, errors.Wrap(err, "failed to FirstRecord sla")
case sla.Approval.ToLower() == apistructs.AuthorizationAuto:
// 如果 SLA 是自动授权的
contract.CurSLAID = req.Body.SLAID
contract.SLACommittedAt = &timeNow
case sla.Source == apistructs.SourceSystem:
// 如果 SLA 是无限制的, 则令 contract 当前 SLA 为申请的 SLA
contract.CurSLAID = req.Body.SLAID
case contract.CurSLAID != nil && *req.Body.SLAID == *contract.CurSLAID:
// 如果申请的 SLA 与 当前的 SLA 一致 (无需操作)
default:
// 默认情形, 令 contract 的申请中 SLA 为传入的 SLA
contract.RequestSLAID = req.Body.SLAID
}
tx := dbclient.Tx()
defer tx.RollbackUnlessCommitted()
// 创建合约记录
if err := tx.Create(&contract).Error; err != nil {
return nil, err
}
// 操作记录
var record = apistructs.ContractRecordModel{
ID: 0,
OrgID: req.OrgID,
ContractID: contract.ID,
Action: "发起了调用申请",
CreatorID: req.Identity.UserID,
CreatedAt: timeNow,
}
switch contract.Status.ToLower() {
case apistructs.ContractApproving:
// 等待审批, 通知管理人员进行审批
go svc.contractMsgToManager(req.OrgID, req.Identity.UserID, asset, access, RequestItemAPI(access.AssetName, access.SwaggerVersion), false)
record.Action += ", 等待审批中"
if err := tx.Create(&record).Error; err != nil {
logrus.Errorf("failed to Create record: %v", err)
return nil, errors.Wrap(err, "failed to Create record")
}
case apistructs.ContractApproved:
// 如果合约已授权, 调用网关侧的授权; 通知用户已通过
go svc.contractMsgToUser(req.OrgID, req.Identity.UserID, access.AssetName, client, ManagerProvedContract)
record.Action += ", 并自动通过了审批"
if err := tx.Create(&record).Error; err != nil {
logrus.Errorf("failed to Create record: %v", err)
return nil, errors.Wrap(err, "failed to Create record")
}
if err := bdl.Bdl.GrantEndpointToClient(client.ClientID, access.EndpointID); err != nil {
logrus.Errorf("failed to GrantEndpointToClient, err: %v", err)
return nil, errors.Wrap(err, "failed to GrantEndpointToClient")
}
}
tx.Commit()
go func() {
err := svc.createOrUpdateClientLimits(access.EndpointID, client.ClientID, contract.ID)
if err != nil {
logrus.Errorf("createOrUpdateClientLimits failed, err:%+v", err)
}
}()
return &contract, nil
}
func (svc *Service) CreateAccess(req *apistructs.CreateAccessReq) (map[string]interface{}, *errorresp.APIError) {
// 参数校验
if req == nil || req.Body == nil {
return nil, apierrors.CreateAccess.InvalidParameter("invalid parameters")
}
if req.OrgID == 0 {
return nil, apierrors.CreateAccess.InvalidParameter("invalid orgID")
}
var asset apistructs.APIAssetsModel
if err := svc.FirstRecord(&asset, map[string]interface{}{"org_id": req.OrgID, "asset_id": req.Body.AssetID}); err != nil {
return nil, apierrors.CreateAccess.InternalError(errors.Wrap(err, "failed to GetAPIAsset"))
}
// 查找一个版本记录 (为了查找swaggerVersion)
var version apistructs.APIAssetVersionsModel
if err := svc.FirstRecord(&version, map[string]interface{}{
"org_id": req.OrgID,
"asset_id": req.Body.AssetID,
"major": req.Body.Major,
}); err != nil {
return nil, apierrors.CreateAccess.InternalError(errors.Wrap(err, "failed to FirstVersion"))
}
swaggerVersion := version.SwaggerVersion
// 检查 access 是否已存在
switch err := dbclient.Sq().First(new(apistructs.APIAccessesModel), map[string]interface{}{
"org_id": req.OrgID,
"asset_id": req.Body.AssetID,
"swagger_version": swaggerVersion,
}).Error; {
case err == nil:
return nil, apierrors.CreateAccess.InternalError(fmt.Errorf("this access is already exists. {assetID: %s, swaggerVersion: %s}", req.Body.AssetID,
swaggerVersion))
case gorm.IsRecordNotFoundError(err):
default:
return nil, apierrors.CreateAccess.InternalError(err)
}
// 查找实例
instantiations, ok, apiError := svc.GetInstantiation(&apistructs.GetInstantiationsReq{
OrgID: req.OrgID,
Identity: req.Identity,
URIParams: &apistructs.GetInstantiationsURIParams{
AssetID: req.Body.AssetID,
SwaggerVersion: swaggerVersion,
Minor: req.Body.Minor,
},
})
if apiError != nil {
return nil, apiError
}
if !ok {
return nil, apierrors.CreateAccess.InternalError(errors.New("no instantiation"))
}
if strings.ToLower(instantiations.Type) == InsTypeDice {
if req.Body.ProjectID != instantiations.ProjectID {
return nil, apierrors.CreateAccess.InvalidParameter("关联的项目错误, 可能实例被变更, 请刷新重试")