-
Notifications
You must be signed in to change notification settings - Fork 210
/
worker.go
201 lines (180 loc) · 4.96 KB
/
worker.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
package sync
import (
"github.com/spacemeshos/go-spacemesh/common/types"
"github.com/spacemeshos/go-spacemesh/log"
"github.com/spacemeshos/go-spacemesh/p2p"
"github.com/spacemeshos/go-spacemesh/p2p/p2pcrypto"
"github.com/spacemeshos/go-spacemesh/p2p/server"
"sync"
"sync/atomic"
"time"
)
type requestFactory func(com networker, peer p2p.Peer) (chan interface{}, error)
type batchRequestFactory func(com networker, peer p2p.Peer, id []types.Hash32) (chan []item, error)
type networker interface {
GetPeers() []p2p.Peer
SendRequest(msgType server.MessageType, payload []byte, address p2pcrypto.PublicKey, resHandler func(msg []byte)) error
GetTimeout() time.Duration
GetExit() chan struct{}
log.Logger
}
type peers interface {
GetPeers() []p2p.Peer
Close()
}
type worker struct {
*sync.Once
work func()
workCount *int32
output chan interface{}
log.Logger
}
func (w *worker) Work() {
w.Debug("worker work")
w.work()
atomic.AddInt32(w.workCount, -1)
w.Debug("worker done")
if atomic.LoadInt32(w.workCount) == 0 { //close once everyone is finished
w.Debug("worker teardown")
w.Do(func() { close(w.output) })
}
}
func (w *worker) Clone() *worker {
return &worker{Logger: w.Logger, Once: w.Once, workCount: w.workCount, output: w.output, work: w.work}
}
func newPeersWorker(s networker, peers []p2p.Peer, mu *sync.Once, reqFactory requestFactory) worker {
count := int32(1)
numOfpeers := len(peers)
output := make(chan interface{}, numOfpeers)
peerfuncs := []func(){}
wg := sync.WaitGroup{}
wg.Add(len(peers))
lg := s.WithName("peersWrkr")
for _, p := range peers {
peer := p
peerFunc := func() {
defer wg.Done()
lg.Debug("send request Peer: %v", peer)
ch, err := reqFactory(s, peer)
if err != nil {
s.Error("request failed, ", err)
return
}
timeout := time.After(s.GetTimeout())
select {
case <-s.GetExit():
lg.Debug("worker received interrupt")
return
case <-timeout:
lg.Error("request to %v timed out", peer)
return
case v := <-ch:
if v != nil {
lg.Debug("Peer: %v responded", peer)
output <- v
}
}
}
peerfuncs = append(peerfuncs, peerFunc)
}
wrkFunc := func() {
for _, p := range peerfuncs {
go p()
}
wg.Wait()
}
return worker{Logger: lg, Once: mu, workCount: &count, output: output, work: wrkFunc}
}
func newNeighborhoodWorker(s networker, count int, reqFactory requestFactory) worker {
output := make(chan interface{}, count)
acount := int32(count)
mu := &sync.Once{}
lg := s.WithName("HoodWrker")
workFunc := func() {
peers := s.GetPeers()
for _, p := range peers {
peer := p
lg.Info("send request Peer: %v", peer)
ch, _ := reqFactory(s, peer)
timeout := time.After(s.GetTimeout())
select {
case <-s.GetExit():
lg.Debug("worker received interrupt")
return
case <-timeout:
lg.Error("request to %v timed out", peer)
case v := <-ch:
if v != nil {
lg.Info("Peer: %v responded ", peer)
lg.Debug("Peer: %v response was %v", v)
output <- v
return
}
}
}
}
return worker{Logger: lg, Once: mu, workCount: &acount, output: output, work: workFunc}
}
func newFetchWorker(s networker, count int, reqFactory batchRequestFactory, idsChan chan []types.Hash32, name string) worker {
output := make(chan interface{}, 10)
acount := int32(count)
mu := &sync.Once{}
lg := s.WithName("FetchWrker")
workFunc := func() {
for ids := range idsChan {
if ids == nil {
lg.Info("close fetch worker ")
return
}
leftToFetch := toMap(ids)
var fetched []item
next:
for _, p := range s.GetPeers() {
peer := p
remainingItems := toSlice(leftToFetch)
idsStr := concatShortIds(remainingItems)
lg.Info("send %s fetch request to Peer: %v ids: %v", name, peer.String(), idsStr)
ch, _ := reqFactory(s, peer, remainingItems)
timeout := time.After(s.GetTimeout())
select {
case <-s.GetExit():
lg.Debug("worker received interrupt")
return
case <-timeout:
lg.Error("fetch %s request to %v on %v timed out %s", name, peer.String(), idsStr)
case v := <-ch:
if v != nil && len(v) > 0 {
lg.Info("Peer: %v responded to fetch %s request %s", peer.String(), name, idsStr)
// remove ids from leftToFetch add to fetched
for _, itm := range v {
fetched = append(fetched, itm)
delete(leftToFetch, itm.Hash32())
}
//if no more left to fetch
if len(leftToFetch) == 0 {
break next
}
}
lg.Info("next peer")
}
}
//finished pass results to chan
output <- fetchJob{ids: ids, items: fetched}
}
}
return worker{Logger: lg, Once: mu, workCount: &acount, output: output, work: workFunc}
}
func toMap(ids []types.Hash32) map[types.Hash32]struct{} {
mp := make(map[types.Hash32]struct{}, len(ids))
for _, id := range ids {
mp[id] = struct{}{}
}
return mp
}
func toSlice(mp map[types.Hash32]struct{}) []types.Hash32 {
sl := make([]types.Hash32, 0, len(mp))
for id := range mp {
sl = append(sl, id)
}
return sl
}