Skip to content

Commit 965407f

Browse files
authored
Merge pull request bnb-chain#3709 from fjl/p2p-context-log
p2p, p2p/discover, p2p/nat: rework logging using context keys
2 parents dc0a006 + 96ae35e commit 965407f

14 files changed

Lines changed: 174 additions & 154 deletions

File tree

‎eth/peer.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -280,7 +280,7 @@ func (p *peer) readStatus(network int, status *statusData, genesis common.Hash)
280280
return errResp(ErrDecode, "msg %v: %v", msg, err)
281281
}
282282
if status.GenesisBlock != genesis {
283-
return errResp(ErrGenesisBlockMismatch, "%x (!= %x)", status.GenesisBlock, genesis)
283+
return errResp(ErrGenesisBlockMismatch, "%x (!= %x)", status.GenesisBlock[:8], genesis[:8])
284284
}
285285
if int(status.NetworkId) != network {
286286
return errResp(ErrNetworkIdMismatch, "%d (!= %d)", status.NetworkId, network)

‎eth/protocol_test.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ func testStatusMsgErrors(t *testing.T, protocol int) {
6363
},
6464
{
6565
code: StatusMsg, data: statusData{uint32(protocol), NetworkId, td, currentBlock, common.Hash{3}},
66-
wantError: errResp(ErrGenesisBlockMismatch, "0300000000000000000000000000000000000000000000000000000000000000 (!= %x)", genesis),
66+
wantError: errResp(ErrGenesisBlockMismatch, "0300000000000000 (!= %x)", genesis[:8]),
6767
},
6868
}
6969

‎les/peer.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -367,7 +367,7 @@ func (p *peer) Handshake(td *big.Int, head common.Hash, headNum uint64, genesis
367367
}
368368

369369
if rGenesis != genesis {
370-
return errResp(ErrGenesisBlockMismatch, "%x (!= %x)", rGenesis, genesis)
370+
return errResp(ErrGenesisBlockMismatch, "%x (!= %x)", rGenesis[:8], genesis[:8])
371371
}
372372
if int(rNetwork) != p.network {
373373
return errResp(ErrNetworkIdMismatch, "%d (!= %d)", rNetwork, p.network)

‎p2p/dial.go‎

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -133,7 +133,7 @@ func (s *dialstate) newTasks(nRunning int, peers map[discover.NodeID]*Peer, now
133133
var newtasks []task
134134
addDial := func(flag connFlag, n *discover.Node) bool {
135135
if err := s.checkDial(n, peers); err != nil {
136-
log.Debug(fmt.Sprintf("skipping dial candidate %x@%v:%d: %v", n.ID[:8], n.IP, n.TCP, err))
136+
log.Trace("Skipping dial candidate", "id", n.ID, "addr", &net.TCPAddr{IP: n.IP, Port: int(n.TCP)}, "err", err)
137137
return false
138138
}
139139
s.dialing[n.ID] = flag
@@ -162,7 +162,7 @@ func (s *dialstate) newTasks(nRunning int, peers map[discover.NodeID]*Peer, now
162162
err := s.checkDial(t.dest, peers)
163163
switch err {
164164
case errNotWhitelisted, errSelf:
165-
log.Debug(fmt.Sprintf("removing static dial candidate %x@%v:%d: %v", t.dest.ID[:8], t.dest.IP, t.dest.TCP, err))
165+
log.Warn("Removing static dial candidate", "id", t.dest.ID, "addr", &net.TCPAddr{IP: t.dest.IP, Port: int(t.dest.TCP)}, "err", err)
166166
delete(s.static, t.dest.ID)
167167
case nil:
168168
s.dialing[id] = t.flags
@@ -266,7 +266,7 @@ func (t *dialTask) Do(srv *Server) {
266266
// The backoff delay resets when the node is found.
267267
func (t *dialTask) resolve(srv *Server) bool {
268268
if srv.ntab == nil {
269-
log.Debug(fmt.Sprintf("can't resolve node %x: discovery is disabled", t.dest.ID[:6]))
269+
log.Debug("Can't resolve node", "id", t.dest.ID, "err", "discovery is disabled")
270270
return false
271271
}
272272
if t.resolveDelay == 0 {
@@ -282,23 +282,22 @@ func (t *dialTask) resolve(srv *Server) bool {
282282
if t.resolveDelay > maxResolveDelay {
283283
t.resolveDelay = maxResolveDelay
284284
}
285-
log.Debug(fmt.Sprintf("resolving node %x failed (new delay: %v)", t.dest.ID[:6], t.resolveDelay))
285+
log.Debug("Resolving node failed", "id", t.dest.ID, "newdelay", t.resolveDelay)
286286
return false
287287
}
288288
// The node was found.
289289
t.resolveDelay = initialResolveDelay
290290
t.dest = resolved
291-
log.Debug(fmt.Sprintf("resolved node %x: %v:%d", t.dest.ID[:6], t.dest.IP, t.dest.TCP))
291+
log.Debug("Resolved node", "id", t.dest.ID, "addr", &net.TCPAddr{IP: t.dest.IP, Port: int(t.dest.TCP)})
292292
return true
293293
}
294294

295295
// dial performs the actual connection attempt.
296296
func (t *dialTask) dial(srv *Server, dest *discover.Node) bool {
297297
addr := &net.TCPAddr{IP: dest.IP, Port: int(dest.TCP)}
298-
log.Debug(fmt.Sprintf("dial tcp %v (%x)", addr, dest.ID[:6]))
299298
fd, err := srv.Dialer.Dial("tcp", addr.String())
300299
if err != nil {
301-
log.Trace(fmt.Sprintf("%v", err))
300+
log.Trace("Dial error", "task", t, "err", err)
302301
return false
303302
}
304303
mfd := newMeteredConn(fd, false)

‎p2p/discover/database.go‎

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,6 @@ import (
2323
"bytes"
2424
"crypto/rand"
2525
"encoding/binary"
26-
"fmt"
2726
"os"
2827
"sync"
2928
"time"
@@ -180,12 +179,11 @@ func (db *nodeDB) storeInt64(key []byte, n int64) error {
180179
func (db *nodeDB) node(id NodeID) *Node {
181180
blob, err := db.lvl.Get(makeKey(id, nodeDBDiscoverRoot), nil)
182181
if err != nil {
183-
log.Trace(fmt.Sprintf("failed to retrieve node %v: %v", id, err))
184182
return nil
185183
}
186184
node := new(Node)
187185
if err := rlp.DecodeBytes(blob, node); err != nil {
188-
log.Warn(fmt.Sprintf("failed to decode node RLP: %v", err))
186+
log.Error("Failed to decode node RLP", "err", err)
189187
return nil
190188
}
191189
node.sha = crypto.Keccak256Hash(node.ID[:])
@@ -233,7 +231,7 @@ func (db *nodeDB) expirer() {
233231
select {
234232
case <-tick:
235233
if err := db.expireNodes(); err != nil {
236-
log.Error(fmt.Sprintf("Failed to expire nodedb items: %v", err))
234+
log.Error("Failed to expire nodedb items", "err", err)
237235
}
238236

239237
case <-db.quit:
@@ -352,7 +350,7 @@ func nextNode(it iterator.Iterator) *Node {
352350
}
353351
var n Node
354352
if err := rlp.DecodeBytes(it.Value(), &n); err != nil {
355-
log.Warn(fmt.Sprintf("invalid node %x: %v", id, err))
353+
log.Warn("Failed to decode node RLP", "id", id, "err", err)
356354
continue
357355
}
358356
return &n

‎p2p/discover/node.go‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -221,6 +221,11 @@ func (n NodeID) GoString() string {
221221
return fmt.Sprintf("discover.HexID(\"%x\")", n[:])
222222
}
223223

224+
// TerminalString returns a shortened hex string for terminal logging.
225+
func (n NodeID) TerminalString() string {
226+
return hex.EncodeToString(n[:8])
227+
}
228+
224229
// HexID converts a hex string to a NodeID.
225230
// The string may be prefixed with 0x.
226231
func HexID(in string) (NodeID, error) {

‎p2p/discover/ntp.go‎

Lines changed: 3 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,6 @@ import (
2323
"fmt"
2424
"net"
2525
"sort"
26-
"strings"
2726
"time"
2827

2928
"github.com/ethereum/go-ethereum/log"
@@ -50,16 +49,10 @@ func checkClockDrift() {
5049
return
5150
}
5251
if drift < -driftThreshold || drift > driftThreshold {
53-
warning := fmt.Sprintf("System clock seems off by %v, which can prevent network connectivity", drift)
54-
howtofix := fmt.Sprintf("Please enable network time synchronisation in system settings")
55-
separator := strings.Repeat("-", len(warning))
56-
57-
log.Warn(fmt.Sprint(separator))
58-
log.Warn(fmt.Sprint(warning))
59-
log.Warn(fmt.Sprint(howtofix))
60-
log.Warn(fmt.Sprint(separator))
52+
log.Warn(fmt.Sprintf("System clock seems off by %v, which can prevent network connectivity", drift))
53+
log.Warn("Please enable network time synchronisation in system settings.")
6154
} else {
62-
log.Debug(fmt.Sprintf("Sanity NTP check reported %v drift, all ok", drift))
55+
log.Debug("NTP sanity check done", "drift", drift)
6356
}
6457
}
6558

‎p2p/discover/table.go‎

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -277,10 +277,10 @@ func (tab *Table) lookup(targetID NodeID, refreshIfEmpty bool) []*Node {
277277
// Bump the failure counter to detect and evacuate non-bonded entries
278278
fails := tab.db.findFails(n.ID) + 1
279279
tab.db.updateFindFails(n.ID, fails)
280-
log.Trace(fmt.Sprintf("Bumping failures for %x: %d", n.ID[:8], fails))
280+
log.Trace("Bumping findnode failure counter", "id", n.ID, "failcount", fails)
281281

282282
if fails >= maxFindnodeFailures {
283-
log.Trace(fmt.Sprintf("Evacuating node %x: %d findnode failures", n.ID[:8], fails))
283+
log.Trace("Too many findnode failures, dropping", "id", n.ID, "failcount", fails)
284284
tab.delete(n)
285285
}
286286
}
@@ -385,13 +385,11 @@ func (tab *Table) doRefresh(done chan struct{}) {
385385
seeds = tab.bondall(append(seeds, tab.nursery...))
386386

387387
if len(seeds) == 0 {
388-
log.Debug(fmt.Sprintf("no seed nodes found"))
388+
log.Debug("No discv4 seed nodes found")
389389
}
390390
for _, n := range seeds {
391-
log.Debug("", "msg", log.Lazy{Fn: func() string {
392-
age := time.Since(tab.db.lastPong(n.ID))
393-
return fmt.Sprintf("seed node (age %v): %v", age, n)
394-
}})
391+
age := log.Lazy{Fn: func() time.Duration { return time.Since(tab.db.lastPong(n.ID)) }}
392+
log.Trace("Found seed node in database", "id", n.ID, "addr", n.addr(), "age", age)
395393
}
396394
tab.mutex.Lock()
397395
tab.stuff(seeds)
@@ -470,7 +468,7 @@ func (tab *Table) bond(pinged bool, id NodeID, addr *net.UDPAddr, tcpPort uint16
470468
var result error
471469
age := time.Since(tab.db.lastPong(id))
472470
if node == nil || fails > 0 || age > nodeDBNodeExpiration {
473-
log.Trace(fmt.Sprintf("Bonding %x: known=%t, fails=%d age=%v", id[:8], node != nil, fails, age))
471+
log.Trace("Starting bonding ping/pong", "id", id, "known", node != nil, "failcount", fails, "age", age)
474472

475473
tab.bondmu.Lock()
476474
w := tab.bonding[id]

‎p2p/discover/udp.go‎

Lines changed: 25 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -147,6 +147,7 @@ func nodeToRPC(n *Node) rpcNode {
147147

148148
type packet interface {
149149
handle(t *udp, from *net.UDPAddr, fromID NodeID, mac []byte) error
150+
name() string
150151
}
151152

152153
type conn interface {
@@ -223,7 +224,7 @@ func ListenUDP(priv *ecdsa.PrivateKey, laddr string, natm nat.Interface, nodeDBP
223224
if err != nil {
224225
return nil, err
225226
}
226-
log.Info(fmt.Sprint("Listening,", tab.self))
227+
log.Debug("UDP listener up", "self", tab.self)
227228
return tab, nil
228229
}
229230

@@ -269,7 +270,7 @@ func (t *udp) close() {
269270
func (t *udp) ping(toid NodeID, toaddr *net.UDPAddr) error {
270271
// TODO: maybe check for ReplyTo field in callback to measure RTT
271272
errc := t.pending(toid, pongPacket, func(interface{}) bool { return true })
272-
t.send(toaddr, pingPacket, ping{
273+
t.send(toaddr, pingPacket, &ping{
273274
Version: Version,
274275
From: t.ourEndpoint,
275276
To: makeEndpoint(toaddr, 0), // TODO: maybe use known TCP port from DB
@@ -293,14 +294,14 @@ func (t *udp) findnode(toid NodeID, toaddr *net.UDPAddr, target NodeID) ([]*Node
293294
nreceived++
294295
n, err := t.nodeFromRPC(toaddr, rn)
295296
if err != nil {
296-
log.Trace(fmt.Sprintf("invalid neighbor node (%v) from %v: %v", rn.IP, toaddr, err))
297+
log.Trace("Invalid neighbor node received", "ip", rn.IP, "addr", toaddr, "err", err)
297298
continue
298299
}
299300
nodes = append(nodes, n)
300301
}
301302
return nreceived >= bucketSize
302303
})
303-
t.send(toaddr, findnodePacket, findnode{
304+
t.send(toaddr, findnodePacket, &findnode{
304305
Target: target,
305306
Expiration: uint64(time.Now().Add(expiration).Unix()),
306307
})
@@ -458,15 +459,13 @@ func init() {
458459
}
459460
}
460461

461-
func (t *udp) send(toaddr *net.UDPAddr, ptype byte, req interface{}) error {
462+
func (t *udp) send(toaddr *net.UDPAddr, ptype byte, req packet) error {
462463
packet, err := encodePacket(t.priv, ptype, req)
463464
if err != nil {
464465
return err
465466
}
466-
log.Trace(fmt.Sprintf(">>> %v %T", toaddr, req))
467-
if _, err = t.conn.WriteToUDP(packet, toaddr); err != nil {
468-
log.Trace(fmt.Sprint("UDP send failed:", err))
469-
}
467+
_, err = t.conn.WriteToUDP(packet, toaddr)
468+
log.Trace(">> "+req.name(), "addr", toaddr, "err", err)
470469
return err
471470
}
472471

@@ -475,13 +474,13 @@ func encodePacket(priv *ecdsa.PrivateKey, ptype byte, req interface{}) ([]byte,
475474
b.Write(headSpace)
476475
b.WriteByte(ptype)
477476
if err := rlp.Encode(b, req); err != nil {
478-
log.Error(fmt.Sprint("error encoding packet:", err))
477+
log.Error("Can't encode discv4 packet", "err", err)
479478
return nil, err
480479
}
481480
packet := b.Bytes()
482481
sig, err := crypto.Sign(crypto.Keccak256(packet[headSize:]), priv)
483482
if err != nil {
484-
log.Error(fmt.Sprint("could not sign packet:", err))
483+
log.Error("Can't sign discv4 packet", "err", err)
485484
return nil, err
486485
}
487486
copy(packet[macSize:], sig)
@@ -503,11 +502,11 @@ func (t *udp) readLoop() {
503502
nbytes, from, err := t.conn.ReadFromUDP(buf)
504503
if netutil.IsTemporaryError(err) {
505504
// Ignore temporary read errors.
506-
log.Debug(fmt.Sprintf("Temporary read error: %v", err))
505+
log.Debug("Temporary UDP read error", "err", err)
507506
continue
508507
} else if err != nil {
509508
// Shut down the loop for permament errors.
510-
log.Debug(fmt.Sprintf("Read error: %v", err))
509+
log.Debug("UDP read error", "err", err)
511510
return
512511
}
513512
t.handlePacket(from, buf[:nbytes])
@@ -517,14 +516,11 @@ func (t *udp) readLoop() {
517516
func (t *udp) handlePacket(from *net.UDPAddr, buf []byte) error {
518517
packet, fromID, hash, err := decodePacket(buf)
519518
if err != nil {
520-
log.Debug(fmt.Sprintf("Bad packet from %v: %v", from, err))
519+
log.Debug("Bad discv4 packet", "addr", from, "err", err)
521520
return err
522521
}
523-
status := "ok"
524-
if err = packet.handle(t, from, fromID, hash); err != nil {
525-
status = err.Error()
526-
}
527-
log.Trace(fmt.Sprintf("<<< %v %T: %s", from, packet, status))
522+
err = packet.handle(t, from, fromID, hash)
523+
log.Trace("<< "+packet.name(), "addr", from, "err", err)
528524
return err
529525
}
530526

@@ -563,7 +559,7 @@ func (req *ping) handle(t *udp, from *net.UDPAddr, fromID NodeID, mac []byte) er
563559
if expired(req.Expiration) {
564560
return errExpired
565561
}
566-
t.send(from, pongPacket, pong{
562+
t.send(from, pongPacket, &pong{
567563
To: makeEndpoint(from, req.From.TCP),
568564
ReplyTok: mac,
569565
Expiration: uint64(time.Now().Add(expiration).Unix()),
@@ -575,6 +571,8 @@ func (req *ping) handle(t *udp, from *net.UDPAddr, fromID NodeID, mac []byte) er
575571
return nil
576572
}
577573

574+
func (req *ping) name() string { return "PING/v4" }
575+
578576
func (req *pong) handle(t *udp, from *net.UDPAddr, fromID NodeID, mac []byte) error {
579577
if expired(req.Expiration) {
580578
return errExpired
@@ -585,6 +583,8 @@ func (req *pong) handle(t *udp, from *net.UDPAddr, fromID NodeID, mac []byte) er
585583
return nil
586584
}
587585

586+
func (req *pong) name() string { return "PONG/v4" }
587+
588588
func (req *findnode) handle(t *udp, from *net.UDPAddr, fromID NodeID, mac []byte) error {
589589
if expired(req.Expiration) {
590590
return errExpired
@@ -613,13 +613,15 @@ func (req *findnode) handle(t *udp, from *net.UDPAddr, fromID NodeID, mac []byte
613613
}
614614
p.Nodes = append(p.Nodes, nodeToRPC(n))
615615
if len(p.Nodes) == maxNeighbors || i == len(closest)-1 {
616-
t.send(from, neighborsPacket, p)
616+
t.send(from, neighborsPacket, &p)
617617
p.Nodes = p.Nodes[:0]
618618
}
619619
}
620620
return nil
621621
}
622622

623+
func (req *findnode) name() string { return "FINDNODE/v4" }
624+
623625
func (req *neighbors) handle(t *udp, from *net.UDPAddr, fromID NodeID, mac []byte) error {
624626
if expired(req.Expiration) {
625627
return errExpired
@@ -630,6 +632,8 @@ func (req *neighbors) handle(t *udp, from *net.UDPAddr, fromID NodeID, mac []byt
630632
return nil
631633
}
632634

635+
func (req *neighbors) name() string { return "NEIGHBORS/v4" }
636+
633637
func expired(ts uint64) bool {
634638
return time.Unix(int64(ts), 0).Before(time.Now())
635639
}

‎p2p/nat/nat.go‎

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -98,16 +98,17 @@ const (
9898
// Map adds a port mapping on m and keeps it alive until c is closed.
9999
// This function is typically invoked in its own goroutine.
100100
func Map(m Interface, c chan struct{}, protocol string, extport, intport int, name string) {
101+
log := log.New("proto", protocol, "extport", extport, "intport", intport, "interface", m)
101102
refresh := time.NewTimer(mapUpdateInterval)
102103
defer func() {
103104
refresh.Stop()
104-
log.Debug(fmt.Sprintf("deleting port mapping: %s %d -> %d (%s) using %s", protocol, extport, intport, name, m))
105+
log.Debug("Deleting port mapping")
105106
m.DeleteMapping(protocol, extport, intport)
106107
}()
107108
if err := m.AddMapping(protocol, extport, intport, name, mapTimeout); err != nil {
108-
log.Debug(fmt.Sprintf("network port %s:%d could not be mapped: %v", protocol, intport, err))
109+
log.Debug("Couldn't add port mapping", "err", err)
109110
} else {
110-
log.Info(fmt.Sprintf("mapped network port %s:%d -> %d (%s) using %s", protocol, extport, intport, name, m))
111+
log.Info("Mapped network port")
111112
}
112113
for {
113114
select {
@@ -116,9 +117,9 @@ func Map(m Interface, c chan struct{}, protocol string, extport, intport int, na
116117
return
117118
}
118119
case <-refresh.C:
119-
log.Trace(fmt.Sprintf("refresh port mapping %s:%d -> %d (%s) using %s", protocol, extport, intport, name, m))
120+
log.Trace("Refreshing port mapping")
120121
if err := m.AddMapping(protocol, extport, intport, name, mapTimeout); err != nil {
121-
log.Debug(fmt.Sprintf("network port %s:%d could not be mapped: %v", protocol, intport, err))
122+
log.Debug("Couldn't add port mapping", "err", err)
122123
}
123124
refresh.Reset(mapUpdateInterval)
124125
}

0 commit comments

Comments
 (0)