-
-
Notifications
You must be signed in to change notification settings - Fork 544
/
azureiothub.go
487 lines (388 loc) · 12.8 KB
/
azureiothub.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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
package azureiothub
import (
"bytes"
"context"
"encoding/base64"
"fmt"
"strings"
"sync"
"time"
"github.com/Azure/azure-amqp-common-go/cbs"
"github.com/Azure/azure-amqp-common-go/sas"
servicebus "github.com/Azure/azure-service-bus-go"
"github.com/gofrs/uuid"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
"pack.ag/amqp"
"github.com/brocaar/chirpstack-api/go/v3/gw"
"github.com/brocaar/chirpstack-network-server/v3/internal/backend/gateway"
"github.com/brocaar/chirpstack-network-server/v3/internal/backend/gateway/marshaler"
"github.com/brocaar/chirpstack-network-server/v3/internal/config"
"github.com/brocaar/chirpstack-network-server/v3/internal/helpers"
"github.com/brocaar/lorawan"
)
// Backend implement an Azure IoT Hub backend.
type Backend struct {
sync.RWMutex
ctx context.Context
cancel context.CancelFunc
closed bool
uplinkFrameChan chan gw.UplinkFrame
gatewayStatsChan chan gw.GatewayStats
downlinkTxAckChan chan gw.DownlinkTXAck
gatewayMarshaler map[lorawan.EUI64]marshaler.Type
downMode string
queueName string
ns *servicebus.Namespace
queue *servicebus.Queue
c2dConn *amqp.Client
c2dTokenProvider *sas.TokenProvider
c2dTokenExpiration time.Duration
c2dHost string
c2dSession *amqp.Session
c2dSender *amqp.Sender
}
// NewBackend creates a new Backend.
func NewBackend(c config.Config) (gateway.Gateway, error) {
var err error
var ok bool
conf := c.NetworkServer.Gateway.Backend.AzureIoTHub
b := Backend{
uplinkFrameChan: make(chan gw.UplinkFrame),
gatewayStatsChan: make(chan gw.GatewayStats),
downlinkTxAckChan: make(chan gw.DownlinkTXAck),
gatewayMarshaler: make(map[lorawan.EUI64]marshaler.Type),
downMode: c.NetworkServer.Gateway.Backend.MultiDownlinkFeature,
ctx: context.Background(),
c2dTokenExpiration: time.Hour,
}
b.ctx, b.cancel = context.WithCancel(b.ctx)
// setup uplink
connProperties, err := parseConnectionString(conf.EventsConnectionString)
if err != nil {
return nil, errors.Wrap(err, "parse connection-string error")
}
b.queueName, ok = connProperties["EntityPath"]
if !ok {
return nil, errors.New("connection-string does not contain 'EntityPath', please use the queue connection-string")
}
log.Info("gateway/azure_iot_hub: setting up service-bus namespace")
b.ns, err = servicebus.NewNamespace(
servicebus.NamespaceWithConnectionString(conf.EventsConnectionString),
)
if err != nil {
return nil, errors.Wrap(err, "new namespace error")
}
b.queue, err = b.ns.NewQueue(b.queueName)
if err != nil {
return nil, errors.Wrap(err, "new queue client error")
}
go func() {
log.WithField("queue", b.queueName).Info("gateway/azure_iot_hub: starting queue consumer")
for {
if b.closed {
break
}
if err := b.queue.Receive(b.ctx, servicebus.HandlerFunc(b.eventHandler)); err != nil {
log.WithError(err).Error("gateway/azure_iot_hub: receive from queue error, trying to recover")
err := b.queue.Close(b.ctx)
if err != nil {
log.WithError(err).Error("gateway/azure_iot_hub: close queue error")
}
b.queue, err = b.ns.NewQueue(b.queueName)
if err != nil {
log.WithError(err).Error("gateway/azure_iot_hub: new queue client error")
}
}
}
}()
// setup Cloud2Device messaging
connProperties, err = parseConnectionString(conf.CommandsConnectionString)
if err != nil {
return nil, errors.Wrap(err, "parse connection-string error")
}
b.c2dHost, ok = connProperties["HostName"]
if !ok {
return nil, errors.New("connection-string does not contain 'HostName'")
}
if sak, ok := connProperties["SharedAccessKey"]; ok {
bb, err := base64.StdEncoding.DecodeString(sak)
if err != nil {
return nil, errors.Wrap(err, "decode SharedAccessKey error")
}
b.c2dTokenProvider, err = sas.NewTokenProvider(sas.TokenProviderWithKey(connProperties["SharedAccessKeyName"], string(bb)))
if err != nil {
return nil, errors.Wrap(err, "new sas token error")
}
} else {
return nil, errors.New("connection-string does not contain 'SharedAccessKey'")
}
if err := b.c2dNewSessionAndLink(); err != nil {
return nil, errors.Wrap(err, "new c2d session and link error")
}
return &b, nil
}
func (b *Backend) SendTXPacket(pl gw.DownlinkFrame) error {
gatewayID := helpers.GetGatewayID(&pl)
downID := helpers.GetDownlinkID(&pl)
t := b.getGatewayMarshaler(gatewayID)
if err := gateway.UpdateDownlinkFrame(b.downMode, &pl); err != nil {
return errors.Wrap(err, "set downlink compatibility mode error")
}
bb, err := marshaler.MarshalDownlinkFrame(t, pl)
if err != nil {
return errors.Wrap(err, "marshal downlink frame error")
}
return b.publishCommand(log.Fields{
"downlink_id": downID,
}, gatewayID, "down", bb)
}
func (b *Backend) SendGatewayConfigPacket(pl gw.GatewayConfiguration) error {
gatewayID := helpers.GetGatewayID(&pl)
t := b.getGatewayMarshaler(gatewayID)
bb, err := marshaler.MarshalGatewayConfiguration(t, pl)
if err != nil {
return errors.Wrap(err, "marshal gateway configuration error")
}
return b.publishCommand(log.Fields{}, gatewayID, "config", bb)
}
func (b *Backend) RXPacketChan() chan gw.UplinkFrame {
return b.uplinkFrameChan
}
func (b *Backend) StatsPacketChan() chan gw.GatewayStats {
return b.gatewayStatsChan
}
func (b *Backend) DownlinkTXAckChan() chan gw.DownlinkTXAck {
return b.downlinkTxAckChan
}
func (b *Backend) Close() error {
log.Info("gateway/azure_iot_hub: closing backend")
b.cancel()
close(b.uplinkFrameChan)
close(b.gatewayStatsChan)
close(b.downlinkTxAckChan)
b.queue.Close(context.Background())
return nil
}
func (b *Backend) setGatewayMarshaler(gatewayID lorawan.EUI64, t marshaler.Type) {
b.Lock()
defer b.Unlock()
b.gatewayMarshaler[gatewayID] = t
}
func (b *Backend) getGatewayMarshaler(gatewayID lorawan.EUI64) marshaler.Type {
b.RLock()
defer b.RUnlock()
return b.gatewayMarshaler[gatewayID]
}
func (b *Backend) eventHandler(ctx context.Context, msg *servicebus.Message) error {
if err := b.handleEventMessage(msg); err != nil {
log.WithError(err).Error("gateway/azure_iot_hub: handle event error")
}
return msg.Complete(ctx)
}
func (b *Backend) handleEventMessage(msg *servicebus.Message) error {
var gatewayID lorawan.EUI64
// decode gateway id
if gwID, ok := msg.UserProperties["iothub-connection-device-id"]; ok {
gwIDStr, ok := gwID.(string)
if !ok {
return fmt.Errorf("expected 'iothub-connection-device-id' to be a string, got: %T", gwID)
}
if err := gatewayID.UnmarshalText([]byte(gwIDStr)); err != nil {
return errors.Wrap(err, "unmarshal gateway id error")
}
} else {
return errors.New("'iothub-connection-device-id' missing in UserProperties")
}
var event string
var err error
// get event type
if _, ok := msg.UserProperties["up"]; ok {
event = "up"
}
if _, ok := msg.UserProperties["ack"]; ok {
event = "ack"
}
if _, ok := msg.UserProperties["stats"]; ok {
event = "stats"
}
azureEventCounter(event).Inc()
switch event {
case "up":
err = b.handleUplinkFrame(gatewayID, msg.Data)
case "stats":
err = b.handleGatewayStats(gatewayID, msg.Data)
case "ack":
err = b.handleDownlinkTXAck(gatewayID, msg.Data)
default:
log.WithFields(log.Fields{
"gateway_id": gatewayID,
"event": event,
}).Warning("gateway/azure_iot_hub: unexpected gateway event received")
}
if err != nil {
log.WithError(err).WithFields(log.Fields{
"gateway_id": gatewayID,
"event": event,
"data_base64": base64.StdEncoding.EncodeToString(msg.Data),
}).Error("gateway/azure_iot_hub: handle gateway event error")
}
return nil
}
func (b *Backend) handleUplinkFrame(gatewayID lorawan.EUI64, data []byte) error {
var uplinkFrame gw.UplinkFrame
t, err := marshaler.UnmarshalUplinkFrame(data, &uplinkFrame)
if err != nil {
return errors.Wrap(err, "unmarshal error")
}
b.setGatewayMarshaler(gatewayID, t)
if uplinkFrame.RxInfo == nil {
return errors.New("rx_info must not be nil")
}
if uplinkFrame.TxInfo == nil {
return errors.New("tx_info must not be nil")
}
// make sure that the registered gateway is not using a different gateway_id
// than the ID used during the registration in Cloud IoT Core.
if !bytes.Equal(uplinkFrame.RxInfo.GatewayId, gatewayID[:]) {
return errors.New("gateway_id is not equal to expected gateway_id")
}
uplinkID := helpers.GetUplinkID(uplinkFrame.RxInfo)
log.WithFields(log.Fields{
"gateway_id": gatewayID,
"uplink_id": uplinkID,
}).Info("gateway/azure_iot_hub: uplink received from gateway")
b.uplinkFrameChan <- uplinkFrame
return nil
}
func (b *Backend) handleGatewayStats(gatewayID lorawan.EUI64, data []byte) error {
var gatewayStats gw.GatewayStats
t, err := marshaler.UnmarshalGatewayStats(data, &gatewayStats)
if err != nil {
return errors.Wrap(err, "unmarshal error")
}
b.setGatewayMarshaler(gatewayID, t)
// make sure that the registered gateway is not using a different gateway_id
// than the ID used during the registration in Cloud IoT Core.
if !bytes.Equal(gatewayStats.GatewayId, gatewayID[:]) {
return errors.New("gateway_id is not equal to expected gateway_id")
}
statsID := helpers.GetStatsID(&gatewayStats)
log.WithFields(log.Fields{
"gateway_id": gatewayID,
"stats_id": statsID,
}).Info("gateway/azure_iot_hub: stats received from gateway")
b.gatewayStatsChan <- gatewayStats
return nil
}
func (b *Backend) handleDownlinkTXAck(gatewayID lorawan.EUI64, data []byte) error {
var ack gw.DownlinkTXAck
t, err := marshaler.UnmarshalDownlinkTXAck(data, &ack)
if err != nil {
return errors.Wrap(err, "unmarshal error")
}
b.setGatewayMarshaler(gatewayID, t)
// make sure that the registered gateway is not using a different gateway_id
// than the ID used during the registration in Cloud IoT Core.
if !bytes.Equal(ack.GatewayId, gatewayID[:]) {
return errors.New("gateway_id is not equal to expected gateway_id")
}
downlinkID := helpers.GetDownlinkID(&ack)
log.WithFields(log.Fields{
"gateway_id": gatewayID,
"downlink_id": downlinkID,
}).Info("gateway/azure_iot_hub: ack received from gateway")
b.downlinkTxAckChan <- ack
return nil
}
func (b *Backend) publishCommand(fields log.Fields, gatewayID lorawan.EUI64, command string, data []byte) error {
msgID, err := uuid.NewV4()
if err != nil {
return errors.Wrap(err, "new uuid error")
}
msg := amqp.NewMessage(data)
msg.Properties = &amqp.MessageProperties{
MessageID: msgID.String(),
To: fmt.Sprintf("/devices/%s/messages/devicebound", gatewayID),
}
msg.ApplicationProperties = map[string]interface{}{
"iothub-ack": "none",
"command": command,
}
retries := 0
for {
select {
case <-b.ctx.Done():
return nil
default:
// aquire a read-lock to make sure an other go routine isn't
// recovering / re-connecting in case of an error.
b.RLock()
err = b.c2dSender.Send(b.ctx, msg)
b.RUnlock()
if err == nil {
fields["gateway_id"] = gatewayID
fields["command"] = command
log.WithFields(fields).Info("gateway/azure_iot_hub: gateway command published")
azureCommandCounter(command).Inc()
return nil
}
if retries > 0 {
log.WithError(err).Error("gateway/azure_iot_hub: send cloud to device message error")
}
// try to recover connection
if err := b.c2dRecover(); err != nil {
log.WithError(err).Error("gateway/azure_iot_hub: recover iot hub connection error, retry in 2 seconds")
time.Sleep(2 * time.Second)
}
}
retries++
}
}
func (b *Backend) c2dNewSessionAndLink() error {
var err error
log.WithField("host", b.c2dHost).Info("gateway/azure_iot_hub: connecting to iot hub")
b.c2dConn, err = amqp.Dial(fmt.Sprintf("amqps://%s", b.c2dHost), amqp.ConnSASLAnonymous())
if err != nil {
return errors.Wrap(err, "amqp dial error")
}
log.Info("gateway/azure_iot_hub: negotiating amqp cbs claim")
if err := cbs.NegotiateClaim(b.ctx, b.c2dHost, b.c2dConn, b.c2dTokenProvider); err != nil {
return errors.Wrap(err, "cbs negotiate claim error")
}
b.c2dSession, err = b.c2dConn.NewSession()
if err != nil {
return errors.Wrap(err, "new amqp session error")
}
b.c2dSender, err = b.c2dSession.NewSender(
amqp.LinkTargetAddress("/messages/devicebound"),
)
if err != nil {
return errors.Wrap(err, "new amqp sender error")
}
return nil
}
func (b *Backend) c2dRecover() error {
// aquire a write-lock to make sure that no Send calls are made during the
// connection recovery
b.Lock()
defer b.Unlock()
azureConnectionRecoverCounter().Inc()
log.Info("gateway/azure_iot_hub: re-connecting to iot hub")
_ = b.c2dSender.Close(b.ctx)
_ = b.c2dSession.Close(b.ctx)
_ = b.c2dConn.Close()
return b.c2dNewSessionAndLink()
}
func parseConnectionString(str string) (map[string]string, error) {
out := make(map[string]string)
pairs := strings.Split(str, ";")
for _, pair := range pairs {
kv := strings.SplitN(pair, "=", 2)
if len(kv) != 2 {
return nil, fmt.Errorf("expected two items in: %+v", kv)
}
out[kv[0]] = kv[1]
}
return out, nil
}