From e4d13f3377cee2f99e81ca7aa37b464776df37de Mon Sep 17 00:00:00 2001 From: "meilin.huang" <954537473@qq.com> Date: Tue, 23 Jan 2024 19:30:28 +0800 Subject: [PATCH] =?UTF-8?q?refactor:=20=E5=BC=95=E5=85=A5=E6=97=A5?= =?UTF-8?q?=E5=BF=97=E5=88=87=E5=89=B2=E5=BA=93=E3=80=81indexApi=E6=8B=86?= =?UTF-8?q?=E5=88=86=E7=AD=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- mayfly_go_web/src/views/home/Home.vue | 28 ++++++++++--- mayfly_go_web/src/views/home/api.ts | 8 ++-- server/config.yml.example | 11 ++++- server/go.mod | 3 +- server/initialize/initialize.go | 2 +- server/internal/common/api/index.go | 36 ----------------- server/internal/common/router/index.go | 20 --------- server/internal/common/router/router.go | 1 - server/internal/db/api/dashbord.go | 23 +++++++++++ server/internal/db/application/db.go | 20 ++++----- server/internal/db/application/db_backup.go | 5 +-- server/internal/db/application/db_binlog.go | 16 ++++---- .../internal/db/application/db_data_sync.go | 6 +-- server/internal/db/application/db_restore.go | 4 -- .../internal/db/application/db_scheduler.go | 5 +-- server/internal/db/application/db_sql_exec.go | 10 ++--- server/internal/db/router/db.go | 5 +++ server/internal/machine/api/dashbord.go | 23 +++++++++++ .../internal/machine/application/machine.go | 14 +++---- .../machine/application/machine_cronjob.go | 38 +++++++++--------- .../machine/application/machine_file.go | 15 ++++--- .../machine/application/machine_script.go | 4 +- server/internal/machine/router/machine.go | 5 +++ server/internal/mongo/api/dashbord.go | 21 ++++++++++ server/internal/mongo/application/mongo.go | 10 ++--- server/internal/mongo/router/mongo.go | 5 +++ server/internal/redis/api/dashbord.go | 21 ++++++++++ server/internal/redis/application/redis.go | 10 ++--- server/internal/redis/router/redis.go | 5 +++ server/internal/sys/application/role.go | 30 +++++++------- server/internal/tag/api/tag_tree.go | 6 +-- server/internal/tag/application/tag_tree.go | 28 ++++++------- server/internal/tag/application/team.go | 34 ++++++++-------- server/pkg/config/config.go | 3 ++ server/pkg/config/log.go | 25 +++--------- server/pkg/config/mysql.go | 2 +- server/pkg/config/sqlite.go | 2 +- server/pkg/ioc/ioc.go | 10 +++-- server/pkg/logx/config.go | 24 +++++++---- server/pkg/utils/collx/map.go | 20 +++++++++ server/resources/data/mayfly-go.sqlite | Bin 225280 -> 225280 bytes server/resources/script/sql/v1.7/v1.7.1.sql | 4 -- server/resources/script/sql/v1.7/v1.7.2.sql | 3 ++ 43 files changed, 324 insertions(+), 241 deletions(-) delete mode 100644 server/internal/common/api/index.go delete mode 100644 server/internal/common/router/index.go create mode 100644 server/internal/db/api/dashbord.go create mode 100644 server/internal/machine/api/dashbord.go create mode 100644 server/internal/mongo/api/dashbord.go create mode 100644 server/internal/redis/api/dashbord.go create mode 100644 server/resources/script/sql/v1.7/v1.7.2.sql diff --git a/mayfly_go_web/src/views/home/Home.vue b/mayfly_go_web/src/views/home/Home.vue index 6af2ceed..031ee2e2 100644 --- a/mayfly_go_web/src/views/home/Home.vue +++ b/mayfly_go_web/src/views/home/Home.vue @@ -73,12 +73,28 @@ const currentTime = computed(() => { // 初始化数字滚动 const initNumCountUp = async () => { - const res: any = await indexApi.getIndexCount.request(); - nextTick(() => { - new CountUp('mongoNum', res.mongoNum).start(); - new CountUp('machineNum', res.machineNum).start(); - new CountUp('dbNum', res.dbNum).start(); - new CountUp('redisNum', res.redisNum).start(); + indexApi.machineDashbord.request().then((res: any) => { + nextTick(() => { + new CountUp('machineNum', res.machineNum).start(); + }); + }); + + indexApi.dbDashbord.request().then((res: any) => { + nextTick(() => { + new CountUp('dbNum', res.dbNum).start(); + }); + }); + + indexApi.redisDashbord.request().then((res: any) => { + nextTick(() => { + new CountUp('redisNum', res.redisNum).start(); + }); + }); + + indexApi.mongoDashbord.request().then((res: any) => { + nextTick(() => { + new CountUp('mongoNum', res.mongoNum).start(); + }); }); }; diff --git a/mayfly_go_web/src/views/home/api.ts b/mayfly_go_web/src/views/home/api.ts index 2553330b..fd8115f3 100644 --- a/mayfly_go_web/src/views/home/api.ts +++ b/mayfly_go_web/src/views/home/api.ts @@ -1,6 +1,8 @@ import Api from '@/common/Api'; export const indexApi = { - getIndexCount: Api.newGet("/common/index/count"), -} - + machineDashbord: Api.newGet('/machines/dashbord'), + dbDashbord: Api.newGet('/dbs/dashbord'), + redisDashbord: Api.newGet('/redis/dashbord'), + mongoDashbord: Api.newGet('/mongos/dashbord'), +}; diff --git a/server/config.yml.example b/server/config.yml.example index bb40243a..c404bd1c 100644 --- a/server/config.yml.example +++ b/server/config.yml.example @@ -37,12 +37,19 @@ sqlite: # password: 111049 # db: 0 log: - # 日志等级, debug, info, warn, error + # 日志等级, debug, info, warn, error level: info # 日志格式类型, text/json type: text # 是否记录方法调用栈信息 add-source: false + # 日志文件配置 # file: - # path: ./ + # path: ./log # name: mayfly-go.log + # # 日志文件的最大大小(以兆字节为单位)。当日志文件大小达到该值时,将触发切割操作 + # max-size: 500 + # # 根据文件名中的时间戳,设置保留旧日志文件的最大天数 + # max-age: 60 + # # 是否使用 gzip 压缩方式压缩轮转后的日志文件 + # compress: true diff --git a/server/go.mod b/server/go.mod index 85848180..ad3efc6d 100644 --- a/server/go.mod +++ b/server/go.mod @@ -31,6 +31,7 @@ require ( go.mongodb.org/mongo-driver v1.13.1 // mongo golang.org/x/crypto v0.18.0 // ssh golang.org/x/oauth2 v0.15.0 + gopkg.in/natefinch/lumberjack.v2 v2.2.1 gopkg.in/yaml.v3 v3.0.1 // gorm gorm.io/driver/mysql v1.5.2 @@ -80,7 +81,7 @@ require ( github.com/xdg-go/stringprep v1.0.4 // indirect github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d // indirect golang.org/x/arch v0.3.0 // indirect - golang.org/x/exp v0.0.0-20230519143937-03e91628a987 + golang.org/x/exp v0.0.0-20230519143937-03e91628a987 // indirect golang.org/x/image v0.13.0 // indirect golang.org/x/net v0.19.0 // indirect golang.org/x/sync v0.1.0 // indirect diff --git a/server/initialize/initialize.go b/server/initialize/initialize.go index df1f31ab..03bfec51 100644 --- a/server/initialize/initialize.go +++ b/server/initialize/initialize.go @@ -39,7 +39,7 @@ func InitOther() { // 调用各个默认的初始化函数 for _, initFunc := range initFuncs { - initFunc() + go initFunc() } initFuncs = nil } diff --git a/server/internal/common/api/index.go b/server/internal/common/api/index.go deleted file mode 100644 index f3853b92..00000000 --- a/server/internal/common/api/index.go +++ /dev/null @@ -1,36 +0,0 @@ -package api - -import ( - "mayfly-go/internal/common/consts" - dbapp "mayfly-go/internal/db/application" - machineapp "mayfly-go/internal/machine/application" - mongoapp "mayfly-go/internal/mongo/application" - redisapp "mayfly-go/internal/redis/application" - tagapp "mayfly-go/internal/tag/application" - "mayfly-go/pkg/req" - "mayfly-go/pkg/utils/collx" -) - -type Index struct { - TagApp tagapp.TagTree `inject:"TagTreeApp"` - MachineApp machineapp.Machine `inject:""` - DbApp dbapp.Db `inject:""` - RedisApp redisapp.Redis `inject:""` - MongoApp mongoapp.Mongo `inject:""` -} - -func (i *Index) Count(rc *req.Ctx) { - accountId := rc.GetLoginAccount().Id - - mongoNum := len(i.TagApp.GetAccountResourceCodes(accountId, consts.TagResourceTypeMongo, "")) - machienNum := len(i.TagApp.GetAccountResourceCodes(accountId, consts.TagResourceTypeMachine, "")) - dbNum := len(i.TagApp.GetAccountResourceCodes(accountId, consts.TagResourceTypeDb, "")) - redisNum := len(i.TagApp.GetAccountResourceCodes(accountId, consts.TagResourceTypeRedis, "")) - - rc.ResData = collx.M{ - "mongoNum": mongoNum, - "machineNum": machienNum, - "dbNum": dbNum, - "redisNum": redisNum, - } -} diff --git a/server/internal/common/router/index.go b/server/internal/common/router/index.go deleted file mode 100644 index b9f911cc..00000000 --- a/server/internal/common/router/index.go +++ /dev/null @@ -1,20 +0,0 @@ -package router - -import ( - "mayfly-go/internal/common/api" - "mayfly-go/pkg/biz" - "mayfly-go/pkg/ioc" - "mayfly-go/pkg/req" - - "github.com/gin-gonic/gin" -) - -func InitIndexRouter(router *gin.RouterGroup) { - index := router.Group("common/index") - i := new(api.Index) - biz.ErrIsNil(ioc.Inject(i)) - { - // 首页基本信息统计 - req.NewGet("count", i.Count).Group(index) - } -} diff --git a/server/internal/common/router/router.go b/server/internal/common/router/router.go index 8c0f1c2b..ce6d6a23 100644 --- a/server/internal/common/router/router.go +++ b/server/internal/common/router/router.go @@ -4,5 +4,4 @@ import "github.com/gin-gonic/gin" func Init(router *gin.RouterGroup) { InitCommonRouter(router) - InitIndexRouter(router) } diff --git a/server/internal/db/api/dashbord.go b/server/internal/db/api/dashbord.go new file mode 100644 index 00000000..a65e9cbe --- /dev/null +++ b/server/internal/db/api/dashbord.go @@ -0,0 +1,23 @@ +package api + +import ( + "mayfly-go/internal/common/consts" + "mayfly-go/internal/db/application" + tagapp "mayfly-go/internal/tag/application" + "mayfly-go/pkg/req" + "mayfly-go/pkg/utils/collx" +) + +type Dashbord struct { + TagTreeApp tagapp.TagTree `inject:""` + DbApp application.Db `inject:""` +} + +func (m *Dashbord) Dashbord(rc *req.Ctx) { + accountId := rc.GetLoginAccount().Id + dbNum := len(m.TagTreeApp.GetAccountResourceCodes(accountId, consts.TagResourceTypeDb, "")) + + rc.ResData = collx.M{ + "dbNum": dbNum, + } +} diff --git a/server/internal/db/application/db.go b/server/internal/db/application/db.go index 818bb26a..35bfa6ef 100644 --- a/server/internal/db/application/db.go +++ b/server/internal/db/application/db.go @@ -43,9 +43,9 @@ type Db interface { type dbAppImpl struct { base.AppImpl[*entity.Db, repository.Db] - DbSqlRepo repository.DbSql `inject:""` - DbInstanceApp Instance `inject:""` - TagApp tagapp.TagTree `inject:"TagTreeApp"` + dbSqlRepo repository.DbSql `inject:"DbSqlRepo"` + dbInstanceApp Instance `inject:"DbInstanceApp"` + tagApp tagapp.TagTree `inject:"TagTreeApp"` } // 注入DbRepo @@ -78,7 +78,7 @@ func (d *dbAppImpl) SaveDb(ctx context.Context, dbEntity *entity.Db, tagIds ...u return d.Tx(ctx, func(ctx context.Context) error { return d.Insert(ctx, dbEntity) }, func(ctx context.Context) error { - return d.TagApp.RelateResource(ctx, resouceCode, consts.TagResourceTypeDb, tagIds) + return d.tagApp.RelateResource(ctx, resouceCode, consts.TagResourceTypeDb, tagIds) }) } @@ -106,13 +106,13 @@ func (d *dbAppImpl) SaveDb(ctx context.Context, dbEntity *entity.Db, tagIds ...u for _, v := range delDb { // 删除该库关联的所有sql记录 - d.DbSqlRepo.DeleteByCond(ctx, &entity.DbSql{DbId: dbId, Db: v}) + d.dbSqlRepo.DeleteByCond(ctx, &entity.DbSql{DbId: dbId, Db: v}) } return d.Tx(ctx, func(ctx context.Context) error { return d.UpdateById(ctx, dbEntity) }, func(ctx context.Context) error { - return d.TagApp.RelateResource(ctx, old.Code, consts.TagResourceTypeDb, tagIds) + return d.tagApp.RelateResource(ctx, old.Code, consts.TagResourceTypeDb, tagIds) }) } @@ -133,10 +133,10 @@ func (d *dbAppImpl) Delete(ctx context.Context, id uint64) error { }, func(ctx context.Context) error { // 删除该库下用户保存的所有sql信息 - return d.DbSqlRepo.DeleteByCond(ctx, &entity.DbSql{DbId: id}) + return d.dbSqlRepo.DeleteByCond(ctx, &entity.DbSql{DbId: id}) }, func(ctx context.Context) error { var tagIds []uint64 - return d.TagApp.RelateResource(ctx, db.Code, consts.TagResourceTypeDb, tagIds) + return d.tagApp.RelateResource(ctx, db.Code, consts.TagResourceTypeDb, tagIds) }) } @@ -147,7 +147,7 @@ func (d *dbAppImpl) GetDbConn(dbId uint64, dbName string) (*dbi.DbConn, error) { return nil, errorx.NewBiz("数据库信息不存在") } - instance, err := d.DbInstanceApp.GetById(new(entity.DbInstance), db.InstanceId) + instance, err := d.dbInstanceApp.GetById(new(entity.DbInstance), db.InstanceId) if err != nil { return nil, errorx.NewBiz("数据库实例不存在") } @@ -168,7 +168,7 @@ func (d *dbAppImpl) GetDbConn(dbId uint64, dbName string) (*dbi.DbConn, error) { if err := instance.PwdDecrypt(); err != nil { return nil, errorx.NewBiz(err.Error()) } - return toDbInfo(instance, dbId, dbName, d.TagApp.ListTagPathByResource(consts.TagResourceTypeDb, db.Code)...), nil + return toDbInfo(instance, dbId, dbName, d.tagApp.ListTagPathByResource(consts.TagResourceTypeDb, db.Code)...), nil }) } diff --git a/server/internal/db/application/db_backup.go b/server/internal/db/application/db_backup.go index ed5d5143..f3a76631 100644 --- a/server/internal/db/application/db_backup.go +++ b/server/internal/db/application/db_backup.go @@ -3,16 +3,15 @@ package application import ( "context" "encoding/binary" - "github.com/google/uuid" "mayfly-go/internal/db/domain/entity" "mayfly-go/internal/db/domain/repository" "mayfly-go/pkg/model" + + "github.com/google/uuid" ) type DbBackupApp struct { - dbApp Db `inject:"DbApp"` scheduler *dbScheduler `inject:"DbScheduler"` - instanceRepo repository.Instance `inject:"DbInstanceRepo"` backupRepo repository.DbBackup `inject:"DbBackupRepo"` backupHistoryRepo repository.DbBackupHistory `inject:"DbBackupHistoryRepo"` } diff --git a/server/internal/db/application/db_binlog.go b/server/internal/db/application/db_binlog.go index 711b3626..002e0932 100644 --- a/server/internal/db/application/db_binlog.go +++ b/server/internal/db/application/db_binlog.go @@ -11,15 +11,13 @@ import ( ) type DbBinlogApp struct { - dbApp Db `inject:"DbApp"` - scheduler *dbScheduler `inject:"DbScheduler"` - binlogRepo repository.DbBinlog `inject:"DbBinlogRepo"` - binlogHistoryRepo repository.DbBinlogHistory `inject:"DbBinlogHistoryRepo"` - backupRepo repository.DbBackup `inject:"DbBackupRepo"` - backupHistoryRepo repository.DbBackupHistory `inject:"DbBackupHistoryRepo"` - context context.Context - cancel context.CancelFunc - waitGroup sync.WaitGroup + scheduler *dbScheduler `inject:"DbScheduler"` + binlogRepo repository.DbBinlog `inject:"DbBinlogRepo"` + backupRepo repository.DbBackup `inject:"DbBackupRepo"` + + context context.Context + cancel context.CancelFunc + waitGroup sync.WaitGroup } func newDbBinlogApp() *DbBinlogApp { diff --git a/server/internal/db/application/db_data_sync.go b/server/internal/db/application/db_data_sync.go index 2e51ba56..a3fbfc33 100644 --- a/server/internal/db/application/db_data_sync.go +++ b/server/internal/db/application/db_data_sync.go @@ -41,7 +41,7 @@ type DataSyncTask interface { type dataSyncAppImpl struct { base.AppImpl[*entity.DataSyncTask, repository.DataSyncTask] - DbDataSyncLogRepo repository.DataSyncLog `inject:""` + dbDataSyncLogRepo repository.DataSyncLog `inject:"DbDataSyncLogRepo"` } func (d *dataSyncAppImpl) InjectDbDataSyncTaskRepo(repo repository.DataSyncTask) { @@ -325,7 +325,7 @@ func (app *dataSyncAppImpl) endRunning(taskEntity *entity.DataSyncTask, log *ent } func (app *dataSyncAppImpl) saveLog(log *entity.DataSyncLog) { - app.DbDataSyncLogRepo.Save(context.Background(), log) + app.dbDataSyncLogRepo.Save(context.Background(), log) } func (app *dataSyncAppImpl) InitCronJob() { @@ -371,5 +371,5 @@ func (app *dataSyncAppImpl) InitCronJob() { } func (app *dataSyncAppImpl) GetTaskLogList(condition *entity.DataSyncLogQuery, pageParam *model.PageParam, toEntity any, orderBy ...string) (*model.PageResult[any], error) { - return app.DbDataSyncLogRepo.GetTaskLogList(condition, pageParam, toEntity, orderBy...) + return app.dbDataSyncLogRepo.GetTaskLogList(condition, pageParam, toEntity, orderBy...) } diff --git a/server/internal/db/application/db_restore.go b/server/internal/db/application/db_restore.go index e486d324..4224ec4c 100644 --- a/server/internal/db/application/db_restore.go +++ b/server/internal/db/application/db_restore.go @@ -8,13 +8,9 @@ import ( ) type DbRestoreApp struct { - dbApp Db `inject:"DbApp"` scheduler *dbScheduler `inject:"DbScheduler"` - instanceRepo repository.Instance `inject:"DbInstanceRepo"` - backupHistoryRepo repository.DbBackupHistory `inject:"DbBackupHistoryRepo"` restoreRepo repository.DbRestore `inject:"DbRestoreRepo"` restoreHistoryRepo repository.DbRestoreHistory `inject:"DbRestoreHistoryRepo"` - binlogHistoryRepo repository.DbBinlogHistory `inject:"DbBinlogHistoryRepo"` } func (app *DbRestoreApp) Init() error { diff --git a/server/internal/db/application/db_scheduler.go b/server/internal/db/application/db_scheduler.go index c97e130c..f7f86ee1 100644 --- a/server/internal/db/application/db_scheduler.go +++ b/server/internal/db/application/db_scheduler.go @@ -28,7 +28,6 @@ type dbScheduler struct { restoreHistoryRepo repository.DbRestoreHistory `inject:"DbRestoreHistoryRepo"` binlogRepo repository.DbBinlog `inject:"DbBinlogRepo"` binlogHistoryRepo repository.DbBinlogHistory `inject:"DbBinlogHistoryRepo"` - binlogTimes map[uint64]time.Time } func newDbScheduler() *dbScheduler { @@ -53,7 +52,7 @@ func (s *dbScheduler) repo(typ entity.DbJobType) repository.DbJob { case entity.DbJobTypeBinlog: return s.binlogRepo default: - panic(errors.New(fmt.Sprintf("无效的数据库任务类型: %v", typ))) + panic(fmt.Errorf("无效的数据库任务类型: %v", typ)) } } @@ -281,7 +280,7 @@ func (s *dbScheduler) runJob(ctx context.Context, job entity.DbJob) { case entity.DbJobTypeBinlog: errRun = s.fetchBinlogMysql(ctx, job) default: - errRun = errors.New(fmt.Sprintf("无效的数据库任务类型: %v", typ)) + errRun = fmt.Errorf("无效的数据库任务类型: %v", typ) } status := entity.DbJobSuccess if errRun != nil { diff --git a/server/internal/db/application/db_sql_exec.go b/server/internal/db/application/db_sql_exec.go index 28fd39fb..eea3f61e 100644 --- a/server/internal/db/application/db_sql_exec.go +++ b/server/internal/db/application/db_sql_exec.go @@ -57,7 +57,7 @@ type DbSqlExec interface { } type dbSqlExecAppImpl struct { - DbSqlExecRepo repository.DbSqlExec `inject:""` + dbSqlExecRepo repository.DbSqlExec `inject:"DbSqlExecRepo"` } func createSqlExecRecord(ctx context.Context, execSqlReq *DbSqlExecReq) *entity.DbSqlExec { @@ -138,23 +138,23 @@ func (d *dbSqlExecAppImpl) Exec(ctx context.Context, execSqlReq *DbSqlExecReq) ( // 保存sql执行记录,如果是查询类则根据系统配置判断是否保存 func (d *dbSqlExecAppImpl) saveSqlExecLog(isQuery bool, dbSqlExecRecord *entity.DbSqlExec) { if !isQuery { - d.DbSqlExecRepo.Insert(context.TODO(), dbSqlExecRecord) + d.dbSqlExecRepo.Insert(context.TODO(), dbSqlExecRecord) return } if config.GetDbSaveQuerySql() { dbSqlExecRecord.Table = "-" dbSqlExecRecord.OldValue = "-" dbSqlExecRecord.Type = entity.DbSqlExecTypeQuery - d.DbSqlExecRepo.Insert(context.TODO(), dbSqlExecRecord) + d.dbSqlExecRepo.Insert(context.TODO(), dbSqlExecRecord) } } func (d *dbSqlExecAppImpl) DeleteBy(ctx context.Context, condition *entity.DbSqlExec) { - d.DbSqlExecRepo.DeleteByCond(ctx, condition) + d.dbSqlExecRepo.DeleteByCond(ctx, condition) } func (d *dbSqlExecAppImpl) GetPageList(condition *entity.DbSqlExecQuery, pageParam *model.PageParam, toEntity any, orderBy ...string) (*model.PageResult[any], error) { - return d.DbSqlExecRepo.GetPageList(condition, pageParam, toEntity, orderBy...) + return d.dbSqlExecRepo.GetPageList(condition, pageParam, toEntity, orderBy...) } func doSelect(ctx context.Context, selectStmt *sqlparser.Select, execSqlReq *DbSqlExecReq) (*DbSqlExecRes, error) { diff --git a/server/internal/db/router/db.go b/server/internal/db/router/db.go index 7ae16ff1..97b735dc 100644 --- a/server/internal/db/router/db.go +++ b/server/internal/db/router/db.go @@ -15,7 +15,12 @@ func InitDbRouter(router *gin.RouterGroup) { d := new(api.Db) biz.ErrIsNil(ioc.Inject(d)) + dashbord := new(api.Dashbord) + biz.ErrIsNil(ioc.Inject(dashbord)) + reqs := [...]*req.Conf{ + req.NewGet("dashbord", dashbord.Dashbord), + // 获取数据库列表 req.NewGet("", d.Dbs), diff --git a/server/internal/machine/api/dashbord.go b/server/internal/machine/api/dashbord.go new file mode 100644 index 00000000..935d0893 --- /dev/null +++ b/server/internal/machine/api/dashbord.go @@ -0,0 +1,23 @@ +package api + +import ( + "mayfly-go/internal/common/consts" + "mayfly-go/internal/machine/application" + tagapp "mayfly-go/internal/tag/application" + "mayfly-go/pkg/req" + "mayfly-go/pkg/utils/collx" +) + +type Dashbord struct { + TagTreeApp tagapp.TagTree `inject:""` + MachineApp application.Machine `inject:""` +} + +func (m *Dashbord) Dashbord(rc *req.Ctx) { + accountId := rc.GetLoginAccount().Id + machienNum := len(m.TagTreeApp.GetAccountResourceCodes(accountId, consts.TagResourceTypeMachine, "")) + + rc.ResData = collx.M{ + "machineNum": machienNum, + } +} diff --git a/server/internal/machine/application/machine.go b/server/internal/machine/application/machine.go index c2d57238..1df75f73 100644 --- a/server/internal/machine/application/machine.go +++ b/server/internal/machine/application/machine.go @@ -52,8 +52,8 @@ type Machine interface { type machineAppImpl struct { base.AppImpl[*entity.Machine, repository.Machine] - AuthCertApp AuthCert `inject:""` - TagApp tagapp.TagTree `inject:"TagTreeApp"` + authCertApp AuthCert `inject:"AuthCertApp"` + tagApp tagapp.TagTree `inject:"TagTreeApp"` } // 注入MachineRepo @@ -91,7 +91,7 @@ func (m *machineAppImpl) SaveMachine(ctx context.Context, me *entity.Machine, ta return m.Tx(ctx, func(ctx context.Context) error { return m.Insert(ctx, me) }, func(ctx context.Context) error { - return m.TagApp.RelateResource(ctx, resouceCode, consts.TagResourceTypeMachine, tagIds) + return m.tagApp.RelateResource(ctx, resouceCode, consts.TagResourceTypeMachine, tagIds) }) } @@ -109,7 +109,7 @@ func (m *machineAppImpl) SaveMachine(ctx context.Context, me *entity.Machine, ta return m.Tx(ctx, func(ctx context.Context) error { return m.UpdateById(ctx, me) }, func(ctx context.Context) error { - return m.TagApp.RelateResource(ctx, oldMachine.Code, consts.TagResourceTypeMachine, tagIds) + return m.tagApp.RelateResource(ctx, oldMachine.Code, consts.TagResourceTypeMachine, tagIds) }) } @@ -154,7 +154,7 @@ func (m *machineAppImpl) Delete(ctx context.Context, id uint64) error { return m.DeleteById(ctx, id) }, func(ctx context.Context) error { var tagIds []uint64 - return m.TagApp.RelateResource(ctx, machine.Code, consts.TagResourceTypeMachine, tagIds) + return m.tagApp.RelateResource(ctx, machine.Code, consts.TagResourceTypeMachine, tagIds) }) } @@ -227,11 +227,11 @@ func (m *machineAppImpl) toMachineInfo(me *entity.Machine) (*mcm.MachineInfo, er mi.Ip = me.Ip mi.Port = me.Port mi.Username = me.Username - mi.TagPath = m.TagApp.ListTagPathByResource(consts.TagResourceTypeMachine, me.Code) + mi.TagPath = m.tagApp.ListTagPathByResource(consts.TagResourceTypeMachine, me.Code) mi.EnableRecorder = me.EnableRecorder if me.UseAuthCert() { - ac, err := m.AuthCertApp.GetById(new(entity.AuthCert), uint64(me.AuthCertId)) + ac, err := m.authCertApp.GetById(new(entity.AuthCert), uint64(me.AuthCertId)) if err != nil { return nil, errorx.NewBiz("授权凭证信息已不存在,请重新关联") } diff --git a/server/internal/machine/application/machine_cronjob.go b/server/internal/machine/application/machine_cronjob.go index 1a2463da..ed3f0f5d 100644 --- a/server/internal/machine/application/machine_cronjob.go +++ b/server/internal/machine/application/machine_cronjob.go @@ -53,9 +53,9 @@ type MachineCronJob interface { type machineCronJobAppImpl struct { base.AppImpl[*entity.MachineCronJob, repository.MachineCronJob] - MachineCronJobRelateRepo repository.MachineCronJobRelate `inject:""` - MachineCronJobExecRepo repository.MachineCronJobExec `inject:""` - MachineApp Machine `inject:""` + machineCronJobRelateRepo repository.MachineCronJobRelate `inject:"MachineCronJobRelateRepo"` + machineCronJobExecRepo repository.MachineCronJobExec `inject:"MachineCronJobExecRepo"` + machineApp Machine `inject:"MachineApp"` } // 注入MachineCronJobRepo @@ -70,7 +70,7 @@ func (m *machineCronJobAppImpl) GetPageList(condition *entity.MachineCronJob, pa // 获取分页执行结果列表 func (m *machineCronJobAppImpl) GetExecPageList(condition *entity.MachineCronJobExec, pageParam *model.PageParam, toEntity any, orderBy ...string) (*model.PageResult[any], error) { - return m.MachineCronJobExecRepo.GetPageList(condition, pageParam, toEntity, orderBy...) + return m.machineCronJobExecRepo.GetPageList(condition, pageParam, toEntity, orderBy...) } // 保存机器任务信息 @@ -96,20 +96,20 @@ func (m *machineCronJobAppImpl) SaveMachineCronJob(ctx context.Context, mcj *ent func (m *machineCronJobAppImpl) Delete(ctx context.Context, id uint64) { m.DeleteById(ctx, id) - m.MachineCronJobExecRepo.DeleteByCond(ctx, &entity.MachineCronJobExec{CronJobId: id}) - m.MachineCronJobRelateRepo.DeleteByCond(ctx, &entity.MachineCronJobRelate{CronJobId: id}) + m.machineCronJobExecRepo.DeleteByCond(ctx, &entity.MachineCronJobExec{CronJobId: id}) + m.machineCronJobRelateRepo.DeleteByCond(ctx, &entity.MachineCronJobRelate{CronJobId: id}) } func (m *machineCronJobAppImpl) GetRelateMachineIds(cronJobId uint64) []uint64 { - return m.MachineCronJobRelateRepo.GetMachineIds(cronJobId) + return m.machineCronJobRelateRepo.GetMachineIds(cronJobId) } func (m *machineCronJobAppImpl) GetRelateCronJobIds(machineId uint64) []uint64 { - return m.MachineCronJobRelateRepo.GetCronJobIds(machineId) + return m.machineCronJobRelateRepo.GetCronJobIds(machineId) } func (m *machineCronJobAppImpl) CronJobRelateMachines(ctx context.Context, cronJobId uint64, machineIds []uint64) { - oldMachineIds := m.MachineCronJobRelateRepo.GetMachineIds(cronJobId) + oldMachineIds := m.machineCronJobRelateRepo.GetMachineIds(cronJobId) addIds, delIds, _ := collx.ArrayCompare[uint64](machineIds, oldMachineIds) addVals := make([]*entity.MachineCronJobRelate, 0) @@ -119,20 +119,20 @@ func (m *machineCronJobAppImpl) CronJobRelateMachines(ctx context.Context, cronJ CronJobId: cronJobId, }) } - m.MachineCronJobRelateRepo.BatchInsert(ctx, addVals) + m.machineCronJobRelateRepo.BatchInsert(ctx, addVals) for _, delId := range delIds { - m.MachineCronJobRelateRepo.DeleteByCond(ctx, &entity.MachineCronJobRelate{CronJobId: cronJobId, MachineId: delId}) + m.machineCronJobRelateRepo.DeleteByCond(ctx, &entity.MachineCronJobRelate{CronJobId: cronJobId, MachineId: delId}) } } func (m *machineCronJobAppImpl) MachineRelateCronJobs(ctx context.Context, machineId uint64, cronJobs []uint64) { if len(cronJobs) == 0 { - m.MachineCronJobRelateRepo.DeleteByCond(ctx, &entity.MachineCronJobRelate{MachineId: machineId}) + m.machineCronJobRelateRepo.DeleteByCond(ctx, &entity.MachineCronJobRelate{MachineId: machineId}) return } - oldCronIds := m.MachineCronJobRelateRepo.GetCronJobIds(machineId) + oldCronIds := m.machineCronJobRelateRepo.GetCronJobIds(machineId) addIds, delIds, _ := collx.ArrayCompare[uint64](cronJobs, oldCronIds) addVals := make([]*entity.MachineCronJobRelate, 0) @@ -142,10 +142,10 @@ func (m *machineCronJobAppImpl) MachineRelateCronJobs(ctx context.Context, machi CronJobId: addId, }) } - m.MachineCronJobRelateRepo.BatchInsert(ctx, addVals) + m.machineCronJobRelateRepo.BatchInsert(ctx, addVals) for _, delId := range delIds { - m.MachineCronJobRelateRepo.DeleteByCond(ctx, &entity.MachineCronJobRelate{CronJobId: delId, MachineId: machineId}) + m.machineCronJobRelateRepo.DeleteByCond(ctx, &entity.MachineCronJobRelate{CronJobId: delId, MachineId: machineId}) } } @@ -199,7 +199,7 @@ func (m *machineCronJobAppImpl) RunCronJob(key string) { scheduler.RemoveByKey(key) } - machienIds := m.MachineCronJobRelateRepo.GetMachineIds(cronJob.Id) + machienIds := m.machineCronJobRelateRepo.GetMachineIds(cronJob.Id) for _, machineId := range machienIds { go m.runCronJob0(machineId, cronJob) } @@ -231,7 +231,7 @@ func (m *machineCronJobAppImpl) runCronJob0(mid uint64, cronJob *entity.MachineC defer func() { if err := recover(); err != nil { res := anyx.ToString(err) - m.MachineCronJobExecRepo.Insert(context.TODO(), &entity.MachineCronJobExec{ + m.machineCronJobExecRepo.Insert(context.TODO(), &entity.MachineCronJobExec{ MachineId: mid, CronJobId: cronJob.Id, ExecTime: time.Now(), @@ -242,7 +242,7 @@ func (m *machineCronJobAppImpl) runCronJob0(mid uint64, cronJob *entity.MachineC } }() - machineCli, err := m.MachineApp.GetCli(uint64(mid)) + machineCli, err := m.machineApp.GetCli(uint64(mid)) biz.ErrIsNilAppendErr(err, "获取客户端连接失败: %s") res, err := machineCli.Run(cronJob.Script) if err != nil { @@ -271,5 +271,5 @@ func (m *machineCronJobAppImpl) runCronJob0(mid uint64, cronJob *entity.MachineC execRes.Status = entity.MachineCronJobExecStatusError } // 保存执行记录 - m.MachineCronJobExecRepo.Insert(context.TODO(), execRes) + m.machineCronJobExecRepo.Insert(context.TODO(), execRes) } diff --git a/server/internal/machine/application/machine_file.go b/server/internal/machine/application/machine_file.go index 0d28acec..3f1f51b7 100644 --- a/server/internal/machine/application/machine_file.go +++ b/server/internal/machine/application/machine_file.go @@ -75,8 +75,7 @@ type MachineFile interface { type machineFileAppImpl struct { base.AppImpl[*entity.MachineFile, repository.MachineFile] - MachineFileRepo repository.MachineFile `inject:""` - MachineApp Machine `inject:""` + machineApp Machine `inject:"MachineApp"` } // 注入MachineFileRepo @@ -86,26 +85,26 @@ func (m *machineFileAppImpl) InjectMachineFileRepo(repo repository.MachineFile) // 分页获取机器脚本信息列表 func (m *machineFileAppImpl) GetPageList(condition *entity.MachineFile, pageParam *model.PageParam, toEntity any, orderBy ...string) (*model.PageResult[any], error) { - return m.MachineFileRepo.GetPageList(condition, pageParam, toEntity, orderBy...) + return m.GetRepo().GetPageList(condition, pageParam, toEntity, orderBy...) } // 根据条件获取 func (m *machineFileAppImpl) GetMachineFile(condition *entity.MachineFile, cols ...string) error { - return m.MachineFileRepo.GetBy(condition, cols...) + return m.GetBy(condition, cols...) } // 保存机器文件配置 func (m *machineFileAppImpl) Save(ctx context.Context, mf *entity.MachineFile) error { - _, err := m.MachineApp.GetById(new(entity.Machine), mf.MachineId, "Name") + _, err := m.machineApp.GetById(new(entity.Machine), mf.MachineId, "Name") if err != nil { return errorx.NewBiz("该机器不存在") } if mf.Id != 0 { - return m.MachineFileRepo.UpdateById(ctx, mf) + return m.UpdateById(ctx, mf) } - return m.MachineFileRepo.Insert(ctx, mf) + return m.Insert(ctx, mf) } func (m *machineFileAppImpl) ReadDir(fid uint64, path string) ([]fs.FileInfo, error) { @@ -306,7 +305,7 @@ func (m *machineFileAppImpl) GetMachineCli(fid uint64, inputPath ...string) (*mc return nil, errorx.NewBiz("无权访问该目录或文件: %s", path) } } - return m.MachineApp.GetCli(mf.MachineId) + return m.machineApp.GetCli(mf.MachineId) } // 获取文件机器 sftp cli diff --git a/server/internal/machine/application/machine_script.go b/server/internal/machine/application/machine_script.go index 51b1ced4..eb0dbd15 100644 --- a/server/internal/machine/application/machine_script.go +++ b/server/internal/machine/application/machine_script.go @@ -23,7 +23,7 @@ type MachineScript interface { type machineScriptAppImpl struct { base.AppImpl[*entity.MachineScript, repository.MachineScript] - MachineApp Machine `inject:""` + machineApp Machine `inject:"MachineApp"` } // 注入MachineScriptRepo @@ -42,7 +42,7 @@ func (m *machineScriptAppImpl) GetPageList(condition *entity.MachineScript, page func (m *machineScriptAppImpl) Save(ctx context.Context, ms *entity.MachineScript) error { // 如果机器id不为公共脚本id,则校验机器是否存在 if machineId := ms.MachineId; machineId != Common_Script_Machine_Id { - _, err := m.MachineApp.GetById(new(entity.Machine), machineId, "Name") + _, err := m.machineApp.GetById(new(entity.Machine), machineId, "Name") if err != nil { return errorx.NewBiz("该机器不存在") } diff --git a/server/internal/machine/router/machine.go b/server/internal/machine/router/machine.go index 1ccb5ed2..520ee1cd 100644 --- a/server/internal/machine/router/machine.go +++ b/server/internal/machine/router/machine.go @@ -13,11 +13,16 @@ func InitMachineRouter(router *gin.RouterGroup) { m := new(api.Machine) biz.ErrIsNil(ioc.Inject(m)) + dashbord := new(api.Dashbord) + biz.ErrIsNil(ioc.Inject(dashbord)) + machines := router.Group("machines") { saveMachineP := req.NewPermission("machine:update") reqs := [...]*req.Conf{ + req.NewGet("dashbord", dashbord.Dashbord), + req.NewGet("", m.Machines), req.NewGet(":machineId/stats", m.MachineStats), diff --git a/server/internal/mongo/api/dashbord.go b/server/internal/mongo/api/dashbord.go new file mode 100644 index 00000000..2adc4d91 --- /dev/null +++ b/server/internal/mongo/api/dashbord.go @@ -0,0 +1,21 @@ +package api + +import ( + "mayfly-go/internal/common/consts" + tagapp "mayfly-go/internal/tag/application" + "mayfly-go/pkg/req" + "mayfly-go/pkg/utils/collx" +) + +type Dashbord struct { + TagTreeApp tagapp.TagTree `inject:""` +} + +func (m *Dashbord) Dashbord(rc *req.Ctx) { + accountId := rc.GetLoginAccount().Id + mongoNum := len(m.TagTreeApp.GetAccountResourceCodes(accountId, consts.TagResourceTypeMongo, "")) + + rc.ResData = collx.M{ + "mongoNum": mongoNum, + } +} diff --git a/server/internal/mongo/application/mongo.go b/server/internal/mongo/application/mongo.go index 6dde59ca..bb0dd61d 100644 --- a/server/internal/mongo/application/mongo.go +++ b/server/internal/mongo/application/mongo.go @@ -34,7 +34,7 @@ type Mongo interface { type mongoAppImpl struct { base.AppImpl[*entity.Mongo, repository.Mongo] - TagApp tagapp.TagTree `inject:"TagTreeApp"` + tagApp tagapp.TagTree `inject:"TagTreeApp"` } // 注入MongoRepo @@ -60,7 +60,7 @@ func (d *mongoAppImpl) Delete(ctx context.Context, id uint64) error { }, func(ctx context.Context) error { var tagIds []uint64 - return d.TagApp.RelateResource(ctx, mongoEntity.Code, consts.TagResourceTypeMongo, tagIds) + return d.tagApp.RelateResource(ctx, mongoEntity.Code, consts.TagResourceTypeMongo, tagIds) }) } @@ -88,7 +88,7 @@ func (d *mongoAppImpl) SaveMongo(ctx context.Context, m *entity.Mongo, tagIds .. return d.Tx(ctx, func(ctx context.Context) error { return d.Insert(ctx, m) }, func(ctx context.Context) error { - return d.TagApp.RelateResource(ctx, resouceCode, consts.TagResourceTypeMongo, tagIds) + return d.tagApp.RelateResource(ctx, resouceCode, consts.TagResourceTypeMongo, tagIds) }) } @@ -106,7 +106,7 @@ func (d *mongoAppImpl) SaveMongo(ctx context.Context, m *entity.Mongo, tagIds .. return d.Tx(ctx, func(ctx context.Context) error { return d.UpdateById(ctx, m) }, func(ctx context.Context) error { - return d.TagApp.RelateResource(ctx, oldMongo.Code, consts.TagResourceTypeMongo, tagIds) + return d.tagApp.RelateResource(ctx, oldMongo.Code, consts.TagResourceTypeMongo, tagIds) }) } @@ -116,6 +116,6 @@ func (d *mongoAppImpl) GetMongoConn(id uint64) (*mgm.MongoConn, error) { if err != nil { return nil, errorx.NewBiz("mongo信息不存在") } - return me.ToMongoInfo(d.TagApp.ListTagPathByResource(consts.TagResourceTypeMongo, me.Code)...), nil + return me.ToMongoInfo(d.tagApp.ListTagPathByResource(consts.TagResourceTypeMongo, me.Code)...), nil }) } diff --git a/server/internal/mongo/router/mongo.go b/server/internal/mongo/router/mongo.go index 691f557f..c166e0a2 100644 --- a/server/internal/mongo/router/mongo.go +++ b/server/internal/mongo/router/mongo.go @@ -15,9 +15,14 @@ func InitMongoRouter(router *gin.RouterGroup) { ma := new(api.Mongo) biz.ErrIsNil(ioc.Inject(ma)) + dashbord := new(api.Dashbord) + biz.ErrIsNil(ioc.Inject(dashbord)) + saveDataPerm := req.NewPermission("mongo:data:save") reqs := [...]*req.Conf{ + req.NewGet("dashbord", dashbord.Dashbord), + // 获取所有mongo列表 req.NewGet("", ma.Mongos), diff --git a/server/internal/redis/api/dashbord.go b/server/internal/redis/api/dashbord.go new file mode 100644 index 00000000..4047369d --- /dev/null +++ b/server/internal/redis/api/dashbord.go @@ -0,0 +1,21 @@ +package api + +import ( + "mayfly-go/internal/common/consts" + tagapp "mayfly-go/internal/tag/application" + "mayfly-go/pkg/req" + "mayfly-go/pkg/utils/collx" +) + +type Dashbord struct { + TagTreeApp tagapp.TagTree `inject:""` +} + +func (m *Dashbord) Dashbord(rc *req.Ctx) { + accountId := rc.GetLoginAccount().Id + redisNum := len(m.TagTreeApp.GetAccountResourceCodes(accountId, consts.TagResourceTypeRedis, "")) + + rc.ResData = collx.M{ + "redisNum": redisNum, + } +} diff --git a/server/internal/redis/application/redis.go b/server/internal/redis/application/redis.go index d2bc31be..cba46c3e 100644 --- a/server/internal/redis/application/redis.go +++ b/server/internal/redis/application/redis.go @@ -38,7 +38,7 @@ type Redis interface { type redisAppImpl struct { base.AppImpl[*entity.Redis, repository.Redis] - TagApp tagapp.TagTree `inject:"TagTreeApp"` + tagApp tagapp.TagTree `inject:"TagTreeApp"` } // 注入RedisRepo @@ -87,7 +87,7 @@ func (r *redisAppImpl) SaveRedis(ctx context.Context, re *entity.Redis, tagIds . return r.Tx(ctx, func(ctx context.Context) error { return r.Insert(ctx, re) }, func(ctx context.Context) error { - return r.TagApp.RelateResource(ctx, resouceCode, consts.TagResourceTypeRedis, tagIds) + return r.tagApp.RelateResource(ctx, resouceCode, consts.TagResourceTypeRedis, tagIds) }) } @@ -113,7 +113,7 @@ func (r *redisAppImpl) SaveRedis(ctx context.Context, re *entity.Redis, tagIds . return r.Tx(ctx, func(ctx context.Context) error { return r.UpdateById(ctx, re) }, func(ctx context.Context) error { - return r.TagApp.RelateResource(ctx, oldRedis.Code, consts.TagResourceTypeRedis, tagIds) + return r.tagApp.RelateResource(ctx, oldRedis.Code, consts.TagResourceTypeRedis, tagIds) }) } @@ -133,7 +133,7 @@ func (r *redisAppImpl) Delete(ctx context.Context, id uint64) error { return r.DeleteById(ctx, id) }, func(ctx context.Context) error { var tagIds []uint64 - return r.TagApp.RelateResource(ctx, re.Code, consts.TagResourceTypeRedis, tagIds) + return r.tagApp.RelateResource(ctx, re.Code, consts.TagResourceTypeRedis, tagIds) }) } @@ -148,6 +148,6 @@ func (r *redisAppImpl) GetRedisConn(id uint64, db int) (*rdm.RedisConn, error) { if err := re.PwdDecrypt(); err != nil { return nil, errorx.NewBiz(err.Error()) } - return re.ToRedisInfo(db, r.TagApp.ListTagPathByResource(consts.TagResourceTypeRedis, re.Code)...), nil + return re.ToRedisInfo(db, r.tagApp.ListTagPathByResource(consts.TagResourceTypeRedis, re.Code)...), nil }) } diff --git a/server/internal/redis/router/redis.go b/server/internal/redis/router/redis.go index 18a6e084..308758e6 100644 --- a/server/internal/redis/router/redis.go +++ b/server/internal/redis/router/redis.go @@ -15,12 +15,17 @@ func InitRedisRouter(router *gin.RouterGroup) { rs := new(api.Redis) biz.ErrIsNil(ioc.Inject(rs)) + dashbord := new(api.Dashbord) + biz.ErrIsNil(ioc.Inject(dashbord)) + // 保存数据权限 saveDataP := req.NewPermission("redis:data:save") // 删除数据权限 deleteDataP := req.NewPermission("redis:data:del") reqs := [...]*req.Conf{ + req.NewGet("dashbord", dashbord.Dashbord), + // 获取redis list req.NewGet("", rs.RedisList), diff --git a/server/internal/sys/application/role.go b/server/internal/sys/application/role.go index 4f1a743d..48a181dc 100644 --- a/server/internal/sys/application/role.go +++ b/server/internal/sys/application/role.go @@ -42,16 +42,16 @@ type Role interface { } type roleAppImpl struct { - RoleRepo repository.Role `inject:""` - AccountRoleRepo repository.AccountRole `inject:""` + roleRepo repository.Role `inject:"RoleRepo"` + accountRoleRepo repository.AccountRole `inject:"AccountRoleRepo"` } func (m *roleAppImpl) GetPageList(condition *entity.RoleQuery, pageParam *model.PageParam, toEntity any, orderBy ...string) (*model.PageResult[any], error) { - return m.RoleRepo.GetPageList(condition, pageParam, toEntity, orderBy...) + return m.roleRepo.GetPageList(condition, pageParam, toEntity, orderBy...) } func (m *roleAppImpl) ListByQuery(condition *entity.RoleQuery) ([]*entity.Role, error) { - return m.RoleRepo.ListByQuery(condition) + return m.roleRepo.ListByQuery(condition) } func (m *roleAppImpl) SaveRole(ctx context.Context, role *entity.Role) error { @@ -62,14 +62,14 @@ func (m *roleAppImpl) SaveRole(ctx context.Context, role *entity.Role) error { } role.Status = 1 - return m.RoleRepo.Insert(ctx, role) + return m.roleRepo.Insert(ctx, role) } func (m *roleAppImpl) DeleteRole(ctx context.Context, id uint64) error { // 删除角色与资源账号的关联关系 return gormx.Tx( func(db *gorm.DB) error { - return m.RoleRepo.DeleteByIdWithDb(ctx, db, id) + return m.roleRepo.DeleteByIdWithDb(ctx, db, id) }, func(db *gorm.DB) error { return gormx.DeleteByWithDb(db, &entity.RoleResource{RoleId: id}) @@ -81,11 +81,11 @@ func (m *roleAppImpl) DeleteRole(ctx context.Context, id uint64) error { } func (m *roleAppImpl) GetRoleResourceIds(roleId uint64) []uint64 { - return m.RoleRepo.GetRoleResourceIds(roleId) + return m.roleRepo.GetRoleResourceIds(roleId) } func (m *roleAppImpl) GetRoleResources(roleId uint64, toEntity any) { - m.RoleRepo.GetRoleResources(roleId, toEntity) + m.roleRepo.GetRoleResources(roleId, toEntity) } func (m *roleAppImpl) SaveRoleResource(ctx context.Context, roleId uint64, resourceIds []uint64) { @@ -105,20 +105,20 @@ func (m *roleAppImpl) SaveRoleResource(ctx context.Context, roleId uint64, resou rr.IsDeleted = undeleted addVals = append(addVals, rr) } - m.RoleRepo.SaveRoleResource(addVals) + m.roleRepo.SaveRoleResource(addVals) for _, v := range delIds { - m.RoleRepo.DeleteRoleResource(roleId, v) + m.roleRepo.DeleteRoleResource(roleId, v) } } func (m *roleAppImpl) RelateAccountRole(ctx context.Context, accountId, roleId uint64, relateType consts.AccountRoleRelateType) error { accountRole := &entity.AccountRole{AccountId: accountId, RoleId: roleId} if relateType == consts.AccountRoleUnbind { - return m.AccountRoleRepo.DeleteByCond(ctx, accountRole) + return m.accountRoleRepo.DeleteByCond(ctx, accountRole) } - err := m.AccountRoleRepo.GetBy(accountRole) + err := m.accountRoleRepo.GetBy(accountRole) if err == nil { return errorx.NewBiz("该用户已拥有该权限") } @@ -128,15 +128,15 @@ func (m *roleAppImpl) RelateAccountRole(ctx context.Context, accountId, roleId u accountRole.Creator = la.Username accountRole.CreatorId = la.Id accountRole.CreateTime = &createTime - return m.AccountRoleRepo.Insert(ctx, accountRole) + return m.accountRoleRepo.Insert(ctx, accountRole) } func (m *roleAppImpl) GetAccountRoles(accountId uint64) ([]*entity.AccountRole, error) { var res []*entity.AccountRole - err := m.AccountRoleRepo.ListByCond(&entity.AccountRole{AccountId: accountId}, &res) + err := m.accountRoleRepo.ListByCond(&entity.AccountRole{AccountId: accountId}, &res) return res, err } func (m *roleAppImpl) GetRoleAccountPage(condition *entity.RoleAccountQuery, pageParam *model.PageParam, toEntity any, orderBy ...string) (*model.PageResult[any], error) { - return m.AccountRoleRepo.GetPageList(condition, pageParam, toEntity, orderBy...) + return m.accountRoleRepo.GetPageList(condition, pageParam, toEntity, orderBy...) } diff --git a/server/internal/tag/api/tag_tree.go b/server/internal/tag/api/tag_tree.go index 7508b908..001c972a 100644 --- a/server/internal/tag/api/tag_tree.go +++ b/server/internal/tag/api/tag_tree.go @@ -12,8 +12,6 @@ import ( "mayfly-go/pkg/utils/collx" "sort" "strings" - - "golang.org/x/exp/maps" ) type TagTree struct { @@ -43,7 +41,7 @@ func (p *TagTree) GetTagTree(rc *req.Ctx) { } // 获取所有以root标签开头的子标签 - tags := p.TagTreeApp.ListTagByPath(maps.Keys(rootTag)...) + tags := p.TagTreeApp.ListTagByPath(collx.MapKeys(rootTag)...) tagTrees := make(vo.TagTreeVOS, 0) for _, tag := range tags { tagPath := tag.CodePath @@ -91,7 +89,7 @@ func (p *TagTree) TagResources(rc *req.Ctx) { return tagResource.TagPath }) - tagPaths := maps.Keys(tagPath2Resource) + tagPaths := collx.MapKeys(tagPath2Resource) sort.Strings(tagPaths) rc.ResData = tagPaths } diff --git a/server/internal/tag/application/tag_tree.go b/server/internal/tag/application/tag_tree.go index 1af66c36..1fdadd6a 100644 --- a/server/internal/tag/application/tag_tree.go +++ b/server/internal/tag/application/tag_tree.go @@ -10,8 +10,6 @@ import ( "mayfly-go/pkg/errorx" "mayfly-go/pkg/utils/collx" "strings" - - "golang.org/x/exp/maps" ) type TagTree interface { @@ -54,8 +52,8 @@ type TagTree interface { type tagTreeAppImpl struct { base.AppImpl[*entity.TagTree, repository.TagTree] - TagTreeTeamRepo repository.TagTreeTeam `inject:""` - TagResourceApp TagResource `inject:""` + tagTreeTeamRepo repository.TagTreeTeam `inject:"TagTreeTeamRepo"` + tagResourceApp TagResource `inject:"TagResourceApp"` } // 注入TagTreeRepo @@ -75,7 +73,7 @@ func (p *tagTreeAppImpl) Save(ctx context.Context, tag *entity.TagTree) error { if err != nil { return errorx.NewBiz("父节点不存在") } - if p.TagResourceApp.CountByCond(&entity.TagResource{TagId: tag.Pid}) > 0 { + if p.tagResourceApp.CountByCond(&entity.TagResource{TagId: tag.Pid}) > 0 { return errorx.NewBiz("该父标签已关联资源, 无法添加子标签") } @@ -128,7 +126,7 @@ func (p *tagTreeAppImpl) GetAccountTagResources(accountId uint64, resourceType i tagResourceQuery.TagPath = tagPath tagResourceQuery.TagPathLikes = accountTagPaths - p.TagResourceApp.ListByQuery(tagResourceQuery, &tagResources) + p.tagResourceApp.ListByQuery(tagResourceQuery, &tagResources) return tagResources } @@ -139,7 +137,7 @@ func (p *tagTreeAppImpl) GetAccountResourceCodes(accountId uint64, resourceType return val.ResourceCode }) - return maps.Keys(code2Resource) + return collx.MapKeys(code2Resource) } func (p *tagTreeAppImpl) RelateResource(ctx context.Context, resourceCode string, resourceType int8, tagIds []uint64) error { @@ -148,14 +146,14 @@ func (p *tagTreeAppImpl) RelateResource(ctx context.Context, resourceCode string } // 如果tagIds为空数组,则为解绑该标签资源关联关系 if len(tagIds) == 0 { - return p.TagResourceApp.DeleteByCond(ctx, &entity.TagResource{ + return p.tagResourceApp.DeleteByCond(ctx, &entity.TagResource{ ResourceCode: resourceCode, ResourceType: resourceType, }) } var oldTagResources []*entity.TagResource - p.TagResourceApp.ListByQuery(&entity.TagResourceQuery{ResourceType: resourceType, ResourceCode: resourceCode}, &oldTagResources) + p.tagResourceApp.ListByQuery(&entity.TagResourceQuery{ResourceType: resourceType, ResourceCode: resourceCode}, &oldTagResources) var addTagIds, delTagIds []uint64 if len(oldTagResources) == 0 { @@ -181,7 +179,7 @@ func (p *tagTreeAppImpl) RelateResource(ctx context.Context, resourceCode string TagPath: tag.CodePath, }) } - if err := p.TagResourceApp.BatchInsert(ctx, addTagResource); err != nil { + if err := p.tagResourceApp.BatchInsert(ctx, addTagResource); err != nil { return err } } @@ -189,7 +187,7 @@ func (p *tagTreeAppImpl) RelateResource(ctx context.Context, resourceCode string if len(delTagIds) > 0 { for _, tagId := range delTagIds { cond := &entity.TagResource{ResourceCode: resourceCode, ResourceType: resourceType, TagId: tagId} - if err := p.TagResourceApp.DeleteByCond(ctx, cond); err != nil { + if err := p.tagResourceApp.DeleteByCond(ctx, cond); err != nil { return err } } @@ -200,7 +198,7 @@ func (p *tagTreeAppImpl) RelateResource(ctx context.Context, resourceCode string func (p *tagTreeAppImpl) ListTagPathByResource(resourceType int8, resourceCode string) []string { var trs []*entity.TagResource - p.TagResourceApp.ListByQuery(&entity.TagResourceQuery{ResourceType: resourceType, ResourceCode: resourceCode}, &trs) + p.tagResourceApp.ListByQuery(&entity.TagResourceQuery{ResourceType: resourceType, ResourceCode: resourceCode}, &trs) return collx.ArrayMap(trs, func(tr *entity.TagResource) string { return tr.TagPath }) @@ -213,7 +211,7 @@ func (p *tagTreeAppImpl) ListTagByPath(tagPaths ...string) []*entity.TagTree { } func (p *tagTreeAppImpl) ListTagByAccountId(accountId uint64) []string { - return p.TagTreeTeamRepo.SelectTagPathsByAccountId(accountId) + return p.tagTreeTeamRepo.SelectTagPathsByAccountId(accountId) } func (p *tagTreeAppImpl) CanAccess(accountId uint64, tagPath ...string) error { @@ -243,7 +241,7 @@ func (p *tagTreeAppImpl) Delete(ctx context.Context, id uint64) error { return errorx.NewBiz("您无权删除该标签") } - if p.TagResourceApp.CountByCond(&entity.TagResource{TagId: id}) > 0 { + if p.tagResourceApp.CountByCond(&entity.TagResource{TagId: id}) > 0 { return errorx.NewBiz("请先移除该标签关联的资源") } @@ -251,6 +249,6 @@ func (p *tagTreeAppImpl) Delete(ctx context.Context, id uint64) error { return p.DeleteById(ctx, id) }, func(ctx context.Context) error { // 删除该标签关联的团队信息 - return p.TagTreeTeamRepo.DeleteByCond(ctx, &entity.TagTreeTeam{TagId: id}) + return p.tagTreeTeamRepo.DeleteByCond(ctx, &entity.TagTreeTeam{TagId: id}) }) } diff --git a/server/internal/tag/application/team.go b/server/internal/tag/application/team.go index d51b52e7..56e8270d 100644 --- a/server/internal/tag/application/team.go +++ b/server/internal/tag/application/team.go @@ -39,32 +39,32 @@ type Team interface { } type teamAppImpl struct { - TeamRepo repository.Team `inject:""` - TeamMemberRepo repository.TeamMember `inject:""` - TagTreeTeamRepo repository.TagTreeTeam `inject:""` + teamRepo repository.Team `inject:"TeamRepo"` + teamMemberRepo repository.TeamMember `inject:"TeamMemberRepo"` + tagTreeTeamRepo repository.TagTreeTeam `inject:"TagTreeTeamRepo"` } func (p *teamAppImpl) GetPageList(condition *entity.TeamQuery, pageParam *model.PageParam, toEntity any, orderBy ...string) (*model.PageResult[any], error) { - return p.TeamRepo.GetPageList(condition, pageParam, toEntity, orderBy...) + return p.teamRepo.GetPageList(condition, pageParam, toEntity, orderBy...) } func (p *teamAppImpl) Save(ctx context.Context, team *entity.Team) error { if team.Id == 0 { - return p.TeamRepo.Insert(ctx, team) + return p.teamRepo.Insert(ctx, team) } - return p.TeamRepo.UpdateById(ctx, team) + return p.teamRepo.UpdateById(ctx, team) } func (p *teamAppImpl) Delete(ctx context.Context, id uint64) error { return gormx.Tx( func(db *gorm.DB) error { - return p.TeamRepo.DeleteByIdWithDb(ctx, db, id) + return p.teamRepo.DeleteByIdWithDb(ctx, db, id) }, func(db *gorm.DB) error { - return p.TeamMemberRepo.DeleteByCondWithDb(ctx, db, &entity.TeamMember{TeamId: id}) + return p.teamMemberRepo.DeleteByCondWithDb(ctx, db, &entity.TeamMember{TeamId: id}) }, func(db *gorm.DB) error { - return p.TagTreeTeamRepo.DeleteByCondWithDb(ctx, db, &entity.TagTreeTeam{TeamId: id}) + return p.tagTreeTeamRepo.DeleteByCondWithDb(ctx, db, &entity.TagTreeTeam{TeamId: id}) }, ) } @@ -72,30 +72,30 @@ func (p *teamAppImpl) Delete(ctx context.Context, id uint64) error { // --------------- 团队成员相关接口 --------------- func (p *teamAppImpl) GetMemberPage(condition *entity.TeamMember, pageParam *model.PageParam, toEntity any) (*model.PageResult[any], error) { - return p.TeamMemberRepo.GetPageList(condition, pageParam, toEntity) + return p.teamMemberRepo.GetPageList(condition, pageParam, toEntity) } // 保存团队成员信息 func (p *teamAppImpl) SaveMember(ctx context.Context, teamMember *entity.TeamMember) { teamMember.Id = 0 - biz.IsTrue(!p.TeamMemberRepo.IsExist(teamMember.TeamId, teamMember.AccountId), "该成员已存在") - p.TeamMemberRepo.Insert(ctx, teamMember) + biz.IsTrue(!p.teamMemberRepo.IsExist(teamMember.TeamId, teamMember.AccountId), "该成员已存在") + p.teamMemberRepo.Insert(ctx, teamMember) } // 删除团队成员信息 func (p *teamAppImpl) DeleteMember(ctx context.Context, teamId, accountId uint64) { - p.TeamMemberRepo.DeleteByCond(ctx, &entity.TeamMember{TeamId: teamId, AccountId: accountId}) + p.teamMemberRepo.DeleteByCond(ctx, &entity.TeamMember{TeamId: teamId, AccountId: accountId}) } func (p *teamAppImpl) IsExistMember(teamId, accounId uint64) bool { - return p.TeamMemberRepo.IsExist(teamId, accounId) + return p.teamMemberRepo.IsExist(teamId, accounId) } //--------------- 关联标签相关接口 --------------- func (p *teamAppImpl) ListTagIds(teamId uint64) []uint64 { tags := &[]entity.TagTreeTeam{} - p.TagTreeTeamRepo.ListByCondOrder(&entity.TagTreeTeam{TeamId: teamId}, tags) + p.tagTreeTeamRepo.ListByCondOrder(&entity.TagTreeTeam{TeamId: teamId}, tags) ids := make([]uint64, 0) for _, v := range *tags { ids = append(ids, v.TagId) @@ -106,10 +106,10 @@ func (p *teamAppImpl) ListTagIds(teamId uint64) []uint64 { // 保存关联项目信息 func (p *teamAppImpl) SaveTag(ctx context.Context, tagTreeTeam *entity.TagTreeTeam) error { tagTreeTeam.Id = 0 - return p.TagTreeTeamRepo.Insert(ctx, tagTreeTeam) + return p.tagTreeTeamRepo.Insert(ctx, tagTreeTeam) } // 删除关联项目信息 func (p *teamAppImpl) DeleteTag(ctx context.Context, teamId, tagId uint64) error { - return p.TagTreeTeamRepo.DeleteByCond(ctx, &entity.TagTreeTeam{TeamId: teamId, TagId: tagId}) + return p.tagTreeTeamRepo.DeleteByCond(ctx, &entity.TagTreeTeam{TeamId: teamId, TagId: tagId}) } diff --git a/server/pkg/config/config.go b/server/pkg/config/config.go index 370fd41f..60ac8f00 100644 --- a/server/pkg/config/config.go +++ b/server/pkg/config/config.go @@ -66,6 +66,9 @@ func (c *Config) IfBlankDefaultValue() { AddSource: c.Log.AddSource, Filename: c.Log.File.Name, Filepath: c.Log.File.Path, + MaxSize: c.Log.File.MaxSize, + MaxAge: c.Log.File.MaxAge, + Compress: c.Log.File.Compress, }) c.Server.Default() diff --git a/server/pkg/config/log.go b/server/pkg/config/log.go index 5d69f858..161f667a 100644 --- a/server/pkg/config/log.go +++ b/server/pkg/config/log.go @@ -2,7 +2,6 @@ package config import ( "mayfly-go/pkg/logx" - "path" ) type Log struct { @@ -26,23 +25,9 @@ func (l *Log) Default() { } type LogFile struct { - Name string `yaml:"name"` - Path string `yaml:"path"` -} - -// 获取完整路径文件名 -func (l *LogFile) GetFilename() string { - var filepath, filename string - if fp := l.Path; fp == "" { - filepath = "./" - } else { - filepath = fp - } - if fn := l.Name; fn == "" { - filename = "default.log" - } else { - filename = fn - } - - return path.Join(filepath, filename) + Name string `yaml:"name"` + Path string `yaml:"path"` + MaxSize int `yaml:"max-size"` + MaxAge int `yaml:"max-age"` + Compress bool `yaml:"compress"` } diff --git a/server/pkg/config/mysql.go b/server/pkg/config/mysql.go index 3a9d04e1..5c06ca81 100644 --- a/server/pkg/config/mysql.go +++ b/server/pkg/config/mysql.go @@ -18,7 +18,7 @@ type Mysql struct { func (m *Mysql) Default() { if m.Host == "" { m.Host = "localhost:3306" - logx.Warnf("未配置mysql.host, 默认值: %s", m.Host) + logx.Warnf("[使用sqlite可忽略]未配置mysql.host, 默认值: %s", m.Host) } if m.Config == "" { m.Config = "charset=utf8&loc=Local&parseTime=true" diff --git a/server/pkg/config/sqlite.go b/server/pkg/config/sqlite.go index cfaee761..a550b8bc 100644 --- a/server/pkg/config/sqlite.go +++ b/server/pkg/config/sqlite.go @@ -11,7 +11,7 @@ type Sqlite struct { func (m *Sqlite) Default() { if m.Path == "" { m.Path = "./mayfly-go.sqlite" - logx.Warnf("未配置sqlite.path, 默认值: %s", m.Path) + logx.Warnf("[使用mysql可忽略]未配置sqlite.path, 默认值: %s", m.Path) } if m.MaxIdleConns == 0 { m.MaxIdleConns = 5 diff --git a/server/pkg/ioc/ioc.go b/server/pkg/ioc/ioc.go index 05099dfb..d7f7d2c8 100644 --- a/server/pkg/ioc/ioc.go +++ b/server/pkg/ioc/ioc.go @@ -109,11 +109,15 @@ func (c *Container) injectWithField(objValue reflect.Value) error { } fieldValue := objValue.Field(i) - fieldPtrValue := reflect.NewAt(fieldValue.Type(), fieldValue.Addr().UnsafePointer()) - fieldValue = fieldPtrValue.Elem() if !fieldValue.IsValid() || !fieldValue.CanSet() { - return fmt.Errorf("%s error: 字段无效或为不可导出类型", injectInfo) + // 不可导出变量处理 + fieldPtrValue := reflect.NewAt(fieldValue.Type(), fieldValue.Addr().UnsafePointer()) + fieldValue = fieldPtrValue.Elem() + if !fieldValue.IsValid() || !fieldValue.CanSet() { + return fmt.Errorf("%s error: 字段无效或为不可导出类型", injectInfo) + } } + fieldValue.Set(reflect.ValueOf(component)) } diff --git a/server/pkg/logx/config.go b/server/pkg/logx/config.go index 3e4bea50..e1e85231 100644 --- a/server/pkg/logx/config.go +++ b/server/pkg/logx/config.go @@ -1,20 +1,25 @@ package logx import ( - "fmt" "io" "log/slog" "os" "path" "strings" + + "gopkg.in/natefinch/lumberjack.v2" ) type Config struct { Level string Type string // 日志类型;text、json AddSource bool // 是否记录调用方法 - Filename string - Filepath string + + Filename string // 日志文件名 + Filepath string // 日志路径 + MaxSize int // 日志文件的最大大小(以兆字节为单位)。当日志文件大小达到该值时,将触发切割操作,默认为 100 兆字节 + MaxAge int // 根据文件名中的时间戳,设置保留旧日志文件的最大天数。一天被定义为 24 小时 + Compress bool // 是否使用 gzip 压缩方式压缩轮转后的日志文件 writer io.Writer } @@ -24,15 +29,18 @@ func (c *Config) GetLogOut() io.Writer { if c.writer != nil { return c.writer } - writer := os.Stdout + var writer io.Writer + writer = os.Stdout // 根据配置文件设置日志级别 if c.Filepath != "" && c.Filename != "" { // 写入文件 - file, err := os.OpenFile(path.Join(c.Filepath, c.Filename), os.O_CREATE|os.O_APPEND|os.O_WRONLY, os.ModeAppend|0666) - if err != nil { - panic(fmt.Sprintf("创建日志文件失败: %s", err.Error())) + writer = &lumberjack.Logger{ + Filename: path.Join(c.Filepath, c.Filename), + MaxSize: c.MaxSize, + MaxAge: c.MaxAge, + Compress: c.Compress, + LocalTime: true, } - writer = file } c.writer = writer diff --git a/server/pkg/utils/collx/map.go b/server/pkg/utils/collx/map.go index 5916df4b..2814b3dc 100644 --- a/server/pkg/utils/collx/map.go +++ b/server/pkg/utils/collx/map.go @@ -22,3 +22,23 @@ func Kvs(elements ...any) M { } return myMap } + +// Keys returns the keys of the map m. +// The keys will be in an indeterminate order. +func MapKeys[M ~map[K]V, K comparable, V any](m M) []K { + r := make([]K, 0, len(m)) + for k := range m { + r = append(r, k) + } + return r +} + +// Values returns the values of the map m. +// The values will be in an indeterminate order. +func MapValues[M ~map[K]V, K comparable, V any](m M) []V { + r := make([]V, 0, len(m)) + for _, v := range m { + r = append(r, v) + } + return r +} diff --git a/server/resources/data/mayfly-go.sqlite b/server/resources/data/mayfly-go.sqlite index 292dcc643cab46bee215d0f146874b1bb0628ea1..407fc6fabd102239b7c4ac8ab8d08959391ee7c9 100644 GIT binary patch delta 66 zcmV-I0KNZ!;0=J_4UiiF2$38^1qc8xV*!C=g=7J>WCEZ+2mlZO01oyJ_OlTX><$6} Y3YYp$0;~i8003Hts!sy9s!sz}Adoi`cmMzZ delta 68 zcmV-K0K5Ny;0=J_4UiiF29X>?1qJ{vX6k`tg=7J>WCEZ+2m%iF01u`P_OlTX>J9{f aEdmUe`c49@1XuwJ0Eeni0=KG916CjbdlkX} diff --git a/server/resources/script/sql/v1.7/v1.7.1.sql b/server/resources/script/sql/v1.7/v1.7.1.sql index 6c9e848d..d70c3891 100644 --- a/server/resources/script/sql/v1.7/v1.7.1.sql +++ b/server/resources/script/sql/v1.7/v1.7.1.sql @@ -1,7 +1,3 @@ ALTER TABLE `t_db_instance` MODIFY `port` int (8) NULL comment '数据库端口', MODIFY `username` varchar (255) NULL comment '数据库用户名'; - -INSERT INTO `mayfly-go`.`t_sys_resource` (`id`, `pid`, `ui_path`, `type`, `status`, `name`, `code`, `weight`, `meta`, `creator_id`, `creator`, `modifier_id`, `modifier`, `create_time`, `update_time`, `is_deleted`, `delete_time`) - VALUES (161, 49, 'dbms23ax/xleaiec2/3NUXQFIO/', 2, 1, '数据库备份', 'db:backup', 1705973876, 'null', 1, 'admin', 1, 'admin', '2024-01-23 09:37:56', '2024-01-23 09:37:56', 0, NULL), - (160, 49, 'dbms23ax/xleaiec2/ghErkTdb/', 2, 1, '数据库恢复', 'db:restore', 1705973909, 'null', 1, 'admin', 1, 'admin', '2024-01-23 09:38:29', '2024-01-23 09:38:29', 0, NULL); diff --git a/server/resources/script/sql/v1.7/v1.7.2.sql b/server/resources/script/sql/v1.7/v1.7.2.sql new file mode 100644 index 00000000..f67f65f0 --- /dev/null +++ b/server/resources/script/sql/v1.7/v1.7.2.sql @@ -0,0 +1,3 @@ +INSERT INTO `t_sys_resource` (`id`, `pid`, `ui_path`, `type`, `status`, `name`, `code`, `weight`, `meta`, `creator_id`, `creator`, `modifier_id`, `modifier`, `create_time`, `update_time`, `is_deleted`, `delete_time`) + VALUES (161, 49, 'dbms23ax/xleaiec2/3NUXQFIO/', 2, 1, '数据库备份', 'db:backup', 1705973876, 'null', 1, 'admin', 1, 'admin', '2024-01-23 09:37:56', '2024-01-23 09:37:56', 0, NULL), + (160, 49, 'dbms23ax/xleaiec2/ghErkTdb/', 2, 1, '数据库恢复', 'db:restore', 1705973909, 'null', 1, 'admin', 1, 'admin', '2024-01-23 09:38:29', '2024-01-23 09:38:29', 0, NULL);