unos/watchdog-go/main.go

95 lines
2.0 KiB
Go

package main
import (
"context"
"fmt"
"git.usbharu.dev/usbharu/unos/watchdog-go/git.usbharu.dev/usbharu/unos/watchdog"
"github.com/shirou/gopsutil/v3/mem"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/protobuf/types/known/timestamppb"
"gopkg.in/ini.v1"
"log"
"regexp"
"strings"
"time"
)
type Config struct {
Url string
ClientName string
ClientDomain string
}
var regex = regexp.MustCompile(`[^a-zA-Z0-9-_]`)
func main() {
fmt.Println("start gRPC Client.")
load, err := ini.Load("config.ini")
if err != nil {
log.Fatal(err)
return
}
config := Config{
Url: load.Section("Parent").Key("url").String(),
ClientName: load.Section("Watch").Key("name").MustString("Watch Dog Go"),
ClientDomain: load.Section("Watch").Key("domain").MustString("watchdog.internal"),
}
dial, err := grpc.Dial(config.Url, grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
log.Fatal(err)
return
}
metrics := make(chan watchdog.Metric)
client := watchdog.NewPushMetricsServiceClient(dial)
go func() {
for {
metricArray := getMetrics(config)
for _, metric := range metricArray {
metrics <- metric
}
time.Sleep(1 * time.Minute)
}
}()
for metric := range metrics {
_, err := client.Push(context.Background(), &metric)
if err != nil {
log.Println(err)
continue
}
}
}
func getMetrics(config Config) []watchdog.Metric {
v, _ := mem.VirtualMemory()
return []watchdog.Metric{usedMemory(*v, config)}
}
func usedMemory(stat mem.VirtualMemoryStat, config Config) watchdog.Metric {
name := config.ClientName + " Used Memory"
usedMemory := fmt.Sprintf("%g", stat.UsedPercent)
log.Printf("Mem: %s%%\n", usedMemory)
return watchdog.Metric{
Name: name,
ObjectId: toId(name),
Domain: config.ClientDomain,
Status: watchdog.Status_OK,
Value: usedMemory,
Timestamp: timestamppb.Now(),
}
}
func toId(value string) string {
return regex.ReplaceAllString(strings.ReplaceAll(value, " ", "-"), "")
}