PostgreSQL Source Code  git master
autoprewarm.c File Reference
#include "postgres.h"
#include <unistd.h>
#include "access/relation.h"
#include "access/xact.h"
#include "catalog/pg_class.h"
#include "catalog/pg_type.h"
#include "miscadmin.h"
#include "pgstat.h"
#include "postmaster/bgworker.h"
#include "postmaster/interrupt.h"
#include "storage/buf_internals.h"
#include "storage/dsm.h"
#include "storage/fd.h"
#include "storage/ipc.h"
#include "storage/latch.h"
#include "storage/lwlock.h"
#include "storage/proc.h"
#include "storage/procsignal.h"
#include "storage/shmem.h"
#include "storage/smgr.h"
#include "tcop/tcopprot.h"
#include "utils/acl.h"
#include "utils/datetime.h"
#include "utils/guc.h"
#include "utils/memutils.h"
#include "utils/rel.h"
#include "utils/relfilenumbermap.h"
#include "utils/resowner.h"
Include dependency graph for autoprewarm.c:

Go to the source code of this file.

Data Structures

struct  BlockInfoRecord
 
struct  AutoPrewarmSharedState
 

Macros

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

Typedefs

typedef struct BlockInfoRecord BlockInfoRecord
 
typedef struct AutoPrewarmSharedState AutoPrewarmSharedState
 

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)
 
static void autoprewarm_shmem_request (void)
 
void _PG_init (void)
 
Datum autoprewarm_start_worker (PG_FUNCTION_ARGS)
 
Datum autoprewarm_dump_now (PG_FUNCTION_ARGS)
 

Variables

static shmem_request_hook_type prev_shmem_request_hook = NULL
 
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 58 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:70
int a
Definition: isn.c:69

Definition at line 890 of file autoprewarm.c.

Typedef Documentation

◆ AutoPrewarmSharedState

◆ BlockInfoRecord

Function Documentation

◆ _PG_init()

void _PG_init ( void  )

Definition at line 112 of file autoprewarm.c.

113 {
114  DefineCustomIntVariable("pg_prewarm.autoprewarm_interval",
115  "Sets the interval between dumps of shared buffers",
116  "If set to zero, time-based dumping is disabled.",
118  300,
119  0, INT_MAX / 1000,
120  PGC_SIGHUP,
121  GUC_UNIT_S,
122  NULL,
123  NULL,
124  NULL);
125 
127  return;
128 
129  /* can't define PGC_POSTMASTER variable after startup */
130  DefineCustomBoolVariable("pg_prewarm.autoprewarm",
131  "Starts the autoprewarm worker.",
132  NULL,
133  &autoprewarm,
134  true,
136  0,
137  NULL,
138  NULL,
139  NULL);
140 
141  MarkGUCPrefixReserved("pg_prewarm");
142 
145 
146  /* Register autoprewarm worker, if enabled. */
147  if (autoprewarm)
149 }
static void autoprewarm_shmem_request(void)
Definition: autoprewarm.c:155
static bool autoprewarm
Definition: autoprewarm.c:105
static void apw_start_leader_worker(void)
Definition: autoprewarm.c:816
static shmem_request_hook_type prev_shmem_request_hook
Definition: autoprewarm.c:99
static int autoprewarm_interval
Definition: autoprewarm.c:106
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:4958
void MarkGUCPrefixReserved(const char *className)
Definition: guc.c:5105
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:4984
@ PGC_POSTMASTER
Definition: guc.h:70
@ PGC_SIGHUP
Definition: guc.h:71
#define GUC_UNIT_S
Definition: guc.h:233
shmem_request_hook_type shmem_request_hook
Definition: miscinit.c:1767
bool process_shared_preload_libraries_in_progress
Definition: miscinit.c:1764

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

◆ apw_compare_blockinfo()

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

Definition at line 908 of file autoprewarm.c.

909 {
910  const BlockInfoRecord *a = (const BlockInfoRecord *) p;
911  const BlockInfoRecord *b = (const BlockInfoRecord *) q;
912 
913  cmp_member_elem(database);
915  cmp_member_elem(filenumber);
916  cmp_member_elem(forknum);
917  cmp_member_elem(blocknum);
918 
919  return 0;
920 }
#define cmp_member_elem(fld)
Definition: autoprewarm.c:890
char * tablespace
Definition: pgbench.c:216

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 802 of file autoprewarm.c.

803 {
810 }
static AutoPrewarmSharedState * apw_state
Definition: autoprewarm.c:102
int MyProcPid
Definition: globals.c:44
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1195
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1808
@ LW_EXCLUSIVE
Definition: lwlock.h:116
#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 581 of file autoprewarm.c.

582 {
583  int num_blocks;
584  int i;
585  int ret;
586  BlockInfoRecord *block_info_array;
587  BufferDesc *bufHdr;
588  FILE *file;
589  char transient_dump_file_path[MAXPGPATH];
590  pid_t pid;
591 
597 
598  if (pid != InvalidPid)
599  {
600  if (!is_bgworker)
601  ereport(ERROR,
602  (errmsg("could not perform block dump because dump file is being used by PID %d",
603  (int) apw_state->pid_using_dumpfile)));
604 
605  ereport(LOG,
606  (errmsg("skipping block dump because it is already being performed by PID %d",
607  (int) apw_state->pid_using_dumpfile)));
608  return 0;
609  }
610 
611  block_info_array =
613 
614  for (num_blocks = 0, i = 0; i < NBuffers; i++)
615  {
616  uint32 buf_state;
617 
619 
620  bufHdr = GetBufferDescriptor(i);
621 
622  /* Lock each buffer header before inspecting. */
623  buf_state = LockBufHdr(bufHdr);
624 
625  /*
626  * Unlogged tables will be automatically truncated after a crash or
627  * unclean shutdown. In such cases we need not prewarm them. Dump them
628  * only if requested by caller.
629  */
630  if (buf_state & BM_TAG_VALID &&
631  ((buf_state & BM_PERMANENT) || dump_unlogged))
632  {
633  block_info_array[num_blocks].database = bufHdr->tag.dbOid;
634  block_info_array[num_blocks].tablespace = bufHdr->tag.spcOid;
635  block_info_array[num_blocks].filenumber =
636  BufTagGetRelNumber(&bufHdr->tag);
637  block_info_array[num_blocks].forknum =
638  BufTagGetForkNum(&bufHdr->tag);
639  block_info_array[num_blocks].blocknum = bufHdr->tag.blockNum;
640  ++num_blocks;
641  }
642 
643  UnlockBufHdr(bufHdr, buf_state);
644  }
645 
646  snprintf(transient_dump_file_path, MAXPGPATH, "%s.tmp", AUTOPREWARM_FILE);
647  file = AllocateFile(transient_dump_file_path, "w");
648  if (!file)
649  ereport(ERROR,
651  errmsg("could not open file \"%s\": %m",
652  transient_dump_file_path)));
653 
654  ret = fprintf(file, "<<%d>>\n", num_blocks);
655  if (ret < 0)
656  {
657  int save_errno = errno;
658 
659  FreeFile(file);
660  unlink(transient_dump_file_path);
661  errno = save_errno;
662  ereport(ERROR,
664  errmsg("could not write to file \"%s\": %m",
665  transient_dump_file_path)));
666  }
667 
668  for (i = 0; i < num_blocks; i++)
669  {
671 
672  ret = fprintf(file, "%u,%u,%u,%u,%u\n",
673  block_info_array[i].database,
674  block_info_array[i].tablespace,
675  block_info_array[i].filenumber,
676  (uint32) block_info_array[i].forknum,
677  block_info_array[i].blocknum);
678  if (ret < 0)
679  {
680  int save_errno = errno;
681 
682  FreeFile(file);
683  unlink(transient_dump_file_path);
684  errno = save_errno;
685  ereport(ERROR,
687  errmsg("could not write to file \"%s\": %m",
688  transient_dump_file_path)));
689  }
690  }
691 
692  pfree(block_info_array);
693 
694  /*
695  * Rename transient_dump_file_path to AUTOPREWARM_FILE to make things
696  * permanent.
697  */
698  ret = FreeFile(file);
699  if (ret != 0)
700  {
701  int save_errno = errno;
702 
703  unlink(transient_dump_file_path);
704  errno = save_errno;
705  ereport(ERROR,
707  errmsg("could not close file \"%s\": %m",
708  transient_dump_file_path)));
709  }
710 
711  (void) durable_rename(transient_dump_file_path, AUTOPREWARM_FILE, ERROR);
713 
714  ereport(DEBUG1,
715  (errmsg_internal("wrote block details for %d blocks", num_blocks)));
716  return num_blocks;
717 }
#define AUTOPREWARM_FILE
Definition: autoprewarm.c:58
#define BM_TAG_VALID
Definition: buf_internals.h:62
#define BM_PERMANENT
Definition: buf_internals.h:68
static ForkNumber BufTagGetForkNum(const BufferTag *tag)
static BufferDesc * GetBufferDescriptor(uint32 id)
static void UnlockBufHdr(BufferDesc *desc, uint32 buf_state)
static RelFileNumber BufTagGetRelNumber(const BufferTag *tag)
uint32 LockBufHdr(BufferDesc *desc)
Definition: bufmgr.c:5300
unsigned int uint32
Definition: c.h:495
int errmsg_internal(const char *fmt,...)
Definition: elog.c:1156
int errcode_for_file_access(void)
Definition: elog.c:881
int errmsg(const char *fmt,...)
Definition: elog.c:1069
#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
FILE * AllocateFile(const char *name, const char *mode)
Definition: fd.c:2528
int durable_rename(const char *oldfile, const char *newfile, int elevel)
Definition: fd.c:734
int FreeFile(FILE *file)
Definition: fd.c:2726
int NBuffers
Definition: globals.c:136
int i
Definition: isn.c:73
void pfree(void *pointer)
Definition: mcxt.c:1456
void * palloc(Size size)
Definition: mcxt.c:1226
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:121
#define MAXPGPATH
#define snprintf
Definition: port.h:238
#define fprintf
Definition: port.h:242
ForkNumber forknum
Definition: autoprewarm.c:66
RelFileNumber filenumber
Definition: autoprewarm.c:65
BlockNumber blocknum
Definition: autoprewarm.c:67
BufferTag tag
BlockNumber blockNum
Definition: buf_internals.h:97
Oid spcOid
Definition: buf_internals.h:93
Oid dbOid
Definition: buf_internals.h:94

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 776 of file autoprewarm.c.

777 {
778  bool found;
779 
780  LWLockAcquire(AddinShmemInitLock, LW_EXCLUSIVE);
781  apw_state = ShmemInitStruct("autoprewarm",
782  sizeof(AutoPrewarmSharedState),
783  &found);
784  if (!found)
785  {
786  /* First time through ... */
790  }
791  LWLockRelease(AddinShmemInitLock);
792 
793  LWLockRegisterTranche(apw_state->lock.tranche, "autoprewarm");
794 
795  return found;
796 }
void LWLockRegisterTranche(int tranche_id, const char *tranche_name)
Definition: lwlock.c:651
int LWLockNewTrancheId(void)
Definition: lwlock.c:627
void LWLockInitialize(LWLock *lock, int tranche_id)
Definition: lwlock.c:730
void * ShmemInitStruct(const char *name, Size size, bool *foundPtr)
Definition: shmem.c:396
uint16 tranche
Definition: lwlock.h:42

References apw_state, AutoPrewarmSharedState::bgworker_pid, InvalidPid, AutoPrewarmSharedState::lock, LW_EXCLUSIVE, LWLockAcquire(), LWLockInitialize(), LWLockNewTrancheId(), LWLockRegisterTranche(), LWLockRelease(), AutoPrewarmSharedState::pid_using_dumpfile, ShmemInitStruct(), and LWLock::tranche.

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

◆ apw_load_buffers()

static void apw_load_buffers ( void  )
static

Definition at line 287 of file autoprewarm.c.

288 {
289  FILE *file = NULL;
290  int num_elements,
291  i;
292  BlockInfoRecord *blkinfo;
293  dsm_segment *seg;
294 
295  /*
296  * Skip the prewarm if the dump file is in use; otherwise, prevent any
297  * other process from writing it while we're using it.
298  */
302  else
303  {
305  ereport(LOG,
306  (errmsg("skipping prewarm because block dump file is being written by PID %d",
307  (int) apw_state->pid_using_dumpfile)));
308  return;
309  }
311 
312  /*
313  * Open the block dump file. Exit quietly if it doesn't exist, but report
314  * any other error.
315  */
316  file = AllocateFile(AUTOPREWARM_FILE, "r");
317  if (!file)
318  {
319  if (errno == ENOENT)
320  {
324  return; /* No file to load. */
325  }
326  ereport(ERROR,
328  errmsg("could not read file \"%s\": %m",
329  AUTOPREWARM_FILE)));
330  }
331 
332  /* First line of the file is a record count. */
333  if (fscanf(file, "<<%d>>\n", &num_elements) != 1)
334  ereport(ERROR,
336  errmsg("could not read from file \"%s\": %m",
337  AUTOPREWARM_FILE)));
338 
339  /* Allocate a dynamic shared memory segment to store the record data. */
340  seg = dsm_create(sizeof(BlockInfoRecord) * num_elements, 0);
341  blkinfo = (BlockInfoRecord *) dsm_segment_address(seg);
342 
343  /* Read records, one per line. */
344  for (i = 0; i < num_elements; i++)
345  {
346  unsigned forknum;
347 
348  if (fscanf(file, "%u,%u,%u,%u,%u\n", &blkinfo[i].database,
349  &blkinfo[i].tablespace, &blkinfo[i].filenumber,
350  &forknum, &blkinfo[i].blocknum) != 5)
351  ereport(ERROR,
352  (errmsg("autoprewarm block dump file is corrupted at line %d",
353  i + 1)));
354  blkinfo[i].forknum = forknum;
355  }
356 
357  FreeFile(file);
358 
359  /* Sort the blocks to be loaded. */
360  pg_qsort(blkinfo, num_elements, sizeof(BlockInfoRecord),
362 
363  /* Populate shared memory state. */
367 
368  /* Get the info position of the first block of the next database. */
369  while (apw_state->prewarm_start_idx < num_elements)
370  {
372  Oid current_db = blkinfo[j].database;
373 
374  /*
375  * Advance the prewarm_stop_idx to the first BlockInfoRecord that does
376  * not belong to this database.
377  */
378  j++;
379  while (j < num_elements)
380  {
381  if (current_db != blkinfo[j].database)
382  {
383  /*
384  * Combine BlockInfoRecords for global objects with those of
385  * the database.
386  */
387  if (current_db != InvalidOid)
388  break;
389  current_db = blkinfo[j].database;
390  }
391 
392  j++;
393  }
394 
395  /*
396  * If we reach this point with current_db == InvalidOid, then only
397  * BlockInfoRecords belonging to global objects exist. We can't
398  * prewarm without a database connection, so just bail out.
399  */
400  if (current_db == InvalidOid)
401  break;
402 
403  /* Configure stop point and database for next per-database worker. */
405  apw_state->database = current_db;
407 
408  /* If we've run out of free buffers, don't launch another worker. */
409  if (!have_free_buffer())
410  break;
411 
412  /*
413  * Likewise, don't launch if we've already been told to shut down.
414  * (The launch would fail anyway, but we might as well skip it.)
415  */
417  break;
418 
419  /*
420  * Start a per-database worker to load blocks for this database; this
421  * function will return once the per-database worker exits.
422  */
424 
425  /* Prepare for next database. */
427  }
428 
429  /* Clean up. */
430  dsm_detach(seg);
435 
436  /* Report our success, if we were able to finish. */
438  ereport(LOG,
439  (errmsg("autoprewarm successfully prewarmed %d of %d previously-loaded blocks",
440  apw_state->prewarmed_blocks, num_elements)));
441 }
static int apw_compare_blockinfo(const void *p, const void *q)
Definition: autoprewarm.c:908
static void apw_start_database_worker(void)
Definition: autoprewarm.c:858
dsm_handle dsm_segment_handle(dsm_segment *seg)
Definition: dsm.c:1094
void * dsm_segment_address(dsm_segment *seg)
Definition: dsm.c:1066
void dsm_detach(dsm_segment *seg)
Definition: dsm.c:776
dsm_segment * dsm_create(Size size, int flags)
Definition: dsm.c:489
#define DSM_HANDLE_INVALID
Definition: dsm_impl.h:58
bool have_free_buffer(void)
Definition: freelist.c:175
volatile sig_atomic_t ShutdownRequestPending
Definition: interrupt.c:28
int j
Definition: isn.c:74
Assert(fmt[strlen(fmt) - 1] !='\n')
void pg_qsort(void *base, size_t nel, size_t elsize, int(*cmp)(const void *, const void *))
#define InvalidOid
Definition: postgres_ext.h:36
unsigned int Oid
Definition: postgres_ext.h:31
dsm_handle block_info_handle
Definition: autoprewarm.c:78

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, pg_qsort(), AutoPrewarmSharedState::pid_using_dumpfile, AutoPrewarmSharedState::prewarm_start_idx, AutoPrewarmSharedState::prewarm_stop_idx, AutoPrewarmSharedState::prewarmed_blocks, ShutdownRequestPending, and tablespace.

Referenced by autoprewarm_main().

◆ apw_start_database_worker()

static void apw_start_database_worker ( void  )
static

Definition at line 858 of file autoprewarm.c.

859 {
860  BackgroundWorker worker;
861  BackgroundWorkerHandle *handle;
862 
863  MemSet(&worker, 0, sizeof(BackgroundWorker));
864  worker.bgw_flags =
868  strcpy(worker.bgw_library_name, "pg_prewarm");
869  strcpy(worker.bgw_function_name, "autoprewarm_database_main");
870  strcpy(worker.bgw_name, "autoprewarm worker");
871  strcpy(worker.bgw_type, "autoprewarm worker");
872 
873  /* must set notify PID to wait for shutdown */
874  worker.bgw_notify_pid = MyProcPid;
875 
876  if (!RegisterDynamicBackgroundWorker(&worker, &handle))
877  ereport(ERROR,
878  (errcode(ERRCODE_INSUFFICIENT_RESOURCES),
879  errmsg("registering dynamic bgworker autoprewarm failed"),
880  errhint("Consider increasing configuration parameter \"max_worker_processes\".")));
881 
882  /*
883  * Ignore return value; if it fails, postmaster has died, but we have
884  * checks for that elsewhere.
885  */
887 }
BgwHandleStatus WaitForBackgroundWorkerShutdown(BackgroundWorkerHandle *handle)
Definition: bgworker.c:1174
bool RegisterDynamicBackgroundWorker(BackgroundWorker *worker, BackgroundWorkerHandle **handle)
Definition: bgworker.c:962
#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
#define MemSet(start, val, len)
Definition: c.h:1009
int errhint(const char *fmt,...)
Definition: elog.c:1316
int errcode(int sqlerrcode)
Definition: elog.c:858
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, MemSet, MyProcPid, RegisterDynamicBackgroundWorker(), and WaitForBackgroundWorkerShutdown().

Referenced by apw_load_buffers().

◆ apw_start_leader_worker()

static void apw_start_leader_worker ( void  )
static

Definition at line 816 of file autoprewarm.c.

817 {
818  BackgroundWorker worker;
819  BackgroundWorkerHandle *handle;
820  BgwHandleStatus status;
821  pid_t pid;
822 
823  MemSet(&worker, 0, sizeof(BackgroundWorker));
826  strcpy(worker.bgw_library_name, "pg_prewarm");
827  strcpy(worker.bgw_function_name, "autoprewarm_main");
828  strcpy(worker.bgw_name, "autoprewarm leader");
829  strcpy(worker.bgw_type, "autoprewarm leader");
830 
832  {
833  RegisterBackgroundWorker(&worker);
834  return;
835  }
836 
837  /* must set notify PID to wait for startup */
838  worker.bgw_notify_pid = MyProcPid;
839 
840  if (!RegisterDynamicBackgroundWorker(&worker, &handle))
841  ereport(ERROR,
842  (errcode(ERRCODE_INSUFFICIENT_RESOURCES),
843  errmsg("could not register background process"),
844  errhint("You may need to increase max_worker_processes.")));
845 
846  status = WaitForBackgroundWorkerStartup(handle, &pid);
847  if (status != BGWH_STARTED)
848  ereport(ERROR,
849  (errcode(ERRCODE_INSUFFICIENT_RESOURCES),
850  errmsg("could not start background process"),
851  errhint("More details may be available in the server log.")));
852 }
void RegisterBackgroundWorker(BackgroundWorker *worker)
Definition: bgworker.c:878
BgwHandleStatus WaitForBackgroundWorkerStartup(BackgroundWorkerHandle *handle, pid_t *pidp)
Definition: bgworker.c:1129
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, MemSet, 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 448 of file autoprewarm.c.

449 {
450  int pos;
451  BlockInfoRecord *block_info;
452  Relation rel = NULL;
453  BlockNumber nblocks = 0;
454  BlockInfoRecord *old_blk = NULL;
455  dsm_segment *seg;
456 
457  /* Establish signal handlers; once that's done, unblock signals. */
458  pqsignal(SIGTERM, die);
460 
461  /* Connect to correct database and get block information. */
462  apw_init_shmem();
464  if (seg == NULL)
465  ereport(ERROR,
466  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
467  errmsg("could not map dynamic shared memory segment")));
469  block_info = (BlockInfoRecord *) dsm_segment_address(seg);
471 
472  /*
473  * Loop until we run out of blocks to prewarm or until we run out of free
474  * buffers.
475  */
476  while (pos < apw_state->prewarm_stop_idx && have_free_buffer())
477  {
478  BlockInfoRecord *blk = &block_info[pos++];
479  Buffer buf;
480 
482 
483  /*
484  * Quit if we've reached records for another database. If previous
485  * blocks are of some global objects, then continue pre-warming.
486  */
487  if (old_blk != NULL && old_blk->database != blk->database &&
488  old_blk->database != 0)
489  break;
490 
491  /*
492  * As soon as we encounter a block of a new relation, close the old
493  * relation. Note that rel will be NULL if try_relation_open failed
494  * previously; in that case, there is nothing to close.
495  */
496  if (old_blk != NULL && old_blk->filenumber != blk->filenumber &&
497  rel != NULL)
498  {
500  rel = NULL;
502  }
503 
504  /*
505  * Try to open each new relation, but only once, when we first
506  * encounter it. If it's been dropped, skip the associated blocks.
507  */
508  if (old_blk == NULL || old_blk->filenumber != blk->filenumber)
509  {
510  Oid reloid;
511 
512  Assert(rel == NULL);
514  reloid = RelidByRelfilenumber(blk->tablespace, blk->filenumber);
515  if (OidIsValid(reloid))
516  rel = try_relation_open(reloid, AccessShareLock);
517 
518  if (!rel)
520  }
521  if (!rel)
522  {
523  old_blk = blk;
524  continue;
525  }
526 
527  /* Once per fork, check for fork existence and size. */
528  if (old_blk == NULL ||
529  old_blk->filenumber != blk->filenumber ||
530  old_blk->forknum != blk->forknum)
531  {
532  /*
533  * smgrexists is not safe for illegal forknum, hence check whether
534  * the passed forknum is valid before using it in smgrexists.
535  */
536  if (blk->forknum > InvalidForkNumber &&
537  blk->forknum <= MAX_FORKNUM &&
538  smgrexists(RelationGetSmgr(rel), blk->forknum))
539  nblocks = RelationGetNumberOfBlocksInFork(rel, blk->forknum);
540  else
541  nblocks = 0;
542  }
543 
544  /* Check whether blocknum is valid and within fork file size. */
545  if (blk->blocknum >= nblocks)
546  {
547  /* Move to next forknum. */
548  old_blk = blk;
549  continue;
550  }
551 
552  /* Prewarm buffer. */
553  buf = ReadBufferExtended(rel, blk->forknum, blk->blocknum, RBM_NORMAL,
554  NULL);
555  if (BufferIsValid(buf))
556  {
559  }
560 
561  old_blk = blk;
562  }
563 
564  dsm_detach(seg);
565 
566  /* Release lock on previous relation. */
567  if (rel)
568  {
571  }
572 }
static bool apw_init_shmem(void)
Definition: autoprewarm.c:776
uint32 BlockNumber
Definition: block.h:31
int Buffer
Definition: buf.h:23
BlockNumber RelationGetNumberOfBlocksInFork(Relation relation, ForkNumber forkNum)
Definition: bufmgr.c:3489
void ReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:4480
Buffer ReadBufferExtended(Relation reln, ForkNumber forkNum, BlockNumber blockNum, ReadBufferMode mode, BufferAccessStrategy strategy)
Definition: bufmgr.c:755
@ RBM_NORMAL
Definition: bufmgr.h:44
static bool BufferIsValid(Buffer bufnum)
Definition: bufmgr.h:301
#define OidIsValid(objectId)
Definition: c.h:764
dsm_segment * dsm_attach(dsm_handle h)
Definition: dsm.c:638
#define AccessShareLock
Definition: lockdefs.h:36
#define die(msg)
Definition: pg_test_fsync.c:95
static char * buf
Definition: pg_test_fsync.c:67
pqsigfunc pqsignal(int signo, pqsigfunc func)
void BackgroundWorkerUnblockSignals(void)
Definition: postmaster.c:5638
void BackgroundWorkerInitializeConnectionByOid(Oid dboid, Oid useroid, uint32 flags)
Definition: postmaster.c:5605
static SMgrRelation RelationGetSmgr(Relation rel)
Definition: rel.h:572
Oid RelidByRelfilenumber(Oid reltablespace, RelFileNumber relfilenumber)
@ InvalidForkNumber
Definition: relpath.h:49
#define MAX_FORKNUM
Definition: relpath.h:62
bool smgrexists(SMgrRelation reln, ForkNumber forknum)
Definition: smgr.c:251
void relation_close(Relation relation, LOCKMODE lockmode)
Definition: relation.c:206
Relation try_relation_open(Oid relationId, LOCKMODE lockmode)
Definition: relation.c:89
void StartTransactionCommand(void)
Definition: xact.c:2937
void CommitTransactionCommand(void)
Definition: xact.c:3034

References AccessShareLock, apw_init_shmem(), apw_state, Assert(), BackgroundWorkerInitializeConnectionByOid(), BackgroundWorkerUnblockSignals(), AutoPrewarmSharedState::block_info_handle, BlockInfoRecord::blocknum, buf, BufferIsValid(), CHECK_FOR_INTERRUPTS, CommitTransactionCommand(), BlockInfoRecord::database, AutoPrewarmSharedState::database, die, dsm_attach(), dsm_detach(), dsm_segment_address(), ereport, errcode(), errmsg(), ERROR, BlockInfoRecord::filenumber, BlockInfoRecord::forknum, have_free_buffer(), InvalidForkNumber, InvalidOid, MAX_FORKNUM, OidIsValid, pqsignal(), AutoPrewarmSharedState::prewarm_start_idx, AutoPrewarmSharedState::prewarmed_blocks, RBM_NORMAL, ReadBufferExtended(), relation_close(), RelationGetNumberOfBlocksInFork(), RelationGetSmgr(), ReleaseBuffer(), RelidByRelfilenumber(), smgrexists(), StartTransactionCommand(), BlockInfoRecord::tablespace, and try_relation_open().

◆ autoprewarm_dump_now()

Datum autoprewarm_dump_now ( PG_FUNCTION_ARGS  )

Definition at line 755 of file autoprewarm.c.

756 {
757  int num_blocks;
758 
759  apw_init_shmem();
760 
762  {
763  num_blocks = apw_dump_now(false, true);
764  }
766 
767  PG_RETURN_INT64((int64) num_blocks);
768 }
static void apw_detach_shmem(int code, Datum arg)
Definition: autoprewarm.c:802
static int apw_dump_now(bool is_bgworker, bool dump_unlogged)
Definition: autoprewarm.c:581
#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 168 of file autoprewarm.c.

169 {
170  bool first_time = true;
171  bool final_dump_allowed = true;
172  TimestampTz last_dump_time = 0;
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  /* Set on-detach hook so that our PID will be cleared on exit. */
186 
187  /*
188  * Store our PID in the shared memory area --- unless there's already
189  * another worker running, in which case just exit.
190  */
193  {
195  ereport(LOG,
196  (errmsg("autoprewarm worker is already running under PID %d",
197  (int) apw_state->bgworker_pid)));
198  return;
199  }
202 
203  /*
204  * Preload buffers from the dump file only if we just created the shared
205  * memory region. Otherwise, it's either already been done or shouldn't
206  * be done - e.g. because the old dump file has been overwritten since the
207  * server was started.
208  *
209  * There's not much point in performing a dump immediately after we finish
210  * preloading; so, if we do end up preloading, consider the last dump time
211  * to be equal to the current time.
212  *
213  * If apw_load_buffers() is terminated early by a shutdown request,
214  * prevent dumping out our state below the loop, because we'd effectively
215  * just truncate the saved state to however much we'd managed to preload.
216  */
217  if (first_time)
218  {
220  final_dump_allowed = !ShutdownRequestPending;
221  last_dump_time = GetCurrentTimestamp();
222  }
223 
224  /* Periodically dump buffers until terminated. */
225  while (!ShutdownRequestPending)
226  {
227  /* In case of a SIGHUP, just reload the configuration. */
229  {
230  ConfigReloadPending = false;
232  }
233 
234  if (autoprewarm_interval <= 0)
235  {
236  /* We're only dumping at shutdown, so just wait forever. */
237  (void) WaitLatch(MyLatch,
239  -1L,
241  }
242  else
243  {
244  TimestampTz next_dump_time;
245  long delay_in_ms;
246 
247  /* Compute the next dump time. */
248  next_dump_time =
249  TimestampTzPlusMilliseconds(last_dump_time,
250  autoprewarm_interval * 1000);
251  delay_in_ms =
253  next_dump_time);
254 
255  /* Perform a dump if it's time. */
256  if (delay_in_ms <= 0)
257  {
258  last_dump_time = GetCurrentTimestamp();
259  apw_dump_now(true, false);
260  continue;
261  }
262 
263  /* Sleep until the next dump time. */
264  (void) WaitLatch(MyLatch,
266  delay_in_ms,
268  }
269 
270  /* Reset the latch, loop. */
272  }
273 
274  /*
275  * Dump one last time. We assume this is probably the result of a system
276  * shutdown, although it's possible that we've merely been terminated.
277  */
278  if (final_dump_allowed)
279  apw_dump_now(true, true);
280 }
static void apw_load_buffers(void)
Definition: autoprewarm.c:287
long TimestampDifferenceMilliseconds(TimestampTz start_time, TimestampTz stop_time)
Definition: timestamp.c:1695
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1583
int64 TimestampTz
Definition: timestamp.h:39
struct Latch * MyLatch
Definition: globals.c:58
void ProcessConfigFile(GucContext context)
void SignalHandlerForShutdownRequest(SIGNAL_ARGS)
Definition: interrupt.c:109
volatile sig_atomic_t ConfigReloadPending
Definition: interrupt.c:27
void SignalHandlerForConfigReload(SIGNAL_ARGS)
Definition: interrupt.c:61
void on_shmem_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:361
void ResetLatch(Latch *latch)
Definition: latch.c:697
int WaitLatch(Latch *latch, int wakeEvents, long timeout, uint32 wait_event_info)
Definition: latch.c:490
#define WL_TIMEOUT
Definition: latch.h:128
#define WL_EXIT_ON_PM_DEATH
Definition: latch.h:130
#define WL_LATCH_SET
Definition: latch.h:125
void procsignal_sigusr1_handler(SIGNAL_ARGS)
Definition: procsignal.c:639
#define TimestampTzPlusMilliseconds(tz, ms)
Definition: timestamp.h:85
@ WAIT_EVENT_EXTENSION
Definition: wait_event.h:58
#define SIGHUP
Definition: win32_port.h:168
#define SIGUSR1
Definition: win32_port.h:180

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

◆ autoprewarm_shmem_request()

static void autoprewarm_shmem_request ( void  )
static

Definition at line 155 of file autoprewarm.c.

156 {
159 
161 }
#define MAXALIGN(LEN)
Definition: c.h:800
void RequestAddinShmemSpace(Size size)
Definition: ipci.c:71

References MAXALIGN, prev_shmem_request_hook, and RequestAddinShmemSpace().

Referenced by _PG_init().

◆ autoprewarm_start_worker()

Datum autoprewarm_start_worker ( PG_FUNCTION_ARGS  )

Definition at line 723 of file autoprewarm.c.

724 {
725  pid_t pid;
726 
727  if (!autoprewarm)
728  ereport(ERROR,
729  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
730  errmsg("autoprewarm is disabled")));
731 
732  apw_init_shmem();
734  pid = apw_state->bgworker_pid;
736 
737  if (pid != InvalidPid)
738  ereport(ERROR,
739  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
740  errmsg("autoprewarm worker is already running under PID %d",
741  (int) pid)));
742 
744 
745  PG_RETURN_VOID();
746 }
#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 105 of file autoprewarm.c.

Referenced by _PG_init(), and autoprewarm_start_worker().

◆ autoprewarm_interval

int autoprewarm_interval = 300
static

Definition at line 106 of file autoprewarm.c.

Referenced by _PG_init(), and autoprewarm_main().

◆ prev_shmem_request_hook

shmem_request_hook_type prev_shmem_request_hook = NULL
static

Definition at line 99 of file autoprewarm.c.

Referenced by _PG_init(), and autoprewarm_shmem_request().