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 "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/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)
 
void _PG_init (void)
 
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 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 880 of file autoprewarm.c.

Typedef Documentation

◆ AutoPrewarmSharedState

◆ BlockInfoRecord

Function Documentation

◆ _PG_init()

void _PG_init ( void  )

Definition at line 110 of file autoprewarm.c.

111 {
112  DefineCustomIntVariable("pg_prewarm.autoprewarm_interval",
113  "Sets the interval between dumps of shared buffers",
114  "If set to zero, time-based dumping is disabled.",
116  300,
117  0, INT_MAX / 1000,
118  PGC_SIGHUP,
119  GUC_UNIT_S,
120  NULL,
121  NULL,
122  NULL);
123 
125  return;
126 
127  /* can't define PGC_POSTMASTER variable after startup */
128  DefineCustomBoolVariable("pg_prewarm.autoprewarm",
129  "Starts the autoprewarm worker.",
130  NULL,
131  &autoprewarm,
132  true,
134  0,
135  NULL,
136  NULL,
137  NULL);
138 
139  MarkGUCPrefixReserved("pg_prewarm");
140 
141  /* Register autoprewarm worker, if enabled. */
142  if (autoprewarm)
144 }
static bool autoprewarm
Definition: autoprewarm.c:103
static void apw_start_leader_worker(void)
Definition: autoprewarm.c:806
static int autoprewarm_interval
Definition: autoprewarm.c:104
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:5075
void MarkGUCPrefixReserved(const char *className)
Definition: guc.c:5222
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:5101
@ PGC_POSTMASTER
Definition: guc.h:70
@ PGC_SIGHUP
Definition: guc.h:71
#define GUC_UNIT_S
Definition: guc.h:235
bool process_shared_preload_libraries_in_progress
Definition: miscinit.c:1778

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

899 {
900  const BlockInfoRecord *a = (const BlockInfoRecord *) p;
901  const BlockInfoRecord *b = (const BlockInfoRecord *) q;
902 
903  cmp_member_elem(database);
905  cmp_member_elem(filenumber);
906  cmp_member_elem(forknum);
907  cmp_member_elem(blocknum);
908 
909  return 0;
910 }
#define cmp_member_elem(fld)
Definition: autoprewarm.c:880
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 792 of file autoprewarm.c.

793 {
800 }
static AutoPrewarmSharedState * apw_state
Definition: autoprewarm.c:100
int MyProcPid
Definition: globals.c:45
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1170
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1783
@ 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 570 of file autoprewarm.c.

571 {
572  int num_blocks;
573  int i;
574  int ret;
575  BlockInfoRecord *block_info_array;
576  BufferDesc *bufHdr;
577  FILE *file;
578  char transient_dump_file_path[MAXPGPATH];
579  pid_t pid;
580 
586 
587  if (pid != InvalidPid)
588  {
589  if (!is_bgworker)
590  ereport(ERROR,
591  (errmsg("could not perform block dump because dump file is being used by PID %d",
592  (int) apw_state->pid_using_dumpfile)));
593 
594  ereport(LOG,
595  (errmsg("skipping block dump because it is already being performed by PID %d",
596  (int) apw_state->pid_using_dumpfile)));
597  return 0;
598  }
599 
600  block_info_array =
602 
603  for (num_blocks = 0, i = 0; i < NBuffers; i++)
604  {
605  uint32 buf_state;
606 
608 
609  bufHdr = GetBufferDescriptor(i);
610 
611  /* Lock each buffer header before inspecting. */
612  buf_state = LockBufHdr(bufHdr);
613 
614  /*
615  * Unlogged tables will be automatically truncated after a crash or
616  * unclean shutdown. In such cases we need not prewarm them. Dump them
617  * only if requested by caller.
618  */
619  if (buf_state & BM_TAG_VALID &&
620  ((buf_state & BM_PERMANENT) || dump_unlogged))
621  {
622  block_info_array[num_blocks].database = bufHdr->tag.dbOid;
623  block_info_array[num_blocks].tablespace = bufHdr->tag.spcOid;
624  block_info_array[num_blocks].filenumber =
625  BufTagGetRelNumber(&bufHdr->tag);
626  block_info_array[num_blocks].forknum =
627  BufTagGetForkNum(&bufHdr->tag);
628  block_info_array[num_blocks].blocknum = bufHdr->tag.blockNum;
629  ++num_blocks;
630  }
631 
632  UnlockBufHdr(bufHdr, buf_state);
633  }
634 
635  snprintf(transient_dump_file_path, MAXPGPATH, "%s.tmp", AUTOPREWARM_FILE);
636  file = AllocateFile(transient_dump_file_path, "w");
637  if (!file)
638  ereport(ERROR,
640  errmsg("could not open file \"%s\": %m",
641  transient_dump_file_path)));
642 
643  ret = fprintf(file, "<<%d>>\n", num_blocks);
644  if (ret < 0)
645  {
646  int save_errno = errno;
647 
648  FreeFile(file);
649  unlink(transient_dump_file_path);
650  errno = save_errno;
651  ereport(ERROR,
653  errmsg("could not write to file \"%s\": %m",
654  transient_dump_file_path)));
655  }
656 
657  for (i = 0; i < num_blocks; i++)
658  {
660 
661  ret = fprintf(file, "%u,%u,%u,%u,%u\n",
662  block_info_array[i].database,
663  block_info_array[i].tablespace,
664  block_info_array[i].filenumber,
665  (uint32) block_info_array[i].forknum,
666  block_info_array[i].blocknum);
667  if (ret < 0)
668  {
669  int save_errno = errno;
670 
671  FreeFile(file);
672  unlink(transient_dump_file_path);
673  errno = save_errno;
674  ereport(ERROR,
676  errmsg("could not write to file \"%s\": %m",
677  transient_dump_file_path)));
678  }
679  }
680 
681  pfree(block_info_array);
682 
683  /*
684  * Rename transient_dump_file_path to AUTOPREWARM_FILE to make things
685  * permanent.
686  */
687  ret = FreeFile(file);
688  if (ret != 0)
689  {
690  int save_errno = errno;
691 
692  unlink(transient_dump_file_path);
693  errno = save_errno;
694  ereport(ERROR,
696  errmsg("could not close file \"%s\": %m",
697  transient_dump_file_path)));
698  }
699 
700  (void) durable_rename(transient_dump_file_path, AUTOPREWARM_FILE, ERROR);
702 
703  ereport(DEBUG1,
704  (errmsg_internal("wrote block details for %d blocks", num_blocks)));
705  return num_blocks;
706 }
#define AUTOPREWARM_FILE
Definition: autoprewarm.c:58
#define BM_TAG_VALID
Definition: buf_internals.h:63
#define BM_PERMANENT
Definition: buf_internals.h:69
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:5688
unsigned int uint32
Definition: c.h:506
int errmsg_internal(const char *fmt,...)
Definition: elog.c:1159
int errcode_for_file_access(void)
Definition: elog.c:882
int errmsg(const char *fmt,...)
Definition: elog.c:1072
#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:2583
int durable_rename(const char *oldfile, const char *newfile, int elevel)
Definition: fd.c:782
int FreeFile(FILE *file)
Definition: fd.c:2781
int NBuffers
Definition: globals.c:139
int i
Definition: isn.c:73
void pfree(void *pointer)
Definition: mcxt.c:1520
void * palloc(Size size)
Definition: mcxt.c:1316
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:122
#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:98
Oid spcOid
Definition: buf_internals.h:94
Oid dbOid
Definition: buf_internals.h:95

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

776 {
777  bool found;
778 
779  apw_state = GetNamedDSMSegment("autoprewarm",
780  sizeof(AutoPrewarmSharedState),
782  &found);
783  LWLockRegisterTranche(apw_state->lock.tranche, "autoprewarm");
784 
785  return found;
786 }
static void apw_init_state(void *ptr)
Definition: autoprewarm.c:760
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:630
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 760 of file autoprewarm.c.

761 {
763 
765  state->bgworker_pid = InvalidPid;
766  state->pid_using_dumpfile = InvalidPid;
767 }
int LWLockNewTrancheId(void)
Definition: lwlock.c:606
void LWLockInitialize(LWLock *lock, int tranche_id)
Definition: lwlock.c:709
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 276 of file autoprewarm.c.

277 {
278  FILE *file = NULL;
279  int num_elements,
280  i;
281  BlockInfoRecord *blkinfo;
282  dsm_segment *seg;
283 
284  /*
285  * Skip the prewarm if the dump file is in use; otherwise, prevent any
286  * other process from writing it while we're using it.
287  */
291  else
292  {
294  ereport(LOG,
295  (errmsg("skipping prewarm because block dump file is being written by PID %d",
296  (int) apw_state->pid_using_dumpfile)));
297  return;
298  }
300 
301  /*
302  * Open the block dump file. Exit quietly if it doesn't exist, but report
303  * any other error.
304  */
305  file = AllocateFile(AUTOPREWARM_FILE, "r");
306  if (!file)
307  {
308  if (errno == ENOENT)
309  {
313  return; /* No file to load. */
314  }
315  ereport(ERROR,
317  errmsg("could not read file \"%s\": %m",
318  AUTOPREWARM_FILE)));
319  }
320 
321  /* First line of the file is a record count. */
322  if (fscanf(file, "<<%d>>\n", &num_elements) != 1)
323  ereport(ERROR,
325  errmsg("could not read from file \"%s\": %m",
326  AUTOPREWARM_FILE)));
327 
328  /* Allocate a dynamic shared memory segment to store the record data. */
329  seg = dsm_create(sizeof(BlockInfoRecord) * num_elements, 0);
330  blkinfo = (BlockInfoRecord *) dsm_segment_address(seg);
331 
332  /* Read records, one per line. */
333  for (i = 0; i < num_elements; i++)
334  {
335  unsigned forknum;
336 
337  if (fscanf(file, "%u,%u,%u,%u,%u\n", &blkinfo[i].database,
338  &blkinfo[i].tablespace, &blkinfo[i].filenumber,
339  &forknum, &blkinfo[i].blocknum) != 5)
340  ereport(ERROR,
341  (errmsg("autoprewarm block dump file is corrupted at line %d",
342  i + 1)));
343  blkinfo[i].forknum = forknum;
344  }
345 
346  FreeFile(file);
347 
348  /* Sort the blocks to be loaded. */
349  qsort(blkinfo, num_elements, sizeof(BlockInfoRecord),
351 
352  /* Populate shared memory state. */
356 
357  /* Get the info position of the first block of the next database. */
358  while (apw_state->prewarm_start_idx < num_elements)
359  {
361  Oid current_db = blkinfo[j].database;
362 
363  /*
364  * Advance the prewarm_stop_idx to the first BlockInfoRecord that does
365  * not belong to this database.
366  */
367  j++;
368  while (j < num_elements)
369  {
370  if (current_db != blkinfo[j].database)
371  {
372  /*
373  * Combine BlockInfoRecords for global objects with those of
374  * the database.
375  */
376  if (current_db != InvalidOid)
377  break;
378  current_db = blkinfo[j].database;
379  }
380 
381  j++;
382  }
383 
384  /*
385  * If we reach this point with current_db == InvalidOid, then only
386  * BlockInfoRecords belonging to global objects exist. We can't
387  * prewarm without a database connection, so just bail out.
388  */
389  if (current_db == InvalidOid)
390  break;
391 
392  /* Configure stop point and database for next per-database worker. */
394  apw_state->database = current_db;
396 
397  /* If we've run out of free buffers, don't launch another worker. */
398  if (!have_free_buffer())
399  break;
400 
401  /*
402  * Likewise, don't launch if we've already been told to shut down.
403  * (The launch would fail anyway, but we might as well skip it.)
404  */
406  break;
407 
408  /*
409  * Start a per-database worker to load blocks for this database; this
410  * function will return once the per-database worker exits.
411  */
413 
414  /* Prepare for next database. */
416  }
417 
418  /* Clean up. */
419  dsm_detach(seg);
424 
425  /* Report our success, if we were able to finish. */
427  ereport(LOG,
428  (errmsg("autoprewarm successfully prewarmed %d of %d previously-loaded blocks",
429  apw_state->prewarmed_blocks, num_elements)));
430 }
static int apw_compare_blockinfo(const void *p, const void *q)
Definition: autoprewarm.c:898
static void apw_start_database_worker(void)
Definition: autoprewarm.c:848
#define Assert(condition)
Definition: c.h:858
dsm_handle dsm_segment_handle(dsm_segment *seg)
Definition: dsm.c:1123
void * dsm_segment_address(dsm_segment *seg)
Definition: dsm.c:1095
void dsm_detach(dsm_segment *seg)
Definition: dsm.c:803
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
volatile sig_atomic_t ShutdownRequestPending
Definition: interrupt.c:28
int j
Definition: isn.c:74
#define qsort(a, b, c, d)
Definition: port.h:449
#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, AutoPrewarmSharedState::pid_using_dumpfile, AutoPrewarmSharedState::prewarm_start_idx, AutoPrewarmSharedState::prewarm_stop_idx, AutoPrewarmSharedState::prewarmed_blocks, qsort, ShutdownRequestPending, and tablespace.

Referenced by autoprewarm_main().

◆ apw_start_database_worker()

static void apw_start_database_worker ( void  )
static

Definition at line 848 of file autoprewarm.c.

849 {
850  BackgroundWorker worker;
851  BackgroundWorkerHandle *handle;
852 
853  MemSet(&worker, 0, sizeof(BackgroundWorker));
854  worker.bgw_flags =
858  strcpy(worker.bgw_library_name, "pg_prewarm");
859  strcpy(worker.bgw_function_name, "autoprewarm_database_main");
860  strcpy(worker.bgw_name, "autoprewarm worker");
861  strcpy(worker.bgw_type, "autoprewarm worker");
862 
863  /* must set notify PID to wait for shutdown */
864  worker.bgw_notify_pid = MyProcPid;
865 
866  if (!RegisterDynamicBackgroundWorker(&worker, &handle))
867  ereport(ERROR,
868  (errcode(ERRCODE_INSUFFICIENT_RESOURCES),
869  errmsg("registering dynamic bgworker autoprewarm failed"),
870  errhint("Consider increasing configuration parameter max_worker_processes.")));
871 
872  /*
873  * Ignore return value; if it fails, postmaster has died, but we have
874  * checks for that elsewhere.
875  */
877 }
BgwHandleStatus WaitForBackgroundWorkerShutdown(BackgroundWorkerHandle *handle)
Definition: bgworker.c:1182
bool RegisterDynamicBackgroundWorker(BackgroundWorker *worker, BackgroundWorkerHandle **handle)
Definition: bgworker.c:970
#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:1020
int errhint(const char *fmt,...)
Definition: elog.c:1319
int errcode(int sqlerrcode)
Definition: elog.c:859
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 806 of file autoprewarm.c.

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

438 {
439  int pos;
440  BlockInfoRecord *block_info;
441  Relation rel = NULL;
442  BlockNumber nblocks = 0;
443  BlockInfoRecord *old_blk = NULL;
444  dsm_segment *seg;
445 
446  /* Establish signal handlers; once that's done, unblock signals. */
447  pqsignal(SIGTERM, die);
449 
450  /* Connect to correct database and get block information. */
451  apw_init_shmem();
453  if (seg == NULL)
454  ereport(ERROR,
455  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
456  errmsg("could not map dynamic shared memory segment")));
458  block_info = (BlockInfoRecord *) dsm_segment_address(seg);
460 
461  /*
462  * Loop until we run out of blocks to prewarm or until we run out of free
463  * buffers.
464  */
465  while (pos < apw_state->prewarm_stop_idx && have_free_buffer())
466  {
467  BlockInfoRecord *blk = &block_info[pos++];
468  Buffer buf;
469 
471 
472  /*
473  * Quit if we've reached records for another database. If previous
474  * blocks are of some global objects, then continue pre-warming.
475  */
476  if (old_blk != NULL && old_blk->database != blk->database &&
477  old_blk->database != 0)
478  break;
479 
480  /*
481  * As soon as we encounter a block of a new relation, close the old
482  * relation. Note that rel will be NULL if try_relation_open failed
483  * previously; in that case, there is nothing to close.
484  */
485  if (old_blk != NULL && old_blk->filenumber != blk->filenumber &&
486  rel != NULL)
487  {
489  rel = NULL;
491  }
492 
493  /*
494  * Try to open each new relation, but only once, when we first
495  * encounter it. If it's been dropped, skip the associated blocks.
496  */
497  if (old_blk == NULL || old_blk->filenumber != blk->filenumber)
498  {
499  Oid reloid;
500 
501  Assert(rel == NULL);
503  reloid = RelidByRelfilenumber(blk->tablespace, blk->filenumber);
504  if (OidIsValid(reloid))
505  rel = try_relation_open(reloid, AccessShareLock);
506 
507  if (!rel)
509  }
510  if (!rel)
511  {
512  old_blk = blk;
513  continue;
514  }
515 
516  /* Once per fork, check for fork existence and size. */
517  if (old_blk == NULL ||
518  old_blk->filenumber != blk->filenumber ||
519  old_blk->forknum != blk->forknum)
520  {
521  /*
522  * smgrexists is not safe for illegal forknum, hence check whether
523  * the passed forknum is valid before using it in smgrexists.
524  */
525  if (blk->forknum > InvalidForkNumber &&
526  blk->forknum <= MAX_FORKNUM &&
527  smgrexists(RelationGetSmgr(rel), blk->forknum))
528  nblocks = RelationGetNumberOfBlocksInFork(rel, blk->forknum);
529  else
530  nblocks = 0;
531  }
532 
533  /* Check whether blocknum is valid and within fork file size. */
534  if (blk->blocknum >= nblocks)
535  {
536  /* Move to next forknum. */
537  old_blk = blk;
538  continue;
539  }
540 
541  /* Prewarm buffer. */
542  buf = ReadBufferExtended(rel, blk->forknum, blk->blocknum, RBM_NORMAL,
543  NULL);
544  if (BufferIsValid(buf))
545  {
548  }
549 
550  old_blk = blk;
551  }
552 
553  dsm_detach(seg);
554 
555  /* Release lock on previous relation. */
556  if (rel)
557  {
560  }
561 }
static bool apw_init_shmem(void)
Definition: autoprewarm.c:775
uint32 BlockNumber
Definition: block.h:31
int Buffer
Definition: buf.h:23
BlockNumber RelationGetNumberOfBlocksInFork(Relation relation, ForkNumber forkNum)
Definition: bufmgr.c:3866
void ReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:4850
Buffer ReadBufferExtended(Relation reln, ForkNumber forkNum, BlockNumber blockNum, ReadBufferMode mode, BufferAccessStrategy strategy)
Definition: bufmgr.c:792
@ RBM_NORMAL
Definition: bufmgr.h:45
static bool BufferIsValid(Buffer bufnum)
Definition: bufmgr.h:359
#define OidIsValid(objectId)
Definition: c.h:775
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:73
pqsigfunc pqsignal(int signo, pqsigfunc func)
void BackgroundWorkerUnblockSignals(void)
Definition: postmaster.c:4229
void BackgroundWorkerInitializeConnectionByOid(Oid dboid, Oid useroid, uint32 flags)
Definition: postmaster.c:4189
static SMgrRelation RelationGetSmgr(Relation rel)
Definition: rel.h:567
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:398
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:2995
void CommitTransactionCommand(void)
Definition: xact.c:3093

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

745 {
746  int num_blocks;
747 
748  apw_init_shmem();
749 
751  {
752  num_blocks = apw_dump_now(false, true);
753  }
755 
756  PG_RETURN_INT64((int64) num_blocks);
757 }
static void apw_detach_shmem(int code, Datum arg)
Definition: autoprewarm.c:792
static int apw_dump_now(bool is_bgworker, bool dump_unlogged)
Definition: autoprewarm.c:570
#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 151 of file autoprewarm.c.

152 {
153  bool first_time = true;
154  bool final_dump_allowed = true;
155  TimestampTz last_dump_time = 0;
156 
157  /* Establish signal handlers; once that's done, unblock signals. */
162 
163  /* Create (if necessary) and attach to our shared memory area. */
164  if (apw_init_shmem())
165  first_time = false;
166 
167  /*
168  * Set on-detach hook so that our PID will be cleared on exit.
169  *
170  * NB: Autoprewarm's state is stored in a DSM segment, and DSM segments
171  * are detached before calling the on_shmem_exit callbacks, so we must put
172  * apw_detach_shmem in the before_shmem_exit callback list.
173  */
175 
176  /*
177  * Store our PID in the shared memory area --- unless there's already
178  * another worker running, in which case just exit.
179  */
182  {
184  ereport(LOG,
185  (errmsg("autoprewarm worker is already running under PID %d",
186  (int) apw_state->bgworker_pid)));
187  return;
188  }
191 
192  /*
193  * Preload buffers from the dump file only if we just created the shared
194  * memory region. Otherwise, it's either already been done or shouldn't
195  * be done - e.g. because the old dump file has been overwritten since the
196  * server was started.
197  *
198  * There's not much point in performing a dump immediately after we finish
199  * preloading; so, if we do end up preloading, consider the last dump time
200  * to be equal to the current time.
201  *
202  * If apw_load_buffers() is terminated early by a shutdown request,
203  * prevent dumping out our state below the loop, because we'd effectively
204  * just truncate the saved state to however much we'd managed to preload.
205  */
206  if (first_time)
207  {
209  final_dump_allowed = !ShutdownRequestPending;
210  last_dump_time = GetCurrentTimestamp();
211  }
212 
213  /* Periodically dump buffers until terminated. */
214  while (!ShutdownRequestPending)
215  {
216  /* In case of a SIGHUP, just reload the configuration. */
218  {
219  ConfigReloadPending = false;
221  }
222 
223  if (autoprewarm_interval <= 0)
224  {
225  /* We're only dumping at shutdown, so just wait forever. */
226  (void) WaitLatch(MyLatch,
228  -1L,
230  }
231  else
232  {
233  TimestampTz next_dump_time;
234  long delay_in_ms;
235 
236  /* Compute the next dump time. */
237  next_dump_time =
238  TimestampTzPlusMilliseconds(last_dump_time,
239  autoprewarm_interval * 1000);
240  delay_in_ms =
242  next_dump_time);
243 
244  /* Perform a dump if it's time. */
245  if (delay_in_ms <= 0)
246  {
247  last_dump_time = GetCurrentTimestamp();
248  apw_dump_now(true, false);
249  continue;
250  }
251 
252  /* Sleep until the next dump time. */
253  (void) WaitLatch(MyLatch,
255  delay_in_ms,
257  }
258 
259  /* Reset the latch, loop. */
261  }
262 
263  /*
264  * Dump one last time. We assume this is probably the result of a system
265  * shutdown, although it's possible that we've merely been terminated.
266  */
267  if (final_dump_allowed)
268  apw_dump_now(true, true);
269 }
static void apw_load_buffers(void)
Definition: autoprewarm.c:276
long TimestampDifferenceMilliseconds(TimestampTz start_time, TimestampTz stop_time)
Definition: timestamp.c:1766
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1654
int64 TimestampTz
Definition: timestamp.h:39
struct Latch * MyLatch
Definition: globals.c:60
void ProcessConfigFile(GucContext context)
void SignalHandlerForShutdownRequest(SIGNAL_ARGS)
Definition: interrupt.c:105
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:337
void ResetLatch(Latch *latch)
Definition: latch.c:724
int WaitLatch(Latch *latch, int wakeEvents, long timeout, uint32 wait_event_info)
Definition: latch.c:517
#define WL_TIMEOUT
Definition: latch.h:130
#define WL_EXIT_ON_PM_DEATH
Definition: latch.h:132
#define WL_LATCH_SET
Definition: latch.h:127
void procsignal_sigusr1_handler(SIGNAL_ARGS)
Definition: procsignal.c:635
#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(), before_shmem_exit(), AutoPrewarmSharedState::bgworker_pid, ConfigReloadPending, ereport, errmsg(), GetCurrentTimestamp(), InvalidPid, AutoPrewarmSharedState::lock, LOG, LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), MyLatch, MyProcPid, 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_start_worker()

Datum autoprewarm_start_worker ( PG_FUNCTION_ARGS  )

Definition at line 712 of file autoprewarm.c.

713 {
714  pid_t pid;
715 
716  if (!autoprewarm)
717  ereport(ERROR,
718  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
719  errmsg("autoprewarm is disabled")));
720 
721  apw_init_shmem();
723  pid = apw_state->bgworker_pid;
725 
726  if (pid != InvalidPid)
727  ereport(ERROR,
728  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
729  errmsg("autoprewarm worker is already running under PID %d",
730  (int) pid)));
731 
733 
734  PG_RETURN_VOID();
735 }
#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 103 of file autoprewarm.c.

Referenced by _PG_init(), and autoprewarm_start_worker().

◆ autoprewarm_interval

int autoprewarm_interval = 300
static

Definition at line 104 of file autoprewarm.c.

Referenced by _PG_init(), and autoprewarm_main().