/
feeder_http.go
88 lines (78 loc) · 2.19 KB
/
feeder_http.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
// balboa
// Copyright (c) 2018, DCSO GmbH
package feeder
import (
"context"
"fmt"
"io/ioutil"
"net/http"
"github.com/DCSO/balboa/format"
"github.com/DCSO/balboa/observation"
log "github.com/sirupsen/logrus"
)
// HTTPFeeder is a Feeder implementation that accepts HTTP requests to obtain
// observations.
type HTTPFeeder struct {
StopChan chan bool
StoppedChan chan bool
IsRunning bool
Port int
Host string
MakeObservationFunc format.MakeObservationFunc
Server *http.Server
OutChan chan observation.InputObservation
}
// MakeHTTPFeeder creates a new HTTPFeeder listening on a specific address
// and port.
func MakeHTTPFeeder(host string, port int) *HTTPFeeder {
return &HTTPFeeder{
IsRunning: false,
StopChan: make(chan bool),
Port: port,
Host: host,
MakeObservationFunc: format.MakeFeverAggregateInputObservations,
}
}
// SetInputDecoder states that the given MakeObservationFunc should be used to
// parse and decode data delivered to this feeder.
func (f *HTTPFeeder) SetInputDecoder(fn format.MakeObservationFunc) {
f.MakeObservationFunc = fn
}
func (f *HTTPFeeder) ServeHTTP(w http.ResponseWriter, r *http.Request) {
sensorID := r.Header.Get("X-Sensor-ID")
if r.Method == http.MethodPost {
body, err := ioutil.ReadAll(r.Body)
log.Infof("got %d bytes via HTTP", len(body))
if err != nil {
log.Warn(err)
return
}
f.MakeObservationFunc(body, sensorID, f.OutChan, f.StopChan)
}
w.WriteHeader(200)
}
// Run starts the feeder.
func (f *HTTPFeeder) Run(out chan observation.InputObservation) error {
f.OutChan = out
f.Server = &http.Server{
Addr: fmt.Sprintf("%s:%d", f.Host, f.Port),
Handler: f,
}
log.Infof("accepting submissions on port %v", f.Port)
go func() {
err := f.Server.ListenAndServe()
if err != nil {
log.Info(err)
}
}()
f.IsRunning = true
return nil
}
// Stop causes the feeder to stop accepting requests and close all
// associated channels, including the passed notification channel.
func (f *HTTPFeeder) Stop(stopChan chan bool) {
if f.IsRunning {
f.Server.Shutdown(context.TODO())
}
close(stopChan)
}