PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
pg_basebackup.c File Reference
#include "postgres_fe.h"
#include <unistd.h>
#include <dirent.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <signal.h>
#include <time.h>
#include "common/file_utils.h"
#include "common/string.h"
#include "fe_utils/string_utils.h"
#include "getopt_long.h"
#include "libpq-fe.h"
#include "pqexpbuffer.h"
#include "pgtar.h"
#include "pgtime.h"
#include "receivelog.h"
#include "replication/basebackup.h"
#include "streamutil.h"
Include dependency graph for pg_basebackup.c:

Go to the source code of this file.

Data Structures

struct  TablespaceListCell
 
struct  TablespaceList
 
struct  logstreamer_param
 

Macros

#define MINIMUM_VERSION_FOR_PG_WAL   100000
 
#define MINIMUM_VERSION_FOR_TEMP_SLOTS   100000
 
#define VERBOSE_FILENAME_LENGTH   35
 
#define WRITE_TAR_DATA(buf, sz)   writeTarData(tarfile, buf, sz, filename)
 

Typedefs

typedef struct TablespaceListCell TablespaceListCell
 
typedef struct TablespaceList TablespaceList
 

Enumerations

enum  IncludeWal { NO_WAL, FETCH_WAL, STREAM_WAL }
 

Functions

static void usage (void)
 
static void disconnect_and_exit (int code)
 
static void verify_dir_is_empty_or_create (char *dirname, bool *created, bool *found)
 
static void progress_report (int tablespacenum, const char *filename, bool force)
 
static void ReceiveTarFile (PGconn *conn, PGresult *res, int rownum)
 
static void ReceiveAndUnpackTarFile (PGconn *conn, PGresult *res, int rownum)
 
static void GenerateRecoveryConf (PGconn *conn)
 
static void WriteRecoveryConf (void)
 
static void BaseBackup (void)
 
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 int LogStreamerMain (logstreamer_param *param)
 
static void StartLogStreamer (char *startpos, uint32 timeline, char *sysidentifier)
 
static int32 parse_max_rate (char *src)
 
static void writeTarData (FILE *tarfile, char *buf, int r, char *current_file)
 
static char * escape_quotes (const char *src)
 
int main (int argc, char **argv)
 

Variables

static char * basedir = NULL
 
static TablespaceList tablespace_dirs = {NULL, NULL}
 
static char * xlog_dir = ""
 
static char format = 'p'
 
static char * label = "pg_basebackup base backup"
 
static bool noclean = false
 
static bool showprogress = false
 
static int verbose = 0
 
static int compresslevel = 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 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
 
static uint64 totaldone
 
static int tablespacecount
 
static int bgpipe [2] = {-1, -1}
 
static pid_t bgchild = -1
 
static bool in_log_streamer = false
 
static XLogRecPtr xlogendptr
 
static int has_xlogendptr = 0
 
static PQExpBuffer recoveryconfcontents = NULL
 

Macro Definition Documentation

#define MINIMUM_VERSION_FOR_PG_WAL   100000

Definition at line 59 of file pg_basebackup.c.

Referenced by main(), and StartLogStreamer().

#define MINIMUM_VERSION_FOR_TEMP_SLOTS   100000

Definition at line 64 of file pg_basebackup.c.

Referenced by StartLogStreamer().

#define VERBOSE_FILENAME_LENGTH   35

Referenced by progress_report().

#define WRITE_TAR_DATA (   buf,
  sz 
)    writeTarData(tarfile, buf, sz, filename)

Definition at line 915 of file pg_basebackup.c.

Referenced by ReceiveTarFile().

Typedef Documentation

Enumeration Type Documentation

enum IncludeWal
Enumerator
NO_WAL 
FETCH_WAL 
STREAM_WAL 

Definition at line 69 of file pg_basebackup.c.

70 {
71  NO_WAL,
72  FETCH_WAL,
74 } IncludeWal;
IncludeWal
Definition: pg_basebackup.c:69

Function Documentation

static void BaseBackup ( void  )
static

Definition at line 1684 of file pg_basebackup.c.

References _, _dosmaperr(), Assert, basedir, bgchild, bgpipe, CheckServerVersionForStreaming(), conn, destroyPQExpBuffer(), disconnect_and_exit(), do_sync, FALSE, fastcheckpoint, FETCH_WAL, format, found_tablespace_dirs, fsync_fname(), fsync_pgdata(), GenerateRecoveryConf(), get_tablespace_mapping(), has_xlogendptr, i, includewal, label, made_tablespace_dirs, MAXPGPATH, maxrate, MemSet, NO_WAL, NULL, PGRES_COMMAND_OK, PGRES_TUPLES_OK, PQclear(), PQerrorMessage(), PQescapeStringConn(), PQfinish(), PQgetisnull(), PQgetResult(), PQgetvalue(), PQnfields(), PQntuples(), PQparameterStatus(), PQresultStatus(), PQsendQuery(), PQserverVersion(), progname, progress_report(), psprintf(), ReceiveAndUnpackTarFile(), ReceiveTarFile(), RunIdentifySystem(), showprogress, StartLogStreamer(), status(), STREAM_WAL, strerror(), strlcpy(), tablespacecount, totaldone, totalsize, verbose, verify_dir_is_empty_or_create(), WEXITSTATUS, WIFEXITED, write, writerecoveryconf, and xlogendptr.

Referenced by main().

1685 {
1686  PGresult *res;
1687  char *sysidentifier;
1688  TimeLineID latesttli;
1689  TimeLineID starttli;
1690  char *basebkp;
1691  char escaped_label[MAXPGPATH];
1692  char *maxrate_clause = NULL;
1693  int i;
1694  char xlogstart[64];
1695  char xlogend[64];
1696  int minServerMajor,
1697  maxServerMajor;
1698  int serverVersion,
1699  serverMajor;
1700 
1701  Assert(conn != NULL);
1702 
1703  /*
1704  * Check server version. BASE_BACKUP command was introduced in 9.1, so we
1705  * can't work with servers older than 9.1.
1706  */
1707  minServerMajor = 901;
1708  maxServerMajor = PG_VERSION_NUM / 100;
1709  serverVersion = PQserverVersion(conn);
1710  serverMajor = serverVersion / 100;
1711  if (serverMajor < minServerMajor || serverMajor > maxServerMajor)
1712  {
1713  const char *serverver = PQparameterStatus(conn, "server_version");
1714 
1715  fprintf(stderr, _("%s: incompatible server version %s\n"),
1716  progname, serverver ? serverver : "'unknown'");
1718  }
1719 
1720  /*
1721  * If WAL streaming was requested, also check that the server is new
1722  * enough for that.
1723  */
1725  {
1726  /*
1727  * Error message already written in CheckServerVersionForStreaming(),
1728  * but add a hint about using -X none.
1729  */
1730  fprintf(stderr, _("HINT: use -X none or -X fetch to disable log streaming\n"));
1732  }
1733 
1734  /*
1735  * Build contents of recovery.conf if requested
1736  */
1737  if (writerecoveryconf)
1739 
1740  /*
1741  * Run IDENTIFY_SYSTEM so we can get the timeline
1742  */
1743  if (!RunIdentifySystem(conn, &sysidentifier, &latesttli, NULL, NULL))
1745 
1746  /*
1747  * Start the actual backup
1748  */
1749  PQescapeStringConn(conn, escaped_label, label, sizeof(escaped_label), &i);
1750 
1751  if (maxrate > 0)
1752  maxrate_clause = psprintf("MAX_RATE %u", maxrate);
1753 
1754  if (verbose)
1755  fprintf(stderr,
1756  _("%s: initiating base backup, waiting for checkpoint to complete\n"),
1757  progname);
1758 
1759  if (showprogress && !verbose)
1760  fprintf(stderr, "waiting for checkpoint\n");
1761 
1762  basebkp =
1763  psprintf("BASE_BACKUP LABEL '%s' %s %s %s %s %s %s",
1764  escaped_label,
1765  showprogress ? "PROGRESS" : "",
1766  includewal == FETCH_WAL ? "WAL" : "",
1767  fastcheckpoint ? "FAST" : "",
1768  includewal == NO_WAL ? "" : "NOWAIT",
1769  maxrate_clause ? maxrate_clause : "",
1770  format == 't' ? "TABLESPACE_MAP" : "");
1771 
1772  if (PQsendQuery(conn, basebkp) == 0)
1773  {
1774  fprintf(stderr, _("%s: could not send replication command \"%s\": %s"),
1775  progname, "BASE_BACKUP", PQerrorMessage(conn));
1777  }
1778 
1779  /*
1780  * Get the starting xlog position
1781  */
1782  res = PQgetResult(conn);
1783  if (PQresultStatus(res) != PGRES_TUPLES_OK)
1784  {
1785  fprintf(stderr, _("%s: could not initiate base backup: %s"),
1788  }
1789  if (PQntuples(res) != 1)
1790  {
1791  fprintf(stderr,
1792  _("%s: server returned unexpected response to BASE_BACKUP command; got %d rows and %d fields, expected %d rows and %d fields\n"),
1793  progname, PQntuples(res), PQnfields(res), 1, 2);
1795  }
1796 
1797  strlcpy(xlogstart, PQgetvalue(res, 0, 0), sizeof(xlogstart));
1798 
1799  if (verbose)
1800  fprintf(stderr, _("%s: checkpoint completed\n"), progname);
1801 
1802  /*
1803  * 9.3 and later sends the TLI of the starting point. With older servers,
1804  * assume it's the same as the latest timeline reported by
1805  * IDENTIFY_SYSTEM.
1806  */
1807  if (PQnfields(res) >= 2)
1808  starttli = atoi(PQgetvalue(res, 0, 1));
1809  else
1810  starttli = latesttli;
1811  PQclear(res);
1812  MemSet(xlogend, 0, sizeof(xlogend));
1813 
1814  if (verbose && includewal != NO_WAL)
1815  fprintf(stderr, _("%s: transaction log start point: %s on timeline %u\n"),
1816  progname, xlogstart, starttli);
1817 
1818  /*
1819  * Get the header
1820  */
1821  res = PQgetResult(conn);
1822  if (PQresultStatus(res) != PGRES_TUPLES_OK)
1823  {
1824  fprintf(stderr, _("%s: could not get backup header: %s"),
1827  }
1828  if (PQntuples(res) < 1)
1829  {
1830  fprintf(stderr, _("%s: no data returned from server\n"), progname);
1832  }
1833 
1834  /*
1835  * Sum up the total size, for progress reporting
1836  */
1837  totalsize = totaldone = 0;
1838  tablespacecount = PQntuples(res);
1839  for (i = 0; i < PQntuples(res); i++)
1840  {
1841  totalsize += atol(PQgetvalue(res, i, 2));
1842 
1843  /*
1844  * Verify tablespace directories are empty. Don't bother with the
1845  * first once since it can be relocated, and it will be checked before
1846  * we do anything anyway.
1847  */
1848  if (format == 'p' && !PQgetisnull(res, i, 1))
1849  {
1850  char *path = (char *) get_tablespace_mapping(PQgetvalue(res, i, 1));
1851 
1853  }
1854  }
1855 
1856  /*
1857  * When writing to stdout, require a single tablespace
1858  */
1859  if (format == 't' && strcmp(basedir, "-") == 0 && PQntuples(res) > 1)
1860  {
1861  fprintf(stderr,
1862  _("%s: can only write single tablespace to stdout, database has %d\n"),
1863  progname, PQntuples(res));
1865  }
1866 
1867  /*
1868  * If we're streaming WAL, start the streaming session before we start
1869  * receiving the actual data chunks.
1870  */
1871  if (includewal == STREAM_WAL)
1872  {
1873  if (verbose)
1874  fprintf(stderr, _("%s: starting background WAL receiver\n"),
1875  progname);
1876  StartLogStreamer(xlogstart, starttli, sysidentifier);
1877  }
1878 
1879  /*
1880  * Start receiving chunks
1881  */
1882  for (i = 0; i < PQntuples(res); i++)
1883  {
1884  if (format == 't')
1885  ReceiveTarFile(conn, res, i);
1886  else
1887  ReceiveAndUnpackTarFile(conn, res, i);
1888  } /* Loop over all tablespaces */
1889 
1890  if (showprogress)
1891  {
1892  progress_report(PQntuples(res), NULL, true);
1893  fprintf(stderr, "\n"); /* Need to move to next line */
1894  }
1895 
1896  PQclear(res);
1897 
1898  /*
1899  * Get the stop position
1900  */
1901  res = PQgetResult(conn);
1902  if (PQresultStatus(res) != PGRES_TUPLES_OK)
1903  {
1904  fprintf(stderr,
1905  _("%s: could not get transaction log end position from server: %s"),
1908  }
1909  if (PQntuples(res) != 1)
1910  {
1911  fprintf(stderr,
1912  _("%s: no transaction log end position returned from server\n"),
1913  progname);
1915  }
1916  strlcpy(xlogend, PQgetvalue(res, 0, 0), sizeof(xlogend));
1917  if (verbose && includewal != NO_WAL)
1918  fprintf(stderr, _("%s: transaction log end point: %s\n"), progname, xlogend);
1919  PQclear(res);
1920 
1921  res = PQgetResult(conn);
1922  if (PQresultStatus(res) != PGRES_COMMAND_OK)
1923  {
1924  fprintf(stderr, _("%s: final receive failed: %s"),
1927  }
1928 
1929  if (bgchild > 0)
1930  {
1931 #ifndef WIN32
1932  int status;
1933  int r;
1934 #else
1935  DWORD status;
1936 
1937  /*
1938  * get a pointer sized version of bgchild to avoid warnings about
1939  * casting to a different size on WIN64.
1940  */
1941  intptr_t bgchild_handle = bgchild;
1942  uint32 hi,
1943  lo;
1944 #endif
1945 
1946  if (verbose)
1947  fprintf(stderr,
1948  _("%s: waiting for background process to finish streaming ...\n"), progname);
1949 
1950 #ifndef WIN32
1951  if (write(bgpipe[1], xlogend, strlen(xlogend)) != strlen(xlogend))
1952  {
1953  fprintf(stderr,
1954  _("%s: could not send command to background pipe: %s\n"),
1955  progname, strerror(errno));
1957  }
1958 
1959  /* Just wait for the background process to exit */
1960  r = waitpid(bgchild, &status, 0);
1961  if (r == -1)
1962  {
1963  fprintf(stderr, _("%s: could not wait for child process: %s\n"),
1964  progname, strerror(errno));
1966  }
1967  if (r != bgchild)
1968  {
1969  fprintf(stderr, _("%s: child %d died, expected %d\n"),
1970  progname, r, (int) bgchild);
1972  }
1973  if (!WIFEXITED(status))
1974  {
1975  fprintf(stderr, _("%s: child process did not exit normally\n"),
1976  progname);
1978  }
1979  if (WEXITSTATUS(status) != 0)
1980  {
1981  fprintf(stderr, _("%s: child process exited with error %d\n"),
1982  progname, WEXITSTATUS(status));
1984  }
1985  /* Exited normally, we're happy! */
1986 #else /* WIN32 */
1987 
1988  /*
1989  * On Windows, since we are in the same process, we can just store the
1990  * value directly in the variable, and then set the flag that says
1991  * it's there.
1992  */
1993  if (sscanf(xlogend, "%X/%X", &hi, &lo) != 2)
1994  {
1995  fprintf(stderr,
1996  _("%s: could not parse transaction log location \"%s\"\n"),
1997  progname, xlogend);
1999  }
2000  xlogendptr = ((uint64) hi) << 32 | lo;
2001  InterlockedIncrement(&has_xlogendptr);
2002 
2003  /* First wait for the thread to exit */
2004  if (WaitForSingleObjectEx((HANDLE) bgchild_handle, INFINITE, FALSE) !=
2005  WAIT_OBJECT_0)
2006  {
2007  _dosmaperr(GetLastError());
2008  fprintf(stderr, _("%s: could not wait for child thread: %s\n"),
2009  progname, strerror(errno));
2011  }
2012  if (GetExitCodeThread((HANDLE) bgchild_handle, &status) == 0)
2013  {
2014  _dosmaperr(GetLastError());
2015  fprintf(stderr, _("%s: could not get child thread exit status: %s\n"),
2016  progname, strerror(errno));
2018  }
2019  if (status != 0)
2020  {
2021  fprintf(stderr, _("%s: child thread exited with error %u\n"),
2022  progname, (unsigned int) status);
2024  }
2025  /* Exited normally, we're happy */
2026 #endif
2027  }
2028 
2029  /* Free the recovery.conf contents */
2031 
2032  /*
2033  * End of copy data. Final result is already checked inside the loop.
2034  */
2035  PQclear(res);
2036  PQfinish(conn);
2037 
2038  /*
2039  * Make data persistent on disk once backup is completed. For tar
2040  * format once syncing the parent directory is fine, each tar file
2041  * created per tablespace has been already synced. In plain format,
2042  * all the data of the base directory is synced, taking into account
2043  * all the tablespaces. Errors are not considered fatal.
2044  */
2045  if (do_sync)
2046  {
2047  if (format == 't')
2048  {
2049  if (strcmp(basedir, "-") != 0)
2050  (void) fsync_fname(basedir, true, progname);
2051  }
2052  else
2053  {
2054  (void) fsync_pgdata(basedir, progname, serverVersion);
2055  }
2056  }
2057 
2058  if (verbose)
2059  fprintf(stderr, _("%s: base backup completed\n"), progname);
2060 }
int PQnfields(const PGresult *res)
Definition: fe-exec.c:2681
static PQExpBuffer recoveryconfcontents
static IncludeWal includewal
Definition: pg_basebackup.c:86
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:6011
static int bgpipe[2]
void fsync_pgdata(const char *pg_data, const char *progname, int serverVersion)
Definition: file_utils.c:58
uint32 TimeLineID
Definition: xlogdefs.h:45
static bool found_tablespace_dirs
char * PQgetvalue(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3067
const char * PQparameterStatus(const PGconn *conn, const char *paramName)
Definition: fe-connect.c:5976
#define write(a, b, c)
Definition: win32.h:19
char * psprintf(const char *fmt,...)
Definition: psprintf.c:46
void fsync_fname(const char *fname, bool isdir)
Definition: fd.c:567
static int tablespacecount
bool RunIdentifySystem(PGconn *conn, char **sysid, TimeLineID *starttli, XLogRecPtr *startpos, char **db_name)
Definition: streamutil.c:242
#define WIFEXITED(w)
Definition: win32.h:180
static bool writerecoveryconf
Definition: pg_basebackup.c:88
void PQfinish(PGconn *conn)
Definition: fe-connect.c:3568
#define MemSet(start, val, len)
Definition: c.h:857
int PQserverVersion(const PGconn *conn)
Definition: fe-connect.c:6001
const char * progname
Definition: pg_standby.c:37
int PQntuples(const PGresult *res)
Definition: fe-exec.c:2673
static void GenerateRecoveryConf(PGconn *conn)
static char * basedir
Definition: pg_basebackup.c:77
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2596
int PQsendQuery(PGconn *conn, const char *query)
Definition: fe-exec.c:1132
void destroyPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:113
#define FALSE
Definition: c.h:221
PGconn * conn
Definition: streamutil.c:42
#define MAXPGPATH
static uint64 totaldone
static int32 maxrate
Definition: pg_basebackup.c:92
static int has_xlogendptr
size_t PQescapeStringConn(PGconn *conn, char *to, const char *from, size_t length, int *error)
Definition: fe-exec.c:3314
unsigned int uint32
Definition: c.h:268
static uint64 totalsize
static const char * get_tablespace_mapping(const char *dir)
static void progress_report(int tablespacenum, const char *filename, bool force)
static int verbose
Definition: pg_basebackup.c:84
static bool showprogress
Definition: pg_basebackup.c:83
static void ReceiveTarFile(PGconn *conn, PGresult *res, int rownum)
static char * label
Definition: pg_basebackup.c:81
static void StartLogStreamer(char *startpos, uint32 timeline, char *sysidentifier)
void PQclear(PGresult *res)
Definition: fe-exec.c:650
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
#define WEXITSTATUS(w)
Definition: win32.h:182
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
void _dosmaperr(unsigned long)
Definition: win32error.c:171
static void ReceiveAndUnpackTarFile(PGconn *conn, PGresult *res, int rownum)
static XLogRecPtr xlogendptr
static bool fastcheckpoint
Definition: pg_basebackup.c:87
static bool made_tablespace_dirs
static pid_t bgchild
int i
const char * strerror(int errnum)
Definition: strerror.c:19
static bool do_sync
Definition: pg_basebackup.c:89
static void verify_dir_is_empty_or_create(char *dirname, bool *created, bool *found)
static char format
Definition: pg_basebackup.c:80
static void disconnect_and_exit(int code)
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:224
int PQgetisnull(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3092
#define _(x)
Definition: elog.c:84
PGresult * PQgetResult(PGconn *conn)
Definition: fe-exec.c:1702
bool CheckServerVersionForStreaming(PGconn *conn)
Definition: receivelog.c:360
static void cleanup_directories_atexit ( void  )
static

Definition at line 150 of file pg_basebackup.c.

References _, basedir, found_existing_pgdata, found_existing_xlogdir, found_tablespace_dirs, in_log_streamer, made_new_pgdata, made_new_xlogdir, made_tablespace_dirs, noclean, progname, rmtree(), success, and xlog_dir.

Referenced by main().

151 {
152  if (success || in_log_streamer)
153  return;
154 
155  if (!noclean)
156  {
157  if (made_new_pgdata)
158  {
159  fprintf(stderr, _("%s: removing data directory \"%s\"\n"),
160  progname, basedir);
161  if (!rmtree(basedir, true))
162  fprintf(stderr, _("%s: failed to remove data directory\n"),
163  progname);
164  }
165  else if (found_existing_pgdata)
166  {
167  fprintf(stderr,
168  _("%s: removing contents of data directory \"%s\"\n"),
169  progname, basedir);
170  if (!rmtree(basedir, false))
171  fprintf(stderr, _("%s: failed to remove contents of data directory\n"),
172  progname);
173  }
174 
175  if (made_new_xlogdir)
176  {
177  fprintf(stderr, _("%s: removing transaction log directory \"%s\"\n"),
178  progname, xlog_dir);
179  if (!rmtree(xlog_dir, true))
180  fprintf(stderr, _("%s: failed to remove transaction log directory\n"),
181  progname);
182  }
183  else if (found_existing_xlogdir)
184  {
185  fprintf(stderr,
186  _("%s: removing contents of transaction log directory \"%s\"\n"),
187  progname, xlog_dir);
188  if (!rmtree(xlog_dir, false))
189  fprintf(stderr, _("%s: failed to remove contents of transaction log directory\n"),
190  progname);
191  }
192  }
193  else
194  {
196  fprintf(stderr,
197  _("%s: data directory \"%s\" not removed at user's request\n"),
198  progname, basedir);
199 
201  fprintf(stderr,
202  _("%s: transaction log directory \"%s\" not removed at user's request\n"),
203  progname, xlog_dir);
204  }
205 
207  fprintf(stderr,
208  _("%s: changes to tablespace directories will not be undone\n"),
209  progname);
210 }
static bool found_existing_pgdata
Definition: pg_basebackup.c:98
static bool found_tablespace_dirs
const char * progname
Definition: pg_standby.c:37
static char * basedir
Definition: pg_basebackup.c:77
static bool found_existing_xlogdir
static bool success
Definition: pg_basebackup.c:96
static bool made_new_pgdata
Definition: pg_basebackup.c:97
bool rmtree(const char *path, bool rmtopdir)
Definition: rmtree.c:36
static bool in_log_streamer
static char * xlog_dir
Definition: pg_basebackup.c:79
static bool made_new_xlogdir
Definition: pg_basebackup.c:99
static bool made_tablespace_dirs
#define _(x)
Definition: elog.c:84
static bool noclean
Definition: pg_basebackup.c:82
static void disconnect_and_exit ( int  code)
static

Definition at line 213 of file pg_basebackup.c.

References bgchild, conn, NULL, and PQfinish().

Referenced by BaseBackup(), GenerateRecoveryConf(), main(), ReceiveAndUnpackTarFile(), ReceiveTarFile(), StartLogStreamer(), verify_dir_is_empty_or_create(), WriteRecoveryConf(), and writeTarData().

214 {
215  if (conn != NULL)
216  PQfinish(conn);
217 
218 #ifndef WIN32
219 
220  /*
221  * On windows, our background thread dies along with the process. But on
222  * Unix, if we have started a subprocess, we want to kill it off so it
223  * doesn't remain running trying to stream data.
224  */
225  if (bgchild > 0)
226  kill(bgchild, SIGTERM);
227 #endif
228 
229  exit(code);
230 }
void PQfinish(PGconn *conn)
Definition: fe-connect.c:3568
PGconn * conn
Definition: streamutil.c:42
#define NULL
Definition: c.h:229
static pid_t bgchild
static char* escape_quotes ( const char *  src)
static

Definition at line 1556 of file pg_basebackup.c.

References _, escape_single_quotes_ascii(), progname, and result.

Referenced by GenerateRecoveryConf().

1557 {
1558  char *result = escape_single_quotes_ascii(src);
1559 
1560  if (!result)
1561  {
1562  fprintf(stderr, _("%s: out of memory\n"), progname);
1563  exit(1);
1564  }
1565  return result;
1566 }
return result
Definition: formatting.c:1618
const char * progname
Definition: pg_standby.c:37
char * escape_single_quotes_ascii(const char *src)
Definition: quotes.c:33
#define _(x)
Definition: elog.c:84
static void GenerateRecoveryConf ( PGconn conn)
static

Definition at line 1572 of file pg_basebackup.c.

References _, appendConnStrVal(), appendPQExpBuffer(), appendPQExpBufferChar(), appendPQExpBufferStr(), createPQExpBuffer(), PQExpBufferData::data, disconnect_and_exit(), escape_quotes(), free, initPQExpBuffer(), _PQconninfoOption::keyword, PQExpBufferData::len, NULL, PQconninfo(), PQconninfoFree(), PQExpBufferBroken, PQExpBufferDataBroken, progname, replication_slot, termPQExpBuffer(), and _PQconninfoOption::val.

Referenced by BaseBackup().

1573 {
1574  PQconninfoOption *connOptions;
1576  PQExpBufferData conninfo_buf;
1577  char *escaped;
1578 
1580  if (!recoveryconfcontents)
1581  {
1582  fprintf(stderr, _("%s: out of memory\n"), progname);
1584  }
1585 
1586  connOptions = PQconninfo(conn);
1587  if (connOptions == NULL)
1588  {
1589  fprintf(stderr, _("%s: out of memory\n"), progname);
1591  }
1592 
1593  appendPQExpBufferStr(recoveryconfcontents, "standby_mode = 'on'\n");
1594 
1595  initPQExpBuffer(&conninfo_buf);
1596  for (option = connOptions; option && option->keyword; option++)
1597  {
1598  /*
1599  * Do not emit this setting if: - the setting is "replication",
1600  * "dbname" or "fallback_application_name", since these would be
1601  * overridden by the libpqwalreceiver module anyway. - not set or
1602  * empty.
1603  */
1604  if (strcmp(option->keyword, "replication") == 0 ||
1605  strcmp(option->keyword, "dbname") == 0 ||
1606  strcmp(option->keyword, "fallback_application_name") == 0 ||
1607  (option->val == NULL) ||
1608  (option->val != NULL && option->val[0] == '\0'))
1609  continue;
1610 
1611  /* Separate key-value pairs with spaces */
1612  if (conninfo_buf.len != 0)
1613  appendPQExpBufferChar(&conninfo_buf, ' ');
1614 
1615  /*
1616  * Write "keyword=value" pieces, the value string is escaped and/or
1617  * quoted if necessary.
1618  */
1619  appendPQExpBuffer(&conninfo_buf, "%s=", option->keyword);
1620  appendConnStrVal(&conninfo_buf, option->val);
1621  }
1622 
1623  /*
1624  * Escape the connection string, so that it can be put in the config file.
1625  * Note that this is different from the escaping of individual connection
1626  * options above!
1627  */
1628  escaped = escape_quotes(conninfo_buf.data);
1629  appendPQExpBuffer(recoveryconfcontents, "primary_conninfo = '%s'\n", escaped);
1630  free(escaped);
1631 
1632  if (replication_slot)
1633  {
1634  escaped = escape_quotes(replication_slot);
1635  appendPQExpBuffer(recoveryconfcontents, "primary_slot_name = '%s'\n", replication_slot);
1636  free(escaped);
1637  }
1638 
1640  PQExpBufferDataBroken(conninfo_buf))
1641  {
1642  fprintf(stderr, _("%s: out of memory\n"), progname);
1644  }
1645 
1646  termPQExpBuffer(&conninfo_buf);
1647 
1648  PQconninfoFree(connOptions);
1649 }
static PQExpBuffer recoveryconfcontents
void termPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:128
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:385
void appendConnStrVal(PQExpBuffer buf, const char *str)
Definition: string_utils.c:536
static char * escape_quotes(const char *src)
const char * progname
Definition: pg_standby.c:37
void appendPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:262
void PQconninfoFree(PQconninfoOption *connOptions)
Definition: fe-connect.c:5861
PQconninfoOption * PQconninfo(PGconn *conn)
Definition: fe-connect.c:5820
PQExpBuffer createPQExpBuffer(void)
Definition: pqexpbuffer.c:71
void appendPQExpBufferChar(PQExpBuffer str, char ch)
Definition: pqexpbuffer.c:396
#define free(a)
Definition: header.h:65
#define PQExpBufferDataBroken(buf)
Definition: pqexpbuffer.h:67
#define NULL
Definition: c.h:229
#define PQExpBufferBroken(str)
Definition: pqexpbuffer.h:59
static void disconnect_and_exit(int code)
static char * replication_slot
Definition: pg_basebackup.c:93
#define _(x)
Definition: elog.c:84
void initPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:89
static const char * get_tablespace_mapping ( const char *  dir)
static

Definition at line 1274 of file pg_basebackup.c.

References TablespaceList::head, TablespaceListCell::new_dir, TablespaceListCell::next, and TablespaceListCell::old_dir.

Referenced by BaseBackup(), and ReceiveAndUnpackTarFile().

1275 {
1276  TablespaceListCell *cell;
1277 
1278  for (cell = tablespace_dirs.head; cell; cell = cell->next)
1279  if (strcmp(dir, cell->old_dir) == 0)
1280  return cell->new_dir;
1281 
1282  return dir;
1283 }
static TablespaceList tablespace_dirs
Definition: pg_basebackup.c:78
char old_dir[MAXPGPATH]
Definition: pg_basebackup.c:45
char new_dir[MAXPGPATH]
Definition: pg_basebackup.c:46
struct TablespaceListCell * next
Definition: pg_basebackup.c:44
TablespaceListCell * head
Definition: pg_basebackup.c:51
static int LogStreamerMain ( logstreamer_param param)
static

Definition at line 472 of file pg_basebackup.c.

References _, logstreamer_param::bgconn, compresslevel, CreateWalDirectoryMethod(), CreateWalTarMethod(), StreamCtl::do_sync, do_sync, WalWriteMethod::finish, format, FreeWalDirectoryMethod(), FreeWalTarMethod(), in_log_streamer, StreamCtl::mark_done, MemSet, NULL, StreamCtl::partial_suffix, pg_free(), PQfinish(), progname, psprintf(), reached_end_position(), ReceiveXlogStream(), StreamCtl::replication_slot, replication_slot, StreamCtl::standby_message_timeout, standby_message_timeout, StreamCtl::startpos, logstreamer_param::startptr, StreamCtl::stream_stop, strerror(), StreamCtl::synchronous, StreamCtl::sysidentifier, logstreamer_param::sysidentifier, StreamCtl::temp_slot, logstreamer_param::temp_slot, StreamCtl::timeline, logstreamer_param::timeline, StreamCtl::walmethod, and logstreamer_param::xlog.

Referenced by StartLogStreamer().

473 {
474  StreamCtl stream;
475 
476  in_log_streamer = true;
477 
478  MemSet(&stream, 0, sizeof(stream));
479  stream.startpos = param->startptr;
480  stream.timeline = param->timeline;
481  stream.sysidentifier = param->sysidentifier;
484  stream.synchronous = false;
485  stream.do_sync = do_sync;
486  stream.mark_done = true;
487  stream.partial_suffix = NULL;
489  stream.temp_slot = param->temp_slot;
490  if (stream.temp_slot && !stream.replication_slot)
491  stream.replication_slot = psprintf("pg_basebackup_%d", (int) getpid());
492 
493  if (format == 'p')
494  stream.walmethod = CreateWalDirectoryMethod(param->xlog, 0, do_sync);
495  else
497 
498  if (!ReceiveXlogStream(param->bgconn, &stream))
499 
500  /*
501  * Any errors will already have been reported in the function process,
502  * but we need to tell the parent that we didn't shutdown in a nice
503  * way.
504  */
505  return 1;
506 
507  if (!stream.walmethod->finish())
508  {
509  fprintf(stderr,
510  _("%s: could not finish writing WAL files: %s\n"),
511  progname, strerror(errno));
512  return 1;
513  }
514 
515  PQfinish(param->bgconn);
516 
517  if (format == 'p')
519  else
521  pg_free(stream.walmethod);
522 
523  return 0;
524 }
bool do_sync
Definition: receivelog.h:40
char * psprintf(const char *fmt,...)
Definition: psprintf.c:46
char * sysidentifier
Definition: receivelog.h:34
void PQfinish(PGconn *conn)
Definition: fe-connect.c:3568
static int compresslevel
Definition: pg_basebackup.c:85
#define MemSet(start, val, len)
Definition: c.h:857
XLogRecPtr startpos
Definition: receivelog.h:32
char * partial_suffix
Definition: receivelog.h:46
const char * progname
Definition: pg_standby.c:37
static bool reached_end_position(XLogRecPtr segendpos, uint32 timeline, bool segment_finished)
TimeLineID timeline
Definition: receivelog.h:33
WalWriteMethod * CreateWalDirectoryMethod(const char *basedir, int compression, bool sync)
Definition: walmethods.c:346
bool(* finish)(void)
Definition: walmethods.h:33
char * replication_slot
Definition: receivelog.h:47
bool mark_done
Definition: receivelog.h:39
XLogRecPtr startptr
stream_stop_callback stream_stop
Definition: receivelog.h:43
WalWriteMethod * walmethod
Definition: receivelog.h:45
static int standby_message_timeout
Definition: pg_basebackup.c:90
void FreeWalTarMethod(void)
Definition: walmethods.c:978
static bool in_log_streamer
#define NULL
Definition: c.h:229
WalWriteMethod * CreateWalTarMethod(const char *tarbase, int compression, bool sync)
Definition: walmethods.c:947
bool ReceiveXlogStream(PGconn *conn, StreamCtl *stream)
Definition: receivelog.c:433
bool synchronous
Definition: receivelog.h:38
void pg_free(void *ptr)
Definition: fe_memutils.c:105
const char * strerror(int errnum)
Definition: strerror.c:19
int standby_message_timeout
Definition: receivelog.h:36
static bool do_sync
Definition: pg_basebackup.c:89
static char format
Definition: pg_basebackup.c:80
static char * replication_slot
Definition: pg_basebackup.c:93
bool temp_slot
Definition: receivelog.h:48
#define _(x)
Definition: elog.c:84
void FreeWalDirectoryMethod(void)
Definition: walmethods.c:370
char xlog[MAXPGPATH]
int main ( int  argc,
char **  argv 
)

Definition at line 2064 of file pg_basebackup.c.

References _, BaseBackup(), basedir, canonicalize_path(), cleanup_directories_atexit(), compresslevel, conn, connection_string, dbgetpassword, dbhost, dbport, dbuser, disconnect_and_exit(), do_sync, 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, maxrate, MINIMUM_VERSION_FOR_PG_WAL, no_argument, NO_WAL, noclean, NULL, optarg, optind, parse_max_rate(), pg_strcasecmp(), pg_strdup(), PG_TEXTDOMAIN, PQserverVersion(), progname, psprintf(), replication_slot, required_argument, set_pglocale_pgservice(), showprogress, standby_message_timeout, STREAM_WAL, strerror(), success, tablespace_list_append(), temp_replication_slot, usage(), verbose, verify_dir_is_empty_or_create(), writerecoveryconf, xlog_dir, and Z_DEFAULT_COMPRESSION.

2065 {
2066  static struct option long_options[] = {
2067  {"help", no_argument, NULL, '?'},
2068  {"version", no_argument, NULL, 'V'},
2069  {"pgdata", required_argument, NULL, 'D'},
2070  {"format", required_argument, NULL, 'F'},
2071  {"checkpoint", required_argument, NULL, 'c'},
2072  {"max-rate", required_argument, NULL, 'r'},
2073  {"write-recovery-conf", no_argument, NULL, 'R'},
2074  {"slot", required_argument, NULL, 'S'},
2075  {"tablespace-mapping", required_argument, NULL, 'T'},
2076  {"wal-method", required_argument, NULL, 'X'},
2077  {"gzip", no_argument, NULL, 'z'},
2078  {"compress", required_argument, NULL, 'Z'},
2079  {"label", required_argument, NULL, 'l'},
2080  {"no-clean", no_argument, NULL, 'n'},
2081  {"no-sync", no_argument, NULL, 'N'},
2082  {"dbname", required_argument, NULL, 'd'},
2083  {"host", required_argument, NULL, 'h'},
2084  {"port", required_argument, NULL, 'p'},
2085  {"username", required_argument, NULL, 'U'},
2086  {"no-password", no_argument, NULL, 'w'},
2087  {"password", no_argument, NULL, 'W'},
2088  {"status-interval", required_argument, NULL, 's'},
2089  {"verbose", no_argument, NULL, 'v'},
2090  {"progress", no_argument, NULL, 'P'},
2091  {"waldir", required_argument, NULL, 1},
2092  {"no-slot", no_argument, NULL, 2},
2093  {NULL, 0, NULL, 0}
2094  };
2095  int c;
2096 
2097  int option_index;
2098  bool no_slot = false;
2099 
2100  progname = get_progname(argv[0]);
2101  set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pg_basebackup"));
2102 
2103  if (argc > 1)
2104  {
2105  if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
2106  {
2107  usage();
2108  exit(0);
2109  }
2110  else if (strcmp(argv[1], "-V") == 0
2111  || strcmp(argv[1], "--version") == 0)
2112  {
2113  puts("pg_basebackup (PostgreSQL) " PG_VERSION);
2114  exit(0);
2115  }
2116  }
2117 
2119 
2120  while ((c = getopt_long(argc, argv, "D:F:r:RT:X:l:nNzZ:d:c:h:p:U:s:S:wWvP",
2121  long_options, &option_index)) != -1)
2122  {
2123  switch (c)
2124  {
2125  case 'D':
2127  break;
2128  case 'F':
2129  if (strcmp(optarg, "p") == 0 || strcmp(optarg, "plain") == 0)
2130  format = 'p';
2131  else if (strcmp(optarg, "t") == 0 || strcmp(optarg, "tar") == 0)
2132  format = 't';
2133  else
2134  {
2135  fprintf(stderr,
2136  _("%s: invalid output format \"%s\", must be \"plain\" or \"tar\"\n"),
2137  progname, optarg);
2138  exit(1);
2139  }
2140  break;
2141  case 'r':
2143  break;
2144  case 'R':
2145  writerecoveryconf = true;
2146  break;
2147  case 'S':
2148 
2149  /*
2150  * When specifying replication slot name, use a permanent
2151  * slot.
2152  */
2154  temp_replication_slot = false;
2155  break;
2156  case 2:
2157  no_slot = true;
2158  break;
2159  case 'T':
2161  break;
2162  case 'X':
2163  if (strcmp(optarg, "n") == 0 ||
2164  strcmp(optarg, "none") == 0)
2165  {
2166  includewal = NO_WAL;
2167  }
2168  else if (strcmp(optarg, "f") == 0 ||
2169  strcmp(optarg, "fetch") == 0)
2170  {
2172  }
2173  else if (strcmp(optarg, "s") == 0 ||
2174  strcmp(optarg, "stream") == 0)
2175  {
2177  }
2178  else
2179  {
2180  fprintf(stderr,
2181  _("%s: invalid wal-method option \"%s\", must be \"fetch\", \"stream\" or \"none\"\n"),
2182  progname, optarg);
2183  exit(1);
2184  }
2185  break;
2186  case 1:
2188  break;
2189  case 'l':
2190  label = pg_strdup(optarg);
2191  break;
2192  case 'n':
2193  noclean = true;
2194  break;
2195  case 'N':
2196  do_sync = false;
2197  break;
2198  case 'z':
2199 #ifdef HAVE_LIBZ
2201 #else
2202  compresslevel = 1; /* will be rejected below */
2203 #endif
2204  break;
2205  case 'Z':
2206  compresslevel = atoi(optarg);
2207  if (compresslevel < 0 || compresslevel > 9)
2208  {
2209  fprintf(stderr, _("%s: invalid compression level \"%s\"\n"),
2210  progname, optarg);
2211  exit(1);
2212  }
2213  break;
2214  case 'c':
2215  if (pg_strcasecmp(optarg, "fast") == 0)
2216  fastcheckpoint = true;
2217  else if (pg_strcasecmp(optarg, "spread") == 0)
2218  fastcheckpoint = false;
2219  else
2220  {
2221  fprintf(stderr, _("%s: invalid checkpoint argument \"%s\", must be \"fast\" or \"spread\"\n"),
2222  progname, optarg);
2223  exit(1);
2224  }
2225  break;
2226  case 'd':
2228  break;
2229  case 'h':
2230  dbhost = pg_strdup(optarg);
2231  break;
2232  case 'p':
2233  dbport = pg_strdup(optarg);
2234  break;
2235  case 'U':
2236  dbuser = pg_strdup(optarg);
2237  break;
2238  case 'w':
2239  dbgetpassword = -1;
2240  break;
2241  case 'W':
2242  dbgetpassword = 1;
2243  break;
2244  case 's':
2245  standby_message_timeout = atoi(optarg) * 1000;
2246  if (standby_message_timeout < 0)
2247  {
2248  fprintf(stderr, _("%s: invalid status interval \"%s\"\n"),
2249  progname, optarg);
2250  exit(1);
2251  }
2252  break;
2253  case 'v':
2254  verbose++;
2255  break;
2256  case 'P':
2257  showprogress = true;
2258  break;
2259  default:
2260 
2261  /*
2262  * getopt_long already emitted a complaint
2263  */
2264  fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
2265  progname);
2266  exit(1);
2267  }
2268  }
2269 
2270  /*
2271  * Any non-option arguments?
2272  */
2273  if (optind < argc)
2274  {
2275  fprintf(stderr,
2276  _("%s: too many command-line arguments (first is \"%s\")\n"),
2277  progname, argv[optind]);
2278  fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
2279  progname);
2280  exit(1);
2281  }
2282 
2283  /*
2284  * Required arguments
2285  */
2286  if (basedir == NULL)
2287  {
2288  fprintf(stderr, _("%s: no target directory specified\n"), progname);
2289  fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
2290  progname);
2291  exit(1);
2292  }
2293 
2294  /*
2295  * Mutually exclusive arguments
2296  */
2297  if (format == 'p' && compresslevel != 0)
2298  {
2299  fprintf(stderr,
2300  _("%s: only tar mode backups can be compressed\n"),
2301  progname);
2302  fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
2303  progname);
2304  exit(1);
2305  }
2306 
2307  if (format == 't' && includewal == STREAM_WAL && strcmp(basedir, "-") == 0)
2308  {
2309  fprintf(stderr,
2310  _("%s: cannot stream transaction logs in tar mode to stdout\n"),
2311  progname);
2312  fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
2313  progname);
2314  exit(1);
2315  }
2316 
2318  {
2319  fprintf(stderr,
2320  _("%s: replication slots can only be used with WAL streaming\n"),
2321  progname);
2322  fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
2323  progname);
2324  exit(1);
2325  }
2326 
2327  if (no_slot)
2328  {
2329  if (replication_slot)
2330  {
2331  fprintf(stderr,
2332  _("%s: --no-slot cannot be used with slot name\n"),
2333  progname);
2334  fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
2335  progname);
2336  exit(1);
2337  }
2338  temp_replication_slot = false;
2339  }
2340 
2341  if (strcmp(xlog_dir, "") != 0)
2342  {
2343  if (format != 'p')
2344  {
2345  fprintf(stderr,
2346  _("%s: transaction log directory location can only be specified in plain mode\n"),
2347  progname);
2348  fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
2349  progname);
2350  exit(1);
2351  }
2352 
2353  /* clean up xlog directory name, check it's absolute */
2355  if (!is_absolute_path(xlog_dir))
2356  {
2357  fprintf(stderr, _("%s: transaction log directory location must be "
2358  "an absolute path\n"), progname);
2359  fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
2360  progname);
2361  exit(1);
2362  }
2363  }
2364 
2365 #ifndef HAVE_LIBZ
2366  if (compresslevel != 0)
2367  {
2368  fprintf(stderr,
2369  _("%s: this build does not support compression\n"),
2370  progname);
2371  exit(1);
2372  }
2373 #endif
2374 
2375  /*
2376  * Verify that the target directory exists, or create it. For plaintext
2377  * backups, always require the directory. For tar backups, require it
2378  * unless we are writing to stdout.
2379  */
2380  if (format == 'p' || strcmp(basedir, "-") != 0)
2382 
2383  /* connection in replication mode to server */
2384  conn = GetConnection();
2385  if (!conn)
2386  {
2387  /* Error message already written in GetConnection() */
2388  exit(1);
2389  }
2390 
2391  /* Create transaction log symlink, if required */
2392  if (strcmp(xlog_dir, "") != 0)
2393  {
2394  char *linkloc;
2395 
2397 
2398  /*
2399  * Form name of the place where the symlink must go. pg_xlog has
2400  * been renamed to pg_wal in post-10 clusters.
2401  */
2402  linkloc = psprintf("%s/%s", basedir,
2404  "pg_xlog" : "pg_wal");
2405 
2406 #ifdef HAVE_SYMLINK
2407  if (symlink(xlog_dir, linkloc) != 0)
2408  {
2409  fprintf(stderr, _("%s: could not create symbolic link \"%s\": %s\n"),
2410  progname, linkloc, strerror(errno));
2412  }
2413 #else
2414  fprintf(stderr, _("%s: symlinks are not supported on this platform\n"));
2416 #endif
2417  free(linkloc);
2418  }
2419 
2420  BaseBackup();
2421 
2422  success = true;
2423  return 0;
2424 }
static IncludeWal includewal
Definition: pg_basebackup.c:86
#define Z_DEFAULT_COMPRESSION
static bool found_existing_pgdata
Definition: pg_basebackup.c:98
static void usage(void)
const char * get_progname(const char *argv0)
Definition: path.c:453
int getopt_long(int argc, char *const argv[], const char *optstring, const struct option *longopts, int *longindex)
Definition: getopt_long.c:57
static int32 parse_max_rate(char *src)
char * psprintf(const char *fmt,...)
Definition: psprintf.c:46
void canonicalize_path(char *path)
Definition: path.c:254
static bool writerecoveryconf
Definition: pg_basebackup.c:88
static int compresslevel
Definition: pg_basebackup.c:85
int pg_strcasecmp(const char *s1, const char *s2)
Definition: pgstrcasecmp.c:36
int PQserverVersion(const PGconn *conn)
Definition: fe-connect.c:6001
const char * progname
Definition: pg_standby.c:37
static char * basedir
Definition: pg_basebackup.c:77
static void BaseBackup(void)
#define required_argument
Definition: getopt_long.h:25
int optind
Definition: getopt.c:51
char * connection_string
Definition: streamutil.c:34
PGconn * conn
Definition: streamutil.c:42
#define MINIMUM_VERSION_FOR_PG_WAL
Definition: pg_basebackup.c:59
static bool found_existing_xlogdir
static bool success
Definition: pg_basebackup.c:96
static int32 maxrate
Definition: pg_basebackup.c:92
char * c
static bool made_new_pgdata
Definition: pg_basebackup.c:97
#define is_absolute_path(filename)
Definition: port.h:77
char * pg_strdup(const char *in)
Definition: fe_memutils.c:85
static int verbose
Definition: pg_basebackup.c:84
static int standby_message_timeout
Definition: pg_basebackup.c:90
static bool showprogress
Definition: pg_basebackup.c:83
int dbgetpassword
Definition: streamutil.c:39
#define no_argument
Definition: getopt_long.h:24
#define PG_TEXTDOMAIN(domain)
Definition: c.h:1012
static bool temp_replication_slot
Definition: pg_basebackup.c:94
static char * label
Definition: pg_basebackup.c:81
char * dbport
Definition: streamutil.c:37
static void cleanup_directories_atexit(void)
#define free(a)
Definition: header.h:65
PGconn * GetConnection(UserMapping *user, bool will_prep_stmt)
Definition: connection.c:97
#define NULL
Definition: c.h:229
char * dbhost
Definition: streamutil.c:35
static char * xlog_dir
Definition: pg_basebackup.c:79
static bool made_new_xlogdir
Definition: pg_basebackup.c:99
static bool fastcheckpoint
Definition: pg_basebackup.c:87
static void tablespace_list_append(const char *arg)
void set_pglocale_pgservice(const char *argv0, const char *app)
Definition: exec.c:550
char * dbuser
Definition: streamutil.c:36
char * optarg
Definition: getopt.c:53
const char * strerror(int errnum)
Definition: strerror.c:19
static bool do_sync
Definition: pg_basebackup.c:89
static void verify_dir_is_empty_or_create(char *dirname, bool *created, bool *found)
static char format
Definition: pg_basebackup.c:80
static void disconnect_and_exit(int code)
static char * replication_slot
Definition: pg_basebackup.c:93
#define _(x)
Definition: elog.c:84
static bool noclean
Definition: pg_basebackup.c:82
static int32 parse_max_rate ( char *  src)
static

Definition at line 788 of file pg_basebackup.c.

References _, MAX_RATE_UPPER, NULL, progname, result, and strerror().

Referenced by main().

789 {
790  double result;
791  char *after_num;
792  char *suffix = NULL;
793 
794  errno = 0;
795  result = strtod(src, &after_num);
796  if (src == after_num)
797  {
798  fprintf(stderr,
799  _("%s: transfer rate \"%s\" is not a valid value\n"),
800  progname, src);
801  exit(1);
802  }
803  if (errno != 0)
804  {
805  fprintf(stderr,
806  _("%s: invalid transfer rate \"%s\": %s\n"),
807  progname, src, strerror(errno));
808  exit(1);
809  }
810 
811  if (result <= 0)
812  {
813  /*
814  * Reject obviously wrong values here.
815  */
816  fprintf(stderr, _("%s: transfer rate must be greater than zero\n"),
817  progname);
818  exit(1);
819  }
820 
821  /*
822  * Evaluate suffix, after skipping over possible whitespace. Lack of
823  * suffix means kilobytes.
824  */
825  while (*after_num != '\0' && isspace((unsigned char) *after_num))
826  after_num++;
827 
828  if (*after_num != '\0')
829  {
830  suffix = after_num;
831  if (*after_num == 'k')
832  {
833  /* kilobyte is the expected unit. */
834  after_num++;
835  }
836  else if (*after_num == 'M')
837  {
838  after_num++;
839  result *= 1024.0;
840  }
841  }
842 
843  /* The rest can only consist of white space. */
844  while (*after_num != '\0' && isspace((unsigned char) *after_num))
845  after_num++;
846 
847  if (*after_num != '\0')
848  {
849  fprintf(stderr,
850  _("%s: invalid --max-rate unit: \"%s\"\n"),
851  progname, suffix);
852  exit(1);
853  }
854 
855  /* Valid integer? */
856  if ((uint64) result != (uint64) ((uint32) result))
857  {
858  fprintf(stderr,
859  _("%s: transfer rate \"%s\" exceeds integer range\n"),
860  progname, src);
861  exit(1);
862  }
863 
864  /*
865  * The range is checked on the server side too, but avoid the server
866  * connection if a nonsensical value was passed.
867  */
868  if (result < MAX_RATE_LOWER || result > MAX_RATE_UPPER)
869  {
870  fprintf(stderr,
871  _("%s: transfer rate \"%s\" is out of range\n"),
872  progname, src);
873  exit(1);
874  }
875 
876  return (int32) result;
877 }
return result
Definition: formatting.c:1618
const char * progname
Definition: pg_standby.c:37
signed int int32
Definition: c.h:256
#define MAX_RATE_UPPER
Definition: basebackup.h:21
unsigned int uint32
Definition: c.h:268
#define NULL
Definition: c.h:229
const char * strerror(int errnum)
Definition: strerror.c:19
#define _(x)
Definition: elog.c:84
static void progress_report ( int  tablespacenum,
const char *  filename,
bool  force 
)
static

Definition at line 702 of file pg_basebackup.c.

References INT64_FORMAT, last_progress_report, ngettext, now(), NULL, showprogress, snprintf(), tablespacecount, totaldone, totalsize, verbose, and VERBOSE_FILENAME_LENGTH.

Referenced by BaseBackup(), main(), ReceiveAndUnpackTarFile(), ReceiveTarFile(), and write_target_range().

703 {
704  int percent;
705  char totaldone_str[32];
706  char totalsize_str[32];
707  pg_time_t now;
708 
709  if (!showprogress)
710  return;
711 
712  now = time(NULL);
713  if (now == last_progress_report && !force)
714  return; /* Max once per second */
715 
717  percent = totalsize ? (int) ((totaldone / 1024) * 100 / totalsize) : 0;
718 
719  /*
720  * Avoid overflowing past 100% or the full size. This may make the total
721  * size number change as we approach the end of the backup (the estimate
722  * will always be wrong if WAL is included), but that's better than having
723  * the done column be bigger than the total.
724  */
725  if (percent > 100)
726  percent = 100;
727  if (totaldone / 1024 > totalsize)
728  totalsize = totaldone / 1024;
729 
730  /*
731  * Separate step to keep platform-dependent format code out of
732  * translatable strings. And we only test for INT64_FORMAT availability
733  * in snprintf, not fprintf.
734  */
735  snprintf(totaldone_str, sizeof(totaldone_str), INT64_FORMAT,
736  totaldone / 1024);
737  snprintf(totalsize_str, sizeof(totalsize_str), INT64_FORMAT, totalsize);
738 
739 #define VERBOSE_FILENAME_LENGTH 35
740  if (verbose)
741  {
742  if (!filename)
743 
744  /*
745  * No filename given, so clear the status line (used for last
746  * call)
747  */
748  fprintf(stderr,
749  ngettext("%*s/%s kB (100%%), %d/%d tablespace %*s",
750  "%*s/%s kB (100%%), %d/%d tablespaces %*s",
752  (int) strlen(totalsize_str),
753  totaldone_str, totalsize_str,
754  tablespacenum, tablespacecount,
755  VERBOSE_FILENAME_LENGTH + 5, "");
756  else
757  {
758  bool truncate = (strlen(filename) > VERBOSE_FILENAME_LENGTH);
759 
760  fprintf(stderr,
761  ngettext("%*s/%s kB (%d%%), %d/%d tablespace (%s%-*.*s)",
762  "%*s/%s kB (%d%%), %d/%d tablespaces (%s%-*.*s)",
764  (int) strlen(totalsize_str),
765  totaldone_str, totalsize_str, percent,
766  tablespacenum, tablespacecount,
767  /* Prefix with "..." if we do leading truncation */
768  truncate ? "..." : "",
771  /* Truncate filename at beginning if it's too long */
772  truncate ? filename + strlen(filename) - VERBOSE_FILENAME_LENGTH + 3 : filename);
773  }
774  }
775  else
776  fprintf(stderr,
777  ngettext("%*s/%s kB (%d%%), %d/%d tablespace",
778  "%*s/%s kB (%d%%), %d/%d tablespaces",
780  (int) strlen(totalsize_str),
781  totaldone_str, totalsize_str, percent,
782  tablespacenum, tablespacecount);
783 
784  fprintf(stderr, "\r");
785 }
int64 pg_time_t
Definition: pgtime.h:23
static pg_time_t last_progress_report
Definition: pg_basebackup.c:91
static int tablespacecount
#define VERBOSE_FILENAME_LENGTH
int snprintf(char *str, size_t count, const char *fmt,...) pg_attribute_printf(3
static uint64 totaldone
static uint64 totalsize
static int verbose
Definition: pg_basebackup.c:84
static bool showprogress
Definition: pg_basebackup.c:83
#define ngettext(s, p, n)
Definition: c.h:127
#define NULL
Definition: c.h:229
#define INT64_FORMAT
Definition: c.h:315
static char * filename
Definition: pg_dumpall.c:87
Datum now(PG_FUNCTION_ARGS)
Definition: timestamp.c:1533
static bool reached_end_position ( XLogRecPtr  segendpos,
uint32  timeline,
bool  segment_finished 
)
static

Definition at line 379 of file pg_basebackup.c.

References _, bgpipe, has_xlogendptr, MemSet, NULL, progname, read, select, strerror(), and xlogendptr.

Referenced by LogStreamerMain().

381 {
382  if (!has_xlogendptr)
383  {
384 #ifndef WIN32
385  fd_set fds;
386  struct timeval tv;
387  int r;
388 
389  /*
390  * Don't have the end pointer yet - check our pipe to see if it has
391  * been sent yet.
392  */
393  FD_ZERO(&fds);
394  FD_SET(bgpipe[0], &fds);
395 
396  MemSet(&tv, 0, sizeof(tv));
397 
398  r = select(bgpipe[0] + 1, &fds, NULL, NULL, &tv);
399  if (r == 1)
400  {
401  char xlogend[64];
402  uint32 hi,
403  lo;
404 
405  MemSet(xlogend, 0, sizeof(xlogend));
406  r = read(bgpipe[0], xlogend, sizeof(xlogend) - 1);
407  if (r < 0)
408  {
409  fprintf(stderr, _("%s: could not read from ready pipe: %s\n"),
410  progname, strerror(errno));
411  exit(1);
412  }
413 
414  if (sscanf(xlogend, "%X/%X", &hi, &lo) != 2)
415  {
416  fprintf(stderr,
417  _("%s: could not parse transaction log location \"%s\"\n"),
418  progname, xlogend);
419  exit(1);
420  }
421  xlogendptr = ((uint64) hi) << 32 | lo;
422  has_xlogendptr = 1;
423 
424  /*
425  * Fall through to check if we've reached the point further
426  * already.
427  */
428  }
429  else
430  {
431  /*
432  * No data received on the pipe means we don't know the end
433  * position yet - so just say it's not time to stop yet.
434  */
435  return false;
436  }
437 #else
438 
439  /*
440  * On win32, has_xlogendptr is set by the main thread, so if it's not
441  * set here, we just go back and wait until it shows up.
442  */
443  return false;
444 #endif
445  }
446 
447  /*
448  * At this point we have an end pointer, so compare it to the current
449  * position to figure out if it's time to stop.
450  */
451  if (segendpos >= xlogendptr)
452  return true;
453 
454  /*
455  * Have end pointer, but haven't reached it yet - so tell the caller to
456  * keep streaming.
457  */
458  return false;
459 }
static int bgpipe[2]
#define MemSet(start, val, len)
Definition: c.h:857
#define select(n, r, w, e, timeout)
Definition: win32.h:384
const char * progname
Definition: pg_standby.c:37
static int has_xlogendptr
unsigned int uint32
Definition: c.h:268
#define NULL
Definition: c.h:229
static XLogRecPtr xlogendptr
const char * strerror(int errnum)
Definition: strerror.c:19
#define _(x)
Definition: elog.c:84
#define read(a, b, c)
Definition: win32.h:18
static void ReceiveAndUnpackTarFile ( PGconn conn,
PGresult res,
int  rownum 
)
static

Definition at line 1296 of file pg_basebackup.c.

References _, basedir, copybuf, disconnect_and_exit(), filename, get_tablespace_mapping(), MAXPGPATH, mkdir, NULL, pg_str_endswith(), pgoff_t, PGRES_COPY_OUT, PQerrorMessage(), PQfreemem(), PQgetCopyData(), PQgetisnull(), PQgetResult(), PQgetvalue(), PQresultStatus(), progname, progress_report(), read_tar_number(), snprintf(), strerror(), strlcpy(), totaldone, writerecoveryconf, and WriteRecoveryConf().

Referenced by BaseBackup().

1297 {
1298  char current_path[MAXPGPATH];
1299  char filename[MAXPGPATH];
1300  const char *mapped_tblspc_path;
1301  pgoff_t current_len_left = 0;
1302  int current_padding = 0;
1303  bool basetablespace;
1304  char *copybuf = NULL;
1305  FILE *file = NULL;
1306 
1307  basetablespace = PQgetisnull(res, rownum, 0);
1308  if (basetablespace)
1309  strlcpy(current_path, basedir, sizeof(current_path));
1310  else
1311  strlcpy(current_path,
1312  get_tablespace_mapping(PQgetvalue(res, rownum, 1)),
1313  sizeof(current_path));
1314 
1315  /*
1316  * Get the COPY data
1317  */
1318  res = PQgetResult(conn);
1319  if (PQresultStatus(res) != PGRES_COPY_OUT)
1320  {
1321  fprintf(stderr, _("%s: could not get COPY data stream: %s"),
1322  progname, PQerrorMessage(conn));
1324  }
1325 
1326  while (1)
1327  {
1328  int r;
1329 
1330  if (copybuf != NULL)
1331  {
1332  PQfreemem(copybuf);
1333  copybuf = NULL;
1334  }
1335 
1336  r = PQgetCopyData(conn, &copybuf, 0);
1337 
1338  if (r == -1)
1339  {
1340  /*
1341  * End of chunk
1342  */
1343  if (file)
1344  fclose(file);
1345 
1346  break;
1347  }
1348  else if (r == -2)
1349  {
1350  fprintf(stderr, _("%s: could not read COPY data: %s"),
1351  progname, PQerrorMessage(conn));
1353  }
1354 
1355  if (file == NULL)
1356  {
1357  int filemode;
1358 
1359  /*
1360  * No current file, so this must be the header for a new file
1361  */
1362  if (r != 512)
1363  {
1364  fprintf(stderr, _("%s: invalid tar block header size: %d\n"),
1365  progname, r);
1367  }
1368  totaldone += 512;
1369 
1370  current_len_left = read_tar_number(&copybuf[124], 12);
1371 
1372  /* Set permissions on the file */
1373  filemode = read_tar_number(&copybuf[100], 8);
1374 
1375  /*
1376  * All files are padded up to 512 bytes
1377  */
1378  current_padding =
1379  ((current_len_left + 511) & ~511) - current_len_left;
1380 
1381  /*
1382  * First part of header is zero terminated filename
1383  */
1384  snprintf(filename, sizeof(filename), "%s/%s", current_path,
1385  copybuf);
1386  if (filename[strlen(filename) - 1] == '/')
1387  {
1388  /*
1389  * Ends in a slash means directory or symlink to directory
1390  */
1391  if (copybuf[156] == '5')
1392  {
1393  /*
1394  * Directory
1395  */
1396  filename[strlen(filename) - 1] = '\0'; /* Remove trailing slash */
1397  if (mkdir(filename, S_IRWXU) != 0)
1398  {
1399  /*
1400  * When streaming WAL, pg_wal (or pg_xlog for pre-9.6
1401  * clusters) will have been created by the wal receiver
1402  * process. Also, when transaction log directory location
1403  * was specified, pg_wal (or pg_xlog) has already been
1404  * created as a symbolic link before starting the actual
1405  * backup. So just ignore creation failures on related
1406  * directories.
1407  */
1408  if (!((pg_str_endswith(filename, "/pg_wal") ||
1409  pg_str_endswith(filename, "/pg_xlog")||
1410  pg_str_endswith(filename, "/archive_status")) &&
1411  errno == EEXIST))
1412  {
1413  fprintf(stderr,
1414  _("%s: could not create directory \"%s\": %s\n"),
1415  progname, filename, strerror(errno));
1417  }
1418  }
1419 #ifndef WIN32
1420  if (chmod(filename, (mode_t) filemode))
1421  fprintf(stderr,
1422  _("%s: could not set permissions on directory \"%s\": %s\n"),
1423  progname, filename, strerror(errno));
1424 #endif
1425  }
1426  else if (copybuf[156] == '2')
1427  {
1428  /*
1429  * Symbolic link
1430  *
1431  * It's most likely a link in pg_tblspc directory, to the
1432  * location of a tablespace. Apply any tablespace mapping
1433  * given on the command line (--tablespace-mapping). (We
1434  * blindly apply the mapping without checking that the
1435  * link really is inside pg_tblspc. We don't expect there
1436  * to be other symlinks in a data directory, but if there
1437  * are, you can call it an undocumented feature that you
1438  * can map them too.)
1439  */
1440  filename[strlen(filename) - 1] = '\0'; /* Remove trailing slash */
1441 
1442  mapped_tblspc_path = get_tablespace_mapping(&copybuf[157]);
1443  if (symlink(mapped_tblspc_path, filename) != 0)
1444  {
1445  fprintf(stderr,
1446  _("%s: could not create symbolic link from \"%s\" to \"%s\": %s\n"),
1447  progname, filename, mapped_tblspc_path,
1448  strerror(errno));
1450  }
1451  }
1452  else
1453  {
1454  fprintf(stderr,
1455  _("%s: unrecognized link indicator \"%c\"\n"),
1456  progname, copybuf[156]);
1458  }
1459  continue; /* directory or link handled */
1460  }
1461 
1462  /*
1463  * regular file
1464  */
1465  file = fopen(filename, "wb");
1466  if (!file)
1467  {
1468  fprintf(stderr, _("%s: could not create file \"%s\": %s\n"),
1469  progname, filename, strerror(errno));
1471  }
1472 
1473 #ifndef WIN32
1474  if (chmod(filename, (mode_t) filemode))
1475  fprintf(stderr, _("%s: could not set permissions on file \"%s\": %s\n"),
1476  progname, filename, strerror(errno));
1477 #endif
1478 
1479  if (current_len_left == 0)
1480  {
1481  /*
1482  * Done with this file, next one will be a new tar header
1483  */
1484  fclose(file);
1485  file = NULL;
1486  continue;
1487  }
1488  } /* new file */
1489  else
1490  {
1491  /*
1492  * Continuing blocks in existing file
1493  */
1494  if (current_len_left == 0 && r == current_padding)
1495  {
1496  /*
1497  * Received the padding block for this file, ignore it and
1498  * close the file, then move on to the next tar header.
1499  */
1500  fclose(file);
1501  file = NULL;
1502  totaldone += r;
1503  continue;
1504  }
1505 
1506  if (fwrite(copybuf, r, 1, file) != 1)
1507  {
1508  fprintf(stderr, _("%s: could not write to file \"%s\": %s\n"),
1509  progname, filename, strerror(errno));
1511  }
1512  totaldone += r;
1513  progress_report(rownum, filename, false);
1514 
1515  current_len_left -= r;
1516  if (current_len_left == 0 && current_padding == 0)
1517  {
1518  /*
1519  * Received the last block, and there is no padding to be
1520  * expected. Close the file and move on to the next tar
1521  * header.
1522  */
1523  fclose(file);
1524  file = NULL;
1525  continue;
1526  }
1527  } /* continuing data in existing file */
1528  } /* loop over all data blocks */
1529  progress_report(rownum, filename, true);
1530 
1531  if (file != NULL)
1532  {
1533  fprintf(stderr,
1534  _("%s: COPY stream ended before last file was finished\n"),
1535  progname);
1537  }
1538 
1539  if (copybuf != NULL)
1540  PQfreemem(copybuf);
1541 
1542  if (basetablespace && writerecoveryconf)
1544 
1545  /*
1546  * No data is synced here, everything is done for all tablespaces at the
1547  * end.
1548  */
1549 }
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:6011
char * PQgetvalue(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3067
bool pg_str_endswith(const char *str, const char *end)
Definition: string.c:31
uint64 read_tar_number(const char *s, int len)
Definition: tar.c:56
#define mkdir(a, b)
Definition: win32.h:65
static bool writerecoveryconf
Definition: pg_basebackup.c:88
int snprintf(char *str, size_t count, const char *fmt,...) pg_attribute_printf(3
const char * progname
Definition: pg_standby.c:37
static char * basedir
Definition: pg_basebackup.c:77
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2596
int PQgetCopyData(PGconn *conn, char **buffer, int async)
Definition: fe-exec.c:2377
#define MAXPGPATH
static uint64 totaldone
static const char * get_tablespace_mapping(const char *dir)
static void progress_report(int tablespacenum, const char *filename, bool force)
#define pgoff_t
Definition: win32.h:241
static void WriteRecoveryConf(void)
StringInfo copybuf
Definition: tablesync.c:109
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
#define NULL
Definition: c.h:229
static char * filename
Definition: pg_dumpall.c:87
const char * strerror(int errnum)
Definition: strerror.c:19
static void disconnect_and_exit(int code)
int PQgetisnull(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3092
#define _(x)
Definition: elog.c:84
void PQfreemem(void *ptr)
Definition: fe-exec.c:3200
PGresult * PQgetResult(PGconn *conn)
Definition: fe-exec.c:1702
static void ReceiveTarFile ( PGconn conn,
PGresult res,
int  rownum 
)
static

Definition at line 929 of file pg_basebackup.c.

References _, basedir, compresslevel, copybuf, PQExpBufferData::data, disconnect_and_exit(), do_sync, filename, fsync_fname(), header(), PQExpBufferData::len, MAXPGPATH, MemSet, NULL, pgoff_t, PGRES_COPY_OUT, PQerrorMessage(), PQfreemem(), PQgetCopyData(), PQgetisnull(), PQgetResult(), PQgetvalue(), PQresultStatus(), progname, progress_report(), read_tar_number(), snprintf(), strerror(), tarCreateHeader(), totaldone, WRITE_TAR_DATA, and writerecoveryconf.

Referenced by BaseBackup().

930 {
931  char filename[MAXPGPATH];
932  char *copybuf = NULL;
933  FILE *tarfile = NULL;
934  char tarhdr[512];
935  bool basetablespace = PQgetisnull(res, rownum, 0);
936  bool in_tarhdr = true;
937  bool skip_file = false;
938  size_t tarhdrsz = 0;
939  pgoff_t filesz = 0;
940 
941 #ifdef HAVE_LIBZ
942  gzFile ztarfile = NULL;
943 #endif
944 
945  if (basetablespace)
946  {
947  /*
948  * Base tablespaces
949  */
950  if (strcmp(basedir, "-") == 0)
951  {
952 #ifdef HAVE_LIBZ
953  if (compresslevel != 0)
954  {
955  ztarfile = gzdopen(dup(fileno(stdout)), "wb");
956  if (gzsetparams(ztarfile, compresslevel,
957  Z_DEFAULT_STRATEGY) != Z_OK)
958  {
959  fprintf(stderr,
960  _("%s: could not set compression level %d: %s\n"),
961  progname, compresslevel, get_gz_error(ztarfile));
963  }
964  }
965  else
966 #endif
967  tarfile = stdout;
968  strcpy(filename, "-");
969  }
970  else
971  {
972 #ifdef HAVE_LIBZ
973  if (compresslevel != 0)
974  {
975  snprintf(filename, sizeof(filename), "%s/base.tar.gz", basedir);
976  ztarfile = gzopen(filename, "wb");
977  if (gzsetparams(ztarfile, compresslevel,
978  Z_DEFAULT_STRATEGY) != Z_OK)
979  {
980  fprintf(stderr,
981  _("%s: could not set compression level %d: %s\n"),
982  progname, compresslevel, get_gz_error(ztarfile));
984  }
985  }
986  else
987 #endif
988  {
989  snprintf(filename, sizeof(filename), "%s/base.tar", basedir);
990  tarfile = fopen(filename, "wb");
991  }
992  }
993  }
994  else
995  {
996  /*
997  * Specific tablespace
998  */
999 #ifdef HAVE_LIBZ
1000  if (compresslevel != 0)
1001  {
1002  snprintf(filename, sizeof(filename), "%s/%s.tar.gz", basedir,
1003  PQgetvalue(res, rownum, 0));
1004  ztarfile = gzopen(filename, "wb");
1005  if (gzsetparams(ztarfile, compresslevel,
1006  Z_DEFAULT_STRATEGY) != Z_OK)
1007  {
1008  fprintf(stderr,
1009  _("%s: could not set compression level %d: %s\n"),
1010  progname, compresslevel, get_gz_error(ztarfile));
1012  }
1013  }
1014  else
1015 #endif
1016  {
1017  snprintf(filename, sizeof(filename), "%s/%s.tar", basedir,
1018  PQgetvalue(res, rownum, 0));
1019  tarfile = fopen(filename, "wb");
1020  }
1021  }
1022 
1023 #ifdef HAVE_LIBZ
1024  if (compresslevel != 0)
1025  {
1026  if (!ztarfile)
1027  {
1028  /* Compression is in use */
1029  fprintf(stderr,
1030  _("%s: could not create compressed file \"%s\": %s\n"),
1031  progname, filename, get_gz_error(ztarfile));
1033  }
1034  }
1035  else
1036 #endif
1037  {
1038  /* Either no zlib support, or zlib support but compresslevel = 0 */
1039  if (!tarfile)
1040  {
1041  fprintf(stderr, _("%s: could not create file \"%s\": %s\n"),
1042  progname, filename, strerror(errno));
1044  }
1045  }
1046 
1047  /*
1048  * Get the COPY data stream
1049  */
1050  res = PQgetResult(conn);
1051  if (PQresultStatus(res) != PGRES_COPY_OUT)
1052  {
1053  fprintf(stderr, _("%s: could not get COPY data stream: %s"),
1054  progname, PQerrorMessage(conn));
1056  }
1057 
1058  while (1)
1059  {
1060  int r;
1061 
1062  if (copybuf != NULL)
1063  {
1064  PQfreemem(copybuf);
1065  copybuf = NULL;
1066  }
1067 
1068  r = PQgetCopyData(conn, &copybuf, 0);
1069  if (r == -1)
1070  {
1071  /*
1072  * End of chunk. If requested, and this is the base tablespace,
1073  * write recovery.conf into the tarfile. When done, close the file
1074  * (but not stdout).
1075  *
1076  * Also, write two completely empty blocks at the end of the tar
1077  * file, as required by some tar programs.
1078  */
1079  char zerobuf[1024];
1080 
1081  MemSet(zerobuf, 0, sizeof(zerobuf));
1082 
1083  if (basetablespace && writerecoveryconf)
1084  {
1085  char header[512];
1086  int padding;
1087 
1088  tarCreateHeader(header, "recovery.conf", NULL,
1090  0600, 04000, 02000,
1091  time(NULL));
1092 
1093  padding = ((recoveryconfcontents->len + 511) & ~511) - recoveryconfcontents->len;
1094 
1095  WRITE_TAR_DATA(header, sizeof(header));
1097  if (padding)
1098  WRITE_TAR_DATA(zerobuf, padding);
1099  }
1100 
1101  /* 2 * 512 bytes empty data at end of file */
1102  WRITE_TAR_DATA(zerobuf, sizeof(zerobuf));
1103 
1104 #ifdef HAVE_LIBZ
1105  if (ztarfile != NULL)
1106  {
1107  if (gzclose(ztarfile) != 0)
1108  {
1109  fprintf(stderr,
1110  _("%s: could not close compressed file \"%s\": %s\n"),
1111  progname, filename, get_gz_error(ztarfile));
1113  }
1114  }
1115  else
1116 #endif
1117  {
1118  if (strcmp(basedir, "-") != 0)
1119  {
1120  if (fclose(tarfile) != 0)
1121  {
1122  fprintf(stderr,
1123  _("%s: could not close file \"%s\": %s\n"),
1124  progname, filename, strerror(errno));
1126  }
1127  }
1128  }
1129 
1130  break;
1131  }
1132  else if (r == -2)
1133  {
1134  fprintf(stderr, _("%s: could not read COPY data: %s"),
1135  progname, PQerrorMessage(conn));
1137  }
1138 
1139  if (!writerecoveryconf || !basetablespace)
1140  {
1141  /*
1142  * When not writing recovery.conf, or when not working on the base
1143  * tablespace, we never have to look for an existing recovery.conf
1144  * file in the stream.
1145  */
1146  WRITE_TAR_DATA(copybuf, r);
1147  }
1148  else
1149  {
1150  /*
1151  * Look for a recovery.conf in the existing tar stream. If it's
1152  * there, we must skip it so we can later overwrite it with our
1153  * own version of the file.
1154  *
1155  * To do this, we have to process the individual files inside the
1156  * TAR stream. The stream consists of a header and zero or more
1157  * chunks, all 512 bytes long. The stream from the server is
1158  * broken up into smaller pieces, so we have to track the size of
1159  * the files to find the next header structure.
1160  */
1161  int rr = r;
1162  int pos = 0;
1163 
1164  while (rr > 0)
1165  {
1166  if (in_tarhdr)
1167  {
1168  /*
1169  * We're currently reading a header structure inside the
1170  * TAR stream, i.e. the file metadata.
1171  */
1172  if (tarhdrsz < 512)
1173  {
1174  /*
1175  * Copy the header structure into tarhdr in case the
1176  * header is not aligned to 512 bytes or it's not
1177  * returned in whole by the last PQgetCopyData call.
1178  */
1179  int hdrleft;
1180  int bytes2copy;
1181 
1182  hdrleft = 512 - tarhdrsz;
1183  bytes2copy = (rr > hdrleft ? hdrleft : rr);
1184 
1185  memcpy(&tarhdr[tarhdrsz], copybuf + pos, bytes2copy);
1186 
1187  rr -= bytes2copy;
1188  pos += bytes2copy;
1189  tarhdrsz += bytes2copy;
1190  }
1191  else
1192  {
1193  /*
1194  * We have the complete header structure in tarhdr,
1195  * look at the file metadata: - the subsequent file
1196  * contents have to be skipped if the filename is
1197  * recovery.conf - find out the size of the file
1198  * padded to the next multiple of 512
1199  */
1200  int padding;
1201 
1202  skip_file = (strcmp(&tarhdr[0], "recovery.conf") == 0);
1203 
1204  filesz = read_tar_number(&tarhdr[124], 12);
1205 
1206  padding = ((filesz + 511) & ~511) - filesz;
1207  filesz += padding;
1208 
1209  /* Next part is the file, not the header */
1210  in_tarhdr = false;
1211 
1212  /*
1213  * If we're not skipping the file, write the tar
1214  * header unmodified.
1215  */
1216  if (!skip_file)
1217  WRITE_TAR_DATA(tarhdr, 512);
1218  }
1219  }
1220  else
1221  {
1222  /*
1223  * We're processing a file's contents.
1224  */
1225  if (filesz > 0)
1226  {
1227  /*
1228  * We still have data to read (and possibly write).
1229  */
1230  int bytes2write;
1231 
1232  bytes2write = (filesz > rr ? rr : filesz);
1233 
1234  if (!skip_file)
1235  WRITE_TAR_DATA(copybuf + pos, bytes2write);
1236 
1237  rr -= bytes2write;
1238  pos += bytes2write;
1239  filesz -= bytes2write;
1240  }
1241  else
1242  {
1243  /*
1244  * No more data in the current file, the next piece of
1245  * data (if any) will be a new file header structure.
1246  */
1247  in_tarhdr = true;
1248  skip_file = false;
1249  tarhdrsz = 0;
1250  filesz = 0;
1251  }
1252  }
1253  }
1254  }
1255  totaldone += r;
1256  progress_report(rownum, filename, false);
1257  } /* while (1) */
1258  progress_report(rownum, filename, true);
1259 
1260  if (copybuf != NULL)
1261  PQfreemem(copybuf);
1262 
1263  /* sync the resulting tar file, errors are not considered fatal */
1264  if (do_sync && strcmp(basedir, "-") != 0)
1265  (void) fsync_fname(filename, false, progname);
1266 }
static PQExpBuffer recoveryconfcontents
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:6011
char * PQgetvalue(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3067
uint64 read_tar_number(const char *s, int len)
Definition: tar.c:56
void fsync_fname(const char *fname, bool isdir)
Definition: fd.c:567
static bool writerecoveryconf
Definition: pg_basebackup.c:88
static int compresslevel
Definition: pg_basebackup.c:85
#define MemSet(start, val, len)
Definition: c.h:857
int snprintf(char *str, size_t count, const char *fmt,...) pg_attribute_printf(3
const char * progname
Definition: pg_standby.c:37
static char * basedir
Definition: pg_basebackup.c:77
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2596
int PQgetCopyData(PGconn *conn, char **buffer, int async)
Definition: fe-exec.c:2377
#define MAXPGPATH
static uint64 totaldone
static void progress_report(int tablespacenum, const char *filename, bool force)
enum tarError tarCreateHeader(char *h, const char *filename, const char *linktarget, pgoff_t size, mode_t mode, uid_t uid, gid_t gid, time_t mtime)
Definition: tar.c:112
#define pgoff_t
Definition: win32.h:241
StringInfo copybuf
Definition: tablesync.c:109
#define NULL
Definition: c.h:229
static void header(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:207
#define WRITE_TAR_DATA(buf, sz)
static char * filename
Definition: pg_dumpall.c:87
const char * strerror(int errnum)
Definition: strerror.c:19
static bool do_sync
Definition: pg_basebackup.c:89
static void disconnect_and_exit(int code)
int PQgetisnull(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3092
#define _(x)
Definition: elog.c:84
void PQfreemem(void *ptr)
Definition: fe-exec.c:3200
PGresult * PQgetResult(PGconn *conn)
Definition: fe-exec.c:1702
static void StartLogStreamer ( char *  startpos,
uint32  timeline,
char *  sysidentifier 
)
static

Definition at line 532 of file pg_basebackup.c.

References _, basedir, bgchild, logstreamer_param::bgconn, bgpipe, conn, disconnect_and_exit(), format, GetConnection(), LogStreamerMain(), MAXPGPATH, MINIMUM_VERSION_FOR_PG_WAL, MINIMUM_VERSION_FOR_TEMP_SLOTS, NULL, pg_malloc0(), pg_mkdir_p(), PQserverVersion(), progname, snprintf(), logstreamer_param::startptr, strerror(), logstreamer_param::sysidentifier, temp_replication_slot, logstreamer_param::temp_slot, logstreamer_param::timeline, and logstreamer_param::xlog.

Referenced by BaseBackup().

533 {
534  logstreamer_param *param;
535  uint32 hi,
536  lo;
537  char statusdir[MAXPGPATH];
538 
539  param = pg_malloc0(sizeof(logstreamer_param));
540  param->timeline = timeline;
541  param->sysidentifier = sysidentifier;
542 
543  /* Convert the starting position */
544  if (sscanf(startpos, "%X/%X", &hi, &lo) != 2)
545  {
546  fprintf(stderr,
547  _("%s: could not parse transaction log location \"%s\"\n"),
548  progname, startpos);
550  }
551  param->startptr = ((uint64) hi) << 32 | lo;
552  /* Round off to even segment position */
553  param->startptr -= param->startptr % XLOG_SEG_SIZE;
554 
555 #ifndef WIN32
556  /* Create our background pipe */
557  if (pipe(bgpipe) < 0)
558  {
559  fprintf(stderr,
560  _("%s: could not create pipe for background process: %s\n"),
561  progname, strerror(errno));
563  }
564 #endif
565 
566  /* Get a second connection */
567  param->bgconn = GetConnection();
568  if (!param->bgconn)
569  /* Error message already written in GetConnection() */
570  exit(1);
571 
572  /* In post-10 cluster, pg_xlog has been renamed to pg_wal */
573  snprintf(param->xlog, sizeof(param->xlog), "%s/%s",
574  basedir,
576  "pg_xlog" : "pg_wal");
577 
578  /* Temporary replication slots are only supported in 10 and newer */
580  param->temp_slot = false;
581  else
583 
584  if (format == 'p')
585  {
586  /*
587  * Create pg_wal/archive_status or pg_xlog/archive_status (and thus
588  * pg_wal or pg_xlog) depending on the target server so we can write to
589  * basedir/pg_wal or basedir/pg_xlog as the directory entry in the tar
590  * file may arrive later.
591  */
592  snprintf(statusdir, sizeof(statusdir), "%s/%s/archive_status",
593  basedir,
595  "pg_xlog" : "pg_wal");
596 
597  if (pg_mkdir_p(statusdir, S_IRWXU) != 0 && errno != EEXIST)
598  {
599  fprintf(stderr,
600  _("%s: could not create directory \"%s\": %s\n"),
601  progname, statusdir, strerror(errno));
603  }
604  }
605 
606  /*
607  * Start a child process and tell it to start streaming. On Unix, this is
608  * a fork(). On Windows, we create a thread.
609  */
610 #ifndef WIN32
611  bgchild = fork();
612  if (bgchild == 0)
613  {
614  /* in child process */
615  exit(LogStreamerMain(param));
616  }
617  else if (bgchild < 0)
618  {
619  fprintf(stderr, _("%s: could not create background process: %s\n"),
620  progname, strerror(errno));
622  }
623 
624  /*
625  * Else we are in the parent process and all is well.
626  */
627 #else /* WIN32 */
628  bgchild = _beginthreadex(NULL, 0, (void *) LogStreamerMain, param, 0, NULL);
629  if (bgchild == 0)
630  {
631  fprintf(stderr, _("%s: could not create background thread: %s\n"),
632  progname, strerror(errno));
634  }
635 #endif
636 }
static int bgpipe[2]
int pg_mkdir_p(char *path, int omode)
Definition: pgmkdirp.c:57
int snprintf(char *str, size_t count, const char *fmt,...) pg_attribute_printf(3
int PQserverVersion(const PGconn *conn)
Definition: fe-connect.c:6001
const char * progname
Definition: pg_standby.c:37
static char * basedir
Definition: pg_basebackup.c:77
void * pg_malloc0(size_t size)
Definition: fe_memutils.c:53
PGconn * conn
Definition: streamutil.c:42
#define MAXPGPATH
#define MINIMUM_VERSION_FOR_PG_WAL
Definition: pg_basebackup.c:59
unsigned int uint32
Definition: c.h:268
XLogRecPtr startptr
static bool temp_replication_slot
Definition: pg_basebackup.c:94
PGconn * GetConnection(UserMapping *user, bool will_prep_stmt)
Definition: connection.c:97
#define NULL
Definition: c.h:229
static XLogRecPtr startpos
static pid_t bgchild
const char * strerror(int errnum)
Definition: strerror.c:19
static char format
Definition: pg_basebackup.c:80
static void disconnect_and_exit(int code)
static int LogStreamerMain(logstreamer_param *param)
#define _(x)
Definition: elog.c:84
#define MINIMUM_VERSION_FOR_TEMP_SLOTS
Definition: pg_basebackup.c:64
char xlog[MAXPGPATH]
static void tablespace_list_append ( const char *  arg)
static

Definition at line 238 of file pg_basebackup.c.

References _, canonicalize_path(), TablespaceList::head, is_absolute_path, MAXPGPATH, TablespaceListCell::new_dir, TablespaceListCell::next, TablespaceListCell::old_dir, pg_malloc0(), progname, and TablespaceList::tail.

Referenced by main().

239 {
241  char *dst;
242  char *dst_ptr;
243  const char *arg_ptr;
244 
245  dst_ptr = dst = cell->old_dir;
246  for (arg_ptr = arg; *arg_ptr; arg_ptr++)
247  {
248  if (dst_ptr - dst >= MAXPGPATH)
249  {
250  fprintf(stderr, _("%s: directory name too long\n"), progname);
251  exit(1);
252  }
253 
254  if (*arg_ptr == '\\' && *(arg_ptr + 1) == '=')
255  ; /* skip backslash escaping = */
256  else if (*arg_ptr == '=' && (arg_ptr == arg || *(arg_ptr - 1) != '\\'))
257  {
258  if (*cell->new_dir)
259  {
260  fprintf(stderr, _("%s: multiple \"=\" signs in tablespace mapping\n"), progname);
261  exit(1);
262  }
263  else
264  dst = dst_ptr = cell->new_dir;
265  }
266  else
267  *dst_ptr++ = *arg_ptr;
268  }
269 
270  if (!*cell->old_dir || !*cell->new_dir)
271  {
272  fprintf(stderr,
273  _("%s: invalid tablespace mapping format \"%s\", must be \"OLDDIR=NEWDIR\"\n"),
274  progname, arg);
275  exit(1);
276  }
277 
278  /*
279  * This check isn't absolutely necessary. But all tablespaces are created
280  * with absolute directories, so specifying a non-absolute path here would
281  * just never match, possibly confusing users. It's also good to be
282  * consistent with the new_dir check.
283  */
284  if (!is_absolute_path(cell->old_dir))
285  {
286  fprintf(stderr, _("%s: old directory is not an absolute path in tablespace mapping: %s\n"),
287  progname, cell->old_dir);
288  exit(1);
289  }
290 
291  if (!is_absolute_path(cell->new_dir))
292  {
293  fprintf(stderr, _("%s: new directory is not an absolute path in tablespace mapping: %s\n"),
294  progname, cell->new_dir);
295  exit(1);
296  }
297 
298  canonicalize_path(cell->old_dir);
299  canonicalize_path(cell->new_dir);
300 
301  if (tablespace_dirs.tail)
302  tablespace_dirs.tail->next = cell;
303  else
304  tablespace_dirs.head = cell;
305  tablespace_dirs.tail = cell;
306 }
static TablespaceList tablespace_dirs
Definition: pg_basebackup.c:78
char old_dir[MAXPGPATH]
Definition: pg_basebackup.c:45
void canonicalize_path(char *path)
Definition: path.c:254
char new_dir[MAXPGPATH]
Definition: pg_basebackup.c:46
const char * progname
Definition: pg_standby.c:37
void * pg_malloc0(size_t size)
Definition: fe_memutils.c:53
#define MAXPGPATH
#define is_absolute_path(filename)
Definition: port.h:77
struct TablespaceListCell * next
Definition: pg_basebackup.c:44
TablespaceListCell * tail
Definition: pg_basebackup.c:52
TablespaceListCell * head
Definition: pg_basebackup.c:51
void * arg
#define _(x)
Definition: elog.c:84
static void usage ( void  )
static

Definition at line 325 of file pg_basebackup.c.

References _, and progname.

Referenced by main().

326 {
327  printf(_("%s takes a base backup of a running PostgreSQL server.\n\n"),
328  progname);
329  printf(_("Usage:\n"));
330  printf(_(" %s [OPTION]...\n"), progname);
331  printf(_("\nOptions controlling the output:\n"));
332  printf(_(" -D, --pgdata=DIRECTORY receive base backup into directory\n"));
333  printf(_(" -F, --format=p|t output format (plain (default), tar)\n"));
334  printf(_(" -r, --max-rate=RATE maximum transfer rate to transfer data directory\n"
335  " (in kB/s, or use suffix \"k\" or \"M\")\n"));
336  printf(_(" -R, --write-recovery-conf\n"
337  " write recovery.conf for replication\n"));
338  printf(_(" -S, --slot=SLOTNAME replication slot to use\n"));
339  printf(_(" --no-slot prevent creation of temporary replication slot\n"));
340  printf(_(" -T, --tablespace-mapping=OLDDIR=NEWDIR\n"
341  " relocate tablespace in OLDDIR to NEWDIR\n"));
342  printf(_(" -X, --wal-method=none|fetch|stream\n"
343  " include required WAL files with specified method\n"));
344  printf(_(" --waldir=WALDIR location for the transaction log directory\n"));
345  printf(_(" -z, --gzip compress tar output\n"));
346  printf(_(" -Z, --compress=0-9 compress tar output with given compression level\n"));
347  printf(_("\nGeneral options:\n"));
348  printf(_(" -c, --checkpoint=fast|spread\n"
349  " set fast or spread checkpointing\n"));
350  printf(_(" -l, --label=LABEL set backup label\n"));
351  printf(_(" -n, --no-clean do not clean up after errors\n"));
352  printf(_(" -N, --no-sync do not wait for changes to be written safely to disk\n"));
353  printf(_(" -P, --progress show progress information\n"));
354  printf(_(" -v, --verbose output verbose messages\n"));
355  printf(_(" -V, --version output version information, then exit\n"));
356  printf(_(" -?, --help show this help, then exit\n"));
357  printf(_("\nConnection options:\n"));
358  printf(_(" -d, --dbname=CONNSTR connection string\n"));
359  printf(_(" -h, --host=HOSTNAME database server host or socket directory\n"));
360  printf(_(" -p, --port=PORT database server port number\n"));
361  printf(_(" -s, --status-interval=INTERVAL\n"
362  " time between status packets sent to server (in seconds)\n"));
363  printf(_(" -U, --username=NAME connect as specified database user\n"));
364  printf(_(" -w, --no-password never prompt for password\n"));
365  printf(_(" -W, --password force password prompt (should happen automatically)\n"));
366  printf(_("\nReport bugs to <pgsql-bugs@postgresql.org>.\n"));
367 }
const char * progname
Definition: pg_standby.c:37
#define _(x)
Definition: elog.c:84
static void verify_dir_is_empty_or_create ( char *  dirname,
bool created,
bool found 
)
static

Definition at line 644 of file pg_basebackup.c.

References _, disconnect_and_exit(), pg_check_dir(), pg_mkdir_p(), progname, and strerror().

Referenced by BaseBackup(), and main().

645 {
646  switch (pg_check_dir(dirname))
647  {
648  case 0:
649 
650  /*
651  * Does not exist, so create
652  */
653  if (pg_mkdir_p(dirname, S_IRWXU) == -1)
654  {
655  fprintf(stderr,
656  _("%s: could not create directory \"%s\": %s\n"),
657  progname, dirname, strerror(errno));
659  }
660  if (created)
661  *created = true;
662  return;
663  case 1:
664 
665  /*
666  * Exists, empty
667  */
668  if (found)
669  *found = true;
670  return;
671  case 2:
672  case 3:
673  case 4:
674 
675  /*
676  * Exists, not empty
677  */
678  fprintf(stderr,
679  _("%s: directory \"%s\" exists but is not empty\n"),
680  progname, dirname);
682  case -1:
683 
684  /*
685  * Access problem
686  */
687  fprintf(stderr, _("%s: could not access directory \"%s\": %s\n"),
688  progname, dirname, strerror(errno));
690  }
691 }
int pg_mkdir_p(char *path, int omode)
Definition: pgmkdirp.c:57
const char * progname
Definition: pg_standby.c:37
int pg_check_dir(const char *dir)
Definition: pgcheckdir.c:31
const char * strerror(int errnum)
Definition: strerror.c:19
static void disconnect_and_exit(int code)
#define _(x)
Definition: elog.c:84
static void WriteRecoveryConf ( void  )
static

Definition at line 1657 of file pg_basebackup.c.

References _, basedir, PQExpBufferData::data, disconnect_and_exit(), filename, PQExpBufferData::len, MAXPGPATH, NULL, progname, and strerror().

Referenced by ReceiveAndUnpackTarFile().

1658 {
1659  char filename[MAXPGPATH];
1660  FILE *cf;
1661 
1662  sprintf(filename, "%s/recovery.conf", basedir);
1663 
1664  cf = fopen(filename, "w");
1665  if (cf == NULL)
1666  {
1667  fprintf(stderr, _("%s: could not create file \"%s\": %s\n"), progname, filename, strerror(errno));
1669  }
1670 
1671  if (fwrite(recoveryconfcontents->data, recoveryconfcontents->len, 1, cf) != 1)
1672  {
1673  fprintf(stderr,
1674  _("%s: could not write to file \"%s\": %s\n"),
1675  progname, filename, strerror(errno));
1677  }
1678 
1679  fclose(cf);
1680 }
static PQExpBuffer recoveryconfcontents
const char * progname
Definition: pg_standby.c:37
static char * basedir
Definition: pg_basebackup.c:77
#define MAXPGPATH
#define NULL
Definition: c.h:229
static char * filename
Definition: pg_dumpall.c:87
const char * strerror(int errnum)
Definition: strerror.c:19
static void disconnect_and_exit(int code)
#define _(x)
Definition: elog.c:84
static void writeTarData ( FILE *  tarfile,
char *  buf,
int  r,
char *  current_file 
)
static

Definition at line 883 of file pg_basebackup.c.

References _, disconnect_and_exit(), NULL, progname, and strerror().

888 {
889 #ifdef HAVE_LIBZ
890  if (ztarfile != NULL)
891  {
892  if (gzwrite(ztarfile, buf, r) != r)
893  {
894  fprintf(stderr,
895  _("%s: could not write to compressed file \"%s\": %s\n"),
896  progname, current_file, get_gz_error(ztarfile));
898  }
899  }
900  else
901 #endif
902  {
903  if (fwrite(buf, r, 1, tarfile) != 1)
904  {
905  fprintf(stderr, _("%s: could not write to file \"%s\": %s\n"),
906  progname, current_file, strerror(errno));
908  }
909  }
910 }
const char * progname
Definition: pg_standby.c:37
static char * buf
Definition: pg_test_fsync.c:65
#define NULL
Definition: c.h:229
const char * strerror(int errnum)
Definition: strerror.c:19
static void disconnect_and_exit(int code)
#define _(x)
Definition: elog.c:84

Variable Documentation

pid_t bgchild = -1
static

Definition at line 115 of file pg_basebackup.c.

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

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

Definition at line 111 of file pg_basebackup.c.

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

int compresslevel = 0
static

Definition at line 85 of file pg_basebackup.c.

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

bool do_sync = true
static

Definition at line 89 of file pg_basebackup.c.

Referenced by BaseBackup(), LogStreamerMain(), main(), and ReceiveTarFile().

bool fastcheckpoint = false
static

Definition at line 87 of file pg_basebackup.c.

Referenced by BaseBackup(), and main().

bool found_existing_pgdata = false
static

Definition at line 98 of file pg_basebackup.c.

Referenced by cleanup_directories_atexit(), and main().

bool found_existing_xlogdir = false
static

Definition at line 100 of file pg_basebackup.c.

Referenced by cleanup_directories_atexit(), and main().

bool found_tablespace_dirs = false
static

Definition at line 102 of file pg_basebackup.c.

Referenced by BaseBackup(), and cleanup_directories_atexit().

int has_xlogendptr = 0
static

Definition at line 122 of file pg_basebackup.c.

Referenced by BaseBackup(), and reached_end_position().

bool in_log_streamer = false
static

Definition at line 116 of file pg_basebackup.c.

Referenced by cleanup_directories_atexit(), and LogStreamerMain().

IncludeWal includewal = STREAM_WAL
static

Definition at line 86 of file pg_basebackup.c.

Referenced by BaseBackup(), and main().

pg_time_t last_progress_report = 0
static

Definition at line 91 of file pg_basebackup.c.

Referenced by progress_report().

bool made_new_pgdata = false
static

Definition at line 97 of file pg_basebackup.c.

Referenced by cleanup_directories_atexit(), and main().

bool made_new_xlogdir = false
static

Definition at line 99 of file pg_basebackup.c.

Referenced by cleanup_directories_atexit(), and main().

bool made_tablespace_dirs = false
static

Definition at line 101 of file pg_basebackup.c.

Referenced by BaseBackup(), and cleanup_directories_atexit().

int32 maxrate = 0
static

Definition at line 92 of file pg_basebackup.c.

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

bool noclean = false
static

Definition at line 82 of file pg_basebackup.c.

Referenced by cleanup_directories_atexit(), and main().

PQExpBuffer recoveryconfcontents = NULL
static

Definition at line 128 of file pg_basebackup.c.

char* replication_slot = NULL
static

Definition at line 93 of file pg_basebackup.c.

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

bool showprogress = false
static

Definition at line 83 of file pg_basebackup.c.

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

int standby_message_timeout = 10 * 1000
static

Definition at line 90 of file pg_basebackup.c.

Referenced by LogStreamerMain(), and main().

TablespaceList tablespace_dirs = {NULL, NULL}
static

Definition at line 78 of file pg_basebackup.c.

int tablespacecount
static

Definition at line 107 of file pg_basebackup.c.

Referenced by BaseBackup(), and progress_report().

bool temp_replication_slot = true
static

Definition at line 94 of file pg_basebackup.c.

Referenced by main(), and StartLogStreamer().

uint64 totaldone
static
int verbose = 0
static
bool writerecoveryconf = false
static

Definition at line 88 of file pg_basebackup.c.

Referenced by BaseBackup(), main(), ReceiveAndUnpackTarFile(), and ReceiveTarFile().

char* xlog_dir = ""
static

Definition at line 79 of file pg_basebackup.c.

Referenced by cleanup_directories_atexit(), and main().

XLogRecPtr xlogendptr
static

Definition at line 119 of file pg_basebackup.c.

Referenced by BaseBackup(), and reached_end_position().