mirror of
https://github.com/fankes/komari-agent.git
synced 2025-12-08 14:13:34 +08:00
feat: #28 支持使用环境变量 / 配置文件来传入 agent 参数
This commit is contained in:
@@ -11,7 +11,6 @@ import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/komari-monitor/komari-agent/cmd/flags"
|
||||
"github.com/komari-monitor/komari-agent/utils"
|
||||
)
|
||||
|
||||
|
||||
@@ -1,28 +1,31 @@
|
||||
package flags
|
||||
package flags_pkg
|
||||
|
||||
var (
|
||||
AutoDiscoveryKey string
|
||||
DisableAutoUpdate bool
|
||||
DisableWebSsh bool
|
||||
MemoryModeAvailable bool
|
||||
Token string
|
||||
Endpoint string
|
||||
Interval float64
|
||||
IgnoreUnsafeCert bool
|
||||
MaxRetries int
|
||||
ReconnectInterval int
|
||||
InfoReportInterval int
|
||||
IncludeNics string
|
||||
ExcludeNics string
|
||||
IncludeMountpoints string
|
||||
MonthRotate int
|
||||
CFAccessClientID string
|
||||
CFAccessClientSecret string
|
||||
MemoryIncludeCache bool
|
||||
CustomDNS string
|
||||
EnableGPU bool // 启用详细GPU监控
|
||||
ShowWarning bool // Windows 上显示安全警告,作为子进程运行一次
|
||||
CustomIpv4 string
|
||||
CustomIpv6 string
|
||||
GetIpAddrFromNic bool // 从网卡获取IP地址
|
||||
)
|
||||
type Config struct {
|
||||
AutoDiscoveryKey string `json:"auto_discovery_key" env:"AGENT_AUTO_DISCOVERY_KEY"` // 自动发现密钥
|
||||
DisableAutoUpdate bool `json:"disable_auto_update" env:"AGENT_DISABLE_AUTO_UPDATE"` // 禁用自动更新
|
||||
DisableWebSsh bool `json:"disable_web_ssh" env:"AGENT_DISABLE_WEB_SSH"` // 禁用远程控制(web ssh 和 rce)
|
||||
MemoryModeAvailable bool `json:"memory_mode_available" env:"AGENT_MEMORY_MODE_AVAILABLE"` // [deprecated] 已弃用,请使用 MemoryIncludeCache
|
||||
Token string `json:"token" env:"AGENT_TOKEN"` // Token
|
||||
Endpoint string `json:"endpoint" env:"AGENT_ENDPOINT"` // 面板地址
|
||||
Interval float64 `json:"interval" env:"AGENT_INTERVAL"` // 数据采集间隔,单位秒
|
||||
IgnoreUnsafeCert bool `json:"ignore_unsafe_cert" env:"AGENT_IGNORE_UNSAFE_CERT"` // 忽略不安全的证书
|
||||
MaxRetries int `json:"max_retries" env:"AGENT_MAX_RETRIES"` // 最大重试次数
|
||||
ReconnectInterval int `json:"reconnect_interval" env:"AGENT_RECONNECT_INTERVAL"` // 重连间隔,单位秒
|
||||
InfoReportInterval int `json:"info_report_interval" env:"AGENT_INFO_REPORT_INTERVAL"` // 基础信息上报间隔,单位分钟
|
||||
IncludeNics string `json:"include_nics" env:"AGENT_INCLUDE_NICS"` // 仅统计网卡,逗号分隔的网卡名称列表,支持通配符
|
||||
ExcludeNics string `json:"exclude_nics" env:"AGENT_EXCLUDE_NICS"` // 统计时排除的网卡,逗号分隔的网卡名称列表,支持通配符
|
||||
IncludeMountpoints string `json:"include_mountpoints" env:"AGENT_INCLUDE_MOUNTPOINTS"` // 磁盘统计的包含挂载点列表,使用分号分隔
|
||||
MonthRotate int `json:"month_rotate" env:"AGENT_MONTH_ROTATE"` // 流量统计的月份重置日期(0表示禁用)
|
||||
CFAccessClientID string `json:"cf_access_client_id" env:"AGENT_CF_ACCESS_CLIENT_ID"` // Cloudflare Access Client ID
|
||||
CFAccessClientSecret string `json:"cf_access_client_secret" env:"AGENT_CF_ACCESS_CLIENT_SECRET"` // Cloudflare Access Client Secret
|
||||
MemoryIncludeCache bool `json:"memory_include_cache" env:"AGENT_MEMORY_INCLUDE_CACHE"` // 包括缓存/缓冲区的内存使用情况
|
||||
CustomDNS string `json:"custom_dns" env:"AGENT_CUSTOM_DNS"` // 使用的自定义DNS服务器
|
||||
EnableGPU bool `json:"enable_gpu" env:"AGENT_ENABLE_GPU"` // 启用详细GPU监控
|
||||
ShowWarning bool `json:"show_warning" env:"AGENT_SHOW_WARNING"` // Windows 上显示安全警告,作为子进程运行一次
|
||||
CustomIpv4 string `json:"custom_ipv4" env:"AGENT_CUSTOM_IPV4"` // 自定义 IPv4 地址
|
||||
CustomIpv6 string `json:"custom_ipv6" env:"AGENT_CUSTOM_IPV6"` // 自定义 IPv6 地址
|
||||
GetIpAddrFromNic bool `json:"get_ip_addr_from_nic" env:"AGENT_GET_IP_ADDR_FROM_NIC"` // 从网卡获取IP地址
|
||||
ConfigFile string `json:"config_file" env:"AGENT_CONFIG_FILE"` // JSON配置文件路径
|
||||
}
|
||||
|
||||
var GlobalConfig = &Config{}
|
||||
|
||||
61
cmd/root.go
61
cmd/root.go
@@ -3,26 +3,44 @@ package cmd
|
||||
import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"encoding/json"
|
||||
"log"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"reflect"
|
||||
"strconv"
|
||||
"strings"
|
||||
"syscall"
|
||||
|
||||
"github.com/komari-monitor/komari-agent/cmd/flags"
|
||||
"github.com/komari-monitor/komari-agent/dnsresolver"
|
||||
"github.com/komari-monitor/komari-agent/monitoring/netstatic"
|
||||
monitoring "github.com/komari-monitor/komari-agent/monitoring/unit"
|
||||
"github.com/komari-monitor/komari-agent/server"
|
||||
"github.com/komari-monitor/komari-agent/update"
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
pkg_flags "github.com/komari-monitor/komari-agent/cmd/flags"
|
||||
)
|
||||
|
||||
var flags = pkg_flags.GlobalConfig
|
||||
|
||||
var RootCmd = &cobra.Command{
|
||||
Use: "komari-agent",
|
||||
Short: "komari agent",
|
||||
Long: `komari agent`,
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
loadFromEnv() // 从环境变量加载配置,覆盖解析
|
||||
if flags.ConfigFile != "" {
|
||||
bytes, err := os.ReadFile(flags.ConfigFile)
|
||||
if err != nil {
|
||||
log.Fatalf("Failed to read config file: %v", err)
|
||||
}
|
||||
err = json.Unmarshal(bytes, flags)
|
||||
if err != nil {
|
||||
log.Fatalf("Failed to parse config file: %v", err)
|
||||
}
|
||||
}
|
||||
// 捕获中止信号,优雅退出
|
||||
stopCtx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||
defer stop()
|
||||
@@ -157,5 +175,46 @@ func init() {
|
||||
RootCmd.PersistentFlags().StringVar(&flags.CustomIpv4, "custom-ipv4", "", "Custom IPv4 address to use")
|
||||
RootCmd.PersistentFlags().StringVar(&flags.CustomIpv6, "custom-ipv6", "", "Custom IPv6 address to use")
|
||||
RootCmd.PersistentFlags().BoolVar(&flags.GetIpAddrFromNic, "get-ip-addr-from-nic", false, "Get IP address from network interface")
|
||||
RootCmd.PersistentFlags().StringVar(&flags.ConfigFile, "config", "", "Path to the configuration file")
|
||||
RootCmd.PersistentFlags().ParseErrorsWhitelist.UnknownFlags = true
|
||||
}
|
||||
|
||||
func loadFromEnv() {
|
||||
val := reflect.ValueOf(flags).Elem()
|
||||
typ := val.Type()
|
||||
|
||||
for i := 0; i < val.NumField(); i++ {
|
||||
field := val.Field(i)
|
||||
fieldType := typ.Field(i)
|
||||
|
||||
// Get the env tag
|
||||
envTag := fieldType.Tag.Get("env")
|
||||
if envTag == "" {
|
||||
continue
|
||||
}
|
||||
|
||||
// Get the environment variable value
|
||||
envValue := os.Getenv(envTag)
|
||||
if envValue == "" {
|
||||
continue
|
||||
}
|
||||
|
||||
// Set the field based on its type
|
||||
switch field.Kind() {
|
||||
case reflect.String:
|
||||
field.SetString(envValue)
|
||||
case reflect.Bool:
|
||||
if strings.ToLower(envValue) == "true" || envValue == "1" {
|
||||
field.SetBool(true)
|
||||
}
|
||||
case reflect.Int:
|
||||
if intVal, err := strconv.Atoi(envValue); err == nil {
|
||||
field.SetInt(int64(intVal))
|
||||
}
|
||||
case reflect.Float64:
|
||||
if floatVal, err := strconv.ParseFloat(envValue, 64); err == nil {
|
||||
field.SetFloat(floatVal)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,9 +12,10 @@ import (
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/komari-monitor/komari-agent/cmd/flags"
|
||||
pkg_flags "github.com/komari-monitor/komari-agent/cmd/flags"
|
||||
)
|
||||
|
||||
var flags = pkg_flags.GlobalConfig
|
||||
var (
|
||||
DNSServers = []string{
|
||||
"[2606:4700:4700::1111]:53", // Cloudflare IPv6
|
||||
|
||||
@@ -5,10 +5,12 @@ import (
|
||||
"fmt"
|
||||
"log"
|
||||
|
||||
"github.com/komari-monitor/komari-agent/cmd/flags"
|
||||
pkg_flags "github.com/komari-monitor/komari-agent/cmd/flags"
|
||||
monitoring "github.com/komari-monitor/komari-agent/monitoring/unit"
|
||||
)
|
||||
|
||||
var flags = pkg_flags.GlobalConfig
|
||||
|
||||
func GenerateReport() []byte {
|
||||
message := ""
|
||||
data := map[string]interface{}{}
|
||||
@@ -92,7 +94,7 @@ func GenerateReport() []byte {
|
||||
// 成功获取详细信息
|
||||
gpuData := make([]map[string]interface{}, len(gpuInfo))
|
||||
totalGPUUsage := 0.0
|
||||
|
||||
|
||||
for i, info := range gpuInfo {
|
||||
gpuData[i] = map[string]interface{}{
|
||||
"name": info.Name,
|
||||
@@ -103,13 +105,13 @@ func GenerateReport() []byte {
|
||||
}
|
||||
totalGPUUsage += info.Utilization
|
||||
}
|
||||
|
||||
|
||||
avgGPUUsage := totalGPUUsage / float64(len(gpuInfo))
|
||||
|
||||
|
||||
data["gpu"] = map[string]interface{}{
|
||||
"count": len(gpuInfo),
|
||||
"average_usage": avgGPUUsage,
|
||||
"detailed_info": gpuData,
|
||||
"count": len(gpuInfo),
|
||||
"average_usage": avgGPUUsage,
|
||||
"detailed_info": gpuData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,9 +8,12 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
pkg_flags "github.com/komari-monitor/komari-agent/cmd/flags"
|
||||
"github.com/shirou/gopsutil/v4/cpu"
|
||||
)
|
||||
|
||||
var flags = pkg_flags.GlobalConfig
|
||||
|
||||
type CpuInfo struct {
|
||||
CPUName string `json:"cpu_name"`
|
||||
CPUArchitecture string `json:"cpu_architecture"`
|
||||
|
||||
@@ -4,7 +4,6 @@ import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/komari-monitor/komari-agent/cmd/flags"
|
||||
"github.com/shirou/gopsutil/v4/disk"
|
||||
)
|
||||
|
||||
|
||||
@@ -9,7 +9,6 @@ import (
|
||||
"regexp"
|
||||
"time"
|
||||
|
||||
"github.com/komari-monitor/komari-agent/cmd/flags"
|
||||
"github.com/komari-monitor/komari-agent/dnsresolver"
|
||||
)
|
||||
|
||||
|
||||
@@ -3,7 +3,6 @@ package monitoring
|
||||
import (
|
||||
"runtime"
|
||||
|
||||
"github.com/komari-monitor/komari-agent/cmd/flags"
|
||||
"github.com/shirou/gopsutil/v4/mem"
|
||||
)
|
||||
|
||||
|
||||
@@ -5,7 +5,6 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/komari-monitor/komari-agent/cmd/flags"
|
||||
"github.com/komari-monitor/komari-agent/monitoring/netstatic"
|
||||
"github.com/komari-monitor/komari-agent/utils"
|
||||
"github.com/shirou/gopsutil/v4/net"
|
||||
|
||||
@@ -2,8 +2,6 @@ package monitoring
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/komari-monitor/komari-agent/cmd/flags"
|
||||
)
|
||||
|
||||
func TestConnectionsCount(t *testing.T) {
|
||||
|
||||
@@ -1 +1,5 @@
|
||||
# komari-agent
|
||||
# komari-agent
|
||||
|
||||
支持使用环境变量 / JSON配置文件来传入 agent 参数
|
||||
|
||||
详见 `cmd/flags/flags.go` 及 `cmd/root.go`
|
||||
@@ -9,12 +9,15 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/komari-monitor/komari-agent/cmd/flags"
|
||||
"github.com/komari-monitor/komari-agent/dnsresolver"
|
||||
monitoring "github.com/komari-monitor/komari-agent/monitoring/unit"
|
||||
"github.com/komari-monitor/komari-agent/update"
|
||||
|
||||
pkg_flags "github.com/komari-monitor/komari-agent/cmd/flags"
|
||||
)
|
||||
|
||||
var flags = pkg_flags.GlobalConfig
|
||||
|
||||
func DoUploadBasicInfoWorks() {
|
||||
ticker := time.NewTicker(time.Duration(flags.InfoReportInterval) * time.Minute)
|
||||
for range ticker.C {
|
||||
|
||||
@@ -13,7 +13,6 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/komari-monitor/komari-agent/cmd/flags"
|
||||
"github.com/komari-monitor/komari-agent/ws"
|
||||
ping "github.com/prometheus-community/pro-bing"
|
||||
)
|
||||
|
||||
@@ -10,7 +10,6 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/gorilla/websocket"
|
||||
"github.com/komari-monitor/komari-agent/cmd/flags"
|
||||
"github.com/komari-monitor/komari-agent/dnsresolver"
|
||||
"github.com/komari-monitor/komari-agent/monitoring"
|
||||
"github.com/komari-monitor/komari-agent/terminal"
|
||||
|
||||
@@ -5,9 +5,12 @@ import (
|
||||
"fmt"
|
||||
|
||||
"github.com/gorilla/websocket"
|
||||
"github.com/komari-monitor/komari-agent/cmd/flags"
|
||||
|
||||
pkg_flags "github.com/komari-monitor/komari-agent/cmd/flags"
|
||||
)
|
||||
|
||||
var flags = pkg_flags.GlobalConfig
|
||||
|
||||
// Terminal 接口定义平台特定的终端操作
|
||||
type Terminal interface {
|
||||
Close() error
|
||||
|
||||
Reference in New Issue
Block a user