forked from gridl/pg_wait_sampling
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcollector.c
427 lines (368 loc) · 10 KB
/
collector.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
/*
* collector.c
* Collector of wait event history and profile.
*
* Copyright (c) 2015-2016, Postgres Professional
*
* IDENTIFICATION
* contrib/pg_wait_sampling/pg_wait_sampling.c
*/
#include "postgres.h"
#include "catalog/pg_type.h"
#include "funcapi.h"
#include "miscadmin.h"
#include "postmaster/bgworker.h"
#include "storage/ipc.h"
#include "storage/procarray.h"
#include "storage/procsignal.h"
#include "storage/shm_mq.h"
#include "storage/shm_toc.h"
#include "storage/spin.h"
#include "utils/memutils.h"
#include "utils/resowner.h"
#include "pgstat.h"
#include "pg_wait_sampling.h"
static volatile sig_atomic_t shutdown_requested = false;
static void handle_sigterm(SIGNAL_ARGS);
/*
* Register background worker for collecting waits history.
*/
void
register_wait_collector(void)
{
BackgroundWorker worker;
/* Set up background worker parameters */
worker.bgw_flags = BGWORKER_SHMEM_ACCESS;
worker.bgw_start_time = BgWorkerStart_ConsistentState;
worker.bgw_restart_time = 0;
worker.bgw_notify_pid = 0;
#if PG_VERSION_NUM >= 100000
memcpy(worker.bgw_library_name, "pg_wait_sampling", BGW_MAXLEN);
memcpy(worker.bgw_function_name, CppAsString(collector_main), BGW_MAXLEN);
#else
worker.bgw_main = collector_main;
#endif
snprintf(worker.bgw_name, BGW_MAXLEN, "pg_wait_sampling collector");
worker.bgw_main_arg = (Datum)0;
RegisterBackgroundWorker(&worker);
}
/*
* Allocate memory for waits history.
*/
void
alloc_history(History *observations, int count)
{
observations->items = (HistoryItem *) palloc0(sizeof(HistoryItem) * count);
observations->index = 0;
observations->count = count;
observations->wraparound = false;
}
/*
* Reallocate memory for changed number of history items.
*/
static void
realloc_history(History *observations, int count)
{
HistoryItem *newitems;
int copyCount,
i,
j;
/* Allocate new array for history */
newitems = (HistoryItem *) palloc0(sizeof(HistoryItem) * count);
/* Copy entries from old array to the new */
if (observations->wraparound)
copyCount = observations->count;
else
copyCount = observations->index;
copyCount = Min(copyCount, count);
i = 0;
if (observations->wraparound)
j = observations->index + 1;
else
j = 0;
while (i < copyCount)
{
if (j >= observations->count)
j = 0;
memcpy(&newitems[i], &observations->items[j], sizeof(HistoryItem));
i++;
j++;
}
/* Switch to new history array */
pfree(observations->items);
observations->items = newitems;
observations->index = copyCount;
observations->count = count;
observations->wraparound = false;
}
static void
handle_sigterm(SIGNAL_ARGS)
{
int save_errno = errno;
shutdown_requested = true;
if (MyProc)
SetLatch(&MyProc->procLatch);
errno = save_errno;
}
/*
* Get next item of history with rotation.
*/
static HistoryItem *
get_next_observation(History *observations)
{
HistoryItem *result;
if (observations->index >= observations->count)
{
observations->index = 0;
observations->wraparound = true;
}
result = &observations->items[observations->index];
observations->index++;
return result;
}
/*
* Read current waits from backends and write them to history array
* and/or profile hash.
*/
static void
probe_waits(History *observations, HTAB *profile_hash,
bool write_history, bool write_profile, bool profile_pid)
{
int i,
newSize;
TimestampTz ts = GetCurrentTimestamp();
/* Realloc waits history if needed */
newSize = collector_hdr->historySize;
if (observations->count != newSize)
realloc_history(observations, newSize);
/* Iterate PGPROCs under shared lock */
LWLockAcquire(ProcArrayLock, LW_SHARED);
for (i = 0; i < ProcGlobal->allProcCount; i++)
{
HistoryItem item,
*observation;
PGPROC *proc = &ProcGlobal->allProcs[i];
if (proc->pid == 0)
continue;
/* Collect next wait event sample */
item.pid = proc->pid;
item.wait_event_info = proc->wait_event_info;
item.ts = ts;
/* Write to the history if needed */
if (write_history)
{
observation = get_next_observation(observations);
*observation = item;
}
/* Write to the profile if needed */
if (write_profile)
{
ProfileItem *profileItem;
bool found;
if (!profile_pid)
item.pid = 0;
profileItem = (ProfileItem *) hash_search(profile_hash, &item, HASH_ENTER, &found);
if (found)
profileItem->count++;
else
profileItem->count = 1;
}
}
LWLockRelease(ProcArrayLock);
}
/*
* Send waits history to shared memory queue.
*/
static void
send_history(History *observations, shm_mq_handle *mqh)
{
Size count,
i;
if (observations->wraparound)
count = observations->count;
else
count = observations->index;
shm_mq_send(mqh, sizeof(count), &count, false);
for (i = 0; i < count; i++)
shm_mq_send(mqh, sizeof(HistoryItem), &observations->items[i], false);
}
/*
* Send profile to shared memory queue.
*/
static void
send_profile(HTAB *profile_hash, shm_mq_handle *mqh)
{
HASH_SEQ_STATUS scan_status;
ProfileItem *item;
Size count = hash_get_num_entries(profile_hash);
shm_mq_send(mqh, sizeof(count), &count, false);
hash_seq_init(&scan_status, profile_hash);
while ((item = (ProfileItem *) hash_seq_search(&scan_status)) != NULL)
{
shm_mq_send(mqh, sizeof(ProfileItem), item, false);
}
}
/*
* Make hash table for wait profile.
*/
static HTAB *
make_profile_hash()
{
HASHCTL hash_ctl;
hash_ctl.hash = tag_hash;
hash_ctl.hcxt = TopMemoryContext;
hash_ctl.keysize = offsetof(ProfileItem, count);
hash_ctl.entrysize = sizeof(ProfileItem);
return hash_create("Waits profile hash", 1024, &hash_ctl,
HASH_FUNCTION | HASH_ELEM);
}
/*
* Delta between two timestamps in milliseconds.
*/
static int64
millisecs_diff(TimestampTz tz1, TimestampTz tz2)
{
long secs;
int millisecs;
TimestampDifference(tz1, tz2, &secs, &millisecs);
return secs * 1000 + millisecs;
}
/*
* Main routine of wait history collector.
*/
void
collector_main(Datum main_arg)
{
HTAB *profile_hash = NULL;
History observations;
MemoryContext old_context,
collector_context;
TimestampTz current_ts,
history_ts,
profile_ts;
/*
* Establish signal handlers.
*
* We want CHECK_FOR_INTERRUPTS() to kill off this worker process just as
* it would a normal user backend. To make that happen, we establish a
* signal handler that is a stripped-down version of die(). We don't have
* any equivalent of the backend's command-read loop, where interrupts can
* be processed immediately, so make sure ImmediateInterruptOK is turned
* off.
*/
pqsignal(SIGTERM, handle_sigterm);
BackgroundWorkerUnblockSignals();
profile_hash = make_profile_hash();
collector_hdr->latch = &MyProc->procLatch;
CurrentResourceOwner = ResourceOwnerCreate(NULL, "pg_wait_sampling collector");
collector_context = AllocSetContextCreate(TopMemoryContext,
"pg_wait_sampling context",
ALLOCSET_DEFAULT_MINSIZE,
ALLOCSET_DEFAULT_INITSIZE,
ALLOCSET_DEFAULT_MAXSIZE);
old_context = MemoryContextSwitchTo(collector_context);
alloc_history(&observations, collector_hdr->historySize);
MemoryContextSwitchTo(old_context);
/* Start counting time for history and profile samples */
profile_ts = history_ts = GetCurrentTimestamp();
while (1)
{
int rc;
shm_mq_handle *mqh;
int64 history_diff,
profile_diff;
int history_period,
profile_period;
bool write_history,
write_profile;
/* Wait calculate time to next sample for history or profile */
current_ts = GetCurrentTimestamp();
history_diff = millisecs_diff(history_ts, current_ts);
profile_diff = millisecs_diff(profile_ts, current_ts);
history_period = collector_hdr->historyPeriod;
profile_period = collector_hdr->profilePeriod;
write_history = (history_diff >= (int64)history_period);
write_profile = (profile_diff >= (int64)profile_period);
if (write_history || write_profile)
{
probe_waits(&observations, profile_hash,
write_history, write_profile, collector_hdr->profilePid);
if (write_history)
{
history_ts = current_ts;
history_diff = 0;
}
if (write_profile)
{
profile_ts = current_ts;
profile_diff = 0;
}
}
/* Shutdown if requested */
if (shutdown_requested)
break;
/*
* Wait until next sample time or request to do something through
* shared memory.
*/
#if PG_VERSION_NUM >= 100000
rc = WaitLatch(&MyProc->procLatch, WL_LATCH_SET | WL_TIMEOUT | WL_POSTMASTER_DEATH,
Min(history_period - (int)history_diff,
profile_period - (int)profile_diff), PG_WAIT_EXTENSION);
#else
rc = WaitLatch(&MyProc->procLatch, WL_LATCH_SET | WL_TIMEOUT | WL_POSTMASTER_DEATH,
Min(history_period - (int)history_diff,
profile_period - (int)profile_diff));
#endif
if (rc & WL_POSTMASTER_DEATH)
proc_exit(1);
ResetLatch(&MyProc->procLatch);
/* Handle request if any */
if (collector_hdr->request != NO_REQUEST)
{
LOCKTAG tag;
SHMRequest request = collector_hdr->request;
init_lock_tag(&tag, PGWS_COLLECTOR_LOCK);
LockAcquire(&tag, ExclusiveLock, false, false);
collector_hdr->request = NO_REQUEST;
if (request == HISTORY_REQUEST || request == PROFILE_REQUEST)
{
/* Send history or profile */
shm_mq_set_sender(collector_mq, MyProc);
mqh = shm_mq_attach(collector_mq, NULL, NULL);
shm_mq_wait_for_attach(mqh);
if (shm_mq_get_receiver(collector_mq) != NULL)
{
if (request == HISTORY_REQUEST)
{
send_history(&observations, mqh);
}
else if (request == PROFILE_REQUEST)
{
send_profile(profile_hash, mqh);
}
}
#if PG_VERSION_NUM >= 100000
shm_mq_detach(mqh);
#else
shm_mq_detach(collector_mq);
#endif
}
else if (request == PROFILE_RESET)
{
/* Reset profile hash */
hash_destroy(profile_hash);
profile_hash = make_profile_hash();
}
LockRelease(&tag, ExclusiveLock, false);
}
}
MemoryContextReset(collector_context);
/*
* We're done. Explicitly detach the shared memory segment so that we
* don't get a resource leak warning at commit time. This will fire any
* on_dsm_detach callbacks we've registered, as well. Once that's done,
* we can go ahead and exit.
*/
proc_exit(0);
}