unos/watchdog-go/watchdog/watchdog_go.go

99 lines
1.9 KiB
Go
Raw Normal View History

2024-03-11 12:39:36 +00:00
package watchdog
import (
"fmt"
"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.")
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("internal"),
}
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),
}
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", collect.Name, collect.Value)
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, " ", "-"), "")
}