feat: add a public function on peering to get the state
PR #9030
Alvin Reyes committed
Jun 11, 2022 at 03:34 UTC
04651e395d6e7923f592bb2c04db872e00844ad6
1 file changed
+34
-14
peering/peering.go
+34
-14
@@ -4,6 +4,7 @@ import (
4
"context"
5
"errors"
6
"math/rand"
7
+ "strconv"
8
"sync"
9
"time"
10
@@ -32,12 +33,25 @@ const (
33
34
var logger = log.Logger("peering")
35
35
-type state int
36
+type State uint
37
+
38
+func (s State) String() string {
39
+ switch s {
40
+ case StateInit:
41
+ return "init"
42
+ case StateRunning:
43
+ return "running"
44
+ case StateStopped:
45
+ return "stopped"
46
+ default:
47
+ return "unkown peering state: " + strconv.FormatUint(uint64(s), 10)
48
+ }
49
+}
50
51
const (
38
- stateInit state = iota
39
- stateRunning
40
- stateStopped
52
+ StateInit State = iota
53
+ StateRunning
54
+ StateStopped
55
)
56
57
// peerHandler keeps track of all state related to a specific "peering" peer.
@@ -155,7 +169,7 @@ type PeeringService struct {
169
170
mu sync.RWMutex
171
peers map[peer.ID]*peerHandler
158
- state state
172
+ state State
173
}
174
175
// NewPeeringService constructs a new peering service. Peers can be added and
@@ -172,35 +186,41 @@ func (ps *PeeringService) Start() error {
186
defer ps.mu.Unlock()
187
188
switch ps.state {
175
- case stateInit:
189
+ case StateInit:
190
logger.Infow("starting")
177
- case stateRunning:
191
+ case StateRunning:
192
return nil
179
- case stateStopped:
193
+ case StateStopped:
194
return errors.New("already stopped")
195
}
196
ps.host.Network().Notify((*netNotifee)(ps))
183
- ps.state = stateRunning
197
+ ps.state = StateRunning
198
for _, handler := range ps.peers {
199
go handler.startIfDisconnected()
200
}
201
return nil
202
}
203
204
+// GetState get the State of the PeeringService
205
+func (ps *PeeringService) GetState() State {
206
+ ps.mu.RLock()
207
+ defer ps.mu.RUnlock()
208
+ return ps.state
209
+}
210
+
211
// Stop stops the peering service.
212
func (ps *PeeringService) Stop() error {
213
ps.host.Network().StopNotify((*netNotifee)(ps))
193
-
214
ps.mu.Lock()
215
defer ps.mu.Unlock()
216
217
switch ps.state {
198
- case stateInit, stateRunning:
218
+ case StateInit, StateRunning:
219
logger.Infow("stopping")
220
for _, handler := range ps.peers {
221
handler.stop()
222
}
203
- ps.state = stateStopped
223
+ ps.state = StateStopped
224
}
225
return nil
226
}
@@ -231,9 +251,9 @@ func (ps *PeeringService) AddPeer(info peer.AddrInfo) {
251
handler.ctx, handler.cancel = context.WithCancel(context.Background())
252
ps.peers[info.ID] = handler
253
switch ps.state {
234
- case stateRunning:
254
+ case StateRunning:
255
go handler.startIfDisconnected()
236
- case stateStopped:
256
+ case StateStopped:
257
// We still construct everything in this state because
258
// it's easier to reason about. But we should still free
259
// resources.