PostgreSQL Source Code git master
All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Pages
autoprewarm.c File Reference
#include "postgres.h"
#include <unistd.h>
#include "access/relation.h"
#include "access/xact.h"
#include "pgstat.h"
#include "postmaster/bgworker.h"
#include "postmaster/interrupt.h"
#include "storage/buf_internals.h"
#include "storage/dsm.h"
#include "storage/dsm_registry.h"
#include "storage/fd.h"
#include "storage/ipc.h"
#include "storage/latch.h"
#include "storage/lwlock.h"
#include "storage/procsignal.h"
#include "storage/read_stream.h"
#include "storage/smgr.h"
#include "tcop/tcopprot.h"
#include "utils/guc.h"
#include "utils/rel.h"
#include "utils/relfilenumbermap.h"
#include "utils/timestamp.h"
Include dependency graph for autoprewarm.c:

Go to the source code of this file.

Data Structures

struct  BlockInfoRecord
 
struct  AutoPrewarmSharedState
 
struct  AutoPrewarmReadStreamData
 

Macros

#define AUTOPREWARM_FILE   "autoprewarm.blocks"
 
#define cmp_member_elem(fld)
 

Typedefs

typedef struct BlockInfoRecord BlockInfoRecord
 
typedef struct AutoPrewarmSharedState AutoPrewarmSharedState
 
typedef struct AutoPrewarmReadStreamData AutoPrewarmReadStreamData
 

Functions

PGDLLEXPORT void autoprewarm_main (Datum main_arg)
 
PGDLLEXPORT void autoprewarm_database_main (Datum main_arg)
 
 PG_FUNCTION_INFO_V1 (autoprewarm_start_worker)
 
 PG_FUNCTION_INFO_V1 (autoprewarm_dump_now)
 
static void apw_load_buffers (void)
 
static int apw_dump_now (bool is_bgworker, bool dump_unlogged)
 
static void apw_start_leader_worker (void)
 
static void apw_start_database_worker (void)
 
static bool apw_init_shmem (void)
 
static void apw_detach_shmem (int code, Datum arg)
 
static int apw_compare_blockinfo (const void *p, const void *q)
 
void _PG_init (void)
 
static BlockNumber apw_read_stream_next_block (ReadStream *stream, void *callback_private_data, void *per_buffer_data)
 
Datum autoprewarm_start_worker (PG_FUNCTION_ARGS)
 
Datum autoprewarm_dump_now (PG_FUNCTION_ARGS)
 
static void apw_init_state (void *ptr)
 

Variables

static AutoPrewarmSharedStateapw_state = NULL
 
static bool autoprewarm = true
 
static int autoprewarm_interval = 300
 

Macro Definition Documentation

◆ AUTOPREWARM_FILE

#define AUTOPREWARM_FILE   "autoprewarm.blocks"

Definition at line 52 of file autoprewarm.c.

◆ cmp_member_elem

#define cmp_member_elem (   fld)
Value:
do { \
if (a->fld < b->fld) \
return -1; \
else if (a->fld > b->fld) \
return 1; \
} while(0)
int b
Definition: isn.c:74
int a
Definition: isn.c:73

Definition at line 973 of file autoprewarm.c.

Typedef Documentation

◆ AutoPrewarmReadStreamData

◆ AutoPrewarmSharedState

◆ BlockInfoRecord

Function Documentation

◆ _PG_init()

void _PG_init ( void  )

Definition at line 126 of file autoprewarm.c.

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.",
132 300,
133 0, INT_MAX / 1000,
136 NULL,
137 NULL,
138 NULL);
139
141 return;
142
143 /* can't define PGC_POSTMASTER variable after startup */
144 DefineCustomBoolVariable("pg_prewarm.autoprewarm",
145 "Starts the autoprewarm worker.",
146 NULL,
148 true,
150 0,
151 NULL,
152 NULL,
153 NULL);
154
155 MarkGUCPrefixReserved("pg_prewarm");
156
157 /* Register autoprewarm worker, if enabled. */
158 if (autoprewarm)
160}
static bool autoprewarm
Definition: autoprewarm.c:119
static void apw_start_leader_worker(void)
Definition: autoprewarm.c:901
static int autoprewarm_interval
Definition: autoprewarm.c:120
void DefineCustomBoolVariable(const char *name, const char *short_desc, const char *long_desc, bool *valueAddr, bool bootValue, GucContext context, int flags, GucBoolCheckHook check_hook, GucBoolAssignHook assign_hook, GucShowHook show_hook)
Definition: guc.c:5133
void MarkGUCPrefixReserved(const char *className)
Definition: guc.c:5280
void DefineCustomIntVariable(const char *name, const char *short_desc, const char *long_desc, int *valueAddr, int bootValue, int minValue, int maxValue, GucContext context, int flags, GucIntCheckHook check_hook, GucIntAssignHook assign_hook, GucShowHook show_hook)
Definition: guc.c:5159
@ PGC_POSTMASTER
Definition: guc.h:74
@ PGC_SIGHUP
Definition: guc.h:75
#define GUC_UNIT_S
Definition: guc.h:240
bool process_shared_preload_libraries_in_progress
Definition: miscinit.c:1837

References apw_start_leader_worker(), autoprewarm, autoprewarm_interval, DefineCustomBoolVariable(), DefineCustomIntVariable(), GUC_UNIT_S, MarkGUCPrefixReserved(), PGC_POSTMASTER, PGC_SIGHUP, and process_shared_preload_libraries_in_progress.

◆ apw_compare_blockinfo()

static int apw_compare_blockinfo ( const void *  p,
const void *  q 
)
static

Definition at line 991 of file autoprewarm.c.

992{
993 const BlockInfoRecord *a = (const BlockInfoRecord *) p;
994 const BlockInfoRecord *b = (const BlockInfoRecord *) q;
995
996 cmp_member_elem(database);
998 cmp_member_elem(filenumber);
999 cmp_member_elem(forknum);
1000 cmp_member_elem(blocknum);
1001
1002 return 0;
1003}
#define cmp_member_elem(fld)
Definition: autoprewarm.c:973
static char * tablespace
Definition: pgbench.c:217

References a, b, cmp_member_elem, and tablespace.

Referenced by apw_load_buffers().

◆ apw_detach_shmem()

static void apw_detach_shmem ( int  code,
Datum  arg 
)
static

Definition at line 887 of file autoprewarm.c.

888{
895}
static AutoPrewarmSharedState * apw_state
Definition: autoprewarm.c:116
int MyProcPid
Definition: globals.c:48
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1182
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1902
@ LW_EXCLUSIVE
Definition: lwlock.h:114
#define InvalidPid
Definition: miscadmin.h:32

References apw_state, AutoPrewarmSharedState::bgworker_pid, InvalidPid, AutoPrewarmSharedState::lock, LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), MyProcPid, and AutoPrewarmSharedState::pid_using_dumpfile.

Referenced by autoprewarm_dump_now(), and autoprewarm_main().

◆ apw_dump_now()

static int apw_dump_now ( bool  is_bgworker,
bool  dump_unlogged 
)
static

Definition at line 665 of file autoprewarm.c.

666{
667 int num_blocks;
668 int i;
669 int ret;
670 BlockInfoRecord *block_info_array;
671 BufferDesc *bufHdr;
672 FILE *file;
673 char transient_dump_file_path[MAXPGPATH];
674 pid_t pid;
675
681
682 if (pid != InvalidPid)
683 {
684 if (!is_bgworker)
686 (errmsg("could not perform block dump because dump file is being used by PID %d",
688
689 ereport(LOG,
690 (errmsg("skipping block dump because it is already being performed by PID %d",
692 return 0;
693 }
694
695 block_info_array =
697
698 for (num_blocks = 0, i = 0; i < NBuffers; i++)
699 {
700 uint32 buf_state;
701
703
704 bufHdr = GetBufferDescriptor(i);
705
706 /* Lock each buffer header before inspecting. */
707 buf_state = LockBufHdr(bufHdr);
708
709 /*
710 * Unlogged tables will be automatically truncated after a crash or
711 * unclean shutdown. In such cases we need not prewarm them. Dump them
712 * only if requested by caller.
713 */
714 if (buf_state & BM_TAG_VALID &&
715 ((buf_state & BM_PERMANENT) || dump_unlogged))
716 {
717 block_info_array[num_blocks].database = bufHdr->tag.dbOid;
718 block_info_array[num_blocks].tablespace = bufHdr->tag.spcOid;
719 block_info_array[num_blocks].filenumber =
720 BufTagGetRelNumber(&bufHdr->tag);
721 block_info_array[num_blocks].forknum =
722 BufTagGetForkNum(&bufHdr->tag);
723 block_info_array[num_blocks].blocknum = bufHdr->tag.blockNum;
724 ++num_blocks;
725 }
726
727 UnlockBufHdr(bufHdr, buf_state);
728 }
729
730 snprintf(transient_dump_file_path, MAXPGPATH, "%s.tmp", AUTOPREWARM_FILE);
731 file = AllocateFile(transient_dump_file_path, "w");
732 if (!file)
735 errmsg("could not open file \"%s\": %m",
736 transient_dump_file_path)));
737
738 ret = fprintf(file, "<<%d>>\n", num_blocks);
739 if (ret < 0)
740 {
741 int save_errno = errno;
742
743 FreeFile(file);
744 unlink(transient_dump_file_path);
745 errno = save_errno;
748 errmsg("could not write to file \"%s\": %m",
749 transient_dump_file_path)));
750 }
751
752 for (i = 0; i < num_blocks; i++)
753 {
755
756 ret = fprintf(file, "%u,%u,%u,%u,%u\n",
757 block_info_array[i].database,
758 block_info_array[i].tablespace,
759 block_info_array[i].filenumber,
760 (uint32) block_info_array[i].forknum,
761 block_info_array[i].blocknum);
762 if (ret < 0)
763 {
764 int save_errno = errno;
765
766 FreeFile(file);
767 unlink(transient_dump_file_path);
768 errno = save_errno;
771 errmsg("could not write to file \"%s\": %m",
772 transient_dump_file_path)));
773 }
774 }
775
776 pfree(block_info_array);
777
778 /*
779 * Rename transient_dump_file_path to AUTOPREWARM_FILE to make things
780 * permanent.
781 */
782 ret = FreeFile(file);
783 if (ret != 0)
784 {
785 int save_errno = errno;
786
787 unlink(transient_dump_file_path);
788 errno = save_errno;
791 errmsg("could not close file \"%s\": %m",
792 transient_dump_file_path)));
793 }
794
795 (void) durable_rename(transient_dump_file_path, AUTOPREWARM_FILE, ERROR);
797
799 (errmsg_internal("wrote block details for %d blocks", num_blocks)));
800 return num_blocks;
801}
#define AUTOPREWARM_FILE
Definition: autoprewarm.c:52
#define BM_TAG_VALID
Definition: buf_internals.h:71
#define BM_PERMANENT
Definition: buf_internals.h:77
static ForkNumber BufTagGetForkNum(const BufferTag *tag)
static void UnlockBufHdr(BufferDesc *desc, uint32 buf_state)
static RelFileNumber BufTagGetRelNumber(const BufferTag *tag)
static BufferDesc * GetBufferDescriptor(uint32 id)
uint32 LockBufHdr(BufferDesc *desc)
Definition: bufmgr.c:6259
uint32_t uint32
Definition: c.h:502
#define fprintf(file, fmt, msg)
Definition: cubescan.l:21
int errmsg_internal(const char *fmt,...)
Definition: elog.c:1158
int errcode_for_file_access(void)
Definition: elog.c:877
int errmsg(const char *fmt,...)
Definition: elog.c:1071
#define LOG
Definition: elog.h:31
#define DEBUG1
Definition: elog.h:30
#define ERROR
Definition: elog.h:39
#define ereport(elevel,...)
Definition: elog.h:149
int durable_rename(const char *oldfile, const char *newfile, int elevel)
Definition: fd.c:782
int FreeFile(FILE *file)
Definition: fd.c:2843
FILE * AllocateFile(const char *name, const char *mode)
Definition: fd.c:2644
int NBuffers
Definition: globals.c:143
int i
Definition: isn.c:77
void pfree(void *pointer)
Definition: mcxt.c:2150
void * palloc(Size size)
Definition: mcxt.c:1943
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:123
#define MAXPGPATH
#define snprintf
Definition: port.h:239
ForkNumber forknum
Definition: autoprewarm.c:60
RelFileNumber filenumber
Definition: autoprewarm.c:59
BlockNumber blocknum
Definition: autoprewarm.c:61
BufferTag tag
BlockNumber blockNum
Oid spcOid

References AllocateFile(), apw_state, AUTOPREWARM_FILE, BlockInfoRecord::blocknum, buftag::blockNum, BM_PERMANENT, BM_TAG_VALID, BufTagGetForkNum(), BufTagGetRelNumber(), CHECK_FOR_INTERRUPTS, BlockInfoRecord::database, buftag::dbOid, DEBUG1, durable_rename(), ereport, errcode_for_file_access(), errmsg(), errmsg_internal(), ERROR, BlockInfoRecord::filenumber, BlockInfoRecord::forknum, fprintf, FreeFile(), GetBufferDescriptor(), i, InvalidPid, AutoPrewarmSharedState::lock, LockBufHdr(), LOG, LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), MAXPGPATH, MyProcPid, NBuffers, palloc(), pfree(), AutoPrewarmSharedState::pid_using_dumpfile, snprintf, buftag::spcOid, BlockInfoRecord::tablespace, tablespace, BufferDesc::tag, and UnlockBufHdr().

Referenced by autoprewarm_dump_now(), and autoprewarm_main().

◆ apw_init_shmem()

static bool apw_init_shmem ( void  )
static

Definition at line 870 of file autoprewarm.c.

871{
872 bool found;
873
874 apw_state = GetNamedDSMSegment("autoprewarm",
877 &found);
879
880 return found;
881}
static void apw_init_state(void *ptr)
Definition: autoprewarm.c:855
void * GetNamedDSMSegment(const char *name, size_t size, void(*init_callback)(void *ptr), bool *found)
Definition: dsm_registry.c:131
void LWLockRegisterTranche(int tranche_id, const char *tranche_name)
Definition: lwlock.c:642
uint16 tranche
Definition: lwlock.h:43

References apw_init_state(), apw_state, GetNamedDSMSegment(), AutoPrewarmSharedState::lock, LWLockRegisterTranche(), and LWLock::tranche.

Referenced by autoprewarm_database_main(), autoprewarm_dump_now(), autoprewarm_main(), and autoprewarm_start_worker().

◆ apw_init_state()

static void apw_init_state ( void *  ptr)
static

Definition at line 855 of file autoprewarm.c.

856{
858
860 state->bgworker_pid = InvalidPid;
861 state->pid_using_dumpfile = InvalidPid;
862}
int LWLockNewTrancheId(void)
Definition: lwlock.c:617
void LWLockInitialize(LWLock *lock, int tranche_id)
Definition: lwlock.c:721
Definition: regguts.h:323

References InvalidPid, LWLockInitialize(), and LWLockNewTrancheId().

Referenced by apw_init_shmem().

◆ apw_load_buffers()

static void apw_load_buffers ( void  )
static

Definition at line 292 of file autoprewarm.c.

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 */
307 else
308 {
310 ereport(LOG,
311 (errmsg("skipping prewarm because block dump file is being written by PID %d",
313 return;
314 }
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 {
329 return; /* No file to load. */
330 }
333 errmsg("could not read file \"%s\": %m",
335 }
336
337 /* First line of the file is a record count. */
338 if (fscanf(file, "<<%d>>\n", &num_elements) != 1)
341 errmsg("could not read from file \"%s\": %m",
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)
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),
367
368 /* Populate shared memory state. */
372
373 /* Get the info position of the first block of the next database. */
374 while (apw_state->prewarm_start_idx < num_elements)
375 {
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. */
410 apw_state->database = current_db;
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 */
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 */
429
430 /* Prepare for next database. */
432 }
433
434 /* Clean up. */
435 dsm_detach(seg);
440
441 /* Report our success, if we were able to finish. */
443 ereport(LOG,
444 (errmsg("autoprewarm successfully prewarmed %d of %d previously-loaded blocks",
445 apw_state->prewarmed_blocks, num_elements)));
446}
static int apw_compare_blockinfo(const void *p, const void *q)
Definition: autoprewarm.c:991
static void apw_start_database_worker(void)
Definition: autoprewarm.c:942
dsm_handle dsm_segment_handle(dsm_segment *seg)
Definition: dsm.c:1123
void dsm_detach(dsm_segment *seg)
Definition: dsm.c:803
void * dsm_segment_address(dsm_segment *seg)
Definition: dsm.c:1095
dsm_segment * dsm_create(Size size, int flags)
Definition: dsm.c:516
#define DSM_HANDLE_INVALID
Definition: dsm_impl.h:58
bool have_free_buffer(void)
Definition: freelist.c:175
Assert(PointerIsAligned(start, uint64))
volatile sig_atomic_t ShutdownRequestPending
Definition: interrupt.c:28
int j
Definition: isn.c:78
#define qsort(a, b, c, d)
Definition: port.h:479
#define InvalidOid
Definition: postgres_ext.h:35
unsigned int Oid
Definition: postgres_ext.h:30
dsm_handle block_info_handle
Definition: autoprewarm.c:72

References AllocateFile(), apw_compare_blockinfo(), apw_start_database_worker(), apw_state, Assert(), AUTOPREWARM_FILE, AutoPrewarmSharedState::block_info_handle, BlockInfoRecord::database, AutoPrewarmSharedState::database, dsm_create(), dsm_detach(), DSM_HANDLE_INVALID, dsm_segment_address(), dsm_segment_handle(), ereport, errcode_for_file_access(), errmsg(), ERROR, BlockInfoRecord::forknum, FreeFile(), have_free_buffer(), i, InvalidOid, InvalidPid, j, AutoPrewarmSharedState::lock, LOG, LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), MyProcPid, AutoPrewarmSharedState::pid_using_dumpfile, AutoPrewarmSharedState::prewarm_start_idx, AutoPrewarmSharedState::prewarm_stop_idx, AutoPrewarmSharedState::prewarmed_blocks, qsort, ShutdownRequestPending, and tablespace.

Referenced by autoprewarm_main().

◆ apw_read_stream_next_block()

static BlockNumber apw_read_stream_next_block ( ReadStream stream,
void *  callback_private_data,
void *  per_buffer_data 
)
static

Definition at line 453 of file autoprewarm.c.

456{
457 AutoPrewarmReadStreamData *p = callback_private_data;
458
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 {
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}
#define InvalidBlockNumber
Definition: block.h:33
RelFileNumber filenumber
Definition: autoprewarm.c:95
BlockInfoRecord * block_info
Definition: autoprewarm.c:86

References apw_state, AutoPrewarmReadStreamData::block_info, BlockInfoRecord::blocknum, CHECK_FOR_INTERRUPTS, BlockInfoRecord::filenumber, AutoPrewarmReadStreamData::filenumber, BlockInfoRecord::forknum, AutoPrewarmReadStreamData::forknum, have_free_buffer(), InvalidBlockNumber, AutoPrewarmReadStreamData::nblocks, AutoPrewarmReadStreamData::pos, AutoPrewarmSharedState::prewarm_stop_idx, BlockInfoRecord::tablespace, and AutoPrewarmReadStreamData::tablespace.

Referenced by autoprewarm_database_main().

◆ apw_start_database_worker()

static void apw_start_database_worker ( void  )
static

Definition at line 942 of file autoprewarm.c.

943{
944 BackgroundWorker worker = {0};
946
947 worker.bgw_flags =
951 strcpy(worker.bgw_library_name, "pg_prewarm");
952 strcpy(worker.bgw_function_name, "autoprewarm_database_main");
953 strcpy(worker.bgw_name, "autoprewarm worker");
954 strcpy(worker.bgw_type, "autoprewarm worker");
955
956 /* must set notify PID to wait for shutdown */
957 worker.bgw_notify_pid = MyProcPid;
958
959 if (!RegisterDynamicBackgroundWorker(&worker, &handle))
961 (errcode(ERRCODE_INSUFFICIENT_RESOURCES),
962 errmsg("registering dynamic bgworker autoprewarm failed"),
963 errhint("Consider increasing the configuration parameter \"%s\".", "max_worker_processes")));
964
965 /*
966 * Ignore return value; if it fails, postmaster has died, but we have
967 * checks for that elsewhere.
968 */
970}
BgwHandleStatus WaitForBackgroundWorkerShutdown(BackgroundWorkerHandle *handle)
Definition: bgworker.c:1257
bool RegisterDynamicBackgroundWorker(BackgroundWorker *worker, BackgroundWorkerHandle **handle)
Definition: bgworker.c:1045
#define BGW_NEVER_RESTART
Definition: bgworker.h:85
@ BgWorkerStart_ConsistentState
Definition: bgworker.h:80
#define BGWORKER_BACKEND_DATABASE_CONNECTION
Definition: bgworker.h:60
#define BGWORKER_SHMEM_ACCESS
Definition: bgworker.h:53
int errhint(const char *fmt,...)
Definition: elog.c:1318
int errcode(int sqlerrcode)
Definition: elog.c:854
char bgw_function_name[BGW_MAXLEN]
Definition: bgworker.h:97
char bgw_name[BGW_MAXLEN]
Definition: bgworker.h:91
int bgw_restart_time
Definition: bgworker.h:95
char bgw_type[BGW_MAXLEN]
Definition: bgworker.h:92
BgWorkerStartTime bgw_start_time
Definition: bgworker.h:94
pid_t bgw_notify_pid
Definition: bgworker.h:100
char bgw_library_name[MAXPGPATH]
Definition: bgworker.h:96

References BackgroundWorker::bgw_flags, BackgroundWorker::bgw_function_name, BackgroundWorker::bgw_library_name, BackgroundWorker::bgw_name, BGW_NEVER_RESTART, BackgroundWorker::bgw_notify_pid, BackgroundWorker::bgw_restart_time, BackgroundWorker::bgw_start_time, BackgroundWorker::bgw_type, BGWORKER_BACKEND_DATABASE_CONNECTION, BGWORKER_SHMEM_ACCESS, BgWorkerStart_ConsistentState, ereport, errcode(), errhint(), errmsg(), ERROR, MyProcPid, RegisterDynamicBackgroundWorker(), and WaitForBackgroundWorkerShutdown().

Referenced by apw_load_buffers().

◆ apw_start_leader_worker()

static void apw_start_leader_worker ( void  )
static

Definition at line 901 of file autoprewarm.c.

902{
903 BackgroundWorker worker = {0};
905 BgwHandleStatus status;
906 pid_t pid;
907
910 strcpy(worker.bgw_library_name, "pg_prewarm");
911 strcpy(worker.bgw_function_name, "autoprewarm_main");
912 strcpy(worker.bgw_name, "autoprewarm leader");
913 strcpy(worker.bgw_type, "autoprewarm leader");
914
916 {
918 return;
919 }
920
921 /* must set notify PID to wait for startup */
922 worker.bgw_notify_pid = MyProcPid;
923
924 if (!RegisterDynamicBackgroundWorker(&worker, &handle))
926 (errcode(ERRCODE_INSUFFICIENT_RESOURCES),
927 errmsg("could not register background process"),
928 errhint("You may need to increase \"max_worker_processes\".")));
929
930 status = WaitForBackgroundWorkerStartup(handle, &pid);
931 if (status != BGWH_STARTED)
933 (errcode(ERRCODE_INSUFFICIENT_RESOURCES),
934 errmsg("could not start background process"),
935 errhint("More details may be available in the server log.")));
936}
void RegisterBackgroundWorker(BackgroundWorker *worker)
Definition: bgworker.c:939
BgwHandleStatus WaitForBackgroundWorkerStartup(BackgroundWorkerHandle *handle, pid_t *pidp)
Definition: bgworker.c:1212
BgwHandleStatus
Definition: bgworker.h:104
@ BGWH_STARTED
Definition: bgworker.h:105

References BackgroundWorker::bgw_flags, BackgroundWorker::bgw_function_name, BackgroundWorker::bgw_library_name, BackgroundWorker::bgw_name, BackgroundWorker::bgw_notify_pid, BackgroundWorker::bgw_start_time, BackgroundWorker::bgw_type, BGWH_STARTED, BGWORKER_SHMEM_ACCESS, BgWorkerStart_ConsistentState, ereport, errcode(), errhint(), errmsg(), ERROR, MyProcPid, process_shared_preload_libraries_in_progress, RegisterBackgroundWorker(), RegisterDynamicBackgroundWorker(), and WaitForBackgroundWorkerStartup().

Referenced by _PG_init(), and autoprewarm_start_worker().

◆ autoprewarm_database_main()

void autoprewarm_database_main ( Datum  main_arg)

Definition at line 501 of file autoprewarm.c.

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);
511
512 /* Connect to correct database and get block information. */
515 if (seg == NULL)
517 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
518 errmsg("could not map dynamic shared memory segment")));
520 block_info = (BlockInfoRecord *) dsm_segment_address(seg);
521
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 {
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
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. */
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 blk.tablespace == tablespace &&
577 blk.filenumber == filenumber &&
579 {
580 ForkNumber forknum = blk.forknum;
581 BlockNumber nblocks;
583 ReadStream *stream;
584 Buffer buf;
585
586 /*
587 * smgrexists is not safe for illegal forknum, hence check whether
588 * the passed forknum is valid before using it in smgrexists.
589 */
590 if (blk.forknum <= InvalidForkNumber ||
591 blk.forknum > MAX_FORKNUM ||
593 {
594 /*
595 * Fast-forward to the next fork. We want to skip all of the
596 * other records referencing this fork since we already know
597 * it's not valid.
598 */
599 for (; i < apw_state->prewarm_stop_idx; i++)
600 {
601 blk = block_info[i];
602 if (blk.tablespace != tablespace ||
603 blk.filenumber != filenumber ||
604 blk.forknum != forknum)
605 break;
606 }
607
608 /* Time to check if this newfound fork is valid */
609 continue;
610 }
611
613
614 p = (struct AutoPrewarmReadStreamData)
615 {
616 .block_info = block_info,
617 .pos = i,
618 .tablespace = tablespace,
619 .filenumber = filenumber,
620 .forknum = forknum,
621 .nblocks = nblocks,
622 };
623
626 NULL,
627 rel,
628 p.forknum,
630 &p,
631 0);
632
633 /*
634 * Loop until we've prewarmed all the blocks from this fork. The
635 * read stream callback will check that we still have free buffers
636 * before requesting each block from the read stream API.
637 */
638 while ((buf = read_stream_next_buffer(stream, NULL)) != InvalidBuffer)
639 {
642 }
643
644 read_stream_end(stream);
645
646 /* Advance i past all the blocks just prewarmed. */
647 i = p.pos;
648 blk = block_info[i];
649 }
650
653 }
654
655 dsm_detach(seg);
656}
static bool apw_init_shmem(void)
Definition: autoprewarm.c:870
static BlockNumber apw_read_stream_next_block(ReadStream *stream, void *callback_private_data, void *per_buffer_data)
Definition: autoprewarm.c:453
void BackgroundWorkerUnblockSignals(void)
Definition: bgworker.c:926
void BackgroundWorkerInitializeConnectionByOid(Oid dboid, Oid useroid, uint32 flags)
Definition: bgworker.c:886
uint32 BlockNumber
Definition: block.h:31
int Buffer
Definition: buf.h:23
#define InvalidBuffer
Definition: buf.h:25
BlockNumber RelationGetNumberOfBlocksInFork(Relation relation, ForkNumber forkNum)
Definition: bufmgr.c:4431
void ReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:5373
#define OidIsValid(objectId)
Definition: c.h:746
dsm_segment * dsm_attach(dsm_handle h)
Definition: dsm.c:665
#define AccessShareLock
Definition: lockdefs.h:36
#define die(msg)
static char * buf
Definition: pg_test_fsync.c:72
#define pqsignal
Definition: port.h:531
Buffer read_stream_next_buffer(ReadStream *stream, void **per_buffer_data)
Definition: read_stream.c:770
ReadStream * read_stream_begin_relation(int flags, BufferAccessStrategy strategy, Relation rel, ForkNumber forknum, ReadStreamBlockNumberCB callback, void *callback_private_data, size_t per_buffer_data_size)
Definition: read_stream.c:716
void read_stream_end(ReadStream *stream)
Definition: read_stream.c:1055
#define READ_STREAM_USE_BATCHING
Definition: read_stream.h:64
#define READ_STREAM_DEFAULT
Definition: read_stream.h:21
static SMgrRelation RelationGetSmgr(Relation rel)
Definition: rel.h:578
Oid RelidByRelfilenumber(Oid reltablespace, RelFileNumber relfilenumber)
Oid RelFileNumber
Definition: relpath.h:25
ForkNumber
Definition: relpath.h:56
@ InvalidForkNumber
Definition: relpath.h:57
#define MAX_FORKNUM
Definition: relpath.h:70
bool smgrexists(SMgrRelation reln, ForkNumber forknum)
Definition: smgr.c:462
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: relation.c:205
Relation try_relation_open(Oid relationId, LOCKMODE lockmode)
Definition: relation.c:88
void StartTransactionCommand(void)
Definition: xact.c:3059
void CommitTransactionCommand(void)
Definition: xact.c:3157

References AccessShareLock, apw_init_shmem(), apw_read_stream_next_block(), apw_state, Assert(), BackgroundWorkerInitializeConnectionByOid(), BackgroundWorkerUnblockSignals(), AutoPrewarmReadStreamData::block_info, AutoPrewarmSharedState::block_info_handle, buf, CommitTransactionCommand(), BlockInfoRecord::database, AutoPrewarmSharedState::database, die, dsm_attach(), dsm_detach(), dsm_segment_address(), ereport, errcode(), errmsg(), ERROR, BlockInfoRecord::filenumber, AutoPrewarmReadStreamData::filenumber, BlockInfoRecord::forknum, AutoPrewarmReadStreamData::forknum, have_free_buffer(), i, InvalidBuffer, InvalidForkNumber, InvalidOid, MAX_FORKNUM, AutoPrewarmReadStreamData::nblocks, OidIsValid, AutoPrewarmReadStreamData::pos, pqsignal, AutoPrewarmSharedState::prewarm_start_idx, AutoPrewarmSharedState::prewarm_stop_idx, AutoPrewarmSharedState::prewarmed_blocks, read_stream_begin_relation(), READ_STREAM_DEFAULT, read_stream_end(), read_stream_next_buffer(), READ_STREAM_USE_BATCHING, relation_close(), RelationGetNumberOfBlocksInFork(), RelationGetSmgr(), ReleaseBuffer(), RelidByRelfilenumber(), smgrexists(), StartTransactionCommand(), BlockInfoRecord::tablespace, AutoPrewarmReadStreamData::tablespace, tablespace, and try_relation_open().

◆ autoprewarm_dump_now()

Datum autoprewarm_dump_now ( PG_FUNCTION_ARGS  )

Definition at line 839 of file autoprewarm.c.

840{
841 int num_blocks;
842
844
846 {
847 num_blocks = apw_dump_now(false, true);
848 }
850
851 PG_RETURN_INT64((int64) num_blocks);
852}
static void apw_detach_shmem(int code, Datum arg)
Definition: autoprewarm.c:887
static int apw_dump_now(bool is_bgworker, bool dump_unlogged)
Definition: autoprewarm.c:665
int64_t int64
Definition: c.h:499
#define PG_RETURN_INT64(x)
Definition: fmgr.h:368
#define PG_ENSURE_ERROR_CLEANUP(cleanup_function, arg)
Definition: ipc.h:47
#define PG_END_ENSURE_ERROR_CLEANUP(cleanup_function, arg)
Definition: ipc.h:52

References apw_detach_shmem(), apw_dump_now(), apw_init_shmem(), PG_END_ENSURE_ERROR_CLEANUP, PG_ENSURE_ERROR_CLEANUP, and PG_RETURN_INT64.

◆ autoprewarm_main()

void autoprewarm_main ( Datum  main_arg)

Definition at line 167 of file autoprewarm.c.

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. */
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 */
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 */
198 {
200 ereport(LOG,
201 (errmsg("autoprewarm worker is already running under PID %d",
202 (int) apw_state->bgworker_pid)));
203 return;
204 }
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 {
225 final_dump_allowed = !ShutdownRequestPending;
226 last_dump_time = GetCurrentTimestamp();
227 }
228
229 /* Periodically dump buffers until terminated. */
231 {
232 /* In case of a SIGHUP, just reload the configuration. */
234 {
235 ConfigReloadPending = false;
237 }
238
239 if (autoprewarm_interval <= 0)
240 {
241 /* We're only dumping at shutdown, so just wait forever. */
242 (void) WaitLatch(MyLatch,
244 -1L,
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 =
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,
271 delay_in_ms,
273 }
274
275 /* Reset the latch, loop. */
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}
static void apw_load_buffers(void)
Definition: autoprewarm.c:292
long TimestampDifferenceMilliseconds(TimestampTz start_time, TimestampTz stop_time)
Definition: timestamp.c:1757
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1645
int64 TimestampTz
Definition: timestamp.h:39
struct Latch * MyLatch
Definition: globals.c:64
void ProcessConfigFile(GucContext context)
Definition: guc-file.l:120
void SignalHandlerForShutdownRequest(SIGNAL_ARGS)
Definition: interrupt.c:109
volatile sig_atomic_t ConfigReloadPending
Definition: interrupt.c:27
void SignalHandlerForConfigReload(SIGNAL_ARGS)
Definition: interrupt.c:65
void before_shmem_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:337
void ResetLatch(Latch *latch)
Definition: latch.c:372
int WaitLatch(Latch *latch, int wakeEvents, long timeout, uint32 wait_event_info)
Definition: latch.c:172
void procsignal_sigusr1_handler(SIGNAL_ARGS)
Definition: procsignal.c:673
#define TimestampTzPlusMilliseconds(tz, ms)
Definition: timestamp.h:85
#define PG_WAIT_EXTENSION
Definition: wait_classes.h:23
#define WL_TIMEOUT
Definition: waiteventset.h:37
#define WL_EXIT_ON_PM_DEATH
Definition: waiteventset.h:39
#define WL_LATCH_SET
Definition: waiteventset.h:34
#define SIGHUP
Definition: win32_port.h:158
#define SIGUSR1
Definition: win32_port.h:170

References apw_detach_shmem(), apw_dump_now(), apw_init_shmem(), apw_load_buffers(), apw_state, autoprewarm_interval, BackgroundWorkerUnblockSignals(), before_shmem_exit(), AutoPrewarmSharedState::bgworker_pid, ConfigReloadPending, ereport, errmsg(), GetCurrentTimestamp(), InvalidPid, AutoPrewarmSharedState::lock, LOG, LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), MyLatch, MyProcPid, PG_WAIT_EXTENSION, PGC_SIGHUP, pqsignal, ProcessConfigFile(), procsignal_sigusr1_handler(), ResetLatch(), ShutdownRequestPending, SIGHUP, SignalHandlerForConfigReload(), SignalHandlerForShutdownRequest(), SIGUSR1, TimestampDifferenceMilliseconds(), TimestampTzPlusMilliseconds, WaitLatch(), WL_EXIT_ON_PM_DEATH, WL_LATCH_SET, and WL_TIMEOUT.

◆ autoprewarm_start_worker()

Datum autoprewarm_start_worker ( PG_FUNCTION_ARGS  )

Definition at line 807 of file autoprewarm.c.

808{
809 pid_t pid;
810
811 if (!autoprewarm)
813 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
814 errmsg("autoprewarm is disabled")));
815
818 pid = apw_state->bgworker_pid;
820
821 if (pid != InvalidPid)
823 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
824 errmsg("autoprewarm worker is already running under PID %d",
825 (int) pid)));
826
828
830}
#define PG_RETURN_VOID()
Definition: fmgr.h:349

References apw_init_shmem(), apw_start_leader_worker(), apw_state, autoprewarm, AutoPrewarmSharedState::bgworker_pid, ereport, errcode(), errmsg(), ERROR, InvalidPid, AutoPrewarmSharedState::lock, LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), and PG_RETURN_VOID.

◆ PG_FUNCTION_INFO_V1() [1/2]

PG_FUNCTION_INFO_V1 ( autoprewarm_dump_now  )

◆ PG_FUNCTION_INFO_V1() [2/2]

PG_FUNCTION_INFO_V1 ( autoprewarm_start_worker  )

Variable Documentation

◆ apw_state

◆ autoprewarm

bool autoprewarm = true
static

Definition at line 119 of file autoprewarm.c.

Referenced by _PG_init(), and autoprewarm_start_worker().

◆ autoprewarm_interval

int autoprewarm_interval = 300
static

Definition at line 120 of file autoprewarm.c.

Referenced by _PG_init(), and autoprewarm_main().