unos/watchdog-go/watchdog/watchdog_go.go

127 lines
2.6 KiB
Go

package watchdog
import (
"fmt"
"github.com/shirou/gopsutil/v3/disk"
"github.com/shirou/gopsutil/v3/host"
"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()
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),
}
collectors = append(collectors, diskCollector(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 message: %s", collect.Name, collect.Value, collect.Message)
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),
}
}
func diskCollector(config Config) []MetricsCollector {
partitions, err := disk.Partitions(true)
if err != nil {
log.Println(err)
return []MetricsCollector{}
}
var collectors []MetricsCollector
for _, partition := range partitions {
collectors = append(collectors, NewUsedDisk(config, partition))
collectors = append(collectors, NewTotalDisk(config, partition))
}
return collectors
}