LCOV - code coverage report
Current view: top level - src/backend/access/transam - xlogfuncs.c (source / functions) Hit Total Coverage
Test: PostgreSQL 13devel Lines: 61 206 29.6 %
Date: 2019-11-15 22:06:47 Functions: 10 22 45.5 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : /*-------------------------------------------------------------------------
       2             :  *
       3             :  * xlogfuncs.c
       4             :  *
       5             :  * PostgreSQL write-ahead log manager user interface functions
       6             :  *
       7             :  * This file contains WAL control and information functions.
       8             :  *
       9             :  *
      10             :  * Portions Copyright (c) 1996-2019, PostgreSQL Global Development Group
      11             :  * Portions Copyright (c) 1994, Regents of the University of California
      12             :  *
      13             :  * src/backend/access/transam/xlogfuncs.c
      14             :  *
      15             :  *-------------------------------------------------------------------------
      16             :  */
      17             : #include "postgres.h"
      18             : 
      19             : #include <unistd.h>
      20             : 
      21             : #include "access/htup_details.h"
      22             : #include "access/xlog.h"
      23             : #include "access/xlog_internal.h"
      24             : #include "access/xlogutils.h"
      25             : #include "catalog/pg_type.h"
      26             : #include "funcapi.h"
      27             : #include "miscadmin.h"
      28             : #include "pgstat.h"
      29             : #include "replication/walreceiver.h"
      30             : #include "storage/fd.h"
      31             : #include "storage/ipc.h"
      32             : #include "storage/smgr.h"
      33             : #include "utils/builtins.h"
      34             : #include "utils/guc.h"
      35             : #include "utils/memutils.h"
      36             : #include "utils/numeric.h"
      37             : #include "utils/pg_lsn.h"
      38             : #include "utils/timestamp.h"
      39             : #include "utils/tuplestore.h"
      40             : 
      41             : /*
      42             :  * Store label file and tablespace map during non-exclusive backups.
      43             :  */
      44             : static StringInfo label_file;
      45             : static StringInfo tblspc_map_file;
      46             : 
      47             : /*
      48             :  * Called when the backend exits with a running non-exclusive base backup,
      49             :  * to clean up state.
      50             :  */
      51             : static void
      52           0 : nonexclusive_base_backup_cleanup(int code, Datum arg)
      53             : {
      54           0 :     do_pg_abort_backup();
      55           0 :     ereport(WARNING,
      56             :             (errmsg("aborting backup due to backend exiting before pg_stop_backup was called")));
      57           0 : }
      58             : 
      59             : /*
      60             :  * pg_start_backup: set up for taking an on-line backup dump
      61             :  *
      62             :  * Essentially what this does is to create a backup label file in $PGDATA,
      63             :  * where it will be archived as part of the backup dump.  The label file
      64             :  * contains the user-supplied label string (typically this would be used
      65             :  * to tell where the backup dump will be stored) and the starting time and
      66             :  * starting WAL location for the dump.
      67             :  *
      68             :  * Permission checking for this function is managed through the normal
      69             :  * GRANT system.
      70             :  */
      71             : Datum
      72           2 : pg_start_backup(PG_FUNCTION_ARGS)
      73             : {
      74           2 :     text       *backupid = PG_GETARG_TEXT_PP(0);
      75           2 :     bool        fast = PG_GETARG_BOOL(1);
      76           2 :     bool        exclusive = PG_GETARG_BOOL(2);
      77             :     char       *backupidstr;
      78             :     XLogRecPtr  startpoint;
      79           2 :     SessionBackupState status = get_backup_status();
      80             : 
      81           2 :     backupidstr = text_to_cstring(backupid);
      82             : 
      83           2 :     if (status == SESSION_BACKUP_NON_EXCLUSIVE)
      84           0 :         ereport(ERROR,
      85             :                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
      86             :                  errmsg("a backup is already in progress in this session")));
      87             : 
      88           2 :     if (exclusive)
      89             :     {
      90           2 :         startpoint = do_pg_start_backup(backupidstr, fast, NULL, NULL,
      91             :                                         NULL, NULL, false, true);
      92             :     }
      93             :     else
      94             :     {
      95             :         MemoryContext oldcontext;
      96             : 
      97             :         /*
      98             :          * Label file and tablespace map file need to be long-lived, since
      99             :          * they are read in pg_stop_backup.
     100             :          */
     101           0 :         oldcontext = MemoryContextSwitchTo(TopMemoryContext);
     102           0 :         label_file = makeStringInfo();
     103           0 :         tblspc_map_file = makeStringInfo();
     104           0 :         MemoryContextSwitchTo(oldcontext);
     105             : 
     106           0 :         startpoint = do_pg_start_backup(backupidstr, fast, NULL, label_file,
     107             :                                         NULL, tblspc_map_file, false, true);
     108             : 
     109           0 :         before_shmem_exit(nonexclusive_base_backup_cleanup, (Datum) 0);
     110             :     }
     111             : 
     112           2 :     PG_RETURN_LSN(startpoint);
     113             : }
     114             : 
     115             : /*
     116             :  * pg_stop_backup: finish taking an on-line backup dump
     117             :  *
     118             :  * We write an end-of-backup WAL record, and remove the backup label file
     119             :  * created by pg_start_backup, creating a backup history file in pg_wal
     120             :  * instead (whence it will immediately be archived). The backup history file
     121             :  * contains the same info found in the label file, plus the backup-end time
     122             :  * and WAL location. Before 9.0, the backup-end time was read from the backup
     123             :  * history file at the beginning of archive recovery, but we now use the WAL
     124             :  * record for that and the file is for informational and debug purposes only.
     125             :  *
     126             :  * Note: different from CancelBackup which just cancels online backup mode.
     127             :  *
     128             :  * Note: this version is only called to stop an exclusive backup. The function
     129             :  *       pg_stop_backup_v2 (overloaded as pg_stop_backup in SQL) is called to
     130             :  *       stop non-exclusive backups.
     131             :  *
     132             :  * Permission checking for this function is managed through the normal
     133             :  * GRANT system.
     134             :  */
     135             : Datum
     136           2 : pg_stop_backup(PG_FUNCTION_ARGS)
     137             : {
     138             :     XLogRecPtr  stoppoint;
     139           2 :     SessionBackupState status = get_backup_status();
     140             : 
     141           2 :     if (status == SESSION_BACKUP_NON_EXCLUSIVE)
     142           0 :         ereport(ERROR,
     143             :                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
     144             :                  errmsg("non-exclusive backup in progress"),
     145             :                  errhint("Did you mean to use pg_stop_backup('f')?")));
     146             : 
     147             :     /*
     148             :      * Exclusive backups were typically started in a different connection, so
     149             :      * don't try to verify that status of backup is set to
     150             :      * SESSION_BACKUP_EXCLUSIVE in this function. Actual verification that an
     151             :      * exclusive backup is in fact running is handled inside
     152             :      * do_pg_stop_backup.
     153             :      */
     154           2 :     stoppoint = do_pg_stop_backup(NULL, true, NULL);
     155             : 
     156           2 :     PG_RETURN_LSN(stoppoint);
     157             : }
     158             : 
     159             : 
     160             : /*
     161             :  * pg_stop_backup_v2: finish taking exclusive or nonexclusive on-line backup.
     162             :  *
     163             :  * Works the same as pg_stop_backup, except for non-exclusive backups it returns
     164             :  * the backup label and tablespace map files as text fields in as part of the
     165             :  * resultset.
     166             :  *
     167             :  * The first parameter (variable 'exclusive') allows the user to tell us if
     168             :  * this is an exclusive or a non-exclusive backup.
     169             :  *
     170             :  * The second parameter (variable 'waitforarchive'), which is optional,
     171             :  * allows the user to choose if they want to wait for the WAL to be archived
     172             :  * or if we should just return as soon as the WAL record is written.
     173             :  *
     174             :  * Permission checking for this function is managed through the normal
     175             :  * GRANT system.
     176             :  */
     177             : Datum
     178           0 : pg_stop_backup_v2(PG_FUNCTION_ARGS)
     179             : {
     180           0 :     ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
     181             :     TupleDesc   tupdesc;
     182             :     Tuplestorestate *tupstore;
     183             :     MemoryContext per_query_ctx;
     184             :     MemoryContext oldcontext;
     185             :     Datum       values[3];
     186             :     bool        nulls[3];
     187             : 
     188           0 :     bool        exclusive = PG_GETARG_BOOL(0);
     189           0 :     bool        waitforarchive = PG_GETARG_BOOL(1);
     190             :     XLogRecPtr  stoppoint;
     191           0 :     SessionBackupState status = get_backup_status();
     192             : 
     193             :     /* check to see if caller supports us returning a tuplestore */
     194           0 :     if (rsinfo == NULL || !IsA(rsinfo, ReturnSetInfo))
     195           0 :         ereport(ERROR,
     196             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
     197             :                  errmsg("set-valued function called in context that cannot accept a set")));
     198           0 :     if (!(rsinfo->allowedModes & SFRM_Materialize))
     199           0 :         ereport(ERROR,
     200             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
     201             :                  errmsg("materialize mode required, but it is not " \
     202             :                         "allowed in this context")));
     203             : 
     204             :     /* Build a tuple descriptor for our result type */
     205           0 :     if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
     206           0 :         elog(ERROR, "return type must be a row type");
     207             : 
     208           0 :     per_query_ctx = rsinfo->econtext->ecxt_per_query_memory;
     209           0 :     oldcontext = MemoryContextSwitchTo(per_query_ctx);
     210             : 
     211           0 :     tupstore = tuplestore_begin_heap(true, false, work_mem);
     212           0 :     rsinfo->returnMode = SFRM_Materialize;
     213           0 :     rsinfo->setResult = tupstore;
     214           0 :     rsinfo->setDesc = tupdesc;
     215             : 
     216           0 :     MemoryContextSwitchTo(oldcontext);
     217             : 
     218           0 :     MemSet(values, 0, sizeof(values));
     219           0 :     MemSet(nulls, 0, sizeof(nulls));
     220             : 
     221           0 :     if (exclusive)
     222             :     {
     223           0 :         if (status == SESSION_BACKUP_NON_EXCLUSIVE)
     224           0 :             ereport(ERROR,
     225             :                     (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
     226             :                      errmsg("non-exclusive backup in progress"),
     227             :                      errhint("Did you mean to use pg_stop_backup('f')?")));
     228             : 
     229             :         /*
     230             :          * Stop the exclusive backup, and since we're in an exclusive backup
     231             :          * return NULL for both backup_label and tablespace_map.
     232             :          */
     233           0 :         stoppoint = do_pg_stop_backup(NULL, waitforarchive, NULL);
     234             : 
     235           0 :         nulls[1] = true;
     236           0 :         nulls[2] = true;
     237             :     }
     238             :     else
     239             :     {
     240           0 :         if (status != SESSION_BACKUP_NON_EXCLUSIVE)
     241           0 :             ereport(ERROR,
     242             :                     (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
     243             :                      errmsg("non-exclusive backup is not in progress"),
     244             :                      errhint("Did you mean to use pg_stop_backup('t')?")));
     245             : 
     246             :         /*
     247             :          * Stop the non-exclusive backup. Return a copy of the backup label
     248             :          * and tablespace map so they can be written to disk by the caller.
     249             :          */
     250           0 :         stoppoint = do_pg_stop_backup(label_file->data, waitforarchive, NULL);
     251           0 :         cancel_before_shmem_exit(nonexclusive_base_backup_cleanup, (Datum) 0);
     252             : 
     253           0 :         values[1] = CStringGetTextDatum(label_file->data);
     254           0 :         values[2] = CStringGetTextDatum(tblspc_map_file->data);
     255             : 
     256             :         /* Free structures allocated in TopMemoryContext */
     257           0 :         pfree(label_file->data);
     258           0 :         pfree(label_file);
     259           0 :         label_file = NULL;
     260           0 :         pfree(tblspc_map_file->data);
     261           0 :         pfree(tblspc_map_file);
     262           0 :         tblspc_map_file = NULL;
     263             :     }
     264             : 
     265             :     /* Stoppoint is included on both exclusive and nonexclusive backups */
     266           0 :     values[0] = LSNGetDatum(stoppoint);
     267             : 
     268           0 :     tuplestore_putvalues(tupstore, tupdesc, values, nulls);
     269             :     tuplestore_donestoring(tupstore);
     270             : 
     271           0 :     return (Datum) 0;
     272             : }
     273             : 
     274             : /*
     275             :  * pg_switch_wal: switch to next xlog file
     276             :  *
     277             :  * Permission checking for this function is managed through the normal
     278             :  * GRANT system.
     279             :  */
     280             : Datum
     281           6 : pg_switch_wal(PG_FUNCTION_ARGS)
     282             : {
     283             :     XLogRecPtr  switchpoint;
     284             : 
     285           6 :     if (RecoveryInProgress())
     286           0 :         ereport(ERROR,
     287             :                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
     288             :                  errmsg("recovery is in progress"),
     289             :                  errhint("WAL control functions cannot be executed during recovery.")));
     290             : 
     291           6 :     switchpoint = RequestXLogSwitch(false);
     292             : 
     293             :     /*
     294             :      * As a convenience, return the WAL location of the switch record
     295             :      */
     296           6 :     PG_RETURN_LSN(switchpoint);
     297             : }
     298             : 
     299             : /*
     300             :  * pg_create_restore_point: a named point for restore
     301             :  *
     302             :  * Permission checking for this function is managed through the normal
     303             :  * GRANT system.
     304             :  */
     305             : Datum
     306           2 : pg_create_restore_point(PG_FUNCTION_ARGS)
     307             : {
     308           2 :     text       *restore_name = PG_GETARG_TEXT_PP(0);
     309             :     char       *restore_name_str;
     310             :     XLogRecPtr  restorepoint;
     311             : 
     312           2 :     if (RecoveryInProgress())
     313           0 :         ereport(ERROR,
     314             :                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
     315             :                  (errmsg("recovery is in progress"),
     316             :                   errhint("WAL control functions cannot be executed during recovery."))));
     317             : 
     318           2 :     if (!XLogIsNeeded())
     319           0 :         ereport(ERROR,
     320             :                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
     321             :                  errmsg("WAL level not sufficient for creating a restore point"),
     322             :                  errhint("wal_level must be set to \"replica\" or \"logical\" at server start.")));
     323             : 
     324           2 :     restore_name_str = text_to_cstring(restore_name);
     325             : 
     326           2 :     if (strlen(restore_name_str) >= MAXFNAMELEN)
     327           0 :         ereport(ERROR,
     328             :                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
     329             :                  errmsg("value too long for restore point (maximum %d characters)", MAXFNAMELEN - 1)));
     330             : 
     331           2 :     restorepoint = XLogRestorePoint(restore_name_str);
     332             : 
     333             :     /*
     334             :      * As a convenience, return the WAL location of the restore point record
     335             :      */
     336           2 :     PG_RETURN_LSN(restorepoint);
     337             : }
     338             : 
     339             : /*
     340             :  * Report the current WAL write location (same format as pg_start_backup etc)
     341             :  *
     342             :  * This is useful for determining how much of WAL is visible to an external
     343             :  * archiving process.  Note that the data before this point is written out
     344             :  * to the kernel, but is not necessarily synced to disk.
     345             :  */
     346             : Datum
     347         140 : pg_current_wal_lsn(PG_FUNCTION_ARGS)
     348             : {
     349             :     XLogRecPtr  current_recptr;
     350             : 
     351         140 :     if (RecoveryInProgress())
     352           0 :         ereport(ERROR,
     353             :                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
     354             :                  errmsg("recovery is in progress"),
     355             :                  errhint("WAL control functions cannot be executed during recovery.")));
     356             : 
     357         140 :     current_recptr = GetXLogWriteRecPtr();
     358             : 
     359         140 :     PG_RETURN_LSN(current_recptr);
     360             : }
     361             : 
     362             : /*
     363             :  * Report the current WAL insert location (same format as pg_start_backup etc)
     364             :  *
     365             :  * This function is mostly for debugging purposes.
     366             :  */
     367             : Datum
     368          36 : pg_current_wal_insert_lsn(PG_FUNCTION_ARGS)
     369             : {
     370             :     XLogRecPtr  current_recptr;
     371             : 
     372          36 :     if (RecoveryInProgress())
     373           0 :         ereport(ERROR,
     374             :                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
     375             :                  errmsg("recovery is in progress"),
     376             :                  errhint("WAL control functions cannot be executed during recovery.")));
     377             : 
     378          36 :     current_recptr = GetXLogInsertRecPtr();
     379             : 
     380          36 :     PG_RETURN_LSN(current_recptr);
     381             : }
     382             : 
     383             : /*
     384             :  * Report the current WAL flush location (same format as pg_start_backup etc)
     385             :  *
     386             :  * This function is mostly for debugging purposes.
     387             :  */
     388             : Datum
     389           0 : pg_current_wal_flush_lsn(PG_FUNCTION_ARGS)
     390             : {
     391             :     XLogRecPtr  current_recptr;
     392             : 
     393           0 :     if (RecoveryInProgress())
     394           0 :         ereport(ERROR,
     395             :                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
     396             :                  errmsg("recovery is in progress"),
     397             :                  errhint("WAL control functions cannot be executed during recovery.")));
     398             : 
     399           0 :     current_recptr = GetFlushRecPtr();
     400             : 
     401           0 :     PG_RETURN_LSN(current_recptr);
     402             : }
     403             : 
     404             : /*
     405             :  * Report the last WAL receive location (same format as pg_start_backup etc)
     406             :  *
     407             :  * This is useful for determining how much of WAL is guaranteed to be received
     408             :  * and synced to disk by walreceiver.
     409             :  */
     410             : Datum
     411           0 : pg_last_wal_receive_lsn(PG_FUNCTION_ARGS)
     412             : {
     413             :     XLogRecPtr  recptr;
     414             : 
     415           0 :     recptr = GetWalRcvWriteRecPtr(NULL, NULL);
     416             : 
     417           0 :     if (recptr == 0)
     418           0 :         PG_RETURN_NULL();
     419             : 
     420           0 :     PG_RETURN_LSN(recptr);
     421             : }
     422             : 
     423             : /*
     424             :  * Report the last WAL replay location (same format as pg_start_backup etc)
     425             :  *
     426             :  * This is useful for determining how much of WAL is visible to read-only
     427             :  * connections during recovery.
     428             :  */
     429             : Datum
     430          62 : pg_last_wal_replay_lsn(PG_FUNCTION_ARGS)
     431             : {
     432             :     XLogRecPtr  recptr;
     433             : 
     434          62 :     recptr = GetXLogReplayRecPtr(NULL);
     435             : 
     436          62 :     if (recptr == 0)
     437           0 :         PG_RETURN_NULL();
     438             : 
     439          62 :     PG_RETURN_LSN(recptr);
     440             : }
     441             : 
     442             : /*
     443             :  * Compute an xlog file name and decimal byte offset given a WAL location,
     444             :  * such as is returned by pg_stop_backup() or pg_switch_wal().
     445             :  *
     446             :  * Note that a location exactly at a segment boundary is taken to be in
     447             :  * the previous segment.  This is usually the right thing, since the
     448             :  * expected usage is to determine which xlog file(s) are ready to archive.
     449             :  */
     450             : Datum
     451           0 : pg_walfile_name_offset(PG_FUNCTION_ARGS)
     452             : {
     453             :     XLogSegNo   xlogsegno;
     454             :     uint32      xrecoff;
     455           0 :     XLogRecPtr  locationpoint = PG_GETARG_LSN(0);
     456             :     char        xlogfilename[MAXFNAMELEN];
     457             :     Datum       values[2];
     458             :     bool        isnull[2];
     459             :     TupleDesc   resultTupleDesc;
     460             :     HeapTuple   resultHeapTuple;
     461             :     Datum       result;
     462             : 
     463           0 :     if (RecoveryInProgress())
     464           0 :         ereport(ERROR,
     465             :                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
     466             :                  errmsg("recovery is in progress"),
     467             :                  errhint("%s cannot be executed during recovery.",
     468             :                          "pg_walfile_name_offset()")));
     469             : 
     470             :     /*
     471             :      * Construct a tuple descriptor for the result row.  This must match this
     472             :      * function's pg_proc entry!
     473             :      */
     474           0 :     resultTupleDesc = CreateTemplateTupleDesc(2);
     475           0 :     TupleDescInitEntry(resultTupleDesc, (AttrNumber) 1, "file_name",
     476             :                        TEXTOID, -1, 0);
     477           0 :     TupleDescInitEntry(resultTupleDesc, (AttrNumber) 2, "file_offset",
     478             :                        INT4OID, -1, 0);
     479             : 
     480           0 :     resultTupleDesc = BlessTupleDesc(resultTupleDesc);
     481             : 
     482             :     /*
     483             :      * xlogfilename
     484             :      */
     485           0 :     XLByteToPrevSeg(locationpoint, xlogsegno, wal_segment_size);
     486           0 :     XLogFileName(xlogfilename, ThisTimeLineID, xlogsegno, wal_segment_size);
     487             : 
     488           0 :     values[0] = CStringGetTextDatum(xlogfilename);
     489           0 :     isnull[0] = false;
     490             : 
     491             :     /*
     492             :      * offset
     493             :      */
     494           0 :     xrecoff = XLogSegmentOffset(locationpoint, wal_segment_size);
     495             : 
     496           0 :     values[1] = UInt32GetDatum(xrecoff);
     497           0 :     isnull[1] = false;
     498             : 
     499             :     /*
     500             :      * Tuple jam: Having first prepared your Datums, then squash together
     501             :      */
     502           0 :     resultHeapTuple = heap_form_tuple(resultTupleDesc, values, isnull);
     503             : 
     504           0 :     result = HeapTupleGetDatum(resultHeapTuple);
     505             : 
     506           0 :     PG_RETURN_DATUM(result);
     507             : }
     508             : 
     509             : /*
     510             :  * Compute an xlog file name given a WAL location,
     511             :  * such as is returned by pg_stop_backup() or pg_switch_wal().
     512             :  */
     513             : Datum
     514           0 : pg_walfile_name(PG_FUNCTION_ARGS)
     515             : {
     516             :     XLogSegNo   xlogsegno;
     517           0 :     XLogRecPtr  locationpoint = PG_GETARG_LSN(0);
     518             :     char        xlogfilename[MAXFNAMELEN];
     519             : 
     520           0 :     if (RecoveryInProgress())
     521           0 :         ereport(ERROR,
     522             :                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
     523             :                  errmsg("recovery is in progress"),
     524             :                  errhint("%s cannot be executed during recovery.",
     525             :                          "pg_walfile_name()")));
     526             : 
     527           0 :     XLByteToPrevSeg(locationpoint, xlogsegno, wal_segment_size);
     528           0 :     XLogFileName(xlogfilename, ThisTimeLineID, xlogsegno, wal_segment_size);
     529             : 
     530           0 :     PG_RETURN_TEXT_P(cstring_to_text(xlogfilename));
     531             : }
     532             : 
     533             : /*
     534             :  * pg_wal_replay_pause - pause recovery now
     535             :  *
     536             :  * Permission checking for this function is managed through the normal
     537             :  * GRANT system.
     538             :  */
     539             : Datum
     540           0 : pg_wal_replay_pause(PG_FUNCTION_ARGS)
     541             : {
     542           0 :     if (!RecoveryInProgress())
     543           0 :         ereport(ERROR,
     544             :                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
     545             :                  errmsg("recovery is not in progress"),
     546             :                  errhint("Recovery control functions can only be executed during recovery.")));
     547             : 
     548           0 :     SetRecoveryPause(true);
     549             : 
     550           0 :     PG_RETURN_VOID();
     551             : }
     552             : 
     553             : /*
     554             :  * pg_wal_replay_resume - resume recovery now
     555             :  *
     556             :  * Permission checking for this function is managed through the normal
     557             :  * GRANT system.
     558             :  */
     559             : Datum
     560           0 : pg_wal_replay_resume(PG_FUNCTION_ARGS)
     561             : {
     562           0 :     if (!RecoveryInProgress())
     563           0 :         ereport(ERROR,
     564             :                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
     565             :                  errmsg("recovery is not in progress"),
     566             :                  errhint("Recovery control functions can only be executed during recovery.")));
     567             : 
     568           0 :     SetRecoveryPause(false);
     569             : 
     570           0 :     PG_RETURN_VOID();
     571             : }
     572             : 
     573             : /*
     574             :  * pg_is_wal_replay_paused
     575             :  */
     576             : Datum
     577           0 : pg_is_wal_replay_paused(PG_FUNCTION_ARGS)
     578             : {
     579           0 :     if (!RecoveryInProgress())
     580           0 :         ereport(ERROR,
     581             :                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
     582             :                  errmsg("recovery is not in progress"),
     583             :                  errhint("Recovery control functions can only be executed during recovery.")));
     584             : 
     585           0 :     PG_RETURN_BOOL(RecoveryIsPaused());
     586             : }
     587             : 
     588             : /*
     589             :  * Returns timestamp of latest processed commit/abort record.
     590             :  *
     591             :  * When the server has been started normally without recovery the function
     592             :  * returns NULL.
     593             :  */
     594             : Datum
     595           0 : pg_last_xact_replay_timestamp(PG_FUNCTION_ARGS)
     596             : {
     597             :     TimestampTz xtime;
     598             : 
     599           0 :     xtime = GetLatestXTime();
     600           0 :     if (xtime == 0)
     601           0 :         PG_RETURN_NULL();
     602             : 
     603           0 :     PG_RETURN_TIMESTAMPTZ(xtime);
     604             : }
     605             : 
     606             : /*
     607             :  * Returns bool with current recovery mode, a global state.
     608             :  */
     609             : Datum
     610         252 : pg_is_in_recovery(PG_FUNCTION_ARGS)
     611             : {
     612         252 :     PG_RETURN_BOOL(RecoveryInProgress());
     613             : }
     614             : 
     615             : /*
     616             :  * Compute the difference in bytes between two WAL locations.
     617             :  */
     618             : Datum
     619           2 : pg_wal_lsn_diff(PG_FUNCTION_ARGS)
     620             : {
     621             :     Datum       result;
     622             : 
     623           2 :     result = DirectFunctionCall2(pg_lsn_mi,
     624             :                                  PG_GETARG_DATUM(0),
     625             :                                  PG_GETARG_DATUM(1));
     626             : 
     627           2 :     PG_RETURN_NUMERIC(result);
     628             : }
     629             : 
     630             : /*
     631             :  * Returns bool with current on-line backup mode, a global state.
     632             :  */
     633             : Datum
     634           0 : pg_is_in_backup(PG_FUNCTION_ARGS)
     635             : {
     636           0 :     PG_RETURN_BOOL(BackupInProgress());
     637             : }
     638             : 
     639             : /*
     640             :  * Returns start time of an online exclusive backup.
     641             :  *
     642             :  * When there's no exclusive backup in progress, the function
     643             :  * returns NULL.
     644             :  */
     645             : Datum
     646           0 : pg_backup_start_time(PG_FUNCTION_ARGS)
     647             : {
     648             :     Datum       xtime;
     649             :     FILE       *lfp;
     650             :     char        fline[MAXPGPATH];
     651             :     char        backup_start_time[30];
     652             : 
     653             :     /*
     654             :      * See if label file is present
     655             :      */
     656           0 :     lfp = AllocateFile(BACKUP_LABEL_FILE, "r");
     657           0 :     if (lfp == NULL)
     658             :     {
     659           0 :         if (errno != ENOENT)
     660           0 :             ereport(ERROR,
     661             :                     (errcode_for_file_access(),
     662             :                      errmsg("could not read file \"%s\": %m",
     663             :                             BACKUP_LABEL_FILE)));
     664           0 :         PG_RETURN_NULL();
     665             :     }
     666             : 
     667             :     /*
     668             :      * Parse the file to find the START TIME line.
     669             :      */
     670           0 :     backup_start_time[0] = '\0';
     671           0 :     while (fgets(fline, sizeof(fline), lfp) != NULL)
     672             :     {
     673           0 :         if (sscanf(fline, "START TIME: %25[^\n]\n", backup_start_time) == 1)
     674           0 :             break;
     675             :     }
     676             : 
     677             :     /* Check for a read error. */
     678           0 :     if (ferror(lfp))
     679           0 :         ereport(ERROR,
     680             :                 (errcode_for_file_access(),
     681             :                  errmsg("could not read file \"%s\": %m", BACKUP_LABEL_FILE)));
     682             : 
     683             :     /* Close the backup label file. */
     684           0 :     if (FreeFile(lfp))
     685           0 :         ereport(ERROR,
     686             :                 (errcode_for_file_access(),
     687             :                  errmsg("could not close file \"%s\": %m", BACKUP_LABEL_FILE)));
     688             : 
     689           0 :     if (strlen(backup_start_time) == 0)
     690           0 :         ereport(ERROR,
     691             :                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
     692             :                  errmsg("invalid data in file \"%s\"", BACKUP_LABEL_FILE)));
     693             : 
     694             :     /*
     695             :      * Convert the time string read from file to TimestampTz form.
     696             :      */
     697           0 :     xtime = DirectFunctionCall3(timestamptz_in,
     698             :                                 CStringGetDatum(backup_start_time),
     699             :                                 ObjectIdGetDatum(InvalidOid),
     700             :                                 Int32GetDatum(-1));
     701             : 
     702           0 :     PG_RETURN_DATUM(xtime);
     703             : }
     704             : 
     705             : /*
     706             :  * Promotes a standby server.
     707             :  *
     708             :  * A result of "true" means that promotion has been completed if "wait" is
     709             :  * "true", or initiated if "wait" is false.
     710             :  */
     711             : Datum
     712           2 : pg_promote(PG_FUNCTION_ARGS)
     713             : {
     714           2 :     bool        wait = PG_GETARG_BOOL(0);
     715           2 :     int         wait_seconds = PG_GETARG_INT32(1);
     716             :     FILE       *promote_file;
     717             :     int         i;
     718             : 
     719           2 :     if (!RecoveryInProgress())
     720           0 :         ereport(ERROR,
     721             :                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
     722             :                  errmsg("recovery is not in progress"),
     723             :                  errhint("Recovery control functions can only be executed during recovery.")));
     724             : 
     725           2 :     if (wait_seconds <= 0)
     726           0 :         ereport(ERROR,
     727             :                 (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
     728             :                  errmsg("\"wait_seconds\" must not be negative or zero")));
     729             : 
     730             :     /* create the promote signal file */
     731           2 :     promote_file = AllocateFile(PROMOTE_SIGNAL_FILE, "w");
     732           2 :     if (!promote_file)
     733           0 :         ereport(ERROR,
     734             :                 (errcode_for_file_access(),
     735             :                  errmsg("could not create file \"%s\": %m",
     736             :                         PROMOTE_SIGNAL_FILE)));
     737             : 
     738           2 :     if (FreeFile(promote_file))
     739           0 :         ereport(ERROR,
     740             :                 (errcode_for_file_access(),
     741             :                  errmsg("could not write file \"%s\": %m",
     742             :                         PROMOTE_SIGNAL_FILE)));
     743             : 
     744             :     /* signal the postmaster */
     745           2 :     if (kill(PostmasterPid, SIGUSR1) != 0)
     746             :     {
     747           0 :         ereport(WARNING,
     748             :                 (errmsg("failed to send signal to postmaster: %m")));
     749           0 :         (void) unlink(PROMOTE_SIGNAL_FILE);
     750           0 :         PG_RETURN_BOOL(false);
     751             :     }
     752             : 
     753             :     /* return immediately if waiting was not requested */
     754           2 :     if (!wait)
     755           0 :         PG_RETURN_BOOL(true);
     756             : 
     757             :     /* wait for the amount of time wanted until promotion */
     758             : #define WAITS_PER_SECOND 10
     759           4 :     for (i = 0; i < WAITS_PER_SECOND * wait_seconds; i++)
     760             :     {
     761             :         int         rc;
     762             : 
     763           4 :         ResetLatch(MyLatch);
     764             : 
     765           4 :         if (!RecoveryInProgress())
     766           2 :             PG_RETURN_BOOL(true);
     767             : 
     768           2 :         CHECK_FOR_INTERRUPTS();
     769             : 
     770           2 :         rc = WaitLatch(MyLatch,
     771             :                        WL_LATCH_SET | WL_TIMEOUT | WL_POSTMASTER_DEATH,
     772             :                        1000L / WAITS_PER_SECOND,
     773             :                        WAIT_EVENT_PROMOTE);
     774             : 
     775             :         /*
     776             :          * Emergency bailout if postmaster has died.  This is to avoid the
     777             :          * necessity for manual cleanup of all postmaster children.
     778             :          */
     779           2 :         if (rc & WL_POSTMASTER_DEATH)
     780           0 :             PG_RETURN_BOOL(false);
     781             :     }
     782             : 
     783           0 :     ereport(WARNING,
     784             :             (errmsg("server did not promote within %d seconds", wait_seconds)));
     785           0 :     PG_RETURN_BOOL(false);
     786             : }

Generated by: LCOV version 1.13