| 1 |
/*------------------------------------------------------------------------- |
| 2 |
* |
| 3 |
* autoprewarm.c |
| 4 |
* Periodically dump information about the blocks present in |
| 5 |
* shared_buffers, and reload them on server restart. |
| 6 |
* |
| 7 |
* Due to locking considerations, we can't actually begin prewarming |
| 8 |
* until the server reaches a consistent state. We need the catalogs |
| 9 |
* to be consistent so that we can figure out which relation to lock, |
| 10 |
* and we need to lock the relations so that we don't try to prewarm |
| 11 |
* pages from a relation that is in the process of being dropped. |
| 12 |
* |
| 13 |
* While prewarming, autoprewarm will use two workers. There's a |
| 14 |
* leader worker that reads and sorts the list of blocks to be |
| 15 |
* prewarmed and then launches a per-database worker for each |
| 16 |
* relevant database in turn. The former keeps running after the |
| 17 |
* initial prewarm is complete to update the dump file periodically. |
| 18 |
* |
| 19 |
* Copyright (c) 2016-2025, PostgreSQL Global Development Group |
| 20 |
* |
| 21 |
* IDENTIFICATION |
| 22 |
* contrib/pg_prewarm/autoprewarm.c |
| 23 |
* |
| 24 |
*------------------------------------------------------------------------- |
| 25 |
*/ |
| 26 |
|
| 27 |
#include "postgres.h" |
| 28 |
|
| 29 |
#include <unistd.h> |
| 30 |
|
| 31 |
#include "access/relation.h" |
| 32 |
#include "access/xact.h" |
| 33 |
#include "pgstat.h" |
| 34 |
#include "postmaster/bgworker.h" |
| 35 |
#include "postmaster/interrupt.h" |
| 36 |
#include "storage/buf_internals.h" |
| 37 |
#include "storage/dsm.h" |
| 38 |
#include "storage/dsm_registry.h" |
| 39 |
#include "storage/fd.h" |
| 40 |
#include "storage/ipc.h" |
| 41 |
#include "storage/latch.h" |
| 42 |
#include "storage/lwlock.h" |
| 43 |
#include "storage/procsignal.h" |
| 44 |
#include "storage/read_stream.h" |
| 45 |
#include "storage/smgr.h" |
| 46 |
#include "tcop/tcopprot.h" |
| 47 |
#include "utils/guc.h" |
| 48 |
#include "utils/rel.h" |
| 49 |
#include "utils/relfilenumbermap.h" |
| 50 |
#include "utils/timestamp.h" |
| 51 |
|
| 52 |
#define AUTOPREWARM_FILE "autoprewarm.blocks" |
| 53 |
|
| 54 |
/* Metadata for each block we dump. */ |
| 55 |
typedef struct BlockInfoRecord |
| 56 |
{ |
| 57 |
Oid database; |
| 58 |
Oid tablespace; |
| 59 |
RelFileNumber filenumber; |
| 60 |
ForkNumber forknum; |
| 61 |
BlockNumber blocknum; |
| 62 |
} BlockInfoRecord; |
| 63 |
|
| 64 |
/* Shared state information for autoprewarm bgworker. */ |
| 65 |
typedef struct AutoPrewarmSharedState |
| 66 |
{ |
| 67 |
LWLock lock; /* mutual exclusion */ |
| 68 |
pid_t bgworker_pid; /* for main bgworker */ |
| 69 |
pid_t pid_using_dumpfile; /* for autoprewarm or block dump */ |
| 70 |
|
| 71 |
/* Following items are for communication with per-database worker */ |
| 72 |
dsm_handle block_info_handle; |
| 73 |
Oid database; |
| 74 |
int prewarm_start_idx; |
| 75 |
int prewarm_stop_idx; |
| 76 |
int prewarmed_blocks; |
| 77 |
} AutoPrewarmSharedState; |
| 78 |
|
| 79 |
/* |
| 80 |
* Private data passed through the read stream API for our use in the |
| 81 |
* callback. |
| 82 |
*/ |
| 83 |
typedef struct AutoPrewarmReadStreamData |
| 84 |
{ |
| 85 |
/* The array of records containing the blocks we should prewarm. */ |
| 86 |
BlockInfoRecord *block_info; |
| 87 |
|
| 88 |
/* |
| 89 |
* pos is the read stream callback's index into block_info. Because the |
| 90 |
* read stream may read ahead, pos is likely to be ahead of the index in |
| 91 |
* the main loop in autoprewarm_database_main(). |
| 92 |
*/ |
| 93 |
int pos; |
| 94 |
Oid tablespace; |
| 95 |
RelFileNumber filenumber; |
| 96 |
ForkNumber forknum; |
| 97 |
BlockNumber nblocks; |
| 98 |
} AutoPrewarmReadStreamData; |
| 99 |
|
| 100 |
|
| 101 |
PGDLLEXPORT void autoprewarm_main(Datum main_arg); |
| 102 |
PGDLLEXPORT void autoprewarm_database_main(Datum main_arg); |
| 103 |
|
| 104 |
PG_FUNCTION_INFO_V1(autoprewarm_start_worker); |
| 105 |
PG_FUNCTION_INFO_V1(autoprewarm_dump_now); |
| 106 |
|
| 107 |
static void apw_load_buffers(void); |
| 108 |
static int apw_dump_now(bool is_bgworker, bool dump_unlogged); |
| 109 |
static void apw_start_leader_worker(void); |
| 110 |
static void apw_start_database_worker(void); |
| 111 |
static bool apw_init_shmem(void); |
| 112 |
static void apw_detach_shmem(int code, Datum arg); |
| 113 |
static int apw_compare_blockinfo(const void *p, const void *q); |
| 114 |
|
| 115 |
/* Pointer to shared-memory state. */ |
| 116 |
static AutoPrewarmSharedState *apw_state = NULL; |
| 117 |
|
| 118 |
/* GUC variables. */ |
| 119 |
static bool autoprewarm = true; /* start worker? */ |
| 120 |
static int autoprewarm_interval = 300; /* dump interval */ |
| 121 |
|
| 122 |
/* |
| 123 |
* Module load callback. |
| 124 |
*/ |
| 125 |
void |
| 126 |
_PG_init(void) |
| 127 |
{ |
| 128 |
DefineCustomIntVariable("pg_prewarm.autoprewarm_interval", |
| 129 |
"Sets the interval between dumps of shared buffers", |
| 130 |
"If set to zero, time-based dumping is disabled.", |
| 131 |
&autoprewarm_interval, |
| 132 |
300, |
| 133 |
0, INT_MAX / 1000, |
| 134 |
PGC_SIGHUP, |
| 135 |
GUC_UNIT_S, |
| 136 |
NULL, |
| 137 |
NULL, |
| 138 |
NULL); |
| 139 |
|
| 140 |
if (!process_shared_preload_libraries_in_progress) |
| 141 |
return; |
| 142 |
|
| 143 |
/* can't define PGC_POSTMASTER variable after startup */ |
| 144 |
DefineCustomBoolVariable("pg_prewarm.autoprewarm", |
| 145 |
"Starts the autoprewarm worker.", |
| 146 |
NULL, |
| 147 |
&autoprewarm, |
| 148 |
true, |
| 149 |
PGC_POSTMASTER, |
| 150 |
0, |
| 151 |
NULL, |
| 152 |
NULL, |
| 153 |
NULL); |
| 154 |
|
| 155 |
MarkGUCPrefixReserved("pg_prewarm"); |
| 156 |
|
| 157 |
/* Register autoprewarm worker, if enabled. */ |
| 158 |
if (autoprewarm) |
| 159 |
apw_start_leader_worker(); |
| 160 |
} |
| 161 |
|
| 162 |
/* |
| 163 |
* Main entry point for the leader autoprewarm process. Per-database workers |
| 164 |
* have a separate entry point. |
| 165 |
*/ |
| 166 |
void |
| 167 |
autoprewarm_main(Datum main_arg) |
| 168 |
{ |
| 169 |
bool first_time = true; |
| 170 |
bool final_dump_allowed = true; |
| 171 |
TimestampTz last_dump_time = 0; |
| 172 |
|
| 173 |
/* Establish signal handlers; once that's done, unblock signals. */ |
| 174 |
pqsignal(SIGTERM, SignalHandlerForShutdownRequest); |
| 175 |
pqsignal(SIGHUP, SignalHandlerForConfigReload); |
| 176 |
pqsignal(SIGUSR1, procsignal_sigusr1_handler); |
| 177 |
BackgroundWorkerUnblockSignals(); |
| 178 |
|
| 179 |
/* Create (if necessary) and attach to our shared memory area. */ |
| 180 |
if (apw_init_shmem()) |
| 181 |
first_time = false; |
| 182 |
|
| 183 |
/* |
| 184 |
* Set on-detach hook so that our PID will be cleared on exit. |
| 185 |
* |
| 186 |
* NB: Autoprewarm's state is stored in a DSM segment, and DSM segments |
| 187 |
* are detached before calling the on_shmem_exit callbacks, so we must put |
| 188 |
* apw_detach_shmem in the before_shmem_exit callback list. |
| 189 |
*/ |
| 190 |
before_shmem_exit(apw_detach_shmem, 0); |
| 191 |
|
| 192 |
/* |
| 193 |
* Store our PID in the shared memory area --- unless there's already |
| 194 |
* another worker running, in which case just exit. |
| 195 |
*/ |
| 196 |
LWLockAcquire(&apw_state->lock, LW_EXCLUSIVE); |
| 197 |
if (apw_state->bgworker_pid != InvalidPid) |
| 198 |
{ |
| 199 |
LWLockRelease(&apw_state->lock); |
| 200 |
ereport(LOG, |
| 201 |
(errmsg("autoprewarm worker is already running under PID %d", |
| 202 |
(int) apw_state->bgworker_pid))); |
| 203 |
return; |
| 204 |
} |
| 205 |
apw_state->bgworker_pid = MyProcPid; |
| 206 |
LWLockRelease(&apw_state->lock); |
| 207 |
|
| 208 |
/* |
| 209 |
* Preload buffers from the dump file only if we just created the shared |
| 210 |
* memory region. Otherwise, it's either already been done or shouldn't |
| 211 |
* be done - e.g. because the old dump file has been overwritten since the |
| 212 |
* server was started. |
| 213 |
* |
| 214 |
* There's not much point in performing a dump immediately after we finish |
| 215 |
* preloading; so, if we do end up preloading, consider the last dump time |
| 216 |
* to be equal to the current time. |
| 217 |
* |
| 218 |
* If apw_load_buffers() is terminated early by a shutdown request, |
| 219 |
* prevent dumping out our state below the loop, because we'd effectively |
| 220 |
* just truncate the saved state to however much we'd managed to preload. |
| 221 |
*/ |
| 222 |
if (first_time) |
| 223 |
{ |
| 224 |
apw_load_buffers(); |
| 225 |
final_dump_allowed = !ShutdownRequestPending; |
| 226 |
last_dump_time = GetCurrentTimestamp(); |
| 227 |
} |
| 228 |
|
| 229 |
/* Periodically dump buffers until terminated. */ |
| 230 |
while (!ShutdownRequestPending) |
| 231 |
{ |
| 232 |
/* In case of a SIGHUP, just reload the configuration. */ |
| 233 |
if (ConfigReloadPending) |
| 234 |
{ |
| 235 |
ConfigReloadPending = false; |
| 236 |
ProcessConfigFile(PGC_SIGHUP); |
| 237 |
} |
| 238 |
|
| 239 |
if (autoprewarm_interval <= 0) |
| 240 |
{ |
| 241 |
/* We're only dumping at shutdown, so just wait forever. */ |
| 242 |
(void) WaitLatch(MyLatch, |
| 243 |
WL_LATCH_SET | WL_EXIT_ON_PM_DEATH, |
| 244 |
-1L, |
| 245 |
PG_WAIT_EXTENSION); |
| 246 |
} |
| 247 |
else |
| 248 |
{ |
| 249 |
TimestampTz next_dump_time; |
| 250 |
long delay_in_ms; |
| 251 |
|
| 252 |
/* Compute the next dump time. */ |
| 253 |
next_dump_time = |
| 254 |
TimestampTzPlusMilliseconds(last_dump_time, |
| 255 |
autoprewarm_interval * 1000); |
| 256 |
delay_in_ms = |
| 257 |
TimestampDifferenceMilliseconds(GetCurrentTimestamp(), |
| 258 |
next_dump_time); |
| 259 |
|
| 260 |
/* Perform a dump if it's time. */ |
| 261 |
if (delay_in_ms <= 0) |
| 262 |
{ |
| 263 |
last_dump_time = GetCurrentTimestamp(); |
| 264 |
apw_dump_now(true, false); |
| 265 |
continue; |
| 266 |
} |
| 267 |
|
| 268 |
/* Sleep until the next dump time. */ |
| 269 |
(void) WaitLatch(MyLatch, |
| 270 |
WL_LATCH_SET | WL_TIMEOUT | WL_EXIT_ON_PM_DEATH, |
| 271 |
delay_in_ms, |
| 272 |
PG_WAIT_EXTENSION); |
| 273 |
} |
| 274 |
|
| 275 |
/* Reset the latch, loop. */ |
| 276 |
ResetLatch(MyLatch); |
| 277 |
} |
| 278 |
|
| 279 |
/* |
| 280 |
* Dump one last time. We assume this is probably the result of a system |
| 281 |
* shutdown, although it's possible that we've merely been terminated. |
| 282 |
*/ |
| 283 |
if (final_dump_allowed) |
| 284 |
apw_dump_now(true, true); |
| 285 |
} |
| 286 |
|
| 287 |
/* |
| 288 |
* Read the dump file and launch per-database workers one at a time to |
| 289 |
* prewarm the buffers found there. |
| 290 |
*/ |
| 291 |
static void |
| 292 |
apw_load_buffers(void) |
| 293 |
{ |
| 294 |
FILE *file = NULL; |
| 295 |
int num_elements, |
| 296 |
i; |
| 297 |
BlockInfoRecord *blkinfo; |
| 298 |
dsm_segment *seg; |
| 299 |
|
| 300 |
/* |
| 301 |
* Skip the prewarm if the dump file is in use; otherwise, prevent any |
| 302 |
* other process from writing it while we're using it. |
| 303 |
*/ |
| 304 |
LWLockAcquire(&apw_state->lock, LW_EXCLUSIVE); |
| 305 |
if (apw_state->pid_using_dumpfile == InvalidPid) |
| 306 |
apw_state->pid_using_dumpfile = MyProcPid; |
| 307 |
else |
| 308 |
{ |
| 309 |
LWLockRelease(&apw_state->lock); |
| 310 |
ereport(LOG, |
| 311 |
(errmsg("skipping prewarm because block dump file is being written by PID %d", |
| 312 |
(int) apw_state->pid_using_dumpfile))); |
| 313 |
return; |
| 314 |
} |
| 315 |
LWLockRelease(&apw_state->lock); |
| 316 |
|
| 317 |
/* |
| 318 |
* Open the block dump file. Exit quietly if it doesn't exist, but report |
| 319 |
* any other error. |
| 320 |
*/ |
| 321 |
file = AllocateFile(AUTOPREWARM_FILE, "r"); |
| 322 |
if (!file) |
| 323 |
{ |
| 324 |
if (errno == ENOENT) |
| 325 |
{ |
| 326 |
LWLockAcquire(&apw_state->lock, LW_EXCLUSIVE); |
| 327 |
apw_state->pid_using_dumpfile = InvalidPid; |
| 328 |
LWLockRelease(&apw_state->lock); |
| 329 |
return; /* No file to load. */ |
| 330 |
} |
| 331 |
ereport(ERROR, |
| 332 |
(errcode_for_file_access(), |
| 333 |
errmsg("could not read file \"%s\": %m", |
| 334 |
AUTOPREWARM_FILE))); |
| 335 |
} |
| 336 |
|
| 337 |
/* First line of the file is a record count. */ |
| 338 |
if (fscanf(file, "<<%d>>\n", &num_elements) != 1) |
| 339 |
ereport(ERROR, |
| 340 |
(errcode_for_file_access(), |
| 341 |
errmsg("could not read from file \"%s\": %m", |
| 342 |
AUTOPREWARM_FILE))); |
| 343 |
|
| 344 |
/* Allocate a dynamic shared memory segment to store the record data. */ |
| 345 |
seg = dsm_create(sizeof(BlockInfoRecord) * num_elements, 0); |
| 346 |
blkinfo = (BlockInfoRecord *) dsm_segment_address(seg); |
| 347 |
|
| 348 |
/* Read records, one per line. */ |
| 349 |
for (i = 0; i < num_elements; i++) |
| 350 |
{ |
| 351 |
unsigned forknum; |
| 352 |
|
| 353 |
if (fscanf(file, "%u,%u,%u,%u,%u\n", &blkinfo[i].database, |
| 354 |
&blkinfo[i].tablespace, &blkinfo[i].filenumber, |
| 355 |
&forknum, &blkinfo[i].blocknum) != 5) |
| 356 |
ereport(ERROR, |
| 357 |
(errmsg("autoprewarm block dump file is corrupted at line %d", |
| 358 |
i + 1))); |
| 359 |
blkinfo[i].forknum = forknum; |
| 360 |
} |
| 361 |
|
| 362 |
FreeFile(file); |
| 363 |
|
| 364 |
/* Sort the blocks to be loaded. */ |
| 365 |
qsort(blkinfo, num_elements, sizeof(BlockInfoRecord), |
| 366 |
apw_compare_blockinfo); |
| 367 |
|
| 368 |
/* Populate shared memory state. */ |
| 369 |
apw_state->block_info_handle = dsm_segment_handle(seg); |
| 370 |
apw_state->prewarm_start_idx = apw_state->prewarm_stop_idx = 0; |
| 371 |
apw_state->prewarmed_blocks = 0; |
| 372 |
|
| 373 |
/* Get the info position of the first block of the next database. */ |
| 374 |
while (apw_state->prewarm_start_idx < num_elements) |
| 375 |
{ |
| 376 |
int j = apw_state->prewarm_start_idx; |
| 377 |
Oid current_db = blkinfo[j].database; |
| 378 |
|
| 379 |
/* |
| 380 |
* Advance the prewarm_stop_idx to the first BlockInfoRecord that does |
| 381 |
* not belong to this database. |
| 382 |
*/ |
| 383 |
j++; |
| 384 |
while (j < num_elements) |
| 385 |
{ |
| 386 |
if (current_db != blkinfo[j].database) |
| 387 |
{ |
| 388 |
/* |
| 389 |
* Combine BlockInfoRecords for global objects with those of |
| 390 |
* the database. |
| 391 |
*/ |
| 392 |
if (current_db != InvalidOid) |
| 393 |
break; |
| 394 |
current_db = blkinfo[j].database; |
| 395 |
} |
| 396 |
|
| 397 |
j++; |
| 398 |
} |
| 399 |
|
| 400 |
/* |
| 401 |
* If we reach this point with current_db == InvalidOid, then only |
| 402 |
* BlockInfoRecords belonging to global objects exist. We can't |
| 403 |
* prewarm without a database connection, so just bail out. |
| 404 |
*/ |
| 405 |
if (current_db == InvalidOid) |
| 406 |
break; |
| 407 |
|
| 408 |
/* Configure stop point and database for next per-database worker. */ |
| 409 |
apw_state->prewarm_stop_idx = j; |
| 410 |
apw_state->database = current_db; |
| 411 |
Assert(apw_state->prewarm_start_idx < apw_state->prewarm_stop_idx); |
| 412 |
|
| 413 |
/* If we've run out of free buffers, don't launch another worker. */ |
| 414 |
if (!have_free_buffer()) |
| 415 |
break; |
| 416 |
|
| 417 |
/* |
| 418 |
* Likewise, don't launch if we've already been told to shut down. |
| 419 |
* (The launch would fail anyway, but we might as well skip it.) |
| 420 |
*/ |
| 421 |
if (ShutdownRequestPending) |
| 422 |
break; |
| 423 |
|
| 424 |
/* |
| 425 |
* Start a per-database worker to load blocks for this database; this |
| 426 |
* function will return once the per-database worker exits. |
| 427 |
*/ |
| 428 |
apw_start_database_worker(); |
| 429 |
|
| 430 |
/* Prepare for next database. */ |
| 431 |
apw_state->prewarm_start_idx = apw_state->prewarm_stop_idx; |
| 432 |
} |
| 433 |
|
| 434 |
/* Clean up. */ |
| 435 |
dsm_detach(seg); |
| 436 |
LWLockAcquire(&apw_state->lock, LW_EXCLUSIVE); |
| 437 |
apw_state->block_info_handle = DSM_HANDLE_INVALID; |
| 438 |
apw_state->pid_using_dumpfile = InvalidPid; |
| 439 |
LWLockRelease(&apw_state->lock); |
| 440 |
|
| 441 |
/* Report our success, if we were able to finish. */ |
| 442 |
if (!ShutdownRequestPending) |
| 443 |
ereport(LOG, |
| 444 |
(errmsg("autoprewarm successfully prewarmed %d of %d previously-loaded blocks", |
| 445 |
apw_state->prewarmed_blocks, num_elements))); |
| 446 |
} |
| 447 |
|
| 448 |
/* |
| 449 |
* Return the next block number of a specific relation and fork to read |
| 450 |
* according to the array of BlockInfoRecord. |
| 451 |
*/ |
| 452 |
static BlockNumber |
| 453 |
apw_read_stream_next_block(ReadStream *stream, |
| 454 |
void *callback_private_data, |
| 455 |
void *per_buffer_data) |
| 456 |
{ |
| 457 |
AutoPrewarmReadStreamData *p = callback_private_data; |
| 458 |
|
| 459 |
CHECK_FOR_INTERRUPTS(); |
| 460 |
|
| 461 |
while (p->pos < apw_state->prewarm_stop_idx) |
| 462 |
{ |
| 463 |
BlockInfoRecord blk = p->block_info[p->pos]; |
| 464 |
|
| 465 |
if (!have_free_buffer()) |
| 466 |
{ |
| 467 |
p->pos = apw_state->prewarm_stop_idx; |
| 468 |
return InvalidBlockNumber; |
| 469 |
} |
| 470 |
|
| 471 |
if (blk.tablespace != p->tablespace) |
| 472 |
return InvalidBlockNumber; |
| 473 |
|
| 474 |
if (blk.filenumber != p->filenumber) |
| 475 |
return InvalidBlockNumber; |
| 476 |
|
| 477 |
if (blk.forknum != p->forknum) |
| 478 |
return InvalidBlockNumber; |
| 479 |
|
| 480 |
p->pos++; |
| 481 |
|
| 482 |
/* |
| 483 |
* Check whether blocknum is valid and within fork file size. |
| 484 |
* Fast-forward through any invalid blocks. We want p->pos to reflect |
| 485 |
* the location of the next relation or fork before ending the stream. |
| 486 |
*/ |
| 487 |
if (blk.blocknum >= p->nblocks) |
| 488 |
continue; |
| 489 |
|
| 490 |
return blk.blocknum; |
| 491 |
} |
| 492 |
|
| 493 |
return InvalidBlockNumber; |
| 494 |
} |
| 495 |
|
| 496 |
/* |
| 497 |
* Prewarm all blocks for one database (and possibly also global objects, if |
| 498 |
* those got grouped with this database). |
| 499 |
*/ |
| 500 |
void |
| 501 |
autoprewarm_database_main(Datum main_arg) |
| 502 |
{ |
| 503 |
BlockInfoRecord *block_info; |
| 504 |
int i; |
| 505 |
BlockInfoRecord blk; |
| 506 |
dsm_segment *seg; |
| 507 |
|
| 508 |
/* Establish signal handlers; once that's done, unblock signals. */ |
| 509 |
pqsignal(SIGTERM, die); |
| 510 |
BackgroundWorkerUnblockSignals(); |
| 511 |
|
| 512 |
/* Connect to correct database and get block information. */ |
| 513 |
apw_init_shmem(); |
| 514 |
seg = dsm_attach(apw_state->block_info_handle); |
| 515 |
if (seg == NULL) |
| 516 |
ereport(ERROR, |
| 517 |
(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE), |
| 518 |
errmsg("could not map dynamic shared memory segment"))); |
| 519 |
BackgroundWorkerInitializeConnectionByOid(apw_state->database, InvalidOid, 0); |
| 520 |
block_info = (BlockInfoRecord *) dsm_segment_address(seg); |
| 521 |
|
| 522 |
i = apw_state->prewarm_start_idx; |
| 523 |
blk = block_info[i]; |
| 524 |
|
| 525 |
/* |
| 526 |
* Loop until we run out of blocks to prewarm or until we run out of free |
| 527 |
* buffers. |
| 528 |
*/ |
| 529 |
while (i < apw_state->prewarm_stop_idx && have_free_buffer()) |
| 530 |
{ |
| 531 |
Oid tablespace = blk.tablespace; |
| 532 |
RelFileNumber filenumber = blk.filenumber; |
| 533 |
Oid reloid; |
| 534 |
Relation rel; |
| 535 |
|
| 536 |
/* |
| 537 |
* All blocks between prewarm_start_idx and prewarm_stop_idx should |
| 538 |
* belong either to global objects or the same database. |
| 539 |
*/ |
| 540 |
Assert(blk.database == apw_state->database || blk.database == 0); |
| 541 |
|
| 542 |
StartTransactionCommand(); |
| 543 |
|
| 544 |
reloid = RelidByRelfilenumber(blk.tablespace, blk.filenumber); |
| 545 |
if (!OidIsValid(reloid) || |
| 546 |
(rel = try_relation_open(reloid, AccessShareLock)) == NULL) |
| 547 |
{ |
| 548 |
/* We failed to open the relation, so there is nothing to close. */ |
| 549 |
CommitTransactionCommand(); |
| 550 |
|
| 551 |
/* |
| 552 |
* Fast-forward to the next relation. We want to skip all of the |
| 553 |
* other records referencing this relation since we know we can't |
| 554 |
* open it. That way, we avoid repeatedly trying and failing to |
| 555 |
* open the same relation. |
| 556 |
*/ |
| 557 |
for (; i < apw_state->prewarm_stop_idx; i++) |
| 558 |
{ |
| 559 |
blk = block_info[i]; |
| 560 |
if (blk.tablespace != tablespace || |
| 561 |
blk.filenumber != filenumber) |
| 562 |
break; |
| 563 |
} |
| 564 |
|
| 565 |
/* Time to try and open our newfound relation */ |
| 566 |
continue; |
| 567 |
} |
| 568 |
|
| 569 |
/* |
| 570 |
* We have a relation; now let's loop until we find a valid fork of |
| 571 |
* the relation or we run out of free buffers. Once we've read from |
| 572 |
* all valid forks or run out of options, we'll close the relation and |
| 573 |
* move on. |
| 574 |
*/ |
| 575 |
while (i < apw_state->prewarm_stop_idx && |
| 576 |
have_free_buffer()) |
| 577 |
{ |
| 578 |
ForkNumber forknum; |
| 579 |
BlockNumber nblocks; |
| 580 |
struct AutoPrewarmReadStreamData p; |
| 581 |
ReadStream *stream; |
| 582 |
Buffer buf; |
| 583 |
|
| 584 |
blk = block_info[i]; |
| 585 |
|
| 586 |
/* Stop when we reach a different relation. */ |
| 587 |
if (blk.tablespace != tablespace || |
| 588 |
blk.filenumber != filenumber) |
| 589 |
break; |
| 590 |
|
| 591 |
forknum = blk.forknum; |
| 592 |
|
| 593 |
/* |
| 594 |
* smgrexists is not safe for illegal forknum, hence check whether |
| 595 |
* the passed forknum is valid before using it in smgrexists. |
| 596 |
*/ |
| 597 |
if (blk.forknum <= InvalidForkNumber || |
| 598 |
blk.forknum > MAX_FORKNUM || |
| 599 |
!smgrexists(RelationGetSmgr(rel), blk.forknum)) |
| 600 |
{ |
| 601 |
/* |
| 602 |
* Fast-forward to the next fork. We want to skip all of the |
| 603 |
* other records referencing this fork since we already know |
| 604 |
* it's not valid. |
| 605 |
*/ |
| 606 |
for (; i < apw_state->prewarm_stop_idx; i++) |
| 607 |
{ |
| 608 |
blk = block_info[i]; |
| 609 |
if (blk.tablespace != tablespace || |
| 610 |
blk.filenumber != filenumber || |
| 611 |
blk.forknum != forknum) |
| 612 |
break; |
| 613 |
} |
| 614 |
|
| 615 |
/* Time to check if this newfound fork is valid */ |
| 616 |
continue; |
| 617 |
} |
| 618 |
|
| 619 |
nblocks = RelationGetNumberOfBlocksInFork(rel, blk.forknum); |
| 620 |
|
| 621 |
p = (struct AutoPrewarmReadStreamData) |
| 622 |
{ |
| 623 |
.block_info = block_info, |
| 624 |
.pos = i, |
| 625 |
.tablespace = tablespace, |
| 626 |
.filenumber = filenumber, |
| 627 |
.forknum = forknum, |
| 628 |
.nblocks = nblocks, |
| 629 |
}; |
| 630 |
|
| 631 |
stream = read_stream_begin_relation(READ_STREAM_MAINTENANCE | |
| 632 |
READ_STREAM_DEFAULT | |
| 633 |
READ_STREAM_USE_BATCHING, |
| 634 |
NULL, |
| 635 |
rel, |
| 636 |
p.forknum, |
| 637 |
apw_read_stream_next_block, |
| 638 |
&p, |
| 639 |
0); |
| 640 |
|
| 641 |
/* |
| 642 |
* Loop until we've prewarmed all the blocks from this fork. The |
| 643 |
* read stream callback will check that we still have free buffers |
| 644 |
* before requesting each block from the read stream API. |
| 645 |
*/ |
| 646 |
while ((buf = read_stream_next_buffer(stream, NULL)) != InvalidBuffer) |
| 647 |
{ |
| 648 |
apw_state->prewarmed_blocks++; |
| 649 |
ReleaseBuffer(buf); |
| 650 |
} |
| 651 |
|
| 652 |
read_stream_end(stream); |
| 653 |
|
| 654 |
/* |
| 655 |
* Advance i past all the blocks just prewarmed. Note that the |
| 656 |
* callback might have advanced the index beyond the last valid |
| 657 |
* block, so don't access block_info[i] yet. |
| 658 |
*/ |
| 659 |
i = p.pos; |
| 660 |
} |
| 661 |
|
| 662 |
relation_close(rel, AccessShareLock); |
| 663 |
CommitTransactionCommand(); |
| 664 |
} |
| 665 |
|
| 666 |
dsm_detach(seg); |
| 667 |
} |
| 668 |
|
| 669 |
/* |
| 670 |
* Dump information on blocks in shared buffers. We use a text format here |
| 671 |
* so that it's easy to understand and even change the file contents if |
| 672 |
* necessary. |
| 673 |
* Returns the number of blocks dumped. |
| 674 |
*/ |
| 675 |
static int |
| 676 |
apw_dump_now(bool is_bgworker, bool dump_unlogged) |
| 677 |
{ |
| 678 |
int num_blocks; |
| 679 |
int i; |
| 680 |
int ret; |
| 681 |
BlockInfoRecord *block_info_array; |
| 682 |
BufferDesc *bufHdr; |
| 683 |
FILE *file; |
| 684 |
char transient_dump_file_path[MAXPGPATH]; |
| 685 |
pid_t pid; |
| 686 |
|
| 687 |
LWLockAcquire(&apw_state->lock, LW_EXCLUSIVE); |
| 688 |
pid = apw_state->pid_using_dumpfile; |
| 689 |
if (apw_state->pid_using_dumpfile == InvalidPid) |
| 690 |
apw_state->pid_using_dumpfile = MyProcPid; |
| 691 |
LWLockRelease(&apw_state->lock); |
| 692 |
|
| 693 |
if (pid != InvalidPid) |
| 694 |
{ |
| 695 |
if (!is_bgworker) |
| 696 |
ereport(ERROR, |
| 697 |
(errmsg("could not perform block dump because dump file is being used by PID %d", |
| 698 |
(int) apw_state->pid_using_dumpfile))); |
| 699 |
|
| 700 |
ereport(LOG, |
| 701 |
(errmsg("skipping block dump because it is already being performed by PID %d", |
| 702 |
(int) apw_state->pid_using_dumpfile))); |
| 703 |
return 0; |
| 704 |
} |
| 705 |
|
| 706 |
/* |
| 707 |
* With sufficiently large shared_buffers, allocation will exceed 1GB, so |
| 708 |
* allow for a huge allocation to prevent outright failure. |
| 709 |
* |
| 710 |
* (In the future, it might be a good idea to redesign this to use a more |
| 711 |
* memory-efficient data structure.) |
| 712 |
*/ |
| 713 |
block_info_array = (BlockInfoRecord *) |
| 714 |
palloc_extended((sizeof(BlockInfoRecord) * NBuffers), MCXT_ALLOC_HUGE); |
| 715 |
|
| 716 |
for (num_blocks = 0, i = 0; i < NBuffers; i++) |
| 717 |
{ |
| 718 |
uint32 buf_state; |
| 719 |
|
| 720 |
CHECK_FOR_INTERRUPTS(); |
| 721 |
|
| 722 |
bufHdr = GetBufferDescriptor(i); |
| 723 |
|
| 724 |
/* Lock each buffer header before inspecting. */ |
| 725 |
buf_state = LockBufHdr(bufHdr); |
| 726 |
|
| 727 |
/* |
| 728 |
* Unlogged tables will be automatically truncated after a crash or |
| 729 |
* unclean shutdown. In such cases we need not prewarm them. Dump them |
| 730 |
* only if requested by caller. |
| 731 |
*/ |
| 732 |
if (buf_state & BM_TAG_VALID && |
| 733 |
((buf_state & BM_PERMANENT) || dump_unlogged)) |
| 734 |
{ |
| 735 |
block_info_array[num_blocks].database = bufHdr->tag.dbOid; |
| 736 |
block_info_array[num_blocks].tablespace = bufHdr->tag.spcOid; |
| 737 |
block_info_array[num_blocks].filenumber = |
| 738 |
BufTagGetRelNumber(&bufHdr->tag); |
| 739 |
block_info_array[num_blocks].forknum = |
| 740 |
BufTagGetForkNum(&bufHdr->tag); |
| 741 |
block_info_array[num_blocks].blocknum = bufHdr->tag.blockNum; |
| 742 |
++num_blocks; |
| 743 |
} |
| 744 |
|
| 745 |
UnlockBufHdr(bufHdr, buf_state); |
| 746 |
} |
| 747 |
|
| 748 |
snprintf(transient_dump_file_path, MAXPGPATH, "%s.tmp", AUTOPREWARM_FILE); |
| 749 |
file = AllocateFile(transient_dump_file_path, "w"); |
| 750 |
if (!file) |
| 751 |
ereport(ERROR, |
| 752 |
(errcode_for_file_access(), |
| 753 |
errmsg("could not open file \"%s\": %m", |
| 754 |
transient_dump_file_path))); |
| 755 |
|
| 756 |
ret = fprintf(file, "<<%d>>\n", num_blocks); |
| 757 |
if (ret < 0) |
| 758 |
{ |
| 759 |
int save_errno = errno; |
| 760 |
|
| 761 |
FreeFile(file); |
| 762 |
unlink(transient_dump_file_path); |
| 763 |
errno = save_errno; |
| 764 |
ereport(ERROR, |
| 765 |
(errcode_for_file_access(), |
| 766 |
errmsg("could not write to file \"%s\": %m", |
| 767 |
transient_dump_file_path))); |
| 768 |
} |
| 769 |
|
| 770 |
for (i = 0; i < num_blocks; i++) |
| 771 |
{ |
| 772 |
CHECK_FOR_INTERRUPTS(); |
| 773 |
|
| 774 |
ret = fprintf(file, "%u,%u,%u,%u,%u\n", |
| 775 |
block_info_array[i].database, |
| 776 |
block_info_array[i].tablespace, |
| 777 |
block_info_array[i].filenumber, |
| 778 |
(uint32) block_info_array[i].forknum, |
| 779 |
block_info_array[i].blocknum); |
| 780 |
if (ret < 0) |
| 781 |
{ |
| 782 |
int save_errno = errno; |
| 783 |
|
| 784 |
FreeFile(file); |
| 785 |
unlink(transient_dump_file_path); |
| 786 |
errno = save_errno; |
| 787 |
ereport(ERROR, |
| 788 |
(errcode_for_file_access(), |
| 789 |
errmsg("could not write to file \"%s\": %m", |
| 790 |
transient_dump_file_path))); |
| 791 |
} |
| 792 |
} |
| 793 |
|
| 794 |
pfree(block_info_array); |
| 795 |
|
| 796 |
/* |
| 797 |
* Rename transient_dump_file_path to AUTOPREWARM_FILE to make things |
| 798 |
* permanent. |
| 799 |
*/ |
| 800 |
ret = FreeFile(file); |
| 801 |
if (ret != 0) |
| 802 |
{ |
| 803 |
int save_errno = errno; |
| 804 |
|
| 805 |
unlink(transient_dump_file_path); |
| 806 |
errno = save_errno; |
| 807 |
ereport(ERROR, |
| 808 |
(errcode_for_file_access(), |
| 809 |
errmsg("could not close file \"%s\": %m", |
| 810 |
transient_dump_file_path))); |
| 811 |
} |
| 812 |
|
| 813 |
(void) durable_rename(transient_dump_file_path, AUTOPREWARM_FILE, ERROR); |
| 814 |
apw_state->pid_using_dumpfile = InvalidPid; |
| 815 |
|
| 816 |
ereport(DEBUG1, |
| 817 |
(errmsg_internal("wrote block details for %d blocks", num_blocks))); |
| 818 |
return num_blocks; |
| 819 |
} |
| 820 |
|
| 821 |
/* |
| 822 |
* SQL-callable function to launch autoprewarm. |
| 823 |
*/ |
| 824 |
Datum |
| 825 |
autoprewarm_start_worker(PG_FUNCTION_ARGS) |
| 826 |
{ |
| 827 |
pid_t pid; |
| 828 |
|
| 829 |
if (!autoprewarm) |
| 830 |
ereport(ERROR, |
| 831 |
(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE), |
| 832 |
errmsg("autoprewarm is disabled"))); |
| 833 |
|
| 834 |
apw_init_shmem(); |
| 835 |
LWLockAcquire(&apw_state->lock, LW_EXCLUSIVE); |
| 836 |
pid = apw_state->bgworker_pid; |
| 837 |
LWLockRelease(&apw_state->lock); |
| 838 |
|
| 839 |
if (pid != InvalidPid) |
| 840 |
ereport(ERROR, |
| 841 |
(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE), |
| 842 |
errmsg("autoprewarm worker is already running under PID %d", |
| 843 |
(int) pid))); |
| 844 |
|
| 845 |
apw_start_leader_worker(); |
| 846 |
|
| 847 |
PG_RETURN_VOID(); |
| 848 |
} |
| 849 |
|
| 850 |
/* |
| 851 |
* SQL-callable function to perform an immediate block dump. |
| 852 |
* |
| 853 |
* Note: this is declared to return int8, as insurance against some |
| 854 |
* very distant day when we might make NBuffers wider than int. |
| 855 |
*/ |
| 856 |
Datum |
| 857 |
autoprewarm_dump_now(PG_FUNCTION_ARGS) |
| 858 |
{ |
| 859 |
int num_blocks; |
| 860 |
|
| 861 |
apw_init_shmem(); |
| 862 |
|
| 863 |
PG_ENSURE_ERROR_CLEANUP(apw_detach_shmem, 0); |
| 864 |
{ |
| 865 |
num_blocks = apw_dump_now(false, true); |
| 866 |
} |
| 867 |
PG_END_ENSURE_ERROR_CLEANUP(apw_detach_shmem, 0); |
| 868 |
|
| 869 |
PG_RETURN_INT64((int64) num_blocks); |
| 870 |
} |
| 871 |
|
| 872 |
static void |
| 873 |
apw_init_state(void *ptr) |
| 874 |
{ |
| 875 |
AutoPrewarmSharedState *state = (AutoPrewarmSharedState *) ptr; |
| 876 |
|
| 877 |
LWLockInitialize(&state->lock, LWLockNewTrancheId()); |
| 878 |
state->bgworker_pid = InvalidPid; |
| 879 |
state->pid_using_dumpfile = InvalidPid; |
| 880 |
} |
| 881 |
|
| 882 |
/* |
| 883 |
* Allocate and initialize autoprewarm related shared memory, if not already |
| 884 |
* done, and set up backend-local pointer to that state. Returns true if an |
| 885 |
* existing shared memory segment was found. |
| 886 |
*/ |
| 887 |
static bool |
| 888 |
apw_init_shmem(void) |
| 889 |
{ |
| 890 |
bool found; |
| 891 |
|
| 892 |
apw_state = GetNamedDSMSegment("autoprewarm", |
| 893 |
sizeof(AutoPrewarmSharedState), |
| 894 |
apw_init_state, |
| 895 |
&found); |
| 896 |
LWLockRegisterTranche(apw_state->lock.tranche, "autoprewarm"); |
| 897 |
|
| 898 |
return found; |
| 899 |
} |
| 900 |
|
| 901 |
/* |
| 902 |
* Clear our PID from autoprewarm shared state. |
| 903 |
*/ |
| 904 |
static void |
| 905 |
apw_detach_shmem(int code, Datum arg) |
| 906 |
{ |
| 907 |
LWLockAcquire(&apw_state->lock, LW_EXCLUSIVE); |
| 908 |
if (apw_state->pid_using_dumpfile == MyProcPid) |
| 909 |
apw_state->pid_using_dumpfile = InvalidPid; |
| 910 |
if (apw_state->bgworker_pid == MyProcPid) |
| 911 |
apw_state->bgworker_pid = InvalidPid; |
| 912 |
LWLockRelease(&apw_state->lock); |
| 913 |
} |
| 914 |
|
| 915 |
/* |
| 916 |
* Start autoprewarm leader worker process. |
| 917 |
*/ |
| 918 |
static void |
| 919 |
apw_start_leader_worker(void) |
| 920 |
{ |
| 921 |
BackgroundWorker worker = {0}; |
| 922 |
BackgroundWorkerHandle *handle; |
| 923 |
BgwHandleStatus status; |
| 924 |
pid_t pid; |
| 925 |
|
| 926 |
worker.bgw_flags = BGWORKER_SHMEM_ACCESS; |
| 927 |
worker.bgw_start_time = BgWorkerStart_ConsistentState; |
| 928 |
strcpy(worker.bgw_library_name, "pg_prewarm"); |
| 929 |
strcpy(worker.bgw_function_name, "autoprewarm_main"); |
| 930 |
strcpy(worker.bgw_name, "autoprewarm leader"); |
| 931 |
strcpy(worker.bgw_type, "autoprewarm leader"); |
| 932 |
|
| 933 |
if (process_shared_preload_libraries_in_progress) |
| 934 |
{ |
| 935 |
RegisterBackgroundWorker(&worker); |
| 936 |
return; |
| 937 |
} |
| 938 |
|
| 939 |
/* must set notify PID to wait for startup */ |
| 940 |
worker.bgw_notify_pid = MyProcPid; |
| 941 |
|
| 942 |
if (!RegisterDynamicBackgroundWorker(&worker, &handle)) |
| 943 |
ereport(ERROR, |
| 944 |
(errcode(ERRCODE_INSUFFICIENT_RESOURCES), |
| 945 |
errmsg("could not register background process"), |
| 946 |
errhint("You may need to increase \"max_worker_processes\"."))); |
| 947 |
|
| 948 |
status = WaitForBackgroundWorkerStartup(handle, &pid); |
| 949 |
if (status != BGWH_STARTED) |
| 950 |
ereport(ERROR, |
| 951 |
(errcode(ERRCODE_INSUFFICIENT_RESOURCES), |
| 952 |
errmsg("could not start background process"), |
| 953 |
errhint("More details may be available in the server log."))); |
| 954 |
} |
| 955 |
|
| 956 |
/* |
| 957 |
* Start autoprewarm per-database worker process. |
| 958 |
*/ |
| 959 |
static void |
| 960 |
apw_start_database_worker(void) |
| 961 |
{ |
| 962 |
BackgroundWorker worker = {0}; |
| 963 |
BackgroundWorkerHandle *handle; |
| 964 |
|
| 965 |
worker.bgw_flags = |
| 966 |
BGWORKER_SHMEM_ACCESS | BGWORKER_BACKEND_DATABASE_CONNECTION; |
| 967 |
worker.bgw_start_time = BgWorkerStart_ConsistentState; |
| 968 |
worker.bgw_restart_time = BGW_NEVER_RESTART; |
| 969 |
strcpy(worker.bgw_library_name, "pg_prewarm"); |
| 970 |
strcpy(worker.bgw_function_name, "autoprewarm_database_main"); |
| 971 |
strcpy(worker.bgw_name, "autoprewarm worker"); |
| 972 |
strcpy(worker.bgw_type, "autoprewarm worker"); |
| 973 |
|
| 974 |
/* must set notify PID to wait for shutdown */ |
| 975 |
worker.bgw_notify_pid = MyProcPid; |
| 976 |
|
| 977 |
if (!RegisterDynamicBackgroundWorker(&worker, &handle)) |
| 978 |
ereport(ERROR, |
| 979 |
(errcode(ERRCODE_INSUFFICIENT_RESOURCES), |
| 980 |
errmsg("registering dynamic bgworker autoprewarm failed"), |
| 981 |
errhint("Consider increasing the configuration parameter \"%s\".", "max_worker_processes"))); |
| 982 |
|
| 983 |
/* |
| 984 |
* Ignore return value; if it fails, postmaster has died, but we have |
| 985 |
* checks for that elsewhere. |
| 986 |
*/ |
| 987 |
WaitForBackgroundWorkerShutdown(handle); |
| 988 |
} |
| 989 |
|
| 990 |
/* Compare member elements to check whether they are not equal. */ |
| 991 |
#define cmp_member_elem(fld) \ |
| 992 |
do { \ |
| 993 |
if (a->fld < b->fld) \ |
| 994 |
return -1; \ |
| 995 |
else if (a->fld > b->fld) \ |
| 996 |
return 1; \ |
| 997 |
} while(0) |
| 998 |
|
| 999 |
/* |
| 1000 |
* apw_compare_blockinfo |
| 1001 |
* |
| 1002 |
* We depend on all records for a particular database being consecutive |
| 1003 |
* in the dump file; each per-database worker will preload blocks until |
| 1004 |
* it sees a block for some other database. Sorting by tablespace, |
| 1005 |
* filenumber, forknum, and blocknum isn't critical for correctness, but |
| 1006 |
* helps us get a sequential I/O pattern. |
| 1007 |
*/ |
| 1008 |
static int |
| 1009 |
apw_compare_blockinfo(const void *p, const void *q) |
| 1010 |
{ |
| 1011 |
const BlockInfoRecord *a = (const BlockInfoRecord *) p; |
| 1012 |
const BlockInfoRecord *b = (const BlockInfoRecord *) q; |
| 1013 |
|
| 1014 |
cmp_member_elem(database); |
| 1015 |
cmp_member_elem(tablespace); |
| 1016 |
cmp_member_elem(filenumber); |
| 1017 |
cmp_member_elem(forknum); |
| 1018 |
cmp_member_elem(blocknum); |
| 1019 |
|
| 1020 |
return 0; |
| 1021 |
} |