Compare commits
56 Commits
feat-db-ma
...
release
| Author | SHA1 | Date |
|---|---|---|
|
|
07a5c81fb2 | |
|
|
5525fe6f2f | |
|
|
e4e12324fe | |
|
|
4cbb9b1201 | |
|
|
832443e1d2 | |
|
|
0c5cb83f69 | |
|
|
1573353f49 | |
|
|
0bf94a0c2b | |
|
|
66f17ef709 | |
|
|
98f9424e77 | |
|
|
80352e8601 | |
|
|
99dda61a84 | |
|
|
08c0752803 | |
|
|
ed2b936bf2 | |
|
|
6d7e6c26fc | |
|
|
3d0253523b | |
|
|
76b6ec7d74 | |
|
|
4bc256aba4 | |
|
|
6481b18fcd | |
|
|
63ea13bbde | |
|
|
dda5035c7c | |
|
|
7be4aeb90e | |
|
|
00aa3b5b7b | |
|
|
dae8a96478 | |
|
|
fc0218e754 | |
|
|
770cde41bd | |
|
|
da70405ab3 | |
|
|
c75dd8b95e | |
|
|
1a2661bf41 | |
|
|
106e27f457 | |
|
|
345d120460 | |
|
|
0edba050c3 | |
|
|
d02cceb775 | |
|
|
f334668e4b | |
|
|
b4f721060f | |
|
|
c0b8c7ba63 | |
|
|
2f8d80184b | |
|
|
ff3e032d6d | |
|
|
defbafd9d6 | |
|
|
27c5b3cd3c | |
|
|
5e184badca | |
|
|
b3492e6826 | |
|
|
44b74e468b | |
|
|
4e2f319229 | |
|
|
94e5c784c0 | |
|
|
b1bb1cb734 | |
|
|
e2ebdc0621 | |
|
|
f0e025bec5 | |
|
|
6e5ee4f0e2 | |
|
|
4592681978 | |
|
|
80ab607432 | |
|
|
1ff1347187 | |
|
|
1244feb7de | |
|
|
6c835e371a | |
|
|
1cfb517fc9 | |
|
|
29c05b0af7 |
|
|
@ -0,0 +1,6 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="Ask2AgentMigrationStateService">
|
||||
<option name="migrationStatus" value="COMPLETED" />
|
||||
</component>
|
||||
</project>
|
||||
|
|
@ -0,0 +1,35 @@
|
|||
version: '1.0'
|
||||
name: pipeline-20250906-release
|
||||
displayName: pipeline-20250906-release
|
||||
triggers:
|
||||
trigger: auto
|
||||
push:
|
||||
branches:
|
||||
precise:
|
||||
- release
|
||||
stages:
|
||||
- name: stage-4863fcf5
|
||||
displayName: 未命名
|
||||
strategy: naturally
|
||||
trigger: auto
|
||||
executor: []
|
||||
steps:
|
||||
- step: build@golang
|
||||
name: build_golang
|
||||
displayName: Golang 构建
|
||||
golangVersion: '1.24'
|
||||
commands:
|
||||
- '# 默认使用goproxy.cn'
|
||||
- export GOPROXY=https://goproxy.cn
|
||||
- '# 输入你的构建命令'
|
||||
- go get
|
||||
- go build
|
||||
artifacts:
|
||||
- name: BUILD_ARTIFACT
|
||||
path:
|
||||
- ./
|
||||
caches:
|
||||
- /go/pkg/mod
|
||||
notify: []
|
||||
strategy:
|
||||
retry: '0'
|
||||
50
dao/cid.go
50
dao/cid.go
|
|
@ -3,16 +3,20 @@ package dao
|
|||
import (
|
||||
"fmt"
|
||||
"gorm.io/gorm"
|
||||
"time"
|
||||
"videoplayer/proto"
|
||||
)
|
||||
|
||||
type CID struct {
|
||||
gorm.Model
|
||||
Auth_id int `gorm:"column:auth_id"`
|
||||
Name string `gorm:"column:name"`
|
||||
Url string `gorm:"column:url"`
|
||||
Time int `gorm:"column:time"` // 定时任务,单位秒,大于0表示定时任务
|
||||
Script string `gorm:"column:script"`
|
||||
Token string `gorm:"column:token"` // 用于外部回调
|
||||
Auth_id int `gorm:"column:auth_id"`
|
||||
Name string `gorm:"column:name"`
|
||||
Url string `gorm:"column:url"`
|
||||
Time int `gorm:"column:time"` // 定时任务,单位秒,大于0表示定时任务
|
||||
LastSuccess time.Time `gorm:"column:last_success" json:"last_success"`
|
||||
LastFail time.Time `gorm:"column:last_fail" json:"last_fail"`
|
||||
Script string `gorm:"column:script"`
|
||||
Token string `gorm:"column:token"` // 用于外部回调
|
||||
}
|
||||
|
||||
type CIDRunLog struct {
|
||||
|
|
@ -25,6 +29,28 @@ type CIDRunLog struct {
|
|||
Error string `gorm:"column:error"`
|
||||
}
|
||||
|
||||
func GetDB() *gorm.DB {
|
||||
var db *gorm.DB
|
||||
if proto.Config.SERVER_SQL_LOG {
|
||||
db = DB.Debug()
|
||||
} else {
|
||||
db = DB
|
||||
}
|
||||
return db
|
||||
}
|
||||
|
||||
func UpdateCIDLastSuccessTime(id int) error {
|
||||
db := GetDB()
|
||||
res := db.Exec("UPDATE c_ids SET last_success = now() where id = ?", id)
|
||||
return res.Error
|
||||
}
|
||||
|
||||
func UpdateCIDLastFailureTime(id int) error {
|
||||
db := GetDB()
|
||||
res := db.Exec("UPDATE c_ids SET last_fail = now() where id = ?", id)
|
||||
return res.Error
|
||||
}
|
||||
|
||||
// CreateCID 创建持续集成、部署
|
||||
func CreateCID(name, url, script, token string, time, auth_id int) uint {
|
||||
cid := CID{Name: name, Url: url, Script: script, Token: token, Auth_id: auth_id, Time: time}
|
||||
|
|
@ -54,7 +80,7 @@ func FindCIDByID(id, auth_id int) CID {
|
|||
// FindCIDByAuthID 查找持续集成、部署
|
||||
func FindCIDByAuthID(auth_id int) []CID {
|
||||
var cids []CID
|
||||
DB.Where("auth_id = ?", auth_id).Find(&cids)
|
||||
DB.Where("auth_id = ?", auth_id).Order("created_at").Find(&cids)
|
||||
return cids
|
||||
}
|
||||
|
||||
|
|
@ -121,3 +147,13 @@ func FindCIDByCID(id uint) CID {
|
|||
DB.Where("id = ? ", id).First(&cid)
|
||||
return cid
|
||||
}
|
||||
|
||||
func UpdateLastSuccessByID(id int, time time.Time) error {
|
||||
res := DB.Where("id = ?", id).Update("last_success", time)
|
||||
return res.Error
|
||||
}
|
||||
|
||||
func UpdateLastFailByID(id int, time time.Time) error {
|
||||
res := DB.Where("id = ?", id).Update("last_fail", time)
|
||||
return res.Error
|
||||
}
|
||||
|
|
|
|||
31
dao/db.go
31
dao/db.go
|
|
@ -4,13 +4,18 @@ import (
|
|||
"fmt"
|
||||
"gorm.io/driver/mysql"
|
||||
"gorm.io/driver/postgres"
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
"log"
|
||||
"sync"
|
||||
"videoplayer/proto"
|
||||
)
|
||||
|
||||
var DB *gorm.DB
|
||||
|
||||
var DBMMap = map[uint]*proto.DBValue{}
|
||||
var DBMMapRWMutex = &sync.RWMutex{} //dbm日志
|
||||
|
||||
func Init() error {
|
||||
var db *gorm.DB
|
||||
var err error
|
||||
|
|
@ -21,17 +26,20 @@ func Init() error {
|
|||
} else if proto.Config.DB == 1 {
|
||||
dsn = proto.Config.PG_DSN
|
||||
db, err = gorm.Open(postgres.Open(dsn), &gorm.Config{})
|
||||
} else if proto.Config.DB == 2 { //sqlite
|
||||
dsn = proto.Config.SQLITE_FILE
|
||||
db, err = gorm.Open(sqlite.Open(dsn), &gorm.Config{})
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
panic("failed to connect database")
|
||||
return err
|
||||
}
|
||||
err = db.AutoMigrate(&User{})
|
||||
if err != nil {
|
||||
fmt.Println("user table:", err)
|
||||
return err
|
||||
} // 自动迁移,创建表,如果表已经存在,会自动更新表结构,不会删除表,只会创建不存在的表
|
||||
//err = db.AutoMigrate(&User{})
|
||||
//if err != nil {
|
||||
// fmt.Println("user table:", err)
|
||||
// return err
|
||||
//}
|
||||
err = db.AutoMigrate(&Video{})
|
||||
if err != nil {
|
||||
fmt.Println("video table:", err)
|
||||
|
|
@ -114,6 +122,19 @@ func Init() error {
|
|||
log.Println("sqlrunhistory table:", err)
|
||||
}
|
||||
|
||||
err = db.AutoMigrate(&proto.DNSServer{})
|
||||
if err != nil {
|
||||
log.Println("dnsserver table:", err)
|
||||
}
|
||||
err = db.AutoMigrate(&proto.DNSZone{})
|
||||
if err != nil {
|
||||
log.Println("dnszone table:", err)
|
||||
}
|
||||
err = db.AutoMigrate(&proto.DNSRecord{})
|
||||
if err != nil {
|
||||
log.Println("dnsrecord table:", err)
|
||||
}
|
||||
|
||||
DB = db
|
||||
return err
|
||||
}
|
||||
|
|
|
|||
115
dao/dbm.go
115
dao/dbm.go
|
|
@ -111,6 +111,17 @@ func DeleteDBManageByID(id uint) error {
|
|||
return res.Error
|
||||
}
|
||||
|
||||
func DeleteDBManageByUserID(id uint) error {
|
||||
var db2 *gorm.DB
|
||||
if proto.Config.SERVER_SQL_LOG {
|
||||
db2 = DB.Debug()
|
||||
} else {
|
||||
db2 = DB
|
||||
}
|
||||
res := db2.Where("user_id = ?", id).Delete(&proto.DBManage{})
|
||||
return res.Error
|
||||
}
|
||||
|
||||
func FindDBRunHistoryByID(id uint) (proto.SQLRunHistory, error) {
|
||||
var history proto.SQLRunHistory
|
||||
var db2 *gorm.DB
|
||||
|
|
@ -125,7 +136,6 @@ func FindDBRunHistoryByID(id uint) (proto.SQLRunHistory, error) {
|
|||
}
|
||||
return history, nil
|
||||
}
|
||||
|
||||
func FindDBRunHistoryByAuthID(auth_id int) ([]proto.SQLRunHistory, error) {
|
||||
var histories []proto.SQLRunHistory
|
||||
var db2 *gorm.DB
|
||||
|
|
@ -134,13 +144,50 @@ func FindDBRunHistoryByAuthID(auth_id int) ([]proto.SQLRunHistory, error) {
|
|||
} else {
|
||||
db2 = DB
|
||||
}
|
||||
res := db2.Where("user_id = ?", auth_id).Find(&histories)
|
||||
res := db2.Where("user_id = ?", auth_id).Order("created_at DESC").Limit(100).Find(&histories)
|
||||
if res.Error != nil {
|
||||
return nil, res.Error
|
||||
}
|
||||
return histories, nil
|
||||
}
|
||||
|
||||
func FindDBRunHistoryByAuthIDAndDbId(auth_id int, db_id uint) ([]proto.SQLRunHistory, error) {
|
||||
var histories []proto.SQLRunHistory
|
||||
var db2 *gorm.DB
|
||||
if proto.Config.SERVER_SQL_LOG {
|
||||
db2 = DB.Debug()
|
||||
} else {
|
||||
db2 = DB
|
||||
}
|
||||
res := db2.Where("user_id = ? and db_id = ?", auth_id, db_id).Order("created_at DESC").Limit(100).Find(&histories)
|
||||
if res.Error != nil {
|
||||
return nil, res.Error
|
||||
}
|
||||
return histories, nil
|
||||
}
|
||||
|
||||
func DelSQLRunHistoryByID(id uint) error {
|
||||
var db2 *gorm.DB
|
||||
if proto.Config.SERVER_SQL_LOG {
|
||||
db2 = DB.Debug()
|
||||
} else {
|
||||
db2 = DB
|
||||
}
|
||||
res := db2.Where("id = ?", id).Delete(&proto.SQLRunHistory{})
|
||||
return res.Error
|
||||
}
|
||||
|
||||
func DelSQLRunHistoryByAuthID(auth_id int) error {
|
||||
var db2 *gorm.DB
|
||||
if proto.Config.SERVER_SQL_LOG {
|
||||
db2 = DB.Debug()
|
||||
} else {
|
||||
db2 = DB
|
||||
}
|
||||
res := db2.Where("user_id = ?", auth_id).Delete(&proto.SQLRunHistory{})
|
||||
return res.Error
|
||||
}
|
||||
|
||||
func FindAllSQLRunHistory() ([]proto.SQLRunHistory, error) {
|
||||
var histories []proto.SQLRunHistory
|
||||
var db2 *gorm.DB
|
||||
|
|
@ -149,9 +196,71 @@ func FindAllSQLRunHistory() ([]proto.SQLRunHistory, error) {
|
|||
} else {
|
||||
db2 = DB
|
||||
}
|
||||
res := db2.Find(&histories)
|
||||
res := db2.Order("created_at DESC").Limit(1000).Find(&histories)
|
||||
if res.Error != nil {
|
||||
return nil, res.Error
|
||||
}
|
||||
return histories, nil
|
||||
}
|
||||
|
||||
func RunSQLWithOrder(sql string, db_ *gorm.DB) (result proto.SQLResult, err error) {
|
||||
var db2 *gorm.DB
|
||||
// 保留 Debug 模式
|
||||
if proto.Config.SERVER_SQL_LOG {
|
||||
db2 = db_.Debug()
|
||||
} else {
|
||||
db2 = db_
|
||||
}
|
||||
|
||||
// 执行 SQL 并获取底层 Rows 对象
|
||||
rows, err := db2.Raw(sql).Rows()
|
||||
if err != nil {
|
||||
return result, err
|
||||
}
|
||||
defer rows.Close() // 确保关闭 Rows
|
||||
|
||||
// 获取列名顺序(关键:这里的顺序与 SQL 查询的列顺序一致)
|
||||
columns, err := rows.Columns()
|
||||
if err != nil {
|
||||
return result, err
|
||||
}
|
||||
for _, col := range columns {
|
||||
result.Columns = append(result.Columns, proto.SQLResultColumnsValue{Prop: col, Label: col})
|
||||
}
|
||||
|
||||
// 遍历每行数据
|
||||
for rows.Next() {
|
||||
// 准备接收每行数据的容器(按列顺序)
|
||||
values := make([]interface{}, len(columns))
|
||||
valuePtrs := make([]interface{}, len(columns)) // 用于 Scan 的指针切片
|
||||
|
||||
// 为每个列绑定指针(Scan 要求传入指针)
|
||||
for i := range values {
|
||||
valuePtrs[i] = &values[i]
|
||||
}
|
||||
|
||||
// 扫描当前行数据到指针切片
|
||||
if err2 := rows.Scan(valuePtrs...); err2 != nil {
|
||||
return result, err2
|
||||
}
|
||||
|
||||
// 将当前行数据存入 map(便于按列名访问)
|
||||
rowMap := make(map[string]interface{})
|
||||
for i, col := range columns {
|
||||
val := values[i]
|
||||
if b, ok := val.([]byte); ok {
|
||||
rowMap[col] = string(b)
|
||||
} else {
|
||||
rowMap[col] = values[i]
|
||||
}
|
||||
}
|
||||
result.Rows = append(result.Rows, rowMap)
|
||||
}
|
||||
|
||||
// 检查遍历过程中是否有错误
|
||||
if err = rows.Err(); err != nil {
|
||||
return result, err
|
||||
}
|
||||
|
||||
return result, nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,289 @@
|
|||
package dao
|
||||
|
||||
import (
|
||||
"videoplayer/proto"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
// ==================== DNSServer 相关操作 ====================
|
||||
|
||||
func CreateDNSServer(server proto.DNSServer) (uint, error) {
|
||||
var db2 *gorm.DB
|
||||
if proto.Config.SERVER_SQL_LOG {
|
||||
db2 = DB.Debug()
|
||||
} else {
|
||||
db2 = DB
|
||||
}
|
||||
res := db2.Create(&server)
|
||||
if res.Error != nil {
|
||||
return 0, res.Error
|
||||
}
|
||||
return server.ID, nil
|
||||
}
|
||||
|
||||
func FindDNSServerByID(id uint) (proto.DNSServer, error) {
|
||||
var server proto.DNSServer
|
||||
var db2 *gorm.DB
|
||||
if proto.Config.SERVER_SQL_LOG {
|
||||
db2 = DB.Debug()
|
||||
} else {
|
||||
db2 = DB
|
||||
}
|
||||
res := db2.Where("id = ?", id).First(&server)
|
||||
if res.Error != nil {
|
||||
return proto.DNSServer{}, res.Error
|
||||
}
|
||||
return server, nil
|
||||
}
|
||||
|
||||
func FindDNSServerByUserID(userID uint) ([]proto.DNSServer, error) {
|
||||
var servers []proto.DNSServer
|
||||
var db2 *gorm.DB
|
||||
if proto.Config.SERVER_SQL_LOG {
|
||||
db2 = DB.Debug()
|
||||
} else {
|
||||
db2 = DB
|
||||
}
|
||||
res := db2.Where("user_id = ?", userID).Find(&servers)
|
||||
if res.Error != nil {
|
||||
return nil, res.Error
|
||||
}
|
||||
return servers, nil
|
||||
}
|
||||
|
||||
func FindAllDNSServer() ([]proto.DNSServer, error) {
|
||||
var servers []proto.DNSServer
|
||||
var db2 *gorm.DB
|
||||
if proto.Config.SERVER_SQL_LOG {
|
||||
db2 = DB.Debug()
|
||||
} else {
|
||||
db2 = DB
|
||||
}
|
||||
res := db2.Find(&servers)
|
||||
if res.Error != nil {
|
||||
return nil, res.Error
|
||||
}
|
||||
return servers, nil
|
||||
}
|
||||
|
||||
func UpdateDNSServer(id uint, server *proto.DNSServer) error {
|
||||
var db2 *gorm.DB
|
||||
if proto.Config.SERVER_SQL_LOG {
|
||||
db2 = DB.Debug()
|
||||
} else {
|
||||
db2 = DB
|
||||
}
|
||||
res := db2.Model(&proto.DNSServer{}).Where("id = ?", id).Updates(server)
|
||||
return res.Error
|
||||
}
|
||||
|
||||
func DeleteDNSServerByID(id uint) error {
|
||||
var db2 *gorm.DB
|
||||
if proto.Config.SERVER_SQL_LOG {
|
||||
db2 = DB.Debug()
|
||||
} else {
|
||||
db2 = DB
|
||||
}
|
||||
res := db2.Where("id = ?", id).Delete(&proto.DNSServer{})
|
||||
return res.Error
|
||||
}
|
||||
|
||||
func DeleteDNSServerByUserID(userID uint) error {
|
||||
var db2 *gorm.DB
|
||||
if proto.Config.SERVER_SQL_LOG {
|
||||
db2 = DB.Debug()
|
||||
} else {
|
||||
db2 = DB
|
||||
}
|
||||
res := db2.Where("user_id = ?", userID).Delete(&proto.DNSServer{})
|
||||
return res.Error
|
||||
}
|
||||
|
||||
// ==================== DNSZone 相关操作 ====================
|
||||
|
||||
func CreateDNSZone(zone proto.DNSZone) (uint, error) {
|
||||
var db2 *gorm.DB
|
||||
if proto.Config.SERVER_SQL_LOG {
|
||||
db2 = DB.Debug()
|
||||
} else {
|
||||
db2 = DB
|
||||
}
|
||||
res := db2.Create(&zone)
|
||||
if res.Error != nil {
|
||||
return 0, res.Error
|
||||
}
|
||||
return zone.ID, nil
|
||||
}
|
||||
|
||||
func FindDNSZoneByID(id uint) (proto.DNSZone, error) {
|
||||
var zone proto.DNSZone
|
||||
var db2 *gorm.DB
|
||||
if proto.Config.SERVER_SQL_LOG {
|
||||
db2 = DB.Debug()
|
||||
} else {
|
||||
db2 = DB
|
||||
}
|
||||
res := db2.Where("id = ?", id).First(&zone)
|
||||
if res.Error != nil {
|
||||
return proto.DNSZone{}, res.Error
|
||||
}
|
||||
return zone, nil
|
||||
}
|
||||
|
||||
func FindDNSZoneByServerID(serverID uint) ([]proto.DNSZone, error) {
|
||||
var zones []proto.DNSZone
|
||||
var db2 *gorm.DB
|
||||
if proto.Config.SERVER_SQL_LOG {
|
||||
db2 = DB.Debug()
|
||||
} else {
|
||||
db2 = DB
|
||||
}
|
||||
res := db2.Where("server_id = ?", serverID).Find(&zones)
|
||||
if res.Error != nil {
|
||||
return nil, res.Error
|
||||
}
|
||||
return zones, nil
|
||||
}
|
||||
|
||||
func FindAllDNSZone() ([]proto.DNSZone, error) {
|
||||
var zones []proto.DNSZone
|
||||
var db2 *gorm.DB
|
||||
if proto.Config.SERVER_SQL_LOG {
|
||||
db2 = DB.Debug()
|
||||
} else {
|
||||
db2 = DB
|
||||
}
|
||||
res := db2.Find(&zones)
|
||||
if res.Error != nil {
|
||||
return nil, res.Error
|
||||
}
|
||||
return zones, nil
|
||||
}
|
||||
|
||||
func UpdateDNSZone(id uint, zone *proto.DNSZone) error {
|
||||
var db2 *gorm.DB
|
||||
if proto.Config.SERVER_SQL_LOG {
|
||||
db2 = DB.Debug()
|
||||
} else {
|
||||
db2 = DB
|
||||
}
|
||||
res := db2.Model(&proto.DNSZone{}).Where("id = ?", id).Updates(zone)
|
||||
return res.Error
|
||||
}
|
||||
|
||||
func DeleteDNSZoneByID(id uint) error {
|
||||
var db2 *gorm.DB
|
||||
if proto.Config.SERVER_SQL_LOG {
|
||||
db2 = DB.Debug()
|
||||
} else {
|
||||
db2 = DB
|
||||
}
|
||||
res := db2.Where("id = ?", id).Delete(&proto.DNSZone{})
|
||||
return res.Error
|
||||
}
|
||||
|
||||
func DeleteDNSZoneByServerID(serverID uint) error {
|
||||
var db2 *gorm.DB
|
||||
if proto.Config.SERVER_SQL_LOG {
|
||||
db2 = DB.Debug()
|
||||
} else {
|
||||
db2 = DB
|
||||
}
|
||||
res := db2.Where("server_id = ?", serverID).Delete(&proto.DNSZone{})
|
||||
return res.Error
|
||||
}
|
||||
|
||||
// ==================== DNSRecord 相关操作 ====================
|
||||
|
||||
func CreateDNSRecord(record proto.DNSRecord) (uint, error) {
|
||||
var db2 *gorm.DB
|
||||
if proto.Config.SERVER_SQL_LOG {
|
||||
db2 = DB.Debug()
|
||||
} else {
|
||||
db2 = DB
|
||||
}
|
||||
res := db2.Create(&record)
|
||||
if res.Error != nil {
|
||||
return 0, res.Error
|
||||
}
|
||||
return record.ID, nil
|
||||
}
|
||||
|
||||
func FindDNSRecordByID(id uint) (proto.DNSRecord, error) {
|
||||
var record proto.DNSRecord
|
||||
var db2 *gorm.DB
|
||||
if proto.Config.SERVER_SQL_LOG {
|
||||
db2 = DB.Debug()
|
||||
} else {
|
||||
db2 = DB
|
||||
}
|
||||
res := db2.Where("id = ?", id).First(&record)
|
||||
if res.Error != nil {
|
||||
return proto.DNSRecord{}, res.Error
|
||||
}
|
||||
return record, nil
|
||||
}
|
||||
|
||||
func FindDNSRecordByZoneID(zoneID uint) ([]proto.DNSRecord, error) {
|
||||
var records []proto.DNSRecord
|
||||
var db2 *gorm.DB
|
||||
if proto.Config.SERVER_SQL_LOG {
|
||||
db2 = DB.Debug()
|
||||
} else {
|
||||
db2 = DB
|
||||
}
|
||||
res := db2.Where("zone_id = ?", zoneID).Find(&records)
|
||||
if res.Error != nil {
|
||||
return nil, res.Error
|
||||
}
|
||||
return records, nil
|
||||
}
|
||||
|
||||
func FindAllDNSRecord() ([]proto.DNSRecord, error) {
|
||||
var records []proto.DNSRecord
|
||||
var db2 *gorm.DB
|
||||
if proto.Config.SERVER_SQL_LOG {
|
||||
db2 = DB.Debug()
|
||||
} else {
|
||||
db2 = DB
|
||||
}
|
||||
res := db2.Find(&records)
|
||||
if res.Error != nil {
|
||||
return nil, res.Error
|
||||
}
|
||||
return records, nil
|
||||
}
|
||||
|
||||
func UpdateDNSRecord(id uint, record *proto.DNSRecord) error {
|
||||
var db2 *gorm.DB
|
||||
if proto.Config.SERVER_SQL_LOG {
|
||||
db2 = DB.Debug()
|
||||
} else {
|
||||
db2 = DB
|
||||
}
|
||||
res := db2.Model(&proto.DNSRecord{}).Where("id = ?", id).Updates(record)
|
||||
return res.Error
|
||||
}
|
||||
|
||||
func DeleteDNSRecordByID(id uint) error {
|
||||
var db2 *gorm.DB
|
||||
if proto.Config.SERVER_SQL_LOG {
|
||||
db2 = DB.Debug()
|
||||
} else {
|
||||
db2 = DB
|
||||
}
|
||||
res := db2.Where("id = ?", id).Delete(&proto.DNSRecord{})
|
||||
return res.Error
|
||||
}
|
||||
|
||||
func DeleteDNSRecordByZoneID(zoneID uint) error {
|
||||
var db2 *gorm.DB
|
||||
if proto.Config.SERVER_SQL_LOG {
|
||||
db2 = DB.Debug()
|
||||
} else {
|
||||
db2 = DB
|
||||
}
|
||||
res := db2.Where("zone_id = ?", zoneID).Delete(&proto.DNSRecord{})
|
||||
return res.Error
|
||||
}
|
||||
34
dao/user.go
34
dao/user.go
|
|
@ -8,21 +8,25 @@ import (
|
|||
|
||||
type User struct {
|
||||
gorm.Model
|
||||
Name string `gorm:"column:name"`
|
||||
Age int `gorm:"column:age"`
|
||||
Email string `gorm:"column:email"`
|
||||
Password string `gorm:"column:password"`
|
||||
Gender string `gorm:"column:gender"`
|
||||
Role string `gorm:"column:role"`
|
||||
Redis bool `gorm:"column:redis"`
|
||||
Run bool `gorm:"column:run"`
|
||||
Upload bool `gorm:"column:upload"`
|
||||
VideoFunc bool `gorm:"column:video_func"` //视频功能
|
||||
DeviceFunc bool `gorm:"column:device_func"` //设备功能
|
||||
CIDFunc bool `gorm:"column:cid_func"` //持续集成功能
|
||||
Avatar string `gorm:"column:avatar"`
|
||||
CreateTime string `gorm:"column:create_time"`
|
||||
UpdateTime string `gorm:"column:update_time"`
|
||||
Name string `gorm:"column:name"`
|
||||
Age int `gorm:"column:age"`
|
||||
Email string `gorm:"column:email"`
|
||||
Password string `gorm:"column:password"`
|
||||
Gender string `gorm:"column:gender"`
|
||||
Role string `gorm:"column:role"`
|
||||
Redis int `gorm:"column:redis"`
|
||||
Run int `gorm:"column:run"`
|
||||
Upload int `gorm:"column:upload"`
|
||||
VideoFunc int `gorm:"column:video_func"` //视频功能
|
||||
DeviceFunc int `gorm:"column:device_func"` //设备功能
|
||||
CIDFunc int `gorm:"column:cid_func"` //持续集成功能, 0为无效, -1为false, 1为true
|
||||
Avatar string `gorm:"column:avatar"`
|
||||
PasswordNeedSecondAuth int `gorm:"column:password_need_second_auth" json:"password_need_second_auth"`
|
||||
ThirdPartyNeedSecondAuth int `gorm:"column:third_party_need_second_auth" json:"third_party_need_second_auth"`
|
||||
CodeNeedSecondAuth int `gorm:"column:code_need_second_auth" json:"code_need_second_auth"`
|
||||
AISecondAuth int `json:"ai_second_auth" column:"ai_second_auth"`
|
||||
LoginAddressInfo string `gorm:"column:login_address_info" json:"login_address_info,omitempty"`
|
||||
LoginDeviceInfo string `gorm:"column:login_device_info" json:"login_device_info,omitempty"`
|
||||
}
|
||||
|
||||
func CreateUser(name, password, email, gender string, age int) uint {
|
||||
|
|
|
|||
19
go.mod
19
go.mod
|
|
@ -1,6 +1,6 @@
|
|||
module videoplayer
|
||||
|
||||
go 1.21
|
||||
go 1.24.0
|
||||
|
||||
require (
|
||||
github.com/gin-gonic/gin v1.10.0
|
||||
|
|
@ -8,10 +8,12 @@ require (
|
|||
github.com/golang-jwt/jwt v3.2.2+incompatible
|
||||
github.com/google/uuid v1.6.0
|
||||
github.com/gorilla/websocket v1.5.3
|
||||
github.com/miekg/dns v1.1.72
|
||||
github.com/robfig/cron/v3 v3.0.1
|
||||
gorm.io/driver/mysql v1.5.6
|
||||
gorm.io/driver/postgres v1.5.9
|
||||
gorm.io/gorm v1.25.10
|
||||
gorm.io/driver/sqlite v1.6.0
|
||||
gorm.io/gorm v1.30.0
|
||||
)
|
||||
|
||||
require (
|
||||
|
|
@ -39,6 +41,7 @@ require (
|
|||
github.com/kr/text v0.2.0 // indirect
|
||||
github.com/leodido/go-urn v1.4.0 // indirect
|
||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||
github.com/mattn/go-sqlite3 v1.14.22 // indirect
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
|
||||
github.com/modern-go/reflect2 v1.0.2 // indirect
|
||||
github.com/pelletier/go-toml/v2 v2.2.2 // indirect
|
||||
|
|
@ -46,11 +49,13 @@ require (
|
|||
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
|
||||
github.com/ugorji/go/codec v1.2.12 // indirect
|
||||
golang.org/x/arch v0.8.0 // indirect
|
||||
golang.org/x/crypto v0.23.0 // indirect
|
||||
golang.org/x/net v0.25.0 // indirect
|
||||
golang.org/x/sync v0.1.0 // indirect
|
||||
golang.org/x/sys v0.20.0 // indirect
|
||||
golang.org/x/text v0.15.0 // indirect
|
||||
golang.org/x/crypto v0.46.0 // indirect
|
||||
golang.org/x/mod v0.31.0 // indirect
|
||||
golang.org/x/net v0.48.0 // indirect
|
||||
golang.org/x/sync v0.19.0 // indirect
|
||||
golang.org/x/sys v0.39.0 // indirect
|
||||
golang.org/x/text v0.32.0 // indirect
|
||||
golang.org/x/tools v0.40.0 // indirect
|
||||
google.golang.org/protobuf v1.34.1 // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
)
|
||||
|
|
|
|||
26
go.sum
26
go.sum
|
|
@ -71,6 +71,10 @@ github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
|
|||
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
|
||||
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
||||
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||
github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU=
|
||||
github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
|
||||
github.com/miekg/dns v1.1.72 h1:vhmr+TF2A3tuoGNkLDFK9zi36F2LS+hKTRW0Uf8kbzI=
|
||||
github.com/miekg/dns v1.1.72/go.mod h1:+EuEPhdHOsfk6Wk5TT2CzssZdqkmFhf8r+aVyDEToIs=
|
||||
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||
|
|
@ -111,16 +115,34 @@ golang.org/x/arch v0.8.0 h1:3wRIsP3pM4yUptoR96otTUOXI367OS0+c9eeRi9doIc=
|
|||
golang.org/x/arch v0.8.0/go.mod h1:FEVrYAQjsQXMVJ1nsMoVVXPZg6p2JE2mx8psSWTDQys=
|
||||
golang.org/x/crypto v0.23.0 h1:dIJU/v2J8Mdglj/8rJ6UUOM3Zc9zLZxVZwwxMooUSAI=
|
||||
golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8=
|
||||
golang.org/x/crypto v0.46.0 h1:cKRW/pmt1pKAfetfu+RCEvjvZkA9RimPbh7bhFjGVBU=
|
||||
golang.org/x/crypto v0.46.0/go.mod h1:Evb/oLKmMraqjZ2iQTwDwvCtJkczlDuTmdJXoZVzqU0=
|
||||
golang.org/x/mod v0.31.0 h1:HaW9xtz0+kOcWKwli0ZXy79Ix+UW/vOfmWI5QVd2tgI=
|
||||
golang.org/x/mod v0.31.0/go.mod h1:43JraMp9cGx1Rx3AqioxrbrhNsLl2l/iNAvuBkrezpg=
|
||||
golang.org/x/net v0.25.0 h1:d/OCCoBEUq33pjydKrGQhw7IlUPI2Oylr+8qLx49kac=
|
||||
golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM=
|
||||
golang.org/x/net v0.48.0 h1:zyQRTTrjc33Lhh0fBgT/H3oZq9WuvRR5gPC70xpDiQU=
|
||||
golang.org/x/net v0.48.0/go.mod h1:+ndRgGjkh8FGtu1w1FGbEC31if4VrNVMuKTgcAAnQRY=
|
||||
golang.org/x/sync v0.1.0 h1:wsuoTGHzEhffawBOhz5CYhcrV4IdKZbEyZjBMuTp12o=
|
||||
golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.9.0 h1:fEo0HyrW1GIgZdpbhCRO0PkJajUS5H9IFUztCgEo2jQ=
|
||||
golang.org/x/sync v0.9.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
|
||||
golang.org/x/sync v0.19.0 h1:vV+1eWNmZ5geRlYjzm2adRgW2/mcpevXNg50YZtPCE4=
|
||||
golang.org/x/sync v0.19.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
|
||||
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.20.0 h1:Od9JTbYCk261bKm4M/mw7AklTlFYIa0bIp9BgSm1S8Y=
|
||||
golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/sys v0.39.0 h1:CvCKL8MeisomCi6qNZ+wbb0DN9E5AATixKsvNtMoMFk=
|
||||
golang.org/x/sys v0.39.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
|
||||
golang.org/x/text v0.15.0 h1:h1V/4gjBv8v9cjcR6+AR5+/cIYK5N/WAgiv4xlsEtAk=
|
||||
golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
|
||||
golang.org/x/text v0.20.0 h1:gK/Kv2otX8gz+wn7Rmb3vT96ZwuoxnQlY+HlJVj7Qug=
|
||||
golang.org/x/text v0.20.0/go.mod h1:D4IsuqiFMhST5bX19pQ9ikHC2GsaKyk/oF+pn3ducp4=
|
||||
golang.org/x/text v0.32.0 h1:ZD01bjUt1FQ9WJ0ClOL5vxgxOI/sVCNgX1YtKwcY0mU=
|
||||
golang.org/x/text v0.32.0/go.mod h1:o/rUWzghvpD5TXrTIBuJU77MTaN0ljMWE47kxGJQ7jY=
|
||||
golang.org/x/tools v0.40.0 h1:yLkxfA+Qnul4cs9QA3KnlFu0lVmd8JJfoq+E41uSutA=
|
||||
golang.org/x/tools v0.40.0/go.mod h1:Ik/tzLRlbscWpqqMRjyWYDisX8bG13FrdXp3o4Sr9lc=
|
||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4=
|
||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
google.golang.org/protobuf v1.34.1 h1:9ddQBjfCyZPOHPUiPxpYESBLc+T8P3E+Vo4IbKZgFWg=
|
||||
|
|
@ -139,8 +161,12 @@ gorm.io/driver/mysql v1.5.6 h1:Ld4mkIickM+EliaQZQx3uOJDJHtrd70MxAUqWqlx3Y8=
|
|||
gorm.io/driver/mysql v1.5.6/go.mod h1:sEtPWMiqiN1N1cMXoXmBbd8C6/l+TESwriotuRRpkDM=
|
||||
gorm.io/driver/postgres v1.5.9 h1:DkegyItji119OlcaLjqN11kHoUgZ/j13E0jkJZgD6A8=
|
||||
gorm.io/driver/postgres v1.5.9/go.mod h1:DX3GReXH+3FPWGrrgffdvCk3DQ1dwDPdmbenSkweRGI=
|
||||
gorm.io/driver/sqlite v1.6.0 h1:WHRRrIiulaPiPFmDcod6prc4l2VGVWHz80KspNsxSfQ=
|
||||
gorm.io/driver/sqlite v1.6.0/go.mod h1:AO9V1qIQddBESngQUKWL9yoH93HIeA1X6V633rBwyT8=
|
||||
gorm.io/gorm v1.25.7/go.mod h1:hbnx/Oo0ChWMn1BIhpy1oYozzpM15i4YPuHDmfYtwg8=
|
||||
gorm.io/gorm v1.25.10 h1:dQpO+33KalOA+aFYGlK+EfxcI5MbO7EP2yYygwh9h+s=
|
||||
gorm.io/gorm v1.25.10/go.mod h1:hbnx/Oo0ChWMn1BIhpy1oYozzpM15i4YPuHDmfYtwg8=
|
||||
gorm.io/gorm v1.30.0 h1:qbT5aPv1UH8gI99OsRlvDToLxW5zR7FzS9acZDOZcgs=
|
||||
gorm.io/gorm v1.30.0/go.mod h1:8Z33v652h4//uMA76KjeDH8mJXPm1QNCYrMeatR0DOE=
|
||||
nullprogram.com/x/optparse v1.0.0/go.mod h1:KdyPE+Igbe0jQUrVfMqDMeJQIJZEuyV7pjYmp6pbG50=
|
||||
rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4=
|
||||
|
|
|
|||
169
handler/cid.go
169
handler/cid.go
|
|
@ -1,13 +1,15 @@
|
|||
package handler
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"github.com/gin-gonic/gin"
|
||||
"log"
|
||||
"net/http"
|
||||
"os/exec"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
"videoplayer/dao"
|
||||
"videoplayer/proto"
|
||||
|
|
@ -15,6 +17,19 @@ import (
|
|||
"videoplayer/worker"
|
||||
)
|
||||
|
||||
type CIDTask struct {
|
||||
Name string
|
||||
Url string
|
||||
Script string
|
||||
ID int
|
||||
AuthID int
|
||||
}
|
||||
|
||||
var (
|
||||
cidTaskQueue = make(chan CIDTask, 100)
|
||||
cidQueueOnce sync.Once
|
||||
)
|
||||
|
||||
type CIDCreateReq struct {
|
||||
Name string `json:"name" form:"name"`
|
||||
Url string `json:"url" form:"url"`
|
||||
|
|
@ -46,7 +61,18 @@ type CIDUpdateReq struct {
|
|||
// 全局变量,记录是否进行cron定时任务的刷新
|
||||
var cron_count int
|
||||
|
||||
func initCIDTaskQueue() {
|
||||
cidQueueOnce.Do(func() {
|
||||
go func() {
|
||||
for task := range cidTaskQueue {
|
||||
RunShellCID(task.Name, task.Url, task.Script, task.ID, task.AuthID)
|
||||
}
|
||||
}()
|
||||
})
|
||||
}
|
||||
|
||||
func SetUpCIDGroup(router *gin.Engine) {
|
||||
initCIDTaskQueue()
|
||||
cidGroup := router.Group("/cid") //持续集成、部署
|
||||
cidGroup.POST("/create", CreateCID)
|
||||
cidGroup.POST("/delete", DeleteCID)
|
||||
|
|
@ -57,6 +83,27 @@ func SetUpCIDGroup(router *gin.Engine) {
|
|||
cidGroup.POST("/log/detail", GetCIDLog) //获取执行日志详情
|
||||
cidGroup.GET("/callback", CIDCallback)
|
||||
cidGroup.POST("/callback", CIDCallback)
|
||||
cidGroup.GET("/running", GetRunningCIDs)
|
||||
}
|
||||
func GetRunningCIDs(c *gin.Context) {
|
||||
id, _ := c.Get("id")
|
||||
user_id := int(id.(float64))
|
||||
req_type := c.Query("type") //请求方式 0默认自己, 1为所有(管理员可选)
|
||||
req_type_ := 0
|
||||
if req_type != "" {
|
||||
req_type_, _ = strconv.Atoi(req_type)
|
||||
}
|
||||
resp_data, err := service.GetCIDRunningList(user_id, req_type_)
|
||||
|
||||
var resp proto.GeneralResp
|
||||
if err != nil {
|
||||
resp.Code = proto.InternalServerError
|
||||
resp.Message = err.Error()
|
||||
} else {
|
||||
resp.Code, resp.Message = 0, ""
|
||||
resp.Data = resp_data
|
||||
}
|
||||
c.JSON(http.StatusOK, resp)
|
||||
}
|
||||
func RunCID(c *gin.Context) {
|
||||
var req CIDRunReq
|
||||
|
|
@ -65,20 +112,25 @@ func RunCID(c *gin.Context) {
|
|||
//获取权限
|
||||
//user := dao.FindUserByUserID(authID)
|
||||
user := service.GetUserByIDFromUserCenter(authID)
|
||||
if user.Run == false {
|
||||
if user.Run <= 0 {
|
||||
c.JSON(200, gin.H{"error": "no run Permissions", "code": proto.NoRunPermissions, "message": "no run Permissions"})
|
||||
return
|
||||
}
|
||||
|
||||
if err := c.ShouldBind(&req); err == nil {
|
||||
// 获取用户ID
|
||||
username, _ := c.Get("username")
|
||||
cid := dao.FindCIDByID(req.ID, authID)
|
||||
if cid.ID == 0 {
|
||||
c.JSON(200, gin.H{"error": "CID not found", "code": proto.OperationFailed, "message": "failed"})
|
||||
return
|
||||
} else {
|
||||
go RunShell(username.(string), cid.Url, cid.Script, req.ID, authID)
|
||||
cidTaskQueue <- CIDTask{
|
||||
Name: cid.Name,
|
||||
Url: cid.Url,
|
||||
Script: cid.Script,
|
||||
ID: req.ID,
|
||||
AuthID: authID,
|
||||
}
|
||||
c.JSON(200, gin.H{"code": proto.SuccessCode, "message": "success", "data": "success"})
|
||||
}
|
||||
} else {
|
||||
|
|
@ -185,32 +237,49 @@ func CIDCallback(c *gin.Context) {
|
|||
// 获取用户ID
|
||||
token := c.Query("token")
|
||||
cid_id := c.Query("id")
|
||||
//fmt.Println("token:", token, "cid_id:", cid_id)
|
||||
//将cid转换为int
|
||||
cid, _ := strconv.Atoi(cid_id)
|
||||
|
||||
if token == "" || cid == 0 {
|
||||
c.JSON(200, gin.H{"error": "parameter error", "code": proto.ParameterError, "message": "failed"})
|
||||
var req proto.CIDCallBackReq
|
||||
var resp proto.GeneralResp
|
||||
if err := c.ShouldBindQuery(&req); err != nil {
|
||||
resp.Code, resp.Message = proto.ParameterError, err.Error()
|
||||
c.JSON(http.StatusOK, resp)
|
||||
return
|
||||
}
|
||||
if req.ID == 0 || req.Token == "" {
|
||||
resp.Code, resp.Message = proto.ParameterError, "token or id is empty"
|
||||
c.JSON(http.StatusOK, resp)
|
||||
return
|
||||
}
|
||||
|
||||
res := dao.FindCIDByIDAndToken(cid, token)
|
||||
if res.ID == 0 {
|
||||
c.JSON(200, gin.H{"error": "CID not found by id and token", "code": proto.OperationFailed, "message": "failed"})
|
||||
resp.Code, resp.Message = proto.ParameterError, "CID not found by id and token:"+req.Token+", id:"+strconv.Itoa(int(res.ID))
|
||||
c.JSON(http.StatusOK, resp)
|
||||
return
|
||||
}
|
||||
|
||||
//user := dao.FindUserByUserID(res.Auth_id)
|
||||
user := service.GetUserByIDFromUserCenter(res.Auth_id)
|
||||
if user.Run == false {
|
||||
c.JSON(200, gin.H{"error": "no run Permissions", "code": proto.NoRunPermissions, "message": "the user has no run Permissions"})
|
||||
if user.Run <= 0 {
|
||||
resp.Code, resp.Message = proto.NoRunPermissions, "the user has no run Permissions"
|
||||
c.JSON(http.StatusOK, resp)
|
||||
return
|
||||
}
|
||||
if res.ID != 0 {
|
||||
user := dao.FindUserByID(res.Auth_id)
|
||||
go RunShell(user[0].Name, res.Url, res.Script, int(res.ID), res.Auth_id)
|
||||
c.JSON(200, gin.H{"code": proto.SuccessCode, "message": "success", "data": "success"})
|
||||
cidTaskQueue <- CIDTask{
|
||||
Name: res.Name,
|
||||
Url: res.Url,
|
||||
Script: res.Script,
|
||||
ID: int(res.ID),
|
||||
AuthID: res.Auth_id,
|
||||
}
|
||||
resp.Code, resp.Message, resp.Data = proto.SuccessCode, "success", res.Name
|
||||
c.JSON(http.StatusOK, resp)
|
||||
return
|
||||
} else {
|
||||
c.JSON(200, gin.H{"error": "CID not found by id and token", "code": proto.OperationFailed, "message": "failed"})
|
||||
resp.Code, resp.Message = proto.OperationFailed, "CID not found by id and token"
|
||||
c.JSON(http.StatusOK, resp)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
|
@ -220,6 +289,41 @@ func RunShell(username, url, script string, id, authID int) {
|
|||
name := strs[len(strs)-1]
|
||||
names := strings.Split(name, ".")
|
||||
name = names[0]
|
||||
//脚本内容,不同用户的持续集成、部署目录不同
|
||||
scriptContent := `
|
||||
echo "start"
|
||||
` + script + `
|
||||
echo "end"`
|
||||
start := time.Now()
|
||||
//执行脚本
|
||||
cmd := exec.Command("/bin/bash", "-c", scriptContent)
|
||||
output, err3 := cmd.CombinedOutput()
|
||||
err3_info := ""
|
||||
if err3 != nil {
|
||||
err3_info = err3.Error()
|
||||
}
|
||||
elapsed := time.Since(start)
|
||||
//fmt.Println("bash content:", scriptContent)
|
||||
dao.CreateRunLog(id, authID, scriptContent, string(output), err3_info, elapsed.Seconds()) //添加执行日志
|
||||
}
|
||||
|
||||
func RunShellCID(cid_name, url, script string, id, authID int) {
|
||||
strs := strings.Split(url, "/")
|
||||
name := strs[len(strs)-1]
|
||||
names := strings.Split(name, ".")
|
||||
name = names[0]
|
||||
now := time.Now()
|
||||
var cid_running proto.CIDRunning
|
||||
cid_running.ID = id
|
||||
cid_running.AuthID = authID
|
||||
cid_running.StartTime = now
|
||||
cid_running.CID = cid_name
|
||||
//加入正在运行
|
||||
proto.CID_RunningMutex.Lock()
|
||||
user_running_list := proto.CID_Running_Map[authID]
|
||||
user_running_list = append(user_running_list, cid_running)
|
||||
proto.CID_Running_Map[authID] = user_running_list
|
||||
proto.CID_RunningMutex.Unlock()
|
||||
|
||||
//脚本内容,不同用户的持续集成、部署目录不同
|
||||
scriptContent := `
|
||||
|
|
@ -229,17 +333,42 @@ echo "end"`
|
|||
start := time.Now()
|
||||
//执行脚本
|
||||
cmd := exec.Command("/bin/bash", "-c", scriptContent)
|
||||
// 使用bytes.Buffer捕获输出
|
||||
var out bytes.Buffer
|
||||
cmd.Stdout = &out
|
||||
err3 := cmd.Run()
|
||||
output, err3 := cmd.CombinedOutput()
|
||||
err3_info := ""
|
||||
if err3 != nil {
|
||||
err3_info = err3.Error()
|
||||
err := dao.UpdateCIDLastFailureTime(id)
|
||||
if err != nil {
|
||||
log.Println("[ERROR] update cid:", id, " last fail time err:", err)
|
||||
}
|
||||
}
|
||||
elapsed := time.Since(start)
|
||||
//fmt.Println("bash content:", scriptContent)
|
||||
dao.CreateRunLog(id, authID, scriptContent, out.String(), err3_info, elapsed.Seconds()) //添加执行日志
|
||||
dao.CreateRunLog(id, authID, scriptContent, string(output), err3_info, elapsed.Seconds()) //添加执行日志
|
||||
if err3 != nil {
|
||||
dao.UpdateLastFailByID(id, time.Now())
|
||||
} else {
|
||||
dao.UpdateLastSuccessByID(id, time.Now())
|
||||
}
|
||||
//移除正在运行
|
||||
proto.CID_RunningMutex.Lock()
|
||||
user_running_list = proto.CID_Running_Map[authID]
|
||||
for i, v := range user_running_list {
|
||||
if v.StartTime.Equal(now) == true {
|
||||
//删除
|
||||
user_running_list = append(user_running_list[:i], user_running_list[i+1:]...)
|
||||
break
|
||||
}
|
||||
}
|
||||
//更新运行成功时间
|
||||
err := dao.UpdateCIDLastSuccessTime(id)
|
||||
if err != nil {
|
||||
log.Println("[ERROR] update cid:", id, " last success time err:", err)
|
||||
return
|
||||
}
|
||||
|
||||
proto.CID_Running_Map[authID] = user_running_list
|
||||
proto.CID_RunningMutex.Unlock()
|
||||
}
|
||||
|
||||
// 定时任务处理逻辑
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ package handler
|
|||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"log"
|
||||
"net/http"
|
||||
"videoplayer/proto"
|
||||
"videoplayer/service"
|
||||
|
|
@ -10,12 +11,61 @@ import (
|
|||
func SetDBManageGroup(router *gin.Engine) {
|
||||
dbm := router.Group("/dbm")
|
||||
|
||||
dbm.POST("/run_sql", RunSQLHandler) // 运行SQL语句
|
||||
dbm.POST("/create_db_manage", CreateDBManageHandler) // 创建数据库管理
|
||||
dbm.POST("/get_db_manage", GetDBManageHandler) // 获取数据库管理信息
|
||||
dbm.POST("/get_sql_history", GetSQLRunHistoryHandler) // 获取SQL运行历史
|
||||
dbm.POST("/update_db_manage", UpdateDBManageHandler) // 更新数据库管理信息
|
||||
dbm.POST("/run_sql", RunSQLHandler) // 运行SQL语句
|
||||
dbm.POST("/create_db_manage", CreateDBManageHandler) // 创建数据库管理
|
||||
dbm.POST("/get_db_manage", GetDBManageHandler) // 获取数据库管理信息
|
||||
dbm.POST("/get_sql_history", GetSQLRunHistoryHandler) // 获取SQL运行历史
|
||||
dbm.POST("/update_db_manage", UpdateDBManageHandler) // 更新数据库管理信息
|
||||
dbm.POST("/del_db_manage", DeleteDBManageHandler) // 删除数据库管理信息
|
||||
dbm.POST("/del_dbm_sql_history", DeleteSQLRunHistoryHandler) // 删除SQL运行历史
|
||||
dbm.POST("/get_db_table_desc", GetDBTableDescHandler) // 获取数据库表描述
|
||||
}
|
||||
|
||||
func DeleteSQLRunHistoryHandler(c *gin.Context) {
|
||||
id, _ := c.Get("id")
|
||||
userID := int(id.(float64))
|
||||
|
||||
var req proto.DeleteDBManageSQLHistoryReq
|
||||
var resp proto.GeneralResp
|
||||
if err := c.ShouldBind(&req); err != nil {
|
||||
resp.Code = proto.ParameterError
|
||||
resp.Message = "请求参数解析错误"
|
||||
} else {
|
||||
err2 := service.DeleteSQLRunHistory(&req, userID)
|
||||
if err2 != nil {
|
||||
resp.Code = proto.DBMRunSQLHistoryDeleteFailed
|
||||
resp.Message = "删除SQL运行历史失败: " + err2.Error()
|
||||
} else {
|
||||
resp.Code = proto.SuccessCode
|
||||
resp.Message = "删除SQL运行历史成功"
|
||||
}
|
||||
}
|
||||
c.JSON(http.StatusOK, resp)
|
||||
|
||||
}
|
||||
|
||||
func DeleteDBManageHandler(c *gin.Context) {
|
||||
id, _ := c.Get("id")
|
||||
userID := int(id.(float64))
|
||||
|
||||
var req proto.DeleteDBManageReq
|
||||
var resp proto.GeneralResp
|
||||
if err := c.ShouldBind(&req); err != nil {
|
||||
resp.Code = proto.ParameterError
|
||||
resp.Message = "请求参数解析错误"
|
||||
} else {
|
||||
err2 := service.DeleteDBManage(&req, userID)
|
||||
if err2 != nil {
|
||||
resp.Code = proto.DBMDeleteFailed
|
||||
resp.Message = "删除数据库管理失败: " + err2.Error()
|
||||
} else {
|
||||
resp.Code = proto.SuccessCode
|
||||
resp.Message = "删除数据库管理成功"
|
||||
}
|
||||
}
|
||||
c.JSON(http.StatusOK, resp)
|
||||
}
|
||||
|
||||
func UpdateDBManageHandler(c *gin.Context) {
|
||||
id, _ := c.Get("id")
|
||||
userID := int(id.(float64))
|
||||
|
|
@ -118,6 +168,7 @@ func RunSQLHandler(c *gin.Context) {
|
|||
resp.Code = proto.ParameterError
|
||||
resp.Message = "请求参数解析错误"
|
||||
} else {
|
||||
log.Println("run sql request, sql is:", req.SQL)
|
||||
req.UserID = userID
|
||||
res, err2 := service.RunSQL(&req)
|
||||
if err2 != nil {
|
||||
|
|
@ -130,4 +181,28 @@ func RunSQLHandler(c *gin.Context) {
|
|||
}
|
||||
}
|
||||
c.JSON(http.StatusOK, resp)
|
||||
return
|
||||
}
|
||||
|
||||
func GetDBTableDescHandler(c *gin.Context) {
|
||||
id, _ := c.Get("id")
|
||||
userID := int(id.(float64))
|
||||
|
||||
var req proto.GetDBTableDescReq
|
||||
var resp proto.GeneralResp
|
||||
if err := c.ShouldBind(&req); err != nil {
|
||||
resp.Code = proto.ParameterError
|
||||
resp.Message = "请求参数解析错误"
|
||||
} else {
|
||||
tableDesc, err2 := service.GetDBTableDesc(&req, userID)
|
||||
if err2 != nil {
|
||||
resp.Code = proto.DBMGetTableDescFailed
|
||||
resp.Message = "获取数据库表描述失败: " + err2.Error()
|
||||
} else {
|
||||
resp.Code = proto.SuccessCode
|
||||
resp.Message = "获取数据库表描述成功"
|
||||
resp.Data = tableDesc
|
||||
}
|
||||
}
|
||||
c.JSON(http.StatusOK, resp)
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,406 @@
|
|||
package handler
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"videoplayer/proto"
|
||||
"videoplayer/service"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func SetDNSGroup(router *gin.Engine) {
|
||||
dns := router.Group("/dns")
|
||||
|
||||
dns.POST("/server/create", CreateDNSServerHandler)
|
||||
dns.POST("/server/get", GetDNSServerHandler)
|
||||
dns.POST("/server/update", UpdateDNSServerHandler)
|
||||
dns.POST("/server/delete", DeleteDNSServerHandler)
|
||||
dns.POST("/server/start", StartDNSServerHandler)
|
||||
dns.POST("/server/stop", StopDNSServerHandler)
|
||||
dns.POST("/server/restart", RestartDNSServerHandler)
|
||||
dns.POST("/server/status", GetDNSServerStatusHandler)
|
||||
|
||||
dns.POST("/zone/create", CreateDNSZoneHandler)
|
||||
dns.POST("/zone/get", GetDNSZoneHandler)
|
||||
dns.POST("/zone/update", UpdateDNSZoneHandler)
|
||||
dns.POST("/zone/delete", DeleteDNSZoneHandler)
|
||||
|
||||
dns.POST("/record/create", CreateDNSRecordHandler)
|
||||
dns.POST("/record/get", GetDNSRecordHandler)
|
||||
dns.POST("/record/update", UpdateDNSRecordHandler)
|
||||
dns.POST("/record/delete", DeleteDNSRecordHandler)
|
||||
}
|
||||
|
||||
// ==================== DNSServer 相关 Handler ====================
|
||||
|
||||
func CreateDNSServerHandler(c *gin.Context) {
|
||||
id, _ := c.Get("id")
|
||||
userID := uint(id.(float64))
|
||||
|
||||
var req proto.CreateDNSServerReq
|
||||
var resp proto.GeneralResp
|
||||
if err := c.ShouldBind(&req); err != nil {
|
||||
resp.Code = proto.ParameterError
|
||||
resp.Message = "请求参数解析错误"
|
||||
} else {
|
||||
server, err := service.CreateDNSServer(&req, userID)
|
||||
if err != nil {
|
||||
resp.Code = proto.ErrorCode
|
||||
resp.Message = "创建DNS服务器失败: " + err.Error()
|
||||
} else {
|
||||
resp.Code = proto.SuccessCode
|
||||
resp.Message = "创建DNS服务器成功"
|
||||
resp.Data = server
|
||||
}
|
||||
}
|
||||
c.JSON(http.StatusOK, resp)
|
||||
}
|
||||
|
||||
func GetDNSServerHandler(c *gin.Context) {
|
||||
id, _ := c.Get("id")
|
||||
userID := uint(id.(float64))
|
||||
|
||||
var req proto.GetDNSServerReq
|
||||
var resp proto.GeneralResp
|
||||
if err := c.ShouldBind(&req); err != nil {
|
||||
resp.Code = proto.ParameterError
|
||||
resp.Message = "请求参数解析错误"
|
||||
} else {
|
||||
servers, err := service.GetDNSServerList(&req, userID)
|
||||
if err != nil {
|
||||
resp.Code = proto.ErrorCode
|
||||
resp.Message = "获取DNS服务器失败: " + err.Error()
|
||||
} else {
|
||||
resp.Code = proto.SuccessCode
|
||||
resp.Message = "获取DNS服务器成功"
|
||||
resp.Data = servers
|
||||
}
|
||||
}
|
||||
c.JSON(http.StatusOK, resp)
|
||||
}
|
||||
|
||||
func UpdateDNSServerHandler(c *gin.Context) {
|
||||
id, _ := c.Get("id")
|
||||
userID := int(id.(float64))
|
||||
|
||||
var req proto.UpdateDNSServerReq
|
||||
var resp proto.GeneralResp
|
||||
if err := c.ShouldBind(&req); err != nil {
|
||||
resp.Code = proto.ParameterError
|
||||
resp.Message = "请求参数解析错误"
|
||||
} else {
|
||||
server, err := service.UpdateDNSServer(&req, userID)
|
||||
if err != nil {
|
||||
resp.Code = proto.ErrorCode
|
||||
resp.Message = "更新DNS服务器失败: " + err.Error()
|
||||
} else {
|
||||
resp.Code = proto.SuccessCode
|
||||
resp.Message = "更新DNS服务器成功"
|
||||
resp.Data = server
|
||||
}
|
||||
}
|
||||
c.JSON(http.StatusOK, resp)
|
||||
}
|
||||
|
||||
func DeleteDNSServerHandler(c *gin.Context) {
|
||||
id, _ := c.Get("id")
|
||||
userID := int(id.(float64))
|
||||
|
||||
var req proto.DeleteDNSServerReq
|
||||
var resp proto.GeneralResp
|
||||
if err := c.ShouldBind(&req); err != nil {
|
||||
resp.Code = proto.ParameterError
|
||||
resp.Message = "请求参数解析错误"
|
||||
} else {
|
||||
err := service.DeleteDNSServer(&req, userID)
|
||||
if err != nil {
|
||||
resp.Code = proto.ErrorCode
|
||||
resp.Message = "删除DNS服务器失败: " + err.Error()
|
||||
} else {
|
||||
resp.Code = proto.SuccessCode
|
||||
resp.Message = "删除DNS服务器成功"
|
||||
}
|
||||
}
|
||||
c.JSON(http.StatusOK, resp)
|
||||
}
|
||||
|
||||
// ==================== DNSZone 相关 Handler ====================
|
||||
|
||||
func CreateDNSZoneHandler(c *gin.Context) {
|
||||
id, _ := c.Get("id")
|
||||
userID := uint(id.(float64))
|
||||
|
||||
var req proto.CreateDNSZoneReq
|
||||
var resp proto.GeneralResp
|
||||
if err := c.ShouldBind(&req); err != nil {
|
||||
resp.Code = proto.ParameterError
|
||||
resp.Message = "请求参数解析错误"
|
||||
} else {
|
||||
zone, err := service.CreateDNSZone(&req, userID)
|
||||
if err != nil {
|
||||
resp.Code = proto.ErrorCode
|
||||
resp.Message = "创建DNS区域失败: " + err.Error()
|
||||
} else {
|
||||
resp.Code = proto.SuccessCode
|
||||
resp.Message = "创建DNS区域成功"
|
||||
resp.Data = zone
|
||||
}
|
||||
}
|
||||
c.JSON(http.StatusOK, resp)
|
||||
}
|
||||
|
||||
func GetDNSZoneHandler(c *gin.Context) {
|
||||
id, _ := c.Get("id")
|
||||
userID := uint(id.(float64))
|
||||
|
||||
var req proto.GetDNSZoneReq
|
||||
var resp proto.GeneralResp
|
||||
if err := c.ShouldBind(&req); err != nil {
|
||||
resp.Code = proto.ParameterError
|
||||
resp.Message = "请求参数解析错误"
|
||||
} else {
|
||||
zones, err := service.GetDNSZoneList(&req, userID)
|
||||
if err != nil {
|
||||
resp.Code = proto.ErrorCode
|
||||
resp.Message = "获取DNS区域失败: " + err.Error()
|
||||
} else {
|
||||
resp.Code = proto.SuccessCode
|
||||
resp.Message = "获取DNS区域成功"
|
||||
resp.Data = zones
|
||||
}
|
||||
}
|
||||
c.JSON(http.StatusOK, resp)
|
||||
}
|
||||
|
||||
func UpdateDNSZoneHandler(c *gin.Context) {
|
||||
id, _ := c.Get("id")
|
||||
userID := int(id.(float64))
|
||||
|
||||
var req proto.UpdateDNSZoneReq
|
||||
var resp proto.GeneralResp
|
||||
if err := c.ShouldBind(&req); err != nil {
|
||||
resp.Code = proto.ParameterError
|
||||
resp.Message = "请求参数解析错误"
|
||||
} else {
|
||||
zone, err := service.UpdateDNSZone(&req, userID)
|
||||
if err != nil {
|
||||
resp.Code = proto.ErrorCode
|
||||
resp.Message = "更新DNS区域失败: " + err.Error()
|
||||
} else {
|
||||
resp.Code = proto.SuccessCode
|
||||
resp.Message = "更新DNS区域成功"
|
||||
resp.Data = zone
|
||||
}
|
||||
}
|
||||
c.JSON(http.StatusOK, resp)
|
||||
}
|
||||
|
||||
func DeleteDNSZoneHandler(c *gin.Context) {
|
||||
id, _ := c.Get("id")
|
||||
userID := int(id.(float64))
|
||||
|
||||
var req proto.DeleteDNSZoneReq
|
||||
var resp proto.GeneralResp
|
||||
if err := c.ShouldBind(&req); err != nil {
|
||||
resp.Code = proto.ParameterError
|
||||
resp.Message = "请求参数解析错误"
|
||||
} else {
|
||||
err := service.DeleteDNSZone(&req, userID)
|
||||
if err != nil {
|
||||
resp.Code = proto.ErrorCode
|
||||
resp.Message = "删除DNS区域失败: " + err.Error()
|
||||
} else {
|
||||
resp.Code = proto.SuccessCode
|
||||
resp.Message = "删除DNS区域成功"
|
||||
}
|
||||
}
|
||||
c.JSON(http.StatusOK, resp)
|
||||
}
|
||||
|
||||
// ==================== DNSRecord 相关 Handler ====================
|
||||
|
||||
func CreateDNSRecordHandler(c *gin.Context) {
|
||||
id, _ := c.Get("id")
|
||||
userID := uint(id.(float64))
|
||||
|
||||
var req proto.CreateDNSRecordReq
|
||||
var resp proto.GeneralResp
|
||||
if err := c.ShouldBind(&req); err != nil {
|
||||
resp.Code = proto.ParameterError
|
||||
resp.Message = "请求参数解析错误"
|
||||
} else {
|
||||
record, err := service.CreateDNSRecord(&req, userID)
|
||||
if err != nil {
|
||||
resp.Code = proto.ErrorCode
|
||||
resp.Message = "创建DNS记录失败: " + err.Error()
|
||||
} else {
|
||||
resp.Code = proto.SuccessCode
|
||||
resp.Message = "创建DNS记录成功"
|
||||
resp.Data = record
|
||||
}
|
||||
}
|
||||
c.JSON(http.StatusOK, resp)
|
||||
}
|
||||
|
||||
func GetDNSRecordHandler(c *gin.Context) {
|
||||
id, _ := c.Get("id")
|
||||
userID := uint(id.(float64))
|
||||
|
||||
var req proto.GetDNSRecordReq
|
||||
var resp proto.GeneralResp
|
||||
if err := c.ShouldBind(&req); err != nil {
|
||||
resp.Code = proto.ParameterError
|
||||
resp.Message = "请求参数解析错误"
|
||||
} else {
|
||||
records, err := service.GetDNSRecordList(&req, userID)
|
||||
if err != nil {
|
||||
resp.Code = proto.ErrorCode
|
||||
resp.Message = "获取DNS记录失败: " + err.Error()
|
||||
} else {
|
||||
resp.Code = proto.SuccessCode
|
||||
resp.Message = "获取DNS记录成功"
|
||||
resp.Data = records
|
||||
}
|
||||
}
|
||||
c.JSON(http.StatusOK, resp)
|
||||
}
|
||||
|
||||
func UpdateDNSRecordHandler(c *gin.Context) {
|
||||
id, _ := c.Get("id")
|
||||
userID := int(id.(float64))
|
||||
|
||||
var req proto.UpdateDNSRecordReq
|
||||
var resp proto.GeneralResp
|
||||
if err := c.ShouldBind(&req); err != nil {
|
||||
resp.Code = proto.ParameterError
|
||||
resp.Message = "请求参数解析错误"
|
||||
} else {
|
||||
record, err := service.UpdateDNSRecord(&req, userID)
|
||||
if err != nil {
|
||||
resp.Code = proto.ErrorCode
|
||||
resp.Message = "更新DNS记录失败: " + err.Error()
|
||||
} else {
|
||||
resp.Code = proto.SuccessCode
|
||||
resp.Message = "更新DNS记录成功"
|
||||
resp.Data = record
|
||||
}
|
||||
}
|
||||
c.JSON(http.StatusOK, resp)
|
||||
}
|
||||
|
||||
func DeleteDNSRecordHandler(c *gin.Context) {
|
||||
id, _ := c.Get("id")
|
||||
userID := int(id.(float64))
|
||||
|
||||
var req proto.DeleteDNSRecordReq
|
||||
var resp proto.GeneralResp
|
||||
if err := c.ShouldBind(&req); err != nil {
|
||||
resp.Code = proto.ParameterError
|
||||
resp.Message = "请求参数解析错误"
|
||||
} else {
|
||||
err := service.DeleteDNSRecord(&req, userID)
|
||||
if err != nil {
|
||||
resp.Code = proto.ErrorCode
|
||||
resp.Message = "删除DNS记录失败: " + err.Error()
|
||||
} else {
|
||||
resp.Code = proto.SuccessCode
|
||||
resp.Message = "删除DNS记录成功"
|
||||
}
|
||||
}
|
||||
c.JSON(http.StatusOK, resp)
|
||||
}
|
||||
|
||||
// 启动DNS服务器
|
||||
func StartDNSServerHandler(c *gin.Context) {
|
||||
id, _ := c.Get("id")
|
||||
userID := int(id.(float64))
|
||||
|
||||
var req proto.StartDNSServerReq
|
||||
var resp proto.GeneralResp
|
||||
if err := c.ShouldBind(&req); err != nil {
|
||||
resp.Code = proto.ParameterError
|
||||
resp.Message = "请求参数解析错误"
|
||||
} else {
|
||||
instance, err := service.StartDNSServer(req.ServerID, userID)
|
||||
if err != nil {
|
||||
resp.Code = proto.ErrorCode
|
||||
resp.Message = "启动DNS服务器失败: " + err.Error()
|
||||
} else {
|
||||
resp.Code = proto.SuccessCode
|
||||
resp.Message = "启动DNS服务器成功"
|
||||
resp.Data = instance
|
||||
}
|
||||
}
|
||||
c.JSON(http.StatusOK, resp)
|
||||
}
|
||||
|
||||
// 停止DNS服务器
|
||||
func StopDNSServerHandler(c *gin.Context) {
|
||||
id, _ := c.Get("id")
|
||||
userID := int(id.(float64))
|
||||
|
||||
var req proto.StopDNSServerReq
|
||||
var resp proto.GeneralResp
|
||||
if err := c.ShouldBind(&req); err != nil {
|
||||
resp.Code = proto.ParameterError
|
||||
resp.Message = "请求参数解析错误"
|
||||
} else {
|
||||
err := service.StopDNSServer(req.ServerID, userID)
|
||||
if err != nil {
|
||||
resp.Code = proto.ErrorCode
|
||||
resp.Message = "停止DNS服务器失败: " + err.Error()
|
||||
} else {
|
||||
resp.Code = proto.SuccessCode
|
||||
resp.Message = "停止DNS服务器成功"
|
||||
}
|
||||
}
|
||||
c.JSON(http.StatusOK, resp)
|
||||
}
|
||||
|
||||
// 重启DNS服务器
|
||||
func RestartDNSServerHandler(c *gin.Context) {
|
||||
id, _ := c.Get("id")
|
||||
userID := int(id.(float64))
|
||||
|
||||
var req proto.RestartDNSServerReq
|
||||
var resp proto.GeneralResp
|
||||
if err := c.ShouldBind(&req); err != nil {
|
||||
resp.Code = proto.ParameterError
|
||||
resp.Message = "请求参数解析错误"
|
||||
} else {
|
||||
instance, err := service.RestartDNSServer(req.ServerID, userID)
|
||||
if err != nil {
|
||||
resp.Code = proto.ErrorCode
|
||||
resp.Message = "重启DNS服务器失败: " + err.Error()
|
||||
} else {
|
||||
resp.Code = proto.SuccessCode
|
||||
resp.Message = "重启DNS服务器成功"
|
||||
resp.Data = instance
|
||||
}
|
||||
}
|
||||
c.JSON(http.StatusOK, resp)
|
||||
}
|
||||
|
||||
// 获取DNS服务器状态
|
||||
func GetDNSServerStatusHandler(c *gin.Context) {
|
||||
id, _ := c.Get("id")
|
||||
userID := int(id.(float64))
|
||||
|
||||
var req proto.GetDNSServerStatusReq
|
||||
var resp proto.GeneralResp
|
||||
if err := c.ShouldBind(&req); err != nil {
|
||||
resp.Code = proto.ParameterError
|
||||
resp.Message = "请求参数解析错误"
|
||||
} else {
|
||||
status, err := service.GetDNSServerStatus(req.ServerID, userID)
|
||||
if err != nil {
|
||||
resp.Code = proto.ErrorCode
|
||||
resp.Message = "获取DNS服务器状态失败: " + err.Error()
|
||||
} else {
|
||||
resp.Code = proto.SuccessCode
|
||||
resp.Message = "获取DNS服务器状态成功"
|
||||
resp.Data = status
|
||||
}
|
||||
}
|
||||
c.JSON(http.StatusOK, resp)
|
||||
}
|
||||
|
|
@ -141,7 +141,7 @@ func UploadFileV2(c *gin.Context) {
|
|||
}
|
||||
|
||||
user := dao.FindUserByUserID(id1)
|
||||
if user.Upload == false {
|
||||
if user.Upload <= 0 {
|
||||
c.JSON(http.StatusOK, gin.H{"error": "no upload Permissions", "code": proto.NoUploadPermissions, "message": "failed"})
|
||||
return
|
||||
}
|
||||
|
|
|
|||
124
handler/tool.go
124
handler/tool.go
|
|
@ -6,7 +6,9 @@ import (
|
|||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"time"
|
||||
"videoplayer/dao"
|
||||
|
|
@ -33,9 +35,9 @@ type GetFileListReq struct {
|
|||
}
|
||||
|
||||
type SendMailReq struct {
|
||||
Title string `json:"title" form:"title"`
|
||||
Content string `json:"content" form:"content"`
|
||||
To string `json:"to" form:"to"`
|
||||
Title string `json:"title" form:"title" binding:"required"`
|
||||
Content string `json:"content" form:"content" binding:"required"`
|
||||
To string `json:"to" form:"to" binding:"required"`
|
||||
}
|
||||
|
||||
func SetUpToolGroup(router *gin.Engine) {
|
||||
|
|
@ -57,6 +59,8 @@ func SetUpToolGroup(router *gin.Engine) {
|
|||
toolGroup.POST("/del_monitor", DelMonitor) //删除设备监控
|
||||
//发送邮件
|
||||
toolGroup.POST("/send_mail", SendMailTool)
|
||||
//下载代理
|
||||
toolGroup.GET("/dlp", DownloadProxyHandle)
|
||||
}
|
||||
|
||||
func GetMonitorList(c *gin.Context) {
|
||||
|
|
@ -254,7 +258,7 @@ func UploadFile(c *gin.Context) {
|
|||
}
|
||||
|
||||
user := dao.FindUserByUserID(id1)
|
||||
if user.Upload == false {
|
||||
if user.Upload <= 0 {
|
||||
c.JSON(http.StatusOK, gin.H{"error": "no upload Permissions", "code": proto.NoUploadPermissions, "message": "failed"})
|
||||
return
|
||||
}
|
||||
|
|
@ -347,7 +351,7 @@ func SetRedis(c *gin.Context) {
|
|||
id, _ := c.Get("id")
|
||||
id1 := int(id.(float64))
|
||||
user := dao.FindUserByUserID(id1)
|
||||
if user.Redis == false {
|
||||
if user.Redis <= 0 {
|
||||
c.JSON(http.StatusOK, gin.H{"error": "no redis Permissions", "code": proto.NoRedisPermissions, "message": "failed"})
|
||||
return
|
||||
}
|
||||
|
|
@ -375,7 +379,7 @@ func GetRedis(c *gin.Context) {
|
|||
id, _ := c.Get("id")
|
||||
id1 := int(id.(float64))
|
||||
user := dao.FindUserByUserID(id1)
|
||||
if user.Redis == false {
|
||||
if user.Redis <= 0 {
|
||||
c.JSON(http.StatusOK, gin.H{"error": "no redis Permissions", "code": proto.NoRedisPermissions, "message": "failed"})
|
||||
return
|
||||
}
|
||||
|
|
@ -440,41 +444,109 @@ func SendMail(title, content string) {
|
|||
em.SmtpUserName = "354425203@qq.com"
|
||||
em.SmtpPort = 587
|
||||
em.ImapPort = 993
|
||||
err := em.Send(title, content, []string{"3236990479@qq.com", "lijun@ljsea.top"})
|
||||
var targetMails []string
|
||||
for _, v := range proto.Config.MONITOR_MAIL {
|
||||
targetMails = append(targetMails, v.Value)
|
||||
}
|
||||
if targetMails == nil || len(targetMails) == 0 {
|
||||
return
|
||||
}
|
||||
err := em.Send(title, content, targetMails)
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
}
|
||||
}
|
||||
|
||||
func SendMailTool(c *gin.Context) {
|
||||
func RequestGetUserInfo(c *gin.Context) *dao.User {
|
||||
id, _ := c.Get("id")
|
||||
id1 := int(id.(float64))
|
||||
userId := int(id.(float64))
|
||||
user := service.GetUserByIDWithCache(userId)
|
||||
return &user
|
||||
}
|
||||
|
||||
func SendMailTool(c *gin.Context) {
|
||||
user := RequestGetUserInfo(c)
|
||||
var resp proto.GeneralResp
|
||||
var req SendMailReq
|
||||
if err := c.ShouldBind(&req); err == nil {
|
||||
user := dao.FindUserByUserID(id1)
|
||||
if user.ID == 0 {
|
||||
c.JSON(http.StatusOK, gin.H{"error": "user not found", "code": proto.ParameterError, "message": "failed"})
|
||||
return
|
||||
}
|
||||
//目标邮箱地址是否合法
|
||||
if !service.CheckEmail(req.To) {
|
||||
c.JSON(http.StatusOK, gin.H{"error": "email address is invalid", "code": proto.ParameterError, "message": "failed"})
|
||||
return
|
||||
}
|
||||
if req.Title == "" || req.Content == "" {
|
||||
c.JSON(http.StatusOK, gin.H{"error": "title or content is empty", "code": proto.ParameterError, "message": "failed"})
|
||||
return
|
||||
}
|
||||
//发送邮件
|
||||
if user.Role == "admin" {
|
||||
log.Println("send mail req:", req)
|
||||
go service.SendEmail(req.To, req.Title, req.Content)
|
||||
c.JSON(http.StatusOK, gin.H{"code": proto.SuccessCode, "message": "success", "data": "mail will be sent"})
|
||||
resp.Code, resp.Data, resp.Message = proto.SuccessCode, "mail will be sent", "success"
|
||||
} else {
|
||||
c.JSON(http.StatusOK, gin.H{"error": "no send mail permission", "code": proto.PermissionDenied, "message": "failed"})
|
||||
resp.Code, resp.Data, resp.Message = proto.PermissionDenied, "mail will be sent", "error"
|
||||
}
|
||||
} else {
|
||||
c.JSON(http.StatusOK, gin.H{"error": err.Error(), "code": proto.ParameterError, "message": "failed"})
|
||||
resp.Data, resp.Data, resp.Message = proto.ParameterError, "toEmail or title or content request param error", "success"
|
||||
}
|
||||
c.JSON(http.StatusOK, resp)
|
||||
}
|
||||
|
||||
// DownloadProxyHandle 处理下载代理请求
|
||||
func DownloadProxyHandle(c *gin.Context) {
|
||||
key := c.Query("key")
|
||||
if key == "" || key != proto.Config.DOWNLOAD_PROXY_KEY {
|
||||
c.JSON(http.StatusOK, gin.H{"code": proto.ParameterError, "message": "failed, key is null or error"})
|
||||
}
|
||||
// 获取URL参数
|
||||
encodedURL := c.Query("url")
|
||||
if encodedURL == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "URL参数不能为空", "code": proto.ParameterError, "message": "failed"})
|
||||
return
|
||||
}
|
||||
|
||||
// URL解码
|
||||
decodedURL, err := url.QueryUnescape(encodedURL)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "URL解码失败: " + err.Error(), "code": proto.ParameterError, "message": "failed"})
|
||||
return
|
||||
}
|
||||
|
||||
// 验证URL格式
|
||||
parsedURL, err := url.Parse(decodedURL)
|
||||
if err != nil || parsedURL.Scheme == "" || parsedURL.Host == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "无效的URL格式", "code": proto.ParameterError, "message": "failed"})
|
||||
return
|
||||
}
|
||||
|
||||
// 发起请求获取目标资源
|
||||
resp, err := http.Get(decodedURL)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "获取资源失败: " + err.Error(), "code": proto.InternalServerError})
|
||||
return
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
// 检查响应状态
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
c.JSON(http.StatusBadGateway, gin.H{"error": "目标资源请求失败,状态码: " + resp.Status, "code": proto.InternalServerError})
|
||||
return
|
||||
}
|
||||
|
||||
// 获取文件名
|
||||
filename := getFilenameFromURL(parsedURL)
|
||||
|
||||
// 设置响应头,告诉浏览器这是一个文件下载
|
||||
c.Header("Content-Disposition", "attachment; filename="+url.QueryEscape(filename))
|
||||
c.Header("Content-Type", resp.Header.Get("Content-Type"))
|
||||
c.Header("Content-Length", resp.Header.Get("Content-Length"))
|
||||
|
||||
// 将响应体流式传输到客户端
|
||||
_, err = io.Copy(c.Writer, resp.Body)
|
||||
if err != nil {
|
||||
// 已经开始传输数据后发生错误,无法返回JSON,只能记录日志
|
||||
log.Println("tool download proxy handle error:", err)
|
||||
}
|
||||
}
|
||||
|
||||
// 从URL中提取文件名
|
||||
func getFilenameFromURL(u *url.URL) string {
|
||||
// 从路径中提取文件名
|
||||
filename := filepath.Base(u.Path)
|
||||
// 如果路径中没有文件名,尝试从查询参数中获取
|
||||
if filename == "" || filename == "/" {
|
||||
filename = "download_file"
|
||||
}
|
||||
return filename
|
||||
}
|
||||
|
|
|
|||
35
main.go
35
main.go
|
|
@ -3,9 +3,6 @@ package main
|
|||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/golang-jwt/jwt"
|
||||
"github.com/robfig/cron/v3"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
|
|
@ -17,6 +14,10 @@ import (
|
|||
"videoplayer/proto"
|
||||
"videoplayer/service"
|
||||
"videoplayer/worker"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/golang-jwt/jwt"
|
||||
"github.com/robfig/cron/v3"
|
||||
)
|
||||
|
||||
func main() {
|
||||
|
|
@ -32,9 +33,11 @@ func main() {
|
|||
if err != nil {
|
||||
panic("failed to connect database:" + err.Error())
|
||||
}
|
||||
err = worker.InitRedis()
|
||||
if err != nil {
|
||||
panic("failed to connect redis:" + err.Error())
|
||||
if proto.Config.MEMORY_CACHE == false { //不开启内存缓存,才使用redis
|
||||
err = worker.InitRedis()
|
||||
if err != nil {
|
||||
panic("failed to connect redis:" + err.Error())
|
||||
}
|
||||
}
|
||||
r.Use(handler.CrosHandler())
|
||||
r.Use(JWTAuthMiddleware()) // 使用 JWT 认证中间件
|
||||
|
|
@ -47,6 +50,7 @@ func main() {
|
|||
handler.SetUpFileGroup(r) // File
|
||||
handler.SetUpShellGroup(r) // Shell
|
||||
handler.SetDBManageGroup(r) // DBM
|
||||
handler.SetDNSGroup(r) // DNS
|
||||
defer dao.Close()
|
||||
defer worker.CloseRedis()
|
||||
//定时任务
|
||||
|
|
@ -101,6 +105,10 @@ func initConfig(configPath string) {
|
|||
err := proto.ReadConfig(configPath)
|
||||
if err != nil {
|
||||
panic("failed to read config file:" + err.Error())
|
||||
} else {
|
||||
//输出配置文件
|
||||
config_bytes, _ := json.Marshal(proto.Config)
|
||||
log.Println(string(config_bytes))
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -157,7 +165,7 @@ func JWTAuthMiddleware() gin.HandlerFunc {
|
|||
}
|
||||
if tokenString == "" {
|
||||
//c.AbortWithStatus(200)
|
||||
c.JSON(http.StatusOK, gin.H{"message": "Unauthorized", "error": "token is empty", "code": proto.TokenIsNull})
|
||||
c.AbortWithStatusJSON(http.StatusOK, gin.H{"message": "Unauthorized", "error": "token is empty", "code": proto.TokenIsNull})
|
||||
return
|
||||
}
|
||||
if proto.Config.TOKEN_USE_REDIS {
|
||||
|
|
@ -232,7 +240,12 @@ func myTask() {
|
|||
RunGeneralCron()
|
||||
service.ShellWillRunFromServer()
|
||||
service.SyncTokenSecretFromUserCenter()
|
||||
|
||||
service.DelDBMMap() //定时处理DBMMap中的数据
|
||||
if proto.Config.MEMORY_CACHE {
|
||||
worker.DeleteMemoryCacheCron()
|
||||
// 清理后持久化
|
||||
worker.WriteMemoryCacheToFile()
|
||||
}
|
||||
}
|
||||
|
||||
func ReadConfigToSetSystem() {
|
||||
|
|
@ -385,13 +398,13 @@ func UserFuncIntercept(id int, url string) bool {
|
|||
//如果用户有权限,则不拦截
|
||||
for k, v := range proto.Per_menu_map {
|
||||
if strings.Contains(url, k) {
|
||||
if v == 1 && user.VideoFunc == false {
|
||||
if v == 1 && user.VideoFunc <= 0 {
|
||||
return true
|
||||
}
|
||||
if v == 2 && user.DeviceFunc == false {
|
||||
if v == 2 && user.DeviceFunc <= 0 {
|
||||
return true
|
||||
}
|
||||
if v == 3 && user.CIDFunc == false {
|
||||
if v == 3 && user.CIDFunc <= 0 {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -12,11 +12,13 @@ import (
|
|||
|
||||
var Config ConfigStruct
|
||||
var SigningKey = []byte{}
|
||||
var Url_map = map[string]bool{"/login": true, "/register": true, "/uuid": true, "/gqr": true, "/cid/callback": true, "/tool/monitor": true, "/user/sync": true, "/tool/file/": true, "/user/reset": true} // 不需要token验证的url
|
||||
var Url_map = map[string]bool{"/login": true, "/register": true, "/uuid": true, "/gqr": true, "/cid/callback": true, "/tool/monitor": true, "/user/sync": true, "/tool/file/": true, "/user/reset": true, "/tool/dlp": true} // 不需要token验证的url
|
||||
var Per_menu_map = map[string]int{"/video/": 1, "/device/": 2, "/cid/": 3}
|
||||
var File_Type = map[string]int{"im": 1, "avatar": 2, "file": 3, "config": 4} // 文件类型
|
||||
var CID_Running_Map = map[int][]CIDRunning{} //正在运行的cid
|
||||
|
||||
// 配置读写锁
|
||||
var CID_RunningMutex = sync.RWMutex{}
|
||||
var ConfigRWLock = &sync.RWMutex{}
|
||||
var SigningKeyRWLock = &sync.RWMutex{}
|
||||
|
||||
|
|
@ -27,13 +29,13 @@ var SigningKeyIsValid = true // 是否有效的签名密钥
|
|||
const (
|
||||
MYSQL_USER = "video_t2"
|
||||
MYSQL_DB = "video_t2"
|
||||
MYSQL_PASSWORD = "2t2SKHmWEYj2xFKF"
|
||||
MYSQL_PASSWORD = "2fdreYj2xFKF"
|
||||
MYSQL_PORT = "3306"
|
||||
MYSQL_HOST = "127.0.0.1"
|
||||
MYSQL_DSN = MYSQL_USER + ":" + MYSQL_PASSWORD + "@tcp(" + MYSQL_HOST + ":" + MYSQL_PORT + ")/" + MYSQL_DB + "?charset=utf8mb4&parseTime=True&loc=Local"
|
||||
|
||||
REDIS_ADDR = "127.0.0.1:6379"
|
||||
REDIS_PASSWORD = "lj502138"
|
||||
REDIS_PASSWORD = "lgybvueiogvter"
|
||||
REIDS_DB = 2
|
||||
|
||||
TOKEN_SECRET = "mfjurnc_32ndj9dfhj"
|
||||
|
|
@ -43,6 +45,8 @@ const (
|
|||
|
||||
// 以下是文件上传的配置
|
||||
FILE_BASE_DIR = "/home/lijun/file/"
|
||||
|
||||
DBMMap_Max_Keep_Time = 10 * 60 //DBMap中的数据最大保持时间,10min
|
||||
)
|
||||
|
||||
const (
|
||||
|
|
@ -73,29 +77,36 @@ type User struct {
|
|||
Email string `gorm:"column:email"`
|
||||
Gender string `gorm:"column:gender"`
|
||||
}
|
||||
type StructValue struct {
|
||||
Value string `json:"value" form:"value"`
|
||||
}
|
||||
|
||||
type ConfigStruct struct {
|
||||
DB int `json:"db"` // 0: mysql, 1: pg
|
||||
MYSQL_DSN string `json:"mysql_dsn"`
|
||||
PG_DSN string `json:"pg_dsn"`
|
||||
REDIS_ADDR string `json:"redis_addr"`
|
||||
TOKEN_USE_REDIS bool `json:"token_use_redis"`
|
||||
REDIS_User_PW bool `json:"redis_user_pw"` // 是否使用密码
|
||||
REDIS_PASSWORD string `json:"redis_password"`
|
||||
REDIS_DB int `json:"redis_db"`
|
||||
TOKEN_SECRET string `json:"token_secret"`
|
||||
CID_BASE_DIR string `json:"cid_base_dir"`
|
||||
FILE_BASE_DIR string `json:"file_base_dir"`
|
||||
MONITOR bool `json:"monitor"` // 状态监控及邮件通知
|
||||
SERVER_SQL_LOG bool `json:"server_sql_log"` // 服务器sql日志
|
||||
SERVER_PORT string `json:"server_port"` // 服务端口
|
||||
LOG_SAVE_DAYS int `json:"log_save_days"` // 日志保存天数,-1表示不保存,0表示永久保存
|
||||
SERVER_USER_TYPE string `json:"user_type"` // 服务器用户类型,master: 主服务器,slave: 从服务器,从服务器会定时同步数据
|
||||
MASTER_SERVER_DOMAIN string `json:"master_server_domain"` // 主服务器域名
|
||||
USER_SYNC_TIME int `json:"user_sync_time"` // 用户数据同步时间,单位秒
|
||||
SERVER_NAME string `json:"server_name"` // 服务器名称,用于区分不同服务器
|
||||
MONITOR_SERVER_TOKEN string `json:"monitor_server_token"` // 监控服务器token,用于状态监控及邮件通知
|
||||
APP_ID string `json:"app_id"` // 应用ID,用于标识不同应用
|
||||
DB int `json:"db"` // 0: mysql, 1: pg, 2:sqlite
|
||||
MYSQL_DSN string `json:"mysql_dsn"`
|
||||
PG_DSN string `json:"pg_dsn"`
|
||||
SQLITE_FILE string `json:"sqlite_file"`
|
||||
REDIS_ADDR string `json:"redis_addr"`
|
||||
TOKEN_USE_REDIS bool `json:"token_use_redis"`
|
||||
REDIS_User_PW bool `json:"redis_user_pw"` // 是否使用密码
|
||||
REDIS_PASSWORD string `json:"redis_password"`
|
||||
MEMORY_CACHE bool `json:"memory_cache"` //使用程序内缓存,开启这个redis将不生效
|
||||
REDIS_DB int `json:"redis_db"`
|
||||
TOKEN_SECRET string `json:"token_secret"`
|
||||
CID_BASE_DIR string `json:"cid_base_dir"`
|
||||
FILE_BASE_DIR string `json:"file_base_dir"`
|
||||
MONITOR bool `json:"monitor"` // 状态监控及邮件通知
|
||||
SERVER_SQL_LOG bool `json:"server_sql_log"` // 服务器sql日志
|
||||
SERVER_PORT string `json:"server_port"` // 服务端口
|
||||
LOG_SAVE_DAYS int `json:"log_save_days"` // 日志保存天数,-1表示不保存,0表示永久保存
|
||||
SERVER_USER_TYPE string `json:"user_type"` // 服务器用户类型,master: 主服务器,slave: 从服务器,从服务器会定时同步数据
|
||||
MASTER_SERVER_DOMAIN string `json:"master_server_domain"` // 主服务器域名
|
||||
USER_SYNC_TIME int `json:"user_sync_time"` // 用户数据同步时间,单位秒
|
||||
SERVER_NAME string `json:"server_name"` // 服务器名称,用于区分不同服务器
|
||||
MONITOR_SERVER_TOKEN string `json:"monitor_server_token"` // 监控服务器token,用于状态监控及邮件通知
|
||||
APP_ID string `json:"app_id"` // 应用ID,用于标识不同应用
|
||||
MONITOR_MAIL []StructValue `json:"monitor_mail"` // 设备监控邮件通知配置
|
||||
DOWNLOAD_PROXY_KEY string `json:"download_proxy_key"` // 下载代理key
|
||||
}
|
||||
|
||||
func WriteConfigToFile() {
|
||||
|
|
@ -121,25 +132,7 @@ func ReadConfig(path string) error {
|
|||
fmt.Println("Config file not found!")
|
||||
//创建默认配置
|
||||
DefaultConfig()
|
||||
//写入json文件
|
||||
file, err := os.Create(path)
|
||||
if err != nil {
|
||||
fmt.Println("Error creating config file")
|
||||
return err
|
||||
}
|
||||
defer file.Close()
|
||||
encoder := json.NewEncoder(file)
|
||||
|
||||
configData, err2 := json.MarshalIndent(Config, "", " ")
|
||||
if err2 != nil {
|
||||
log.Println("WriteConfigToFile json marshal error:", err)
|
||||
return err2
|
||||
}
|
||||
err = encoder.Encode(string(configData))
|
||||
if err != nil {
|
||||
fmt.Println("Error encoding config")
|
||||
}
|
||||
return err
|
||||
WriteConfigToFile()
|
||||
}
|
||||
|
||||
//读json文件
|
||||
|
|
@ -182,6 +175,7 @@ func DefaultConfig() {
|
|||
Config.MYSQL_DSN = MYSQL_DSN
|
||||
Config.PG_DSN = ""
|
||||
Config.REDIS_ADDR = REDIS_ADDR
|
||||
Config.SQLITE_FILE = ""
|
||||
Config.TOKEN_USE_REDIS = false
|
||||
Config.REDIS_User_PW = false
|
||||
Config.REDIS_PASSWORD = REDIS_PASSWORD
|
||||
|
|
|
|||
53
proto/dbm.go
53
proto/dbm.go
|
|
@ -1,6 +1,8 @@
|
|||
package proto
|
||||
|
||||
import "gorm.io/gorm"
|
||||
import (
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
const (
|
||||
DB_TYPE_MYSQL = 0 // DBTypeMySQL MySQL数据库
|
||||
|
|
@ -21,7 +23,7 @@ type RunSQLRequest struct {
|
|||
type DBManage struct {
|
||||
gorm.Model
|
||||
UserID uint `gorm:"column:user_id"` // 用户ID
|
||||
DB_IP string `gorm:"column:db_ip;type:varchar(255);uniqueIndex:idx_db_ip"` // 数据库IP
|
||||
DB_IP string `gorm:"column:db_ip;type:varchar(255)"` // 数据库IP
|
||||
DB_Port uint `gorm:"column:db_port"` // 数据库端口
|
||||
DB_NAME string `gorm:"column:db_name;type:varchar(255);uniqueIndex:idx_db_name"` // 数据库名称
|
||||
DB_User string `gorm:"column:db_user;type:varchar(255);uniqueIndex:idx_db_user"` // 数据库用户名
|
||||
|
|
@ -46,6 +48,7 @@ type CreateDBManageReq struct {
|
|||
DB_User string `json:"db_user" form:"db_user"` // 数据库用户名
|
||||
DB_Password string `json:"db_password" form:"db_password"` // 数据库密码
|
||||
DB_Type uint `json:"db_type" form:"db_type"` // 数据库类型: 0为mysql,1为postgres,2为sqlite,3为sqlserver,4为oracle,5为mongodb,6为redis
|
||||
DB_Desc string `json:"db_desc" form:"db_desc"` // 数据库描述备注
|
||||
}
|
||||
|
||||
type UpdateDBManageReq struct {
|
||||
|
|
@ -56,6 +59,7 @@ type UpdateDBManageReq struct {
|
|||
DB_User string `json:"db_user" form:"db_user"` // 数据库用户名
|
||||
DB_Password string `json:"db_password" form:"db_password"` // 数据库密码
|
||||
DB_Type uint `json:"db_type" form:"db_type"` // 数据库类型: 0为mysql,1为postgres,2为sqlite,3为sqlserver,4为oracle,5为mongodb,6为redis
|
||||
DB_Desc string `json:"db_desc" form:"db_desc"` // 数据库描述备注
|
||||
}
|
||||
|
||||
type GetDBManageReq struct {
|
||||
|
|
@ -67,3 +71,48 @@ type GetSQLRunHistoryReq struct {
|
|||
DB_ID uint `json:"db_id" form:"db_id"` // 数据库ID
|
||||
GET_TYPE int `json:"get_type" form:"get_type"` // 获取类型: 0获取自己,1为获取全部(管理员权限)
|
||||
}
|
||||
|
||||
// SQLResult 包含查询结果的列名顺序和对应数据
|
||||
type SQLResult struct {
|
||||
Columns []SQLResultColumnsValue // 列名顺序(与 SQL 查询的列顺序一致)
|
||||
Rows []map[string]interface{} // 每行数据(map 便于按列名访问)
|
||||
}
|
||||
|
||||
type SQLResultColumnsValue struct {
|
||||
Prop string `json:"prop"`
|
||||
Label string `json:"label"`
|
||||
Attr string `json:"attr"`
|
||||
}
|
||||
|
||||
type DeleteDBManageReq struct {
|
||||
DB_ID uint `json:"db_id" form:"db_id"` // 数据库ID
|
||||
Del_Type uint `json:"del_type" form:"del_type"` // 删除类型: 0为删除单条,1为所有
|
||||
UserID uint `json:"user_id" form:"user_id"` // 用户ID
|
||||
}
|
||||
|
||||
type DeleteDBManageSQLHistoryReq struct {
|
||||
DB_ID uint `json:"db_id" form:"db_id"` // 数据库ID
|
||||
Del_Type uint `json:"del_type" form:"del_type"` // 删除类型: 0为删除单条,1为所有
|
||||
History_ID uint `json:"history_id" form:"history_id"` // SQL执行历史ID,如果为0则删除所有
|
||||
UserID uint `json:"user_id" form:"user_id"` // 用户ID
|
||||
}
|
||||
|
||||
type GetDBTableDescReq struct {
|
||||
DB_ID uint `json:"db_id" form:"db_id"` // 数据库ID
|
||||
Table string `json:"table" form:"table"` // 数据库表名
|
||||
GetType int `json:"get_type" form:"get_type"` // 获取类型: 0获取全部,1获取1个
|
||||
}
|
||||
|
||||
type GetDBTableDescResp struct {
|
||||
TableName string `json:"table_name"` // 表名
|
||||
}
|
||||
|
||||
type DBTableAttribute struct {
|
||||
ColumnName string `json:"column_name"` // 列名
|
||||
ColumnType string `json:"column_type"` // 列类型
|
||||
}
|
||||
|
||||
type DBValue struct {
|
||||
LastUserTime int64 `json:"last_user_time"`
|
||||
Value *gorm.DB `json:"value"`
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,200 @@
|
|||
package proto
|
||||
|
||||
import (
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
const (
|
||||
DNS_STATUS_STOPPED = 0 // DNS服务器状态:已停止
|
||||
DNS_STATUS_RUNNING = 1 // DNS服务器状态:运行中
|
||||
DNS_STATUS_ERROR = 2 // DNS服务器状态:错误
|
||||
|
||||
RECORD_TYPE_A = 1 // A记录
|
||||
RECORD_TYPE_AAAA = 28 // AAAA记录
|
||||
RECORD_TYPE_CNAME = 5 // CNAME记录
|
||||
RECORD_TYPE_MX = 15 // MX记录
|
||||
RECORD_TYPE_NS = 2 // NS记录
|
||||
RECORD_TYPE_SOA = 6 // SOA记录
|
||||
RECORD_TYPE_TXT = 16 // TXT记录
|
||||
RECORD_TYPE_SRV = 33 // SRV记录
|
||||
)
|
||||
|
||||
type DNSServer struct {
|
||||
gorm.Model
|
||||
UserID uint `gorm:"column:user_id;index" json:"user_id" form:"user_id"` // 用户ID
|
||||
Name string `gorm:"column:name;type:varchar(255)" json:"name" form:"name"` // DNS服务器名称
|
||||
Port uint `gorm:"column:port;default:53" json:"port" form:"port"` // 监听端口,默认53
|
||||
ListenIP string `gorm:"column:listen_ip;type:varchar(255)" json:"listen_ip" form:"listen_ip"` // 监听IP,默认0.0.0.0
|
||||
UpstreamDNS string `gorm:"column:upstream_dns;type:varchar(255)" json:"upstream_dns" form:"upstream_dns"` // 上游DNS服务器,多个用逗号分隔
|
||||
EnableRecursion bool `gorm:"column:enable_recursion;default:true" json:"enable_recursion" form:"enable_recursion"` // 是否启用递归查询
|
||||
Status uint `gorm:"column:status;default:0" json:"status" form:"status"` // 状态:0停止,1运行中,2错误
|
||||
Description string `gorm:"column:description;type:text" json:"description" form:"description"` // 描述
|
||||
Zones []DNSZone `gorm:"foreignKey:ServerID" json:"zones,omitempty"` // 关联的Zone
|
||||
}
|
||||
|
||||
type DNSZone struct {
|
||||
gorm.Model
|
||||
ServerID uint `gorm:"column:server_id;index" json:"server_id" form:"server_id"` // 所属DNS服务器ID
|
||||
Domain string `gorm:"column:domain;type:varchar(255);index" json:"domain" form:"domain"` // 域名,如 example.com
|
||||
SOA_MName string `gorm:"column:soa_mname;type:varchar(255)" json:"soa_mname" form:"soa_mname"` // SOA记录的主域名服务器
|
||||
SOA_RName string `gorm:"column:soa_rname;type:varchar(255)" json:"soa_rname" form:"soa_rname"` // SOA记录的管理员邮箱
|
||||
SOA_Serial uint `gorm:"column:soa_serial;default:1" json:"soa_serial" form:"soa_serial"` // SOA记录的序列号
|
||||
SOA_Refresh uint `gorm:"column:soa_refresh;default:86400" json:"soa_refresh" form:"soa_refresh"` // SOA记录的刷新时间(秒)
|
||||
SOA_Retry uint `gorm:"column:soa_retry;default:7200" json:"soa_retry" form:"soa_retry"` // SOA记录的重试时间(秒)
|
||||
SOA_Expire uint `gorm:"column:soa_expire;default:3600000" json:"soa_expire" form:"soa_expire"` // SOA记录的过期时间(秒)
|
||||
SOA_Minimum uint `gorm:"column:soa_minimum;default:3600" json:"soa_minimum" form:"soa_minimum"` // SOA记录的最小TTL(秒)
|
||||
TTL uint `gorm:"column:ttl;default:3600" json:"ttl" form:"ttl"` // 默认TTL(秒)
|
||||
Description string `gorm:"column:description;type:text" json:"description" form:"description"` // 描述
|
||||
Server DNSServer `gorm:"foreignKey:ServerID" json:"server,omitempty"` // 关联的DNS服务器
|
||||
Records []DNSRecord `gorm:"foreignKey:ZoneID" json:"records,omitempty"` // 关联的记录
|
||||
}
|
||||
|
||||
type DNSRecord struct {
|
||||
gorm.Model
|
||||
ZoneID uint `gorm:"column:zone_id;index" json:"zone_id" form:"zone_id"` // 所属Zone ID
|
||||
Name string `gorm:"column:name;type:varchar(255);index" json:"name" form:"name"` // 记录名称,如 www 或 @
|
||||
Type uint `gorm:"column:type;index" json:"type" form:"type"` // 记录类型:1=A, 28=AAAA, 5=CNAME, 15=MX等
|
||||
Value string `gorm:"column:value;type:text" json:"value" form:"value"` // 记录值
|
||||
TTL uint `gorm:"column:ttl;default:3600" json:"ttl" form:"ttl"` // TTL(秒),如果为0则使用Zone的默认TTL
|
||||
Priority uint `gorm:"column:priority;default:0" json:"priority" form:"priority"` // 优先级(用于MX、SRV等记录)
|
||||
Weight uint `gorm:"column:weight;default:0" json:"weight" form:"weight"` // 权重(用于SRV记录)
|
||||
Port uint `gorm:"column:port;default:0" json:"port" form:"port"` // 端口(用于SRV记录)
|
||||
Target string `gorm:"column:target;type:varchar(255)" json:"target" form:"target"` // 目标(用于SRV记录)
|
||||
Zone DNSZone `gorm:"foreignKey:ZoneID" json:"zone,omitempty"` // 关联的Zone
|
||||
}
|
||||
|
||||
// DNSServer 创建请求
|
||||
type CreateDNSServerReq struct {
|
||||
Name string `json:"name" form:"name"` // DNS服务器名称
|
||||
Port uint `json:"port" form:"port"` // 监听端口,默认53
|
||||
ListenIP string `json:"listen_ip" form:"listen_ip"` // 监听IP,默认0.0.0.0
|
||||
UpstreamDNS string `json:"upstream_dns" form:"upstream_dns"` // 上游DNS服务器,多个用逗号分隔
|
||||
EnableRecursion bool `json:"enable_recursion" form:"enable_recursion"` // 是否启用递归查询
|
||||
Description string `json:"description" form:"description"` // 描述
|
||||
}
|
||||
|
||||
// DNSServer 更新请求
|
||||
type UpdateDNSServerReq struct {
|
||||
ServerID uint `json:"server_id" form:"server_id"` // DNS服务器ID
|
||||
Name string `json:"name" form:"name"` // DNS服务器名称
|
||||
Port uint `json:"port" form:"port"` // 监听端口
|
||||
ListenIP string `json:"listen_ip" form:"listen_ip"` // 监听IP
|
||||
UpstreamDNS string `json:"upstream_dns" form:"upstream_dns"` // 上游DNS服务器
|
||||
EnableRecursion bool `json:"enable_recursion" form:"enable_recursion"` // 是否启用递归查询
|
||||
Status uint `json:"status" form:"status"` // 状态:0停止,1运行中,2错误
|
||||
Description string `json:"description" form:"description"` // 描述
|
||||
}
|
||||
|
||||
// DNSServer 获取请求
|
||||
type GetDNSServerReq struct {
|
||||
ServerID uint `json:"server_id" form:"server_id"` // DNS服务器ID,0表示获取全部
|
||||
GetType int `json:"get_type" form:"get_type"` // 获取类型:0获取自己的,1获取全部(管理员)
|
||||
}
|
||||
|
||||
// DNSServer 删除请求
|
||||
type DeleteDNSServerReq struct {
|
||||
ServerID uint `json:"server_id" form:"server_id"` // DNS服务器ID
|
||||
DelType uint `json:"del_type" form:"del_type"` // 删除类型:0删除单条,1删除所有
|
||||
}
|
||||
|
||||
// DNSZone 创建请求
|
||||
type CreateDNSZoneReq struct {
|
||||
ServerID uint `json:"server_id" form:"server_id"` // 所属DNS服务器ID
|
||||
Domain string `json:"domain" form:"domain"` // 域名,如 example.com
|
||||
SOA_MName string `json:"soa_mname" form:"soa_mname"` // SOA记录的主域名服务器
|
||||
SOA_RName string `json:"soa_rname" form:"soa_rname"` // SOA记录的管理员邮箱
|
||||
SOA_Serial uint `json:"soa_serial" form:"soa_serial"` // SOA记录的序列号
|
||||
SOA_Refresh uint `json:"soa_refresh" form:"soa_refresh"` // SOA记录的刷新时间(秒)
|
||||
SOA_Retry uint `json:"soa_retry" form:"soa_retry"` // SOA记录的重试时间(秒)
|
||||
SOA_Expire uint `json:"soa_expire" form:"soa_expire"` // SOA记录的过期时间(秒)
|
||||
SOA_Minimum uint `json:"soa_minimum" form:"soa_minimum"` // SOA记录的最小TTL(秒)
|
||||
TTL uint `json:"ttl" form:"ttl"` // 默认TTL(秒)
|
||||
Description string `json:"description" form:"description"` // 描述
|
||||
}
|
||||
|
||||
// DNSZone 更新请求
|
||||
type UpdateDNSZoneReq struct {
|
||||
ZoneID uint `json:"zone_id" form:"zone_id"` // Zone ID
|
||||
Domain string `json:"domain" form:"domain"` // 域名
|
||||
SOA_MName string `json:"soa_mname" form:"soa_mname"` // SOA记录的主域名服务器
|
||||
SOA_RName string `json:"soa_rname" form:"soa_rname"` // SOA记录的管理员邮箱
|
||||
SOA_Serial uint `json:"soa_serial" form:"soa_serial"` // SOA记录的序列号
|
||||
SOA_Refresh uint `json:"soa_refresh" form:"soa_refresh"` // SOA记录的刷新时间(秒)
|
||||
SOA_Retry uint `json:"soa_retry" form:"soa_retry"` // SOA记录的重试时间(秒)
|
||||
SOA_Expire uint `json:"soa_expire" form:"soa_expire"` // SOA记录的过期时间(秒)
|
||||
SOA_Minimum uint `json:"soa_minimum" form:"soa_minimum"` // SOA记录的最小TTL(秒)
|
||||
TTL uint `json:"ttl" form:"ttl"` // 默认TTL(秒)
|
||||
Description string `json:"description" form:"description"` // 描述
|
||||
}
|
||||
|
||||
// DNSZone 获取请求
|
||||
type GetDNSZoneReq struct {
|
||||
ZoneID uint `json:"zone_id" form:"zone_id"` // Zone ID,0表示获取全部
|
||||
ServerID uint `json:"server_id" form:"server_id"` // DNS服务器ID,用于过滤
|
||||
GetType int `json:"get_type" form:"get_type"` // 获取类型:0获取自己的,1获取全部(管理员)
|
||||
}
|
||||
|
||||
// DNSZone 删除请求
|
||||
type DeleteDNSZoneReq struct {
|
||||
ZoneID uint `json:"zone_id" form:"zone_id"` // Zone ID
|
||||
DelType uint `json:"del_type" form:"del_type"` // 删除类型:0删除单条,1删除所有
|
||||
}
|
||||
|
||||
// DNSRecord 创建请求
|
||||
type CreateDNSRecordReq struct {
|
||||
ZoneID uint `json:"zone_id" form:"zone_id"` // 所属Zone ID
|
||||
Name string `json:"name" form:"name"` // 记录名称,如 www 或 @
|
||||
Type uint `json:"type" form:"type"` // 记录类型:1=A, 28=AAAA, 5=CNAME, 15=MX等
|
||||
Value string `json:"value" form:"value"` // 记录值
|
||||
TTL uint `json:"ttl" form:"ttl"` // TTL(秒)
|
||||
Priority uint `json:"priority" form:"priority"` // 优先级(用于MX、SRV等记录)
|
||||
Weight uint `json:"weight" form:"weight"` // 权重(用于SRV记录)
|
||||
Port uint `json:"port" form:"port"` // 端口(用于SRV记录)
|
||||
Target string `json:"target" form:"target"` // 目标(用于SRV记录)
|
||||
}
|
||||
|
||||
// DNSRecord 更新请求
|
||||
type UpdateDNSRecordReq struct {
|
||||
RecordID uint `json:"record_id" form:"record_id"` // 记录ID
|
||||
Name string `json:"name" form:"name"` // 记录名称
|
||||
Type uint `json:"type" form:"type"` // 记录类型
|
||||
Value string `json:"value" form:"value"` // 记录值
|
||||
TTL uint `json:"ttl" form:"ttl"` // TTL(秒)
|
||||
Priority uint `json:"priority" form:"priority"` // 优先级
|
||||
Weight uint `json:"weight" form:"weight"` // 权重
|
||||
Port uint `json:"port" form:"port"` // 端口
|
||||
Target string `json:"target" form:"target"` // 目标
|
||||
}
|
||||
|
||||
// DNSRecord 获取请求
|
||||
type GetDNSRecordReq struct {
|
||||
RecordID uint `json:"record_id" form:"record_id"` // 记录ID,0表示获取全部
|
||||
ZoneID uint `json:"zone_id" form:"zone_id"` // Zone ID,用于过滤
|
||||
GetType int `json:"get_type" form:"get_type"` // 获取类型:0获取自己的,1获取全部(管理员)
|
||||
}
|
||||
|
||||
// DNSRecord 删除请求
|
||||
type DeleteDNSRecordReq struct {
|
||||
RecordID uint `json:"record_id" form:"record_id"` // 记录ID
|
||||
DelType uint `json:"del_type" form:"del_type"` // 删除类型:0删除单条,1删除所有
|
||||
}
|
||||
|
||||
// 启动DNS服务器请求
|
||||
type StartDNSServerReq struct {
|
||||
ServerID uint `json:"server_id" form:"server_id" binding:"required"` // DNS服务器ID
|
||||
}
|
||||
|
||||
// 停止DNS服务器请求
|
||||
type StopDNSServerReq struct {
|
||||
ServerID uint `json:"server_id" form:"server_id" binding:"required"` // DNS服务器ID
|
||||
}
|
||||
|
||||
// 重启DNS服务器请求
|
||||
type RestartDNSServerReq struct {
|
||||
ServerID uint `json:"server_id" form:"server_id" binding:"required"` // DNS服务器ID
|
||||
}
|
||||
|
||||
// 获取DNS服务器状态请求
|
||||
type GetDNSServerStatusReq struct {
|
||||
ServerID uint `json:"server_id" form:"server_id" binding:"required"` // DNS服务器ID
|
||||
}
|
||||
10
proto/im.go
10
proto/im.go
|
|
@ -1,5 +1,7 @@
|
|||
package proto
|
||||
|
||||
import "time"
|
||||
|
||||
type ImKeyReq struct {
|
||||
To_user_id int `json:"to_user_id" form:"to_user_id" binding:"required"`
|
||||
}
|
||||
|
|
@ -12,3 +14,11 @@ type Message struct {
|
|||
From_user_id int `json:"from_user_id"`
|
||||
Session string `json:"session"`
|
||||
}
|
||||
|
||||
// cid正在运行结构
|
||||
type CIDRunning struct {
|
||||
ID int `json:"id" form:"id"` //cid的id
|
||||
CID string `json:"cid" form:"cid"` //cid名称
|
||||
AuthID int `json:"auth_id" form:"auth_id"` //所属用户
|
||||
StartTime time.Time `json:"start_time" form:"start_time"` //开始时间
|
||||
}
|
||||
|
|
|
|||
|
|
@ -5,3 +5,8 @@ type GeneralResp struct {
|
|||
Message string `json:"message"`
|
||||
Data any `json:"data"`
|
||||
}
|
||||
|
||||
type CIDCallBackReq struct {
|
||||
Token string `json:"token" form:"token"`
|
||||
ID int `json:"id" form:"id"`
|
||||
}
|
||||
|
|
|
|||
|
|
@ -81,8 +81,11 @@ const (
|
|||
SigningKeyVersionIsTooOld = 200
|
||||
|
||||
//下面是数据库管理工具-错误状态码 100x
|
||||
DBMRunSQLFailed = 1001 // 执行SQL失败
|
||||
DBMCreateFailed = 1002 // 创建数据库管理失败
|
||||
DBMGetFailed = 1003 // 获取数据库管理信息失败`
|
||||
DBMUpdateFailed = 1004 // 更新数据库管理信息失败
|
||||
DBMRunSQLFailed = 1001 // 执行SQL失败
|
||||
DBMCreateFailed = 1002 // 创建数据库管理失败
|
||||
DBMGetFailed = 1003 // 获取数据库管理信息失败`
|
||||
DBMUpdateFailed = 1004 // 更新数据库管理信息失败
|
||||
DBMDeleteFailed = 1005 // 删除数据库管理信息失败
|
||||
DBMRunSQLHistoryDeleteFailed = 1006 // 删除SQL运行历史失败
|
||||
DBMGetTableDescFailed = 1007 // 获取表描述信息失败
|
||||
)
|
||||
|
|
|
|||
|
|
@ -8,9 +8,10 @@ import (
|
|||
"strconv"
|
||||
"videoplayer/dao"
|
||||
"videoplayer/proto"
|
||||
"videoplayer/worker"
|
||||
)
|
||||
|
||||
func RunSQL(req *proto.RunSQLRequest) ([]map[string]interface{}, error) {
|
||||
func RunSQL(req *proto.RunSQLRequest) (*proto.SQLResult, error) {
|
||||
|
||||
dbmInfo, err := dao.FindDBManageByID(req.DB_ID)
|
||||
if err != nil {
|
||||
|
|
@ -23,7 +24,7 @@ func RunSQL(req *proto.RunSQLRequest) ([]map[string]interface{}, error) {
|
|||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
res, err := dao.RunSQL(req.SQL, db_)
|
||||
res, err := dao.RunSQLWithOrder(req.SQL, db_)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
|
@ -33,10 +34,20 @@ func RunSQL(req *proto.RunSQLRequest) ([]map[string]interface{}, error) {
|
|||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return res, nil
|
||||
return &res, nil
|
||||
}
|
||||
|
||||
func GetGORMDBObject(dbmInfo *proto.DBManage) (db_ *gorm.DB, err error) {
|
||||
//dao.DBMMapRWMutex.RLock()
|
||||
if dao.DBMMap != nil {
|
||||
dbValue := dao.DBMMap[dbmInfo.ID]
|
||||
if dbValue != nil {
|
||||
dbValue.LastUserTime = worker.GetCurrentTimestamp()
|
||||
return dbValue.Value, nil
|
||||
}
|
||||
}
|
||||
//dao.DBMMapRWMutex.RUnlock()
|
||||
|
||||
switch dbmInfo.DB_Type {
|
||||
case proto.DB_TYPE_MYSQL: // MySQL
|
||||
dsn := dbmInfo.DB_User + ":" + dbmInfo.DB_Password + "@tcp(" + dbmInfo.DB_IP + ":" + strconv.Itoa(int(dbmInfo.DB_Port)) + ")/" + dbmInfo.DB_NAME + "?charset=utf8mb4&parseTime=True&loc=Local"
|
||||
|
|
@ -46,6 +57,7 @@ func GetGORMDBObject(dbmInfo *proto.DBManage) (db_ *gorm.DB, err error) {
|
|||
}
|
||||
case proto.DB_TYPE_POSTGRES: // PostgreSQL
|
||||
dsn := "host=" + dbmInfo.DB_IP + " user=" + dbmInfo.DB_User + " password=" + dbmInfo.DB_Password + " dbname=" + dbmInfo.DB_NAME + " port=" + strconv.Itoa(int(dbmInfo.DB_Port)) + " sslmode=disable TimeZone=Asia/Shanghai"
|
||||
|
||||
db_, err = gorm.Open(postgres.Open(dsn), &gorm.Config{})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
|
@ -53,6 +65,13 @@ func GetGORMDBObject(dbmInfo *proto.DBManage) (db_ *gorm.DB, err error) {
|
|||
default:
|
||||
err = errors.New("unsupported database type")
|
||||
}
|
||||
|
||||
dao.DBMMapRWMutex.Lock()
|
||||
var dbValue proto.DBValue
|
||||
dbValue.Value = db_
|
||||
dbValue.LastUserTime = worker.GetCurrentTimestamp()
|
||||
dao.DBMMap[dbmInfo.ID] = &dbValue
|
||||
dao.DBMMapRWMutex.Unlock()
|
||||
return db_, err
|
||||
}
|
||||
|
||||
|
|
@ -65,7 +84,7 @@ func CreateDBManage(req *proto.CreateDBManageReq, userID uint) (proto.DBManage,
|
|||
DB_User: req.DB_User,
|
||||
DB_Password: req.DB_Password,
|
||||
DB_Type: req.DB_Type,
|
||||
DB_Desc: "",
|
||||
DB_Desc: req.DB_Desc,
|
||||
DB_STATUS: 0, // 初始状态为未连接
|
||||
}
|
||||
|
||||
|
|
@ -103,7 +122,11 @@ func GetSQLRunHistory(req *proto.GetSQLRunHistoryReq, userID int) ([]proto.SQLRu
|
|||
var err error
|
||||
|
||||
if req.GET_TYPE == 0 { // 获取自己的SQL执行历史
|
||||
historyList, err = dao.FindDBRunHistoryByAuthID(userID)
|
||||
if req.DB_ID > 0 {
|
||||
historyList, err = dao.FindDBRunHistoryByAuthIDAndDbId(userID, req.DB_ID)
|
||||
} else {
|
||||
historyList, err = dao.FindDBRunHistoryByAuthID(userID)
|
||||
}
|
||||
} else if req.GET_TYPE == 1 { // 管理员获取所有SQL执行历史
|
||||
user := GetUserByIDFromUserCenter(userID)
|
||||
if user.Role != "admin" {
|
||||
|
|
@ -133,6 +156,7 @@ func UpdateDBManage(req *proto.UpdateDBManageReq, userID int) (proto.DBManage, e
|
|||
dbmInfo.DB_User = req.DB_User
|
||||
dbmInfo.DB_Password = req.DB_Password
|
||||
dbmInfo.DB_Type = req.DB_Type
|
||||
dbmInfo.DB_Desc = req.DB_Desc
|
||||
|
||||
err = dao.UpdateDBManage(dbmInfo.ID, &dbmInfo)
|
||||
if err != nil {
|
||||
|
|
@ -140,3 +164,87 @@ func UpdateDBManage(req *proto.UpdateDBManageReq, userID int) (proto.DBManage, e
|
|||
}
|
||||
return dbmInfo, nil
|
||||
}
|
||||
|
||||
func DeleteDBManage(req *proto.DeleteDBManageReq, userId int) error {
|
||||
user := GetUserByIDFromUserCenter(userId)
|
||||
if req.Del_Type == 0 && req.DB_ID > 0 {
|
||||
dbmInfo, err := dao.FindDBManageByID(req.DB_ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if dbmInfo.UserID != uint(req.UserID) && user.Role != "admin" {
|
||||
return errors.New("unauthorized access to the database management system")
|
||||
}
|
||||
err = dao.DeleteDBManageByID(req.DB_ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
} else if req.Del_Type == 1 && req.UserID > 0 {
|
||||
if req.UserID != uint(userId) && user.Role != "admin" {
|
||||
return errors.New("unauthorized access to delete all database management systems")
|
||||
}
|
||||
err := dao.DeleteDBManageByUserID(req.UserID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
return errors.New("invalid delete type or parameters")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func DeleteSQLRunHistory(req *proto.DeleteDBManageSQLHistoryReq, userId int) error {
|
||||
user := GetUserByIDFromUserCenter(userId)
|
||||
if req.Del_Type == 0 && req.History_ID > 0 {
|
||||
history, err := dao.FindDBRunHistoryByID(req.History_ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if history.UserID != uint(req.UserID) && user.Role != "admin" {
|
||||
return errors.New("unauthorized access to the SQL run history")
|
||||
}
|
||||
err = dao.DelSQLRunHistoryByID(req.History_ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
} else if req.Del_Type == 1 && req.UserID > 0 {
|
||||
if req.UserID != uint(userId) && user.Role != "admin" {
|
||||
return errors.New("unauthorized access to delete all SQL run history")
|
||||
}
|
||||
err := dao.DelSQLRunHistoryByAuthID(int(req.UserID))
|
||||
return err
|
||||
} else {
|
||||
return errors.New("invalid delete type or parameters")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func GetDBTableDesc(req *proto.GetDBTableDescReq, userId int) (*proto.SQLResult, error) {
|
||||
//dbmInfo, err := dao.FindDBManageByID(req.DB_ID)
|
||||
//if err != nil {`
|
||||
// return nil, err
|
||||
//}
|
||||
//if dbmInfo.UserID != uint(userId) && GetUserByIDFromUserCenter(userId).Role != "admin" {
|
||||
// return nil, errors.New("unauthorized access to the database management system")
|
||||
//}
|
||||
//db_, err := GetGORMDBObject(&dbmInfo)
|
||||
//if err != nil {
|
||||
// return nil, err
|
||||
//}
|
||||
//res, err := dao.GetDBTableDesc(db_, req.Table, req.GetType)
|
||||
//if err != nil {
|
||||
// return nil, err
|
||||
//}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func DelDBMMap() {
|
||||
dao.DBMMapRWMutex.Lock()
|
||||
cur := worker.GetCurrentTimestamp()
|
||||
for k, v := range dao.DBMMap {
|
||||
if (cur - v.LastUserTime) > proto.DBMMap_Max_Keep_Time {
|
||||
delete(dao.DBMMap, k) //删除
|
||||
}
|
||||
}
|
||||
dao.DBMMapRWMutex.Unlock()
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,786 @@
|
|||
package service
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"sync"
|
||||
"videoplayer/dao"
|
||||
"videoplayer/proto"
|
||||
|
||||
"github.com/miekg/dns"
|
||||
)
|
||||
|
||||
// DNSServiceInstance 运行中的DNS服务实例
|
||||
type DNSServiceInstance struct {
|
||||
ServerID uint `json:"server_id"`
|
||||
Config *proto.DNSServer `json:"config"`
|
||||
Server *dns.Server `json:"-"`
|
||||
Running bool `json:"running"`
|
||||
mutex sync.Mutex `json:"-"`
|
||||
}
|
||||
|
||||
// DNSServiceManager DNS服务管理器
|
||||
type DNSServiceManager struct {
|
||||
instances map[uint]*DNSServiceInstance
|
||||
rwMutex sync.RWMutex
|
||||
}
|
||||
|
||||
var dnsServiceManager *DNSServiceManager
|
||||
|
||||
func init() {
|
||||
dnsServiceManager = &DNSServiceManager{
|
||||
instances: make(map[uint]*DNSServiceInstance),
|
||||
}
|
||||
}
|
||||
|
||||
// ==================== DNSServer 相关操作 ====================
|
||||
|
||||
func CreateDNSServer(req *proto.CreateDNSServerReq, userID uint) (proto.DNSServer, error) {
|
||||
server := proto.DNSServer{
|
||||
UserID: userID,
|
||||
Name: req.Name,
|
||||
Port: req.Port,
|
||||
ListenIP: req.ListenIP,
|
||||
UpstreamDNS: req.UpstreamDNS,
|
||||
EnableRecursion: req.EnableRecursion,
|
||||
Status: proto.DNS_STATUS_STOPPED,
|
||||
Description: req.Description,
|
||||
}
|
||||
|
||||
if server.Port == 0 {
|
||||
server.Port = 53
|
||||
}
|
||||
if server.ListenIP == "" {
|
||||
server.ListenIP = "0.0.0.0"
|
||||
}
|
||||
|
||||
id, err := dao.CreateDNSServer(server)
|
||||
if err != nil {
|
||||
return proto.DNSServer{}, err
|
||||
}
|
||||
server.ID = id
|
||||
return server, nil
|
||||
}
|
||||
|
||||
func GetDNSServerList(req *proto.GetDNSServerReq, userID uint) ([]proto.DNSServer, error) {
|
||||
var servers []proto.DNSServer
|
||||
var err error
|
||||
|
||||
if req.ServerID > 0 {
|
||||
server, err := dao.FindDNSServerByID(req.ServerID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if server.UserID != userID && GetUserByIDFromUserCenter(int(userID)).Role != "admin" {
|
||||
return nil, errors.New("未授权访问DNS服务器")
|
||||
}
|
||||
servers = append(servers, server)
|
||||
} else {
|
||||
if req.GetType == 0 {
|
||||
servers, err = dao.FindDNSServerByUserID(userID)
|
||||
} else if req.GetType == 1 {
|
||||
user := GetUserByIDFromUserCenter(int(userID))
|
||||
if user.Role != "admin" {
|
||||
return nil, errors.New("未授权访问,仅管理员可获取全部DNS服务器")
|
||||
}
|
||||
servers, err = dao.FindAllDNSServer()
|
||||
} else {
|
||||
return nil, errors.New("无效的获取类型")
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return servers, nil
|
||||
}
|
||||
|
||||
func UpdateDNSServer(req *proto.UpdateDNSServerReq, userID int) (proto.DNSServer, error) {
|
||||
server, err := dao.FindDNSServerByID(req.ServerID)
|
||||
if err != nil {
|
||||
return proto.DNSServer{}, err
|
||||
}
|
||||
if server.UserID != uint(userID) && GetUserByIDFromUserCenter(userID).Role != "admin" {
|
||||
return proto.DNSServer{}, errors.New("未授权访问DNS服务器")
|
||||
}
|
||||
|
||||
server.Name = req.Name
|
||||
server.Port = req.Port
|
||||
server.ListenIP = req.ListenIP
|
||||
server.UpstreamDNS = req.UpstreamDNS
|
||||
server.EnableRecursion = req.EnableRecursion
|
||||
server.Status = req.Status
|
||||
server.Description = req.Description
|
||||
|
||||
err = dao.UpdateDNSServer(server.ID, &server)
|
||||
if err != nil {
|
||||
return proto.DNSServer{}, err
|
||||
}
|
||||
|
||||
// 如果服务正在运行,自动重启以应用新配置
|
||||
go RestartDNSServerIfRunning(req.ServerID, userID)
|
||||
|
||||
return server, nil
|
||||
}
|
||||
|
||||
func DeleteDNSServer(req *proto.DeleteDNSServerReq, userID int) error {
|
||||
user := GetUserByIDFromUserCenter(userID)
|
||||
if req.DelType == 0 && req.ServerID > 0 {
|
||||
server, err := dao.FindDNSServerByID(req.ServerID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if server.UserID != uint(userID) && user.Role != "admin" {
|
||||
return errors.New("未授权访问DNS服务器")
|
||||
}
|
||||
err = dao.DeleteDNSZoneByServerID(req.ServerID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = dao.DeleteDNSServerByID(req.ServerID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
} else if req.DelType == 1 {
|
||||
if user.Role != "admin" {
|
||||
return errors.New("未授权访问,仅管理员可删除所有DNS服务器")
|
||||
}
|
||||
servers, err := dao.FindAllDNSServer()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, server := range servers {
|
||||
err = dao.DeleteDNSZoneByServerID(server.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = dao.DeleteDNSServerByID(server.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
} else {
|
||||
return errors.New("无效的删除类型或参数")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ==================== DNSZone 相关操作 ====================
|
||||
|
||||
func CreateDNSZone(req *proto.CreateDNSZoneReq, userID uint) (proto.DNSZone, error) {
|
||||
server, err := dao.FindDNSServerByID(req.ServerID)
|
||||
if err != nil {
|
||||
return proto.DNSZone{}, err
|
||||
}
|
||||
if server.UserID != userID && GetUserByIDFromUserCenter(int(userID)).Role != "admin" {
|
||||
return proto.DNSZone{}, errors.New("未授权访问DNS服务器")
|
||||
}
|
||||
|
||||
zone := proto.DNSZone{
|
||||
ServerID: req.ServerID,
|
||||
Domain: req.Domain,
|
||||
SOA_MName: req.SOA_MName,
|
||||
SOA_RName: req.SOA_RName,
|
||||
SOA_Serial: req.SOA_Serial,
|
||||
SOA_Refresh: req.SOA_Refresh,
|
||||
SOA_Retry: req.SOA_Retry,
|
||||
SOA_Expire: req.SOA_Expire,
|
||||
SOA_Minimum: req.SOA_Minimum,
|
||||
TTL: req.TTL,
|
||||
Description: req.Description,
|
||||
}
|
||||
|
||||
if zone.SOA_Serial == 0 {
|
||||
zone.SOA_Serial = 1
|
||||
}
|
||||
if zone.SOA_Refresh == 0 {
|
||||
zone.SOA_Refresh = 86400
|
||||
}
|
||||
if zone.SOA_Retry == 0 {
|
||||
zone.SOA_Retry = 7200
|
||||
}
|
||||
if zone.SOA_Expire == 0 {
|
||||
zone.SOA_Expire = 3600000
|
||||
}
|
||||
if zone.SOA_Minimum == 0 {
|
||||
zone.SOA_Minimum = 3600
|
||||
}
|
||||
if zone.TTL == 0 {
|
||||
zone.TTL = 3600
|
||||
}
|
||||
|
||||
id, err := dao.CreateDNSZone(zone)
|
||||
if err != nil {
|
||||
return proto.DNSZone{}, err
|
||||
}
|
||||
zone.ID = id
|
||||
return zone, nil
|
||||
}
|
||||
|
||||
func GetDNSZoneList(req *proto.GetDNSZoneReq, userID uint) ([]proto.DNSZone, error) {
|
||||
var zones []proto.DNSZone
|
||||
var err error
|
||||
|
||||
if req.ZoneID > 0 {
|
||||
zone, err := dao.FindDNSZoneByID(req.ZoneID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
server, err := dao.FindDNSServerByID(zone.ServerID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if server.UserID != userID && GetUserByIDFromUserCenter(int(userID)).Role != "admin" {
|
||||
return nil, errors.New("未授权访问DNS区域")
|
||||
}
|
||||
zones = append(zones, zone)
|
||||
} else {
|
||||
if req.GetType == 0 {
|
||||
if req.ServerID > 0 {
|
||||
zones, err = dao.FindDNSZoneByServerID(req.ServerID)
|
||||
} else {
|
||||
servers, err := dao.FindDNSServerByUserID(userID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, server := range servers {
|
||||
serverZones, err := dao.FindDNSZoneByServerID(server.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
zones = append(zones, serverZones...)
|
||||
}
|
||||
}
|
||||
} else if req.GetType == 1 {
|
||||
user := GetUserByIDFromUserCenter(int(userID))
|
||||
if user.Role != "admin" {
|
||||
return nil, errors.New("未授权访问,仅管理员可获取全部DNS区域")
|
||||
}
|
||||
if req.ServerID > 0 {
|
||||
zones, err = dao.FindDNSZoneByServerID(req.ServerID)
|
||||
} else {
|
||||
zones, err = dao.FindAllDNSZone()
|
||||
}
|
||||
} else {
|
||||
return nil, errors.New("无效的获取类型")
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return zones, nil
|
||||
}
|
||||
|
||||
func UpdateDNSZone(req *proto.UpdateDNSZoneReq, userID int) (proto.DNSZone, error) {
|
||||
zone, err := dao.FindDNSZoneByID(req.ZoneID)
|
||||
if err != nil {
|
||||
return proto.DNSZone{}, err
|
||||
}
|
||||
server, err := dao.FindDNSServerByID(zone.ServerID)
|
||||
if err != nil {
|
||||
return proto.DNSZone{}, err
|
||||
}
|
||||
if server.UserID != uint(userID) && GetUserByIDFromUserCenter(userID).Role != "admin" {
|
||||
return proto.DNSZone{}, errors.New("未授权访问DNS区域")
|
||||
}
|
||||
|
||||
zone.Domain = req.Domain
|
||||
zone.SOA_MName = req.SOA_MName
|
||||
zone.SOA_RName = req.SOA_RName
|
||||
zone.SOA_Serial = req.SOA_Serial
|
||||
zone.SOA_Refresh = req.SOA_Refresh
|
||||
zone.SOA_Retry = req.SOA_Retry
|
||||
zone.SOA_Expire = req.SOA_Expire
|
||||
zone.SOA_Minimum = req.SOA_Minimum
|
||||
zone.TTL = req.TTL
|
||||
zone.Description = req.Description
|
||||
|
||||
err = dao.UpdateDNSZone(zone.ID, &zone)
|
||||
if err != nil {
|
||||
return proto.DNSZone{}, err
|
||||
}
|
||||
return zone, nil
|
||||
}
|
||||
|
||||
func DeleteDNSZone(req *proto.DeleteDNSZoneReq, userID int) error {
|
||||
user := GetUserByIDFromUserCenter(userID)
|
||||
if req.DelType == 0 && req.ZoneID > 0 {
|
||||
zone, err := dao.FindDNSZoneByID(req.ZoneID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
server, err := dao.FindDNSServerByID(zone.ServerID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if server.UserID != uint(userID) && user.Role != "admin" {
|
||||
return errors.New("未授权访问DNS区域")
|
||||
}
|
||||
err = dao.DeleteDNSRecordByZoneID(req.ZoneID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = dao.DeleteDNSZoneByID(req.ZoneID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
} else if req.DelType == 1 {
|
||||
if user.Role != "admin" {
|
||||
return errors.New("未授权访问,仅管理员可删除所有DNS区域")
|
||||
}
|
||||
zones, err := dao.FindAllDNSZone()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, zone := range zones {
|
||||
err = dao.DeleteDNSRecordByZoneID(zone.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
err = dao.DeleteDNSZoneByID(zone.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
} else {
|
||||
return errors.New("无效的删除类型或参数")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ==================== DNSRecord 相关操作 ====================
|
||||
|
||||
func CreateDNSRecord(req *proto.CreateDNSRecordReq, userID uint) (proto.DNSRecord, error) {
|
||||
zone, err := dao.FindDNSZoneByID(req.ZoneID)
|
||||
if err != nil {
|
||||
return proto.DNSRecord{}, err
|
||||
}
|
||||
server, err := dao.FindDNSServerByID(zone.ServerID)
|
||||
if err != nil {
|
||||
return proto.DNSRecord{}, err
|
||||
}
|
||||
if server.UserID != userID && GetUserByIDFromUserCenter(int(userID)).Role != "admin" {
|
||||
return proto.DNSRecord{}, errors.New("未授权访问DNS区域")
|
||||
}
|
||||
|
||||
record := proto.DNSRecord{
|
||||
ZoneID: req.ZoneID,
|
||||
Name: req.Name,
|
||||
Type: req.Type,
|
||||
Value: req.Value,
|
||||
TTL: req.TTL,
|
||||
Priority: req.Priority,
|
||||
Weight: req.Weight,
|
||||
Port: req.Port,
|
||||
Target: req.Target,
|
||||
}
|
||||
|
||||
if record.TTL == 0 {
|
||||
record.TTL = zone.TTL
|
||||
}
|
||||
|
||||
id, err := dao.CreateDNSRecord(record)
|
||||
if err != nil {
|
||||
return proto.DNSRecord{}, err
|
||||
}
|
||||
record.ID = id
|
||||
return record, nil
|
||||
}
|
||||
|
||||
func GetDNSRecordList(req *proto.GetDNSRecordReq, userID uint) ([]proto.DNSRecord, error) {
|
||||
var records []proto.DNSRecord
|
||||
var err error
|
||||
|
||||
if req.RecordID > 0 {
|
||||
record, err := dao.FindDNSRecordByID(req.RecordID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
zone, err := dao.FindDNSZoneByID(record.ZoneID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
server, err := dao.FindDNSServerByID(zone.ServerID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if server.UserID != userID && GetUserByIDFromUserCenter(int(userID)).Role != "admin" {
|
||||
return nil, errors.New("未授权访问DNS记录")
|
||||
}
|
||||
records = append(records, record)
|
||||
} else {
|
||||
if req.GetType == 0 {
|
||||
if req.ZoneID > 0 {
|
||||
records, err = dao.FindDNSRecordByZoneID(req.ZoneID)
|
||||
} else {
|
||||
servers, err := dao.FindDNSServerByUserID(userID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, server := range servers {
|
||||
zones, err := dao.FindDNSZoneByServerID(server.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, zone := range zones {
|
||||
zoneRecords, err := dao.FindDNSRecordByZoneID(zone.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
records = append(records, zoneRecords...)
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if req.GetType == 1 {
|
||||
user := GetUserByIDFromUserCenter(int(userID))
|
||||
if user.Role != "admin" {
|
||||
return nil, errors.New("未授权访问,仅管理员可获取全部DNS记录")
|
||||
}
|
||||
if req.ZoneID > 0 {
|
||||
records, err = dao.FindDNSRecordByZoneID(req.ZoneID)
|
||||
} else {
|
||||
records, err = dao.FindAllDNSRecord()
|
||||
}
|
||||
} else {
|
||||
return nil, errors.New("无效的获取类型")
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return records, nil
|
||||
}
|
||||
|
||||
func UpdateDNSRecord(req *proto.UpdateDNSRecordReq, userID int) (proto.DNSRecord, error) {
|
||||
record, err := dao.FindDNSRecordByID(req.RecordID)
|
||||
if err != nil {
|
||||
return proto.DNSRecord{}, err
|
||||
}
|
||||
zone, err := dao.FindDNSZoneByID(record.ZoneID)
|
||||
if err != nil {
|
||||
return proto.DNSRecord{}, err
|
||||
}
|
||||
server, err := dao.FindDNSServerByID(zone.ServerID)
|
||||
if err != nil {
|
||||
return proto.DNSRecord{}, err
|
||||
}
|
||||
if server.UserID != uint(userID) && GetUserByIDFromUserCenter(userID).Role != "admin" {
|
||||
return proto.DNSRecord{}, errors.New("未授权访问DNS记录")
|
||||
}
|
||||
|
||||
record.Name = req.Name
|
||||
record.Type = req.Type
|
||||
record.Value = req.Value
|
||||
record.TTL = req.TTL
|
||||
record.Priority = req.Priority
|
||||
record.Weight = req.Weight
|
||||
record.Port = req.Port
|
||||
record.Target = req.Target
|
||||
|
||||
err = dao.UpdateDNSRecord(record.ID, &record)
|
||||
if err != nil {
|
||||
return proto.DNSRecord{}, err
|
||||
}
|
||||
return record, nil
|
||||
}
|
||||
|
||||
func DeleteDNSRecord(req *proto.DeleteDNSRecordReq, userID int) error {
|
||||
user := GetUserByIDFromUserCenter(userID)
|
||||
if req.DelType == 0 && req.RecordID > 0 {
|
||||
record, err := dao.FindDNSRecordByID(req.RecordID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
zone, err := dao.FindDNSZoneByID(record.ZoneID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
server, err := dao.FindDNSServerByID(zone.ServerID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if server.UserID != uint(userID) && user.Role != "admin" {
|
||||
return errors.New("未授权访问DNS记录")
|
||||
}
|
||||
err = dao.DeleteDNSRecordByID(req.RecordID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
} else if req.DelType == 1 {
|
||||
if user.Role != "admin" {
|
||||
return errors.New("未授权访问,仅管理员可删除所有DNS记录")
|
||||
}
|
||||
records, err := dao.FindAllDNSRecord()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, record := range records {
|
||||
err = dao.DeleteDNSRecordByID(record.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
} else {
|
||||
return errors.New("无效的删除类型或参数")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ==================== DNS 服务运行管理 ====================
|
||||
|
||||
// handleDNSRequest 处理DNS查询请求
|
||||
func (instance *DNSServiceInstance) handleDNSRequest(w dns.ResponseWriter, r *dns.Msg) {
|
||||
m := new(dns.Msg)
|
||||
m.SetReply(r)
|
||||
m.Authoritative = true
|
||||
|
||||
for _, q := range r.Question {
|
||||
// 查找对应的Zone
|
||||
zones, err := dao.FindDNSZoneByServerID(instance.ServerID)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
var matchedZone *proto.DNSZone
|
||||
var qName string = dns.Fqdn(q.Name)
|
||||
|
||||
for _, zone := range zones {
|
||||
zoneFqdn := dns.Fqdn(zone.Domain)
|
||||
if dns.IsSubDomain(zoneFqdn, qName) {
|
||||
matchedZone = &zone
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if matchedZone == nil {
|
||||
// 递归查询
|
||||
if instance.Config.EnableRecursion {
|
||||
c := new(dns.Client)
|
||||
upstreams := instance.Config.UpstreamDNS
|
||||
if upstreams == "" {
|
||||
upstreams = "8.8.8.8:53"
|
||||
}
|
||||
resp, _, err := c.Exchange(r, upstreams)
|
||||
if err == nil {
|
||||
m.Answer = append(m.Answer, resp.Answer...)
|
||||
}
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
// 查找匹配的记录
|
||||
records, err := dao.FindDNSRecordByZoneID(matchedZone.ID)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
|
||||
for _, record := range records {
|
||||
recordName := dns.Fqdn(record.Name + "." + matchedZone.Domain)
|
||||
if record.Name == "@" {
|
||||
recordName = dns.Fqdn(matchedZone.Domain)
|
||||
}
|
||||
|
||||
if recordName == qName && record.Type == uint(q.Qtype) {
|
||||
var rr dns.RR
|
||||
var ttl uint32
|
||||
if record.TTL > 0 {
|
||||
ttl = uint32(record.TTL)
|
||||
} else {
|
||||
ttl = uint32(matchedZone.TTL)
|
||||
}
|
||||
|
||||
switch q.Qtype {
|
||||
case dns.TypeA:
|
||||
rr, _ = dns.NewRR(fmt.Sprintf("%s %d IN A %s", q.Name, ttl, record.Value))
|
||||
case dns.TypeAAAA:
|
||||
rr, _ = dns.NewRR(fmt.Sprintf("%s %d IN AAAA %s", q.Name, ttl, record.Value))
|
||||
case dns.TypeCNAME:
|
||||
rr, _ = dns.NewRR(fmt.Sprintf("%s %d IN CNAME %s", q.Name, ttl, record.Value))
|
||||
case dns.TypeMX:
|
||||
rr, _ = dns.NewRR(fmt.Sprintf("%s %d IN MX %d %s", q.Name, ttl, record.Priority, record.Value))
|
||||
case dns.TypeNS:
|
||||
rr, _ = dns.NewRR(fmt.Sprintf("%s %d IN NS %s", q.Name, ttl, record.Value))
|
||||
case dns.TypeTXT:
|
||||
rr, _ = dns.NewRR(fmt.Sprintf("%s %d IN TXT \"%s\"", q.Name, ttl, record.Value))
|
||||
case dns.TypeSRV:
|
||||
rr, _ = dns.NewRR(fmt.Sprintf("%s %d IN SRV %d %d %d %s", q.Name, ttl, record.Priority, record.Weight, record.Port, record.Target))
|
||||
}
|
||||
|
||||
if rr != nil {
|
||||
m.Answer = append(m.Answer, rr)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
w.WriteMsg(m)
|
||||
}
|
||||
|
||||
// StartDNSServer 启动DNS服务
|
||||
func StartDNSServer(serverID uint, userID int) (*DNSServiceInstance, error) {
|
||||
// 检查权限
|
||||
server, err := dao.FindDNSServerByID(serverID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if server.UserID != uint(userID) && GetUserByIDFromUserCenter(userID).Role != "admin" {
|
||||
return nil, errors.New("未授权访问DNS服务器")
|
||||
}
|
||||
|
||||
dnsServiceManager.rwMutex.Lock()
|
||||
defer dnsServiceManager.rwMutex.Unlock()
|
||||
|
||||
// 检查是否已经在运行
|
||||
if instance, exists := dnsServiceManager.instances[serverID]; exists && instance.Running {
|
||||
return instance, nil
|
||||
}
|
||||
|
||||
// 创建服务实例
|
||||
instance := &DNSServiceInstance{
|
||||
ServerID: serverID,
|
||||
Config: &server,
|
||||
Running: false,
|
||||
}
|
||||
|
||||
// 创建DNS服务器
|
||||
dns.HandleFunc(".", instance.handleDNSRequest)
|
||||
|
||||
addr := fmt.Sprintf("%s:%d", server.ListenIP, server.Port)
|
||||
udpAddr, err := net.ResolveUDPAddr("udp", addr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
udpConn, err := net.ListenUDP("udp", udpAddr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
tcpAddr, err := net.ResolveTCPAddr("tcp", addr)
|
||||
if err != nil {
|
||||
udpConn.Close()
|
||||
return nil, err
|
||||
}
|
||||
|
||||
tcpListener, err := net.ListenTCP("tcp", tcpAddr)
|
||||
if err != nil {
|
||||
udpConn.Close()
|
||||
return nil, err
|
||||
}
|
||||
|
||||
instance.Server = &dns.Server{
|
||||
Listener: tcpListener,
|
||||
PacketConn: udpConn,
|
||||
}
|
||||
|
||||
// 启动服务
|
||||
go func() {
|
||||
instance.mutex.Lock()
|
||||
instance.Running = true
|
||||
instance.mutex.Unlock()
|
||||
|
||||
err := instance.Server.ActivateAndServe()
|
||||
if err != nil {
|
||||
instance.mutex.Lock()
|
||||
instance.Running = false
|
||||
instance.mutex.Unlock()
|
||||
}
|
||||
}()
|
||||
|
||||
// 更新数据库状态
|
||||
server.Status = proto.DNS_STATUS_RUNNING
|
||||
dao.UpdateDNSServer(serverID, &server)
|
||||
|
||||
dnsServiceManager.instances[serverID] = instance
|
||||
return instance, nil
|
||||
}
|
||||
|
||||
// StopDNSServer 停止DNS服务
|
||||
func StopDNSServer(serverID uint, userID int) error {
|
||||
server, err := dao.FindDNSServerByID(serverID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if server.UserID != uint(userID) && GetUserByIDFromUserCenter(userID).Role != "admin" {
|
||||
return errors.New("未授权访问DNS服务器")
|
||||
}
|
||||
|
||||
dnsServiceManager.rwMutex.Lock()
|
||||
defer dnsServiceManager.rwMutex.Unlock()
|
||||
|
||||
instance, exists := dnsServiceManager.instances[serverID]
|
||||
if !exists || !instance.Running {
|
||||
return nil
|
||||
}
|
||||
|
||||
// 停止服务
|
||||
err = instance.Server.Shutdown()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
instance.mutex.Lock()
|
||||
instance.Running = false
|
||||
instance.mutex.Unlock()
|
||||
|
||||
// 更新数据库状态
|
||||
server.Status = proto.DNS_STATUS_STOPPED
|
||||
dao.UpdateDNSServer(serverID, &server)
|
||||
|
||||
delete(dnsServiceManager.instances, serverID)
|
||||
return nil
|
||||
}
|
||||
|
||||
// RestartDNSServer 重启DNS服务
|
||||
func RestartDNSServer(serverID uint, userID int) (*DNSServiceInstance, error) {
|
||||
err := StopDNSServer(serverID, userID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return StartDNSServer(serverID, userID)
|
||||
}
|
||||
|
||||
// GetDNSServerStatus 获取DNS服务运行状态
|
||||
func GetDNSServerStatus(serverID uint, userID int) (*DNSServiceInstance, error) {
|
||||
server, err := dao.FindDNSServerByID(serverID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if server.UserID != uint(userID) && GetUserByIDFromUserCenter(userID).Role != "admin" {
|
||||
return nil, errors.New("未授权访问DNS服务器")
|
||||
}
|
||||
|
||||
dnsServiceManager.rwMutex.RLock()
|
||||
defer dnsServiceManager.rwMutex.RUnlock()
|
||||
|
||||
instance, exists := dnsServiceManager.instances[serverID]
|
||||
if exists {
|
||||
return instance, nil
|
||||
}
|
||||
|
||||
// 不在运行中,返回配置中的状态
|
||||
return &DNSServiceInstance{
|
||||
ServerID: serverID,
|
||||
Config: &server,
|
||||
Running: server.Status == proto.DNS_STATUS_RUNNING,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// RestartDNSServerIfRunning 如果服务正在运行则重启(配置更新时调用)
|
||||
func RestartDNSServerIfRunning(serverID uint, userID int) error {
|
||||
dnsServiceManager.rwMutex.RLock()
|
||||
instance, exists := dnsServiceManager.instances[serverID]
|
||||
dnsServiceManager.rwMutex.RUnlock()
|
||||
|
||||
if exists && instance.Running {
|
||||
// 获取最新配置
|
||||
server, err := dao.FindDNSServerByID(serverID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// 重启服务(管理员权限)
|
||||
_, err = RestartDNSServer(server.ID, userID) // 假设管理员ID为1
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
|
@ -1,7 +1,6 @@
|
|||
package service
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"log"
|
||||
"os/exec"
|
||||
|
|
@ -130,13 +129,10 @@ func GetShellWillRunFromMaster(server string) ([]dao.Shell, error) {
|
|||
|
||||
func RunShell(script string) (res, err string) {
|
||||
cmd := exec.Command("/bin/bash", "-c", script)
|
||||
// 使用bytes.Buffer捕获输出
|
||||
var out bytes.Buffer
|
||||
cmd.Stdout = &out
|
||||
err3 := cmd.Run()
|
||||
output, err3 := cmd.CombinedOutput()
|
||||
err3_info := ""
|
||||
if err3 != nil {
|
||||
err3_info = err3.Error()
|
||||
}
|
||||
return strings.TrimSpace(out.String()), err3_info
|
||||
return strings.TrimSpace(string(output)), err3_info
|
||||
}
|
||||
|
|
|
|||
|
|
@ -104,6 +104,10 @@ func SendEmail(email, subject, body string) {
|
|||
em.SmtpUserName = "354425203@qq.com"
|
||||
em.SmtpPort = 587
|
||||
em.ImapPort = 993
|
||||
if email == "" || subject == "" || body == "" {
|
||||
log.Println("tool send email fail: email or subject or body is empty")
|
||||
return
|
||||
}
|
||||
err := em.Send(subject, body, []string{email})
|
||||
if err != nil {
|
||||
fmt.Println("send mail error:", err)
|
||||
|
|
@ -325,3 +329,28 @@ func GetTokenSecretFromUserCenter() (*proto.SecretSyncSettings, error) {
|
|||
}
|
||||
return &secretResp, nil
|
||||
}
|
||||
|
||||
// 获取cid正在运行
|
||||
func GetCIDRunningList(user_id int, req_type int) ([]proto.CIDRunning, error) {
|
||||
var err error
|
||||
var resp []proto.CIDRunning
|
||||
if req_type == 0 {
|
||||
proto.CID_RunningMutex.RLock()
|
||||
resp = proto.CID_Running_Map[user_id]
|
||||
proto.CID_RunningMutex.RUnlock()
|
||||
} else if req_type == 1 {
|
||||
user := GetUserByIDFromUserCenter(user_id)
|
||||
if user.Role != "admin" {
|
||||
err = errors.New("no permission")
|
||||
} else {
|
||||
proto.CID_RunningMutex.RLock()
|
||||
for _, v := range proto.CID_Running_Map {
|
||||
resp = append(resp, v...)
|
||||
}
|
||||
proto.CID_RunningMutex.RUnlock()
|
||||
}
|
||||
} else {
|
||||
err = errors.New("request type is error")
|
||||
}
|
||||
return resp, err
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,186 @@
|
|||
package worker
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"log"
|
||||
"math"
|
||||
"os"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// MemoryCacheValue 缓存值结构,包含值和过期时间
|
||||
type MemoryCacheValue struct {
|
||||
Value string `json:"value"`
|
||||
ExpireAt int64 `json:"expireAt"` // 过期时间戳,秒级
|
||||
}
|
||||
|
||||
var (
|
||||
memoryCacheData = NewMemoryCache()
|
||||
)
|
||||
|
||||
// MemoryCache 线程安全的内存缓存
|
||||
type MemoryCache struct {
|
||||
data map[string]MemoryCacheValue
|
||||
mu sync.RWMutex
|
||||
}
|
||||
|
||||
// NewMemoryCache 创建新的内存缓存实例
|
||||
func NewMemoryCache() *MemoryCache {
|
||||
return &MemoryCache{
|
||||
data: make(map[string]MemoryCacheValue),
|
||||
}
|
||||
}
|
||||
|
||||
// InitStaticMemoryCache 初始化全局缓存实例
|
||||
func InitStaticMemoryCache() {
|
||||
// 先尝试从文件加载
|
||||
ReadMemoryCacheFromJsonFile()
|
||||
|
||||
}
|
||||
|
||||
// SetWithExp 设置带过期时间的键值对
|
||||
func (mc *MemoryCache) SetWithExp(key string, value string, expireAt int64) {
|
||||
mc.mu.Lock()
|
||||
defer mc.mu.Unlock()
|
||||
mc.data[key] = MemoryCacheValue{value, expireAt}
|
||||
}
|
||||
|
||||
// Get 获取键值,如果已过期则返回空并删除
|
||||
func (mc *MemoryCache) Get(key string) string {
|
||||
// 先加读锁检查
|
||||
mc.mu.RLock()
|
||||
value, ok := mc.data[key]
|
||||
mc.mu.RUnlock()
|
||||
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
|
||||
// 检查是否过期
|
||||
now := time.Now().Unix()
|
||||
if value.ExpireAt > now {
|
||||
return value.Value
|
||||
}
|
||||
|
||||
// 已过期,删除该键
|
||||
mc.mu.Lock()
|
||||
// 二次检查,防止并发情况下已被删除
|
||||
if v, exists := mc.data[key]; exists && v.ExpireAt <= now {
|
||||
delete(mc.data, key)
|
||||
}
|
||||
mc.mu.Unlock()
|
||||
|
||||
return ""
|
||||
}
|
||||
|
||||
// Set 设置永不过期的键值对
|
||||
func (mc *MemoryCache) Set(key string, value string) {
|
||||
mc.SetWithExp(key, value, math.MaxInt64)
|
||||
}
|
||||
|
||||
// Del 删除指定键
|
||||
func (mc *MemoryCache) Del(key string) {
|
||||
mc.mu.Lock()
|
||||
defer mc.mu.Unlock()
|
||||
delete(mc.data, key)
|
||||
}
|
||||
|
||||
// Clear 清空所有缓存
|
||||
func (mc *MemoryCache) Clear() {
|
||||
mc.mu.Lock()
|
||||
defer mc.mu.Unlock()
|
||||
mc.data = make(map[string]MemoryCacheValue)
|
||||
}
|
||||
|
||||
const CRON_MAX_DEL_NUMBER = 100 // 每次清理的最大数量
|
||||
|
||||
// DeleteMemoryCacheCron 定时清理过期键
|
||||
func DeleteMemoryCacheCron() {
|
||||
memoryCacheData.mu.Lock()
|
||||
defer memoryCacheData.mu.Unlock()
|
||||
|
||||
now := time.Now().Unix()
|
||||
i := 0
|
||||
for key, value := range memoryCacheData.data {
|
||||
if i >= CRON_MAX_DEL_NUMBER {
|
||||
break
|
||||
}
|
||||
if value.ExpireAt < now {
|
||||
delete(memoryCacheData.data, key)
|
||||
i++
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// GetMemoryCacheFilePath 获取缓存持久化文件路径
|
||||
func GetMemoryCacheFilePath() string {
|
||||
if os.Getenv("OS") == "Windows_NT" {
|
||||
return "C:/Users/Administrator/vp_mc.json"
|
||||
}
|
||||
return "/etc/vp_mc.json"
|
||||
}
|
||||
|
||||
// WriteMemoryCacheToFile 将缓存写入文件持久化
|
||||
func WriteMemoryCacheToFile() {
|
||||
memoryCacheData.mu.RLock()
|
||||
defer memoryCacheData.mu.RUnlock()
|
||||
|
||||
path := GetMemoryCacheFilePath()
|
||||
data, err := json.MarshalIndent(memoryCacheData.data, "", " ")
|
||||
if err != nil {
|
||||
log.Println("mc write file json err:", err)
|
||||
return
|
||||
}
|
||||
|
||||
// 先写入临时文件,再原子替换,防止文件损坏
|
||||
tempPath := path + ".tmp"
|
||||
if err := os.WriteFile(tempPath, data, 0644); err != nil {
|
||||
log.Println("mc write temp file err:", err)
|
||||
return
|
||||
}
|
||||
|
||||
if err := os.Rename(tempPath, path); err != nil {
|
||||
log.Println("mc rename file err:", err)
|
||||
os.Remove(tempPath) // 清理临时文件
|
||||
}
|
||||
}
|
||||
|
||||
// ReadMemoryCacheFromJsonFile 从文件加载缓存
|
||||
func ReadMemoryCacheFromJsonFile() {
|
||||
path := GetMemoryCacheFilePath()
|
||||
_, err := os.Stat(path)
|
||||
if err != nil {
|
||||
log.Println("mc file not exists:", err)
|
||||
return
|
||||
}
|
||||
|
||||
file, err := os.Open(path)
|
||||
if err != nil {
|
||||
log.Println("mc open file err:", err)
|
||||
return
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
var data map[string]MemoryCacheValue
|
||||
decoder := json.NewDecoder(file)
|
||||
if err := decoder.Decode(&data); err != nil {
|
||||
log.Println("mc decode file err:", err)
|
||||
return
|
||||
}
|
||||
|
||||
// 过滤已过期的数据
|
||||
now := time.Now().Unix()
|
||||
memoryCacheData.mu.Lock()
|
||||
for k, v := range data {
|
||||
if v.ExpireAt > now || v.ExpireAt == math.MaxInt64 {
|
||||
memoryCacheData.data[k] = v
|
||||
}
|
||||
}
|
||||
memoryCacheData.mu.Unlock()
|
||||
}
|
||||
|
||||
// 提供全局缓存的访问方法
|
||||
func GetGlobalCache() *MemoryCache {
|
||||
return memoryCacheData
|
||||
}
|
||||
|
|
@ -1,16 +1,14 @@
|
|||
package worker
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"github.com/go-redis/redis/v8"
|
||||
"strconv"
|
||||
"time"
|
||||
"videoplayer/proto"
|
||||
)
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"github.com/go-redis/redis/v8"
|
||||
)
|
||||
|
||||
var RedisClient *redis.Client // Redis 客户端, 用于连接 Redis 服务器
|
||||
func InitRedis() error {
|
||||
|
|
|
|||
Loading…
Reference in New Issue