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-2003, 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.16 2004/02/17 03:45:17 momjian Exp $
28 *-------------------------------------------------------------------------
41 #include "access/xlog.h"
42 #include "catalog/catversion.h"
43 #include "catalog/pg_control.h"
45 /******************** stuff copied from xlog.c ********************/
47 /* Increment an xlogid/segment pair */
48 #define NextLogSeg(logId, logSeg) \
50 if ((logSeg) >= XLogSegsPerFile-1) \
59 #define XLogFileName(path, log, seg) \
60 snprintf(path, MAXPGPATH, "%s/%08X%08X", \
63 /******************** end of stuff copied from xlog.c ********************/
65 #define _(x) gettext((x))
67 static char XLogDir[MAXPGPATH];
68 static char ControlFilePath[MAXPGPATH];
70 static ControlFileData ControlFile; /* pg_control values */
71 static uint32 newXlogId,
72 newXlogSeg; /* ID/Segment of new XLOG segment */
73 static bool guessed = false; /* T if we had to guess at any values */
74 static char *progname;
76 static bool ReadControlFile(void);
77 static void GuessControlValues(void);
78 static void PrintControlValues(bool guessed);
79 static void RewriteControlFile(void);
80 static void KillExistingXLOG(void);
81 static void WriteEmptyXLOG(void);
82 static void usage(void);
89 main(int argc, char *argv[])
93 bool noupdate = false;
94 TransactionId set_xid = 0;
102 char path[MAXPGPATH];
104 setlocale(LC_ALL, "");
106 bindtextdomain("pg_resetxlog", LOCALEDIR);
107 textdomain("pg_resetxlog");
110 progname = get_progname(argv[0]);
114 if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
119 if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
121 puts("pg_resetxlog (PostgreSQL) " PG_VERSION);
127 while ((c = getopt(argc, argv, "fl:no:x:")) != -1)
140 set_xid = strtoul(optarg, &endptr, 0);
141 if (endptr == optarg || *endptr != '\0')
143 fprintf(stderr, _("%s: invalid argument for option -x\n"), progname);
144 fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
149 fprintf(stderr, _("%s: transaction ID (-x) must not be 0\n"), progname);
155 set_oid = strtoul(optarg, &endptr, 0);
156 if (endptr == optarg || *endptr != '\0')
158 fprintf(stderr, _("%s: invalid argument for option -o\n"), progname);
159 fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
164 fprintf(stderr, _("%s: OID (-o) must not be 0\n"), progname);
170 minXlogId = strtoul(optarg, &endptr, 0);
171 if (endptr == optarg || *endptr != ',')
173 fprintf(stderr, _("%s: invalid argument for option -l\n"), progname);
174 fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
177 minXlogSeg = strtoul(endptr + 1, &endptr2, 0);
178 if (endptr2 == endptr + 1 || *endptr2 != '\0')
180 fprintf(stderr, _("%s: invalid argument for option -l\n"), progname);
181 fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
187 fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
194 fprintf(stderr, _("%s: no data directory specified\n"), progname);
195 fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
199 DataDir = argv[optind];
200 snprintf(XLogDir, MAXPGPATH, "%s/pg_xlog", DataDir);
201 snprintf(ControlFilePath, MAXPGPATH, "%s/global/pg_control", DataDir);
204 * Check for a postmaster lock file --- if there is one, refuse to
205 * proceed, on grounds we might be interfering with a live
208 snprintf(path, MAXPGPATH, "%s/postmaster.pid", DataDir);
210 if ((fd = open(path, O_RDONLY)) < 0)
214 fprintf(stderr, _("%s: could not open file \"%s\" for reading: %s\n"), progname, path, strerror(errno));
220 fprintf(stderr, _("%s: lock file \"%s\" exists\n"
221 "Is a server running? If not, delete the lock file and try again.\n"),
227 * Attempt to read the existing pg_control file
229 if (!ReadControlFile())
230 GuessControlValues();
233 * Adjust fields if required by switches. (Do this now so that
234 * printout, if any, includes these values.)
237 ControlFile.checkPointCopy.nextXid = set_xid;
240 ControlFile.checkPointCopy.nextOid = set_oid;
242 if (minXlogId > ControlFile.logId ||
243 (minXlogId == ControlFile.logId &&
244 minXlogSeg > ControlFile.logSeg))
246 ControlFile.logId = minXlogId;
247 ControlFile.logSeg = minXlogSeg;
251 * If we had to guess anything, and -f was not given, just print the
252 * guessed values and exit. Also print if -n is given.
254 if ((guessed && !force) || noupdate)
256 PrintControlValues(guessed);
259 printf(_("\nIf these values seem acceptable, use -f to force reset.\n"));
267 * Don't reset from a dirty pg_control without -f, either.
269 if (ControlFile.state != DB_SHUTDOWNED && !force)
271 printf(_("The database server was not shut down cleanly.\n"
272 "Resetting the transaction log may cause data to be lost.\n"
273 "If you want to proceed anyway, use -f to force reset.\n"));
278 * Else, do the dirty deed.
280 RewriteControlFile();
284 printf(_("Transaction log reset\n"));
290 * Try to read the existing pg_control file.
292 * This routine is also responsible for updating old pg_control versions
293 * to the current format. (Currently we don't do anything of the sort.)
296 ReadControlFile(void)
303 if ((fd = open(ControlFilePath, O_RDONLY)) < 0)
306 * If pg_control is not there at all, or we can't read it, the
307 * odds are we've been handed a bad DataDir path, so give up. User
308 * can do "touch pg_control" to force us to proceed.
310 fprintf(stderr, _("%s: could not open file \"%s\" for reading: %s\n"),
311 progname, ControlFilePath, strerror(errno));
313 fprintf(stderr, _("If you are sure the data directory path is correct, execute\n"
320 /* Use malloc to ensure we have a maxaligned buffer */
321 buffer = (char *) malloc(BLCKSZ);
323 len = read(fd, buffer, BLCKSZ);
326 fprintf(stderr, _("%s: could not read file \"%s\": %s\n"),
327 progname, ControlFilePath, strerror(errno));
332 if (len >= sizeof(ControlFileData) &&
333 ((ControlFileData *) buffer)->pg_control_version == PG_CONTROL_VERSION)
338 buffer + sizeof(crc64),
339 sizeof(ControlFileData) - sizeof(crc64));
342 if (EQ_CRC64(crc, ((ControlFileData *) buffer)->crc))
345 memcpy(&ControlFile, buffer, sizeof(ControlFile));
349 fprintf(stderr, _("%s: pg_control exists but has invalid CRC; proceed with caution\n"),
351 /* We will use the data anyway, but treat it as guessed. */
352 memcpy(&ControlFile, buffer, sizeof(ControlFile));
357 /* Looks like it's a mess. */
358 fprintf(stderr, _("%s: pg_control exists but is broken or unknown version; ignoring it\n"),
365 * Guess at pg_control values when we can't read the old ones.
368 GuessControlValues(void)
370 uint64 sysidentifier;
375 * Set up a completely default set of pg_control values.
378 memset(&ControlFile, 0, sizeof(ControlFile));
380 ControlFile.pg_control_version = PG_CONTROL_VERSION;
381 ControlFile.catalog_version_no = CATALOG_VERSION_NO;
384 * Create a new unique installation identifier, since we can no longer
385 * use any old XLOG records. See notes in xlog.c about the algorithm.
387 gettimeofday(&tv, NULL);
388 sysidentifier = ((uint64) tv.tv_sec) << 32;
389 sysidentifier |= (uint32) (tv.tv_sec | tv.tv_usec);
391 ControlFile.system_identifier = sysidentifier;
393 ControlFile.checkPointCopy.redo.xlogid = 0;
394 ControlFile.checkPointCopy.redo.xrecoff = SizeOfXLogPHD + SizeOfXLogRecord + SizeOfXLogFHD;
395 ControlFile.checkPointCopy.undo = ControlFile.checkPointCopy.redo;
396 ControlFile.checkPointCopy.ThisStartUpID = 0;
397 ControlFile.checkPointCopy.nextXid = (TransactionId) 514; /* XXX */
398 ControlFile.checkPointCopy.nextOid = BootstrapObjectIdData;
399 ControlFile.checkPointCopy.time = time(NULL);
401 ControlFile.state = DB_SHUTDOWNED;
402 ControlFile.time = time(NULL);
403 ControlFile.logId = 0;
404 ControlFile.logSeg = 1;
405 ControlFile.checkPoint = ControlFile.checkPointCopy.redo;
407 ControlFile.blcksz = BLCKSZ;
408 ControlFile.relseg_size = RELSEG_SIZE;
409 ControlFile.xlog_seg_size = XLOG_SEG_SIZE;
410 ControlFile.nameDataLen = NAMEDATALEN;
411 ControlFile.funcMaxArgs = FUNC_MAX_ARGS;
412 #ifdef HAVE_INT64_TIMESTAMP
413 ControlFile.enableIntTimes = TRUE;
415 ControlFile.enableIntTimes = FALSE;
417 ControlFile.localeBuflen = LOCALE_NAME_BUFLEN;
419 localeptr = setlocale(LC_COLLATE, "");
422 fprintf(stderr, _("%s: invalid LC_COLLATE setting\n"), progname);
425 StrNCpy(ControlFile.lc_collate, localeptr, LOCALE_NAME_BUFLEN);
426 localeptr = setlocale(LC_CTYPE, "");
429 fprintf(stderr, _("%s: invalid LC_CTYPE setting\n"), progname);
432 StrNCpy(ControlFile.lc_ctype, localeptr, LOCALE_NAME_BUFLEN);
435 * XXX eventually, should try to grovel through old XLOG to develop
436 * more accurate values for startupid, nextXID, and nextOID.
442 * Print the guessed pg_control values when we had to guess.
444 * NB: this display should be just those fields that will not be
445 * reset by RewriteControlFile().
448 PrintControlValues(bool guessed)
450 char sysident_str[32];
453 printf(_("Guessed pg_control values:\n\n"));
455 printf(_("pg_control values:\n\n"));
458 * Format system_identifier separately to keep platform-dependent format
459 * code out of the translatable message string.
461 snprintf(sysident_str, sizeof(sysident_str), UINT64_FORMAT,
462 ControlFile.system_identifier);
464 printf(_("pg_control version number: %u\n"), ControlFile.pg_control_version);
465 printf(_("Catalog version number: %u\n"), ControlFile.catalog_version_no);
466 printf(_("Database system identifier: %s\n"), sysident_str);
467 printf(_("Current log file ID: %u\n"), ControlFile.logId);
468 printf(_("Next log file segment: %u\n"), ControlFile.logSeg);
469 printf(_("Latest checkpoint's StartUpID: %u\n"), ControlFile.checkPointCopy.ThisStartUpID);
470 printf(_("Latest checkpoint's NextXID: %u\n"), ControlFile.checkPointCopy.nextXid);
471 printf(_("Latest checkpoint's NextOID: %u\n"), ControlFile.checkPointCopy.nextOid);
472 printf(_("Database block size: %u\n"), ControlFile.blcksz);
473 printf(_("Blocks per segment of large relation: %u\n"), ControlFile.relseg_size);
474 printf(_("Maximum length of identifiers: %u\n"), ControlFile.nameDataLen);
475 printf(_("Maximum number of function arguments: %u\n"), ControlFile.funcMaxArgs);
476 printf(_("Date/time type storage: %s\n"),
477 (ControlFile.enableIntTimes ? _("64-bit integers") : _("floating-point numbers")));
478 printf(_("Maximum length of locale name: %u\n"), ControlFile.localeBuflen);
479 printf(_("LC_COLLATE: %s\n"), ControlFile.lc_collate);
480 printf(_("LC_CTYPE: %s\n"), ControlFile.lc_ctype);
485 * Write out the new pg_control file.
488 RewriteControlFile(void)
491 char buffer[BLCKSZ]; /* need not be aligned */
494 * Adjust fields as needed to force an empty XLOG starting at the next
497 newXlogId = ControlFile.logId;
498 newXlogSeg = ControlFile.logSeg;
500 /* adjust in case we are changing segment size */
501 newXlogSeg *= ControlFile.xlog_seg_size;
502 newXlogSeg = (newXlogSeg + XLogSegSize-1) / XLogSegSize;
504 /* be sure we wrap around correctly at end of a logfile */
505 NextLogSeg(newXlogId, newXlogSeg);
507 /* Now we can force the recorded xlog seg size to the right thing. */
508 ControlFile.xlog_seg_size = XLogSegSize;
510 ControlFile.checkPointCopy.redo.xlogid = newXlogId;
511 ControlFile.checkPointCopy.redo.xrecoff =
512 newXlogSeg * XLogSegSize + SizeOfXLogPHD + SizeOfXLogRecord + SizeOfXLogFHD;
513 ControlFile.checkPointCopy.undo = ControlFile.checkPointCopy.redo;
514 ControlFile.checkPointCopy.time = time(NULL);
516 ControlFile.state = DB_SHUTDOWNED;
517 ControlFile.time = time(NULL);
518 ControlFile.logId = newXlogId;
519 ControlFile.logSeg = newXlogSeg + 1;
520 ControlFile.checkPoint = ControlFile.checkPointCopy.redo;
521 ControlFile.prevCheckPoint.xlogid = 0;
522 ControlFile.prevCheckPoint.xrecoff = 0;
524 /* Contents are protected with a CRC */
525 INIT_CRC64(ControlFile.crc);
526 COMP_CRC64(ControlFile.crc,
527 (char *) &ControlFile + sizeof(crc64),
528 sizeof(ControlFileData) - sizeof(crc64));
529 FIN_CRC64(ControlFile.crc);
532 * We write out BLCKSZ bytes into pg_control, zero-padding the excess
533 * over sizeof(ControlFileData). This reduces the odds of
534 * premature-EOF errors when reading pg_control. We'll still fail
535 * when we check the contents of the file, but hopefully with a more
536 * specific error than "couldn't read pg_control".
538 if (sizeof(ControlFileData) > BLCKSZ)
541 _("%s: internal error -- sizeof(ControlFileData) is too large ... fix xlog.c\n"),
546 memset(buffer, 0, BLCKSZ);
547 memcpy(buffer, &ControlFile, sizeof(ControlFileData));
549 unlink(ControlFilePath);
551 fd = open(ControlFilePath, O_RDWR | O_CREAT | O_EXCL | PG_BINARY, S_IRUSR | S_IWUSR);
554 fprintf(stderr, _("%s: could not create pg_control file: %s\n"),
555 progname, strerror(errno));
560 if (write(fd, buffer, BLCKSZ) != BLCKSZ)
562 /* if write didn't set errno, assume problem is no disk space */
565 fprintf(stderr, _("%s: could not write pg_control file: %s\n"),
566 progname, strerror(errno));
572 fprintf(stderr, _("%s: fsync error: %s\n"), progname, strerror(errno));
581 * Remove existing XLOG files
584 KillExistingXLOG(void)
588 char path[MAXPGPATH];
590 xldir = opendir(XLogDir);
593 fprintf(stderr, _("%s: could not open directory \"%s\": %s\n"),
594 progname, XLogDir, strerror(errno));
599 while ((xlde = readdir(xldir)) != NULL)
601 if (strlen(xlde->d_name) == 16 &&
602 strspn(xlde->d_name, "0123456789ABCDEF") == 16)
604 snprintf(path, MAXPGPATH, "%s/%s", XLogDir, xlde->d_name);
605 if (unlink(path) < 0)
607 fprintf(stderr, _("%s: could not delete file \"%s\": %s\n"),
608 progname, path, strerror(errno));
615 /* This fix is in mingw cvs (runtime/mingwex/dirent.c rev 1.4), but
616 not in released version */
617 if (GetLastError() == ERROR_NO_MORE_FILES)
623 fprintf(stderr, _("%s: could not read from directory \"%s\": %s\n"),
624 progname, XLogDir, strerror(errno));
632 * Write an empty XLOG file, containing only the checkpoint record
633 * already set up in ControlFile.
641 XLogFileHeaderData *fhdr;
643 char path[MAXPGPATH];
647 /* Use malloc() to ensure buffer is MAXALIGNED */
648 buffer = (char *) malloc(BLCKSZ);
649 page = (XLogPageHeader) buffer;
650 memset(buffer, 0, BLCKSZ);
652 /* Set up the XLOG page header */
653 page->xlp_magic = XLOG_PAGE_MAGIC;
655 page->xlp_sui = ControlFile.checkPointCopy.ThisStartUpID;
656 page->xlp_pageaddr.xlogid =
657 ControlFile.checkPointCopy.redo.xlogid;
658 page->xlp_pageaddr.xrecoff =
659 ControlFile.checkPointCopy.redo.xrecoff -
660 (SizeOfXLogPHD + SizeOfXLogRecord + SizeOfXLogFHD);
662 /* Insert the file header record */
663 record = (XLogRecord *) ((char *) page + SizeOfXLogPHD);
664 record->xl_prev.xlogid = 0;
665 record->xl_prev.xrecoff = 0;
666 record->xl_xact_prev.xlogid = 0;
667 record->xl_xact_prev.xrecoff = 0;
668 record->xl_xid = InvalidTransactionId;
669 record->xl_len = SizeOfXLogFHD;
670 record->xl_info = XLOG_FILE_HEADER;
671 record->xl_rmid = RM_XLOG_ID;
672 fhdr = (XLogFileHeaderData *) XLogRecGetData(record);
673 fhdr->xlfhd_sysid = ControlFile.system_identifier;
674 fhdr->xlfhd_xlogid = page->xlp_pageaddr.xlogid;
675 fhdr->xlfhd_segno = page->xlp_pageaddr.xrecoff / XLogSegSize;
676 fhdr->xlfhd_seg_size = XLogSegSize;
679 COMP_CRC64(crc, fhdr, SizeOfXLogFHD);
680 COMP_CRC64(crc, (char *) record + sizeof(crc64),
681 SizeOfXLogRecord - sizeof(crc64));
683 record->xl_crc = crc;
685 /* Insert the initial checkpoint record */
686 record = (XLogRecord *) ((char *) page + SizeOfXLogPHD + SizeOfXLogRecord + SizeOfXLogFHD);
687 record->xl_prev.xlogid = page->xlp_pageaddr.xlogid;
688 record->xl_prev.xrecoff = page->xlp_pageaddr.xrecoff + SizeOfXLogPHD;
689 record->xl_xact_prev.xlogid = 0;
690 record->xl_xact_prev.xrecoff = 0;
691 record->xl_xid = InvalidTransactionId;
692 record->xl_len = sizeof(CheckPoint);
693 record->xl_info = XLOG_CHECKPOINT_SHUTDOWN;
694 record->xl_rmid = RM_XLOG_ID;
695 memcpy(XLogRecGetData(record), &ControlFile.checkPointCopy,
699 COMP_CRC64(crc, &ControlFile.checkPointCopy, sizeof(CheckPoint));
700 COMP_CRC64(crc, (char *) record + sizeof(crc64),
701 SizeOfXLogRecord - sizeof(crc64));
703 record->xl_crc = crc;
705 /* Write the first page */
706 XLogFileName(path, newXlogId, newXlogSeg);
710 fd = open(path, O_RDWR | O_CREAT | O_EXCL | PG_BINARY,
714 fprintf(stderr, _("%s: could not open file \"%s\": %s\n"),
715 progname, path, strerror(errno));
720 if (write(fd, buffer, BLCKSZ) != BLCKSZ)
722 /* if write didn't set errno, assume problem is no disk space */
725 fprintf(stderr, _("%s: could not write file \"%s\": %s\n"),
726 progname, path, strerror(errno));
730 /* Fill the rest of the file with zeroes */
731 memset(buffer, 0, BLCKSZ);
732 for (nbytes = BLCKSZ; nbytes < XLogSegSize; nbytes += BLCKSZ)
735 if (write(fd, buffer, BLCKSZ) != BLCKSZ)
739 fprintf(stderr, _("%s: could not write file \"%s\": %s\n"),
740 progname, path, strerror(errno));
747 fprintf(stderr, _("%s: fsync error: %s\n"), progname, strerror(errno));
758 printf(_("%s resets the PostgreSQL transaction log.\n\n"), progname);
759 printf(_("Usage:\n %s [OPTION]... DATADIR\n\n"), progname);
760 printf(_("Options:\n"));
761 printf(_(" -f force update to be done\n"));
762 printf(_(" -l FILEID,SEG force minimum WAL starting location for new transaction log\n"));
763 printf(_(" -n no update, just show extracted control values (for testing)\n"));
764 printf(_(" -o OID set next OID\n"));
765 printf(_(" -x XID set next transaction ID\n"));
766 printf(_(" --help show this help, then exit\n"));
767 printf(_(" --version output version information, then exit\n"));
768 printf(_("\nReport bugs to <pgsql-bugs@postgresql.org>.\n"));