From fb7b45527b8e517374b120bd7410e118c9dd733e Mon Sep 17 00:00:00 2001 From: UUBulb <35923940+uubulb@users.noreply.github.com> Date: Fri, 5 Jul 2024 22:31:56 +0800 Subject: [PATCH] service: logging to syslog (#33) * service: logging to syslog * chore: update gopsutil to v4 * chore: move println() to the util package * gpu: only return 0 on failure --- cmd/agent/edit.go | 6 ++--- cmd/agent/main.go | 42 +++----------------------------- cmd/agent/service.go | 33 +++++++++++++++++++++++++ go.mod | 4 +-- go.sum | 8 +++--- pkg/gpu/stat/stat_darwin.go | 2 +- pkg/gpu/stat/stat_freebsd.go | 4 +-- pkg/gpu/stat/stat_linux.go | 2 +- pkg/gpu/stat/stat_windows.go | 8 +++--- pkg/monitor/monitor.go | 47 +++++++++++++++++------------------- pkg/pty/pty_windows.go | 2 +- pkg/util/util.go | 18 +++++++++++++- 12 files changed, 94 insertions(+), 82 deletions(-) diff --git a/cmd/agent/edit.go b/cmd/agent/edit.go index f66edce..b829c03 100644 --- a/cmd/agent/edit.go +++ b/cmd/agent/edit.go @@ -7,8 +7,8 @@ import ( "strings" "github.com/AlecAivazis/survey/v2" - "github.com/shirou/gopsutil/v3/disk" - psnet "github.com/shirou/gopsutil/v3/net" + "github.com/shirou/gopsutil/v4/disk" + psnet "github.com/shirou/gopsutil/v4/net" "github.com/spf13/cobra" ) @@ -123,4 +123,4 @@ func editAgentConfig(cmd *cobra.Command, args []string) { } fmt.Println("修改自定义配置成功,重启 Agent 后生效") -} \ No newline at end of file +} diff --git a/cmd/agent/main.go b/cmd/agent/main.go index f1853e0..6624467 100644 --- a/cmd/agent/main.go +++ b/cmd/agent/main.go @@ -25,7 +25,7 @@ import ( "github.com/nezhahq/go-github-selfupdate/selfupdate" "github.com/nezhahq/service" "github.com/quic-go/quic-go/http3" - "github.com/shirou/gopsutil/v3/host" + "github.com/shirou/gopsutil/v4/host" "github.com/spf13/cobra" "google.golang.org/grpc" "google.golang.org/grpc/credentials" @@ -55,17 +55,11 @@ type AgentCliParam struct { IPReportPeriod uint32 // 上报IP间隔 } -type program struct { - exit chan struct{} - service service.Service -} - var ( version string arch string client pb.NezhaServiceClient inited bool - logger service.Logger ) var agentCmd = &cobra.Command{ @@ -211,33 +205,6 @@ func preRun(cmd *cobra.Command, args []string) { } } -func (p *program) Start(s service.Service) error { - go p.run() - return nil -} - -func (p *program) Stop(s service.Service) error { - close(p.exit) - if service.Interactive() { - os.Exit(0) - } - return nil -} - -func (p *program) run() { - defer func() { - if service.Interactive() { - p.Stop(p.service) - } else { - p.service.Stop() - } - }() - - run() - - return -} - func run() { auth := model.AuthHandler{ ClientSecret: agentCliParam.ClientSecret, @@ -345,7 +312,7 @@ func runService(action string, flags []string) { prg.service = s errs := make(chan error, 5) - logger, err = s.Logger(errs) + util.Logger, err = s.Logger(errs) if err != nil { log.Fatal(err) } @@ -374,7 +341,7 @@ func runService(action string, flags []string) { err = s.Run() if err != nil { - logger.Error(err) + util.Logger.Error(err) } } @@ -740,8 +707,7 @@ func handleTerminalTask(task *pb.Task) { func println(v ...interface{}) { if agentCliParam.Debug { - fmt.Printf("NEZHA@%s>> ", time.Now().Format("2006-01-02 15:04:05")) - fmt.Println(v...) + util.Println(v...) } } diff --git a/cmd/agent/service.go b/cmd/agent/service.go index 25ddec9..08ae082 100644 --- a/cmd/agent/service.go +++ b/cmd/agent/service.go @@ -4,6 +4,7 @@ import ( "fmt" "os" + "github.com/nezhahq/service" "github.com/spf13/cobra" ) @@ -13,6 +14,11 @@ type AgentCliFlags struct { Value string } +type program struct { + exit chan struct{} + service service.Service +} + var serviceCmd = &cobra.Command{ Use: "service ", Short: "服务与自启动设置", @@ -21,6 +27,33 @@ var serviceCmd = &cobra.Command{ PreRun: servicePreRun, } +func (p *program) Start(s service.Service) error { + go p.run() + return nil +} + +func (p *program) Stop(s service.Service) error { + close(p.exit) + if service.Interactive() { + os.Exit(0) + } + return nil +} + +func (p *program) run() { + defer func() { + if service.Interactive() { + p.Stop(p.service) + } else { + p.service.Stop() + } + }() + + run() + + return +} + func init() { agentCmd.AddCommand(serviceCmd) } diff --git a/go.mod b/go.mod index ec43ca6..ceb9d49 100644 --- a/go.mod +++ b/go.mod @@ -17,9 +17,9 @@ require ( github.com/jaypipes/ghw v0.12.0 github.com/json-iterator/go v1.1.12 github.com/nezhahq/go-github-selfupdate v0.0.0-20240418134522-9d84a13bbf2d - github.com/nezhahq/service v0.0.0-20240519060034-90701692f8ef + github.com/nezhahq/service v0.0.0-20240704142721-eba37f9cc709 github.com/quic-go/quic-go v0.40.1 - github.com/shirou/gopsutil/v3 v3.24.5 + github.com/shirou/gopsutil/v4 v4.24.6 github.com/spf13/cobra v1.8.0 github.com/spf13/viper v1.18.2 google.golang.org/grpc v1.63.2 diff --git a/go.sum b/go.sum index f028925..e8533ea 100644 --- a/go.sum +++ b/go.sum @@ -112,8 +112,8 @@ github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9G github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= github.com/nezhahq/go-github-selfupdate v0.0.0-20240418134522-9d84a13bbf2d h1:gUt6JLTE/HH7qXS5F7SSYrmsj8NXx3i5CaF6mzYw6pA= github.com/nezhahq/go-github-selfupdate v0.0.0-20240418134522-9d84a13bbf2d/go.mod h1:fOsabb2tjwCe7/kGSsout6oL2cp0sKhOwYQp6fP/Xfg= -github.com/nezhahq/service v0.0.0-20240519060034-90701692f8ef h1:nC+Cxc9MyBFT+snkl5lBUpxGqSGqXv9B2AMHtZOtXzo= -github.com/nezhahq/service v0.0.0-20240519060034-90701692f8ef/go.mod h1:i6zO7Vzuv5+mdaCzHrvAC4U63W59uXmX9n6o7p4PJGk= +github.com/nezhahq/service v0.0.0-20240704142721-eba37f9cc709 h1:WzZo/RXmJI2ReodnIg09QI4J6D/cHsU7o1WHWcmtqqo= +github.com/nezhahq/service v0.0.0-20240704142721-eba37f9cc709/go.mod h1:i6zO7Vzuv5+mdaCzHrvAC4U63W59uXmX9n6o7p4PJGk= github.com/onsi/ginkgo/v2 v2.9.5 h1:+6Hr4uxzP4XIUyAkg61dWBw8lb/gc4/X5luuxN/EC+Q= github.com/onsi/ginkgo/v2 v2.9.5/go.mod h1:tvAoo1QUJwNEU2ITftXTpR7R1RbCzoZUOs3RonqW57k= github.com/onsi/gomega v1.27.6 h1:ENqfyGeS5AX/rlXDd/ETokDz93u0YufY1Pgxuy/PvWE= @@ -137,8 +137,8 @@ github.com/sagikazarmark/locafero v0.4.0 h1:HApY1R9zGo4DBgr7dqsTH/JJxLTTsOt7u6ke 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= github.com/sagikazarmark/slog-shim v0.1.0/go.mod h1:SrcSrq8aKtyuqEI1uvTDTK1arOWRIczQRv+GVI1AkeQ= -github.com/shirou/gopsutil/v3 v3.24.5 h1:i0t8kL+kQTvpAYToeuiVk3TgDeKOFioZO3Ztz/iZ9pI= -github.com/shirou/gopsutil/v3 v3.24.5/go.mod h1:bsoOS1aStSs9ErQ1WWfxllSeS1K5D+U30r2NfcubMVk= +github.com/shirou/gopsutil/v4 v4.24.6 h1:9qqCSYF2pgOU+t+NgJtp7Co5+5mHF/HyKBUckySQL64= +github.com/shirou/gopsutil/v4 v4.24.6/go.mod h1:aoebb2vxetJ/yIDZISmduFvVNPHqXQ9SEJwRXxkf0RA= github.com/shoenig/go-m1cpu v0.1.6 h1:nxdKQNcEB6vzgA2E2bvzKIYRuNj7XNJ4S/aRSwKzFtM= github.com/shoenig/go-m1cpu v0.1.6/go.mod h1:1JJMcUBvfNwpq05QDQVAnx3gUHr9IYF7GNg9SUEw2VQ= github.com/shoenig/test v0.6.4 h1:kVTaSd7WLz5WZ2IaoM0RSzRsUD+m8wRR+5qvntpn4LU= diff --git a/pkg/gpu/stat/stat_darwin.go b/pkg/gpu/stat/stat_darwin.go index 46807b5..5b50be9 100644 --- a/pkg/gpu/stat/stat_darwin.go +++ b/pkg/gpu/stat/stat_darwin.go @@ -30,7 +30,7 @@ func GetGPUStat() (float64, error) { ioreg := exec.Command("ioreg", "-rd1", "-c", "IOAccelerator") gs, err := extractGPUStat(ioreg) if err != nil || len(gs) == 0 { - return -1, err + return 0, err } return gs[0], nil } diff --git a/pkg/gpu/stat/stat_freebsd.go b/pkg/gpu/stat/stat_freebsd.go index 9108c3b..dcd0da7 100644 --- a/pkg/gpu/stat/stat_freebsd.go +++ b/pkg/gpu/stat/stat_freebsd.go @@ -3,5 +3,5 @@ package stat func GetGPUStat() (float64, error) { - return -1, nil -} \ No newline at end of file + return 0, nil +} diff --git a/pkg/gpu/stat/stat_linux.go b/pkg/gpu/stat/stat_linux.go index ed183be..f7274c8 100644 --- a/pkg/gpu/stat/stat_linux.go +++ b/pkg/gpu/stat/stat_linux.go @@ -38,7 +38,7 @@ func GetGPUStat() (float64, error) { gs, err = getAMDStat() } if err != nil || len(gs) == 0 { - return -1, err + return 0, err } return gs[0], nil } diff --git a/pkg/gpu/stat/stat_windows.go b/pkg/gpu/stat/stat_windows.go index 3ea6f5f..1fceb6e 100644 --- a/pkg/gpu/stat/stat_windows.go +++ b/pkg/gpu/stat/stat_windows.go @@ -11,7 +11,7 @@ import ( func GetGPUStat() (float64, error) { shellPath, err := exec.LookPath("powershell.exe") if err != nil || shellPath == "" { - return -1, err + return 0, err } cmd := exec.Command( shellPath, @@ -20,12 +20,12 @@ func GetGPUStat() (float64, error) { ) output, err1 := cmd.CombinedOutput() if err1 != nil { - return -1, err1 + return 0, err1 } t := strings.TrimSpace(string(output)) gs, err2 := strconv.ParseFloat(t, 64) if err2 != nil { - return -1, err2 + return 0, err2 } return gs, nil -} \ No newline at end of file +} diff --git a/pkg/monitor/monitor.go b/pkg/monitor/monitor.go index f3f1ea7..d1ceb7d 100644 --- a/pkg/monitor/monitor.go +++ b/pkg/monitor/monitor.go @@ -13,17 +13,19 @@ import ( "time" "github.com/dean2021/goss" - "github.com/shirou/gopsutil/v3/cpu" - "github.com/shirou/gopsutil/v3/disk" - "github.com/shirou/gopsutil/v3/host" - "github.com/shirou/gopsutil/v3/load" - "github.com/shirou/gopsutil/v3/mem" - "github.com/shirou/gopsutil/v3/net" - "github.com/shirou/gopsutil/v3/process" + "github.com/shirou/gopsutil/v4/cpu" + "github.com/shirou/gopsutil/v4/disk" + "github.com/shirou/gopsutil/v4/host" + "github.com/shirou/gopsutil/v4/load" + "github.com/shirou/gopsutil/v4/mem" + "github.com/shirou/gopsutil/v4/net" + "github.com/shirou/gopsutil/v4/process" + "github.com/shirou/gopsutil/v4/sensors" "github.com/nezhahq/agent/model" "github.com/nezhahq/agent/pkg/gpu" gpustat "github.com/nezhahq/agent/pkg/gpu/stat" + "github.com/nezhahq/agent/pkg/util" ) var ( @@ -65,7 +67,7 @@ func GetHost(agentConfig *model.AgentConfig) *model.Host { var cpuType string hi, err := host.Info() if err != nil { - println("host.Info error:", err) + util.Println("host.Info error:", err) } else { if hi.VirtualizationRole == "guest" { cpuType = "Virtual" @@ -86,7 +88,7 @@ func GetHost(agentConfig *model.AgentConfig) *model.Host { cpuModelCount := make(map[string]int) ci, err := cpu.Info() if err != nil { - println("cpu.Info error:", err) + util.Println("cpu.Info error:", err) } else { for i := 0; i < len(ci); i++ { cpuModelCount[ci[i].ModelName]++ @@ -108,7 +110,7 @@ func GetHost(agentConfig *model.AgentConfig) *model.Host { mv, err := mem.VirtualMemory() if err != nil { - println("mem.VirtualMemory error:", err) + util.Println("mem.VirtualMemory error:", err) } else { ret.MemTotal = mv.Total if runtime.GOOS != "windows" { @@ -119,7 +121,7 @@ func GetHost(agentConfig *model.AgentConfig) *model.Host { if runtime.GOOS == "windows" { ms, err := mem.SwapMemory() if err != nil { - println("mem.SwapMemory error:", err) + util.Println("mem.SwapMemory error:", err) } else { ret.SwapTotal = ms.Total } @@ -139,14 +141,14 @@ func GetState(agentConfig *model.AgentConfig, skipConnectionCount bool, skipProc cp, err := cpu.Percent(0, false) if err != nil || len(cp) == 0 { - println("cpu.Percent error:", err) + util.Println("cpu.Percent error:", err) } else { ret.CPU = cp[0] } vm, err := mem.VirtualMemory() if err != nil { - println("mem.VirtualMemory error:", err) + util.Println("mem.VirtualMemory error:", err) } else { ret.MemUsed = vm.Total - vm.Available if runtime.GOOS != "windows" { @@ -157,7 +159,7 @@ func GetState(agentConfig *model.AgentConfig, skipConnectionCount bool, skipProc // gopsutil 在 Windows 下不能正确取 swap ms, err := mem.SwapMemory() if err != nil { - println("mem.SwapMemory error:", err) + util.Println("mem.SwapMemory error:", err) } else { ret.SwapUsed = ms.Used } @@ -167,7 +169,7 @@ func GetState(agentConfig *model.AgentConfig, skipConnectionCount bool, skipProc loadStat, err := load.Avg() if err != nil { - println("load.Avg error:", err) + util.Println("load.Avg error:", err) } else { ret.Load1 = loadStat.Load1 ret.Load5 = loadStat.Load5 @@ -178,7 +180,7 @@ func GetState(agentConfig *model.AgentConfig, skipConnectionCount bool, skipProc if !skipProcsCount { procs, err = process.Pids() if err != nil { - println("process.Pids error:", err) + util.Println("process.Pids error:", err) } else { ret.ProcessCount = uint64(len(procs)) } @@ -325,13 +327,13 @@ func updateGPUStat(agentConfig *model.AgentConfig, gpuStat *uint64) { if agentConfig.GPU { gs, err := gpustat.GetGPUStat() if err != nil { - fmt.Println("gpustat.GetGPUStat error:", err) + util.Println("gpustat.GetGPUStat error:", err) atomicStoreFloat64(gpuStat, gs) } else { atomicStoreFloat64(gpuStat, gs) } } else { - atomicStoreFloat64(gpuStat, -1) + atomicStoreFloat64(gpuStat, 0) } } @@ -342,10 +344,10 @@ func updateTemperatureStat() { defer atomic.StoreInt32(&updateTempStatus, 0) if deviceDataFetchAttempts["Temperatures"] <= maxDeviceDataFetchAttempts { - temperatures, err := host.SensorsTemperatures() + temperatures, err := sensors.SensorsTemperatures() if err != nil { deviceDataFetchAttempts["Temperatures"]++ - println("host.SensorsTemperatures error:", err, "attempt:", deviceDataFetchAttempts["Temperatures"]) + util.Println("host.SensorsTemperatures error:", err, "attempt:", deviceDataFetchAttempts["Temperatures"]) } else { deviceDataFetchAttempts["Temperatures"] = 0 tempStat := []model.SensorTemperature{} @@ -374,11 +376,6 @@ func isListContainsStr(list []string, str string) bool { return false } -func println(v ...interface{}) { - fmt.Printf("NEZHA@%s>> ", time.Now().Format("2006-01-02 15:04:05")) - fmt.Println(v...) -} - func atomicStoreFloat64(x *uint64, v float64) { atomic.StoreUint64(x, math.Float64bits(v)) } diff --git a/pkg/pty/pty_windows.go b/pkg/pty/pty_windows.go index 83b8fc7..9f9f712 100644 --- a/pkg/pty/pty_windows.go +++ b/pkg/pty/pty_windows.go @@ -17,7 +17,7 @@ import ( "github.com/UserExistsError/conpty" "github.com/artdarek/go-unzip" "github.com/iamacarpet/go-winpty" - "github.com/shirou/gopsutil/v3/host" + "github.com/shirou/gopsutil/v4/host" ) var isWin10 bool diff --git a/pkg/util/util.go b/pkg/util/util.go index 156b39d..1bb4e6e 100644 --- a/pkg/util/util.go +++ b/pkg/util/util.go @@ -1,13 +1,29 @@ package util import ( + "fmt" "os" + "runtime" + "time" jsoniter "github.com/json-iterator/go" + "github.com/nezhahq/service" ) -var Json = jsoniter.ConfigCompatibleWithStandardLibrary +var ( + Json = jsoniter.ConfigCompatibleWithStandardLibrary + Logger service.Logger +) func IsWindows() bool { return os.PathSeparator == '\\' && os.PathListSeparator == ';' } + +func Println(v ...interface{}) { + if runtime.GOOS != "darwin" { + Logger.Infof("NEZHA@%s>> %v", time.Now().Format("2006-01-02 15:04:05"), fmt.Sprint(v...)) + } else { + fmt.Printf("NEZHA@%s>> ", time.Now().Format("2006-01-02 15:04:05")) + fmt.Println(v...) + } +}