-
Notifications
You must be signed in to change notification settings - Fork 1
/
pull.go
329 lines (272 loc) · 9.12 KB
/
pull.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
/*
Copyright IBM Corp. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package algo
import (
"sync"
"sync/atomic"
"time"
"github.com/hyperledger/fabric/gossip/util"
)
/* PullEngine is an object that performs pull-based gossip, and maintains an internal state of items
identified by string numbers.
The protocol is as follows:
1) The Initiator sends a Hello message with a specific NONCE to a set of remote peers.
2) Each remote peer responds with a digest of its messages and returns that NONCE.
3) The initiator checks the validity of the NONCEs received, aggregates the digests,
and crafts a request containing specific item ids it wants to receive from each remote peer and then
sends each request to its corresponding peer.
4) Each peer sends back the response containing the items requested, if it still holds them and the NONCE.
Other peer Initiator
O <-------- Hello <NONCE> ------------------------- O
/|\ --------- Digest <[3,5,8, 10...], NONCE> --------> /|\
| <-------- Request <[3,8], NONCE> ----------------- |
/ \ --------- Response <[item3, item8], NONCE>-------> / \
*/
const (
DefDigestWaitTime = 1000 * time.Millisecond
DefRequestWaitTime = 1500 * time.Millisecond
DefResponseWaitTime = 2000 * time.Millisecond
)
// DigestFilter filters digests to be sent to a remote peer that
// sent a hello or a request, based on its messages's context
type DigestFilter func(context interface{}) func(digestItem string) bool
// PullAdapter is needed by the PullEngine in order to
// send messages to the remote PullEngine instances.
// The PullEngine expects to be invoked with
// OnHello, OnDigest, OnReq, OnRes when the respective message arrives
// from a remote PullEngine
type PullAdapter interface {
// SelectPeers returns a slice of peers which the engine will initiate the protocol with
SelectPeers() []string
// Hello sends a hello message to initiate the protocol
// and returns an NONCE that is expected to be returned
// in the digest message.
Hello(dest string, nonce uint64)
// SendDigest sends a digest to a remote PullEngine.
// The context parameter specifies the remote engine to send to.
SendDigest(digest []string, nonce uint64, context interface{})
// SendReq sends an array of items to a certain remote PullEngine identified
// by a string
SendReq(dest string, items []string, nonce uint64)
// SendRes sends an array of items to a remote PullEngine identified by a context.
SendRes(items []string, context interface{}, nonce uint64)
}
// PullEngine is the component that actually invokes the pull algorithm
// with the help of the PullAdapter
type PullEngine struct {
PullAdapter
stopFlag int32
state *util.Set
item2owners map[string][]string
peers2nonces map[string]uint64
nonces2peers map[uint64]string
acceptingDigests int32
acceptingResponses int32
lock sync.Mutex
outgoingNONCES *util.Set
incomingNONCES *util.Set
digFilter DigestFilter
digestWaitTime time.Duration
requestWaitTime time.Duration
responseWaitTime time.Duration
}
// PullEngineConfig is the configuration required to initialize a new pull engine
type PullEngineConfig struct {
DigestWaitTime time.Duration
RequestWaitTime time.Duration
ResponseWaitTime time.Duration
}
// NewPullEngineWithFilter creates an instance of a PullEngine with a certain sleep time
// between pull initiations, and uses the given filters when sending digests and responses
func NewPullEngineWithFilter(participant PullAdapter, sleepTime time.Duration, df DigestFilter,
config PullEngineConfig) *PullEngine {
engine := &PullEngine{
PullAdapter: participant,
stopFlag: int32(0),
state: util.NewSet(),
item2owners: make(map[string][]string),
peers2nonces: make(map[string]uint64),
nonces2peers: make(map[uint64]string),
acceptingDigests: int32(0),
acceptingResponses: int32(0),
incomingNONCES: util.NewSet(),
outgoingNONCES: util.NewSet(),
digFilter: df,
digestWaitTime: config.DigestWaitTime,
requestWaitTime: config.RequestWaitTime,
responseWaitTime: config.ResponseWaitTime,
}
go func() {
for !engine.toDie() {
time.Sleep(sleepTime)
if engine.toDie() {
return
}
engine.initiatePull()
}
}()
return engine
}
// NewPullEngine creates an instance of a PullEngine with a certain sleep time
// between pull initiations
func NewPullEngine(participant PullAdapter, sleepTime time.Duration, config PullEngineConfig) *PullEngine {
acceptAllFilter := func(_ interface{}) func(string) bool {
return func(_ string) bool {
return true
}
}
return NewPullEngineWithFilter(participant, sleepTime, acceptAllFilter, config)
}
func (engine *PullEngine) toDie() bool {
return atomic.LoadInt32(&(engine.stopFlag)) == int32(1)
}
func (engine *PullEngine) acceptResponses() {
atomic.StoreInt32(&(engine.acceptingResponses), int32(1))
}
func (engine *PullEngine) isAcceptingResponses() bool {
return atomic.LoadInt32(&(engine.acceptingResponses)) == int32(1)
}
func (engine *PullEngine) acceptDigests() {
atomic.StoreInt32(&(engine.acceptingDigests), int32(1))
}
func (engine *PullEngine) isAcceptingDigests() bool {
return atomic.LoadInt32(&(engine.acceptingDigests)) == int32(1)
}
func (engine *PullEngine) ignoreDigests() {
atomic.StoreInt32(&(engine.acceptingDigests), int32(0))
}
// Stop stops the engine
func (engine *PullEngine) Stop() {
atomic.StoreInt32(&(engine.stopFlag), int32(1))
}
func (engine *PullEngine) initiatePull() {
engine.lock.Lock()
defer engine.lock.Unlock()
engine.acceptDigests()
for _, peer := range engine.SelectPeers() {
nonce := engine.newNONCE()
engine.outgoingNONCES.Add(nonce)
engine.nonces2peers[nonce] = peer
engine.peers2nonces[peer] = nonce
engine.Hello(peer, nonce)
}
time.AfterFunc(engine.digestWaitTime, func() {
engine.processIncomingDigests()
})
}
func (engine *PullEngine) processIncomingDigests() {
engine.ignoreDigests()
engine.lock.Lock()
defer engine.lock.Unlock()
requestMapping := make(map[string][]string)
for n, sources := range engine.item2owners {
// select a random source
source := sources[util.RandomInt(len(sources))]
if _, exists := requestMapping[source]; !exists {
requestMapping[source] = make([]string, 0)
}
// append the number to that source
requestMapping[source] = append(requestMapping[source], n)
}
engine.acceptResponses()
for dest, seqsToReq := range requestMapping {
engine.SendReq(dest, seqsToReq, engine.peers2nonces[dest])
}
time.AfterFunc(engine.responseWaitTime, engine.endPull)
}
func (engine *PullEngine) endPull() {
engine.lock.Lock()
defer engine.lock.Unlock()
atomic.StoreInt32(&(engine.acceptingResponses), int32(0))
engine.outgoingNONCES.Clear()
engine.item2owners = make(map[string][]string)
engine.peers2nonces = make(map[string]uint64)
engine.nonces2peers = make(map[uint64]string)
}
// OnDigest notifies the engine that a digest has arrived
func (engine *PullEngine) OnDigest(digest []string, nonce uint64, context interface{}) {
if !engine.isAcceptingDigests() || !engine.outgoingNONCES.Exists(nonce) {
return
}
engine.lock.Lock()
defer engine.lock.Unlock()
for _, n := range digest {
if engine.state.Exists(n) {
continue
}
if _, exists := engine.item2owners[n]; !exists {
engine.item2owners[n] = make([]string, 0)
}
engine.item2owners[n] = append(engine.item2owners[n], engine.nonces2peers[nonce])
}
}
// Add adds items to the state
func (engine *PullEngine) Add(seqs ...string) {
for _, seq := range seqs {
engine.state.Add(seq)
}
}
// Remove removes items from the state
func (engine *PullEngine) Remove(seqs ...string) {
for _, seq := range seqs {
engine.state.Remove(seq)
}
}
// OnHello notifies the engine a hello has arrived
func (engine *PullEngine) OnHello(nonce uint64, context interface{}) {
engine.incomingNONCES.Add(nonce)
time.AfterFunc(engine.requestWaitTime, func() {
engine.incomingNONCES.Remove(nonce)
})
a := engine.state.ToArray()
var digest []string
filter := engine.digFilter(context)
for _, item := range a {
dig := item.(string)
if !filter(dig) {
continue
}
digest = append(digest, dig)
}
if len(digest) == 0 {
return
}
engine.SendDigest(digest, nonce, context)
}
// OnReq notifies the engine a request has arrived
func (engine *PullEngine) OnReq(items []string, nonce uint64, context interface{}) {
if !engine.incomingNONCES.Exists(nonce) {
return
}
engine.lock.Lock()
defer engine.lock.Unlock()
filter := engine.digFilter(context)
var items2Send []string
for _, item := range items {
if engine.state.Exists(item) && filter(item) {
items2Send = append(items2Send, item)
}
}
if len(items2Send) == 0 {
return
}
go engine.SendRes(items2Send, context, nonce)
}
// OnRes notifies the engine a response has arrived
func (engine *PullEngine) OnRes(items []string, nonce uint64) {
if !engine.outgoingNONCES.Exists(nonce) || !engine.isAcceptingResponses() {
return
}
engine.Add(items...)
}
func (engine *PullEngine) newNONCE() uint64 {
n := uint64(0)
for {
n = util.RandomUInt64()
if !engine.outgoingNONCES.Exists(n) {
return n
}
}
}