unos/watchdog-go/watchdog/watchdog_go.go

109 lines
2.1 KiB
Go
Raw Normal View History

2024-03-11 12:39:36 +00:00
package watchdog
import (
"fmt"
"github.com/shirou/gopsutil/v3/host"
2024-03-11 12:39:36 +00:00
"golang.org/x/net/context"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"gopkg.in/ini.v1"
"log"
"regexp"
"strings"
"time"
)
var regex = regexp.MustCompile(`[^a-zA-Z0-9-_]`)
func Run() {
fmt.Println("start gRPC Client.")
config := buildConfig()
2024-03-11 12:39:36 +00:00
dial, err := grpc.Dial(config.Url, grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
log.Fatal(err)
return
}
client := NewPushMetricsServiceClient(dial)
collectors := []MetricsCollector{
NewUsedMemory(config),
NewUsedSwap(config),
NewTotalMemory(config),
NewTotalSwap(config),
NewUsedCpu(config),
2024-03-11 12:39:36 +00:00
}
collectorMap := map[time.Duration][]MetricsCollector{}
for _, collector := range collectors {
timer := collector.Timer()
metricsCollectors, ok := collectorMap[timer]
if ok {
collectorMap[timer] = append(metricsCollectors, collector)
} else {
collectorMap[timer] = []MetricsCollector{collector}
}
}
metrics := make(chan Metric)
for duration, metricsCollectors := range collectorMap {
duration := duration
metricsCollectors := metricsCollectors
go func() {
for {
for _, collector := range metricsCollectors {
collect, err := collector.Collect()
if err != nil {
continue
}
log.Printf("%s: %s message: %s", collect.Name, collect.Value, collect.Message)
2024-03-11 12:39:36 +00:00
metrics <- *collect
}
time.Sleep(duration)
}
}()
}
for metric := range metrics {
_, err := client.Push(context.Background(), &metric)
if err != nil {
log.Println(err)
continue
}
}
}
func toId(value string) string {
return regex.ReplaceAllString(strings.ReplaceAll(value, " ", "-"), "")
}
func buildConfig() Config {
load, err := ini.Load("config.ini")
if err != nil {
log.Fatal(err)
}
hostinfo, err := host.Info()
if err != nil {
log.Fatal(err)
}
return Config{
Url: load.Section("Parent").Key("url").String(),
ClientName: load.Section("Watch").Key("name").MustString(hostinfo.Hostname),
ClientDomain: load.Section("Watch").Key("domain").MustString(hostinfo.Hostname),
}
}