unos/watchdog-go/watchdog/memory_collector.go

142 lines
2.7 KiB
Go
Raw Permalink Normal View History

2024-03-11 12:39:36 +00:00
package watchdog
import (
"fmt"
"github.com/shirou/gopsutil/v3/mem"
"google.golang.org/protobuf/types/known/timestamppb"
"log"
"time"
)
type UsedMemory struct {
config Config
}
func NewUsedMemory(config Config) MetricsCollector {
return &UsedMemory{
config,
}
}
func (m UsedMemory) Collect() (*Metric, error) {
memory, err := mem.VirtualMemory()
if err != nil {
return nil, err
}
name := m.config.ClientName + " Used Memory"
usedMemory := fmt.Sprintf("%g", memory.UsedPercent)
return &Metric{
Name: name,
ObjectId: toId(name),
Domain: m.config.ClientDomain,
Status: Status_OK,
Value: usedMemory,
Timestamp: timestamppb.Now(),
Message: "",
}, nil
}
func (m UsedMemory) Timer() time.Duration {
return 1 * time.Minute
}
type UsedSwap struct {
config Config
}
func NewUsedSwap(config Config) MetricsCollector {
return &UsedSwap{
config: config,
}
}
func (m UsedSwap) Collect() (*Metric, error) {
memory, err := mem.SwapMemory()
if err != nil {
return nil, err
}
name := m.config.ClientName + " Used Swap"
usedMemory := fmt.Sprintf("%g", memory.UsedPercent)
return &Metric{
Name: name,
ObjectId: toId(name),
Domain: m.config.ClientDomain,
Status: Status_OK,
Value: usedMemory,
Timestamp: timestamppb.Now(),
Message: "",
}, nil
}
func (m UsedSwap) Timer() time.Duration {
return 1 * time.Minute
}
type TotalMemory struct {
config Config
}
func NewTotalMemory(config Config) MetricsCollector {
return &TotalMemory{config: config}
}
func (t TotalMemory) Collect() (*Metric, error) {
memory, err := mem.VirtualMemory()
if err != nil {
log.Println(err)
return nil, nil
}
name := t.config.ClientName + " Total Mem"
totalMemory := fmt.Sprintf("%d", memory.Total)
log.Printf("Total Mem: %s%%\n", totalMemory)
return &Metric{
Name: name,
ObjectId: toId(name),
Domain: t.config.ClientDomain,
Status: Status_OK,
Value: totalMemory,
Timestamp: timestamppb.Now(),
Message: "",
}, nil
}
func (t TotalMemory) Timer() time.Duration {
return 24 * time.Hour
}
type TotalSwap struct {
config Config
}
func NewTotalSwap(config Config) MetricsCollector {
return &TotalSwap{config: config}
}
func (t TotalSwap) Collect() (*Metric, error) {
memory, err := mem.SwapMemory()
if err != nil {
log.Println(err)
return nil, nil
}
name := t.config.ClientName + " Total Swap"
totalMemory := fmt.Sprintf("%d", memory.Total)
return &Metric{
Name: name,
ObjectId: toId(name),
Domain: t.config.ClientDomain,
Status: Status_OK,
Value: totalMemory,
Timestamp: timestamppb.Now(),
Message: "",
}, nil
}
func (t TotalSwap) Timer() time.Duration {
return 24 * time.Hour
}