Skip to content

Commit ffe4a95

Browse files
frncmxkiku-jw
authored andcommitted
p2p, swarm: fix node up races by granular locking (ethereum#18976)
* swarm/network: DRY out repeated giga comment I not necessarily agree with the way we wait for event propagation. But I truly disagree with having duplicated giga comments. * p2p/simulations: encapsulate Node.Up field so we avoid data races The Node.Up field was accessed concurrently without "proper" locking. There was a lock on Network and that was used sometimes to access the field. Other times the locking was missed and we had a data race. For example: ethereum#18464 The case above was solved, but there were still intermittent/hard to reproduce races. So let's solve the issue permanently. resolves: ethersphere/swarm#1146 * p2p/simulations: fix unmarshal of simulations.Node Making Node.Up field private in 13292ee broke TestHTTPNetwork and TestHTTPSnapshot. Because the default UnmarshalJSON does not handle unexported fields. Important: The fix is partial and not proper to my taste. But I cut scope as I think the fix may require a change to the current serialization format. New ticket: ethersphere/swarm#1177 * p2p/simulations: Add a sanity test case for Node.Config UnmarshalJSON * p2p/simulations: revert back to defer Unlock() pattern for Network It's a good patten to call `defer Unlock()` right after `Lock()` so (new) error cases won't miss to unlock. Let's get back to that pattern. The patten was abandoned in 85a79b3, while fixing a data race. That data race does not exist anymore, since the Node.Up field got hidden behind its own lock. * p2p/simulations: consistent naming for test providers Node.UnmarshalJSON * p2p/simulations: remove JSON annotation from private fields of Node As unexported fields are not serialized. * p2p/simulations: fix deadlock in Network.GetRandomDownNode() Problem: GetRandomDownNode() locks -> getDownNodeIDs() -> GetNodes() tries to lock -> deadlock On Network type, unexported functions must assume that `net.lock` is already acquired and should not call exported functions which might try to lock again. * p2p/simulations: ensure method conformity for Network Connect* methods were moved to p2p/simulations.Network from swarm/network/simulation. However these new methods did not follow the pattern of Network methods, i.e., all exported method locks the whole Network either for read or write. * p2p/simulations: fix deadlock during network shutdown `TestDiscoveryPersistenceSimulationSimAdapter` often got into deadlock. The execution was stuck on two locks, i.e, `Kademlia.lock` and `p2p/simulations.Network.lock`. Usually the test got stuck once in each 20 executions with high confidence. `Kademlia` was stuck in `Kademlia.EachAddr()` and `Network` in `Network.Stop()`. Solution: in `Network.Stop()` `net.lock` must be released before calling `node.Stop()` as stopping a node (somehow - I did not find the exact code path) causes `Network.InitConn()` to be called from `Kademlia.SuggestPeer()` and that blocks on `net.lock`. Related ticket: ethersphere/swarm#1223 * swarm/state: simplify if statement in DBStore.Put() * p2p/simulations: remove faulty godoc from private function The comment started with the wrong method name. The method is simple and self explanatory. Also, it's private. => Let's just remove the comment.
1 parent 300a420 commit ffe4a95

File tree

12 files changed

+323
-123
lines changed

12 files changed

+323
-123
lines changed

p2p/simulations/connect.go

+32-11
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,9 @@ var (
3232
// It is useful when constructing a chain network topology
3333
// when Network adds and removes nodes dynamically.
3434
func (net *Network) ConnectToLastNode(id enode.ID) (err error) {
35+
net.lock.Lock()
36+
defer net.lock.Unlock()
37+
3538
ids := net.getUpNodeIDs()
3639
l := len(ids)
3740
if l < 2 {
@@ -41,29 +44,35 @@ func (net *Network) ConnectToLastNode(id enode.ID) (err error) {
4144
if last == id {
4245
last = ids[l-2]
4346
}
44-
return net.connect(last, id)
47+
return net.connectNotConnected(last, id)
4548
}
4649

4750
// ConnectToRandomNode connects the node with provided NodeID
4851
// to a random node that is up.
4952
func (net *Network) ConnectToRandomNode(id enode.ID) (err error) {
50-
selected := net.GetRandomUpNode(id)
53+
net.lock.Lock()
54+
defer net.lock.Unlock()
55+
56+
selected := net.getRandomUpNode(id)
5157
if selected == nil {
5258
return ErrNodeNotFound
5359
}
54-
return net.connect(selected.ID(), id)
60+
return net.connectNotConnected(selected.ID(), id)
5561
}
5662

5763
// ConnectNodesFull connects all nodes one to another.
5864
// It provides a complete connectivity in the network
5965
// which should be rarely needed.
6066
func (net *Network) ConnectNodesFull(ids []enode.ID) (err error) {
67+
net.lock.Lock()
68+
defer net.lock.Unlock()
69+
6170
if ids == nil {
6271
ids = net.getUpNodeIDs()
6372
}
6473
for i, lid := range ids {
6574
for _, rid := range ids[i+1:] {
66-
if err = net.connect(lid, rid); err != nil {
75+
if err = net.connectNotConnected(lid, rid); err != nil {
6776
return err
6877
}
6978
}
@@ -74,12 +83,19 @@ func (net *Network) ConnectNodesFull(ids []enode.ID) (err error) {
7483
// ConnectNodesChain connects all nodes in a chain topology.
7584
// If ids argument is nil, all nodes that are up will be connected.
7685
func (net *Network) ConnectNodesChain(ids []enode.ID) (err error) {
86+
net.lock.Lock()
87+
defer net.lock.Unlock()
88+
89+
return net.connectNodesChain(ids)
90+
}
91+
92+
func (net *Network) connectNodesChain(ids []enode.ID) (err error) {
7793
if ids == nil {
7894
ids = net.getUpNodeIDs()
7995
}
8096
l := len(ids)
8197
for i := 0; i < l-1; i++ {
82-
if err := net.connect(ids[i], ids[i+1]); err != nil {
98+
if err := net.connectNotConnected(ids[i], ids[i+1]); err != nil {
8399
return err
84100
}
85101
}
@@ -89,39 +105,44 @@ func (net *Network) ConnectNodesChain(ids []enode.ID) (err error) {
89105
// ConnectNodesRing connects all nodes in a ring topology.
90106
// If ids argument is nil, all nodes that are up will be connected.
91107
func (net *Network) ConnectNodesRing(ids []enode.ID) (err error) {
108+
net.lock.Lock()
109+
defer net.lock.Unlock()
110+
92111
if ids == nil {
93112
ids = net.getUpNodeIDs()
94113
}
95114
l := len(ids)
96115
if l < 2 {
97116
return nil
98117
}
99-
if err := net.ConnectNodesChain(ids); err != nil {
118+
if err := net.connectNodesChain(ids); err != nil {
100119
return err
101120
}
102-
return net.connect(ids[l-1], ids[0])
121+
return net.connectNotConnected(ids[l-1], ids[0])
103122
}
104123

105124
// ConnectNodesStar connects all nodes into a star topology
106125
// If ids argument is nil, all nodes that are up will be connected.
107126
func (net *Network) ConnectNodesStar(ids []enode.ID, center enode.ID) (err error) {
127+
net.lock.Lock()
128+
defer net.lock.Unlock()
129+
108130
if ids == nil {
109131
ids = net.getUpNodeIDs()
110132
}
111133
for _, id := range ids {
112134
if center == id {
113135
continue
114136
}
115-
if err := net.connect(center, id); err != nil {
137+
if err := net.connectNotConnected(center, id); err != nil {
116138
return err
117139
}
118140
}
119141
return nil
120142
}
121143

122-
// connect connects two nodes but ignores already connected error.
123-
func (net *Network) connect(oneID, otherID enode.ID) error {
124-
return ignoreAlreadyConnectedErr(net.Connect(oneID, otherID))
144+
func (net *Network) connectNotConnected(oneID, otherID enode.ID) error {
145+
return ignoreAlreadyConnectedErr(net.connect(oneID, otherID))
125146
}
126147

127148
func ignoreAlreadyConnectedErr(err error) error {

p2p/simulations/events.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -100,7 +100,7 @@ func ControlEvent(v interface{}) *Event {
100100
func (e *Event) String() string {
101101
switch e.Type {
102102
case EventTypeNode:
103-
return fmt.Sprintf("<node-event> id: %s up: %t", e.Node.ID().TerminalString(), e.Node.Up)
103+
return fmt.Sprintf("<node-event> id: %s up: %t", e.Node.ID().TerminalString(), e.Node.Up())
104104
case EventTypeConn:
105105
return fmt.Sprintf("<conn-event> nodes: %s->%s up: %t", e.Conn.One.TerminalString(), e.Conn.Other.TerminalString(), e.Conn.Up)
106106
case EventTypeMsg:

p2p/simulations/http_test.go

+10-8
Original file line numberDiff line numberDiff line change
@@ -421,14 +421,15 @@ type expectEvents struct {
421421
}
422422

423423
func (t *expectEvents) nodeEvent(id string, up bool) *Event {
424+
node := Node{
425+
Config: &adapters.NodeConfig{
426+
ID: enode.HexID(id),
427+
},
428+
up: up,
429+
}
424430
return &Event{
425431
Type: EventTypeNode,
426-
Node: &Node{
427-
Config: &adapters.NodeConfig{
428-
ID: enode.HexID(id),
429-
},
430-
Up: up,
431-
},
432+
Node: &node,
432433
}
433434
}
434435

@@ -480,6 +481,7 @@ loop:
480481
}
481482

482483
func (t *expectEvents) expect(events ...*Event) {
484+
t.Helper()
483485
timeout := time.After(10 * time.Second)
484486
i := 0
485487
for {
@@ -501,8 +503,8 @@ func (t *expectEvents) expect(events ...*Event) {
501503
if event.Node.ID() != expected.Node.ID() {
502504
t.Fatalf("expected node event %d to have id %q, got %q", i, expected.Node.ID().TerminalString(), event.Node.ID().TerminalString())
503505
}
504-
if event.Node.Up != expected.Node.Up {
505-
t.Fatalf("expected node event %d to have up=%t, got up=%t", i, expected.Node.Up, event.Node.Up)
506+
if event.Node.Up() != expected.Node.Up() {
507+
t.Fatalf("expected node event %d to have up=%t, got up=%t", i, expected.Node.Up(), event.Node.Up())
506508
}
507509

508510
case EventTypeConn:

p2p/simulations/mocker_test.go

+5-4
Original file line numberDiff line numberDiff line change
@@ -90,15 +90,12 @@ func TestMocker(t *testing.T) {
9090
for {
9191
select {
9292
case event := <-events:
93-
//if the event is a node Up event only
94-
if event.Node != nil && event.Node.Up {
93+
if isNodeUp(event) {
9594
//add the correspondent node ID to the map
9695
nodemap[event.Node.Config.ID] = true
9796
//this means all nodes got a nodeUp event, so we can continue the test
9897
if len(nodemap) == nodeCount {
9998
nodesComplete = true
100-
//wait for 3s as the mocker will need time to connect the nodes
101-
//time.Sleep( 3 *time.Second)
10299
}
103100
} else if event.Conn != nil && nodesComplete {
104101
connCount += 1
@@ -169,3 +166,7 @@ func TestMocker(t *testing.T) {
169166
t.Fatalf("Expected empty list of nodes, got: %d", len(nodesInfo))
170167
}
171168
}
169+
170+
func isNodeUp(event *Event) bool {
171+
return event.Node != nil && event.Node.Up()
172+
}

0 commit comments

Comments
 (0)