PostgreSQL Source Code git master
Loading...
Searching...
No Matches
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 "utils/wait_event.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, void *arg)
 

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 53 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
static int fb(int x)

Definition at line 989 of file autoprewarm.c.

990 { \
991 if (a->fld < b->fld) \
992 return -1; \
993 else if (a->fld > b->fld) \
994 return 1; \
995} while(0)

Typedef Documentation

◆ AutoPrewarmReadStreamData

◆ AutoPrewarmSharedState

◆ BlockInfoRecord

Function Documentation

◆ _PG_init()

void _PG_init ( void  )

Definition at line 127 of file autoprewarm.c.

128{
129 DefineCustomIntVariable("pg_prewarm.autoprewarm_interval",
130 "Sets the interval between dumps of shared buffers",
131 "If set to zero, time-based dumping is disabled.",
133 300,
134 0, INT_MAX / 1000,
137 NULL,
138 NULL,
139 NULL);
140
142 return;
143
144 /* can't define PGC_POSTMASTER variable after startup */
145 DefineCustomBoolVariable("pg_prewarm.autoprewarm",
146 "Starts the autoprewarm worker.",
147 NULL,
149 true,
151 0,
152 NULL,
153 NULL,
154 NULL);
155
156 MarkGUCPrefixReserved("pg_prewarm");
157
158 /* Register autoprewarm worker, if enabled. */
159 if (autoprewarm)
161}
static bool autoprewarm
static void apw_start_leader_worker(void)
static int autoprewarm_interval
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:5049
void MarkGUCPrefixReserved(const char *className)
Definition guc.c:5186
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:5073
@ 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:1788

References apw_start_leader_worker(), autoprewarm, autoprewarm_interval, DefineCustomBoolVariable(), DefineCustomIntVariable(), fb(), 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 1007 of file autoprewarm.c.

1008{
1009 const BlockInfoRecord *a = (const BlockInfoRecord *) p;
1010 const BlockInfoRecord *b = (const BlockInfoRecord *) q;
1011
1012 cmp_member_elem(database);
1014 cmp_member_elem(filenumber);
1015 cmp_member_elem(forknum);
1016 cmp_member_elem(blocknum);
1017
1018 return 0;
1019}
#define cmp_member_elem(fld)
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 903 of file autoprewarm.c.

904{
911}
static AutoPrewarmSharedState * apw_state
int MyProcPid
Definition globals.c:49
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition lwlock.c:1150
void LWLockRelease(LWLock *lock)
Definition lwlock.c:1767
@ LW_EXCLUSIVE
Definition lwlock.h:104
#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 675 of file autoprewarm.c.

676{
677 int num_blocks;
678 int i;
679 int ret;
682 FILE *file;
684 pid_t pid;
685
691
692 if (pid != InvalidPid)
693 {
694 if (!is_bgworker)
696 (errmsg("could not perform block dump because dump file is being used by PID %d",
698
699 ereport(LOG,
700 (errmsg("skipping block dump because it is already being performed by PID %d",
702 return 0;
703 }
704
705 /*
706 * With sufficiently large shared_buffers, allocation will exceed 1GB, so
707 * allow for a huge allocation to prevent outright failure.
708 *
709 * (In the future, it might be a good idea to redesign this to use a more
710 * memory-efficient data structure.)
711 */
714
715 for (num_blocks = 0, i = 0; i < NBuffers; i++)
716 {
718
720
722
723 /* Lock each buffer header before inspecting. */
725
726 /*
727 * Unlogged tables will be automatically truncated after a crash or
728 * unclean shutdown. In such cases we need not prewarm them. Dump them
729 * only if requested by caller.
730 */
731 if (buf_state & BM_TAG_VALID &&
733 {
734 block_info_array[num_blocks].database = bufHdr->tag.dbOid;
735 block_info_array[num_blocks].tablespace = bufHdr->tag.spcOid;
736 block_info_array[num_blocks].filenumber =
738 block_info_array[num_blocks].forknum =
740 block_info_array[num_blocks].blocknum = bufHdr->tag.blockNum;
741 ++num_blocks;
742 }
743
745 }
746
749 if (!file)
752 errmsg("could not open file \"%s\": %m",
754
755 ret = fprintf(file, "<<%d>>\n", num_blocks);
756 if (ret < 0)
757 {
758 int save_errno = errno;
759
760 FreeFile(file);
765 errmsg("could not write to file \"%s\": %m",
767 }
768
769 for (i = 0; i < num_blocks; i++)
770 {
772
773 ret = fprintf(file, "%u,%u,%u,%u,%u\n",
774 block_info_array[i].database,
776 block_info_array[i].filenumber,
777 (uint32) block_info_array[i].forknum,
778 block_info_array[i].blocknum);
779 if (ret < 0)
780 {
781 int save_errno = errno;
782
783 FreeFile(file);
788 errmsg("could not write to file \"%s\": %m",
790 }
791 }
792
794
795 /*
796 * Rename transient_dump_file_path to AUTOPREWARM_FILE to make things
797 * permanent.
798 */
799 ret = FreeFile(file);
800 if (ret != 0)
801 {
802 int save_errno = errno;
803
808 errmsg("could not close file \"%s\": %m",
810 }
811
814
816 (errmsg_internal("wrote block details for %d blocks", num_blocks)));
817 return num_blocks;
818}
#define AUTOPREWARM_FILE
Definition autoprewarm.c:53
#define BM_TAG_VALID
#define BM_PERMANENT
static ForkNumber BufTagGetForkNum(const BufferTag *tag)
static RelFileNumber BufTagGetRelNumber(const BufferTag *tag)
static void UnlockBufHdr(BufferDesc *desc)
static BufferDesc * GetBufferDescriptor(int id)
uint64 LockBufHdr(BufferDesc *desc)
Definition bufmgr.c:7567
uint64_t uint64
Definition c.h:684
uint32_t uint32
Definition c.h:683
#define fprintf(file, fmt, msg)
Definition cubescan.l:21
int errcode_for_file_access(void)
Definition elog.c:898
#define LOG
Definition elog.h:32
int int errmsg_internal(const char *fmt,...) pg_attribute_printf(1
#define DEBUG1
Definition elog.h:31
#define ERROR
Definition elog.h:40
#define ereport(elevel,...)
Definition elog.h:152
int durable_rename(const char *oldfile, const char *newfile, int elevel)
Definition fd.c:783
int FreeFile(FILE *file)
Definition fd.c:2827
FILE * AllocateFile(const char *name, const char *mode)
Definition fd.c:2628
#define MCXT_ALLOC_HUGE
Definition fe_memutils.h:28
int NBuffers
Definition globals.c:144
int i
Definition isn.c:77
void pfree(void *pointer)
Definition mcxt.c:1619
void * palloc_extended(Size size, int flags)
Definition mcxt.c:1442
#define CHECK_FOR_INTERRUPTS()
Definition miscadmin.h:125
static char * errmsg
#define MAXPGPATH
#define snprintf
Definition port.h:261

References AllocateFile(), apw_state, AUTOPREWARM_FILE, BM_PERMANENT, BM_TAG_VALID, BufTagGetForkNum(), BufTagGetRelNumber(), CHECK_FOR_INTERRUPTS, DEBUG1, durable_rename(), ereport, errcode_for_file_access(), errmsg, errmsg_internal(), ERROR, fb(), fprintf, FreeFile(), GetBufferDescriptor(), i, InvalidPid, AutoPrewarmSharedState::lock, LockBufHdr(), LOG, LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), MAXPGPATH, MCXT_ALLOC_HUGE, MyProcPid, NBuffers, palloc_extended(), pfree(), AutoPrewarmSharedState::pid_using_dumpfile, snprintf, tablespace, and UnlockBufHdr().

Referenced by autoprewarm_dump_now(), and autoprewarm_main().

◆ apw_init_shmem()

static bool apw_init_shmem ( void  )
static

Definition at line 887 of file autoprewarm.c.

888{
889 bool found;
890
891 apw_state = GetNamedDSMSegment("autoprewarm",
894 &found, NULL);
895
896 return found;
897}
static void apw_init_state(void *ptr, void *arg)
void * GetNamedDSMSegment(const char *name, size_t size, void(*init_callback)(void *ptr, void *arg), bool *found, void *arg)

References apw_init_state(), apw_state, fb(), and GetNamedDSMSegment().

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

◆ apw_init_state()

static void apw_init_state ( void ptr,
void arg 
)
static

Definition at line 872 of file autoprewarm.c.

873{
875
876 LWLockInitialize(&state->lock, LWLockNewTrancheId("autoprewarm"));
877 state->bgworker_pid = InvalidPid;
878 state->pid_using_dumpfile = InvalidPid;
879}
int LWLockNewTrancheId(const char *name)
Definition lwlock.c:562
void LWLockInitialize(LWLock *lock, int tranche_id)
Definition lwlock.c:670

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

Referenced by apw_init_shmem().

◆ apw_load_buffers()

static void apw_load_buffers ( void  )
static

Definition at line 293 of file autoprewarm.c.

294{
295 FILE *file = NULL;
296 int num_elements,
297 i;
299 dsm_segment *seg;
300
301 /*
302 * Skip the prewarm if the dump file is in use; otherwise, prevent any
303 * other process from writing it while we're using it.
304 */
308 else
309 {
311 ereport(LOG,
312 (errmsg("skipping prewarm because block dump file is being written by PID %d",
314 return;
315 }
317
318 /*
319 * Open the block dump file. Exit quietly if it doesn't exist, but report
320 * any other error.
321 */
322 file = AllocateFile(AUTOPREWARM_FILE, "r");
323 if (!file)
324 {
325 if (errno == ENOENT)
326 {
330 return; /* No file to load. */
331 }
334 errmsg("could not read file \"%s\": %m",
336 }
337
338 /* First line of the file is a record count. */
339 if (fscanf(file, "<<%d>>\n", &num_elements) != 1)
342 errmsg("could not read from file \"%s\": %m",
344
345 /* Allocate a dynamic shared memory segment to store the record data. */
346 seg = dsm_create(sizeof(BlockInfoRecord) * num_elements, 0);
348
349 /* Read records, one per line. */
350 for (i = 0; i < num_elements; i++)
351 {
352 unsigned forknum;
353
354 if (fscanf(file, "%u,%u,%u,%u,%u\n", &blkinfo[i].database,
355 &blkinfo[i].tablespace, &blkinfo[i].filenumber,
356 &forknum, &blkinfo[i].blocknum) != 5)
358 (errmsg("autoprewarm block dump file is corrupted at line %d",
359 i + 1)));
360 blkinfo[i].forknum = forknum;
361 }
362
363 FreeFile(file);
364
365 /* Sort the blocks to be loaded. */
368
369 /* Populate shared memory state. */
373
374 /* Don't prewarm more than we can fit. */
376 {
378 ereport(LOG,
379 (errmsg("autoprewarm capping prewarmed blocks to %d (shared_buffers size)",
380 NBuffers)));
381 }
382
383 /* Get the info position of the first block of the next database. */
385 {
387 Oid current_db = blkinfo[j].database;
388
389 /*
390 * Advance the prewarm_stop_idx to the first BlockInfoRecord that does
391 * not belong to this database.
392 */
393 j++;
394 while (j < num_elements)
395 {
396 if (current_db != blkinfo[j].database)
397 {
398 /*
399 * Combine BlockInfoRecords for global objects with those of
400 * the database.
401 */
402 if (current_db != InvalidOid)
403 break;
404 current_db = blkinfo[j].database;
405 }
406
407 j++;
408 }
409
410 /*
411 * If we reach this point with current_db == InvalidOid, then only
412 * BlockInfoRecords belonging to global objects exist. We can't
413 * prewarm without a database connection, so just bail out.
414 */
415 if (current_db == InvalidOid)
416 break;
417
418 /* Configure stop point and database for next per-database worker. */
422
423 /*
424 * Likewise, don't launch if we've already been told to shut down.
425 * (The launch would fail anyway, but we might as well skip it.)
426 */
428 break;
429
430 /*
431 * Start a per-database worker to load blocks for this database; this
432 * function will return once the per-database worker exits.
433 */
435
436 /* Prepare for next database. */
438 }
439
440 /* Clean up. */
441 dsm_detach(seg);
446
447 /* Report our success, if we were able to finish. */
449 ereport(LOG,
450 (errmsg("autoprewarm successfully prewarmed %d of %d previously-loaded blocks",
452}
static int apw_compare_blockinfo(const void *p, const void *q)
static void apw_start_database_worker(void)
#define Assert(condition)
Definition c.h:1002
dsm_handle dsm_segment_handle(dsm_segment *seg)
Definition dsm.c:1131
void dsm_detach(dsm_segment *seg)
Definition dsm.c:811
void * dsm_segment_address(dsm_segment *seg)
Definition dsm.c:1103
dsm_segment * dsm_create(Size size, int flags)
Definition dsm.c:524
#define DSM_HANDLE_INVALID
Definition dsm_impl.h:58
volatile sig_atomic_t ShutdownRequestPending
Definition interrupt.c:28
int j
Definition isn.c:78
#define qsort(a, b, c, d)
Definition port.h:496
#define InvalidOid
unsigned int Oid
dsm_handle block_info_handle
Definition autoprewarm.c:73

References AllocateFile(), apw_compare_blockinfo(), apw_start_database_worker(), apw_state, Assert, AUTOPREWARM_FILE, AutoPrewarmSharedState::block_info_handle, AutoPrewarmSharedState::database, dsm_create(), dsm_detach(), DSM_HANDLE_INVALID, dsm_segment_address(), dsm_segment_handle(), ereport, errcode_for_file_access(), errmsg, ERROR, fb(), FreeFile(), i, InvalidOid, InvalidPid, j, AutoPrewarmSharedState::lock, LOG, LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), MyProcPid, NBuffers, 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 459 of file autoprewarm.c.

462{
463 AutoPrewarmReadStreamData *p = callback_private_data;
464
466
467 while (p->pos < apw_state->prewarm_stop_idx)
468 {
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
BlockInfoRecord * block_info
Definition autoprewarm.c:87

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

Referenced by autoprewarm_database_main().

◆ apw_start_database_worker()

static void apw_start_database_worker ( void  )
static

Definition at line 958 of file autoprewarm.c.

959{
960 BackgroundWorker worker = {0};
962
963 worker.bgw_flags =
967 strcpy(worker.bgw_library_name, "pg_prewarm");
968 strcpy(worker.bgw_function_name, "autoprewarm_database_main");
969 strcpy(worker.bgw_name, "autoprewarm worker");
970 strcpy(worker.bgw_type, "autoprewarm worker");
971
972 /* must set notify PID to wait for shutdown */
973 worker.bgw_notify_pid = MyProcPid;
974
975 if (!RegisterDynamicBackgroundWorker(&worker, &handle))
978 errmsg("registering dynamic bgworker autoprewarm failed"),
979 errhint("Consider increasing the configuration parameter \"%s\".", "max_worker_processes")));
980
981 /*
982 * Ignore return value; if it fails, postmaster has died, but we have
983 * checks for that elsewhere.
984 */
986}
BgwHandleStatus WaitForBackgroundWorkerShutdown(BackgroundWorkerHandle *handle)
Definition bgworker.c:1280
bool RegisterDynamicBackgroundWorker(BackgroundWorker *worker, BackgroundWorkerHandle **handle)
Definition bgworker.c:1068
#define BGW_NEVER_RESTART
Definition bgworker.h:92
@ BgWorkerStart_ConsistentState
Definition bgworker.h:87
#define BGWORKER_BACKEND_DATABASE_CONNECTION
Definition bgworker.h:60
#define BGWORKER_SHMEM_ACCESS
Definition bgworker.h:53
int errcode(int sqlerrcode)
Definition elog.c:875
int errhint(const char *fmt,...) pg_attribute_printf(1
char bgw_function_name[BGW_MAXLEN]
Definition bgworker.h:104
char bgw_name[BGW_MAXLEN]
Definition bgworker.h:98
char bgw_type[BGW_MAXLEN]
Definition bgworker.h:99
BgWorkerStartTime bgw_start_time
Definition bgworker.h:101
pid_t bgw_notify_pid
Definition bgworker.h:107
char bgw_library_name[MAXPGPATH]
Definition bgworker.h:103

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, fb(), MyProcPid, RegisterDynamicBackgroundWorker(), and WaitForBackgroundWorkerShutdown().

Referenced by apw_load_buffers().

◆ apw_start_leader_worker()

static void apw_start_leader_worker ( void  )
static

Definition at line 917 of file autoprewarm.c.

918{
919 BackgroundWorker worker = {0};
921 BgwHandleStatus status;
922 pid_t pid;
923
926 strcpy(worker.bgw_library_name, "pg_prewarm");
927 strcpy(worker.bgw_function_name, "autoprewarm_main");
928 strcpy(worker.bgw_name, "autoprewarm leader");
929 strcpy(worker.bgw_type, "autoprewarm leader");
930
932 {
934 return;
935 }
936
937 /* must set notify PID to wait for startup */
938 worker.bgw_notify_pid = MyProcPid;
939
940 if (!RegisterDynamicBackgroundWorker(&worker, &handle))
943 errmsg("could not register background process"),
944 errhint("You may need to increase \"max_worker_processes\".")));
945
946 status = WaitForBackgroundWorkerStartup(handle, &pid);
947 if (status != BGWH_STARTED)
950 errmsg("could not start background process"),
951 errhint("More details may be available in the server log.")));
952}
void RegisterBackgroundWorker(BackgroundWorker *worker)
Definition bgworker.c:962
BgwHandleStatus WaitForBackgroundWorkerStartup(BackgroundWorkerHandle *handle, pid_t *pidp)
Definition bgworker.c:1235
BgwHandleStatus
Definition bgworker.h:111
@ BGWH_STARTED
Definition bgworker.h:112

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, fb(), 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;
506 dsm_segment *seg;
507
508 /* Establish signal handlers; once that's done, unblock signals. */
511
512 /* Connect to correct database and get block information. */
515 if (seg == NULL)
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
527 * buffers.
528 */
529 while (i < apw_state->prewarm_stop_idx)
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 buffers. Once we've read from all
572 * 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 {
577 ForkNumber forknum;
578 BlockNumber nblocks;
580 ReadStream *stream;
581 Buffer buf;
582
583 blk = block_info[i];
584
585 /* Stop when we reach a different relation. */
586 if (blk.tablespace != tablespace ||
587 blk.filenumber != filenumber)
588 break;
589
591
592 /*
593 * smgrexists is not safe for illegal forknum, hence check whether
594 * the passed forknum is valid before using it in smgrexists.
595 */
596 if (blk.forknum <= InvalidForkNumber ||
597 blk.forknum > MAX_FORKNUM ||
598 !smgrexists(RelationGetSmgr(rel), blk.forknum))
599 {
600 /*
601 * Fast-forward to the next fork. We want to skip all of the
602 * other records referencing this fork since we already know
603 * it's not valid.
604 */
605 for (; i < apw_state->prewarm_stop_idx; i++)
606 {
607 blk = block_info[i];
608 if (blk.tablespace != tablespace ||
609 blk.filenumber != filenumber ||
610 blk.forknum != forknum)
611 break;
612 }
613
614 /* Time to check if this newfound fork is valid */
615 continue;
616 }
617
619
620 p = (struct AutoPrewarmReadStreamData)
621 {
622 .block_info = block_info,
623 .pos = i,
625 .filenumber = filenumber,
626 .forknum = forknum,
627 .nblocks = nblocks,
628 };
629
633 NULL,
634 rel,
635 p.forknum,
637 &p,
638 0);
639
640 /*
641 * Loop until we've prewarmed all the blocks from this fork. The
642 * read stream callback will check that we still have free buffers
643 * before requesting each block from the read stream API.
644 */
645 while ((buf = read_stream_next_buffer(stream, NULL)) != InvalidBuffer)
646 {
649 }
650
651 read_stream_end(stream);
652
653 /*
654 * Advance i past all the blocks just prewarmed. Note that the
655 * callback might have advanced the index beyond the last valid
656 * block, so don't access block_info[i] yet.
657 */
658 i = p.pos;
659 }
660
663 }
664
665 dsm_detach(seg);
666}
static bool apw_init_shmem(void)
static BlockNumber apw_read_stream_next_block(ReadStream *stream, void *callback_private_data, void *per_buffer_data)
void BackgroundWorkerUnblockSignals(void)
Definition bgworker.c:949
void BackgroundWorkerInitializeConnectionByOid(Oid dboid, Oid useroid, uint32 flags)
Definition bgworker.c:909
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:4668
void ReleaseBuffer(Buffer buffer)
Definition bufmgr.c:5609
#define OidIsValid(objectId)
Definition c.h:917
dsm_segment * dsm_attach(dsm_handle h)
Definition dsm.c:673
#define AccessShareLock
Definition lockdefs.h:36
static char buf[DEFAULT_XLOG_SEG_SIZE]
#define die(msg)
#define pqsignal
Definition port.h:548
Buffer read_stream_next_buffer(ReadStream *stream, void **per_buffer_data)
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)
void read_stream_end(ReadStream *stream)
#define READ_STREAM_MAINTENANCE
Definition read_stream.h:28
#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:206
Relation try_relation_open(Oid relationId, LOCKMODE lockmode)
Definition relation.c:89
ForkNumber forknum
Definition autoprewarm.c:61
void StartTransactionCommand(void)
Definition xact.c:3112
void CommitTransactionCommand(void)
Definition xact.c:3210

References AccessShareLock, apw_init_shmem(), apw_read_stream_next_block(), apw_state, Assert, BackgroundWorkerInitializeConnectionByOid(), BackgroundWorkerUnblockSignals(), AutoPrewarmReadStreamData::block_info, AutoPrewarmSharedState::block_info_handle, buf, CommitTransactionCommand(), AutoPrewarmSharedState::database, die, dsm_attach(), dsm_detach(), dsm_segment_address(), ereport, errcode(), errmsg, ERROR, fb(), AutoPrewarmReadStreamData::filenumber, BlockInfoRecord::forknum, AutoPrewarmReadStreamData::forknum, 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_MAINTENANCE, 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 856 of file autoprewarm.c.

857{
858 int num_blocks;
859
861
863 {
864 num_blocks = apw_dump_now(false, true);
865 }
867
868 PG_RETURN_INT64((int64) num_blocks);
869}
static void apw_detach_shmem(int code, Datum arg)
static int apw_dump_now(bool is_bgworker, bool dump_unlogged)
int64_t int64
Definition c.h:680
#define PG_RETURN_INT64(x)
Definition fmgr.h:370
#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 168 of file autoprewarm.c.

169{
170 bool first_time = true;
171 bool final_dump_allowed = true;
173
174 /* Establish signal handlers; once that's done, unblock signals. */
179
180 /* Create (if necessary) and attach to our shared memory area. */
181 if (apw_init_shmem())
182 first_time = false;
183
184 /*
185 * Set on-detach hook so that our PID will be cleared on exit.
186 *
187 * NB: Autoprewarm's state is stored in a DSM segment, and DSM segments
188 * are detached before calling the on_shmem_exit callbacks, so we must put
189 * apw_detach_shmem in the before_shmem_exit callback list.
190 */
192
193 /*
194 * Store our PID in the shared memory area --- unless there's already
195 * another worker running, in which case just exit.
196 */
199 {
201 ereport(LOG,
202 (errmsg("autoprewarm worker is already running under PID %d",
203 (int) apw_state->bgworker_pid)));
204 return;
205 }
208
209 /*
210 * Preload buffers from the dump file only if we just created the shared
211 * memory region. Otherwise, it's either already been done or shouldn't
212 * be done - e.g. because the old dump file has been overwritten since the
213 * server was started.
214 *
215 * There's not much point in performing a dump immediately after we finish
216 * preloading; so, if we do end up preloading, consider the last dump time
217 * to be equal to the current time.
218 *
219 * If apw_load_buffers() is terminated early by a shutdown request,
220 * prevent dumping out our state below the loop, because we'd effectively
221 * just truncate the saved state to however much we'd managed to preload.
222 */
223 if (first_time)
224 {
228 }
229
230 /* Periodically dump buffers until terminated. */
232 {
233 /* In case of a SIGHUP, just reload the configuration. */
235 {
236 ConfigReloadPending = false;
238 }
239
240 if (autoprewarm_interval <= 0)
241 {
242 /* We're only dumping at shutdown, so just wait forever. */
245 -1L,
247 }
248 else
249 {
251 long delay_in_ms;
252
253 /* Compute the next dump time. */
256 autoprewarm_interval * 1000);
260
261 /* Perform a dump if it's time. */
262 if (delay_in_ms <= 0)
263 {
265 apw_dump_now(true, false);
266 continue;
267 }
268
269 /* Sleep until the next dump time. */
274 }
275
276 /* Reset the latch, loop. */
278 }
279
280 /*
281 * Dump one last time. We assume this is probably the result of a system
282 * shutdown, although it's possible that we've merely been terminated.
283 */
285 apw_dump_now(true, true);
286}
static void apw_load_buffers(void)
long TimestampDifferenceMilliseconds(TimestampTz start_time, TimestampTz stop_time)
Definition timestamp.c:1765
TimestampTz GetCurrentTimestamp(void)
Definition timestamp.c:1649
int64 TimestampTz
Definition timestamp.h:39
struct Latch * MyLatch
Definition globals.c:65
void ProcessConfigFile(GucContext context)
Definition guc-file.l:120
void SignalHandlerForShutdownRequest(SIGNAL_ARGS)
Definition interrupt.c:104
volatile sig_atomic_t ConfigReloadPending
Definition interrupt.c:27
void SignalHandlerForConfigReload(SIGNAL_ARGS)
Definition interrupt.c:61
void before_shmem_exit(pg_on_exit_callback function, Datum arg)
Definition ipc.c:344
void ResetLatch(Latch *latch)
Definition latch.c:374
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:696
#define TimestampTzPlusMilliseconds(tz, ms)
Definition timestamp.h:85
#define PG_WAIT_EXTENSION
#define WL_TIMEOUT
#define WL_EXIT_ON_PM_DEATH
#define WL_LATCH_SET
#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, fb(), 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 824 of file autoprewarm.c.

825{
826 pid_t pid;
827
828 if (!autoprewarm)
831 errmsg("autoprewarm is disabled")));
832
835 pid = apw_state->bgworker_pid;
837
838 if (pid != InvalidPid)
841 errmsg("autoprewarm worker is already running under PID %d",
842 (int) pid)));
843
845
847}
#define PG_RETURN_VOID()
Definition fmgr.h:350

References apw_init_shmem(), apw_start_leader_worker(), apw_state, autoprewarm, AutoPrewarmSharedState::bgworker_pid, ereport, errcode(), errmsg, ERROR, fb(), 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 120 of file autoprewarm.c.

Referenced by _PG_init(), and autoprewarm_start_worker().

◆ autoprewarm_interval

int autoprewarm_interval = 300
static

Definition at line 121 of file autoprewarm.c.

Referenced by _PG_init(), and autoprewarm_main().