From 36efbeec1d184c7d0723014cda83c17a45a4c485 Mon Sep 17 00:00:00 2001 From: wuko233 Date: Sun, 19 Apr 2026 21:11:51 +0800 Subject: [PATCH] =?UTF-8?q?[cmd]=20=E5=AE=9E=E7=8E=B0=E8=8E=B7=E5=8F=96?= =?UTF-8?q?=E5=92=8C=E6=98=BE=E7=A4=BA=E7=B3=BB=E7=BB=9F=E8=BF=90=E8=A1=8C?= =?UTF-8?q?=E6=97=B6=E9=95=BF=E5=8A=9F=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- cmd/status/status.go | 73 +++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 72 insertions(+), 1 deletion(-) diff --git a/cmd/status/status.go b/cmd/status/status.go index c046e2a..dea8d4e 100644 --- a/cmd/status/status.go +++ b/cmd/status/status.go @@ -4,10 +4,15 @@ import ( "bufio" "fmt" "os" + "os/exec" "path/filepath" + "strings" "sysmonitord/internal/config" + "sysmonitord/pkg/logger" + "time" "github.com/spf13/cobra" + "go.uber.org/zap" ) func NewStatusCmd() *cobra.Command { @@ -35,7 +40,7 @@ func printStatus(cfg *config.Config) { fmt.Println("================") // Todo: 显示运行时长 - runtimeInfo := "N/A" + runtimeInfo := getRuntime() fmt.Printf("Runtime: %s\n", runtimeInfo) fmt.Printf("Data Directory: %s\n", dataDir) @@ -87,3 +92,69 @@ func countLines(filePath string) (int, error) { return lineCount, scanner.Err() } + +func getRuntime() string { + cmd := exec.Command("systemctl", "is-active", "sysmonitord") + output, err := cmd.Output() + if err != nil || strings.TrimSpace(string(output)) != "active" { + return "N/A" + } + + cmd = exec.Command("systemctl", "show", "sysmonitord", "--property=ActiveEnterTimestamp") + output, err = cmd.Output() + if err != nil { + return "N/A" + } + + parts := strings.SplitN(string(output), "=", 2) + if len(parts) != 2 { + return "N/A" + } + + timestampStr := strings.TrimSpace(parts[1]) + if timestampStr == "" { + return "N/A" + } + + layouts := []string{ + "Mon 2006-01-02 15:04:05 MST", + "Mon 2006-01-02 15:04:05", + "2006-01-02 15:04:05 MST", + "2006-01-02 15:04:05", + "Mon 2006-01-02 15:04:05 MST 2006", + } + + var startTime time.Time + var parseErr error + for _, layout := range layouts { + startTime, parseErr = time.Parse(layout, timestampStr) + if parseErr == nil { + logger.Log.Debug("时间解析成功", zap.String("layout", layout)) + break + } + } + if parseErr != nil { + return "N/A" + } + + if time.Since(startTime) < 0 { + return "N/A" + } + + runtime := time.Since(startTime) + + days := int(runtime.Hours()) / 24 + hours := int(runtime.Hours()) % 24 + minutes := int(runtime.Minutes()) % 60 + seconds := int(runtime.Seconds()) % 60 + + if days > 0 { + return fmt.Sprintf("%d天 %d小时 %d分钟 %d秒", days, hours, minutes, seconds) + } else if hours > 0 { + return fmt.Sprintf("%d小时 %d分钟 %d秒", hours, minutes, seconds) + } else if minutes > 0 { + return fmt.Sprintf("%d分钟 %d秒", minutes, seconds) + } else { + return fmt.Sprintf("%d秒", seconds) + } +}