PostgreSQL Source Code  git master
pg_basebackup.c File Reference
#include "postgres_fe.h"
#include <unistd.h>
#include <dirent.h>
#include <limits.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <signal.h>
#include <time.h>
#include "access/xlog_internal.h"
#include "bbstreamer.h"
#include "common/compression.h"
#include "common/file_perm.h"
#include "common/file_utils.h"
#include "common/logging.h"
#include "fe_utils/option_utils.h"
#include "fe_utils/recovery_gen.h"
#include "getopt_long.h"
#include "receivelog.h"
#include "replication/basebackup.h"
#include "streamutil.h"
Include dependency graph for pg_basebackup.c:

Go to the source code of this file.

Data Structures

struct  TablespaceListCell
 
struct  TablespaceList
 
struct  ArchiveStreamState
 
struct  WriteTarState
 
struct  WriteManifestState
 
struct  logstreamer_param
 

Macros

#define ERRCODE_DATA_CORRUPTED   "XX001"
 
#define MINIMUM_VERSION_FOR_PG_WAL   100000
 
#define MINIMUM_VERSION_FOR_TEMP_SLOTS   100000
 
#define MINIMUM_VERSION_FOR_MANIFESTS   130000
 
#define MINIMUM_VERSION_FOR_TERMINATED_TARFILE   150000
 
#define VERBOSE_FILENAME_LENGTH   35
 

Typedefs

typedef struct TablespaceListCell TablespaceListCell
 
typedef struct TablespaceList TablespaceList
 
typedef struct ArchiveStreamState ArchiveStreamState
 
typedef struct WriteTarState WriteTarState
 
typedef struct WriteManifestState WriteManifestState
 
typedef void(* WriteDataCallback) (size_t nbytes, char *buf, void *callback_data)
 

Enumerations

enum  IncludeWal { NO_WAL , FETCH_WAL , STREAM_WAL }
 
enum  CompressionLocation { COMPRESS_LOCATION_UNSPECIFIED , COMPRESS_LOCATION_CLIENT , COMPRESS_LOCATION_SERVER }
 

Functions

static void usage (void)
 
static void verify_dir_is_empty_or_create (char *dirname, bool *created, bool *found)
 
static void progress_update_filename (const char *filename)
 
static void progress_report (int tablespacenum, bool force, bool finished)
 
static bbstreamerCreateBackupStreamer (char *archive_name, char *spclocation, bbstreamer **manifest_inject_streamer_p, bool is_recovery_guc_supported, bool expect_unterminated_tarfile, pg_compress_specification *compress)
 
static void ReceiveArchiveStreamChunk (size_t r, char *copybuf, void *callback_data)
 
static char GetCopyDataByte (size_t r, char *copybuf, size_t *cursor)
 
static char * GetCopyDataString (size_t r, char *copybuf, size_t *cursor)
 
static uint64 GetCopyDataUInt64 (size_t r, char *copybuf, size_t *cursor)
 
static void GetCopyDataEnd (size_t r, char *copybuf, size_t cursor)
 
static void ReportCopyDataParseError (size_t r, char *copybuf)
 
static void ReceiveTarFile (PGconn *conn, char *archive_name, char *spclocation, bool tablespacenum, pg_compress_specification *compress)
 
static void ReceiveTarCopyChunk (size_t r, char *copybuf, void *callback_data)
 
static void ReceiveBackupManifest (PGconn *conn)
 
static void ReceiveBackupManifestChunk (size_t r, char *copybuf, void *callback_data)
 
static void ReceiveBackupManifestInMemory (PGconn *conn, PQExpBuffer buf)
 
static void ReceiveBackupManifestInMemoryChunk (size_t r, char *copybuf, void *callback_data)
 
static void BaseBackup (char *compression_algorithm, char *compression_detail, CompressionLocation compressloc, pg_compress_specification *client_compress)
 
static bool reached_end_position (XLogRecPtr segendpos, uint32 timeline, bool segment_finished)
 
static const char * get_tablespace_mapping (const char *dir)
 
static void tablespace_list_append (const char *arg)
 
static void cleanup_directories_atexit (void)
 
static void disconnect_atexit (void)
 
static void sigchld_handler (SIGNAL_ARGS)
 
static void kill_bgchild_atexit (void)
 
static int LogStreamerMain (logstreamer_param *param)
 
static void StartLogStreamer (char *startpos, uint32 timeline, char *sysidentifier, pg_compress_algorithm wal_compress_algorithm, int wal_compress_level)
 
static int32 parse_max_rate (char *src)
 
static void parse_compress_options (char *option, char **algorithm, char **detail, CompressionLocation *locationres)
 
static void ReceiveCopyData (PGconn *conn, WriteDataCallback callback, void *callback_data)
 
static void ReceiveArchiveStream (PGconn *conn, pg_compress_specification *compress)
 
int main (int argc, char **argv)
 

Variables

static char * basedir = NULL
 
static TablespaceList tablespace_dirs = {NULL, NULL}
 
static char * xlog_dir = NULL
 
static char format = '\0'
 
static char * label = "pg_basebackup base backup"
 
static bool noclean = false
 
static bool checksum_failure = false
 
static bool showprogress = false
 
static bool estimatesize = true
 
static int verbose = 0
 
static IncludeWal includewal = STREAM_WAL
 
static bool fastcheckpoint = false
 
static bool writerecoveryconf = false
 
static bool do_sync = true
 
static int standby_message_timeout = 10 * 1000
 
static pg_time_t last_progress_report = 0
 
static int32 maxrate = 0
 
static char * replication_slot = NULL
 
static bool temp_replication_slot = true
 
static char * backup_target = NULL
 
static bool create_slot = false
 
static bool no_slot = false
 
static bool verify_checksums = true
 
static bool manifest = true
 
static bool manifest_force_encode = false
 
static char * manifest_checksums = NULL
 
static bool success = false
 
static bool made_new_pgdata = false
 
static bool found_existing_pgdata = false
 
static bool made_new_xlogdir = false
 
static bool found_existing_xlogdir = false
 
static bool made_tablespace_dirs = false
 
static bool found_tablespace_dirs = false
 
static uint64 totalsize_kb
 
static uint64 totaldone
 
static int tablespacecount
 
static char * progress_filename = NULL
 
static int bgpipe [2] = {-1, -1}
 
static pid_t bgchild = -1
 
static bool in_log_streamer = false
 
static volatile sig_atomic_t bgchild_exited = false
 
static XLogRecPtr xlogendptr
 
static int has_xlogendptr = 0
 
static PQExpBuffer recoveryconfcontents = NULL
 

Macro Definition Documentation

◆ ERRCODE_DATA_CORRUPTED

#define ERRCODE_DATA_CORRUPTED   "XX001"

Definition at line 43 of file pg_basebackup.c.

◆ MINIMUM_VERSION_FOR_MANIFESTS

#define MINIMUM_VERSION_FOR_MANIFESTS   130000

Definition at line 98 of file pg_basebackup.c.

◆ MINIMUM_VERSION_FOR_PG_WAL

#define MINIMUM_VERSION_FOR_PG_WAL   100000

Definition at line 88 of file pg_basebackup.c.

◆ MINIMUM_VERSION_FOR_TEMP_SLOTS

#define MINIMUM_VERSION_FOR_TEMP_SLOTS   100000

Definition at line 93 of file pg_basebackup.c.

◆ MINIMUM_VERSION_FOR_TERMINATED_TARFILE

#define MINIMUM_VERSION_FOR_TERMINATED_TARFILE   150000

Definition at line 104 of file pg_basebackup.c.

◆ VERBOSE_FILENAME_LENGTH

#define VERBOSE_FILENAME_LENGTH   35

Typedef Documentation

◆ ArchiveStreamState

◆ TablespaceList

◆ TablespaceListCell

◆ WriteDataCallback

typedef void(* WriteDataCallback) (size_t nbytes, char *buf, void *callback_data)

Definition at line 81 of file pg_basebackup.c.

◆ WriteManifestState

◆ WriteTarState

typedef struct WriteTarState WriteTarState

Enumeration Type Documentation

◆ CompressionLocation

Enumerator
COMPRESS_LOCATION_UNSPECIFIED 
COMPRESS_LOCATION_CLIENT 
COMPRESS_LOCATION_SERVER 

Definition at line 119 of file pg_basebackup.c.

120 {
CompressionLocation
@ COMPRESS_LOCATION_UNSPECIFIED
@ COMPRESS_LOCATION_CLIENT
@ COMPRESS_LOCATION_SERVER

◆ IncludeWal

enum IncludeWal
Enumerator
NO_WAL 
FETCH_WAL 
STREAM_WAL 

Definition at line 109 of file pg_basebackup.c.

110 {
111  NO_WAL,
112  FETCH_WAL,
113  STREAM_WAL
114 } IncludeWal;
IncludeWal
@ STREAM_WAL
@ FETCH_WAL
@ NO_WAL

Function Documentation

◆ BaseBackup()

static void BaseBackup ( char *  compression_algorithm,
char *  compression_detail,
CompressionLocation  compressloc,
pg_compress_specification client_compress 
)
static

Definition at line 1760 of file pg_basebackup.c.

1762 {
1763  PGresult *res;
1764  char *sysidentifier;
1765  TimeLineID latesttli;
1766  TimeLineID starttli;
1767  char *basebkp;
1768  int i;
1769  char xlogstart[64];
1770  char xlogend[64];
1771  int minServerMajor,
1772  maxServerMajor;
1773  int serverVersion,
1774  serverMajor;
1775  int writing_to_stdout;
1776  bool use_new_option_syntax = false;
1778 
1779  Assert(conn != NULL);
1780  initPQExpBuffer(&buf);
1781 
1782  /*
1783  * Check server version. BASE_BACKUP command was introduced in 9.1, so we
1784  * can't work with servers older than 9.1.
1785  */
1786  minServerMajor = 901;
1787  maxServerMajor = PG_VERSION_NUM / 100;
1788  serverVersion = PQserverVersion(conn);
1789  serverMajor = serverVersion / 100;
1790  if (serverMajor < minServerMajor || serverMajor > maxServerMajor)
1791  {
1792  const char *serverver = PQparameterStatus(conn, "server_version");
1793 
1794  pg_fatal("incompatible server version %s",
1795  serverver ? serverver : "'unknown'");
1796  }
1797  if (serverMajor >= 1500)
1798  use_new_option_syntax = true;
1799 
1800  /*
1801  * If WAL streaming was requested, also check that the server is new
1802  * enough for that.
1803  */
1805  {
1806  /*
1807  * Error message already written in CheckServerVersionForStreaming(),
1808  * but add a hint about using -X none.
1809  */
1810  pg_log_info("HINT: use -X none or -X fetch to disable log streaming");
1811  exit(1);
1812  }
1813 
1814  /*
1815  * Build contents of configuration file if requested
1816  */
1817  if (writerecoveryconf)
1819 
1820  /*
1821  * Run IDENTIFY_SYSTEM so we can get the timeline
1822  */
1823  if (!RunIdentifySystem(conn, &sysidentifier, &latesttli, NULL, NULL))
1824  exit(1);
1825 
1826  /*
1827  * Start the actual backup
1828  */
1829  AppendStringCommandOption(&buf, use_new_option_syntax, "LABEL", label);
1830  if (estimatesize)
1831  AppendPlainCommandOption(&buf, use_new_option_syntax, "PROGRESS");
1832  if (includewal == FETCH_WAL)
1833  AppendPlainCommandOption(&buf, use_new_option_syntax, "WAL");
1834  if (fastcheckpoint)
1835  {
1836  if (use_new_option_syntax)
1837  AppendStringCommandOption(&buf, use_new_option_syntax,
1838  "CHECKPOINT", "fast");
1839  else
1840  AppendPlainCommandOption(&buf, use_new_option_syntax, "FAST");
1841  }
1842  if (includewal != NO_WAL)
1843  {
1844  if (use_new_option_syntax)
1845  AppendIntegerCommandOption(&buf, use_new_option_syntax, "WAIT", 0);
1846  else
1847  AppendPlainCommandOption(&buf, use_new_option_syntax, "NOWAIT");
1848  }
1849  if (maxrate > 0)
1850  AppendIntegerCommandOption(&buf, use_new_option_syntax, "MAX_RATE",
1851  maxrate);
1852  if (format == 't')
1853  AppendPlainCommandOption(&buf, use_new_option_syntax, "TABLESPACE_MAP");
1854  if (!verify_checksums)
1855  {
1856  if (use_new_option_syntax)
1857  AppendIntegerCommandOption(&buf, use_new_option_syntax,
1858  "VERIFY_CHECKSUMS", 0);
1859  else
1860  AppendPlainCommandOption(&buf, use_new_option_syntax,
1861  "NOVERIFY_CHECKSUMS");
1862  }
1863 
1864  if (manifest)
1865  {
1866  AppendStringCommandOption(&buf, use_new_option_syntax, "MANIFEST",
1867  manifest_force_encode ? "force-encode" : "yes");
1868  if (manifest_checksums != NULL)
1869  AppendStringCommandOption(&buf, use_new_option_syntax,
1870  "MANIFEST_CHECKSUMS", manifest_checksums);
1871  }
1872 
1873  if (backup_target != NULL)
1874  {
1875  char *colon;
1876 
1877  if (serverMajor < 1500)
1878  pg_fatal("backup targets are not supported by this server version");
1879 
1880  if (writerecoveryconf)
1881  pg_fatal("recovery configuration cannot be written when a backup target is used");
1882 
1883  AppendPlainCommandOption(&buf, use_new_option_syntax, "TABLESPACE_MAP");
1884 
1885  if ((colon = strchr(backup_target, ':')) == NULL)
1886  {
1887  AppendStringCommandOption(&buf, use_new_option_syntax,
1888  "TARGET", backup_target);
1889  }
1890  else
1891  {
1892  char *target;
1893 
1894  target = pnstrdup(backup_target, colon - backup_target);
1895  AppendStringCommandOption(&buf, use_new_option_syntax,
1896  "TARGET", target);
1897  AppendStringCommandOption(&buf, use_new_option_syntax,
1898  "TARGET_DETAIL", colon + 1);
1899  }
1900  }
1901  else if (serverMajor >= 1500)
1902  AppendStringCommandOption(&buf, use_new_option_syntax,
1903  "TARGET", "client");
1904 
1905  if (compressloc == COMPRESS_LOCATION_SERVER)
1906  {
1907  if (!use_new_option_syntax)
1908  pg_fatal("server does not support server-side compression");
1909  AppendStringCommandOption(&buf, use_new_option_syntax,
1910  "COMPRESSION", compression_algorithm);
1911  if (compression_detail != NULL)
1912  AppendStringCommandOption(&buf, use_new_option_syntax,
1913  "COMPRESSION_DETAIL",
1914  compression_detail);
1915  }
1916 
1917  if (verbose)
1918  pg_log_info("initiating base backup, waiting for checkpoint to complete");
1919 
1920  if (showprogress && !verbose)
1921  {
1922  fprintf(stderr, "waiting for checkpoint");
1923  if (isatty(fileno(stderr)))
1924  fprintf(stderr, "\r");
1925  else
1926  fprintf(stderr, "\n");
1927  }
1928 
1929  if (use_new_option_syntax && buf.len > 0)
1930  basebkp = psprintf("BASE_BACKUP (%s)", buf.data);
1931  else
1932  basebkp = psprintf("BASE_BACKUP %s", buf.data);
1933 
1934  if (PQsendQuery(conn, basebkp) == 0)
1935  pg_fatal("could not send replication command \"%s\": %s",
1936  "BASE_BACKUP", PQerrorMessage(conn));
1937 
1938  /*
1939  * Get the starting WAL location
1940  */
1941  res = PQgetResult(conn);
1943  pg_fatal("could not initiate base backup: %s",
1944  PQerrorMessage(conn));
1945  if (PQntuples(res) != 1)
1946  pg_fatal("server returned unexpected response to BASE_BACKUP command; got %d rows and %d fields, expected %d rows and %d fields",
1947  PQntuples(res), PQnfields(res), 1, 2);
1948 
1949  strlcpy(xlogstart, PQgetvalue(res, 0, 0), sizeof(xlogstart));
1950 
1951  if (verbose)
1952  pg_log_info("checkpoint completed");
1953 
1954  /*
1955  * 9.3 and later sends the TLI of the starting point. With older servers,
1956  * assume it's the same as the latest timeline reported by
1957  * IDENTIFY_SYSTEM.
1958  */
1959  if (PQnfields(res) >= 2)
1960  starttli = atoi(PQgetvalue(res, 0, 1));
1961  else
1962  starttli = latesttli;
1963  PQclear(res);
1964  MemSet(xlogend, 0, sizeof(xlogend));
1965 
1966  if (verbose && includewal != NO_WAL)
1967  pg_log_info("write-ahead log start point: %s on timeline %u",
1968  xlogstart, starttli);
1969 
1970  /*
1971  * Get the header
1972  */
1973  res = PQgetResult(conn);
1975  pg_fatal("could not get backup header: %s",
1976  PQerrorMessage(conn));
1977  if (PQntuples(res) < 1)
1978  pg_fatal("no data returned from server");
1979 
1980  /*
1981  * Sum up the total size, for progress reporting
1982  */
1983  totalsize_kb = totaldone = 0;
1985  for (i = 0; i < PQntuples(res); i++)
1986  {
1987  totalsize_kb += atol(PQgetvalue(res, i, 2));
1988 
1989  /*
1990  * Verify tablespace directories are empty. Don't bother with the
1991  * first once since it can be relocated, and it will be checked before
1992  * we do anything anyway.
1993  *
1994  * Note that this is skipped for tar format backups and backups that
1995  * the server is storing to a target location, since in that case we
1996  * won't be storing anything into these directories and thus should
1997  * not create them.
1998  */
1999  if (backup_target == NULL && format == 'p' && !PQgetisnull(res, i, 1))
2000  {
2001  char *path = unconstify(char *, get_tablespace_mapping(PQgetvalue(res, i, 1)));
2002 
2004  }
2005  }
2006 
2007  /*
2008  * When writing to stdout, require a single tablespace
2009  */
2010  writing_to_stdout = format == 't' && basedir != NULL &&
2011  strcmp(basedir, "-") == 0;
2012  if (writing_to_stdout && PQntuples(res) > 1)
2013  pg_fatal("can only write single tablespace to stdout, database has %d",
2014  PQntuples(res));
2015 
2016  /*
2017  * If we're streaming WAL, start the streaming session before we start
2018  * receiving the actual data chunks.
2019  */
2020  if (includewal == STREAM_WAL)
2021  {
2022  pg_compress_algorithm wal_compress_algorithm;
2023  int wal_compress_level;
2024 
2025  if (verbose)
2026  pg_log_info("starting background WAL receiver");
2027 
2028  if (client_compress->algorithm == PG_COMPRESSION_GZIP)
2029  {
2030  wal_compress_algorithm = PG_COMPRESSION_GZIP;
2031  wal_compress_level =
2032  (client_compress->options & PG_COMPRESSION_OPTION_LEVEL)
2033  != 0 ? client_compress->level : 0;
2034  }
2035  else
2036  {
2037  wal_compress_algorithm = PG_COMPRESSION_NONE;
2038  wal_compress_level = 0;
2039  }
2040 
2041  StartLogStreamer(xlogstart, starttli, sysidentifier,
2042  wal_compress_algorithm, wal_compress_level);
2043  }
2044 
2045  if (serverMajor >= 1500)
2046  {
2047  /* Receive a single tar stream with everything. */
2048  ReceiveArchiveStream(conn, client_compress);
2049  }
2050  else
2051  {
2052  /* Receive a tar file for each tablespace in turn */
2053  for (i = 0; i < PQntuples(res); i++)
2054  {
2055  char archive_name[MAXPGPATH];
2056  char *spclocation;
2057 
2058  /*
2059  * If we write the data out to a tar file, it will be named
2060  * base.tar if it's the main data directory or <tablespaceoid>.tar
2061  * if it's for another tablespace. CreateBackupStreamer() will
2062  * arrange to add .gz to the archive name if pg_basebackup is
2063  * performing compression.
2064  */
2065  if (PQgetisnull(res, i, 0))
2066  {
2067  strlcpy(archive_name, "base.tar", sizeof(archive_name));
2068  spclocation = NULL;
2069  }
2070  else
2071  {
2072  snprintf(archive_name, sizeof(archive_name),
2073  "%s.tar", PQgetvalue(res, i, 0));
2074  spclocation = PQgetvalue(res, i, 1);
2075  }
2076 
2077  ReceiveTarFile(conn, archive_name, spclocation, i,
2078  client_compress);
2079  }
2080 
2081  /*
2082  * Now receive backup manifest, if appropriate.
2083  *
2084  * If we're writing a tarfile to stdout, ReceiveTarFile will have
2085  * already processed the backup manifest and included it in the output
2086  * tarfile. Such a configuration doesn't allow for writing multiple
2087  * files.
2088  *
2089  * If we're talking to an older server, it won't send a backup
2090  * manifest, so don't try to receive one.
2091  */
2092  if (!writing_to_stdout && manifest)
2094  }
2095 
2096  if (showprogress)
2097  {
2099  progress_report(PQntuples(res), true, true);
2100  }
2101 
2102  PQclear(res);
2103 
2104  /*
2105  * Get the stop position
2106  */
2107  res = PQgetResult(conn);
2109  pg_fatal("backup failed: %s",
2110  PQerrorMessage(conn));
2111  if (PQntuples(res) != 1)
2112  pg_fatal("no write-ahead log end position returned from server");
2113  strlcpy(xlogend, PQgetvalue(res, 0, 0), sizeof(xlogend));
2114  if (verbose && includewal != NO_WAL)
2115  pg_log_info("write-ahead log end point: %s", xlogend);
2116  PQclear(res);
2117 
2118  res = PQgetResult(conn);
2120  {
2121  const char *sqlstate = PQresultErrorField(res, PG_DIAG_SQLSTATE);
2122 
2123  if (sqlstate &&
2124  strcmp(sqlstate, ERRCODE_DATA_CORRUPTED) == 0)
2125  {
2126  pg_log_error("checksum error occurred");
2127  checksum_failure = true;
2128  }
2129  else
2130  {
2131  pg_log_error("final receive failed: %s",
2132  PQerrorMessage(conn));
2133  }
2134  exit(1);
2135  }
2136 
2137  if (bgchild > 0)
2138  {
2139 #ifndef WIN32
2140  int status;
2141  pid_t r;
2142 #else
2143  DWORD status;
2144 
2145  /*
2146  * get a pointer sized version of bgchild to avoid warnings about
2147  * casting to a different size on WIN64.
2148  */
2149  intptr_t bgchild_handle = bgchild;
2150  uint32 hi,
2151  lo;
2152 #endif
2153 
2154  if (verbose)
2155  pg_log_info("waiting for background process to finish streaming ...");
2156 
2157 #ifndef WIN32
2158  if (write(bgpipe[1], xlogend, strlen(xlogend)) != strlen(xlogend))
2159  pg_fatal("could not send command to background pipe: %m");
2160 
2161  /* Just wait for the background process to exit */
2162  r = waitpid(bgchild, &status, 0);
2163  if (r == (pid_t) -1)
2164  pg_fatal("could not wait for child process: %m");
2165  if (r != bgchild)
2166  pg_fatal("child %d died, expected %d", (int) r, (int) bgchild);
2167  if (status != 0)
2169  /* Exited normally, we're happy! */
2170 #else /* WIN32 */
2171 
2172  /*
2173  * On Windows, since we are in the same process, we can just store the
2174  * value directly in the variable, and then set the flag that says
2175  * it's there.
2176  */
2177  if (sscanf(xlogend, "%X/%X", &hi, &lo) != 2)
2178  pg_fatal("could not parse write-ahead log location \"%s\"",
2179  xlogend);
2180  xlogendptr = ((uint64) hi) << 32 | lo;
2181  InterlockedIncrement(&has_xlogendptr);
2182 
2183  /* First wait for the thread to exit */
2184  if (WaitForSingleObjectEx((HANDLE) bgchild_handle, INFINITE, FALSE) !=
2185  WAIT_OBJECT_0)
2186  {
2187  _dosmaperr(GetLastError());
2188  pg_fatal("could not wait for child thread: %m");
2189  }
2190  if (GetExitCodeThread((HANDLE) bgchild_handle, &status) == 0)
2191  {
2192  _dosmaperr(GetLastError());
2193  pg_fatal("could not get child thread exit status: %m");
2194  }
2195  if (status != 0)
2196  pg_fatal("child thread exited with error %u",
2197  (unsigned int) status);
2198  /* Exited normally, we're happy */
2199 #endif
2200  }
2201 
2202  /* Free the configuration file contents */
2204 
2205  /*
2206  * End of copy data. Final result is already checked inside the loop.
2207  */
2208  PQclear(res);
2209  PQfinish(conn);
2210  conn = NULL;
2211 
2212  /*
2213  * Make data persistent on disk once backup is completed. For tar format
2214  * sync the parent directory and all its contents as each tar file was not
2215  * synced after being completed. In plain format, all the data of the
2216  * base directory is synced, taking into account all the tablespaces.
2217  * Errors are not considered fatal.
2218  *
2219  * If, however, there's a backup target, we're not writing anything
2220  * locally, so in that case we skip this step.
2221  */
2222  if (do_sync && backup_target == NULL)
2223  {
2224  if (verbose)
2225  pg_log_info("syncing data to disk ...");
2226  if (format == 't')
2227  {
2228  if (strcmp(basedir, "-") != 0)
2229  (void) fsync_dir_recurse(basedir);
2230  }
2231  else
2232  {
2233  (void) fsync_pgdata(basedir, serverVersion);
2234  }
2235  }
2236 
2237  /*
2238  * After synchronizing data to disk, perform a durable rename of
2239  * backup_manifest.tmp to backup_manifest, if we wrote such a file. This
2240  * way, a failure or system crash before we reach this point will leave us
2241  * without a backup_manifest file, decreasing the chances that a directory
2242  * we leave behind will be mistaken for a valid backup.
2243  */
2244  if (!writing_to_stdout && manifest && backup_target == NULL)
2245  {
2246  char tmp_filename[MAXPGPATH];
2247  char filename[MAXPGPATH];
2248 
2249  if (verbose)
2250  pg_log_info("renaming backup_manifest.tmp to backup_manifest");
2251 
2252  snprintf(tmp_filename, MAXPGPATH, "%s/backup_manifest.tmp", basedir);
2253  snprintf(filename, MAXPGPATH, "%s/backup_manifest", basedir);
2254 
2255  if (do_sync)
2256  {
2257  /* durable_rename emits its own log message in case of failure */
2258  if (durable_rename(tmp_filename, filename) != 0)
2259  exit(1);
2260  }
2261  else
2262  {
2263  if (rename(tmp_filename, filename) != 0)
2264  pg_fatal("could not rename file \"%s\" to \"%s\": %m",
2265  tmp_filename, filename);
2266  }
2267  }
2268 
2269  if (verbose)
2270  pg_log_info("base backup completed");
2271 }
#define unconstify(underlying_type, expr)
Definition: c.h:1240
unsigned int uint32
Definition: c.h:441
#define MemSet(start, val, len)
Definition: c.h:1008
#define PG_COMPRESSION_OPTION_LEVEL
Definition: compression.h:25
pg_compress_algorithm
Definition: compression.h:18
@ PG_COMPRESSION_GZIP
Definition: compression.h:20
@ PG_COMPRESSION_NONE
Definition: compression.h:19
int durable_rename(const char *oldfile, const char *newfile, int elevel)
Definition: fd.c:699
const char * PQparameterStatus(const PGconn *conn, const char *paramName)
Definition: fe-connect.c:6873
int PQserverVersion(const PGconn *conn)
Definition: fe-connect.c:6898
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:6908
void PQfinish(PGconn *conn)
Definition: fe-connect.c:4261
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:3270
void PQclear(PGresult *res)
Definition: fe-exec.c:718
int PQntuples(const PGresult *res)
Definition: fe-exec.c:3340
char * PQgetvalue(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3735
int PQgetisnull(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3760
int PQsendQuery(PGconn *conn, const char *query)
Definition: fe-exec.c:1424
char * PQresultErrorField(const PGresult *res, int fieldcode)
Definition: fe-exec.c:3325
int PQnfields(const PGresult *res)
Definition: fe-exec.c:3348
PGresult * PQgetResult(PGconn *conn)
Definition: fe-exec.c:2082
#define write(a, b, c)
Definition: win32.h:14
int i
Definition: isn.c:73
@ PGRES_COMMAND_OK
Definition: libpq-fe.h:97
@ PGRES_TUPLES_OK
Definition: libpq-fe.h:100
Assert(fmt[strlen(fmt) - 1] !='\n')
exit(1)
#define pg_log_error(...)
Definition: logging.h:106
#define pg_log_info(...)
Definition: logging.h:124
char * pnstrdup(const char *in, Size len)
Definition: mcxt.c:1316
#define pg_fatal(...)
static int verbose
static bool checksum_failure
static bool estimatesize
static bool manifest
static int32 maxrate
static void ReceiveTarFile(PGconn *conn, char *archive_name, char *spclocation, bool tablespacenum, pg_compress_specification *compress)
static char * backup_target
static char format
static void StartLogStreamer(char *startpos, uint32 timeline, char *sysidentifier, pg_compress_algorithm wal_compress_algorithm, int wal_compress_level)
static int bgpipe[2]
static void ReceiveArchiveStream(PGconn *conn, pg_compress_specification *compress)
static PQExpBuffer recoveryconfcontents
static int tablespacecount
static void progress_update_filename(const char *filename)
static pid_t bgchild
static int has_xlogendptr
static void verify_dir_is_empty_or_create(char *dirname, bool *created, bool *found)
static uint64 totalsize_kb
static bool verify_checksums
static char * replication_slot
static void ReceiveBackupManifest(PGconn *conn)
static uint64 totaldone
static void progress_report(int tablespacenum, bool force, bool finished)
static bool manifest_force_encode
static char * manifest_checksums
static bool found_tablespace_dirs
static IncludeWal includewal
static bool do_sync
static bool writerecoveryconf
static bool made_tablespace_dirs
static bool fastcheckpoint
#define ERRCODE_DATA_CORRUPTED
Definition: pg_basebackup.c:43
static char * label
static bool showprogress
static const char * get_tablespace_mapping(const char *dir)
static char * basedir
static XLogRecPtr xlogendptr
#define MAXPGPATH
static char * filename
Definition: pg_dumpall.c:94
static pg_compress_algorithm compression_algorithm
Definition: pg_receivewal.c:55
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:229
static char * buf
Definition: pg_test_fsync.c:67
#define snprintf
Definition: port.h:225
#define fprintf
Definition: port.h:229
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
#define PG_DIAG_SQLSTATE
Definition: postgres_ext.h:57
void initPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:92
void destroyPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:116
char * psprintf(const char *fmt,...)
Definition: psprintf.c:46
bool CheckServerVersionForStreaming(PGconn *conn)
Definition: receivelog.c:381
PQExpBuffer GenerateRecoveryConfig(PGconn *pgconn, char *replication_slot)
Definition: recovery_gen.c:23
void AppendIntegerCommandOption(PQExpBuffer buf, bool use_new_option_syntax, char *option_name, int32 option_value)
Definition: streamutil.c:779
void AppendPlainCommandOption(PQExpBuffer buf, bool use_new_option_syntax, char *option_name)
Definition: streamutil.c:735
void AppendStringCommandOption(PQExpBuffer buf, bool use_new_option_syntax, char *option_name, char *option_value)
Definition: streamutil.c:756
PGconn * conn
Definition: streamutil.c:54
bool RunIdentifySystem(PGconn *conn, char **sysid, TimeLineID *starttli, XLogRecPtr *startpos, char **db_name)
Definition: streamutil.c:403
pg_compress_algorithm algorithm
Definition: compression.h:30
char * wait_result_to_str(int exitstatus)
Definition: wait_error.c:32
void _dosmaperr(unsigned long)
Definition: win32error.c:171
uint32 TimeLineID
Definition: xlogdefs.h:59

References _dosmaperr(), pg_compress_specification::algorithm, AppendIntegerCommandOption(), AppendPlainCommandOption(), AppendStringCommandOption(), Assert(), backup_target, basedir, bgchild, bgpipe, buf, CheckServerVersionForStreaming(), checksum_failure, COMPRESS_LOCATION_SERVER, compression_algorithm, conn, destroyPQExpBuffer(), do_sync, durable_rename(), ERRCODE_DATA_CORRUPTED, estimatesize, exit(), fastcheckpoint, FETCH_WAL, filename, format, found_tablespace_dirs, fprintf, GenerateRecoveryConfig(), get_tablespace_mapping(), has_xlogendptr, i, includewal, initPQExpBuffer(), label, pg_compress_specification::level, made_tablespace_dirs, manifest, manifest_checksums, manifest_force_encode, MAXPGPATH, maxrate, MemSet, NO_WAL, pg_compress_specification::options, PG_COMPRESSION_GZIP, PG_COMPRESSION_NONE, PG_COMPRESSION_OPTION_LEVEL, PG_DIAG_SQLSTATE, pg_fatal, pg_log_error, pg_log_info, PGRES_COMMAND_OK, PGRES_TUPLES_OK, pnstrdup(), PQclear(), PQerrorMessage(), PQfinish(), PQgetisnull(), PQgetResult(), PQgetvalue(), PQnfields(), PQntuples(), PQparameterStatus(), PQresultErrorField(), PQresultStatus(), PQsendQuery(), PQserverVersion(), progress_report(), progress_update_filename(), psprintf(), ReceiveArchiveStream(), ReceiveBackupManifest(), ReceiveTarFile(), recoveryconfcontents, replication_slot, res, RunIdentifySystem(), showprogress, snprintf, StartLogStreamer(), status(), STREAM_WAL, strlcpy(), tablespacecount, totaldone, totalsize_kb, unconstify, verbose, verify_checksums, verify_dir_is_empty_or_create(), wait_result_to_str(), write, writerecoveryconf, and xlogendptr.

Referenced by main().

◆ cleanup_directories_atexit()

static void cleanup_directories_atexit ( void  )
static

Definition at line 231 of file pg_basebackup.c.

232 {
233  if (success || in_log_streamer)
234  return;
235 
236  if (!noclean && !checksum_failure)
237  {
238  if (made_new_pgdata)
239  {
240  pg_log_info("removing data directory \"%s\"", basedir);
241  if (!rmtree(basedir, true))
242  pg_log_error("failed to remove data directory");
243  }
244  else if (found_existing_pgdata)
245  {
246  pg_log_info("removing contents of data directory \"%s\"", basedir);
247  if (!rmtree(basedir, false))
248  pg_log_error("failed to remove contents of data directory");
249  }
250 
251  if (made_new_xlogdir)
252  {
253  pg_log_info("removing WAL directory \"%s\"", xlog_dir);
254  if (!rmtree(xlog_dir, true))
255  pg_log_error("failed to remove WAL directory");
256  }
257  else if (found_existing_xlogdir)
258  {
259  pg_log_info("removing contents of WAL directory \"%s\"", xlog_dir);
260  if (!rmtree(xlog_dir, false))
261  pg_log_error("failed to remove contents of WAL directory");
262  }
263  }
264  else
265  {
267  pg_log_info("data directory \"%s\" not removed at user's request", basedir);
268 
270  pg_log_info("WAL directory \"%s\" not removed at user's request", xlog_dir);
271  }
272 
274  pg_log_info("changes to tablespace directories will not be undone");
275 }
static bool noclean
static bool found_existing_pgdata
static bool found_existing_xlogdir
static char * xlog_dir
static bool success
static bool in_log_streamer
static bool made_new_xlogdir
static bool made_new_pgdata
bool rmtree(const char *path, bool rmtopdir)
Definition: rmtree.c:42

References basedir, checksum_failure, found_existing_pgdata, found_existing_xlogdir, found_tablespace_dirs, in_log_streamer, made_new_pgdata, made_new_xlogdir, made_tablespace_dirs, noclean, pg_log_error, pg_log_info, rmtree(), success, and xlog_dir.

Referenced by main().

◆ CreateBackupStreamer()

static bbstreamer * CreateBackupStreamer ( char *  archive_name,
char *  spclocation,
bbstreamer **  manifest_inject_streamer_p,
bool  is_recovery_guc_supported,
bool  expect_unterminated_tarfile,
pg_compress_specification compress 
)
static

Definition at line 1077 of file pg_basebackup.c.

1082 {
1083  bbstreamer *streamer = NULL;
1084  bbstreamer *manifest_inject_streamer = NULL;
1085  bool inject_manifest;
1086  bool is_tar,
1087  is_tar_gz,
1088  is_tar_lz4,
1089  is_tar_zstd,
1090  is_compressed_tar;
1091  bool must_parse_archive;
1092  int archive_name_len = strlen(archive_name);
1093 
1094  /*
1095  * Normally, we emit the backup manifest as a separate file, but when
1096  * we're writing a tarfile to stdout, we don't have that option, so
1097  * include it in the one tarfile we've got.
1098  */
1099  inject_manifest = (format == 't' && strcmp(basedir, "-") == 0 && manifest);
1100 
1101  /* Is this a tar archive? */
1102  is_tar = (archive_name_len > 4 &&
1103  strcmp(archive_name + archive_name_len - 4, ".tar") == 0);
1104 
1105  /* Is this a .tar.gz archive? */
1106  is_tar_gz = (archive_name_len > 7 &&
1107  strcmp(archive_name + archive_name_len - 7, ".tar.gz") == 0);
1108 
1109  /* Is this a .tar.lz4 archive? */
1110  is_tar_lz4 = (archive_name_len > 8 &&
1111  strcmp(archive_name + archive_name_len - 8, ".tar.lz4") == 0);
1112 
1113  /* Is this a .tar.zst archive? */
1114  is_tar_zstd = (archive_name_len > 8 &&
1115  strcmp(archive_name + archive_name_len - 8, ".tar.zst") == 0);
1116 
1117  /* Is this any kind of compressed tar? */
1118  is_compressed_tar = is_tar_gz || is_tar_lz4 || is_tar_zstd;
1119 
1120  /*
1121  * Injecting the manifest into a compressed tar file would be possible if
1122  * we decompressed it, parsed the tarfile, generated a new tarfile, and
1123  * recompressed it, but compressing and decompressing multiple times just
1124  * to inject the manifest seems inefficient enough that it's probably not
1125  * what the user wants. So, instead, reject the request and tell the user
1126  * to specify something more reasonable.
1127  */
1128  if (inject_manifest && is_compressed_tar)
1129  {
1130  pg_log_error("cannot inject manifest into a compressed tarfile");
1131  pg_log_info("use client-side compression, send the output to a directory rather than standard output, or use --no-manifest");
1132  exit(1);
1133  }
1134 
1135  /*
1136  * We have to parse the archive if (1) we're suppose to extract it, or if
1137  * (2) we need to inject backup_manifest or recovery configuration into
1138  * it. However, we only know how to parse tar archives.
1139  */
1140  must_parse_archive = (format == 'p' || inject_manifest ||
1141  (spclocation == NULL && writerecoveryconf));
1142 
1143  /* At present, we only know how to parse tar archives. */
1144  if (must_parse_archive && !is_tar && !is_compressed_tar)
1145  {
1146  pg_log_error("unable to parse archive: %s", archive_name);
1147  pg_log_error_detail("Only tar archives can be parsed.");
1148  if (format == 'p')
1149  pg_log_error_detail("Plain format requires pg_basebackup to parse the archive.");
1150  if (inject_manifest)
1151  pg_log_error_detail("Using - as the output directory requires pg_basebackup to parse the archive.");
1152  if (writerecoveryconf)
1153  pg_log_error_detail("The -R option requires pg_basebackup to parse the archive.");
1154  exit(1);
1155  }
1156 
1157  if (format == 'p')
1158  {
1159  const char *directory;
1160 
1161  /*
1162  * In plain format, we must extract the archive. The data for the main
1163  * tablespace will be written to the base directory, and the data for
1164  * other tablespaces will be written to the directory where they're
1165  * located on the server, after applying any user-specified tablespace
1166  * mappings.
1167  */
1168  directory = spclocation == NULL ? basedir
1169  : get_tablespace_mapping(spclocation);
1173  }
1174  else
1175  {
1176  FILE *archive_file;
1177  char archive_filename[MAXPGPATH];
1178 
1179  /*
1180  * In tar format, we just write the archive without extracting it.
1181  * Normally, we write it to the archive name provided by the caller,
1182  * but when the base directory is "-" that means we need to write to
1183  * standard output.
1184  */
1185  if (strcmp(basedir, "-") == 0)
1186  {
1187  snprintf(archive_filename, sizeof(archive_filename), "-");
1188  archive_file = stdout;
1189  }
1190  else
1191  {
1192  snprintf(archive_filename, sizeof(archive_filename),
1193  "%s/%s", basedir, archive_name);
1194  archive_file = NULL;
1195  }
1196 
1197  if (compress->algorithm == PG_COMPRESSION_NONE)
1198  streamer = bbstreamer_plain_writer_new(archive_filename,
1199  archive_file);
1200  else if (compress->algorithm == PG_COMPRESSION_GZIP)
1201  {
1202  strlcat(archive_filename, ".gz", sizeof(archive_filename));
1203  streamer = bbstreamer_gzip_writer_new(archive_filename,
1204  archive_file, compress);
1205  }
1206  else if (compress->algorithm == PG_COMPRESSION_LZ4)
1207  {
1208  strlcat(archive_filename, ".lz4", sizeof(archive_filename));
1209  streamer = bbstreamer_plain_writer_new(archive_filename,
1210  archive_file);
1211  streamer = bbstreamer_lz4_compressor_new(streamer, compress);
1212  }
1213  else if (compress->algorithm == PG_COMPRESSION_ZSTD)
1214  {
1215  strlcat(archive_filename, ".zst", sizeof(archive_filename));
1216  streamer = bbstreamer_plain_writer_new(archive_filename,
1217  archive_file);
1218  streamer = bbstreamer_zstd_compressor_new(streamer, compress);
1219  }
1220  else
1221  {
1222  Assert(false); /* not reachable */
1223  }
1224 
1225  /*
1226  * If we need to parse the archive for whatever reason, then we'll
1227  * also need to re-archive, because, if the output format is tar, the
1228  * only point of parsing the archive is to be able to inject stuff
1229  * into it.
1230  */
1231  if (must_parse_archive)
1232  streamer = bbstreamer_tar_archiver_new(streamer);
1233  progress_update_filename(archive_filename);
1234  }
1235 
1236  /*
1237  * If we're supposed to inject the backup manifest into the results, it
1238  * should be done here, so that the file content can be injected directly,
1239  * without worrying about the details of the tar format.
1240  */
1241  if (inject_manifest)
1242  manifest_inject_streamer = streamer;
1243 
1244  /*
1245  * If this is the main tablespace and we're supposed to write recovery
1246  * information, arrange to do that.
1247  */
1248  if (spclocation == NULL && writerecoveryconf)
1249  {
1250  Assert(must_parse_archive);
1251  streamer = bbstreamer_recovery_injector_new(streamer,
1252  is_recovery_guc_supported,
1254  }
1255 
1256  /*
1257  * If we're doing anything that involves understanding the contents of the
1258  * archive, we'll need to parse it. If not, we can skip parsing it, but
1259  * old versions of the server send improperly terminated tarfiles, so if
1260  * we're talking to such a server we'll need to add the terminator here.
1261  */
1262  if (must_parse_archive)
1263  streamer = bbstreamer_tar_parser_new(streamer);
1264  else if (expect_unterminated_tarfile)
1265  streamer = bbstreamer_tar_terminator_new(streamer);
1266 
1267  /*
1268  * If the user has requested a server compressed archive along with
1269  * archive extraction at client then we need to decompress it.
1270  */
1271  if (format == 'p')
1272  {
1273  if (is_tar_gz)
1274  streamer = bbstreamer_gzip_decompressor_new(streamer);
1275  else if (is_tar_lz4)
1276  streamer = bbstreamer_lz4_decompressor_new(streamer);
1277  else if (is_tar_zstd)
1278  streamer = bbstreamer_zstd_decompressor_new(streamer);
1279  }
1280 
1281  /* Return the results. */
1282  *manifest_inject_streamer_p = manifest_inject_streamer;
1283  return streamer;
1284 }
bbstreamer * bbstreamer_gzip_writer_new(char *pathname, FILE *file, pg_compress_specification *compress)
bbstreamer * bbstreamer_zstd_compressor_new(bbstreamer *next, pg_compress_specification *compress)
bbstreamer * bbstreamer_tar_terminator_new(bbstreamer *next)
bbstreamer * bbstreamer_lz4_compressor_new(bbstreamer *next, pg_compress_specification *compress)
bbstreamer * bbstreamer_tar_parser_new(bbstreamer *next)
bbstreamer * bbstreamer_lz4_decompressor_new(bbstreamer *next)
bbstreamer * bbstreamer_recovery_injector_new(bbstreamer *next, bool is_recovery_guc_supported, PQExpBuffer recoveryconfcontents)
bbstreamer * bbstreamer_tar_archiver_new(bbstreamer *next)
bbstreamer * bbstreamer_zstd_decompressor_new(bbstreamer *next)
bbstreamer * bbstreamer_plain_writer_new(char *pathname, FILE *file)
bbstreamer * bbstreamer_extractor_new(const char *basepath, const char *(*link_map)(const char *), void(*report_output_file)(const char *))
bbstreamer * bbstreamer_gzip_decompressor_new(bbstreamer *next)
@ PG_COMPRESSION_LZ4
Definition: compression.h:21
@ PG_COMPRESSION_ZSTD
Definition: compression.h:22
#define pg_log_error_detail(...)
Definition: logging.h:109
size_t strlcat(char *dst, const char *src, size_t siz)
Definition: strlcat.c:33
static const char * directory
Definition: zic.c:632

References pg_compress_specification::algorithm, Assert(), basedir, bbstreamer_extractor_new(), bbstreamer_gzip_decompressor_new(), bbstreamer_gzip_writer_new(), bbstreamer_lz4_compressor_new(), bbstreamer_lz4_decompressor_new(), bbstreamer_plain_writer_new(), bbstreamer_recovery_injector_new(), bbstreamer_tar_archiver_new(), bbstreamer_tar_parser_new(), bbstreamer_tar_terminator_new(), bbstreamer_zstd_compressor_new(), bbstreamer_zstd_decompressor_new(), directory, exit(), format, get_tablespace_mapping(), manifest, MAXPGPATH, PG_COMPRESSION_GZIP, PG_COMPRESSION_LZ4, PG_COMPRESSION_NONE, PG_COMPRESSION_ZSTD, pg_log_error, pg_log_error_detail, pg_log_info, progress_update_filename(), recoveryconfcontents, snprintf, generate_unaccent_rules::stdout, strlcat(), and writerecoveryconf.

Referenced by ReceiveArchiveStreamChunk(), and ReceiveTarFile().

◆ disconnect_atexit()

static void disconnect_atexit ( void  )
static

Definition at line 278 of file pg_basebackup.c.

279 {
280  if (conn != NULL)
281  PQfinish(conn);
282 }

References conn, and PQfinish().

Referenced by main().

◆ get_tablespace_mapping()

static const char * get_tablespace_mapping ( const char *  dir)
static

Definition at line 1685 of file pg_basebackup.c.

1686 {
1687  TablespaceListCell *cell;
1688  char canon_dir[MAXPGPATH];
1689 
1690  /* Canonicalize path for comparison consistency */
1691  strlcpy(canon_dir, dir, sizeof(canon_dir));
1692  canonicalize_path(canon_dir);
1693 
1694  for (cell = tablespace_dirs.head; cell; cell = cell->next)
1695  if (strcmp(canon_dir, cell->old_dir) == 0)
1696  return cell->new_dir;
1697 
1698  return dir;
1699 }
static TablespaceList tablespace_dirs
void canonicalize_path(char *path)
Definition: path.c:264
struct TablespaceListCell * next
Definition: pg_basebackup.c:47
char old_dir[MAXPGPATH]
Definition: pg_basebackup.c:48
char new_dir[MAXPGPATH]
Definition: pg_basebackup.c:49
TablespaceListCell * head
Definition: pg_basebackup.c:54

References canonicalize_path(), TablespaceList::head, MAXPGPATH, TablespaceListCell::new_dir, TablespaceListCell::next, TablespaceListCell::old_dir, strlcpy(), and tablespace_dirs.

Referenced by BaseBackup(), and CreateBackupStreamer().

◆ GetCopyDataByte()

static char GetCopyDataByte ( size_t  r,
char *  copybuf,
size_t *  cursor 
)
static

Definition at line 1523 of file pg_basebackup.c.

1524 {
1525  if (*cursor >= r)
1527 
1528  return copybuf[(*cursor)++];
1529 }
static void ReportCopyDataParseError(size_t r, char *copybuf)
Definition: type.h:131
static StringInfo copybuf
Definition: tablesync.c:127

References copybuf, and ReportCopyDataParseError().

Referenced by ReceiveArchiveStreamChunk().

◆ GetCopyDataEnd()

static void GetCopyDataEnd ( size_t  r,
char *  copybuf,
size_t  cursor 
)
static

Definition at line 1576 of file pg_basebackup.c.

1577 {
1578  if (r != cursor)
1580 }

References copybuf, and ReportCopyDataParseError().

Referenced by ReceiveArchiveStreamChunk().

◆ GetCopyDataString()

static char * GetCopyDataString ( size_t  r,
char *  copybuf,
size_t *  cursor 
)
static

Definition at line 1537 of file pg_basebackup.c.

1538 {
1539  size_t startpos = *cursor;
1540  size_t endpos = startpos;
1541 
1542  while (1)
1543  {
1544  if (endpos >= r)
1546  if (copybuf[endpos] == '\0')
1547  break;
1548  ++endpos;
1549  }
1550 
1551  *cursor = endpos + 1;
1552  return &copybuf[startpos];
1553 }
static XLogRecPtr endpos
Definition: pg_receivewal.c:56
static XLogRecPtr startpos

References copybuf, endpos, ReportCopyDataParseError(), and startpos.

Referenced by ReceiveArchiveStreamChunk().

◆ GetCopyDataUInt64()

static uint64 GetCopyDataUInt64 ( size_t  r,
char *  copybuf,
size_t *  cursor 
)
static

Definition at line 1561 of file pg_basebackup.c.

1562 {
1563  uint64 result;
1564 
1565  if (*cursor + sizeof(uint64) > r)
1567  memcpy(&result, &copybuf[*cursor], sizeof(uint64));
1568  *cursor += sizeof(uint64);
1569  return pg_ntoh64(result);
1570 }
#define pg_ntoh64(x)
Definition: pg_bswap.h:126

References copybuf, pg_ntoh64, and ReportCopyDataParseError().

Referenced by ReceiveArchiveStreamChunk().

◆ kill_bgchild_atexit()

static void kill_bgchild_atexit ( void  )
static

Definition at line 303 of file pg_basebackup.c.

304 {
305  if (bgchild > 0 && !bgchild_exited)
306  kill(bgchild, SIGTERM);
307 }
static volatile sig_atomic_t bgchild_exited
#define kill(pid, sig)
Definition: win32_port.h:464

References bgchild, bgchild_exited, and kill.

Referenced by StartLogStreamer().

◆ LogStreamerMain()

static int LogStreamerMain ( logstreamer_param param)
static

Definition at line 529 of file pg_basebackup.c.

530 {
531  StreamCtl stream;
532 
533  in_log_streamer = true;
534 
535  MemSet(&stream, 0, sizeof(stream));
536  stream.startpos = param->startptr;
537  stream.timeline = param->timeline;
538  stream.sysidentifier = param->sysidentifier;
540 #ifndef WIN32
541  stream.stop_socket = bgpipe[0];
542 #else
543  stream.stop_socket = PGINVALID_SOCKET;
544 #endif
546  stream.synchronous = false;
547  /* fsync happens at the end of pg_basebackup for all data */
548  stream.do_sync = false;
549  stream.mark_done = true;
550  stream.partial_suffix = NULL;
552  if (format == 'p')
553  stream.walmethod = CreateWalDirectoryMethod(param->xlog,
555  stream.do_sync);
556  else
557  stream.walmethod = CreateWalTarMethod(param->xlog,
558  param->wal_compress_algorithm,
559  param->wal_compress_level,
560  stream.do_sync);
561 
562  if (!ReceiveXlogStream(param->bgconn, &stream))
563  {
564  /*
565  * Any errors will already have been reported in the function process,
566  * but we need to tell the parent that we didn't shutdown in a nice
567  * way.
568  */
569 #ifdef WIN32
570  /*
571  * In order to signal the main thread of an ungraceful exit we set the
572  * same flag that we use on Unix to signal SIGCHLD.
573  */
574  bgchild_exited = true;
575 #endif
576  return 1;
577  }
578 
579  if (!stream.walmethod->finish())
580  {
581  pg_log_error("could not finish writing WAL files: %m");
582 #ifdef WIN32
583  bgchild_exited = true;
584 #endif
585  return 1;
586  }
587 
588  PQfinish(param->bgconn);
589 
590  if (format == 'p')
592  else
594  pg_free(stream.walmethod);
595 
596  return 0;
597 }
void pg_free(void *ptr)
Definition: fe_memutils.c:105
static bool reached_end_position(XLogRecPtr segendpos, uint32 timeline, bool segment_finished)
static int standby_message_timeout
#define PGINVALID_SOCKET
Definition: port.h:31
bool ReceiveXlogStream(PGconn *conn, StreamCtl *stream)
Definition: receivelog.c:459
char * sysidentifier
Definition: receivelog.h:33
TimeLineID timeline
Definition: receivelog.h:32
stream_stop_callback stream_stop
Definition: receivelog.h:41
char * replication_slot
Definition: receivelog.h:48
XLogRecPtr startpos
Definition: receivelog.h:31
bool do_sync
Definition: receivelog.h:38
pgsocket stop_socket
Definition: receivelog.h:43
int standby_message_timeout
Definition: receivelog.h:35
WalWriteMethod * walmethod
Definition: receivelog.h:46
bool mark_done
Definition: receivelog.h:37
char * partial_suffix
Definition: receivelog.h:47
bool synchronous
Definition: receivelog.h:36
bool(* finish)(void)
Definition: walmethods.h:85
XLogRecPtr startptr
pg_compress_algorithm wal_compress_algorithm
char xlog[MAXPGPATH]
WalWriteMethod * CreateWalDirectoryMethod(const char *basedir, pg_compress_algorithm compression_algorithm, int compression_level, bool sync)
Definition: walmethods.c:625
void FreeWalTarMethod(void)
Definition: walmethods.c:1375
WalWriteMethod * CreateWalTarMethod(const char *tarbase, pg_compress_algorithm compression_algorithm, int compression_level, bool sync)
Definition: walmethods.c:1338
void FreeWalDirectoryMethod(void)
Definition: walmethods.c:654

References bgchild_exited, logstreamer_param::bgconn, bgpipe, CreateWalDirectoryMethod(), CreateWalTarMethod(), StreamCtl::do_sync, WalWriteMethod::finish, format, FreeWalDirectoryMethod(), FreeWalTarMethod(), in_log_streamer, StreamCtl::mark_done, MemSet, StreamCtl::partial_suffix, PG_COMPRESSION_NONE, pg_free(), pg_log_error, PGINVALID_SOCKET, PQfinish(), reached_end_position(), ReceiveXlogStream(), replication_slot, StreamCtl::replication_slot, standby_message_timeout, StreamCtl::standby_message_timeout, StreamCtl::startpos, logstreamer_param::startptr, StreamCtl::stop_socket, StreamCtl::stream_stop, StreamCtl::synchronous, logstreamer_param::sysidentifier, StreamCtl::sysidentifier, logstreamer_param::timeline, StreamCtl::timeline, logstreamer_param::wal_compress_algorithm, logstreamer_param::wal_compress_level, StreamCtl::walmethod, and logstreamer_param::xlog.

Referenced by StartLogStreamer().

◆ main()

int main ( int  argc,
char **  argv 
)

Definition at line 2275 of file pg_basebackup.c.

2276 {
2277  static struct option long_options[] = {
2278  {"help", no_argument, NULL, '?'},
2279  {"version", no_argument, NULL, 'V'},
2280  {"pgdata", required_argument, NULL, 'D'},
2281  {"format", required_argument, NULL, 'F'},
2282  {"checkpoint", required_argument, NULL, 'c'},
2283  {"create-slot", no_argument, NULL, 'C'},
2284  {"max-rate", required_argument, NULL, 'r'},
2285  {"write-recovery-conf", no_argument, NULL, 'R'},
2286  {"slot", required_argument, NULL, 'S'},
2287  {"target", required_argument, NULL, 't'},
2288  {"tablespace-mapping", required_argument, NULL, 'T'},
2289  {"wal-method", required_argument, NULL, 'X'},
2290  {"gzip", no_argument, NULL, 'z'},
2291  {"compress", required_argument, NULL, 'Z'},
2292  {"label", required_argument, NULL, 'l'},
2293  {"no-clean", no_argument, NULL, 'n'},
2294  {"no-sync", no_argument, NULL, 'N'},
2295  {"dbname", required_argument, NULL, 'd'},
2296  {"host", required_argument, NULL, 'h'},
2297  {"port", required_argument, NULL, 'p'},
2298  {"username", required_argument, NULL, 'U'},
2299  {"no-password", no_argument, NULL, 'w'},
2300  {"password", no_argument, NULL, 'W'},
2301  {"status-interval", required_argument, NULL, 's'},
2302  {"verbose", no_argument, NULL, 'v'},
2303  {"progress", no_argument, NULL, 'P'},
2304  {"waldir", required_argument, NULL, 1},
2305  {"no-slot", no_argument, NULL, 2},
2306  {"no-verify-checksums", no_argument, NULL, 3},
2307  {"no-estimate-size", no_argument, NULL, 4},
2308  {"no-manifest", no_argument, NULL, 5},
2309  {"manifest-force-encode", no_argument, NULL, 6},
2310  {"manifest-checksums", required_argument, NULL, 7},
2311  {NULL, 0, NULL, 0}
2312  };
2313  int c;
2314 
2315  int option_index;
2316  char *compression_algorithm = "none";
2317  char *compression_detail = NULL;
2319  pg_compress_specification client_compress;
2320 
2321  pg_logging_init(argv[0]);
2322  progname = get_progname(argv[0]);
2323  set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pg_basebackup"));
2324 
2325  if (argc > 1)
2326  {
2327  if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
2328  {
2329  usage();
2330  exit(0);
2331  }
2332  else if (strcmp(argv[1], "-V") == 0
2333  || strcmp(argv[1], "--version") == 0)
2334  {
2335  puts("pg_basebackup (PostgreSQL) " PG_VERSION);
2336  exit(0);
2337  }
2338  }
2339 
2341 
2342  while ((c = getopt_long(argc, argv, "CD:F:r:RS:t:T:X:l:nNzZ:d:c:h:p:U:s:wWkvP",
2343  long_options, &option_index)) != -1)
2344  {
2345  switch (c)
2346  {
2347  case 'C':
2348  create_slot = true;
2349  break;
2350  case 'D':
2352  break;
2353  case 'F':
2354  if (strcmp(optarg, "p") == 0 || strcmp(optarg, "plain") == 0)
2355  format = 'p';
2356  else if (strcmp(optarg, "t") == 0 || strcmp(optarg, "tar") == 0)
2357  format = 't';
2358  else
2359  pg_fatal("invalid output format \"%s\", must be \"plain\" or \"tar\"",
2360  optarg);
2361  break;
2362  case 'r':
2364  break;
2365  case 'R':
2366  writerecoveryconf = true;
2367  break;
2368  case 'S':
2369 
2370  /*
2371  * When specifying replication slot name, use a permanent
2372  * slot.
2373  */
2375  temp_replication_slot = false;
2376  break;
2377  case 2:
2378  no_slot = true;
2379  break;
2380  case 't':
2382  break;
2383  case 'T':
2385  break;
2386  case 'X':
2387  if (strcmp(optarg, "n") == 0 ||
2388  strcmp(optarg, "none") == 0)
2389  {
2390  includewal = NO_WAL;
2391  }
2392  else if (strcmp(optarg, "f") == 0 ||
2393  strcmp(optarg, "fetch") == 0)
2394  {
2396  }
2397  else if (strcmp(optarg, "s") == 0 ||
2398  strcmp(optarg, "stream") == 0)
2399  {
2401  }
2402  else
2403  pg_fatal("invalid wal-method option \"%s\", must be \"fetch\", \"stream\", or \"none\"",
2404  optarg);
2405  break;
2406  case 1:
2408  break;
2409  case 'l':
2410  label = pg_strdup(optarg);
2411  break;
2412  case 'n':
2413  noclean = true;
2414  break;
2415  case 'N':
2416  do_sync = false;
2417  break;
2418  case 'z':
2419  compression_algorithm = "gzip";
2420  compression_detail = NULL;
2421  compressloc = COMPRESS_LOCATION_UNSPECIFIED;
2422  break;
2423  case 'Z':
2425  &compression_detail, &compressloc);
2426  break;
2427  case 'c':
2428  if (pg_strcasecmp(optarg, "fast") == 0)
2429  fastcheckpoint = true;
2430  else if (pg_strcasecmp(optarg, "spread") == 0)
2431  fastcheckpoint = false;
2432  else
2433  pg_fatal("invalid checkpoint argument \"%s\", must be \"fast\" or \"spread\"",
2434  optarg);
2435  break;
2436  case 'd':
2438  break;
2439  case 'h':
2440  dbhost = pg_strdup(optarg);
2441  break;
2442  case 'p':
2443  dbport = pg_strdup(optarg);
2444  break;
2445  case 'U':
2446  dbuser = pg_strdup(optarg);
2447  break;
2448  case 'w':
2449  dbgetpassword = -1;
2450  break;
2451  case 'W':
2452  dbgetpassword = 1;
2453  break;
2454  case 's':
2455  if (!option_parse_int(optarg, "-s/--status-interval", 0,
2456  INT_MAX / 1000,
2458  exit(1);
2459  standby_message_timeout *= 1000;
2460  break;
2461  case 'v':
2462  verbose++;
2463  break;
2464  case 'P':
2465  showprogress = true;
2466  break;
2467  case 3:
2468  verify_checksums = false;
2469  break;
2470  case 4:
2471  estimatesize = false;
2472  break;
2473  case 5:
2474  manifest = false;
2475  break;
2476  case 6:
2477  manifest_force_encode = true;
2478  break;
2479  case 7:
2481  break;
2482  default:
2483  /* getopt_long already emitted a complaint */
2484  pg_log_error_hint("Try \"%s --help\" for more information.", progname);
2485  exit(1);
2486  }
2487  }
2488 
2489  /*
2490  * Any non-option arguments?
2491  */
2492  if (optind < argc)
2493  {
2494  pg_log_error("too many command-line arguments (first is \"%s\")",
2495  argv[optind]);
2496  pg_log_error_hint("Try \"%s --help\" for more information.", progname);
2497  exit(1);
2498  }
2499 
2500  /*
2501  * Setting the backup target to 'client' is equivalent to leaving out the
2502  * option. This logic allows us to assume elsewhere that the backup is
2503  * being stored locally if and only if backup_target == NULL.
2504  */
2505  if (backup_target != NULL && strcmp(backup_target, "client") == 0)
2506  {
2508  backup_target = NULL;
2509  }
2510 
2511  /*
2512  * Can't use --format with --target. Without --target, default format is
2513  * tar.
2514  */
2515  if (backup_target != NULL && format != '\0')
2516  {
2517  pg_log_error("cannot specify both format and backup target");
2518  pg_log_error_hint("Try \"%s --help\" for more information.", progname);
2519  exit(1);
2520  }
2521  if (format == '\0')
2522  format = 'p';
2523 
2524  /*
2525  * Either directory or backup target should be specified, but not both
2526  */
2527  if (basedir == NULL && backup_target == NULL)
2528  {
2529  pg_log_error("must specify output directory or backup target");
2530  pg_log_error_hint("Try \"%s --help\" for more information.", progname);
2531  exit(1);
2532  }
2533  if (basedir != NULL && backup_target != NULL)
2534  {
2535  pg_log_error("cannot specify both output directory and backup target");
2536  pg_log_error_hint("Try \"%s --help\" for more information.", progname);
2537  exit(1);
2538  }
2539 
2540  /*
2541  * If the user has not specified where to perform backup compression,
2542  * default to the client, unless the user specified --target, in which
2543  * case the server is the only choice.
2544  */
2545  if (compressloc == COMPRESS_LOCATION_UNSPECIFIED)
2546  {
2547  if (backup_target == NULL)
2548  compressloc = COMPRESS_LOCATION_CLIENT;
2549  else
2550  compressloc = COMPRESS_LOCATION_SERVER;
2551  }
2552 
2553  /*
2554  * If any compression that we're doing is happening on the client side, we
2555  * must try to parse the compression algorithm and detail, but if it's all
2556  * on the server side, then we're just going to pass through whatever was
2557  * requested and let the server decide what to do.
2558  */
2559  if (compressloc == COMPRESS_LOCATION_CLIENT)
2560  {
2562  char *error_detail;
2563 
2565  pg_fatal("unrecognized compression algorithm \"%s\"",
2567 
2568  parse_compress_specification(alg, compression_detail, &client_compress);
2569  error_detail = validate_compress_specification(&client_compress);
2570  if (error_detail != NULL)
2571  pg_fatal("invalid compression specification: %s",
2572  error_detail);
2573  }
2574  else
2575  {
2576  Assert(compressloc == COMPRESS_LOCATION_SERVER);
2577  client_compress.algorithm = PG_COMPRESSION_NONE;
2578  client_compress.options = 0;
2579  }
2580 
2581  /*
2582  * Can't perform client-side compression if the backup is not being sent
2583  * to the client.
2584  */
2585  if (backup_target != NULL && compressloc == COMPRESS_LOCATION_CLIENT)
2586  {
2587  pg_log_error("client-side compression is not possible when a backup target is specified");
2588  pg_log_error_hint("Try \"%s --help\" for more information.", progname);
2589  exit(1);
2590  }
2591 
2592  /*
2593  * Client-side compression doesn't make sense unless tar format is in use.
2594  */
2595  if (format == 'p' && compressloc == COMPRESS_LOCATION_CLIENT &&
2596  client_compress.algorithm != PG_COMPRESSION_NONE)
2597  {
2598  pg_log_error("only tar mode backups can be compressed");
2599  pg_log_error_hint("Try \"%s --help\" for more information.", progname);
2600  exit(1);
2601  }
2602 
2603  /*
2604  * Sanity checks for WAL method.
2605  */
2606  if (backup_target != NULL && includewal == STREAM_WAL)
2607  {
2608  pg_log_error("WAL cannot be streamed when a backup target is specified");
2609  pg_log_error_hint("Try \"%s --help\" for more information.", progname);
2610  exit(1);
2611  }
2612  if (format == 't' && includewal == STREAM_WAL && strcmp(basedir, "-") == 0)
2613  {
2614  pg_log_error("cannot stream write-ahead logs in tar mode to stdout");
2615  pg_log_error_hint("Try \"%s --help\" for more information.", progname);
2616  exit(1);
2617  }
2618 
2620  {
2621  pg_log_error("replication slots can only be used with WAL streaming");
2622  pg_log_error_hint("Try \"%s --help\" for more information.", progname);
2623  exit(1);
2624  }
2625 
2626  /*
2627  * Sanity checks for replication slot options.
2628  */
2629  if (no_slot)
2630  {
2631  if (replication_slot)
2632  {
2633  pg_log_error("--no-slot cannot be used with slot name");
2634  pg_log_error_hint("Try \"%s --help\" for more information.", progname);
2635  exit(1);
2636  }
2637  temp_replication_slot = false;
2638  }
2639 
2640  if (create_slot)
2641  {
2642  if (!replication_slot)
2643  {
2644  pg_log_error("%s needs a slot to be specified using --slot",
2645  "--create-slot");
2646  pg_log_error_hint("Try \"%s --help\" for more information.", progname);
2647  exit(1);
2648  }
2649 
2650  if (no_slot)
2651  {
2652  pg_log_error("%s and %s are incompatible options",
2653  "--create-slot", "--no-slot");
2654  pg_log_error_hint("Try \"%s --help\" for more information.", progname);
2655  exit(1);
2656  }
2657  }
2658 
2659  /*
2660  * Sanity checks on WAL directory.
2661  */
2662  if (xlog_dir)
2663  {
2664  if (backup_target != NULL)
2665  {
2666  pg_log_error("WAL directory location cannot be specified along with a backup target");
2667  pg_log_error_hint("Try \"%s --help\" for more information.", progname);
2668  exit(1);
2669  }
2670  if (format != 'p')
2671  {
2672  pg_log_error("WAL directory location can only be specified in plain mode");
2673  pg_log_error_hint("Try \"%s --help\" for more information.", progname);
2674  exit(1);
2675  }
2676 
2677  /* clean up xlog directory name, check it's absolute */
2679  if (!is_absolute_path(xlog_dir))
2680  {
2681  pg_log_error("WAL directory location must be an absolute path");
2682  pg_log_error_hint("Try \"%s --help\" for more information.", progname);
2683  exit(1);
2684  }
2685  }
2686 
2687  /*
2688  * Sanity checks for progress reporting options.
2689  */
2690  if (showprogress && !estimatesize)
2691  {
2692  pg_log_error("%s and %s are incompatible options",
2693  "--progress", "--no-estimate-size");
2694  pg_log_error_hint("Try \"%s --help\" for more information.", progname);
2695  exit(1);
2696  }
2697 
2698  /*
2699  * Sanity checks for backup manifest options.
2700  */
2701  if (!manifest && manifest_checksums != NULL)
2702  {
2703  pg_log_error("%s and %s are incompatible options",
2704  "--no-manifest", "--manifest-checksums");
2705  pg_log_error_hint("Try \"%s --help\" for more information.", progname);
2706  exit(1);
2707  }
2708 
2710  {
2711  pg_log_error("%s and %s are incompatible options",
2712  "--no-manifest", "--manifest-force-encode");
2713  pg_log_error_hint("Try \"%s --help\" for more information.", progname);
2714  exit(1);
2715  }
2716 
2717  /* connection in replication mode to server */
2718  conn = GetConnection();
2719  if (!conn)
2720  {
2721  /* Error message already written in GetConnection() */
2722  exit(1);
2723  }
2724  atexit(disconnect_atexit);
2725 
2726 #ifndef WIN32
2727 
2728  /*
2729  * Trap SIGCHLD to be able to handle the WAL stream process exiting. There
2730  * is no SIGCHLD on Windows, there we rely on the background thread
2731  * setting the signal variable on unexpected but graceful exit. If the WAL
2732  * stream thread crashes on Windows it will bring down the entire process
2733  * as it's a thread, so there is nothing to catch should that happen. A
2734  * crash on UNIX will be caught by the signal handler.
2735  */
2737 #endif
2738 
2739  /*
2740  * Set umask so that directories/files are created with the same
2741  * permissions as directories/files in the source data directory.
2742  *
2743  * pg_mode_mask is set to owner-only by default and then updated in
2744  * GetConnection() where we get the mode from the server-side with
2745  * RetrieveDataDirCreatePerm() and then call SetDataDirectoryCreatePerm().
2746  */
2747  umask(pg_mode_mask);
2748 
2749  /* Backup manifests are supported in 13 and newer versions */
2751  manifest = false;
2752 
2753  /*
2754  * If an output directory was specified, verify that it exists, or create
2755  * it. Note that for a tar backup, an output directory of "-" means we are
2756  * writing to stdout, so do nothing in that case.
2757  */
2758  if (basedir != NULL && (format == 'p' || strcmp(basedir, "-") != 0))
2760 
2761  /* determine remote server's xlog segment size */
2762  if (!RetrieveWalSegSize(conn))
2763  exit(1);
2764 
2765  /* Create pg_wal symlink, if required */
2766  if (xlog_dir)
2767  {
2768  char *linkloc;
2769 
2771 
2772  /*
2773  * Form name of the place where the symlink must go. pg_xlog has been
2774  * renamed to pg_wal in post-10 clusters.
2775  */
2776  linkloc = psprintf("%s/%s", basedir,
2778  "pg_xlog" : "pg_wal");
2779 
2780 #ifdef HAVE_SYMLINK
2781  if (symlink(xlog_dir, linkloc) != 0)
2782  pg_fatal("could not create symbolic link \"%s\": %m", linkloc);
2783 #else
2784  pg_fatal("symlinks are not supported on this platform");
2785 #endif
2786  free(linkloc);
2787  }
2788 
2789  BaseBackup(compression_algorithm, compression_detail, compressloc,
2790  &client_compress);
2791 
2792  success = true;
2793  return 0;
2794 }
#define PG_TEXTDOMAIN(domain)
Definition: c.h:1212
void set_pglocale_pgservice(const char *argv0, const char *app)
Definition: exec.c:446
bool parse_compress_algorithm(char *name, pg_compress_algorithm *algorithm)
Definition: compression.c:40
void parse_compress_specification(pg_compress_algorithm algorithm, char *specification, pg_compress_specification *result)
Definition: compression.c:95
char * validate_compress_specification(pg_compress_specification *spec)
Definition: compression.c:250
PGconn * GetConnection(UserMapping *user, bool will_prep_stmt, PgFdwConnState **state)
Definition: connection.c:134
char * pg_strdup(const char *in)
Definition: fe_memutils.c:85
int pg_mode_mask
Definition: file_perm.c:25
int getopt_long(int argc, char *const argv[], const char *optstring, const struct option *longopts, int *longindex)
Definition: getopt_long.c:57
#define no_argument
Definition: getopt_long.h:24
#define required_argument
Definition: getopt_long.h:25
#define free(a)
Definition: header.h:65
void pg_logging_init(const char *argv0)
Definition: logging.c:83
#define pg_log_error_hint(...)
Definition: logging.h:112
const char * progname
Definition: main.c:50
bool option_parse_int(const char *optarg, const char *optname, int min_range, int max_range, int *result)
Definition: option_utils.c:50
static int32 parse_max_rate(char *src)
static bool create_slot
static void BaseBackup(char *compression_algorithm, char *compression_detail, CompressionLocation compressloc, pg_compress_specification *client_compress)
static void cleanup_directories_atexit(void)
static bool temp_replication_slot
#define MINIMUM_VERSION_FOR_MANIFESTS
Definition: pg_basebackup.c:98
static bool no_slot
static void usage(void)
static void tablespace_list_append(const char *arg)
static void disconnect_atexit(void)
#define MINIMUM_VERSION_FOR_PG_WAL
Definition: pg_basebackup.c:88
static void parse_compress_options(char *option, char **algorithm, char **detail, CompressionLocation *locationres)
static void sigchld_handler(SIGNAL_ARGS)
PGDLLIMPORT int optind
Definition: getopt.c:50
PGDLLIMPORT char * optarg
Definition: getopt.c:52
#define is_absolute_path(filename)
Definition: port.h:89
int pg_strcasecmp(const char *s1, const char *s2)
Definition: pgstrcasecmp.c:36
const char * get_progname(const char *argv0)
Definition: path.c:574
char * c
pqsigfunc pqsignal(int signum, pqsigfunc handler)
Definition: signal.c:180
int dbgetpassword
Definition: streamutil.c:52
bool RetrieveWalSegSize(PGconn *conn)
Definition: streamutil.c:271
char * dbhost
Definition: streamutil.c:48
char * dbport
Definition: streamutil.c:50
char * connection_string
Definition: streamutil.c:47
char * dbuser
Definition: streamutil.c:49
#define SIGCHLD
Definition: win32_port.h:177
#define symlink(oldpath, newpath)
Definition: win32_port.h:235

References pg_compress_specification::algorithm, Assert(), backup_target, BaseBackup(), basedir, canonicalize_path(), cleanup_directories_atexit(), COMPRESS_LOCATION_CLIENT, COMPRESS_LOCATION_SERVER, COMPRESS_LOCATION_UNSPECIFIED, compression_algorithm, conn, connection_string, create_slot, dbgetpassword, dbhost, dbport, dbuser, disconnect_atexit(), do_sync, estimatesize, exit(), fastcheckpoint, FETCH_WAL, format, found_existing_pgdata, found_existing_xlogdir, free, get_progname(), GetConnection(), getopt_long(), includewal, is_absolute_path, label, made_new_pgdata, made_new_xlogdir, manifest, manifest_checksums, manifest_force_encode, maxrate, MINIMUM_VERSION_FOR_MANIFESTS, MINIMUM_VERSION_FOR_PG_WAL, no_argument, no_slot, NO_WAL, noclean, optarg, optind, option_parse_int(), pg_compress_specification::options, parse_compress_algorithm(), parse_compress_options(), parse_compress_specification(), parse_max_rate(), PG_COMPRESSION_NONE, pg_fatal, pg_free(), pg_log_error, pg_log_error_hint, pg_logging_init(), pg_mode_mask, pg_strcasecmp(), pg_strdup(), PG_TEXTDOMAIN, PQserverVersion(), pqsignal(), progname, psprintf(), replication_slot, required_argument, RetrieveWalSegSize(), set_pglocale_pgservice(), showprogress, SIGCHLD, sigchld_handler(), standby_message_timeout, STREAM_WAL, success, symlink, tablespace_list_append(), temp_replication_slot, usage(), validate_compress_specification(), verbose, verify_checksums, verify_dir_is_empty_or_create(), writerecoveryconf, and xlog_dir.

◆ parse_compress_options()

static void parse_compress_options ( char *  option,
char **  algorithm,
char **  detail,
CompressionLocation locationres 
)
static

Definition at line 968 of file pg_basebackup.c.

970 {
971  char *sep;
972  char *endp;
973 
974  /*
975  * Check whether the compression specification consists of a bare integer.
976  *
977  * If so, for backward compatibility, assume gzip.
978  */
979  (void) strtol(option, &endp, 10);
980  if (*endp == '\0')
981  {
982  *locationres = COMPRESS_LOCATION_UNSPECIFIED;
983  *algorithm = pstrdup("gzip");
984  *detail = pstrdup(option);
985  return;
986  }
987 
988  /* Strip off any "client-" or "server-" prefix. */
989  if (strncmp(option, "server-", 7) == 0)
990  {
991  *locationres = COMPRESS_LOCATION_SERVER;
992  option += 7;
993  }
994  else if (strncmp(option, "client-", 7) == 0)
995  {
996  *locationres = COMPRESS_LOCATION_CLIENT;
997  option += 7;
998  }
999  else
1000  *locationres = COMPRESS_LOCATION_UNSPECIFIED;
1001 
1002  /*
1003  * Check whether there is a compression detail following the algorithm
1004  * name.
1005  */
1006  sep = strchr(option, ':');
1007  if (sep == NULL)
1008  {
1009  *algorithm = pstrdup(option);
1010  *detail = NULL;
1011  }
1012  else
1013  {
1014  char *alg;
1015 
1016  alg = palloc((sep - option) + 1);
1017  memcpy(alg, option, sep - option);
1018  alg[sep - option] = '\0';
1019 
1020  *algorithm = alg;
1021  *detail = pstrdup(sep + 1);
1022  }
1023 }
char * pstrdup(const char *in)
Definition: mcxt.c:1305
void * palloc(Size size)
Definition: mcxt.c:1068

References COMPRESS_LOCATION_CLIENT, COMPRESS_LOCATION_SERVER, COMPRESS_LOCATION_UNSPECIFIED, palloc(), and pstrdup().

Referenced by main().

◆ parse_max_rate()

static int32 parse_max_rate ( char *  src)
static

Definition at line 883 of file pg_basebackup.c.

884 {
885  double result;
886  char *after_num;
887  char *suffix = NULL;
888 
889  errno = 0;
890  result = strtod(src, &after_num);
891  if (src == after_num)
892  pg_fatal("transfer rate \"%s\" is not a valid value", src);
893  if (errno != 0)
894  pg_fatal("invalid transfer rate \"%s\": %m", src);
895 
896  if (result <= 0)
897  {
898  /*
899  * Reject obviously wrong values here.
900  */
901  pg_fatal("transfer rate must be greater than zero");
902  }
903 
904  /*
905  * Evaluate suffix, after skipping over possible whitespace. Lack of
906  * suffix means kilobytes.
907  */
908  while (*after_num != '\0' && isspace((unsigned char) *after_num))
909  after_num++;
910 
911  if (*after_num != '\0')
912  {
913  suffix = after_num;
914  if (*after_num == 'k')
915  {
916  /* kilobyte is the expected unit. */
917  after_num++;
918  }
919  else if (*after_num == 'M')
920  {
921  after_num++;
922  result *= 1024.0;
923  }
924  }
925 
926  /* The rest can only consist of white space. */
927  while (*after_num != '\0' && isspace((unsigned char) *after_num))
928  after_num++;
929 
930  if (*after_num != '\0')
931  pg_fatal("invalid --max-rate unit: \"%s\"", suffix);
932 
933  /* Valid integer? */
934  if ((uint64) result != (uint64) ((uint32) result))
935  pg_fatal("transfer rate \"%s\" exceeds integer range", src);
936 
937  /*
938  * The range is checked on the server side too, but avoid the server
939  * connection if a nonsensical value was passed.
940  */
941  if (result < MAX_RATE_LOWER || result > MAX_RATE_UPPER)
942  pg_fatal("transfer rate \"%s\" is out of range", src);
943 
944  return (int32) result;
945 }
#define MAX_RATE_UPPER
Definition: basebackup.h:21
signed int int32
Definition: c.h:429

References MAX_RATE_UPPER, and pg_fatal.

Referenced by main().

◆ progress_report()

static void progress_report ( int  tablespacenum,
bool  force,
bool  finished 
)
static

Definition at line 798 of file pg_basebackup.c.

799 {
800  int percent;
801  char totaldone_str[32];
802  char totalsize_str[32];
803  pg_time_t now;
804 
805  if (!showprogress)
806  return;
807 
808  now = time(NULL);
809  if (now == last_progress_report && !force && !finished)
810  return; /* Max once per second */
811 
813  percent = totalsize_kb ? (int) ((totaldone / 1024) * 100 / totalsize_kb) : 0;
814 
815  /*
816  * Avoid overflowing past 100% or the full size. This may make the total
817  * size number change as we approach the end of the backup (the estimate
818  * will always be wrong if WAL is included), but that's better than having
819  * the done column be bigger than the total.
820  */
821  if (percent > 100)
822  percent = 100;
823  if (totaldone / 1024 > totalsize_kb)
824  totalsize_kb = totaldone / 1024;
825 
826  snprintf(totaldone_str, sizeof(totaldone_str), UINT64_FORMAT,
827  totaldone / 1024);
828  snprintf(totalsize_str, sizeof(totalsize_str), UINT64_FORMAT, totalsize_kb);
829 
830 #define VERBOSE_FILENAME_LENGTH 35
831  if (verbose)
832  {
833  if (!progress_filename)
834 
835  /*
836  * No filename given, so clear the status line (used for last
837  * call)
838  */
839  fprintf(stderr,
840  ngettext("%*s/%s kB (100%%), %d/%d tablespace %*s",
841  "%*s/%s kB (100%%), %d/%d tablespaces %*s",
843  (int) strlen(totalsize_str),
844  totaldone_str, totalsize_str,
845  tablespacenum, tablespacecount,
846  VERBOSE_FILENAME_LENGTH + 5, "");
847  else
848  {
849  bool truncate = (strlen(progress_filename) > VERBOSE_FILENAME_LENGTH);
850 
851  fprintf(stderr,
852  ngettext("%*s/%s kB (%d%%), %d/%d tablespace (%s%-*.*s)",
853  "%*s/%s kB (%d%%), %d/%d tablespaces (%s%-*.*s)",
855  (int) strlen(totalsize_str),
856  totaldone_str, totalsize_str, percent,
857  tablespacenum, tablespacecount,
858  /* Prefix with "..." if we do leading truncation */
859  truncate ? "..." : "",
862  /* Truncate filename at beginning if it's too long */
864  }
865  }
866  else
867  fprintf(stderr,
868  ngettext("%*s/%s kB (%d%%), %d/%d tablespace",
869  "%*s/%s kB (%d%%), %d/%d tablespaces",
871  (int) strlen(totalsize_str),
872  totaldone_str, totalsize_str, percent,
873  tablespacenum, tablespacecount);
874 
875  /*
876  * Stay on the same line if reporting to a terminal and we're not done
877  * yet.
878  */
879  fputc((!finished && isatty(fileno(stderr))) ? '\r' : '\n', stderr);
880 }
Datum now(PG_FUNCTION_ARGS)
Definition: timestamp.c:1538
#define ngettext(s, p, n)
Definition: c.h:1179
#define UINT64_FORMAT
Definition: c.h:484
static char * progress_filename
static pg_time_t last_progress_report
#define VERBOSE_FILENAME_LENGTH
int64 pg_time_t
Definition: pgtime.h:23

References fprintf, last_progress_report, ngettext, now(), progress_filename, showprogress, snprintf, tablespacecount, totaldone, totalsize_kb, UINT64_FORMAT, verbose, and VERBOSE_FILENAME_LENGTH.

Referenced by BaseBackup(), ReceiveArchiveStreamChunk(), ReceiveTarCopyChunk(), and ReceiveTarFile().

◆ progress_update_filename()

static void progress_update_filename ( const char *  filename)
static

Definition at line 773 of file pg_basebackup.c.

774 {
775  /* We needn't maintain this variable if not doing verbose reports. */
776  if (showprogress && verbose)
777  {
778  if (progress_filename)
780  if (filename)
782  else
783  progress_filename = NULL;
784  }
785 }

References filename, free, pg_strdup(), progress_filename, showprogress, and verbose.

Referenced by BaseBackup(), CreateBackupStreamer(), and ReceiveTarFile().

◆ reached_end_position()

static bool reached_end_position ( XLogRecPtr  segendpos,
uint32  timeline,
bool  segment_finished 
)
static

Definition at line 443 of file pg_basebackup.c.

445 {
446  if (!has_xlogendptr)
447  {
448 #ifndef WIN32
449  fd_set fds;
450  struct timeval tv;
451  int r;
452 
453  /*
454  * Don't have the end pointer yet - check our pipe to see if it has
455  * been sent yet.
456  */
457  FD_ZERO(&fds);
458  FD_SET(bgpipe[0], &fds);
459 
460  MemSet(&tv, 0, sizeof(tv));
461 
462  r = select(bgpipe[0] + 1, &fds, NULL, NULL, &tv);
463  if (r == 1)
464  {
465  char xlogend[64];
466  uint32 hi,
467  lo;
468 
469  MemSet(xlogend, 0, sizeof(xlogend));
470  r = read(bgpipe[0], xlogend, sizeof(xlogend) - 1);
471  if (r < 0)
472  pg_fatal("could not read from ready pipe: %m");
473 
474  if (sscanf(xlogend, "%X/%X", &hi, &lo) != 2)
475  pg_fatal("could not parse write-ahead log location \"%s\"",
476  xlogend);
477  xlogendptr = ((uint64) hi) << 32 | lo;
478  has_xlogendptr = 1;
479 
480  /*
481  * Fall through to check if we've reached the point further
482  * already.
483  */
484  }
485  else
486  {
487  /*
488  * No data received on the pipe means we don't know the end
489  * position yet - so just say it's not time to stop yet.
490  */
491  return false;
492  }
493 #else
494 
495  /*
496  * On win32, has_xlogendptr is set by the main thread, so if it's not
497  * set here, we just go back and wait until it shows up.
498  */
499  return false;
500 #endif
501  }
502 
503  /*
504  * At this point we have an end pointer, so compare it to the current
505  * position to figure out if it's time to stop.
506  */
507  if (segendpos >= xlogendptr)
508  return true;
509 
510  /*
511  * Have end pointer, but haven't reached it yet - so tell the caller to
512  * keep streaming.
513  */
514  return false;
515 }
#define read(a, b, c)
Definition: win32.h:13
#define select(n, r, w, e, timeout)
Definition: win32_port.h:474

References bgpipe, has_xlogendptr, MemSet, pg_fatal, read, select, and xlogendptr.

Referenced by LogStreamerMain().

◆ ReceiveArchiveStream()

static void ReceiveArchiveStream ( PGconn conn,
pg_compress_specification compress 
)
static

Definition at line 1291 of file pg_basebackup.c.

1292 {
1294 
1295  /* Set up initial state. */
1296  memset(&state, 0, sizeof(state));
1297  state.tablespacenum = -1;
1298  state.compress = compress;
1299 
1300  /* All the real work happens in ReceiveArchiveStreamChunk. */
1302 
1303  /* If we wrote the backup manifest to a file, close the file. */
1304  if (state.manifest_file !=NULL)
1305  {
1306  fclose(state.manifest_file);
1307  state.manifest_file = NULL;
1308  }
1309 
1310  /*
1311  * If we buffered the backup manifest in order to inject it into the
1312  * output tarfile, do that now.
1313  */
1314  if (state.manifest_inject_streamer != NULL &&
1315  state.manifest_buffer != NULL)
1316  {
1317  bbstreamer_inject_file(state.manifest_inject_streamer,
1318  "backup_manifest",
1319  state.manifest_buffer->data,
1320  state.manifest_buffer->len);
1321  destroyPQExpBuffer(state.manifest_buffer);
1322  state.manifest_buffer = NULL;
1323  }
1324 
1325  /* If there's still an archive in progress, end processing. */
1326  if (state.streamer != NULL)
1327  {
1328  bbstreamer_finalize(state.streamer);
1329  bbstreamer_free(state.streamer);
1330  state.streamer = NULL;
1331  }
1332 }
static void bbstreamer_finalize(bbstreamer *streamer)
Definition: bbstreamer.h:136
static void bbstreamer_free(bbstreamer *streamer)
Definition: bbstreamer.h:144
void bbstreamer_inject_file(bbstreamer *streamer, char *pathname, char *data, int len)
static void ReceiveArchiveStreamChunk(size_t r, char *copybuf, void *callback_data)
static void ReceiveCopyData(PGconn *conn, WriteDataCallback callback, void *callback_data)
Definition: regguts.h:318

References bbstreamer_finalize(), bbstreamer_free(), bbstreamer_inject_file(), conn, destroyPQExpBuffer(), ReceiveArchiveStreamChunk(), and ReceiveCopyData().

Referenced by BaseBackup().

◆ ReceiveArchiveStreamChunk()

static void ReceiveArchiveStreamChunk ( size_t  r,
char *  copybuf,
void *  callback_data 
)
static

Definition at line 1339 of file pg_basebackup.c.

1340 {
1341  ArchiveStreamState *state = callback_data;
1342  size_t cursor = 0;
1343 
1344  /* Each CopyData message begins with a type byte. */
1345  switch (GetCopyDataByte(r, copybuf, &cursor))
1346  {
1347  case 'n':
1348  {
1349  /* New archive. */
1350  char *archive_name;
1351  char *spclocation;
1352 
1353  /*
1354  * We force a progress report at the end of each tablespace. A
1355  * new tablespace starts when the previous one ends, except in
1356  * the case of the very first one.
1357  */
1358  if (++state->tablespacenum > 0)
1359  progress_report(state->tablespacenum, true, false);
1360 
1361  /* Sanity check. */
1362  if (state->manifest_buffer != NULL ||
1363  state->manifest_file !=NULL)
1364  pg_fatal("archives should precede manifest");
1365 
1366  /* Parse the rest of the CopyData message. */
1367  archive_name = GetCopyDataString(r, copybuf, &cursor);
1368  spclocation = GetCopyDataString(r, copybuf, &cursor);
1370 
1371  /*
1372  * Basic sanity checks on the archive name: it shouldn't be
1373  * empty, it shouldn't start with a dot, and it shouldn't
1374  * contain a path separator.
1375  */
1376  if (archive_name[0] == '\0' || archive_name[0] == '.' ||
1377  strchr(archive_name, '/') != NULL ||
1378  strchr(archive_name, '\\') != NULL)
1379  pg_fatal("invalid archive name: \"%s\"",
1380  archive_name);
1381 
1382  /*
1383  * An empty spclocation is treated as NULL. We expect this
1384  * case to occur for the data directory itself, but not for
1385  * any archives that correspond to tablespaces.
1386  */
1387  if (spclocation[0] == '\0')
1388  spclocation = NULL;
1389 
1390  /* End processing of any prior archive. */
1391  if (state->streamer != NULL)
1392  {
1393  bbstreamer_finalize(state->streamer);
1394  bbstreamer_free(state->streamer);
1395  state->streamer = NULL;
1396  }
1397 
1398  /*
1399  * Create an appropriate backup streamer, unless a backup
1400  * target was specified. In that case, it's up to the server
1401  * to put the backup wherever it needs to go.
1402  */
1403  if (backup_target == NULL)
1404  {
1405  /*
1406  * We know that recovery GUCs are supported, because this
1407  * protocol can only be used on v15+.
1408  */
1409  state->streamer =
1410  CreateBackupStreamer(archive_name,
1411  spclocation,
1412  &state->manifest_inject_streamer,
1413  true, false,
1414  state->compress);
1415  }
1416  break;
1417  }
1418 
1419  case 'd':
1420  {
1421  /* Archive or manifest data. */
1422  if (state->manifest_buffer != NULL)
1423  {
1424  /* Manifest data, buffer in memory. */
1425  appendPQExpBuffer(state->manifest_buffer, copybuf + 1,
1426  r - 1);
1427  }
1428  else if (state->manifest_file !=NULL)
1429  {
1430  /* Manifest data, write to disk. */
1431  if (fwrite(copybuf + 1, r - 1, 1,
1432  state->manifest_file) != 1)
1433  {
1434  /*
1435  * If fwrite() didn't set errno, assume that the
1436  * problem is that we're out of disk space.
1437  */
1438  if (errno == 0)
1439  errno = ENOSPC;
1440  pg_fatal("could not write to file \"%s\": %m",
1441  state->manifest_filename);
1442  }
1443  }
1444  else if (state->streamer != NULL)
1445  {
1446  /* Archive data. */
1447  bbstreamer_content(state->streamer, NULL, copybuf + 1,
1448  r - 1, BBSTREAMER_UNKNOWN);
1449  }
1450  else
1451  pg_fatal("unexpected payload data");
1452  break;
1453  }
1454 
1455  case 'p':
1456  {
1457  /*
1458  * Progress report.
1459  *
1460  * The remainder of the message is expected to be an 8-byte
1461  * count of bytes completed.
1462  */
1465 
1466  /*
1467  * The server shouldn't send progress report messages too
1468  * often, so we force an update each time we receive one.
1469  */
1470  progress_report(state->tablespacenum, true, false);
1471  break;
1472  }
1473 
1474  case 'm':
1475  {
1476  /*
1477  * Manifest data will be sent next. This message is not
1478  * expected to have any further payload data.
1479  */
1481 
1482  /*
1483  * If a backup target was specified, figuring out where to put
1484  * the manifest is the server's problem. Otherwise, we need to
1485  * deal with it.
1486  */
1487  if (backup_target == NULL)
1488  {
1489  /*
1490  * If we're supposed inject the manifest into the archive,
1491  * we prepare to buffer it in memory; otherwise, we
1492  * prepare to write it to a temporary file.
1493  */
1494  if (state->manifest_inject_streamer != NULL)
1495  state->manifest_buffer = createPQExpBuffer();
1496  else
1497  {
1498  snprintf(state->manifest_filename,
1499  sizeof(state->manifest_filename),
1500  "%s/backup_manifest.tmp", basedir);
1501  state->manifest_file =
1502  fopen(state->manifest_filename, "wb");
1503  if (state->manifest_file == NULL)
1504  pg_fatal("could not create file \"%s\": %m",
1505  state->manifest_filename);
1506  }
1507  }
1508  break;
1509  }
1510 
1511  default:
1513  break;
1514  }
1515 }
static void bbstreamer_content(bbstreamer *streamer, bbstreamer_member *member, const char *data, int len, bbstreamer_archive_context context)
Definition: bbstreamer.h:126
@ BBSTREAMER_UNKNOWN
Definition: bbstreamer.h:55
static char * GetCopyDataString(size_t r, char *copybuf, size_t *cursor)
static void GetCopyDataEnd(size_t r, char *copybuf, size_t cursor)
static bbstreamer * CreateBackupStreamer(char *archive_name, char *spclocation, bbstreamer **manifest_inject_streamer_p, bool is_recovery_guc_supported, bool expect_unterminated_tarfile, pg_compress_specification *compress)
static char GetCopyDataByte(size_t r, char *copybuf, size_t *cursor)
static uint64 GetCopyDataUInt64(size_t r, char *copybuf, size_t *cursor)
PQExpBuffer createPQExpBuffer(void)
Definition: pqexpbuffer.c:74
void appendPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:267

References appendPQExpBuffer(), backup_target, basedir, bbstreamer_content(), bbstreamer_finalize(), bbstreamer_free(), BBSTREAMER_UNKNOWN, copybuf, CreateBackupStreamer(), createPQExpBuffer(), GetCopyDataByte(), GetCopyDataEnd(), GetCopyDataString(), GetCopyDataUInt64(), pg_fatal, progress_report(), ReportCopyDataParseError(), snprintf, and totaldone.

Referenced by ReceiveArchiveStream().

◆ ReceiveBackupManifest()

static void ReceiveBackupManifest ( PGconn conn)
static

Definition at line 1705 of file pg_basebackup.c.

1706 {
1708 
1709  snprintf(state.filename, sizeof(state.filename),
1710  "%s/backup_manifest.tmp", basedir);
1711  state.file = fopen(state.filename, "wb");
1712  if (state.file == NULL)
1713  pg_fatal("could not create file \"%s\": %m", state.filename);
1714 
1716 
1717  fclose(state.file);
1718 }
static void ReceiveBackupManifestChunk(size_t r, char *copybuf, void *callback_data)

References basedir, conn, pg_fatal, ReceiveBackupManifestChunk(), ReceiveCopyData(), and snprintf.

Referenced by BaseBackup().

◆ ReceiveBackupManifestChunk()

static void ReceiveBackupManifestChunk ( size_t  r,
char *  copybuf,
void *  callback_data 
)
static

Definition at line 1724 of file pg_basebackup.c.

1725 {
1726  WriteManifestState *state = callback_data;
1727 
1728  errno = 0;
1729  if (fwrite(copybuf, r, 1, state->file) != 1)
1730  {
1731  /* if write didn't set errno, assume problem is no disk space */
1732  if (errno == 0)
1733  errno = ENOSPC;
1734  pg_fatal("could not write to file \"%s\": %m", state->filename);
1735  }
1736 }

References copybuf, and pg_fatal.

Referenced by ReceiveBackupManifest().

◆ ReceiveBackupManifestInMemory()

static void ReceiveBackupManifestInMemory ( PGconn conn,
PQExpBuffer  buf 
)
static

Definition at line 1742 of file pg_basebackup.c.

1743 {
1745 }
static void ReceiveBackupManifestInMemoryChunk(size_t r, char *copybuf, void *callback_data)

References buf, conn, ReceiveBackupManifestInMemoryChunk(), and ReceiveCopyData().

Referenced by ReceiveTarFile().

◆ ReceiveBackupManifestInMemoryChunk()

static void ReceiveBackupManifestInMemoryChunk ( size_t  r,
char *  copybuf,
void *  callback_data 
)
static

Definition at line 1751 of file pg_basebackup.c.

1753 {
1754  PQExpBuffer buf = callback_data;
1755 
1757 }

References appendPQExpBuffer(), buf, and copybuf.

Referenced by ReceiveBackupManifestInMemory().

◆ ReceiveCopyData()

static void ReceiveCopyData ( PGconn conn,
WriteDataCallback  callback,
void *  callback_data 
)
static

Definition at line 1030 of file pg_basebackup.c.

1032 {
1033  PGresult *res;
1034 
1035  /* Get the COPY data stream. */
1036  res = PQgetResult(conn);
1038  pg_fatal("could not get COPY data stream: %s",
1039  PQerrorMessage(conn));
1040  PQclear(res);
1041 
1042  /* Loop over chunks until done. */
1043  while (1)
1044  {
1045  int r;
1046  char *copybuf;
1047 
1048  r = PQgetCopyData(conn, &copybuf, 0);
1049  if (r == -1)
1050  {
1051  /* End of chunk. */
1052  break;
1053  }
1054  else if (r == -2)
1055  pg_fatal("could not read COPY data: %s",
1056  PQerrorMessage(conn));
1057 
1058  if (bgchild_exited)
1059  pg_fatal("background process terminated unexpectedly");
1060 
1061  (*callback) (r, copybuf, callback_data);
1062 
1063  PQfreemem(copybuf);
1064  }
1065 }
void PQfreemem(void *ptr)
Definition: fe-exec.c:3891
int PQgetCopyData(PGconn *conn, char **buffer, int async)
Definition: fe-exec.c:2751
@ PGRES_COPY_OUT
Definition: libpq-fe.h:103

References bgchild_exited, conn, copybuf, pg_fatal, PGRES_COPY_OUT, PQclear(), PQerrorMessage(), PQfreemem(), PQgetCopyData(), PQgetResult(), PQresultStatus(), and res.

Referenced by ReceiveArchiveStream(), ReceiveBackupManifest(), ReceiveBackupManifestInMemory(), and ReceiveTarFile().

◆ ReceiveTarCopyChunk()

static void ReceiveTarCopyChunk ( size_t  r,
char *  copybuf,
void *  callback_data 
)
static

Definition at line 1669 of file pg_basebackup.c.

1670 {
1671  WriteTarState *state = callback_data;
1672 
1673  bbstreamer_content(state->streamer, NULL, copybuf, r, BBSTREAMER_UNKNOWN);
1674 
1675  totaldone += r;
1676  progress_report(state->tablespacenum, false, false);
1677 }

References bbstreamer_content(), BBSTREAMER_UNKNOWN, copybuf, progress_report(), and totaldone.

Referenced by ReceiveTarFile().

◆ ReceiveTarFile()

static void ReceiveTarFile ( PGconn conn,
char *  archive_name,
char *  spclocation,
bool  tablespacenum,
pg_compress_specification compress 
)
static

Definition at line 1606 of file pg_basebackup.c.

1608 {
1610  bbstreamer *manifest_inject_streamer;
1611  bool is_recovery_guc_supported;
1612  bool expect_unterminated_tarfile;
1613 
1614  /* Pass all COPY data through to the backup streamer. */
1615  memset(&state, 0, sizeof(state));
1616  is_recovery_guc_supported =
1618  expect_unterminated_tarfile =
1620  state.streamer = CreateBackupStreamer(archive_name, spclocation,
1621  &manifest_inject_streamer,
1622  is_recovery_guc_supported,
1623  expect_unterminated_tarfile,
1624  compress);
1625  state.tablespacenum = tablespacenum;
1628 
1629  /*
1630  * The decision as to whether we need to inject the backup manifest into
1631  * the output at this stage is made by CreateBackupStreamer; if that is
1632  * needed, manifest_inject_streamer will be non-NULL; otherwise, it will
1633  * be NULL.
1634  */
1635  if (manifest_inject_streamer != NULL)
1636  {
1638 
1639  /* Slurp the entire backup manifest into a buffer. */
1640  initPQExpBuffer(&buf);
1643  pg_fatal("out of memory");
1644 
1645  /* Inject it into the output tarfile. */
1646  bbstreamer_inject_file(manifest_inject_streamer, "backup_manifest",
1647  buf.data, buf.len);
1648 
1649  /* Free memory. */
1650  termPQExpBuffer(&buf);
1651  }
1652 
1653  /* Cleanup. */
1654  bbstreamer_finalize(state.streamer);
1655  bbstreamer_free(state.streamer);
1656 
1657  progress_report(tablespacenum, true, false);
1658 
1659  /*
1660  * Do not sync the resulting tar file yet, all files are synced once at
1661  * the end.
1662  */
1663 }
static void ReceiveTarCopyChunk(size_t r, char *copybuf, void *callback_data)
#define MINIMUM_VERSION_FOR_TERMINATED_TARFILE
static void ReceiveBackupManifestInMemory(PGconn *conn, PQExpBuffer buf)
void termPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:131
#define PQExpBufferDataBroken(buf)
Definition: pqexpbuffer.h:67
#define MINIMUM_VERSION_FOR_RECOVERY_GUC
Definition: recovery_gen.h:21

References bbstreamer_finalize(), bbstreamer_free(), bbstreamer_inject_file(), buf, conn, CreateBackupStreamer(), initPQExpBuffer(), MINIMUM_VERSION_FOR_RECOVERY_GUC, MINIMUM_VERSION_FOR_TERMINATED_TARFILE, pg_fatal, PQExpBufferDataBroken, PQserverVersion(), progress_report(), progress_update_filename(), ReceiveBackupManifestInMemory(), ReceiveCopyData(), ReceiveTarCopyChunk(), and termPQExpBuffer().

Referenced by BaseBackup().

◆ ReportCopyDataParseError()

static void ReportCopyDataParseError ( size_t  r,
char *  copybuf 
)
static

Definition at line 1591 of file pg_basebackup.c.

1592 {
1593  if (r == 0)
1594  pg_fatal("empty COPY message");
1595  else
1596  pg_fatal("malformed COPY message of type %d, length %zu",
1597  copybuf[0], r);
1598 }

References copybuf, and pg_fatal.

Referenced by GetCopyDataByte(), GetCopyDataEnd(), GetCopyDataString(), GetCopyDataUInt64(), and ReceiveArchiveStreamChunk().

◆ sigchld_handler()

static void sigchld_handler ( SIGNAL_ARGS  )
static

Definition at line 292 of file pg_basebackup.c.

293 {
294  bgchild_exited = true;
295 }

References bgchild_exited.

Referenced by main().

◆ StartLogStreamer()

static void StartLogStreamer ( char *  startpos,
uint32  timeline,
char *  sysidentifier,
pg_compress_algorithm  wal_compress_algorithm,
int  wal_compress_level 
)
static

Definition at line 605 of file pg_basebackup.c.

608 {
609  logstreamer_param *param;
610  uint32 hi,
611  lo;
612  char statusdir[MAXPGPATH];
613 
614  param = pg_malloc0(sizeof(logstreamer_param));
615  param->timeline = timeline;
616  param->sysidentifier = sysidentifier;
617  param->wal_compress_algorithm = wal_compress_algorithm;
618  param->wal_compress_level = wal_compress_level;
619 
620  /* Convert the starting position */
621  if (sscanf(startpos, "%X/%X", &hi, &lo) != 2)
622  pg_fatal("could not parse write-ahead log location \"%s\"",
623  startpos);
624  param->startptr = ((uint64) hi) << 32 | lo;
625  /* Round off to even segment position */
626  param->startptr -= XLogSegmentOffset(param->startptr, WalSegSz);
627 
628 #ifndef WIN32
629  /* Create our background pipe */
630  if (pipe(bgpipe) < 0)
631  pg_fatal("could not create pipe for background process: %m");
632 #endif
633 
634  /* Get a second connection */
635  param->bgconn = GetConnection();
636  if (!param->bgconn)
637  /* Error message already written in GetConnection() */
638  exit(1);
639 
640  /* In post-10 cluster, pg_xlog has been renamed to pg_wal */
641  snprintf(param->xlog, sizeof(param->xlog), "%s/%s",
642  basedir,
644  "pg_xlog" : "pg_wal");
645 
646  /* Temporary replication slots are only supported in 10 and newer */
648  temp_replication_slot = false;
649 
650  /*
651  * Create replication slot if requested
652  */
654  replication_slot = psprintf("pg_basebackup_%d", (int) PQbackendPID(param->bgconn));
656  {
657  if (!CreateReplicationSlot(param->bgconn, replication_slot, NULL,
658  temp_replication_slot, true, true, false, false))
659  exit(1);
660 
661  if (verbose)
662  {
664  pg_log_info("created temporary replication slot \"%s\"",
666  else
667  pg_log_info("created replication slot \"%s\"",
669  }
670  }
671 
672  if (format == 'p')
673  {
674  /*
675  * Create pg_wal/archive_status or pg_xlog/archive_status (and thus
676  * pg_wal or pg_xlog) depending on the target server so we can write
677  * to basedir/pg_wal or basedir/pg_xlog as the directory entry in the
678  * tar file may arrive later.
679  */
680  snprintf(statusdir, sizeof(statusdir), "%s/%s/archive_status",
681  basedir,
683  "pg_xlog" : "pg_wal");
684 
685  if (pg_mkdir_p(statusdir, pg_dir_create_mode) != 0 && errno != EEXIST)
686  pg_fatal("could not create directory \"%s\": %m", statusdir);
687  }
688 
689  /*
690  * Start a child process and tell it to start streaming. On Unix, this is
691  * a fork(). On Windows, we create a thread.
692  */
693 #ifndef WIN32
694  bgchild = fork();
695  if (bgchild == 0)
696  {
697  int ret;
698 
699  /* in child process */
700  ret = LogStreamerMain(param);
701 
702  /* temp debugging aid to analyze 019_replslot_limit failures */
703  if (verbose)
704  pg_log_info("log streamer with pid %d exiting", getpid());
705 
706  exit(ret);
707  }
708  else if (bgchild < 0)
709  pg_fatal("could not create background process: %m");
710 
711  /*
712  * Else we are in the parent process and all is well.
713  */
714  atexit(kill_bgchild_atexit);
715 #else /* WIN32 */
716  bgchild = _beginthreadex(NULL, 0, (void *) LogStreamerMain, param, 0, NULL);
717  if (bgchild == 0)
718  pg_fatal("could not create background thread: %m");
719 #endif
720 }
int PQbackendPID(const PGconn *conn)
Definition: fe-connect.c:6942
void * pg_malloc0(size_t size)
Definition: fe_memutils.c:53
int pg_dir_create_mode
Definition: file_perm.c:18
#define MINIMUM_VERSION_FOR_TEMP_SLOTS
Definition: pg_basebackup.c:93
static int LogStreamerMain(logstreamer_param *param)
static void kill_bgchild_atexit(void)
int pg_mkdir_p(char *path, int omode)
Definition: pgmkdirp.c:57
uint32 WalSegSz
Definition: streamutil.c:34
static void CreateReplicationSlot(CreateReplicationSlotCmd *cmd)
Definition: walsender.c:1047
#define XLogSegmentOffset(xlogptr, wal_segsz_bytes)

References basedir, bgchild, logstreamer_param::bgconn, bgpipe, conn, create_slot, CreateReplicationSlot(), exit(), format, GetConnection(), kill_bgchild_atexit(), LogStreamerMain(), MAXPGPATH, MINIMUM_VERSION_FOR_PG_WAL, MINIMUM_VERSION_FOR_TEMP_SLOTS, pg_dir_create_mode, pg_fatal, pg_log_info, pg_malloc0(), pg_mkdir_p(), PQbackendPID(), PQserverVersion(), psprintf(), replication_slot, snprintf, startpos, logstreamer_param::startptr, logstreamer_param::sysidentifier, temp_replication_slot, logstreamer_param::timeline, verbose, logstreamer_param::wal_compress_algorithm, logstreamer_param::wal_compress_level, WalSegSz, logstreamer_param::xlog, and XLogSegmentOffset.

Referenced by BaseBackup().

◆ tablespace_list_append()

static void tablespace_list_append ( const char *  arg)
static

Definition at line 315 of file pg_basebackup.c.

316 {
318  char *dst;
319  char *dst_ptr;
320  const char *arg_ptr;
321 
322  dst_ptr = dst = cell->old_dir;
323  for (arg_ptr = arg; *arg_ptr; arg_ptr++)
324  {
325  if (dst_ptr - dst >= MAXPGPATH)
326  pg_fatal("directory name too long");
327 
328  if (*arg_ptr == '\\' && *(arg_ptr + 1) == '=')
329  ; /* skip backslash escaping = */
330  else if (*arg_ptr == '=' && (arg_ptr == arg || *(arg_ptr - 1) != '\\'))
331  {
332  if (*cell->new_dir)
333  pg_fatal("multiple \"=\" signs in tablespace mapping");
334  else
335  dst = dst_ptr = cell->new_dir;
336  }
337  else
338  *dst_ptr++ = *arg_ptr;
339  }
340 
341  if (!*cell->old_dir || !*cell->new_dir)
342  pg_fatal("invalid tablespace mapping format \"%s\", must be \"OLDDIR=NEWDIR\"", arg);
343 
344  /*
345  * This check isn't absolutely necessary. But all tablespaces are created
346  * with absolute directories, so specifying a non-absolute path here would
347  * just never match, possibly confusing users. It's also good to be
348  * consistent with the new_dir check.
349  */
350  if (!is_absolute_path(cell->old_dir))
351  pg_fatal("old directory is not an absolute path in tablespace mapping: %s",
352  cell->old_dir);
353 
354  if (!is_absolute_path(cell->new_dir))
355  pg_fatal("new directory is not an absolute path in tablespace mapping: %s",
356  cell->new_dir);
357 
358  /*
359  * Comparisons done with these values should involve similarly
360  * canonicalized path values. This is particularly sensitive on Windows
361  * where path values may not necessarily use Unix slashes.
362  */
363  canonicalize_path(cell->old_dir);
364  canonicalize_path(cell->new_dir);
365 
366  if (tablespace_dirs.tail)
367  tablespace_dirs.tail->next = cell;
368  else
369  tablespace_dirs.head = cell;
370  tablespace_dirs.tail = cell;
371 }
void * arg
TablespaceListCell * tail
Definition: pg_basebackup.c:55

References arg, canonicalize_path(), TablespaceList::head, is_absolute_path, MAXPGPATH, TablespaceListCell::new_dir, TablespaceListCell::next, TablespaceListCell::old_dir, pg_fatal, pg_malloc0(), tablespace_dirs, and TablespaceList::tail.

Referenced by main().

◆ usage()

static void usage ( void  )
static

Definition at line 375 of file pg_basebackup.c.

376 {
377  printf(_("%s takes a base backup of a running PostgreSQL server.\n\n"),
378  progname);
379  printf(_("Usage:\n"));
380  printf(_(" %s [OPTION]...\n"), progname);
381  printf(_("\nOptions controlling the output:\n"));
382  printf(_(" -D, --pgdata=DIRECTORY receive base backup into directory\n"));
383  printf(_(" -F, --format=p|t output format (plain (default), tar)\n"));
384  printf(_(" -r, --max-rate=RATE maximum transfer rate to transfer data directory\n"
385  " (in kB/s, or use suffix \"k\" or \"M\")\n"));
386  printf(_(" -R, --write-recovery-conf\n"
387  " write configuration for replication\n"));
388  printf(_(" -t, --target=TARGET[:DETAIL]\n"
389  " backup target (if other than client)\n"));
390  printf(_(" -T, --tablespace-mapping=OLDDIR=NEWDIR\n"
391  " relocate tablespace in OLDDIR to NEWDIR\n"));
392  printf(_(" --waldir=WALDIR location for the write-ahead log directory\n"));
393  printf(_(" -X, --wal-method=none|fetch|stream\n"
394  " include required WAL files with specified method\n"));
395  printf(_(" -z, --gzip compress tar output\n"));
396  printf(_(" -Z, --compress=[{client|server}-]METHOD[:DETAIL]\n"
397  " compress on client or server as specified\n"));
398  printf(_(" -Z, --compress=none do not compress tar output\n"));
399  printf(_("\nGeneral options:\n"));
400  printf(_(" -c, --checkpoint=fast|spread\n"
401  " set fast or spread checkpointing\n"));
402  printf(_(" -C, --create-slot create replication slot\n"));
403  printf(_(" -l, --label=LABEL set backup label\n"));
404  printf(_(" -n, --no-clean do not clean up after errors\n"));
405  printf(_(" -N, --no-sync do not wait for changes to be written safely to disk\n"));
406  printf(_(" -P, --progress show progress information\n"));
407  printf(_(" -S, --slot=SLOTNAME replication slot to use\n"));
408  printf(_(" -v, --verbose output verbose messages\n"));
409  printf(_(" -V, --version output version information, then exit\n"));
410  printf(_(" --manifest-checksums=SHA{224,256,384,512}|CRC32C|NONE\n"
411  " use algorithm for manifest checksums\n"));
412  printf(_(" --manifest-force-encode\n"
413  " hex encode all file names in manifest\n"));
414  printf(_(" --no-estimate-size do not estimate backup size in server side\n"));
415  printf(_(" --no-manifest suppress generation of backup manifest\n"));
416  printf(_(" --no-slot prevent creation of temporary replication slot\n"));
417  printf(_(" --no-verify-checksums\n"
418  " do not verify checksums\n"));
419  printf(_(" -?, --help show this help, then exit\n"));
420  printf(_("\nConnection options:\n"));
421  printf(_(" -d, --dbname=CONNSTR connection string\n"));
422  printf(_(" -h, --host=HOSTNAME database server host or socket directory\n"));
423  printf(_(" -p, --port=PORT database server port number\n"));
424  printf(_(" -s, --status-interval=INTERVAL\n"
425  " time between status packets sent to server (in seconds)\n"));
426  printf(_(" -U, --username=NAME connect as specified database user\n"));
427  printf(_(" -w, --no-password never prompt for password\n"));
428  printf(_(" -W, --password force password prompt (should happen automatically)\n"));
429  printf(_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT);
430  printf(_("%s home page: <%s>\n"), PACKAGE_NAME, PACKAGE_URL);
431 }
#define _(x)
Definition: elog.c:89
#define printf(...)
Definition: port.h:231

References _, printf, and progname.

Referenced by main().

◆ verify_dir_is_empty_or_create()

static void verify_dir_is_empty_or_create ( char *  dirname,
bool created,
bool found 
)
static

Definition at line 728 of file pg_basebackup.c.

729 {
730  switch (pg_check_dir(dirname))
731  {
732  case 0:
733 
734  /*
735  * Does not exist, so create
736  */
737  if (pg_mkdir_p(dirname, pg_dir_create_mode) == -1)
738  pg_fatal("could not create directory \"%s\": %m", dirname);
739  if (created)
740  *created = true;
741  return;
742  case 1:
743 
744  /*
745  * Exists, empty
746  */
747  if (found)
748  *found = true;
749  return;
750  case 2:
751  case 3:
752  case 4:
753 
754  /*
755  * Exists, not empty
756  */
757  pg_fatal("directory \"%s\" exists but is not empty", dirname);
758  case -1:
759 
760  /*
761  * Access problem
762  */
763  pg_fatal("could not access directory \"%s\": %m", dirname);
764  }
765 }
int pg_check_dir(const char *dir)
Definition: pgcheckdir.c:33

References pg_check_dir(), pg_dir_create_mode, pg_fatal, and pg_mkdir_p().

Referenced by BaseBackup(), and main().

Variable Documentation

◆ backup_target

char* backup_target = NULL
static

Definition at line 146 of file pg_basebackup.c.

Referenced by BaseBackup(), main(), and ReceiveArchiveStreamChunk().

◆ basedir

◆ bgchild

pid_t bgchild = -1
static

Definition at line 174 of file pg_basebackup.c.

Referenced by BaseBackup(), kill_bgchild_atexit(), and StartLogStreamer().

◆ bgchild_exited

volatile sig_atomic_t bgchild_exited = false
static

◆ bgpipe

int bgpipe[2] = {-1, -1}
static

◆ checksum_failure

bool checksum_failure = false
static

Definition at line 133 of file pg_basebackup.c.

Referenced by BaseBackup(), cleanup_directories_atexit(), and PageIsVerifiedExtended().

◆ create_slot

bool create_slot = false
static

Definition at line 147 of file pg_basebackup.c.

Referenced by main(), and StartLogStreamer().

◆ do_sync

bool do_sync = true
static

Definition at line 140 of file pg_basebackup.c.

Referenced by BaseBackup(), and main().

◆ estimatesize

bool estimatesize = true
static

Definition at line 135 of file pg_basebackup.c.

Referenced by BaseBackup(), and main().

◆ fastcheckpoint

bool fastcheckpoint = false
static

Definition at line 138 of file pg_basebackup.c.

Referenced by BaseBackup(), and main().

◆ format

char format = '\0'
static

Definition at line 130 of file pg_basebackup.c.

Referenced by _conv(), _copyJsonArrayQueryConstructor(), _copyJsonExpr(), _copyJsonIsPredicate(), _copyJsonReturning(), _copyJsonTableColumn(), _copyJsonValueExpr(), _equalJsonArrayQueryConstructor(), _equalJsonExpr(), _equalJsonIsPredicate(), _equalJsonReturning(), _equalJsonTableColumn(), _equalJsonValueExpr(), _fmt(), _outJsonExpr(), _outJsonIsPredicate(), _outJsonReturning(), _outJsonValueExpr(), _print_horizontal_line(), _readJsonExpr(), _readJsonIsPredicate(), _readJsonReturning(), _readJsonValueExpr(), BaseBackup(), check_selective_binary_conversion(), checkJsonOutputFormat(), CreateBackupStreamer(), datetime_to_char_body(), do_to_timestamp(), doabbr(), dopr(), ecpg_log(), exec_simple_query(), ExplainMissingMembers(), find_arguments(), float4_to_char(), float8_to_char(), get_json_format(), getCopyStart(), getJsonEncodingConst(), getRowDescriptions(), int4_to_char(), int8_to_char(), JumbleExpr(), LogStreamerMain(), main(), makeJsonByteaToTextConversion(), makeJsonIsPredicate(), makeJsonValueExpr(), NUM_cache(), numeric_to_char(), numeric_to_number(), parseArchiveFormat(), pg_strftime(), PGTYPESdate_fmt_asc(), print_aligned_text(), print_aligned_vertical(), print_aligned_vertical_line(), printtup_prepare_info(), raw_expression_tree_walker(), ReceiveCopyBegin(), SendCopyBegin(), SendFunctionResult(), SendRowDescriptionMessage(), StartLogStreamer(), transformJsonConstructorRet(), transformJsonExprCommon(), transformJsonParseArg(), transformJsonPassingArgs(), and transformJsonValueExprExt().

◆ found_existing_pgdata

bool found_existing_pgdata = false
static

Definition at line 156 of file pg_basebackup.c.

Referenced by cleanup_directories_atexit(), and main().

◆ found_existing_xlogdir

bool found_existing_xlogdir = false
static

Definition at line 158 of file pg_basebackup.c.

Referenced by cleanup_directories_atexit(), and main().

◆ found_tablespace_dirs

bool found_tablespace_dirs = false
static

Definition at line 160 of file pg_basebackup.c.

Referenced by BaseBackup(), and cleanup_directories_atexit().

◆ has_xlogendptr

int has_xlogendptr = 0
static

Definition at line 184 of file pg_basebackup.c.

Referenced by BaseBackup(), and reached_end_position().

◆ in_log_streamer

bool in_log_streamer = false
static

Definition at line 175 of file pg_basebackup.c.

Referenced by cleanup_directories_atexit(), and LogStreamerMain().

◆ includewal

IncludeWal includewal = STREAM_WAL
static

Definition at line 137 of file pg_basebackup.c.

Referenced by BaseBackup(), and main().

◆ label

◆ last_progress_report

pg_time_t last_progress_report = 0
static

Definition at line 142 of file pg_basebackup.c.

Referenced by progress_report().

◆ made_new_pgdata

bool made_new_pgdata = false
static

Definition at line 155 of file pg_basebackup.c.

Referenced by cleanup_directories_atexit(), and main().

◆ made_new_xlogdir

bool made_new_xlogdir = false
static

Definition at line 157 of file pg_basebackup.c.

Referenced by cleanup_directories_atexit(), and main().

◆ made_tablespace_dirs

bool made_tablespace_dirs = false
static

Definition at line 159 of file pg_basebackup.c.

Referenced by BaseBackup(), and cleanup_directories_atexit().

◆ manifest

◆ manifest_checksums

char* manifest_checksums = NULL
static

Definition at line 152 of file pg_basebackup.c.

Referenced by BaseBackup(), and main().

◆ manifest_force_encode

bool manifest_force_encode = false
static

Definition at line 151 of file pg_basebackup.c.

Referenced by BaseBackup(), and main().

◆ maxrate

int32 maxrate = 0
static

Definition at line 143 of file pg_basebackup.c.

Referenced by BaseBackup(), bbsink_throttle_new(), main(), and parse_basebackup_options().

◆ no_slot

bool no_slot = false
static

Definition at line 148 of file pg_basebackup.c.

Referenced by main().

◆ noclean

bool noclean = false
static

Definition at line 132 of file pg_basebackup.c.

Referenced by cleanup_directories_atexit(), and main().

◆ progress_filename

char* progress_filename = NULL
static

Definition at line 166 of file pg_basebackup.c.

Referenced by progress_report(), and progress_update_filename().

◆ recoveryconfcontents

PQExpBuffer recoveryconfcontents = NULL
static

◆ replication_slot

char* replication_slot = NULL
static

◆ showprogress

bool showprogress = false
static

Definition at line 134 of file pg_basebackup.c.

Referenced by BaseBackup(), main(), progress_report(), and progress_update_filename().

◆ standby_message_timeout

int standby_message_timeout = 10 * 1000
static

Definition at line 141 of file pg_basebackup.c.

Referenced by CalculateCopyStreamSleeptime(), LogStreamerMain(), and main().

◆ success

bool success = false
static

Definition at line 154 of file pg_basebackup.c.

Referenced by cleanup_directories_atexit(), and main().

◆ tablespace_dirs

TablespaceList tablespace_dirs = {NULL, NULL}
static

Definition at line 128 of file pg_basebackup.c.

Referenced by get_tablespace_mapping(), and tablespace_list_append().

◆ tablespacecount

int tablespacecount
static

Definition at line 165 of file pg_basebackup.c.

Referenced by BaseBackup(), and progress_report().

◆ temp_replication_slot

bool temp_replication_slot = true
static

Definition at line 145 of file pg_basebackup.c.

Referenced by main(), and StartLogStreamer().

◆ totaldone

uint64 totaldone
static

◆ totalsize_kb

uint64 totalsize_kb
static

Definition at line 163 of file pg_basebackup.c.

Referenced by BaseBackup(), and progress_report().

◆ verbose

◆ verify_checksums

bool verify_checksums = true
static

Definition at line 149 of file pg_basebackup.c.

Referenced by BaseBackup(), and main().

◆ writerecoveryconf

bool writerecoveryconf = false
static

Definition at line 139 of file pg_basebackup.c.

Referenced by BaseBackup(), CreateBackupStreamer(), and main().

◆ xlog_dir

char* xlog_dir = NULL
static

Definition at line 129 of file pg_basebackup.c.

Referenced by cleanup_directories_atexit(), and main().

◆ xlogendptr

XLogRecPtr xlogendptr
static

Definition at line 181 of file pg_basebackup.c.

Referenced by BaseBackup(), and reached_end_position().