-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathserver.go
224 lines (205 loc) · 4.85 KB
/
server.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
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
package patrol
import (
"bytes"
_ "embed"
"encoding/base64"
"fmt"
"log"
"net/http"
"net/url"
"strings"
"text/template"
"time"
"github.com/andanhm/go-prettytime"
"github.com/wcharczuk/go-chart"
"github.com/wcharczuk/go-chart/drawing"
"github.com/karimsa/patrol/internal/history"
"github.com/karimsa/patrol/internal/logger"
)
type chartResult struct {
SVG string
Min, Max, Avg float64
Error string
}
//go:embed dist/index.html
var indexHTML string
//go:embed dist/styles.css
var stylesCSS string
var (
gridMajorStyle = chart.Style{
Show: true,
StrokeWidth: 1.5,
StrokeColor: drawing.Color{
A: 90,
},
}
gridMinorStyle = chart.Style{
Show: true,
StrokeWidth: 1.0,
StrokeColor: drawing.Color{
A: 50,
},
}
seriesStyle = chart.Style{
Show: true,
FontColor: drawing.ColorBlack,
StrokeWidth: 3,
}
metricChartDefaults = chart.Chart{
XAxis: chart.XAxis{
Style: chart.StyleShow(),
GridMajorStyle: gridMajorStyle,
GridMinorStyle: gridMinorStyle,
},
YAxis: chart.YAxis{
Style: chart.StyleShow(),
GridMajorStyle: gridMajorStyle,
GridMinorStyle: gridMinorStyle,
},
}
pageView = template.Must(
template.New("index").Funcs(template.FuncMap{
"mul": func(a, b int) int {
return a * b
},
"sub": func(a, b int) int {
return a - b
},
"plus": func(a, b int) int {
return a + b
},
"nums": func(a, b int) []int {
if a > b {
r := make([]int, a-b+1)
for i := 0; a >= b; i++ {
r[i] = a
a--
}
return r
}
r := make([]int, b-a+1)
for i := 0; a <= b; i++ {
r[i] = a
a++
}
return r
},
"since": prettytime.Format,
"fmtNum": func(n float64) string {
parts := strings.Split(fmt.Sprintf("%.2f", n), ".")
for i := len(parts[0]) - 3; i > 0; i -= 3 {
parts[0] = parts[0][0:i] + ", " + parts[0][i:]
}
return parts[0] + "." + parts[1]
},
"chart": func(items []history.Item) chartResult {
if len(items) < 1 {
return chartResult{Error: "Data pending"}
}
res := chartResult{
Min: items[0].Metric,
Max: items[0].Metric,
Avg: 0,
}
xValues := make([]time.Time, len(items))
yValues := make([]float64, len(items))
for i, item := range items {
xValues[i] = item.CreatedAt
yValues[i] = item.Metric
if res.Min > item.Metric {
res.Min = item.Metric
}
if res.Max < item.Metric {
res.Max = item.Metric
}
res.Avg += item.Metric
}
res.Avg /= float64(len(items))
c := metricChartDefaults
c.Series = []chart.Series{
chart.TimeSeries{
XValues: xValues,
YValues: yValues,
Style: seriesStyle,
},
}
// go-chart cannot draw constant functions
if res.Min == res.Max {
c.YAxis.Range = &chart.ContinuousRange{
Min: res.Min - 1,
Max: res.Max + 1,
}
}
if len(items) == 1 {
c.XAxis.Range = &chart.ContinuousRange{
Min: float64(items[0].CreatedAt.UnixNano() - int64(24*time.Hour)),
Max: float64(items[0].CreatedAt.UnixNano() + int64(24*time.Hour)),
}
} else if len(items) == 0 {
c.XAxis.Range = &chart.ContinuousRange{
Min: 0,
Max: 1,
}
}
buffer := bytes.Buffer{}
if err := c.Render(chart.SVG, &buffer); err != nil {
res.Error = fmt.Sprintf("Failed to render graph: %s", err)
} else {
res.SVG = base64.StdEncoding.EncodeToString(buffer.Bytes())
}
return res
},
}).Parse(indexHTML),
)
)
func init() {
template.Must(pageView.New("styles.css").Parse(stylesCSS))
}
func (p *Patrol) ServeHTTP(res http.ResponseWriter, req *http.Request) {
defer func() {
if err := recover(); err != nil {
log.Printf("Error while serving http: %s", err)
}
}()
query, err := url.ParseQuery(req.URL.RawQuery)
if err != nil {
log.Printf("warn: Query parsing failed: %s", err)
}
data := struct {
Name string
Groups map[string]map[string][]history.Item
NumServicesDown int
NumServices int
LatestCreatedAt time.Time
GroupFilter string
StatusFilter string
Debug bool
}{
Name: p.name,
Groups: p.History.GetData(),
NumServicesDown: 0,
NumServices: 0,
LatestCreatedAt: time.Unix(0, 0),
GroupFilter: query.Get("group"),
StatusFilter: query.Get("status"),
Debug: p.logLevel == logger.LevelDebug,
}
for _, group := range data.Groups {
for _, items := range group {
if len(items) > 0 {
if items[0].Status == "unhealthy" {
data.NumServicesDown++
}
if data.LatestCreatedAt.Before(items[0].CreatedAt) {
data.LatestCreatedAt = items[0].CreatedAt
}
data.NumServices++
}
}
}
if err := pageView.Execute(res, data); err != nil {
p.logger.Warnf("Failed to execute template: %s", err)
res.WriteHeader(500)
res.Write([]byte(err.Error()))
}
}