forked from brocaar/chirpstack-application-server
/
postgresql.go
616 lines (536 loc) · 14.8 KB
/
postgresql.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
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
package postgresql
import (
"context"
"database/sql"
"embed"
"encoding/json"
"fmt"
"net/http"
"time"
"github.com/gofrs/uuid"
"github.com/golang-migrate/migrate/v4"
"github.com/golang-migrate/migrate/v4/database/postgres"
"github.com/golang-migrate/migrate/v4/source/httpfs"
"github.com/golang/protobuf/ptypes"
"github.com/jmoiron/sqlx"
"github.com/lib/pq/hstore"
"github.com/mmcloughlin/geohash"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
pb "github.com/brocaar/chirpstack-api/go/v3/as/integration"
"github.com/brocaar/lorawan"
"github.com/kamicuu/chirpstack-application-server/internal/config"
"github.com/kamicuu/chirpstack-application-server/internal/integration/marshaler"
"github.com/kamicuu/chirpstack-application-server/internal/integration/models"
"github.com/kamicuu/chirpstack-application-server/internal/logging"
)
// Migrations
//go:embed migrations/*
var migrations embed.FS
// Integration implements a PostgreSQL integration.
type Integration struct {
db *sqlx.DB
marshaler marshaler.Type
}
// New creates a new PostgreSQL integration.
func New(m marshaler.Type, conf config.IntegrationPostgreSQLConfig) (*Integration, error) {
// In case of (binary) Protobuf marshaler, use JSON Protobuf mapping as we
// write the output to a jsonb field.
if m == marshaler.Protobuf {
m = marshaler.ProtobufJSON
}
log.Info("integration/postgresql: connecting to PostgreSQL database")
d, err := sqlx.Open("postgres", conf.DSN)
if err != nil {
return nil, errors.Wrap(err, "integration/postgresql: PostgreSQL connection error")
}
for {
if err := d.Ping(); err != nil {
log.WithError(err).Warning("integration/postgresql: ping PostgreSQL database error, will retry in 2s")
time.Sleep(2 * time.Second)
} else {
break
}
}
d.SetMaxOpenConns(conf.MaxOpenConnections)
d.SetMaxIdleConns(conf.MaxIdleConnections)
if err := MigrateUp(d); err != nil {
return nil, err
}
return &Integration{
db: d,
marshaler: m,
}, nil
}
// Close closes the integration.
func (i *Integration) Close() error {
if err := i.db.Close(); err != nil {
return errors.Wrap(err, "close database error")
}
return nil
}
// MigrateUp configure postgres-integration migration down
func MigrateUp(db *sqlx.DB) error {
log.Info("integration/postgresql: applying PostgreSQL schema migrations")
driver, err := postgres.WithInstance(db.DB, &postgres.Config{})
if err != nil {
return fmt.Errorf("integration/postgresql: migrate postgres driver error: %w", err)
}
src, err := httpfs.New(http.FS(migrations), "/migrations")
if err != nil {
return fmt.Errorf("new httpfs error: %w", err)
}
m, err := migrate.NewWithInstance("httpfs", src, "postgres", driver)
if err != nil {
return fmt.Errorf("integration/postgresql: new migrate instance error: %w", err)
}
oldVersion, _, _ := m.Version()
if err := m.Up(); err != nil && err != migrate.ErrNoChange {
return fmt.Errorf("integration/postgresql: migrate up error: %w", err)
}
newVersion, _, _ := m.Version()
if oldVersion != newVersion {
log.WithFields(log.Fields{
"from_version": oldVersion,
"to_version": newVersion,
}).Info("integration/postgresql: applied database migrations")
}
return nil
}
// MigrateDown configure postgres-integration migration down
func MigrateDown(db *sqlx.DB) error {
log.Info("integration/postgresql: reverting PostgreSQL schema migrations")
driver, err := postgres.WithInstance(db.DB, &postgres.Config{})
if err != nil {
return fmt.Errorf("integration/postgresql: migrate postgres driver error: %w", err)
}
src, err := httpfs.New(http.FS(migrations), "/migrations")
if err != nil {
return fmt.Errorf("new httpfs error: %w", err)
}
m, err := migrate.NewWithInstance("httpfs", src, "postgres", driver)
if err != nil {
return fmt.Errorf("integration/postgresql: new migrate instance error: %w", err)
}
oldVersion, _, _ := m.Version()
if err := m.Down(); err != nil && err != migrate.ErrNoChange {
return fmt.Errorf("integration/postgresql: migrate down error: %w", err)
}
newVersion, _, _ := m.Version()
if oldVersion != newVersion {
log.WithFields(log.Fields{
"from_version": oldVersion,
"to_version": newVersion,
}).Info("integration/postgresql: applied database migrations")
}
return nil
}
// HandleUplinkEvent writes an UplinkEvent into the database.
func (i *Integration) HandleUplinkEvent(ctx context.Context, _ models.Integration, vars map[string]string, pl pb.UplinkEvent) error {
// use an UUID here so that we can later refactor this for correlation
id, err := uuid.NewV4()
if err != nil {
return errors.Wrap(err, "new uuid error")
}
// get the rxTime either using the system-time or using one of the
// gateway provided timestamps.
rxTime := time.Now()
for _, rxInfo := range pl.RxInfo {
if rxInfo.Time != nil {
ts, err := ptypes.Timestamp(rxInfo.Time)
if err != nil {
return errors.Wrap(err, "protobuf timestamp error")
}
rxTime = ts
}
}
var rxInfoItems []json.RawMessage
for ii := range pl.GetRxInfo() {
b, err := marshaler.Marshal(i.marshaler, pl.RxInfo[ii])
if err != nil {
return errors.Wrap(err, "marshal rx_info error")
}
rxInfoItems = append(rxInfoItems, json.RawMessage(b))
}
rxInfoB, err := json.Marshal(rxInfoItems)
if err != nil {
return errors.Wrap(err, "marshal json error")
}
txInfoB := []byte("null")
if txInfo := pl.GetTxInfo(); txInfo != nil {
txInfoB, err = marshaler.Marshal(i.marshaler, txInfo)
if err != nil {
return errors.Wrap(err, "marshal tx_info error")
}
}
objectJSON := json.RawMessage("null")
if pl.ObjectJson != "" {
objectJSON = json.RawMessage(pl.ObjectJson)
}
var devEUI lorawan.EUI64
var devAddr lorawan.DevAddr
copy(devEUI[:], pl.DevEui)
copy(devAddr[:], pl.DevAddr)
_, err = i.db.Exec(`
insert into device_up (
id,
received_at,
dev_eui,
device_name,
application_id,
application_name,
frequency,
dr,
adr,
f_cnt,
f_port,
data,
rx_info,
tx_info,
object,
tags,
confirmed_uplink,
dev_addr
) values ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18)`,
id,
rxTime,
devEUI,
pl.DeviceName,
pl.ApplicationId,
pl.ApplicationName,
// TODO: deprecate this field, as it is part of tx_info.
pl.GetTxInfo().GetFrequency(),
pl.Dr,
pl.Adr,
pl.FCnt,
pl.FPort,
pl.Data,
json.RawMessage(rxInfoB),
json.RawMessage(txInfoB),
objectJSON,
tagsToHstore(pl.Tags),
pl.ConfirmedUplink,
devAddr[:],
)
if err != nil {
return errors.Wrap(err, "insert error")
}
log.WithFields(log.Fields{
"event": "up",
"dev_eui": devEUI,
"ctx_id": ctx.Value(logging.ContextIDKey),
}).Info("integration/postgresql: event stored")
return nil
}
// HandleStatusEvent writes a StatusEvent into the database.
func (i *Integration) HandleStatusEvent(ctx context.Context, _ models.Integration, vars map[string]string, pl pb.StatusEvent) error {
// use an UUID here so that we can later refactor this for correlation
id, err := uuid.NewV4()
if err != nil {
return errors.Wrap(err, "new uuid error")
}
// TODO: refactor to use gateway provided time once RXInfo is available
// and timestamp is provided by gateway.
rxTime := time.Now()
var devEUI lorawan.EUI64
copy(devEUI[:], pl.DevEui)
_, err = i.db.Exec(`
insert into device_status (
id,
received_at,
dev_eui,
device_name,
application_id,
application_name,
margin,
external_power_source,
battery_level_unavailable,
battery_level,
tags
) values ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)`,
id,
rxTime,
devEUI,
pl.DeviceName,
pl.ApplicationId,
pl.ApplicationName,
pl.Margin,
pl.ExternalPowerSource,
pl.BatteryLevelUnavailable,
pl.BatteryLevel,
tagsToHstore(pl.Tags),
)
if err != nil {
return errors.Wrap(err, "insert error")
}
log.WithFields(log.Fields{
"event": "status",
"dev_eui": devEUI,
"ctx_id": ctx.Value(logging.ContextIDKey),
}).Info("integration/postgresql: event stored")
return nil
}
// HandleJoinEvent writes a JoinEvent into the database.
func (i *Integration) HandleJoinEvent(ctx context.Context, _ models.Integration, vars map[string]string, pl pb.JoinEvent) error {
// use an UUID here so that we can later refactor this for correlation
id, err := uuid.NewV4()
if err != nil {
return errors.Wrap(err, "new uuid error")
}
// get the rxTime either using the system-time or using one of the
// gateway provided timestamps.
rxTime := time.Now()
for _, rxInfo := range pl.RxInfo {
if rxInfo.Time != nil {
ts, err := ptypes.Timestamp(rxInfo.Time)
if err != nil {
return errors.Wrap(err, "protobuf timestamp error")
}
rxTime = ts
}
}
var devEUI lorawan.EUI64
var devAddr lorawan.DevAddr
copy(devEUI[:], pl.DevEui)
copy(devAddr[:], pl.DevAddr)
_, err = i.db.Exec(`
insert into device_join (
id,
received_at,
dev_eui,
device_name,
application_id,
application_name,
dev_addr,
tags
) values ($1, $2, $3, $4, $5, $6, $7, $8)`,
id,
rxTime,
devEUI,
pl.DeviceName,
pl.ApplicationId,
pl.ApplicationName,
devAddr[:],
tagsToHstore(pl.Tags),
)
if err != nil {
return errors.Wrap(err, "insert error")
}
log.WithFields(log.Fields{
"event": "join",
"dev_eui": devEUI,
"ctx_id": ctx.Value(logging.ContextIDKey),
}).Info("integration/postgresql: event stored")
return nil
}
// HandleAckEvent writes an AckEvent into the database.
func (i *Integration) HandleAckEvent(ctx context.Context, _ models.Integration, vars map[string]string, pl pb.AckEvent) error {
// use an UUID here so that we can later refactor this for correlation
id, err := uuid.NewV4()
if err != nil {
return errors.Wrap(err, "new uuid error")
}
var devEUI lorawan.EUI64
copy(devEUI[:], pl.DevEui)
// TODO: refactor to use gateway provided time once RXInfo is available
// and timestamp is provided by gateway.
rxTime := time.Now()
_, err = i.db.Exec(`
insert into device_ack (
id,
received_at,
dev_eui,
device_name,
application_id,
application_name,
acknowledged,
f_cnt,
tags
) values ($1, $2, $3, $4, $5, $6, $7, $8, $9)`,
id,
rxTime,
devEUI,
pl.DeviceName,
pl.ApplicationId,
pl.ApplicationName,
pl.Acknowledged,
pl.FCnt,
tagsToHstore(pl.Tags),
)
if err != nil {
return errors.Wrap(err, "insert error")
}
log.WithFields(log.Fields{
"event": "ack",
"dev_eui": devEUI,
"ctx_id": ctx.Value(logging.ContextIDKey),
}).Info("integration/postgresql: event stored")
return nil
}
// HandleErrorEvent writes an ErrorEvent into the database.
func (i *Integration) HandleErrorEvent(ctx context.Context, _ models.Integration, vars map[string]string, pl pb.ErrorEvent) error {
// use an UUID here so that we can later refactor this for correlation
id, err := uuid.NewV4()
if err != nil {
return errors.Wrap(err, "new uuid error")
}
var devEUI lorawan.EUI64
copy(devEUI[:], pl.DevEui)
// TODO: refactor to use gateway provided time once RXInfo is available
// and timestamp is provided by gateway.
rxTime := time.Now()
_, err = i.db.Exec(`
insert into device_error (
id,
received_at,
dev_eui,
device_name,
application_id,
application_name,
type,
error,
f_cnt,
tags
) values ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)`,
id,
rxTime,
devEUI,
pl.DeviceName,
pl.ApplicationId,
pl.ApplicationName,
pl.Type.String(),
pl.Error,
pl.FCnt,
tagsToHstore(pl.Tags),
)
if err != nil {
return errors.Wrap(err, "insert error")
}
log.WithFields(log.Fields{
"event": "error",
"dev_eui": devEUI,
"ctx_id": ctx.Value(logging.ContextIDKey),
}).Info("integration/postgresql: event stored")
return nil
}
// HandleLocationEvent writes a LocationEvent into the database.
func (i *Integration) HandleLocationEvent(ctx context.Context, _ models.Integration, vars map[string]string, pl pb.LocationEvent) error {
// use an UUID here so that we can later refactor this for correlation
id, err := uuid.NewV4()
if err != nil {
return errors.Wrap(err, "new uuid error")
}
var devEUI lorawan.EUI64
copy(devEUI[:], pl.DevEui)
// TODO: refactor to use gateway provided time once RXInfo is available
// and timestamp is provided by gateway.
rxTime := time.Now()
_, err = i.db.Exec(`
insert into device_location (
id,
received_at,
dev_eui,
device_name,
application_id,
application_name,
altitude,
latitude,
longitude,
geohash,
accuracy,
tags
) values ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12)`,
id,
rxTime,
devEUI,
pl.DeviceName,
pl.ApplicationId,
pl.ApplicationName,
pl.GetLocation().GetAltitude(),
pl.GetLocation().GetLatitude(),
pl.GetLocation().GetLongitude(),
geohash.Encode(pl.GetLocation().GetLatitude(), pl.GetLocation().GetLongitude()),
0,
tagsToHstore(pl.Tags),
)
if err != nil {
return errors.Wrap(err, "insert error")
}
log.WithFields(log.Fields{
"event": "location",
"dev_eui": devEUI,
"ctx_id": ctx.Value(logging.ContextIDKey),
}).Info("integration/postgresql: event stored")
return nil
}
// HandleTxAckEvent writes TX events into postgres database.
func (i *Integration) HandleTxAckEvent(ctx context.Context, _ models.Integration, vars map[string]string, pl pb.TxAckEvent) error {
// use an UUID here so that we can later refactor this for correlation
id, err := uuid.NewV4()
if err != nil {
return errors.Wrap(err, "new uuid error")
}
var devEUI, gatewayID lorawan.EUI64
copy(devEUI[:], pl.DevEui)
copy(gatewayID[:], pl.GatewayId)
txInfoB := []byte("null")
if txInfo := pl.GetTxInfo(); txInfo != nil {
txInfoB, err = marshaler.Marshal(i.marshaler, txInfo)
if err != nil {
return errors.Wrap(err, "marshal tx_info error")
}
}
rxTime := time.Now()
_, err = i.db.Exec(`
insert into device_txack (
id,
received_at,
dev_eui,
device_name,
application_id,
application_name,
gateway_id,
f_cnt,
tags,
tx_info
) values ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)`,
id,
rxTime,
devEUI,
pl.DeviceName,
pl.ApplicationId,
pl.ApplicationName,
gatewayID,
pl.FCnt,
tagsToHstore(pl.Tags),
json.RawMessage(txInfoB),
)
if err != nil {
return errors.Wrap(err, "insert error")
}
log.WithFields(log.Fields{
"event": "txack",
"dev_eui": devEUI,
"gateway_id": gatewayID,
"ctx_id": ctx.Value(logging.ContextIDKey),
}).Info("integration/postgresql: event stored")
return nil
}
// HandleIntegrationEvent is not implemented.
// TODO: implement this + schema migrations for the PostgreSQL database!
func (i *Integration) HandleIntegrationEvent(ctx context.Context, _ models.Integration, vars map[string]string, pl pb.IntegrationEvent) error {
return nil
}
// DataDownChan return nil.
func (i *Integration) DataDownChan() chan models.DataDownPayload {
return nil
}
func tagsToHstore(tags map[string]string) hstore.Hstore {
out := hstore.Hstore{
Map: make(map[string]sql.NullString),
}
for k, v := range tags {
out.Map[k] = sql.NullString{String: v, Valid: true}
}
return out
}