/
handler.go
623 lines (541 loc) · 15.6 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
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
package admin
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"path"
"sort"
"strconv"
"sync"
"github.com/ipfs/go-cid"
"github.com/ipni/go-indexer-core"
"github.com/ipni/storetheindex/admin/model"
"github.com/ipni/storetheindex/internal/httpserver"
"github.com/ipni/storetheindex/internal/ingest"
"github.com/ipni/storetheindex/internal/registry"
"github.com/libp2p/go-libp2p/core/peer"
"github.com/multiformats/go-multiaddr"
"github.com/multiformats/go-multihash"
)
type adminHandler struct {
ctx context.Context
id peer.ID
indexer indexer.Interface
ingester *ingest.Ingester
reg *registry.Registry
reloadErrChan chan<- chan error
pendingSyncs sync.WaitGroup
pendingSyncsPeers map[peer.ID]struct{}
pendingSyncsLock sync.Mutex
}
func newHandler(ctx context.Context, id peer.ID, indexer indexer.Interface, ingester *ingest.Ingester, reg *registry.Registry, reloadErrChan chan<- chan error) *adminHandler {
return &adminHandler{
ctx: ctx,
id: id,
indexer: indexer,
ingester: ingester,
reg: reg,
reloadErrChan: reloadErrChan,
pendingSyncsPeers: make(map[peer.ID]struct{}),
}
}
// ----- assignment handlers -----
func (h *adminHandler) listAssignedPeers(w http.ResponseWriter, r *http.Request) {
if !httpserver.MethodOK(w, r, http.MethodGet) {
return
}
publishers, continued, err := h.reg.ListAssignedPeers()
if err != nil {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return
}
if len(publishers) == 0 {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(http.StatusNoContent)
return
}
apiAssigned := make([]model.Assigned, len(publishers))
for i := range publishers {
apiAssigned[i].Publisher = publishers[i]
apiAssigned[i].Continued = continued[i]
}
data, err := json.Marshal(apiAssigned)
if err != nil {
log.Errorw("Error marshaling assigned list", "err", err)
http.Error(w, "", http.StatusInternalServerError)
return
}
httpserver.WriteJsonResponse(w, http.StatusOK, data)
}
func (h *adminHandler) listPreferredPeers(w http.ResponseWriter, r *http.Request) {
if !httpserver.MethodOK(w, r, http.MethodGet) {
return
}
preferred, err := h.reg.ListPreferredPeers()
if err != nil {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
return
}
if len(preferred) == 0 {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(http.StatusNoContent)
return
}
data, err := json.Marshal(preferred)
if err != nil {
log.Errorw("Error marshaling preferred list", "err", err)
http.Error(w, "", http.StatusInternalServerError)
return
}
httpserver.WriteJsonResponse(w, http.StatusOK, data)
}
func (h *adminHandler) handoffPeer(w http.ResponseWriter, r *http.Request) {
if !httpserver.MethodOK(w, r, http.MethodPost) {
return
}
peerID, ok := decodePeerID(path.Base(r.URL.Path), w)
if !ok {
return
}
log := log.With("publisher", peerID)
data, err := io.ReadAll(r.Body)
if err != nil {
log.Errorw("Failed reading body", "err", err)
http.Error(w, "", http.StatusInternalServerError)
return
}
if len(data) == 0 {
http.Error(w, "missing handoff data", http.StatusBadRequest)
return
}
var handoff model.Handoff
err = json.Unmarshal(data, &handoff)
if err != nil {
log.Errorw("Cannot unmarshal handoff data", "err", err)
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
log = log.With("from", handoff.FrozenID.String())
frozenURL, err := url.Parse(handoff.FrozenURL)
if err != nil {
log.Errorw("Cannot parse handoff 'frozen' URL", "err", err, "url", handoff.FrozenURL)
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
err = h.reg.Handoff(r.Context(), peerID, handoff.FrozenID, frozenURL)
if err != nil {
assignError(w, err)
return
}
}
func (h *adminHandler) assignPeer(w http.ResponseWriter, r *http.Request) {
if !httpserver.MethodOK(w, r, http.MethodPost) {
return
}
peerID, ok := decodePeerID(path.Base(r.URL.Path), w)
if !ok {
return
}
err := h.reg.AssignPeer(peerID)
if err != nil {
assignError(w, err)
return
}
}
func assignError(w http.ResponseWriter, err error) {
log.Errorw("Cannot assign publisher to indexer", "err", err)
switch {
case errors.Is(err, registry.ErrNotAllowed), errors.Is(err, registry.ErrPublisherNotAllowed), errors.Is(err, registry.ErrCannotPublish):
http.Error(w, err.Error(), http.StatusForbidden)
case errors.Is(err, registry.ErrNoAssigner):
http.Error(w, err.Error(), http.StatusServiceUnavailable)
case errors.Is(err, registry.ErrAlreadyAssigned):
http.Error(w, err.Error(), http.StatusBadRequest)
default:
http.Error(w, "", http.StatusInternalServerError)
}
}
func (h *adminHandler) unassignPeer(w http.ResponseWriter, r *http.Request) {
if !httpserver.MethodOK(w, r, http.MethodPut) {
return
}
peerID, ok := decodePeerID(path.Base(r.URL.Path), w)
if !ok {
return
}
ok, err := h.reg.UnassignPeer(peerID)
if err != nil {
log.Infow("Cannot unassign peer from indexer", "peer", peerID.String())
if errors.Is(err, registry.ErrNoAssigner) {
http.Error(w, err.Error(), http.StatusServiceUnavailable)
} else {
http.Error(w, "", http.StatusInternalServerError)
}
return
}
if !ok {
http.Error(w, "peer was not assigned", http.StatusNotFound)
return
}
log.Infow("Unassigned publisher from indexer", "publisher", peerID)
}
// ----- ingest handlers -----
func (h *adminHandler) allowPeer(w http.ResponseWriter, r *http.Request) {
if !httpserver.MethodOK(w, r, http.MethodPut) {
return
}
peerID, ok := decodePeerID(path.Base(r.URL.Path), w)
if !ok {
return
}
log.Infow("Allowing peer to publish and provide content", "peer", peerID)
if h.reg.AllowPeer(peerID) {
log.Infow("Update config to persist allowing peer", "peerr", peerID)
}
}
func (h *adminHandler) blockPeer(w http.ResponseWriter, r *http.Request) {
if !httpserver.MethodOK(w, r, http.MethodPut) {
return
}
peerID, ok := decodePeerID(path.Base(r.URL.Path), w)
if !ok {
return
}
log.Infow("Blocking peer from publishing or providing content", "peer", peerID.String())
if h.reg.BlockPeer(peerID) {
log.Infow("Update config to persist blocking peer", "provider", peerID)
}
}
func (h *adminHandler) markAdProcessed(w http.ResponseWriter, r *http.Request) {
if !httpserver.MethodOK(w, r, http.MethodPut) {
return
}
peerID, ok := decodePeerID(path.Base(r.URL.Path), w)
if !ok {
return
}
pinfo, found := h.reg.ProviderInfo(peerID)
if !found {
http.Error(w, "", http.StatusNotFound)
return
}
cidStr := r.URL.Query().Get("cid")
stopCid, err := cid.Decode(cidStr)
if err != nil {
log.Errorw("error decoding cid", "cid", cidStr, "err", err)
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
err = h.ingester.MarkAdProcessed(pinfo.Publisher, stopCid)
if err != nil {
log.Errorw("Failed to explicitly mark adas processed", "err", err)
http.Error(w, "", http.StatusInternalServerError)
return
}
log.Infow("Explicitly marked advertisement as processed", "adCid", stopCid, "provider", peerID)
}
func (h *adminHandler) handlePostSyncs(w http.ResponseWriter, r *http.Request) {
if !httpserver.MethodOK(w, r, http.MethodPost) {
return
}
if h.ingester == nil {
log.Warn("sync not available, ingester disabled")
http.Error(w, "ingester disabled", http.StatusServiceUnavailable)
return
}
peerID, ok := decodePeerID(path.Base(r.URL.Path), w)
if !ok {
return
}
log := log.With("peerID", peerID)
query := r.URL.Query()
var depth int64
depthStr := query.Get("depth")
if depthStr != "" {
var err error
depth, err = strconv.ParseInt(depthStr, 10, 0)
if err != nil {
log.Errorw("Cannot unmarshal recursion depth as integer", "depthStr", depthStr, "err", err)
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
log = log.With("depth", depth)
}
var resync bool
resyncStr := query.Get("resync")
if resyncStr != "" {
var err error
resync, err = strconv.ParseBool(resyncStr)
if err != nil {
log.Errorw("Cannot unmarshal flag resync as bool", "resync", resyncStr, "err", err)
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
log = log.With("resync", resync)
}
data, err := io.ReadAll(r.Body)
if err != nil {
log.Errorw("Failed reading body", "err", err)
http.Error(w, "", http.StatusInternalServerError)
return
}
var syncAddr multiaddr.Multiaddr
if len(data) != 0 {
var v string
err = json.Unmarshal(data, &v)
if err == nil {
syncAddr, err = multiaddr.NewMultiaddr(v)
}
if err != nil {
log.Errorw("Cannot unmarshal sync multiaddr", "err", err)
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
log = log.With("address", syncAddr)
}
// Start the sync, but do not wait for it to complete.
h.pendingSyncsLock.Lock()
if _, ok := h.pendingSyncsPeers[peerID]; ok {
h.pendingSyncsLock.Unlock()
log.Info("Manual sync ignored because another sync is in progress")
msg := fmt.Sprintf("Peer %s has already a sync in progress", peerID.String())
http.Error(w, msg, http.StatusConflict)
return
}
h.pendingSyncsPeers[peerID] = struct{}{}
h.pendingSyncsLock.Unlock()
log.Info("Syncing with peer")
h.pendingSyncs.Add(1)
go func() {
peerInfo := peer.AddrInfo{
ID: peerID,
}
if syncAddr != nil {
peerInfo.Addrs = []multiaddr.Multiaddr{syncAddr}
}
_, err := h.ingester.Sync(h.ctx, peerInfo, int(depth), resync)
if err != nil {
log.Errorw("Cannot sync with peer", "err", err)
}
h.pendingSyncs.Done()
h.pendingSyncsLock.Lock()
delete(h.pendingSyncsPeers, peerID)
h.pendingSyncsLock.Unlock()
}()
// Return (202) Accepted
w.WriteHeader(http.StatusAccepted)
}
func (h *adminHandler) handleGetSyncs(w http.ResponseWriter, r *http.Request) {
h.pendingSyncsLock.Lock()
peers := make([]string, 0, len(h.pendingSyncsPeers))
for k := range h.pendingSyncsPeers {
peers = append(peers, k.String())
}
h.pendingSyncsLock.Unlock()
sort.Strings(peers)
marshalled, err := json.Marshal(peers)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
httpserver.WriteJsonResponse(w, http.StatusOK, marshalled)
}
func (h *adminHandler) sync(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodPost:
h.handlePostSyncs(w, r)
case http.MethodGet:
h.handleGetSyncs(w, r)
default:
http.Error(w, "", http.StatusMethodNotAllowed)
}
}
func (h *adminHandler) importProviders(w http.ResponseWriter, r *http.Request) {
if !httpserver.MethodOK(w, r, http.MethodPost) {
return
}
body, err := io.ReadAll(r.Body)
if err != nil {
log.Errorw("failed reading import providers request", "err", err)
http.Error(w, "", http.StatusBadRequest)
return
}
var params map[string][]byte
err = json.Unmarshal(body, ¶ms)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
from, ok := params["indexer"]
if !ok {
http.Error(w, "missing indexer url in request", http.StatusBadRequest)
return
}
fromURL := &url.URL{}
err = fromURL.UnmarshalBinary(from)
if err != nil {
http.Error(w, "bad indexer url: "+err.Error(), http.StatusBadRequest)
return
}
_, err = h.reg.ImportProviders(h.ctx, fromURL)
if err != nil {
msg := "Cannot get providers from other indexer"
log.Errorw(msg, "err", err)
http.Error(w, msg, http.StatusBadGateway)
return
}
}
func (h *adminHandler) reloadConfig(w http.ResponseWriter, r *http.Request) {
if !httpserver.MethodOK(w, r, http.MethodPost) {
return
}
errChan := make(chan error)
h.reloadErrChan <- errChan
err := <-errChan
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
// ----- admin handlers -----
func (h *adminHandler) freeze(w http.ResponseWriter, r *http.Request) {
if !httpserver.MethodOK(w, r, http.MethodPut) {
return
}
err := h.reg.Freeze()
if err != nil {
if errors.Is(err, registry.ErrNoFreeze) {
log.Infow("Cannot freeze indexer", "reason", err)
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
log.Errorw("Cannot freeze indexer", "err", err)
http.Error(w, "", http.StatusInternalServerError)
return
}
}
func (h *adminHandler) status(w http.ResponseWriter, r *http.Request) {
if !httpserver.MethodOK(w, r, http.MethodGet) {
return
}
var usage float64
du, err := h.reg.ValueStoreUsage()
if err != nil {
log.Error(err)
usage = -1.0
} else if du != nil {
usage = du.Percent
}
status := model.Status{
Frozen: h.reg.Frozen(),
ID: h.id,
Usage: usage,
}
data, err := json.Marshal(status)
if err != nil {
log.Errorw("Error marshaling status", "err", err)
http.Error(w, "", http.StatusInternalServerError)
return
}
httpserver.WriteJsonResponse(w, http.StatusOK, data)
}
func (h *adminHandler) healthCheckHandler(w http.ResponseWriter, r *http.Request) {
if !httpserver.MethodOK(w, r, http.MethodGet) {
return
}
if err := healthCheckValueStore(h); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if _, err := w.Write([]byte("\"OK\"")); err != nil {
log.Errorw("Cannot write HealthCheck response:", "err", err)
}
}
// ----- Telemetry routes -----
func (h *adminHandler) listTelemetry(w http.ResponseWriter, r *http.Request) {
if !httpserver.MethodOK(w, r, http.MethodGet) {
return
}
ingestRates := h.ingester.GetAllIngestRates()
if len(ingestRates) == 0 {
w.WriteHeader(http.StatusNoContent)
return
}
data, err := json.Marshal(ingestRates)
if err != nil {
log.Errorw("Error marshaling telemetry data", "err", err)
http.Error(w, "", http.StatusInternalServerError)
return
}
httpserver.WriteJsonResponse(w, http.StatusOK, data)
}
func (h *adminHandler) getTelemetry(w http.ResponseWriter, r *http.Request) {
if !httpserver.MethodOK(w, r, http.MethodGet) {
return
}
providerID, err := peer.Decode(path.Base(r.URL.Path))
if err != nil {
http.Error(w, "cannot decode provider id", http.StatusBadRequest)
return
}
ingestRate, ok := h.ingester.GetIngestRate(providerID)
if !ok {
w.WriteHeader(http.StatusNoContent)
return
}
data, err := json.Marshal(ingestRate)
if err != nil {
log.Errorw("Error marshaling telemetry data", "err", err)
http.Error(w, "", http.StatusInternalServerError)
return
}
httpserver.WriteJsonResponse(w, http.StatusOK, data)
}
// ----- utility functions -----
func decodePeerID(id string, w http.ResponseWriter) (peer.ID, bool) {
peerID, err := peer.Decode(id)
if err != nil {
msg := "Cannot decode peer id"
log.Errorw(msg, "id", id, "err", err)
http.Error(w, msg, http.StatusBadRequest)
return peerID, false
}
return peerID, true
}
var healthCheckMH multihash.Multihash
var healthCheckValue indexer.Value
func init() {
provider, err := peer.Decode("12D3KooWBUNzpAz1Jfvnaag1nHBi6gbG5Q1BQm8kCfcpmt7bGKa6")
if err != nil {
panic(err.Error())
}
healthCheckMH = multihash.Multihash("2DrjgbFdhNiSJghFWcQbzw6E8y4jU1Z7ZsWo3dJbYxwGTNFmAj")
healthCheckValue = indexer.Value{
ProviderID: provider,
ContextID: []byte(healthCheckMH),
MetadataBytes: []byte("healthcheck-metadata"),
}
}
func healthCheckValueStore(h *adminHandler) error {
if err := h.indexer.Put(healthCheckValue, healthCheckMH); err != nil {
return fmt.Errorf("cannot write to valuestore: %s", err)
}
rval, present, err := h.indexer.Get(healthCheckMH)
if err != nil {
return fmt.Errorf("cannot get value from valuestore: %s", err)
}
if !present {
return errors.New("health-check value not found in valuestore")
}
if !healthCheckValue.Equal(rval[0]) {
return errors.New("value stored does not match value retrieved from valuestore")
}
if err = h.indexer.Remove(healthCheckValue, healthCheckMH); err != nil {
return fmt.Errorf("unable to remove value from valuestore: %s", err)
}
return nil
}