-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathmain.go
276 lines (238 loc) · 7.21 KB
/
main.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
package main
import (
"context"
"crypto/subtle"
"embed"
"encoding/json"
"log"
"net"
"net/http"
"os"
"time"
"github.com/ipfs/go-cid"
"github.com/libp2p/go-libp2p/core/peer"
"github.com/multiformats/go-multiaddr"
"github.com/multiformats/go-multihash"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/collectors"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/urfave/cli/v2"
)
//go:embed web
var webFS embed.FS
func main() {
app := cli.NewApp()
app.Name = name
app.Usage = "Server tool for checking the accessibility of your data by IPFS peers"
app.Flags = []cli.Flag{
&cli.StringFlag{
Name: "address",
Value: ":3333",
Usage: "address to run on",
EnvVars: []string{"IPFS_CHECK_ADDRESS"},
},
&cli.BoolFlag{
Name: "accelerated-dht",
Value: true,
EnvVars: []string{"IPFS_CHECK_ACCELERATED_DHT"},
Usage: "run the accelerated DHT client",
},
&cli.StringFlag{
Name: "metrics-auth-username",
Value: "",
EnvVars: []string{"IPFS_CHECK_METRICS_AUTH_USER"},
Usage: "http basic auth user for the metrics endpoints",
},
&cli.StringFlag{
Name: "metrics-auth-password",
Value: "",
EnvVars: []string{"IPFS_CHECK_METRICS_AUTH_PASS"},
Usage: "http basic auth password for the metrics endpoints",
},
}
app.Action = func(cctx *cli.Context) error {
ctx := cctx.Context
d, err := newDaemon(ctx, cctx.Bool("accelerated-dht"))
if err != nil {
return err
}
return startServer(ctx, d, cctx.String("address"), cctx.String("metrics-auth-username"), cctx.String("metrics-auth-password"))
}
err := app.Run(os.Args)
if err != nil {
log.Fatal(err)
}
}
const (
defaultCheckTimeout = 60 * time.Second
defaultIndexerURL = "https://cid.contact"
)
func startServer(ctx context.Context, d *daemon, tcpListener, metricsUsername, metricPassword string) error {
log.Printf("Starting %s %s\n", name, version)
l, err := net.Listen("tcp", tcpListener)
if err != nil {
return err
}
log.Printf("Libp2p host peer id %s\n", d.h.ID())
log.Printf("Libp2p host listening on %v\n", d.h.Addrs())
d.mustStart()
log.Printf("Backend ready and listening on %v\n", l.Addr())
webAddr := getWebAddress(l)
log.Printf("Test fronted at http://%s/web/?backendURL=http://%s\n", webAddr, webAddr)
log.Printf("Metrics endpoint at http://%s/metrics\n", webAddr)
log.Printf("Ready to start serving.")
checkHandler := func(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Access-Control-Allow-Origin", "*")
maStr := r.URL.Query().Get("multiaddr")
cidStr := r.URL.Query().Get("cid")
timeoutStr := r.URL.Query().Get("timeoutSeconds")
ipniURL := r.URL.Query().Get("ipniIndexer")
if cidStr == "" {
http.Error(w, "missing 'cid' query parameter", http.StatusBadRequest)
return
}
cidKey, err := cid.Decode(cidStr)
if err != nil {
mh, mhErr := multihash.FromB58String(cidStr)
if mhErr != nil {
mh, mhErr = multihash.FromHexString(cidStr)
if mhErr != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
}
cidKey = cid.NewCidV1(cid.Raw, mh)
}
checkTimeout := defaultCheckTimeout
if timeoutStr != "" {
checkTimeout, err = time.ParseDuration(timeoutStr + "s")
if err != nil {
http.Error(w, "Invalid timeout value (in seconds)", http.StatusBadRequest)
return
}
}
if ipniURL == "" {
ipniURL = defaultIndexerURL
}
log.Printf("Checking %s with timeout %s seconds", cidStr, checkTimeout.String())
withTimeout, cancel := context.WithTimeout(r.Context(), checkTimeout)
defer cancel()
var data interface{}
if maStr == "" {
data, err = d.runCidCheck(withTimeout, cidKey, ipniURL)
} else {
ma, ai, err400 := parseMultiaddr(maStr)
if err400 != nil {
http.Error(w, err400.Error(), http.StatusBadRequest)
return
}
data, err = d.runPeerCheck(withTimeout, ma, ai, cidKey, ipniURL)
}
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Add("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(data)
}
// Register the default Go collector
d.promRegistry.MustRegister(collectors.NewGoCollector())
// Register the process collector
d.promRegistry.MustRegister(collectors.NewProcessCollector(collectors.ProcessCollectorOpts{}))
requestsTotal := prometheus.NewCounterVec(
prometheus.CounterOpts{
Name: "http_requests_total",
Help: "Total number of HTTP requests",
},
[]string{"code"},
)
requestDuration := prometheus.NewHistogramVec(
prometheus.HistogramOpts{
Name: "http_request_duration_seconds",
Help: "Duration of HTTP requests",
Buckets: prometheus.DefBuckets,
},
[]string{"code"},
)
requestsInFlight := prometheus.NewGauge(prometheus.GaugeOpts{
Name: "http_requests_in_flight",
Help: "Number of HTTP requests currently being served",
})
// Register metrics with our custom registry
d.promRegistry.MustRegister(requestsTotal)
d.promRegistry.MustRegister(requestDuration)
d.promRegistry.MustRegister(requestsInFlight)
// Instrument the checkHandler
instrumentedHandler := promhttp.InstrumentHandlerCounter(
requestsTotal,
promhttp.InstrumentHandlerDuration(
requestDuration,
promhttp.InstrumentHandlerInFlight(
requestsInFlight,
http.HandlerFunc(checkHandler),
),
),
)
http.Handle("/check", instrumentedHandler)
// Use a single metrics endpoint for all Prometheus metrics
http.Handle("/metrics", BasicAuth(promhttp.HandlerFor(d.promRegistry, promhttp.HandlerOpts{}), metricsUsername, metricPassword))
// Serve frontend on /web
fileServer := http.FileServer(http.FS(webFS))
http.Handle("/web/", fileServer)
// Set up the root route to redirect to /web
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "/web", http.StatusFound)
})
done := make(chan error, 1)
go func() {
defer close(done)
done <- http.Serve(l, nil)
}()
select {
case err := <-done:
return err
case <-ctx.Done():
_ = l.Close()
return <-done
}
}
func BasicAuth(handler http.Handler, username, password string) http.Handler {
if username == "" || password == "" {
log.Println("Warning: no http basic auth for the metrics endpoint.")
return handler
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
user, pass, ok := r.BasicAuth()
if !ok || subtle.ConstantTimeCompare([]byte(user), []byte(username)) != 1 || subtle.ConstantTimeCompare([]byte(pass), []byte(password)) != 1 {
w.Header().Set("WWW-Authenticate", `Basic realm="Restricted"`)
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
handler.ServeHTTP(w, r)
})
}
// getWebAddress returns listener with [::] and 0.0.0.0 replaced by localhost
func getWebAddress(l net.Listener) string {
addr := l.Addr().String()
host, port, err := net.SplitHostPort(addr)
if err != nil {
return addr
}
switch host {
case "", "0.0.0.0", "::":
return net.JoinHostPort("localhost", port)
default:
return addr
}
}
func parseMultiaddr(maStr string) (multiaddr.Multiaddr, *peer.AddrInfo, error) {
ma, err := multiaddr.NewMultiaddr(maStr)
if err != nil {
return nil, nil, err
}
ai, err := peer.AddrInfoFromP2pAddr(ma)
if err != nil {
return nil, nil, err
}
return ma, ai, nil
}