-
Notifications
You must be signed in to change notification settings - Fork 0
/
keeper.go
146 lines (130 loc) · 3.89 KB
/
keeper.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
//
// Copyright 2019 Insolar Technologies GmbH
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
package main
import (
"context"
"encoding/json"
"net/http"
"net/url"
"sync"
"sync/atomic"
"time"
"github.com/insolar/insolar/instrumentation/inslogger"
)
type Keeper struct {
config KeeperConfig
configLock sync.RWMutex
isAvailable uint32
}
func NewKeeper(cfg KeeperConfig) *Keeper {
return &Keeper{
config: cfg,
isAvailable: 0,
}
}
func (k *Keeper) SetConfig(cfg KeeperConfig) {
k.configLock.Lock()
defer k.configLock.Unlock()
k.config = cfg
}
func (k *Keeper) Config() KeeperConfig {
k.configLock.RLock()
defer k.configLock.RUnlock()
return k.config
}
func (k *Keeper) Run(ctx context.Context) {
go k.startChecker(ctx)
go k.startServer(ctx)
}
func (k *Keeper) startChecker(ctx context.Context) {
ticker := time.NewTicker(k.Config().PollPeriod)
for range ticker.C {
k.checkMetrics(ctx)
}
}
func (k *Keeper) checkMetrics(ctx context.Context) {
queries := k.Config().Queries
var isOK uint32 = 1
if !k.Config().FakeTrue {
for _, q := range queries {
if !k.checkMetric(ctx, q) {
isOK = 0
}
}
}
atomic.StoreUint32(&k.isAvailable, isOK)
}
func (k *Keeper) checkMetric(ctx context.Context, query string) bool {
logger := inslogger.FromContext(ctx)
logger.Debugf("Checking metric: %s", query)
metricURL := k.Config().QueryURL + url.QueryEscape(query)
resp, err := http.Get(metricURL)
if err != nil {
logger.Errorf("Error while getting <<%s>> query: %s", query, err.Error())
return false
}
defer func() {
if resp != nil && resp.Body != nil {
err = resp.Body.Close()
if err != nil {
logger.Warnf("Failed to close response body: %s", err.Error())
}
}
}()
promRsp := PromRsp{}
err = json.NewDecoder(resp.Body).Decode(&promRsp)
if err != nil {
logger.Errorf("Metric <<%s>>. Failed to parse Prometheus response: %s", query, err.Error())
return false
}
if promRsp.Status != "success" {
logger.Errorf("Metric <<%s>>. Bad response from Prometheus: %s: %s", query, promRsp.ErrorType, promRsp.Error)
return false
}
for _, res := range promRsp.Data.Result {
ts, ok := res.Value[0].(float64)
if !ok {
logger.Errorf("Metric <<%s>> failed on instance %s. Cannot parse timestamp %v", query, res.Metric.Instance, res.Value[0])
return false
}
metricLag := time.Since(time.Unix(int64(ts), 0))
logger.Debugf("Metric <<%s>> on instance %s lag: %s", query, res.Metric.Instance, metricLag)
if metricLag > k.Config().MaxMetricLag {
logger.Errorf("Metric <<%s>> failed on instance %s. Last data point was too long ago: %s", query, res.Metric.Instance, res.Value[0], metricLag)
return false
}
if res.Value[1] != "1" {
logger.Infof("Metric <<%s>> failed on instance %s. Value is %s", query, res.Metric.Instance, res.Value[1])
return false
}
}
return true
}
func (k *Keeper) startServer(ctx context.Context) {
logger := inslogger.FromContext(ctx)
http.HandleFunc("/check", func(writer http.ResponseWriter, request *http.Request) {
response := KeeperRsp{
Available: atomic.LoadUint32(&k.isAvailable) > 0,
}
writer.Header().Set("Content-Type", "application/json")
err := json.NewEncoder(writer).Encode(response)
if err != nil {
logger.Errorf("Failed to encode response: %s", err.Error())
}
})
logger.Infof("Starting http server on %s", k.Config().ListenAddress)
logger.Fatal(http.ListenAndServe(k.Config().ListenAddress, nil))
}