wireguard-dashboard/queues/async_wg_config.go
2024-03-11 11:30:36 +08:00

104 lines
2.8 KiB
Go

package queues
import (
"context"
"encoding/json"
"fmt"
"gitee.ltd/lxh/logger/log"
"os"
"strconv"
"wireguard-dashboard/client"
"wireguard-dashboard/component"
"wireguard-dashboard/constant"
"wireguard-dashboard/model/template_data"
"wireguard-dashboard/repository"
)
// asyncWireguardConfigFile
// @description: 同步配置文件
func asyncWireguardConfigFile() {
for {
result, err := client.Redis.BRPop(context.Background(), 0, fmt.Sprintf("%s", constant.SyncWgConfigFile)).Result()
if err != nil {
log.Errorf("获取任务失败")
continue
}
serverId := result[1]
// 使用serverId获取服务信息
serverEnt, err := repository.Server().GetServerWithClient(serverId)
if err != nil {
log.Errorf("获取服务端信息失败: %s", err.Error())
continue
}
// 获取服务端全局配置
globalSetting, err := repository.System().GetServerSetting()
if err != nil {
log.Errorf("获取服务端配置失败: %s", err.Error())
continue
}
if globalSetting.ConfigFilePath == "" {
globalSetting.ConfigFilePath = "/etc/wireguard/wg0.conf"
}
// 获取模板文件和输出目录
var templatePath, outFilePath string
if os.Getenv("GIN_MODE") != "release" {
templatePath = "E:\\Workspace\\Go\\wireguard-dashboard\\template\\wg.conf"
outFilePath = "E:\\Workspace\\Go\\wireguard-dashboard\\wg0.conf"
} else {
templatePath = "./template/wg.conf"
outFilePath = globalSetting.ConfigFilePath
}
// 组装数据
renderServer := template_data.Server{
Address: serverEnt.IpScope,
ListenPort: serverEnt.ListenPort,
PrivateKey: serverEnt.PrivateKey,
MTU: globalSetting.MTU,
PostUp: serverEnt.PostUpScript,
PreDown: serverEnt.PreDownScript,
PostDown: serverEnt.PostDownScript,
Table: globalSetting.Table,
}
var renderClients []template_data.Client
for _, v := range serverEnt.Clients {
var clientKey template_data.Keys
_ = json.Unmarshal([]byte(v.Keys), &clientKey)
var createUserName string
if v.User != nil {
createUserName = v.User.Name
}
renderClients = append(renderClients, template_data.Client{
ID: v.Id,
Name: v.Name,
PublicKey: clientKey.PublicKey,
PresharedKey: clientKey.PrivateKey,
AllowedIPS: v.AllowedIps,
PersistentKeepalive: strconv.Itoa(globalSetting.PersistentKeepalive),
Endpoint: v.Endpoint,
CreatedAt: v.CreatedAt.String(),
UpdatedAt: v.UpdatedAt.String(),
CreateUser: createUserName,
})
}
renderData := map[string]any{
"Server": renderServer,
"Clients": renderClients,
}
err = component.Wireguard().Apply(templatePath, outFilePath, renderData)
if err != nil {
log.Errorf("同步配置文件失败: %s", err.Error())
continue
}
}
}