-
Notifications
You must be signed in to change notification settings - Fork 86
/
Copy pathcatalog.c
3109 lines (2635 loc) · 84.7 KB
/
catalog.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
/*-------------------------------------------------------------------------
*
* catalog.c: backup catalog operation
*
* Portions Copyright (c) 2009-2011, NIPPON TELEGRAPH AND TELEPHONE CORPORATION
* Portions Copyright (c) 2015-2019, Postgres Professional
*
*-------------------------------------------------------------------------
*/
#include "pg_probackup.h"
#include "access/timeline.h"
#include <dirent.h>
#include <signal.h>
#include <sys/stat.h>
#include <unistd.h>
#include "utils/file.h"
#include "utils/configuration.h"
static pgBackup* get_closest_backup(timelineInfo *tlinfo);
static pgBackup* get_oldest_backup(timelineInfo *tlinfo);
static const char *backupModes[] = {"", "PAGE", "PTRACK", "DELTA", "FULL"};
static pgBackup *readBackupControlFile(const char *path);
static time_t create_backup_dir(pgBackup *backup, const char *backup_instance_path);
static bool backup_lock_exit_hook_registered = false;
static parray *locks = NULL;
static int grab_excl_lock_file(const char *backup_dir, const char *backup_id, bool strict);
static int grab_shared_lock_file(pgBackup *backup);
static int wait_shared_owners(pgBackup *backup);
static void unlock_backup(const char *backup_dir, const char *backup_id, bool exclusive);
static void release_excl_lock_file(const char *backup_dir);
static void release_shared_lock_file(const char *backup_dir);
#define LOCK_OK 0
#define LOCK_FAIL_TIMEOUT 1
#define LOCK_FAIL_ENOSPC 2
#define LOCK_FAIL_EROFS 3
typedef struct LockInfo
{
char backup_id[10];
char backup_dir[MAXPGPATH];
bool exclusive;
} LockInfo;
timelineInfo *
timelineInfoNew(TimeLineID tli)
{
timelineInfo *tlinfo = (timelineInfo *) pgut_malloc(sizeof(timelineInfo));
MemSet(tlinfo, 0, sizeof(timelineInfo));
tlinfo->tli = tli;
tlinfo->switchpoint = InvalidXLogRecPtr;
tlinfo->parent_link = NULL;
tlinfo->xlog_filelist = parray_new();
tlinfo->anchor_lsn = InvalidXLogRecPtr;
tlinfo->anchor_tli = 0;
tlinfo->n_xlog_files = 0;
return tlinfo;
}
/* free timelineInfo object */
void
timelineInfoFree(void *tliInfo)
{
timelineInfo *tli = (timelineInfo *) tliInfo;
parray_walk(tli->xlog_filelist, pgFileFree);
parray_free(tli->xlog_filelist);
if (tli->backups)
{
/* backups themselves should freed separately */
// parray_walk(tli->backups, pgBackupFree);
parray_free(tli->backups);
}
pfree(tliInfo);
}
/* Iterate over locked backups and unlock them */
static void
unlink_lock_atexit(void)
{
int i;
if (locks == NULL)
return;
for (i = 0; i < parray_num(locks); i++)
{
LockInfo *lock = (LockInfo *) parray_get(locks, i);
unlock_backup(lock->backup_dir, lock->backup_dir, lock->exclusive);
}
parray_walk(locks, pg_free);
parray_free(locks);
locks = NULL;
}
/*
* Read backup meta information from BACKUP_CONTROL_FILE.
* If no backup matches, return NULL.
*/
pgBackup *
read_backup(const char *root_dir)
{
char conf_path[MAXPGPATH];
join_path_components(conf_path, root_dir, BACKUP_CONTROL_FILE);
return readBackupControlFile(conf_path);
}
/*
* Save the backup status into BACKUP_CONTROL_FILE.
*
* We need to reread the backup using its ID and save it changing only its
* status.
*/
void
write_backup_status(pgBackup *backup, BackupStatus status,
const char *instance_name, bool strict)
{
pgBackup *tmp;
tmp = read_backup(backup->root_dir);
if (!tmp)
{
/*
* Silently exit the function, since read_backup already logged the
* warning message.
*/
return;
}
/* overwrite control file only if status has changed */
if (tmp->status == status)
{
pgBackupFree(tmp);
return;
}
backup->status = status;
tmp->status = backup->status;
tmp->root_dir = pgut_strdup(backup->root_dir);
/* lock backup in exclusive mode */
if (!lock_backup(tmp, strict, true))
elog(ERROR, "Cannot lock backup %s directory", base36enc(backup->start_time));
write_backup(tmp, strict);
pgBackupFree(tmp);
}
/*
* Lock backup in either exclusive or shared mode.
* "strict" flag allows to ignore "out of space" errors and should be
* used only by DELETE command to free disk space on filled up
* filesystem.
*
* Only read only tasks (validate, restore) are allowed to take shared locks.
* Changing backup metadata must be done with exclusive lock.
*
* Only one process can hold exclusive lock at any time.
* Exlusive lock - PID of process, holding the lock - is placed in
* lock file: BACKUP_LOCK_FILE.
*
* Multiple proccess are allowed to take shared locks simultaneously.
* Shared locks - PIDs of proccesses, holding the lock - are placed in
* separate lock file: BACKUP_RO_LOCK_FILE.
* When taking shared lock, a brief exclusive lock is taken.
*
* -> exclusive -> grab exclusive lock file and wait until all shared lockers are gone, return
* -> shared -> grab exclusive lock file, grab shared lock file, release exclusive lock file, return
*
* TODO: lock-timeout as parameter
*/
bool
lock_backup(pgBackup *backup, bool strict, bool exclusive)
{
int rc;
char lock_file[MAXPGPATH];
bool enospc_detected = false;
LockInfo *lock = NULL;
join_path_components(lock_file, backup->root_dir, BACKUP_LOCK_FILE);
rc = grab_excl_lock_file(backup->root_dir, base36enc(backup->start_time), strict);
if (rc == LOCK_FAIL_TIMEOUT)
return false;
else if (rc == LOCK_FAIL_ENOSPC)
{
/*
* If we failed to take exclusive lock due to ENOSPC,
* then in lax mode treat such condition as if lock was taken.
*/
enospc_detected = true;
if (strict)
return false;
}
else if (rc == LOCK_FAIL_EROFS)
{
/*
* If we failed to take exclusive lock due to EROFS,
* then in shared mode treat such condition as if lock was taken.
*/
return !exclusive;
}
/*
* We have exclusive lock, now there are following scenarios:
*
* 1. If we are for exlusive lock, then we must open the shared lock file
* and check if any of the processes listed there are still alive.
* If some processes are alive and are not going away in lock_timeout,
* then return false.
*
* 2. If we are here for non-exlusive lock, then write the pid
* into shared lock file and release the exclusive lock.
*/
if (exclusive)
rc = wait_shared_owners(backup);
else
rc = grab_shared_lock_file(backup);
if (rc != 0)
{
/*
* Failed to grab shared lock or (in case of exclusive mode) shared lock owners
* are not going away in time, release the exclusive lock file and return in shame.
*/
release_excl_lock_file(backup->root_dir);
return false;
}
if (!exclusive)
{
/* Shared lock file is grabbed, now we can release exclusive lock file */
release_excl_lock_file(backup->root_dir);
}
if (exclusive && !strict && enospc_detected)
{
/* We are in lax exclusive mode and EONSPC was encountered:
* once again try to grab exclusive lock file,
* because there is a chance that release of shared lock file in wait_shared_owners may have
* freed some space on filesystem, thanks to unlinking of BACKUP_RO_LOCK_FILE.
* If somebody concurrently acquired exclusive lock file first, then we should give up.
*/
if (grab_excl_lock_file(backup->root_dir, base36enc(backup->start_time), strict) == LOCK_FAIL_TIMEOUT)
return false;
return true;
}
/*
* Arrange the unlocking at proc_exit.
*/
if (!backup_lock_exit_hook_registered)
{
atexit(unlink_lock_atexit);
backup_lock_exit_hook_registered = true;
}
/* save lock metadata for later unlocking */
lock = pgut_malloc(sizeof(LockInfo));
snprintf(lock->backup_id, 10, "%s", base36enc(backup->backup_id));
snprintf(lock->backup_dir, MAXPGPATH, "%s", backup->root_dir);
lock->exclusive = exclusive;
/* Use parray for lock release */
if (locks == NULL)
locks = parray_new();
parray_append(locks, lock);
return true;
}
/*
* Lock backup in exclusive mode
* Result codes:
* LOCK_OK Success
* LOCK_FAIL_TIMEOUT Failed to acquire lock in lock_timeout time
* LOCK_FAIL_ENOSPC Failed to acquire lock due to ENOSPC
* LOCK_FAIL_EROFS Failed to acquire lock due to EROFS
*/
int
grab_excl_lock_file(const char *root_dir, const char *backup_id, bool strict)
{
char lock_file[MAXPGPATH];
int fd = 0;
char buffer[256];
int ntries = LOCK_TIMEOUT;
int empty_tries = LOCK_STALE_TIMEOUT;
int len;
int encoded_pid;
join_path_components(lock_file, root_dir, BACKUP_LOCK_FILE);
/*
* We need a loop here because of race conditions. But don't loop forever
* (for example, a non-writable $backup_instance_path directory might cause a failure
* that won't go away).
*/
do
{
FILE *fp_out = NULL;
if (interrupted)
elog(ERROR, "Interrupted while locking backup %s", backup_id);
/*
* Try to create the lock file --- O_EXCL makes this atomic.
*
* Think not to make the file protection weaker than 0600. See
* comments below.
*/
fd = fio_open(lock_file, O_RDWR | O_CREAT | O_EXCL, FIO_BACKUP_HOST);
if (fd >= 0)
break; /* Success; exit the retry loop */
/* read-only fs is a special case */
if (errno == EROFS)
{
elog(WARNING, "Could not create lock file \"%s\": %s",
lock_file, strerror(errno));
return LOCK_FAIL_EROFS;
}
/*
* Couldn't create the pid file. Probably it already exists.
* If file already exists or we have some permission problem (???),
* then retry;
*/
// if ((errno != EEXIST && errno != EACCES))
if (errno != EEXIST)
elog(ERROR, "Could not create lock file \"%s\": %s",
lock_file, strerror(errno));
/*
* Read the file to get the old owner's PID. Note race condition
* here: file might have been deleted since we tried to create it.
*/
fp_out = fopen(lock_file, "r");
if (fp_out == NULL)
{
if (errno == ENOENT)
continue; /* race condition; try again */
elog(ERROR, "Cannot open lock file \"%s\": %s", lock_file, strerror(errno));
}
len = fread(buffer, 1, sizeof(buffer) - 1, fp_out);
if (ferror(fp_out))
elog(ERROR, "Cannot read from lock file: \"%s\"", lock_file);
fclose(fp_out);
/*
* There are several possible reasons for lock file
* to be empty:
* - system crash
* - process crash
* - race between writer and reader
*
* Consider empty file to be stale after LOCK_STALE_TIMEOUT attempts.
*
* TODO: alternatively we can write into temp file (lock_file_%pid),
* rename it and then re-read lock file to make sure,
* that we are successfully acquired the lock.
*/
if (len == 0)
{
if (empty_tries == 0)
{
elog(WARNING, "Lock file \"%s\" is empty", lock_file);
goto grab_lock;
}
if ((empty_tries % LOG_FREQ) == 0)
elog(WARNING, "Waiting %u seconds on empty exclusive lock for backup %s",
empty_tries, backup_id);
sleep(1);
/*
* waiting on empty lock file should not affect
* the timer for concurrent lockers (ntries).
*/
empty_tries--;
ntries++;
continue;
}
encoded_pid = atoi(buffer);
if (encoded_pid <= 0)
{
elog(WARNING, "Bogus data in lock file \"%s\": \"%s\"",
lock_file, buffer);
goto grab_lock;
}
/*
* Check to see if the other process still exists
* Normally kill() will fail with ESRCH if the given PID doesn't
* exist.
*/
if (encoded_pid == my_pid)
return LOCK_OK;
if (kill(encoded_pid, 0) == 0)
{
/* complain every fifth interval */
if ((ntries % LOG_FREQ) == 0)
{
elog(WARNING, "Process %d is using backup %s, and is still running",
encoded_pid, backup_id);
elog(WARNING, "Waiting %u seconds on exclusive lock for backup %s",
ntries, backup_id);
}
sleep(1);
/* try again */
continue;
}
else
{
if (errno == ESRCH)
elog(WARNING, "Process %d which used backup %s no longer exists",
encoded_pid, backup_id);
else
elog(ERROR, "Failed to send signal 0 to a process %d: %s",
encoded_pid, strerror(errno));
}
grab_lock:
/*
* Looks like nobody's home. Unlink the file and try again to create
* it. Need a loop because of possible race condition against other
* would-be creators.
*/
if (fio_unlink(lock_file, FIO_BACKUP_HOST) < 0)
{
if (errno == ENOENT)
continue; /* race condition, again */
elog(ERROR, "Could not remove old lock file \"%s\": %s",
lock_file, strerror(errno));
}
} while (ntries--);
/* Failed to acquire exclusive lock in time */
if (fd <= 0)
return LOCK_FAIL_TIMEOUT;
/*
* Successfully created the file, now fill it.
*/
snprintf(buffer, sizeof(buffer), "%d\n", my_pid);
errno = 0;
if (fio_write(fd, buffer, strlen(buffer)) != strlen(buffer))
{
int save_errno = errno;
fio_close(fd);
fio_unlink(lock_file, FIO_BACKUP_HOST);
/* In lax mode if we failed to grab lock because of 'out of space error',
* then treat backup as locked.
* Only delete command should be run in lax mode.
*/
if (!strict && save_errno == ENOSPC)
return LOCK_FAIL_ENOSPC;
else
elog(ERROR, "Could not write lock file \"%s\": %s",
lock_file, strerror(save_errno));
}
if (fio_flush(fd) != 0)
{
int save_errno = errno;
fio_close(fd);
fio_unlink(lock_file, FIO_BACKUP_HOST);
/* In lax mode if we failed to grab lock because of 'out of space error',
* then treat backup as locked.
* Only delete command should be run in lax mode.
*/
if (!strict && save_errno == ENOSPC)
return LOCK_FAIL_ENOSPC;
else
elog(ERROR, "Could not flush lock file \"%s\": %s",
lock_file, strerror(save_errno));
}
if (fio_close(fd) != 0)
{
int save_errno = errno;
fio_unlink(lock_file, FIO_BACKUP_HOST);
if (!strict && errno == ENOSPC)
return LOCK_FAIL_ENOSPC;
else
elog(ERROR, "Could not close lock file \"%s\": %s",
lock_file, strerror(save_errno));
}
// elog(LOG, "Acquired exclusive lock for backup %s after %ds",
// base36enc(backup->start_time),
// LOCK_TIMEOUT - ntries + LOCK_STALE_TIMEOUT - empty_tries);
return LOCK_OK;
}
/* Wait until all shared lock owners are gone
* 0 - successs
* 1 - fail
*/
int
wait_shared_owners(pgBackup *backup)
{
FILE *fp = NULL;
char buffer[256];
pid_t encoded_pid = 0;
int ntries = LOCK_TIMEOUT;
char lock_file[MAXPGPATH];
join_path_components(lock_file, backup->root_dir, BACKUP_RO_LOCK_FILE);
fp = fopen(lock_file, "r");
if (fp == NULL && errno != ENOENT)
elog(ERROR, "Cannot open lock file \"%s\": %s", lock_file, strerror(errno));
/* iterate over pids in lock file */
while (fp && fgets(buffer, sizeof(buffer), fp))
{
encoded_pid = atoi(buffer);
if (encoded_pid <= 0)
{
elog(WARNING, "Bogus data in lock file \"%s\": \"%s\"", lock_file, buffer);
continue;
}
/* wait until shared lock owners go away */
do
{
if (interrupted)
elog(ERROR, "Interrupted while locking backup %s",
base36enc(backup->start_time));
if (encoded_pid == my_pid)
break;
/* check if lock owner is still alive */
if (kill(encoded_pid, 0) == 0)
{
/* complain from time to time */
if ((ntries % LOG_FREQ) == 0)
{
elog(WARNING, "Process %d is using backup %s in shared mode, and is still running",
encoded_pid, base36enc(backup->start_time));
elog(WARNING, "Waiting %u seconds on lock for backup %s", ntries,
base36enc(backup->start_time));
}
sleep(1);
/* try again */
continue;
}
else if (errno != ESRCH)
elog(ERROR, "Failed to send signal 0 to a process %d: %s",
encoded_pid, strerror(errno));
/* locker is dead */
break;
} while (ntries--);
}
if (fp && ferror(fp))
elog(ERROR, "Cannot read from lock file: \"%s\"", lock_file);
if (fp)
fclose(fp);
/* some shared owners are still alive */
if (ntries <= 0)
{
elog(WARNING, "Cannot to lock backup %s in exclusive mode, because process %u owns shared lock",
base36enc(backup->start_time), encoded_pid);
return 1;
}
/* unlink shared lock file */
fio_unlink(lock_file, FIO_BACKUP_HOST);
return 0;
}
/*
* Lock backup in shared mode
* 0 - successs
* 1 - fail
*/
int
grab_shared_lock_file(pgBackup *backup)
{
FILE *fp_in = NULL;
FILE *fp_out = NULL;
char buf_in[256];
pid_t encoded_pid;
char lock_file[MAXPGPATH];
char buffer[8192]; /*TODO: should be enough, but maybe malloc+realloc is better ? */
char lock_file_tmp[MAXPGPATH];
int buffer_len = 0;
join_path_components(lock_file, backup->root_dir, BACKUP_RO_LOCK_FILE);
snprintf(lock_file_tmp, MAXPGPATH, "%s%s", lock_file, "tmp");
/* open already existing lock files */
fp_in = fopen(lock_file, "r");
if (fp_in == NULL && errno != ENOENT)
elog(ERROR, "Cannot open lock file \"%s\": %s", lock_file, strerror(errno));
/* read PIDs of owners */
while (fp_in && fgets(buf_in, sizeof(buf_in), fp_in))
{
encoded_pid = atoi(buf_in);
if (encoded_pid <= 0)
{
elog(WARNING, "Bogus data in lock file \"%s\": \"%s\"", lock_file, buf_in);
continue;
}
if (encoded_pid == my_pid)
continue;
if (kill(encoded_pid, 0) == 0)
{
/*
* Somebody is still using this backup in shared mode,
* copy this pid into a new file.
*/
buffer_len += snprintf(buffer+buffer_len, 4096, "%u\n", encoded_pid);
}
else if (errno != ESRCH)
elog(ERROR, "Failed to send signal 0 to a process %d: %s",
encoded_pid, strerror(errno));
}
if (fp_in)
{
if (ferror(fp_in))
elog(ERROR, "Cannot read from lock file: \"%s\"", lock_file);
fclose(fp_in);
}
fp_out = fopen(lock_file_tmp, "w");
if (fp_out == NULL)
{
if (errno == EROFS)
return 0;
elog(ERROR, "Cannot open temp lock file \"%s\": %s", lock_file_tmp, strerror(errno));
}
/* add my own pid */
buffer_len += snprintf(buffer+buffer_len, sizeof(buffer), "%u\n", my_pid);
/* write out the collected PIDs to temp lock file */
fwrite(buffer, 1, buffer_len, fp_out);
if (ferror(fp_out))
elog(ERROR, "Cannot write to lock file: \"%s\"", lock_file_tmp);
if (fclose(fp_out) != 0)
elog(ERROR, "Cannot close temp lock file \"%s\": %s", lock_file_tmp, strerror(errno));
if (rename(lock_file_tmp, lock_file) < 0)
elog(ERROR, "Cannot rename file \"%s\" to \"%s\": %s",
lock_file_tmp, lock_file, strerror(errno));
return 0;
}
void
unlock_backup(const char *backup_dir, const char *backup_id, bool exclusive)
{
if (exclusive)
{
release_excl_lock_file(backup_dir);
return;
}
/* To remove shared lock, we must briefly obtain exclusive lock, ... */
if (grab_excl_lock_file(backup_dir, backup_id, false) != LOCK_OK)
/* ... if it's not possible then leave shared lock */
return;
release_shared_lock_file(backup_dir);
release_excl_lock_file(backup_dir);
}
void
release_excl_lock_file(const char *backup_dir)
{
char lock_file[MAXPGPATH];
join_path_components(lock_file, backup_dir, BACKUP_LOCK_FILE);
/* TODO Sanity check: maybe we should check, that pid in lock file is my_pid */
/* unlink pid file */
fio_unlink(lock_file, FIO_BACKUP_HOST);
}
void
release_shared_lock_file(const char *backup_dir)
{
FILE *fp_in = NULL;
FILE *fp_out = NULL;
char buf_in[256];
pid_t encoded_pid;
char lock_file[MAXPGPATH];
char buffer[8192]; /*TODO: should be enough, but maybe malloc+realloc is better ? */
char lock_file_tmp[MAXPGPATH];
int buffer_len = 0;
join_path_components(lock_file, backup_dir, BACKUP_RO_LOCK_FILE);
snprintf(lock_file_tmp, MAXPGPATH, "%s%s", lock_file, "tmp");
/* open lock file */
fp_in = fopen(lock_file, "r");
if (fp_in == NULL)
{
if (errno == ENOENT)
return;
else
elog(ERROR, "Cannot open lock file \"%s\": %s", lock_file, strerror(errno));
}
/* read PIDs of owners */
while (fgets(buf_in, sizeof(buf_in), fp_in))
{
encoded_pid = atoi(buf_in);
if (encoded_pid <= 0)
{
elog(WARNING, "Bogus data in lock file \"%s\": \"%s\"", lock_file, buf_in);
continue;
}
/* remove my pid */
if (encoded_pid == my_pid)
continue;
if (kill(encoded_pid, 0) == 0)
{
/*
* Somebody is still using this backup in shared mode,
* copy this pid into a new file.
*/
buffer_len += snprintf(buffer+buffer_len, 4096, "%u\n", encoded_pid);
}
else if (errno != ESRCH)
elog(ERROR, "Failed to send signal 0 to a process %d: %s",
encoded_pid, strerror(errno));
}
if (ferror(fp_in))
elog(ERROR, "Cannot read from lock file: \"%s\"", lock_file);
fclose(fp_in);
/* if there is no active pid left, then there is nothing to do */
if (buffer_len == 0)
{
fio_unlink(lock_file, FIO_BACKUP_HOST);
return;
}
fp_out = fopen(lock_file_tmp, "w");
if (fp_out == NULL)
elog(ERROR, "Cannot open temp lock file \"%s\": %s", lock_file_tmp, strerror(errno));
/* write out the collected PIDs to temp lock file */
fwrite(buffer, 1, buffer_len, fp_out);
if (ferror(fp_out))
elog(ERROR, "Cannot write to lock file: \"%s\"", lock_file_tmp);
if (fclose(fp_out) != 0)
elog(ERROR, "Cannot close temp lock file \"%s\": %s", lock_file_tmp, strerror(errno));
if (rename(lock_file_tmp, lock_file) < 0)
elog(ERROR, "Cannot rename file \"%s\" to \"%s\": %s",
lock_file_tmp, lock_file, strerror(errno));
return;
}
/*
* Get backup_mode in string representation.
*/
const char *
pgBackupGetBackupMode(pgBackup *backup)
{
return backupModes[backup->backup_mode];
}
static bool
IsDir(const char *dirpath, const char *entry, fio_location location)
{
char path[MAXPGPATH];
struct stat st;
join_path_components(path, dirpath, entry);
return fio_stat(path, &st, false, location) == 0 && S_ISDIR(st.st_mode);
}
/*
* Create list of instances in given backup catalog.
*
* Returns parray of "InstanceConfig" structures, filled with
* actual config of each instance.
*/
parray *
catalog_get_instance_list(void)
{
char path[MAXPGPATH];
DIR *dir;
struct dirent *dent;
parray *instances;
instances = parray_new();
/* open directory and list contents */
join_path_components(path, backup_path, BACKUPS_DIR);
dir = opendir(path);
if (dir == NULL)
elog(ERROR, "Cannot open directory \"%s\": %s",
path, strerror(errno));
while (errno = 0, (dent = readdir(dir)) != NULL)
{
char child[MAXPGPATH];
struct stat st;
InstanceConfig *instance;
/* skip entries point current dir or parent dir */
if (strcmp(dent->d_name, ".") == 0 ||
strcmp(dent->d_name, "..") == 0)
continue;
join_path_components(child, path, dent->d_name);
if (lstat(child, &st) == -1)
elog(ERROR, "Cannot stat file \"%s\": %s",
child, strerror(errno));
if (!S_ISDIR(st.st_mode))
continue;
instance = readInstanceConfigFile(dent->d_name);
parray_append(instances, instance);
}
/* TODO 3.0: switch to ERROR */
if (parray_num(instances) == 0)
elog(WARNING, "This backup catalog contains no backup instances. Backup instance can be added via 'add-instance' command.");
if (errno)
elog(ERROR, "Cannot read directory \"%s\": %s",
path, strerror(errno));
if (closedir(dir))
elog(ERROR, "Cannot close directory \"%s\": %s",
path, strerror(errno));
return instances;
}
/*
* Create list of backups.
* If 'requested_backup_id' is INVALID_BACKUP_ID, return list of all backups.
* The list is sorted in order of descending start time.
* If valid backup id is passed only matching backup will be added to the list.
*/
parray *
catalog_get_backup_list(const char *instance_name, time_t requested_backup_id)
{
DIR *data_dir = NULL;
struct dirent *data_ent = NULL;
parray *backups = NULL;
int i;
char backup_instance_path[MAXPGPATH];
sprintf(backup_instance_path, "%s/%s/%s",
backup_path, BACKUPS_DIR, instance_name);
/* open backup instance backups directory */
data_dir = fio_opendir(backup_instance_path, FIO_BACKUP_HOST);
if (data_dir == NULL)
{
elog(WARNING, "cannot open directory \"%s\": %s", backup_instance_path,
strerror(errno));
goto err_proc;
}
/* scan the directory and list backups */
backups = parray_new();
for (; (data_ent = fio_readdir(data_dir)) != NULL; errno = 0)
{
char backup_conf_path[MAXPGPATH];
char data_path[MAXPGPATH];
pgBackup *backup = NULL;
/* skip not-directory entries and hidden entries */
if (!IsDir(backup_instance_path, data_ent->d_name, FIO_BACKUP_HOST)
|| data_ent->d_name[0] == '.')
continue;
/* open subdirectory of specific backup */
join_path_components(data_path, backup_instance_path, data_ent->d_name);
/* read backup information from BACKUP_CONTROL_FILE */
join_path_components(backup_conf_path, data_path, BACKUP_CONTROL_FILE);
backup = readBackupControlFile(backup_conf_path);
if (!backup)
{
backup = pgut_new(pgBackup);
pgBackupInit(backup);
backup->start_time = base36dec(data_ent->d_name);
}
else if (strcmp(base36enc(backup->start_time), data_ent->d_name) != 0)
{
elog(WARNING, "backup ID in control file \"%s\" doesn't match name of the backup folder \"%s\"",
base36enc(backup->start_time), backup_conf_path);
}
backup->root_dir = pgut_strdup(data_path);
backup->database_dir = pgut_malloc(MAXPGPATH);
join_path_components(backup->database_dir, backup->root_dir, DATABASE_DIR);
/* Initialize page header map */
init_header_map(backup);
/* TODO: save encoded backup id */
backup->backup_id = backup->start_time;
if (requested_backup_id != INVALID_BACKUP_ID
&& requested_backup_id != backup->start_time)
{
pgBackupFree(backup);
continue;
}
parray_append(backups, backup);
}
if (errno)
{
elog(WARNING, "Cannot read backup root directory \"%s\": %s",
backup_instance_path, strerror(errno));
goto err_proc;
}
fio_closedir(data_dir);
data_dir = NULL;
parray_qsort(backups, pgBackupCompareIdDesc);
/* Link incremental backups with their ancestors.*/
for (i = 0; i < parray_num(backups); i++)
{
pgBackup *curr = parray_get(backups, i);
pgBackup **ancestor;
pgBackup key;
if (curr->backup_mode == BACKUP_MODE_FULL)
continue;
key.start_time = curr->parent_backup;