]> granicus.if.org Git - postgresql/blob - src/bin/pg_resetxlog/pg_resetxlog.c
Create libpgcommon, and move pg_malloc et al to it
[postgresql] / src / bin / pg_resetxlog / pg_resetxlog.c
1 /*-------------------------------------------------------------------------
2  *
3  * pg_resetxlog.c
4  *        A utility to "zero out" the xlog when it's corrupt beyond recovery.
5  *        Can also rebuild pg_control if needed.
6  *
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
10  *               current format.
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
20  * step 2 ...
21  *
22  *
23  * Portions Copyright (c) 1996-2013, PostgreSQL Global Development Group
24  * Portions Copyright (c) 1994, Regents of the University of California
25  *
26  * src/bin/pg_resetxlog/pg_resetxlog.c
27  *
28  *-------------------------------------------------------------------------
29  */
30
31 /*
32  * We have to use postgres.h not postgres_fe.h here, because there's so much
33  * backend-only stuff in the XLOG include files we need.  But we need a
34  * frontend-ish environment otherwise.  Hence this ugly hack.
35  */
36 #define FRONTEND 1
37
38 #include "postgres.h"
39
40 #include <dirent.h>
41 #include <fcntl.h>
42 #include <locale.h>
43 #include <sys/stat.h>
44 #include <sys/time.h>
45 #include <time.h>
46 #include <unistd.h>
47 #ifdef HAVE_GETOPT_H
48 #include <getopt.h>
49 #endif
50
51 #include "access/transam.h"
52 #include "access/tuptoaster.h"
53 #include "access/multixact.h"
54 #include "access/xlog_internal.h"
55 #include "catalog/catversion.h"
56 #include "catalog/pg_control.h"
57 #include "common/fe_memutils.h"
58
59 extern int      optind;
60 extern char *optarg;
61
62
63 static ControlFileData ControlFile;             /* pg_control values */
64 static XLogSegNo newXlogSegNo;  /* new XLOG segment # */
65 static bool guessed = false;    /* T if we had to guess at any values */
66 static const char *progname;
67
68 static bool ReadControlFile(void);
69 static void GuessControlValues(void);
70 static void PrintControlValues(bool guessed);
71 static void RewriteControlFile(void);
72 static void FindEndOfXLOG(void);
73 static void KillExistingXLOG(void);
74 static void KillExistingArchiveStatus(void);
75 static void WriteEmptyXLOG(void);
76 static void usage(void);
77
78
79 int
80 main(int argc, char *argv[])
81 {
82         int                     c;
83         bool            force = false;
84         bool            noupdate = false;
85         uint32          set_xid_epoch = (uint32) -1;
86         TransactionId set_xid = 0;
87         Oid                     set_oid = 0;
88         MultiXactId set_mxid = 0;
89         MultiXactId set_oldestmxid = 0;
90         MultiXactOffset set_mxoff = (MultiXactOffset) -1;
91         uint32          minXlogTli = 0;
92         XLogSegNo       minXlogSegNo = 0;
93         char       *endptr;
94         char       *endptr2;
95         char       *DataDir;
96         int                     fd;
97
98         set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pg_resetxlog"));
99
100         progname = get_progname(argv[0]);
101
102         if (argc > 1)
103         {
104                 if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
105                 {
106                         usage();
107                         exit(0);
108                 }
109                 if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
110                 {
111                         puts("pg_resetxlog (PostgreSQL) " PG_VERSION);
112                         exit(0);
113                 }
114         }
115
116
117         while ((c = getopt(argc, argv, "fl:m:no:O:x:e:")) != -1)
118         {
119                 switch (c)
120                 {
121                         case 'f':
122                                 force = true;
123                                 break;
124
125                         case 'n':
126                                 noupdate = true;
127                                 break;
128
129                         case 'e':
130                                 set_xid_epoch = strtoul(optarg, &endptr, 0);
131                                 if (endptr == optarg || *endptr != '\0')
132                                 {
133                                         fprintf(stderr, _("%s: invalid argument for option -e\n"), progname);
134                                         fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
135                                         exit(1);
136                                 }
137                                 if (set_xid_epoch == -1)
138                                 {
139                                         fprintf(stderr, _("%s: transaction ID epoch (-e) must not be -1\n"), progname);
140                                         exit(1);
141                                 }
142                                 break;
143
144                         case 'x':
145                                 set_xid = strtoul(optarg, &endptr, 0);
146                                 if (endptr == optarg || *endptr != '\0')
147                                 {
148                                         fprintf(stderr, _("%s: invalid argument for option -x\n"), progname);
149                                         fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
150                                         exit(1);
151                                 }
152                                 if (set_xid == 0)
153                                 {
154                                         fprintf(stderr, _("%s: transaction ID (-x) must not be 0\n"), progname);
155                                         exit(1);
156                                 }
157                                 break;
158
159                         case 'o':
160                                 set_oid = strtoul(optarg, &endptr, 0);
161                                 if (endptr == optarg || *endptr != '\0')
162                                 {
163                                         fprintf(stderr, _("%s: invalid argument for option -o\n"), progname);
164                                         fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
165                                         exit(1);
166                                 }
167                                 if (set_oid == 0)
168                                 {
169                                         fprintf(stderr, _("%s: OID (-o) must not be 0\n"), progname);
170                                         exit(1);
171                                 }
172                                 break;
173
174                         case 'm':
175                                 set_mxid = strtoul(optarg, &endptr, 0);
176                                 if (endptr == optarg || *endptr != ',')
177                                 {
178                                         fprintf(stderr, _("%s: invalid argument for option -m\n"), progname);
179                                         fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
180                                         exit(1);
181                                 }
182
183                                 set_oldestmxid = strtoul(endptr + 1, &endptr2, 0);
184                                 if (endptr2 == endptr + 1 || *endptr2 != '\0')
185                                 {
186                                         fprintf(stderr, _("%s: invalid argument for option -m\n"), progname);
187                                         fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
188                                         exit(1);
189                                 }
190                                 if (set_mxid == 0)
191                                 {
192                                         fprintf(stderr, _("%s: multitransaction ID (-m) must not be 0\n"), progname);
193                                         exit(1);
194                                 }
195                                 /*
196                                  * XXX It'd be nice to have more sanity checks here, e.g. so
197                                  * that oldest is not wrapped around w.r.t. nextMulti.
198                                  */
199                                 if (set_oldestmxid == 0)
200                                 {
201                                         fprintf(stderr, _("%s: oldest multitransaction ID (-m) must not be 0\n"),
202                                                         progname);
203                                         exit(1);
204                                 }
205                                 break;
206
207                         case 'O':
208                                 set_mxoff = strtoul(optarg, &endptr, 0);
209                                 if (endptr == optarg || *endptr != '\0')
210                                 {
211                                         fprintf(stderr, _("%s: invalid argument for option -O\n"), progname);
212                                         fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
213                                         exit(1);
214                                 }
215                                 if (set_mxoff == -1)
216                                 {
217                                         fprintf(stderr, _("%s: multitransaction offset (-O) must not be -1\n"), progname);
218                                         exit(1);
219                                 }
220                                 break;
221
222                         case 'l':
223                                 if (strspn(optarg, "01234567890ABCDEFabcdef") != 24)
224                                 {
225                                         fprintf(stderr, _("%s: invalid argument for option -l\n"), progname);
226                                         fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
227                                         exit(1);
228                                 }
229                                 XLogFromFileName(optarg, &minXlogTli, &minXlogSegNo);
230                                 break;
231
232                         default:
233                                 fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
234                                 exit(1);
235                 }
236         }
237
238         if (optind == argc)
239         {
240                 fprintf(stderr, _("%s: no data directory specified\n"), progname);
241                 fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
242                 exit(1);
243         }
244
245         /*
246          * Don't allow pg_resetxlog to be run as root, to avoid overwriting the
247          * ownership of files in the data directory. We need only check for root
248          * -- any other user won't have sufficient permissions to modify files in
249          * the data directory.
250          */
251 #ifndef WIN32
252         if (geteuid() == 0)
253         {
254                 fprintf(stderr, _("%s: cannot be executed by \"root\"\n"),
255                                 progname);
256                 fprintf(stderr, _("You must run %s as the PostgreSQL superuser.\n"),
257                                 progname);
258                 exit(1);
259         }
260 #endif
261
262         DataDir = argv[optind];
263
264         if (chdir(DataDir) < 0)
265         {
266                 fprintf(stderr, _("%s: could not change directory to \"%s\": %s\n"),
267                                 progname, DataDir, strerror(errno));
268                 exit(1);
269         }
270
271         /*
272          * Check for a postmaster lock file --- if there is one, refuse to
273          * proceed, on grounds we might be interfering with a live installation.
274          */
275         if ((fd = open("postmaster.pid", O_RDONLY, 0)) < 0)
276         {
277                 if (errno != ENOENT)
278                 {
279                         fprintf(stderr, _("%s: could not open file \"%s\" for reading: %s\n"),
280                                         progname, "postmaster.pid", strerror(errno));
281                         exit(1);
282                 }
283         }
284         else
285         {
286                 fprintf(stderr, _("%s: lock file \"%s\" exists\n"
287                                                   "Is a server running?  If not, delete the lock file and try again.\n"),
288                                 progname, "postmaster.pid");
289                 exit(1);
290         }
291
292         /*
293          * Attempt to read the existing pg_control file
294          */
295         if (!ReadControlFile())
296                 GuessControlValues();
297
298         /*
299          * Also look at existing segment files to set up newXlogSegNo
300          */
301         FindEndOfXLOG();
302
303         /*
304          * Adjust fields if required by switches.  (Do this now so that printout,
305          * if any, includes these values.)
306          */
307         if (set_xid_epoch != -1)
308                 ControlFile.checkPointCopy.nextXidEpoch = set_xid_epoch;
309
310         if (set_xid != 0)
311         {
312                 ControlFile.checkPointCopy.nextXid = set_xid;
313
314                 /*
315                  * For the moment, just set oldestXid to a value that will force
316                  * immediate autovacuum-for-wraparound.  It's not clear whether adding
317                  * user control of this is useful, so let's just do something that's
318                  * reasonably safe.  The magic constant here corresponds to the
319                  * maximum allowed value of autovacuum_freeze_max_age.
320                  */
321                 ControlFile.checkPointCopy.oldestXid = set_xid - 2000000000;
322                 if (ControlFile.checkPointCopy.oldestXid < FirstNormalTransactionId)
323                         ControlFile.checkPointCopy.oldestXid += FirstNormalTransactionId;
324                 ControlFile.checkPointCopy.oldestXidDB = InvalidOid;
325         }
326
327         if (set_oid != 0)
328                 ControlFile.checkPointCopy.nextOid = set_oid;
329
330         if (set_mxid != 0)
331         {
332                 ControlFile.checkPointCopy.nextMulti = set_mxid;
333
334                 ControlFile.checkPointCopy.oldestMulti = set_oldestmxid;
335                 if (ControlFile.checkPointCopy.oldestMulti < FirstMultiXactId)
336                         ControlFile.checkPointCopy.oldestMulti += FirstMultiXactId;
337                 ControlFile.checkPointCopy.oldestMultiDB = InvalidOid;
338         }
339
340         if (set_mxoff != -1)
341                 ControlFile.checkPointCopy.nextMultiOffset = set_mxoff;
342
343         if (minXlogTli > ControlFile.checkPointCopy.ThisTimeLineID)
344         {
345                 ControlFile.checkPointCopy.ThisTimeLineID = minXlogTli;
346                 ControlFile.checkPointCopy.PrevTimeLineID = minXlogTli;
347         }
348
349         if (minXlogSegNo > newXlogSegNo)
350                 newXlogSegNo = minXlogSegNo;
351
352         /*
353          * If we had to guess anything, and -f was not given, just print the
354          * guessed values and exit.  Also print if -n is given.
355          */
356         if ((guessed && !force) || noupdate)
357         {
358                 PrintControlValues(guessed);
359                 if (!noupdate)
360                 {
361                         printf(_("\nIf these values seem acceptable, use -f to force reset.\n"));
362                         exit(1);
363                 }
364                 else
365                         exit(0);
366         }
367
368         /*
369          * Don't reset from a dirty pg_control without -f, either.
370          */
371         if (ControlFile.state != DB_SHUTDOWNED && !force)
372         {
373                 printf(_("The database server was not shut down cleanly.\n"
374                            "Resetting the transaction log might cause data to be lost.\n"
375                                  "If you want to proceed anyway, use -f to force reset.\n"));
376                 exit(1);
377         }
378
379         /*
380          * Else, do the dirty deed.
381          */
382         RewriteControlFile();
383         KillExistingXLOG();
384         KillExistingArchiveStatus();
385         WriteEmptyXLOG();
386
387         printf(_("Transaction log reset\n"));
388         return 0;
389 }
390
391
392 /*
393  * Try to read the existing pg_control file.
394  *
395  * This routine is also responsible for updating old pg_control versions
396  * to the current format.  (Currently we don't do anything of the sort.)
397  */
398 static bool
399 ReadControlFile(void)
400 {
401         int                     fd;
402         int                     len;
403         char       *buffer;
404         pg_crc32        crc;
405
406         if ((fd = open(XLOG_CONTROL_FILE, O_RDONLY | PG_BINARY, 0)) < 0)
407         {
408                 /*
409                  * If pg_control is not there at all, or we can't read it, the odds
410                  * are we've been handed a bad DataDir path, so give up. User can do
411                  * "touch pg_control" to force us to proceed.
412                  */
413                 fprintf(stderr, _("%s: could not open file \"%s\" for reading: %s\n"),
414                                 progname, XLOG_CONTROL_FILE, strerror(errno));
415                 if (errno == ENOENT)
416                         fprintf(stderr, _("If you are sure the data directory path is correct, execute\n"
417                                                           "  touch %s\n"
418                                                           "and try again.\n"),
419                                         XLOG_CONTROL_FILE);
420                 exit(1);
421         }
422
423         /* Use malloc to ensure we have a maxaligned buffer */
424         buffer = (char *) pg_malloc(PG_CONTROL_SIZE);
425
426         len = read(fd, buffer, PG_CONTROL_SIZE);
427         if (len < 0)
428         {
429                 fprintf(stderr, _("%s: could not read file \"%s\": %s\n"),
430                                 progname, XLOG_CONTROL_FILE, strerror(errno));
431                 exit(1);
432         }
433         close(fd);
434
435         if (len >= sizeof(ControlFileData) &&
436           ((ControlFileData *) buffer)->pg_control_version == PG_CONTROL_VERSION)
437         {
438                 /* Check the CRC. */
439                 INIT_CRC32(crc);
440                 COMP_CRC32(crc,
441                                    buffer,
442                                    offsetof(ControlFileData, crc));
443                 FIN_CRC32(crc);
444
445                 if (EQ_CRC32(crc, ((ControlFileData *) buffer)->crc))
446                 {
447                         /* Valid data... */
448                         memcpy(&ControlFile, buffer, sizeof(ControlFile));
449                         return true;
450                 }
451
452                 fprintf(stderr, _("%s: pg_control exists but has invalid CRC; proceed with caution\n"),
453                                 progname);
454                 /* We will use the data anyway, but treat it as guessed. */
455                 memcpy(&ControlFile, buffer, sizeof(ControlFile));
456                 guessed = true;
457                 return true;
458         }
459
460         /* Looks like it's a mess. */
461         fprintf(stderr, _("%s: pg_control exists but is broken or unknown version; ignoring it\n"),
462                         progname);
463         return false;
464 }
465
466
467 /*
468  * Guess at pg_control values when we can't read the old ones.
469  */
470 static void
471 GuessControlValues(void)
472 {
473         uint64          sysidentifier;
474         struct timeval tv;
475
476         /*
477          * Set up a completely default set of pg_control values.
478          */
479         guessed = true;
480         memset(&ControlFile, 0, sizeof(ControlFile));
481
482         ControlFile.pg_control_version = PG_CONTROL_VERSION;
483         ControlFile.catalog_version_no = CATALOG_VERSION_NO;
484
485         /*
486          * Create a new unique installation identifier, since we can no longer use
487          * any old XLOG records.  See notes in xlog.c about the algorithm.
488          */
489         gettimeofday(&tv, NULL);
490         sysidentifier = ((uint64) tv.tv_sec) << 32;
491         sysidentifier |= (uint32) (tv.tv_sec | tv.tv_usec);
492
493         ControlFile.system_identifier = sysidentifier;
494
495         ControlFile.checkPointCopy.redo = SizeOfXLogLongPHD;
496         ControlFile.checkPointCopy.ThisTimeLineID = 1;
497         ControlFile.checkPointCopy.PrevTimeLineID = 1;
498         ControlFile.checkPointCopy.fullPageWrites = false;
499         ControlFile.checkPointCopy.nextXidEpoch = 0;
500         ControlFile.checkPointCopy.nextXid = FirstNormalTransactionId;
501         ControlFile.checkPointCopy.nextOid = FirstBootstrapObjectId;
502         ControlFile.checkPointCopy.nextMulti = FirstMultiXactId;
503         ControlFile.checkPointCopy.nextMultiOffset = 0;
504         ControlFile.checkPointCopy.oldestXid = FirstNormalTransactionId;
505         ControlFile.checkPointCopy.oldestXidDB = InvalidOid;
506         ControlFile.checkPointCopy.oldestMulti = FirstMultiXactId;
507         ControlFile.checkPointCopy.oldestMultiDB = InvalidOid;
508         ControlFile.checkPointCopy.time = (pg_time_t) time(NULL);
509         ControlFile.checkPointCopy.oldestActiveXid = InvalidTransactionId;
510
511         ControlFile.state = DB_SHUTDOWNED;
512         ControlFile.time = (pg_time_t) time(NULL);
513         ControlFile.checkPoint = ControlFile.checkPointCopy.redo;
514         ControlFile.unloggedLSN = 1;
515
516         /* minRecoveryPoint, backupStartPoint and backupEndPoint can be left zero */
517
518         ControlFile.wal_level = WAL_LEVEL_MINIMAL;
519         ControlFile.MaxConnections = 100;
520         ControlFile.max_prepared_xacts = 0;
521         ControlFile.max_locks_per_xact = 64;
522
523         ControlFile.maxAlign = MAXIMUM_ALIGNOF;
524         ControlFile.floatFormat = FLOATFORMAT_VALUE;
525         ControlFile.blcksz = BLCKSZ;
526         ControlFile.relseg_size = RELSEG_SIZE;
527         ControlFile.xlog_blcksz = XLOG_BLCKSZ;
528         ControlFile.xlog_seg_size = XLOG_SEG_SIZE;
529         ControlFile.nameDataLen = NAMEDATALEN;
530         ControlFile.indexMaxKeys = INDEX_MAX_KEYS;
531         ControlFile.toast_max_chunk_size = TOAST_MAX_CHUNK_SIZE;
532 #ifdef HAVE_INT64_TIMESTAMP
533         ControlFile.enableIntTimes = true;
534 #else
535         ControlFile.enableIntTimes = false;
536 #endif
537         ControlFile.float4ByVal = FLOAT4PASSBYVAL;
538         ControlFile.float8ByVal = FLOAT8PASSBYVAL;
539
540         /*
541          * XXX eventually, should try to grovel through old XLOG to develop more
542          * accurate values for TimeLineID, nextXID, etc.
543          */
544 }
545
546
547 /*
548  * Print the guessed pg_control values when we had to guess.
549  *
550  * NB: this display should be just those fields that will not be
551  * reset by RewriteControlFile().
552  */
553 static void
554 PrintControlValues(bool guessed)
555 {
556         char            sysident_str[32];
557         char            fname[MAXFNAMELEN];
558
559         if (guessed)
560                 printf(_("Guessed pg_control values:\n\n"));
561         else
562                 printf(_("pg_control values:\n\n"));
563
564         /*
565          * Format system_identifier separately to keep platform-dependent format
566          * code out of the translatable message string.
567          */
568         snprintf(sysident_str, sizeof(sysident_str), UINT64_FORMAT,
569                          ControlFile.system_identifier);
570
571         XLogFileName(fname, ControlFile.checkPointCopy.ThisTimeLineID, newXlogSegNo);
572
573         printf(_("First log segment after reset:        %s\n"),
574                    fname);
575         printf(_("pg_control version number:            %u\n"),
576                    ControlFile.pg_control_version);
577         printf(_("Catalog version number:               %u\n"),
578                    ControlFile.catalog_version_no);
579         printf(_("Database system identifier:           %s\n"),
580                    sysident_str);
581         printf(_("Latest checkpoint's TimeLineID:       %u\n"),
582                    ControlFile.checkPointCopy.ThisTimeLineID);
583         printf(_("Latest checkpoint's full_page_writes: %s\n"),
584                    ControlFile.checkPointCopy.fullPageWrites ? _("on") : _("off"));
585         printf(_("Latest checkpoint's NextXID:          %u/%u\n"),
586                    ControlFile.checkPointCopy.nextXidEpoch,
587                    ControlFile.checkPointCopy.nextXid);
588         printf(_("Latest checkpoint's NextOID:          %u\n"),
589                    ControlFile.checkPointCopy.nextOid);
590         printf(_("Latest checkpoint's NextMultiXactId:  %u\n"),
591                    ControlFile.checkPointCopy.nextMulti);
592         printf(_("Latest checkpoint's NextMultiOffset:  %u\n"),
593                    ControlFile.checkPointCopy.nextMultiOffset);
594         printf(_("Latest checkpoint's oldestXID:        %u\n"),
595                    ControlFile.checkPointCopy.oldestXid);
596         printf(_("Latest checkpoint's oldestXID's DB:   %u\n"),
597                    ControlFile.checkPointCopy.oldestXidDB);
598         printf(_("Latest checkpoint's oldestActiveXID:  %u\n"),
599                    ControlFile.checkPointCopy.oldestActiveXid);
600         printf(_("Latest checkpoint's oldestMultiXid:   %u\n"),
601                    ControlFile.checkPointCopy.oldestMulti);
602         printf(_("Latest checkpoint's oldestMulti's DB: %u\n"),
603                    ControlFile.checkPointCopy.oldestMultiDB);
604         printf(_("Maximum data alignment:               %u\n"),
605                    ControlFile.maxAlign);
606         /* we don't print floatFormat since can't say much useful about it */
607         printf(_("Database block size:                  %u\n"),
608                    ControlFile.blcksz);
609         printf(_("Blocks per segment of large relation: %u\n"),
610                    ControlFile.relseg_size);
611         printf(_("WAL block size:                       %u\n"),
612                    ControlFile.xlog_blcksz);
613         printf(_("Bytes per WAL segment:                %u\n"),
614                    ControlFile.xlog_seg_size);
615         printf(_("Maximum length of identifiers:        %u\n"),
616                    ControlFile.nameDataLen);
617         printf(_("Maximum columns in an index:          %u\n"),
618                    ControlFile.indexMaxKeys);
619         printf(_("Maximum size of a TOAST chunk:        %u\n"),
620                    ControlFile.toast_max_chunk_size);
621         printf(_("Date/time type storage:               %s\n"),
622                    (ControlFile.enableIntTimes ? _("64-bit integers") : _("floating-point numbers")));
623         printf(_("Float4 argument passing:              %s\n"),
624                    (ControlFile.float4ByVal ? _("by value") : _("by reference")));
625         printf(_("Float8 argument passing:              %s\n"),
626                    (ControlFile.float8ByVal ? _("by value") : _("by reference")));
627 }
628
629
630 /*
631  * Write out the new pg_control file.
632  */
633 static void
634 RewriteControlFile(void)
635 {
636         int                     fd;
637         char            buffer[PG_CONTROL_SIZE];                /* need not be aligned */
638
639         /*
640          * Adjust fields as needed to force an empty XLOG starting at
641          * newXlogSegNo.
642          */
643         XLogSegNoOffsetToRecPtr(newXlogSegNo, SizeOfXLogLongPHD,
644                                                         ControlFile.checkPointCopy.redo);
645         ControlFile.checkPointCopy.time = (pg_time_t) time(NULL);
646
647         ControlFile.state = DB_SHUTDOWNED;
648         ControlFile.time = (pg_time_t) time(NULL);
649         ControlFile.checkPoint = ControlFile.checkPointCopy.redo;
650         ControlFile.prevCheckPoint = 0;
651         ControlFile.minRecoveryPoint = 0;
652         ControlFile.minRecoveryPointTLI = 0;
653         ControlFile.backupStartPoint = 0;
654         ControlFile.backupEndPoint = 0;
655         ControlFile.backupEndRequired = false;
656
657         /*
658          * Force the defaults for max_* settings. The values don't really matter
659          * as long as wal_level='minimal'; the postmaster will reset these fields
660          * anyway at startup.
661          */
662         ControlFile.wal_level = WAL_LEVEL_MINIMAL;
663         ControlFile.MaxConnections = 100;
664         ControlFile.max_prepared_xacts = 0;
665         ControlFile.max_locks_per_xact = 64;
666
667         /* Now we can force the recorded xlog seg size to the right thing. */
668         ControlFile.xlog_seg_size = XLogSegSize;
669
670         /* Contents are protected with a CRC */
671         INIT_CRC32(ControlFile.crc);
672         COMP_CRC32(ControlFile.crc,
673                            (char *) &ControlFile,
674                            offsetof(ControlFileData, crc));
675         FIN_CRC32(ControlFile.crc);
676
677         /*
678          * We write out PG_CONTROL_SIZE bytes into pg_control, zero-padding the
679          * excess over sizeof(ControlFileData).  This reduces the odds of
680          * premature-EOF errors when reading pg_control.  We'll still fail when we
681          * check the contents of the file, but hopefully with a more specific
682          * error than "couldn't read pg_control".
683          */
684         if (sizeof(ControlFileData) > PG_CONTROL_SIZE)
685         {
686                 fprintf(stderr,
687                                 _("%s: internal error -- sizeof(ControlFileData) is too large ... fix PG_CONTROL_SIZE\n"),
688                                 progname);
689                 exit(1);
690         }
691
692         memset(buffer, 0, PG_CONTROL_SIZE);
693         memcpy(buffer, &ControlFile, sizeof(ControlFileData));
694
695         unlink(XLOG_CONTROL_FILE);
696
697         fd = open(XLOG_CONTROL_FILE,
698                           O_RDWR | O_CREAT | O_EXCL | PG_BINARY,
699                           S_IRUSR | S_IWUSR);
700         if (fd < 0)
701         {
702                 fprintf(stderr, _("%s: could not create pg_control file: %s\n"),
703                                 progname, strerror(errno));
704                 exit(1);
705         }
706
707         errno = 0;
708         if (write(fd, buffer, PG_CONTROL_SIZE) != PG_CONTROL_SIZE)
709         {
710                 /* if write didn't set errno, assume problem is no disk space */
711                 if (errno == 0)
712                         errno = ENOSPC;
713                 fprintf(stderr, _("%s: could not write pg_control file: %s\n"),
714                                 progname, strerror(errno));
715                 exit(1);
716         }
717
718         if (fsync(fd) != 0)
719         {
720                 fprintf(stderr, _("%s: fsync error: %s\n"), progname, strerror(errno));
721                 exit(1);
722         }
723
724         close(fd);
725 }
726
727
728 /*
729  * Scan existing XLOG files and determine the highest existing WAL address
730  *
731  * On entry, ControlFile.checkPointCopy.redo and ControlFile.xlog_seg_size
732  * are assumed valid (note that we allow the old xlog seg size to differ
733  * from what we're using).  On exit, newXlogId and newXlogSeg are set to
734  * suitable values for the beginning of replacement WAL (in our seg size).
735  */
736 static void
737 FindEndOfXLOG(void)
738 {
739         DIR                *xldir;
740         struct dirent *xlde;
741         uint64          segs_per_xlogid;
742         uint64          xlogbytepos;
743
744         /*
745          * Initialize the max() computation using the last checkpoint address from
746          * old pg_control.      Note that for the moment we are working with segment
747          * numbering according to the old xlog seg size.
748          */
749         segs_per_xlogid = (UINT64CONST(0x0000000100000000) / ControlFile.xlog_seg_size);
750         newXlogSegNo = ControlFile.checkPointCopy.redo / ControlFile.xlog_seg_size;
751
752         /*
753          * Scan the pg_xlog directory to find existing WAL segment files. We
754          * assume any present have been used; in most scenarios this should be
755          * conservative, because of xlog.c's attempts to pre-create files.
756          */
757         xldir = opendir(XLOGDIR);
758         if (xldir == NULL)
759         {
760                 fprintf(stderr, _("%s: could not open directory \"%s\": %s\n"),
761                                 progname, XLOGDIR, strerror(errno));
762                 exit(1);
763         }
764
765         errno = 0;
766         while ((xlde = readdir(xldir)) != NULL)
767         {
768                 if (strlen(xlde->d_name) == 24 &&
769                         strspn(xlde->d_name, "0123456789ABCDEF") == 24)
770                 {
771                         unsigned int tli,
772                                                 log,
773                                                 seg;
774                         XLogSegNo       segno;
775
776                         sscanf(xlde->d_name, "%08X%08X%08X", &tli, &log, &seg);
777                         segno = ((uint64) log) * segs_per_xlogid + seg;
778
779                         /*
780                          * Note: we take the max of all files found, regardless of their
781                          * timelines.  Another possibility would be to ignore files of
782                          * timelines other than the target TLI, but this seems safer.
783                          * Better too large a result than too small...
784                          */
785                         if (segno > newXlogSegNo)
786                                 newXlogSegNo = segno;
787                 }
788                 errno = 0;
789         }
790 #ifdef WIN32
791
792         /*
793          * This fix is in mingw cvs (runtime/mingwex/dirent.c rev 1.4), but not in
794          * released version
795          */
796         if (GetLastError() == ERROR_NO_MORE_FILES)
797                 errno = 0;
798 #endif
799
800         if (errno)
801         {
802                 fprintf(stderr, _("%s: could not read from directory \"%s\": %s\n"),
803                                 progname, XLOGDIR, strerror(errno));
804                 exit(1);
805         }
806         closedir(xldir);
807
808         /*
809          * Finally, convert to new xlog seg size, and advance by one to ensure we
810          * are in virgin territory.
811          */
812         xlogbytepos = newXlogSegNo * ControlFile.xlog_seg_size;
813         newXlogSegNo = (xlogbytepos + XLogSegSize - 1) / XLogSegSize;
814         newXlogSegNo++;
815 }
816
817
818 /*
819  * Remove existing XLOG files
820  */
821 static void
822 KillExistingXLOG(void)
823 {
824         DIR                *xldir;
825         struct dirent *xlde;
826         char            path[MAXPGPATH];
827
828         xldir = opendir(XLOGDIR);
829         if (xldir == NULL)
830         {
831                 fprintf(stderr, _("%s: could not open directory \"%s\": %s\n"),
832                                 progname, XLOGDIR, strerror(errno));
833                 exit(1);
834         }
835
836         errno = 0;
837         while ((xlde = readdir(xldir)) != NULL)
838         {
839                 if (strlen(xlde->d_name) == 24 &&
840                         strspn(xlde->d_name, "0123456789ABCDEF") == 24)
841                 {
842                         snprintf(path, MAXPGPATH, "%s/%s", XLOGDIR, xlde->d_name);
843                         if (unlink(path) < 0)
844                         {
845                                 fprintf(stderr, _("%s: could not delete file \"%s\": %s\n"),
846                                                 progname, path, strerror(errno));
847                                 exit(1);
848                         }
849                 }
850                 errno = 0;
851         }
852 #ifdef WIN32
853
854         /*
855          * This fix is in mingw cvs (runtime/mingwex/dirent.c rev 1.4), but not in
856          * released version
857          */
858         if (GetLastError() == ERROR_NO_MORE_FILES)
859                 errno = 0;
860 #endif
861
862         if (errno)
863         {
864                 fprintf(stderr, _("%s: could not read from directory \"%s\": %s\n"),
865                                 progname, XLOGDIR, strerror(errno));
866                 exit(1);
867         }
868         closedir(xldir);
869 }
870
871
872 /*
873  * Remove existing archive status files
874  */
875 static void
876 KillExistingArchiveStatus(void)
877 {
878         DIR                *xldir;
879         struct dirent *xlde;
880         char            path[MAXPGPATH];
881
882 #define ARCHSTATDIR XLOGDIR "/archive_status"
883
884         xldir = opendir(ARCHSTATDIR);
885         if (xldir == NULL)
886         {
887                 fprintf(stderr, _("%s: could not open directory \"%s\": %s\n"),
888                                 progname, ARCHSTATDIR, strerror(errno));
889                 exit(1);
890         }
891
892         errno = 0;
893         while ((xlde = readdir(xldir)) != NULL)
894         {
895                 if (strspn(xlde->d_name, "0123456789ABCDEF") == 24 &&
896                         (strcmp(xlde->d_name + 24, ".ready") == 0 ||
897                          strcmp(xlde->d_name + 24, ".done") == 0))
898                 {
899                         snprintf(path, MAXPGPATH, "%s/%s", ARCHSTATDIR, xlde->d_name);
900                         if (unlink(path) < 0)
901                         {
902                                 fprintf(stderr, _("%s: could not delete file \"%s\": %s\n"),
903                                                 progname, path, strerror(errno));
904                                 exit(1);
905                         }
906                 }
907                 errno = 0;
908         }
909 #ifdef WIN32
910
911         /*
912          * This fix is in mingw cvs (runtime/mingwex/dirent.c rev 1.4), but not in
913          * released version
914          */
915         if (GetLastError() == ERROR_NO_MORE_FILES)
916                 errno = 0;
917 #endif
918
919         if (errno)
920         {
921                 fprintf(stderr, _("%s: could not read from directory \"%s\": %s\n"),
922                                 progname, ARCHSTATDIR, strerror(errno));
923                 exit(1);
924         }
925         closedir(xldir);
926 }
927
928
929 /*
930  * Write an empty XLOG file, containing only the checkpoint record
931  * already set up in ControlFile.
932  */
933 static void
934 WriteEmptyXLOG(void)
935 {
936         char       *buffer;
937         XLogPageHeader page;
938         XLogLongPageHeader longpage;
939         XLogRecord *record;
940         pg_crc32        crc;
941         char            path[MAXPGPATH];
942         int                     fd;
943         int                     nbytes;
944
945         /* Use malloc() to ensure buffer is MAXALIGNED */
946         buffer = (char *) pg_malloc(XLOG_BLCKSZ);
947         page = (XLogPageHeader) buffer;
948         memset(buffer, 0, XLOG_BLCKSZ);
949
950         /* Set up the XLOG page header */
951         page->xlp_magic = XLOG_PAGE_MAGIC;
952         page->xlp_info = XLP_LONG_HEADER;
953         page->xlp_tli = ControlFile.checkPointCopy.ThisTimeLineID;
954         page->xlp_pageaddr = ControlFile.checkPointCopy.redo - SizeOfXLogLongPHD;
955         longpage = (XLogLongPageHeader) page;
956         longpage->xlp_sysid = ControlFile.system_identifier;
957         longpage->xlp_seg_size = XLogSegSize;
958         longpage->xlp_xlog_blcksz = XLOG_BLCKSZ;
959
960         /* Insert the initial checkpoint record */
961         record = (XLogRecord *) ((char *) page + SizeOfXLogLongPHD);
962         record->xl_prev = 0;
963         record->xl_xid = InvalidTransactionId;
964         record->xl_tot_len = SizeOfXLogRecord + sizeof(CheckPoint);
965         record->xl_len = sizeof(CheckPoint);
966         record->xl_info = XLOG_CHECKPOINT_SHUTDOWN;
967         record->xl_rmid = RM_XLOG_ID;
968         memcpy(XLogRecGetData(record), &ControlFile.checkPointCopy,
969                    sizeof(CheckPoint));
970
971         INIT_CRC32(crc);
972         COMP_CRC32(crc, &ControlFile.checkPointCopy, sizeof(CheckPoint));
973         COMP_CRC32(crc, (char *) record, offsetof(XLogRecord, xl_crc));
974         FIN_CRC32(crc);
975         record->xl_crc = crc;
976
977         /* Write the first page */
978         XLogFilePath(path, ControlFile.checkPointCopy.ThisTimeLineID, newXlogSegNo);
979
980         unlink(path);
981
982         fd = open(path, O_RDWR | O_CREAT | O_EXCL | PG_BINARY,
983                           S_IRUSR | S_IWUSR);
984         if (fd < 0)
985         {
986                 fprintf(stderr, _("%s: could not open file \"%s\": %s\n"),
987                                 progname, path, strerror(errno));
988                 exit(1);
989         }
990
991         errno = 0;
992         if (write(fd, buffer, XLOG_BLCKSZ) != XLOG_BLCKSZ)
993         {
994                 /* if write didn't set errno, assume problem is no disk space */
995                 if (errno == 0)
996                         errno = ENOSPC;
997                 fprintf(stderr, _("%s: could not write file \"%s\": %s\n"),
998                                 progname, path, strerror(errno));
999                 exit(1);
1000         }
1001
1002         /* Fill the rest of the file with zeroes */
1003         memset(buffer, 0, XLOG_BLCKSZ);
1004         for (nbytes = XLOG_BLCKSZ; nbytes < XLogSegSize; nbytes += XLOG_BLCKSZ)
1005         {
1006                 errno = 0;
1007                 if (write(fd, buffer, XLOG_BLCKSZ) != XLOG_BLCKSZ)
1008                 {
1009                         if (errno == 0)
1010                                 errno = ENOSPC;
1011                         fprintf(stderr, _("%s: could not write file \"%s\": %s\n"),
1012                                         progname, path, strerror(errno));
1013                         exit(1);
1014                 }
1015         }
1016
1017         if (fsync(fd) != 0)
1018         {
1019                 fprintf(stderr, _("%s: fsync error: %s\n"), progname, strerror(errno));
1020                 exit(1);
1021         }
1022
1023         close(fd);
1024 }
1025
1026
1027 static void
1028 usage(void)
1029 {
1030         printf(_("%s resets the PostgreSQL transaction log.\n\n"), progname);
1031         printf(_("Usage:\n  %s [OPTION]... DATADIR\n\n"), progname);
1032         printf(_("Options:\n"));
1033         printf(_("  -e XIDEPOCH      set next transaction ID epoch\n"));
1034         printf(_("  -f               force update to be done\n"));
1035         printf(_("  -l xlogfile      force minimum WAL starting location for new transaction log\n"));
1036         printf(_("  -m XID,OLDEST    set next multitransaction ID and oldest value\n"));
1037         printf(_("  -n               no update, just show extracted control values (for testing)\n"));
1038         printf(_("  -o OID           set next OID\n"));
1039         printf(_("  -O OFFSET        set next multitransaction offset\n"));
1040         printf(_("  -V, --version    output version information, then exit\n"));
1041         printf(_("  -x XID           set next transaction ID\n"));
1042         printf(_("  -?, --help       show this help, then exit\n"));
1043         printf(_("\nReport bugs to <pgsql-bugs@postgresql.org>.\n"));
1044 }