-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathweb_handlers.go
327 lines (271 loc) · 8.56 KB
/
web_handlers.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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
package main
import (
"encoding/json"
"fmt"
"mime"
"net/http"
"os"
"path"
"sort"
"strings"
"time"
"github.com/gorilla/mux"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
)
type output struct {
APIKey string `json:"api_key,omitempty"`
Metrics []outputMetric `json:"metrics"`
}
type outputMetricConfig struct {
HideMAD bool `json:"hide_mad"`
HideValue bool `json:"hide_value"`
}
type outputMetric struct {
ID string `json:"id"`
Config outputMetricConfig `json:"config"`
Description string `json:"description"`
DetailURL string `json:"detail_url"`
HistoryBar []historyBarSegment `json:"history_bar,omitempty"`
LastOK time.Time `json:"last_ok"`
LastUpdate time.Time `json:"last_update"`
Median float64 `json:"median"`
MADMultiplier float64 `json:"mad_multiplier"`
Status string `json:"status"`
Title string `json:"title"`
Value float64 `json:"value"`
ValueHistory map[int64]float64 `json:"value_history,omitempty"`
}
type outputMetricFromMetricOpts struct {
Metric *dashboardMetric
AddHistoryBar bool
AddValueHistory bool
}
func outputMetricFromMetric(opts outputMetricFromMetricOpts) outputMetric {
out := outputMetric{
ID: opts.Metric.MetricID,
Description: opts.Metric.Description,
DetailURL: opts.Metric.DetailURL,
LastOK: opts.Metric.Meta.LastOK,
LastUpdate: opts.Metric.Meta.LastUpdate,
Median: opts.Metric.Median(),
MADMultiplier: opts.Metric.MadMultiplier(),
Status: opts.Metric.PreferredStatus(),
Title: opts.Metric.Title,
Value: opts.Metric.Value,
Config: outputMetricConfig{
HideMAD: opts.Metric.HideMAD,
HideValue: opts.Metric.HideValue,
},
}
if opts.AddHistoryBar {
out.HistoryBar = opts.Metric.GetHistoryBar()
}
if opts.AddValueHistory {
out.ValueHistory = opts.Metric.HistoricalValueMap()
}
return out
}
func handleStaticFile(w http.ResponseWriter, r *http.Request, filename string) error {
if _, err := os.Stat(path.Join(cfg.FrontendDir, filename)); err == nil {
http.ServeFile(w, r, path.Join(cfg.FrontendDir, filename))
return nil
}
// File was not found in filesystem, serve from packed assets
body, err := Asset(path.Join("frontend", filename))
if err != nil {
return errors.Wrapf(err, "File %q was neither found in FrontendDir nor in assets", filename)
}
log.WithField("filename", filename).Debug("Static file loaded from assets")
w.Header().Set("Content-Type", mime.TypeByExtension(filename[strings.LastIndexByte(filename, '.'):]))
_, err = w.Write(body)
return errors.Wrap(err, "Unable to write body")
}
func handleAppJS(w http.ResponseWriter, r *http.Request) { handleStaticFile(w, r, "app.js") }
func handleCreateRandomDashboard(w http.ResponseWriter, r *http.Request) {
var urlProposal string
for {
urlProposal = generateAPIKey()[0:20]
if exists, err := store.Exists(urlProposal); err == nil && !exists {
break
}
}
http.Redirect(w, r, fmt.Sprintf("/%s", urlProposal), http.StatusTemporaryRedirect)
}
func handleDisplayDashboard(w http.ResponseWriter, r *http.Request) {
handleStaticFile(w, r, "index.html")
}
func handleDisplayDashboardJSON(w http.ResponseWriter, r *http.Request) {
var vars = mux.Vars(r)
dash, err := loadDashboard(vars["dashid"], store)
switch err {
case nil:
// All fine
case errDashboardNotFound:
dash = &dashboard{APIKey: generateAPIKey(), Metrics: []*dashboardMetric{}}
default:
log.WithError(err).
WithField("dashboard_id", vars["dashid"]).
Error("Unable to load dashboard")
http.Error(w, "Could not load dashboard", http.StatusInternalServerError)
return
}
var (
addHistoryBar = r.URL.Query().Get("history_bar") == "true"
addValueHistory = r.URL.Query().Get("value_history") == "true"
response = output{}
)
// Filter out expired metrics
for _, m := range dash.Metrics {
if m.Meta.LastUpdate.After(time.Now().Add(time.Duration(m.Expires*-1) * time.Second)) {
response.Metrics = append(response.Metrics, outputMetricFromMetric(outputMetricFromMetricOpts{
AddHistoryBar: addHistoryBar,
AddValueHistory: addValueHistory,
Metric: m,
}))
}
}
sort.Slice(response.Metrics, func(j, i int) bool { return response.Metrics[i].LastUpdate.Before(response.Metrics[j].LastUpdate) })
if len(response.Metrics) == 0 {
response.APIKey = dash.APIKey
}
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Cache-Control", "no-cache")
if err = json.NewEncoder(w).Encode(response); err != nil {
log.WithError(err).Error("Unable to encode API JSON")
http.Error(w, "Unable to encode JSON", http.StatusInternalServerError)
}
}
func handleDeleteDashboard(w http.ResponseWriter, r *http.Request) {
var (
token = strings.TrimPrefix(r.Header.Get("Authorization"), "Token ")
vars = mux.Vars(r)
)
dash, err := loadDashboard(vars["dashid"], store)
switch err {
case nil:
// All fine
case errDashboardNotFound:
http.Error(w, "Dasboard not found", http.StatusNotFound)
return
default:
log.WithError(err).
WithField("dashboard_id", vars["dashid"]).
Error("Unable to load dashboard")
http.Error(w, "Could not load dashboard", http.StatusInternalServerError)
return
}
if dash.APIKey != token {
http.Error(w, "APIKey did not match.", http.StatusUnauthorized)
return
}
if err = store.Delete(vars["dashid"]); err != nil {
log.WithError(err).WithField("dashboard_id", vars["dashid"]).Error("Unable to delete dashboard")
http.Error(w, "Failed to delete dashboard", http.StatusInternalServerError)
return
}
http.Error(w, "OK", http.StatusOK)
}
func handleDeleteMetric(w http.ResponseWriter, r *http.Request) {
var (
token = strings.TrimPrefix(r.Header.Get("Authorization"), "Token ")
vars = mux.Vars(r)
)
dash, err := loadDashboard(vars["dashid"], store)
switch err {
case nil:
// All fine
case errDashboardNotFound:
http.Error(w, "Dashboard not found", http.StatusNotFound)
return
default:
log.WithError(err).
WithField("dashboard_id", vars["dashid"]).
Error("Unable to load dashboard")
http.Error(w, "Could not load dashboard", http.StatusInternalServerError)
return
}
if dash.APIKey != token {
http.Error(w, "APIKey did not match.", http.StatusUnauthorized)
return
}
tmp := []*dashboardMetric{}
for _, m := range dash.Metrics {
if m.MetricID != vars["metricid"] {
tmp = append(tmp, m)
}
}
dash.Metrics = tmp
if err := dash.Save(); err != nil {
log.WithError(err).Error("Unable to save dashboard")
http.Error(w, "Was not able to save the dashboard", http.StatusInternalServerError)
return
}
http.Error(w, "OK", http.StatusOK)
}
func handlePutMetric(w http.ResponseWriter, r *http.Request) {
var (
token = strings.TrimPrefix(r.Header.Get("Authorization"), "Token ")
vars = mux.Vars(r)
)
metricUpdate := newDashboardMetric()
if err := json.NewDecoder(r.Body).Decode(metricUpdate); err != nil {
http.Error(w, "Unable to unmarshal json body", http.StatusBadRequest)
return
}
dash, err := loadDashboard(vars["dashid"], store)
switch err {
case nil:
// All fine
case errDashboardNotFound:
// Dashboard may be created with first metrics put
if len(token) < 10 {
http.Error(w, "APIKey is too insecure", http.StatusBadRequest)
return
}
dash = &dashboard{
APIKey: token,
Metrics: []*dashboardMetric{},
DashboardID: vars["dashid"],
storage: store,
}
default:
log.WithError(err).
WithField("dashboard_id", vars["dashid"]).
Error("Unable to load dashboard")
http.Error(w, "Could not load dashboard", http.StatusInternalServerError)
return
}
if dash.APIKey != token {
http.Error(w, "APIKey did not match.", http.StatusUnauthorized)
return
}
valid, reason := metricUpdate.IsValid()
if !valid {
http.Error(w, fmt.Sprintf("Invalid data: %s", reason), http.StatusBadRequest)
return
}
updated := false
for _, m := range dash.Metrics {
if m.MetricID == vars["metricid"] {
m.Update(metricUpdate)
updated = true
break
}
}
if !updated {
tmp := newDashboardMetric()
tmp.MetricID = vars["metricid"]
tmp.Update(metricUpdate)
dash.Metrics = append(dash.Metrics, tmp)
}
if err := dash.Save(); err != nil {
log.WithError(err).Error("Unable to save dashboard")
http.Error(w, "Was not able to save the dashboard", http.StatusInternalServerError)
return
}
http.Error(w, "OK", http.StatusOK)
}
func handleRedirectWelcome(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "/welcome", http.StatusTemporaryRedirect)
}