forked from grafana/carbon-relay-ng
/
web.go
303 lines (267 loc) · 9.64 KB
/
web.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
package web
import (
"encoding/json"
"fmt"
"net/http"
"os"
"strconv"
"time"
assetfs "github.com/elazarl/go-bindata-assetfs"
"github.com/gorilla/mux"
"github.com/graphite-ng/carbon-relay-ng/aggregator"
"github.com/graphite-ng/carbon-relay-ng/badmetrics"
"github.com/graphite-ng/carbon-relay-ng/cfg"
"github.com/graphite-ng/carbon-relay-ng/destination"
"github.com/graphite-ng/carbon-relay-ng/rewriter"
"github.com/graphite-ng/carbon-relay-ng/route"
tbl "github.com/graphite-ng/carbon-relay-ng/table"
logging "github.com/op/go-logging"
)
var table *tbl.Table
var config cfg.Config
var badMetrics *badmetrics.BadMetrics
var log = logging.MustGetLogger("ui-web") // for tests. overridden by main
func SetLogger(l *logging.Logger) {
log = l
}
// error response contains everything we need to use http.Error
type handlerError struct {
Error error
Message string
Code int
}
// a custom type that we can use for handling errors and formatting responses
type handler func(w http.ResponseWriter, r *http.Request) (interface{}, *handlerError)
// attach the standard ServeHTTP method to our handler so the http library can call it
func (fn handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// here we could do some prep work before calling the handler if we wanted to
// call the actual handler
response, err := fn(w, r)
// check for errors
if err != nil {
//log.Printf("ERROR: %v\n", err.Error)
http.Error(w, fmt.Sprintf(`{"error":"%s"}`, err.Message+": "+err.Error.Error()), err.Code)
return
}
if response == nil {
//log.Printf("ERROR: response from method is nil\n")
http.Error(w, "Internal server error. Check the logs.", http.StatusInternalServerError)
return
}
// turn the response into JSON
bytes, e := json.Marshal(response)
if e != nil {
http.Error(w, fmt.Sprintf("Error marshalling JSON:'%s'", e), http.StatusInternalServerError)
return
}
// send the response and log
w.Header().Set("Content-Type", "application/json")
w.Write(bytes)
}
func showConfig(w http.ResponseWriter, r *http.Request) (interface{}, *handlerError) {
return config, nil
}
func listTable(w http.ResponseWriter, r *http.Request) (interface{}, *handlerError) {
t := table.Snapshot()
return t, nil
}
func badMetricsHandler(w http.ResponseWriter, r *http.Request) (interface{}, *handlerError) {
timespec := mux.Vars(r)["timespec"]
duration, err := time.ParseDuration(timespec)
if err != nil {
return nil, &handlerError{err, "Could not parse timespec", http.StatusBadRequest}
}
records := badMetrics.Get(duration)
return records, nil
}
func removeRewriter(w http.ResponseWriter, r *http.Request) (interface{}, *handlerError) {
index := mux.Vars(r)["index"]
idx, _ := strconv.Atoi(index)
err := table.DelRewriter(idx)
if err != nil {
return nil, &handlerError{nil, "Could not find entry " + index, http.StatusNotFound}
}
return make(map[string]string), nil
}
func removeBlacklist(w http.ResponseWriter, r *http.Request) (interface{}, *handlerError) {
index := mux.Vars(r)["index"]
idx, _ := strconv.Atoi(index)
err := table.DelBlacklist(idx)
if err != nil {
return nil, &handlerError{nil, "Could not find entry " + index, http.StatusNotFound}
}
return make(map[string]string), nil
}
func removeAggregator(w http.ResponseWriter, r *http.Request) (interface{}, *handlerError) {
index := mux.Vars(r)["index"]
idx, _ := strconv.Atoi(index)
err := table.DelAggregator(idx)
if err != nil {
return nil, &handlerError{nil, err.Error(), http.StatusNotFound}
}
return make(map[string]string), nil
}
func removeDestination(w http.ResponseWriter, r *http.Request) (interface{}, *handlerError) {
key := mux.Vars(r)["key"]
index := mux.Vars(r)["index"]
idx, _ := strconv.Atoi(index)
err := table.DelDestination(key, idx)
if err != nil {
return nil, &handlerError{nil, "Could not find entry " + key + "/" + index, http.StatusNotFound}
}
return make(map[string]string), nil
}
func listRoutes(w http.ResponseWriter, r *http.Request) (interface{}, *handlerError) {
t := table.Snapshot()
return t.Routes, nil
}
func getRoute(w http.ResponseWriter, r *http.Request) (interface{}, *handlerError) {
key := mux.Vars(r)["key"]
route := table.GetRoute(key)
if route == nil {
return nil, &handlerError{nil, "Could not find route " + key, http.StatusNotFound}
}
return route, nil
}
func removeRoute(w http.ResponseWriter, r *http.Request) (interface{}, *handlerError) {
key := mux.Vars(r)["key"]
err := table.DelRoute(key)
if err != nil {
return nil, &handlerError{nil, "Could not find entry " + key, http.StatusNotFound}
}
return make(map[string]string), nil
}
func parseRouteRequest(r *http.Request) (route.Route, *handlerError) {
var request struct {
Address string
Key string
Pickle bool
Spool bool
Type string
Substring string
Prefix string
Regex string
}
if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
return nil, &handlerError{err, "Couldn't parse json", http.StatusBadRequest}
}
// use hard coded defaults for flush and reconn as specified in
// readDestinations
periodFlush := time.Duration(1000) * time.Millisecond
periodReconn := time.Duration(10000) * time.Millisecond
dest, err := destination.New("", "", "", request.Address, table.SpoolDir, request.Spool, request.Pickle, periodFlush, periodReconn)
if err != nil {
return nil, &handlerError{err, "unable to create destination", http.StatusBadRequest}
}
var ro route.Route
var e error
switch request.Type {
case "sendAllMatch":
ro, e = route.NewSendAllMatch(request.Key, request.Prefix, request.Substring, request.Regex, []*destination.Destination{dest})
case "sendFirstMatch":
ro, e = route.NewSendFirstMatch(request.Key, request.Prefix, request.Substring, request.Regex, []*destination.Destination{dest})
default:
return nil, &handlerError{nil, "unknown route type: " + request.Type, http.StatusBadRequest}
}
if e != nil {
return nil, &handlerError{e, "could not create route", http.StatusBadRequest}
}
return ro, nil
}
func parseAggregateRequest(r *http.Request) (*aggregator.Aggregator, *handlerError) {
var request struct {
Fun string
OutFmt string
Interval uint
Wait uint
Regex string
}
if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
return nil, &handlerError{err, "Couldn't parse json", http.StatusBadRequest}
}
aggregate, err := aggregator.New(request.Fun, request.Regex, request.OutFmt, request.Interval, request.Wait, table.In)
if err != nil {
return nil, &handlerError{err, "Couldn't create aggregator", http.StatusBadRequest}
}
return aggregate, nil
}
func parseRewriterRequest(r *http.Request) (rewriter.RW, *handlerError) {
var request struct {
Old string
New string
Max int
}
if err := json.NewDecoder(r.Body).Decode(&request); err != nil {
return rewriter.RW{}, &handlerError{err, "Couldn't parse json", http.StatusBadRequest}
}
rw, err := rewriter.New(request.Old, request.New, request.Max)
if err != nil {
return rewriter.RW{}, &handlerError{err, "Couldn't create rewriter", http.StatusBadRequest}
}
return rw, nil
}
/* needs updating, but using what api?
func updateRoute(w http.ResponseWriter, r *http.Request) (interface{}, *handlerError) {
payload, err := parseRouteRequest(r)
if err != nil {
return nil, err
}
e := routes.Update(payload.Key, &payload.Addr, &payload.Patt)
if e != nil {
return nil, &handlerError{e, "Could not update route (" + e.Error() + ")", http.StatusBadRequest}
}
return routes.Map[payload.Key], nil
}
*/
func addAggregate(w http.ResponseWriter, r *http.Request) (interface{}, *handlerError) {
aggregate, err := parseAggregateRequest(r)
if err != nil {
return nil, err
}
table.AddAggregator(aggregate)
return map[string]string{"Message": "aggregate added"}, nil
}
func addRewrite(w http.ResponseWriter, r *http.Request) (interface{}, *handlerError) {
rw, err := parseRewriterRequest(r)
if err != nil {
return nil, err
}
table.AddRewriter(rw)
return map[string]string{"Message": "rewriter added"}, nil
}
func addRoute(w http.ResponseWriter, r *http.Request) (interface{}, *handlerError) {
route, err := parseRouteRequest(r)
if err != nil {
return nil, err
}
table.AddRoute(route)
return map[string]string{"Message": "route added"}, nil
}
func Start(addr string, c cfg.Config, t *tbl.Table, bad *badmetrics.BadMetrics) {
table = t
config = c
badMetrics = bad
router := mux.NewRouter()
router.Handle("/badMetrics/{timespec}.json", handler(badMetricsHandler)).Methods("GET")
router.Handle("/config", handler(showConfig)).Methods("GET")
router.Handle("/table", handler(listTable)).Methods("GET")
router.Handle("/blacklists/{index}", handler(removeBlacklist)).Methods("DELETE")
router.Handle("/rewriters/{index}", handler(removeRewriter)).Methods("DELETE")
router.Handle("/rewriters", handler(addRewrite)).Methods("POST")
router.Handle("/aggregators/{index}", handler(removeAggregator)).Methods("DELETE")
router.Handle("/aggregators", handler(addAggregate)).Methods("POST")
router.Handle("/routes", handler(listRoutes)).Methods("GET")
router.Handle("/routes", handler(addRoute)).Methods("POST")
router.Handle("/routes/{key}", handler(getRoute)).Methods("GET")
//router.Handle("/routes/{key}", handler(updateRoute)).Methods("POST")
router.Handle("/routes/{key}", handler(removeRoute)).Methods("DELETE")
router.Handle("/routes/{key}/destinations/{index}", handler(removeDestination)).Methods("DELETE")
router.PathPrefix("/").Handler(http.FileServer(&assetfs.AssetFS{Asset: Asset, AssetDir: AssetDir, AssetInfo: AssetInfo, Prefix: "admin_http_assets/"}))
http.Handle("/", router)
log.Notice("admin HTTP listener starting on %v", addr)
err := http.ListenAndServe(addr, nil)
if err != nil {
fmt.Println("Error listening:", err.Error())
os.Exit(1)
}
}