-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathhandlers.go
352 lines (299 loc) · 10.5 KB
/
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
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
package main
import (
"context"
"encoding/json"
"fmt"
"net/http"
"os"
"runtime"
"strconv"
"strings"
"github.com/ipfs/boxo/blockstore"
leveldb "github.com/ipfs/go-ds-leveldb"
"github.com/ipfs/go-log/v2"
_ "embed"
_ "net/http/pprof"
"github.com/felixge/httpsnoop"
"github.com/ipfs/boxo/gateway"
servertiming "github.com/mitchellh/go-server-timing"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/promhttp"
"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
)
//go:embed static/index.html
var indexHTML []byte
func makeMetricsAndDebuggingHandler() *http.ServeMux {
mux := http.NewServeMux()
gatherers := prometheus.Gatherers{
prometheus.DefaultGatherer,
}
options := promhttp.HandlerOpts{}
mux.Handle("/debug/metrics/prometheus", promhttp.HandlerFor(gatherers, options))
mux.Handle("/debug/vars", http.DefaultServeMux)
mux.Handle("/debug/pprof/", http.DefaultServeMux)
mux.HandleFunc("/debug/stack", func(w http.ResponseWriter, r *http.Request) {
if err := writeAllGoroutineStacks(w); err != nil {
goLog.Error(err)
}
})
MutexFractionOption("/debug/pprof-mutex/", mux)
BlockProfileRateOption("/debug/pprof-block/", mux)
return mux
}
func addLogHandlers(mux *http.ServeMux) {
mux.HandleFunc("/mgr/log/level", func(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
q := r.URL.Query()
subsystem := q.Get("subsystem")
level := q.Get("level")
if subsystem == "" || level == "" {
http.Error(w, "both subsystem and level must be passed", http.StatusBadRequest)
return
}
if err := log.SetLogLevel(subsystem, level); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
})
mux.HandleFunc("/mgr/log/ls", func(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write([]byte(strings.Join(log.GetSubsystems(), ",")))
})
}
func GCHandler(gnd *Node) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
var body struct {
BytesToFree int64
}
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if err := gnd.GC(r.Context(), body.BytesToFree); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
}
func withConnect(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// ServeMux does not support requests with CONNECT method,
// so we need to handle them separately
// https://golang.org/src/net/http/request.go#L111
if r.Method == http.MethodConnect {
w.WriteHeader(http.StatusOK)
return
}
next.ServeHTTP(w, r)
})
}
func withRequestLogger(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
m := httpsnoop.CaptureMetrics(next, w, r)
goLog.Infow(r.Method, "url", r.URL, "host", r.Host, "code", m.Code, "duration", m.Duration, "written", m.Written, "ua", r.UserAgent(), "referer", r.Referer())
})
}
func setupGatewayHandler(cfg Config, nd *Node) (http.Handler, error) {
var (
backend gateway.IPFSBackend
err error
)
options := []gateway.BackendOption{
gateway.WithValueStore(nd.vs),
gateway.WithNameSystem(nd.ns),
gateway.WithResolver(nd.resolver), // May be nil, but that is fine.
}
if len(cfg.RemoteBackends) > 0 && cfg.RemoteBackendMode == RemoteBackendCAR {
var fetcher gateway.CarFetcher
fetcher, err = gateway.NewRemoteCarFetcher(cfg.RemoteBackends, nil)
if err != nil {
return nil, err
}
backend, err = gateway.NewCarBackend(fetcher, options...)
} else {
backend, err = gateway.NewBlocksBackend(nd.bsrv, options...)
}
if err != nil {
return nil, err
}
headers := map[string][]string{}
// Note: in the future we may want to make this more configurable.
noDNSLink := false
// TODO: allow appending hostnames to this list via ENV variable (separate PATH_GATEWAY_HOSTS & SUBDOMAIN_GATEWAY_HOSTS)
publicGateways := map[string]*gateway.PublicGateway{
"localhost": {
Paths: []string{"/ipfs", "/ipns", "/version"},
NoDNSLink: noDNSLink,
InlineDNSLink: false,
DeserializedResponses: true,
UseSubdomains: true,
},
}
for _, domain := range cfg.GatewayDomains {
publicGateways[domain] = &gateway.PublicGateway{
Paths: []string{"/ipfs", "/ipns", "/version"},
NoDNSLink: noDNSLink,
InlineDNSLink: true,
DeserializedResponses: true,
UseSubdomains: false,
}
}
for _, domain := range cfg.SubdomainGatewayDomains {
publicGateways[domain] = &gateway.PublicGateway{
Paths: []string{"/ipfs", "/ipns", "/version"},
NoDNSLink: noDNSLink,
InlineDNSLink: true,
DeserializedResponses: true,
UseSubdomains: true,
}
}
for _, domain := range cfg.TrustlessGatewayDomains {
publicGateways[domain] = &gateway.PublicGateway{
Paths: []string{"/ipfs", "/ipns", "/version"},
NoDNSLink: true,
InlineDNSLink: true,
DeserializedResponses: false,
UseSubdomains: contains(cfg.SubdomainGatewayDomains, domain),
}
}
// If we're doing tests, ensure the right public gateways are enabled.
if os.Getenv("GATEWAY_CONFORMANCE_TEST") == "true" {
publicGateways["example.com"] = &gateway.PublicGateway{
Paths: []string{"/ipfs", "/ipns"},
NoDNSLink: noDNSLink,
InlineDNSLink: true,
DeserializedResponses: true,
UseSubdomains: true,
}
// TODO: revisit the below once we clarify desired behavior in https://specs.ipfs.tech/http-gateways/subdomain-gateway/
publicGateways["localhost"].InlineDNSLink = true
}
gwConf := gateway.Config{
DeserializedResponses: true,
PublicGateways: publicGateways,
NoDNSLink: noDNSLink,
}
gwHandler := gateway.NewHandler(gwConf, backend)
ipfsHandler := withHTTPMetrics(gwHandler, "ipfs", cfg.disableMetrics)
ipnsHandler := withHTTPMetrics(gwHandler, "ipns", cfg.disableMetrics)
topMux := http.NewServeMux()
topMux.Handle("/ipfs/", ipfsHandler)
topMux.Handle("/ipns/", ipnsHandler)
topMux.HandleFunc("/version", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Client: %s\n", name)
fmt.Fprintf(w, "Version: %s\n", version)
})
topMux.HandleFunc("/api/v0/", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotImplemented)
w.Write([]byte("The /api/v0 Kubo RPC is not part of IPFS Gateway Specs (https://specs.ipfs.tech/http-gateways/). Consider refactoring your app. If you still need this Kubo endpoint, please self-host a Kubo instance yourself: https://docs.ipfs.tech/install/command-line/ with proper auth https://github.com/ipfs/kubo/blob/master/docs/config.md#apiauthorizations"))
})
topMux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Write(indexHTML)
})
// Construct the HTTP handler for the gateway.
handler := withConnect(topMux)
handler = http.Handler(gateway.NewHostnameHandler(gwConf, backend, handler))
// Add custom headers and liberal CORS.
handler = gateway.NewHeaders(headers).ApplyCors().Wrap(handler)
handler = servertiming.Middleware(handler, nil)
// Add logging.
handler = withRequestLogger(handler)
// Add tracing.
handler = withTracingAndDebug(handler, cfg.TracingAuthToken)
return handler, nil
}
func withTracingAndDebug(next http.Handler, authToken string) http.Handler {
next = otelhttp.NewHandler(next, "Gateway")
// Remove tracing and cache skipping headers if not authorized
return http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
// Disable tracing/debug headers if auth token missing or invalid
if authToken == "" || request.Header.Get("Authorization") != authToken {
if request.Header.Get("Traceparent") != "" {
request.Header.Del("Traceparent")
}
if request.Header.Get("Tracestate") != "" {
request.Header.Del("Tracestate")
}
if request.Header.Get(NoBlockcacheHeader) != "" {
request.Header.Del(NoBlockcacheHeader)
}
}
// Process cache skipping header
if noBlockCache := request.Header.Get(NoBlockcacheHeader); noBlockCache == "true" {
ds, err := leveldb.NewDatastore("", nil)
if err != nil {
writer.WriteHeader(http.StatusInternalServerError)
_, _ = writer.Write([]byte(err.Error()))
return
}
newCtx := context.WithValue(request.Context(), NoBlockcache{}, blockstore.NewBlockstore(ds))
request = request.WithContext(newCtx)
}
next.ServeHTTP(writer, request)
})
}
const NoBlockcacheHeader = "Rainbow-No-Blockcache"
type NoBlockcache struct{}
// MutexFractionOption allows to set runtime.SetMutexProfileFraction via HTTP
// using POST request with parameter 'fraction'.
func MutexFractionOption(path string, mux *http.ServeMux) *http.ServeMux {
mux.HandleFunc(path, func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "only POST allowed", http.StatusMethodNotAllowed)
return
}
if err := r.ParseForm(); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
asfr := r.Form.Get("fraction")
if len(asfr) == 0 {
http.Error(w, "parameter 'fraction' must be set", http.StatusBadRequest)
return
}
fr, err := strconv.Atoi(asfr)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
runtime.SetMutexProfileFraction(fr)
})
return mux
}
// BlockProfileRateOption allows to set runtime.SetBlockProfileRate via HTTP
// using POST request with parameter 'rate'.
// The profiler tries to sample 1 event every <rate> nanoseconds.
// If rate == 1, then the profiler samples every blocking event.
// To disable, set rate = 0.
func BlockProfileRateOption(path string, mux *http.ServeMux) *http.ServeMux {
mux.HandleFunc(path, func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "only POST allowed", http.StatusMethodNotAllowed)
return
}
if err := r.ParseForm(); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
rateStr := r.Form.Get("rate")
if len(rateStr) == 0 {
http.Error(w, "parameter 'rate' must be set", http.StatusBadRequest)
return
}
rate, err := strconv.Atoi(rateStr)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
runtime.SetBlockProfileRate(rate)
})
return mux
}
func contains[T comparable](collection []T, element T) bool {
for _, item := range collection {
if item == element {
return true
}
}
return false
}