Skip to content

Commit 4e70494

Browse files
authored
optimize sendFlushQuotaRequest log & fix create or update quota (#5609)
* optimize sendFlushQuotaRequest log & fix create or update quota * optimize: user remove the watching AnnotationChangedPredicate * optimize initialize the account data
1 parent 563ce80 commit 4e70494

File tree

5 files changed

+51
-27
lines changed

5 files changed

+51
-27
lines changed

controllers/account/controllers/account_controller.go

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,8 @@ const (
101101
EnvSubscriptionEnabled = "SUBSCRIPTION_ENABLED"
102102
EnvJwtSecret = "ACCOUNT_API_JWT_SECRET"
103103
EnvDesktopJwtSecret = "DESKTOP_API_JWT_SECRET"
104+
105+
InitAccountTimeAnnotation = "user.sealos.io/init-account-time"
104106
)
105107

106108
var SubscriptionEnabled = false
@@ -144,13 +146,20 @@ func (r *AccountReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ct
144146
if owner = user.Annotations[userv1.UserAnnotationOwnerKey]; owner == "" {
145147
return ctrl.Result{}, fmt.Errorf("user owner is empty")
146148
}
149+
if user.Annotations[InitAccountTimeAnnotation] != "" {
150+
return ctrl.Result{}, nil
151+
}
147152
// This is only used to monitor and initialize user resource creation data,
148153
// determine the resource quota created by the owner user and the resource quota initialized by the account user,
149154
// and only the resource quota created by the team user
150155
_, err = r.syncAccount(ctx, owner, "ns-"+user.Name)
151156
if errors.Is(err, gorm.ErrRecordNotFound) && user.CreationTimestamp.Add(r.SkipExpiredUserTimeDuration).Before(time.Now()) {
152157
return ctrl.Result{}, nil
153158
}
159+
if err == nil {
160+
user.Annotations[InitAccountTimeAnnotation] = time.Now().Format(time.RFC3339)
161+
return ctrl.Result{}, r.Update(ctx, user)
162+
}
154163
return ctrl.Result{}, err
155164
} else if client.IgnoreNotFound(err) != nil {
156165
return ctrl.Result{}, err
@@ -181,7 +190,8 @@ func (r *AccountReconciler) syncAccount(ctx context.Context, owner string, userN
181190
}
182191
}
183192
if err = r.SyncNSQuotaFunc(ctx, owner, userNamespace); err != nil {
184-
r.Logger.Error(err, "sync resource resourceQuota and limitRange failed")
193+
//r.Logger.Error(err, "sync resource resourceQuota and limitRange failed")
194+
return nil, fmt.Errorf("sync resource resourceQuota and limitRange failed: %v", err)
185195
}
186196
return
187197
}

controllers/account/controllers/subscription.go

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -238,7 +238,12 @@ func (sp *SubscriptionProcessor) sendFlushQuotaRequest(userUID, planID uuid.UUID
238238
lastErr = nil
239239
break
240240
}
241-
lastErr = fmt.Errorf("unexpected status code: %d", resp.StatusCode)
241+
body, err := io.ReadAll(resp.Body)
242+
if err != nil {
243+
lastErr = fmt.Errorf("unexpected status code: %d, failed to read response body: %w", resp.StatusCode, err)
244+
} else {
245+
lastErr = fmt.Errorf("unexpected status code: %d, response body: %s", resp.StatusCode, string(body))
246+
}
242247
}
243248

244249
// 进行重试

controllers/pkg/database/cockroach/accountv2.go

Lines changed: 27 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1496,27 +1496,6 @@ func (c *Cockroach) NewAccountWithFreeSubscriptionPlan(ops *types.UserQueryOpts)
14961496
}
14971497
ops.UID = userUID
14981498
}
1499-
freePlan, err := c.GetSubscriptionPlan(types.FreeSubscriptionPlanName)
1500-
if err != nil {
1501-
return nil, fmt.Errorf("failed to get free plan: %w", err)
1502-
}
1503-
userInfo := &types.UserInfo{}
1504-
err = c.DB.Model(&types.UserInfo{}).Where(`"userUid" = ?`, ops.UID).Find(userInfo).Error
1505-
if err != nil && err != gorm.ErrRecordNotFound {
1506-
return nil, fmt.Errorf("failed to get user info: %w", err)
1507-
}
1508-
githubDetection := true
1509-
if userInfo.Config != nil {
1510-
if userInfo.Config.Github.CreatedAt != "" {
1511-
createdAt, err := time.Parse(time.RFC3339, userInfo.Config.Github.CreatedAt)
1512-
if err != nil {
1513-
return nil, fmt.Errorf("failed to parse github created at: %w", err)
1514-
}
1515-
if time.Since(createdAt) < 7*24*time.Hour {
1516-
githubDetection = false
1517-
}
1518-
}
1519-
}
15201499
now := time.Now().UTC()
15211500
account := &types.Account{
15221501
UserUID: ops.UID,
@@ -1530,10 +1509,35 @@ func (c *Cockroach) NewAccountWithFreeSubscriptionPlan(ops *types.UserQueryOpts)
15301509
// 1. create credits
15311510
// 2. create account
15321511
// 3. create subscription
1533-
err = c.DB.Transaction(func(tx *gorm.DB) error {
1534-
if err := tx.Where(&types.Account{UserUID: ops.UID}).FirstOrCreate(account).Error; err != nil {
1512+
err := c.DB.Transaction(func(tx *gorm.DB) error {
1513+
result := tx.Where(&types.Account{UserUID: ops.UID}).FirstOrCreate(account)
1514+
if err := result.Error; err != nil {
15351515
return fmt.Errorf("failed to create account: %w", err)
15361516
}
1517+
if result.RowsAffected == 0 {
1518+
return nil
1519+
}
1520+
freePlan, err := c.GetSubscriptionPlan(types.FreeSubscriptionPlanName)
1521+
if err != nil {
1522+
return fmt.Errorf("failed to get free plan: %w", err)
1523+
}
1524+
userInfo := &types.UserInfo{}
1525+
err = c.DB.Model(&types.UserInfo{}).Where(`"userUid" = ?`, ops.UID).Find(userInfo).Error
1526+
if err != nil && err != gorm.ErrRecordNotFound {
1527+
return fmt.Errorf("failed to get user info: %w", err)
1528+
}
1529+
githubDetection := true
1530+
if userInfo.Config != nil {
1531+
if userInfo.Config.Github.CreatedAt != "" {
1532+
createdAt, err := time.Parse(time.RFC3339, userInfo.Config.Github.CreatedAt)
1533+
if err != nil {
1534+
return fmt.Errorf("failed to parse github created at: %w", err)
1535+
}
1536+
if time.Since(createdAt) < 7*24*time.Hour {
1537+
githubDetection = false
1538+
}
1539+
}
1540+
}
15371541
if freePlan.GiftAmount > 0 && githubDetection {
15381542
credits := &types.Credits{
15391543
ID: uuid.New(),

controllers/user/controllers/user_controller.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -157,7 +157,7 @@ func (r *UserReconciler) SetupWithManager(mgr ctrl.Manager, opts ratelimiter.Rat
157157
ownerEventHandler := handler.EnqueueRequestForOwner(r.Scheme, r.Client.RESTMapper(), &userv1.User{}, handler.OnlyControllerOwner())
158158

159159
return ctrl.NewControllerManagedBy(mgr).
160-
For(&userv1.User{}, builder.WithPredicates(predicate.Or(predicate.GenerationChangedPredicate{}, predicate.AnnotationChangedPredicate{}))).
160+
For(&userv1.User{}, builder.WithPredicates(predicate.Or(predicate.GenerationChangedPredicate{}))).
161161
Watches(&rbacv1.Role{}, ownerEventHandler).
162162
Watches(&rbacv1.RoleBinding{}, ownerEventHandler).
163163
Watches(&v1.Secret{}, ownerEventHandler).

service/account/api/flush.go

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -290,7 +290,12 @@ func AdminFlushSubscriptionQuota(c *gin.Context) {
290290
}
291291
for _, ns := range nsList {
292292
quota := getDefaultResourceQuota(ns, "quota-"+ns, rs)
293-
if err = dao.K8sManager.GetClient().Update(context.Background(), quota); err != nil {
293+
hard := quota.Spec.Hard.DeepCopy()
294+
_, err = controllerutil.CreateOrUpdate(context.Background(), dao.K8sManager.GetClient(), quota, func() error {
295+
quota.Spec.Hard = hard
296+
return nil
297+
})
298+
if err != nil {
294299
c.JSON(http.StatusInternalServerError, helper.ErrorMessage{Error: fmt.Sprintf("update resource quota failed: %v", err)})
295300
return
296301
}

0 commit comments

Comments
 (0)