statping/checker.go

64 lines
1.5 KiB
Go
Raw Normal View History

2018-06-10 01:31:13 +00:00
package main
import (
"fmt"
"io/ioutil"
"net/http"
"regexp"
"time"
)
func CheckServices() {
2018-06-10 03:44:47 +00:00
services = SelectAllServices()
2018-06-10 01:31:13 +00:00
for _, v := range services {
obj := v
go obj.CheckQueue()
}
}
func (s *Service) CheckQueue() {
s.Check()
2018-06-10 04:16:04 +00:00
fmt.Printf(" Service: %v | Online: %v | Latency: %v\n", s.Name, s.Online, s.Latency)
time.Sleep(time.Duration(s.Interval) * time.Second)
2018-06-10 01:31:13 +00:00
s.CheckQueue()
}
func (s *Service) Check() {
t1 := time.Now()
2018-06-10 05:05:08 +00:00
client := http.Client{
Timeout: 30 * time.Second,
}
response, err := client.Get(s.Domain)
2018-06-10 01:31:13 +00:00
t2 := time.Now()
s.Latency = t2.Sub(t1).Seconds()
if err != nil {
2018-06-10 05:05:08 +00:00
s.Failure(fmt.Sprintf("HTTP Error %v", err))
2018-06-10 01:31:13 +00:00
return
}
2018-06-10 05:05:08 +00:00
defer response.Body.Close()
2018-06-10 01:31:13 +00:00
if s.Expected != "" {
contents, _ := ioutil.ReadAll(response.Body)
match, _ := regexp.MatchString(s.Expected, string(contents))
if !match {
2018-06-10 05:05:08 +00:00
s.Failure(fmt.Sprintf("HTTP Response Body did not match '%v'", s.Expected))
2018-06-10 01:31:13 +00:00
return
}
}
if s.ExpectedStatus != response.StatusCode {
2018-06-10 05:05:08 +00:00
s.Failure(fmt.Sprintf("HTTP Status Code %v did not match %v", response.StatusCode, s.ExpectedStatus))
2018-06-10 01:31:13 +00:00
return
}
2018-06-10 03:44:47 +00:00
s.Online = true
2018-06-10 01:31:13 +00:00
s.Record(response)
}
func (s *Service) Record(response *http.Response) {
db.QueryRow("INSERT INTO hits(service,latency,created_at) VALUES($1,$2,NOW()) returning id;", s.Id, s.Latency).Scan()
2018-06-14 01:19:00 +00:00
OnHit(s)
2018-06-10 01:31:13 +00:00
}
2018-06-10 05:05:08 +00:00
func (s *Service) Failure(issue string) {
2018-06-10 01:31:13 +00:00
db.QueryRow("INSERT INTO failures(issue,service,created_at) VALUES($1,$2,NOW()) returning id;", issue, s.Id).Scan()
2018-06-14 01:19:00 +00:00
OnFailure(s)
2018-06-10 01:31:13 +00:00
}