spacepanel_aggregator/poll.go

73 lines
1.1 KiB
Go
Raw Normal View History

2020-02-04 20:25:10 +00:00
package main
2020-01-30 23:24:19 +00:00
import (
2020-02-04 18:32:54 +00:00
"crypto/tls"
"errors"
2020-01-31 00:59:39 +00:00
"io/ioutil"
"net/http"
2020-01-30 23:24:19 +00:00
"time"
2020-02-04 18:32:54 +00:00
2020-02-04 20:25:10 +00:00
"github.com/sirupsen/logrus"
2020-02-04 18:32:54 +00:00
"github.com/valyala/fastjson"
2020-01-30 23:24:19 +00:00
)
2020-02-04 20:25:10 +00:00
const (
SleepTime = 60 * time.Minute
)
2020-01-31 00:59:39 +00:00
2020-02-04 18:32:54 +00:00
var (
insecureTransport = &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
client = &http.Client{
Transport: insecureTransport,
}
)
2020-02-04 20:25:10 +00:00
func StartPollWorker(space *Space) {
for {
state, err := requestSpaceState(space.URL)
if err != nil {
logrus.Errorf("URL: %s, Err: %v", space.URL, err)
}
space.State = state
time.Sleep(SleepTime)
}
}
func requestSpaceState(url string) (State, error) {
2020-02-04 18:32:54 +00:00
req, err := http.NewRequest("GET", url, nil)
if err != nil {
2020-02-04 20:25:10 +00:00
return Unknown, err
2020-02-04 18:32:54 +00:00
}
resp, err := client.Do(req)
if err != nil {
2020-02-04 20:25:10 +00:00
return Unknown, err
2020-02-04 18:32:54 +00:00
}
defer resp.Body.Close()
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
2020-02-04 20:25:10 +00:00
return Unknown, err
2020-02-04 18:32:54 +00:00
}
value, err := fastjson.ParseBytes(data)
if err != nil {
2020-02-04 20:25:10 +00:00
return Unknown, err
2020-02-04 18:32:54 +00:00
}
if !value.Exists("state", "open") {
2020-02-04 20:25:10 +00:00
return Unknown, errors.New("no space state existing")
2020-01-31 00:59:39 +00:00
}
2020-02-04 18:32:54 +00:00
state := value.GetBool("state", "open")
if state {
2020-02-04 20:25:10 +00:00
return Open, nil
2020-02-04 18:32:54 +00:00
}
2020-02-04 20:25:10 +00:00
return Close, nil
2020-01-31 14:20:40 +00:00
}