marge: 合并代码,包名变更be.ems
This commit is contained in:
@@ -5,12 +5,12 @@ import (
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
sysMenuService "ems.agt/features/sys_menu/service"
|
||||
sysRoleService "ems.agt/features/sys_role/service"
|
||||
"ems.agt/lib/core/cache"
|
||||
"ems.agt/lib/core/vo"
|
||||
"ems.agt/lib/dborm"
|
||||
srcConfig "ems.agt/src/framework/config"
|
||||
sysMenuService "be.ems/features/sys_menu/service"
|
||||
sysRoleService "be.ems/features/sys_role/service"
|
||||
"be.ems/lib/core/cache"
|
||||
"be.ems/lib/core/vo"
|
||||
"be.ems/lib/dborm"
|
||||
srcConfig "be.ems/src/framework/config"
|
||||
)
|
||||
|
||||
// 登录缓存用户信息
|
||||
|
||||
@@ -1,201 +0,0 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"os/exec"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
func Exec(cmdStr string) (string, error) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
||||
defer cancel()
|
||||
cmd := exec.Command("bash", "-c", cmdStr)
|
||||
var stdout, stderr bytes.Buffer
|
||||
cmd.Stdout = &stdout
|
||||
cmd.Stderr = &stderr
|
||||
err := cmd.Run()
|
||||
if ctx.Err() == context.DeadlineExceeded {
|
||||
return "", fmt.Errorf("errCmdTimeout %v", err)
|
||||
}
|
||||
if err != nil {
|
||||
errMsg := ""
|
||||
if len(stderr.String()) != 0 {
|
||||
errMsg = fmt.Sprintf("stderr: %s", stderr.String())
|
||||
}
|
||||
if len(stdout.String()) != 0 {
|
||||
if len(errMsg) != 0 {
|
||||
errMsg = fmt.Sprintf("%s; stdout: %s", errMsg, stdout.String())
|
||||
} else {
|
||||
errMsg = fmt.Sprintf("stdout: %s", stdout.String())
|
||||
}
|
||||
}
|
||||
return errMsg, err
|
||||
}
|
||||
return stdout.String(), nil
|
||||
}
|
||||
|
||||
func ExecWithTimeOut(cmdStr string, timeout time.Duration) (string, error) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
cmd := exec.Command("bash", "-c", cmdStr)
|
||||
var stdout, stderr bytes.Buffer
|
||||
cmd.Stdout = &stdout
|
||||
cmd.Stderr = &stderr
|
||||
err := cmd.Run()
|
||||
if ctx.Err() == context.DeadlineExceeded {
|
||||
return "", fmt.Errorf("errCmdTimeout %v", err)
|
||||
}
|
||||
if err != nil {
|
||||
errMsg := ""
|
||||
if len(stderr.String()) != 0 {
|
||||
errMsg = fmt.Sprintf("stderr: %s", stderr.String())
|
||||
}
|
||||
if len(stdout.String()) != 0 {
|
||||
if len(errMsg) != 0 {
|
||||
errMsg = fmt.Sprintf("%s; stdout: %s", errMsg, stdout.String())
|
||||
} else {
|
||||
errMsg = fmt.Sprintf("stdout: %s", stdout.String())
|
||||
}
|
||||
}
|
||||
return errMsg, err
|
||||
}
|
||||
return stdout.String(), nil
|
||||
}
|
||||
|
||||
func ExecCronjobWithTimeOut(cmdStr string, workdir string, timeout time.Duration) (string, error) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||
defer cancel()
|
||||
cmd := exec.Command("bash", "-c", cmdStr)
|
||||
cmd.Dir = workdir
|
||||
var stdout, stderr bytes.Buffer
|
||||
cmd.Stdout = &stdout
|
||||
cmd.Stderr = &stderr
|
||||
err := cmd.Run()
|
||||
if ctx.Err() == context.DeadlineExceeded {
|
||||
return "", fmt.Errorf("errCmdTimeout %v", err)
|
||||
}
|
||||
|
||||
errMsg := ""
|
||||
if len(stderr.String()) != 0 {
|
||||
errMsg = fmt.Sprintf("stderr:\n %s", stderr.String())
|
||||
}
|
||||
if len(stdout.String()) != 0 {
|
||||
if len(errMsg) != 0 {
|
||||
errMsg = fmt.Sprintf("%s \n\n; stdout:\n %s", errMsg, stdout.String())
|
||||
} else {
|
||||
errMsg = fmt.Sprintf("stdout:\n %s", stdout.String())
|
||||
}
|
||||
}
|
||||
return errMsg, err
|
||||
}
|
||||
|
||||
func Execf(cmdStr string, a ...interface{}) (string, error) {
|
||||
cmd := exec.Command("bash", "-c", fmt.Sprintf(cmdStr, a...))
|
||||
var stdout, stderr bytes.Buffer
|
||||
cmd.Stdout = &stdout
|
||||
cmd.Stderr = &stderr
|
||||
err := cmd.Run()
|
||||
if err != nil {
|
||||
errMsg := ""
|
||||
if len(stderr.String()) != 0 {
|
||||
errMsg = fmt.Sprintf("stderr: %s", stderr.String())
|
||||
}
|
||||
if len(stdout.String()) != 0 {
|
||||
if len(errMsg) != 0 {
|
||||
errMsg = fmt.Sprintf("%s; stdout: %s", errMsg, stdout.String())
|
||||
} else {
|
||||
errMsg = fmt.Sprintf("stdout: %s", stdout.String())
|
||||
}
|
||||
}
|
||||
return errMsg, err
|
||||
}
|
||||
return stdout.String(), nil
|
||||
}
|
||||
|
||||
func ExecWithCheck(name string, a ...string) (string, error) {
|
||||
cmd := exec.Command(name, a...)
|
||||
var stdout, stderr bytes.Buffer
|
||||
cmd.Stdout = &stdout
|
||||
cmd.Stderr = &stderr
|
||||
err := cmd.Run()
|
||||
if err != nil {
|
||||
errMsg := ""
|
||||
if len(stderr.String()) != 0 {
|
||||
errMsg = fmt.Sprintf("stderr: %s", stderr.String())
|
||||
}
|
||||
if len(stdout.String()) != 0 {
|
||||
if len(errMsg) != 0 {
|
||||
errMsg = fmt.Sprintf("%s; stdout: %s", errMsg, stdout.String())
|
||||
} else {
|
||||
errMsg = fmt.Sprintf("stdout: %s", stdout.String())
|
||||
}
|
||||
}
|
||||
return errMsg, err
|
||||
}
|
||||
return stdout.String(), nil
|
||||
}
|
||||
|
||||
func ExecScript(scriptPath, workDir string) (string, error) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute)
|
||||
defer cancel()
|
||||
cmd := exec.Command("bash", scriptPath)
|
||||
cmd.Dir = workDir
|
||||
var stdout, stderr bytes.Buffer
|
||||
cmd.Stdout = &stdout
|
||||
cmd.Stderr = &stderr
|
||||
err := cmd.Run()
|
||||
if ctx.Err() == context.DeadlineExceeded {
|
||||
return "", fmt.Errorf("errCmdTimeout %v", err)
|
||||
}
|
||||
if err != nil {
|
||||
errMsg := ""
|
||||
if len(stderr.String()) != 0 {
|
||||
errMsg = fmt.Sprintf("stderr: %s", stderr.String())
|
||||
}
|
||||
if len(stdout.String()) != 0 {
|
||||
if len(errMsg) != 0 {
|
||||
errMsg = fmt.Sprintf("%s; stdout: %s", errMsg, stdout.String())
|
||||
} else {
|
||||
errMsg = fmt.Sprintf("stdout: %s", stdout.String())
|
||||
}
|
||||
}
|
||||
return errMsg, err
|
||||
}
|
||||
return stdout.String(), nil
|
||||
}
|
||||
|
||||
func CheckIllegal(args ...string) bool {
|
||||
if args == nil {
|
||||
return false
|
||||
}
|
||||
for _, arg := range args {
|
||||
if strings.Contains(arg, "&") || strings.Contains(arg, "|") || strings.Contains(arg, ";") ||
|
||||
strings.Contains(arg, "$") || strings.Contains(arg, "'") || strings.Contains(arg, "`") ||
|
||||
strings.Contains(arg, "(") || strings.Contains(arg, ")") || strings.Contains(arg, "\"") {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func HasNoPasswordSudo() bool {
|
||||
cmd2 := exec.Command("sudo", "-n", "ls")
|
||||
err2 := cmd2.Run()
|
||||
return err2 == nil
|
||||
}
|
||||
|
||||
func SudoHandleCmd() string {
|
||||
cmd := exec.Command("sudo", "-n", "ls")
|
||||
if err := cmd.Run(); err == nil {
|
||||
return "sudo "
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func Which(name string) bool {
|
||||
_, err := exec.LookPath(name)
|
||||
return err == nil
|
||||
}
|
||||
@@ -4,7 +4,7 @@ import (
|
||||
"database/sql"
|
||||
"regexp"
|
||||
|
||||
"ems.agt/lib/dborm"
|
||||
"be.ems/lib/dborm"
|
||||
"xorm.io/xorm"
|
||||
)
|
||||
|
||||
|
||||
@@ -1,88 +0,0 @@
|
||||
package file
|
||||
|
||||
import (
|
||||
"encoding/csv"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"ems.agt/lib/log"
|
||||
)
|
||||
|
||||
// 写入CSV文件,需要转换数据
|
||||
// 例如:
|
||||
// data := [][]string{}
|
||||
// data = append(data, []string{"姓名", "年龄", "城市"})
|
||||
// data = append(data, []string{"1", "2", "3"})
|
||||
// err := file.WriterCSVFile(data, filePath)
|
||||
func WriterCSVFile(data [][]string, filePath string) error {
|
||||
// 获取文件所在的目录路径
|
||||
dirPath := filepath.Dir(filePath)
|
||||
|
||||
// 确保文件夹路径存在
|
||||
err := os.MkdirAll(dirPath, os.ModePerm)
|
||||
if err != nil {
|
||||
log.Errorf("创建文件夹失败 CreateFile %v", err)
|
||||
}
|
||||
|
||||
// 创建或打开文件
|
||||
file, err := os.Create(filePath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
// 创建CSV编写器
|
||||
writer := csv.NewWriter(file)
|
||||
defer writer.Flush()
|
||||
|
||||
// 写入数据
|
||||
for _, row := range data {
|
||||
writer.Write(row)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// 读取CSV文件,转换map数据
|
||||
func ReadCSVFile(filePath string) []map[string]string {
|
||||
// 创建 map 存储 CSV 数据
|
||||
arr := make([]map[string]string, 0)
|
||||
|
||||
// 打开 CSV 文件
|
||||
file, err := os.Open(filePath)
|
||||
if err != nil {
|
||||
log.Fatal("无法打开 CSV 文件:", err)
|
||||
return arr
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
// 创建 CSV Reader
|
||||
reader := csv.NewReader(file)
|
||||
|
||||
// 读取 CSV 头部行
|
||||
header, err := reader.Read()
|
||||
if err != nil {
|
||||
log.Fatal("无法读取 CSV 头部行:", err)
|
||||
return arr
|
||||
}
|
||||
|
||||
// 遍历 CSV 数据行
|
||||
for {
|
||||
// 读取一行数据
|
||||
record, err := reader.Read()
|
||||
if err != nil {
|
||||
// 到达文件末尾或遇到错误时退出循环
|
||||
break
|
||||
}
|
||||
|
||||
// 将 CSV 数据插入到 map 中
|
||||
data := make(map[string]string)
|
||||
for i, value := range record {
|
||||
key := strings.ToLower(header[i])
|
||||
data[key] = value
|
||||
}
|
||||
arr = append(arr, data)
|
||||
}
|
||||
|
||||
return arr
|
||||
}
|
||||
@@ -1,49 +0,0 @@
|
||||
package file
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
|
||||
"ems.agt/lib/core/conf"
|
||||
"ems.agt/lib/log"
|
||||
)
|
||||
|
||||
// 网元NE 文件复制到远程文件
|
||||
func FileSCPLocalToNe(neIp, localPath, nePath string) error {
|
||||
usernameNe := conf.Get("ne.user").(string)
|
||||
// scp /path/to/local/file.txt user@remote-server:/path/to/remote/directory/
|
||||
neDir := fmt.Sprintf("%s@%s:%s", usernameNe, neIp, nePath)
|
||||
cmd := exec.Command("scp", "-r", localPath, neDir)
|
||||
out, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
log.Infof("FileSCPLocalToNe %s", string(out))
|
||||
return nil
|
||||
}
|
||||
|
||||
// 网元NE 远程文件复制到本地文件
|
||||
func FileSCPNeToLocal(neIp, nePath, localPath string) error {
|
||||
// 获取文件所在的目录路径
|
||||
dirPath := filepath.Dir(localPath)
|
||||
|
||||
// 确保文件夹路径存在
|
||||
err := os.MkdirAll(dirPath, os.ModePerm)
|
||||
if err != nil {
|
||||
log.Errorf("创建文件夹失败 CreateFile %v", err)
|
||||
return err
|
||||
}
|
||||
|
||||
usernameNe := conf.Get("ne.user").(string)
|
||||
// scp user@remote-server:/path/to/remote/directory/ /path/to/local/file.txt
|
||||
neDir := fmt.Sprintf("%s@%s:%s", usernameNe, neIp, nePath)
|
||||
cmd := exec.Command("scp", "-r", neDir, localPath)
|
||||
out, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
log.Infof("FileSCPNeToLocal %s", string(out))
|
||||
return nil
|
||||
}
|
||||
@@ -1,79 +0,0 @@
|
||||
package file
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"ems.agt/lib/log"
|
||||
)
|
||||
|
||||
// 写入Txt文件用,号分割 需要转换数据
|
||||
// 例如:
|
||||
// data := [][]string{}
|
||||
// data = append(data, []string{"姓名", "年龄", "城市"})
|
||||
// data = append(data, []string{"1", "2", "3"})
|
||||
// err := file.WriterCSVFile(data, filePath)
|
||||
func WriterTxtFile(data [][]string, filePath string) error {
|
||||
// 获取文件所在的目录路径
|
||||
dirPath := filepath.Dir(filePath)
|
||||
|
||||
// 确保文件夹路径存在
|
||||
err := os.MkdirAll(dirPath, os.ModePerm)
|
||||
if err != nil {
|
||||
log.Errorf("创建文件夹失败 CreateFile %v", err)
|
||||
}
|
||||
|
||||
// 创建或打开文件
|
||||
file, err := os.Create(filePath)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
// 创建一个 Writer 对象,用于将数据写入文件
|
||||
writer := bufio.NewWriter(file)
|
||||
for _, row := range data {
|
||||
line := strings.Join(row, ",")
|
||||
fmt.Fprintln(writer, line)
|
||||
}
|
||||
|
||||
// 将缓冲区中的数据刷新到文件中
|
||||
err = writer.Flush()
|
||||
if err != nil {
|
||||
log.Errorf("刷新缓冲区时发生错误:", err)
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// 读取Txt文件,用,号分割 转换数组数据
|
||||
func ReadTxtFile(filePath string) [][]string {
|
||||
// 创建 map 存储 CSV 数据
|
||||
arr := make([][]string, 0)
|
||||
|
||||
// 打开文本文件
|
||||
file, err := os.Open(filePath)
|
||||
if err != nil {
|
||||
log.Fatal("无法打开文件:", err)
|
||||
return arr
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
// 创建一个 Scanner 对象,用于逐行读取文件内容
|
||||
scanner := bufio.NewScanner(file)
|
||||
if scanner.Err() != nil {
|
||||
log.Fatal("读取文件时出错:", scanner.Err())
|
||||
return arr
|
||||
}
|
||||
|
||||
for scanner.Scan() {
|
||||
line := scanner.Text()
|
||||
fields := strings.Split(line, ",")
|
||||
arr = append(arr, fields)
|
||||
}
|
||||
|
||||
return arr
|
||||
}
|
||||
@@ -7,7 +7,7 @@ import (
|
||||
"net"
|
||||
"time"
|
||||
|
||||
"ems.agt/lib/core/conf"
|
||||
"be.ems/lib/core/conf"
|
||||
)
|
||||
|
||||
// 定义MMLClient结构体
|
||||
|
||||
@@ -1,358 +0,0 @@
|
||||
package redis
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"ems.agt/lib/core/conf"
|
||||
"ems.agt/lib/log"
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
// Redis连接实例
|
||||
var rdbMap = make(map[string]*redis.Client)
|
||||
|
||||
// 声明定义限流脚本命令
|
||||
var rateLimitCommand = redis.NewScript(`
|
||||
local key = KEYS[1]
|
||||
local time = tonumber(ARGV[1])
|
||||
local count = tonumber(ARGV[2])
|
||||
local current = redis.call('get', key);
|
||||
if current and tonumber(current) >= count then
|
||||
return tonumber(current);
|
||||
end
|
||||
current = redis.call('incr', key)
|
||||
if tonumber(current) == 1 then
|
||||
redis.call('expire', key, time)
|
||||
end
|
||||
return tonumber(current);`)
|
||||
|
||||
// 连接Redis实例
|
||||
func Connect() {
|
||||
ctx := context.Background()
|
||||
// 读取数据源配置
|
||||
datasource := conf.Get("redis.dataSource").(map[string]any)
|
||||
for k, v := range datasource {
|
||||
client := v.(map[string]any)
|
||||
// 创建连接
|
||||
address := fmt.Sprintf("%s:%d", client["host"], client["port"])
|
||||
rdb := redis.NewClient(&redis.Options{
|
||||
Addr: address,
|
||||
Password: client["password"].(string),
|
||||
DB: client["db"].(int),
|
||||
})
|
||||
// 测试数据库连接
|
||||
pong, err := rdb.Ping(ctx).Result()
|
||||
if err != nil {
|
||||
log.Fatalf("failed error ping redis %s %d is %v", client["host"], client["db"], err)
|
||||
continue
|
||||
}
|
||||
log.Infof("redis %s %d %s connection is successful.", client["host"], client["db"], pong)
|
||||
rdbMap[k] = rdb
|
||||
}
|
||||
}
|
||||
|
||||
// 关闭Redis实例
|
||||
func Close() {
|
||||
for _, rdb := range rdbMap {
|
||||
if err := rdb.Close(); err != nil {
|
||||
log.Errorf("fatal error db close: %s", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 获取默认实例
|
||||
func DefaultRDB() *redis.Client {
|
||||
source := conf.Get("redis.defaultDataSourceName").(string)
|
||||
return rdbMap[source]
|
||||
}
|
||||
|
||||
// 获取实例
|
||||
func RDB(source string) *redis.Client {
|
||||
return rdbMap[source]
|
||||
}
|
||||
|
||||
// Info 获取redis服务信息
|
||||
func Info(source string) map[string]map[string]string {
|
||||
// 数据源
|
||||
rdb := DefaultRDB()
|
||||
if source != "" {
|
||||
rdb = RDB(source)
|
||||
}
|
||||
|
||||
ctx := context.Background()
|
||||
info, err := rdb.Info(ctx).Result()
|
||||
if err != nil {
|
||||
return map[string]map[string]string{}
|
||||
}
|
||||
infoObj := make(map[string]map[string]string)
|
||||
lines := strings.Split(info, "\r\n")
|
||||
label := ""
|
||||
for _, line := range lines {
|
||||
if strings.Contains(line, "#") {
|
||||
label = strings.Fields(line)[len(strings.Fields(line))-1]
|
||||
label = strings.ToLower(label)
|
||||
infoObj[label] = make(map[string]string)
|
||||
continue
|
||||
}
|
||||
kvArr := strings.Split(line, ":")
|
||||
if len(kvArr) >= 2 {
|
||||
key := strings.TrimSpace(kvArr[0])
|
||||
value := strings.TrimSpace(kvArr[len(kvArr)-1])
|
||||
infoObj[label][key] = value
|
||||
}
|
||||
}
|
||||
return infoObj
|
||||
}
|
||||
|
||||
// KeySize 获取redis当前连接可用键Key总数信息
|
||||
func KeySize(source string) int64 {
|
||||
// 数据源
|
||||
rdb := DefaultRDB()
|
||||
if source != "" {
|
||||
rdb = RDB(source)
|
||||
}
|
||||
|
||||
ctx := context.Background()
|
||||
size, err := rdb.DBSize(ctx).Result()
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
return size
|
||||
}
|
||||
|
||||
// CommandStats 获取redis命令状态信息
|
||||
func CommandStats(source string) []map[string]string {
|
||||
// 数据源
|
||||
rdb := DefaultRDB()
|
||||
if source != "" {
|
||||
rdb = RDB(source)
|
||||
}
|
||||
|
||||
ctx := context.Background()
|
||||
commandstats, err := rdb.Info(ctx, "commandstats").Result()
|
||||
if err != nil {
|
||||
return []map[string]string{}
|
||||
}
|
||||
statsObjArr := make([]map[string]string, 0)
|
||||
lines := strings.Split(commandstats, "\r\n")
|
||||
for _, line := range lines {
|
||||
if !strings.HasPrefix(line, "cmdstat_") {
|
||||
continue
|
||||
}
|
||||
kvArr := strings.Split(line, ":")
|
||||
key := kvArr[0]
|
||||
valueStr := kvArr[len(kvArr)-1]
|
||||
statsObj := make(map[string]string)
|
||||
statsObj["name"] = key[8:]
|
||||
statsObj["value"] = valueStr[6:strings.Index(valueStr, ",usec=")]
|
||||
statsObjArr = append(statsObjArr, statsObj)
|
||||
}
|
||||
return statsObjArr
|
||||
}
|
||||
|
||||
// 获取键的剩余有效时间(秒)
|
||||
func GetExpire(source string, key string) (float64, error) {
|
||||
// 数据源
|
||||
rdb := DefaultRDB()
|
||||
if source != "" {
|
||||
rdb = RDB(source)
|
||||
}
|
||||
|
||||
ctx := context.Background()
|
||||
ttl, err := rdb.TTL(ctx, key).Result()
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return ttl.Seconds(), nil
|
||||
}
|
||||
|
||||
// 获得缓存数据的key列表
|
||||
func GetKeys(source string, pattern string) ([]string, error) {
|
||||
// 数据源
|
||||
rdb := DefaultRDB()
|
||||
if source != "" {
|
||||
rdb = RDB(source)
|
||||
}
|
||||
|
||||
// 初始化变量
|
||||
var keys []string
|
||||
var cursor uint64 = 0
|
||||
ctx := context.Background()
|
||||
// 循环遍历获取匹配的键
|
||||
for {
|
||||
// 使用 SCAN 命令获取匹配的键
|
||||
batchKeys, nextCursor, err := rdb.Scan(ctx, cursor, pattern, 100).Result()
|
||||
if err != nil {
|
||||
log.Errorf("Failed to scan keys: %v", err)
|
||||
return keys, err
|
||||
}
|
||||
cursor = nextCursor
|
||||
keys = append(keys, batchKeys...)
|
||||
// 当 cursor 为 0,表示遍历完成
|
||||
if cursor == 0 {
|
||||
break
|
||||
}
|
||||
}
|
||||
return keys, nil
|
||||
}
|
||||
|
||||
// 批量获得缓存数据
|
||||
func GetBatch(source string, keys []string) ([]any, error) {
|
||||
if len(keys) == 0 {
|
||||
return []any{}, fmt.Errorf("not keys")
|
||||
}
|
||||
|
||||
// 数据源
|
||||
rdb := DefaultRDB()
|
||||
if source != "" {
|
||||
rdb = RDB(source)
|
||||
}
|
||||
|
||||
// 获取缓存数据
|
||||
result, err := rdb.MGet(context.Background(), keys...).Result()
|
||||
if err != nil {
|
||||
log.Errorf("Failed to get batch data: %v", err)
|
||||
return []any{}, err
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// 获得缓存数据
|
||||
func Get(source, key string) (string, error) {
|
||||
// 数据源
|
||||
rdb := DefaultRDB()
|
||||
if source != "" {
|
||||
rdb = RDB(source)
|
||||
}
|
||||
|
||||
ctx := context.Background()
|
||||
value, err := rdb.Get(ctx, key).Result()
|
||||
if err == redis.Nil || err != nil {
|
||||
return "", err
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
|
||||
// 获得缓存数据Hash
|
||||
func GetHash(source, key string) (map[string]string, error) {
|
||||
// 数据源
|
||||
rdb := DefaultRDB()
|
||||
if source != "" {
|
||||
rdb = RDB(source)
|
||||
}
|
||||
|
||||
ctx := context.Background()
|
||||
value, err := rdb.HGetAll(ctx, key).Result()
|
||||
if err == redis.Nil || err != nil {
|
||||
return map[string]string{}, err
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
|
||||
// 判断是否存在
|
||||
func Has(source string, keys ...string) (bool, error) {
|
||||
// 数据源
|
||||
rdb := DefaultRDB()
|
||||
if source != "" {
|
||||
rdb = RDB(source)
|
||||
}
|
||||
|
||||
ctx := context.Background()
|
||||
exists, err := rdb.Exists(ctx, keys...).Result()
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return exists >= 1, nil
|
||||
}
|
||||
|
||||
// 设置缓存数据
|
||||
func Set(source, key string, value any) (bool, error) {
|
||||
// 数据源
|
||||
rdb := DefaultRDB()
|
||||
if source != "" {
|
||||
rdb = RDB(source)
|
||||
}
|
||||
|
||||
ctx := context.Background()
|
||||
err := rdb.Set(ctx, key, value, 0).Err()
|
||||
if err != nil {
|
||||
log.Errorf("redis lua script err %v", err)
|
||||
return false, err
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// 设置缓存数据与过期时间
|
||||
func SetByExpire(source, key string, value any, expiration time.Duration) (bool, error) {
|
||||
// 数据源
|
||||
rdb := DefaultRDB()
|
||||
if source != "" {
|
||||
rdb = RDB(source)
|
||||
}
|
||||
|
||||
ctx := context.Background()
|
||||
err := rdb.Set(ctx, key, value, expiration).Err()
|
||||
if err != nil {
|
||||
log.Errorf("redis lua script err %v", err)
|
||||
return false, err
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// 删除单个
|
||||
func Del(source string, key string) (bool, error) {
|
||||
// 数据源
|
||||
rdb := DefaultRDB()
|
||||
if source != "" {
|
||||
rdb = RDB(source)
|
||||
}
|
||||
|
||||
ctx := context.Background()
|
||||
err := rdb.Del(ctx, key).Err()
|
||||
if err != nil {
|
||||
log.Errorf("redis lua script err %v", err)
|
||||
return false, err
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// 删除多个
|
||||
func DelKeys(source string, keys []string) (bool, error) {
|
||||
if len(keys) == 0 {
|
||||
return false, fmt.Errorf("no keys")
|
||||
}
|
||||
|
||||
// 数据源
|
||||
rdb := DefaultRDB()
|
||||
if source != "" {
|
||||
rdb = RDB(source)
|
||||
}
|
||||
|
||||
ctx := context.Background()
|
||||
err := rdb.Del(ctx, keys...).Err()
|
||||
if err != nil {
|
||||
log.Errorf("redis lua script err %v", err)
|
||||
return false, err
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// 限流查询并记录
|
||||
func RateLimit(source, limitKey string, time, count int64) (int64, error) {
|
||||
// 数据源
|
||||
rdb := DefaultRDB()
|
||||
if source != "" {
|
||||
rdb = RDB(source)
|
||||
}
|
||||
|
||||
ctx := context.Background()
|
||||
result, err := rateLimitCommand.Run(ctx, rdb, []string{limitKey}, time, count).Result()
|
||||
if err != nil {
|
||||
log.Errorf("redis lua script err %v", err)
|
||||
return 0, err
|
||||
}
|
||||
return result.(int64), err
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
package crypto
|
||||
|
||||
import (
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
// BcryptHash Bcrypt密码加密
|
||||
func BcryptHash(originStr string) string {
|
||||
hash, err := bcrypt.GenerateFromPassword([]byte(originStr), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
return string(hash)
|
||||
}
|
||||
|
||||
// BcryptCompare Bcrypt密码匹配检查
|
||||
func BcryptCompare(originStr, hashStr string) bool {
|
||||
err := bcrypt.CompareHashAndPassword([]byte(hashStr), []byte(originStr))
|
||||
return err == nil
|
||||
}
|
||||
@@ -10,10 +10,11 @@ import (
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"ems.agt/lib/core/vo"
|
||||
commonConstants "ems.agt/src/framework/constants/common"
|
||||
tokenConst "ems.agt/src/framework/constants/token"
|
||||
"be.ems/lib/core/vo"
|
||||
commonConstants "be.ems/src/framework/constants/common"
|
||||
tokenConst "be.ems/src/framework/constants/token"
|
||||
"github.com/gorilla/mux"
|
||||
"golang.org/x/text/language"
|
||||
)
|
||||
|
||||
// Param 地址栏参数{id}
|
||||
@@ -31,6 +32,11 @@ func GetQuery(r *http.Request, key string) string {
|
||||
return r.URL.Query().Get(key)
|
||||
}
|
||||
|
||||
// GetHeader 请求头参数
|
||||
func GetHeader(r *http.Request, key string) string {
|
||||
return r.Header.Get(key)
|
||||
}
|
||||
|
||||
// QueryMap 查询参数转换Map
|
||||
func QueryMap(r *http.Request) map[string]any {
|
||||
queryValues := r.URL.Query()
|
||||
@@ -41,6 +47,16 @@ func QueryMap(r *http.Request) map[string]any {
|
||||
return queryParams
|
||||
}
|
||||
|
||||
// ShouldBindQuery 查询参数读取json请求结构团体
|
||||
func ShouldBindQuery(r *http.Request, args any) error {
|
||||
queryParams := QueryMap(r)
|
||||
body, err := json.Marshal(queryParams)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return json.Unmarshal(body, args)
|
||||
}
|
||||
|
||||
// 读取json请求结构团体
|
||||
func ShouldBindJSON(r *http.Request, args any) error {
|
||||
body, err := io.ReadAll(io.LimitReader(r.Body, 1<<20)) // 设置较大的长度,例如 1<<20 (1MB)
|
||||
@@ -118,7 +134,32 @@ func Authorization(r *http.Request) string {
|
||||
return arr[1]
|
||||
}
|
||||
|
||||
// 定义自定义类型作为键
|
||||
// AcceptLanguage 解析客户端接收语言 zh:中文 en: 英文
|
||||
func AcceptLanguage(r *http.Request) string {
|
||||
preferredLanguage := language.English
|
||||
|
||||
// Query请求查询
|
||||
if v := GetQuery(r, "language"); v != "" {
|
||||
tags, _, _ := language.ParseAcceptLanguage(v)
|
||||
if len(tags) > 0 {
|
||||
preferredLanguage = tags[0]
|
||||
}
|
||||
}
|
||||
// Header请求头
|
||||
if v := GetHeader(r, "Accept-Language"); v != "" {
|
||||
tags, _, _ := language.ParseAcceptLanguage(v)
|
||||
if len(tags) > 0 {
|
||||
preferredLanguage = tags[0]
|
||||
}
|
||||
}
|
||||
|
||||
// 只取前缀
|
||||
lang := preferredLanguage.String()
|
||||
arr := strings.Split(lang, "-")
|
||||
return arr[0]
|
||||
}
|
||||
|
||||
// ContextKey 定义自定义类型作为键
|
||||
type ContextKey string
|
||||
|
||||
// LoginUser 登录用户信息需要Authorize中间件
|
||||
|
||||
@@ -4,7 +4,7 @@ import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"ems.agt/lib/log"
|
||||
"be.ems/lib/log"
|
||||
)
|
||||
|
||||
const (
|
||||
|
||||
@@ -1,34 +0,0 @@
|
||||
package firewall
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
|
||||
"ems.agt/lib/core/utils/firewall/client"
|
||||
)
|
||||
|
||||
type FirewallClient interface {
|
||||
Name() string // ufw firewalld
|
||||
Start() error
|
||||
Stop() error
|
||||
Reload() error
|
||||
Status() (string, error) // running not running
|
||||
Version() (string, error)
|
||||
|
||||
ListPort() ([]client.FireInfo, error)
|
||||
ListAddress() ([]client.FireInfo, error)
|
||||
|
||||
Port(port client.FireInfo, operation string) error
|
||||
RichRules(rule client.FireInfo, operation string) error
|
||||
PortForward(info client.Forward, operation string) error
|
||||
}
|
||||
|
||||
func NewFirewallClient() (FirewallClient, error) {
|
||||
if _, err := os.Stat("/usr/sbin/firewalld"); err == nil {
|
||||
return client.NewFirewalld()
|
||||
}
|
||||
if _, err := os.Stat("/usr/sbin/ufw"); err == nil {
|
||||
return client.NewUfw()
|
||||
}
|
||||
return nil, errors.New("no such type")
|
||||
}
|
||||
@@ -1,209 +0,0 @@
|
||||
package client
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"ems.agt/lib/core/cmd"
|
||||
)
|
||||
|
||||
type Firewall struct{}
|
||||
|
||||
func NewFirewalld() (*Firewall, error) {
|
||||
return &Firewall{}, nil
|
||||
}
|
||||
|
||||
func (f *Firewall) Name() string {
|
||||
return "firewalld"
|
||||
}
|
||||
|
||||
func (f *Firewall) Status() (string, error) {
|
||||
stdout, _ := cmd.Exec("firewall-cmd --state")
|
||||
if stdout == "running\n" {
|
||||
return "running", nil
|
||||
}
|
||||
return "not running", nil
|
||||
}
|
||||
|
||||
func (f *Firewall) Version() (string, error) {
|
||||
stdout, err := cmd.Exec("firewall-cmd --version")
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("load the firewall version failed, err: %s", stdout)
|
||||
}
|
||||
return strings.ReplaceAll(stdout, "\n ", ""), nil
|
||||
}
|
||||
|
||||
func (f *Firewall) Start() error {
|
||||
stdout, err := cmd.Exec("systemctl start firewalld")
|
||||
if err != nil {
|
||||
return fmt.Errorf("enable the firewall failed, err: %s", stdout)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *Firewall) Stop() error {
|
||||
stdout, err := cmd.Exec("systemctl stop firewalld")
|
||||
if err != nil {
|
||||
return fmt.Errorf("stop the firewall failed, err: %s", stdout)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *Firewall) Reload() error {
|
||||
stdout, err := cmd.Exec("firewall-cmd --reload")
|
||||
if err != nil {
|
||||
return fmt.Errorf("reload firewall failed, err: %s", stdout)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *Firewall) ListPort() ([]FireInfo, error) {
|
||||
var wg sync.WaitGroup
|
||||
var datas []FireInfo
|
||||
wg.Add(2)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
stdout, err := cmd.Exec("firewall-cmd --zone=public --list-ports")
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
ports := strings.Split(strings.ReplaceAll(stdout, "\n", ""), " ")
|
||||
for _, port := range ports {
|
||||
if len(port) == 0 {
|
||||
continue
|
||||
}
|
||||
var itemPort FireInfo
|
||||
if strings.Contains(port, "/") {
|
||||
itemPort.Port = strings.Split(port, "/")[0]
|
||||
itemPort.Protocol = strings.Split(port, "/")[1]
|
||||
}
|
||||
itemPort.Strategy = "accept"
|
||||
datas = append(datas, itemPort)
|
||||
}
|
||||
}()
|
||||
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
stdout1, err := cmd.Exec("firewall-cmd --zone=public --list-rich-rules")
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
rules := strings.Split(stdout1, "\n")
|
||||
for _, rule := range rules {
|
||||
if len(rule) == 0 {
|
||||
continue
|
||||
}
|
||||
itemRule := f.loadInfo(rule)
|
||||
if len(itemRule.Port) != 0 && itemRule.Family == "ipv4" {
|
||||
datas = append(datas, itemRule)
|
||||
}
|
||||
}
|
||||
}()
|
||||
wg.Wait()
|
||||
return datas, nil
|
||||
}
|
||||
|
||||
func (f *Firewall) ListAddress() ([]FireInfo, error) {
|
||||
stdout, err := cmd.Exec("firewall-cmd --zone=public --list-rich-rules")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var datas []FireInfo
|
||||
rules := strings.Split(stdout, "\n")
|
||||
for _, rule := range rules {
|
||||
if len(rule) == 0 {
|
||||
continue
|
||||
}
|
||||
itemRule := f.loadInfo(rule)
|
||||
if len(itemRule.Port) == 0 && len(itemRule.Address) != 0 {
|
||||
datas = append(datas, itemRule)
|
||||
}
|
||||
}
|
||||
return datas, nil
|
||||
}
|
||||
|
||||
func (f *Firewall) Port(port FireInfo, operation string) error {
|
||||
if cmd.CheckIllegal(operation, port.Protocol, port.Port) {
|
||||
return fmt.Errorf("errCmdIllegal %v", port)
|
||||
}
|
||||
|
||||
stdout, err := cmd.Execf("firewall-cmd --zone=public --%s-port=%s/%s --permanent", operation, port.Port, port.Protocol)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s port failed, err: %s", operation, stdout)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *Firewall) RichRules(rule FireInfo, operation string) error {
|
||||
if cmd.CheckIllegal(operation, rule.Address, rule.Protocol, rule.Port, rule.Strategy) {
|
||||
return fmt.Errorf("errCmdIllegal %v", rule)
|
||||
}
|
||||
ruleStr := ""
|
||||
if strings.Contains(rule.Address, "-") {
|
||||
std, err := cmd.Execf("firewall-cmd --permanent --new-ipset=%s --type=hash:ip", rule.Address)
|
||||
if err != nil {
|
||||
return fmt.Errorf("add new ipset failed, err: %s", std)
|
||||
}
|
||||
std2, err := cmd.Execf("firewall-cmd --permanent --ipset=%s --add-entry=%s", rule.Address, rule.Address)
|
||||
if err != nil {
|
||||
return fmt.Errorf("add entry to ipset failed, err: %s", std2)
|
||||
}
|
||||
if err := f.Reload(); err != nil {
|
||||
return err
|
||||
}
|
||||
ruleStr = fmt.Sprintf("rule source ipset=%s %s", rule.Address, rule.Strategy)
|
||||
} else {
|
||||
ruleStr = "rule family=ipv4 "
|
||||
if len(rule.Address) != 0 {
|
||||
ruleStr += fmt.Sprintf("source address=%s ", rule.Address)
|
||||
}
|
||||
if len(rule.Port) != 0 {
|
||||
ruleStr += fmt.Sprintf("port port=%s ", rule.Port)
|
||||
}
|
||||
if len(rule.Protocol) != 0 {
|
||||
ruleStr += fmt.Sprintf("protocol=%s ", rule.Protocol)
|
||||
}
|
||||
ruleStr += rule.Strategy
|
||||
}
|
||||
stdout, err := cmd.Execf("firewall-cmd --zone=public --%s-rich-rule '%s' --permanent", operation, ruleStr)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s rich rules failed, err: %s", operation, stdout)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *Firewall) PortForward(info Forward, operation string) error {
|
||||
ruleStr := fmt.Sprintf("firewall-cmd --%s-forward-port=port=%s:proto=%s:toport=%s --permanent", operation, info.Port, info.Protocol, info.Target)
|
||||
if len(info.Address) != 0 {
|
||||
ruleStr = fmt.Sprintf("firewall-cmd --%s-forward-port=port=%s:proto=%s:toaddr=%s:toport=%s --permanent", operation, info.Port, info.Protocol, info.Address, info.Target)
|
||||
}
|
||||
|
||||
stdout, err := cmd.Exec(ruleStr)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s port forward failed, err: %s", operation, stdout)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *Firewall) loadInfo(line string) FireInfo {
|
||||
var itemRule FireInfo
|
||||
ruleInfo := strings.Split(strings.ReplaceAll(line, "\"", ""), " ")
|
||||
for _, item := range ruleInfo {
|
||||
switch {
|
||||
case strings.Contains(item, "family="):
|
||||
itemRule.Family = strings.ReplaceAll(item, "family=", "")
|
||||
case strings.Contains(item, "ipset="):
|
||||
itemRule.Address = strings.ReplaceAll(item, "ipset=", "")
|
||||
case strings.Contains(item, "address="):
|
||||
itemRule.Address = strings.ReplaceAll(item, "address=", "")
|
||||
case strings.Contains(item, "port="):
|
||||
itemRule.Port = strings.ReplaceAll(item, "port=", "")
|
||||
case strings.Contains(item, "protocol="):
|
||||
itemRule.Protocol = strings.ReplaceAll(item, "protocol=", "")
|
||||
case item == "accept" || item == "drop" || item == "reject":
|
||||
itemRule.Strategy = item
|
||||
}
|
||||
}
|
||||
return itemRule
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
package client
|
||||
|
||||
type FireInfo struct {
|
||||
Family string `json:"family"` // ipv4 ipv6
|
||||
Address string `json:"address"` // Anywhere
|
||||
Port string `json:"port"`
|
||||
Protocol string `json:"protocol"` // tcp udp tcp/udp
|
||||
Strategy string `json:"strategy"` // accept drop
|
||||
|
||||
APPName string `json:"appName"`
|
||||
IsUsed bool `json:"isUsed"`
|
||||
Description string `json:"description"`
|
||||
}
|
||||
|
||||
type Forward struct {
|
||||
Protocol string `json:"protocol"`
|
||||
Address string `json:"address"`
|
||||
Port string `json:"port"`
|
||||
Target string `json:"target"`
|
||||
}
|
||||
@@ -1,238 +0,0 @@
|
||||
package client
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"ems.agt/lib/core/cmd"
|
||||
)
|
||||
|
||||
type Ufw struct {
|
||||
CmdStr string
|
||||
}
|
||||
|
||||
func NewUfw() (*Ufw, error) {
|
||||
var ufw Ufw
|
||||
if cmd.HasNoPasswordSudo() {
|
||||
ufw.CmdStr = "sudo ufw"
|
||||
} else {
|
||||
ufw.CmdStr = "ufw"
|
||||
}
|
||||
return &ufw, nil
|
||||
}
|
||||
|
||||
func (f *Ufw) Name() string {
|
||||
return "ufw"
|
||||
}
|
||||
|
||||
func (f *Ufw) Status() (string, error) {
|
||||
stdout, _ := cmd.Execf("%s status | grep Status", f.CmdStr)
|
||||
if stdout == "Status: active\n" {
|
||||
return "running", nil
|
||||
}
|
||||
stdout1, _ := cmd.Execf("%s status | grep 状态", f.CmdStr)
|
||||
if stdout1 == "状态: 激活\n" {
|
||||
return "running", nil
|
||||
}
|
||||
return "not running", nil
|
||||
}
|
||||
|
||||
func (f *Ufw) Version() (string, error) {
|
||||
stdout, err := cmd.Execf("%s version | grep ufw", f.CmdStr)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("load the firewall status failed, err: %s", stdout)
|
||||
}
|
||||
info := strings.ReplaceAll(stdout, "\n", "")
|
||||
return strings.ReplaceAll(info, "ufw ", ""), nil
|
||||
}
|
||||
|
||||
func (f *Ufw) Start() error {
|
||||
stdout, err := cmd.Execf("echo y | %s enable", f.CmdStr)
|
||||
if err != nil {
|
||||
return fmt.Errorf("enable the firewall failed, err: %s", stdout)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *Ufw) Stop() error {
|
||||
stdout, err := cmd.Execf("%s disable", f.CmdStr)
|
||||
if err != nil {
|
||||
return fmt.Errorf("stop the firewall failed, err: %s", stdout)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *Ufw) Reload() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *Ufw) ListPort() ([]FireInfo, error) {
|
||||
stdout, err := cmd.Execf("%s status verbose", f.CmdStr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
portInfos := strings.Split(stdout, "\n")
|
||||
var datas []FireInfo
|
||||
isStart := false
|
||||
for _, line := range portInfos {
|
||||
if strings.HasPrefix(line, "-") {
|
||||
isStart = true
|
||||
continue
|
||||
}
|
||||
if !isStart {
|
||||
continue
|
||||
}
|
||||
itemFire := f.loadInfo(line, "port")
|
||||
if len(itemFire.Port) != 0 && itemFire.Port != "Anywhere" && !strings.Contains(itemFire.Port, ".") {
|
||||
itemFire.Port = strings.ReplaceAll(itemFire.Port, ":", "-")
|
||||
datas = append(datas, itemFire)
|
||||
}
|
||||
}
|
||||
return datas, nil
|
||||
}
|
||||
|
||||
func (f *Ufw) ListAddress() ([]FireInfo, error) {
|
||||
stdout, err := cmd.Execf("%s status verbose", f.CmdStr)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
portInfos := strings.Split(stdout, "\n")
|
||||
var datas []FireInfo
|
||||
isStart := false
|
||||
for _, line := range portInfos {
|
||||
if strings.HasPrefix(line, "-") {
|
||||
isStart = true
|
||||
continue
|
||||
}
|
||||
if !isStart {
|
||||
continue
|
||||
}
|
||||
if !strings.Contains(line, " IN") {
|
||||
continue
|
||||
}
|
||||
itemFire := f.loadInfo(line, "address")
|
||||
if strings.Contains(itemFire.Port, ".") {
|
||||
itemFire.Address += ("-" + itemFire.Port)
|
||||
itemFire.Port = ""
|
||||
}
|
||||
if len(itemFire.Port) == 0 && len(itemFire.Address) != 0 {
|
||||
datas = append(datas, itemFire)
|
||||
}
|
||||
}
|
||||
return datas, nil
|
||||
}
|
||||
|
||||
func (f *Ufw) Port(port FireInfo, operation string) error {
|
||||
switch port.Strategy {
|
||||
case "accept":
|
||||
port.Strategy = "allow"
|
||||
case "drop":
|
||||
port.Strategy = "deny"
|
||||
default:
|
||||
return fmt.Errorf("unsupport strategy %s", port.Strategy)
|
||||
}
|
||||
if cmd.CheckIllegal(port.Protocol, port.Port) {
|
||||
return fmt.Errorf("errCmdIllegal %v", port)
|
||||
}
|
||||
|
||||
command := fmt.Sprintf("%s %s %s", f.CmdStr, port.Strategy, port.Port)
|
||||
if operation == "remove" {
|
||||
command = fmt.Sprintf("%s delete %s %s", f.CmdStr, port.Strategy, port.Port)
|
||||
}
|
||||
if len(port.Protocol) != 0 {
|
||||
command += fmt.Sprintf("/%s", port.Protocol)
|
||||
}
|
||||
stdout, err := cmd.Exec(command)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s port failed, err: %s", operation, stdout)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *Ufw) RichRules(rule FireInfo, operation string) error {
|
||||
switch rule.Strategy {
|
||||
case "accept":
|
||||
rule.Strategy = "allow"
|
||||
case "drop":
|
||||
rule.Strategy = "deny"
|
||||
default:
|
||||
return fmt.Errorf("unsupport strategy %s", rule.Strategy)
|
||||
}
|
||||
|
||||
if cmd.CheckIllegal(operation, rule.Protocol, rule.Address, rule.Port) {
|
||||
return fmt.Errorf("errCmdIllegal %v", rule)
|
||||
}
|
||||
|
||||
ruleStr := fmt.Sprintf("%s %s ", f.CmdStr, rule.Strategy)
|
||||
if operation == "remove" {
|
||||
ruleStr = fmt.Sprintf("%s delete %s ", f.CmdStr, rule.Strategy)
|
||||
}
|
||||
if len(rule.Protocol) != 0 {
|
||||
ruleStr += fmt.Sprintf("proto %s ", rule.Protocol)
|
||||
}
|
||||
if strings.Contains(rule.Address, "-") {
|
||||
ruleStr += fmt.Sprintf("from %s to %s ", strings.Split(rule.Address, "-")[0], strings.Split(rule.Address, "-")[1])
|
||||
} else {
|
||||
ruleStr += fmt.Sprintf("from %s ", rule.Address)
|
||||
}
|
||||
if len(rule.Port) != 0 {
|
||||
ruleStr += fmt.Sprintf("to any port %s ", rule.Port)
|
||||
}
|
||||
|
||||
stdout, err := cmd.Exec(ruleStr)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s rich rules failed, err: %s", operation, stdout)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *Ufw) PortForward(info Forward, operation string) error {
|
||||
ruleStr := fmt.Sprintf("firewall-cmd --%s-forward-port=port=%s:proto=%s:toport=%s --permanent", operation, info.Port, info.Protocol, info.Target)
|
||||
if len(info.Address) != 0 {
|
||||
ruleStr = fmt.Sprintf("firewall-cmd --%s-forward-port=port=%s:proto=%s:toaddr=%s:toport=%s --permanent", operation, info.Port, info.Protocol, info.Address, info.Target)
|
||||
}
|
||||
|
||||
stdout, err := cmd.Exec(ruleStr)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%s port forward failed, err: %s", operation, stdout)
|
||||
}
|
||||
if err := f.Reload(); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *Ufw) loadInfo(line string, fireType string) FireInfo {
|
||||
fields := strings.Fields(line)
|
||||
var itemInfo FireInfo
|
||||
if len(fields) < 4 {
|
||||
return itemInfo
|
||||
}
|
||||
if fields[1] == "(v6)" {
|
||||
return itemInfo
|
||||
}
|
||||
if fields[0] == "Anywhere" && fireType != "port" {
|
||||
itemInfo.Strategy = "drop"
|
||||
if fields[1] == "ALLOW" {
|
||||
itemInfo.Strategy = "accept"
|
||||
}
|
||||
itemInfo.Address = fields[3]
|
||||
return itemInfo
|
||||
}
|
||||
if strings.Contains(fields[0], "/") {
|
||||
itemInfo.Port = strings.Split(fields[0], "/")[0]
|
||||
itemInfo.Protocol = strings.Split(fields[0], "/")[1]
|
||||
} else {
|
||||
itemInfo.Port = fields[0]
|
||||
itemInfo.Protocol = "tcp/udp"
|
||||
}
|
||||
itemInfo.Family = "ipv4"
|
||||
if fields[1] == "ALLOW" {
|
||||
itemInfo.Strategy = "accept"
|
||||
} else {
|
||||
itemInfo.Strategy = "drop"
|
||||
}
|
||||
itemInfo.Address = fields[3]
|
||||
|
||||
return itemInfo
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
package vo
|
||||
|
||||
import (
|
||||
"ems.agt/lib/dborm"
|
||||
"be.ems/lib/dborm"
|
||||
)
|
||||
|
||||
// LoginUser 登录用户身份权限信息对象
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
package vo
|
||||
|
||||
// import sysmenu "ems.agt/features/sys_menu"
|
||||
// import sysmenu "be.ems/features/sys_menu"
|
||||
|
||||
// TreeSelect 树结构实体类
|
||||
type TreeSelect struct {
|
||||
|
||||
@@ -10,9 +10,9 @@ import (
|
||||
|
||||
"strings"
|
||||
|
||||
"ems.agt/features/sys_role/model"
|
||||
"ems.agt/lib/log"
|
||||
"ems.agt/lib/oauth"
|
||||
"be.ems/features/sys_role/model"
|
||||
"be.ems/lib/log"
|
||||
"be.ems/lib/oauth"
|
||||
|
||||
_ "github.com/go-sql-driver/mysql"
|
||||
"xorm.io/xorm"
|
||||
@@ -228,12 +228,12 @@ func XormGetNeInfo(neType string, neId string) (*NeInfo, error) {
|
||||
log.Debug("XormGetNeInfo processing... ")
|
||||
|
||||
neInfo := new(NeInfo)
|
||||
has, err := xEngine.Where("status in ('0','3') and ne_type=? and ne_id=?", strings.ToUpper(neType), neId).Get(neInfo)
|
||||
has, err := xEngine.Where("ne_type=? and ne_id=?", strings.ToUpper(neType), neId).Get(neInfo)
|
||||
if err != nil {
|
||||
log.Error("Failed to get table ne_info from database:", err)
|
||||
return nil, err
|
||||
} else if !has {
|
||||
log.Infof("Not found ne_info from database, status in ('0','3'), neType=%s, neId=%s", neType, neId)
|
||||
log.Infof("Not found ne_info from database, neType=%s, neId=%s", neType, neId)
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
@@ -245,12 +245,12 @@ func XormGetNeInfoByRmUID(neType string, rmUID string) (*NeInfo, error) {
|
||||
log.Debug("XormGetNeInfoByRmUID processing... ")
|
||||
|
||||
neInfo := new(NeInfo)
|
||||
has, err := xEngine.Where("status in ('0','3') and ne_type=? and rm_uid=?", strings.ToUpper(neType), rmUID).Get(neInfo)
|
||||
has, err := xEngine.Where("ne_type=? and rm_uid=?", strings.ToUpper(neType), rmUID).Get(neInfo)
|
||||
if err != nil {
|
||||
log.Error("Failed to get table ne_info from database:", err)
|
||||
return nil, err
|
||||
} else if !has {
|
||||
log.Infof("Not found ne_info from database, status in ('0','3'), neType=%s, neId=%s", neType, rmUID)
|
||||
log.Infof("Not found ne_info from database, neType=%s, neId=%s", neType, rmUID)
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
@@ -262,7 +262,7 @@ func XormGetAllNeInfo(nes *[]NeInfo) (*[]NeInfo, error) {
|
||||
log.Debug("XormGetAllNeInfo processing... ")
|
||||
|
||||
ne := new(NeInfo)
|
||||
rows, err := xEngine.Table("ne_info").Where("status in ('0','3')").Rows(ne)
|
||||
rows, err := xEngine.Table("ne_info").Rows(ne)
|
||||
if err != nil {
|
||||
log.Error("Failed to get table ne_info from database:", err)
|
||||
return nil, err
|
||||
@@ -284,7 +284,7 @@ func XormGetNeInfoByNeType(neType string, nes *[]NeInfo) error {
|
||||
log.Debug("XormGetNeInfoByNeType processing... ")
|
||||
|
||||
ne := new(NeInfo)
|
||||
rows, err := xEngine.Table("ne_info").Where("status in ('0','3') and ne_type=?", neType).Rows(ne)
|
||||
rows, err := xEngine.Table("ne_info").Where("ne_type=?", neType).Rows(ne)
|
||||
if err != nil {
|
||||
log.Error("Failed to get table ne_info from database:", err)
|
||||
return err
|
||||
@@ -310,12 +310,12 @@ func XormGetNeInfo2(neType string, neIDs []string, nes *[]NeInfo) error {
|
||||
var err error
|
||||
if len(neIDs) == 0 {
|
||||
rows, err = xEngine.Table("ne_info").
|
||||
Where("status in ('0','3') and ne_type=?", neType).
|
||||
Where("ne_type=?", neType).
|
||||
Rows(ne)
|
||||
} else {
|
||||
rows, err = xEngine.Table("ne_info").
|
||||
In("ne_id", neIDs).
|
||||
And("status in ('0','3') and ne_type=?", neType).
|
||||
And("ne_type=?", neType).
|
||||
Rows(ne)
|
||||
}
|
||||
if err != nil {
|
||||
|
||||
@@ -6,8 +6,8 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"ems.agt/lib/dborm"
|
||||
"ems.agt/lib/services"
|
||||
"be.ems/lib/dborm"
|
||||
"be.ems/lib/services"
|
||||
)
|
||||
|
||||
// 登录策略限制登录时间和访问ip范围
|
||||
|
||||
@@ -5,13 +5,13 @@ import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"ems.agt/lib/core/cache"
|
||||
"ems.agt/lib/core/utils/ctx"
|
||||
"ems.agt/lib/core/vo"
|
||||
"ems.agt/lib/core/vo/result"
|
||||
"ems.agt/lib/dborm"
|
||||
commonConstants "ems.agt/src/framework/constants/common"
|
||||
tokenUtils "ems.agt/src/framework/utils/token"
|
||||
"be.ems/lib/core/cache"
|
||||
"be.ems/lib/core/utils/ctx"
|
||||
"be.ems/lib/core/vo"
|
||||
"be.ems/lib/core/vo/result"
|
||||
"be.ems/lib/dborm"
|
||||
commonConstants "be.ems/src/framework/constants/common"
|
||||
tokenUtils "be.ems/src/framework/utils/token"
|
||||
)
|
||||
|
||||
// Authorize 用户身份授权认证校验
|
||||
|
||||
@@ -4,9 +4,9 @@ import (
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"ems.agt/lib/log"
|
||||
"ems.agt/lib/services"
|
||||
tokenConst "ems.agt/src/framework/constants/token"
|
||||
"be.ems/lib/log"
|
||||
"be.ems/lib/services"
|
||||
tokenConst "be.ems/src/framework/constants/token"
|
||||
"github.com/gorilla/mux"
|
||||
)
|
||||
|
||||
|
||||
@@ -9,11 +9,11 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"ems.agt/lib/core/datasource"
|
||||
"ems.agt/lib/core/utils/ctx"
|
||||
"ems.agt/lib/core/utils/date"
|
||||
"ems.agt/lib/dborm"
|
||||
"ems.agt/lib/log"
|
||||
"be.ems/lib/core/datasource"
|
||||
"be.ems/lib/core/utils/ctx"
|
||||
"be.ems/lib/core/utils/date"
|
||||
"be.ems/lib/dborm"
|
||||
"be.ems/lib/log"
|
||||
)
|
||||
|
||||
// LogMML mml操作日志搜集
|
||||
|
||||
@@ -11,13 +11,13 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"ems.agt/lib/core/utils/parse"
|
||||
"ems.agt/lib/dborm"
|
||||
"ems.agt/src/framework/constants/common"
|
||||
"ems.agt/src/framework/middleware/collectlogs"
|
||||
"ems.agt/src/framework/utils/ip2region"
|
||||
"ems.agt/src/modules/system/model"
|
||||
"ems.agt/src/modules/system/service"
|
||||
"be.ems/lib/core/utils/parse"
|
||||
"be.ems/lib/dborm"
|
||||
"be.ems/src/framework/constants/common"
|
||||
"be.ems/src/framework/middleware/collectlogs"
|
||||
"be.ems/src/framework/utils/ip2region"
|
||||
"be.ems/src/modules/system/model"
|
||||
"be.ems/src/modules/system/service"
|
||||
)
|
||||
|
||||
// 敏感属性字段进行掩码
|
||||
|
||||
@@ -11,11 +11,11 @@ import (
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"ems.agt/lib/dborm"
|
||||
"ems.agt/lib/global"
|
||||
"ems.agt/lib/log"
|
||||
"ems.agt/lib/run"
|
||||
tokenConst "ems.agt/src/framework/constants/token"
|
||||
"be.ems/lib/dborm"
|
||||
"be.ems/lib/global"
|
||||
"be.ems/lib/log"
|
||||
"be.ems/lib/run"
|
||||
tokenConst "be.ems/src/framework/constants/token"
|
||||
"github.com/go-resty/resty/v2"
|
||||
)
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"ems.agt/lib/log"
|
||||
"be.ems/lib/log"
|
||||
|
||||
"github.com/dgrijalva/jwt-go"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
|
||||
@@ -5,33 +5,33 @@ import (
|
||||
|
||||
// "log"
|
||||
|
||||
"ems.agt/features/aaaa"
|
||||
"ems.agt/features/cdr"
|
||||
"ems.agt/features/cm"
|
||||
"ems.agt/features/dbrest"
|
||||
"ems.agt/features/file"
|
||||
"ems.agt/features/fm"
|
||||
"ems.agt/features/lm"
|
||||
"ems.agt/features/mml"
|
||||
"ems.agt/features/monitor/monitor"
|
||||
"ems.agt/features/monitor/psnet"
|
||||
"ems.agt/features/nbi"
|
||||
"ems.agt/features/pm"
|
||||
"ems.agt/features/security"
|
||||
"ems.agt/features/sm"
|
||||
"ems.agt/features/state"
|
||||
sysconfig "ems.agt/features/sys_config"
|
||||
sysdictdata "ems.agt/features/sys_dict_data"
|
||||
sysdicttype "ems.agt/features/sys_dict_type"
|
||||
sysmenu "ems.agt/features/sys_menu"
|
||||
sysrole "ems.agt/features/sys_role"
|
||||
sysuser "ems.agt/features/sys_user"
|
||||
"ems.agt/features/trace"
|
||||
udmuser "ems.agt/features/udm_user"
|
||||
"ems.agt/features/ue"
|
||||
"ems.agt/lib/midware"
|
||||
"ems.agt/lib/services"
|
||||
"ems.agt/src/framework/middleware/collectlogs"
|
||||
"be.ems/features/aaaa"
|
||||
"be.ems/features/cdr"
|
||||
"be.ems/features/cm"
|
||||
"be.ems/features/dbrest"
|
||||
"be.ems/features/file"
|
||||
"be.ems/features/fm"
|
||||
"be.ems/features/lm"
|
||||
"be.ems/features/mml"
|
||||
"be.ems/features/monitor/monitor"
|
||||
"be.ems/features/monitor/psnet"
|
||||
"be.ems/features/nbi"
|
||||
"be.ems/features/pm"
|
||||
"be.ems/features/security"
|
||||
"be.ems/features/sm"
|
||||
"be.ems/features/state"
|
||||
sysconfig "be.ems/features/sys_config"
|
||||
sysdictdata "be.ems/features/sys_dict_data"
|
||||
sysdicttype "be.ems/features/sys_dict_type"
|
||||
sysmenu "be.ems/features/sys_menu"
|
||||
sysrole "be.ems/features/sys_role"
|
||||
sysuser "be.ems/features/sys_user"
|
||||
"be.ems/features/trace"
|
||||
udmuser "be.ems/features/udm_user"
|
||||
"be.ems/features/ue"
|
||||
"be.ems/lib/midware"
|
||||
"be.ems/lib/services"
|
||||
"be.ems/src/framework/middleware/collectlogs"
|
||||
|
||||
"github.com/gorilla/mux"
|
||||
)
|
||||
@@ -166,9 +166,6 @@ func init() {
|
||||
Register("PUT", cm.CustomUriNeInfo, cm.PutNeInfo, nil)
|
||||
Register("DELETE", cm.CustomUriNeInfo, cm.DeleteNeInfo, nil)
|
||||
|
||||
Register("PUT", cm.UriOmcNeConfig, cm.PutOMCNeConfig, nil)
|
||||
Register("PUT", cm.CustomUriOmcNeConfig, cm.PutOMCNeConfig, nil)
|
||||
|
||||
//ne service action handle
|
||||
Register("POST", cm.UriNeService, cm.PostNeServiceAction, nil)
|
||||
//ne service action handle
|
||||
@@ -177,9 +174,12 @@ func init() {
|
||||
Register("POST", mml.UriMML, mml.PostMMLToNF, midware.LogMML)
|
||||
Register("POST", mml.UriMMLDiscard, mml.PostMMLToNF, nil)
|
||||
Register("POST", mml.UriOmMmlExt, mml.PostMMLToOMC, midware.LogMML)
|
||||
|
||||
Register("POST", mml.CustomUriMML, mml.PostMMLToNF, midware.LogMML)
|
||||
Register("POST", mml.CustomUriOmMmlExt, mml.PostMMLToOMC, midware.LogMML)
|
||||
// post mml2 (standard upf port=5002)
|
||||
Register("POST", mml.UriMML2, mml.PostMML2ToNF, midware.LogMML)
|
||||
Register("POST", mml.CustomUriMML2, mml.PostMML2ToNF, midware.LogMML)
|
||||
|
||||
// Northbound Get NRM
|
||||
Register("GET", nbi.GetNRMUri, nbi.NBIGetNRMFromNF, nil)
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ import (
|
||||
"bytes"
|
||||
"os/exec"
|
||||
|
||||
"ems.agt/lib/log"
|
||||
"be.ems/lib/log"
|
||||
)
|
||||
|
||||
func ExecCmd(command, path string) ([]byte, error) {
|
||||
|
||||
@@ -6,7 +6,7 @@ package run
|
||||
import (
|
||||
"os/exec"
|
||||
|
||||
"ems.agt/lib/log"
|
||||
"be.ems/lib/log"
|
||||
)
|
||||
|
||||
func ExecCmd(command, path string) ([]byte, error) {
|
||||
|
||||
@@ -6,7 +6,7 @@ package run
|
||||
import (
|
||||
"os/exec"
|
||||
|
||||
"ems.agt/lib/log"
|
||||
"be.ems/lib/log"
|
||||
)
|
||||
|
||||
func ExecCmd(command, path string) ([]byte, error) {
|
||||
|
||||
@@ -11,7 +11,7 @@ import (
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"ems.agt/lib/log"
|
||||
"be.ems/lib/log"
|
||||
)
|
||||
|
||||
const (
|
||||
|
||||
@@ -16,11 +16,11 @@ import (
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"ems.agt/lib/dborm"
|
||||
"ems.agt/lib/global"
|
||||
"ems.agt/lib/log"
|
||||
"ems.agt/lib/oauth"
|
||||
"ems.agt/restagent/config"
|
||||
"be.ems/lib/dborm"
|
||||
"be.ems/lib/global"
|
||||
"be.ems/lib/log"
|
||||
"be.ems/lib/oauth"
|
||||
"be.ems/restagent/config"
|
||||
"github.com/gorilla/mux"
|
||||
)
|
||||
|
||||
|
||||
@@ -11,9 +11,9 @@ import (
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"ems.agt/lib/log"
|
||||
"ems.agt/lib/oauth"
|
||||
"ems.agt/restagent/config"
|
||||
"be.ems/lib/log"
|
||||
"be.ems/lib/oauth"
|
||||
"be.ems/restagent/config"
|
||||
)
|
||||
|
||||
// SessionMgr session manager
|
||||
|
||||
@@ -8,7 +8,7 @@ import (
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"ems.agt/lib/log"
|
||||
"be.ems/lib/log"
|
||||
"github.com/shirou/gopsutil/v3/host"
|
||||
"github.com/shirou/gopsutil/v3/net"
|
||||
"github.com/shirou/gopsutil/v3/process"
|
||||
|
||||
Reference in New Issue
Block a user