-
Notifications
You must be signed in to change notification settings - Fork 230
/
pgwatch2.go
5996 lines (5394 loc) · 228 KB
/
pgwatch2.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
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"container/list"
"context"
"crypto/aes"
"crypto/cipher"
"crypto/rand"
"crypto/sha256"
go_sql "database/sql"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"math"
"net"
"net/http"
"os"
"path"
"path/filepath"
"regexp"
"sort"
"strconv"
"strings"
"sync"
"sync/atomic"
"syscall"
"time"
"github.com/shirou/gopsutil/v3/disk"
"github.com/shirou/gopsutil/v3/mem"
"github.com/coreos/go-systemd/daemon"
client "github.com/influxdata/influxdb1-client/v2"
"github.com/jessevdk/go-flags"
"github.com/jmoiron/sqlx"
"github.com/lib/pq"
"github.com/marpaia/graphite-golang"
"github.com/op/go-logging"
"github.com/shirou/gopsutil/v3/cpu"
"github.com/shirou/gopsutil/v3/load"
"github.com/shopspring/decimal"
"golang.org/x/crypto/pbkdf2"
"gopkg.in/yaml.v2"
)
var commit = "" // Git hash. Will be set on build time by build_gatherer.sh / goreleaser
var date = "" // Will be set on build time by build_gatherer.sh / goreleaser
type MonitoredDatabase struct {
DBUniqueName string `yaml:"unique_name"`
DBUniqueNameOrig string // to preserve belonging to a specific instance for continuous modes where DBUniqueName will be dynamic
Group string
Host string
Port string
DBName string
User string
Password string
PasswordType string `yaml:"password_type"`
LibPQConnStr string `yaml:"libpq_conn_str"`
SslMode string
SslRootCAPath string `yaml:"sslrootcert"`
SslClientCertPath string `yaml:"sslcert"`
SslClientKeyPath string `yaml:"sslkey"`
Metrics map[string]float64 `yaml:"custom_metrics"`
MetricsStandby map[string]float64 `yaml:"custom_metrics_standby"`
StmtTimeout int64 `yaml:"stmt_timeout"`
DBType string
DBNameIncludePattern string `yaml:"dbname_include_pattern"`
DBNameExcludePattern string `yaml:"dbname_exclude_pattern"`
PresetMetrics string `yaml:"preset_metrics"`
PresetMetricsStandby string `yaml:"preset_metrics_standby"`
IsSuperuser bool `yaml:"is_superuser"`
IsEnabled bool `yaml:"is_enabled"`
CustomTags map[string]string `yaml:"custom_tags"` // ignored on graphite
HostConfig HostConfigAttrs `yaml:"host_config"`
OnlyIfMaster bool `yaml:"only_if_master"`
}
type HostConfigAttrs struct {
DcsType string `yaml:"dcs_type"`
DcsEndpoints []string `yaml:"dcs_endpoints"`
Scope string
Namespace string
Username string
Password string
CAFile string `yaml:"ca_file"`
CertFile string `yaml:"cert_file"`
KeyFile string `yaml:"key_file"`
LogsGlobPath string `yaml:"logs_glob_path"` // default $data_directory / $log_directory / *.csvlog
LogsMatchRegex string `yaml:"logs_match_regex"` // default is for CSVLOG format. needs to capture following named groups: log_time, user_name, database_name and error_severity
PerMetricDisabledTimes []HostConfigPerMetricDisabledTimes `yaml:"per_metric_disabled_intervals"`
}
type HostConfigPerMetricDisabledTimes struct { // metric gathering override per host / metric / time
Metrics []string `yaml:"metrics"`
DisabledTimes []string `yaml:"disabled_times"`
DisabledDays string `yaml:"disabled_days"`
}
type PatroniClusterMember struct {
Scope string
Name string
ConnUrl string `yaml:"conn_url"`
Role string
}
type PresetConfig struct {
Name string
Description string
Metrics map[string]float64
}
type MetricColumnAttrs struct {
PrometheusGaugeColumns []string `yaml:"prometheus_gauge_columns"`
PrometheusIgnoredColumns []string `yaml:"prometheus_ignored_columns"` // for cases where we don't want some columns to be exposed in Prom mode
PrometheusAllGaugeColumns bool `yaml:"prometheus_all_gauge_columns"`
}
type MetricAttrs struct {
IsInstanceLevel bool `yaml:"is_instance_level"`
MetricStorageName string `yaml:"metric_storage_name"`
ExtensionVersionOverrides []ExtensionOverrides `yaml:"extension_version_based_overrides"`
IsPrivate bool `yaml:"is_private"` // used only for extension overrides currently and ignored otherwise
DisabledDays string `yaml:"disabled_days"` // Cron style, 0 = Sunday. Ranges allowed: 0,2-4
DisableTimes []string `yaml:"disabled_times"` // "11:00-13:00"
StatementTimeoutSeconds int64 `yaml:"statement_timeout_seconds"` // overrides per monitored DB settings
}
type MetricVersionProperties struct {
Sql string
SqlSU string
MasterOnly bool
StandbyOnly bool
ColumnAttrs MetricColumnAttrs // Prometheus Metric Type (Counter is default) and ignore list
MetricAttrs MetricAttrs
CallsHelperFunctions bool
}
type ControlMessage struct {
Action string // START, STOP, PAUSE
Config map[string]float64
}
type MetricFetchMessage struct {
DBUniqueName string
DBUniqueNameOrig string
MetricName string
DBType string
Interval time.Duration
CreatedOn time.Time
StmtTimeoutOverride int64
}
type MetricStoreMessage struct {
DBUniqueName string
DBType string
MetricName string
CustomTags map[string]string
Data [](map[string]interface{})
MetricDefinitionDetails MetricVersionProperties
RealDbname string
SystemIdentifier string
}
type MetricStoreMessagePostgres struct {
Time time.Time
DBName string
Metric string
Data map[string]interface{}
TagData map[string]interface{}
}
type ChangeDetectionResults struct { // for passing around DDL/index/config change detection results
Created int
Altered int
Dropped int
}
type DBVersionMapEntry struct {
LastCheckedOn time.Time
IsInRecovery bool
Version decimal.Decimal
VersionStr string
RealDbname string
SystemIdentifier string
IsSuperuser bool // if true and no helpers are installed, use superuser SQL version of metric if available
Extensions map[string]decimal.Decimal
ExecEnv string
ApproxDBSizeB int64
}
type ExistingPartitionInfo struct {
StartTime time.Time
EndTime time.Time
}
type ExtensionOverrides struct {
TargetMetric string `yaml:"target_metric"`
ExpectedExtensionVersions []ExtensionInfo `yaml:"expected_extension_versions"`
}
type ExtensionInfo struct {
ExtName string `yaml:"ext_name"`
ExtMinVersion decimal.Decimal `yaml:"ext_min_version"`
}
const EPOCH_COLUMN_NAME string = "epoch_ns" // this column (epoch in nanoseconds) is expected in every metric query
const TAG_PREFIX string = "tag_"
const METRIC_DEFINITION_REFRESH_TIME int64 = 120 // min time before checking for new/changed metric definitions
const GRAPHITE_METRICS_PREFIX string = "pgwatch2"
const PERSIST_QUEUE_MAX_SIZE = 10000 // storage queue max elements. when reaching the limit, older metrics will be dropped.
// actual requirements depend a lot of metric type and nr. of obects in schemas,
// but 100k should be enough for 24h, assuming 5 hosts monitored with "exhaustive" preset config. this would also require ~2 GB RAM per one Influx host
const DATASTORE_INFLUX = "influx"
const DATASTORE_GRAPHITE = "graphite"
const DATASTORE_JSON = "json"
const DATASTORE_POSTGRES = "postgres"
const DATASTORE_PROMETHEUS = "prometheus"
const PRESET_CONFIG_YAML_FILE = "preset-configs.yaml"
const FILE_BASED_METRIC_HELPERS_DIR = "00_helpers"
const PG_CONN_RECYCLE_SECONDS = 1800 // applies for monitored nodes
const APPLICATION_NAME = "pgwatch2" // will be set on all opened PG connections for informative purposes
const GATHERER_STATUS_START = "START"
const GATHERER_STATUS_STOP = "STOP"
const METRICDB_IDENT = "metricDb"
const CONFIGDB_IDENT = "configDb"
const CONTEXT_PROMETHEUS_SCRAPE = "prometheus-scrape"
const DCS_TYPE_ETCD = "etcd"
const DCS_TYPE_ZOOKEEPER = "zookeeper"
const DCS_TYPE_CONSUL = "consul"
const DBTYPE_PG = "postgres"
const DBTYPE_PG_CONT = "postgres-continuous-discovery"
const DBTYPE_BOUNCER = "pgbouncer"
const DBTYPE_PGPOOL = "pgpool"
const DBTYPE_PATRONI = "patroni"
const DBTYPE_PATRONI_CONT = "patroni-continuous-discovery"
const DBTYPE_PATRONI_NAMESPACE_DISCOVERY = "patroni-namespace-discovery"
const MONITORED_DBS_DATASTORE_SYNC_INTERVAL_SECONDS = 600 // write actively monitored DBs listing to metrics store after so many seconds
const MONITORED_DBS_DATASTORE_SYNC_METRIC_NAME = "configured_dbs" // FYI - for Postgres datastore there's also the admin.all_unique_dbnames table with all recent DB unique names with some metric data
const RECO_PREFIX = "reco_" // special handling for metrics with such prefix, data stored in RECO_METRIC_NAME
const RECO_METRIC_NAME = "recommendations"
const SPECIAL_METRIC_CHANGE_EVENTS = "change_events"
const SPECIAL_METRIC_SERVER_LOG_EVENT_COUNTS = "server_log_event_counts"
const SPECIAL_METRIC_PGBOUNCER = "^pgbouncer_(stats|pools)$"
const SPECIAL_METRIC_PGPOOL_STATS = "pgpool_stats"
const SPECIAL_METRIC_INSTANCE_UP = "instance_up"
const SPECIAL_METRIC_DB_SIZE = "db_size" // can be transparently switched to db_size_approx on instances with very slow FS access (Azure Single Server)
const SPECIAL_METRIC_TABLE_STATS = "table_stats" // can be transparently switched to table_stats_approx on instances with very slow FS (Azure Single Server)
const METRIC_CPU_LOAD = "cpu_load"
const METRIC_PSUTIL_CPU = "psutil_cpu"
const METRIC_PSUTIL_DISK = "psutil_disk"
const METRIC_PSUTIL_DISK_IO_TOTAL = "psutil_disk_io_total"
const METRIC_PSUTIL_MEM = "psutil_mem"
const DEFAULT_METRICS_DEFINITION_PATH_PKG = "/etc/pgwatch2/metrics" // prebuilt packages / Docker default location
const DEFAULT_METRICS_DEFINITION_PATH_DOCKER = "/pgwatch2/metrics" // prebuilt packages / Docker default location
const DB_SIZE_CACHING_INTERVAL = 30 * time.Minute
const DB_METRIC_JOIN_STR = "¤¤¤" // just some unlikely string for a DB name to avoid using maps of maps for DB+metric data
const EXEC_ENV_UNKNOWN = "UNKNOWN"
const EXEC_ENV_AZURE_SINGLE = "AZURE_SINGLE"
const EXEC_ENV_AZURE_FLEXIBLE = "AZURE_FLEXIBLE"
const EXEC_ENV_GOOGLE = "GOOGLE"
var dbTypeMap = map[string]bool{DBTYPE_PG: true, DBTYPE_PG_CONT: true, DBTYPE_BOUNCER: true, DBTYPE_PATRONI: true, DBTYPE_PATRONI_CONT: true, DBTYPE_PGPOOL: true, DBTYPE_PATRONI_NAMESPACE_DISCOVERY: true}
var dbTypes = []string{DBTYPE_PG, DBTYPE_PG_CONT, DBTYPE_BOUNCER, DBTYPE_PATRONI, DBTYPE_PATRONI_CONT, DBTYPE_PATRONI_NAMESPACE_DISCOVERY} // used for informational purposes
var specialMetrics = map[string]bool{RECO_METRIC_NAME: true, SPECIAL_METRIC_CHANGE_EVENTS: true, SPECIAL_METRIC_SERVER_LOG_EVENT_COUNTS: true}
var directlyFetchableOSMetrics = map[string]bool{METRIC_PSUTIL_CPU: true, METRIC_PSUTIL_DISK: true, METRIC_PSUTIL_DISK_IO_TOTAL: true, METRIC_PSUTIL_MEM: true, METRIC_CPU_LOAD: true}
var configDb *sqlx.DB
var metricDb *sqlx.DB
var graphiteConnection *graphite.Graphite
var graphite_host string
var graphite_port int
var log = logging.MustGetLogger("main")
var metric_def_map map[string]map[decimal.Decimal]MetricVersionProperties
var metric_def_map_lock = sync.RWMutex{}
var host_metric_interval_map = make(map[string]float64) // [db1_metric] = 30
var db_pg_version_map = make(map[string]DBVersionMapEntry)
var db_pg_version_map_lock = sync.RWMutex{}
var db_get_pg_version_map_lock = make(map[string]sync.RWMutex) // synchronize initial PG version detection to 1 instance for each defined host
var monitored_db_cache map[string]MonitoredDatabase
var monitored_db_cache_lock sync.RWMutex
var monitored_db_conn_cache map[string]*sqlx.DB = make(map[string]*sqlx.DB)
var monitored_db_conn_cache_lock = sync.RWMutex{}
var last_sql_fetch_error sync.Map
var influx_host_count = 1
var InfluxConnectStrings [2]string // Max. 2 Influx metrics stores currently supported
var InfluxSkipSSLCertVerify, InfluxSkipSSLCertVerify2 bool
// secondary Influx meant for HA or Grafana load balancing for 100+ instances with lots of alerts
var fileBasedMetrics = false
var adHocMode = false
var preset_metric_def_map map[string]map[string]float64 // read from metrics folder in "file mode"
// / internal statistics calculation
var lastSuccessfulDatastoreWriteTimeEpoch int64
var datastoreWriteFailuresCounter uint64
var datastoreWriteSuccessCounter uint64
var totalMetricFetchFailuresCounter uint64
var datastoreTotalWriteTimeMicroseconds uint64
var totalMetricsFetchedCounter uint64
var totalMetricsReusedFromCacheCounter uint64
var totalMetricsDroppedCounter uint64
var totalDatasetsFetchedCounter uint64
var metricPointsPerMinuteLast5MinAvg int64 = -1 // -1 means the summarization ticker has not yet run
var gathererStartTime time.Time = time.Now()
var useConnPooling bool
var partitionMapMetric = make(map[string]ExistingPartitionInfo) // metric = min/max bounds
var partitionMapMetricDbname = make(map[string]map[string]ExistingPartitionInfo) // metric[dbname = min/max bounds]
var testDataGenerationModeWG sync.WaitGroup
var PGDummyMetricTables = make(map[string]time.Time)
var PGDummyMetricTablesLock = sync.RWMutex{}
var PGSchemaType string
var failedInitialConnectHosts = make(map[string]bool) // hosts that couldn't be connected to even once
var addRealDbname bool
var addSystemIdentifier bool
var noHelperFunctions bool
var forceRecreatePGMetricPartitions = false // to signal override PG metrics storage cache
var lastMonitoredDBsUpdate time.Time
var instanceMetricCache = make(map[string]([]map[string]interface{})) // [dbUnique+metric]lastly_fetched_data
var instanceMetricCacheLock = sync.RWMutex{}
var instanceMetricCacheTimestamp = make(map[string]time.Time) // [dbUnique+metric]last_fetch_time
var instanceMetricCacheTimestampLock = sync.RWMutex{}
var MinExtensionInfoAvailable, _ = decimal.NewFromString("9.1")
var regexIsAlpha = regexp.MustCompile("^[a-zA-Z]+$")
var rBouncerAndPgpoolVerMatch = regexp.MustCompile(`\d+\.+\d+`) // extract $major.minor from "4.1.2 (karasukiboshi)" or "PgBouncer 1.12.0"
var regexIsPgbouncerMetrics = regexp.MustCompile(SPECIAL_METRIC_PGBOUNCER)
var tryDirectOSStats bool
var unreachableDBsLock sync.RWMutex
var unreachableDB = make(map[string]time.Time)
var pgBouncerNumericCountersStartVersion decimal.Decimal // pgBouncer changed internal counters data type in v1.12
// "cache" of last CPU utilization stats for GetGoPsutilCPU to get more exact results and not having to sleep
var prevCPULoadTimeStatsLock sync.RWMutex
var prevCPULoadTimeStats cpu.TimesStat
var prevCPULoadTimestamp time.Time
// Async Prom cache
var promAsyncMetricCache = make(map[string]map[string][]MetricStoreMessage) // [dbUnique][metric]lastly_fetched_data
var promAsyncMetricCacheLock = sync.RWMutex{}
var promAsyncMode = false
var lastDBSizeMB = make(map[string]int64)
var lastDBSizeFetchTime = make(map[string]time.Time) // cached for DB_SIZE_CACHING_INTERVAL
var lastDBSizeCheckLock sync.RWMutex
var mainLoopInitialized int32 // 0/1
var prevLoopMonitoredDBs []MonitoredDatabase // to be able to detect DBs removed from config
var undersizedDBs = make(map[string]bool) // DBs below the --min-db-size-mb limit, if set
var undersizedDBsLock = sync.RWMutex{}
var recoveryIgnoredDBs = make(map[string]bool) // DBs in recovery state and OnlyIfMaster specified in config
var recoveryIgnoredDBsLock = sync.RWMutex{}
var regexSQLHelperFunctionCalled = regexp.MustCompile(`(?si)^\s*(select|with).*\s+get_\w+\(\)[\s,$]+`) // SQL helpers expected to follow get_smth() naming
var metricNameRemaps = make(map[string]string)
var metricNameRemapLock = sync.RWMutex{}
func IsPostgresDBType(dbType string) bool {
if dbType == DBTYPE_BOUNCER || dbType == DBTYPE_PGPOOL {
return false
}
return true
}
func GetPostgresDBConnection(libPqConnString, host, port, dbname, user, password, sslmode, sslrootcert, sslcert, sslkey string) (*sqlx.DB, error) {
var connStr string
//log.Debug("Connecting to: ", host, port, dbname, user, password)
if len(libPqConnString) > 0 {
connStr = libPqConnString
if !strings.Contains(strings.ToLower(connStr), "sslmode") {
if strings.Contains(connStr, "postgresql://") || strings.Contains(connStr, "postgres://") { // JDBC style
if strings.Contains(connStr, "?") { // has some extra params already
connStr += "&sslmode=disable" // defaulting to "disable" as Go driver doesn't support "prefer"
} else {
connStr += "?sslmode=disable"
}
} else { // LibPQ style
connStr += " sslmode=disable"
}
}
if !strings.Contains(strings.ToLower(connStr), "connect_timeout") {
if strings.Contains(connStr, "postgresql://") || strings.Contains(connStr, "postgres://") { // JDBC style
if strings.Contains(connStr, "?") { // has some extra params already
connStr += "&connect_timeout=5" // 5 seconds
} else {
connStr += "?connect_timeout=5"
}
} else { // LibPQ style
connStr += " connect_timeout=5"
}
}
} else {
connStr = fmt.Sprintf("host=%s port=%s dbname='%s' sslmode=%s user=%s application_name=%s sslrootcert='%s' sslcert='%s' sslkey='%s' connect_timeout=5",
host, port, dbname, sslmode, user, APPLICATION_NAME, sslrootcert, sslcert, sslkey)
if password != "" { // having empty string as password effectively disables .pgpass so include only if password given
connStr += fmt.Sprintf(" password='%s'", password)
}
}
return sqlx.Open("postgres", connStr)
}
func StringToBoolOrFail(boolAsString, inputParamName string) bool {
conversionMap := map[string]bool{
"true": true, "t": true, "on": true, "y": true, "yes": true, "require": true, "1": true,
"false": false, "f": false, "off": false, "n": false, "no": false, "disable": false, "0": false,
}
val, ok := conversionMap[strings.TrimSpace(strings.ToLower(boolAsString))]
if !ok {
if inputParamName != "" {
log.Fatalf("invalid input for boolean string parameter \"%s\": \"%s\". can be of: 1, t, T, TRUE, true, True, 0, f, F, FALSE, false, False", inputParamName, boolAsString)
} else {
log.Fatalf("invalid input for boolean string: %s. can be of: 1, t, T, TRUE, true, True, 0, f, F, FALSE, false, False", boolAsString)
}
}
return val
}
func InitAndTestConfigStoreConnection(host, port, dbname, user, password, requireSSL string, failOnErr bool) error {
var err error
SSLMode := "disable"
var retries = 3 // ~15s
if StringToBoolOrFail(requireSSL, "--pg-require-ssl") {
SSLMode = "require"
}
for i := 0; i <= retries; i++ {
// configDb is used by the main thread only. no verify-ca/verify-full support currently
configDb, err = GetPostgresDBConnection("", host, port, dbname, user, password, SSLMode, "", "", "")
if err != nil {
if i < retries {
log.Errorf("could not open metricDb connection. retrying in 5s. %d retries left. err: %v", retries-i, err)
time.Sleep(time.Second * 5)
continue
}
if failOnErr {
log.Fatal("could not open configDb connection! exit.")
} else {
log.Error("could not open configDb connection!")
return err
}
}
err = configDb.Ping()
if err != nil {
if i < retries {
log.Errorf("could not ping configDb! retrying in 5s. %d retries left. err: %v", retries-i, err)
time.Sleep(time.Second * 5)
continue
}
if failOnErr {
log.Fatal("could not ping configDb! exit.", err)
} else {
log.Error("could not ping configDb!", err)
return err
}
} else {
log.Info("connect to configDb OK!")
break
}
}
configDb.SetMaxIdleConns(1)
configDb.SetMaxOpenConns(2)
configDb.SetConnMaxLifetime(time.Second * time.Duration(PG_CONN_RECYCLE_SECONDS))
return nil
}
func InitAndTestMetricStoreConnection(connStr string, failOnErr bool) error {
var err error
var retries = 3 // ~15s
for i := 0; i <= retries; i++ {
metricDb, err = GetPostgresDBConnection(connStr, "", "", "", "", "", "", "", "", "")
if err != nil {
if i < retries {
log.Errorf("could not open metricDb connection. retrying in 5s. %d retries left. err: %v", retries-i, err)
time.Sleep(time.Second * 5)
continue
}
if failOnErr {
log.Fatal("could not open metricDb connection! exit. err:", err)
} else {
log.Error("could not open metricDb connection:", err)
return err
}
}
err = metricDb.Ping()
if err != nil {
if i < retries {
log.Errorf("could not ping metricDb! retrying in 5s. %d retries left. err: %v", retries-i, err)
time.Sleep(time.Second * 5)
continue
}
if failOnErr {
log.Fatal("could not ping metricDb! exit.", err)
} else {
return err
}
} else {
log.Info("connect to metricDb OK!")
break
}
}
metricDb.SetMaxIdleConns(2)
metricDb.SetMaxOpenConns(2)
metricDb.SetConnMaxLifetime(time.Second * 172800) // 2d
return nil
}
// every DB under monitoring should have exactly 1 sql.DB connection assigned, that will internally limit parallel access
func InitSqlConnPoolForMonitoredDBIfNil(md MonitoredDatabase) error {
monitored_db_conn_cache_lock.Lock()
defer monitored_db_conn_cache_lock.Unlock()
conn, ok := monitored_db_conn_cache[md.DBUniqueName]
if ok && conn != nil {
return nil
}
if md.DBType == DBTYPE_BOUNCER {
md.DBName = "pgbouncer"
}
conn, err := GetPostgresDBConnection(md.LibPQConnStr, md.Host, md.Port, md.DBName, md.User, md.Password,
md.SslMode, md.SslRootCAPath, md.SslClientCertPath, md.SslClientKeyPath)
if err != nil {
return err
}
if useConnPooling {
conn.SetMaxIdleConns(opts.MaxParallelConnectionsPerDb)
} else {
conn.SetMaxIdleConns(0)
}
conn.SetMaxOpenConns(opts.MaxParallelConnectionsPerDb)
// recycling periodically makes sense as long sessions might bloat memory or maybe conn info (password) was changed
conn.SetConnMaxLifetime(time.Second * time.Duration(PG_CONN_RECYCLE_SECONDS))
monitored_db_conn_cache[md.DBUniqueName] = conn
log.Debugf("[%s] Connection pool initialized with max %d parallel connections. Conn pooling: %v", md.DBUniqueName, opts.MaxParallelConnectionsPerDb, useConnPooling)
return nil
}
func CloseOrLimitSqlConnPoolForMonitoredDBIfAny(dbUnique string) {
monitored_db_conn_cache_lock.Lock()
defer monitored_db_conn_cache_lock.Unlock()
conn, ok := monitored_db_conn_cache[dbUnique]
if !ok || conn == nil {
return
}
if IsDBUndersized(dbUnique) || IsDBIgnoredBasedOnRecoveryState(dbUnique) {
if useConnPooling {
s := conn.Stats()
if s.MaxOpenConnections > 1 {
log.Debugf("[%s] Limiting SQL connection pool to max 1 connection due to dormant state ...", dbUnique)
conn.SetMaxIdleConns(1)
conn.SetMaxOpenConns(1)
}
}
} else { // removed from config
log.Debugf("[%s] Closing SQL connection pool ...", dbUnique)
err := conn.Close()
if err != nil {
log.Error("[%s] Failed to close connection pool to %s nicely. Err: %v", dbUnique, err)
}
delete(monitored_db_conn_cache, dbUnique)
}
}
func RestoreSqlConnPoolLimitsForPreviouslyDormantDB(dbUnique string) {
if !useConnPooling {
return
}
monitored_db_conn_cache_lock.Lock()
defer monitored_db_conn_cache_lock.Unlock()
conn, ok := monitored_db_conn_cache[dbUnique]
if !ok || conn == nil {
log.Error("DB conn to re-instate pool limits not found, should not happen")
return
}
log.Debugf("[%s] Re-instating SQL connection pool max connections ...", dbUnique)
conn.SetMaxIdleConns(opts.MaxParallelConnectionsPerDb)
conn.SetMaxOpenConns(opts.MaxParallelConnectionsPerDb)
}
func InitPGVersionInfoFetchingLockIfNil(md MonitoredDatabase) {
db_pg_version_map_lock.Lock()
if _, ok := db_get_pg_version_map_lock[md.DBUniqueName]; !ok {
db_get_pg_version_map_lock[md.DBUniqueName] = sync.RWMutex{}
}
db_pg_version_map_lock.Unlock()
}
func DBExecRead(conn *sqlx.DB, host_ident, sql string, args ...interface{}) ([](map[string]interface{}), error) {
ret := make([]map[string]interface{}, 0)
var rows *sqlx.Rows
var err error
if conn == nil {
return nil, errors.New("nil connection")
}
rows, err = conn.Queryx(sql, args...)
if err != nil {
// connection problems or bad queries etc are quite common so caller should decide if to output something
log.Debug("failed to query", host_ident, "sql:", sql, "err:", err)
return nil, err
}
defer rows.Close()
for rows.Next() {
row := make(map[string]interface{})
err = rows.MapScan(row)
if err != nil {
log.Error("failed to MapScan a result row", host_ident, err)
return nil, err
}
ret = append(ret, row)
}
err = rows.Err()
if err != nil {
log.Error("failed to fully process resultset for", host_ident, "sql:", sql, "err:", err)
}
return ret, err
}
func DBExecInExplicitTX(conn *sqlx.DB, host_ident, sql string, args ...interface{}) ([](map[string]interface{}), error) {
ret := make([]map[string]interface{}, 0)
var rows *sqlx.Rows
var err error
if conn == nil {
return nil, errors.New("nil connection")
}
ctx := context.Background()
txOpts := go_sql.TxOptions{ReadOnly: true}
tx, err := conn.BeginTxx(ctx, &txOpts)
if err != nil {
return ret, err
}
defer tx.Commit()
rows, err = tx.Queryx(sql, args...)
if err != nil {
// connection problems or bad queries etc are quite common so caller should decide if to output something
log.Debug("failed to query", host_ident, "sql:", sql, "err:", err)
return nil, err
}
defer rows.Close()
for rows.Next() {
row := make(map[string]interface{})
err = rows.MapScan(row)
if err != nil {
log.Error("failed to MapScan a result row", host_ident, err)
return nil, err
}
ret = append(ret, row)
}
err = rows.Err()
if err != nil {
log.Error("failed to fully process resultset for", host_ident, "sql:", sql, "err:", err)
}
return ret, err
}
func DBExecReadByDbUniqueName(dbUnique, metricName string, stmtTimeoutOverride int64, sql string, args ...interface{}) ([](map[string]interface{}), error, time.Duration) {
var conn *sqlx.DB
var md MonitoredDatabase
var data [](map[string]interface{})
var err error
var duration time.Duration
var exists bool
var sqlStmtTimeout string
var sqlLockTimeout = "SET LOCAL lock_timeout TO '100ms';"
if strings.TrimSpace(sql) == "" {
return nil, errors.New("empty SQL"), duration
}
md, err = GetMonitoredDatabaseByUniqueName(dbUnique)
if err != nil {
return nil, err, duration
}
monitored_db_conn_cache_lock.RLock()
// sqlx.DB itself is parallel safe
conn, exists = monitored_db_conn_cache[dbUnique]
monitored_db_conn_cache_lock.RUnlock()
if !exists || conn == nil {
log.Errorf("SQL connection for dbUnique %s not found or nil", dbUnique) // Should always be initialized in the main loop DB discovery code ...
return nil, errors.New("SQL connection not found or nil"), duration
}
if !adHocMode && IsPostgresDBType(md.DBType) {
stmtTimeout := md.StmtTimeout
if stmtTimeoutOverride > 0 {
stmtTimeout = stmtTimeoutOverride
}
if stmtTimeout > 0 { // 0 = don't change, use DB level settings
if useConnPooling {
sqlStmtTimeout = fmt.Sprintf("SET LOCAL statement_timeout TO '%ds';", stmtTimeout)
} else {
sqlStmtTimeout = fmt.Sprintf("SET statement_timeout TO '%ds';", stmtTimeout)
}
}
if err != nil {
atomic.AddUint64(&totalMetricFetchFailuresCounter, 1)
return nil, err, duration
}
}
if IsPostgresDBType(md.DBType) {
if !useConnPooling {
sqlLockTimeout = "SET lock_timeout TO '100ms';"
}
} else {
sqlLockTimeout = ""
}
sqlToExec := sqlLockTimeout + sqlStmtTimeout + sql // bundle timeouts with actual SQL to reduce round-trip times
//log.Debugf("Executing SQL: %s", sqlToExec)
t1 := time.Now()
if IsPostgresDBType(md.DBType) {
if useConnPooling {
data, err = DBExecInExplicitTX(conn, dbUnique, sqlToExec, args...)
} else {
data, err = DBExecRead(conn, dbUnique, sqlToExec, args...)
}
} else {
for _, sql := range strings.Split(sqlToExec, ";") {
sql = strings.TrimSpace(sql)
if len(sql) > 0 {
data, err = DBExecRead(conn, dbUnique, sql, args...)
}
}
}
t2 := time.Now()
if err != nil {
atomic.AddUint64(&totalMetricFetchFailuresCounter, 1)
}
return data, err, t2.Sub(t1)
}
func GetAllActiveHostsFromConfigDB() ([](map[string]interface{}), error) {
sql_latest := `
select /* pgwatch2_generated */
md_unique_name, md_group, md_dbtype, md_hostname, md_port, md_dbname, md_user, coalesce(md_password, '') as md_password,
coalesce(p.pc_config, md_config)::text as md_config, coalesce(s.pc_config, md_config_standby, '{}'::jsonb)::text as md_config_standby,
md_statement_timeout_seconds, md_sslmode, md_is_superuser,
coalesce(md_include_pattern, '') as md_include_pattern, coalesce(md_exclude_pattern, '') as md_exclude_pattern,
coalesce(md_custom_tags::text, '{}') as md_custom_tags, md_root_ca_path, md_client_cert_path, md_client_key_path,
md_password_type, coalesce(md_host_config, '{}')::text as md_host_config, md_only_if_master
from
pgwatch2.monitored_db
left join
pgwatch2.preset_config p on p.pc_name = md_preset_config_name /* primary preset if any */
left join
pgwatch2.preset_config s on s.pc_name = md_preset_config_name_standby /* standby preset if any */
where
md_is_enabled
`
sql_prev := `
select /* pgwatch2_generated */
md_unique_name, md_group, md_dbtype, md_hostname, md_port, md_dbname, md_user, coalesce(md_password, '') as md_password,
coalesce(pc_config, md_config)::text as md_config, md_statement_timeout_seconds, md_sslmode, md_is_superuser,
coalesce(md_include_pattern, '') as md_include_pattern, coalesce(md_exclude_pattern, '') as md_exclude_pattern,
coalesce(md_custom_tags::text, '{}') as md_custom_tags, md_root_ca_path, md_client_cert_path, md_client_key_path,
md_password_type, coalesce(md_host_config, '{}')::text as md_host_config, md_only_if_master
from
pgwatch2.monitored_db
left join
pgwatch2.preset_config on pc_name = md_preset_config_name
where
md_is_enabled
`
data, err := DBExecRead(configDb, CONFIGDB_IDENT, sql_latest)
if err != nil {
err1 := err
log.Debugf("Failed to query the monitored DB-s config with latest SQL: %v ", err1)
data, err = DBExecRead(configDb, CONFIGDB_IDENT, sql_prev)
if err == nil {
log.Warning("Fetching monitored DB-s config succeeded with SQL from previous schema version - gatherer update required!")
} else {
log.Errorf("Failed to query the monitored DB-s config: %v", err1) // show the original error
}
}
return data, err
}
func GetMonitoredDatabasesFromConfigDB() ([]MonitoredDatabase, error) {
monitoredDBs := make([]MonitoredDatabase, 0)
activeHostData, err := GetAllActiveHostsFromConfigDB()
groups := strings.Split(opts.Group, ",")
skippedEntries := 0
if err != nil {
log.Errorf("Failed to read monitoring config from DB: %s", err)
return monitoredDBs, err
}
for _, row := range activeHostData {
if len(opts.Group) > 0 { // filter out rows with non-matching groups
matched := false
for _, g := range groups {
if row["md_group"].(string) == g {
matched = true
break
}
}
if !matched {
skippedEntries += 1
continue
}
}
if skippedEntries > 0 {
log.Infof("Filtered out %d config entries based on --groups input", skippedEntries)
}
metricConfig, err := jsonTextToMap(row["md_config"].(string))
if err != nil {
log.Warningf("Cannot parse metrics JSON config for \"%s\": %v", row["md_unique_name"].(string), err)
continue
}
metricConfigStandby := make(map[string]float64)
if configStandby, ok := row["md_config_standby"]; ok {
metricConfigStandby, err = jsonTextToMap(configStandby.(string))
if err != nil {
log.Warningf("Cannot parse standby metrics JSON config for \"%s\". Ignoring standby config: %v", row["md_unique_name"].(string), err)
}
}
customTags, err := jsonTextToStringMap(row["md_custom_tags"].(string))
if err != nil {
log.Warningf("Cannot parse custom tags JSON for \"%s\". Ignoring custom tags. Error: %v", row["md_unique_name"].(string), err)
customTags = nil
}
hostConfigAttrs := HostConfigAttrs{}
err = yaml.Unmarshal([]byte(row["md_host_config"].(string)), &hostConfigAttrs)
if err != nil {
log.Warningf("Cannot parse host config JSON for \"%s\". Ignoring host config. Error: %v", row["md_unique_name"].(string), err)
}
md := MonitoredDatabase{
DBUniqueName: row["md_unique_name"].(string),
DBUniqueNameOrig: row["md_unique_name"].(string),
Host: row["md_hostname"].(string),
Port: row["md_port"].(string),
DBName: row["md_dbname"].(string),
User: row["md_user"].(string),
IsSuperuser: row["md_is_superuser"].(bool),
Password: row["md_password"].(string),
PasswordType: row["md_password_type"].(string),
SslMode: row["md_sslmode"].(string),
SslRootCAPath: row["md_root_ca_path"].(string),
SslClientCertPath: row["md_client_cert_path"].(string),
SslClientKeyPath: row["md_client_key_path"].(string),
StmtTimeout: row["md_statement_timeout_seconds"].(int64),
Metrics: metricConfig,
MetricsStandby: metricConfigStandby,
DBType: row["md_dbtype"].(string),
DBNameIncludePattern: row["md_include_pattern"].(string),
DBNameExcludePattern: row["md_exclude_pattern"].(string),
Group: row["md_group"].(string),
HostConfig: hostConfigAttrs,
OnlyIfMaster: row["md_only_if_master"].(bool),
CustomTags: customTags}
if _, ok := dbTypeMap[md.DBType]; !ok {
log.Warningf("Ignoring host \"%s\" - unknown dbtype: %s. Expected one of: %+v", md.DBUniqueName, md.DBType, dbTypes)
continue
}
if md.PasswordType == "aes-gcm-256" && opts.AesGcmKeyphrase != "" {
md.Password = decrypt(md.DBUniqueName, opts.AesGcmKeyphrase, md.Password)
}
if md.DBType == DBTYPE_PG_CONT {
resolved, err := ResolveDatabasesFromConfigEntry(md)
if err != nil {
log.Errorf("Failed to resolve DBs for \"%s\": %s", md.DBUniqueName, err)
if md.PasswordType == "aes-gcm-256" && opts.AesGcmKeyphrase == "" {
log.Errorf("No decryption key set. Use the --aes-gcm-keyphrase or --aes-gcm-keyphrase params to set")
}
continue
}
temp_arr := make([]string, 0)
for _, rdb := range resolved {
monitoredDBs = append(monitoredDBs, rdb)
temp_arr = append(temp_arr, rdb.DBName)
}
log.Debugf("Resolved %d DBs with prefix \"%s\": [%s]", len(resolved), md.DBUniqueName, strings.Join(temp_arr, ", "))
} else if md.DBType == DBTYPE_PATRONI || md.DBType == DBTYPE_PATRONI_CONT || md.DBType == DBTYPE_PATRONI_NAMESPACE_DISCOVERY {
resolved, err := ResolveDatabasesFromPatroni(md)
if err != nil {
log.Errorf("Failed to resolve DBs for \"%s\": %s", md.DBUniqueName, err)
continue
}
temp_arr := make([]string, 0)
for _, rdb := range resolved {
monitoredDBs = append(monitoredDBs, rdb)
temp_arr = append(temp_arr, rdb.DBName)
}
log.Debugf("Resolved %d DBs with prefix \"%s\": [%s]", len(resolved), md.DBUniqueName, strings.Join(temp_arr, ", "))
} else {
monitoredDBs = append(monitoredDBs, md)
}
monitoredDBs = append(monitoredDBs)
}
return monitoredDBs, err
}
func SendToInflux(connect_str, conn_id string, storeMessages []MetricStoreMessage) error {
if len(storeMessages) == 0 {
return nil
}
skipSSLCertVerify := InfluxSkipSSLCertVerify // conn_id == "0"
if conn_id == "1" {
skipSSLCertVerify = InfluxSkipSSLCertVerify2
}
ts_warning_printed := false
retries := 1 // 1 retry
retry:
c, err := client.NewHTTPClient(client.HTTPConfig{
Addr: connect_str,
Username: opts.InfluxUser,
Password: opts.InfluxPassword,
InsecureSkipVerify: skipSSLCertVerify,
})
if err != nil {
log.Error("Error connecting to Influx", conn_id, ": ", err)
if retries > 0 {
retries--
time.Sleep(time.Millisecond * 200)
goto retry
}
atomic.AddUint64(&datastoreWriteFailuresCounter, 1)
return err
}
defer c.Close()
bp, err := client.NewBatchPoints(client.BatchPointsConfig{Database: opts.InfluxDbname})
if err != nil {
atomic.AddUint64(&datastoreWriteFailuresCounter, 1)
return err
}
rows_batched := 0
total_rows := 0
for _, msg := range storeMessages {
if msg.Data == nil || len(msg.Data) == 0 {
continue
}
log.Debugf("SendToInflux %s data[0] of %d [%s:%s]: %v", conn_id, len(msg.Data), msg.DBUniqueName, msg.MetricName, msg.Data[0])
for _, dr := range msg.Data {
// Create a point and add to batch
var epoch_time time.Time
var epoch_ns int64
tags := make(map[string]string)
fields := make(map[string]interface{})
total_rows += 1
tags["dbname"] = msg.DBUniqueName
if msg.CustomTags != nil {
for k, v := range msg.CustomTags {
tags[k] = fmt.Sprintf("%v", v)
}
}
for k, v := range dr {
if v == nil || v == "" {
continue // not storing NULLs
}