LCOV - code coverage report
Current view: top level - src/bin/pg_waldump - pg_waldump.c (source / functions) Hit Total Coverage
Test: PostgreSQL 14devel Lines: 159 423 37.6 %
Date: 2020-11-27 12:05:55 Functions: 9 16 56.2 %
Legend: Lines: hit not hit

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

Generated by: LCOV version 1.13