/
handler.go
452 lines (384 loc) · 11.7 KB
/
handler.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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
// Copyright 2022 Matt Layher
// 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 zedhook
import (
"context"
"database/sql"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"net"
"net/http"
"net/url"
"strconv"
"time"
"github.com/gorilla/mux"
"github.com/mdlayher/metricslite"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"inet.af/peercred"
)
var _ http.Handler = (*Handler)(nil)
// A Handler is an http.Handler for zedhookd logic.
type Handler struct {
// OnPayload is an optional hook which is fired when a valid zedhook payload
// push request is sent to a Server. If not nil, the callback will be fired
// with the contents of the Payload.
OnPayload func(p Payload)
index *eventIndex
s *Storage
mux http.Handler
ll *log.Logger
mm metrics
}
// NewHandler constructs a Handler and prepares it for use with the Server. If
// any of its dependencies are nil, defaults will be used.
func NewHandler(ctx context.Context, s *Storage, ll *log.Logger, reg *prometheus.Registry) (*Handler, error) {
if s == nil {
s = MemoryStorage()
}
if ll == nil {
ll = log.New(io.Discard, "", 0)
}
if reg == nil {
reg = prometheus.NewPedanticRegistry()
}
// Index the known latest events for each zpool.
latest, err := s.LatestEvents(ctx)
if err != nil {
return nil, fmt.Errorf("failed to fetch latest events: %v", err)
}
index := newEventIndex(latest)
h := &Handler{
index: index,
s: s,
ll: ll,
mm: newMetrics(metricslite.NewPrometheus(reg), index),
}
r := mux.NewRouter()
r.HandleFunc("/push", h.push)
r.HandleFunc("/events", h.listEvents)
r.HandleFunc("/events/", h.listEvents)
r.HandleFunc("/events/{id}", h.getEvent)
r.Handle("/metrics", promhttp.HandlerFor(reg, promhttp.HandlerOpts{
ErrorLog: ll,
}))
h.mux = r
return h, nil
}
// ServeHTTP implements http.Handler.
func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Server", "zedhook")
if r.URL.Path == "/" {
// TODO(mdlayher): banner.
_, _ = io.WriteString(w, "zedhookd\n")
return
}
h.mux.ServeHTTP(w, r)
}
// push implements the HTTP POST push logic for the all-zedhook ZEDLET.
func (h *Handler) push(w http.ResponseWriter, r *http.Request) {
pr, ok := h.pushRequest(w, r)
if !ok {
// Middleware already wrote HTTP response.
h.mm.PushErrorsTotal(1.0)
return
}
if pr.Creds != nil {
h.logf(r, "local: %s, creds: %+v", pr.Local, pr.Creds)
} else {
h.logf(r, "local: %s", pr.Local)
}
h.logf(r, "payload: %d variables", len(pr.Payload.Variables))
event, err := parseEvent(pr.Payload)
if err != nil {
return
}
// Don't obey request context: we want to persist the Event.
if err := h.s.SaveEvent(context.Background(), event); err != nil {
h.logf(r, "failed to save client event: %v", err)
return
}
h.index.Insert(event)
if h.OnPayload != nil {
// Fire payload hook.
h.OnPayload(pr.Payload)
}
h.mm.PushTotal(1, event.Zpool)
w.WriteHeader(http.StatusNoContent)
}
// A pushRequest contains HTTP request data sent by a client to the push handler.
type pushRequest struct {
Payload Payload
Local net.Addr
// May be nil if connection did not arrive over UNIX socket.
Creds *peercred.Creds
}
// pushRequest is a middleware which parses a valid pushRequest or returns an
// HTTP error status to the client due to an invalid request. If pushRequest
// returns true, the request is valid and can be processed.
func (h *Handler) pushRequest(w http.ResponseWriter, r *http.Request) (*pushRequest, bool) {
// We expect client push to use one-shot requests from the ZEDLET and
// therefore there's no advantage to keepalives.
w.Header().Set("Connection", "close")
if r.Method != http.MethodPost {
return nil, h.pushErrorf(
w, r,
http.StatusMethodNotAllowed,
"method not allowed: %q", r.Method,
)
}
if ct := r.Header.Get("Content-Type"); ct != contentJSON {
return nil, h.pushErrorf(
w, r,
http.StatusBadRequest,
"bad request content type: %q", ct,
)
}
var p Payload
if err := json.NewDecoder(r.Body).Decode(&p); err != nil {
return nil, h.pushErrorf(
w, r,
http.StatusBadRequest,
"bad request payload: %v", err,
)
}
var (
// Fetch data stored in the request context. For UNIX sockets, creds
// will be non-nil.
ctx = r.Context()
local = ctx.Value(http.LocalAddrContextKey).(net.Addr)
creds = peercredContext(ctx)
)
return &pushRequest{
Payload: p,
Local: local,
Creds: creds,
}, true
}
// pushErrorf writes a formatted error to the client and to the Handler's
// logger. It always returns "false" for use in h.pushRequest.
func (h *Handler) pushErrorf(
w http.ResponseWriter, r *http.Request,
status int,
format string, v ...any,
) bool {
text := fmt.Sprintf(format, v...)
h.logf(r, text)
http.Error(w, text, status)
return false
}
// listEvents implements GET /events.
func (h *Handler) listEvents(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", contentJSON)
var body responseBody
if er, err := h.eventsRequest(w, r); err != nil {
h.logf(r, "failed to list events: %v", err)
body = errorBody(err)
} else {
body = responseBody{
Metadata: &responseMetadata{Page: er.Page},
Events: er.Events,
}
}
_ = json.NewEncoder(w).Encode(body)
}
// An eventsRequest contains HTTP request data sent by a client to fetch and
// display events from zedhookd.
type eventsRequest struct {
Events []Event
Page page
}
// eventsRequest is a middleware which parses a valid eventsRequest or returns
// an HTTP error status to the client.
func (h *Handler) eventsRequest(w http.ResponseWriter, r *http.Request) (*eventsRequest, error) {
if r.Method != http.MethodGet {
w.WriteHeader(http.StatusMethodNotAllowed)
return nil, fmt.Errorf("method not allowed: %q", r.Method)
}
q := r.URL.Query()
p, err := queryPage(q)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
return nil, fmt.Errorf("invalid pagination request parameters: %v", err)
}
events, err := h.s.ListEvents(r.Context(), ListEventsOptions{
Zpool: q.Get("zpool"),
Class: q.Get("class"),
Offset: p.Offset,
Limit: p.Limit,
})
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return nil, fmt.Errorf("failed to list events from database: %v", err)
}
return &eventsRequest{
Events: events,
Page: p,
}, nil
}
// getEvent implements GET /events/{id}.
func (h *Handler) getEvent(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", contentJSON)
var body responseBody
if e, err := h.getEventRequest(w, r); err != nil {
h.logf(r, "failed to get event: %v", err)
body = errorBody(err)
} else {
body = responseBody{Event: &e}
}
_ = json.NewEncoder(w).Encode(body)
}
// getEventRequest is a middleware which returns a valid Event or an HTTP status
// error to the client.
func (h *Handler) getEventRequest(w http.ResponseWriter, r *http.Request) (Event, error) {
if r.Method != http.MethodGet {
w.WriteHeader(http.StatusMethodNotAllowed)
return Event{}, fmt.Errorf("method not allowed: %q", r.Method)
}
id, err := strconv.Atoi(mux.Vars(r)["id"])
if err != nil {
w.WriteHeader(http.StatusBadRequest)
return Event{}, fmt.Errorf("invalid event ID: %v", err)
}
e, err := h.s.GetEvent(r.Context(), id)
if err != nil {
// Specific handling for 404.
if errors.Is(err, sql.ErrNoRows) {
w.WriteHeader(http.StatusNotFound)
return Event{}, errors.New("event not found for requested ID")
}
w.WriteHeader(http.StatusInternalServerError)
return Event{}, fmt.Errorf("failed to get event from database: %v", err)
}
return e, nil
}
// logf logs a formatted log for a client request.
func (h *Handler) logf(r *http.Request, format string, v ...any) {
h.ll.Printf("%s: %s", r.RemoteAddr, fmt.Sprintf(format, v...))
}
// responseBody is the top-level HTTP JSON response body object.
type responseBody struct {
Error *responseError `json:"error"`
Metadata *responseMetadata `json:"metadata,omitempty"`
// GET /events
Events []Event `json:"events,omitempty"`
// GET /events/id
Event *Event `json:"event,omitempty"`
}
// responseMetadata contains metadata for the client about an HTTP response.
type responseMetadata struct {
Page page `json:"page"`
}
// responseError contains error information for a client about an HTTP response.
type responseError struct {
Message string `json:"message"`
}
// A page contains API pagination parameters.
type page struct {
Offset int `json:"offset"`
Limit int `json:"limit"`
}
// errorBody returns a responseBody with the input error.
func errorBody(err error) responseBody {
return responseBody{Error: &responseError{Message: err.Error()}}
}
// queryPage creates a page from query parameters.
func queryPage(query url.Values) (page, error) {
type tuple struct {
Name string
Value string
}
newTuple := func(name string) tuple {
return tuple{
Name: name,
Value: query.Get(name),
}
}
// By default, set a zero offset and reasonably large limit.
p := page{Limit: 1000}
for _, t := range [2]tuple{newTuple("offset"), newTuple("limit")} {
if t.Value == "" {
// Not specified.
continue
}
v, err := strconv.Atoi(t.Value)
if err != nil {
return page{}, fmt.Errorf("failed to parse query parameter %q: %v", t.Name, err)
}
switch t.Name {
case "offset":
p.Offset = v
case "limit":
p.Limit = v
default:
panicf("unhandled query parameter: %v", t)
}
}
return p, nil
}
// metrics contains metrics for the zedhookd handler.
type metrics struct {
PushTotal, PushErrorsTotal metricslite.Counter
}
// epoch is the zero UNIX time.
var epoch = time.Unix(0, 0)
// newMetrics produces metrics based on the input metricslite.Interface.
func newMetrics(mm metricslite.Interface, index *eventIndex) metrics {
mm.ConstGauge(
"zedhook_event_latest_timestamp_seconds",
"The UNIX timestamp with nanosecond precision of the most recent event for a given zpool and event class.",
"zpool", "class",
)
mm.OnConstScrape(func(metrics map[string]func(float64, ...string)) error {
for m, c := range metrics {
switch m {
case "zedhook_event_latest_timestamp_seconds":
// Note the latest event by class for each zpool.
index.Walk(func(e Event) {
// Convert nanosecond-precision time.Time into float64
// seconds for Prometheus.
c(e.Timestamp.Sub(epoch).Seconds(), e.Zpool, e.Class)
})
default:
panicf("zedhook: unhandled metric name %q", m)
}
}
return nil
})
return metrics{
PushTotal: mm.Counter(
"zedhook_push_total",
"The number of times a client successfully pushed data to the zedhookd server, partitioned by ZFS pool.",
// TODO(mdlayher): ultimately the values for this field are created
// by user input which means we could experience a cardinality
// explosion in the case of malicious input. The intent is for
// all-zedhook and zedhookd to live on the same system and
// communicate over localhost, but there's no way to know for sure
// that a given pool actually exists unless we exec in this server,
// which is something we'd like to avoid.
//
// Reconsider in the the future.
"zpool",
),
PushErrorsTotal: mm.Counter(
"zedhook_push_errors_total",
"The number of times a client pushed invalid data to the zedhookd server.",
),
}
}
func panicf(format string, a ...any) {
panic(fmt.Sprintf(format, a...))
}