chore: Refactor code to use model package for memory, processes, disk, and CPU metrics

This commit is contained in:
Simon Larsen
2024-05-13 21:12:45 +01:00
parent 1f53ecb093
commit db0aee6c0f
7 changed files with 41 additions and 36 deletions

View File

@@ -1,8 +1,10 @@
package utils
package main
import (
"encoding/json"
"log/slog"
"oneuptime-infrastructure-agent/model"
"oneuptime-infrastructure-agent/utils"
"os"
"time"
@@ -78,29 +80,29 @@ func (ag *Agent) Close() {
}
func collectMetricsJob(secretKey string, oneuptimeURL string) {
memMetrics := getMemoryMetrics()
memMetrics := utils.GetMemoryMetrics()
if memMetrics == nil {
slog.Warn("Failed to get memory metrics")
}
cpuMetrics := getCpuMetrics()
cpuMetrics := utils.GetCpuMetrics()
if cpuMetrics == nil {
slog.Warn("Failed to get CPU metrics")
}
diskMetrics := listDiskMetrics()
diskMetrics := utils.ListDiskMetrics()
if diskMetrics == nil {
slog.Warn("Failed to get disk metrics")
}
servProcesses := getServerProcesses()
servProcesses := utils.GetServerProcesses()
if servProcesses == nil {
slog.Warn("Failed to get server processes")
}
metricsReport := &ServerMonitorReport{
metricsReport := &model.ServerMonitorReport{
SecretKey: secretKey,
BasicInfrastructureMetrics: &BasicInfrastructureMetrics{
BasicInfrastructureMetrics: &model.BasicInfrastructureMetrics{
MemoryMetrics: memMetrics,
CpuMetrics: cpuMetrics,
DiskMetrics: diskMetrics,
@@ -111,7 +113,7 @@ func collectMetricsJob(secretKey string, oneuptimeURL string) {
}
reqData := struct {
ServerMonitorResponse *ServerMonitorReport `json:"serverMonitorResponse"`
ServerMonitorResponse *model.ServerMonitorReport `json:"serverMonitorResponse"`
}{
ServerMonitorResponse: metricsReport,
}

View File

@@ -11,20 +11,20 @@ import (
"github.com/gookit/config/v2"
)
type configFile struct {
type ConfigFile struct {
SecretKey string `json:"secret_key"`
OneUptimeURL string `json:"oneuptime_url"`
}
func newConfigFile() *configFile {
return &configFile{
func newConfigFile() *ConfigFile {
return &ConfigFile{
SecretKey: "",
OneUptimeURL: "",
}
}
func (c *configFile) loadConfig() error {
cfg := &configFile{}
func (c *ConfigFile) loadConfig() error {
cfg := &ConfigFile{}
err := config.LoadFiles(c.configPath())
if err != nil {
return err
@@ -38,7 +38,7 @@ func (c *configFile) loadConfig() error {
return nil
}
func (c *configFile) save(secretKey string, url string) error {
func (c *ConfigFile) save(secretKey string, url string) error {
err := c.loadConfig()
if err != nil && !os.IsNotExist(err) {
return err
@@ -66,7 +66,7 @@ func (c *configFile) save(secretKey string, url string) error {
}
// removeConfigFile deletes the configuration file.
func (c *configFile) removeConfigFile() error {
func (c *ConfigFile) removeConfigFile() error {
// Check if the file exists before attempting to remove it.
if _, err := os.Stat(c.configPath()); os.IsNotExist(err) {
@@ -85,7 +85,7 @@ func (c *configFile) removeConfigFile() error {
}
// ensureDir checks if a directory exists and makes it if it does not.
func (c *configFile) ensureDir(dirName string) error {
func (c *ConfigFile) ensureDir(dirName string) error {
// Check if the directory exists
info, err := os.Stat(dirName)
if os.IsNotExist(err) {
@@ -104,7 +104,7 @@ func (c *configFile) ensureDir(dirName string) error {
// configPath returns the full path to the configuration file,
// ensuring the directory exists or creating it if it does not.
func (c *configFile) configPath() string {
func (c *ConfigFile) configPath() string {
var basePath string
if runtime.GOOS == "windows" {
basePath = os.Getenv("PROGRAMDATA")

View File

@@ -4,7 +4,6 @@ import (
"flag"
"fmt"
"log/slog"
agentgo "oneuptime_infrastructure_agent"
"os"
"github.com/gookit/config/v2"
@@ -13,8 +12,8 @@ import (
type program struct {
exit chan struct{}
agent *agentgo.Agent
config *configFile
agent *Agent
config *ConfigFile
}
func (p *program) Start(s service.Service) error {
@@ -30,11 +29,11 @@ func (p *program) Start(s service.Service) error {
}
func (p *program) run() {
p.agent = agentgo.NewAgent(p.config.SecretKey, p.config.OneUptimeURL)
p.agent = NewAgent(p.config.SecretKey, p.config.OneUptimeURL)
p.agent.Start()
if service.Interactive() {
slog.Info("Running in terminal.")
agentgo.NewShutdownHook().Close(func() {
NewShutdownHook().Close(func() {
slog.Info("Service Exiting...")
p.agent.Close()
})

View File

@@ -3,12 +3,13 @@ package utils
import (
"fmt"
"log/slog"
"oneuptime-infrastructure-agent/model"
"time"
"github.com/shirou/gopsutil/v3/cpu"
)
func getCpuMetrics() *CPUMetrics {
func GetCpuMetrics() *model.CPUMetrics {
//avg, err := load.Avg()
//if err != nil {
// slog.Error(err)
@@ -43,7 +44,7 @@ func getCpuMetrics() *CPUMetrics {
}
// Calculate the difference in total and idle times
totalDelta := totalCPUTime(endTimes[0]) - totalCPUTime(startTimes[0])
totalDelta := TotalCPUTime(endTimes[0]) - TotalCPUTime(startTimes[0])
idleDelta := endTimes[0].Idle - startTimes[0].Idle
// Calculate the CPU usage percentage
@@ -53,12 +54,12 @@ func getCpuMetrics() *CPUMetrics {
}
cpuUsagePercent := (1 - idleDelta/totalDelta) * 100
return &CPUMetrics{
return &model.CPUMetrics{
PercentUsed: cpuUsagePercent,
}
}
func totalCPUTime(times cpu.TimesStat) float64 {
func TotalCPUTime(times cpu.TimesStat) float64 {
return times.User + times.System + times.Idle + times.Nice +
times.Iowait + times.Irq + times.Softirq + times.Steal +
times.Guest + times.GuestNice

View File

@@ -2,12 +2,13 @@ package utils
import (
"log/slog"
"oneuptime-infrastructure-agent/model"
"github.com/shirou/gopsutil/v3/disk"
)
// getDiskMetrics retrieves disk metrics for a given path
func getDiskMetrics(path string) *BasicDiskMetrics {
func GetDiskMetrics(path string) *model.BasicDiskMetrics {
usageStat, err := disk.Usage(path)
if err != nil {
slog.Error(err.Error())
@@ -19,7 +20,7 @@ func getDiskMetrics(path string) *BasicDiskMetrics {
percentFree = float64(usageStat.Free) / float64(usageStat.Total) * 100
}
metrics := &BasicDiskMetrics{
metrics := &model.BasicDiskMetrics{
Total: usageStat.Total,
Free: usageStat.Free,
Used: usageStat.Used,
@@ -32,16 +33,16 @@ func getDiskMetrics(path string) *BasicDiskMetrics {
}
// listDiskMetrics lists disk metrics for all partitions
func listDiskMetrics() []*BasicDiskMetrics {
func ListDiskMetrics() []*model.BasicDiskMetrics {
partitions, err := disk.Partitions(false) // set to true if you want all filesystems
if err != nil {
slog.Error(err.Error())
return nil
}
var metricsList []*BasicDiskMetrics
var metricsList []*model.BasicDiskMetrics
for _, partition := range partitions {
metrics := getDiskMetrics(partition.Mountpoint)
metrics := GetDiskMetrics(partition.Mountpoint)
if metrics == nil {
continue // Skip this partition on error
}

View File

@@ -2,17 +2,18 @@ package utils
import (
"log/slog"
"oneuptime-infrastructure-agent/model"
"github.com/shirou/gopsutil/v3/mem"
)
func getMemoryMetrics() *MemoryMetrics {
func GetMemoryMetrics() *model.MemoryMetrics {
memoryInfo, err := mem.VirtualMemory()
if err != nil {
slog.Error("Error while fetching memory metrics: ", err)
return nil
}
return &MemoryMetrics{
return &model.MemoryMetrics{
Total: memoryInfo.Total,
Free: memoryInfo.Free,
Used: memoryInfo.Used,

View File

@@ -2,13 +2,14 @@ package utils
import (
"log/slog"
"oneuptime-infrastructure-agent/model"
"github.com/shirou/gopsutil/v3/process"
)
// getServerProcesses retrieves the list of server processes
func getServerProcesses() []*ServerProcess {
var serverProcesses []*ServerProcess
func GetServerProcesses() []*model.ServerProcess {
var serverProcesses []*model.ServerProcess
// Fetch all processes
processList, err := process.Processes()
@@ -28,7 +29,7 @@ func getServerProcesses() []*ServerProcess {
continue
}
serverProcesses = append(serverProcesses, &ServerProcess{
serverProcesses = append(serverProcesses, &model.ServerProcess{
Pid: p.Pid,
Name: name,
Command: cmdline,