-
Notifications
You must be signed in to change notification settings - Fork 1k
/
info.go
67 lines (58 loc) · 1.73 KB
/
info.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
package p2p
import (
"bytes"
"fmt"
"net/http"
"strings"
"github.com/libp2p/go-libp2p/core/host"
"github.com/libp2p/go-libp2p/core/peer"
ma "github.com/multiformats/go-multiaddr"
)
// InfoHandler is a handler to serve /p2p page in metrics.
func (s *Service) InfoHandler(w http.ResponseWriter, _ *http.Request) {
buf := new(bytes.Buffer)
if _, err := fmt.Fprintf(buf, `bootnode=%s
self=%s
%d peers
%v
`,
s.cfg.BootstrapNodeAddr,
s.selfAddresses(),
len(s.host.Network().Peers()),
formatPeers(s.host), // Must be last. Writes one entry per row.
); err != nil {
log.WithError(err).Error("Failed to render p2p info page")
return
}
w.WriteHeader(http.StatusOK)
if _, err := w.Write(buf.Bytes()); err != nil {
log.WithError(err).Error("Failed to render p2p info page")
}
}
// selfAddresses formats the host data into dialable strings, comma separated.
func (s *Service) selfAddresses() string {
var addresses []string
if s.dv5Listener != nil {
addresses = append(addresses, s.dv5Listener.Self().String())
}
for _, addr := range s.host.Addrs() {
addresses = append(addresses, addr.String()+"/p2p/"+s.host.ID().Pretty())
}
return strings.Join(addresses, ",")
}
// Format peer list to dialable addresses, separated by new line.
func formatPeers(h host.Host) string {
var addresses []string
for _, pid := range h.Network().Peers() {
addresses = append(addresses, formatPeer(pid, h.Peerstore().PeerInfo(pid).Addrs))
}
return strings.Join(addresses, "\n")
}
// Format single peer info to dialable addresses, comma separated.
func formatPeer(pid peer.ID, ma []ma.Multiaddr) string {
var addresses []string
for _, a := range ma {
addresses = append(addresses, a.String()+"/p2p/"+pid.Pretty())
}
return strings.Join(addresses, ",")
}