Skip to content

Commit

Permalink
adapt cockroachdb for license & init job
Browse files Browse the repository at this point in the history
  • Loading branch information
bxy4543 committed Mar 15, 2024
1 parent b52d0cc commit ae252be
Show file tree
Hide file tree
Showing 12 changed files with 73 additions and 201 deletions.
7 changes: 4 additions & 3 deletions controllers/job/init/cmd/preset/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,10 @@ import (
"errors"
"os"

"gorm.io/gorm"

"github.com/labring/sealos/controllers/job/init/internal/util/controller"
"github.com/labring/sealos/controllers/job/init/internal/util/database"
utilserror "github.com/labring/sealos/controllers/job/init/internal/util/errors"
"github.com/labring/sealos/controllers/pkg/utils/logger"
)

Expand All @@ -34,8 +35,8 @@ func main() {
}
logger.Info("preset admin user in kubernetes successfully")

if err := database.PresetAdminUser(ctx); err != nil {
if errors.Is(err, utilserror.ErrAdminExists) {
if err := database.PresetAdminUser(); err != nil {
if errors.Is(err, gorm.ErrDuplicatedKey) {
logger.Info("admin user already exists in database")
} else {
logger.Error(err, "preset admin user in database failed")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,52 +12,28 @@
# See the License for the specific language governing permissions and
# limitations under the License.

apiVersion: v1
kind: ServiceAccount
metadata:
name: sealos-job-init-sa
namespace: sealos
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: sealos-job-init-user-editor-role-binding
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: user-editor-role
subjects:
- kind: ServiceAccount
name: sealos-job-init-sa
namespace: sealos
---
apiVersion: batch/v1
kind: Job
metadata:
name: init-job
namespace: sealos
namespace: account-system
spec:
ttlSecondsAfterFinished: 86400
template:
spec:
serviceAccountName: sealos-job-init-sa
serviceAccountName: account-controller-manager
securityContext:
runAsNonRoot: true
containers:
- name: job-init
image: ghcr.io/labring/sealos-job-init-controller:latest
# get env from desktop-frontend-secret
env:
- name: MONGO_URI
valueFrom:
secretKeyRef:
name: desktop-frontend-secret
key: mongodb_uri
- name: PASSWORD_SALT
valueFrom:
secretKeyRef:
name: desktop-frontend-secret
key: password_salt
value: {{ .PASSWORD_SALT }}
envFrom:
- configMapRef:
name: account-manager-env
securityContext:
allowPrivilegeEscalation: false
capabilities:
Expand Down
8 changes: 4 additions & 4 deletions controllers/job/init/internal/util/common/uuid.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,11 @@ package common

import "github.com/google/uuid"

var adminUID string
var adminUID uuid.UUID

func AdminUID() string {
if adminUID == "" {
adminUID = uuid.New().String()
func AdminUID() uuid.UUID {
if adminUID == uuid.Nil {
adminUID = uuid.New()
}
return adminUID
}
4 changes: 2 additions & 2 deletions controllers/job/init/internal/util/controller/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,9 +57,9 @@ func newAdminUser(ctx context.Context, c client.Client) (*userv1.User, error) {
return nil, err
}
if u.Labels == nil {
u.SetLabels(map[string]string{"uid": common.AdminUID(), "updateTime": "T2301-01T00-00-00"})
u.SetLabels(map[string]string{"uid": common.AdminUID().String(), "updateTime": "T2301-01T00-00-00"})
} else if u.Labels["uid"] == "" {
u.Labels["uid"] = common.AdminUID()
u.Labels["uid"] = common.AdminUID().String()
u.Labels["updateTime"] = "T2301-01T00-00-00"
}
return u, nil
Expand Down
55 changes: 0 additions & 55 deletions controllers/job/init/internal/util/database/database.go

This file was deleted.

41 changes: 10 additions & 31 deletions controllers/job/init/internal/util/database/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,41 +15,20 @@
package database

import (
"context"
"errors"

"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"github.com/labring/sealos/controllers/pkg/utils/env"
)

// User struct in mongoDB.
type User struct {
UID string `bson:"uid" json:"uid"`
Name string `bson:"name" json:"name"`
PasswordUser string `bson:"password_user" json:"password_user"`
Password string `bson:"password" json:"password"`
CreatedTime string `bson:"created_time" json:"created_time"`
K8sUsers []K8sUser `bson:"k8s_users" json:"k8s_users"`
}

type K8sUser struct {
Name string `bson:"name" json:"name"`
}

const (
DefaultAdminUserName = "admin"
DefaultAdminPassword = "sealos2023"
)

func (u *User) Exist(ctx context.Context, collection *mongo.Collection) (bool, error) {
filter := &bson.M{"password_user": u.PasswordUser}
user := &User{}
err := collection.FindOne(ctx, filter).Decode(user)
if err != nil {
if errors.Is(err, mongo.ErrNoDocuments) {
return false, nil
}
return false, err
}
return true, nil
}
const (
EnvAdminUserName = "ADMIN_USER_NAME"
EnvAdminPassword = "ADMIN_PASSWORD"
)

var (
adminPassword = hashPassword(env.GetEnvWithDefault(EnvAdminPassword, DefaultAdminPassword))
adminUserName = env.GetEnvWithDefault(EnvAdminUserName, DefaultAdminUserName)
)
84 changes: 29 additions & 55 deletions controllers/job/init/internal/util/database/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,75 +15,49 @@
package database

import (
"context"
"fmt"
"time"
"os"

"github.com/labring/sealos/controllers/job/init/internal/util/common"
"github.com/labring/sealos/controllers/job/init/internal/util/controller"
"github.com/labring/sealos/controllers/job/init/internal/util/errors"

"github.com/labring/sealos/controllers/pkg/database"
"github.com/labring/sealos/controllers/pkg/utils/logger"
gonanoid "github.com/matoous/go-nanoid/v2"

"github.com/labring/sealos/controllers/pkg/database/cockroach"
"github.com/labring/sealos/controllers/pkg/types"
)

func PresetAdminUser(ctx context.Context) error {
//init mongodb database
client, err := InitMongoDB(ctx)
func PresetAdminUser() error {
var ck cockroach.Cockroach
v2Account, err := cockroach.NewCockRoach(os.Getenv(database.GlobalCockroachURI), os.Getenv(database.LocalCockroachURI))
if err != nil {
return err
return fmt.Errorf("failed to connect to cockroach: %v", err)
}

defer func() {
if client == nil {
logger.Error(fmt.Errorf("mongodb client is nil"), "disconnect mongodb client failed")
return
}
err := client.Disconnect(ctx)
err := v2Account.Close()
if err != nil {
logger.Error(err, "disconnect mongodb client failed")
return
logger.Warn("failed to close cockroach connection: %v", err)
}
}()

collection := client.Database(mongoUserDatabase).Collection(mongoUserCollection)

// create admin user
user, err := newAdminUser()
if err != nil {
return err
}

// check if the user already exists
exist, err := user.Exist(ctx, collection)
userNanoID, err := gonanoid.New(10)
if err != nil {
return err
}
if exist {
return errors.ErrAdminExists
return fmt.Errorf("failed to generate nano id: %v", err)
}

// insert root user
if _, err := collection.InsertOne(ctx, user); err != nil {
return err
if err = ck.CreateUser(&types.OauthProvider{
UserUID: common.AdminUID(),
ProviderType: types.OauthProviderTypePassword,
ProviderID: adminPassword,
}, &types.RegionUserCr{
CrName: adminUserName,
UserUID: common.AdminUID(),
}, &types.User{
UID: common.AdminUID(),
ID: userNanoID,
Name: adminUserName,
Nickname: userNanoID,
}); err != nil {
return fmt.Errorf("failed to create user: %v", err)
}
return nil
}

func newAdminUser() (*User, error) {
return newUser(common.AdminUID(), DefaultAdminUserName, DefaultAdminUserName, hashPassword(DefaultAdminPassword), controller.DefaultAdminUserName), nil
}

func newUser(uid, name, passwordUser, hashedPassword, k8sUser string) *User {
return &User{
UID: uid,
Name: name,
PasswordUser: passwordUser,
Password: hashedPassword,
// to iso string
CreatedTime: time.Now().Format(time.RFC3339),
K8sUsers: []K8sUser{
{
Name: k8sUser,
},
},
}
}
4 changes: 0 additions & 4 deletions controllers/job/init/internal/util/errors/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,3 @@
// limitations under the License.

package errors

import "fmt"

var ErrAdminExists = fmt.Errorf("admin user already exists")
15 changes: 15 additions & 0 deletions controllers/pkg/database/cockroach/accountv2.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,21 @@ const (
EnvBaseBalance = "BASE_BALANCE"
)

func (g *Cockroach) CreateUser(oAuth *types.OauthProvider, regionUserCr *types.RegionUserCr, user *types.User) error {
return g.DB.Transaction(func(tx *gorm.DB) error {
if err := tx.FirstOrCreate(user).Error; err != nil {
return fmt.Errorf("failed to create user: %w", err)
}
if err := tx.FirstOrCreate(oAuth).Error; err != nil {
return fmt.Errorf("failed to create user oauth provider: %w", err)
}
if err := tx.FirstOrCreate(&regionUserCr).Error; err != nil {
return fmt.Errorf("failed to create user region cr: %w", err)
}
return nil
})
}

func (g *Cockroach) GetUserCr(ops *types.UserQueryOpts) (*types.RegionUserCr, error) {
if err := checkOps(ops); err != nil {
return nil, err
Expand Down
1 change: 1 addition & 0 deletions controllers/pkg/database/interface.go
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +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
GetAccount(user *types.UserQueryOpts) (*types.Account, error)
GetUserOauthProvider(ops *types.UserQueryOpts) (*types.OauthProvider, error)
AddBalance(user *types.UserQueryOpts, balance int64) error
Expand Down
15 changes: 0 additions & 15 deletions controllers/pkg/types/User.go

This file was deleted.

4 changes: 2 additions & 2 deletions controllers/pkg/types/global.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,8 +76,8 @@ type User struct {
UID uuid.UUID `gorm:"type:uuid;default:gen_random_uuid();primary_key"`
CreateAt time.Time `gorm:"type:timestamp(3) with time zone;default:current_timestamp();not null"`
UpdateAt time.Time `gorm:"type:timestamp(3) with time zone;default:current_timestamp();not null"`
AvatarURI string `gorm:"column:avatarUri;type:text;not null"`
Nickname string `gorm:"type:text;not null"`
AvatarURI string `gorm:"column:avatarUri;type:text"`
Nickname string `gorm:"type:text"`
ID string `gorm:"type:text;not null;unique"`
Name string `gorm:"type:text;not null"`
}
Expand Down

0 comments on commit ae252be

Please sign in to comment.