-
Notifications
You must be signed in to change notification settings - Fork 86
/
Copy pathrestore.c
2239 lines (1899 loc) · 66.5 KB
/
restore.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*-------------------------------------------------------------------------
*
* restore.c: restore DB cluster and archived WAL.
*
* Portions Copyright (c) 2009-2013, NIPPON TELEGRAPH AND TELEPHONE CORPORATION
* Portions Copyright (c) 2015-2019, Postgres Professional
*
*-------------------------------------------------------------------------
*/
#include "pg_probackup.h"
#include "access/timeline.h"
#include <sys/stat.h>
#include <unistd.h>
#include "utils/thread.h"
typedef struct
{
parray *pgdata_files;
parray *dest_files;
pgBackup *dest_backup;
parray *dest_external_dirs;
parray *parent_chain;
parray *dbOid_exclude_list;
bool skip_external_dirs;
const char *to_root;
size_t restored_bytes;
bool use_bitmap;
IncrRestoreMode incremental_mode;
XLogRecPtr shift_lsn; /* used only in LSN incremental_mode */
/*
* Return value from the thread.
* 0 means there is no error, 1 - there is an error.
*/
int ret;
} restore_files_arg;
static void
print_recovery_settings(InstanceState *instanceState, FILE *fp, pgBackup *backup,
pgRestoreParams *params, pgRecoveryTarget *rt);
static void
print_standby_settings_common(FILE *fp, pgBackup *backup, pgRestoreParams *params);
#if PG_VERSION_NUM >= 120000
static void
update_recovery_options(InstanceState *instanceState, pgBackup *backup,
pgRestoreParams *params, pgRecoveryTarget *rt);
#else
static void
update_recovery_options_before_v12(InstanceState *instanceState, pgBackup *backup,
pgRestoreParams *params, pgRecoveryTarget *rt);
#endif
static void create_recovery_conf(InstanceState *instanceState, time_t backup_id,
pgRecoveryTarget *rt,
pgBackup *backup,
pgRestoreParams *params);
static void *restore_files(void *arg);
static void set_orphan_status(parray *backups, pgBackup *parent_backup);
static void restore_chain(pgBackup *dest_backup, parray *parent_chain,
parray *dbOid_exclude_list, pgRestoreParams *params,
const char *pgdata_path, bool no_sync, bool cleanup_pgdata,
bool backup_has_tblspc);
/*
* Iterate over backup list to find all ancestors of the broken parent_backup
* and update their status to BACKUP_STATUS_ORPHAN
*/
static void
set_orphan_status(parray *backups, pgBackup *parent_backup)
{
/* chain is intact, but at least one parent is invalid */
char *parent_backup_id;
int j;
/* parent_backup_id is a human-readable backup ID */
parent_backup_id = base36enc_dup(parent_backup->start_time);
for (j = 0; j < parray_num(backups); j++)
{
pgBackup *backup = (pgBackup *) parray_get(backups, j);
if (is_parent(parent_backup->start_time, backup, false))
{
if (backup->status == BACKUP_STATUS_OK ||
backup->status == BACKUP_STATUS_DONE)
{
write_backup_status(backup, BACKUP_STATUS_ORPHAN, true);
elog(WARNING,
"Backup %s is orphaned because his parent %s has status: %s",
base36enc(backup->start_time),
parent_backup_id,
status2str(parent_backup->status));
}
else
{
elog(WARNING, "Backup %s has parent %s with status: %s",
base36enc(backup->start_time), parent_backup_id,
status2str(parent_backup->status));
}
}
}
pg_free(parent_backup_id);
}
/*
* Entry point of pg_probackup RESTORE and VALIDATE subcommands.
*/
int
do_restore_or_validate(InstanceState *instanceState, time_t target_backup_id, pgRecoveryTarget *rt,
pgRestoreParams *params, bool no_sync)
{
int i = 0;
int j = 0;
parray *backups = NULL;
pgBackup *tmp_backup = NULL;
pgBackup *current_backup = NULL;
pgBackup *dest_backup = NULL;
pgBackup *base_full_backup = NULL;
pgBackup *corrupted_backup = NULL;
char *action = params->is_restore ? "Restore":"Validate";
parray *parent_chain = NULL;
parray *dbOid_exclude_list = NULL;
bool pgdata_is_empty = true;
bool cleanup_pgdata = false;
bool backup_has_tblspc = true; /* backup contain tablespace */
XLogRecPtr shift_lsn = InvalidXLogRecPtr;
if (instanceState == NULL)
elog(ERROR, "required parameter not specified: --instance");
if (params->is_restore)
{
if (instance_config.pgdata == NULL)
elog(ERROR,
"required parameter not specified: PGDATA (-D, --pgdata)");
/* Check if restore destination empty */
if (!dir_is_empty(instance_config.pgdata, FIO_DB_HOST))
{
/* if destination directory is empty, then incremental restore may be disabled */
pgdata_is_empty = false;
/* Check that remote system is NOT running and systemd id is the same as ours */
if (params->incremental_mode != INCR_NONE)
{
DestDirIncrCompatibility rc;
bool ok_to_go = true;
elog(INFO, "Running incremental restore into nonempty directory: \"%s\"",
instance_config.pgdata);
rc = check_incremental_compatibility(instance_config.pgdata,
instance_config.system_identifier,
params->incremental_mode);
if (rc == POSTMASTER_IS_RUNNING)
{
/* Even with force flag it is unwise to run
* incremental restore over running instance
*/
ok_to_go = false;
}
else if (rc == SYSTEM_ID_MISMATCH)
{
/*
* In force mode it is possible to ignore system id mismatch
* by just wiping clean the destination directory.
*/
if (params->incremental_mode != INCR_NONE && params->force)
cleanup_pgdata = true;
else
ok_to_go = false;
}
else if (rc == BACKUP_LABEL_EXISTS)
{
/*
* A big no-no for lsn-based incremental restore
* If there is backup label in PGDATA, then this cluster was probably
* restored from backup, but not started yet. Which means that values
* in pg_control are not synchronized with PGDATA and so we cannot use
* incremental restore in LSN mode, because it is relying on pg_control
* to calculate switchpoint.
*/
if (params->incremental_mode == INCR_LSN)
ok_to_go = false;
}
else if (rc == DEST_IS_NOT_OK)
{
/*
* Something else is wrong. For example, postmaster.pid is mangled,
* so we cannot be sure that postmaster is running or not.
* It is better to just error out.
*/
ok_to_go = false;
}
if (!ok_to_go)
elog(ERROR, "Incremental restore is not allowed");
}
else
elog(ERROR, "Restore destination is not empty: \"%s\"",
instance_config.pgdata);
}
}
elog(LOG, "%s begin.", action);
/* Get list of all backups sorted in order of descending start time */
backups = catalog_get_backup_list(instanceState, INVALID_BACKUP_ID);
/* Find backup range we should restore or validate. */
while ((i < parray_num(backups)) && !dest_backup)
{
current_backup = (pgBackup *) parray_get(backups, i);
i++;
/* Skip all backups which started after target backup */
if (target_backup_id && current_backup->start_time > target_backup_id)
continue;
/*
* [PGPRO-1164] If BACKUP_ID is not provided for restore command,
* we must find the first valid(!) backup.
* If target_backup_id is not provided, we can be sure that
* PITR for restore or validate is requested.
* So we can assume that user is more interested in recovery to specific point
* in time and NOT interested in revalidation of invalid backups.
* So based on that assumptions we should choose only OK and DONE backups
* as candidates for validate and restore.
*/
if (target_backup_id == INVALID_BACKUP_ID &&
(current_backup->status != BACKUP_STATUS_OK &&
current_backup->status != BACKUP_STATUS_DONE))
{
elog(WARNING, "Skipping backup %s, because it has non-valid status: %s",
base36enc(current_backup->start_time), status2str(current_backup->status));
continue;
}
/*
* We found target backup. Check its status and
* ensure that it satisfies recovery target.
*/
if ((target_backup_id == current_backup->start_time
|| target_backup_id == INVALID_BACKUP_ID))
{
/* backup is not ok,
* but in case of CORRUPT or ORPHAN revalidation is possible
* unless --no-validate is used,
* in other cases throw an error.
*/
// 1. validate
// 2. validate -i INVALID_ID <- allowed revalidate
// 3. restore -i INVALID_ID <- allowed revalidate and restore
// 4. restore <- impossible
// 5. restore --no-validate <- forbidden
if (current_backup->status != BACKUP_STATUS_OK &&
current_backup->status != BACKUP_STATUS_DONE)
{
if ((current_backup->status == BACKUP_STATUS_ORPHAN ||
current_backup->status == BACKUP_STATUS_CORRUPT ||
current_backup->status == BACKUP_STATUS_RUNNING)
&& (!params->no_validate || params->force))
elog(WARNING, "Backup %s has status: %s",
base36enc(current_backup->start_time), status2str(current_backup->status));
else
elog(ERROR, "Backup %s has status: %s",
base36enc(current_backup->start_time), status2str(current_backup->status));
}
if (rt->target_tli)
{
parray *timelines;
// elog(LOG, "target timeline ID = %u", rt->target_tli);
/* Read timeline history files from archives */
timelines = read_timeline_history(instanceState->instance_wal_subdir_path,
rt->target_tli, true);
if (!timelines)
elog(ERROR, "Failed to get history file for target timeline %i", rt->target_tli);
if (!satisfy_timeline(timelines, current_backup->tli, current_backup->stop_lsn))
{
if (target_backup_id != INVALID_BACKUP_ID)
elog(ERROR, "target backup %s does not satisfy target timeline",
base36enc(target_backup_id));
else
/* Try to find another backup that satisfies target timeline */
continue;
}
parray_walk(timelines, pfree);
parray_free(timelines);
}
if (!satisfy_recovery_target(current_backup, rt))
{
if (target_backup_id != INVALID_BACKUP_ID)
elog(ERROR, "Requested backup %s does not satisfy restore options",
base36enc(target_backup_id));
else
/* Try to find another backup that satisfies target options */
continue;
}
/*
* Backup is fine and satisfies all recovery options.
* Save it as dest_backup
*/
dest_backup = current_backup;
}
}
/* TODO: Show latest possible target */
if (dest_backup == NULL)
{
/* Failed to find target backup */
if (target_backup_id)
elog(ERROR, "Requested backup %s is not found.", base36enc(target_backup_id));
else
elog(ERROR, "Backup satisfying target options is not found.");
/* TODO: check if user asked PITR or just restore of latest backup */
}
/* If we already found dest_backup, look for full backup. */
if (dest_backup->backup_mode == BACKUP_MODE_FULL)
base_full_backup = dest_backup;
else
{
int result;
result = scan_parent_chain(dest_backup, &tmp_backup);
if (result == ChainIsBroken)
{
/* chain is broken, determine missing backup ID
* and orphinize all his descendants
*/
char *missing_backup_id;
time_t missing_backup_start_time;
missing_backup_start_time = tmp_backup->parent_backup;
missing_backup_id = base36enc_dup(tmp_backup->parent_backup);
for (j = 0; j < parray_num(backups); j++)
{
pgBackup *backup = (pgBackup *) parray_get(backups, j);
/* use parent backup start_time because he is missing
* and we must orphinize his descendants
*/
if (is_parent(missing_backup_start_time, backup, false))
{
if (backup->status == BACKUP_STATUS_OK ||
backup->status == BACKUP_STATUS_DONE)
{
write_backup_status(backup, BACKUP_STATUS_ORPHAN, true);
elog(WARNING, "Backup %s is orphaned because his parent %s is missing",
base36enc(backup->start_time), missing_backup_id);
}
else
{
elog(WARNING, "Backup %s has missing parent %s",
base36enc(backup->start_time), missing_backup_id);
}
}
}
pg_free(missing_backup_id);
/* No point in doing futher */
elog(ERROR, "%s of backup %s failed.", action, base36enc(dest_backup->start_time));
}
else if (result == ChainIsInvalid)
{
/* chain is intact, but at least one parent is invalid */
set_orphan_status(backups, tmp_backup);
tmp_backup = find_parent_full_backup(dest_backup);
/* sanity */
if (!tmp_backup)
elog(ERROR, "Parent full backup for the given backup %s was not found",
base36enc(dest_backup->start_time));
}
/* We have found full backup */
base_full_backup = tmp_backup;
}
if (base_full_backup == NULL)
elog(ERROR, "Full backup satisfying target options is not found.");
/*
* Ensure that directories provided in tablespace mapping are valid
* i.e. empty or not exist.
*/
if (params->is_restore)
{
int rc = check_tablespace_mapping(dest_backup,
params->incremental_mode != INCR_NONE, params->force,
pgdata_is_empty, params->no_validate);
/* backup contain no tablespaces */
if (rc == NoTblspc)
backup_has_tblspc = false;
if (params->incremental_mode != INCR_NONE && !cleanup_pgdata && pgdata_is_empty && (rc != NotEmptyTblspc))
{
elog(INFO, "Destination directory and tablespace directories are empty, "
"disable incremental restore");
params->incremental_mode = INCR_NONE;
}
/* no point in checking external directories if their restore is not requested */
//TODO:
// - make check_external_dir_mapping more like check_tablespace_mapping
// - honor force flag in case of incremental restore just like check_tablespace_mapping
if (!params->skip_external_dirs)
check_external_dir_mapping(dest_backup, params->incremental_mode != INCR_NONE);
}
/* At this point we are sure that parent chain is whole
* so we can build separate array, containing all needed backups,
* to simplify validation and restore
*/
parent_chain = parray_new();
/* Take every backup that is a child of base_backup AND parent of dest_backup
* including base_backup and dest_backup
*/
tmp_backup = dest_backup;
while (tmp_backup)
{
parray_append(parent_chain, tmp_backup);
tmp_backup = tmp_backup->parent_backup_link;
}
/*
* Determine the shift-LSN
* Consider the example A:
*
*
* /----D----------F->
* -A--B---C---*-------X----->
*
* [A,F] - incremental chain
* X - the state of pgdata
* F - destination backup
* * - switch point
*
* When running incremental restore in 'lsn' mode, we get a bitmap of pages,
* whose LSN is less than shift-LSN (backup C stop_lsn).
* So when restoring file, we can skip restore of pages coming from
* A, B and C.
* Pages from D and F cannot be skipped due to incremental restore.
*
* Consider the example B:
*
*
* /----------X---->
* ----*---A---B---C-->
*
* [A,C] - incremental chain
* X - the state of pgdata
* C - destination backup
* * - switch point
*
* Incremental restore in shift mode IS NOT POSSIBLE in this case.
* We must be able to differentiate the scenario A and scenario B.
*
*/
if (params->is_restore && params->incremental_mode == INCR_LSN)
{
RedoParams redo;
parray *timelines = NULL;
get_redo(instance_config.pgdata, FIO_DB_HOST, &redo);
if (redo.checksum_version == 0)
elog(ERROR, "Incremental restore in 'lsn' mode require "
"data_checksums to be enabled in destination data directory");
timelines = read_timeline_history(instanceState->instance_wal_subdir_path,
redo.tli, false);
if (!timelines)
elog(WARNING, "Failed to get history for redo timeline %i, "
"multi-timeline incremental restore in 'lsn' mode is impossible", redo.tli);
tmp_backup = dest_backup;
while (tmp_backup)
{
/* Candidate, whose stop_lsn if less than shift LSN, is found */
if (tmp_backup->stop_lsn < redo.lsn)
{
/* if candidate timeline is the same as redo TLI,
* then we are good to go.
*/
if (redo.tli == tmp_backup->tli)
{
elog(INFO, "Backup %s is chosen as shiftpoint, its Stop LSN will be used as shift LSN",
base36enc(tmp_backup->start_time));
shift_lsn = tmp_backup->stop_lsn;
break;
}
if (!timelines)
{
elog(WARNING, "Redo timeline %i differs from target timeline %i, "
"in this case, to safely run incremental restore in 'lsn' mode, "
"the history file for timeline %i is mandatory",
redo.tli, tmp_backup->tli, redo.tli);
break;
}
/* check whether the candidate tli is a part of redo TLI history */
if (tliIsPartOfHistory(timelines, tmp_backup->tli))
{
shift_lsn = tmp_backup->stop_lsn;
break;
}
else
elog(INFO, "Backup %s cannot be a shiftpoint, "
"because its tli %i is not in history of redo timeline %i",
base36enc(tmp_backup->start_time), tmp_backup->tli, redo.tli);
}
tmp_backup = tmp_backup->parent_backup_link;
}
if (XLogRecPtrIsInvalid(shift_lsn))
elog(ERROR, "Cannot perform incremental restore of backup chain %s in 'lsn' mode, "
"because destination directory redo point %X/%X on tli %i is out of reach",
base36enc(dest_backup->start_time),
(uint32) (redo.lsn >> 32), (uint32) redo.lsn, redo.tli);
else
elog(INFO, "Destination directory redo point %X/%X on tli %i is "
"within reach of backup %s with Stop LSN %X/%X on tli %i",
(uint32) (redo.lsn >> 32), (uint32) redo.lsn, redo.tli,
base36enc(tmp_backup->start_time),
(uint32) (tmp_backup->stop_lsn >> 32), (uint32) tmp_backup->stop_lsn,
tmp_backup->tli);
elog(INFO, "shift LSN: %X/%X",
(uint32) (shift_lsn >> 32), (uint32) shift_lsn);
}
params->shift_lsn = shift_lsn;
/* for validation or restore with enabled validation */
if (!params->is_restore || !params->no_validate)
{
if (dest_backup->backup_mode != BACKUP_MODE_FULL)
elog(INFO, "Validating parents for backup %s", base36enc(dest_backup->start_time));
/*
* Validate backups from base_full_backup to dest_backup.
*/
for (i = parray_num(parent_chain) - 1; i >= 0; i--)
{
tmp_backup = (pgBackup *) parray_get(parent_chain, i);
/* lock every backup in chain in read-only mode */
if (!lock_backup(tmp_backup, true, false))
{
elog(ERROR, "Cannot lock backup %s directory",
base36enc(tmp_backup->start_time));
}
/* validate datafiles only */
pgBackupValidate(tmp_backup, params);
/* After pgBackupValidate() only following backup
* states are possible: ERROR, RUNNING, CORRUPT and OK.
* Validate WAL only for OK, because there is no point
* in WAL validation for corrupted, errored or running backups.
*/
if (tmp_backup->status != BACKUP_STATUS_OK)
{
corrupted_backup = tmp_backup;
break;
}
/* We do not validate WAL files of intermediate backups
* It`s done to speed up restore
*/
}
/* There is no point in wal validation of corrupted backups */
// TODO: there should be a way for a user to request only(!) WAL validation
if (!corrupted_backup)
{
/*
* Validate corresponding WAL files.
* We pass base_full_backup timeline as last argument to this function,
* because it's needed to form the name of xlog file.
*/
validate_wal(dest_backup, instanceState->instance_wal_subdir_path, rt->target_time,
rt->target_xid, rt->target_lsn,
dest_backup->tli, instance_config.xlog_seg_size);
}
/* Orphanize every OK descendant of corrupted backup */
else
set_orphan_status(backups, corrupted_backup);
}
/*
* If dest backup is corrupted or was orphaned in previous check
* produce corresponding error message
*/
if (dest_backup->status == BACKUP_STATUS_OK ||
dest_backup->status == BACKUP_STATUS_DONE)
{
if (params->no_validate)
elog(WARNING, "Backup %s is used without validation.", base36enc(dest_backup->start_time));
else
elog(INFO, "Backup %s is valid.", base36enc(dest_backup->start_time));
}
else if (dest_backup->status == BACKUP_STATUS_CORRUPT)
{
if (params->force)
elog(WARNING, "Backup %s is corrupt.", base36enc(dest_backup->start_time));
else
elog(ERROR, "Backup %s is corrupt.", base36enc(dest_backup->start_time));
}
else if (dest_backup->status == BACKUP_STATUS_ORPHAN)
{
if (params->force)
elog(WARNING, "Backup %s is orphan.", base36enc(dest_backup->start_time));
else
elog(ERROR, "Backup %s is orphan.", base36enc(dest_backup->start_time));
}
else
elog(ERROR, "Backup %s has status: %s",
base36enc(dest_backup->start_time), status2str(dest_backup->status));
/* We ensured that all backups are valid, now restore if required
*/
if (params->is_restore)
{
/*
* Get a list of dbOids to skip if user requested the partial restore.
* It is important that we do this after(!) validation so
* database_map can be trusted.
* NOTE: database_map could be missing for legal reasons, e.g. missing
* permissions on pg_database during `backup` and, as long as user
* do not request partial restore, it`s OK.
*
* If partial restore is requested and database map doesn't exist,
* throw an error.
*/
if (params->partial_db_list)
dbOid_exclude_list = get_dbOid_exclude_list(dest_backup, params->partial_db_list,
params->partial_restore_type);
if (rt->lsn_string &&
parse_server_version(dest_backup->server_version) < 100000)
elog(ERROR, "Backup %s was created for version %s which doesn't support recovery_target_lsn",
base36enc(dest_backup->start_time),
dest_backup->server_version);
restore_chain(dest_backup, parent_chain, dbOid_exclude_list, params,
instance_config.pgdata, no_sync, cleanup_pgdata, backup_has_tblspc);
//TODO rename and update comment
/* Create recovery.conf with given recovery target parameters */
create_recovery_conf(instanceState, target_backup_id, rt, dest_backup, params);
}
/* ssh connection to longer needed */
fio_disconnect();
elog(INFO, "%s of backup %s completed.",
action, base36enc(dest_backup->start_time));
/* cleanup */
parray_walk(backups, pgBackupFree);
parray_free(backups);
parray_free(parent_chain);
return 0;
}
/*
* Restore backup chain.
* Flag 'cleanup_pgdata' demands the removing of already existing content in PGDATA.
*/
void
restore_chain(pgBackup *dest_backup, parray *parent_chain,
parray *dbOid_exclude_list, pgRestoreParams *params,
const char *pgdata_path, bool no_sync, bool cleanup_pgdata,
bool backup_has_tblspc)
{
int i;
char timestamp[100];
parray *pgdata_files = NULL;
parray *dest_files = NULL;
parray *external_dirs = NULL;
/* arrays with meta info for multi threaded backup */
pthread_t *threads;
restore_files_arg *threads_args;
bool restore_isok = true;
bool use_bitmap = true;
/* fancy reporting */
char pretty_dest_bytes[20];
char pretty_total_bytes[20];
size_t dest_bytes = 0;
size_t total_bytes = 0;
char pretty_time[20];
time_t start_time, end_time;
/* Preparations for actual restoring */
time2iso(timestamp, lengthof(timestamp), dest_backup->start_time, false);
elog(INFO, "Restoring the database from backup at %s", timestamp);
dest_files = get_backup_filelist(dest_backup, true);
/* Lock backup chain and make sanity checks */
for (i = parray_num(parent_chain) - 1; i >= 0; i--)
{
pgBackup *backup = (pgBackup *) parray_get(parent_chain, i);
if (!lock_backup(backup, true, false))
elog(ERROR, "Cannot lock backup %s", base36enc(backup->start_time));
if (backup->status != BACKUP_STATUS_OK &&
backup->status != BACKUP_STATUS_DONE)
{
if (params->force)
elog(WARNING, "Backup %s is not valid, restore is forced",
base36enc(backup->start_time));
else
elog(ERROR, "Backup %s cannot be restored because it is not valid",
base36enc(backup->start_time));
}
/* confirm block size compatibility */
if (backup->block_size != BLCKSZ)
elog(ERROR,
"BLCKSZ(%d) is not compatible(%d expected)",
backup->block_size, BLCKSZ);
if (backup->wal_block_size != XLOG_BLCKSZ)
elog(ERROR,
"XLOG_BLCKSZ(%d) is not compatible(%d expected)",
backup->wal_block_size, XLOG_BLCKSZ);
/* populate backup filelist */
if (backup->start_time != dest_backup->start_time)
backup->files = get_backup_filelist(backup, true);
else
backup->files = dest_files;
/*
* this sorting is important, because we rely on it to find
* destination file in intermediate backups file lists
* using bsearch.
*/
parray_qsort(backup->files, pgFileCompareRelPathWithExternal);
}
/* If dest backup version is older than 2.4.0, then bitmap optimization
* is impossible to use, because bitmap restore rely on pgFile.n_blocks,
* which is not always available in old backups.
*/
if (parse_program_version(dest_backup->program_version) < 20400)
{
use_bitmap = false;
if (params->incremental_mode != INCR_NONE)
elog(ERROR, "incremental restore is not possible for backups older than 2.3.0 version");
}
/* There is no point in bitmap restore, when restoring a single FULL backup,
* unless we are running incremental-lsn restore, then bitmap is mandatory.
*/
if (use_bitmap && parray_num(parent_chain) == 1)
{
if (params->incremental_mode == INCR_NONE)
use_bitmap = false;
else
use_bitmap = true;
}
/*
* Restore dest_backup internal directories.
*/
create_data_directories(dest_files, instance_config.pgdata,
dest_backup->root_dir, backup_has_tblspc,
params->incremental_mode != INCR_NONE,
FIO_DB_HOST);
/*
* Restore dest_backup external directories.
*/
if (dest_backup->external_dir_str && !params->skip_external_dirs)
{
external_dirs = make_external_directory_list(dest_backup->external_dir_str, true);
if (!external_dirs)
elog(ERROR, "Failed to get a list of external directories");
if (parray_num(external_dirs) > 0)
elog(LOG, "Restore external directories");
for (i = 0; i < parray_num(external_dirs); i++)
fio_mkdir(parray_get(external_dirs, i),
DIR_PERMISSION, FIO_DB_HOST);
}
/*
* Setup directory structure for external directories
*/
for (i = 0; i < parray_num(dest_files); i++)
{
pgFile *file = (pgFile *) parray_get(dest_files, i);
if (S_ISDIR(file->mode))
total_bytes += 4096;
if (!params->skip_external_dirs &&
file->external_dir_num && S_ISDIR(file->mode))
{
char *external_path;
char dirpath[MAXPGPATH];
if (parray_num(external_dirs) < file->external_dir_num - 1)
elog(ERROR, "Inconsistent external directory backup metadata");
external_path = parray_get(external_dirs, file->external_dir_num - 1);
join_path_components(dirpath, external_path, file->rel_path);
elog(VERBOSE, "Create external directory \"%s\"", dirpath);
fio_mkdir(dirpath, file->mode, FIO_DB_HOST);
}
}
/* setup threads */
pfilearray_clear_locks(dest_files);
/* Get list of files in destination directory and remove redundant files */
if (params->incremental_mode != INCR_NONE || cleanup_pgdata)
{
pgdata_files = parray_new();
elog(INFO, "Extracting the content of destination directory for incremental restore");
time(&start_time);
fio_list_dir(pgdata_files, pgdata_path, false, true, false, false, true, 0);
/*
* TODO:
* 1. Currently we are cleaning the tablespaces in check_tablespace_mapping and PGDATA here.
* It would be great to do all this work in one place.
*
* 2. In case of tablespace remapping we do not cleanup the old tablespace path,
* it is just left as it is.
* Lookup tests.incr_restore.IncrRestoreTest.test_incr_restore_with_tablespace_5
*/
/* get external dirs content */
if (external_dirs)
{
for (i = 0; i < parray_num(external_dirs); i++)
{
char *external_path = parray_get(external_dirs, i);
parray *external_files = parray_new();
fio_list_dir(external_files, external_path,
false, true, false, false, true, i+1);
parray_concat(pgdata_files, external_files);
parray_free(external_files);
}
}
parray_qsort(pgdata_files, pgFileCompareRelPathWithExternalDesc);
time(&end_time);
pretty_time_interval(difftime(end_time, start_time),
pretty_time, lengthof(pretty_time));
elog(INFO, "Destination directory content extracted, time elapsed: %s",
pretty_time);
elog(INFO, "Removing redundant files in destination directory");
time(&start_time);
for (i = 0; i < parray_num(pgdata_files); i++)
{
bool redundant = true;
pgFile *file = (pgFile *) parray_get(pgdata_files, i);
if (parray_bsearch(dest_backup->files, file, pgFileCompareRelPathWithExternal))
redundant = false;
/* pg_filenode.map are always restored, because it's crc cannot be trusted */
if (file->external_dir_num == 0 &&
pg_strcasecmp(file->name, RELMAPPER_FILENAME) == 0)
redundant = true;
/* do not delete the useful internal directories */
if (S_ISDIR(file->mode) && !redundant)
continue;
/* if file does not exists in destination list, then we can safely unlink it */
if (cleanup_pgdata || redundant)
{
char fullpath[MAXPGPATH];
join_path_components(fullpath, pgdata_path, file->rel_path);
fio_delete(file->mode, fullpath, FIO_DB_HOST);
elog(VERBOSE, "Deleted file \"%s\"", fullpath);
/* shrink pgdata list */
pgFileFree(file);
parray_remove(pgdata_files, i);
i--;
}
}
if (cleanup_pgdata)
{
/* Destination PGDATA and tablespaces were cleaned up, so it's the regular restore from this point */
params->incremental_mode = INCR_NONE;
parray_free(pgdata_files);
pgdata_files = NULL;
}
time(&end_time);
pretty_time_interval(difftime(end_time, start_time),
pretty_time, lengthof(pretty_time));
/* At this point PDATA do not contain files, that do not exists in dest backup file list */
elog(INFO, "Redundant files are removed, time elapsed: %s", pretty_time);
}
/*
* Close ssh connection belonging to the main thread
* to avoid the possibility of been killed for idleness
*/
fio_disconnect();
threads = (pthread_t *) palloc(sizeof(pthread_t) * num_threads);
threads_args = (restore_files_arg *) palloc(sizeof(restore_files_arg) *
num_threads);
if (dest_backup->stream)
dest_bytes = dest_backup->pgdata_bytes + dest_backup->wal_bytes;
else
dest_bytes = dest_backup->pgdata_bytes;
pretty_size(dest_bytes, pretty_dest_bytes, lengthof(pretty_dest_bytes));
elog(INFO, "Start restoring backup files. PGDATA size: %s", pretty_dest_bytes);
time(&start_time);
thread_interrupted = false;
/* Restore files into target directory */
for (i = 0; i < num_threads; i++)
{
restore_files_arg *arg = &(threads_args[i]);
arg->dest_files = dest_files;
arg->pgdata_files = pgdata_files;
arg->dest_backup = dest_backup;
arg->dest_external_dirs = external_dirs;
arg->parent_chain = parent_chain;
arg->dbOid_exclude_list = dbOid_exclude_list;
arg->skip_external_dirs = params->skip_external_dirs;
arg->to_root = pgdata_path;
arg->use_bitmap = use_bitmap;
arg->incremental_mode = params->incremental_mode;
arg->shift_lsn = params->shift_lsn;
threads_args[i].restored_bytes = 0;
/* By default there are some error */
threads_args[i].ret = 1;
/* Useless message TODO: rewrite */
elog(LOG, "Start thread %i", i + 1);
pthread_create(&threads[i], NULL, restore_files, arg);
}
/* Wait theads */
for (i = 0; i < num_threads; i++)
{
pthread_join(threads[i], NULL);
if (threads_args[i].ret == 1)