PostgreSQL Source Code git master
Loading...
Searching...
No Matches
timeline.c
Go to the documentation of this file.
1/*-------------------------------------------------------------------------
2 *
3 * timeline.c
4 * Functions for reading and writing timeline history files.
5 *
6 * A timeline history file lists the timeline changes of the timeline, in
7 * a simple text format. They are archived along with the WAL segments.
8 *
9 * The files are named like "<tli>.history". For example, if the database
10 * starts up and switches to timeline 5, the timeline history file would be
11 * called "00000005.history".
12 *
13 * Each line in the file represents a timeline switch:
14 *
15 * <parentTLI> <switchpoint> <reason>
16 *
17 * parentTLI ID of the parent timeline
18 * switchpoint XLogRecPtr of the WAL location where the switch happened
19 * reason human-readable explanation of why the timeline was changed
20 *
21 * The fields are separated by tabs. Lines beginning with # are comments, and
22 * are ignored. Empty lines are also ignored.
23 *
24 * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
25 * Portions Copyright (c) 1994, Regents of the University of California
26 *
27 * src/backend/access/transam/timeline.c
28 *
29 *-------------------------------------------------------------------------
30 */
31
32#include "postgres.h"
33
34#include <sys/stat.h>
35#include <unistd.h>
36
37#include "access/timeline.h"
38#include "access/xlog.h"
40#include "access/xlogarchive.h"
41#include "access/xlogdefs.h"
42#include "pgstat.h"
43#include "storage/fd.h"
44#include "utils/wait_event.h"
45
46/*
47 * Copies all timeline history files with id's between 'begin' and 'end'
48 * from archive to pg_wal.
49 */
50void
52{
53 char path[MAXPGPATH];
55 TimeLineID tli;
56
57 for (tli = begin; tli < end; tli++)
58 {
59 if (tli == 1)
60 continue;
61
63 if (RestoreArchivedFile(path, histfname, "RECOVERYHISTORY", 0, false))
65 }
66}
67
68/*
69 * Try to read a timeline's history file.
70 *
71 * If successful, return the list of component TLIs (the given TLI followed by
72 * its ancestor TLIs). If we can't find the history file, assume that the
73 * timeline has no parents, and return a list of just the specified timeline
74 * ID.
75 */
76List *
78{
79 List *result;
80 char path[MAXPGPATH];
82 FILE *fd;
86 bool fromArchive = false;
87
88 /* Timeline 1 does not have a history file, so no need to check */
89 if (targetTLI == 1)
90 {
92 entry->tli = targetTLI;
93 entry->begin = entry->end = InvalidXLogRecPtr;
94 return list_make1(entry);
95 }
96
98 {
101 RestoreArchivedFile(path, histfname, "RECOVERYHISTORY", 0, false);
102 }
103 else
105
106 fd = AllocateFile(path, "r");
107 if (fd == NULL)
108 {
109 if (errno != ENOENT)
112 errmsg("could not open file \"%s\": %m", path)));
113 /* Not there, so assume no parents */
115 entry->tli = targetTLI;
116 entry->begin = entry->end = InvalidXLogRecPtr;
117 return list_make1(entry);
118 }
119
120 result = NIL;
121
122 /*
123 * Parse the file...
124 */
126 for (;;)
127 {
128 char fline[MAXPGPATH];
129 char *res;
130 char *ptr;
131 TimeLineID tli;
134 int nfields;
135
137 res = fgets(fline, sizeof(fline), fd);
139 if (res == NULL)
140 {
141 if (ferror(fd))
144 errmsg("could not read file \"%s\": %m", path)));
145
146 break;
147 }
148
149 /* skip leading whitespace and check for # comment */
150 for (ptr = fline; *ptr; ptr++)
151 {
152 if (!isspace((unsigned char) *ptr))
153 break;
154 }
155 if (*ptr == '\0' || *ptr == '#')
156 continue;
157
158 nfields = sscanf(fline, "%u\t%X/%08X", &tli, &switchpoint_hi, &switchpoint_lo);
159
160 if (nfields < 1)
161 {
162 /* expect a numeric timeline ID as first field of line */
164 (errmsg("syntax error in history file: %s", fline),
165 errhint("Expected a numeric timeline ID.")));
166 }
167 if (nfields != 3)
169 (errmsg("syntax error in history file: %s", fline),
170 errhint("Expected a write-ahead log switchpoint location.")));
171
172 if (result && tli <= lasttli)
174 (errmsg("invalid data in history file: %s", fline),
175 errhint("Timeline IDs must be in increasing sequence.")));
176
177 lasttli = tli;
178
180 entry->tli = tli;
181 entry->begin = prevend;
182 entry->end = ((uint64) (switchpoint_hi)) << 32 | (uint64) switchpoint_lo;
183 prevend = entry->end;
184
185 /* Build list with newest item first */
186 result = lcons(entry, result);
187
188 /* we ignore the remainder of each line */
189 }
190
191 FreeFile(fd);
192
193 if (result && targetTLI <= lasttli)
195 (errmsg("invalid data in history file \"%s\"", path),
196 errhint("Timeline IDs must be less than child timeline's ID.")));
197
198 /*
199 * Create one more entry for the "tip" of the timeline, which has no entry
200 * in the history file.
201 */
203 entry->tli = targetTLI;
204 entry->begin = prevend;
205 entry->end = InvalidXLogRecPtr;
206
207 result = lcons(entry, result);
208
209 /*
210 * If the history file was fetched from archive, save it in pg_wal for
211 * future reference.
212 */
213 if (fromArchive)
215
216 return result;
217}
218
219/*
220 * Probe whether a timeline history file exists for the given timeline ID
221 */
222bool
224{
225 char path[MAXPGPATH];
227 FILE *fd;
228
229 /* Timeline 1 does not have a history file, so no need to check */
230 if (probeTLI == 1)
231 return false;
232
234 {
236 RestoreArchivedFile(path, histfname, "RECOVERYHISTORY", 0, false);
237 }
238 else
240
241 fd = AllocateFile(path, "r");
242 if (fd != NULL)
243 {
244 FreeFile(fd);
245 return true;
246 }
247 else
248 {
249 if (errno != ENOENT)
252 errmsg("could not open file \"%s\": %m", path)));
253 return false;
254 }
255}
256
257/*
258 * Find the newest existing timeline, assuming that startTLI exists.
259 *
260 * Note: while this is somewhat heuristic, it does positively guarantee
261 * that (result + 1) is not a known timeline, and therefore it should
262 * be safe to assign that ID to a new timeline.
263 */
266{
269
270 /*
271 * The algorithm is just to probe for the existence of timeline history
272 * files. XXX is it useful to allow gaps in the sequence?
273 */
275
276 for (probeTLI = startTLI + 1;; probeTLI++)
277 {
279 {
280 newestTLI = probeTLI; /* probeTLI exists */
281 }
282 else
283 {
284 /* doesn't exist, assume we're done */
285 break;
286 }
287 }
288
289 return newestTLI;
290}
291
292/*
293 * Create a new timeline history file.
294 *
295 * newTLI: ID of the new timeline
296 * parentTLI: ID of its immediate parent
297 * switchpoint: WAL location where the system switched to the new timeline
298 * reason: human-readable explanation of why the timeline was switched
299 *
300 * Currently this is only used at the end recovery, and so there are no locking
301 * considerations. But we should be just as tense as XLogFileInit to avoid
302 * emplacing a bogus file.
303 */
304void
306 XLogRecPtr switchpoint, char *reason)
307{
308 char path[MAXPGPATH];
309 char tmppath[MAXPGPATH];
311 char buffer[BLCKSZ];
312 int srcfd;
313 int fd;
314 int nbytes;
315
316 Assert(newTLI > parentTLI); /* else bad selection of newTLI */
317
318 /*
319 * Write into a temp file name.
320 */
321 snprintf(tmppath, MAXPGPATH, XLOGDIR "/xlogtemp.%d", (int) getpid());
322
324
325 /* do not use get_sync_bit() here --- want to fsync only at end of fill */
327 if (fd < 0)
330 errmsg("could not create file \"%s\": %m", tmppath)));
331
332 /*
333 * If a history file exists for the parent, copy it verbatim
334 */
336 {
338 RestoreArchivedFile(path, histfname, "RECOVERYHISTORY", 0, false);
339 }
340 else
342
344 if (srcfd < 0)
345 {
346 if (errno != ENOENT)
349 errmsg("could not open file \"%s\": %m", path)));
350 /* Not there, so assume parent has no parents */
351 }
352 else
353 {
354 for (;;)
355 {
356 errno = 0;
358 nbytes = (int) read(srcfd, buffer, sizeof(buffer));
360 if (nbytes < 0 || errno != 0)
363 errmsg("could not read file \"%s\": %m", path)));
364 if (nbytes == 0)
365 break;
366 errno = 0;
368 if ((int) write(fd, buffer, nbytes) != nbytes)
369 {
370 int save_errno = errno;
371
372 /*
373 * If we fail to make the file, delete it to release disk
374 * space
375 */
377
378 /*
379 * if write didn't set errno, assume problem is no disk space
380 */
382
385 errmsg("could not write to file \"%s\": %m", tmppath)));
386 }
388 }
389
390 if (CloseTransientFile(srcfd) != 0)
393 errmsg("could not close file \"%s\": %m", path)));
394 }
395
396 /*
397 * Append one line with the details of this timeline split.
398 *
399 * If we did have a parent file, insert an extra newline just in case the
400 * parent file failed to end with one.
401 */
402 snprintf(buffer, sizeof(buffer),
403 "%s%u\t%X/%08X\t%s\n",
404 (srcfd < 0) ? "" : "\n",
405 parentTLI,
407 reason);
408
409 nbytes = strlen(buffer);
410 errno = 0;
412 if ((int) write(fd, buffer, nbytes) != nbytes)
413 {
414 int save_errno = errno;
415
416 /*
417 * If we fail to make the file, delete it to release disk space
418 */
420 /* if write didn't set errno, assume problem is no disk space */
422
425 errmsg("could not write to file \"%s\": %m", tmppath)));
426 }
428
430 if (pg_fsync(fd) != 0)
433 errmsg("could not fsync file \"%s\": %m", tmppath)));
435
436 if (CloseTransientFile(fd) != 0)
439 errmsg("could not close file \"%s\": %m", tmppath)));
440
441 /*
442 * Now move the completed history file into place with its final name.
443 */
445 Assert(access(path, F_OK) != 0 && errno == ENOENT);
447
448 /* The history file can be archived immediately. */
450 {
453 }
454}
455
456/*
457 * Writes a history file for given timeline and contents.
458 *
459 * Currently this is only used in the walreceiver process, and so there are
460 * no locking considerations. But we should be just as tense as XLogFileInit
461 * to avoid emplacing a bogus file.
462 */
463void
464writeTimeLineHistoryFile(TimeLineID tli, char *content, int size)
465{
466 char path[MAXPGPATH];
467 char tmppath[MAXPGPATH];
468 int fd;
469
470 /*
471 * Write into a temp file name.
472 */
473 snprintf(tmppath, MAXPGPATH, XLOGDIR "/xlogtemp.%d", (int) getpid());
474
476
477 /* do not use get_sync_bit() here --- want to fsync only at end of fill */
479 if (fd < 0)
482 errmsg("could not create file \"%s\": %m", tmppath)));
483
484 errno = 0;
486 if ((int) write(fd, content, size) != size)
487 {
488 int save_errno = errno;
489
490 /*
491 * If we fail to make the file, delete it to release disk space
492 */
494 /* if write didn't set errno, assume problem is no disk space */
496
499 errmsg("could not write to file \"%s\": %m", tmppath)));
500 }
502
504 if (pg_fsync(fd) != 0)
507 errmsg("could not fsync file \"%s\": %m", tmppath)));
509
510 if (CloseTransientFile(fd) != 0)
513 errmsg("could not close file \"%s\": %m", tmppath)));
514
515 /*
516 * Now move the completed history file into place with its final name,
517 * replacing any existing file with the same name.
518 */
519 TLHistoryFilePath(path, tli);
521}
522
523/*
524 * Returns true if 'expectedTLEs' contains a timeline with id 'tli'
525 */
526bool
528{
529 ListCell *cell;
530
531 foreach(cell, expectedTLEs)
532 {
533 if (((TimeLineHistoryEntry *) lfirst(cell))->tli == tli)
534 return true;
535 }
536
537 return false;
538}
539
540/*
541 * Returns the ID of the timeline in use at a particular point in time, in
542 * the given timeline history.
543 */
546{
547 ListCell *cell;
548
549 foreach(cell, history)
550 {
552
553 if ((!XLogRecPtrIsValid(tle->begin) || tle->begin <= ptr) &&
554 (!XLogRecPtrIsValid(tle->end) || ptr < tle->end))
555 {
556 /* found it */
557 return tle->tli;
558 }
559 }
560
561 /* shouldn't happen. */
562 elog(ERROR, "timeline history was not contiguous");
563 return 0; /* keep compiler quiet */
564}
565
566/*
567 * Returns the point in history where we branched off the given timeline,
568 * and the timeline we branched to (*nextTLI). Returns InvalidXLogRecPtr if
569 * the timeline is current, ie. we have not branched off from it, and throws
570 * an error if the timeline is not part of this server's history.
571 */
574{
575 ListCell *cell;
576
577 if (nextTLI)
578 *nextTLI = 0;
579 foreach(cell, history)
580 {
582
583 if (tle->tli == tli)
584 return tle->end;
585 if (nextTLI)
586 *nextTLI = tle->tli;
587 }
588
590 (errmsg("requested timeline %u is not in this server's history",
591 tli)));
592 return InvalidXLogRecPtr; /* keep compiler quiet */
593}
List * readTimeLineHistory(TimeLineID targetTLI)
Definition timeline.c:77
TimeLineID findNewestTimeLine(TimeLineID startTLI)
Definition timeline.c:265
void writeTimeLineHistoryFile(TimeLineID tli, char *content, int size)
Definition timeline.c:464
TimeLineID tliOfPointInHistory(XLogRecPtr ptr, List *history)
Definition timeline.c:545
XLogRecPtr tliSwitchPoint(TimeLineID tli, List *history, TimeLineID *nextTLI)
Definition timeline.c:573
bool existsTimeLineHistory(TimeLineID probeTLI)
Definition timeline.c:223
void restoreTimeLineHistoryFiles(TimeLineID begin, TimeLineID end)
Definition timeline.c:51
void writeTimeLineHistory(TimeLineID newTLI, TimeLineID parentTLI, XLogRecPtr switchpoint, char *reason)
Definition timeline.c:305
bool tliInHistory(TimeLineID tli, List *expectedTLEs)
Definition timeline.c:527
#define Assert(condition)
Definition c.h:945
uint64_t uint64
Definition c.h:619
uint32_t uint32
Definition c.h:618
int errcode_for_file_access(void)
Definition elog.c:897
int errhint(const char *fmt,...) pg_attribute_printf(1
#define FATAL
Definition elog.h:41
#define ERROR
Definition elog.h:39
#define elog(elevel,...)
Definition elog.h:226
#define ereport(elevel,...)
Definition elog.h:150
int durable_rename(const char *oldfile, const char *newfile, int elevel)
Definition fd.c:783
int CloseTransientFile(int fd)
Definition fd.c:2855
int FreeFile(FILE *file)
Definition fd.c:2827
int data_sync_elevel(int elevel)
Definition fd.c:3986
int pg_fsync(int fd)
Definition fd.c:390
FILE * AllocateFile(const char *name, const char *mode)
Definition fd.c:2628
int OpenTransientFile(const char *fileName, int fileFlags)
Definition fd.c:2678
#define palloc_object(type)
Definition fe_memutils.h:74
#define write(a, b, c)
Definition win32.h:14
#define read(a, b, c)
Definition win32.h:13
List * lcons(void *datum, List *list)
Definition list.c:495
static char * errmsg
#define MAXPGPATH
#define lfirst(lc)
Definition pg_list.h:172
#define NIL
Definition pg_list.h:68
#define list_make1(x1)
Definition pg_list.h:212
#define snprintf
Definition port.h:260
static int fd(const char *x, int i)
static int fb(int x)
short access
Definition pg_list.h:54
XLogRecPtr begin
Definition timeline.h:28
static void pgstat_report_wait_start(uint32 wait_event_info)
Definition wait_event.h:69
static void pgstat_report_wait_end(void)
Definition wait_event.h:85
#define XLogArchivingActive()
Definition xlog.h:101
#define MAXFNAMELEN
#define XLOGDIR
static void TLHistoryFilePath(char *path, TimeLineID tli)
static void TLHistoryFileName(char *fname, TimeLineID tli)
bool RestoreArchivedFile(char *path, const char *xlogfname, const char *recovername, off_t expectedSize, bool cleanupEnabled)
Definition xlogarchive.c:55
void XLogArchiveNotify(const char *xlog)
void KeepFileRestoredFromArchive(const char *path, const char *xlogfname)
#define XLogRecPtrIsValid(r)
Definition xlogdefs.h:29
#define LSN_FORMAT_ARGS(lsn)
Definition xlogdefs.h:47
uint64 XLogRecPtr
Definition xlogdefs.h:21
#define InvalidXLogRecPtr
Definition xlogdefs.h:28
uint32 TimeLineID
Definition xlogdefs.h:63
bool ArchiveRecoveryRequested
static List * expectedTLEs