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/relfilenodemap.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

void _PG_init (void)
 
void autoprewarm_main (Datum main_arg)
 
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)
 
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
 

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

Typedef Documentation

◆ AutoPrewarmSharedState

◆ BlockInfoRecord

Function Documentation

◆ _PG_init()

void _PG_init ( void  )

Definition at line 113 of file autoprewarm.c.

114 {
115  DefineCustomIntVariable("pg_prewarm.autoprewarm_interval",
116  "Sets the interval between dumps of shared buffers",
117  "If set to zero, time-based dumping is disabled.",
119  300,
120  0, INT_MAX / 1000,
121  PGC_SIGHUP,
122  GUC_UNIT_S,
123  NULL,
124  NULL,
125  NULL);
126 
128  return;
129 
130  /* can't define PGC_POSTMASTER variable after startup */
131  DefineCustomBoolVariable("pg_prewarm.autoprewarm",
132  "Starts the autoprewarm worker.",
133  NULL,
134  &autoprewarm,
135  true,
137  0,
138  NULL,
139  NULL,
140  NULL);
141 
142  MarkGUCPrefixReserved("pg_prewarm");
143 
146 
147  /* Register autoprewarm worker, if enabled. */
148  if (autoprewarm)
150 }
static void autoprewarm_shmem_request(void)
Definition: autoprewarm.c:156
static bool autoprewarm
Definition: autoprewarm.c:106
static void apw_start_leader_worker(void)
Definition: autoprewarm.c:815
static shmem_request_hook_type prev_shmem_request_hook
Definition: autoprewarm.c:100
static int autoprewarm_interval
Definition: autoprewarm.c:107
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:9476
void MarkGUCPrefixReserved(const char *className)
Definition: guc.c:9623
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:9502
@ PGC_POSTMASTER
Definition: guc.h:71
@ PGC_SIGHUP
Definition: guc.h:72
#define GUC_UNIT_S
Definition: guc.h:225
shmem_request_hook_type shmem_request_hook
Definition: miscinit.c:1621
bool process_shared_preload_libraries_in_progress
Definition: miscinit.c:1618

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

908 {
909  const BlockInfoRecord *a = (const BlockInfoRecord *) p;
910  const BlockInfoRecord *b = (const BlockInfoRecord *) q;
911 
912  cmp_member_elem(database);
914  cmp_member_elem(filenode);
915  cmp_member_elem(forknum);
916  cmp_member_elem(blocknum);
917 
918  return 0;
919 }
#define cmp_member_elem(fld)
Definition: autoprewarm.c:889
char * tablespace
Definition: pgbench.c:229

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

802 {
809 }
static AutoPrewarmSharedState * apw_state
Definition: autoprewarm.c:103
int MyProcPid
Definition: globals.c:44
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1196
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1800
@ 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 582 of file autoprewarm.c.

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

References AllocateFile(), apw_state, AUTOPREWARM_FILE, BlockInfoRecord::blocknum, buftag::blockNum, BM_PERMANENT, BM_TAG_VALID, CHECK_FOR_INTERRUPTS, BlockInfoRecord::database, RelFileNode::dbNode, DEBUG1, durable_rename(), ereport, errcode_for_file_access(), errmsg(), errmsg_internal(), ERROR, BlockInfoRecord::filenode, BlockInfoRecord::forknum, buftag::forkNum, fprintf, FreeFile(), GetBufferDescriptor, i, InvalidPid, AutoPrewarmSharedState::lock, LockBufHdr(), LOG, LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), MAXPGPATH, MyProcPid, NBuffers, palloc(), pfree(), AutoPrewarmSharedState::pid_using_dumpfile, RelFileNode::relNode, buftag::rnode, snprintf, RelFileNode::spcNode, 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  LWLockAcquire(AddinShmemInitLock, LW_EXCLUSIVE);
780  apw_state = ShmemInitStruct("autoprewarm",
781  sizeof(AutoPrewarmSharedState),
782  &found);
783  if (!found)
784  {
785  /* First time through ... */
789  }
790  LWLockRelease(AddinShmemInitLock);
791 
792  LWLockRegisterTranche(apw_state->lock.tranche, "autoprewarm");
793 
794  return found;
795 }
void LWLockRegisterTranche(int tranche_id, const char *tranche_name)
Definition: lwlock.c:650
int LWLockNewTrancheId(void)
Definition: lwlock.c:626
void LWLockInitialize(LWLock *lock, int tranche_id)
Definition: lwlock.c:734
void * ShmemInitStruct(const char *name, Size size, bool *foundPtr)
Definition: shmem.c:396
uint16 tranche
Definition: lwlock.h:33

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

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

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

816 {
817  BackgroundWorker worker;
818  BackgroundWorkerHandle *handle;
820  pid_t pid;
821 
822  MemSet(&worker, 0, sizeof(BackgroundWorker));
825  strcpy(worker.bgw_library_name, "pg_prewarm");
826  strcpy(worker.bgw_function_name, "autoprewarm_main");
827  strcpy(worker.bgw_name, "autoprewarm leader");
828  strcpy(worker.bgw_type, "autoprewarm leader");
829 
831  {
832  RegisterBackgroundWorker(&worker);
833  return;
834  }
835 
836  /* must set notify PID to wait for startup */
837  worker.bgw_notify_pid = MyProcPid;
838 
839  if (!RegisterDynamicBackgroundWorker(&worker, &handle))
840  ereport(ERROR,
841  (errcode(ERRCODE_INSUFFICIENT_RESOURCES),
842  errmsg("could not register background process"),
843  errhint("You may need to increase max_worker_processes.")));
844 
845  status = WaitForBackgroundWorkerStartup(handle, &pid);
846  if (status != BGWH_STARTED)
847  ereport(ERROR,
848  (errcode(ERRCODE_INSUFFICIENT_RESOURCES),
849  errmsg("could not start background process"),
850  errhint("More details may be available in the server log.")));
851 }
void RegisterBackgroundWorker(BackgroundWorker *worker)
Definition: bgworker.c:872
BgwHandleStatus WaitForBackgroundWorkerStartup(BackgroundWorkerHandle *handle, pid_t *pidp)
Definition: bgworker.c:1123
BgwHandleStatus
Definition: bgworker.h:104
@ BGWH_STARTED
Definition: bgworker.h:105
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:229

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(), status(), and WaitForBackgroundWorkerStartup().

Referenced by _PG_init(), and autoprewarm_start_worker().

◆ autoprewarm_database_main()

void autoprewarm_database_main ( Datum  main_arg)

Definition at line 449 of file autoprewarm.c.

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

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::filenode, 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(), RelidByRelfilenode(), smgrexists(), StartTransactionCommand(), BlockInfoRecord::tablespace, and try_relation_open().

◆ autoprewarm_dump_now()

Datum autoprewarm_dump_now ( PG_FUNCTION_ARGS  )

Definition at line 754 of file autoprewarm.c.

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

170 {
171  bool first_time = true;
172  bool final_dump_allowed = true;
173  TimestampTz last_dump_time = 0;
174 
175  /* Establish signal handlers; once that's done, unblock signals. */
180 
181  /* Create (if necessary) and attach to our shared memory area. */
182  if (apw_init_shmem())
183  first_time = false;
184 
185  /* Set on-detach hook so that our PID will be cleared on exit. */
187 
188  /*
189  * Store our PID in the shared memory area --- unless there's already
190  * another worker running, in which case just exit.
191  */
194  {
196  ereport(LOG,
197  (errmsg("autoprewarm worker is already running under PID %lu",
198  (unsigned long) apw_state->bgworker_pid)));
199  return;
200  }
203 
204  /*
205  * Preload buffers from the dump file only if we just created the shared
206  * memory region. Otherwise, it's either already been done or shouldn't
207  * be done - e.g. because the old dump file has been overwritten since the
208  * server was started.
209  *
210  * There's not much point in performing a dump immediately after we finish
211  * preloading; so, if we do end up preloading, consider the last dump time
212  * to be equal to the current time.
213  *
214  * If apw_load_buffers() is terminated early by a shutdown request,
215  * prevent dumping out our state below the loop, because we'd effectively
216  * just truncate the saved state to however much we'd managed to preload.
217  */
218  if (first_time)
219  {
221  final_dump_allowed = !ShutdownRequestPending;
222  last_dump_time = GetCurrentTimestamp();
223  }
224 
225  /* Periodically dump buffers until terminated. */
226  while (!ShutdownRequestPending)
227  {
228  /* In case of a SIGHUP, just reload the configuration. */
230  {
231  ConfigReloadPending = false;
233  }
234 
235  if (autoprewarm_interval <= 0)
236  {
237  /* We're only dumping at shutdown, so just wait forever. */
238  (void) WaitLatch(MyLatch,
240  -1L,
242  }
243  else
244  {
245  TimestampTz next_dump_time;
246  long delay_in_ms;
247 
248  /* Compute the next dump time. */
249  next_dump_time =
250  TimestampTzPlusMilliseconds(last_dump_time,
251  autoprewarm_interval * 1000);
252  delay_in_ms =
254  next_dump_time);
255 
256  /* Perform a dump if it's time. */
257  if (delay_in_ms <= 0)
258  {
259  last_dump_time = GetCurrentTimestamp();
260  apw_dump_now(true, false);
261  continue;
262  }
263 
264  /* Sleep until the next dump time. */
265  (void) WaitLatch(MyLatch,
267  delay_in_ms,
269  }
270 
271  /* Reset the latch, loop. */
273  }
274 
275  /*
276  * Dump one last time. We assume this is probably the result of a system
277  * shutdown, although it's possible that we've merely been terminated.
278  */
279  if (final_dump_allowed)
280  apw_dump_now(true, true);
281 }
static void apw_load_buffers(void)
Definition: autoprewarm.c:288
long TimestampDifferenceMilliseconds(TimestampTz start_time, TimestampTz stop_time)
Definition: timestamp.c:1687
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1574
int64 TimestampTz
Definition: timestamp.h:39
struct Latch * MyLatch
Definition: globals.c:58
void ProcessConfigFile(GucContext context)
void SignalHandlerForShutdownRequest(SIGNAL_ARGS)
Definition: interrupt.c:108
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:658
int WaitLatch(Latch *latch, int wakeEvents, long timeout, uint32 wait_event_info)
Definition: latch.c:451
#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:638
#define TimestampTzPlusMilliseconds(tz, ms)
Definition: timestamp.h:56
#define PG_WAIT_EXTENSION
Definition: wait_event.h:23
#define SIGHUP
Definition: win32_port.h:167
#define SIGUSR1
Definition: win32_port.h:179

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(), 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_shmem_request()

static void autoprewarm_shmem_request ( void  )
static

Definition at line 156 of file autoprewarm.c.

157 {
160 
162 }
#define MAXALIGN(LEN)
Definition: c.h:757
void RequestAddinShmemSpace(Size size)
Definition: ipci.c:69

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

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

Referenced by _PG_init(), and autoprewarm_start_worker().

◆ autoprewarm_interval

int autoprewarm_interval
static

Definition at line 107 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 100 of file autoprewarm.c.

Referenced by _PG_init(), and autoprewarm_shmem_request().