...
This commit is contained in:
164
pkg/system/stats/cmd/manager_example/main.go
Normal file
164
pkg/system/stats/cmd/manager_example/main.go
Normal file
@@ -0,0 +1,164 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/freeflowuniverse/heroagent/pkg/system/stats"
|
||||
)
|
||||
|
||||
func main() {
|
||||
fmt.Println("Stats Manager Example")
|
||||
fmt.Println("====================")
|
||||
|
||||
// Create a new stats manager with Redis connection
|
||||
// Create a custom configuration
|
||||
config := &stats.Config{
|
||||
RedisAddr: "localhost:6379",
|
||||
RedisPassword: "",
|
||||
RedisDB: 0,
|
||||
Debug: false,
|
||||
QueueSize: 100,
|
||||
DefaultTimeout: 5 * time.Second,
|
||||
ExpirationTimes: map[string]time.Duration{
|
||||
"system": 60 * time.Second, // System info expires after 60 seconds
|
||||
"disk": 300 * time.Second, // Disk info expires after 5 minutes
|
||||
"process": 60 * time.Second, // Process info expires after 1 minute
|
||||
"network": 30 * time.Second, // Network info expires after 30 seconds
|
||||
"hardware": 120 * time.Second, // Hardware stats expire after 2 minutes
|
||||
},
|
||||
}
|
||||
|
||||
manager, err := stats.NewStatsManager(config)
|
||||
if err != nil {
|
||||
fmt.Printf("Error creating stats manager: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
defer manager.Close()
|
||||
|
||||
// Set up signal handling for graceful shutdown
|
||||
sigChan := make(chan os.Signal, 1)
|
||||
signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
|
||||
go func() {
|
||||
<-sigChan
|
||||
fmt.Println("\nShutting down...")
|
||||
manager.Close()
|
||||
os.Exit(0)
|
||||
}()
|
||||
|
||||
// Example 1: Get system info
|
||||
fmt.Println("\n1. SYSTEM INFORMATION")
|
||||
fmt.Println("--------------------")
|
||||
sysInfo, err := manager.GetSystemInfo()
|
||||
if err != nil {
|
||||
fmt.Printf("Error getting system info: %v\n", err)
|
||||
} else {
|
||||
fmt.Println("CPU Information:")
|
||||
fmt.Printf(" Cores: %d\n", sysInfo.CPU.Cores)
|
||||
fmt.Printf(" Model: %s\n", sysInfo.CPU.ModelName)
|
||||
fmt.Printf(" Usage: %.1f%%\n", sysInfo.CPU.UsagePercent)
|
||||
|
||||
fmt.Println("\nMemory Information:")
|
||||
fmt.Printf(" Total: %.1f GB\n", sysInfo.Memory.Total)
|
||||
fmt.Printf(" Used: %.1f GB (%.1f%%)\n", sysInfo.Memory.Used, sysInfo.Memory.UsedPercent)
|
||||
fmt.Printf(" Free: %.1f GB\n", sysInfo.Memory.Free)
|
||||
|
||||
fmt.Println("\nNetwork Information:")
|
||||
fmt.Printf(" Upload Speed: %s\n", sysInfo.Network.UploadSpeed)
|
||||
fmt.Printf(" Download Speed: %s\n", sysInfo.Network.DownloadSpeed)
|
||||
}
|
||||
|
||||
// Example 2: Get disk stats
|
||||
fmt.Println("\n2. DISK INFORMATION")
|
||||
fmt.Println("------------------")
|
||||
diskStats, err := manager.GetDiskStats()
|
||||
if err != nil {
|
||||
fmt.Printf("Error getting disk stats: %v\n", err)
|
||||
} else {
|
||||
fmt.Printf("Found %d disks:\n", len(diskStats.Disks))
|
||||
for _, disk := range diskStats.Disks {
|
||||
fmt.Printf(" %s: %.1f GB total, %.1f GB free (%.1f%% used)\n",
|
||||
disk.Path, disk.Total, disk.Free, disk.UsedPercent)
|
||||
}
|
||||
}
|
||||
|
||||
// Example 3: Get process stats
|
||||
fmt.Println("\n3. PROCESS INFORMATION")
|
||||
fmt.Println("---------------------")
|
||||
processStats, err := manager.GetProcessStats(5) // Get top 5 processes
|
||||
if err != nil {
|
||||
fmt.Printf("Error getting process stats: %v\n", err)
|
||||
} else {
|
||||
fmt.Printf("Total processes: %d (showing top %d)\n",
|
||||
processStats.Total, len(processStats.Processes))
|
||||
|
||||
fmt.Println("\nTop Processes by CPU Usage:")
|
||||
for i, proc := range processStats.Processes {
|
||||
fmt.Printf(" %d. PID %d: %s (CPU: %.1f%%, Memory: %.1f MB)\n",
|
||||
i+1, proc.PID, proc.Name, proc.CPUPercent, proc.MemoryMB)
|
||||
}
|
||||
}
|
||||
|
||||
// Example 4: Demonstrate caching by getting the same data multiple times
|
||||
fmt.Println("\n4. CACHING DEMONSTRATION")
|
||||
fmt.Println("----------------------")
|
||||
fmt.Println("Getting network speed multiple times (should use cache):")
|
||||
|
||||
for i := 0; i < 3; i++ {
|
||||
netSpeed := manager.GetNetworkSpeedResult()
|
||||
fmt.Printf(" Request %d: Upload: %s, Download: %s\n",
|
||||
i+1, netSpeed.UploadSpeed, netSpeed.DownloadSpeed)
|
||||
time.Sleep(500 * time.Millisecond)
|
||||
}
|
||||
|
||||
// Example 5: Get hardware stats JSON
|
||||
fmt.Println("\n5. HARDWARE STATS JSON")
|
||||
fmt.Println("--------------------")
|
||||
hardwareJSON := manager.GetHardwareStatsJSON()
|
||||
prettyJSON, _ := json.MarshalIndent(hardwareJSON, "", " ")
|
||||
fmt.Println(string(prettyJSON))
|
||||
|
||||
// Example 6: Debug mode demonstration
|
||||
fmt.Println("\n6. DEBUG MODE DEMONSTRATION")
|
||||
fmt.Println("--------------------------")
|
||||
fmt.Println("Enabling debug mode (direct fetching without cache)...")
|
||||
manager.Debug = true
|
||||
|
||||
fmt.Println("Getting system info in debug mode:")
|
||||
debugSysInfo, err := manager.GetSystemInfo()
|
||||
if err != nil {
|
||||
fmt.Printf("Error: %v\n", err)
|
||||
} else {
|
||||
fmt.Printf(" CPU Usage: %.1f%%\n", debugSysInfo.CPU.UsagePercent)
|
||||
fmt.Printf(" Memory Used: %.1f GB (%.1f%%)\n",
|
||||
debugSysInfo.Memory.Used, debugSysInfo.Memory.UsedPercent)
|
||||
}
|
||||
|
||||
// Reset debug mode
|
||||
manager.Debug = false
|
||||
|
||||
// Example 7: Modify expiration times
|
||||
fmt.Println("\n7. CUSTOM EXPIRATION TIMES")
|
||||
fmt.Println("------------------------")
|
||||
fmt.Println("Current expiration times:")
|
||||
for statsType, duration := range manager.Expiration {
|
||||
fmt.Printf(" %s: %v\n", statsType, duration)
|
||||
}
|
||||
|
||||
fmt.Println("\nChanging system stats expiration to 10 seconds...")
|
||||
manager.Expiration["system"] = 10 * time.Second
|
||||
|
||||
fmt.Println("Updated expiration times:")
|
||||
for statsType, duration := range manager.Expiration {
|
||||
fmt.Printf(" %s: %v\n", statsType, duration)
|
||||
}
|
||||
|
||||
fmt.Println("\nDemo complete. Press Ctrl+C to exit.")
|
||||
|
||||
// Keep the program running
|
||||
select {}
|
||||
}
|
285
pkg/system/stats/cmd/performance_test/main.go
Normal file
285
pkg/system/stats/cmd/performance_test/main.go
Normal file
@@ -0,0 +1,285 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"flag"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/signal"
|
||||
"runtime"
|
||||
"runtime/pprof"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/freeflowuniverse/heroagent/pkg/system/stats"
|
||||
"github.com/shirou/gopsutil/v3/cpu"
|
||||
"github.com/shirou/gopsutil/v3/process"
|
||||
)
|
||||
|
||||
// TestResult stores the results of a single test run
|
||||
type TestResult struct {
|
||||
StartTime time.Time
|
||||
EndTime time.Time
|
||||
SystemInfoTime time.Duration
|
||||
DiskStatsTime time.Duration
|
||||
ProcessTime time.Duration
|
||||
NetworkTime time.Duration
|
||||
HardwareTime time.Duration
|
||||
TotalTime time.Duration
|
||||
UserCPU float64
|
||||
SystemCPU float64
|
||||
TotalCPU float64
|
||||
OverallCPU float64
|
||||
MemoryUsageMB float32
|
||||
NumGoroutines int
|
||||
}
|
||||
|
||||
func main() {
|
||||
// Parse command line flags
|
||||
intervalPtr := flag.Int("interval", 5, "Interval between tests in seconds")
|
||||
sleepPtr := flag.Int("sleep", 0, "Sleep time between operations in milliseconds")
|
||||
cpuProfilePtr := flag.String("cpuprofile", "", "Write cpu profile to file")
|
||||
flag.Parse()
|
||||
|
||||
// If CPU profiling is enabled, set it up
|
||||
if *cpuProfilePtr != "" {
|
||||
f, err := os.Create(*cpuProfilePtr)
|
||||
if err != nil {
|
||||
fmt.Printf("Error creating CPU profile: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
defer f.Close()
|
||||
if err := pprof.StartCPUProfile(f); err != nil {
|
||||
fmt.Printf("Error starting CPU profile: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
defer pprof.StopCPUProfile()
|
||||
}
|
||||
|
||||
fmt.Println("StatsManager Performance Test")
|
||||
fmt.Println("============================")
|
||||
fmt.Printf("This test measures the performance of retrieving stats from Redis cache\n")
|
||||
fmt.Printf("It will run every %d seconds and print performance metrics\n", *intervalPtr)
|
||||
fmt.Printf("Sleep between operations: %d ms\n", *sleepPtr)
|
||||
fmt.Println("Press Ctrl+C to exit and view summary statistics")
|
||||
fmt.Println()
|
||||
|
||||
// Create a new stats manager with Redis connection
|
||||
config := &stats.Config{
|
||||
RedisAddr: "localhost:6379",
|
||||
RedisPassword: "",
|
||||
RedisDB: 0,
|
||||
Debug: false,
|
||||
QueueSize: 100,
|
||||
DefaultTimeout: 5 * time.Second,
|
||||
ExpirationTimes: map[string]time.Duration{
|
||||
"system": 60 * time.Second, // System info expires after 60 seconds
|
||||
"disk": 300 * time.Second, // Disk info expires after 5 minutes
|
||||
"process": 60 * time.Second, // Process info expires after 1 minute
|
||||
"network": 30 * time.Second, // Network info expires after 30 seconds
|
||||
"hardware": 120 * time.Second, // Hardware stats expire after 2 minutes
|
||||
},
|
||||
}
|
||||
|
||||
manager, err := stats.NewStatsManager(config)
|
||||
if err != nil {
|
||||
fmt.Printf("Error creating stats manager: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
defer manager.Close()
|
||||
|
||||
// Initialize the cache with initial values
|
||||
fmt.Println("Initializing cache with initial values...")
|
||||
_, _ = manager.GetSystemInfo()
|
||||
_, _ = manager.GetDiskStats()
|
||||
_, _ = manager.GetProcessStats(10)
|
||||
_ = manager.GetNetworkSpeedResult()
|
||||
_ = manager.GetHardwareStatsJSON()
|
||||
fmt.Println("Cache initialized. Starting performance test...")
|
||||
fmt.Println()
|
||||
|
||||
// Set up signal handling for graceful shutdown
|
||||
sigChan := make(chan os.Signal, 1)
|
||||
signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
|
||||
|
||||
// Create a ticker for running tests at the specified interval
|
||||
ticker := time.NewTicker(time.Duration(*intervalPtr) * time.Second)
|
||||
defer ticker.Stop()
|
||||
|
||||
// Store the sleep duration between operations
|
||||
sleepDuration := time.Duration(*sleepPtr) * time.Millisecond
|
||||
|
||||
// Get the current process for CPU and memory measurements
|
||||
currentProcess, err := process.NewProcess(int32(os.Getpid()))
|
||||
if err != nil {
|
||||
fmt.Printf("Error getting current process: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
// Store test results
|
||||
var results []TestResult
|
||||
|
||||
// Print header
|
||||
fmt.Printf("%-20s %-20s %-12s %-12s %-12s %-12s %-12s %-12s %-12s %-12s %-12s %-12s %-12s\n",
|
||||
"Start Time", "End Time", "System(ms)", "Disk(ms)", "Process(ms)", "Network(ms)", "Hardware(ms)", "Total(ms)", "UserCPU(%)", "SysCPU(%)", "TotalCPU(%)", "Memory(MB)", "Goroutines")
|
||||
fmt.Println(strings.Repeat("-", 180))
|
||||
|
||||
// Run the test until interrupted
|
||||
for {
|
||||
select {
|
||||
case <-ticker.C:
|
||||
// Run a test and record the results
|
||||
result := runTest(manager, currentProcess, sleepDuration)
|
||||
results = append(results, result)
|
||||
|
||||
// Print the result
|
||||
fmt.Printf("%-20s %-20s %-12.2f %-12.2f %-12.2f %-12.2f %-12.2f %-12.2f %-12.2f %-12.2f %-12.2f %-12.2f %-12d\n",
|
||||
result.StartTime.Format("15:04:05.000000"),
|
||||
result.EndTime.Format("15:04:05.000000"),
|
||||
float64(result.SystemInfoTime.Microseconds())/1000,
|
||||
float64(result.DiskStatsTime.Microseconds())/1000,
|
||||
float64(result.ProcessTime.Microseconds())/1000,
|
||||
float64(result.NetworkTime.Microseconds())/1000,
|
||||
float64(result.HardwareTime.Microseconds())/1000,
|
||||
float64(result.TotalTime.Microseconds())/1000,
|
||||
result.UserCPU,
|
||||
result.SystemCPU,
|
||||
result.TotalCPU,
|
||||
result.MemoryUsageMB,
|
||||
result.NumGoroutines)
|
||||
|
||||
case <-sigChan:
|
||||
// Calculate and print summary statistics
|
||||
fmt.Println("\nTest Summary:")
|
||||
fmt.Println(strings.Repeat("-", 50))
|
||||
|
||||
var totalSystemTime, totalDiskTime, totalProcessTime, totalNetworkTime, totalHardwareTime, totalTime time.Duration
|
||||
var totalUserCPU, totalSystemCPU, totalCombinedCPU, totalOverallCPU float64
|
||||
var totalMemory float32
|
||||
|
||||
for _, r := range results {
|
||||
totalSystemTime += r.SystemInfoTime
|
||||
totalDiskTime += r.DiskStatsTime
|
||||
totalProcessTime += r.ProcessTime
|
||||
totalNetworkTime += r.NetworkTime
|
||||
totalHardwareTime += r.HardwareTime
|
||||
totalTime += r.TotalTime
|
||||
totalUserCPU += r.UserCPU
|
||||
totalSystemCPU += r.SystemCPU
|
||||
totalCombinedCPU += r.TotalCPU
|
||||
totalOverallCPU += r.OverallCPU
|
||||
totalMemory += r.MemoryUsageMB
|
||||
}
|
||||
|
||||
count := float64(len(results))
|
||||
if count > 0 {
|
||||
fmt.Printf("Average System Info Time: %.2f ms\n", float64(totalSystemTime.Microseconds())/(count*1000))
|
||||
fmt.Printf("Average Disk Stats Time: %.2f ms\n", float64(totalDiskTime.Microseconds())/(count*1000))
|
||||
fmt.Printf("Average Process Time: %.2f ms\n", float64(totalProcessTime.Microseconds())/(count*1000))
|
||||
fmt.Printf("Average Network Time: %.2f ms\n", float64(totalNetworkTime.Microseconds())/(count*1000))
|
||||
fmt.Printf("Average Hardware Time: %.2f ms\n", float64(totalHardwareTime.Microseconds())/(count*1000))
|
||||
fmt.Printf("Average Total Time: %.2f ms\n", float64(totalTime.Microseconds())/(count*1000))
|
||||
fmt.Printf("Average User CPU: %.2f%%\n", totalUserCPU/count)
|
||||
fmt.Printf("Average System CPU: %.2f%%\n", totalSystemCPU/count)
|
||||
fmt.Printf("Average Process CPU: %.2f%%\n", totalCombinedCPU/count)
|
||||
fmt.Printf("Average Overall CPU: %.2f%%\n", totalOverallCPU/count)
|
||||
fmt.Printf("Average Memory Usage: %.2f MB\n", float64(totalMemory)/count)
|
||||
}
|
||||
|
||||
fmt.Println("\nTest completed. Exiting...")
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// runTest runs a single test iteration and returns the results
|
||||
func runTest(manager *stats.StatsManager, proc *process.Process, sleepBetweenOps time.Duration) TestResult {
|
||||
// Get initial CPU times for the process
|
||||
initialTimes, _ := proc.Times()
|
||||
|
||||
// Get initial overall CPU usage
|
||||
_, _ = cpu.Percent(0, false) // Discard initial reading, we'll only use the final reading
|
||||
|
||||
result := TestResult{
|
||||
StartTime: time.Now(),
|
||||
}
|
||||
|
||||
// Measure total time
|
||||
totalStart := time.Now()
|
||||
|
||||
// Measure system info time
|
||||
start := time.Now()
|
||||
_, _ = manager.GetSystemInfo()
|
||||
result.SystemInfoTime = time.Since(start)
|
||||
|
||||
// Sleep between operations if configured
|
||||
if sleepBetweenOps > 0 {
|
||||
time.Sleep(sleepBetweenOps)
|
||||
}
|
||||
|
||||
// Measure disk stats time
|
||||
start = time.Now()
|
||||
_, _ = manager.GetDiskStats()
|
||||
result.DiskStatsTime = time.Since(start)
|
||||
|
||||
// Sleep between operations if configured
|
||||
if sleepBetweenOps > 0 {
|
||||
time.Sleep(sleepBetweenOps)
|
||||
}
|
||||
|
||||
// Measure process stats time
|
||||
start = time.Now()
|
||||
_, _ = manager.GetProcessStats(10)
|
||||
result.ProcessTime = time.Since(start)
|
||||
|
||||
// Sleep between operations if configured
|
||||
if sleepBetweenOps > 0 {
|
||||
time.Sleep(sleepBetweenOps)
|
||||
}
|
||||
|
||||
// Measure network speed time
|
||||
start = time.Now()
|
||||
_ = manager.GetNetworkSpeedResult()
|
||||
result.NetworkTime = time.Since(start)
|
||||
|
||||
// Sleep between operations if configured
|
||||
if sleepBetweenOps > 0 {
|
||||
time.Sleep(sleepBetweenOps)
|
||||
}
|
||||
|
||||
// Measure hardware stats time
|
||||
start = time.Now()
|
||||
_ = manager.GetHardwareStatsJSON()
|
||||
result.HardwareTime = time.Since(start)
|
||||
|
||||
// Record total time
|
||||
result.TotalTime = time.Since(totalStart)
|
||||
result.EndTime = time.Now()
|
||||
|
||||
// Get final CPU times for the process
|
||||
finalTimes, _ := proc.Times()
|
||||
|
||||
// Calculate CPU usage for this specific operation
|
||||
if initialTimes != nil && finalTimes != nil {
|
||||
result.UserCPU = (finalTimes.User - initialTimes.User) * 100
|
||||
result.SystemCPU = (finalTimes.System - initialTimes.System) * 100
|
||||
result.TotalCPU = result.UserCPU + result.SystemCPU
|
||||
}
|
||||
|
||||
// Get overall CPU usage
|
||||
finalOverallCPU, _ := cpu.Percent(0, false)
|
||||
if len(finalOverallCPU) > 0 {
|
||||
result.OverallCPU = finalOverallCPU[0]
|
||||
}
|
||||
|
||||
// Measure memory usage
|
||||
memInfo, _ := proc.MemoryInfo()
|
||||
if memInfo != nil {
|
||||
result.MemoryUsageMB = float32(memInfo.RSS) / (1024 * 1024)
|
||||
}
|
||||
|
||||
// Record number of goroutines
|
||||
result.NumGoroutines = runtime.NumGoroutine()
|
||||
|
||||
return result
|
||||
}
|
67
pkg/system/stats/cmd/redis_test/main.go
Normal file
67
pkg/system/stats/cmd/redis_test/main.go
Normal file
@@ -0,0 +1,67 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/freeflowuniverse/heroagent/pkg/system/stats"
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
func main() {
|
||||
fmt.Println("Redis Connection Test")
|
||||
fmt.Println("====================")
|
||||
|
||||
// Create a configuration for Redis
|
||||
config := &stats.Config{
|
||||
RedisAddr: "localhost:6379",
|
||||
RedisPassword: "",
|
||||
RedisDB: 0,
|
||||
}
|
||||
|
||||
// Create Redis client
|
||||
client := redis.NewClient(&redis.Options{
|
||||
Addr: config.RedisAddr,
|
||||
Password: config.RedisPassword,
|
||||
DB: config.RedisDB,
|
||||
})
|
||||
|
||||
// Test connection with timeout
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
// Try to ping Redis
|
||||
pong, err := client.Ping(ctx).Result()
|
||||
if err != nil {
|
||||
fmt.Printf("Error connecting to Redis: %v\n", err)
|
||||
fmt.Println("\nPlease ensure Redis is running with:")
|
||||
fmt.Println(" - docker run --name redis -p 6379:6379 -d redis")
|
||||
fmt.Println(" - or install Redis locally and start the service")
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
fmt.Printf("Successfully connected to Redis at %s\n", config.RedisAddr)
|
||||
fmt.Printf("Response: %s\n", pong)
|
||||
|
||||
// Test basic operations
|
||||
fmt.Println("\nTesting basic Redis operations...")
|
||||
|
||||
// Set a key
|
||||
err = client.Set(ctx, "test:key", "Hello from HeroLauncher!", 1*time.Minute).Err()
|
||||
if err != nil {
|
||||
fmt.Printf("Error setting key: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
// Get the key
|
||||
val, err := client.Get(ctx, "test:key").Result()
|
||||
if err != nil {
|
||||
fmt.Printf("Error getting key: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
fmt.Printf("Retrieved value: %s\n", val)
|
||||
fmt.Println("Redis connection test successful!")
|
||||
}
|
195
pkg/system/stats/cmd/stats_test/main.go
Normal file
195
pkg/system/stats/cmd/stats_test/main.go
Normal file
@@ -0,0 +1,195 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/freeflowuniverse/heroagent/pkg/system/stats"
|
||||
)
|
||||
|
||||
func main() {
|
||||
fmt.Println("System Stats Test Program")
|
||||
fmt.Println("========================")
|
||||
|
||||
// Create a new stats manager with Redis connection
|
||||
config := &stats.Config{
|
||||
RedisAddr: "localhost:6379",
|
||||
RedisPassword: "",
|
||||
RedisDB: 0,
|
||||
Debug: false,
|
||||
QueueSize: 100,
|
||||
DefaultTimeout: 5 * time.Second,
|
||||
ExpirationTimes: map[string]time.Duration{
|
||||
"system": 30 * time.Second, // System info expires after 30 seconds
|
||||
"disk": 60 * time.Second, // Disk info expires after 1 minute
|
||||
"process": 15 * time.Second, // Process info expires after 15 seconds
|
||||
"network": 20 * time.Second, // Network info expires after 20 seconds
|
||||
"hardware": 60 * time.Second, // Hardware stats expire after 1 minute
|
||||
},
|
||||
}
|
||||
|
||||
manager, err := stats.NewStatsManager(config)
|
||||
if err != nil {
|
||||
fmt.Printf("Error creating stats manager: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
defer manager.Close()
|
||||
|
||||
// DISK INFORMATION
|
||||
fmt.Println("\n1. DISK INFORMATION")
|
||||
fmt.Println("------------------")
|
||||
|
||||
// Get all disk stats using the manager
|
||||
diskStats, err := manager.GetDiskStats()
|
||||
if err != nil {
|
||||
fmt.Printf("Error getting disk stats: %v\n", err)
|
||||
} else {
|
||||
fmt.Printf("Found %d disks:\n", len(diskStats.Disks))
|
||||
for _, disk := range diskStats.Disks {
|
||||
fmt.Printf(" %s: %.1f GB total, %.1f GB free (%.1f%% used)\n",
|
||||
disk.Path, disk.Total, disk.Free, disk.UsedPercent)
|
||||
}
|
||||
}
|
||||
|
||||
// Get root disk info using the manager
|
||||
rootDisk, err := manager.GetRootDiskInfo()
|
||||
if err != nil {
|
||||
fmt.Printf("Error getting root disk info: %v\n", err)
|
||||
} else {
|
||||
fmt.Printf("\nRoot Disk: %.1f GB total, %.1f GB free (%.1f%% used)\n",
|
||||
rootDisk.Total, rootDisk.Free, rootDisk.UsedPercent)
|
||||
}
|
||||
|
||||
// Get formatted disk info
|
||||
fmt.Printf("Formatted Disk Info: %s\n", manager.GetFormattedDiskInfo())
|
||||
|
||||
// SYSTEM INFORMATION
|
||||
fmt.Println("\n2. SYSTEM INFORMATION")
|
||||
fmt.Println("--------------------")
|
||||
|
||||
// Get system info using the manager
|
||||
sysInfo, err := manager.GetSystemInfo()
|
||||
if err != nil {
|
||||
fmt.Printf("Error getting system info: %v\n", err)
|
||||
} else {
|
||||
fmt.Println("CPU Information:")
|
||||
fmt.Printf(" Cores: %d\n", sysInfo.CPU.Cores)
|
||||
fmt.Printf(" Model: %s\n", sysInfo.CPU.ModelName)
|
||||
fmt.Printf(" Usage: %.1f%%\n", sysInfo.CPU.UsagePercent)
|
||||
|
||||
fmt.Println("\nMemory Information:")
|
||||
fmt.Printf(" Total: %.1f GB\n", sysInfo.Memory.Total)
|
||||
fmt.Printf(" Used: %.1f GB (%.1f%%)\n", sysInfo.Memory.Used, sysInfo.Memory.UsedPercent)
|
||||
fmt.Printf(" Free: %.1f GB\n", sysInfo.Memory.Free)
|
||||
|
||||
fmt.Println("\nNetwork Information:")
|
||||
fmt.Printf(" Upload Speed: %s\n", sysInfo.Network.UploadSpeed)
|
||||
fmt.Printf(" Download Speed: %s\n", sysInfo.Network.DownloadSpeed)
|
||||
}
|
||||
|
||||
// Get network speed using the manager
|
||||
fmt.Println("\nNetwork Speed Test:")
|
||||
netSpeed := manager.GetNetworkSpeedResult()
|
||||
fmt.Printf(" Upload: %s\n", netSpeed.UploadSpeed)
|
||||
fmt.Printf(" Download: %s\n", netSpeed.DownloadSpeed)
|
||||
|
||||
// PROCESS INFORMATION
|
||||
fmt.Println("\n3. PROCESS INFORMATION")
|
||||
fmt.Println("---------------------")
|
||||
|
||||
// Get process stats using the manager
|
||||
processStats, err := manager.GetProcessStats(5) // Get top 5 processes
|
||||
if err != nil {
|
||||
fmt.Printf("Error getting process stats: %v\n", err)
|
||||
} else {
|
||||
fmt.Printf("Total processes: %d (showing top %d)\n",
|
||||
processStats.Total, len(processStats.Processes))
|
||||
|
||||
fmt.Println("\nTop Processes by CPU Usage:")
|
||||
for i, proc := range processStats.Processes {
|
||||
fmt.Printf(" %d. PID %d: %s (CPU: %.1f%%, Memory: %.1f MB)\n",
|
||||
i+1, proc.PID, proc.Name, proc.CPUPercent, proc.MemoryMB)
|
||||
}
|
||||
}
|
||||
|
||||
// Get top processes using the manager
|
||||
fmt.Println("\nTop 3 Processes:")
|
||||
topProcs, err := manager.GetTopProcesses(3)
|
||||
if err != nil {
|
||||
fmt.Printf("Error getting top processes: %v\n", err)
|
||||
} else {
|
||||
for i, proc := range topProcs {
|
||||
fmt.Printf(" %d. %s (PID %d)\n", i+1, proc.Name, proc.PID)
|
||||
}
|
||||
}
|
||||
|
||||
// COMBINED STATS
|
||||
fmt.Println("\n4. COMBINED STATS FUNCTIONS")
|
||||
fmt.Println("--------------------------")
|
||||
|
||||
// Hardware stats using the manager
|
||||
fmt.Println("\nHardware Stats:")
|
||||
hardwareStats := manager.GetHardwareStats()
|
||||
for key, value := range hardwareStats {
|
||||
fmt.Printf(" %s: %v\n", key, value)
|
||||
}
|
||||
|
||||
// Hardware stats JSON using the manager
|
||||
fmt.Println("\nHardware Stats (JSON):")
|
||||
hardwareJSON := manager.GetHardwareStatsJSON()
|
||||
prettyJSON, _ := json.MarshalIndent(hardwareJSON, "", " ")
|
||||
fmt.Println(string(prettyJSON))
|
||||
|
||||
// Process stats JSON using the manager
|
||||
fmt.Println("\nProcess Stats (JSON):")
|
||||
processJSON := manager.GetProcessStatsJSON(3) // Top 3 processes
|
||||
prettyJSON, _ = json.MarshalIndent(processJSON, "", " ")
|
||||
fmt.Println(string(prettyJSON))
|
||||
|
||||
// Wait and measure network speed again
|
||||
fmt.Println("\nWaiting 2 seconds for another network speed measurement...")
|
||||
time.Sleep(2 * time.Second)
|
||||
|
||||
// Get updated network speed using the manager
|
||||
updatedNetSpeed := manager.GetNetworkSpeedResult()
|
||||
fmt.Println("\nUpdated Network Speed:")
|
||||
fmt.Printf(" Upload: %s\n", updatedNetSpeed.UploadSpeed)
|
||||
fmt.Printf(" Download: %s\n", updatedNetSpeed.DownloadSpeed)
|
||||
|
||||
// CACHE MANAGEMENT
|
||||
fmt.Println("\n5. CACHE MANAGEMENT")
|
||||
fmt.Println("------------------")
|
||||
|
||||
// Force update of system stats
|
||||
fmt.Println("\nForcing update of system stats...")
|
||||
err = manager.ForceUpdate("system")
|
||||
if err != nil {
|
||||
fmt.Printf("Error forcing update: %v\n", err)
|
||||
} else {
|
||||
fmt.Println("System stats updated successfully")
|
||||
}
|
||||
|
||||
// Get updated system info
|
||||
updatedSysInfo, err := manager.GetSystemInfo()
|
||||
if err != nil {
|
||||
fmt.Printf("Error getting updated system info: %v\n", err)
|
||||
} else {
|
||||
fmt.Println("\nUpdated CPU Usage: " + fmt.Sprintf("%.1f%%", updatedSysInfo.CPU.UsagePercent))
|
||||
}
|
||||
|
||||
// Clear cache for disk stats
|
||||
fmt.Println("\nClearing cache for disk stats...")
|
||||
err = manager.ClearCache("disk")
|
||||
if err != nil {
|
||||
fmt.Printf("Error clearing cache: %v\n", err)
|
||||
} else {
|
||||
fmt.Println("Disk stats cache cleared successfully")
|
||||
}
|
||||
|
||||
// Toggle debug mode
|
||||
fmt.Println("\nToggling debug mode (direct fetching without cache)...")
|
||||
manager.Debug = !manager.Debug
|
||||
fmt.Printf("Debug mode is now: %v\n", manager.Debug)
|
||||
}
|
Reference in New Issue
Block a user