/
project.go
1825 lines (1654 loc) · 59.3 KB
/
project.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 project 封装项目资源相关操作
package project
import (
"context"
"encoding/json"
"fmt"
"math"
"strconv"
"strings"
"time"
"github.com/jinzhu/gorm"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"github.com/erda-project/erda-infra/providers/i18n"
"github.com/erda-project/erda/apistructs"
"github.com/erda-project/erda/bundle"
"github.com/erda-project/erda/modules/core-services/conf"
"github.com/erda-project/erda/modules/core-services/dao"
"github.com/erda-project/erda/modules/core-services/model"
"github.com/erda-project/erda/modules/core-services/types"
"github.com/erda-project/erda/pkg/crypto/uuid"
"github.com/erda-project/erda/pkg/filehelper"
"github.com/erda-project/erda/pkg/numeral"
calcu "github.com/erda-project/erda/pkg/resourcecalculator"
"github.com/erda-project/erda/pkg/ucauth"
)
// Project 资源对象操作封装
type Project struct {
db *dao.DBClient
uc *ucauth.UCClient
bdl *bundle.Bundle
trans i18n.Translator
memberCache *Cache
clusterCache *Cache
}
// Option 定义 Project 对象的配置选项
type Option func(*Project)
// New 新建 Project 实例,通过 Project 实例操作企业资源
func New(opts ...Option) *Project {
p := &Project{
memberCache: NewCache(time.Minute),
clusterCache: NewCache(time.Minute),
}
for _, f := range opts {
f(p)
}
return p
}
// WithDBClient 配置 db client
func WithDBClient(dbClient *dao.DBClient) Option {
return func(project *Project) {
project.db = dbClient
}
}
// WithUCClient 配置 uc client
func WithUCClient(ucClient *ucauth.UCClient) Option {
return func(project *Project) {
project.uc = ucClient
}
}
// WithBundle 配置 bundle
func WithBundle(bdl *bundle.Bundle) Option {
return func(project *Project) {
project.bdl = bdl
}
}
// WithI18n set the translator
func WithI18n(trans i18n.Translator) Option {
return func(project *Project) {
project.trans = trans
}
}
// CreateWithEvent 创建项目 & 发送事件
func (p *Project) CreateWithEvent(userID string, createReq *apistructs.ProjectCreateRequest) (int64, error) {
// 创建项目
if createReq.DisplayName == "" {
createReq.DisplayName = createReq.Name
}
project, err := p.Create(userID, createReq)
if err != nil {
return 0, err
}
ev := &apistructs.EventCreateRequest{
EventHeader: apistructs.EventHeader{
Event: bundle.ProjectEvent,
Action: bundle.CreateAction,
OrgID: strconv.FormatInt(project.OrgID, 10),
ProjectID: strconv.FormatInt(project.ID, 10),
ApplicationID: "-1",
TimeStamp: time.Now().Format("2006-01-02 15:04:05"),
},
Sender: bundle.SenderCoreServices,
Content: *project,
}
// 发送项目创建事件
if err = p.bdl.CreateEvent(ev); err != nil {
logrus.Warnf("failed to send project create event, (%v)", err)
}
return project.ID, nil
}
// Create 创建项目
func (p *Project) Create(userID string, createReq *apistructs.ProjectCreateRequest) (*model.Project, error) {
// 参数合法性检查
if createReq.Name == "" {
return nil, errors.Errorf("failed to create project(name is empty)")
}
if createReq.OrgID == 0 {
return nil, errors.Errorf("failed to create project(org id is empty)")
}
userIDuint, err := strconv.ParseUint(userID, 10, 64)
if err != nil {
return nil, errors.Wrap(err, "failed to parse userID")
}
// 只有 DevOps 类型的项目,才能配置 quota
if createReq.Template != apistructs.DevopsTemplate {
createReq.ResourceConfigs = nil
}
var clusterConfig []byte
if rc := createReq.ResourceConfigs; rc != nil {
if err := rc.Check(); err != nil {
return nil, err
}
createReq.ClusterConfig = map[string]string{
"PROD": rc.PROD.ClusterName,
"STAGING": rc.STAGING.ClusterName,
"TEST": rc.TEST.ClusterName,
"DEV": rc.DEV.ClusterName,
}
clusterConfig, _ = json.Marshal(createReq.ClusterConfig)
createReq.CpuQuota = float64(calcu.CoreToMillcore(rc.PROD.CPUQuota + rc.STAGING.CPUQuota + rc.TEST.CPUQuota + rc.DEV.CPUQuota))
createReq.MemQuota = float64(calcu.GibibyteToByte(rc.PROD.MemQuota + rc.STAGING.MemQuota + rc.TEST.MemQuota + rc.DEV.MemQuota))
}
if err := initRollbackConfig(&createReq.RollbackConfig); err != nil {
return nil, err
}
rollbackConfig, err := json.Marshal(createReq.RollbackConfig)
if err != nil {
logrus.Infof("failed to marshal rollbackConfig, (%v)", err)
return nil, errors.Errorf("failed to marshal rollbackConfig")
}
functions, err := json.Marshal(createReq.Template.GetProjectFunctionsByTemplate())
if err != nil {
logrus.Infof("failed to marshal projectFunctions, (%v)", err)
return nil, errors.Errorf("failed to marshal projectFunctions")
}
project, err := p.db.GetProjectByOrgAndName(int64(createReq.OrgID), createReq.Name)
if err != nil {
if !gorm.IsRecordNotFoundError(err) {
return nil, err
}
}
if project != nil {
return nil, errors.Errorf("failed to create project(name already exists)")
}
tx := p.db.Begin()
defer tx.RollbackUnlessCommitted()
now := time.Now()
// 添加项目至DB
project = &model.Project{
BaseModel: model.BaseModel{},
Name: createReq.Name,
DisplayName: createReq.DisplayName,
Desc: createReq.Desc,
Logo: createReq.Logo,
OrgID: int64(createReq.OrgID),
UserID: userID,
DDHook: createReq.DdHook,
ClusterConfig: string(clusterConfig),
RollbackConfig: string(rollbackConfig),
CpuQuota: createReq.CpuQuota,
MemQuota: createReq.MemQuota,
Functions: string(functions),
ActiveTime: now,
EnableNS: conf.EnableNS(),
IsPublic: false,
Type: string(createReq.Template),
}
if err := tx.Create(&project).Error; err != nil {
logrus.WithError(err).WithField("model", project.TableName()).
Errorln("failed to Create")
return nil, errors.Errorf("failed to insert project to database")
}
// record quota if it is configured
logrus.WithField("createReq.ResourceConfigs", createReq.ResourceConfigs).Infoln()
if createReq.ResourceConfigs != nil {
quota := &apistructs.ProjectQuota{
ProjectID: uint64(project.ID),
ProjectName: createReq.Name,
ProdClusterName: createReq.ResourceConfigs.PROD.ClusterName,
StagingClusterName: createReq.ResourceConfigs.STAGING.ClusterName,
TestClusterName: createReq.ResourceConfigs.TEST.ClusterName,
DevClusterName: createReq.ResourceConfigs.DEV.ClusterName,
ProdCPUQuota: calcu.CoreToMillcore(createReq.ResourceConfigs.PROD.CPUQuota),
ProdMemQuota: calcu.GibibyteToByte(createReq.ResourceConfigs.PROD.MemQuota),
StagingCPUQuota: calcu.CoreToMillcore(createReq.ResourceConfigs.STAGING.CPUQuota),
StagingMemQuota: calcu.GibibyteToByte(createReq.ResourceConfigs.STAGING.MemQuota),
TestCPUQuota: calcu.CoreToMillcore(createReq.ResourceConfigs.TEST.CPUQuota),
TestMemQuota: calcu.GibibyteToByte(createReq.ResourceConfigs.TEST.MemQuota),
DevCPUQuota: calcu.CoreToMillcore(createReq.ResourceConfigs.DEV.CPUQuota),
DevMemQuota: calcu.GibibyteToByte(createReq.ResourceConfigs.DEV.MemQuota),
CreatorID: userIDuint,
UpdaterID: userIDuint,
}
if err := tx.Debug().Create("a).Error; err != nil {
logrus.WithError(err).WithField("model", quota.TableName()).
Errorln("failed to Create")
return nil, errors.Errorf("failed to insert project quota to database")
}
}
// 新增项目管理员至admin_members表
users, err := p.uc.FindUsers([]string{userID})
if err != nil {
logrus.Warnf("user query error: %v", err)
}
if len(users) > 0 {
member := model.Member{
ScopeType: apistructs.ProjectScope,
ScopeID: project.ID,
ScopeName: project.Name,
ParentID: project.OrgID,
UserID: userID,
Email: users[0].Email,
Mobile: users[0].Phone,
Name: users[0].Name,
Nick: users[0].Nick,
Avatar: users[0].AvatarURL,
UserSyncAt: time.Now(),
OrgID: project.OrgID,
ProjectID: project.ID,
Token: uuid.UUID(),
}
memberExtra := model.MemberExtra{
UserID: userID,
ScopeID: project.ID,
ScopeType: apistructs.ProjectScope,
ParentID: project.OrgID,
ResourceKey: apistructs.RoleResourceKey,
ResourceValue: types.RoleProjectOwner,
}
if err := tx.Create(&member).Error; err != nil {
logrus.WithError(err).WithField("model", member.TableName()).
Errorln("failed to add member to database while creating project")
return nil, errors.Errorf("failed to add member to database while creating project")
}
if err := tx.Create(&memberExtra).Error; err != nil {
logrus.WithError(err).WithField("model", memberExtra.TableName()).
Errorln("failed to add member roles to database while creating project")
return nil, errors.Errorf("failed to add member roles to database while creating project")
}
}
tx.Commit()
return project, nil
}
// UpdateWithEvent 更新项目 & 发送事件
func (p *Project) UpdateWithEvent(ctx context.Context, orgID, projectID int64, userID string, updateReq *apistructs.ProjectUpdateBody) error {
// 更新项目
project, err := p.Update(ctx, orgID, projectID, userID, updateReq)
if err != nil {
return err
}
ev := &apistructs.EventCreateRequest{
EventHeader: apistructs.EventHeader{
Event: bundle.ProjectEvent,
Action: bundle.UpdateAction,
OrgID: strconv.FormatInt(project.OrgID, 10),
ProjectID: strconv.FormatInt(project.ID, 10),
ApplicationID: "-1",
TimeStamp: time.Now().Format("2006-01-02 15:04:05"),
},
Sender: bundle.SenderCoreServices,
Content: *project,
}
// 发送项目更新事件
if err = p.bdl.CreateEvent(ev); err != nil {
logrus.Warnf("failed to send project update event, (%v)", err)
}
return nil
}
// Update 更新项目
func (p *Project) Update(ctx context.Context, orgID, projectID int64, userID string, updateReq *apistructs.ProjectUpdateBody) (*model.Project, error) {
userIDuint, err := strconv.ParseUint(userID, 10, 64)
if err != nil {
return nil, errors.Wrap(err, "failed to parse userID")
}
if rc := updateReq.ResourceConfigs; rc != nil {
updateReq.ClusterConfig = map[string]string{
"PROD": updateReq.ResourceConfigs.PROD.ClusterName,
"STAGING": updateReq.ResourceConfigs.STAGING.ClusterName,
"TEST": updateReq.ResourceConfigs.TEST.ClusterName,
"DEV": updateReq.ResourceConfigs.DEV.ClusterName,
}
if err := updateReq.ResourceConfigs.Check(); err != nil {
return nil, err
}
updateReq.CpuQuota = float64(calcu.CoreToMillcore(rc.PROD.CPUQuota + rc.STAGING.CPUQuota + rc.TEST.CPUQuota + rc.DEV.CPUQuota))
updateReq.MemQuota = float64(calcu.GibibyteToByte(rc.PROD.MemQuota + rc.STAGING.MemQuota + rc.TEST.MemQuota + rc.DEV.MemQuota))
}
if err := checkRollbackConfig(&updateReq.RollbackConfig); err != nil {
return nil, err
}
// 检查待更新的project是否存在
project, err := p.db.GetProjectByID(projectID)
if err != nil {
return nil, errors.Wrap(err, "failed to GetProjectByID")
}
oldQuota, err := p.db.GetQuotaByProjectID(projectID)
if err != nil {
return nil, errors.Wrap(err, "failed to GetQuotaByProjectID")
}
hasOldQuota := oldQuota != nil
if hasOldQuota {
project.Quota = new(apistructs.ProjectQuota)
*project.Quota = *oldQuota
}
if err := patchProject(&project, updateReq, userIDuint); err != nil {
return nil, err
}
tx := p.db.Begin()
defer tx.RollbackUnlessCommitted()
if err = tx.Save(&project).Error; err != nil {
logrus.Warnf("failed to update project, (%v)", err)
return nil, errors.Errorf("failed to update project")
}
if project.Quota == nil {
tx.Commit()
return &project, nil
}
// check new quota is less than reqeust
var dto = new(apistructs.ProjectDTO)
dto.ID = uint64(project.ID)
setProjectDtoQuotaFromModel(dto, project.Quota)
p.fetchPodInfo(dto)
changedRecord := make(map[string]bool)
if oldQuota == nil {
oldQuota = new(apistructs.ProjectQuota)
}
isQuotaChangedOnTheWorkspace(changedRecord, *oldQuota, *project.Quota)
if msg, ok := p.checkNewQuotaIsLessThanRequest(ctx, dto, changedRecord); !ok {
logrus.Errorf("checkNewQuotaIsLessThanRequest is not ok: %s", msg)
return nil, errors.New(msg)
}
if hasOldQuota {
err = tx.Debug().Save(project.Quota).Error
} else {
err = tx.Debug().Create(project.Quota).Error
}
if err != nil {
logrus.WithError(err).Errorln("failed to update project quota")
return nil, errors.Errorf("failed to update project quota: %v", err)
}
if err = tx.Commit().Error; err != nil {
err = errors.Wrap(err, "failed commit to update project and quota")
logrus.WithError(err).Errorln()
return nil, err
}
// audit
go func() {
if project.Quota == nil {
return
}
if !isQuotaChanged(*oldQuota, *project.Quota) {
return
}
var orgName = strconv.FormatInt(orgID, 10)
if org, err := p.db.GetOrg(orgID); err == nil {
orgName = fmt.Sprintf("%s", org.Name)
}
auditCtx := map[string]interface{}{
"orgName": orgName,
"projectName": project.Name,
"newDevCluster": project.Quota.DevClusterName,
"newDevCPU": fmt.Sprintf("%.3f", updateReq.ResourceConfigs.DEV.CPUQuota),
"newDevMem": fmt.Sprintf("%.3fGB", updateReq.ResourceConfigs.DEV.MemQuota),
"newTestCluster": project.Quota.TestClusterName,
"newTestCPU": fmt.Sprintf("%.3f", updateReq.ResourceConfigs.TEST.CPUQuota),
"newTestMem": fmt.Sprintf("%.3fGB", updateReq.ResourceConfigs.TEST.MemQuota),
"newStagingCluster": project.Quota.StagingClusterName,
"newStagingCPU": fmt.Sprintf("%.3f", updateReq.ResourceConfigs.STAGING.CPUQuota),
"newStagingMem": fmt.Sprintf("%.3fGB", updateReq.ResourceConfigs.STAGING.MemQuota),
"newProdCluster": project.Quota.ProdClusterName,
"newProdCPU": fmt.Sprintf("%.3f", updateReq.ResourceConfigs.PROD.CPUQuota),
"newProdMem": fmt.Sprintf("%.3fGB", updateReq.ResourceConfigs.PROD.MemQuota),
"oldDevCluster": oldQuota.DevClusterName,
"oldDevCPU": calcu.ResourceToString(float64(oldQuota.DevCPUQuota), "cpu"),
"oldDevMem": calcu.ResourceToString(float64(oldQuota.DevMemQuota), "memory"),
"oldTestCluster": oldQuota.TestClusterName,
"oldTestCPU": calcu.ResourceToString(float64(oldQuota.TestCPUQuota), "cpu"),
"oldTestMem": calcu.ResourceToString(float64(oldQuota.TestMemQuota), "memory"),
"oldStagingCluster": oldQuota.StagingClusterName,
"oldStagingCPU": calcu.ResourceToString(float64(oldQuota.StagingCPUQuota), "cpu"),
"oldStagingMem": calcu.ResourceToString(float64(oldQuota.StagingMemQuota), "memory"),
"oldProdCluster": oldQuota.ProdClusterName,
"oldProdCPU": calcu.ResourceToString(float64(oldQuota.ProdCPUQuota), "cpu"),
"oldProdMem": calcu.ResourceToString(float64(oldQuota.ProdMemQuota), "memory"),
}
now := time.Now().Format("2006-01-02 15:04:05")
audit := apistructs.Audit{
UserID: userID,
ScopeType: apistructs.OrgScope,
ScopeID: uint64(orgID),
OrgID: uint64(orgID),
ProjectID: uint64(projectID),
Context: auditCtx,
TemplateName: "updateProjectResourceConfig",
Result: "success",
StartTime: now,
EndTime: now,
}
auditRecord, err := convertAuditCreateReq2Model(audit)
if err != nil {
logrus.WithError(err).WithField("audit", audit).
Errorf("failed to convertAuditCreateReq2Model")
return
}
if err = p.db.CreateAudit(auditRecord); err != nil {
logrus.Errorf("failed to create quota audit event when update project %s, %v", project.Name, err)
}
}()
return &project, nil
}
func setQuotaFromResourceConfig(quota *apistructs.ProjectQuota, resourceConfigs *apistructs.ResourceConfigs) {
if quota == nil || resourceConfigs == nil {
return
}
if resourceConfigs.PROD != nil {
quota.ProdClusterName = resourceConfigs.PROD.ClusterName
quota.ProdCPUQuota = calcu.CoreToMillcore(resourceConfigs.PROD.CPUQuota)
quota.ProdMemQuota = calcu.GibibyteToByte(resourceConfigs.PROD.MemQuota)
}
if resourceConfigs.STAGING != nil {
quota.StagingClusterName = resourceConfigs.STAGING.ClusterName
quota.StagingCPUQuota = calcu.CoreToMillcore(resourceConfigs.STAGING.CPUQuota)
quota.StagingMemQuota = calcu.GibibyteToByte(resourceConfigs.STAGING.MemQuota)
}
if resourceConfigs.TEST != nil {
quota.TestClusterName = resourceConfigs.TEST.ClusterName
quota.TestCPUQuota = calcu.CoreToMillcore(resourceConfigs.TEST.CPUQuota)
quota.TestMemQuota = calcu.GibibyteToByte(resourceConfigs.TEST.MemQuota)
}
if resourceConfigs.DEV != nil {
quota.DevClusterName = resourceConfigs.DEV.ClusterName
quota.DevCPUQuota = calcu.CoreToMillcore(resourceConfigs.DEV.CPUQuota)
quota.DevMemQuota = calcu.GibibyteToByte(resourceConfigs.DEV.MemQuota)
}
}
func isQuotaChanged(oldQuota, newQuota apistructs.ProjectQuota) bool {
var changedRecord = make(map[string]bool)
isQuotaChangedOnTheWorkspace(changedRecord, oldQuota, newQuota)
return changedRecord["PROD"] || changedRecord["STAGING"] || changedRecord["TEST"] || changedRecord["DEV"]
}
func isQuotaChangedOnTheWorkspace(workspaces map[string]bool, oldQuota, newQuota apistructs.ProjectQuota) {
if workspaces == nil {
return
}
workspaces["PROD"] = oldQuota.ProdCPUQuota != newQuota.ProdCPUQuota ||
oldQuota.ProdMemQuota != newQuota.ProdMemQuota ||
oldQuota.ProdClusterName != newQuota.ProdClusterName
workspaces["STAGING"] = oldQuota.StagingCPUQuota != newQuota.StagingCPUQuota ||
oldQuota.StagingMemQuota != newQuota.StagingMemQuota ||
oldQuota.StagingClusterName != newQuota.StagingClusterName
workspaces["TEST"] = oldQuota.TestCPUQuota != newQuota.TestCPUQuota ||
oldQuota.TestMemQuota != newQuota.TestMemQuota ||
oldQuota.TestClusterName != newQuota.TestClusterName
workspaces["DEV"] = oldQuota.DevCPUQuota != newQuota.DevCPUQuota ||
oldQuota.DevMemQuota != newQuota.DevMemQuota ||
oldQuota.DevClusterName != newQuota.DevClusterName
}
func patchProject(project *model.Project, updateReq *apistructs.ProjectUpdateBody, userID uint64) error {
clusterConf, err := json.Marshal(updateReq.ClusterConfig)
if err != nil {
logrus.Errorf("failed to marshal clusterConfig, (%v)", err)
return errors.Errorf("failed to marshal clusterConfig")
}
rollbackConf, err := json.Marshal(updateReq.RollbackConfig)
if err != nil {
logrus.Errorf("failed to marshal rollbackConfig, (%v)", err)
return errors.Errorf("failed to marshal rollbackConfig")
}
if updateReq.DisplayName != "" {
project.DisplayName = updateReq.DisplayName
}
if updateReq.ResourceConfigs != nil {
project.ClusterConfig = string(clusterConf)
}
if len(updateReq.RollbackConfig) != 0 {
project.RollbackConfig = string(rollbackConf)
}
if updateReq.ResourceConfigs != nil {
if project.Quota == nil {
project.Quota = new(apistructs.ProjectQuota)
project.Quota.ProjectID = uint64(project.ID)
project.Quota.ProjectName = updateReq.Name
project.Quota.CreatorID = userID
}
setQuotaFromResourceConfig(project.Quota, updateReq.ResourceConfigs)
project.Quota.UpdaterID = userID
}
project.Desc = updateReq.Desc
project.Logo = updateReq.Logo
project.DDHook = updateReq.DdHook
project.ActiveTime = time.Now()
project.IsPublic = updateReq.IsPublic
project.CpuQuota = updateReq.CpuQuota
project.MemQuota = updateReq.MemQuota
return nil
}
func convertAuditCreateReq2Model(req apistructs.Audit) (*model.Audit, error) {
context, err := json.Marshal(req.Context)
if err != nil {
return nil, err
}
startAt, err := time.ParseInLocation("2006-01-02 15:04:05", req.StartTime, time.Local)
if err != nil {
return nil, err
}
endAt, err := time.ParseInLocation("2006-01-02 15:04:05", req.EndTime, time.Local)
if err != nil {
return nil, err
}
audit := &model.Audit{
StartTime: startAt,
EndTime: endAt,
UserID: req.UserID,
ScopeType: req.ScopeType,
ScopeID: req.ScopeID,
FDPProjectID: req.FDPProjectID,
AppID: req.AppID,
OrgID: req.OrgID,
ProjectID: req.ProjectID,
Context: string(context),
TemplateName: req.TemplateName,
AuditLevel: req.AuditLevel,
Result: req.Result,
ErrorMsg: req.ErrorMsg,
ClientIP: req.ClientIP,
UserAgent: req.UserAgent,
}
return audit, nil
}
// DeleteWithEvent 删除项目 & 发送事件
func (p *Project) DeleteWithEvent(projectID int64) error {
// 删除项目
project, err := p.Delete(projectID)
if err != nil {
return err
}
ev := &apistructs.EventCreateRequest{
EventHeader: apistructs.EventHeader{
Event: bundle.ProjectEvent,
Action: bundle.DeleteAction,
OrgID: strconv.FormatInt(project.OrgID, 10),
ProjectID: strconv.FormatInt(projectID, 10),
ApplicationID: "-1",
TimeStamp: time.Now().Format("2006-01-02 15:04:05"),
},
Sender: bundle.SenderCoreServices,
Content: *project,
}
// 发送项目删除事件
if err = p.bdl.CreateEvent(ev); err != nil {
logrus.Warnf("failed to send project delete event, (%v)", err)
}
return nil
}
// Delete 删除项目
func (p *Project) Delete(projectID int64) (*model.Project, error) {
// check if application exists
if count, err := p.db.GetApplicationCountByProjectID(projectID); err != nil || count > 0 {
return nil, errors.Errorf("failed to delete project(there exists applications)")
}
project, err := p.db.GetProjectByID(projectID)
if err != nil {
return nil, errors.Errorf("failed to get project, (%v)", err)
}
// TODO We need to turn this check on after adding the delete portal to the UI
// check if addon exists
// addOnListResp, err := p.bdl.ListAddonByProjectID(projectID, project.OrgID)
// if err != nil {
// return nil, err
// }
// if addOnListResp != nil && len(addOnListResp.Data) > 0 {
// return nil, errors.Errorf("failed to delete project(there exists addons)")
// }
if err = p.db.DeleteProject(projectID); err != nil {
return nil, errors.Errorf("failed to delete project, (%v)", err)
}
_ = p.db.DeleteProjectQutoa(projectID)
logrus.Infof("deleted project %d", projectID)
// 删除权限表记录
if err = p.db.DeleteMembersByScope(apistructs.ProjectScope, projectID); err != nil {
logrus.Warnf("failed to delete members, (%v)", err)
}
if err = p.db.DeleteMemberExtraByScope(apistructs.ProjectScope, projectID); err != nil {
logrus.Warnf("failed to delete members extra, (%v)", err)
}
return &project, nil
}
// Get 获取项目
func (p *Project) Get(ctx context.Context, projectID int64, withQuota bool) (*apistructs.ProjectDTO, error) {
project, err := p.db.GetProjectByID(projectID)
if err != nil {
return nil, errors.Wrap(err, "failed to get project")
}
projectDTO := p.convertToProjectDTO(true, &project)
owners, err := p.db.GetMemberByScopeAndRole(apistructs.ProjectScope, []uint64{uint64(projectID)}, []string{"owner"})
if err != nil {
return nil, err
}
for _, v := range owners {
projectDTO.Owners = append(projectDTO.Owners, v.UserID)
}
if withQuota {
// 查询项目 quota
p.fetchQuota(&projectDTO)
// 查询项目下的 pod 的 request 数据
p.fetchPodInfo(&projectDTO)
// 根据已有统计值计算比率
p.calcuRequestRate(&projectDTO)
}
return &projectDTO, nil
}
func (p *Project) fetchQuota(dto *apistructs.ProjectDTO) {
defaultResourceConfig(dto)
var projectQuota apistructs.ProjectQuota
if err := p.db.First(&projectQuota, map[string]interface{}{"project_id": dto.ID}).Error; err != nil {
logrus.WithError(err).WithField("project_id", dto.ID).
Warnln("failed to select the quota record of the project")
return
}
setProjectDtoQuotaFromModel(dto, &projectQuota)
}
func defaultResourceConfig(dto *apistructs.ProjectDTO) {
if dto == nil || dto.ClusterConfig == nil {
return
}
var (
prodCluster, hasProdCluster = dto.ClusterConfig["PROD"]
stagingCluster, hasStagingCluster = dto.ClusterConfig["STAGING"]
testCluster, hasTestCluster = dto.ClusterConfig["TEST"]
devCluster, hasDevCluster = dto.ClusterConfig["DEV"]
)
if hasProdCluster && hasStagingCluster && hasTestCluster && hasDevCluster {
dto.ResourceConfig = apistructs.NewResourceConfig()
dto.ResourceConfig.PROD.ClusterName = prodCluster
dto.ResourceConfig.STAGING.ClusterName = stagingCluster
dto.ResourceConfig.TEST.ClusterName = testCluster
dto.ResourceConfig.DEV.ClusterName = devCluster
return
}
if !hasProdCluster && !hasStagingCluster && !hasTestCluster && !hasDevCluster {
return
}
logrus.Warnf("the config of cluster must be all empty or all not empty: prod: %s, staging: %s, test: %s, dev: %s",
prodCluster, stagingCluster, testCluster, devCluster)
}
func setProjectDtoQuotaFromModel(dto *apistructs.ProjectDTO, quota *apistructs.ProjectQuota) {
if dto == nil || quota == nil {
return
}
dto.ClusterConfig = make(map[string]string)
dto.ResourceConfig = apistructs.NewResourceConfig()
dto.ClusterConfig["PROD"] = quota.ProdClusterName
dto.ClusterConfig["STAGING"] = quota.StagingClusterName
dto.ClusterConfig["TEST"] = quota.TestClusterName
dto.ClusterConfig["DEV"] = quota.DevClusterName
dto.ResourceConfig.PROD.ClusterName = quota.ProdClusterName
dto.ResourceConfig.STAGING.ClusterName = quota.StagingClusterName
dto.ResourceConfig.TEST.ClusterName = quota.TestClusterName
dto.ResourceConfig.DEV.ClusterName = quota.DevClusterName
dto.ResourceConfig.PROD.CPUQuota = calcu.MillcoreToCore(quota.ProdCPUQuota, 3)
dto.ResourceConfig.STAGING.CPUQuota = calcu.MillcoreToCore(quota.StagingCPUQuota, 3)
dto.ResourceConfig.TEST.CPUQuota = calcu.MillcoreToCore(quota.TestCPUQuota, 3)
dto.ResourceConfig.DEV.CPUQuota = calcu.MillcoreToCore(quota.DevCPUQuota, 3)
dto.ResourceConfig.PROD.MemQuota = calcu.ByteToGibibyte(quota.ProdMemQuota, 3)
dto.ResourceConfig.STAGING.MemQuota = calcu.ByteToGibibyte(quota.StagingMemQuota, 3)
dto.ResourceConfig.TEST.MemQuota = calcu.ByteToGibibyte(quota.TestMemQuota, 3)
dto.ResourceConfig.DEV.MemQuota = calcu.ByteToGibibyte(quota.DevMemQuota, 3)
dto.CpuQuota = calcu.MillcoreToCore(quota.ProdCPUQuota+quota.StagingCPUQuota+quota.TestCPUQuota+quota.DevCPUQuota, 3)
dto.MemQuota = calcu.ByteToGibibyte(quota.ProdMemQuota+quota.StagingMemQuota+quota.TestMemQuota+quota.DevMemQuota, 3)
}
// 从 s_pod_info 中读取 cpu/mem_request 数据记录到 dto
func (p *Project) fetchPodInfo(dto *apistructs.ProjectDTO) {
if dto == nil || dto.ResourceConfig == nil {
return
}
var podInfos []apistructs.PodInfo
if err := p.db.Find(&podInfos, map[string]interface{}{"project_id": dto.ID, "phase": "running"}).Error; err != nil {
logrus.WithError(err).WithField("project_id", dto.ID).
Warnln("failed to Find the namespaces info in the project")
return
}
for workspace, rc := range map[string]*apistructs.ResourceConfigInfo{
"prod": dto.ResourceConfig.PROD,
"staging": dto.ResourceConfig.STAGING,
"test": dto.ResourceConfig.TEST,
"dev": dto.ResourceConfig.DEV,
} {
if rc == nil {
continue
}
for _, podInfo := range podInfos {
if !strings.EqualFold(podInfo.Workspace, workspace) {
continue
}
if podInfo.Cluster != rc.ClusterName {
continue
}
rc.CPURequest += podInfo.CPURequest
rc.MemRequest += podInfo.MemRequest / 1024
switch podInfo.ServiceType {
case "addon":
rc.CPURequestByAddon += podInfo.CPURequest
rc.MemRequestByAddon += podInfo.MemRequest / 1024
case "stateless-service":
rc.CPURequestByService += podInfo.CPURequest
rc.MemRequestByService += podInfo.MemRequest / 1024
}
}
rc.CPURequest = calcu.Accuracy(rc.CPURequest, 3)
rc.CPURequestByAddon = calcu.Accuracy(rc.CPURequestByAddon, 3)
rc.CPURequestByService = calcu.Accuracy(rc.CPURequestByService, 3)
rc.MemRequest = calcu.Accuracy(rc.MemRequest, 3)
rc.MemRequestByAddon = calcu.Accuracy(rc.MemRequestByAddon, 3)
rc.MemRequestByService = calcu.Accuracy(rc.MemRequestByService, 3)
}
}
// 根据已有统计值计算比率
func (p *Project) calcuRequestRate(dto *apistructs.ProjectDTO) {
if dto == nil || dto.ResourceConfig == nil {
return
}
for _, rc := range []*apistructs.ResourceConfigInfo{
dto.ResourceConfig.PROD,
dto.ResourceConfig.STAGING,
dto.ResourceConfig.TEST,
dto.ResourceConfig.DEV,
} {
if rc == nil {
continue
}
if rc.CPUQuota != 0 {
rc.CPURequestRate = calcu.Accuracy(rc.CPURequest/rc.CPUQuota*100, 2)
rc.CPURequestByAddonRate = calcu.Accuracy(rc.CPURequestByAddon/rc.CPUQuota*100, 2)
rc.CPURequestByServiceRate = calcu.Accuracy(rc.CPURequestByService/rc.CPUQuota*100, 2)
}
if rc.MemQuota != 0 {
rc.MemRequestRate = calcu.Accuracy(rc.MemRequest/rc.MemQuota*100, 2)
rc.MemRequestByAddonRate = calcu.Accuracy(rc.MemRequestByAddon/rc.MemQuota*100, 2)
rc.MemRequestByServiceRate = calcu.Accuracy(rc.MemRequestByService/rc.MemQuota*100, 2)
}
}
}
// GetModelProject 获取项目
func (p *Project) GetModelProject(projectID int64) (*model.Project, error) {
project, err := p.db.GetProjectByID(projectID)
if err != nil {
return nil, errors.Wrap(err, "failed to get project")
}
return &project, nil
}
func (p *Project) GetModelProjectsMap(projectIDs []uint64) (map[int64]*model.Project, error) {
_, projects, err := p.db.GetProjectsByIDs(projectIDs, &apistructs.ProjectListRequest{
PageNo: 1,
PageSize: len(projectIDs),
})
if err != nil {
return nil, errors.Errorf("failed to get projects, (%v)", err)
}
projectMap := make(map[int64]*model.Project)
for i, p := range projects {
projectMap[p.ID] = &projects[i]
}
return projectMap, nil
}
// FillQuota 根据项目资源使用情况填充项目资源配额
func (p *Project) FillQuota(orgResources map[uint64]apistructs.OrgResourceInfo) error {
for k, v := range orgResources {
projects, err := p.db.ListProjectByOrgID(k)
if err != nil {
return err
}
// 获取当前企业下各项目已使用资源
projectIDs := make([]uint64, 0, len(projects))
for _, proj := range projects {
projectIDs = append(projectIDs, uint64(proj.ID))
}
resp, err := p.bdl.ProjectResource(projectIDs)
if err != nil {
return err
}
// 企业资源使用
var (
orgCpuUsed float64
orgMemUsed float64
)
projectCpuUsed := make(map[uint64]float64, len(projects))
projectMemUsed := make(map[uint64]float64, len(projects))
for pk, pv := range resp.Data {
projectCpuUsed[pk] = pv.CpuServiceUsed + pv.CpuAddonUsed
projectMemUsed[pk] = pv.MemServiceUsed + pv.MemAddonUsed
orgCpuUsed += projectCpuUsed[pk]
orgMemUsed += projectMemUsed[pk]
}
for i, proj := range projects {
// 修正已有项目无配额情况
if math.Round(proj.CpuQuota) == 0 {
projectCpuQuota := projectCpuUsed[uint64(proj.ID)] + projectCpuUsed[uint64(proj.ID)]*(v.TotalCpu-orgCpuUsed)/orgCpuUsed
projects[i].CpuQuota = numeral.Round(projectCpuQuota, 2)
}
if math.Round(proj.MemQuota) == 0 {
projectMemQuota := projectMemUsed[uint64(proj.ID)] + projectMemUsed[uint64(proj.ID)]*(v.TotalMem-orgMemUsed)/orgMemUsed
projects[i].MemQuota = numeral.Round(projectMemQuota, 2)
}
if err := p.db.UpdateProject(&projects[i]); err != nil {
return err
}
}
}
return nil
}
// GetAllProjects list all project
func (p *Project) GetAllProjects() ([]apistructs.ProjectDTO, error) {
projects, err := p.db.GetAllProjects()
if err != nil {
return nil, err
}
projectsDTO := make([]apistructs.ProjectDTO, 0, len(projects))
for _, v := range projects {
projectsDTO = append(projectsDTO, p.convertToProjectDTO(true, &v))
}
return projectsDTO, nil
}
// ListAllProjects 企业管理员可查看当前企业下所有项目,包括未加入的项目
func (p *Project) ListAllProjects(userID string, params *apistructs.ProjectListRequest) (
*apistructs.PagingProjectDTO, error) {
total, projects, err := p.db.GetProjectsByOrgIDAndName(int64(params.OrgID), params)
if err != nil {
return nil, errors.Errorf("failed to get projects, (%v)", err)
}
members, err := p.db.GetMembersByScopeTypeAndUser(apistructs.ProjectScope, userID)
if err != nil {
return nil, errors.Errorf("failed to get projects, (%v)", err)
}
// 转换成所需格式
projectDTOs := make([]apistructs.ProjectDTO, 0, len(projects))
projectIDs := make([]uint64, 0, len(projects))
for i := range projects {
// 找出企业管理员已加入的项目
flag := params.Joined
for j := range members {
if projects[i].ID == members[j].ScopeID {
flag = true
}
}
projectDTOs = append(projectDTOs, p.convertToProjectDTO(flag, &projects[i]))
projectIDs = append(projectIDs, uint64(projects[i].ID))
}
resp, err := p.bdl.ProjectResource(projectIDs)
if err != nil {
return nil, err
}
projectOwnerMap := make(map[uint64][]string)
owners, err := p.db.GetMemberByScopeAndRole(apistructs.ProjectScope, projectIDs, []string{types.RoleProjectOwner})
if err != nil {
return nil, err
}
for _, v := range owners {
projectID := uint64(v.ScopeID)
projectOwnerMap[projectID] = append(projectOwnerMap[projectID], v.UserID)
}
for i := range projectDTOs {
projectDTOs[i].CpuQuota = calcu.MillcoreToCore(uint64(projectDTOs[i].CpuQuota), 3)
projectDTOs[i].MemQuota = calcu.ByteToGibibyte(uint64(projectDTOs[i].MemQuota), 3)
if v, ok := resp.Data[projectDTOs[i].ID]; ok {
projectDTOs[i].CpuServiceUsed = v.CpuServiceUsed
projectDTOs[i].MemServiceUsed = v.MemServiceUsed
projectDTOs[i].CpuAddonUsed = v.CpuAddonUsed
projectDTOs[i].MemAddonUsed = v.MemAddonUsed
}
if v, ok := projectOwnerMap[projectDTOs[i].ID]; ok {
projectDTOs[i].Owners = v
}
}
return &apistructs.PagingProjectDTO{Total: total, List: projectDTOs}, nil
}
// ListPublicProjects 获取公开项目列表
func (p *Project) ListPublicProjects(userID string, params *apistructs.ProjectListRequest) (
*apistructs.PagingProjectDTO, error) {
// 查找有权限的列表
members, err := p.db.GetMembersByParentID(apistructs.ProjectScope, int64(params.OrgID), userID)
if err != nil {
return nil, errors.Errorf("failed to get permission when get projects, (%v)", err)
}
projectIDs := make([]uint64, 0, len(members))
isManager := map[uint64]bool{} // 是否有管理权限
isJoined := map[uint64]bool{} // 是否加入了项目
for i := range members {
if members[i].ResourceKey == apistructs.RoleResourceKey {