1 /*-------------------------------------------------------------------------
5 * PostgreSQL WAL archiver
7 * All functions relating to archiver are included here
9 * - All functions executed by archiver process
11 * - archiver is forked from postmaster, and the two
12 * processes then communicate using signals. All functions
13 * executed by postmaster are included in this file.
15 * Initial author: Simon Riggs simon@2ndquadrant.com
17 * Portions Copyright (c) 1996-2024, PostgreSQL Global Development Group
18 * Portions Copyright (c) 1994, Regents of the University of California
22 * src/backend/postmaster/pgarch.c
24 *-------------------------------------------------------------------------
32 #include "access/xlog.h"
33 #include "access/xlog_internal.h"
34 #include "archive/archive_module.h"
35 #include "archive/shell_archive.h"
36 #include "lib/binaryheap.h"
37 #include "libpq/pqsignal.h"
39 #include "postmaster/auxprocess.h"
40 #include "postmaster/interrupt.h"
41 #include "postmaster/pgarch.h"
42 #include "storage/condition_variable.h"
43 #include "storage/fd.h"
44 #include "storage/ipc.h"
45 #include "storage/latch.h"
46 #include "storage/pmsignal.h"
47 #include "storage/proc.h"
48 #include "storage/procsignal.h"
49 #include "storage/shmem.h"
50 #include "utils/guc.h"
51 #include "utils/memutils.h"
52 #include "utils/ps_status.h"
53 #include "utils/resowner.h"
54 #include "utils/timeout.h"
61 #define PGARCH_AUTOWAKE_INTERVAL 60 /* How often to force a poll of the
62 * archive status directory; in seconds. */
63 #define PGARCH_RESTART_INTERVAL 10 /* How often to attempt to restart a
64 * failed archiver; in seconds. */
67 * Maximum number of retries allowed when attempting to archive a WAL
70 #define NUM_ARCHIVE_RETRIES 3
73 * Maximum number of retries allowed when attempting to remove an
74 * orphan archive status file.
76 #define NUM_ORPHAN_CLEANUP_RETRIES 3
79 * Maximum number of .ready files to gather per directory scan.
81 #define NUM_FILES_PER_DIRECTORY_SCAN 64
83 /* Shared memory area for archiver process */
84 typedef struct PgArchData
86 int pgprocno
; /* proc number of archiver process */
89 * Forces a directory scan in pgarch_readyXlog().
91 pg_atomic_uint32 force_dir_scan
;
94 char *XLogArchiveLibrary
= "";
95 char *arch_module_check_errdetail_string
;
102 static time_t last_sigterm_time
= 0;
103 static PgArchData
*PgArch
= NULL
;
104 static const ArchiveModuleCallbacks
*ArchiveCallbacks
;
105 static ArchiveModuleState
*archive_module_state
;
106 static MemoryContext archive_context
;
110 * Stuff for tracking multiple files to archive from each scan of
111 * archive_status. Minimizing the number of directory scans when there are
112 * many files to archive can significantly improve archival rate.
114 * arch_heap is a max-heap that is used during the directory scan to track
115 * the highest-priority files to archive. After the directory scan
116 * completes, the file names are stored in ascending order of priority in
117 * arch_files. pgarch_readyXlog() returns files from arch_files until it
118 * is empty, at which point another directory scan must be performed.
120 * We only need this data in the archiver process, so make it a palloc'd
121 * struct rather than a bunch of static arrays.
123 struct arch_files_state
125 binaryheap
*arch_heap
;
126 int arch_files_size
; /* number of live entries in arch_files[] */
127 char *arch_files
[NUM_FILES_PER_DIRECTORY_SCAN
];
128 /* buffers underlying heap, and later arch_files[], entries: */
129 char arch_filenames
[NUM_FILES_PER_DIRECTORY_SCAN
][MAX_XFN_CHARS
+ 1];
132 static struct arch_files_state
*arch_files
= NULL
;
135 * Flags set by interrupt handlers for later service in the main loop.
137 static volatile sig_atomic_t ready_to_stop
= false;
140 * Local function forward declarations
143 static void pgarch_waken_stop(SIGNAL_ARGS
);
144 static void pgarch_MainLoop(void);
145 static void pgarch_ArchiverCopyLoop(void);
146 static bool pgarch_archiveXlog(char *xlog
);
147 static bool pgarch_readyXlog(char *xlog
);
148 static void pgarch_archiveDone(char *xlog
);
149 static void pgarch_die(int code
, Datum arg
);
150 static void HandlePgArchInterrupts(void);
151 static int ready_file_comparator(Datum a
, Datum b
, void *arg
);
152 static void LoadArchiveLibrary(void);
153 static void pgarch_call_module_shutdown_cb(int code
, Datum arg
);
155 /* Report shared memory space needed by PgArchShmemInit */
157 PgArchShmemSize(void)
161 size
= add_size(size
, sizeof(PgArchData
));
166 /* Allocate and initialize archiver-related shared memory */
168 PgArchShmemInit(void)
172 PgArch
= (PgArchData
*)
173 ShmemInitStruct("Archiver Data", PgArchShmemSize(), &found
);
177 /* First time through, so initialize */
178 MemSet(PgArch
, 0, PgArchShmemSize());
179 PgArch
->pgprocno
= INVALID_PROC_NUMBER
;
180 pg_atomic_init_u32(&PgArch
->force_dir_scan
, 0);
187 * Return true and archiver is allowed to restart if enough time has
188 * passed since it was launched last to reach PGARCH_RESTART_INTERVAL.
189 * Otherwise return false.
191 * This is a safety valve to protect against continuous respawn attempts if the
192 * archiver is dying immediately at launch. Note that since we will retry to
193 * launch the archiver from the postmaster main loop, we will get another
197 PgArchCanRestart(void)
199 static time_t last_pgarch_start_time
= 0;
200 time_t curtime
= time(NULL
);
203 * Return false and don't restart archiver if too soon since last archiver
206 if ((unsigned int) (curtime
- last_pgarch_start_time
) <
207 (unsigned int) PGARCH_RESTART_INTERVAL
)
210 last_pgarch_start_time
= curtime
;
215 /* Main entry point for archiver process */
217 PgArchiverMain(char *startup_data
, size_t startup_data_len
)
219 Assert(startup_data_len
== 0);
221 MyBackendType
= B_ARCHIVER
;
222 AuxiliaryProcessMainCommon();
225 * Ignore all signals usually bound to some action in the postmaster,
226 * except for SIGHUP, SIGTERM, SIGUSR1, SIGUSR2, and SIGQUIT.
228 pqsignal(SIGHUP
, SignalHandlerForConfigReload
);
229 pqsignal(SIGINT
, SIG_IGN
);
230 pqsignal(SIGTERM
, SignalHandlerForShutdownRequest
);
231 /* SIGQUIT handler was already set up by InitPostmasterChild */
232 pqsignal(SIGALRM
, SIG_IGN
);
233 pqsignal(SIGPIPE
, SIG_IGN
);
234 pqsignal(SIGUSR1
, procsignal_sigusr1_handler
);
235 pqsignal(SIGUSR2
, pgarch_waken_stop
);
237 /* Reset some signals that are accepted by postmaster but not here */
238 pqsignal(SIGCHLD
, SIG_DFL
);
240 /* Unblock signals (they were blocked when the postmaster forked us) */
241 sigprocmask(SIG_SETMASK
, &UnBlockSig
, NULL
);
243 /* We shouldn't be launched unnecessarily. */
244 Assert(XLogArchivingActive());
246 /* Arrange to clean up at archiver exit */
247 on_shmem_exit(pgarch_die
, 0);
250 * Advertise our proc number so that backends can use our latch to wake us
251 * up while we're sleeping.
253 PgArch
->pgprocno
= MyProcNumber
;
255 /* Create workspace for pgarch_readyXlog() */
256 arch_files
= palloc(sizeof(struct arch_files_state
));
257 arch_files
->arch_files_size
= 0;
259 /* Initialize our max-heap for prioritizing files to archive. */
260 arch_files
->arch_heap
= binaryheap_allocate(NUM_FILES_PER_DIRECTORY_SCAN
,
261 ready_file_comparator
, NULL
);
263 /* Initialize our memory context. */
264 archive_context
= AllocSetContextCreate(TopMemoryContext
,
266 ALLOCSET_DEFAULT_SIZES
);
268 /* Load the archive_library. */
269 LoadArchiveLibrary();
277 * Wake up the archiver
282 int arch_pgprocno
= PgArch
->pgprocno
;
285 * We don't acquire ProcArrayLock here. It's actually fine because
286 * procLatch isn't ever freed, so we just can potentially set the wrong
287 * process' (or no process') latch. Even in that case the archiver will
288 * be relaunched shortly and will start archiving.
290 if (arch_pgprocno
!= INVALID_PROC_NUMBER
)
291 SetLatch(&ProcGlobal
->allProcs
[arch_pgprocno
].procLatch
);
295 /* SIGUSR2 signal handler for archiver process */
297 pgarch_waken_stop(SIGNAL_ARGS
)
299 /* set flag to do a final cycle and shut down afterwards */
300 ready_to_stop
= true;
307 * Main loop for archiver
310 pgarch_MainLoop(void)
315 * There shouldn't be anything for the archiver to do except to wait for a
316 * signal ... however, the archiver exists to protect our data, so it
317 * wakes up occasionally to allow itself to be proactive.
323 /* When we get SIGUSR2, we do one more archive cycle, then exit */
324 time_to_stop
= ready_to_stop
;
326 /* Check for barrier events and config update */
327 HandlePgArchInterrupts();
330 * If we've gotten SIGTERM, we normally just sit and do nothing until
331 * SIGUSR2 arrives. However, that means a random SIGTERM would
332 * disable archiving indefinitely, which doesn't seem like a good
333 * idea. If more than 60 seconds pass since SIGTERM, exit anyway, so
334 * that the postmaster can start a new archiver if needed.
336 if (ShutdownRequestPending
)
338 time_t curtime
= time(NULL
);
340 if (last_sigterm_time
== 0)
341 last_sigterm_time
= curtime
;
342 else if ((unsigned int) (curtime
- last_sigterm_time
) >=
347 /* Do what we're here for */
348 pgarch_ArchiverCopyLoop();
351 * Sleep until a signal is received, or until a poll is forced by
352 * PGARCH_AUTOWAKE_INTERVAL, or until postmaster dies.
354 if (!time_to_stop
) /* Don't wait during last iteration */
358 rc
= WaitLatch(MyLatch
,
359 WL_LATCH_SET
| WL_TIMEOUT
| WL_POSTMASTER_DEATH
,
360 PGARCH_AUTOWAKE_INTERVAL
* 1000L,
361 WAIT_EVENT_ARCHIVER_MAIN
);
362 if (rc
& WL_POSTMASTER_DEATH
)
367 * The archiver quits either when the postmaster dies (not expected)
368 * or after completing one more archiving cycle after receiving
371 } while (!time_to_stop
);
375 * pgarch_ArchiverCopyLoop
377 * Archives all outstanding xlogs then returns
380 pgarch_ArchiverCopyLoop(void)
382 char xlog
[MAX_XFN_CHARS
+ 1];
384 /* force directory scan in the first call to pgarch_readyXlog() */
385 arch_files
->arch_files_size
= 0;
388 * loop through all xlogs with archive_status of .ready and archive
389 * them...mostly we expect this to be a single file, though it is possible
390 * some backend will add files onto the list of those that need archiving
391 * while we are still copying earlier archives
393 while (pgarch_readyXlog(xlog
))
396 int failures_orphan
= 0;
400 struct stat stat_buf
;
401 char pathname
[MAXPGPATH
];
404 * Do not initiate any more archive commands after receiving
405 * SIGTERM, nor after the postmaster has died unexpectedly. The
406 * first condition is to try to keep from having init SIGKILL the
407 * command, and the second is to avoid conflicts with another
408 * archiver spawned by a newer postmaster.
410 if (ShutdownRequestPending
|| !PostmasterIsAlive())
414 * Check for barrier events and config update. This is so that
415 * we'll adopt a new setting for archive_command as soon as
416 * possible, even if there is a backlog of files to be archived.
418 HandlePgArchInterrupts();
420 /* Reset variables that might be set by the callback */
421 arch_module_check_errdetail_string
= NULL
;
423 /* can't do anything if not configured ... */
424 if (ArchiveCallbacks
->check_configured_cb
!= NULL
&&
425 !ArchiveCallbacks
->check_configured_cb(archive_module_state
))
428 (errmsg("\"archive_mode\" enabled, yet archiving is not configured"),
429 arch_module_check_errdetail_string
?
430 errdetail_internal("%s", arch_module_check_errdetail_string
) : 0));
435 * Since archive status files are not removed in a durable manner,
436 * a system crash could leave behind .ready files for WAL segments
437 * that have already been recycled or removed. In this case,
438 * simply remove the orphan status file and move on. unlink() is
439 * used here as even on subsequent crashes the same orphan files
440 * would get removed, so there is no need to worry about
443 snprintf(pathname
, MAXPGPATH
, XLOGDIR
"/%s", xlog
);
444 if (stat(pathname
, &stat_buf
) != 0 && errno
== ENOENT
)
446 char xlogready
[MAXPGPATH
];
448 StatusFilePath(xlogready
, xlog
, ".ready");
449 if (unlink(xlogready
) == 0)
452 (errmsg("removed orphan archive status file \"%s\"",
455 /* leave loop and move to the next status file */
459 if (++failures_orphan
>= NUM_ORPHAN_CLEANUP_RETRIES
)
462 (errmsg("removal of orphan archive status file \"%s\" failed too many times, will try again later",
465 /* give up cleanup of orphan status files */
469 /* wait a bit before retrying */
474 if (pgarch_archiveXlog(xlog
))
477 pgarch_archiveDone(xlog
);
480 * Tell the cumulative stats system about the WAL file that we
481 * successfully archived
483 pgstat_report_archiver(xlog
, false);
485 break; /* out of inner retry loop */
490 * Tell the cumulative stats system about the WAL file that we
493 pgstat_report_archiver(xlog
, true);
495 if (++failures
>= NUM_ARCHIVE_RETRIES
)
498 (errmsg("archiving write-ahead log file \"%s\" failed too many times, will try again later",
500 return; /* give up archiving for now */
502 pg_usleep(1000000L); /* wait a bit before retrying */
511 * Invokes archive_file_cb to copy one archive file to wherever it should go
513 * Returns true if successful
516 pgarch_archiveXlog(char *xlog
)
518 sigjmp_buf local_sigjmp_buf
;
519 MemoryContext oldcontext
;
520 char pathname
[MAXPGPATH
];
521 char activitymsg
[MAXFNAMELEN
+ 16];
524 snprintf(pathname
, MAXPGPATH
, XLOGDIR
"/%s", xlog
);
526 /* Report archive activity in PS display */
527 snprintf(activitymsg
, sizeof(activitymsg
), "archiving %s", xlog
);
528 set_ps_display(activitymsg
);
530 oldcontext
= MemoryContextSwitchTo(archive_context
);
533 * Since the archiver operates at the bottom of the exception stack,
534 * ERRORs turn into FATALs and cause the archiver process to restart.
535 * However, using ereport(ERROR, ...) when there are problems is easy to
536 * code and maintain. Therefore, we create our own exception handler to
537 * catch ERRORs and return false instead of restarting the archiver
538 * whenever there is a failure.
540 * We assume ERRORs from the archiving callback are the most common
541 * exceptions experienced by the archiver, so we opt to handle exceptions
542 * here instead of PgArchiverMain() to avoid reinitializing the archiver
543 * too frequently. We could instead add a sigsetjmp() block to
544 * PgArchiverMain() and use PG_TRY/PG_CATCH here, but the extra code to
545 * avoid the odd archiver restart doesn't seem worth it.
547 if (sigsetjmp(local_sigjmp_buf
, 1) != 0)
549 /* Since not using PG_TRY, must reset error stack by hand */
550 error_context_stack
= NULL
;
552 /* Prevent interrupts while cleaning up */
555 /* Report the error to the server log. */
559 * Try to clean up anything the archive module left behind. We try to
560 * cover anything that an archive module could conceivably have left
561 * behind, but it is of course possible that modules could be doing
562 * unexpected things that require additional cleanup. Module authors
563 * should be sure to do any extra required cleanup in a PG_CATCH block
564 * within the archiving callback, and they are encouraged to notify
565 * the pgsql-hackers mailing list so that we can add it here.
567 disable_all_timeouts(false);
569 ConditionVariableCancelSleep();
570 pgstat_report_wait_end();
571 ReleaseAuxProcessResources(false);
572 AtEOXact_Files(false);
573 AtEOXact_HashTables(false);
576 * Return to the original memory context and clear ErrorContext for
579 MemoryContextSwitchTo(oldcontext
);
582 /* Flush any leaked data */
583 MemoryContextReset(archive_context
);
585 /* Remove our exception handler */
586 PG_exception_stack
= NULL
;
588 /* Now we can allow interrupts again */
591 /* Report failure so that the archiver retries this file */
596 /* Enable our exception handler */
597 PG_exception_stack
= &local_sigjmp_buf
;
599 /* Archive the file! */
600 ret
= ArchiveCallbacks
->archive_file_cb(archive_module_state
,
603 /* Remove our exception handler */
604 PG_exception_stack
= NULL
;
606 /* Reset our memory context and switch back to the original one */
607 MemoryContextSwitchTo(oldcontext
);
608 MemoryContextReset(archive_context
);
612 snprintf(activitymsg
, sizeof(activitymsg
), "last was %s", xlog
);
614 snprintf(activitymsg
, sizeof(activitymsg
), "failed on %s", xlog
);
615 set_ps_display(activitymsg
);
623 * Return name of the oldest xlog file that has not yet been archived.
624 * No notification is set that file archiving is now in progress, so
625 * this would need to be extended if multiple concurrent archival
626 * tasks were created. If a failure occurs, we will completely
627 * re-copy the file at the next available opportunity.
629 * It is important that we return the oldest, so that we archive xlogs
630 * in order that they were written, for two reasons:
631 * 1) to maintain the sequential chain of xlogs required for recovery
632 * 2) because the oldest ones will sooner become candidates for
633 * recycling at time of checkpoint
635 * NOTE: the "oldest" comparison will consider any .history file to be older
636 * than any other file except another .history file. Segments on a timeline
637 * with a smaller ID will be older than all segments on a timeline with a
638 * larger ID; the net result being that past timelines are given higher
639 * priority for archiving. This seems okay, or at least not obviously worth
643 pgarch_readyXlog(char *xlog
)
645 char XLogArchiveStatusDir
[MAXPGPATH
];
650 * If a directory scan was requested, clear the stored file names and
653 if (pg_atomic_exchange_u32(&PgArch
->force_dir_scan
, 0) == 1)
654 arch_files
->arch_files_size
= 0;
657 * If we still have stored file names from the previous directory scan,
658 * try to return one of those. We check to make sure the status file is
659 * still present, as the archive_command for a previous file may have
660 * already marked it done.
662 while (arch_files
->arch_files_size
> 0)
665 char status_file
[MAXPGPATH
];
668 arch_files
->arch_files_size
--;
669 arch_file
= arch_files
->arch_files
[arch_files
->arch_files_size
];
670 StatusFilePath(status_file
, arch_file
, ".ready");
672 if (stat(status_file
, &st
) == 0)
674 strcpy(xlog
, arch_file
);
677 else if (errno
!= ENOENT
)
679 (errcode_for_file_access(),
680 errmsg("could not stat file \"%s\": %m", status_file
)));
683 /* arch_heap is probably empty, but let's make sure */
684 binaryheap_reset(arch_files
->arch_heap
);
687 * Open the archive status directory and read through the list of files
688 * with the .ready suffix, looking for the earliest files.
690 snprintf(XLogArchiveStatusDir
, MAXPGPATH
, XLOGDIR
"/archive_status");
691 rldir
= AllocateDir(XLogArchiveStatusDir
);
693 while ((rlde
= ReadDir(rldir
, XLogArchiveStatusDir
)) != NULL
)
695 int basenamelen
= (int) strlen(rlde
->d_name
) - 6;
696 char basename
[MAX_XFN_CHARS
+ 1];
699 /* Ignore entries with unexpected number of characters */
700 if (basenamelen
< MIN_XFN_CHARS
||
701 basenamelen
> MAX_XFN_CHARS
)
704 /* Ignore entries with unexpected characters */
705 if (strspn(rlde
->d_name
, VALID_XFN_CHARS
) < basenamelen
)
708 /* Ignore anything not suffixed with .ready */
709 if (strcmp(rlde
->d_name
+ basenamelen
, ".ready") != 0)
712 /* Truncate off the .ready */
713 memcpy(basename
, rlde
->d_name
, basenamelen
);
714 basename
[basenamelen
] = '\0';
717 * Store the file in our max-heap if it has a high enough priority.
719 if (arch_files
->arch_heap
->bh_size
< NUM_FILES_PER_DIRECTORY_SCAN
)
721 /* If the heap isn't full yet, quickly add it. */
722 arch_file
= arch_files
->arch_filenames
[arch_files
->arch_heap
->bh_size
];
723 strcpy(arch_file
, basename
);
724 binaryheap_add_unordered(arch_files
->arch_heap
, CStringGetDatum(arch_file
));
726 /* If we just filled the heap, make it a valid one. */
727 if (arch_files
->arch_heap
->bh_size
== NUM_FILES_PER_DIRECTORY_SCAN
)
728 binaryheap_build(arch_files
->arch_heap
);
730 else if (ready_file_comparator(binaryheap_first(arch_files
->arch_heap
),
731 CStringGetDatum(basename
), NULL
) > 0)
734 * Remove the lowest priority file and add the current one to the
737 arch_file
= DatumGetCString(binaryheap_remove_first(arch_files
->arch_heap
));
738 strcpy(arch_file
, basename
);
739 binaryheap_add(arch_files
->arch_heap
, CStringGetDatum(arch_file
));
744 /* If no files were found, simply return. */
745 if (arch_files
->arch_heap
->bh_size
== 0)
749 * If we didn't fill the heap, we didn't make it a valid one. Do that
752 if (arch_files
->arch_heap
->bh_size
< NUM_FILES_PER_DIRECTORY_SCAN
)
753 binaryheap_build(arch_files
->arch_heap
);
756 * Fill arch_files array with the files to archive in ascending order of
759 arch_files
->arch_files_size
= arch_files
->arch_heap
->bh_size
;
760 for (int i
= 0; i
< arch_files
->arch_files_size
; i
++)
761 arch_files
->arch_files
[i
] = DatumGetCString(binaryheap_remove_first(arch_files
->arch_heap
));
763 /* Return the highest priority file. */
764 arch_files
->arch_files_size
--;
765 strcpy(xlog
, arch_files
->arch_files
[arch_files
->arch_files_size
]);
771 * ready_file_comparator
773 * Compares the archival priority of the given files to archive. If "a"
774 * has a higher priority than "b", a negative value will be returned. If
775 * "b" has a higher priority than "a", a positive value will be returned.
776 * If "a" and "b" have equivalent values, 0 will be returned.
779 ready_file_comparator(Datum a
, Datum b
, void *arg
)
781 char *a_str
= DatumGetCString(a
);
782 char *b_str
= DatumGetCString(b
);
783 bool a_history
= IsTLHistoryFileName(a_str
);
784 bool b_history
= IsTLHistoryFileName(b_str
);
786 /* Timeline history files always have the highest priority. */
787 if (a_history
!= b_history
)
788 return a_history
? -1 : 1;
790 /* Priority is given to older files. */
791 return strcmp(a_str
, b_str
);
797 * When called, the next call to pgarch_readyXlog() will perform a
798 * directory scan. This is useful for ensuring that important files such
799 * as timeline history files are archived as quickly as possible.
802 PgArchForceDirScan(void)
804 pg_atomic_write_membarrier_u32(&PgArch
->force_dir_scan
, 1);
810 * Emit notification that an xlog file has been successfully archived.
811 * We do this by renaming the status file from NNN.ready to NNN.done.
812 * Eventually, a checkpoint process will notice this and delete both the
813 * NNN.done file and the xlog file itself.
816 pgarch_archiveDone(char *xlog
)
818 char rlogready
[MAXPGPATH
];
819 char rlogdone
[MAXPGPATH
];
821 StatusFilePath(rlogready
, xlog
, ".ready");
822 StatusFilePath(rlogdone
, xlog
, ".done");
825 * To avoid extra overhead, we don't durably rename the .ready file to
826 * .done. Archive commands and libraries must gracefully handle attempts
827 * to re-archive files (e.g., if the server crashes just before this
828 * function is called), so it should be okay if the .ready file reappears
831 if (rename(rlogready
, rlogdone
) < 0)
833 (errcode_for_file_access(),
834 errmsg("could not rename file \"%s\" to \"%s\": %m",
835 rlogready
, rlogdone
)));
842 * Exit-time cleanup handler
845 pgarch_die(int code
, Datum arg
)
847 PgArch
->pgprocno
= INVALID_PROC_NUMBER
;
851 * Interrupt handler for WAL archiver process.
853 * This is called in the loops pgarch_MainLoop and pgarch_ArchiverCopyLoop.
854 * It checks for barrier events, config update and request for logging of
855 * memory contexts, but not shutdown request because how to handle
856 * shutdown request is different between those loops.
859 HandlePgArchInterrupts(void)
861 if (ProcSignalBarrierPending
)
862 ProcessProcSignalBarrier();
864 /* Perform logging of memory contexts of this process */
865 if (LogMemoryContextPending
)
866 ProcessLogMemoryContextInterrupt();
868 if (ConfigReloadPending
)
870 char *archiveLib
= pstrdup(XLogArchiveLibrary
);
871 bool archiveLibChanged
;
873 ConfigReloadPending
= false;
874 ProcessConfigFile(PGC_SIGHUP
);
876 if (XLogArchiveLibrary
[0] != '\0' && XLogArchiveCommand
[0] != '\0')
878 (errcode(ERRCODE_INVALID_PARAMETER_VALUE
),
879 errmsg("both \"archive_command\" and \"archive_library\" set"),
880 errdetail("Only one of \"archive_command\", \"archive_library\" may be set.")));
882 archiveLibChanged
= strcmp(XLogArchiveLibrary
, archiveLib
) != 0;
885 if (archiveLibChanged
)
888 * Ideally, we would simply unload the previous archive module and
889 * load the new one, but there is presently no mechanism for
890 * unloading a library (see the comment above
891 * internal_load_library()). To deal with this, we simply restart
892 * the archiver. The new archive module will be loaded when the
893 * new archiver process starts up. Note that this triggers the
894 * module's shutdown callback, if defined.
897 (errmsg("restarting archiver process because value of "
898 "\"archive_library\" was changed")));
908 * Loads the archiving callbacks into our local ArchiveCallbacks.
911 LoadArchiveLibrary(void)
913 ArchiveModuleInit archive_init
;
915 if (XLogArchiveLibrary
[0] != '\0' && XLogArchiveCommand
[0] != '\0')
917 (errcode(ERRCODE_INVALID_PARAMETER_VALUE
),
918 errmsg("both \"archive_command\" and \"archive_library\" set"),
919 errdetail("Only one of \"archive_command\", \"archive_library\" may be set.")));
922 * If shell archiving is enabled, use our special initialization function.
923 * Otherwise, load the library and call its _PG_archive_module_init().
925 if (XLogArchiveLibrary
[0] == '\0')
926 archive_init
= shell_archive_init
;
928 archive_init
= (ArchiveModuleInit
)
929 load_external_function(XLogArchiveLibrary
,
930 "_PG_archive_module_init", false, NULL
);
932 if (archive_init
== NULL
)
934 (errmsg("archive modules have to define the symbol %s", "_PG_archive_module_init")));
936 ArchiveCallbacks
= (*archive_init
) ();
938 if (ArchiveCallbacks
->archive_file_cb
== NULL
)
940 (errmsg("archive modules must register an archive callback")));
942 archive_module_state
= (ArchiveModuleState
*) palloc0(sizeof(ArchiveModuleState
));
943 if (ArchiveCallbacks
->startup_cb
!= NULL
)
944 ArchiveCallbacks
->startup_cb(archive_module_state
);
946 before_shmem_exit(pgarch_call_module_shutdown_cb
, 0);
950 * Call the shutdown callback of the loaded archive module, if defined.
953 pgarch_call_module_shutdown_cb(int code
, Datum arg
)
955 if (ArchiveCallbacks
->shutdown_cb
!= NULL
)
956 ArchiveCallbacks
->shutdown_cb(archive_module_state
);