Skip to content

Commit

Permalink
add init job (#4629)
Browse files Browse the repository at this point in the history
* fix init job

* fix init job

* fix init job

* fix init job

* fix
  • Loading branch information
bxy4543 authored Mar 27, 2024
1 parent b2beb0a commit 8d6e23f
Show file tree
Hide file tree
Showing 7 changed files with 96 additions and 21 deletions.
7 changes: 1 addition & 6 deletions controllers/account/api/v1/debt_webhook.go
Original file line number Diff line number Diff line change
Expand Up @@ -148,15 +148,10 @@ func (d *DebtValidate) checkOption(ctx context.Context, logger logr.Logger, c cl
return admission.ValidationResponse(false, fmt.Sprintf("this namespace is not user namespace %s,or have not create", ns.Name))
}
logger.V(1).Info("check user namespace", "ns", ns.Name, "user", user)
accountList := AccountList{}
if err := c.List(ctx, &accountList, client.MatchingFields{Name: user}); err != nil {
logger.Error(err, "get account error", "user", user)
return admission.ValidationResponse(true, err.Error())
}
account, err := d.AccountV2.GetAccount(&pkgtype.UserQueryOpts{Owner: user})
if err != nil {
logger.Error(err, "get account error", "user", user)
return admission.ValidationResponse(false, err.Error())
return admission.ValidationResponse(true, err.Error())
}
if account.Balance < account.DeductionBalance {
return admission.ValidationResponse(false, fmt.Sprintf(code.MessageFormat, code.InsufficientBalance, fmt.Sprintf("account balance less than 0,now account is %.2f¥. Please recharge the user %s.", GetAccountDebtBalance(*account), user)))
Expand Down
2 changes: 1 addition & 1 deletion controllers/account/controllers/debt_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ func (r *DebtReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.
}
}
r.Logger.Error(fmt.Errorf("account %s not exist", owner), "account not exist")
return ctrl.Result{RequeueAfter: 60 * time.Minute}, nil
return ctrl.Result{RequeueAfter: 10 * time.Minute}, nil
}
// In a multi-region scenario, select the region where the account is created for SMS notification
smsEnable := account.CreateRegionID == r.LocalRegionID
Expand Down
10 changes: 6 additions & 4 deletions controllers/job/init/internal/util/database/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,13 @@ const (
)

const (
EnvAdminUserName = "ADMIN_USER_NAME"
EnvAdminPassword = "ADMIN_PASSWORD"
EnvAdminUserName = "ADMIN_USER_NAME"
EnvAdminPassword = "ADMIN_PASSWORD"
EnvWorkspacePrefix = "WORKSPACE_PREFIX"
)

var (
adminPassword = hashPassword(env.GetEnvWithDefault(EnvAdminPassword, DefaultAdminPassword))
adminUserName = env.GetEnvWithDefault(EnvAdminUserName, DefaultAdminUserName)
adminPassword = hashPassword(env.GetEnvWithDefault(EnvAdminPassword, DefaultAdminPassword))
adminUserName = env.GetEnvWithDefault(EnvAdminUserName, DefaultAdminUserName)
workspacePrefix = env.GetEnvWithDefault(EnvWorkspacePrefix, "ns-")
)
19 changes: 18 additions & 1 deletion controllers/job/init/internal/util/database/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,14 +67,15 @@ func PresetAdminUser() error {
Domain: domain,
DisplayName: domain,
Location: domain,
Description: domain,
}); err != nil {
return fmt.Errorf("failed to create region: %v", err)
}

userNanoID, err := gonanoid.New(10)
if err != nil {
return fmt.Errorf("failed to generate nano id: %v", err)
}
genUserCrUID, genWorkspaceUID := uuid.New(), uuid.New()
if err = v2Account.CreateUser(&types.OauthProvider{
UserUID: common.AdminUID(),
ProviderType: types.OauthProviderTypePassword,
Expand All @@ -83,6 +84,7 @@ func PresetAdminUser() error {
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
}, &types.RegionUserCr{
UID: genUserCrUID,
CrName: adminUserName,
UserUID: common.AdminUID(),
CreatedAt: time.Now(),
Expand All @@ -94,6 +96,21 @@ func PresetAdminUser() error {
Nickname: userNanoID,
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
}, &types.Workspace{
UID: genWorkspaceUID,
ID: workspacePrefix + adminUserName,
DisplayName: "private team",
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
}, &types.UserWorkspace{
WorkspaceUID: genWorkspaceUID,
UserCrUID: genUserCrUID,
Role: types.RoleOwner,
Status: types.JoinStatusInWorkspace,
IsPrivate: true,
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
JoinAt: time.Now(),
}); err != nil {
return fmt.Errorf("failed to create user: %v", err)
}
Expand Down
32 changes: 27 additions & 5 deletions controllers/pkg/database/cockroach/accountv2.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,18 +51,40 @@ const (
EnvBaseBalance = "BASE_BALANCE"
)

func (g *Cockroach) CreateUser(oAuth *types.OauthProvider, regionUserCr *types.RegionUserCr, user *types.User) error {
if g.Localdb.Where(&types.RegionUserCr{CrName: regionUserCr.CrName}).First(&types.RegionUserCr{}).Error == gorm.ErrRecordNotFound {
if err := g.DB.Where(&types.User{Name: user.Name}).FirstOrCreate(user).Error; err != nil {
func (g *Cockroach) CreateUser(oAuth *types.OauthProvider, regionUserCr *types.RegionUserCr, user *types.User, workspace *types.Workspace, userWorkspace *types.UserWorkspace) error {
findUser, findRegionUserCr, findUserWorkspace := &types.User{}, &types.RegionUserCr{}, &types.UserWorkspace{}
if g.DB.Where(&types.User{Name: user.Name}).First(findUser).Error == gorm.ErrRecordNotFound {
findUser = user
if err := g.DB.Save(user).Error; err != nil {
return fmt.Errorf("failed to create user: %w", err)
}
if err := g.DB.Where(types.OauthProvider{ProviderID: oAuth.ProviderID}).FirstOrCreate(oAuth).Error; err != nil {
}
if g.DB.Where(types.OauthProvider{UserUID: findUser.UID}).First(&types.OauthProvider{}).Error == gorm.ErrRecordNotFound {
oAuth.UserUID = findUser.UID
if err := g.DB.Save(oAuth).Error; err != nil {
return fmt.Errorf("failed to create user oauth provider: %w", err)
}
if err := g.Localdb.Where(types.RegionUserCr{CrName: regionUserCr.CrName}).FirstOrCreate(&regionUserCr).Error; err != nil {
}
if g.Localdb.Where(&types.RegionUserCr{CrName: regionUserCr.CrName}).First(findRegionUserCr).Error == gorm.ErrRecordNotFound {
regionUserCr.UserUID = findUser.UID
findRegionUserCr = regionUserCr
if err := g.Localdb.Save(regionUserCr).Error; err != nil {
return fmt.Errorf("failed to create user region cr: %w", err)
}
}
if g.Localdb.Where(types.UserWorkspace{UserCrUID: findRegionUserCr.UID}).First(findUserWorkspace).Error == gorm.ErrRecordNotFound {
userWorkspace.UserCrUID = findRegionUserCr.UID
findUserWorkspace = userWorkspace
if err := g.Localdb.Save(userWorkspace).Error; err != nil {
return fmt.Errorf("failed to create user workspace: %w", err)
}
}
if g.Localdb.Where(types.Workspace{UID: findUserWorkspace.WorkspaceUID}).First(&types.Workspace{}).Error == gorm.ErrRecordNotFound {
workspace.UID = findUserWorkspace.WorkspaceUID
if err := g.Localdb.Save(workspace).Error; err != nil {
return fmt.Errorf("failed to create workspace: %w", err)
}
}
return nil
}

Expand Down
2 changes: 1 addition & 1 deletion controllers/pkg/database/interface.go
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ type Traffic interface {
type AccountV2 interface {
Close() error
GetUserCr(user *types.UserQueryOpts) (*types.RegionUserCr, error)
CreateUser(oAuth *types.OauthProvider, regionUserCr *types.RegionUserCr, user *types.User) error
CreateUser(oAuth *types.OauthProvider, regionUserCr *types.RegionUserCr, user *types.User, workspace *types.Workspace, userWorkspace *types.UserWorkspace) error
GetAccount(user *types.UserQueryOpts) (*types.Account, error)
GetUserOauthProvider(ops *types.UserQueryOpts) (*types.OauthProvider, error)
AddBalance(user *types.UserQueryOpts, balance int64) error
Expand Down
45 changes: 42 additions & 3 deletions controllers/pkg/types/global.go
Original file line number Diff line number Diff line change
Expand Up @@ -89,15 +89,54 @@ func (User) TableName() string {
return "User"
}

type OauthProviderType string
type Workspace struct {
UID uuid.UUID `gorm:"type:uuid;default:gen_random_uuid();primary_key"`
ID string `gorm:"type:text;not null;unique"`
DisplayName string `gorm:"column:displayName;type:text;not null"`
CreatedAt time.Time `gorm:"column:createdAt;type:timestamp(3) with time zone;default:current_timestamp()"`
UpdatedAt time.Time `gorm:"column:updatedAt;type:timestamp(3) with time zone;default:current_timestamp()"`
}

type UserWorkspace struct {
UID uuid.UUID `gorm:"type:uuid;default:gen_random_uuid();primary_key"`
CreatedAt time.Time `gorm:"column:createdAt;type:timestamp(3) with time zone;default:current_timestamp()"`
UpdatedAt time.Time `gorm:"column:updatedAt;type:timestamp(3) with time zone;default:current_timestamp()"`
WorkspaceUID uuid.UUID `gorm:"column:workspaceUid;type:uuid;not null"`
UserCrUID uuid.UUID `gorm:"column:userCrUid;type:uuid;not null"`
HandlerUID uuid.UUID `gorm:"column:handlerUid;type:uuid"`
Role Role `gorm:"type:Role;default:'DEVELOPER'::defaultdb.public.'Role';not null"`
Status JoinStatus
IsPrivate bool `gorm:"column:isPrivate;type:boolean;not null"`
JoinAt time.Time `gorm:"column:joinAt;type:timestamp(3) with time zone"`
}

type (
Role string
JoinStatus string
OauthProviderType string
)

const (
OauthProviderTypePhone OauthProviderType = "PHONE"
OauthProviderTypeGithub OauthProviderType = "GITHUB"
OauthProviderTypeWechat OauthProviderType = "WECHAT"
OauthProviderTypePassword OauthProviderType = "PASSWORD"
//OauthProviderTypeGithub OauthProviderType = "GITHUB"
//OauthProviderTypeWechat OauthProviderType = "WECHAT"

RoleOwner Role = "OWNER"
//RoleDeveloper Role = "DEVELOPER"
//RoleManager Role = "MANAGER"

JoinStatusInWorkspace JoinStatus = "IN_WORKSPACE"
)

func (UserWorkspace) TableName() string {
return "UserWorkspace"
}

func (Workspace) TableName() string {
return "Workspace"
}

func (OauthProvider) TableName() string {
return "OauthProvider"
}
Expand Down

0 comments on commit 8d6e23f

Please sign in to comment.