mirror of
https://github.com/fankes/komari-agent.git
synced 2025-12-10 23:43:40 +08:00
feat: #28 支持使用环境变量 / 配置文件来传入 agent 参数
This commit is contained in:
@@ -11,7 +11,6 @@ import (
|
|||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
|
|
||||||
"github.com/komari-monitor/komari-agent/cmd/flags"
|
|
||||||
"github.com/komari-monitor/komari-agent/utils"
|
"github.com/komari-monitor/komari-agent/utils"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
@@ -1,28 +1,31 @@
|
|||||||
package flags
|
package flags_pkg
|
||||||
|
|
||||||
var (
|
type Config struct {
|
||||||
AutoDiscoveryKey string
|
AutoDiscoveryKey string `json:"auto_discovery_key" env:"AGENT_AUTO_DISCOVERY_KEY"` // 自动发现密钥
|
||||||
DisableAutoUpdate bool
|
DisableAutoUpdate bool `json:"disable_auto_update" env:"AGENT_DISABLE_AUTO_UPDATE"` // 禁用自动更新
|
||||||
DisableWebSsh bool
|
DisableWebSsh bool `json:"disable_web_ssh" env:"AGENT_DISABLE_WEB_SSH"` // 禁用远程控制(web ssh 和 rce)
|
||||||
MemoryModeAvailable bool
|
MemoryModeAvailable bool `json:"memory_mode_available" env:"AGENT_MEMORY_MODE_AVAILABLE"` // [deprecated] 已弃用,请使用 MemoryIncludeCache
|
||||||
Token string
|
Token string `json:"token" env:"AGENT_TOKEN"` // Token
|
||||||
Endpoint string
|
Endpoint string `json:"endpoint" env:"AGENT_ENDPOINT"` // 面板地址
|
||||||
Interval float64
|
Interval float64 `json:"interval" env:"AGENT_INTERVAL"` // 数据采集间隔,单位秒
|
||||||
IgnoreUnsafeCert bool
|
IgnoreUnsafeCert bool `json:"ignore_unsafe_cert" env:"AGENT_IGNORE_UNSAFE_CERT"` // 忽略不安全的证书
|
||||||
MaxRetries int
|
MaxRetries int `json:"max_retries" env:"AGENT_MAX_RETRIES"` // 最大重试次数
|
||||||
ReconnectInterval int
|
ReconnectInterval int `json:"reconnect_interval" env:"AGENT_RECONNECT_INTERVAL"` // 重连间隔,单位秒
|
||||||
InfoReportInterval int
|
InfoReportInterval int `json:"info_report_interval" env:"AGENT_INFO_REPORT_INTERVAL"` // 基础信息上报间隔,单位分钟
|
||||||
IncludeNics string
|
IncludeNics string `json:"include_nics" env:"AGENT_INCLUDE_NICS"` // 仅统计网卡,逗号分隔的网卡名称列表,支持通配符
|
||||||
ExcludeNics string
|
ExcludeNics string `json:"exclude_nics" env:"AGENT_EXCLUDE_NICS"` // 统计时排除的网卡,逗号分隔的网卡名称列表,支持通配符
|
||||||
IncludeMountpoints string
|
IncludeMountpoints string `json:"include_mountpoints" env:"AGENT_INCLUDE_MOUNTPOINTS"` // 磁盘统计的包含挂载点列表,使用分号分隔
|
||||||
MonthRotate int
|
MonthRotate int `json:"month_rotate" env:"AGENT_MONTH_ROTATE"` // 流量统计的月份重置日期(0表示禁用)
|
||||||
CFAccessClientID string
|
CFAccessClientID string `json:"cf_access_client_id" env:"AGENT_CF_ACCESS_CLIENT_ID"` // Cloudflare Access Client ID
|
||||||
CFAccessClientSecret string
|
CFAccessClientSecret string `json:"cf_access_client_secret" env:"AGENT_CF_ACCESS_CLIENT_SECRET"` // Cloudflare Access Client Secret
|
||||||
MemoryIncludeCache bool
|
MemoryIncludeCache bool `json:"memory_include_cache" env:"AGENT_MEMORY_INCLUDE_CACHE"` // 包括缓存/缓冲区的内存使用情况
|
||||||
CustomDNS string
|
CustomDNS string `json:"custom_dns" env:"AGENT_CUSTOM_DNS"` // 使用的自定义DNS服务器
|
||||||
EnableGPU bool // 启用详细GPU监控
|
EnableGPU bool `json:"enable_gpu" env:"AGENT_ENABLE_GPU"` // 启用详细GPU监控
|
||||||
ShowWarning bool // Windows 上显示安全警告,作为子进程运行一次
|
ShowWarning bool `json:"show_warning" env:"AGENT_SHOW_WARNING"` // Windows 上显示安全警告,作为子进程运行一次
|
||||||
CustomIpv4 string
|
CustomIpv4 string `json:"custom_ipv4" env:"AGENT_CUSTOM_IPV4"` // 自定义 IPv4 地址
|
||||||
CustomIpv6 string
|
CustomIpv6 string `json:"custom_ipv6" env:"AGENT_CUSTOM_IPV6"` // 自定义 IPv6 地址
|
||||||
GetIpAddrFromNic bool // 从网卡获取IP地址
|
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 (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"crypto/tls"
|
"crypto/tls"
|
||||||
|
"encoding/json"
|
||||||
"log"
|
"log"
|
||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
"os/signal"
|
"os/signal"
|
||||||
|
"reflect"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
"syscall"
|
"syscall"
|
||||||
|
|
||||||
"github.com/komari-monitor/komari-agent/cmd/flags"
|
|
||||||
"github.com/komari-monitor/komari-agent/dnsresolver"
|
"github.com/komari-monitor/komari-agent/dnsresolver"
|
||||||
"github.com/komari-monitor/komari-agent/monitoring/netstatic"
|
"github.com/komari-monitor/komari-agent/monitoring/netstatic"
|
||||||
monitoring "github.com/komari-monitor/komari-agent/monitoring/unit"
|
monitoring "github.com/komari-monitor/komari-agent/monitoring/unit"
|
||||||
"github.com/komari-monitor/komari-agent/server"
|
"github.com/komari-monitor/komari-agent/server"
|
||||||
"github.com/komari-monitor/komari-agent/update"
|
"github.com/komari-monitor/komari-agent/update"
|
||||||
"github.com/spf13/cobra"
|
"github.com/spf13/cobra"
|
||||||
|
|
||||||
|
pkg_flags "github.com/komari-monitor/komari-agent/cmd/flags"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
var flags = pkg_flags.GlobalConfig
|
||||||
|
|
||||||
var RootCmd = &cobra.Command{
|
var RootCmd = &cobra.Command{
|
||||||
Use: "komari-agent",
|
Use: "komari-agent",
|
||||||
Short: "komari agent",
|
Short: "komari agent",
|
||||||
Long: `komari agent`,
|
Long: `komari agent`,
|
||||||
Run: func(cmd *cobra.Command, args []string) {
|
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)
|
stopCtx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||||
defer stop()
|
defer stop()
|
||||||
@@ -157,5 +175,46 @@ func init() {
|
|||||||
RootCmd.PersistentFlags().StringVar(&flags.CustomIpv4, "custom-ipv4", "", "Custom IPv4 address to use")
|
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().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().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
|
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"
|
"sync"
|
||||||
"time"
|
"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 (
|
var (
|
||||||
DNSServers = []string{
|
DNSServers = []string{
|
||||||
"[2606:4700:4700::1111]:53", // Cloudflare IPv6
|
"[2606:4700:4700::1111]:53", // Cloudflare IPv6
|
||||||
|
|||||||
@@ -5,10 +5,12 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"log"
|
"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"
|
monitoring "github.com/komari-monitor/komari-agent/monitoring/unit"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
var flags = pkg_flags.GlobalConfig
|
||||||
|
|
||||||
func GenerateReport() []byte {
|
func GenerateReport() []byte {
|
||||||
message := ""
|
message := ""
|
||||||
data := map[string]interface{}{}
|
data := map[string]interface{}{}
|
||||||
@@ -92,7 +94,7 @@ func GenerateReport() []byte {
|
|||||||
// 成功获取详细信息
|
// 成功获取详细信息
|
||||||
gpuData := make([]map[string]interface{}, len(gpuInfo))
|
gpuData := make([]map[string]interface{}, len(gpuInfo))
|
||||||
totalGPUUsage := 0.0
|
totalGPUUsage := 0.0
|
||||||
|
|
||||||
for i, info := range gpuInfo {
|
for i, info := range gpuInfo {
|
||||||
gpuData[i] = map[string]interface{}{
|
gpuData[i] = map[string]interface{}{
|
||||||
"name": info.Name,
|
"name": info.Name,
|
||||||
@@ -103,13 +105,13 @@ func GenerateReport() []byte {
|
|||||||
}
|
}
|
||||||
totalGPUUsage += info.Utilization
|
totalGPUUsage += info.Utilization
|
||||||
}
|
}
|
||||||
|
|
||||||
avgGPUUsage := totalGPUUsage / float64(len(gpuInfo))
|
avgGPUUsage := totalGPUUsage / float64(len(gpuInfo))
|
||||||
|
|
||||||
data["gpu"] = map[string]interface{}{
|
data["gpu"] = map[string]interface{}{
|
||||||
"count": len(gpuInfo),
|
"count": len(gpuInfo),
|
||||||
"average_usage": avgGPUUsage,
|
"average_usage": avgGPUUsage,
|
||||||
"detailed_info": gpuData,
|
"detailed_info": gpuData,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,9 +8,12 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
pkg_flags "github.com/komari-monitor/komari-agent/cmd/flags"
|
||||||
"github.com/shirou/gopsutil/v4/cpu"
|
"github.com/shirou/gopsutil/v4/cpu"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
var flags = pkg_flags.GlobalConfig
|
||||||
|
|
||||||
type CpuInfo struct {
|
type CpuInfo struct {
|
||||||
CPUName string `json:"cpu_name"`
|
CPUName string `json:"cpu_name"`
|
||||||
CPUArchitecture string `json:"cpu_architecture"`
|
CPUArchitecture string `json:"cpu_architecture"`
|
||||||
|
|||||||
@@ -4,7 +4,6 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
"strings"
|
"strings"
|
||||||
|
|
||||||
"github.com/komari-monitor/komari-agent/cmd/flags"
|
|
||||||
"github.com/shirou/gopsutil/v4/disk"
|
"github.com/shirou/gopsutil/v4/disk"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
@@ -9,7 +9,6 @@ import (
|
|||||||
"regexp"
|
"regexp"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/komari-monitor/komari-agent/cmd/flags"
|
|
||||||
"github.com/komari-monitor/komari-agent/dnsresolver"
|
"github.com/komari-monitor/komari-agent/dnsresolver"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
@@ -3,7 +3,6 @@ package monitoring
|
|||||||
import (
|
import (
|
||||||
"runtime"
|
"runtime"
|
||||||
|
|
||||||
"github.com/komari-monitor/komari-agent/cmd/flags"
|
|
||||||
"github.com/shirou/gopsutil/v4/mem"
|
"github.com/shirou/gopsutil/v4/mem"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
@@ -5,7 +5,6 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/komari-monitor/komari-agent/cmd/flags"
|
|
||||||
"github.com/komari-monitor/komari-agent/monitoring/netstatic"
|
"github.com/komari-monitor/komari-agent/monitoring/netstatic"
|
||||||
"github.com/komari-monitor/komari-agent/utils"
|
"github.com/komari-monitor/komari-agent/utils"
|
||||||
"github.com/shirou/gopsutil/v4/net"
|
"github.com/shirou/gopsutil/v4/net"
|
||||||
|
|||||||
@@ -2,8 +2,6 @@ package monitoring
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"github.com/komari-monitor/komari-agent/cmd/flags"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestConnectionsCount(t *testing.T) {
|
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"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/komari-monitor/komari-agent/cmd/flags"
|
|
||||||
"github.com/komari-monitor/komari-agent/dnsresolver"
|
"github.com/komari-monitor/komari-agent/dnsresolver"
|
||||||
monitoring "github.com/komari-monitor/komari-agent/monitoring/unit"
|
monitoring "github.com/komari-monitor/komari-agent/monitoring/unit"
|
||||||
"github.com/komari-monitor/komari-agent/update"
|
"github.com/komari-monitor/komari-agent/update"
|
||||||
|
|
||||||
|
pkg_flags "github.com/komari-monitor/komari-agent/cmd/flags"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
var flags = pkg_flags.GlobalConfig
|
||||||
|
|
||||||
func DoUploadBasicInfoWorks() {
|
func DoUploadBasicInfoWorks() {
|
||||||
ticker := time.NewTicker(time.Duration(flags.InfoReportInterval) * time.Minute)
|
ticker := time.NewTicker(time.Duration(flags.InfoReportInterval) * time.Minute)
|
||||||
for range ticker.C {
|
for range ticker.C {
|
||||||
|
|||||||
@@ -13,7 +13,6 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/komari-monitor/komari-agent/cmd/flags"
|
|
||||||
"github.com/komari-monitor/komari-agent/ws"
|
"github.com/komari-monitor/komari-agent/ws"
|
||||||
ping "github.com/prometheus-community/pro-bing"
|
ping "github.com/prometheus-community/pro-bing"
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -10,7 +10,6 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
|
|
||||||
"github.com/gorilla/websocket"
|
"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/dnsresolver"
|
||||||
"github.com/komari-monitor/komari-agent/monitoring"
|
"github.com/komari-monitor/komari-agent/monitoring"
|
||||||
"github.com/komari-monitor/komari-agent/terminal"
|
"github.com/komari-monitor/komari-agent/terminal"
|
||||||
|
|||||||
@@ -5,9 +5,12 @@ import (
|
|||||||
"fmt"
|
"fmt"
|
||||||
|
|
||||||
"github.com/gorilla/websocket"
|
"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 接口定义平台特定的终端操作
|
// Terminal 接口定义平台特定的终端操作
|
||||||
type Terminal interface {
|
type Terminal interface {
|
||||||
Close() error
|
Close() error
|
||||||
|
|||||||
Reference in New Issue
Block a user