/
db.go
506 lines (400 loc) · 12.7 KB
/
db.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
package db
import (
"context"
"database/sql"
"errors"
"fmt"
"github.com/ZeljkoBenovic/tsbc/cmd/helpers/flagnames"
"github.com/ZeljkoBenovic/tsbc/sbc/types"
"github.com/hashicorp/go-hclog"
_ "github.com/mattn/go-sqlite3"
"github.com/spf13/viper"
)
type IDB interface {
Close() error
CreateFreshDB() error
SaveSBCInformation() (int64, error)
SaveContainerID(rowID int64, tableName, id string) error
GetSBCParameters(sbcID int64) (types.Sbc, error)
GetSBCIdFromFqdn(sbcFqdn string) int64
GetKamailioInsertID(sbcFqdn string) int64
GetRTPEngineInsertID(sbcFqdn string) int64
GetContainerIDsFromSbcFqdn(sbcFqdn string) []string
GetAllFqdnNames() ([]string, error)
GetLetsEncryptNodeID() (string, error)
RevertLastInsert()
RemoveSbcInfo(sbcFqdn string) error
RemoveLetsEncryptInfo(nodeID string) error
}
var (
ErrPbxIPNotDefined = errors.New("pbx ip address not defined")
ErrSbcFqdnNotDefined = errors.New("sbc fqdn not defined")
ErrRTPEnginePublicIPNotDefined = errors.New("rtp engine public ip address not defined")
)
type db struct {
db *sql.DB
log hclog.Logger
insertID
}
type insertID struct {
kamailio, rtpEngine, sbcInstance int64
}
func NewDB(logger hclog.Logger, dbLocation string) (IDB, error) {
var err error
dbInstance := &db{
log: logger.Named("db"),
}
dbInstance.log.Debug("Creating new SQLite instance")
dbInstance.db, err = sql.Open("sqlite3", dbLocation)
if err != nil {
dbInstance.log.Error("Could not open db connection", "data_source", "sbc.db", "err", err)
return nil, err
}
dbInstance.log.Debug("SQLite instance created")
return dbInstance, nil
}
func (d *db) Close() error {
if err := d.db.Close(); err != nil {
return err
}
return nil
}
func (d *db) GetKamailioInsertID(sbcFqdn string) int64 {
var id int64 = 0
if err := d.db.QueryRowContext(
context.Background(),
"SELECT kamailio_id FROM sbc_info WHERE fqdn=?", sbcFqdn).
Scan(&id); err != nil {
d.log.Error("Could not get kamailio_id", "err", err)
}
if id != 0 {
d.insertID.kamailio = id
}
return d.insertID.kamailio
}
func (d *db) GetRTPEngineInsertID(sbcFqdn string) int64 {
var id int64 = 0
if err := d.db.QueryRowContext(
context.Background(),
"SELECT rtp_engine_id FROM sbc_info WHERE fqdn=?", sbcFqdn).
Scan(&id); err != nil {
d.log.Error("Could not get rtp_engine_id", "err", err)
}
if id != 0 {
d.insertID.rtpEngine = id
}
return d.insertID.rtpEngine
}
func (d *db) GetAllFqdnNames() ([]string, error) {
rows, err := d.db.QueryContext(context.Background(), "SELECT fqdn from sbc_info")
if err != nil {
return nil, fmt.Errorf("could not get fqdns from database: %w", err)
}
resp := make([]string, 0)
fqdn := ""
for rows.Next() {
if err = rows.Scan(&fqdn); err != nil {
d.log.Error("Could not scan fqdn from database", "err", err)
}
resp = append(resp, fqdn)
}
return resp, nil
}
func (d *db) GetLetsEncryptNodeID() (string, error) {
var nodeID = new(string)
// there is always only one letsencrypt node
err := d.db.QueryRowContext(
context.Background(),
"SELECT container_id FROM letsencrypt").
Scan(nodeID)
switch {
case err == sql.ErrNoRows:
d.log.Debug("No rows in letsencrypt container_id")
case err != nil:
return "", err
}
return *nodeID, nil
}
func (d *db) RemoveLetsEncryptInfo(nodeID string) error {
stmt, err := d.db.Prepare("DELETE FROM letsencrypt WHERE container_id = ?")
if err != nil {
return fmt.Errorf("could not prepare delete letsencrypt node: %w", err)
}
_, err = stmt.Exec(nodeID)
if err != nil {
return fmt.Errorf("could not execute delete letsencrypt statement: %w", err)
}
d.log.Debug("LetsEncrypt data deleted")
return nil
}
func (d *db) RemoveSbcInfo(sbcFqdn string) error {
stmt, err := d.db.Prepare(
"SELECT sbc_info.id, k.id, re.id " +
"FROM sbc_info " +
"JOIN kamailio k on k.id = sbc_info.kamailio_id " +
"JOIN rtp_engine re on re.id = sbc_info.rtp_engine_id " +
"WHERE sbc_info.id == (" +
"SELECT id from sbc_info WHERE fqdn = ?)")
if err != nil {
return fmt.Errorf("could not prepare select statement: %w", err)
}
row, err := stmt.Query(sbcFqdn)
if err != nil {
return fmt.Errorf("could not query select statement: %w", err)
}
sbcID := int64(0)
kamID := int64(0)
rtpID := int64(0)
for row.Next() {
if err = row.Scan(&sbcID, &kamID, &rtpID); err != nil {
return fmt.Errorf("could not scan ids into vars: %w", err)
}
}
d.deleteRowWithID("sbc_info", sbcID)
d.deleteRowWithID("kamailio", kamID)
d.deleteRowWithID("rtp_engine", rtpID)
d.log.Debug("Deleted sbc information from database", "sbc_fqdn", sbcFqdn)
return nil
}
func (d *db) GetContainerIDsFromSbcFqdn(sbcFqdn string) []string {
stmt, err := d.db.Prepare(
"SELECT k.container_id, r.container_id " +
"FROM sbc_info " +
"JOIN kamailio k ON k.id = sbc_info.kamailio_id " +
"JOIN rtp_engine r ON sbc_info.rtp_engine_id = r.id " +
"WHERE sbc_info.fqdn = ?")
if err != nil {
d.log.Error("Could not prepare select statement", "err", err)
return nil
}
ids := struct {
kamailio string
rtpEngine string
}{}
if err = stmt.QueryRow(sbcFqdn).Scan(&ids.kamailio, &ids.rtpEngine); err != nil {
d.log.Error("Could not query and scan prepared select statement", "err", err)
return nil
}
_ = stmt.Close()
return []string{ids.kamailio, ids.rtpEngine}
}
func (d *db) SaveContainerID(rowID int64, tableName, containerID string) error {
row, err := d.insertOrUpdateContainerID(rowID, tableName, containerID)
if err != nil {
return fmt.Errorf("could not execute prepared insert statement: %w", err)
}
afRows, _ := row.RowsAffected()
d.log.Debug("Container ID saved", "affected_rows", afRows)
return nil
}
func (d *db) RevertLastInsert() {
d.deleteRowWithID("sbc_info", d.insertID.sbcInstance)
d.deleteRowWithID("kamailio", d.insertID.kamailio)
d.deleteRowWithID("rtp_engine", d.insertID.rtpEngine)
}
func (d *db) SaveSBCInformation() (int64, error) {
var err error
// check if required flags are present
if err = checkForRequiredFlags(); err != nil {
d.log.Error("Required flags check failed", "err", err)
return -1, err
}
// store kamailio config and save insert id
if err = d.storeKamailioData(); err != nil {
d.log.Error("Could not store kamailio data", "err", err)
return -1, err
}
// store rtp engine config and save insert id
if err = d.storeRTPEngineData(); err != nil {
d.log.Error("Could not store rtp engine data", "err", err)
return -1, err
}
// store sbc info using the kamailio and rtp engine ids
if err = d.storeSbcInfo(); err != nil {
d.log.Error("Could not store sbc configuration information")
return -1, err
}
return d.insertID.sbcInstance, nil
}
func (d *db) storeSbcInfo() error {
stmt, err := d.db.Prepare("INSERT INTO sbc_info(fqdn, kamailio_id, rtp_engine_id, created) " +
"VALUES(?,?,?,datetime());")
if err != nil {
return fmt.Errorf("could not prepare insert statement err=%w", err)
}
res, err := stmt.Exec(
viper.GetString(flagnames.SbcFqdn),
d.insertID.kamailio,
d.insertID.rtpEngine,
)
if err != nil {
return fmt.Errorf("could not execute insert statement err=%w", err)
}
d.log.Info("Sbc configuration information successfully saved")
d.insertID.sbcInstance, err = res.LastInsertId()
if err != nil {
return fmt.Errorf("could not get last insert id from insert into sbc_info err=%w", err)
}
d.log.Debug("SBC configuration inserted", "insert_id", d.insertID.sbcInstance)
return nil
}
func (d *db) GetSBCIdFromFqdn(sbcFqdn string) int64 {
var sbcID int64
if err := d.db.QueryRowContext(
context.Background(),
"SELECT id FROM sbc_info WHERE fqdn = ?", sbcFqdn).Scan(&sbcID); err != nil {
d.log.Error("Could not get sbc id", "fqdn", sbcFqdn, "err", err)
}
return sbcID
}
func (d *db) GetSBCParameters(sbcID int64) (types.Sbc, error) {
stmt, err := d.db.Prepare(
"SELECT " +
"fqdn, sbc_name, sbc_tls_port, sbc_udp_port, " +
"pbx_ip, pbx_port, rtp_engine_port, rtp_max, " +
"rtp_min, media_public_ip, ng_listen, new_config, enable_sipdump " +
"FROM sbc_info " +
"JOIN kamailio k ON k.id = sbc_info.kamailio_id " +
"JOIN rtp_engine re ON re.id = sbc_info.rtp_engine_id " +
"WHERE sbc_info.id == ?")
if err != nil {
return types.Sbc{}, fmt.Errorf("could not prepare select statement err=%w", err)
}
res, err := stmt.Query(sbcID)
if err != nil {
return types.Sbc{}, fmt.Errorf("could not run query for select statement err=%w", err)
}
sbcResult := types.Sbc{}
for res.Next() {
if err := res.Scan(
&sbcResult.Fqdn,
&sbcResult.SbcName,
&sbcResult.SbcTLSPort,
&sbcResult.SbcUDPPort,
&sbcResult.PbxIP,
&sbcResult.PbxPort,
&sbcResult.RTPEnginePort,
&sbcResult.RTPMaxPort,
&sbcResult.RTPMinPort,
&sbcResult.MediaPublicIP,
&sbcResult.NgListen,
&sbcResult.NewConfig,
&sbcResult.EnableSIPDump,
); err != nil {
return types.Sbc{}, fmt.Errorf("could not scan data into struct err=%w", err)
}
}
d.log.Debug("Data fetched from database", "data", sbcResult)
return sbcResult, nil
}
func (d *db) storeRTPEngineData() error {
// select the last record in the table
rows, err := d.db.Query("SELECT * FROM rtp_engine ORDER BY id DESC LIMIT 1;")
if err != nil {
return err
}
var (
rtpMaxPort, rtpMinPort, rtpSignalPort string
rtpPubIP = viper.GetString(flagnames.RTPPublicIP)
)
// check if the table is empty
if !rows.Next() {
d.log.Debug("Rtp engine table is empty, using default first data")
rtpMaxPort = viper.GetString(flagnames.RTPMaxPort)
rtpMinPort = viper.GetString(flagnames.RTPMinPort)
rtpSignalPort = viper.GetString(flagnames.RTPSignalPort)
} else {
rtpSignalPort = d.getSingleRecordAndIncreaseByValue(1, "ng_listen", "rtp_engine")
rtpMinPort = d.getSingleRecordAndIncreaseByValue(500, "rtp_min", "rtp_engine")
rtpMaxPort = d.getSingleRecordAndIncreaseByValue(500, "rtp_max", "rtp_engine")
}
_ = rows.Close()
stmt, err := d.db.Prepare("INSERT INTO rtp_engine(rtp_max, rtp_min, media_public_ip, ng_listen) " +
"VALUES (?,?,?,?);")
if err != nil {
return fmt.Errorf("could not prepare insert statement err=%w", err)
}
res, err := stmt.Exec(
rtpMaxPort,
rtpMinPort,
rtpPubIP,
rtpSignalPort,
)
if err != nil {
return fmt.Errorf("could not execute prepared statement err=%w", err)
}
d.insertID.rtpEngine, err = res.LastInsertId()
if err != nil {
return fmt.Errorf("could not get last inserted id err=%w", err)
}
d.log.Debug("RTP engine configuration inserted", "insert_id", d.insertID.kamailio)
return nil
}
func (d *db) storeKamailioData() error {
// get Kamailio values from flags
var (
newConfig int
enableSIPDump int
sbcPort, udpSIPPort, rtpEngPort string
// user must always set these values and/or they don't have to be unique
pbxIP = viper.GetString(flagnames.KamailioPbxIP)
pbxPort = viper.GetString(flagnames.KamailioPbxPort)
sbcFqdn = viper.GetString(flagnames.SbcFqdn)
)
// translate bool to int
if viper.GetBool(flagnames.KamailioNewConfig) {
newConfig = 1
}
if viper.GetBool(flagnames.KamailioSIPDump) {
enableSIPDump = 1
}
// select the last record in the table
qRes, err := d.db.Query("SELECT * FROM kamailio ORDER BY sbc_name DESC LIMIT 1;")
if err != nil {
return err
}
// check if the table is empty
if !qRes.Next() {
d.log.Debug("Kamailio table is empty, using default first data")
// if there are no records in the table, default values will be used
rtpEngPort = viper.GetString(flagnames.KamailioRTPEngPort)
sbcPort = viper.GetString(flagnames.KamailioSbcPort)
udpSIPPort = viper.GetString(flagnames.KamailioUDPSIPPort)
} else {
d.log.Debug("Existing Kamailio data found, calculating next values")
// if there are some records, next values will be calculated
rtpEngPort = d.getSingleRecordAndIncreaseByValue(1, "rtp_engine_port", "kamailio")
udpSIPPort = d.getSingleRecordAndIncreaseByValue(1, "sbc_udp_port", "kamailio")
sbcPort = d.getSingleRecordAndIncreaseByValue(1, "sbc_tls_port", "kamailio")
}
_ = qRes.Close()
// prepare statement
stmt, err := d.db.Prepare(
"INSERT INTO kamailio(new_config, enable_sipdump, pbx_ip, " +
"pbx_port, rtp_engine_port, sbc_name, sbc_tls_port, sbc_udp_port) " +
"VALUES (?,?,?,?,?,?,?,?);")
if err != nil {
return fmt.Errorf("could not prepare insert statement err=%w", err)
}
// pass flag values and execute
res, err := stmt.Exec(
newConfig,
enableSIPDump,
pbxIP,
pbxPort,
rtpEngPort,
sbcFqdn,
sbcPort,
udpSIPPort,
)
if err != nil {
return fmt.Errorf("could not execute insert statement err=%w", err)
}
// save insert id
d.insertID.kamailio, err = res.LastInsertId()
if err != nil {
return fmt.Errorf("could not get last insert id err=%w", err)
}
d.log.Debug("Kamailio configuration inserted", "insert_id", d.insertID.kamailio)
return nil
}