-
Notifications
You must be signed in to change notification settings - Fork 10
/
ccx_notification_writer.go
732 lines (643 loc) · 25.9 KB
/
ccx_notification_writer.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
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
/*
Copyright © 2021, 2022, 2023 Red Hat, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
// Entry point to the notification writer service.
//
// The service contains consumer (usually Kafka consumer) that consumes
// messages from given source, processes those messages and stores them
// in configured data store.
//
// The main task for this service is to listen to configured Kafka topic,
// consume all messages from such topic, and write OCP results (in JSON format)
// with additional information (like organization ID, cluster name, Kafka
// offset etc.) into a database table named new_reports. Multiple reports can
// be consumed and written into the database for the same cluster, because the
// primary (compound) key for new_reports table is set to the combination
// (org_id, cluster, updated_at).
//
// When some message does not conform to expected schema (for example if org_id
// is missing for any reason), such message is dropped and the error message
// with all relevant information about the issue is stored into the log.
// Messages are expected to contain report body represented as JSON. This body
// is shrunk before it's stored into database so the database remains
// relatively small.
package main
// Entry point to the CCX Notification writer service
// Generated documentation is available at:
// https://pkg.go.dev/github.com/RedHatInsights/ccx-notification-writer/
//
// Documentation in literate-programming-style is available at:
// https://redhatinsights.github.io/ccx-notification-writer/packages/ccx_notification_writer.html
import (
"flag"
"fmt"
"math"
"net/http"
"os"
"strconv"
"strings"
"github.com/RedHatInsights/insights-operator-utils/logger"
utils "github.com/RedHatInsights/insights-operator-utils/migrations"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/Shopify/sarama"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
)
// Messages to be displayed on terminal or written into logs
const (
versionMessage = "CCX Notification Writer version 1.0"
authorsMessage = "Pavel Tisnovsky, Red Hat Inc."
connectionToBrokerMessage = "Connection to broker"
allBrokerConnectionAttemptsMessage = "Couldn't connect to any of the provided brokers"
operationFailedMessage = "Operation failed"
notConnectedToBrokerMessage = "Not connected to broker"
brokerConnectionSuccessMessage = "Broker connection OK"
databaseCleanupOperationFailedMessage = "Database cleanup operation failed"
databaseDropTablesOperationFailedMessage = "Database drop tables operation failed"
databasePrintNewReportsForCleanupOperationFailedMessage = "Print records to cleanup from `new_reports` failed"
databasePrintOldReportsForCleanupOperationFailedMessage = "Print records to cleanup from `reported` table failed"
databasePrintReadErrorsForCleanupOperationFailedMessage = "Print records to cleanup from `read_errors` table failed"
databaseCleanupNewReportsOperationFailedMessage = "Cleanup records from `new_reports` table failed"
databaseCleanupOldReportsOperationFailedMessage = "Cleanup records from `reported` table failed"
databaseCleanupReadErrorsOperationFailedMessage = "Cleanup records from `read_errors` table failed"
rowsInsertedMessage = "Rows inserted"
rowsDeletedMessage = "Rows deleted"
rowsAffectedMessage = "Rows affected"
brokerAddresses = "Broker addresses"
StorageHandleErr = "unable to get storage handle"
)
// Configuration-related constants
const (
// environment variable that might contain name of configuration file
// (it does not have to exist - in this case defaultConfigFileName
// value is used instead)
configFileEnvVariableName = "CCX_NOTIFICATION_WRITER_CONFIG_FILE"
// default configuration file name without implicit extension (.toml)
defaultConfigFileName = "config"
)
// Exit codes
const (
// ExitStatusOK means that the tool finished with success
ExitStatusOK = iota
// ExitStatusConfigurationError is returned in case of any configuration-related error
ExitStatusConfigurationError
// ExitStatusConsumerError is returned in case of any consumer-related error
ExitStatusConsumerError
// ExitStatusProducerError is returned in case of any producer-related error
ExitStatusProducerError
// ExitStatusKafkaError is returned in case of any Kafka-related error
ExitStatusKafkaError
// ExitStatusStorageError is returned in case of any consumer-related error
ExitStatusStorageError
// ExitStatusHTTPServerError is returned in case the HTTP server can not be started
ExitStatusHTTPServerError
// ExitStatusMigrationError is returned in case of an error while attempting to perform DB migrations
ExitStatusMigrationError
)
// showVersion function displays version information to standard output.
func showVersion() {
fmt.Println(versionMessage)
}
// showAuthors function displays information about authors to standard output.
func showAuthors() {
fmt.Println(authorsMessage)
}
// showConfiguration function displays actual configuration.
func showConfiguration(configuration *ConfigStruct) {
// retrieve and then display broker configuration
brokerConfig := GetBrokerConfiguration(configuration)
log.Info().
Str(brokerAddresses, brokerConfig.Addresses).
Str("Security protocol", brokerConfig.SecurityProtocol).
Str("Cert path", brokerConfig.CertPath).
Str("Sasl mechanism", brokerConfig.SaslMechanism).
Str("Sasl username", brokerConfig.SaslUsername). // SASL password is omitted on purpose
Str("Topic", brokerConfig.Topic).
Str("Group", brokerConfig.Group).
Bool("Enabled", brokerConfig.Enabled).
Msg("Broker configuration")
// retrieve and then display storage configuration
storageConfig := GetStorageConfiguration(configuration)
log.Info().
Str("Driver", storageConfig.Driver).
Str("DB Name", storageConfig.PGDBName).
Str("Username", storageConfig.PGUsername). // password is omitted on purpose
Str("Host", storageConfig.PGHost).
Int("Port", storageConfig.PGPort).
Bool("LogSQLQueries", storageConfig.LogSQLQueries).
Msg("Storage configuration")
// retrieve and then display logging configuration
loggingConfig := GetLoggingConfiguration(configuration)
log.Info().
Str("Level", loggingConfig.LogLevel).
Bool("Pretty colored debug logging", loggingConfig.Debug).
Msg("Logging configuration")
// retrieve and then display metrics configuration
metricsConfig := GetMetricsConfiguration(configuration)
log.Info().
Str("Namespace", metricsConfig.Namespace).
Str("Address", metricsConfig.Address).
Msg("Metrics configuration")
}
// tryToConnectToKafka function just tries to establish connection to Kafka
// broker
func tryToConnectToKafka(configuration *ConfigStruct) (int, error) {
log.Info().Msg("Checking connection to Kafka")
// prepare broker configuration
brokerConfiguration := GetBrokerConfiguration(configuration)
// display basic info about broker that will be used
log.Info().
Str(brokerAddresses, brokerConfiguration.Addresses)
var err error
for _, addr := range strings.Split(brokerConfiguration.Addresses, ",") {
// create new broker instance (w/o any checks)
broker := sarama.NewBroker(addr)
// check broker connection
err = broker.Open(nil)
if err != nil {
log.Error().Err(err).Msg(connectionToBrokerMessage)
continue
}
// check if connection remain
connected, err := broker.Connected()
if err != nil {
log.Error().Err(err).Msg(connectionToBrokerMessage)
continue
}
if !connected {
log.Error().Err(err).Msg(notConnectedToBrokerMessage)
continue
}
// connection was established
log.Info().Msg(brokerConnectionSuccessMessage)
// everything seems to be ok
return ExitStatusOK, nil
}
log.Error().Msg(allBrokerConnectionAttemptsMessage)
return ExitStatusKafkaError, err
}
// performDatabaseInitialization function performs database initialization -
// creates all tables and indexes in database, also insert constant record into
// database.
func performDatabaseInitialization(configuration *ConfigStruct) (int, error) {
// prepare the storage
storageConfiguration := GetStorageConfiguration(configuration)
storage, err := NewStorage(&storageConfiguration)
if err != nil {
log.Err(err).Msg(operationFailedMessage)
return ExitStatusStorageError, err
}
// try to perform database initialization
err = storage.DatabaseInitialization()
if err != nil {
log.Err(err).Msg("Database initialization operation failed")
return ExitStatusStorageError, err
}
return ExitStatusOK, nil
}
// performDatabaseInitMigration function initialize migration table.
func performDatabaseInitMigration(configuration *ConfigStruct) (int, error) {
// prepare the storage
storageConfiguration := GetStorageConfiguration(configuration)
storage, err := NewStorage(&storageConfiguration)
if err != nil {
log.Err(err).Msg(operationFailedMessage)
return ExitStatusStorageError, err
}
// try to initialize database migration
err = storage.DatabaseInitMigration()
if err != nil {
log.Err(err).Msg("Database migration initialization operation failed")
return ExitStatusStorageError, err
}
return ExitStatusOK, nil
}
// performDatabaseCleanup function performs database cleanup - deletes content
// of all tables in database.
func performDatabaseCleanup(configuration *ConfigStruct) (int, error) {
// prepare the storage
storageConfiguration := GetStorageConfiguration(configuration)
storage, err := NewStorage(&storageConfiguration)
if err != nil {
log.Err(err).Msg(operationFailedMessage)
return ExitStatusStorageError, err
}
// try to cleanup the whole database
err = storage.DatabaseCleanup()
if err != nil {
log.Err(err).Msg(databaseCleanupOperationFailedMessage)
return ExitStatusStorageError, err
}
return ExitStatusOK, nil
}
// performDatabaseDropTables function performs drop of all databases tables.
func performDatabaseDropTables(configuration *ConfigStruct) (int, error) {
// prepare the storage
storageConfiguration := GetStorageConfiguration(configuration)
storage, err := NewStorage(&storageConfiguration)
if err != nil {
log.Err(err).Msg(operationFailedMessage)
return ExitStatusStorageError, err
}
// try to drop all tables from database
err = storage.DatabaseDropTables()
if err != nil {
log.Err(err).Msg(databaseDropTablesOperationFailedMessage)
return ExitStatusStorageError, err
}
return ExitStatusOK, nil
}
// printNewReportsForCleanup function print all reports stored in `new_reports`
// table that are older than specified maximum age.
//
// See also: performNewReportsCleanup
func printNewReportsForCleanup(configuration *ConfigStruct, cliFlags CliFlags) (int, error) {
// prepare the storage
storageConfiguration := GetStorageConfiguration(configuration)
storage, err := NewStorage(&storageConfiguration)
if err != nil {
log.Error().Err(err).Msg(operationFailedMessage)
return ExitStatusStorageError, err
}
err = storage.PrintNewReportsForCleanup(cliFlags.MaxAge)
if err != nil {
log.Error().Err(err).Msg(databasePrintNewReportsForCleanupOperationFailedMessage)
return ExitStatusStorageError, err
}
return ExitStatusOK, nil
}
// performNewReportsCleanup function deletes all reports from `new_reports`
// table that are older than specified max age.
//
// See also: printNewReportsForCleanup
func performNewReportsCleanup(configuration *ConfigStruct, cliFlags CliFlags) (int, error) {
// prepare the storage
storageConfiguration := GetStorageConfiguration(configuration)
storage, err := NewStorage(&storageConfiguration)
if err != nil {
log.Error().Err(err).Msg(operationFailedMessage)
return ExitStatusStorageError, err
}
affected, err := storage.CleanupNewReports(cliFlags.MaxAge)
if err != nil {
log.Error().Err(err).Msg(databaseCleanupNewReportsOperationFailedMessage)
return ExitStatusStorageError, err
}
log.Info().Int(rowsDeletedMessage, affected).Msg("Cleanup `new_reports` finished")
return ExitStatusOK, nil
}
// printOldReportsForCleanup function print all reports stored in `reported`
// table that are older than specified max age.
//
// See also: performOldReportsCleanup
func printOldReportsForCleanup(configuration *ConfigStruct, cliFlags CliFlags) (int, error) {
// prepare the storage
storageConfiguration := GetStorageConfiguration(configuration)
storage, err := NewStorage(&storageConfiguration)
if err != nil {
log.Error().Err(err).Msg(operationFailedMessage)
return ExitStatusStorageError, err
}
err = storage.PrintOldReportsForCleanup(cliFlags.MaxAge)
if err != nil {
log.Error().Err(err).Msg(databasePrintOldReportsForCleanupOperationFailedMessage)
return ExitStatusStorageError, err
}
return ExitStatusOK, nil
}
// performOldReportsCleanup function deletes all reports from `reported` table
// that are older than specified max age.
//
// See also: printOldReportsForCleanup
func performOldReportsCleanup(configuration *ConfigStruct, cliFlags CliFlags) (int, error) {
// prepare the storage
storageConfiguration := GetStorageConfiguration(configuration)
storage, err := NewStorage(&storageConfiguration)
if err != nil {
log.Error().Err(err).Msg(operationFailedMessage)
return ExitStatusStorageError, err
}
affected, err := storage.CleanupOldReports(cliFlags.MaxAge)
if err != nil {
log.Error().Err(err).Msg(databaseCleanupOldReportsOperationFailedMessage)
return ExitStatusStorageError, err
}
log.Info().Int(rowsDeletedMessage, affected).Msg("Cleanup `reported` finished")
return ExitStatusOK, nil
}
// printReadErrorsForCleanup function print all reports stored in `read_errors`
// table that are older than specified max age.
//
// See also: performReadErrorsForCleanup
func printReadErrorsForCleanup(configuration *ConfigStruct, cliFlags CliFlags) (int, error) {
// prepare the storage
storageConfiguration := GetStorageConfiguration(configuration)
storage, err := NewStorage(&storageConfiguration)
if err != nil {
log.Error().Err(err).Msg(operationFailedMessage)
return ExitStatusStorageError, err
}
err = storage.PrintReadErrorsForCleanup(cliFlags.MaxAge)
if err != nil {
log.Error().Err(err).Msg(databasePrintReadErrorsForCleanupOperationFailedMessage)
return ExitStatusStorageError, err
}
return ExitStatusOK, nil
}
// performReadErrorsCleanup function deletes all reports from `read_errors` table
// that are older than specified max age.
func performReadErrorsCleanup(configuration *ConfigStruct, cliFlags CliFlags) (int, error) {
// prepare the storage
storageConfiguration := GetStorageConfiguration(configuration)
storage, err := NewStorage(&storageConfiguration)
if err != nil {
log.Error().Err(err).Msg(operationFailedMessage)
return ExitStatusStorageError, err
}
affected, err := storage.CleanupReadErrors(cliFlags.MaxAge)
if err != nil {
log.Error().Err(err).Msg(databaseCleanupReadErrorsOperationFailedMessage)
return ExitStatusStorageError, err
}
log.Info().Int(rowsDeletedMessage, affected).Msg("Cleanup `read_errors` finished")
return ExitStatusOK, nil
}
// startService function tries to start the notification writer service,
// connect to storage and initialize connection to message broker.
func startService(configuration *ConfigStruct) (int, error) {
// show configuration at startup
showConfiguration(configuration)
// configure metrics
metricsConfig := GetMetricsConfiguration(configuration)
if metricsConfig.Namespace != "" {
log.Info().Str("namespace", metricsConfig.Namespace).Msg("Setting metrics namespace")
AddMetricsWithNamespace(metricsConfig.Namespace)
}
// prepare the storage
storageConfiguration := GetStorageConfiguration(configuration)
storage, err := NewStorage(&storageConfiguration)
if err != nil {
log.Err(err).Msg(operationFailedMessage)
return ExitStatusStorageError, err
}
// prepare HTTP server with metrics exposed
err = startHTTPServer(metricsConfig.Address)
if err != nil {
log.Error().Err(err).Send()
return ExitStatusHTTPServerError, err
}
// prepare broker
brokerConfiguration := GetBrokerConfiguration(configuration)
// if broker is disabled, simply don't start it
if brokerConfiguration.Enabled {
err := startConsumer(configuration, storage)
if err != nil {
log.Error().Err(err).Send()
return ExitStatusConsumerError, err
}
} else {
log.Info().Msg("Broker is disabled, not starting it")
}
return ExitStatusOK, nil
}
// startConsumer function starts the Kafka consumer.
func startConsumer(config *ConfigStruct, storage Storage) error {
consumer, err := NewConsumer(&config.Broker, storage)
if err != nil {
log.Error().Err(err).Msg("Construct broker failed")
return err
}
pt, err := NewPayloadTrackerProducer(config)
if err != nil {
log.Error().Err(err).Msg("Construct payload tracker producer failed")
return err
}
consumer.Tracker = pt
consumer.Serve()
return nil
}
// startHTTP server starts HTTP or HTTPS server with exposed metrics.
func startHTTPServer(address string) error {
// setup handlers
http.Handle("/metrics", promhttp.Handler())
// start the server
go func() {
log.Info().Str("HTTP server address", address).Msg("Starting HTTP server")
err := http.ListenAndServe(address, nil) // #nosec G114
if err != nil {
log.Error().Err(err).Msg("Listen and serve")
}
}()
return nil
}
// doSelectedOperation function perform operation selected on command line.
// When no operation is specified, the Notification writer service is started
// instead.
//
//gocyclo:ignore
func doSelectedOperation(configuration *ConfigStruct, cliFlags CliFlags) (int, error) {
switch {
case cliFlags.ShowVersion:
showVersion()
return ExitStatusOK, nil
case cliFlags.ShowAuthors:
showAuthors()
return ExitStatusOK, nil
case cliFlags.ShowConfiguration:
showConfiguration(configuration)
return ExitStatusOK, nil
case cliFlags.CheckConnectionToKafka:
return tryToConnectToKafka(configuration)
case cliFlags.PerformDatabaseInitialization:
return performDatabaseInitialization(configuration)
case cliFlags.PerformDatabaseCleanup:
return performDatabaseCleanup(configuration)
case cliFlags.PerformDatabaseDropTables:
return performDatabaseDropTables(configuration)
case cliFlags.PerformDatabaseInitMigration:
return performDatabaseInitMigration(configuration)
case cliFlags.PrintNewReportsForCleanup:
return printNewReportsForCleanup(configuration, cliFlags)
case cliFlags.PerformNewReportsCleanup:
return performNewReportsCleanup(configuration, cliFlags)
case cliFlags.PrintOldReportsForCleanup:
return printOldReportsForCleanup(configuration, cliFlags)
case cliFlags.PerformOldReportsCleanup:
return performOldReportsCleanup(configuration, cliFlags)
case cliFlags.PrintReadErrorsForCleanup:
return printReadErrorsForCleanup(configuration, cliFlags)
case cliFlags.PerformReadErrorsCleanup:
return performReadErrorsCleanup(configuration, cliFlags)
case cliFlags.MigrationInfo:
return PrintMigrationInfo(configuration)
case cliFlags.PerformMigrations != "":
return PerformMigrations(configuration, cliFlags.PerformMigrations)
case cliFlags.TruncateOldReports:
return performTruncateOldReports(configuration)
default:
exitCode, err := startService(configuration)
return exitCode, err
}
// this can not happen: return ExitStatusOK, nil
}
// convertLogLevel function converts log level specified in configuration file
// into proper zerolog constant.
//
// TODO: refactor utils/logger appropriately
func convertLogLevel(level string) zerolog.Level {
level = strings.ToLower(strings.TrimSpace(level))
switch level {
case "debug":
return zerolog.DebugLevel
case "info":
return zerolog.InfoLevel
case "warn", "warning":
return zerolog.WarnLevel
case "error":
return zerolog.ErrorLevel
case "fatal":
return zerolog.FatalLevel
}
return zerolog.DebugLevel
}
// main function is entry point to the Notification writer service.
func main() {
var cliFlags CliFlags
// define and then parse all command line options
flag.BoolVar(&cliFlags.PerformDatabaseInitialization, "db-init", false, "perform database initialization")
flag.BoolVar(&cliFlags.PerformDatabaseCleanup, "db-cleanup", false, "perform database cleanup")
flag.BoolVar(&cliFlags.PerformDatabaseDropTables, "db-drop-tables", false, "drop all tables from database")
flag.BoolVar(&cliFlags.PerformDatabaseInitMigration, "db-init-migration", false, "initialize migration")
flag.BoolVar(&cliFlags.CheckConnectionToKafka, "check-kafka", false, "check connection to Kafka")
flag.BoolVar(&cliFlags.ShowVersion, "version", false, "show version")
flag.BoolVar(&cliFlags.ShowAuthors, "authors", false, "show authors")
flag.BoolVar(&cliFlags.ShowConfiguration, "show-configuration", false, "show configuration")
flag.BoolVar(&cliFlags.PrintNewReportsForCleanup, "print-new-reports-for-cleanup", false, "print new reports to be cleaned up")
flag.BoolVar(&cliFlags.PerformNewReportsCleanup, "new-reports-cleanup", false, "perform new reports clean up")
flag.BoolVar(&cliFlags.PrintOldReportsForCleanup, "print-old-reports-for-cleanup", false, "print old reports to be cleaned up")
flag.BoolVar(&cliFlags.PerformOldReportsCleanup, "old-reports-cleanup", false, "perform old reports clean up")
flag.BoolVar(&cliFlags.PrintReadErrorsForCleanup, "print-read-errors-for-cleanup", false, "print records from read_errors table to be cleaned up")
flag.BoolVar(&cliFlags.PerformReadErrorsCleanup, "read-errors-cleanup", false, "perform clean up of read_errors table")
flag.BoolVar(&cliFlags.MigrationInfo, "migration-info", false, "prints migration info")
flag.BoolVar(&cliFlags.TruncateOldReports, "truncate-old-reports", false, "truncate the reported table")
flag.StringVar(&cliFlags.MaxAge, "max-age", "", "max age for displaying/cleaning old records")
flag.StringVar(&cliFlags.PerformMigrations, "migrate", "", "set database version")
flag.Parse()
// service configuration has exactly the same structure as *.toml file
configuration, err := LoadConfiguration(configFileEnvVariableName, defaultConfigFileName)
if err != nil {
log.Err(err).Msg("Load configuration")
os.Exit(ExitStatusConfigurationError)
}
err = logger.InitZerolog(
GetLoggingConfiguration(&configuration),
GetCloudWatchConfiguration(&configuration),
GetSentryConfiguration(&configuration),
logger.KafkaZerologConfiguration{},
)
if err != nil {
log.Err(err).Msg("Logging configuration error")
os.Exit(ExitStatusConfigurationError)
}
log.Debug().Msg("Started")
// override default value read from configuration file
if cliFlags.MaxAge == "" {
cliFlags.MaxAge = "7 days"
}
// perform selected operation
exitStatus, err := doSelectedOperation(&configuration, cliFlags)
if err != nil {
log.Err(err).Msg("Do selected operation")
os.Exit(exitStatus)
return
}
log.Debug().Msg("Finished")
}
// PrintMigrationInfo function prints information about current DB migration
// version without making any modifications in database.
func PrintMigrationInfo(configuration *ConfigStruct) (int, error) {
storageConfiguration := GetStorageConfiguration(configuration)
storage, err := NewStorage(&storageConfiguration)
if err != nil {
log.Error().Err(err).Msg(StorageHandleErr)
return ExitStatusMigrationError, err
}
currMigVer, err := utils.GetDBVersion(storage.connection)
if err != nil {
log.Error().Err(err).Msg("Unable to get current DB version")
return ExitStatusMigrationError, err
}
log.Info().Msgf("Current DB version: %d", currMigVer)
log.Info().Msgf("Maximum available version: %d", utils.GetMaxVersion())
return ExitStatusOK, nil
}
// PerformMigrations migrates the database to the version
// specified in params
func PerformMigrations(configuration *ConfigStruct, migParam string) (exitStatus int, err error) {
// init migration utils
utils.Set(All())
// get db handle
storageConfiguration := GetStorageConfiguration(configuration)
storage, err := NewStorage(&storageConfiguration)
if err != nil {
log.Error().Err(err).Msg(StorageHandleErr)
exitStatus = ExitStatusMigrationError
return
}
// parse migration params
var desiredVersion utils.Version
if migParam == "latest" {
desiredVersion = utils.GetMaxVersion()
} else {
vers, convErr := strconv.Atoi(migParam)
if err != nil {
log.Error().Err(err).Msgf("Unable to parse migration version: %v", migParam)
exitStatus = ExitStatusMigrationError
err = convErr
return
}
if vers < 0 || vers > math.MaxUint32 {
log.Error().Err(err).Msgf("Unable to parse migration version: %v version out of range", migParam)
exitStatus = ExitStatusMigrationError
err = fmt.Errorf("version out of range: %v", vers)
return
}
desiredVersion = utils.Version(uint32(vers))
}
// perform database migration
err = Migrate(storage.Connection(), desiredVersion)
if err != nil {
log.Error().Err(err).Msg("migration failure")
exitStatus = ExitStatusMigrationError
return
}
exitStatus = ExitStatusOK
return
}
// performTruncateOldReports function truncates the reported table.
func performTruncateOldReports(configuration *ConfigStruct) (int, error) {
// prepare the storage
storageConfiguration := GetStorageConfiguration(configuration)
storage, err := NewStorage(&storageConfiguration)
if err != nil {
log.Error().Err(err).Msg(operationFailedMessage)
return ExitStatusStorageError, err
}
// try to truncate the reported table
err = storage.TruncateOldReports()
if err != nil {
log.Err(err).Msg(databaseDropTablesOperationFailedMessage)
return ExitStatusStorageError, err
}
log.Info().Msg("Truncated `reported` table successfully")
return ExitStatusOK, nil
}