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/select.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <signal.h>
#include <time.h>
#include "access/xlog_internal.h"
#include "backup/basebackup.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 "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 MINIMUM_VERSION_FOR_WAL_SUMMARIES   170000
 
#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, char *incremental_manifest)
 
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 backup_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 DataDirSyncMethod sync_method = DATA_DIR_SYNC_METHOD_FSYNC
 
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 41 of file pg_basebackup.c.

◆ MINIMUM_VERSION_FOR_MANIFESTS

#define MINIMUM_VERSION_FOR_MANIFESTS   130000

Definition at line 96 of file pg_basebackup.c.

◆ MINIMUM_VERSION_FOR_PG_WAL

#define MINIMUM_VERSION_FOR_PG_WAL   100000

Definition at line 86 of file pg_basebackup.c.

◆ MINIMUM_VERSION_FOR_TEMP_SLOTS

#define MINIMUM_VERSION_FOR_TEMP_SLOTS   100000

Definition at line 91 of file pg_basebackup.c.

◆ MINIMUM_VERSION_FOR_TERMINATED_TARFILE

#define MINIMUM_VERSION_FOR_TERMINATED_TARFILE   150000

Definition at line 102 of file pg_basebackup.c.

◆ MINIMUM_VERSION_FOR_WAL_SUMMARIES

#define MINIMUM_VERSION_FOR_WAL_SUMMARIES   170000

Definition at line 107 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 79 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 122 of file pg_basebackup.c.

123 {
CompressionLocation
@ COMPRESS_LOCATION_UNSPECIFIED
@ COMPRESS_LOCATION_CLIENT
@ COMPRESS_LOCATION_SERVER

◆ IncludeWal

enum IncludeWal
Enumerator
NO_WAL 
FETCH_WAL 
STREAM_WAL 

Definition at line 112 of file pg_basebackup.c.

113 {
114  NO_WAL,
115  FETCH_WAL,
116  STREAM_WAL,
117 } IncludeWal;
IncludeWal
@ STREAM_WAL
@ FETCH_WAL
@ NO_WAL

Function Documentation

◆ backup_parse_compress_options()

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

Definition at line 986 of file pg_basebackup.c.

988 {
989  /*
990  * Strip off any "client-" or "server-" prefix, calculating the location.
991  */
992  if (strncmp(option, "server-", 7) == 0)
993  {
994  *locationres = COMPRESS_LOCATION_SERVER;
995  option += 7;
996  }
997  else if (strncmp(option, "client-", 7) == 0)
998  {
999  *locationres = COMPRESS_LOCATION_CLIENT;
1000  option += 7;
1001  }
1002  else
1003  *locationres = COMPRESS_LOCATION_UNSPECIFIED;
1004 
1005  /* fallback to the common parsing for the algorithm and detail */
1006  parse_compress_options(option, algorithm, detail);
1007 }
void parse_compress_options(const char *option, char **algorithm, char **detail)

References COMPRESS_LOCATION_CLIENT, COMPRESS_LOCATION_SERVER, COMPRESS_LOCATION_UNSPECIFIED, and parse_compress_options().

Referenced by main().

◆ BaseBackup()

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

Definition at line 1753 of file pg_basebackup.c.

1757 {
1758  PGresult *res;
1759  char *sysidentifier;
1760  TimeLineID latesttli;
1761  TimeLineID starttli;
1762  char *basebkp;
1763  int i;
1764  char xlogstart[64];
1765  char xlogend[64] = {0};
1766  int minServerMajor,
1767  maxServerMajor;
1768  int serverVersion,
1769  serverMajor;
1770  int writing_to_stdout;
1771  bool use_new_option_syntax = false;
1773 
1774  Assert(conn != NULL);
1775  initPQExpBuffer(&buf);
1776 
1777  /*
1778  * Check server version. BASE_BACKUP command was introduced in 9.1, so we
1779  * can't work with servers older than 9.1.
1780  */
1781  minServerMajor = 901;
1782  maxServerMajor = PG_VERSION_NUM / 100;
1783  serverVersion = PQserverVersion(conn);
1784  serverMajor = serverVersion / 100;
1785  if (serverMajor < minServerMajor || serverMajor > maxServerMajor)
1786  {
1787  const char *serverver = PQparameterStatus(conn, "server_version");
1788 
1789  pg_fatal("incompatible server version %s",
1790  serverver ? serverver : "'unknown'");
1791  }
1792  if (serverMajor >= 1500)
1793  use_new_option_syntax = true;
1794 
1795  /*
1796  * If WAL streaming was requested, also check that the server is new
1797  * enough for that.
1798  */
1800  {
1801  /*
1802  * Error message already written in CheckServerVersionForStreaming(),
1803  * but add a hint about using -X none.
1804  */
1805  pg_log_error_hint("Use -X none or -X fetch to disable log streaming.");
1806  exit(1);
1807  }
1808 
1809  /*
1810  * Build contents of configuration file if requested
1811  */
1812  if (writerecoveryconf)
1814 
1815  /*
1816  * Run IDENTIFY_SYSTEM so we can get the timeline
1817  */
1818  if (!RunIdentifySystem(conn, &sysidentifier, &latesttli, NULL, NULL))
1819  exit(1);
1820 
1821  /*
1822  * If the user wants an incremental backup, we must upload the manifest
1823  * for the previous backup upon which it is to be based.
1824  */
1825  if (incremental_manifest != NULL)
1826  {
1827  int fd;
1828  char mbuf[65536];
1829  int nbytes;
1830 
1831  /* Reject if server is too old. */
1832  if (serverVersion < MINIMUM_VERSION_FOR_WAL_SUMMARIES)
1833  pg_fatal("server does not support incremental backup");
1834 
1835  /* Open the file. */
1836  fd = open(incremental_manifest, O_RDONLY | PG_BINARY, 0);
1837  if (fd < 0)
1838  pg_fatal("could not open file \"%s\": %m", incremental_manifest);
1839 
1840  /* Tell the server what we want to do. */
1841  if (PQsendQuery(conn, "UPLOAD_MANIFEST") == 0)
1842  pg_fatal("could not send replication command \"%s\": %s",
1843  "UPLOAD_MANIFEST", PQerrorMessage(conn));
1844  res = PQgetResult(conn);
1846  {
1848  pg_fatal("could not upload manifest: %s",
1849  PQerrorMessage(conn));
1850  else
1851  pg_fatal("could not upload manifest: unexpected status %s",
1853  }
1854 
1855  /* Loop, reading from the file and sending the data to the server. */
1856  while ((nbytes = read(fd, mbuf, sizeof mbuf)) > 0)
1857  {
1858  if (PQputCopyData(conn, mbuf, nbytes) < 0)
1859  pg_fatal("could not send COPY data: %s",
1860  PQerrorMessage(conn));
1861  }
1862 
1863  /* Bail out if we exited the loop due to an error. */
1864  if (nbytes < 0)
1865  pg_fatal("could not read file \"%s\": %m", incremental_manifest);
1866 
1867  /* End the COPY operation. */
1868  if (PQputCopyEnd(conn, NULL) < 0)
1869  pg_fatal("could not send end-of-COPY: %s",
1870  PQerrorMessage(conn));
1871 
1872  /* See whether the server is happy with what we sent. */
1873  res = PQgetResult(conn);
1875  pg_fatal("could not upload manifest: %s",
1876  PQerrorMessage(conn));
1877  else if (PQresultStatus(res) != PGRES_COMMAND_OK)
1878  pg_fatal("could not upload manifest: unexpected status %s",
1880 
1881  /* Consume ReadyForQuery message from server. */
1882  res = PQgetResult(conn);
1883  if (res != NULL)
1884  pg_fatal("unexpected extra result while sending manifest");
1885 
1886  /* Add INCREMENTAL option to BASE_BACKUP command. */
1887  AppendPlainCommandOption(&buf, use_new_option_syntax, "INCREMENTAL");
1888  }
1889 
1890  /*
1891  * Continue building up the options list for the BASE_BACKUP command.
1892  */
1893  AppendStringCommandOption(&buf, use_new_option_syntax, "LABEL", label);
1894  if (estimatesize)
1895  AppendPlainCommandOption(&buf, use_new_option_syntax, "PROGRESS");
1896  if (includewal == FETCH_WAL)
1897  AppendPlainCommandOption(&buf, use_new_option_syntax, "WAL");
1898  if (fastcheckpoint)
1899  {
1900  if (use_new_option_syntax)
1901  AppendStringCommandOption(&buf, use_new_option_syntax,
1902  "CHECKPOINT", "fast");
1903  else
1904  AppendPlainCommandOption(&buf, use_new_option_syntax, "FAST");
1905  }
1906  if (includewal != NO_WAL)
1907  {
1908  if (use_new_option_syntax)
1909  AppendIntegerCommandOption(&buf, use_new_option_syntax, "WAIT", 0);
1910  else
1911  AppendPlainCommandOption(&buf, use_new_option_syntax, "NOWAIT");
1912  }
1913  if (maxrate > 0)
1914  AppendIntegerCommandOption(&buf, use_new_option_syntax, "MAX_RATE",
1915  maxrate);
1916  if (format == 't')
1917  AppendPlainCommandOption(&buf, use_new_option_syntax, "TABLESPACE_MAP");
1918  if (!verify_checksums)
1919  {
1920  if (use_new_option_syntax)
1921  AppendIntegerCommandOption(&buf, use_new_option_syntax,
1922  "VERIFY_CHECKSUMS", 0);
1923  else
1924  AppendPlainCommandOption(&buf, use_new_option_syntax,
1925  "NOVERIFY_CHECKSUMS");
1926  }
1927 
1928  if (manifest)
1929  {
1930  AppendStringCommandOption(&buf, use_new_option_syntax, "MANIFEST",
1931  manifest_force_encode ? "force-encode" : "yes");
1932  if (manifest_checksums != NULL)
1933  AppendStringCommandOption(&buf, use_new_option_syntax,
1934  "MANIFEST_CHECKSUMS", manifest_checksums);
1935  }
1936 
1937  if (backup_target != NULL)
1938  {
1939  char *colon;
1940 
1941  if (serverMajor < 1500)
1942  pg_fatal("backup targets are not supported by this server version");
1943 
1944  if (writerecoveryconf)
1945  pg_fatal("recovery configuration cannot be written when a backup target is used");
1946 
1947  AppendPlainCommandOption(&buf, use_new_option_syntax, "TABLESPACE_MAP");
1948 
1949  if ((colon = strchr(backup_target, ':')) == NULL)
1950  {
1951  AppendStringCommandOption(&buf, use_new_option_syntax,
1952  "TARGET", backup_target);
1953  }
1954  else
1955  {
1956  char *target;
1957 
1959  AppendStringCommandOption(&buf, use_new_option_syntax,
1960  "TARGET", target);
1961  AppendStringCommandOption(&buf, use_new_option_syntax,
1962  "TARGET_DETAIL", colon + 1);
1963  }
1964  }
1965  else if (serverMajor >= 1500)
1966  AppendStringCommandOption(&buf, use_new_option_syntax,
1967  "TARGET", "client");
1968 
1969  if (compressloc == COMPRESS_LOCATION_SERVER)
1970  {
1971  if (!use_new_option_syntax)
1972  pg_fatal("server does not support server-side compression");
1973  AppendStringCommandOption(&buf, use_new_option_syntax,
1974  "COMPRESSION", compression_algorithm);
1975  if (compression_detail != NULL)
1976  AppendStringCommandOption(&buf, use_new_option_syntax,
1977  "COMPRESSION_DETAIL",
1978  compression_detail);
1979  }
1980 
1981  if (verbose)
1982  pg_log_info("initiating base backup, waiting for checkpoint to complete");
1983 
1984  if (showprogress && !verbose)
1985  {
1986  fprintf(stderr, _("waiting for checkpoint"));
1987  if (isatty(fileno(stderr)))
1988  fprintf(stderr, "\r");
1989  else
1990  fprintf(stderr, "\n");
1991  }
1992 
1993  if (use_new_option_syntax && buf.len > 0)
1994  basebkp = psprintf("BASE_BACKUP (%s)", buf.data);
1995  else
1996  basebkp = psprintf("BASE_BACKUP %s", buf.data);
1997 
1998  /* OK, try to start the backup. */
1999  if (PQsendQuery(conn, basebkp) == 0)
2000  pg_fatal("could not send replication command \"%s\": %s",
2001  "BASE_BACKUP", PQerrorMessage(conn));
2002 
2003  /*
2004  * Get the starting WAL location
2005  */
2006  res = PQgetResult(conn);
2008  pg_fatal("could not initiate base backup: %s",
2009  PQerrorMessage(conn));
2010  if (PQntuples(res) != 1)
2011  pg_fatal("server returned unexpected response to BASE_BACKUP command; got %d rows and %d fields, expected %d rows and %d fields",
2012  PQntuples(res), PQnfields(res), 1, 2);
2013 
2014  strlcpy(xlogstart, PQgetvalue(res, 0, 0), sizeof(xlogstart));
2015 
2016  if (verbose)
2017  pg_log_info("checkpoint completed");
2018 
2019  /*
2020  * 9.3 and later sends the TLI of the starting point. With older servers,
2021  * assume it's the same as the latest timeline reported by
2022  * IDENTIFY_SYSTEM.
2023  */
2024  if (PQnfields(res) >= 2)
2025  starttli = atoi(PQgetvalue(res, 0, 1));
2026  else
2027  starttli = latesttli;
2028  PQclear(res);
2029 
2030  if (verbose && includewal != NO_WAL)
2031  pg_log_info("write-ahead log start point: %s on timeline %u",
2032  xlogstart, starttli);
2033 
2034  /*
2035  * Get the header
2036  */
2037  res = PQgetResult(conn);
2039  pg_fatal("could not get backup header: %s",
2040  PQerrorMessage(conn));
2041  if (PQntuples(res) < 1)
2042  pg_fatal("no data returned from server");
2043 
2044  /*
2045  * Sum up the total size, for progress reporting
2046  */
2047  totalsize_kb = totaldone = 0;
2049  for (i = 0; i < PQntuples(res); i++)
2050  {
2051  totalsize_kb += atol(PQgetvalue(res, i, 2));
2052 
2053  /*
2054  * Verify tablespace directories are empty. Don't bother with the
2055  * first once since it can be relocated, and it will be checked before
2056  * we do anything anyway.
2057  *
2058  * Note that this is skipped for tar format backups and backups that
2059  * the server is storing to a target location, since in that case we
2060  * won't be storing anything into these directories and thus should
2061  * not create them.
2062  */
2063  if (backup_target == NULL && format == 'p' && !PQgetisnull(res, i, 1))
2064  {
2065  char *path = PQgetvalue(res, i, 1);
2066 
2067  if (is_absolute_path(path))
2068  path = unconstify(char *, get_tablespace_mapping(path));
2069  else
2070  {
2071  /* This is an in-place tablespace, so prepend basedir. */
2072  path = psprintf("%s/%s", basedir, path);
2073  }
2074 
2076  }
2077  }
2078 
2079  /*
2080  * When writing to stdout, require a single tablespace
2081  */
2082  writing_to_stdout = format == 't' && basedir != NULL &&
2083  strcmp(basedir, "-") == 0;
2084  if (writing_to_stdout && PQntuples(res) > 1)
2085  pg_fatal("can only write single tablespace to stdout, database has %d",
2086  PQntuples(res));
2087 
2088  /*
2089  * If we're streaming WAL, start the streaming session before we start
2090  * receiving the actual data chunks.
2091  */
2092  if (includewal == STREAM_WAL)
2093  {
2094  pg_compress_algorithm wal_compress_algorithm;
2095  int wal_compress_level;
2096 
2097  if (verbose)
2098  pg_log_info("starting background WAL receiver");
2099 
2100  if (client_compress->algorithm == PG_COMPRESSION_GZIP)
2101  {
2102  wal_compress_algorithm = PG_COMPRESSION_GZIP;
2103  wal_compress_level = client_compress->level;
2104  }
2105  else
2106  {
2107  wal_compress_algorithm = PG_COMPRESSION_NONE;
2108  wal_compress_level = 0;
2109  }
2110 
2111  StartLogStreamer(xlogstart, starttli, sysidentifier,
2112  wal_compress_algorithm,
2113  wal_compress_level);
2114  }
2115 
2116  if (serverMajor >= 1500)
2117  {
2118  /* Receive a single tar stream with everything. */
2119  ReceiveArchiveStream(conn, client_compress);
2120  }
2121  else
2122  {
2123  /* Receive a tar file for each tablespace in turn */
2124  for (i = 0; i < PQntuples(res); i++)
2125  {
2126  char archive_name[MAXPGPATH];
2127  char *spclocation;
2128 
2129  /*
2130  * If we write the data out to a tar file, it will be named
2131  * base.tar if it's the main data directory or <tablespaceoid>.tar
2132  * if it's for another tablespace. CreateBackupStreamer() will
2133  * arrange to add an extension to the archive name if
2134  * pg_basebackup is performing compression, depending on the
2135  * compression type.
2136  */
2137  if (PQgetisnull(res, i, 0))
2138  {
2139  strlcpy(archive_name, "base.tar", sizeof(archive_name));
2140  spclocation = NULL;
2141  }
2142  else
2143  {
2144  snprintf(archive_name, sizeof(archive_name),
2145  "%s.tar", PQgetvalue(res, i, 0));
2146  spclocation = PQgetvalue(res, i, 1);
2147  }
2148 
2149  ReceiveTarFile(conn, archive_name, spclocation, i,
2150  client_compress);
2151  }
2152 
2153  /*
2154  * Now receive backup manifest, if appropriate.
2155  *
2156  * If we're writing a tarfile to stdout, ReceiveTarFile will have
2157  * already processed the backup manifest and included it in the output
2158  * tarfile. Such a configuration doesn't allow for writing multiple
2159  * files.
2160  *
2161  * If we're talking to an older server, it won't send a backup
2162  * manifest, so don't try to receive one.
2163  */
2164  if (!writing_to_stdout && manifest)
2166  }
2167 
2168  if (showprogress)
2169  {
2171  progress_report(PQntuples(res), true, true);
2172  }
2173 
2174  PQclear(res);
2175 
2176  /*
2177  * Get the stop position
2178  */
2179  res = PQgetResult(conn);
2181  pg_fatal("backup failed: %s",
2182  PQerrorMessage(conn));
2183  if (PQntuples(res) != 1)
2184  pg_fatal("no write-ahead log end position returned from server");
2185  strlcpy(xlogend, PQgetvalue(res, 0, 0), sizeof(xlogend));
2186  if (verbose && includewal != NO_WAL)
2187  pg_log_info("write-ahead log end point: %s", xlogend);
2188  PQclear(res);
2189 
2190  res = PQgetResult(conn);
2192  {
2193  const char *sqlstate = PQresultErrorField(res, PG_DIAG_SQLSTATE);
2194 
2195  if (sqlstate &&
2196  strcmp(sqlstate, ERRCODE_DATA_CORRUPTED) == 0)
2197  {
2198  pg_log_error("checksum error occurred");
2199  checksum_failure = true;
2200  }
2201  else
2202  {
2203  pg_log_error("final receive failed: %s",
2204  PQerrorMessage(conn));
2205  }
2206  exit(1);
2207  }
2208 
2209  if (bgchild > 0)
2210  {
2211 #ifndef WIN32
2212  int status;
2213  pid_t r;
2214 #else
2215  DWORD status;
2216 
2217  /*
2218  * get a pointer sized version of bgchild to avoid warnings about
2219  * casting to a different size on WIN64.
2220  */
2221  intptr_t bgchild_handle = bgchild;
2222  uint32 hi,
2223  lo;
2224 #endif
2225 
2226  if (verbose)
2227  pg_log_info("waiting for background process to finish streaming ...");
2228 
2229 #ifndef WIN32
2230  if (write(bgpipe[1], xlogend, strlen(xlogend)) != strlen(xlogend))
2231  pg_fatal("could not send command to background pipe: %m");
2232 
2233  /* Just wait for the background process to exit */
2234  r = waitpid(bgchild, &status, 0);
2235  if (r == (pid_t) -1)
2236  pg_fatal("could not wait for child process: %m");
2237  if (r != bgchild)
2238  pg_fatal("child %d died, expected %d", (int) r, (int) bgchild);
2239  if (status != 0)
2240  pg_fatal("%s", wait_result_to_str(status));
2241  /* Exited normally, we're happy! */
2242 #else /* WIN32 */
2243 
2244  /*
2245  * On Windows, since we are in the same process, we can just store the
2246  * value directly in the variable, and then set the flag that says
2247  * it's there.
2248  */
2249  if (sscanf(xlogend, "%X/%X", &hi, &lo) != 2)
2250  pg_fatal("could not parse write-ahead log location \"%s\"",
2251  xlogend);
2252  xlogendptr = ((uint64) hi) << 32 | lo;
2253  InterlockedIncrement(&has_xlogendptr);
2254 
2255  /* First wait for the thread to exit */
2256  if (WaitForSingleObjectEx((HANDLE) bgchild_handle, INFINITE, FALSE) !=
2257  WAIT_OBJECT_0)
2258  {
2259  _dosmaperr(GetLastError());
2260  pg_fatal("could not wait for child thread: %m");
2261  }
2262  if (GetExitCodeThread((HANDLE) bgchild_handle, &status) == 0)
2263  {
2264  _dosmaperr(GetLastError());
2265  pg_fatal("could not get child thread exit status: %m");
2266  }
2267  if (status != 0)
2268  pg_fatal("child thread exited with error %u",
2269  (unsigned int) status);
2270  /* Exited normally, we're happy */
2271 #endif
2272  }
2273 
2274  /* Free the configuration file contents */
2276 
2277  /*
2278  * End of copy data. Final result is already checked inside the loop.
2279  */
2280  PQclear(res);
2281  PQfinish(conn);
2282  conn = NULL;
2283 
2284  /*
2285  * Make data persistent on disk once backup is completed. For tar format
2286  * sync the parent directory and all its contents as each tar file was not
2287  * synced after being completed. In plain format, all the data of the
2288  * base directory is synced, taking into account all the tablespaces.
2289  * Errors are not considered fatal.
2290  *
2291  * If, however, there's a backup target, we're not writing anything
2292  * locally, so in that case we skip this step.
2293  */
2294  if (do_sync && backup_target == NULL)
2295  {
2296  if (verbose)
2297  pg_log_info("syncing data to disk ...");
2298  if (format == 't')
2299  {
2300  if (strcmp(basedir, "-") != 0)
2301  (void) sync_dir_recurse(basedir, sync_method);
2302  }
2303  else
2304  {
2305  (void) sync_pgdata(basedir, serverVersion, sync_method);
2306  }
2307  }
2308 
2309  /*
2310  * After synchronizing data to disk, perform a durable rename of
2311  * backup_manifest.tmp to backup_manifest, if we wrote such a file. This
2312  * way, a failure or system crash before we reach this point will leave us
2313  * without a backup_manifest file, decreasing the chances that a directory
2314  * we leave behind will be mistaken for a valid backup.
2315  */
2316  if (!writing_to_stdout && manifest && backup_target == NULL)
2317  {
2318  char tmp_filename[MAXPGPATH];
2319  char filename[MAXPGPATH];
2320 
2321  if (verbose)
2322  pg_log_info("renaming backup_manifest.tmp to backup_manifest");
2323 
2324  snprintf(tmp_filename, MAXPGPATH, "%s/backup_manifest.tmp", basedir);
2325  snprintf(filename, MAXPGPATH, "%s/backup_manifest", basedir);
2326 
2327  if (do_sync)
2328  {
2329  /* durable_rename emits its own log message in case of failure */
2330  if (durable_rename(tmp_filename, filename) != 0)
2331  exit(1);
2332  }
2333  else
2334  {
2335  if (rename(tmp_filename, filename) != 0)
2336  pg_fatal("could not rename file \"%s\" to \"%s\": %m",
2337  tmp_filename, filename);
2338  }
2339  }
2340 
2341  if (verbose)
2342  pg_log_info("base backup completed");
2343 }
#define unconstify(underlying_type, expr)
Definition: c.h:1232
unsigned int uint32
Definition: c.h:493
#define PG_BINARY
Definition: c.h:1260
pg_compress_algorithm
Definition: compression.h:22
@ PG_COMPRESSION_GZIP
Definition: compression.h:24
@ PG_COMPRESSION_NONE
Definition: compression.h:23
#define _(x)
Definition: elog.c:91
int durable_rename(const char *oldfile, const char *newfile, int elevel)
Definition: fd.c:782
const char * PQparameterStatus(const PGconn *conn, const char *paramName)
Definition: fe-connect.c:6806
int PQserverVersion(const PGconn *conn)
Definition: fe-connect.c:6831
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:6841
void PQfinish(PGconn *conn)
Definition: fe-connect.c:4562
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:3371
int PQputCopyEnd(PGconn *conn, const char *errormsg)
Definition: fe-exec.c:2711
int PQntuples(const PGresult *res)
Definition: fe-exec.c:3441
int PQputCopyData(PGconn *conn, const char *buffer, int nbytes)
Definition: fe-exec.c:2657
char * PQgetvalue(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3836
int PQgetisnull(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3861
int PQsendQuery(PGconn *conn, const char *query)
Definition: fe-exec.c:1425
char * PQresStatus(ExecStatusType status)
Definition: fe-exec.c:3379
char * PQresultErrorField(const PGresult *res, int fieldcode)
Definition: fe-exec.c:3426
int PQnfields(const PGresult *res)
Definition: fe-exec.c:3449
PGresult * PQgetResult(PGconn *conn)
Definition: fe-exec.c:2038
#define colon
Definition: indent_codes.h:43
#define write(a, b, c)
Definition: win32.h:14
#define read(a, b, c)
Definition: win32.h:13
int i
Definition: isn.c:73
@ PGRES_COPY_IN
Definition: libpq-fe.h:104
@ PGRES_COMMAND_OK
Definition: libpq-fe.h:97
@ PGRES_FATAL_ERROR
Definition: libpq-fe.h:108
@ 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_error_hint(...)
Definition: logging.h:112
#define pg_log_info(...)
Definition: logging.h:124
char * pnstrdup(const char *in, Size len)
Definition: mcxt.c:1591
#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
static DataDirSyncMethod sync_method
#define ERRCODE_DATA_CORRUPTED
Definition: pg_basebackup.c:41
static char * label
static bool showprogress
static const char * get_tablespace_mapping(const char *dir)
static char * basedir
static XLogRecPtr xlogendptr
#define MINIMUM_VERSION_FOR_WAL_SUMMARIES
#define MAXPGPATH
static char * filename
Definition: pg_dumpall.c:121
static pg_compress_algorithm compression_algorithm
Definition: pg_receivewal.c:55
static char * buf
Definition: pg_test_fsync.c:73
#define is_absolute_path(filename)
Definition: port.h:103
#define snprintf
Definition: port.h:238
#define fprintf
Definition: port.h:242
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
#define PG_DIAG_SQLSTATE
Definition: postgres_ext.h:56
void initPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:90
void destroyPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:114
static int fd(const char *x, int i)
Definition: preproc-init.c:105
char * psprintf(const char *fmt,...)
Definition: psprintf.c:46
bool CheckServerVersionForStreaming(PGconn *conn)
Definition: receivelog.c:375
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:784
void AppendPlainCommandOption(PQExpBuffer buf, bool use_new_option_syntax, char *option_name)
Definition: streamutil.c:740
void AppendStringCommandOption(PQExpBuffer buf, bool use_new_option_syntax, char *option_name, char *option_value)
Definition: streamutil.c:761
PGconn * conn
Definition: streamutil.c:54
bool RunIdentifySystem(PGconn *conn, char **sysid, TimeLineID *starttli, XLogRecPtr *startpos, char **db_name)
Definition: streamutil.c:408
pg_compress_algorithm algorithm
Definition: compression.h:34
char * wait_result_to_str(int exitstatus)
Definition: wait_error.c:33
void _dosmaperr(unsigned long)
Definition: win32error.c:177
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, colon, COMPRESS_LOCATION_SERVER, compression_algorithm, conn, destroyPQExpBuffer(), do_sync, durable_rename(), ERRCODE_DATA_CORRUPTED, estimatesize, exit(), fastcheckpoint, fd(), FETCH_WAL, filename, format, found_tablespace_dirs, fprintf, GenerateRecoveryConfig(), get_tablespace_mapping(), has_xlogendptr, i, includewal, initPQExpBuffer(), is_absolute_path, label, pg_compress_specification::level, made_tablespace_dirs, manifest, manifest_checksums, manifest_force_encode, MAXPGPATH, maxrate, MINIMUM_VERSION_FOR_WAL_SUMMARIES, NO_WAL, PG_BINARY, PG_COMPRESSION_GZIP, PG_COMPRESSION_NONE, PG_DIAG_SQLSTATE, pg_fatal, pg_log_error, pg_log_error_hint, pg_log_info, PGRES_COMMAND_OK, PGRES_COPY_IN, PGRES_FATAL_ERROR, PGRES_TUPLES_OK, pnstrdup(), PQclear(), PQerrorMessage(), PQfinish(), PQgetisnull(), PQgetResult(), PQgetvalue(), PQnfields(), PQntuples(), PQparameterStatus(), PQputCopyData(), PQputCopyEnd(), PQresStatus(), PQresultErrorField(), PQresultStatus(), PQsendQuery(), PQserverVersion(), progress_report(), progress_update_filename(), psprintf(), read, ReceiveArchiveStream(), ReceiveBackupManifest(), ReceiveTarFile(), recoveryconfcontents, replication_slot, res, RunIdentifySystem(), showprogress, snprintf, StartLogStreamer(), STREAM_WAL, strlcpy(), sync_method, 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 236 of file pg_basebackup.c.

237 {
238  if (success || in_log_streamer)
239  return;
240 
241  if (!noclean && !checksum_failure)
242  {
243  if (made_new_pgdata)
244  {
245  pg_log_info("removing data directory \"%s\"", basedir);
246  if (!rmtree(basedir, true))
247  pg_log_error("failed to remove data directory");
248  }
249  else if (found_existing_pgdata)
250  {
251  pg_log_info("removing contents of data directory \"%s\"", basedir);
252  if (!rmtree(basedir, false))
253  pg_log_error("failed to remove contents of data directory");
254  }
255 
256  if (made_new_xlogdir)
257  {
258  pg_log_info("removing WAL directory \"%s\"", xlog_dir);
259  if (!rmtree(xlog_dir, true))
260  pg_log_error("failed to remove WAL directory");
261  }
262  else if (found_existing_xlogdir)
263  {
264  pg_log_info("removing contents of WAL directory \"%s\"", xlog_dir);
265  if (!rmtree(xlog_dir, false))
266  pg_log_error("failed to remove contents of WAL directory");
267  }
268  }
269  else
270  {
272  pg_log_info("data directory \"%s\" not removed at user's request", basedir);
273 
275  pg_log_info("WAL directory \"%s\" not removed at user's request", xlog_dir);
276  }
277 
279  pg_log_info("changes to tablespace directories will not be undone");
280 }
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:50

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 1061 of file pg_basebackup.c.

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

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(), is_absolute_path, manifest, MAXPGPATH, PG_COMPRESSION_GZIP, PG_COMPRESSION_LZ4, PG_COMPRESSION_NONE, PG_COMPRESSION_ZSTD, pg_log_error, pg_log_error_detail, pg_log_error_hint, progress_update_filename(), psprintf(), 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 283 of file pg_basebackup.c.

284 {
285  if (conn != NULL)
286  PQfinish(conn);
287 }

References conn, and PQfinish().

Referenced by main().

◆ get_tablespace_mapping()

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

Definition at line 1678 of file pg_basebackup.c.

1679 {
1680  TablespaceListCell *cell;
1681  char canon_dir[MAXPGPATH];
1682 
1683  /* Canonicalize path for comparison consistency */
1684  strlcpy(canon_dir, dir, sizeof(canon_dir));
1685  canonicalize_path(canon_dir);
1686 
1687  for (cell = tablespace_dirs.head; cell; cell = cell->next)
1688  if (strcmp(canon_dir, cell->old_dir) == 0)
1689  return cell->new_dir;
1690 
1691  return dir;
1692 }
static TablespaceList tablespace_dirs
void canonicalize_path(char *path)
Definition: path.c:264
struct TablespaceListCell * next
Definition: pg_basebackup.c:45
char old_dir[MAXPGPATH]
Definition: pg_basebackup.c:46
char new_dir[MAXPGPATH]
Definition: pg_basebackup.c:47
TablespaceListCell * head
Definition: pg_basebackup.c:52

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 1516 of file pg_basebackup.c.

1517 {
1518  if (*cursor >= r)
1520 
1521  return copybuf[(*cursor)++];
1522 }
static void ReportCopyDataParseError(size_t r, char *copybuf)
Definition: type.h:137
static StringInfo copybuf
Definition: tablesync.c:130

References copybuf, and ReportCopyDataParseError().

Referenced by ReceiveArchiveStreamChunk().

◆ GetCopyDataEnd()

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

Definition at line 1569 of file pg_basebackup.c.

1570 {
1571  if (r != cursor)
1573 }

References copybuf, and ReportCopyDataParseError().

Referenced by ReceiveArchiveStreamChunk().

◆ GetCopyDataString()

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

Definition at line 1530 of file pg_basebackup.c.

1531 {
1532  size_t startpos = *cursor;
1533  size_t endpos = startpos;
1534 
1535  while (1)
1536  {
1537  if (endpos >= r)
1539  if (copybuf[endpos] == '\0')
1540  break;
1541  ++endpos;
1542  }
1543 
1544  *cursor = endpos + 1;
1545  return &copybuf[startpos];
1546 }
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 1554 of file pg_basebackup.c.

1555 {
1556  uint64 result;
1557 
1558  if (*cursor + sizeof(uint64) > r)
1560  memcpy(&result, &copybuf[*cursor], sizeof(uint64));
1561  *cursor += sizeof(uint64);
1562  return pg_ntoh64(result);
1563 }
#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 308 of file pg_basebackup.c.

309 {
310  if (bgchild > 0 && !bgchild_exited)
311  kill(bgchild, SIGTERM);
312 }
static volatile sig_atomic_t bgchild_exited
#define kill(pid, sig)
Definition: win32_port.h:485

References bgchild, bgchild_exited, and kill.

Referenced by StartLogStreamer().

◆ LogStreamerMain()

static int LogStreamerMain ( logstreamer_param param)
static

Definition at line 545 of file pg_basebackup.c.

546 {
547  StreamCtl stream = {0};
548 
549  in_log_streamer = true;
550 
551  stream.startpos = param->startptr;
552  stream.timeline = param->timeline;
553  stream.sysidentifier = param->sysidentifier;
555 #ifndef WIN32
556  stream.stop_socket = bgpipe[0];
557 #else
558  stream.stop_socket = PGINVALID_SOCKET;
559 #endif
561  stream.synchronous = false;
562  /* fsync happens at the end of pg_basebackup for all data */
563  stream.do_sync = false;
564  stream.mark_done = true;
565  stream.partial_suffix = NULL;
567  if (format == 'p')
568  stream.walmethod = CreateWalDirectoryMethod(param->xlog,
570  stream.do_sync);
571  else
572  stream.walmethod = CreateWalTarMethod(param->xlog,
573  param->wal_compress_algorithm,
574  param->wal_compress_level,
575  stream.do_sync);
576 
577  if (!ReceiveXlogStream(param->bgconn, &stream))
578  {
579  /*
580  * Any errors will already have been reported in the function process,
581  * but we need to tell the parent that we didn't shutdown in a nice
582  * way.
583  */
584 #ifdef WIN32
585  /*
586  * In order to signal the main thread of an ungraceful exit we set the
587  * same flag that we use on Unix to signal SIGCHLD.
588  */
589  bgchild_exited = true;
590 #endif
591  return 1;
592  }
593 
594  if (!stream.walmethod->ops->finish(stream.walmethod))
595  {
596  pg_log_error("could not finish writing WAL files: %m");
597 #ifdef WIN32
598  bgchild_exited = true;
599 #endif
600  return 1;
601  }
602 
603  PQfinish(param->bgconn);
604 
605  stream.walmethod->ops->free(stream.walmethod);
606 
607  return 0;
608 }
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:453
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
void(* free)(WalWriteMethod *wwmethod)
Definition: walmethods.h:92
bool(* finish)(WalWriteMethod *wwmethod)
Definition: walmethods.h:86
const WalWriteMethodOps * ops
Definition: walmethods.h:105
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:640
WalWriteMethod * CreateWalTarMethod(const char *tarbase, pg_compress_algorithm compression_algorithm, int compression_level, bool sync)
Definition: walmethods.c:1355

References bgchild_exited, logstreamer_param::bgconn, bgpipe, CreateWalDirectoryMethod(), CreateWalTarMethod(), StreamCtl::do_sync, WalWriteMethodOps::finish, format, WalWriteMethodOps::free, in_log_streamer, StreamCtl::mark_done, WalWriteMethod::ops, StreamCtl::partial_suffix, PG_COMPRESSION_NONE, 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 2347 of file pg_basebackup.c.

2348 {
2349  static struct option long_options[] = {
2350  {"help", no_argument, NULL, '?'},
2351  {"version", no_argument, NULL, 'V'},
2352  {"pgdata", required_argument, NULL, 'D'},
2353  {"format", required_argument, NULL, 'F'},
2354  {"incremental", required_argument, NULL, 'i'},
2355  {"checkpoint", required_argument, NULL, 'c'},
2356  {"create-slot", no_argument, NULL, 'C'},
2357  {"max-rate", required_argument, NULL, 'r'},
2358  {"write-recovery-conf", no_argument, NULL, 'R'},
2359  {"slot", required_argument, NULL, 'S'},
2360  {"target", required_argument, NULL, 't'},
2361  {"tablespace-mapping", required_argument, NULL, 'T'},
2362  {"wal-method", required_argument, NULL, 'X'},
2363  {"gzip", no_argument, NULL, 'z'},
2364  {"compress", required_argument, NULL, 'Z'},
2365  {"label", required_argument, NULL, 'l'},
2366  {"no-clean", no_argument, NULL, 'n'},
2367  {"no-sync", no_argument, NULL, 'N'},
2368  {"dbname", required_argument, NULL, 'd'},
2369  {"host", required_argument, NULL, 'h'},
2370  {"port", required_argument, NULL, 'p'},
2371  {"username", required_argument, NULL, 'U'},
2372  {"no-password", no_argument, NULL, 'w'},
2373  {"password", no_argument, NULL, 'W'},
2374  {"status-interval", required_argument, NULL, 's'},
2375  {"verbose", no_argument, NULL, 'v'},
2376  {"progress", no_argument, NULL, 'P'},
2377  {"waldir", required_argument, NULL, 1},
2378  {"no-slot", no_argument, NULL, 2},
2379  {"no-verify-checksums", no_argument, NULL, 3},
2380  {"no-estimate-size", no_argument, NULL, 4},
2381  {"no-manifest", no_argument, NULL, 5},
2382  {"manifest-force-encode", no_argument, NULL, 6},
2383  {"manifest-checksums", required_argument, NULL, 7},
2384  {"sync-method", required_argument, NULL, 8},
2385  {NULL, 0, NULL, 0}
2386  };
2387  int c;
2388 
2389  int option_index;
2390  char *compression_algorithm = "none";
2391  char *compression_detail = NULL;
2392  char *incremental_manifest = NULL;
2394  pg_compress_specification client_compress;
2395 
2396  pg_logging_init(argv[0]);
2397  progname = get_progname(argv[0]);
2398  set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pg_basebackup"));
2399 
2400  if (argc > 1)
2401  {
2402  if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
2403  {
2404  usage();
2405  exit(0);
2406  }
2407  else if (strcmp(argv[1], "-V") == 0
2408  || strcmp(argv[1], "--version") == 0)
2409  {
2410  puts("pg_basebackup (PostgreSQL) " PG_VERSION);
2411  exit(0);
2412  }
2413  }
2414 
2416 
2417  while ((c = getopt_long(argc, argv, "c:Cd:D:F:h:i:l:nNp:Pr:Rs:S:t:T:U:vwWX:zZ:",
2418  long_options, &option_index)) != -1)
2419  {
2420  switch (c)
2421  {
2422  case 'c':
2423  if (pg_strcasecmp(optarg, "fast") == 0)
2424  fastcheckpoint = true;
2425  else if (pg_strcasecmp(optarg, "spread") == 0)
2426  fastcheckpoint = false;
2427  else
2428  pg_fatal("invalid checkpoint argument \"%s\", must be \"fast\" or \"spread\"",
2429  optarg);
2430  break;
2431  case 'C':
2432  create_slot = true;
2433  break;
2434  case 'd':
2436  break;
2437  case 'D':
2439  break;
2440  case 'F':
2441  if (strcmp(optarg, "p") == 0 || strcmp(optarg, "plain") == 0)
2442  format = 'p';
2443  else if (strcmp(optarg, "t") == 0 || strcmp(optarg, "tar") == 0)
2444  format = 't';
2445  else
2446  pg_fatal("invalid output format \"%s\", must be \"plain\" or \"tar\"",
2447  optarg);
2448  break;
2449  case 'h':
2450  dbhost = pg_strdup(optarg);
2451  break;
2452  case 'i':
2453  incremental_manifest = pg_strdup(optarg);
2454  break;
2455  case 'l':
2456  label = pg_strdup(optarg);
2457  break;
2458  case 'n':
2459  noclean = true;
2460  break;
2461  case 'N':
2462  do_sync = false;
2463  break;
2464  case 'p':
2465  dbport = pg_strdup(optarg);
2466  break;
2467  case 'P':
2468  showprogress = true;
2469  break;
2470  case 'r':
2472  break;
2473  case 'R':
2474  writerecoveryconf = true;
2475  break;
2476  case 's':
2477  if (!option_parse_int(optarg, "-s/--status-interval", 0,
2478  INT_MAX / 1000,
2480  exit(1);
2481  standby_message_timeout *= 1000;
2482  break;
2483  case 'S':
2484 
2485  /*
2486  * When specifying replication slot name, use a permanent
2487  * slot.
2488  */
2490  temp_replication_slot = false;
2491  break;
2492  case 't':
2494  break;
2495  case 'T':
2497  break;
2498  case 'U':
2499  dbuser = pg_strdup(optarg);
2500  break;
2501  case 'v':
2502  verbose++;
2503  break;
2504  case 'w':
2505  dbgetpassword = -1;
2506  break;
2507  case 'W':
2508  dbgetpassword = 1;
2509  break;
2510  case 'X':
2511  if (strcmp(optarg, "n") == 0 ||
2512  strcmp(optarg, "none") == 0)
2513  {
2514  includewal = NO_WAL;
2515  }
2516  else if (strcmp(optarg, "f") == 0 ||
2517  strcmp(optarg, "fetch") == 0)
2518  {
2520  }
2521  else if (strcmp(optarg, "s") == 0 ||
2522  strcmp(optarg, "stream") == 0)
2523  {
2525  }
2526  else
2527  pg_fatal("invalid wal-method option \"%s\", must be \"fetch\", \"stream\", or \"none\"",
2528  optarg);
2529  break;
2530  case 'z':
2531  compression_algorithm = "gzip";
2532  compression_detail = NULL;
2533  compressloc = COMPRESS_LOCATION_UNSPECIFIED;
2534  break;
2535  case 'Z':
2537  &compression_detail, &compressloc);
2538  break;
2539  case 1:
2541  break;
2542  case 2:
2543  no_slot = true;
2544  break;
2545  case 3:
2546  verify_checksums = false;
2547  break;
2548  case 4:
2549  estimatesize = false;
2550  break;
2551  case 5:
2552  manifest = false;
2553  break;
2554  case 6:
2555  manifest_force_encode = true;
2556  break;
2557  case 7:
2559  break;
2560  case 8:
2562  exit(1);
2563  break;
2564  default:
2565  /* getopt_long already emitted a complaint */
2566  pg_log_error_hint("Try \"%s --help\" for more information.", progname);
2567  exit(1);
2568  }
2569  }
2570 
2571  /*
2572  * Any non-option arguments?
2573  */
2574  if (optind < argc)
2575  {
2576  pg_log_error("too many command-line arguments (first is \"%s\")",
2577  argv[optind]);
2578  pg_log_error_hint("Try \"%s --help\" for more information.", progname);
2579  exit(1);
2580  }
2581 
2582  /*
2583  * Setting the backup target to 'client' is equivalent to leaving out the
2584  * option. This logic allows us to assume elsewhere that the backup is
2585  * being stored locally if and only if backup_target == NULL.
2586  */
2587  if (backup_target != NULL && strcmp(backup_target, "client") == 0)
2588  {
2590  backup_target = NULL;
2591  }
2592 
2593  /*
2594  * Can't use --format with --target. Without --target, default format is
2595  * tar.
2596  */
2597  if (backup_target != NULL && format != '\0')
2598  {
2599  pg_log_error("cannot specify both format and backup target");
2600  pg_log_error_hint("Try \"%s --help\" for more information.", progname);
2601  exit(1);
2602  }
2603  if (format == '\0')
2604  format = 'p';
2605 
2606  /*
2607  * Either directory or backup target should be specified, but not both
2608  */
2609  if (basedir == NULL && backup_target == NULL)
2610  {
2611  pg_log_error("must specify output directory or backup target");
2612  pg_log_error_hint("Try \"%s --help\" for more information.", progname);
2613  exit(1);
2614  }
2615  if (basedir != NULL && backup_target != NULL)
2616  {
2617  pg_log_error("cannot specify both output directory and backup target");
2618  pg_log_error_hint("Try \"%s --help\" for more information.", progname);
2619  exit(1);
2620  }
2621 
2622  /*
2623  * If the user has not specified where to perform backup compression,
2624  * default to the client, unless the user specified --target, in which
2625  * case the server is the only choice.
2626  */
2627  if (compressloc == COMPRESS_LOCATION_UNSPECIFIED)
2628  {
2629  if (backup_target == NULL)
2630  compressloc = COMPRESS_LOCATION_CLIENT;
2631  else
2632  compressloc = COMPRESS_LOCATION_SERVER;
2633  }
2634 
2635  /*
2636  * If any compression that we're doing is happening on the client side, we
2637  * must try to parse the compression algorithm and detail, but if it's all
2638  * on the server side, then we're just going to pass through whatever was
2639  * requested and let the server decide what to do.
2640  */
2641  if (compressloc == COMPRESS_LOCATION_CLIENT)
2642  {
2644  char *error_detail;
2645 
2647  pg_fatal("unrecognized compression algorithm: \"%s\"",
2649 
2650  parse_compress_specification(alg, compression_detail, &client_compress);
2651  error_detail = validate_compress_specification(&client_compress);
2652  if (error_detail != NULL)
2653  pg_fatal("invalid compression specification: %s",
2654  error_detail);
2655  }
2656  else
2657  {
2658  Assert(compressloc == COMPRESS_LOCATION_SERVER);
2659  client_compress.algorithm = PG_COMPRESSION_NONE;
2660  client_compress.options = 0;
2661  }
2662 
2663  /*
2664  * Can't perform client-side compression if the backup is not being sent
2665  * to the client.
2666  */
2667  if (backup_target != NULL && compressloc == COMPRESS_LOCATION_CLIENT)
2668  {
2669  pg_log_error("client-side compression is not possible when a backup target is specified");
2670  pg_log_error_hint("Try \"%s --help\" for more information.", progname);
2671  exit(1);
2672  }
2673 
2674  /*
2675  * Client-side compression doesn't make sense unless tar format is in use.
2676  */
2677  if (format == 'p' && compressloc == COMPRESS_LOCATION_CLIENT &&
2678  client_compress.algorithm != PG_COMPRESSION_NONE)
2679  {
2680  pg_log_error("only tar mode backups can be compressed");
2681  pg_log_error_hint("Try \"%s --help\" for more information.", progname);
2682  exit(1);
2683  }
2684 
2685  /*
2686  * Sanity checks for WAL method.
2687  */
2688  if (backup_target != NULL && includewal == STREAM_WAL)
2689  {
2690  pg_log_error("WAL cannot be streamed when a backup target is specified");
2691  pg_log_error_hint("Try \"%s --help\" for more information.", progname);
2692  exit(1);
2693  }
2694  if (format == 't' && includewal == STREAM_WAL && strcmp(basedir, "-") == 0)
2695  {
2696  pg_log_error("cannot stream write-ahead logs in tar mode to stdout");
2697  pg_log_error_hint("Try \"%s --help\" for more information.", progname);
2698  exit(1);
2699  }
2700 
2702  {
2703  pg_log_error("replication slots can only be used with WAL streaming");
2704  pg_log_error_hint("Try \"%s --help\" for more information.", progname);
2705  exit(1);
2706  }
2707 
2708  /*
2709  * Sanity checks for replication slot options.
2710  */
2711  if (no_slot)
2712  {
2713  if (replication_slot)
2714  {
2715  pg_log_error("--no-slot cannot be used with slot name");
2716  pg_log_error_hint("Try \"%s --help\" for more information.", progname);
2717  exit(1);
2718  }
2719  temp_replication_slot = false;
2720  }
2721 
2722  if (create_slot)
2723  {
2724  if (!replication_slot)
2725  {
2726  pg_log_error("%s needs a slot to be specified using --slot",
2727  "--create-slot");
2728  pg_log_error_hint("Try \"%s --help\" for more information.", progname);
2729  exit(1);
2730  }
2731 
2732  if (no_slot)
2733  {
2734  pg_log_error("%s and %s are incompatible options",
2735  "--create-slot", "--no-slot");
2736  pg_log_error_hint("Try \"%s --help\" for more information.", progname);
2737  exit(1);
2738  }
2739  }
2740 
2741  /*
2742  * Sanity checks on WAL directory.
2743  */
2744  if (xlog_dir)
2745  {
2746  if (backup_target != NULL)
2747  {
2748  pg_log_error("WAL directory location cannot be specified along with a backup target");
2749  pg_log_error_hint("Try \"%s --help\" for more information.", progname);
2750  exit(1);
2751  }
2752  if (format != 'p')
2753  {
2754  pg_log_error("WAL directory location can only be specified in plain mode");
2755  pg_log_error_hint("Try \"%s --help\" for more information.", progname);
2756  exit(1);
2757  }
2758 
2759  /* clean up xlog directory name, check it's absolute */
2761  if (!is_absolute_path(xlog_dir))
2762  {
2763  pg_log_error("WAL directory location must be an absolute path");
2764  pg_log_error_hint("Try \"%s --help\" for more information.", progname);
2765  exit(1);
2766  }
2767  }
2768 
2769  /*
2770  * Sanity checks for progress reporting options.
2771  */
2772  if (showprogress && !estimatesize)
2773  {
2774  pg_log_error("%s and %s are incompatible options",
2775  "--progress", "--no-estimate-size");
2776  pg_log_error_hint("Try \"%s --help\" for more information.", progname);
2777  exit(1);
2778  }
2779 
2780  /*
2781  * Sanity checks for backup manifest options.
2782  */
2783  if (!manifest && manifest_checksums != NULL)
2784  {
2785  pg_log_error("%s and %s are incompatible options",
2786  "--no-manifest", "--manifest-checksums");
2787  pg_log_error_hint("Try \"%s --help\" for more information.", progname);
2788  exit(1);
2789  }
2790 
2792  {
2793  pg_log_error("%s and %s are incompatible options",
2794  "--no-manifest", "--manifest-force-encode");
2795  pg_log_error_hint("Try \"%s --help\" for more information.", progname);
2796  exit(1);
2797  }
2798 
2799  /* connection in replication mode to server */
2800  conn = GetConnection();
2801  if (!conn)
2802  {
2803  /* Error message already written in GetConnection() */
2804  exit(1);
2805  }
2806  atexit(disconnect_atexit);
2807 
2808 #ifndef WIN32
2809 
2810  /*
2811  * Trap SIGCHLD to be able to handle the WAL stream process exiting. There
2812  * is no SIGCHLD on Windows, there we rely on the background thread
2813  * setting the signal variable on unexpected but graceful exit. If the WAL
2814  * stream thread crashes on Windows it will bring down the entire process
2815  * as it's a thread, so there is nothing to catch should that happen. A
2816  * crash on UNIX will be caught by the signal handler.
2817  */
2819 #endif
2820 
2821  /*
2822  * Set umask so that directories/files are created with the same
2823  * permissions as directories/files in the source data directory.
2824  *
2825  * pg_mode_mask is set to owner-only by default and then updated in
2826  * GetConnection() where we get the mode from the server-side with
2827  * RetrieveDataDirCreatePerm() and then call SetDataDirectoryCreatePerm().
2828  */
2829  umask(pg_mode_mask);
2830 
2831  /* Backup manifests are supported in 13 and newer versions */
2833  manifest = false;
2834 
2835  /*
2836  * If an output directory was specified, verify that it exists, or create
2837  * it. Note that for a tar backup, an output directory of "-" means we are
2838  * writing to stdout, so do nothing in that case.
2839  */
2840  if (basedir != NULL && (format == 'p' || strcmp(basedir, "-") != 0))
2842 
2843  /* determine remote server's xlog segment size */
2844  if (!RetrieveWalSegSize(conn))
2845  exit(1);
2846 
2847  /* Create pg_wal symlink, if required */
2848  if (xlog_dir)
2849  {
2850  char *linkloc;
2851 
2853 
2854  /*
2855  * Form name of the place where the symlink must go. pg_xlog has been
2856  * renamed to pg_wal in post-10 clusters.
2857  */
2858  linkloc = psprintf("%s/%s", basedir,
2860  "pg_xlog" : "pg_wal");
2861 
2862  if (symlink(xlog_dir, linkloc) != 0)
2863  pg_fatal("could not create symbolic link \"%s\": %m", linkloc);
2864  free(linkloc);
2865  }
2866 
2867  BaseBackup(compression_algorithm, compression_detail, compressloc,
2868  &client_compress, incremental_manifest);
2869 
2870  success = true;
2871  return 0;
2872 }
#define PG_TEXTDOMAIN(domain)
Definition: c.h:1201
void set_pglocale_pgservice(const char *argv0, const char *app)
Definition: exec.c:447
bool parse_compress_algorithm(char *name, pg_compress_algorithm *algorithm)
Definition: compression.c:49
void parse_compress_specification(pg_compress_algorithm algorithm, char *specification, pg_compress_specification *result)
Definition: compression.c:107
char * validate_compress_specification(pg_compress_specification *spec)
Definition: compression.c:344
PGconn * GetConnection(UserMapping *user, bool will_prep_stmt, PgFdwConnState **state)
Definition: connection.c:177
char * pg_strdup(const char *in)
Definition: fe_memutils.c:85
void pg_free(void *ptr)
Definition: fe_memutils.c:105
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:60
#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
const char * progname
Definition: main.c:45
bool option_parse_int(const char *optarg, const char *optname, int min_range, int max_range, int *result)
Definition: option_utils.c:50
bool parse_sync_method(const char *optarg, DataDirSyncMethod *sync_method)
Definition: option_utils.c:90
static void BaseBackup(char *compression_algorithm, char *compression_detail, CompressionLocation compressloc, pg_compress_specification *client_compress, char *incremental_manifest)
static int32 parse_max_rate(char *src)
static bool create_slot
static void backup_parse_compress_options(char *option, char **algorithm, char **detail, CompressionLocation *locationres)
static void cleanup_directories_atexit(void)
static bool temp_replication_slot
#define MINIMUM_VERSION_FOR_MANIFESTS
Definition: pg_basebackup.c:96
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:86
static void sigchld_handler(SIGNAL_ARGS)
PGDLLIMPORT int optind
Definition: getopt.c:50
PGDLLIMPORT char * optarg
Definition: getopt.c:52
int pg_strcasecmp(const char *s1, const char *s2)
Definition: pgstrcasecmp.c:36
const char * get_progname(const char *argv0)
Definition: path.c:574
pqsigfunc pqsignal(int signo, pqsigfunc func)
char * c
int dbgetpassword
Definition: streamutil.c:52
bool RetrieveWalSegSize(PGconn *conn)
Definition: streamutil.c:275
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:178
#define symlink(oldpath, newpath)
Definition: win32_port.h:235

References pg_compress_specification::algorithm, Assert(), backup_parse_compress_options(), 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_specification(), parse_max_rate(), parse_sync_method(), 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, sync_method, tablespace_list_append(), temp_replication_slot, usage(), validate_compress_specification(), verbose, verify_checksums, verify_dir_is_empty_or_create(), writerecoveryconf, and xlog_dir.

◆ parse_max_rate()

static int32 parse_max_rate ( char *  src)
static

Definition at line 901 of file pg_basebackup.c.

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

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 816 of file pg_basebackup.c.

817 {
818  int percent;
819  char totaldone_str[32];
820  char totalsize_str[32];
821  pg_time_t now;
822 
823  if (!showprogress)
824  return;
825 
826  now = time(NULL);
827  if (now == last_progress_report && !force && !finished)
828  return; /* Max once per second */
829 
831  percent = totalsize_kb ? (int) ((totaldone / 1024) * 100 / totalsize_kb) : 0;
832 
833  /*
834  * Avoid overflowing past 100% or the full size. This may make the total
835  * size number change as we approach the end of the backup (the estimate
836  * will always be wrong if WAL is included), but that's better than having
837  * the done column be bigger than the total.
838  */
839  if (percent > 100)
840  percent = 100;
841  if (totaldone / 1024 > totalsize_kb)
842  totalsize_kb = totaldone / 1024;
843 
844  snprintf(totaldone_str, sizeof(totaldone_str), UINT64_FORMAT,
845  totaldone / 1024);
846  snprintf(totalsize_str, sizeof(totalsize_str), UINT64_FORMAT, totalsize_kb);
847 
848 #define VERBOSE_FILENAME_LENGTH 35
849  if (verbose)
850  {
851  if (!progress_filename)
852 
853  /*
854  * No filename given, so clear the status line (used for last
855  * call)
856  */
857  fprintf(stderr,
858  ngettext("%*s/%s kB (100%%), %d/%d tablespace %*s",
859  "%*s/%s kB (100%%), %d/%d tablespaces %*s",
861  (int) strlen(totalsize_str),
862  totaldone_str, totalsize_str,
863  tablespacenum, tablespacecount,
864  VERBOSE_FILENAME_LENGTH + 5, "");
865  else
866  {
867  bool truncate = (strlen(progress_filename) > VERBOSE_FILENAME_LENGTH);
868 
869  fprintf(stderr,
870  ngettext("%*s/%s kB (%d%%), %d/%d tablespace (%s%-*.*s)",
871  "%*s/%s kB (%d%%), %d/%d tablespaces (%s%-*.*s)",
873  (int) strlen(totalsize_str),
874  totaldone_str, totalsize_str, percent,
875  tablespacenum, tablespacecount,
876  /* Prefix with "..." if we do leading truncation */
877  truncate ? "..." : "",
880  /* Truncate filename at beginning if it's too long */
882  }
883  }
884  else
885  fprintf(stderr,
886  ngettext("%*s/%s kB (%d%%), %d/%d tablespace",
887  "%*s/%s kB (%d%%), %d/%d tablespaces",
889  (int) strlen(totalsize_str),
890  totaldone_str, totalsize_str, percent,
891  tablespacenum, tablespacecount);
892 
893  /*
894  * Stay on the same line if reporting to a terminal and we're not done
895  * yet.
896  */
897  fputc((!finished && isatty(fileno(stderr))) ? '\r' : '\n', stderr);
898 }
Datum now(PG_FUNCTION_ARGS)
Definition: timestamp.c:1619
#define ngettext(s, p, n)
Definition: c.h:1168
#define UINT64_FORMAT
Definition: c.h:536
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 792 of file pg_basebackup.c.

793 {
794  /* We needn't maintain this variable if not doing verbose reports. */
795  if (showprogress && verbose)
796  {
798  if (filename)
800  else
801  progress_filename = NULL;
802  }
803 }

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 462 of file pg_basebackup.c.

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

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

Referenced by LogStreamerMain().

◆ ReceiveArchiveStream()

static void ReceiveArchiveStream ( PGconn conn,
pg_compress_specification compress 
)
static

Definition at line 1284 of file pg_basebackup.c.

1285 {
1287 
1288  /* Set up initial state. */
1289  memset(&state, 0, sizeof(state));
1290  state.tablespacenum = -1;
1291  state.compress = compress;
1292 
1293  /* All the real work happens in ReceiveArchiveStreamChunk. */
1295 
1296  /* If we wrote the backup manifest to a file, close the file. */
1297  if (state.manifest_file !=NULL)
1298  {
1299  fclose(state.manifest_file);
1300  state.manifest_file = NULL;
1301  }
1302 
1303  /*
1304  * If we buffered the backup manifest in order to inject it into the
1305  * output tarfile, do that now.
1306  */
1307  if (state.manifest_inject_streamer != NULL &&
1308  state.manifest_buffer != NULL)
1309  {
1310  bbstreamer_inject_file(state.manifest_inject_streamer,
1311  "backup_manifest",
1312  state.manifest_buffer->data,
1313  state.manifest_buffer->len);
1314  destroyPQExpBuffer(state.manifest_buffer);
1315  state.manifest_buffer = NULL;
1316  }
1317 
1318  /* If there's still an archive in progress, end processing. */
1319  if (state.streamer != NULL)
1320  {
1321  bbstreamer_finalize(state.streamer);
1322  bbstreamer_free(state.streamer);
1323  state.streamer = NULL;
1324  }
1325 }
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:323

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 1332 of file pg_basebackup.c.

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

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 1698 of file pg_basebackup.c.

1699 {
1701 
1702  snprintf(state.filename, sizeof(state.filename),
1703  "%s/backup_manifest.tmp", basedir);
1704  state.file = fopen(state.filename, "wb");
1705  if (state.file == NULL)
1706  pg_fatal("could not create file \"%s\": %m", state.filename);
1707 
1709 
1710  fclose(state.file);
1711 }
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 1717 of file pg_basebackup.c.

1718 {
1719  WriteManifestState *state = callback_data;
1720 
1721  errno = 0;
1722  if (fwrite(copybuf, r, 1, state->file) != 1)
1723  {
1724  /* if write didn't set errno, assume problem is no disk space */
1725  if (errno == 0)
1726  errno = ENOSPC;
1727  pg_fatal("could not write to file \"%s\": %m", state->filename);
1728  }
1729 }

References copybuf, and pg_fatal.

Referenced by ReceiveBackupManifest().

◆ ReceiveBackupManifestInMemory()

static void ReceiveBackupManifestInMemory ( PGconn conn,
PQExpBuffer  buf 
)
static

Definition at line 1735 of file pg_basebackup.c.

1736 {
1738 }
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 1744 of file pg_basebackup.c.

1746 {
1747  PQExpBuffer buf = callback_data;
1748 
1750 }

References appendPQExpBuffer(), buf, and copybuf.

Referenced by ReceiveBackupManifestInMemory().

◆ ReceiveCopyData()

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

Definition at line 1014 of file pg_basebackup.c.

1016 {
1017  PGresult *res;
1018 
1019  /* Get the COPY data stream. */
1020  res = PQgetResult(conn);
1022  pg_fatal("could not get COPY data stream: %s",
1023  PQerrorMessage(conn));
1024  PQclear(res);
1025 
1026  /* Loop over chunks until done. */
1027  while (1)
1028  {
1029  int r;
1030  char *copybuf;
1031 
1032  r = PQgetCopyData(conn, &copybuf, 0);
1033  if (r == -1)
1034  {
1035  /* End of chunk. */
1036  break;
1037  }
1038  else if (r == -2)
1039  pg_fatal("could not read COPY data: %s",
1040  PQerrorMessage(conn));
1041 
1042  if (bgchild_exited)
1043  pg_fatal("background process terminated unexpectedly");
1044 
1045  (*callback) (r, copybuf, callback_data);
1046 
1047  PQfreemem(copybuf);
1048  }
1049 }
void PQfreemem(void *ptr)
Definition: fe-exec.c:3992
int PQgetCopyData(PGconn *conn, char **buffer, int async)
Definition: fe-exec.c:2778
@ 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 1662 of file pg_basebackup.c.

1663 {
1664  WriteTarState *state = callback_data;
1665 
1666  bbstreamer_content(state->streamer, NULL, copybuf, r, BBSTREAMER_UNKNOWN);
1667 
1668  totaldone += r;
1669  progress_report(state->tablespacenum, false, false);
1670 }

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 1599 of file pg_basebackup.c.

1601 {
1603  bbstreamer *manifest_inject_streamer;
1604  bool is_recovery_guc_supported;
1605  bool expect_unterminated_tarfile;
1606 
1607  /* Pass all COPY data through to the backup streamer. */
1608  memset(&state, 0, sizeof(state));
1609  is_recovery_guc_supported =
1611  expect_unterminated_tarfile =
1613  state.streamer = CreateBackupStreamer(archive_name, spclocation,
1614  &manifest_inject_streamer,
1615  is_recovery_guc_supported,
1616  expect_unterminated_tarfile,
1617  compress);
1618  state.tablespacenum = tablespacenum;
1621 
1622  /*
1623  * The decision as to whether we need to inject the backup manifest into
1624  * the output at this stage is made by CreateBackupStreamer; if that is
1625  * needed, manifest_inject_streamer will be non-NULL; otherwise, it will
1626  * be NULL.
1627  */
1628  if (manifest_inject_streamer != NULL)
1629  {
1631 
1632  /* Slurp the entire backup manifest into a buffer. */
1633  initPQExpBuffer(&buf);
1636  pg_fatal("out of memory");
1637 
1638  /* Inject it into the output tarfile. */
1639  bbstreamer_inject_file(manifest_inject_streamer, "backup_manifest",
1640  buf.data, buf.len);
1641 
1642  /* Free memory. */
1643  termPQExpBuffer(&buf);
1644  }
1645 
1646  /* Cleanup. */
1647  bbstreamer_finalize(state.streamer);
1648  bbstreamer_free(state.streamer);
1649 
1650  progress_report(tablespacenum, true, false);
1651 
1652  /*
1653  * Do not sync the resulting tar file yet, all files are synced once at
1654  * the end.
1655  */
1656 }
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:129
#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 1584 of file pg_basebackup.c.

1585 {
1586  if (r == 0)
1587  pg_fatal("empty COPY message");
1588  else
1589  pg_fatal("malformed COPY message of type %d, length %zu",
1590  copybuf[0], r);
1591 }

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 297 of file pg_basebackup.c.

298 {
299  bgchild_exited = true;
300 }

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 616 of file pg_basebackup.c.

619 {
620  logstreamer_param *param;
621  uint32 hi,
622  lo;
623  char statusdir[MAXPGPATH];
624 
625  param = pg_malloc0(sizeof(logstreamer_param));
626  param->timeline = timeline;
627  param->sysidentifier = sysidentifier;
628  param->wal_compress_algorithm = wal_compress_algorithm;
629  param->wal_compress_level = wal_compress_level;
630 
631  /* Convert the starting position */
632  if (sscanf(startpos, "%X/%X", &hi, &lo) != 2)
633  pg_fatal("could not parse write-ahead log location \"%s\"",
634  startpos);
635  param->startptr = ((uint64) hi) << 32 | lo;
636  /* Round off to even segment position */
637  param->startptr -= XLogSegmentOffset(param->startptr, WalSegSz);
638 
639 #ifndef WIN32
640  /* Create our background pipe */
641  if (pipe(bgpipe) < 0)
642  pg_fatal("could not create pipe for background process: %m");
643 #endif
644 
645  /* Get a second connection */
646  param->bgconn = GetConnection();
647  if (!param->bgconn)
648  /* Error message already written in GetConnection() */
649  exit(1);
650 
651  /* In post-10 cluster, pg_xlog has been renamed to pg_wal */
652  snprintf(param->xlog, sizeof(param->xlog), "%s/%s",
653  basedir,
655  "pg_xlog" : "pg_wal");
656 
657  /* Temporary replication slots are only supported in 10 and newer */
659  temp_replication_slot = false;
660 
661  /*
662  * Create replication slot if requested
663  */
665  replication_slot = psprintf("pg_basebackup_%u",
666  (unsigned int) PQbackendPID(param->bgconn));
668  {
669  if (!CreateReplicationSlot(param->bgconn, replication_slot, NULL,
670  temp_replication_slot, true, true, false, false))
671  exit(1);
672 
673  if (verbose)
674  {
676  pg_log_info("created temporary replication slot \"%s\"",
678  else
679  pg_log_info("created replication slot \"%s\"",
681  }
682  }
683 
684  if (format == 'p')
685  {
686  /*
687  * Create pg_wal/archive_status or pg_xlog/archive_status (and thus
688  * pg_wal or pg_xlog) depending on the target server so we can write
689  * to basedir/pg_wal or basedir/pg_xlog as the directory entry in the
690  * tar file may arrive later.
691  */
692  snprintf(statusdir, sizeof(statusdir), "%s/%s/archive_status",
693  basedir,
695  "pg_xlog" : "pg_wal");
696 
697  if (pg_mkdir_p(statusdir, pg_dir_create_mode) != 0 && errno != EEXIST)
698  pg_fatal("could not create directory \"%s\": %m", statusdir);
699 
700  /*
701  * For newer server versions, likewise create pg_wal/summaries
702  */
704  {
705  char summarydir[MAXPGPATH];
706 
707  snprintf(summarydir, sizeof(summarydir), "%s/%s/summaries",
708  basedir, "pg_wal");
709 
710  if (pg_mkdir_p(summarydir, pg_dir_create_mode) != 0 &&
711  errno != EEXIST)
712  pg_fatal("could not create directory \"%s\": %m", summarydir);
713  }
714  }
715 
716  /*
717  * Start a child process and tell it to start streaming. On Unix, this is
718  * a fork(). On Windows, we create a thread.
719  */
720 #ifndef WIN32
721  bgchild = fork();
722  if (bgchild == 0)
723  {
724  /* in child process */
725  exit(LogStreamerMain(param));
726  }
727  else if (bgchild < 0)
728  pg_fatal("could not create background process: %m");
729 
730  /*
731  * Else we are in the parent process and all is well.
732  */
733  atexit(kill_bgchild_atexit);
734 #else /* WIN32 */
735  bgchild = _beginthreadex(NULL, 0, (void *) LogStreamerMain, param, 0, NULL);
736  if (bgchild == 0)
737  pg_fatal("could not create background thread: %m");
738 #endif
739 }
int PQbackendPID(const PGconn *conn)
Definition: fe-connect.c:6875
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:91
static int LogStreamerMain(logstreamer_param *param)
static void kill_bgchild_atexit(void)
int pg_mkdir_p(char *path, int omode)
Definition: pgmkdirp.c:57
int WalSegSz
Definition: streamutil.c:34
static void CreateReplicationSlot(CreateReplicationSlotCmd *cmd)
Definition: walsender.c:1203
#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, MINIMUM_VERSION_FOR_WAL_SUMMARIES, 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 320 of file pg_basebackup.c.

321 {
323  char *dst;
324  char *dst_ptr;
325  const char *arg_ptr;
326 
327  dst_ptr = dst = cell->old_dir;
328  for (arg_ptr = arg; *arg_ptr; arg_ptr++)
329  {
330  if (dst_ptr - dst >= MAXPGPATH)
331  pg_fatal("directory name too long");
332 
333  if (*arg_ptr == '\\' && *(arg_ptr + 1) == '=')
334  ; /* skip backslash escaping = */
335  else if (*arg_ptr == '=' && (arg_ptr == arg || *(arg_ptr - 1) != '\\'))
336  {
337  if (*cell->new_dir)
338  pg_fatal("multiple \"=\" signs in tablespace mapping");
339  else
340  dst = dst_ptr = cell->new_dir;
341  }
342  else
343  *dst_ptr++ = *arg_ptr;
344  }
345 
346  if (!*cell->old_dir || !*cell->new_dir)
347  pg_fatal("invalid tablespace mapping format \"%s\", must be \"OLDDIR=NEWDIR\"", arg);
348 
349  /*
350  * All tablespaces are created with absolute directories, so specifying a
351  * non-absolute path here would just never match, possibly confusing
352  * users. Since we don't know whether the remote side is Windows or not,
353  * and it might be different than the local side, permit any path that
354  * could be absolute under either set of rules.
355  *
356  * (There is little practical risk of confusion here, because someone
357  * running entirely on Linux isn't likely to have a relative path that
358  * begins with a backslash or something that looks like a drive
359  * specification. If they do, and they also incorrectly believe that a
360  * relative path is acceptable here, we'll silently fail to warn them of
361  * their mistake, and the -T option will just not get applied, same as if
362  * they'd specified -T for a nonexistent tablespace.)
363  */
364  if (!is_nonwindows_absolute_path(cell->old_dir) &&
366  pg_fatal("old directory is not an absolute path in tablespace mapping: %s",
367  cell->old_dir);
368 
369  if (!is_absolute_path(cell->new_dir))
370  pg_fatal("new directory is not an absolute path in tablespace mapping: %s",
371  cell->new_dir);
372 
373  /*
374  * Comparisons done with these values should involve similarly
375  * canonicalized path values. This is particularly sensitive on Windows
376  * where path values may not necessarily use Unix slashes.
377  */
378  canonicalize_path(cell->old_dir);
379  canonicalize_path(cell->new_dir);
380 
381  if (tablespace_dirs.tail)
382  tablespace_dirs.tail->next = cell;
383  else
384  tablespace_dirs.head = cell;
385  tablespace_dirs.tail = cell;
386 }
void * arg
#define is_windows_absolute_path(filename)
Definition: port.h:89
#define is_nonwindows_absolute_path(filename)
Definition: port.h:82
TablespaceListCell * tail
Definition: pg_basebackup.c:53

References arg, canonicalize_path(), TablespaceList::head, is_absolute_path, is_nonwindows_absolute_path, is_windows_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 390 of file pg_basebackup.c.

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

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 747 of file pg_basebackup.c.

748 {
749  switch (pg_check_dir(dirname))
750  {
751  case 0:
752 
753  /*
754  * Does not exist, so create
755  */
756  if (pg_mkdir_p(dirname, pg_dir_create_mode) == -1)
757  pg_fatal("could not create directory \"%s\": %m", dirname);
758  if (created)
759  *created = true;
760  return;
761  case 1:
762 
763  /*
764  * Exists, empty
765  */
766  if (found)
767  *found = true;
768  return;
769  case 2:
770  case 3:
771  case 4:
772 
773  /*
774  * Exists, not empty
775  */
776  pg_fatal("directory \"%s\" exists but is not empty", dirname);
777  case -1:
778 
779  /*
780  * Access problem
781  */
782  pg_fatal("could not access directory \"%s\": %m", dirname);
783  }
784 }
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 149 of file pg_basebackup.c.

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

◆ basedir

◆ bgchild

pid_t bgchild = -1
static

Definition at line 178 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 136 of file pg_basebackup.c.

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

◆ create_slot

bool create_slot = false
static

Definition at line 150 of file pg_basebackup.c.

Referenced by main(), and StartLogStreamer().

◆ do_sync

bool do_sync = true
static

Definition at line 143 of file pg_basebackup.c.

Referenced by BaseBackup(), and main().

◆ estimatesize

bool estimatesize = true
static

Definition at line 138 of file pg_basebackup.c.

Referenced by BaseBackup(), and main().

◆ fastcheckpoint

bool fastcheckpoint = false
static

Definition at line 141 of file pg_basebackup.c.

Referenced by BaseBackup(), and main().

◆ format

◆ found_existing_pgdata

bool found_existing_pgdata = false
static

Definition at line 160 of file pg_basebackup.c.

Referenced by cleanup_directories_atexit(), and main().

◆ found_existing_xlogdir

bool found_existing_xlogdir = false
static

Definition at line 162 of file pg_basebackup.c.

Referenced by cleanup_directories_atexit(), and main().

◆ found_tablespace_dirs

bool found_tablespace_dirs = false
static

Definition at line 164 of file pg_basebackup.c.

Referenced by BaseBackup(), and cleanup_directories_atexit().

◆ has_xlogendptr

int has_xlogendptr = 0
static

Definition at line 188 of file pg_basebackup.c.

Referenced by BaseBackup(), and reached_end_position().

◆ in_log_streamer

bool in_log_streamer = false
static

Definition at line 179 of file pg_basebackup.c.

Referenced by cleanup_directories_atexit(), and LogStreamerMain().

◆ includewal

IncludeWal includewal = STREAM_WAL
static

Definition at line 140 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 145 of file pg_basebackup.c.

Referenced by progress_report().

◆ made_new_pgdata

bool made_new_pgdata = false
static

Definition at line 159 of file pg_basebackup.c.

Referenced by cleanup_directories_atexit(), and main().

◆ made_new_xlogdir

bool made_new_xlogdir = false
static

Definition at line 161 of file pg_basebackup.c.

Referenced by cleanup_directories_atexit(), and main().

◆ made_tablespace_dirs

bool made_tablespace_dirs = false
static

Definition at line 163 of file pg_basebackup.c.

Referenced by BaseBackup(), and cleanup_directories_atexit().

◆ manifest

◆ manifest_checksums

char* manifest_checksums = NULL
static

Definition at line 155 of file pg_basebackup.c.

Referenced by BaseBackup(), and main().

◆ manifest_force_encode

bool manifest_force_encode = false
static

Definition at line 154 of file pg_basebackup.c.

Referenced by BaseBackup(), and main().

◆ maxrate

int32 maxrate = 0
static

Definition at line 146 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 151 of file pg_basebackup.c.

Referenced by main().

◆ noclean

bool noclean = false
static

Definition at line 135 of file pg_basebackup.c.

Referenced by cleanup_directories_atexit(), and main().

◆ progress_filename

char* progress_filename = NULL
static

Definition at line 170 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 137 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 144 of file pg_basebackup.c.

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

◆ success

bool success = false
static

Definition at line 158 of file pg_basebackup.c.

Referenced by cleanup_directories_atexit(), and main().

◆ sync_method

Definition at line 156 of file pg_basebackup.c.

Referenced by BaseBackup(), and main().

◆ tablespace_dirs

TablespaceList tablespace_dirs = {NULL, NULL}
static

Definition at line 131 of file pg_basebackup.c.

Referenced by get_tablespace_mapping(), and tablespace_list_append().

◆ tablespacecount

int tablespacecount
static

Definition at line 169 of file pg_basebackup.c.

Referenced by BaseBackup(), and progress_report().

◆ temp_replication_slot

bool temp_replication_slot = true
static

Definition at line 148 of file pg_basebackup.c.

Referenced by main(), and StartLogStreamer().

◆ totaldone

uint64 totaldone
static

◆ totalsize_kb

uint64 totalsize_kb
static

Definition at line 167 of file pg_basebackup.c.

Referenced by BaseBackup(), and progress_report().

◆ verbose

int verbose = 0
static

◆ verify_checksums

bool verify_checksums = true
static

Definition at line 152 of file pg_basebackup.c.

Referenced by BaseBackup(), and main().

◆ writerecoveryconf

bool writerecoveryconf = false
static

Definition at line 142 of file pg_basebackup.c.

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

◆ xlog_dir

char* xlog_dir = NULL
static

Definition at line 132 of file pg_basebackup.c.

Referenced by cleanup_directories_atexit(), and main().

◆ xlogendptr

XLogRecPtr xlogendptr
static

Definition at line 185 of file pg_basebackup.c.

Referenced by BaseBackup(), and reached_end_position().