Implement 'inteval' config parameter -> number of seconds between checks

This commit is contained in:
Soulou
2015-08-23 17:33:23 +02:00
parent 270dbd361b
commit 76b897eb05
3 changed files with 73 additions and 16 deletions

View File

@@ -4,13 +4,14 @@ import (
"encoding/json" "encoding/json"
"flag" "flag"
"fmt" "fmt"
"github.com/castawaylabs/cachet-monitor/system"
"io" "io"
"io/ioutil" "io/ioutil"
"log" "log"
"net/http" "net/http"
"net/url" "net/url"
"os" "os"
"github.com/castawaylabs/cachet-monitor/system"
) )
// Static config // Static config
@@ -69,6 +70,13 @@ func init() {
os.Exit(1) os.Exit(1)
} }
for _, mon := range Config.Monitors {
if mon.Interval <= 0 {
mon.Interval = 1
}
mon.stopC = make(chan struct{})
}
if len(systemName) > 0 { if len(systemName) > 0 {
Config.SystemName = systemName Config.SystemName = systemName
} }

View File

@@ -19,10 +19,14 @@ type Monitor struct {
ComponentID *int `json:"component_id"` ComponentID *int `json:"component_id"`
ExpectedStatusCode int `json:"expected_status_code"` ExpectedStatusCode int `json:"expected_status_code"`
StrictTLS *bool `json:"strict_tls"` StrictTLS *bool `json:"strict_tls"`
Interval time.Duration `json:"interval"`
History []bool `json:"-"` History []bool `json:"-"`
LastFailReason *string `json:"-"` LastFailReason *string `json:"-"`
Incident *Incident `json:"-"` Incident *Incident `json:"-"`
// Closed when mon.Stop() is called
stopC chan struct{} `json:"-"`
} }
// Run loop // Run loop
@@ -42,6 +46,26 @@ func (monitor *Monitor) Run() {
} }
} }
func (monitor *Monitor) Stop() {
if monitor.Stopped() {
return
}
close(monitor.stopC)
}
func (monitor *Monitor) StopC() <-chan struct{} {
return monitor.stopC
}
func (monitor *Monitor) Stopped() bool {
select {
case <-monitor.stopC:
return true
default:
return false
}
}
func (monitor *Monitor) doRequest() bool { func (monitor *Monitor) doRequest() bool {
client := &http.Client{ client := &http.Client{
Timeout: timeout, Timeout: timeout,

33
main.go
View File

@@ -1,8 +1,12 @@
package main package main
import ( import (
"github.com/castawaylabs/cachet-monitor/cachet" "os"
"os/signal"
"sync"
"time" "time"
"github.com/castawaylabs/cachet-monitor/cachet"
) )
func main() { func main() {
@@ -20,10 +24,31 @@ func main() {
log.Println() log.Println()
ticker := time.NewTicker(time.Second) wg := &sync.WaitGroup{}
for range ticker.C {
for _, mon := range config.Monitors { for _, mon := range config.Monitors {
go mon.Run() wg.Add(1)
go func(mon *cachet.Monitor) {
ticker := time.NewTicker(mon.Interval * time.Second)
for {
select {
case <-ticker.C:
mon.Run()
case <-mon.StopC():
wg.Done()
return
} }
} }
}(mon)
}
signals := make(chan os.Signal, 1)
signal.Notify(signals, os.Interrupt, os.Kill)
<-signals
log.Println("Waiting monitors to end current operation")
for _, mon := range config.Monitors {
mon.Stop()
}
wg.Wait()
} }