From 169cf49c13f9c8145d293d3f5a2855f1a262a129 Mon Sep 17 00:00:00 2001 From: rkfg Date: Mon, 29 Mar 2021 14:20:50 +0300 Subject: [PATCH] Add downtime detection&reporting --- config.go | 3 +++ config_sample.json | 1 + query.go | 20 ++++++++++++++++++++ 3 files changed, 24 insertions(+) diff --git a/config.go b/config.go index d98a682..2581d34 100644 --- a/config.go +++ b/config.go @@ -30,6 +30,8 @@ type ns2server struct { currentMap string avgSkill int restartChan chan bool + failures int + downSince *time.Time } func (s *ns2server) playersString() string { @@ -72,6 +74,7 @@ var config struct { LevelDBPath string `json:"ldb_database_path"` BoltDBPath string `json:"bdb_database_path"` QueryInterval time.Duration `json:"query_interval"` + FailureLimit int `json:"failure_limit"` Servers []*ns2server Seeding seeding } diff --git a/config_sample.json b/config_sample.json index 1a38909..6139498 100644 --- a/config_sample.json +++ b/config_sample.json @@ -4,6 +4,7 @@ "steam_key": "get your key at https://steamcommunity.com/dev/apikey", "bdb_database_path": "/path/to/botdb/", "query_interval": 60, + "failure_limit": 10, "servers": [ { "name": "Server 1", diff --git a/query.go b/query.go index c64f692..8825a5b 100644 --- a/query.go +++ b/query.go @@ -11,6 +11,10 @@ import ( "github.com/rumblefrog/go-a2s" ) +const ( + timeFormat = "2 Jan 2006 15:04:05 -0700" +) + type queryError struct { description string err error @@ -52,6 +56,9 @@ func serverStatus(srv *ns2server) *discordgo.MessageSend { Footer: &discordgo.MessageEmbedFooter{Text: fmt.Sprintf("Skill: %d", srv.avgSkill)}, }, } + if srv.failures > config.FailureLimit && srv.downSince != nil { + msg.Embed.Title = fmt.Sprintf("%s [%s] currently DOWN since %s", srv.Name, srv.currentMap, srv.downSince.Format(timeFormat)) + } playersCount := len(srv.players) if playersCount < config.Seeding.AlmostFull { msg.Embed.Color = 0x009900 @@ -155,6 +162,19 @@ func query(srv *ns2server) { err = queryServer(client, srv) if err != nil { log.Printf("Error: %s", err) + srv.failures++ + if srv.failures > config.FailureLimit && srv.downSince == nil { + now := time.Now() + srv.downSince = &now + sendChan <- message{MessageSend: &discordgo.MessageSend{Content: fmt.Sprintf("Server %s is down!", srv.Name)}} + } + } else { + if srv.failures > config.FailureLimit && srv.downSince != nil { + sendChan <- message{MessageSend: &discordgo.MessageSend{Content: fmt.Sprintf("Server %s is back up! Was down since: %s", + srv.Name, srv.downSince.Format(timeFormat))}} + srv.downSince = nil + } + srv.failures = 0 } if err, ok := err.(queryError); ok { if err, ok := err.err.(*net.OpError); ok && err.Op == "write" {