PostgreSQL Source Code  git master
pg_waldump.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * pg_waldump.c - decode and display WAL
4  *
5  * Copyright (c) 2013-2019, PostgreSQL Global Development Group
6  *
7  * IDENTIFICATION
8  * src/bin/pg_waldump/pg_waldump.c
9  *-------------------------------------------------------------------------
10  */
11 
12 #define FRONTEND 1
13 #include "postgres.h"
14 
15 #include <dirent.h>
16 #include <sys/stat.h>
17 #include <unistd.h>
18 
19 #include "access/transam.h"
20 #include "access/xlog_internal.h"
21 #include "access/xlogreader.h"
22 #include "access/xlogrecord.h"
23 #include "common/fe_memutils.h"
24 #include "common/logging.h"
25 #include "getopt_long.h"
26 #include "rmgrdesc.h"
27 
28 static const char *progname;
29 
30 static int WalSegSz;
31 
32 typedef struct XLogDumpPrivate
33 {
39 
40 typedef struct XLogDumpConfig
41 {
42  /* display options */
46  bool follow;
47  bool stats;
49 
50  /* filter options */
55 
56 typedef struct Stats
57 {
58  uint64 count;
59  uint64 rec_len;
60  uint64 fpi_len;
61 } Stats;
62 
63 #define MAX_XLINFO_TYPES 16
64 
65 typedef struct XLogDumpStats
66 {
67  uint64 count;
68  Stats rmgr_stats[RM_NEXT_ID];
71 
72 #define fatal_error(...) do { pg_log_fatal(__VA_ARGS__); exit(EXIT_FAILURE); } while(0)
73 
74 static void
76 {
77  int i;
78 
79  for (i = 0; i <= RM_MAX_ID; i++)
80  {
81  printf("%s\n", RmgrDescTable[i].rm_name);
82  }
83 }
84 
85 /*
86  * Check whether directory exists and whether we can open it. Keep errno set so
87  * that the caller can report errors somewhat more accurately.
88  */
89 static bool
91 {
92  DIR *dir = opendir(directory);
93 
94  if (dir == NULL)
95  return false;
96  closedir(dir);
97  return true;
98 }
99 
100 /*
101  * Split a pathname as dirname(1) and basename(1) would.
102  *
103  * XXX this probably doesn't do very well on Windows. We probably need to
104  * apply canonicalize_path(), at the very least.
105  */
106 static void
107 split_path(const char *path, char **dir, char **fname)
108 {
109  char *sep;
110 
111  /* split filepath into directory & filename */
112  sep = strrchr(path, '/');
113 
114  /* directory path */
115  if (sep != NULL)
116  {
117  *dir = pnstrdup(path, sep - path);
118  *fname = pg_strdup(sep + 1);
119  }
120  /* local directory */
121  else
122  {
123  *dir = NULL;
124  *fname = pg_strdup(path);
125  }
126 }
127 
128 /*
129  * Open the file in the valid target directory.
130  *
131  * return a read only fd
132  */
133 static int
134 open_file_in_directory(const char *directory, const char *fname)
135 {
136  int fd = -1;
137  char fpath[MAXPGPATH];
138 
139  Assert(directory != NULL);
140 
141  snprintf(fpath, MAXPGPATH, "%s/%s", directory, fname);
142  fd = open(fpath, O_RDONLY | PG_BINARY, 0);
143 
144  if (fd < 0 && errno != ENOENT)
145  fatal_error("could not open file \"%s\": %s",
146  fname, strerror(errno));
147  return fd;
148 }
149 
150 /*
151  * Try to find fname in the given directory. Returns true if it is found,
152  * false otherwise. If fname is NULL, search the complete directory for any
153  * file with a valid WAL file name. If file is successfully opened, set the
154  * wal segment size.
155  */
156 static bool
157 search_directory(const char *directory, const char *fname)
158 {
159  int fd = -1;
160  DIR *xldir;
161 
162  /* open file if valid filename is provided */
163  if (fname != NULL)
164  fd = open_file_in_directory(directory, fname);
165 
166  /*
167  * A valid file name is not passed, so search the complete directory. If
168  * we find any file whose name is a valid WAL file name then try to open
169  * it. If we cannot open it, bail out.
170  */
171  else if ((xldir = opendir(directory)) != NULL)
172  {
173  struct dirent *xlde;
174 
175  while ((xlde = readdir(xldir)) != NULL)
176  {
177  if (IsXLogFileName(xlde->d_name))
178  {
179  fd = open_file_in_directory(directory, xlde->d_name);
180  fname = xlde->d_name;
181  break;
182  }
183  }
184 
185  closedir(xldir);
186  }
187 
188  /* set WalSegSz if file is successfully opened */
189  if (fd >= 0)
190  {
192  int r;
193 
194  r = read(fd, buf.data, XLOG_BLCKSZ);
195  if (r == XLOG_BLCKSZ)
196  {
198 
199  WalSegSz = longhdr->xlp_seg_size;
200 
202  fatal_error(ngettext("WAL segment size must be a power of two between 1 MB and 1 GB, but the WAL file \"%s\" header specifies %d byte",
203  "WAL segment size must be a power of two between 1 MB and 1 GB, but the WAL file \"%s\" header specifies %d bytes",
204  WalSegSz),
205  fname, WalSegSz);
206  }
207  else
208  {
209  if (errno != 0)
210  fatal_error("could not read file \"%s\": %s",
211  fname, strerror(errno));
212  else
213  fatal_error("could not read file \"%s\": read %d of %zu",
214  fname, r, (Size) XLOG_BLCKSZ);
215  }
216  close(fd);
217  return true;
218  }
219 
220  return false;
221 }
222 
223 /*
224  * Identify the target directory.
225  *
226  * Try to find the file in several places:
227  * if directory != NULL:
228  * directory /
229  * directory / XLOGDIR /
230  * else
231  * .
232  * XLOGDIR /
233  * $PGDATA / XLOGDIR /
234  *
235  * The valid target directory is returned.
236  */
237 static char *
239 {
240  char fpath[MAXPGPATH];
241 
242  if (directory != NULL)
243  {
244  if (search_directory(directory, fname))
245  return pg_strdup(directory);
246 
247  /* directory / XLOGDIR */
248  snprintf(fpath, MAXPGPATH, "%s/%s", directory, XLOGDIR);
249  if (search_directory(fpath, fname))
250  return pg_strdup(fpath);
251  }
252  else
253  {
254  const char *datadir;
255 
256  /* current directory */
257  if (search_directory(".", fname))
258  return pg_strdup(".");
259  /* XLOGDIR */
260  if (search_directory(XLOGDIR, fname))
261  return pg_strdup(XLOGDIR);
262 
263  datadir = getenv("PGDATA");
264  /* $PGDATA / XLOGDIR */
265  if (datadir != NULL)
266  {
267  snprintf(fpath, MAXPGPATH, "%s/%s", datadir, XLOGDIR);
268  if (search_directory(fpath, fname))
269  return pg_strdup(fpath);
270  }
271  }
272 
273  /* could not locate WAL file */
274  if (fname)
275  fatal_error("could not locate WAL file \"%s\"", fname);
276  else
277  fatal_error("could not find any WAL file");
278 
279  return NULL; /* not reached */
280 }
281 
282 /* pg_waldump's openSegment callback for WALRead */
283 static int
285  TimeLineID *tli_p)
286 {
287  TimeLineID tli = *tli_p;
288  char fname[MAXPGPATH];
289  int fd;
290  int tries;
291 
292  XLogFileName(fname, tli, nextSegNo, segcxt->ws_segsize);
293 
294  /*
295  * In follow mode there is a short period of time after the server has
296  * written the end of the previous file before the new file is available.
297  * So we loop for 5 seconds looking for the file to appear before giving
298  * up.
299  */
300  for (tries = 0; tries < 10; tries++)
301  {
302  fd = open_file_in_directory(segcxt->ws_dir, fname);
303  if (fd >= 0)
304  return fd;
305  if (errno == ENOENT)
306  {
307  int save_errno = errno;
308 
309  /* File not there yet, try again */
310  pg_usleep(500 * 1000);
311 
312  errno = save_errno;
313  continue;
314  }
315  /* Any other error, fall through and fail */
316  break;
317  }
318 
319  fatal_error("could not find file \"%s\": %s", fname, strerror(errno));
320  return -1; /* keep compiler quiet */
321 }
322 
323 /*
324  * XLogReader read_page callback
325  */
326 static int
327 WALDumpReadPage(XLogReaderState *state, XLogRecPtr targetPagePtr, int reqLen,
328  XLogRecPtr targetPtr, char *readBuff)
329 {
330  XLogDumpPrivate *private = state->private_data;
331  int count = XLOG_BLCKSZ;
332  WALReadError errinfo;
333 
334  if (private->endptr != InvalidXLogRecPtr)
335  {
336  if (targetPagePtr + XLOG_BLCKSZ <= private->endptr)
337  count = XLOG_BLCKSZ;
338  else if (targetPagePtr + reqLen <= private->endptr)
339  count = private->endptr - targetPagePtr;
340  else
341  {
342  private->endptr_reached = true;
343  return -1;
344  }
345  }
346 
347  if (!WALRead(readBuff, targetPagePtr, count, private->timeline,
348  &state->seg, &state->segcxt, WALDumpOpenSegment, &errinfo))
349  {
350  WALOpenSegment *seg = &errinfo.wre_seg;
351  char fname[MAXPGPATH];
352 
353  XLogFileName(fname, seg->ws_tli, seg->ws_segno,
354  state->segcxt.ws_segsize);
355 
356  if (errinfo.wre_errno != 0)
357  {
358  errno = errinfo.wre_errno;
359  fatal_error("could not read from file %s, offset %u: %m",
360  fname, errinfo.wre_off);
361  }
362  else
363  fatal_error("could not read from file %s, offset %u: read %d of %zu",
364  fname, errinfo.wre_off, errinfo.wre_read,
365  (Size) errinfo.wre_req);
366  }
367 
368  return count;
369 }
370 
371 /*
372  * Calculate the size of a record, split into !FPI and FPI parts.
373  */
374 static void
375 XLogDumpRecordLen(XLogReaderState *record, uint32 *rec_len, uint32 *fpi_len)
376 {
377  int block_id;
378 
379  /*
380  * Calculate the amount of FPI data in the record.
381  *
382  * XXX: We peek into xlogreader's private decoded backup blocks for the
383  * bimg_len indicating the length of FPI data. It doesn't seem worth it to
384  * add an accessor macro for this.
385  */
386  *fpi_len = 0;
387  for (block_id = 0; block_id <= record->max_block_id; block_id++)
388  {
389  if (XLogRecHasBlockImage(record, block_id))
390  *fpi_len += record->blocks[block_id].bimg_len;
391  }
392 
393  /*
394  * Calculate the length of the record as the total length - the length of
395  * all the block images.
396  */
397  *rec_len = XLogRecGetTotalLen(record) - *fpi_len;
398 }
399 
400 /*
401  * Store per-rmgr and per-record statistics for a given record.
402  */
403 static void
405  XLogReaderState *record)
406 {
407  RmgrId rmid;
408  uint8 recid;
409  uint32 rec_len;
410  uint32 fpi_len;
411 
412  stats->count++;
413 
414  rmid = XLogRecGetRmid(record);
415 
416  XLogDumpRecordLen(record, &rec_len, &fpi_len);
417 
418  /* Update per-rmgr statistics */
419 
420  stats->rmgr_stats[rmid].count++;
421  stats->rmgr_stats[rmid].rec_len += rec_len;
422  stats->rmgr_stats[rmid].fpi_len += fpi_len;
423 
424  /*
425  * Update per-record statistics, where the record is identified by a
426  * combination of the RmgrId and the four bits of the xl_info field that
427  * are the rmgr's domain (resulting in sixteen possible entries per
428  * RmgrId).
429  */
430 
431  recid = XLogRecGetInfo(record) >> 4;
432 
433  stats->record_stats[rmid][recid].count++;
434  stats->record_stats[rmid][recid].rec_len += rec_len;
435  stats->record_stats[rmid][recid].fpi_len += fpi_len;
436 }
437 
438 /*
439  * Print a record to stdout
440  */
441 static void
443 {
444  const char *id;
445  const RmgrDescData *desc = &RmgrDescTable[XLogRecGetRmid(record)];
446  uint32 rec_len;
447  uint32 fpi_len;
448  RelFileNode rnode;
449  ForkNumber forknum;
450  BlockNumber blk;
451  int block_id;
452  uint8 info = XLogRecGetInfo(record);
453  XLogRecPtr xl_prev = XLogRecGetPrev(record);
454  StringInfoData s;
455 
456  XLogDumpRecordLen(record, &rec_len, &fpi_len);
457 
458  printf("rmgr: %-11s len (rec/tot): %6u/%6u, tx: %10u, lsn: %X/%08X, prev %X/%08X, ",
459  desc->rm_name,
460  rec_len, XLogRecGetTotalLen(record),
461  XLogRecGetXid(record),
462  (uint32) (record->ReadRecPtr >> 32), (uint32) record->ReadRecPtr,
463  (uint32) (xl_prev >> 32), (uint32) xl_prev);
464 
465  id = desc->rm_identify(info);
466  if (id == NULL)
467  printf("desc: UNKNOWN (%x) ", info & ~XLR_INFO_MASK);
468  else
469  printf("desc: %s ", id);
470 
471  initStringInfo(&s);
472  desc->rm_desc(&s, record);
473  printf("%s", s.data);
474  pfree(s.data);
475 
476  if (!config->bkp_details)
477  {
478  /* print block references (short format) */
479  for (block_id = 0; block_id <= record->max_block_id; block_id++)
480  {
481  if (!XLogRecHasBlockRef(record, block_id))
482  continue;
483 
484  XLogRecGetBlockTag(record, block_id, &rnode, &forknum, &blk);
485  if (forknum != MAIN_FORKNUM)
486  printf(", blkref #%u: rel %u/%u/%u fork %s blk %u",
487  block_id,
488  rnode.spcNode, rnode.dbNode, rnode.relNode,
489  forkNames[forknum],
490  blk);
491  else
492  printf(", blkref #%u: rel %u/%u/%u blk %u",
493  block_id,
494  rnode.spcNode, rnode.dbNode, rnode.relNode,
495  blk);
496  if (XLogRecHasBlockImage(record, block_id))
497  {
498  if (XLogRecBlockImageApply(record, block_id))
499  printf(" FPW");
500  else
501  printf(" FPW for WAL verification");
502  }
503  }
504  putchar('\n');
505  }
506  else
507  {
508  /* print block references (detailed format) */
509  putchar('\n');
510  for (block_id = 0; block_id <= record->max_block_id; block_id++)
511  {
512  if (!XLogRecHasBlockRef(record, block_id))
513  continue;
514 
515  XLogRecGetBlockTag(record, block_id, &rnode, &forknum, &blk);
516  printf("\tblkref #%u: rel %u/%u/%u fork %s blk %u",
517  block_id,
518  rnode.spcNode, rnode.dbNode, rnode.relNode,
519  forkNames[forknum],
520  blk);
521  if (XLogRecHasBlockImage(record, block_id))
522  {
523  if (record->blocks[block_id].bimg_info &
525  {
526  printf(" (FPW%s); hole: offset: %u, length: %u, "
527  "compression saved: %u",
528  XLogRecBlockImageApply(record, block_id) ?
529  "" : " for WAL verification",
530  record->blocks[block_id].hole_offset,
531  record->blocks[block_id].hole_length,
532  BLCKSZ -
533  record->blocks[block_id].hole_length -
534  record->blocks[block_id].bimg_len);
535  }
536  else
537  {
538  printf(" (FPW%s); hole: offset: %u, length: %u",
539  XLogRecBlockImageApply(record, block_id) ?
540  "" : " for WAL verification",
541  record->blocks[block_id].hole_offset,
542  record->blocks[block_id].hole_length);
543  }
544  }
545  putchar('\n');
546  }
547  }
548 }
549 
550 /*
551  * Display a single row of record counts and sizes for an rmgr or record.
552  */
553 static void
554 XLogDumpStatsRow(const char *name,
555  uint64 n, uint64 total_count,
556  uint64 rec_len, uint64 total_rec_len,
557  uint64 fpi_len, uint64 total_fpi_len,
558  uint64 tot_len, uint64 total_len)
559 {
560  double n_pct,
561  rec_len_pct,
562  fpi_len_pct,
563  tot_len_pct;
564 
565  n_pct = 0;
566  if (total_count != 0)
567  n_pct = 100 * (double) n / total_count;
568 
569  rec_len_pct = 0;
570  if (total_rec_len != 0)
571  rec_len_pct = 100 * (double) rec_len / total_rec_len;
572 
573  fpi_len_pct = 0;
574  if (total_fpi_len != 0)
575  fpi_len_pct = 100 * (double) fpi_len / total_fpi_len;
576 
577  tot_len_pct = 0;
578  if (total_len != 0)
579  tot_len_pct = 100 * (double) tot_len / total_len;
580 
581  printf("%-27s "
582  "%20" INT64_MODIFIER "u (%6.02f) "
583  "%20" INT64_MODIFIER "u (%6.02f) "
584  "%20" INT64_MODIFIER "u (%6.02f) "
585  "%20" INT64_MODIFIER "u (%6.02f)\n",
586  name, n, n_pct, rec_len, rec_len_pct, fpi_len, fpi_len_pct,
587  tot_len, tot_len_pct);
588 }
589 
590 
591 /*
592  * Display summary statistics about the records seen so far.
593  */
594 static void
596 {
597  int ri,
598  rj;
599  uint64 total_count = 0;
600  uint64 total_rec_len = 0;
601  uint64 total_fpi_len = 0;
602  uint64 total_len = 0;
603  double rec_len_pct,
604  fpi_len_pct;
605 
606  /* ---
607  * Make a first pass to calculate column totals:
608  * count(*),
609  * sum(xl_len+SizeOfXLogRecord),
610  * sum(xl_tot_len-xl_len-SizeOfXLogRecord), and
611  * sum(xl_tot_len).
612  * These are used to calculate percentages for each record type.
613  * ---
614  */
615 
616  for (ri = 0; ri < RM_NEXT_ID; ri++)
617  {
618  total_count += stats->rmgr_stats[ri].count;
619  total_rec_len += stats->rmgr_stats[ri].rec_len;
620  total_fpi_len += stats->rmgr_stats[ri].fpi_len;
621  }
622  total_len = total_rec_len + total_fpi_len;
623 
624  /*
625  * 27 is strlen("Transaction/COMMIT_PREPARED"), 20 is strlen(2^64), 8 is
626  * strlen("(100.00%)")
627  */
628 
629  printf("%-27s %20s %8s %20s %8s %20s %8s %20s %8s\n"
630  "%-27s %20s %8s %20s %8s %20s %8s %20s %8s\n",
631  "Type", "N", "(%)", "Record size", "(%)", "FPI size", "(%)", "Combined size", "(%)",
632  "----", "-", "---", "-----------", "---", "--------", "---", "-------------", "---");
633 
634  for (ri = 0; ri < RM_NEXT_ID; ri++)
635  {
636  uint64 count,
637  rec_len,
638  fpi_len,
639  tot_len;
640  const RmgrDescData *desc = &RmgrDescTable[ri];
641 
642  if (!config->stats_per_record)
643  {
644  count = stats->rmgr_stats[ri].count;
645  rec_len = stats->rmgr_stats[ri].rec_len;
646  fpi_len = stats->rmgr_stats[ri].fpi_len;
647  tot_len = rec_len + fpi_len;
648 
650  count, total_count, rec_len, total_rec_len,
651  fpi_len, total_fpi_len, tot_len, total_len);
652  }
653  else
654  {
655  for (rj = 0; rj < MAX_XLINFO_TYPES; rj++)
656  {
657  const char *id;
658 
659  count = stats->record_stats[ri][rj].count;
660  rec_len = stats->record_stats[ri][rj].rec_len;
661  fpi_len = stats->record_stats[ri][rj].fpi_len;
662  tot_len = rec_len + fpi_len;
663 
664  /* Skip undefined combinations and ones that didn't occur */
665  if (count == 0)
666  continue;
667 
668  /* the upper four bits in xl_info are the rmgr's */
669  id = desc->rm_identify(rj << 4);
670  if (id == NULL)
671  id = psprintf("UNKNOWN (%x)", rj << 4);
672 
673  XLogDumpStatsRow(psprintf("%s/%s", desc->rm_name, id),
674  count, total_count, rec_len, total_rec_len,
675  fpi_len, total_fpi_len, tot_len, total_len);
676  }
677  }
678  }
679 
680  printf("%-27s %20s %8s %20s %8s %20s %8s %20s\n",
681  "", "--------", "", "--------", "", "--------", "", "--------");
682 
683  /*
684  * The percentages in earlier rows were calculated against the column
685  * total, but the ones that follow are against the row total. Note that
686  * these are displayed with a % symbol to differentiate them from the
687  * earlier ones, and are thus up to 9 characters long.
688  */
689 
690  rec_len_pct = 0;
691  if (total_len != 0)
692  rec_len_pct = 100 * (double) total_rec_len / total_len;
693 
694  fpi_len_pct = 0;
695  if (total_len != 0)
696  fpi_len_pct = 100 * (double) total_fpi_len / total_len;
697 
698  printf("%-27s "
699  "%20" INT64_MODIFIER "u %-9s"
700  "%20" INT64_MODIFIER "u %-9s"
701  "%20" INT64_MODIFIER "u %-9s"
702  "%20" INT64_MODIFIER "u %-6s\n",
703  "Total", stats->count, "",
704  total_rec_len, psprintf("[%.02f%%]", rec_len_pct),
705  total_fpi_len, psprintf("[%.02f%%]", fpi_len_pct),
706  total_len, "[100%]");
707 }
708 
709 static void
710 usage(void)
711 {
712  printf(_("%s decodes and displays PostgreSQL write-ahead logs for debugging.\n\n"),
713  progname);
714  printf(_("Usage:\n"));
715  printf(_(" %s [OPTION]... [STARTSEG [ENDSEG]]\n"), progname);
716  printf(_("\nOptions:\n"));
717  printf(_(" -b, --bkp-details output detailed information about backup blocks\n"));
718  printf(_(" -e, --end=RECPTR stop reading at WAL location RECPTR\n"));
719  printf(_(" -f, --follow keep retrying after reaching end of WAL\n"));
720  printf(_(" -n, --limit=N number of records to display\n"));
721  printf(_(" -p, --path=PATH directory in which to find log segment files or a\n"
722  " directory with a ./pg_wal that contains such files\n"
723  " (default: current directory, ./pg_wal, $PGDATA/pg_wal)\n"));
724  printf(_(" -r, --rmgr=RMGR only show records generated by resource manager RMGR;\n"
725  " use --rmgr=list to list valid resource manager names\n"));
726  printf(_(" -s, --start=RECPTR start reading at WAL location RECPTR\n"));
727  printf(_(" -t, --timeline=TLI timeline from which to read log records\n"
728  " (default: 1 or the value used in STARTSEG)\n"));
729  printf(_(" -V, --version output version information, then exit\n"));
730  printf(_(" -x, --xid=XID only show records with transaction ID XID\n"));
731  printf(_(" -z, --stats[=record] show statistics instead of records\n"
732  " (optionally, show per-record statistics)\n"));
733  printf(_(" -?, --help show this help, then exit\n"));
734  printf(_("\nReport bugs to <pgsql-bugs@lists.postgresql.org>.\n"));
735 }
736 
737 int
738 main(int argc, char **argv)
739 {
740  uint32 xlogid;
741  uint32 xrecoff;
742  XLogReaderState *xlogreader_state;
743  XLogDumpPrivate private;
744  XLogDumpConfig config;
745  XLogDumpStats stats;
746  XLogRecord *record;
747  XLogRecPtr first_record;
748  char *waldir = NULL;
749  char *errormsg;
750 
751  static struct option long_options[] = {
752  {"bkp-details", no_argument, NULL, 'b'},
753  {"end", required_argument, NULL, 'e'},
754  {"follow", no_argument, NULL, 'f'},
755  {"help", no_argument, NULL, '?'},
756  {"limit", required_argument, NULL, 'n'},
757  {"path", required_argument, NULL, 'p'},
758  {"rmgr", required_argument, NULL, 'r'},
759  {"start", required_argument, NULL, 's'},
760  {"timeline", required_argument, NULL, 't'},
761  {"xid", required_argument, NULL, 'x'},
762  {"version", no_argument, NULL, 'V'},
763  {"stats", optional_argument, NULL, 'z'},
764  {NULL, 0, NULL, 0}
765  };
766 
767  int option;
768  int optindex = 0;
769 
770  pg_logging_init(argv[0]);
771  set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pg_waldump"));
772  progname = get_progname(argv[0]);
773 
774  if (argc > 1)
775  {
776  if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
777  {
778  usage();
779  exit(0);
780  }
781  if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
782  {
783  puts("pg_waldump (PostgreSQL) " PG_VERSION);
784  exit(0);
785  }
786  }
787 
788  memset(&private, 0, sizeof(XLogDumpPrivate));
789  memset(&config, 0, sizeof(XLogDumpConfig));
790  memset(&stats, 0, sizeof(XLogDumpStats));
791 
792  private.timeline = 1;
793  private.startptr = InvalidXLogRecPtr;
794  private.endptr = InvalidXLogRecPtr;
795  private.endptr_reached = false;
796 
797  config.bkp_details = false;
798  config.stop_after_records = -1;
799  config.already_displayed_records = 0;
800  config.follow = false;
801  config.filter_by_rmgr = -1;
803  config.filter_by_xid_enabled = false;
804  config.stats = false;
805  config.stats_per_record = false;
806 
807  if (argc <= 1)
808  {
809  pg_log_error("no arguments specified");
810  goto bad_argument;
811  }
812 
813  while ((option = getopt_long(argc, argv, "be:fn:p:r:s:t:x:z",
814  long_options, &optindex)) != -1)
815  {
816  switch (option)
817  {
818  case 'b':
819  config.bkp_details = true;
820  break;
821  case 'e':
822  if (sscanf(optarg, "%X/%X", &xlogid, &xrecoff) != 2)
823  {
824  pg_log_error("could not parse end WAL location \"%s\"",
825  optarg);
826  goto bad_argument;
827  }
828  private.endptr = (uint64) xlogid << 32 | xrecoff;
829  break;
830  case 'f':
831  config.follow = true;
832  break;
833  case 'n':
834  if (sscanf(optarg, "%d", &config.stop_after_records) != 1)
835  {
836  pg_log_error("could not parse limit \"%s\"", optarg);
837  goto bad_argument;
838  }
839  break;
840  case 'p':
841  waldir = pg_strdup(optarg);
842  break;
843  case 'r':
844  {
845  int i;
846 
847  if (pg_strcasecmp(optarg, "list") == 0)
848  {
849  print_rmgr_list();
850  exit(EXIT_SUCCESS);
851  }
852 
853  for (i = 0; i <= RM_MAX_ID; i++)
854  {
855  if (pg_strcasecmp(optarg, RmgrDescTable[i].rm_name) == 0)
856  {
857  config.filter_by_rmgr = i;
858  break;
859  }
860  }
861 
862  if (config.filter_by_rmgr == -1)
863  {
864  pg_log_error("resource manager \"%s\" does not exist",
865  optarg);
866  goto bad_argument;
867  }
868  }
869  break;
870  case 's':
871  if (sscanf(optarg, "%X/%X", &xlogid, &xrecoff) != 2)
872  {
873  pg_log_error("could not parse start WAL location \"%s\"",
874  optarg);
875  goto bad_argument;
876  }
877  else
878  private.startptr = (uint64) xlogid << 32 | xrecoff;
879  break;
880  case 't':
881  if (sscanf(optarg, "%d", &private.timeline) != 1)
882  {
883  pg_log_error("could not parse timeline \"%s\"", optarg);
884  goto bad_argument;
885  }
886  break;
887  case 'x':
888  if (sscanf(optarg, "%u", &config.filter_by_xid) != 1)
889  {
890  pg_log_error("could not parse \"%s\" as a transaction ID",
891  optarg);
892  goto bad_argument;
893  }
894  config.filter_by_xid_enabled = true;
895  break;
896  case 'z':
897  config.stats = true;
898  config.stats_per_record = false;
899  if (optarg)
900  {
901  if (strcmp(optarg, "record") == 0)
902  config.stats_per_record = true;
903  else if (strcmp(optarg, "rmgr") != 0)
904  {
905  pg_log_error("unrecognized argument to --stats: %s",
906  optarg);
907  goto bad_argument;
908  }
909  }
910  break;
911  default:
912  goto bad_argument;
913  }
914  }
915 
916  if ((optind + 2) < argc)
917  {
918  pg_log_error("too many command-line arguments (first is \"%s\")",
919  argv[optind + 2]);
920  goto bad_argument;
921  }
922 
923  if (waldir != NULL)
924  {
925  /* validate path points to directory */
926  if (!verify_directory(waldir))
927  {
928  pg_log_error("path \"%s\" could not be opened: %s",
929  waldir, strerror(errno));
930  goto bad_argument;
931  }
932  }
933 
934  /* parse files as start/end boundaries, extract path if not specified */
935  if (optind < argc)
936  {
937  char *directory = NULL;
938  char *fname = NULL;
939  int fd;
940  XLogSegNo segno;
941 
942  split_path(argv[optind], &directory, &fname);
943 
944  if (waldir == NULL && directory != NULL)
945  {
946  waldir = directory;
947 
948  if (!verify_directory(waldir))
949  fatal_error("could not open directory \"%s\": %s",
950  waldir, strerror(errno));
951  }
952 
953  waldir = identify_target_directory(waldir, fname);
954  fd = open_file_in_directory(waldir, fname);
955  if (fd < 0)
956  fatal_error("could not open file \"%s\"", fname);
957  close(fd);
958 
959  /* parse position from file */
960  XLogFromFileName(fname, &private.timeline, &segno, WalSegSz);
961 
962  if (XLogRecPtrIsInvalid(private.startptr))
963  XLogSegNoOffsetToRecPtr(segno, 0, WalSegSz, private.startptr);
964  else if (!XLByteInSeg(private.startptr, segno, WalSegSz))
965  {
966  pg_log_error("start WAL location %X/%X is not inside file \"%s\"",
967  (uint32) (private.startptr >> 32),
968  (uint32) private.startptr,
969  fname);
970  goto bad_argument;
971  }
972 
973  /* no second file specified, set end position */
974  if (!(optind + 1 < argc) && XLogRecPtrIsInvalid(private.endptr))
975  XLogSegNoOffsetToRecPtr(segno + 1, 0, WalSegSz, private.endptr);
976 
977  /* parse ENDSEG if passed */
978  if (optind + 1 < argc)
979  {
980  XLogSegNo endsegno;
981 
982  /* ignore directory, already have that */
983  split_path(argv[optind + 1], &directory, &fname);
984 
985  fd = open_file_in_directory(waldir, fname);
986  if (fd < 0)
987  fatal_error("could not open file \"%s\"", fname);
988  close(fd);
989 
990  /* parse position from file */
991  XLogFromFileName(fname, &private.timeline, &endsegno, WalSegSz);
992 
993  if (endsegno < segno)
994  fatal_error("ENDSEG %s is before STARTSEG %s",
995  argv[optind + 1], argv[optind]);
996 
997  if (XLogRecPtrIsInvalid(private.endptr))
998  XLogSegNoOffsetToRecPtr(endsegno + 1, 0, WalSegSz,
999  private.endptr);
1000 
1001  /* set segno to endsegno for check of --end */
1002  segno = endsegno;
1003  }
1004 
1005 
1006  if (!XLByteInSeg(private.endptr, segno, WalSegSz) &&
1007  private.endptr != (segno + 1) * WalSegSz)
1008  {
1009  pg_log_error("end WAL location %X/%X is not inside file \"%s\"",
1010  (uint32) (private.endptr >> 32),
1011  (uint32) private.endptr,
1012  argv[argc - 1]);
1013  goto bad_argument;
1014  }
1015  }
1016  else
1017  waldir = identify_target_directory(waldir, NULL);
1018 
1019  /* we don't know what to print */
1020  if (XLogRecPtrIsInvalid(private.startptr))
1021  {
1022  pg_log_error("no start WAL location given");
1023  goto bad_argument;
1024  }
1025 
1026  /* done with argument parsing, do the actual work */
1027 
1028  /* we have everything we need, start reading */
1029  xlogreader_state = XLogReaderAllocate(WalSegSz, waldir, WALDumpReadPage,
1030  &private);
1031  if (!xlogreader_state)
1032  fatal_error("out of memory");
1033 
1034  /* first find a valid recptr to start from */
1035  first_record = XLogFindNextRecord(xlogreader_state, private.startptr);
1036 
1037  if (first_record == InvalidXLogRecPtr)
1038  fatal_error("could not find a valid record after %X/%X",
1039  (uint32) (private.startptr >> 32),
1040  (uint32) private.startptr);
1041 
1042  /*
1043  * Display a message that we're skipping data if `from` wasn't a pointer
1044  * to the start of a record and also wasn't a pointer to the beginning of
1045  * a segment (e.g. we were used in file mode).
1046  */
1047  if (first_record != private.startptr &&
1048  XLogSegmentOffset(private.startptr, WalSegSz) != 0)
1049  printf(ngettext("first record is after %X/%X, at %X/%X, skipping over %u byte\n",
1050  "first record is after %X/%X, at %X/%X, skipping over %u bytes\n",
1051  (first_record - private.startptr)),
1052  (uint32) (private.startptr >> 32), (uint32) private.startptr,
1053  (uint32) (first_record >> 32), (uint32) first_record,
1054  (uint32) (first_record - private.startptr));
1055 
1056  for (;;)
1057  {
1058  /* try to read the next record */
1059  record = XLogReadRecord(xlogreader_state, first_record, &errormsg);
1060  if (!record)
1061  {
1062  if (!config.follow || private.endptr_reached)
1063  break;
1064  else
1065  {
1066  pg_usleep(1000000L); /* 1 second */
1067  continue;
1068  }
1069  }
1070 
1071  /* after reading the first record, continue at next one */
1072  first_record = InvalidXLogRecPtr;
1073 
1074  /* apply all specified filters */
1075  if (config.filter_by_rmgr != -1 &&
1076  config.filter_by_rmgr != record->xl_rmid)
1077  continue;
1078 
1079  if (config.filter_by_xid_enabled &&
1080  config.filter_by_xid != record->xl_xid)
1081  continue;
1082 
1083  /* process the record */
1084  if (config.stats == true)
1085  XLogDumpCountRecord(&config, &stats, xlogreader_state);
1086  else
1087  XLogDumpDisplayRecord(&config, xlogreader_state);
1088 
1089  /* check whether we printed enough */
1090  config.already_displayed_records++;
1091  if (config.stop_after_records > 0 &&
1093  break;
1094  }
1095 
1096  if (config.stats == true)
1097  XLogDumpDisplayStats(&config, &stats);
1098 
1099  if (errormsg)
1100  fatal_error("error in WAL record at %X/%X: %s",
1101  (uint32) (xlogreader_state->ReadRecPtr >> 32),
1102  (uint32) xlogreader_state->ReadRecPtr,
1103  errormsg);
1104 
1105  XLogReaderFree(xlogreader_state);
1106 
1107  return EXIT_SUCCESS;
1108 
1109 bad_argument:
1110  fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
1111  return EXIT_FAILURE;
1112 }
#define fatal_error(...)
Definition: pg_waldump.c:72
WALOpenSegment wre_seg
Definition: xlogreader.h:264
#define IsValidWalSegSize(size)
Definition: xlog_internal.h:97
static void usage(void)
Definition: pg_waldump.c:710
char ws_dir[MAXPGPATH]
Definition: xlogreader.h:45
static int WALDumpOpenSegment(XLogSegNo nextSegNo, WALSegmentContext *segcxt, TimeLineID *tli_p)
Definition: pg_waldump.c:284
static void XLogDumpDisplayStats(XLogDumpConfig *config, XLogDumpStats *stats)
Definition: pg_waldump.c:595
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
int already_displayed_records
Definition: pg_waldump.c:45
char * pnstrdup(const char *in, Size len)
Definition: mcxt.c:1197
XLogRecPtr endptr
Definition: pg_waldump.c:36
uint32 TimeLineID
Definition: xlogdefs.h:52
#define EXIT_SUCCESS
Definition: settings.h:149
static bool search_directory(const char *directory, const char *fname)
Definition: pg_waldump.c:157
uint32 TransactionId
Definition: c.h:514
uint64 count
Definition: pg_waldump.c:58
#define XLogRecHasBlockImage(decoder, block_id)
Definition: xlogreader.h:288
int filter_by_rmgr
Definition: pg_waldump.c:51
XLogRecPtr startptr
Definition: pg_waldump.c:35
const char * get_progname(const char *argv0)
Definition: path.c:453
#define pg_log_error(...)
Definition: logging.h:79
int getopt_long(int argc, char *const argv[], const char *optstring, const struct option *longopts, int *longindex)
Definition: getopt_long.c:57
void pg_logging_init(const char *argv0)
Definition: logging.c:39
char * psprintf(const char *fmt,...)
Definition: psprintf.c:46
uint64 count
Definition: pg_waldump.c:67
uint16 hole_offset
Definition: xlogreader.h:75
struct Stats Stats
unsigned char uint8
Definition: c.h:357
int closedir(DIR *)
Definition: dirent.c:113
#define XLogRecHasBlockRef(decoder, block_id)
Definition: xlogreader.h:286
Stats record_stats[RM_NEXT_ID][MAX_XLINFO_TYPES]
Definition: pg_waldump.c:69
RmgrId xl_rmid
Definition: xlogrecord.h:47
#define printf(...)
Definition: port.h:198
uint32 BlockNumber
Definition: block.h:31
TransactionId filter_by_xid
Definition: pg_waldump.c:52
int pg_strcasecmp(const char *s1, const char *s2)
Definition: pgstrcasecmp.c:36
bool bkp_details
Definition: pg_waldump.c:43
bool endptr_reached
Definition: pg_waldump.c:37
void * private_data
Definition: xlogreader.h:125
uint16 bimg_len
Definition: xlogreader.h:77
#define fprintf
Definition: port.h:196
Definition: dirent.h:9
static char * identify_target_directory(char *directory, char *fname)
Definition: pg_waldump.c:238
static int fd(const char *x, int i)
Definition: preproc-init.c:105
#define PG_BINARY
Definition: c.h:1222
#define XLogRecGetTotalLen(decoder)
Definition: xlogreader.h:277
XLogRecord * XLogReadRecord(XLogReaderState *state, XLogRecPtr RecPtr, char **errormsg)
Definition: xlogreader.c:238
#define XLByteInSeg(xlrp, logSegNo, wal_segsz_bytes)
XLogLongPageHeaderData * XLogLongPageHeader
Definition: xlog_internal.h:74
Stats rmgr_stats[RM_NEXT_ID]
Definition: pg_waldump.c:68
WALOpenSegment seg
Definition: xlogreader.h:169
bool filter_by_xid_enabled
Definition: pg_waldump.c:53
void pg_usleep(long microsec)
Definition: signal.c:53
#define required_argument
Definition: getopt_long.h:25
void pfree(void *pointer)
Definition: mcxt.c:1056
int optind
Definition: getopt.c:50
Definition: dirent.c:25
uint16 hole_length
Definition: xlogreader.h:76
#define IsXLogFileName(fname)
TimeLineID timeline
Definition: pg_waldump.c:34
#define MAXPGPATH
const RmgrDescData RmgrDescTable[RM_MAX_ID+1]
Definition: rmgrdesc.c:38
DIR * opendir(const char *)
Definition: dirent.c:33
#define XLogRecGetPrev(decoder)
Definition: xlogreader.h:278
#define XLogFromFileName(fname, tli, logSegNo, wal_segsz_bytes)
static void XLogDumpCountRecord(XLogDumpConfig *config, XLogDumpStats *stats, XLogReaderState *record)
Definition: pg_waldump.c:404
static char * buf
Definition: pg_test_fsync.c:67
uint64 XLogSegNo
Definition: xlogdefs.h:41
static void XLogDumpDisplayRecord(XLogDumpConfig *config, XLogReaderState *record)
Definition: pg_waldump.c:442
bool WALRead(char *buf, XLogRecPtr startptr, Size count, TimeLineID tli, WALOpenSegment *seg, WALSegmentContext *segcxt, WALSegmentOpen openSegment, WALReadError *errinfo)
Definition: xlogreader.c:1033
XLogRecPtr ReadRecPtr
Definition: xlogreader.h:131
XLogSegNo ws_segno
Definition: xlogreader.h:38
char * datadir
char * pg_strdup(const char *in)
Definition: fe_memutils.c:85
#define InvalidTransactionId
Definition: transam.h:31
static void split_path(const char *path, char **dir, char **fname)
Definition: pg_waldump.c:107
unsigned int uint32
Definition: c.h:359
struct XLogDumpConfig XLogDumpConfig
static int WALDumpReadPage(XLogReaderState *state, XLogRecPtr targetPagePtr, int reqLen, XLogRecPtr targetPtr, char *readBuff)
Definition: pg_waldump.c:327
#define XLogRecGetInfo(decoder)
Definition: xlogreader.h:279
ForkNumber
Definition: relpath.h:40
const char * rm_name
Definition: rmgrdesc.h:16
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
#define XLogRecPtrIsInvalid(r)
Definition: xlogdefs.h:29
void XLogReaderFree(XLogReaderState *state)
Definition: xlogreader.c:135
#define RM_MAX_ID
Definition: rmgr.h:33
bool XLogRecGetBlockTag(XLogReaderState *record, uint8 block_id, RelFileNode *rnode, ForkNumber *forknum, BlockNumber *blknum)
Definition: xlogreader.c:1460
#define XLogRecGetXid(decoder)
Definition: xlogreader.h:281
#define no_argument
Definition: getopt_long.h:24
#define ngettext(s, p, n)
Definition: c.h:1134
#define PG_TEXTDOMAIN(domain)
Definition: c.h:1166
#define BKPIMAGE_IS_COMPRESSED
Definition: xlogrecord.h:147
static int WalSegSz
Definition: pg_waldump.c:30
#define XLOGDIR
#define XLogSegmentOffset(xlogptr, wal_segsz_bytes)
const char *(* rm_identify)(uint8 info)
Definition: rmgrdesc.h:18
uint8 RmgrId
Definition: rmgr.h:11
#define XLogSegNoOffsetToRecPtr(segno, offset, wal_segsz_bytes, dest)
uint64 XLogRecPtr
Definition: xlogdefs.h:21
#define Assert(condition)
Definition: c.h:739
#define XLR_INFO_MASK
Definition: xlogrecord.h:62
#define MAX_XLINFO_TYPES
Definition: pg_waldump.c:63
Definition: regguts.h:298
#define strerror
Definition: port.h:205
size_t Size
Definition: c.h:467
#define XLogFileName(fname, tli, logSegNo, wal_segsz_bytes)
static const char * directory
Definition: zic.c:622
static int open_file_in_directory(const char *directory, const char *fname)
Definition: pg_waldump.c:134
#define optional_argument
Definition: getopt_long.h:26
struct dirent * readdir(DIR *)
Definition: dirent.c:77
static bool verify_directory(const char *directory)
Definition: pg_waldump.c:90
struct XLogDumpPrivate XLogDumpPrivate
const char * name
Definition: encode.c:521
TimeLineID ws_tli
Definition: xlogreader.h:39
uint64 fpi_len
Definition: pg_waldump.c:60
uint64 rec_len
Definition: pg_waldump.c:59
XLogReaderState * XLogReaderAllocate(int wal_segment_size, const char *waldir, XLogPageReadCB pagereadfunc, void *private_data)
Definition: xlogreader.c:73
TransactionId xl_xid
Definition: xlogrecord.h:44
void set_pglocale_pgservice(const char *argv0, const char *app)
Definition: exec.c:565
static const char * progname
Definition: pg_waldump.c:28
static void XLogDumpStatsRow(const char *name, uint64 n, uint64 total_count, uint64 rec_len, uint64 total_rec_len, uint64 fpi_len, uint64 total_fpi_len, uint64 tot_len, uint64 total_len)
Definition: pg_waldump.c:554
char * optarg
Definition: getopt.c:52
int i
int stop_after_records
Definition: pg_waldump.c:44
#define EXIT_FAILURE
Definition: settings.h:153
struct XLogDumpStats XLogDumpStats
WALSegmentContext segcxt
Definition: xlogreader.h:168
void(* rm_desc)(StringInfo buf, XLogReaderState *record)
Definition: rmgrdesc.h:17
char d_name[MAX_PATH]
Definition: dirent.h:14
#define XLogRecBlockImageApply(decoder, block_id)
Definition: xlogreader.h:290
static void print_rmgr_list(void)
Definition: pg_waldump.c:75
bool stats_per_record
Definition: pg_waldump.c:48
#define close(a)
Definition: win32.h:12
const char *const forkNames[]
Definition: relpath.c:33
char data[XLOG_BLCKSZ]
Definition: c.h:1099
#define snprintf
Definition: port.h:192
#define _(x)
Definition: elog.c:87
int main(int argc, char **argv)
Definition: pg_waldump.c:738
#define read(a, b, c)
Definition: win32.h:13
DecodedBkpBlock blocks[XLR_MAX_BLOCK_ID+1]
Definition: xlogreader.h:151
#define XLogRecGetRmid(decoder)
Definition: xlogreader.h:280
static void XLogDumpRecordLen(XLogReaderState *record, uint32 *rec_len, uint32 *fpi_len)
Definition: pg_waldump.c:375