PostgreSQL Source Code  git master
backup_manifest.c File Reference
#include "postgres.h"
#include "access/timeline.h"
#include "libpq/libpq.h"
#include "libpq/pqformat.h"
#include "mb/pg_wchar.h"
#include "replication/backup_manifest.h"
#include "utils/builtins.h"
#include "utils/json.h"
Include dependency graph for backup_manifest.c:

Go to the source code of this file.

Macros

#define AppendToManifest(manifest, ...)
 

Functions

static void AppendStringToManifest (backup_manifest_info *manifest, char *s)
 
static bool IsManifestEnabled (backup_manifest_info *manifest)
 
void InitializeBackupManifest (backup_manifest_info *manifest, backup_manifest_option want_manifest, pg_checksum_type manifest_checksum_type)
 
void FreeBackupManifest (backup_manifest_info *manifest)
 
void AddFileToBackupManifest (backup_manifest_info *manifest, const char *spcoid, const char *pathname, size_t size, pg_time_t mtime, pg_checksum_context *checksum_ctx)
 
void AddWALInfoToBackupManifest (backup_manifest_info *manifest, XLogRecPtr startptr, TimeLineID starttli, XLogRecPtr endptr, TimeLineID endtli)
 
void SendBackupManifest (backup_manifest_info *manifest)
 

Macro Definition Documentation

◆ AppendToManifest

#define AppendToManifest (   manifest,
  ... 
)
Value:
{ \
char *_manifest_s = psprintf(__VA_ARGS__); \
AppendStringToManifest(manifest, _manifest_s); \
pfree(_manifest_s); \
}
char * psprintf(const char *fmt,...)
Definition: psprintf.c:46
static bool manifest

Definition at line 41 of file backup_manifest.c.

Referenced by AddWALInfoToBackupManifest(), and InitializeBackupManifest().

Function Documentation

◆ AddFileToBackupManifest()

void AddFileToBackupManifest ( backup_manifest_info manifest,
const char *  spcoid,
const char *  pathname,
size_t  size,
pg_time_t  mtime,
pg_checksum_context checksum_ctx 
)

Definition at line 98 of file backup_manifest.c.

References appendStringInfo(), appendStringInfoChar(), appendStringInfoString(), AppendStringToManifest(), buf, CHECKSUM_TYPE_NONE, StringInfoData::data, elog, enlargeStringInfo(), ERROR, escape_json(), backup_manifest_info::first_file, backup_manifest_info::force_encode, hex_encode(), initStringInfo(), IsManifestEnabled(), StringInfoData::len, MAXPGPATH, pfree(), pg_checksum_final(), PG_CHECKSUM_MAX_LENGTH, pg_checksum_type_name(), pg_gmtime(), pg_strftime(), PG_UTF8, pg_verify_mbstr(), snprintf, and pg_checksum_context::type.

Referenced by sendFile(), and sendFileWithContent().

101 {
102  char pathbuf[MAXPGPATH];
103  int pathlen;
105 
106  if (!IsManifestEnabled(manifest))
107  return;
108 
109  /*
110  * If this file is part of a tablespace, the pathname passed to this
111  * function will be relative to the tar file that contains it. We want the
112  * pathname relative to the data directory (ignoring the intermediate
113  * symlink traversal).
114  */
115  if (spcoid != NULL)
116  {
117  snprintf(pathbuf, sizeof(pathbuf), "pg_tblspc/%s/%s", spcoid,
118  pathname);
119  pathname = pathbuf;
120  }
121 
122  /*
123  * Each file's entry needs to be separated from any entry that follows by
124  * a comma, but there's no comma before the first one or after the last
125  * one. To make that work, adding a file to the manifest starts by
126  * terminating the most recently added line, with a comma if appropriate,
127  * but does not terminate the line inserted for this file.
128  */
129  initStringInfo(&buf);
130  if (manifest->first_file)
131  {
132  appendStringInfoChar(&buf, '\n');
133  manifest->first_file = false;
134  }
135  else
136  appendStringInfoString(&buf, ",\n");
137 
138  /*
139  * Write the relative pathname to this file out to the manifest. The
140  * manifest is always stored in UTF-8, so we have to encode paths that are
141  * not valid in that encoding.
142  */
143  pathlen = strlen(pathname);
144  if (!manifest->force_encode &&
145  pg_verify_mbstr(PG_UTF8, pathname, pathlen, true))
146  {
147  appendStringInfoString(&buf, "{ \"Path\": ");
148  escape_json(&buf, pathname);
149  appendStringInfoString(&buf, ", ");
150  }
151  else
152  {
153  appendStringInfoString(&buf, "{ \"Encoded-Path\": \"");
154  enlargeStringInfo(&buf, 2 * pathlen);
155  buf.len += hex_encode(pathname, pathlen,
156  &buf.data[buf.len]);
157  appendStringInfoString(&buf, "\", ");
158  }
159 
160  appendStringInfo(&buf, "\"Size\": %zu, ", size);
161 
162  /*
163  * Convert last modification time to a string and append it to the
164  * manifest. Since it's not clear what time zone to use and since time
165  * zone definitions can change, possibly causing confusion, use GMT
166  * always.
167  */
168  appendStringInfoString(&buf, "\"Last-Modified\": \"");
169  enlargeStringInfo(&buf, 128);
170  buf.len += pg_strftime(&buf.data[buf.len], 128, "%Y-%m-%d %H:%M:%S %Z",
171  pg_gmtime(&mtime));
172  appendStringInfoChar(&buf, '"');
173 
174  /* Add checksum information. */
175  if (checksum_ctx->type != CHECKSUM_TYPE_NONE)
176  {
177  uint8 checksumbuf[PG_CHECKSUM_MAX_LENGTH];
178  int checksumlen;
179 
180  checksumlen = pg_checksum_final(checksum_ctx, checksumbuf);
181  if (checksumlen < 0)
182  elog(ERROR, "could not finalize checksum of file \"%s\"",
183  pathname);
184 
185  appendStringInfo(&buf,
186  ", \"Checksum-Algorithm\": \"%s\", \"Checksum\": \"",
187  pg_checksum_type_name(checksum_ctx->type));
188  enlargeStringInfo(&buf, 2 * checksumlen);
189  buf.len += hex_encode((char *) checksumbuf, checksumlen,
190  &buf.data[buf.len]);
191  appendStringInfoChar(&buf, '"');
192  }
193 
194  /* Close out the object. */
195  appendStringInfoString(&buf, " }");
196 
197  /* OK, add it to the manifest. */
198  AppendStringToManifest(manifest, buf.data);
199 
200  /* Avoid leaking memory. */
201  pfree(buf.data);
202 }
size_t pg_strftime(char *s, size_t max, const char *format, const struct pg_tm *tm)
Definition: strftime.c:128
char * pg_checksum_type_name(pg_checksum_type type)
void escape_json(StringInfo buf, const char *str)
Definition: json.c:1279
struct pg_tm * pg_gmtime(const pg_time_t *timep)
Definition: localtime.c:1387
unsigned char uint8
Definition: c.h:427
#define PG_CHECKSUM_MAX_LENGTH
bool pg_verify_mbstr(int encoding, const char *mbstr, int len, bool noError)
Definition: mbutils.c:1457
void pfree(void *pointer)
Definition: mcxt.c:1057
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
#define ERROR
Definition: elog.h:43
#define MAXPGPATH
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:176
static char * buf
Definition: pg_test_fsync.c:68
void enlargeStringInfo(StringInfo str, int needed)
Definition: stringinfo.c:283
static void AppendStringToManifest(backup_manifest_info *manifest, char *s)
uint64 hex_encode(const char *src, size_t len, char *dst)
Definition: encode.c:161
void appendStringInfoChar(StringInfo str, char ch)
Definition: stringinfo.c:188
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
int pg_checksum_final(pg_checksum_context *context, uint8 *output)
static bool IsManifestEnabled(backup_manifest_info *manifest)
#define elog(elevel,...)
Definition: elog.h:228
pg_checksum_type type
#define snprintf
Definition: port.h:215

◆ AddWALInfoToBackupManifest()

void AddWALInfoToBackupManifest ( backup_manifest_info manifest,
XLogRecPtr  startptr,
TimeLineID  starttli,
XLogRecPtr  endptr,
TimeLineID  endtli 
)

Definition at line 209 of file backup_manifest.c.

References AppendStringToManifest(), AppendToManifest, TimeLineHistoryEntry::begin, TimeLineHistoryEntry::end, ereport, errmsg(), ERROR, IsManifestEnabled(), lfirst, readTimeLineHistory(), startptr, TimeLineHistoryEntry::tli, and XLogRecPtrIsInvalid.

Referenced by perform_base_backup().

212 {
213  List *timelines;
214  ListCell *lc;
215  bool first_wal_range = true;
216  bool found_start_timeline = false;
217 
218  if (!IsManifestEnabled(manifest))
219  return;
220 
221  /* Terminate the list of files. */
222  AppendStringToManifest(manifest, "\n],\n");
223 
224  /* Read the timeline history for the ending timeline. */
225  timelines = readTimeLineHistory(endtli);
226 
227  /* Start a list of LSN ranges. */
228  AppendStringToManifest(manifest, "\"WAL-Ranges\": [\n");
229 
230  foreach(lc, timelines)
231  {
232  TimeLineHistoryEntry *entry = lfirst(lc);
233  XLogRecPtr tl_beginptr;
234 
235  /*
236  * We only care about timelines that were active during the backup.
237  * Skip any that ended before the backup started. (Note that if
238  * entry->end is InvalidXLogRecPtr, it means that the timeline has not
239  * yet ended.)
240  */
241  if (!XLogRecPtrIsInvalid(entry->end) && entry->end < startptr)
242  continue;
243 
244  /*
245  * Because the timeline history file lists newer timelines before
246  * older ones, the first timeline we encounter that is new enough to
247  * matter ought to match the ending timeline of the backup.
248  */
249  if (first_wal_range && endtli != entry->tli)
250  ereport(ERROR,
251  errmsg("expected end timeline %u but found timeline %u",
252  starttli, entry->tli));
253 
254  if (!XLogRecPtrIsInvalid(entry->begin))
255  tl_beginptr = entry->begin;
256  else
257  {
258  tl_beginptr = startptr;
259 
260  /*
261  * If we reach a TLI that has no valid beginning LSN, there can't
262  * be any more timelines in the history after this point, so we'd
263  * better have arrived at the expected starting TLI. If not,
264  * something's gone horribly wrong.
265  */
266  if (starttli != entry->tli)
267  ereport(ERROR,
268  errmsg("expected start timeline %u but found timeline %u",
269  starttli, entry->tli));
270  }
271 
272  AppendToManifest(manifest,
273  "%s{ \"Timeline\": %u, \"Start-LSN\": \"%X/%X\", \"End-LSN\": \"%X/%X\" }",
274  first_wal_range ? "" : ",\n",
275  entry->tli,
276  (uint32) (tl_beginptr >> 32), (uint32) tl_beginptr,
277  (uint32) (endptr >> 32), (uint32) endptr);
278 
279  if (starttli == entry->tli)
280  {
281  found_start_timeline = true;
282  break;
283  }
284 
285  endptr = entry->begin;
286  first_wal_range = false;
287  }
288 
289  /*
290  * The last entry in the timeline history for the ending timeline should
291  * be the ending timeline itself. Verify that this is what we observed.
292  */
293  if (!found_start_timeline)
294  ereport(ERROR,
295  errmsg("start timeline %u not found in history of timeline %u",
296  starttli, endtli));
297 
298  /* Terminate the list of WAL ranges. */
299  AppendStringToManifest(manifest, "\n],\n");
300 }
List * readTimeLineHistory(TimeLineID targetTLI)
Definition: timeline.c:76
TimeLineID tli
Definition: timeline.h:27
#define AppendToManifest(manifest,...)
#define ERROR
Definition: elog.h:43
unsigned int uint32
Definition: c.h:429
static void AppendStringToManifest(backup_manifest_info *manifest, char *s)
#define XLogRecPtrIsInvalid(r)
Definition: xlogdefs.h:29
static bool IsManifestEnabled(backup_manifest_info *manifest)
#define ereport(elevel,...)
Definition: elog.h:155
XLogRecPtr end
Definition: timeline.h:29
uint64 XLogRecPtr
Definition: xlogdefs.h:21
#define lfirst(lc)
Definition: pg_list.h:169
int errmsg(const char *fmt,...)
Definition: elog.c:902
XLogRecPtr begin
Definition: timeline.h:28
Definition: pg_list.h:50
static XLogRecPtr startptr
Definition: basebackup.c:116

◆ AppendStringToManifest()

static void AppendStringToManifest ( backup_manifest_info manifest,
char *  s 
)
static

Definition at line 386 of file backup_manifest.c.

References Assert, backup_manifest_info::buffile, BufFileWrite(), elog, ERROR, backup_manifest_info::manifest_ctx, backup_manifest_info::manifest_size, pg_cryptohash_update(), and backup_manifest_info::still_checksumming.

Referenced by AddFileToBackupManifest(), AddWALInfoToBackupManifest(), and SendBackupManifest().

387 {
388  int len = strlen(s);
389 
390  Assert(manifest != NULL);
391  if (manifest->still_checksumming)
392  {
393  if (pg_cryptohash_update(manifest->manifest_ctx, (uint8 *) s, len) < 0)
394  elog(ERROR, "failed to update checksum of backup manifest");
395  }
396  BufFileWrite(manifest->buffile, s, len);
397  manifest->manifest_size += len;
398 }
unsigned char uint8
Definition: c.h:427
#define ERROR
Definition: elog.h:43
#define Assert(condition)
Definition: c.h:800
pg_cryptohash_ctx * manifest_ctx
int pg_cryptohash_update(pg_cryptohash_ctx *ctx, const uint8 *data, size_t len)
Definition: cryptohash.c:122
#define elog(elevel,...)
Definition: elog.h:228
void BufFileWrite(BufFile *file, void *ptr, size_t size)
Definition: buffile.c:586

◆ FreeBackupManifest()

void FreeBackupManifest ( backup_manifest_info manifest)

Definition at line 88 of file backup_manifest.c.

References backup_manifest_info::manifest_ctx, and pg_cryptohash_free().

Referenced by perform_base_backup().

89 {
91  manifest->manifest_ctx = NULL;
92 }
pg_cryptohash_ctx * manifest_ctx
void pg_cryptohash_free(pg_cryptohash_ctx *ctx)
Definition: cryptohash.c:183

◆ InitializeBackupManifest()

void InitializeBackupManifest ( backup_manifest_info manifest,
backup_manifest_option  want_manifest,
pg_checksum_type  manifest_checksum_type 
)

Definition at line 56 of file backup_manifest.c.

References AppendToManifest, backup_manifest_info::buffile, BufFileCreateTemp(), backup_manifest_info::checksum_type, elog, ERROR, backup_manifest_info::first_file, backup_manifest_info::force_encode, backup_manifest_info::manifest_ctx, MANIFEST_OPTION_FORCE_ENCODE, MANIFEST_OPTION_NO, backup_manifest_info::manifest_size, pg_cryptohash_create(), pg_cryptohash_init(), PG_SHA256, and backup_manifest_info::still_checksumming.

Referenced by perform_base_backup().

59 {
60  memset(manifest, 0, sizeof(backup_manifest_info));
61  manifest->checksum_type = manifest_checksum_type;
62 
63  if (want_manifest == MANIFEST_OPTION_NO)
64  manifest->buffile = NULL;
65  else
66  {
67  manifest->buffile = BufFileCreateTemp(false);
69  if (pg_cryptohash_init(manifest->manifest_ctx) < 0)
70  elog(ERROR, "failed to initialize checksum of backup manifest");
71  }
72 
73  manifest->manifest_size = UINT64CONST(0);
74  manifest->force_encode = (want_manifest == MANIFEST_OPTION_FORCE_ENCODE);
75  manifest->first_file = true;
76  manifest->still_checksumming = true;
77 
78  if (want_manifest != MANIFEST_OPTION_NO)
79  AppendToManifest(manifest,
80  "{ \"PostgreSQL-Backup-Manifest-Version\": 1,\n"
81  "\"Files\": [");
82 }
#define AppendToManifest(manifest,...)
#define ERROR
Definition: elog.h:43
BufFile * BufFileCreateTemp(bool interXact)
Definition: buffile.c:188
pg_checksum_type checksum_type
pg_cryptohash_ctx * pg_cryptohash_create(pg_cryptohash_type type)
Definition: cryptohash.c:48
int pg_cryptohash_init(pg_cryptohash_ctx *ctx)
Definition: cryptohash.c:91
pg_cryptohash_ctx * manifest_ctx
#define elog(elevel,...)
Definition: elog.h:228

◆ IsManifestEnabled()

static bool IsManifestEnabled ( backup_manifest_info manifest)
inlinestatic

Definition at line 33 of file backup_manifest.c.

References backup_manifest_info::buffile.

Referenced by AddFileToBackupManifest(), AddWALInfoToBackupManifest(), and SendBackupManifest().

34 {
35  return (manifest->buffile != NULL);
36 }

◆ SendBackupManifest()

void SendBackupManifest ( backup_manifest_info manifest)

Definition at line 306 of file backup_manifest.c.

References AppendStringToManifest(), backup_manifest_info::buffile, BufFileClose(), BufFileRead(), BufFileSeek(), elog, ereport, errcode_for_file_access(), errmsg(), ERROR, hex_encode(), IsManifestEnabled(), backup_manifest_info::manifest_ctx, backup_manifest_info::manifest_size, Min, pg_cryptohash_final(), PG_SHA256_DIGEST_LENGTH, PG_SHA256_DIGEST_STRING_LENGTH, pq_beginmessage(), pq_endmessage(), pq_putemptymessage(), pq_putmessage, pq_sendbyte(), pq_sendint16(), and backup_manifest_info::still_checksumming.

Referenced by perform_base_backup().

307 {
308  StringInfoData protobuf;
309  uint8 checksumbuf[PG_SHA256_DIGEST_LENGTH];
310  char checksumstringbuf[PG_SHA256_DIGEST_STRING_LENGTH];
311  size_t manifest_bytes_done = 0;
312 
313  if (!IsManifestEnabled(manifest))
314  return;
315 
316  /*
317  * Append manifest checksum, so that the problems with the manifest itself
318  * can be detected.
319  *
320  * We always use SHA-256 for this, regardless of what algorithm is chosen
321  * for checksumming the files. If we ever want to make the checksum
322  * algorithm used for the manifest file variable, the client will need a
323  * way to figure out which algorithm to use as close to the beginning of
324  * the manifest file as possible, to avoid having to read the whole thing
325  * twice.
326  */
327  manifest->still_checksumming = false;
328  if (pg_cryptohash_final(manifest->manifest_ctx, checksumbuf) < 0)
329  elog(ERROR, "failed to finalize checksum of backup manifest");
330  AppendStringToManifest(manifest, "\"Manifest-Checksum\": \"");
331  hex_encode((char *) checksumbuf, sizeof checksumbuf, checksumstringbuf);
332  checksumstringbuf[PG_SHA256_DIGEST_STRING_LENGTH - 1] = '\0';
333  AppendStringToManifest(manifest, checksumstringbuf);
334  AppendStringToManifest(manifest, "\"}\n");
335 
336  /*
337  * We've written all the data to the manifest file. Rewind the file so
338  * that we can read it all back.
339  */
340  if (BufFileSeek(manifest->buffile, 0, 0L, SEEK_SET))
341  ereport(ERROR,
343  errmsg("could not rewind temporary file")));
344 
345  /* Send CopyOutResponse message */
346  pq_beginmessage(&protobuf, 'H');
347  pq_sendbyte(&protobuf, 0); /* overall format */
348  pq_sendint16(&protobuf, 0); /* natts */
349  pq_endmessage(&protobuf);
350 
351  /*
352  * Send CopyData messages.
353  *
354  * We choose to read back the data from the temporary file in chunks of
355  * size BLCKSZ; this isn't necessary, but buffile.c uses that as the I/O
356  * size, so it seems to make sense to match that value here.
357  */
358  while (manifest_bytes_done < manifest->manifest_size)
359  {
360  char manifestbuf[BLCKSZ];
361  size_t bytes_to_read;
362  size_t rc;
363 
364  bytes_to_read = Min(sizeof(manifestbuf),
365  manifest->manifest_size - manifest_bytes_done);
366  rc = BufFileRead(manifest->buffile, manifestbuf, bytes_to_read);
367  if (rc != bytes_to_read)
368  ereport(ERROR,
370  errmsg("could not read from temporary file: %m")));
371  pq_putmessage('d', manifestbuf, bytes_to_read);
372  manifest_bytes_done += bytes_to_read;
373  }
374 
375  /* No more data, so send CopyDone message */
376  pq_putemptymessage('c');
377 
378  /* Release resources */
379  BufFileClose(manifest->buffile);
380 }
static void pq_sendint16(StringInfo buf, uint16 i)
Definition: pqformat.h:137
int BufFileSeek(BufFile *file, int fileno, off_t offset, int whence)
Definition: buffile.c:650
#define Min(x, y)
Definition: c.h:982
#define PG_SHA256_DIGEST_LENGTH
Definition: sha2.h:23
unsigned char uint8
Definition: c.h:427
void pq_putemptymessage(char msgtype)
Definition: pqformat.c:390
void BufFileClose(BufFile *file)
Definition: buffile.c:395
void pq_beginmessage(StringInfo buf, char msgtype)
Definition: pqformat.c:87
static void pq_sendbyte(StringInfo buf, uint8 byt)
Definition: pqformat.h:161
#define ERROR
Definition: elog.h:43
int errcode_for_file_access(void)
Definition: elog.c:714
static void AppendStringToManifest(backup_manifest_info *manifest, char *s)
#define PG_SHA256_DIGEST_STRING_LENGTH
Definition: sha2.h:24
int pg_cryptohash_final(pg_cryptohash_ctx *ctx, uint8 *dest)
Definition: cryptohash.c:153
uint64 hex_encode(const char *src, size_t len, char *dst)
Definition: encode.c:161
static bool IsManifestEnabled(backup_manifest_info *manifest)
#define ereport(elevel,...)
Definition: elog.h:155
pg_cryptohash_ctx * manifest_ctx
int errmsg(const char *fmt,...)
Definition: elog.c:902
void pq_endmessage(StringInfo buf)
Definition: pqformat.c:298
#define elog(elevel,...)
Definition: elog.h:228
size_t BufFileRead(BufFile *file, void *ptr, size_t size)
Definition: buffile.c:543
#define pq_putmessage(msgtype, s, len)
Definition: libpq.h:42