-
Notifications
You must be signed in to change notification settings - Fork 2
/
percona_pg_telemetry.c
1138 lines (920 loc) · 29.6 KB
/
percona_pg_telemetry.c
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
/*-------------------------------------------------------------------------
*
* percona_pg_telemetry.c
* Collects telemetry information for the database cluster.
*
* IDENTIFICATION
* contrib/percona_pg_telemetry/percona_pg_telemetry.c
*
*-------------------------------------------------------------------------
*/
#include "postgres.h"
#include "fmgr.h"
#include "funcapi.h"
#include "pg_config.h"
#include "utils/guc_tables.h"
#include "access/genam.h"
#include "access/heapam.h"
#include "access/relscan.h"
#include "access/table.h"
#include "access/tableam.h"
#include "commands/dbcommands.h"
#include "catalog/namespace.h"
#include "catalog/pg_extension.h"
#include "catalog/pg_database.h"
#include "catalog/pg_namespace_d.h"
#include "catalog/pg_type_d.h"
#include "executor/spi.h"
#include "postmaster/bgworker.h"
#include "storage/fd.h"
#include "storage/latch.h"
#include "storage/proc.h"
#include "utils/builtins.h"
#include "utils/guc.h"
#include "utils/fmgroids.h"
#include "utils/fmgrprotos.h"
#include "utils/lsyscache.h"
#include "utils/memutils.h"
#include "utils/relcache.h"
#include "utils/syscache.h"
#include "utils/snapmgr.h"
#include "percona_pg_telemetry.h"
#include "pt_json.h"
#if PG_VERSION_NUM >= 130000
#include "postmaster/interrupt.h"
#endif
#if PG_VERSION_NUM >= 140000
#include "utils/backend_status.h"
#include "utils/wait_event.h"
#else
#include "pgstat.h"
#endif
#include <sys/stat.h>
PG_MODULE_MAGIC;
/* General defines */
#define PT_BUILD_VERSION "1.0"
#define PT_FILE_MODE (S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)
/* Init and exported functions */
void _PG_init(void);
PGDLLEXPORT void percona_pg_telemetry_main(Datum);
PGDLLEXPORT void percona_pg_telemetry_worker(Datum);
PG_FUNCTION_INFO_V1(percona_pg_telemetry_status);
PG_FUNCTION_INFO_V1(percona_pg_telemetry_version);
/* Internal init, shared memeory and signal functions */
static void init_guc(void);
static void pt_sigterm(SIGNAL_ARGS);
static void pt_shmem_init(void);
static void pt_shmem_request(void);
#if PG_VERSION_NUM >= 150000
static shmem_request_hook_type prev_shmem_request_hook = NULL;
#endif
/* Helper functions */
static BgwHandleStatus setup_background_worker(const char *bgw_function_name, const char *bgw_name, const char *bgw_type, Oid datid, pid_t bgw_notify_pid);
static void start_leader(void);
static long server_uptime(void);
static void load_telemetry_files(void);
static char *generate_filename(char *filename);
static bool validate_dir(char *folder_path);
#if PG_VERSION_NUM >= 130000
static int compare_file_names(const ListCell *a, const ListCell *b);
#else
static int compare_file_names(const void *a, const void *b);
#endif
/* Database information collection and writing to file */
static void write_pg_settings(void);
static List *get_database_list(void);
static List *get_extensions_list(PTDatabaseInfo *dbinfo, MemoryContext cxt);
static bool write_database_info(PTDatabaseInfo *dbinfo, List *extlist);
/* Shared state stuff */
static PTSharedState *ptss = NULL;
#define PT_SHARED_STATE_HEADER_SIZE (offsetof(PTSharedState, telemetry_filenames))
#define PT_SHARED_STATE_PREV_FILE_SIZE (files_to_keep * MAXPGPATH)
#define PT_SHARED_STATE_SIZE (PT_SHARED_STATE_HEADER_SIZE + PT_SHARED_STATE_PREV_FILE_SIZE)
#define PT_DEFAULT_FOLDER_PATH "/usr/local/percona/telemetry/pg"
/* variable for signal handlers' variables */
static volatile sig_atomic_t sigterm_recvd = false;
/* GUC variables */
char *t_folder = PT_DEFAULT_FOLDER_PATH;
int scrape_interval = HOURS_PER_DAY * MINS_PER_HOUR * SECS_PER_MINUTE;
bool telemetry_enabled = true;
int files_to_keep = 7;
/* General global variables */
static MemoryContext pt_cxt;
/*
* Signal handler for SIGTERM. When received, sets the flag and the latch.
*/
static void
pt_sigterm(SIGNAL_ARGS)
{
sigterm_recvd = true;
/* Only if MyProc is set... */
if (MyProc != NULL)
{
SetLatch(&MyProc->procLatch);
}
}
/*
* Initializing everything here
*/
void
_PG_init(void)
{
if (!process_shared_preload_libraries_in_progress)
return;
init_guc();
#if PG_VERSION_NUM >= 150000
prev_shmem_request_hook = shmem_request_hook;
shmem_request_hook = pt_shmem_request;
#else
pt_shmem_request();
#endif
start_leader();
}
/*
* Start the launcher process
*/
static void
start_leader(void)
{
setup_background_worker("percona_pg_telemetry_main", "percona_pg_telemetry launcher", "percona_pg_telemetry launcher", InvalidOid, 0);
}
/*
*
*/
static char *
generate_filename(char *filename)
{
char f_name[MAXPGPATH];
uint64 system_id = GetSystemIdentifier();
time_t currentTime;
time(¤tTime);
pg_snprintf(f_name, MAXPGPATH, "%ld-%lu.json", currentTime, system_id);
join_path_components(filename, ptss->telemetry_path, f_name);
return filename;
}
/*
*
*/
static char *
telemetry_add_filename(char *filename)
{
Assert(filename);
snprintf(ptss->telemetry_filenames[ptss->curr_file_index], MAXPGPATH, "%s", filename);
return ptss->telemetry_filenames[ptss->curr_file_index];
}
/*
*
*/
static char *
telemetry_curr_filename(void)
{
return ptss->telemetry_filenames[ptss->curr_file_index];
}
/*
*
*/
static bool
telemetry_file_is_valid(void)
{
return (*ptss->telemetry_filenames[ptss->curr_file_index] != '\0');
}
/*
* Adds a new filename to the next position in the circular buffer. If position already has a filename
* (i.e. we made full circle), then it will try to remove this file from filesystem.
* Returns the previous filename that was in the position.
*/
static char *
telemetry_file_next(char *filename)
{
/* Get current file that will become previous */
char *previous = telemetry_curr_filename();
/* Increment the index. We are using a circular buffer. */
ptss->curr_file_index = (ptss->curr_file_index + 1) % files_to_keep;
/* Remove the existing file on this location if valid */
if (telemetry_file_is_valid())
{
PathNameDeleteTemporaryFile(ptss->telemetry_filenames[ptss->curr_file_index], false);
}
/* Add new file to the new current position */
telemetry_add_filename(filename);
/* Return previous file */
return (*previous) ? previous : NULL;
}
/*
* Load all telemetry files from the telemetry directory.
*/
static void
load_telemetry_files(void)
{
DIR *d;
struct dirent *de;
uint64 system_id = GetSystemIdentifier();
char filename_tail[MAXPGPATH];
char full_path[MAXPGPATH];
List *files_list = NIL;
ListCell *lc = NULL;
validate_dir(ptss->telemetry_path);
d = AllocateDir(ptss->telemetry_path);
if (d == NULL)
{
ereport(ERROR,
(errcode_for_file_access(),
errmsg("could not open percona telemetry directory \"%s\": %m",
ptss->telemetry_path)));
}
pg_snprintf(filename_tail, sizeof(filename_tail), "%lu.json", system_id);
while ((de = ReadDir(d, ptss->telemetry_path)) != NULL)
{
if (strstr(de->d_name, filename_tail) != NULL)
{
/* Construct the file full path */
snprintf(full_path, sizeof(full_path), "%s/%s", ptss->telemetry_path, de->d_name);
files_list = lappend(files_list, pstrdup(full_path));
}
}
#if PG_VERSION_NUM >= 130000
list_sort(files_list, compare_file_names);
#else
files_list = list_qsort(files_list, compare_file_names);
#endif
foreach(lc, files_list)
{
char *file_path = lfirst(lc);
telemetry_file_next(file_path);
}
list_free_deep(files_list);
FreeDir(d);
}
#if PG_VERSION_NUM >= 130000
static int
compare_file_names(const ListCell *a, const ListCell *b)
{
char *fna = (char *) lfirst(a);
char *fnb = (char *) lfirst(b);
return strcmp(fna, fnb);
}
#else
static int
compare_file_names(const void *a, const void *b)
{
char *fna = (char *) lfirst(*(ListCell **) a);
char *fnb = (char *) lfirst(*(ListCell **) b);
return strcmp(fna, fnb);
}
#endif
/*
* telemetry_path
*/
bool
validate_dir(char *folder_path)
{
struct stat st;
bool is_dir = false;
/* Let's validate the path. */
if (stat(folder_path, &st) == 0)
{
is_dir = S_ISDIR(st.st_mode);
}
if (is_dir == false)
{
ereport(LOG,
(errcode_for_file_access(),
errmsg("percona_pg_telemetry.path \"%s\" is not set to a writeable folder or the folder does not exist.", folder_path)));
PT_WORKER_EXIT(PT_FILE_ERROR);
}
return is_dir;
}
/*
* Select the status of percona_pg_telemetry.
*/
Datum
percona_pg_telemetry_status(PG_FUNCTION_ARGS)
{
#define PT_STATUS_COLUMN_COUNT 2
TupleDesc tupdesc;
Datum values[PT_STATUS_COLUMN_COUNT];
bool nulls[PT_STATUS_COLUMN_COUNT] = {false};
HeapTuple tup;
Datum result;
int col_index = 0;
/* Initialize shmem */
pt_shmem_init();
tupdesc = CreateTemplateTupleDesc(PT_STATUS_COLUMN_COUNT);
TupleDescInitEntry(tupdesc, (AttrNumber) 1, "latest_output_filename", TEXTOID, -1, 0);
TupleDescInitEntry(tupdesc, (AttrNumber) 2, "pt_enabled", BOOLOID, -1, 0);
tupdesc = BlessTupleDesc(tupdesc);
col_index = 0;
if (telemetry_curr_filename()[0] != '\0')
values[col_index] = CStringGetTextDatum(telemetry_curr_filename());
else
nulls[col_index] = true;
col_index++;
values[col_index] = BoolGetDatum(telemetry_enabled);
tup = heap_form_tuple(tupdesc, values, nulls);
result = HeapTupleGetDatum(tup);
PG_RETURN_DATUM(result);
}
/*
* Select the version of percona_pg_telemetry.
*/
Datum
percona_pg_telemetry_version(PG_FUNCTION_ARGS)
{
PG_RETURN_TEXT_P(cstring_to_text(PT_BUILD_VERSION));
}
/*
* Request additional shared memory required
*/
static void
pt_shmem_request(void)
{
#if PG_VERSION_NUM >= 150000
if (prev_shmem_request_hook)
prev_shmem_request_hook();
#endif
RequestAddinShmemSpace(MAXALIGN(PT_SHARED_STATE_SIZE));
}
/*
* Initialize the shared memory
*/
static void
pt_shmem_init(void)
{
bool found;
LWLockAcquire(AddinShmemInitLock, LW_EXCLUSIVE);
ptss = (PTSharedState *) ShmemInitStruct("percona_pg_telemetry shared state", sizeof(PTSharedState), &found);
if (!found)
{
uint64 system_id = GetSystemIdentifier();
/* Set paths */
strncpy(ptss->telemetry_path, t_folder, MAXPGPATH);
pg_snprintf(ptss->dbtemp_filepath, MAXPGPATH, "%s/%lu.temp", ptss->telemetry_path, system_id);
/*
* Let's be optimistic here. No error code and no file currently being
* written.
*/
ptss->error_code = PT_SUCCESS;
ptss->write_in_progress = false;
ptss->json_file_indent = 0;
ptss->first_db_entry = false;
ptss->last_db_entry = false;
ptss->curr_file_index = 0;
memset(ptss->telemetry_filenames, 0, PT_SHARED_STATE_PREV_FILE_SIZE);
}
LWLockRelease(AddinShmemInitLock);
}
/*
* Intialize the GUCs
*/
static void
init_guc(void)
{
char *env;
/* is the extension enabled? */
DefineCustomBoolVariable("percona_pg_telemetry.enabled",
"Enable or disable the percona_pg_telemetry extension",
NULL,
&telemetry_enabled,
true,
PGC_SIGHUP,
0,
NULL,
NULL,
NULL);
/* telemetry files path */
DefineCustomStringVariable("percona_pg_telemetry.path",
"Directory path for writing database info file(s)",
NULL,
&t_folder,
PT_DEFAULT_FOLDER_PATH,
PGC_SIGHUP,
0,
NULL,
NULL,
NULL);
env = getenv("PT_DEBUG");
if (env != NULL)
{
/* scan time interval for the main launch process */
DefineCustomIntVariable("percona_pg_telemetry.scrape_interval",
"Data scrape interval",
NULL,
&scrape_interval,
HOURS_PER_DAY * MINS_PER_HOUR * SECS_PER_MINUTE,
1,
INT_MAX,
PGC_SIGHUP,
GUC_UNIT_S,
NULL,
NULL,
NULL);
/* Number of files to keep */
DefineCustomIntVariable("percona_pg_telemetry.files_to_keep",
"Number of JSON files to keep for this instance.",
NULL,
&files_to_keep,
7,
1,
100,
PGC_SIGHUP,
0,
NULL,
NULL,
NULL);
}
#if PG_VERSION_NUM >= 150000
MarkGUCPrefixReserved("percona_pg_telemetry");
#endif
}
/*
* Sets up a background worker. If we have received a pid to notify, then
* setup a dynamic worker and wait until it shuts down. This prevents ending
* up with multiple background workers and prevents overloading system
* resources. So, we process databases sequentially which is fine.
*
* datid is ignored for launcher which is identified by a notify_pid = 0
*/
static BgwHandleStatus
setup_background_worker(const char *bgw_function_name, const char *bgw_name, const char *bgw_type, Oid datid, pid_t bgw_notify_pid)
{
BackgroundWorker worker;
BackgroundWorkerHandle *handle;
MemSet(&worker, 0, sizeof(BackgroundWorker));
worker.bgw_flags = BGWORKER_SHMEM_ACCESS | BGWORKER_BACKEND_DATABASE_CONNECTION;
worker.bgw_start_time = BgWorkerStart_RecoveryFinished;
worker.bgw_restart_time = BGW_NEVER_RESTART;
strcpy(worker.bgw_library_name, "percona_pg_telemetry");
strcpy(worker.bgw_function_name, bgw_function_name);
strcpy(worker.bgw_name, bgw_name);
strcpy(worker.bgw_type, bgw_type);
worker.bgw_main_arg = ObjectIdGetDatum(datid);
worker.bgw_notify_pid = bgw_notify_pid;
/* Case of a launcher */
if (bgw_notify_pid == 0)
{
/* Leader should never connect to a valid database. */
worker.bgw_main_arg = ObjectIdGetDatum(InvalidOid);
RegisterBackgroundWorker(&worker);
/* Let's be optimistic about it's start. */
return BGWH_STARTED;
}
/* Validate that it's a valid database Oid */
Assert(datid != InvalidOid);
worker.bgw_main_arg = ObjectIdGetDatum(datid);
/*
* Register the work and wait until it shuts down. This enforces creation
* only one background worker process. So, don't have to implement any
* locking for error handling or file writing.
*/
RegisterDynamicBackgroundWorker(&worker, &handle);
return WaitForBackgroundWorkerShutdown(handle);
}
/*
* Returns string contain server uptime in seconds
*/
static long
server_uptime(void)
{
long secs;
int microsecs;
TimestampDifference(PgStartTime, GetCurrentTimestamp(), &secs, µsecs);
return secs;
}
/*
* Getting pg_settings values:
* -> name, units, setting, boot_val, and reset_val
*/
#define PT_SETTINGS_COL_COUNT 5
static void
write_pg_settings(void)
{
SPITupleTable *tuptable;
int spi_result;
char *query = "SELECT name, unit, setting, reset_val, boot_val FROM pg_settings where vartype != 'string'";
char msg[2048] = {0};
char msg_json[4096] = {0};
size_t sz_json;
FILE *fp;
int flags;
sz_json = sizeof(msg_json);
/* Open file in append mode. */
fp = json_file_open(ptss->dbtemp_filepath, "a+");
/* Construct and initiate the active extensions array block. */
construct_json_block(msg_json, sz_json, "", "settings", PT_JSON_ARRAY_START, &ptss->json_file_indent);
write_json_to_file(fp, msg_json);
SetCurrentStatementStartTimestamp();
StartTransactionCommand();
/* Initialize SPI */
if (SPI_connect() != SPI_OK_CONNECT)
{
ereport(ERROR, (errmsg("Failed to connect to SPI")));
}
PushActiveSnapshot(GetTransactionSnapshot());
/* Execute the query */
spi_result = SPI_execute(query, true, 0);
if (spi_result != SPI_OK_SELECT)
{
SPI_finish();
ereport(ERROR, (errmsg("Query failed execution.")));
}
/* Process the result */
if (SPI_processed > 0)
{
tuptable = SPI_tuptable;
for (int row_count = 0; row_count < SPI_processed; row_count++)
{
char *null_value = "NULL";
char *value_str[PT_SETTINGS_COL_COUNT];
/* Construct and initiate the active extensions array block. */
construct_json_block(msg_json, sz_json, "setting", "", PT_JSON_BLOCK_ARRAY_VALUE, &ptss->json_file_indent);
write_json_to_file(fp, msg_json);
/* Process the tuple as needed */
for (int col_count = 1; col_count <= tuptable->tupdesc->natts; col_count++)
{
char *str = SPI_getvalue(tuptable->vals[row_count], tuptable->tupdesc, col_count);
value_str[col_count - 1] = (str == NULL || str[0] == '\0') ? null_value : str;
flags = (col_count == tuptable->tupdesc->natts) ? (PT_JSON_BLOCK_SIMPLE | PT_JSON_BLOCK_LAST) : PT_JSON_BLOCK_SIMPLE;
construct_json_block(msg_json, sz_json, NameStr(tuptable->tupdesc->attrs[col_count - 1].attname),
value_str[col_count - 1], flags, &ptss->json_file_indent);
write_json_to_file(fp, msg_json);
}
/* Close the array */
construct_json_block(msg, sizeof(msg), "setting", "", PT_JSON_ARRAY_END | PT_JSON_BLOCK_LAST, &ptss->json_file_indent);
strcpy(msg_json, msg);
/* Close the extension block */
flags = (row_count == (SPI_processed - 1)) ? (PT_JSON_BLOCK_END | PT_JSON_BLOCK_LAST) : PT_JSON_BLOCK_END;
construct_json_block(msg, sizeof(msg), "setting", "", flags, &ptss->json_file_indent);
strlcat(msg_json, msg, sz_json);
/* Write both to file. */
write_json_to_file(fp, msg_json);
}
}
/* Close the array */
construct_json_block(msg, sizeof(msg), "settings", "", PT_JSON_ARRAY_END, &ptss->json_file_indent);
strcpy(msg_json, msg);
/* Write both to file. */
write_json_to_file(fp, msg_json);
/* Clean up */
fclose(fp);
/* Disconnect from SPI */
SPI_finish();
PopActiveSnapshot();
CommitTransactionCommand();
}
#undef PT_SETTINGS_COL_COUNT
/*
* Return a list of databases from the pg_database catalog
*/
static List *
get_database_list(void)
{
List *dblist = NIL;
Relation rel;
TableScanDesc scan;
HeapTuple tup;
MemoryContext oldcxt;
ScanKeyData key;
/* Start a transaction to access pg_database */
StartTransactionCommand();
rel = relation_open(DatabaseRelationId, AccessShareLock);
/* Ignore databases that we can't connect to */
ScanKeyInit(&key,
Anum_pg_database_datallowconn,
BTEqualStrategyNumber,
F_BOOLEQ,
BoolGetDatum(true));
scan = table_beginscan_catalog(rel, 1, &key);
while (HeapTupleIsValid(tup = heap_getnext(scan, ForwardScanDirection)))
{
PTDatabaseInfo *dbinfo;
int64 datsize;
Form_pg_database pgdatabase = (Form_pg_database) GETSTRUCT(tup);
datsize = DatumGetInt64(DirectFunctionCall1(pg_database_size_oid, ObjectIdGetDatum(pgdatabase->oid)));
/* Switch to our memory context instead of the transaction one */
oldcxt = MemoryContextSwitchTo(pt_cxt);
dbinfo = (PTDatabaseInfo *) palloc(sizeof(PTDatabaseInfo));
/* Fill in the structure */
dbinfo->datid = pgdatabase->oid;
strncpy(dbinfo->datname, NameStr(pgdatabase->datname), sizeof(dbinfo->datname));
dbinfo->datsize = datsize;
/* Add to the list */
dblist = lappend(dblist, dbinfo);
/* Switch back the memory context */
pt_cxt = MemoryContextSwitchTo(oldcxt);
}
/* Clean up */
table_endscan(scan);
relation_close(rel, AccessShareLock);
CommitTransactionCommand();
/* Return the list */
return dblist;
}
/*
* Get a list of installed extensions for a database
*/
static List *
get_extensions_list(PTDatabaseInfo *dbinfo, MemoryContext cxt)
{
List *extlist = NIL;
Relation rel;
TableScanDesc scan;
HeapTuple tup;
MemoryContext oldcxt;
Assert(dbinfo);
/* Start a transaction to access pg_extensions */
StartTransactionCommand();
/* Open the extension catalog... */
rel = table_open(ExtensionRelationId, AccessShareLock);
scan = table_beginscan_catalog(rel, 0, NULL);
while (HeapTupleIsValid(tup = heap_getnext(scan, ForwardScanDirection)))
{
PTExtensionInfo *extinfo;
Form_pg_extension extform = (Form_pg_extension) GETSTRUCT(tup);
/* Switch to the given memory context */
oldcxt = MemoryContextSwitchTo(cxt);
extinfo = (PTExtensionInfo *) palloc(sizeof(PTExtensionInfo));
/* Fill in the structure */
extinfo->db_data = dbinfo;
strncpy(extinfo->extname, NameStr(extform->extname), sizeof(extinfo->extname));
/* Add to the list */
extlist = lappend(extlist, extinfo);
/* Switch back the memory context */
cxt = MemoryContextSwitchTo(oldcxt);
}
/* Clean up */
table_endscan(scan);
table_close(rel, AccessShareLock);
CommitTransactionCommand();
/* Return the list */
return extlist;
}
/*
* Writes database information along with names of the active extensions to
* the file.
*/
static bool
write_database_info(PTDatabaseInfo *dbinfo, List *extlist)
{
char msg[2048] = {0};
char msg_json[4096] = {0};
size_t sz_json;
FILE *fp;
ListCell *lc;
int flags;
sz_json = sizeof(msg_json);
/* Open file in append mode. */
fp = json_file_open(ptss->dbtemp_filepath, "a+");
if (ptss->first_db_entry)
{
/* Construct and initiate the active extensions array block. */
construct_json_block(msg_json, sz_json, "", "databases", PT_JSON_ARRAY_START, &ptss->json_file_indent);
write_json_to_file(fp, msg_json);
}
/* Construct and initiate the active extensions array block. */
construct_json_block(msg_json, sz_json, "database", "value", PT_JSON_BLOCK_ARRAY_VALUE, &ptss->json_file_indent);
write_json_to_file(fp, msg_json);
/* Construct and write the database OID block. */
snprintf(msg, sizeof(msg), "%u", dbinfo->datid);
construct_json_block(msg_json, sz_json, "database_oid", msg, PT_JSON_BLOCK_SIMPLE, &ptss->json_file_indent);
write_json_to_file(fp, msg_json);
/* Construct and write the database size block. */
snprintf(msg, sizeof(msg), "%lu", dbinfo->datsize);
construct_json_block(msg_json, sz_json, "database_size", msg, PT_JSON_BLOCK_SIMPLE, &ptss->json_file_indent);
write_json_to_file(fp, msg_json);
/* Construct and initiate the active extensions array block. */
construct_json_block(msg_json, sz_json, "active_extensions", "value", PT_JSON_BLOCK_ARRAY_VALUE, &ptss->json_file_indent);
write_json_to_file(fp, msg_json);
/* Iterate through all extensions and those to the array. */
foreach(lc, extlist)
{
PTExtensionInfo *extinfo = lfirst(lc);
flags = (list_tail(extlist) == lc) ? (PT_JSON_BLOCK_SIMPLE | PT_JSON_BLOCK_LAST) : PT_JSON_BLOCK_SIMPLE;
construct_json_block(msg_json, sz_json, "extension_name", extinfo->extname, flags, &ptss->json_file_indent);
write_json_to_file(fp, msg_json);
}
/* Close the array and block and write to file */
construct_json_block(msg, sizeof(msg), "active_extensions", "active_extensions", PT_JSON_ARRAY_END | PT_JSON_BLOCK_END | PT_JSON_BLOCK_LAST, &ptss->json_file_indent);
strcpy(msg_json, msg);
write_json_to_file(fp, msg_json);
/* Close the array */
construct_json_block(msg, sizeof(msg), "database", "", PT_JSON_ARRAY_END | PT_JSON_BLOCK_LAST, &ptss->json_file_indent);
strcpy(msg_json, msg);
/* Close the database block */
flags = (ptss->last_db_entry) ? (PT_JSON_BLOCK_END | PT_JSON_BLOCK_LAST) : PT_JSON_BLOCK_END;
construct_json_block(msg, sizeof(msg), "database", "", flags, &ptss->json_file_indent);
strlcat(msg_json, msg, sz_json);
/* Write both to file. */
write_json_to_file(fp, msg_json);
if (ptss->last_db_entry)
{
/* Close the array */
construct_json_block(msg, sizeof(msg), "databases", "", PT_JSON_ARRAY_END | PT_JSON_BLOCK_LAST, &ptss->json_file_indent);
strcpy(msg_json, msg);
/* Write both to file. */
write_json_to_file(fp, msg_json);
}
/* Clean up */
fclose(fp);
return true;
}
/*
* Main function for the background launcher process
*/
void
percona_pg_telemetry_main(Datum main_arg)
{
int rc = 0;
List *dblist = NIL;
ListCell *lc = NULL;
char json_pg_version[1024];
FILE *fp;
char msg[2048] = {0};
char msg_json[4096] = {0};
size_t sz_json = sizeof(msg_json);
bool first_time = true;
/* Save the version in a JSON escaped stirng just to be safe. */
strcpy(json_pg_version, PG_VERSION);
/* Setup signal callbacks */
pqsignal(SIGTERM, pt_sigterm);
#if PG_VERSION_NUM >= 130000
pqsignal(SIGHUP, SignalHandlerForConfigReload);
#else
pqsignal(SIGHUP, PostgresSigHupHandler);
#endif
/* We can now receive signals */
BackgroundWorkerUnblockSignals();
/* Initialize shmem */
pt_shmem_init();
/* Load existing telemetry files */
load_telemetry_files();
/* Set up connection */
BackgroundWorkerInitializeConnectionByOid(InvalidOid, InvalidOid, 0);
/* Set name to make percona_pg_telemetry visible in pg_stat_activity */
pgstat_report_appname("percona_pg_telemetry");
/* This is the context that we will allocate our data in */
pt_cxt = AllocSetContextCreate(TopMemoryContext, "Percona Telemetry Context", ALLOCSET_DEFAULT_SIZES);
/* Should never really terminate unless... */
while (!sigterm_recvd && ptss->error_code == PT_SUCCESS)
{
/* Don't sleep the first time */
if (first_time == false)
{
rc = WaitLatch(MyLatch,
WL_LATCH_SET | WL_TIMEOUT | WL_POSTMASTER_DEATH,
scrape_interval * 1000L,
PG_WAIT_EXTENSION);
ResetLatch(MyLatch);
}
CHECK_FOR_INTERRUPTS();
if (ConfigReloadPending)
{
ConfigReloadPending = false;
ProcessConfigFile(PGC_SIGHUP);
}
/* Don't do any processing but keep the launcher alive */
if (telemetry_enabled == false)
continue;
/* Time to end the loop as the server is shutting down */
if ((rc & WL_POSTMASTER_DEATH) || ptss->error_code != PT_SUCCESS)
break;
/*
* We are not processing a cell at the moment. So, let's get the
* updated database list.
*/
if (dblist == NIL && (rc & WL_TIMEOUT || first_time))
{
char temp_buff[100];
/* Data collection will start now */
first_time = false;
dblist = get_database_list();
/* Set writing state to true */
Assert(ptss->write_in_progress == false);
ptss->write_in_progress = true;
/* Open file for writing. */
fp = json_file_open(ptss->dbtemp_filepath, "w");
construct_json_block(msg_json, sz_json, "", "", PT_JSON_BLOCK_START, &ptss->json_file_indent);
write_json_to_file(fp, msg_json);
/* Construct and write the database size block. */
pg_snprintf(msg, sizeof(msg), "%lu", GetSystemIdentifier());
construct_json_block(msg_json, sz_json, "db_instance_id", msg, PT_JSON_KEY_VALUE_PAIR, &ptss->json_file_indent);
write_json_to_file(fp, msg_json);
/* Construct and initiate the active extensions array block. */
construct_json_block(msg_json, sz_json, "pillar_version", json_pg_version, PT_JSON_KEY_VALUE_PAIR, &ptss->json_file_indent);
write_json_to_file(fp, msg_json);
/* Construct and initiate the active extensions array block. */
pg_snprintf(msg, sizeof(msg), "%ld", server_uptime());
construct_json_block(msg_json, sz_json, "uptime", msg, PT_JSON_KEY_VALUE_PAIR, &ptss->json_file_indent);
write_json_to_file(fp, msg_json);
/* Construct and initiate the active extensions array block. */
pg_snprintf(temp_buff, sizeof(temp_buff), "%d", list_length(dblist));