-
Notifications
You must be signed in to change notification settings - Fork 13
/
subscriber.go
251 lines (215 loc) · 6.22 KB
/
subscriber.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
// Copyright (c) 2014-2017 Bitmark Inc.
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.
package peer
import (
"bytes"
"encoding/hex"
"github.com/bitmark-inc/bitmarkd/fault"
"github.com/bitmark-inc/bitmarkd/messagebus"
"github.com/bitmark-inc/bitmarkd/mode"
"github.com/bitmark-inc/bitmarkd/util"
"github.com/bitmark-inc/bitmarkd/zmqutil"
"github.com/bitmark-inc/logger"
zmq "github.com/pebbe/zmq4"
"time"
)
const (
subscriberSignal = "inproc://bitmark-subscriber-signal"
)
type subscriber struct {
log *logger.L
chain string
push *zmq.Socket
pull *zmq.Socket
clients []*zmqutil.Client
dynamicStart int
}
// initialise the subscriber
func (sbsc *subscriber) initialise(privateKey []byte, publicKey []byte, subscribe []Connection, dynamicEnabled bool) error {
log := logger.New("subscriber")
if nil == log {
return fault.ErrInvalidLoggerChannel
}
sbsc.chain = mode.ChainName()
sbsc.log = log
log.Info("initialising…")
// validate connection count
staticCount := len(subscribe) // can be zero
if 0 == staticCount && !dynamicEnabled {
log.Error("zero static connections and dynamic is disabled")
return fault.ErrNoConnectionsAvailable
}
// signalling channel
err := error(nil)
sbsc.push, sbsc.pull, err = zmqutil.NewSignalPair(subscriberSignal)
if nil != err {
return err
}
// all sockets
sbsc.clients = make([]*zmqutil.Client, staticCount+offsetCount)
sbsc.dynamicStart = staticCount // index of first dynamic socket
globalData.subscriberClients = sbsc.clients
// error for goto fail
errX := error(nil)
// initially connect all static sockets
for i, c := range subscribe {
address, err := util.NewConnection(c.Address)
if nil != err {
log.Errorf("client[%d]=address: %q error: %v", i, c.Address, err)
errX = err
goto fail
}
serverPublicKey, err := hex.DecodeString(c.PublicKey)
if nil != err {
log.Errorf("client[%d]=public: %q error: %v", i, c.PublicKey, err)
errX = err
goto fail
}
// prevent connection to self
if bytes.Equal(publicKey, serverPublicKey) {
errX = fault.ErrConnectingToSelfForbidden
log.Errorf("client[%d]=public: %q error: %v", i, c.PublicKey, errX)
goto fail
}
client, err := zmqutil.NewClient(zmq.SUB, privateKey, publicKey, 0)
if nil != err {
log.Errorf("client[%d]=%q error: %v", i, c.Address, err)
errX = err
goto fail
}
sbsc.clients[i] = client
err = client.Connect(address, serverPublicKey, sbsc.chain)
if nil != err {
log.Errorf("connect[%d]=%q error: %v", i, c.Address, err)
errX = err
goto fail
}
log.Infof("public key: %x at: %q", serverPublicKey, c.Address)
}
// just create sockets for dynamic clients
for i := sbsc.dynamicStart; i < len(sbsc.clients); i += 1 {
client, err := zmqutil.NewClient(zmq.SUB, privateKey, publicKey, 0)
if nil != err {
log.Errorf("client[%d] error: %v", i, err)
errX = err
goto fail
}
sbsc.clients[i] = client
}
return nil
// error handling
fail:
zmqutil.CloseClients(sbsc.clients)
return errX
}
// subscriber main loop
func (sbsc *subscriber) Run(args interface{}, shutdown <-chan struct{}) {
log := sbsc.log
log.Info("starting…")
queue := messagebus.Bus.Subscriber.Chan()
go func() {
expiryRegister := make(map[*zmq.Socket]time.Time)
checkAt := time.Now().Add(heartbeatTimeout)
poller := zmqutil.NewPoller()
for _, client := range sbsc.clients {
socket := client.BeginPolling(poller, zmq.POLLIN)
if nil != socket {
expiryRegister[socket] = checkAt
}
}
poller.Add(sbsc.pull, zmq.POLLIN)
loop:
for {
log.Info("waiting…")
//polled, _ := poller.Poll(-1)
polled, _ := poller.Poll(heartbeatTimeout)
now := time.Now()
expiresAt := now.Add(heartbeatTimeout)
if now.After(checkAt) {
checkAt = expiresAt
for s, expires := range expiryRegister {
if now.After(expires) {
client := zmqutil.ClientFromSocket(s)
if nil == client { // this socket has been closed
delete(expiryRegister, s)
} else if client.IsConnected() {
log.Warnf("reconnecting to: %q", client)
skt, err := client.ReconnectReturningSocket()
if nil != err {
log.Errorf("reconnect error: %s", err)
} else {
delete(expiryRegister, s)
// note this new entry may or may not be rescanned by range in this loop
// since it will have future time it will not be immediately deleted
expiryRegister[skt] = expiresAt
}
} else {
expiryRegister[s] = expiresAt
}
} else if expires.Before(checkAt) {
checkAt = expires
}
}
}
for _, p := range polled {
switch s := p.Socket; s {
case sbsc.pull:
data, err := s.RecvMessageBytes(0)
if nil != err {
log.Errorf("pull receive error: %v", err)
break loop
}
switch string(data[0]) {
case "connect":
command := string(data[1])
publicKey := data[2]
broadcasts := data[3]
connectToPublisher(sbsc.log, sbsc.chain, sbsc.clients, sbsc.dynamicStart, command, publicKey, broadcasts)
default:
break loop
}
default:
data, err := s.RecvMessageBytes(0)
if nil != err {
log.Errorf("receive error: %v", err)
} else {
dataLength := len(data)
if dataLength < 3 {
log.Warnf("with too few data: %d items", dataLength)
continue loop
}
theChain := string(data[0])
if theChain != sbsc.chain {
log.Errorf("invalid chain: actual: %q expect: %s", theChain, sbsc.chain)
continue loop
}
processSubscription(sbsc.log, string(data[1]), data[2:])
}
expiryRegister[s] = expiresAt
}
}
}
log.Info("shutting down…")
sbsc.pull.Close()
zmqutil.CloseClients(sbsc.clients)
log.Info("stopped")
}()
loop:
for {
log.Info("select…")
select {
// wait for shutdown
case <-shutdown:
break loop
// wait for message
case item := <-queue:
sbsc.log.Infof("received: %s public key: %x connect: %x", item.Command, item.Parameters[0], item.Parameters[1])
sbsc.push.SendMessage("connect", item.Command, item.Parameters[0], item.Parameters[1])
}
}
log.Info("initiate shutdown")
sbsc.push.SendMessage("stop")
sbsc.push.Close()
log.Info("finished")
}