From f0c2a7a7665062ddc6822769e965ba18e0995580 Mon Sep 17 00:00:00 2001 From: naiba Date: Sun, 20 Oct 2024 22:54:48 +0800 Subject: [PATCH] refactor cmd arch & auth func --- .github/workflows/test.yml | 2 - cmd/agent/edit.go | 14 +-- cmd/agent/main.go | 178 +++++++++++++++---------------------- cmd/agent/service.go | 63 ------------- go.mod | 2 - go.sum | 6 -- model/auth.go | 3 +- model/model.go | 31 +++++-- pkg/monitor/myip.go | 7 +- proto/nezha.pb.go | 22 ++--- proto/nezha_grpc.pb.go | 2 +- 11 files changed, 115 insertions(+), 215 deletions(-) diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index ba1c11d..54087c0 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -2,8 +2,6 @@ name: Run Tests on: push: - branches: - - main paths-ignore: - ".github/workflows/agent.yml" - ".github/workflows/codeql-analysis.yml" diff --git a/cmd/agent/edit.go b/cmd/agent/edit.go index 0067318..bcd76a4 100644 --- a/cmd/agent/edit.go +++ b/cmd/agent/edit.go @@ -9,22 +9,10 @@ import ( "github.com/AlecAivazis/survey/v2" "github.com/shirou/gopsutil/v4/disk" psnet "github.com/shirou/gopsutil/v4/net" - "github.com/spf13/cobra" ) -var editCmd = &cobra.Command{ - Use: "edit", - Short: "修改要监控的网卡/分区名单,修改自定义 DNS", - Run: editAgentConfig, - Args: cobra.NoArgs, -} - -func init() { - agentCmd.AddCommand(editCmd) -} - // 修改Agent要监控的网卡与硬盘分区 -func editAgentConfig(cmd *cobra.Command, args []string) { +func editAgentConfig() { nc, err := psnet.IOCounters(true) if err != nil { panic(err) diff --git a/cmd/agent/main.go b/cmd/agent/main.go index f6d310c..fb7f577 100644 --- a/cmd/agent/main.go +++ b/cmd/agent/main.go @@ -4,6 +4,7 @@ import ( "context" "crypto/tls" "errors" + "flag" "fmt" "io" "log" @@ -25,7 +26,6 @@ import ( "github.com/quic-go/quic-go/http3" utls "github.com/refraction-networking/utls" "github.com/shirou/gopsutil/v4/host" - "github.com/spf13/cobra" "google.golang.org/grpc" "google.golang.org/grpc/credentials" "google.golang.org/grpc/credentials/insecure" @@ -41,45 +41,15 @@ import ( pb "github.com/nezhahq/agent/proto" ) -// Agent 运行时参数。如需添加新参数,记得同时在 service.go 中添加 -type AgentCliParam struct { - SkipConnectionCount bool // 跳过连接数检查 - SkipProcsCount bool // 跳过进程数量检查 - DisableAutoUpdate bool // 关闭自动更新 - DisableForceUpdate bool // 关闭强制更新 - DisableCommandExecute bool // 关闭命令执行 - Server string // 服务器地址 - ClientSecret string // 客户端密钥 - ReportDelay int // 报告间隔 - TLS bool // 是否使用TLS加密传输至服务端 - InsecureTLS bool // 是否禁用证书检查 - Version bool // 当前版本号 - IPReportPeriod uint32 // 上报IP间隔 - UseIPv6CountryCode bool // 默认优先展示IPv6旗帜 - UseGiteeToUpgrade bool // 强制从Gitee获取更新 -} - var ( - version string - arch string - client pb.NezhaServiceClient - initialized bool - dnsResolver = &net.Resolver{PreferGo: true} -) - -var agentCmd = &cobra.Command{ - Use: "agent", - Run: func(cmd *cobra.Command, args []string) { - runService("", nil) - }, - PreRun: preRun, - PersistentPreRun: persistPreRun, -} - -var ( - agentCliParam AgentCliParam - agentConfig model.AgentConfig - httpClient = &http.Client{ + version string + arch string + executablePath string + client pb.NezhaServiceClient + initialized bool + dnsResolver = &net.Resolver{PreferGo: true} + agentConfig model.AgentConfig + httpClient = &http.Client{ CheckRedirect: func(req *http.Request, via []*http.Request) error { return http.ErrUseLastResponse }, @@ -122,7 +92,6 @@ func init() { } return nil, err } - headers := util.BrowserHeaders() http.DefaultClient.Timeout = time.Second * 30 httpClient.Transport = utlsx.NewUTLSHTTPRoundTripperWithProxy( @@ -130,43 +99,44 @@ func init() { http.DefaultTransport, nil, &headers, ) - ex, err := os.Executable() + // 来自于 GoReleaser 的版本号 + monitor.Version = version +} + +func main() { + var err error + executablePath, err = os.Executable() if err != nil { panic(err) } + var showVersion, isEditConfig, showHelp bool + var configPath, serviceAction string + // 初始化运行参数 - agentCmd.PersistentFlags().StringVarP(&agentCliParam.Server, "server", "s", "localhost:5555", "管理面板RPC端口") - agentCmd.PersistentFlags().StringVarP(&agentCliParam.ClientSecret, "password", "p", "", "Agent连接Secret") - agentCmd.PersistentFlags().BoolVar(&agentCliParam.TLS, "tls", false, "启用SSL/TLS加密") - agentCmd.PersistentFlags().BoolVarP(&agentCliParam.InsecureTLS, "insecure", "k", false, "禁用证书检查") - agentCmd.PersistentFlags().BoolVarP(&agentConfig.Debug, "debug", "d", false, "开启调试信息") - agentCmd.PersistentFlags().IntVar(&agentCliParam.ReportDelay, "report-delay", 1, "系统状态上报间隔") - agentCmd.PersistentFlags().BoolVar(&agentCliParam.SkipConnectionCount, "skip-conn", false, "不监控连接数") - agentCmd.PersistentFlags().BoolVar(&agentCliParam.SkipProcsCount, "skip-procs", false, "不监控进程数") - agentCmd.PersistentFlags().BoolVar(&agentCliParam.DisableCommandExecute, "disable-command-execute", false, "禁止在此机器上执行命令") - agentCmd.PersistentFlags().BoolVar(&agentCliParam.DisableAutoUpdate, "disable-auto-update", false, "禁用自动升级") - agentCmd.PersistentFlags().BoolVar(&agentCliParam.DisableForceUpdate, "disable-force-update", false, "禁用强制升级") - agentCmd.PersistentFlags().BoolVar(&agentCliParam.UseIPv6CountryCode, "use-ipv6-countrycode", false, "使用IPv6的位置上报") - agentCmd.PersistentFlags().BoolVar(&agentConfig.GPU, "gpu", false, "启用GPU监控") - agentCmd.PersistentFlags().BoolVar(&agentConfig.Temperature, "temperature", false, "启用温度监控") - agentCmd.PersistentFlags().BoolVar(&agentCliParam.UseGiteeToUpgrade, "gitee", false, "使用Gitee获取更新") - agentCmd.PersistentFlags().Uint32VarP(&agentCliParam.IPReportPeriod, "ip-report-period", "u", 30*60, "本地IP更新间隔, 上报频率依旧取决于report-delay的值") - agentCmd.Flags().BoolVarP(&agentCliParam.Version, "version", "v", false, "查看当前版本号") + flag.BoolVar(&showVersion, "v", false, "查看当前版本号") + flag.BoolVar(&showHelp, "h", false, "查看帮助") + flag.BoolVar(&isEditConfig, "edit", false, "编辑配置文件") + flag.StringVar(&serviceAction, "service", "", "服务操作 ") + flag.StringVar(&configPath, "c", filepath.Dir(executablePath)+"/config.yml", "配置文件路径") - agentConfig.Read(filepath.Dir(ex) + "/config.yml") + flag.Parse() - monitor.InitConfig(&agentConfig) -} - -func main() { - if err := agentCmd.Execute(); err != nil { - println(err) - os.Exit(1) + if showHelp { + flag.Usage() + os.Exit(0) + } + + if showVersion { + fmt.Println(version) + os.Exit(0) + } + + if isEditConfig { + editAgentConfig() + os.Exit(0) } -} -func persistPreRun(cmd *cobra.Command, args []string) { // windows环境处理 if runtime.GOOS == "windows" { hostArch, err := host.KernelArch() @@ -186,35 +156,35 @@ func persistPreRun(cmd *cobra.Command, args []string) { panic(fmt.Sprintf("与当前系统不匹配,当前运行 %s_%s, 需要下载 %s_%s", runtime.GOOS, arch, runtime.GOOS, hostArch)) } } -} -func preRun(cmd *cobra.Command, args []string) { - // 来自于 GoReleaser 的版本号 - monitor.Version = version - - if agentCliParam.Version { - fmt.Println(version) - os.Exit(0) - } - - if agentCliParam.ClientSecret == "" { - cmd.Help() + if err := agentConfig.Read(configPath); err != nil { + println(err) os.Exit(1) } - if agentCliParam.ReportDelay < 1 || agentCliParam.ReportDelay > 4 { + monitor.InitConfig(&agentConfig) + + if agentConfig.ClientSecret == "" { + println("ClientSecret 不能为空") + os.Exit(1) + } + + if agentConfig.ReportDelay < 1 || agentConfig.ReportDelay > 4 { println("report-delay 的区间为 1-4") os.Exit(1) } + + runService(serviceAction) } func run() { auth := model.AuthHandler{ - ClientSecret: agentCliParam.ClientSecret, + ClientSecret: agentConfig.ClientSecret, + ClientUUID: agentConfig.UUID, } // 下载远程命令执行需要的终端 - if !agentCliParam.DisableCommandExecute { + if !agentConfig.DisableCommandExecute { go func() { if err := pty.DownloadDependency(); err != nil { printf("pty 下载依赖失败: %v", err) @@ -224,10 +194,10 @@ func run() { // 上报服务器信息 go reportStateDaemon() // 更新IP信息 - go monitor.UpdateIP(agentCliParam.UseIPv6CountryCode, agentCliParam.IPReportPeriod) + go monitor.UpdateIP(agentConfig.UseIPv6CountryCode, agentConfig.IPReportPeriod) // 定时检查更新 - if _, err := semver.Parse(version); err == nil && !agentCliParam.DisableAutoUpdate { + if _, err := semver.Parse(version); err == nil && !agentConfig.DisableAutoUpdate { doSelfUpdate(true) go func() { for range time.Tick(20 * time.Minute) { @@ -251,8 +221,8 @@ func run() { for { var securityOption grpc.DialOption - if agentCliParam.TLS { - if agentCliParam.InsecureTLS { + if agentConfig.TLS { + if agentConfig.InsecureTLS { securityOption = grpc.WithTransportCredentials(credentials.NewTLS(&tls.Config{MinVersion: tls.VersionTLS12, InsecureSkipVerify: true})) } else { securityOption = grpc.WithTransportCredentials(credentials.NewTLS(&tls.Config{MinVersion: tls.VersionTLS12})) @@ -260,7 +230,7 @@ func run() { } else { securityOption = grpc.WithTransportCredentials(insecure.NewCredentials()) } - conn, err = grpc.NewClient(agentCliParam.Server, securityOption, grpc.WithPerRPCCredentials(&auth)) + conn, err = grpc.NewClient(agentConfig.Server, securityOption, grpc.WithPerRPCCredentials(&auth)) if err != nil { printf("与面板建立连接失败: %v", err) retry() @@ -291,23 +261,16 @@ func run() { } } -func runService(action string, flags []string) { - dir, err := os.Getwd() - if err != nil { - printf("获取当前工作目录时出错: ", err) - return - } - +func runService(action string) { winConfig := map[string]interface{}{ "OnFailure": "restart", } svcConfig := &service.Config{ - Name: "nezha-agent", - DisplayName: "Nezha Agent", + Name: filepath.Base(executablePath), + DisplayName: filepath.Base(executablePath), Description: "哪吒探针监控端", - Arguments: flags, - WorkingDirectory: dir, + WorkingDirectory: filepath.Dir(executablePath), Option: winConfig, } @@ -414,7 +377,7 @@ func reportStateDaemon() { for { // 为了更准确的记录时段流量,inited 后再上传状态信息 lastReportHostInfo = reportState(lastReportHostInfo) - time.Sleep(time.Second * time.Duration(agentCliParam.ReportDelay)) + time.Sleep(time.Second * time.Duration(agentConfig.ReportDelay)) } } @@ -422,14 +385,15 @@ func reportState(lastReportHostInfo time.Time) time.Time { if client != nil && initialized { monitor.TrackNetworkSpeed() timeOutCtx, cancel := context.WithTimeout(context.Background(), networkTimeOut) - _, err := client.ReportSystemState(timeOutCtx, monitor.GetState(agentCliParam.SkipConnectionCount, agentCliParam.SkipProcsCount).PB()) + _, err := client.ReportSystemState(timeOutCtx, monitor.GetState(agentConfig.SkipConnectionCount, agentConfig.SkipProcsCount).PB()) cancel() if err != nil { printf("reportState error: %v", err) time.Sleep(delayWhenError) } // 每10分钟重新获取一次硬件信息 - if lastReportHostInfo.Before(time.Now().Add(-10 * time.Minute)) { + if lastReportHostInfo.Before(time.Now().Add(-10*time.Minute)) || monitor.GeoQueryIPChanged { + monitor.GeoQueryIPChanged = false lastReportHostInfo = time.Now() client.ReportSystemInfo(context.Background(), monitor.GetHost().PB()) if monitor.GeoQueryIP != "" { @@ -452,7 +416,7 @@ func doSelfUpdate(useLocalVersion bool) { printf("检查更新: %v", v) var latest *selfupdate.Release var err error - if monitor.CachedCountryCode != "cn" && !agentCliParam.UseGiteeToUpgrade { + if monitor.CachedCountryCode != "cn" && !agentConfig.UseGiteeToUpgrade { latest, err = selfupdate.UpdateSelf(v, "nezhahq/agent") } else { latest, err = selfupdate.UpdateSelfGitee(v, "naibahq/agent") @@ -468,7 +432,7 @@ func doSelfUpdate(useLocalVersion bool) { } func handleUpgradeTask(*pb.Task, *pb.TaskResult) { - if agentCliParam.DisableForceUpdate { + if agentConfig.DisableForceUpdate { return } doSelfUpdate(false) @@ -617,7 +581,7 @@ func checkAltSvc(start time.Time, altSvcStr string, taskUrl string, result *pb.T } func handleCommandTask(task *pb.Task, result *pb.TaskResult) { - if agentCliParam.DisableCommandExecute { + if agentConfig.DisableCommandExecute { result.Data = "此 Agent 已禁止命令执行" return } @@ -666,7 +630,7 @@ type WindowSize struct { } func handleTerminalTask(task *pb.Task) { - if agentCliParam.DisableCommandExecute { + if agentConfig.DisableCommandExecute { println("此 Agent 已禁止命令执行") return } @@ -798,7 +762,7 @@ func handleNATTask(task *pb.Task) { } func handleFMTask(task *pb.Task) { - if agentCliParam.DisableCommandExecute { + if agentConfig.DisableCommandExecute { println("此 Agent 已禁止命令执行") return } diff --git a/cmd/agent/service.go b/cmd/agent/service.go index f01c21f..0fe66d4 100644 --- a/cmd/agent/service.go +++ b/cmd/agent/service.go @@ -1,11 +1,9 @@ package main import ( - "fmt" "os" "github.com/nezhahq/service" - "github.com/spf13/cobra" ) type AgentCliFlags struct { @@ -19,14 +17,6 @@ type program struct { service service.Service } -var serviceCmd = &cobra.Command{ - Use: "service ", - Short: "服务与自启动设置", - Args: cobra.ExactArgs(1), - Run: serviceActions, - PreRun: servicePreRun, -} - func (p *program) Start(s service.Service) error { go p.run() return nil @@ -48,58 +38,5 @@ func (p *program) run() { p.service.Stop() } }() - run() } - -func init() { - agentCmd.AddCommand(serviceCmd) -} - -func servicePreRun(cmd *cobra.Command, args []string) { - if args[0] == "install" { - if agentCliParam.ClientSecret == "" { - cmd.Help() - os.Exit(1) - } - } - - if agentCliParam.ReportDelay < 1 || agentCliParam.ReportDelay > 4 { - println("report-delay 的区间为 1-4") - os.Exit(1) - } -} - -func serviceActions(cmd *cobra.Command, args []string) { - var agentCliFlags []string - - flags := []AgentCliFlags{ - {agentCliParam.Server != "localhost:5555", "-s", agentCliParam.Server}, - {agentCliParam.ClientSecret != "", "-p", agentCliParam.ClientSecret}, - {agentCliParam.TLS, "--tls", ""}, - {agentConfig.Debug, "-d", ""}, - {agentCliParam.ReportDelay != 1, "--report-delay", fmt.Sprint(agentCliParam.ReportDelay)}, - {agentCliParam.SkipConnectionCount, "--skip-conn", ""}, - {agentCliParam.SkipProcsCount, "--skip-procs", ""}, - {agentCliParam.DisableCommandExecute, "--disable-command-execute", ""}, - {agentCliParam.DisableAutoUpdate, "--disable-auto-update", ""}, - {agentCliParam.DisableForceUpdate, "--disable-force-update", ""}, - {agentCliParam.UseIPv6CountryCode, "--use-ipv6-countrycode", ""}, - {agentConfig.GPU, "--gpu", ""}, - {agentCliParam.UseGiteeToUpgrade, "--gitee", ""}, - {agentCliParam.IPReportPeriod != 30*60, "-u", fmt.Sprint(agentCliParam.IPReportPeriod)}, - } - - for _, f := range flags { - if f.IsSpecified { - if f.Value == "" { - agentCliFlags = append(agentCliFlags, f.Flag) - } else { - agentCliFlags = append(agentCliFlags, f.Flag, f.Value) - } - } - } - - action := args[0] - runService(action, agentCliFlags) -} diff --git a/go.mod b/go.mod index 1cbae72..9b07ade 100644 --- a/go.mod +++ b/go.mod @@ -20,7 +20,6 @@ require ( github.com/quic-go/quic-go v0.40.1 github.com/refraction-networking/utls v1.6.3 github.com/shirou/gopsutil/v4 v4.24.9 - github.com/spf13/cobra v1.8.1 github.com/spf13/viper v1.19.0 golang.org/x/net v0.29.0 golang.org/x/sys v0.25.0 @@ -45,7 +44,6 @@ require ( github.com/google/uuid v1.6.0 // indirect github.com/hashicorp/hcl v1.0.0 // indirect github.com/inconshreveable/go-update v0.0.0-20160112193335-8152e7eb6ccf // indirect - github.com/inconshreveable/mousetrap v1.1.0 // indirect github.com/jaypipes/pcidb v1.0.0 // indirect github.com/kballard/go-shellquote v0.0.0-20180428030007-95032a82bc51 // indirect github.com/klauspost/compress v1.17.4 // indirect diff --git a/go.sum b/go.sum index 49f3364..9f2c63c 100644 --- a/go.sum +++ b/go.sum @@ -22,7 +22,6 @@ github.com/chzyer/readline v0.0.0-20180603132655-2972be24d48e/go.mod h1:nSuG5e5P github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU= github.com/cloudflare/circl v1.3.7 h1:qlCDlTPz2n9fu58M0Nh1J/JzcFpfgkFHHX3O35r5vcU= github.com/cloudflare/circl v1.3.7/go.mod h1:sRTcRWXGLrKw6yIGJ+l7amYJFfAXbZG0kBSc8r4zxgA= -github.com/cpuguy83/go-md2man/v2 v2.0.4/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= github.com/creack/pty v1.1.17/go.mod h1:MOBLtS5ELjhRRrroQr9kyvTxUAFNvYEK993ew/Vr4O4= github.com/creack/pty v1.1.23 h1:4M6+isWdcStXEf15G/RbrMPOQj1dZ7HPZCGwE4kOeP0= github.com/creack/pty v1.1.23/go.mod h1:08sCNb52WyoAwi2QDyzUCTgcvVFhUzewun7wtTfvcwE= @@ -69,8 +68,6 @@ github.com/iamacarpet/go-winpty v1.0.4/go.mod h1:50yLtqN2hFb5sYO5Qm2LegB166oAEw/ github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= github.com/inconshreveable/go-update v0.0.0-20160112193335-8152e7eb6ccf h1:WfD7VjIE6z8dIvMsI4/s+1qr5EL+zoIGev1BQj1eoJ8= github.com/inconshreveable/go-update v0.0.0-20160112193335-8152e7eb6ccf/go.mod h1:hyb9oH7vZsitZCiBt0ZvifOrB+qc8PS5IiilCIb87rg= -github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= -github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= github.com/jaypipes/ghw v0.12.0 h1:xU2/MDJfWmBhJnujHY9qwXQLs3DBsf0/Xa9vECY0Tho= github.com/jaypipes/ghw v0.12.0/go.mod h1:jeJGbkRB2lL3/gxYzNYzEDETV1ZJ56OKr+CSeSEym+g= github.com/jaypipes/pcidb v1.0.0 h1:vtZIfkiCUE42oYbJS0TAq9XSfSmcsgo9IdxSm9qzYU8= @@ -133,7 +130,6 @@ github.com/quic-go/quic-go v0.40.1/go.mod h1:PeN7kuVJ4xZbxSv/4OX6S1USOX8MJvydwpT github.com/refraction-networking/utls v1.6.3 h1:MFOfRN35sSx6K5AZNIoESsBuBxS2LCgRilRIdHb6fDc= github.com/refraction-networking/utls v1.6.3/go.mod h1:yil9+7qSl+gBwJqztoQseO6Pr3h62pQoY1lXiNR/FPs= github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8= -github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/sagikazarmark/locafero v0.4.0 h1:HApY1R9zGo4DBgr7dqsTH/JJxLTTsOt7u6keLGt6kNQ= github.com/sagikazarmark/locafero v0.4.0/go.mod h1:Pe1W6UlPYUk/+wc/6KFhbORCfqzgYEpgQ3O5fPuL3H4= github.com/sagikazarmark/slog-shim v0.1.0 h1:diDBnUNK9N/354PgrxMywXnAwEr1QZcOr6gto+ugjYE= @@ -146,8 +142,6 @@ github.com/spf13/afero v1.11.0 h1:WJQKhtpdm3v2IzqG8VMqrr6Rf3UYpEF239Jy9wNepM8= github.com/spf13/afero v1.11.0/go.mod h1:GH9Y3pIexgf1MTIWtNGyogA5MwRIDXGUr+hbWNoBjkY= github.com/spf13/cast v1.6.0 h1:GEiTHELF+vaR5dhz3VqZfFSzZjYbgeKDpBxQVS4GYJ0= github.com/spf13/cast v1.6.0/go.mod h1:ancEpBxwJDODSW/UG4rDrAqiKolqNNh2DX3mk86cAdo= -github.com/spf13/cobra v1.8.1 h1:e5/vxKd/rZsfSJMUX1agtjeTDf+qv1/JdBF8gg5k9ZM= -github.com/spf13/cobra v1.8.1/go.mod h1:wHxEcudfqmLYa8iTfL+OuZPbBZkmvliBWKIezN3kD9Y= github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/spf13/viper v1.19.0 h1:RWq5SEjt8o25SROyN3z2OrDB9l7RPd3lwTWU8EcEdcI= diff --git a/model/auth.go b/model/auth.go index e941ddf..7bd0f4d 100644 --- a/model/auth.go +++ b/model/auth.go @@ -6,10 +6,11 @@ import ( type AuthHandler struct { ClientSecret string + ClientUUID string } func (a *AuthHandler) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) { - return map[string]string{"client_secret": a.ClientSecret}, nil + return map[string]string{"client_secret": a.ClientSecret, "client_uuid": a.ClientUUID}, nil } func (a *AuthHandler) RequireTransportSecurity() bool { diff --git a/model/model.go b/model/model.go index 628c86c..e37715f 100644 --- a/model/model.go +++ b/model/model.go @@ -8,13 +8,30 @@ import ( ) type AgentConfig struct { - HardDrivePartitionAllowlist []string - NICAllowlist map[string]bool - DNS []string - GPU bool - Temperature bool - Debug bool - v *viper.Viper + Debug bool `json:"debug,omitempty"` + + Server string `json:"server,omitempty"` // 服务器地址 + ClientSecret string `json:"client_secret,omitempty"` // 客户端密钥 + UUID string `json:"uuid,omitempty"` + + HardDrivePartitionAllowlist []string `json:"hard_drive_partition_allowlist,omitempty"` + NICAllowlist map[string]bool `json:"nic_allowlist,omitempty"` + DNS []string `json:"dns,omitempty"` + GPU bool `json:"gpu,omitempty"` // 是否检查GPU + Temperature bool `json:"temperature,omitempty"` // 是否检查温度 + SkipConnectionCount bool `json:"skip_connection_count,omitempty"` // 跳过连接数检查 + SkipProcsCount bool `json:"skip_procs_count,omitempty"` // 跳过进程数量检查 + DisableAutoUpdate bool `json:"disable_auto_update,omitempty"` // 关闭自动更新 + DisableForceUpdate bool `json:"disable_force_update,omitempty"` // 关闭强制更新 + DisableCommandExecute bool `json:"disable_command_execute,omitempty"` // 关闭命令执行 + ReportDelay int `json:"report_delay,omitempty"` // 报告间隔 + TLS bool `json:"tls,omitempty"` // 是否使用TLS加密传输至服务端 + InsecureTLS bool `json:"insecure_tls,omitempty"` // 是否禁用证书检查 + UseIPv6CountryCode bool `json:"use_i_pv_6_country_code,omitempty"` // 默认优先展示IPv6旗帜 + UseGiteeToUpgrade bool `json:"use_gitee_to_upgrade,omitempty"` // 强制从Gitee获取更新 + IPReportPeriod uint32 `json:"ip_report_period,omitempty"` // IP上报周期 + + v *viper.Viper } // Read 从给定的文件目录加载配置文件 diff --git a/pkg/monitor/myip.go b/pkg/monitor/myip.go index 5f6f398..398fb8f 100644 --- a/pkg/monitor/myip.go +++ b/pkg/monitor/myip.go @@ -18,8 +18,9 @@ var ( "https://developers.cloudflare.com/cdn-cgi/trace", } CachedIP, GeoQueryIP, CachedCountryCode string - httpClientV4 = util.NewSingleStackHTTPClient(time.Second*20, time.Second*5, time.Second*10, false) - httpClientV6 = util.NewSingleStackHTTPClient(time.Second*20, time.Second*5, time.Second*10, true) + GeoQueryIPChanged bool = true + httpClientV4 = util.NewSingleStackHTTPClient(time.Second*20, time.Second*5, time.Second*10, false) + httpClientV6 = util.NewSingleStackHTTPClient(time.Second*20, time.Second*5, time.Second*10, true) ) // UpdateIP 按设置时间间隔更新IP地址的缓存 @@ -55,8 +56,10 @@ func UpdateIP(useIPv6CountryCode bool, period uint32) { } if ipv6 != "" && (useIPv6CountryCode || ipv4 == "") { + GeoQueryIPChanged = GeoQueryIP != ipv6 || GeoQueryIPChanged GeoQueryIP = ipv6 } else { + GeoQueryIPChanged = GeoQueryIP != ipv4 || GeoQueryIPChanged GeoQueryIP = ipv4 } diff --git a/proto/nezha.pb.go b/proto/nezha.pb.go index 729deb0..f491d51 100644 --- a/proto/nezha.pb.go +++ b/proto/nezha.pb.go @@ -1,7 +1,7 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.34.1 -// protoc v5.26.1 +// protoc-gen-go v1.34.2 +// protoc v5.28.1 // source: proto/nezha.proto package proto @@ -808,7 +808,7 @@ func file_proto_nezha_proto_rawDescGZIP() []byte { } var file_proto_nezha_proto_msgTypes = make([]protoimpl.MessageInfo, 8) -var file_proto_nezha_proto_goTypes = []interface{}{ +var file_proto_nezha_proto_goTypes = []any{ (*Host)(nil), // 0: proto.Host (*State)(nil), // 1: proto.State (*State_SensorTemperature)(nil), // 2: proto.State_SensorTemperature @@ -845,7 +845,7 @@ func file_proto_nezha_proto_init() { return } if !protoimpl.UnsafeEnabled { - file_proto_nezha_proto_msgTypes[0].Exporter = func(v interface{}, i int) interface{} { + file_proto_nezha_proto_msgTypes[0].Exporter = func(v any, i int) any { switch v := v.(*Host); i { case 0: return &v.state @@ -857,7 +857,7 @@ func file_proto_nezha_proto_init() { return nil } } - file_proto_nezha_proto_msgTypes[1].Exporter = func(v interface{}, i int) interface{} { + file_proto_nezha_proto_msgTypes[1].Exporter = func(v any, i int) any { switch v := v.(*State); i { case 0: return &v.state @@ -869,7 +869,7 @@ func file_proto_nezha_proto_init() { return nil } } - file_proto_nezha_proto_msgTypes[2].Exporter = func(v interface{}, i int) interface{} { + file_proto_nezha_proto_msgTypes[2].Exporter = func(v any, i int) any { switch v := v.(*State_SensorTemperature); i { case 0: return &v.state @@ -881,7 +881,7 @@ func file_proto_nezha_proto_init() { return nil } } - file_proto_nezha_proto_msgTypes[3].Exporter = func(v interface{}, i int) interface{} { + file_proto_nezha_proto_msgTypes[3].Exporter = func(v any, i int) any { switch v := v.(*Task); i { case 0: return &v.state @@ -893,7 +893,7 @@ func file_proto_nezha_proto_init() { return nil } } - file_proto_nezha_proto_msgTypes[4].Exporter = func(v interface{}, i int) interface{} { + file_proto_nezha_proto_msgTypes[4].Exporter = func(v any, i int) any { switch v := v.(*TaskResult); i { case 0: return &v.state @@ -905,7 +905,7 @@ func file_proto_nezha_proto_init() { return nil } } - file_proto_nezha_proto_msgTypes[5].Exporter = func(v interface{}, i int) interface{} { + file_proto_nezha_proto_msgTypes[5].Exporter = func(v any, i int) any { switch v := v.(*Receipt); i { case 0: return &v.state @@ -917,7 +917,7 @@ func file_proto_nezha_proto_init() { return nil } } - file_proto_nezha_proto_msgTypes[6].Exporter = func(v interface{}, i int) interface{} { + file_proto_nezha_proto_msgTypes[6].Exporter = func(v any, i int) any { switch v := v.(*IOStreamData); i { case 0: return &v.state @@ -929,7 +929,7 @@ func file_proto_nezha_proto_init() { return nil } } - file_proto_nezha_proto_msgTypes[7].Exporter = func(v interface{}, i int) interface{} { + file_proto_nezha_proto_msgTypes[7].Exporter = func(v any, i int) any { switch v := v.(*GeoIP); i { case 0: return &v.state diff --git a/proto/nezha_grpc.pb.go b/proto/nezha_grpc.pb.go index 07543ce..bbe775b 100644 --- a/proto/nezha_grpc.pb.go +++ b/proto/nezha_grpc.pb.go @@ -1,7 +1,7 @@ // Code generated by protoc-gen-go-grpc. DO NOT EDIT. // versions: // - protoc-gen-go-grpc v1.3.0 -// - protoc v5.26.1 +// - protoc v5.28.1 // source: proto/nezha.proto package proto