forked from tinkerbell/smee
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhttp.go
251 lines (223 loc) · 7.22 KB
/
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
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
package main
import (
"bytes"
"encoding/json"
"flag"
"io"
"io/ioutil"
"net"
"net/http"
"net/http/pprof"
"runtime"
"strconv"
"time"
"github.com/pkg/errors"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/sebest/xff"
"github.com/tinkerbell/boots/conf"
"github.com/tinkerbell/boots/httplog"
"github.com/tinkerbell/boots/installers"
"github.com/tinkerbell/boots/job"
"github.com/tinkerbell/boots/metrics"
)
var (
httpAddr = conf.HTTPBind
)
func init() {
flag.StringVar(&httpAddr, "http-addr", httpAddr, "IP and port to listen on for HTTP.")
}
func serveHealthchecker(rev string, start time.Time) http.HandlerFunc {
return func(w http.ResponseWriter, req *http.Request) {
res := struct {
GitRev string `json:"git_rev"`
Uptime float64 `json:"uptime"`
Goroutines int `json:"goroutines"`
}{
GitRev: rev,
Uptime: time.Since(start).Seconds(),
Goroutines: runtime.NumGoroutine(),
}
b, err := json.Marshal(&res)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
mainlog.Error(errors.Wrap(err, "marshaling healtcheck json"))
}
w.Header().Set("Content-Type", "application/json")
w.Write(b)
}
}
// ServeHTTP is a useless comment
func ServeHTTP() {
mux := http.NewServeMux()
mux.HandleFunc("/", serveJobFile)
mux.Handle("/metrics", promhttp.Handler())
mux.HandleFunc("/_packet/healthcheck", serveHealthchecker(GitRev, StartTime))
mux.HandleFunc("/_packet/pprof/", pprof.Index)
mux.HandleFunc("/_packet/pprof/cmdline", pprof.Cmdline)
mux.HandleFunc("/_packet/pprof/profile", pprof.Profile)
mux.HandleFunc("/_packet/pprof/symbol", pprof.Symbol)
mux.HandleFunc("/_packet/pprof/trace", pprof.Trace)
mux.HandleFunc("/healthcheck", serveHealthchecker(GitRev, StartTime))
mux.HandleFunc("/phone-home", servePhoneHome)
mux.HandleFunc("/phone-home/key", job.ServePublicKey)
mux.HandleFunc("/problem", serveProblem)
// Events endpoint used to forward customer generated custom events from a running device (instance) to packet API
mux.HandleFunc("/events", func(w http.ResponseWriter, req *http.Request) {
code, err := serveEvents(client, w, req)
if err == nil {
return
}
if code != http.StatusOK {
mainlog.Error(err)
}
})
mux.HandleFunc("/hardware-components", serveHardware)
installers.RegisterHTTPHandlers(mux)
var h http.Handler
if len(conf.TrustedProxies) > 0 {
xffmw, _ := xff.New(xff.Options{
AllowedSubnets: conf.TrustedProxies,
})
h = xffmw.Handler(&httplog.Handler{
Handler: mux,
})
} else {
h = &httplog.Handler{
Handler: mux,
}
}
if err := http.ListenAndServe(httpAddr, h); err != nil {
err = errors.Wrap(err, "listen and serve http")
mainlog.Fatal(err)
}
}
func serveJobFile(w http.ResponseWriter, req *http.Request) {
labels := prometheus.Labels{"from": "http", "op": "file"}
metrics.JobsTotal.With(labels).Inc()
metrics.JobsInProgress.With(labels).Inc()
defer metrics.JobsInProgress.With(labels).Dec()
timer := prometheus.NewTimer(metrics.JobDuration.With(labels))
defer timer.ObserveDuration()
j, err := job.CreateFromRemoteAddr(req.RemoteAddr)
if err != nil {
w.WriteHeader(http.StatusNotFound)
mainlog.With("client", req.RemoteAddr, "error", err).Info("no job found for client address")
return
}
j.ServeFile(w, req)
}
func serveHardware(w http.ResponseWriter, req *http.Request) {
labels := prometheus.Labels{"from": "http", "op": "hardware-components"}
metrics.JobsTotal.With(labels).Inc()
metrics.JobsInProgress.With(labels).Inc()
defer metrics.JobsInProgress.With(labels).Dec()
timer := prometheus.NewTimer(metrics.JobDuration.With(labels))
defer timer.ObserveDuration()
j, err := job.CreateFromRemoteAddr(req.RemoteAddr)
if err != nil {
w.WriteHeader(http.StatusNotFound)
mainlog.With("client", req.RemoteAddr, "error", err).Info("no job found for client address")
return
}
j.AddHardware(w, req)
}
func servePhoneHome(w http.ResponseWriter, req *http.Request) {
labels := prometheus.Labels{"from": "http", "op": "phone-home"}
metrics.JobsTotal.With(labels).Inc()
metrics.JobsInProgress.With(labels).Inc()
defer metrics.JobsInProgress.With(labels).Dec()
timer := prometheus.NewTimer(metrics.JobDuration.With(labels))
defer timer.ObserveDuration()
j, err := job.CreateFromRemoteAddr(req.RemoteAddr)
if err != nil {
w.WriteHeader(http.StatusOK)
mainlog.With("client", req.RemoteAddr, "error", err).Info("no job found for client address")
return
}
j.ServePhoneHomeEndpoint(w, req)
}
func serveProblem(w http.ResponseWriter, req *http.Request) {
labels := prometheus.Labels{"from": "http", "op": "problem"}
metrics.JobsTotal.With(labels).Inc()
metrics.JobsInProgress.With(labels).Inc()
defer metrics.JobsInProgress.With(labels).Dec()
timer := prometheus.NewTimer(metrics.JobDuration.With(labels))
defer timer.ObserveDuration()
j, err := job.CreateFromRemoteAddr(req.RemoteAddr)
if err != nil {
w.WriteHeader(http.StatusNotFound)
mainlog.With("client", req.RemoteAddr, "error", err).Info("no job found for client address")
return
}
j.ServeProblemEndpoint(w, req)
}
func readClose(r io.ReadCloser) (b []byte, err error) {
b, err = ioutil.ReadAll(r)
err = errors.Wrap(err, "read data")
r.Close()
return
}
type eventsServer interface {
GetInstanceIDFromIP(net.IP) (string, error)
PostInstanceEvent(string, io.Reader) (string, error)
}
// Forward user generated events to Packet API
func serveEvents(client eventsServer, w http.ResponseWriter, req *http.Request) (int, error) {
host, _, err := net.SplitHostPort(req.RemoteAddr)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
return http.StatusBadRequest, errors.Wrap(err, "split host port")
}
ip := net.ParseIP(host)
if ip == nil {
w.WriteHeader(http.StatusOK)
return http.StatusOK, errors.New("no device found for client address")
}
deviceID, err := client.GetInstanceIDFromIP(ip)
if err != nil || deviceID == "" {
w.WriteHeader(http.StatusOK)
return http.StatusOK, errors.New("no device found for client address")
}
b, err := readClose(req.Body)
if err != nil {
w.WriteHeader(http.StatusBadRequest)
return http.StatusBadRequest, err
}
if len(b) == 0 {
w.WriteHeader(http.StatusBadRequest)
return http.StatusBadRequest, errors.New("userEvent body is empty")
}
var res struct {
Code int `json:"code"`
State string `json:"state"`
Message string `json:"message"`
}
if err := json.Unmarshal(b, &res); err != nil {
w.WriteHeader(http.StatusBadRequest)
return http.StatusBadRequest, errors.New("userEvent cannot be generated from supplied json")
}
e := struct {
Code string `json:"type"`
State string `json:"state"`
Message string `json:"body"`
}{
Code: "user." + strconv.Itoa(res.Code),
State: res.State,
Message: res.Message,
}
payload, err := json.Marshal(e)
if err != nil {
// TODO(mmlb): this should be 500
w.WriteHeader(http.StatusBadRequest)
return http.StatusBadRequest, errors.New("userEvent cannot be encoded")
}
if _, err := client.PostInstanceEvent(deviceID, bytes.NewReader(payload)); err != nil {
// TODO(mmlb): this should be 500
w.WriteHeader(http.StatusBadRequest)
return http.StatusBadRequest, errors.New("failed to post userEvent")
}
w.WriteHeader(http.StatusOK)
w.Write([]byte{})
return http.StatusOK, nil
}