1 /*-------------------------------------------------------------------------
4 * A utility to "zero out" the xlog when it's corrupt beyond recovery.
5 * Can also rebuild pg_control if needed.
7 * The theory of operation is fairly simple:
8 * 1. Read the existing pg_control (which will include the last
9 * checkpoint record). If it is an old format then update to
11 * 2. If pg_control is corrupt, attempt to intuit reasonable values,
12 * by scanning the old xlog if necessary.
13 * 3. Modify pg_control to reflect a "shutdown" state with a checkpoint
14 * record at the start of xlog.
15 * 4. Flush the existing xlog files and write a new segment with
16 * just a checkpoint record in it. The new segment is positioned
17 * just past the end of the old xlog, so that existing LSNs in
18 * data pages will appear to be "in the past".
19 * This is all pretty straightforward except for the intuition part of
23 * Portions Copyright (c) 1996-2005, PostgreSQL Global Development Group
24 * Portions Copyright (c) 1994, Regents of the University of California
26 * $PostgreSQL: pgsql/src/bin/pg_resetxlog/pg_resetxlog.c,v 1.38 2005/10/15 02:49:40 momjian Exp $
28 *-------------------------------------------------------------------------
43 #include "access/multixact.h"
44 #include "access/xlog.h"
45 #include "access/xlog_internal.h"
46 #include "catalog/catversion.h"
47 #include "catalog/pg_control.h"
53 static ControlFileData ControlFile; /* pg_control values */
54 static uint32 newXlogId,
55 newXlogSeg; /* ID/Segment of new XLOG segment */
56 static bool guessed = false; /* T if we had to guess at any values */
57 static const char *progname;
59 static bool ReadControlFile(void);
60 static void GuessControlValues(void);
61 static void PrintControlValues(bool guessed);
62 static void RewriteControlFile(void);
63 static void KillExistingXLOG(void);
64 static void WriteEmptyXLOG(void);
65 static void usage(void);
69 main(int argc, char *argv[])
73 bool noupdate = false;
74 TransactionId set_xid = 0;
76 MultiXactId set_mxid = 0;
77 MultiXactOffset set_mxoff = -1;
78 uint32 minXlogTli = 0,
88 set_pglocale_pgservice(argv[0], "pg_resetxlog");
90 progname = get_progname(argv[0]);
94 if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
99 if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
101 puts("pg_resetxlog (PostgreSQL) " PG_VERSION);
107 while ((c = getopt(argc, argv, "fl:m:no:O:x:")) != -1)
120 set_xid = strtoul(optarg, &endptr, 0);
121 if (endptr == optarg || *endptr != '\0')
123 fprintf(stderr, _("%s: invalid argument for option -x\n"), progname);
124 fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
129 fprintf(stderr, _("%s: transaction ID (-x) must not be 0\n"), progname);
135 set_oid = strtoul(optarg, &endptr, 0);
136 if (endptr == optarg || *endptr != '\0')
138 fprintf(stderr, _("%s: invalid argument for option -o\n"), progname);
139 fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
144 fprintf(stderr, _("%s: OID (-o) must not be 0\n"), progname);
150 set_mxid = strtoul(optarg, &endptr, 0);
151 if (endptr == optarg || *endptr != '\0')
153 fprintf(stderr, _("%s: invalid argument for option -m\n"), progname);
154 fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
159 fprintf(stderr, _("%s: multitransaction ID (-m) must not be 0\n"), progname);
165 set_mxoff = strtoul(optarg, &endptr, 0);
166 if (endptr == optarg || *endptr != '\0')
168 fprintf(stderr, _("%s: invalid argument for option -O\n"), progname);
169 fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
174 fprintf(stderr, _("%s: multitransaction offset (-O) must not be -1\n"), progname);
180 minXlogTli = strtoul(optarg, &endptr, 0);
181 if (endptr == optarg || *endptr != ',')
183 fprintf(stderr, _("%s: invalid argument for option -l\n"), progname);
184 fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
187 minXlogId = strtoul(endptr + 1, &endptr2, 0);
188 if (endptr2 == endptr + 1 || *endptr2 != ',')
190 fprintf(stderr, _("%s: invalid argument for option -l\n"), progname);
191 fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
194 minXlogSeg = strtoul(endptr2 + 1, &endptr3, 0);
195 if (endptr3 == endptr2 + 1 || *endptr3 != '\0')
197 fprintf(stderr, _("%s: invalid argument for option -l\n"), progname);
198 fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
204 fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
211 fprintf(stderr, _("%s: no data directory specified\n"), progname);
212 fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
217 * Don't allow pg_resetxlog to be run as root, to avoid overwriting the
218 * ownership of files in the data directory. We need only check for root
219 * -- any other user won't have sufficient permissions to modify files in
220 * the data directory.
223 #ifndef __BEOS__ /* no root check on BeOS */
226 fprintf(stderr, _("%s: cannot be executed by \"root\"\n"),
228 fprintf(stderr, _("You must run %s as the PostgreSQL superuser.\n"),
235 DataDir = argv[optind];
237 if (chdir(DataDir) < 0)
239 fprintf(stderr, _("%s: could not change directory to \"%s\": %s\n"),
240 progname, DataDir, strerror(errno));
245 * Check for a postmaster lock file --- if there is one, refuse to
246 * proceed, on grounds we might be interfering with a live installation.
248 snprintf(path, MAXPGPATH, "%s/postmaster.pid", DataDir);
250 if ((fd = open(path, O_RDONLY)) < 0)
254 fprintf(stderr, _("%s: could not open file \"%s\" for reading: %s\n"), progname, path, strerror(errno));
260 fprintf(stderr, _("%s: lock file \"%s\" exists\n"
261 "Is a server running? If not, delete the lock file and try again.\n"),
267 * Attempt to read the existing pg_control file
269 if (!ReadControlFile())
270 GuessControlValues();
273 * Adjust fields if required by switches. (Do this now so that printout,
274 * if any, includes these values.)
277 ControlFile.checkPointCopy.nextXid = set_xid;
280 ControlFile.checkPointCopy.nextOid = set_oid;
283 ControlFile.checkPointCopy.nextMulti = set_mxid;
286 ControlFile.checkPointCopy.nextMultiOffset = set_mxoff;
288 if (minXlogTli > ControlFile.checkPointCopy.ThisTimeLineID)
289 ControlFile.checkPointCopy.ThisTimeLineID = minXlogTli;
291 if (minXlogId > ControlFile.logId ||
292 (minXlogId == ControlFile.logId &&
293 minXlogSeg > ControlFile.logSeg))
295 ControlFile.logId = minXlogId;
296 ControlFile.logSeg = minXlogSeg;
300 * If we had to guess anything, and -f was not given, just print the
301 * guessed values and exit. Also print if -n is given.
303 if ((guessed && !force) || noupdate)
305 PrintControlValues(guessed);
308 printf(_("\nIf these values seem acceptable, use -f to force reset.\n"));
316 * Don't reset from a dirty pg_control without -f, either.
318 if (ControlFile.state != DB_SHUTDOWNED && !force)
320 printf(_("The database server was not shut down cleanly.\n"
321 "Resetting the transaction log may cause data to be lost.\n"
322 "If you want to proceed anyway, use -f to force reset.\n"));
327 * Else, do the dirty deed.
329 RewriteControlFile();
333 printf(_("Transaction log reset\n"));
339 * Try to read the existing pg_control file.
341 * This routine is also responsible for updating old pg_control versions
342 * to the current format. (Currently we don't do anything of the sort.)
345 ReadControlFile(void)
352 if ((fd = open(XLOG_CONTROL_FILE, O_RDONLY)) < 0)
355 * If pg_control is not there at all, or we can't read it, the odds
356 * are we've been handed a bad DataDir path, so give up. User can do
357 * "touch pg_control" to force us to proceed.
359 fprintf(stderr, _("%s: could not open file \"%s\" for reading: %s\n"),
360 progname, XLOG_CONTROL_FILE, strerror(errno));
362 fprintf(stderr, _("If you are sure the data directory path is correct, execute\n"
369 /* Use malloc to ensure we have a maxaligned buffer */
370 buffer = (char *) malloc(BLCKSZ);
372 len = read(fd, buffer, BLCKSZ);
375 fprintf(stderr, _("%s: could not read file \"%s\": %s\n"),
376 progname, XLOG_CONTROL_FILE, strerror(errno));
381 if (len >= sizeof(ControlFileData) &&
382 ((ControlFileData *) buffer)->pg_control_version == PG_CONTROL_VERSION)
388 offsetof(ControlFileData, crc));
391 if (EQ_CRC32(crc, ((ControlFileData *) buffer)->crc))
394 memcpy(&ControlFile, buffer, sizeof(ControlFile));
398 fprintf(stderr, _("%s: pg_control exists but has invalid CRC; proceed with caution\n"),
400 /* We will use the data anyway, but treat it as guessed. */
401 memcpy(&ControlFile, buffer, sizeof(ControlFile));
406 /* Looks like it's a mess. */
407 fprintf(stderr, _("%s: pg_control exists but is broken or unknown version; ignoring it\n"),
414 * Guess at pg_control values when we can't read the old ones.
417 GuessControlValues(void)
419 uint64 sysidentifier;
424 * Set up a completely default set of pg_control values.
427 memset(&ControlFile, 0, sizeof(ControlFile));
429 ControlFile.pg_control_version = PG_CONTROL_VERSION;
430 ControlFile.catalog_version_no = CATALOG_VERSION_NO;
433 * Create a new unique installation identifier, since we can no longer use
434 * any old XLOG records. See notes in xlog.c about the algorithm.
436 gettimeofday(&tv, NULL);
437 sysidentifier = ((uint64) tv.tv_sec) << 32;
438 sysidentifier |= (uint32) (tv.tv_sec | tv.tv_usec);
440 ControlFile.system_identifier = sysidentifier;
442 ControlFile.checkPointCopy.redo.xlogid = 0;
443 ControlFile.checkPointCopy.redo.xrecoff = SizeOfXLogLongPHD;
444 ControlFile.checkPointCopy.undo = ControlFile.checkPointCopy.redo;
445 ControlFile.checkPointCopy.ThisTimeLineID = 1;
446 ControlFile.checkPointCopy.nextXid = (TransactionId) 514; /* XXX */
447 ControlFile.checkPointCopy.nextOid = FirstBootstrapObjectId;
448 ControlFile.checkPointCopy.nextMulti = FirstMultiXactId;
449 ControlFile.checkPointCopy.nextMultiOffset = 0;
450 ControlFile.checkPointCopy.time = time(NULL);
452 ControlFile.state = DB_SHUTDOWNED;
453 ControlFile.time = time(NULL);
454 ControlFile.logId = 0;
455 ControlFile.logSeg = 1;
456 ControlFile.checkPoint = ControlFile.checkPointCopy.redo;
458 ControlFile.maxAlign = MAXIMUM_ALIGNOF;
459 ControlFile.floatFormat = FLOATFORMAT_VALUE;
460 ControlFile.blcksz = BLCKSZ;
461 ControlFile.relseg_size = RELSEG_SIZE;
462 ControlFile.xlog_seg_size = XLOG_SEG_SIZE;
463 ControlFile.nameDataLen = NAMEDATALEN;
464 ControlFile.indexMaxKeys = INDEX_MAX_KEYS;
465 #ifdef HAVE_INT64_TIMESTAMP
466 ControlFile.enableIntTimes = TRUE;
468 ControlFile.enableIntTimes = FALSE;
470 ControlFile.localeBuflen = LOCALE_NAME_BUFLEN;
472 localeptr = setlocale(LC_COLLATE, "");
475 fprintf(stderr, _("%s: invalid LC_COLLATE setting\n"), progname);
478 StrNCpy(ControlFile.lc_collate, localeptr, LOCALE_NAME_BUFLEN);
479 localeptr = setlocale(LC_CTYPE, "");
482 fprintf(stderr, _("%s: invalid LC_CTYPE setting\n"), progname);
485 StrNCpy(ControlFile.lc_ctype, localeptr, LOCALE_NAME_BUFLEN);
488 * XXX eventually, should try to grovel through old XLOG to develop more
489 * accurate values for TimeLineID, nextXID, etc.
495 * Print the guessed pg_control values when we had to guess.
497 * NB: this display should be just those fields that will not be
498 * reset by RewriteControlFile().
501 PrintControlValues(bool guessed)
503 char sysident_str[32];
506 printf(_("Guessed pg_control values:\n\n"));
508 printf(_("pg_control values:\n\n"));
511 * Format system_identifier separately to keep platform-dependent format
512 * code out of the translatable message string.
514 snprintf(sysident_str, sizeof(sysident_str), UINT64_FORMAT,
515 ControlFile.system_identifier);
517 printf(_("pg_control version number: %u\n"), ControlFile.pg_control_version);
518 printf(_("Catalog version number: %u\n"), ControlFile.catalog_version_no);
519 printf(_("Database system identifier: %s\n"), sysident_str);
520 printf(_("Current log file ID: %u\n"), ControlFile.logId);
521 printf(_("Next log file segment: %u\n"), ControlFile.logSeg);
522 printf(_("Latest checkpoint's TimeLineID: %u\n"), ControlFile.checkPointCopy.ThisTimeLineID);
523 printf(_("Latest checkpoint's NextXID: %u\n"), ControlFile.checkPointCopy.nextXid);
524 printf(_("Latest checkpoint's NextOID: %u\n"), ControlFile.checkPointCopy.nextOid);
525 printf(_("Latest checkpoint's NextMultiXactId: %u\n"), ControlFile.checkPointCopy.nextMulti);
526 printf(_("Latest checkpoint's NextMultiOffset: %u\n"), ControlFile.checkPointCopy.nextMultiOffset);
527 printf(_("Maximum data alignment: %u\n"), ControlFile.maxAlign);
528 /* we don't print floatFormat since can't say much useful about it */
529 printf(_("Database block size: %u\n"), ControlFile.blcksz);
530 printf(_("Blocks per segment of large relation: %u\n"), ControlFile.relseg_size);
531 printf(_("Maximum length of identifiers: %u\n"), ControlFile.nameDataLen);
532 printf(_("Maximum columns in an index: %u\n"), ControlFile.indexMaxKeys);
533 printf(_("Date/time type storage: %s\n"),
534 (ControlFile.enableIntTimes ? _("64-bit integers") : _("floating-point numbers")));
535 printf(_("Maximum length of locale name: %u\n"), ControlFile.localeBuflen);
536 printf(_("LC_COLLATE: %s\n"), ControlFile.lc_collate);
537 printf(_("LC_CTYPE: %s\n"), ControlFile.lc_ctype);
542 * Write out the new pg_control file.
545 RewriteControlFile(void)
548 char buffer[BLCKSZ]; /* need not be aligned */
551 * Adjust fields as needed to force an empty XLOG starting at the next
554 newXlogId = ControlFile.logId;
555 newXlogSeg = ControlFile.logSeg;
557 /* adjust in case we are changing segment size */
558 newXlogSeg *= ControlFile.xlog_seg_size;
559 newXlogSeg = (newXlogSeg + XLogSegSize - 1) / XLogSegSize;
561 /* be sure we wrap around correctly at end of a logfile */
562 NextLogSeg(newXlogId, newXlogSeg);
564 /* Now we can force the recorded xlog seg size to the right thing. */
565 ControlFile.xlog_seg_size = XLogSegSize;
567 ControlFile.checkPointCopy.redo.xlogid = newXlogId;
568 ControlFile.checkPointCopy.redo.xrecoff =
569 newXlogSeg * XLogSegSize + SizeOfXLogLongPHD;
570 ControlFile.checkPointCopy.undo = ControlFile.checkPointCopy.redo;
571 ControlFile.checkPointCopy.time = time(NULL);
573 ControlFile.state = DB_SHUTDOWNED;
574 ControlFile.time = time(NULL);
575 ControlFile.logId = newXlogId;
576 ControlFile.logSeg = newXlogSeg + 1;
577 ControlFile.checkPoint = ControlFile.checkPointCopy.redo;
578 ControlFile.prevCheckPoint.xlogid = 0;
579 ControlFile.prevCheckPoint.xrecoff = 0;
581 /* Contents are protected with a CRC */
582 INIT_CRC32(ControlFile.crc);
583 COMP_CRC32(ControlFile.crc,
584 (char *) &ControlFile,
585 offsetof(ControlFileData, crc));
586 FIN_CRC32(ControlFile.crc);
589 * We write out BLCKSZ bytes into pg_control, zero-padding the excess over
590 * sizeof(ControlFileData). This reduces the odds of premature-EOF errors
591 * when reading pg_control. We'll still fail when we check the contents
592 * of the file, but hopefully with a more specific error than "couldn't
595 if (sizeof(ControlFileData) > BLCKSZ)
598 _("%s: internal error -- sizeof(ControlFileData) is too large ... fix xlog.c\n"),
603 memset(buffer, 0, BLCKSZ);
604 memcpy(buffer, &ControlFile, sizeof(ControlFileData));
606 unlink(XLOG_CONTROL_FILE);
608 fd = open(XLOG_CONTROL_FILE,
609 O_RDWR | O_CREAT | O_EXCL | PG_BINARY,
613 fprintf(stderr, _("%s: could not create pg_control file: %s\n"),
614 progname, strerror(errno));
619 if (write(fd, buffer, BLCKSZ) != BLCKSZ)
621 /* if write didn't set errno, assume problem is no disk space */
624 fprintf(stderr, _("%s: could not write pg_control file: %s\n"),
625 progname, strerror(errno));
631 fprintf(stderr, _("%s: fsync error: %s\n"), progname, strerror(errno));
640 * Remove existing XLOG files
643 KillExistingXLOG(void)
647 char path[MAXPGPATH];
649 xldir = opendir(XLOGDIR);
652 fprintf(stderr, _("%s: could not open directory \"%s\": %s\n"),
653 progname, XLOGDIR, strerror(errno));
658 while ((xlde = readdir(xldir)) != NULL)
660 if (strlen(xlde->d_name) == 24 &&
661 strspn(xlde->d_name, "0123456789ABCDEF") == 24)
663 snprintf(path, MAXPGPATH, "%s/%s", XLOGDIR, xlde->d_name);
664 if (unlink(path) < 0)
666 fprintf(stderr, _("%s: could not delete file \"%s\": %s\n"),
667 progname, path, strerror(errno));
676 * This fix is in mingw cvs (runtime/mingwex/dirent.c rev 1.4), but not in
679 if (GetLastError() == ERROR_NO_MORE_FILES)
685 fprintf(stderr, _("%s: could not read from directory \"%s\": %s\n"),
686 progname, XLOGDIR, strerror(errno));
694 * Write an empty XLOG file, containing only the checkpoint record
695 * already set up in ControlFile.
702 XLogLongPageHeader longpage;
705 char path[MAXPGPATH];
709 /* Use malloc() to ensure buffer is MAXALIGNED */
710 buffer = (char *) malloc(BLCKSZ);
711 page = (XLogPageHeader) buffer;
712 memset(buffer, 0, BLCKSZ);
714 /* Set up the XLOG page header */
715 page->xlp_magic = XLOG_PAGE_MAGIC;
716 page->xlp_info = XLP_LONG_HEADER;
717 page->xlp_tli = ControlFile.checkPointCopy.ThisTimeLineID;
718 page->xlp_pageaddr.xlogid =
719 ControlFile.checkPointCopy.redo.xlogid;
720 page->xlp_pageaddr.xrecoff =
721 ControlFile.checkPointCopy.redo.xrecoff - SizeOfXLogLongPHD;
722 longpage = (XLogLongPageHeader) page;
723 longpage->xlp_sysid = ControlFile.system_identifier;
724 longpage->xlp_seg_size = XLogSegSize;
726 /* Insert the initial checkpoint record */
727 record = (XLogRecord *) ((char *) page + SizeOfXLogLongPHD);
728 record->xl_prev.xlogid = 0;
729 record->xl_prev.xrecoff = 0;
730 record->xl_xid = InvalidTransactionId;
731 record->xl_tot_len = SizeOfXLogRecord + sizeof(CheckPoint);
732 record->xl_len = sizeof(CheckPoint);
733 record->xl_info = XLOG_CHECKPOINT_SHUTDOWN;
734 record->xl_rmid = RM_XLOG_ID;
735 memcpy(XLogRecGetData(record), &ControlFile.checkPointCopy,
739 COMP_CRC32(crc, &ControlFile.checkPointCopy, sizeof(CheckPoint));
740 COMP_CRC32(crc, (char *) record + sizeof(pg_crc32),
741 SizeOfXLogRecord - sizeof(pg_crc32));
743 record->xl_crc = crc;
745 /* Write the first page */
746 XLogFilePath(path, ControlFile.checkPointCopy.ThisTimeLineID,
747 newXlogId, newXlogSeg);
751 fd = open(path, O_RDWR | O_CREAT | O_EXCL | PG_BINARY,
755 fprintf(stderr, _("%s: could not open file \"%s\": %s\n"),
756 progname, path, strerror(errno));
761 if (write(fd, buffer, BLCKSZ) != BLCKSZ)
763 /* if write didn't set errno, assume problem is no disk space */
766 fprintf(stderr, _("%s: could not write file \"%s\": %s\n"),
767 progname, path, strerror(errno));
771 /* Fill the rest of the file with zeroes */
772 memset(buffer, 0, BLCKSZ);
773 for (nbytes = BLCKSZ; nbytes < XLogSegSize; nbytes += BLCKSZ)
776 if (write(fd, buffer, BLCKSZ) != BLCKSZ)
780 fprintf(stderr, _("%s: could not write file \"%s\": %s\n"),
781 progname, path, strerror(errno));
788 fprintf(stderr, _("%s: fsync error: %s\n"), progname, strerror(errno));
799 printf(_("%s resets the PostgreSQL transaction log.\n\n"), progname);
800 printf(_("Usage:\n %s [OPTION]... DATADIR\n\n"), progname);
801 printf(_("Options:\n"));
802 printf(_(" -f force update to be done\n"));
803 printf(_(" -l TLI,FILE,SEG force minimum WAL starting location for new transaction log\n"));
804 printf(_(" -m XID set next multitransaction ID\n"));
805 printf(_(" -n no update, just show extracted control values (for testing)\n"));
806 printf(_(" -o OID set next OID\n"));
807 printf(_(" -O OFFSET set next multitransaction offset\n"));
808 printf(_(" -x XID set next transaction ID\n"));
809 printf(_(" --help show this help, then exit\n"));
810 printf(_(" --version output version information, then exit\n"));
811 printf(_("\nReport bugs to <pgsql-bugs@postgresql.org>.\n"));