1
1
package canonicallog
2
2
3
3
import (
4
+ "fmt"
5
+ "math/rand"
4
6
"net"
7
+ "strings"
5
8
6
9
logging "github.com/ipfs/go-log/v2"
7
10
"github.com/libp2p/go-libp2p-core/peer"
@@ -15,7 +18,7 @@ var log = logging.WithSkip(logging.Logger("canonical-log"), 1)
15
18
// Protocols should use this to identify a misbehaving peer to allow the end
16
19
// user to easily identify these nodes across protocols and libp2p.
17
20
func LogMisbehavingPeer (p peer.ID , peerAddr multiaddr.Multiaddr , component string , err error , msg string ) {
18
- log .Warnf ("CANONICAL_MISBEHAVING_PEER: peer=%s addr=%s component=%s err=%v msg=%s " , p , peerAddr .String (), component , err , msg )
21
+ log .Warnf ("CANONICAL_MISBEHAVING_PEER: peer=%s addr=%s component=%s err=%q msg=%q " , p , peerAddr .String (), component , err , msg )
19
22
}
20
23
21
24
// LogMisbehavingPeerNetAddr is the canonical way to log a misbehaving peer.
@@ -24,9 +27,30 @@ func LogMisbehavingPeer(p peer.ID, peerAddr multiaddr.Multiaddr, component strin
24
27
func LogMisbehavingPeerNetAddr (p peer.ID , peerAddr net.Addr , component string , originalErr error , msg string ) {
25
28
ma , err := manet .FromNetAddr (peerAddr )
26
29
if err != nil {
27
- log .Warnf ("CANONICAL_MISBEHAVING_PEER: peer=%s netAddr =%s component=%s err=%v msg=%s " , p , peerAddr .String (), component , originalErr , msg )
30
+ log .Warnf ("CANONICAL_MISBEHAVING_PEER: peer=%s net_addr =%s component=%s err=%q msg=%q " , p , peerAddr .String (), component , originalErr , msg )
28
31
return
29
32
}
30
33
31
- log .Warnf ("CANONICAL_MISBEHAVING_PEER: peer=%s addr=%s component=%s err=%v msg=%s" , p , ma , component , originalErr , msg )
34
+ LogMisbehavingPeer (p , ma , component , originalErr , msg )
35
+ }
36
+
37
+ // LogPeerStatus logs any useful information about a peer. It takes in a sample
38
+ // rate and will only log one in every sampleRate messages (randomly). This is
39
+ // useful in surfacing events that are normal in isolation, but may be abnormal
40
+ // in large quantities. For example, a successful connection from an IP address
41
+ // is normal. 10,000 connections from that same IP address is not normal. libp2p
42
+ // itself does nothing besides emitting this log. Hook this up to another tool
43
+ // like fail2ban to action on the log.
44
+ func LogPeerStatus (sampleRate int , p peer.ID , peerAddr multiaddr.Multiaddr , keyVals ... string ) {
45
+ if rand .Intn (sampleRate ) == 0 {
46
+ keyValsStr := strings.Builder {}
47
+ for i , kOrV := range keyVals {
48
+ if i % 2 == 0 {
49
+ fmt .Fprintf (& keyValsStr , " %v=" , kOrV )
50
+ } else {
51
+ fmt .Fprintf (& keyValsStr , "%q" , kOrV )
52
+ }
53
+ }
54
+ log .Infof ("CANONICAL_PEER_STATUS: peer=%s addr=%s sample_rate=%v%s" , p , peerAddr .String (), sampleRate , keyValsStr .String ())
55
+ }
32
56
}
0 commit comments