Skip to content

Commit 330539e

Browse files
committed
Add callback to mem_guard if loaded
Add code to call mem_guard to enable memory tracking for background workers. This is enabled for all background workers started by timescaledb, but not to other workers started by PostgreSQL.
1 parent 9115e12 commit 330539e

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed

.unreleased/pr_7788

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Implements: #7788 Add callback to mem_guard for background workers

src/bgw/job.c

+52
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,50 @@
5656
static scheduler_test_hook_type scheduler_test_hook = NULL;
5757
static char *job_entrypoint_function_name = "ts_bgw_job_entrypoint";
5858

59+
/*
60+
* This is copied from mem_guard and have to be the same as the type in
61+
* mem_guard.
62+
*
63+
* These are intended as an interim solution and will be removed once we have
64+
* a stable plugin ABI for TimescaleDB.
65+
*/
66+
67+
#define MG_CALLBACKS_VERSION 1
68+
#define MG_CALLBACKS_VAR_NAME "mg_callbacks"
69+
70+
typedef void (*mg_toggle_allocation_blocking)(bool enable);
71+
typedef size_t (*mg_get_allocated_memory)();
72+
typedef size_t (*mg_get_total_allocated_memory)();
73+
typedef bool (*mg_enabled)();
74+
75+
typedef struct MGCallbacks
76+
{
77+
int64 version_num;
78+
mg_toggle_allocation_blocking toggle_allocation_blocking;
79+
mg_get_allocated_memory get_allocated_memory;
80+
mg_get_total_allocated_memory get_total_allocated_memory;
81+
mg_enabled enabled;
82+
} MGCallbacks;
83+
84+
/*
85+
* Get the mem_guard callbacks.
86+
*
87+
* You might get a NULL pointer back if there are no mem_guard installed, so
88+
* check before using.
89+
*/
90+
static MGCallbacks *
91+
get_mem_guard_callbacks()
92+
{
93+
static MGCallbacks **mem_guard_callback_ptr = NULL;
94+
95+
if (mem_guard_callback_ptr)
96+
return *mem_guard_callback_ptr;
97+
98+
mem_guard_callback_ptr = (MGCallbacks **) find_rendezvous_variable(MG_CALLBACKS_VAR_NAME);
99+
100+
return *mem_guard_callback_ptr;
101+
}
102+
59103
typedef enum JobLockLifetime
60104
{
61105
SESSION_LOCK = 0,
@@ -1141,6 +1185,14 @@ ts_bgw_job_entrypoint(PG_FUNCTION_ARGS)
11411185
pqsignal(SIGTERM, die);
11421186
BackgroundWorkerUnblockSignals();
11431187

1188+
/*
1189+
* Set up mem_guard before starting to allocate memory.
1190+
*/
1191+
MGCallbacks *callbacks = get_mem_guard_callbacks();
1192+
if (callbacks && callbacks->version_num == MG_CALLBACKS_VERSION &&
1193+
callbacks->toggle_allocation_blocking && !callbacks->enabled)
1194+
callbacks->toggle_allocation_blocking(/*enable=*/true);
1195+
11441196
BackgroundWorkerInitializeConnectionByOid(db_oid, params.user_oid, 0);
11451197

11461198
log_min_messages = ts_guc_bgw_log_level;

0 commit comments

Comments
 (0)