-
Notifications
You must be signed in to change notification settings - Fork 86
/
Copy patharchive.c
1885 lines (1600 loc) · 52.6 KB
/
archive.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
/*-------------------------------------------------------------------------
*
* archive.c: - pg_probackup specific archive commands for archive backups.
*
*
* Portions Copyright (c) 2018-2021, Postgres Professional
*
*-------------------------------------------------------------------------
*/
#include <unistd.h>
#include "pg_probackup.h"
#include "utils/thread.h"
#include "instr_time.h"
static int push_file_internal_uncompressed(const char *wal_file_name, const char *pg_xlog_dir,
const char *archive_dir, bool overwrite, bool no_sync,
uint32 archive_timeout, xlogFileType type);
#ifdef HAVE_LIBZ
static int push_file_internal_gz(const char *wal_file_name, const char *pg_xlog_dir,
const char *archive_dir, bool overwrite, bool no_sync,
int compress_level, uint32 archive_timeout, xlogFileType type);
#endif
static void *push_files(void *arg);
static void *get_files(void *arg);
static bool
get_wal_file_wrapper(const char *filename, const char *archive_root_dir,
const char *to_fullpath, bool prefetch_mode);
static bool get_wal_file(const char *filename, const char *from_path, const char *to_path,
bool prefetch_mode);
static int get_wal_file_internal(const char *from_path, const char *to_path, FILE *out,
bool is_decompress);
#ifdef HAVE_LIBZ
static const char *get_gz_error(gzFile gzf, int errnum);
#endif
//static void copy_file_attributes(const char *from_path,
// fio_location from_location,
// const char *to_path, fio_location to_location,
// bool unlink_on_error);
static bool next_wal_segment_exists(TimeLineID tli, XLogSegNo segno, const char *prefetch_dir, uint32 wal_seg_size);
static uint32 run_wal_prefetch(const char *prefetch_dir, const char *archive_dir, TimeLineID tli,
XLogSegNo first_segno, int num_threads, bool inclusive, int batch_size,
uint32 wal_seg_size);
static bool wal_satisfy_from_prefetch(TimeLineID tli, XLogSegNo segno, const char *wal_file_name,
const char *prefetch_dir, const char *absolute_wal_file_path,
uint32 wal_seg_size, bool parse_wal);
static uint32 maintain_prefetch(const char *prefetch_dir, XLogSegNo first_segno, uint32 wal_seg_size);
static bool prefetch_stop = false;
static uint32 xlog_seg_size;
typedef struct
{
const char *first_filename;
const char *pg_xlog_dir;
const char *archive_dir;
const char *archive_status_dir;
bool overwrite;
bool compress;
bool no_sync;
bool no_ready_rename;
uint32 archive_timeout;
CompressAlg compress_alg;
int compress_level;
int thread_num;
parray *files;
uint32 n_pushed;
uint32 n_skipped;
/*
* Return value from the thread.
* 0 means there is no error,
* 1 - there is an error.
* 2 - no error, but nothing to push
*/
int ret;
} archive_push_arg;
typedef struct
{
const char *prefetch_dir;
const char *archive_dir;
int thread_num;
parray *files;
uint32 n_fetched;
} archive_get_arg;
typedef struct WALSegno
{
char name[MAXFNAMELEN];
volatile pg_atomic_flag lock;
xlogFileType type;
} WALSegno;
static int push_file(WALSegno *xlogfile, const char *archive_status_dir,
const char *pg_xlog_dir, const char *archive_dir,
bool overwrite, bool no_sync, uint32 archive_timeout,
bool no_ready_rename, bool is_compress,
int compress_level);
static parray *setup_push_filelist(const char *archive_status_dir,
const char *first_file, int batch_size);
static parray *setup_archive_subdirs(parray *batch_files, const char *archive_dir);
static xlogFileType
get_xlogFileType(const char *filename)
{
if IsXLogFileName(filename)
return SEGMENT;
else if IsPartialXLogFileName(filename)
return PARTIAL_SEGMENT;
else if IsBackupHistoryFileName(filename)
return BACKUP_HISTORY_FILE;
else if IsTLHistoryFileName(filename)
return HISTORY_FILE;
else if IsBackupHistoryFileName(filename)
return BACKUP_HISTORY_FILE;
return UNKNOWN;
}
/*
* At this point, we already done one roundtrip to archive server
* to get instance config.
*
* pg_probackup specific archive command for archive backups
* set archive_command to
* 'pg_probackup archive-push -B /home/anastasia/backup --wal-file-name %f',
* to move backups into arclog_path.
* Where archlog_path is $BACKUP_PATH/wal/instance_name
*/
void
do_archive_push(InstanceState *instanceState, InstanceConfig *instance, char *pg_xlog_dir,
char *wal_file_name, int batch_size, bool overwrite,
bool no_sync, bool no_ready_rename)
{
uint64 i;
/* usually instance pgdata/pg_wal/archive_status, empty if no_ready_rename or batch_size == 1 */
char archive_status_dir[MAXPGPATH] = "";
bool is_compress = false;
/* arrays with meta info for multi threaded backup */
pthread_t *threads;
archive_push_arg *threads_args;
bool push_isok = true;
/* reporting */
uint32 n_total_pushed = 0;
uint32 n_total_skipped = 0;
uint32 n_total_failed = 0;
instr_time start_time, end_time;
double push_time;
char pretty_time_str[20];
/* files to push in multi-thread mode */
parray *batch_files = NULL;
parray *archive_subdirs = NULL;
int n_threads;
if (!no_ready_rename || batch_size > 1)
join_path_components(archive_status_dir, pg_xlog_dir, "archive_status");
#ifdef HAVE_LIBZ
if (instance->compress_alg == ZLIB_COMPRESS)
is_compress = true;
#endif
/* Setup filelist and locks */
batch_files = setup_push_filelist(archive_status_dir, wal_file_name, batch_size);
n_threads = num_threads;
if (num_threads > parray_num(batch_files))
n_threads = parray_num(batch_files);
elog(INFO, "pg_probackup archive-push WAL file: %s, "
"threads: %i/%i, batch: %lu/%i, compression: %s",
wal_file_name, n_threads, num_threads,
parray_num(batch_files), batch_size,
is_compress ? "zlib" : "none");
/* Extract subdirectories */
archive_subdirs = setup_archive_subdirs(batch_files, instanceState->instance_wal_subdir_path);
if (archive_subdirs)
{
for (i = 0; i < parray_num(archive_subdirs); i++)
{
char *subdir = (char *) parray_get(archive_subdirs, i);
if (fio_mkdir(subdir, DIR_PERMISSION, FIO_BACKUP_HOST) != 0)
elog(ERROR, "Cannot create subdirectory in WAL archive: '%s'", subdir);
pg_free(subdir);
}
parray_free(archive_subdirs);
}
num_threads = n_threads;
/* Single-thread push
* We don`t want to start multi-thread push, if number of threads in equal to 1,
* or the number of files ready to push is small.
* Multithreading in remote mode isn`t cheap,
* establishing ssh connection can take 100-200ms, so running and terminating
* one thread using generic multithread approach can take
* almost as much time as copying itself.
* TODO: maybe we should be more conservative and force single thread
* push if batch_files array is small.
*/
if (num_threads == 1 || (parray_num(batch_files) == 1))
{
INSTR_TIME_SET_CURRENT(start_time);
for (i = 0; i < parray_num(batch_files); i++)
{
int rc;
WALSegno *xlogfile = (WALSegno *) parray_get(batch_files, i);
bool first_wal = strcmp(xlogfile->name, wal_file_name) == 0;
rc = push_file(xlogfile, first_wal ? NULL : archive_status_dir,
pg_xlog_dir, instanceState->instance_wal_subdir_path,
overwrite, no_sync,
instance->archive_timeout,
no_ready_rename || first_wal,
is_compress && IsXLogFileName(xlogfile->name) ? true : false,
instance->compress_level);
if (rc == 0)
n_total_pushed++;
else
n_total_skipped++;
}
push_isok = true;
goto push_done;
}
/* init thread args with its own segno */
threads = (pthread_t *) palloc(sizeof(pthread_t) * num_threads);
threads_args = (archive_push_arg *) palloc(sizeof(archive_push_arg) * num_threads);
for (i = 0; i < num_threads; i++)
{
archive_push_arg *arg = &(threads_args[i]);
arg->first_filename = wal_file_name;
arg->archive_dir = instanceState->instance_wal_subdir_path;
arg->pg_xlog_dir = pg_xlog_dir;
arg->archive_status_dir = (!no_ready_rename || batch_size > 1) ? archive_status_dir : NULL;
arg->overwrite = overwrite;
arg->compress = is_compress;
arg->no_sync = no_sync;
arg->no_ready_rename = no_ready_rename;
arg->archive_timeout = instance->archive_timeout;
arg->compress_alg = instance->compress_alg;
arg->compress_level = instance->compress_level;
arg->files = batch_files;
arg->n_pushed = 0;
arg->n_skipped = 0;
arg->thread_num = i+1;
/* By default there are some error */
arg->ret = 1;
}
/* Run threads */
INSTR_TIME_SET_CURRENT(start_time);
for (i = 0; i < num_threads; i++)
{
archive_push_arg *arg = &(threads_args[i]);
pthread_create(&threads[i], NULL, push_files, arg);
}
/* Wait threads */
for (i = 0; i < num_threads; i++)
{
pthread_join(threads[i], NULL);
if (threads_args[i].ret == 1)
{
push_isok = false;
n_total_failed++;
}
n_total_pushed += threads_args[i].n_pushed;
n_total_skipped += threads_args[i].n_skipped;
}
/* Note, that we are leaking memory here,
* because pushing into archive is a very
* time-sensitive operation, so we skip freeing stuff.
*/
push_done:
fio_disconnect();
/* calculate elapsed time */
INSTR_TIME_SET_CURRENT(end_time);
INSTR_TIME_SUBTRACT(end_time, start_time);
push_time = INSTR_TIME_GET_DOUBLE(end_time);
pretty_time_interval(push_time, pretty_time_str, 20);
if (push_isok)
/* report number of files pushed into archive */
elog(INFO, "pg_probackup archive-push completed successfully, "
"pushed: %u, skipped: %u, time elapsed: %s",
n_total_pushed, n_total_skipped, pretty_time_str);
else
elog(ERROR, "pg_probackup archive-push failed, "
"pushed: %i, skipped: %u, failed: %u, time elapsed: %s",
n_total_pushed, n_total_skipped, n_total_failed,
pretty_time_str);
}
/* ------------- INTERNAL FUNCTIONS ---------- */
/*
* Copy files from pg_wal to archive catalog with possible compression.
*/
static void *
push_files(void *arg)
{
int i;
int rc;
archive_push_arg *args = (archive_push_arg *) arg;
my_thread_num = args->thread_num;
for (i = 0; i < parray_num(args->files); i++)
{
bool no_ready_rename = args->no_ready_rename;
WALSegno *xlogfile = (WALSegno *) parray_get(args->files, i);
if (!pg_atomic_test_set_flag(&xlogfile->lock))
continue;
/* Do not rename ready file of the first file,
* we do this to avoid flooding PostgreSQL log with
* warnings about ready file been missing.
*/
if (strcmp(args->first_filename, xlogfile->name) == 0)
no_ready_rename = true;
rc = push_file(xlogfile, args->archive_status_dir,
args->pg_xlog_dir, args->archive_dir,
args->overwrite, args->no_sync,
args->archive_timeout, no_ready_rename,
/* do not compress .backup, .partial and .history files */
args->compress && IsXLogFileName(xlogfile->name) ? true : false,
args->compress_level);
if (rc == 0)
args->n_pushed++;
else
args->n_skipped++;
}
/* close ssh connection */
fio_disconnect();
args->ret = 0;
return NULL;
}
int
push_file(WALSegno *xlogfile, const char *archive_status_dir,
const char *pg_xlog_dir, const char *archive_dir,
bool overwrite, bool no_sync, uint32 archive_timeout,
bool no_ready_rename, bool is_compress,
int compress_level)
{
int rc;
elog(LOG, "pushing file \"%s\"", xlogfile->name);
/* If compression is not required, then just copy it as is */
if (!is_compress)
rc = push_file_internal_uncompressed(xlogfile->name, pg_xlog_dir,
archive_dir, overwrite, no_sync,
archive_timeout, xlogfile->type);
#ifdef HAVE_LIBZ
else
rc = push_file_internal_gz(xlogfile->name, pg_xlog_dir, archive_dir,
overwrite, no_sync, compress_level,
archive_timeout, xlogfile->type);
#endif
/* take '--no-ready-rename' flag into account */
if (!no_ready_rename && archive_status_dir != NULL)
{
char wal_file_dummy[MAXPGPATH];
char wal_file_ready[MAXPGPATH];
char wal_file_done[MAXPGPATH];
join_path_components(wal_file_dummy, archive_status_dir, xlogfile->name);
snprintf(wal_file_ready, MAXPGPATH, "%s.%s", wal_file_dummy, "ready");
snprintf(wal_file_done, MAXPGPATH, "%s.%s", wal_file_dummy, "done");
canonicalize_path(wal_file_ready);
canonicalize_path(wal_file_done);
/* It is ok to rename status file in archive_status directory */
elog(VERBOSE, "Rename \"%s\" to \"%s\"", wal_file_ready, wal_file_done);
/* do not error out, if rename failed */
if (fio_rename(wal_file_ready, wal_file_done, FIO_DB_HOST) < 0)
elog(WARNING, "Cannot rename ready file \"%s\" to \"%s\": %s",
wal_file_ready, wal_file_done, strerror(errno));
}
return rc;
}
/*
* Copy non WAL file, such as .backup or .history file, into WAL archive.
* Such files are not compressed.
* Returns:
* 0 - file was successfully pushed
* 1 - push was skipped because file already exists in the archive and
* has the same checksum
*/
int
push_file_internal_uncompressed(const char *wal_file_name, const char *pg_xlog_dir,
const char *archive_dir, bool overwrite, bool no_sync,
uint32 archive_timeout, xlogFileType type)
{
FILE *in = NULL;
int out = -1;
char *buf = pgut_malloc(OUT_BUF_SIZE); /* 1MB buffer */
char from_fullpath[MAXPGPATH];
char to_fullpath[MAXPGPATH];
char archive_subdir[MAXPGPATH];
/* partial handling */
struct stat st;
char to_fullpath_part[MAXPGPATH];
int partial_try_count = 0;
int partial_file_size = 0;
bool partial_is_stale = true;
/* remote agent error message */
char *errmsg = NULL;
/* from path */
join_path_components(from_fullpath, pg_xlog_dir, wal_file_name);
canonicalize_path(from_fullpath);
/* calculate subdir in WAL archive */
get_archive_subdir(archive_subdir, archive_dir, wal_file_name, type);
/* to path */
join_path_components(to_fullpath, archive_subdir, wal_file_name);
canonicalize_path(to_fullpath);
/* Open source file for read */
in = fopen(from_fullpath, PG_BINARY_R);
if (in == NULL)
elog(ERROR, "Cannot open source file \"%s\": %s", from_fullpath, strerror(errno));
/* disable stdio buffering for input file */
setvbuf(in, NULL, _IONBF, BUFSIZ);
/* open destination partial file for write */
snprintf(to_fullpath_part, sizeof(to_fullpath_part), "%s.part", to_fullpath);
/* Grab lock by creating temp file in exclusive mode */
out = fio_open(to_fullpath_part, O_RDWR | O_CREAT | O_EXCL | PG_BINARY, FIO_BACKUP_HOST);
if (out < 0)
{
if (errno != EEXIST)
elog(ERROR, "Failed to open temp WAL file \"%s\": %s",
to_fullpath_part, strerror(errno));
/* Already existing destination temp file is not an error condition */
}
else
goto part_opened;
/*
* Partial file already exists, it could have happened due to:
* 1. failed archive-push
* 2. concurrent archiving
*
* For ARCHIVE_TIMEOUT period we will try to create partial file
* and look for the size of already existing partial file, to
* determine if it is changing or not.
* If after ARCHIVE_TIMEOUT we still failed to create partial
* file, we will make a decision about discarding
* already existing partial file.
*/
while (partial_try_count < archive_timeout)
{
if (fio_stat(to_fullpath_part, &st, false, FIO_BACKUP_HOST) < 0)
{
if (errno == ENOENT)
{
//part file is gone, lets try to grab it
out = fio_open(to_fullpath_part, O_RDWR | O_CREAT | O_EXCL | PG_BINARY, FIO_BACKUP_HOST);
if (out < 0)
{
if (errno != EEXIST)
elog(ERROR, "Failed to open temp WAL file \"%s\": %s",
to_fullpath_part, strerror(errno));
}
else
/* Successfully created partial file */
break;
}
else
elog(ERROR, "Cannot stat temp WAL file \"%s\": %s", to_fullpath_part, strerror(errno));
}
/* first round */
if (!partial_try_count)
{
elog(LOG, "Temp WAL file already exists, waiting on it %u seconds: \"%s\"",
archive_timeout, to_fullpath_part);
partial_file_size = st.st_size;
}
/* file size is changing */
if (st.st_size > partial_file_size)
partial_is_stale = false;
sleep(1);
partial_try_count++;
}
/* The possible exit conditions:
* 1. File is grabbed
* 2. File is not grabbed, and it is not stale
* 2. File is not grabbed, and it is stale.
*/
/*
* If temp file was not grabbed for ARCHIVE_TIMEOUT and temp file is not stale,
* then exit with error.
*/
if (out < 0)
{
if (!partial_is_stale)
elog(ERROR, "Failed to open temp WAL file \"%s\" in %i seconds",
to_fullpath_part, archive_timeout);
/* Partial segment is considered stale, so reuse it */
elog(LOG, "Reusing stale temp WAL file \"%s\"", to_fullpath_part);
fio_unlink(to_fullpath_part, FIO_BACKUP_HOST);
out = fio_open(to_fullpath_part, O_RDWR | O_CREAT | O_EXCL | PG_BINARY, FIO_BACKUP_HOST);
if (out < 0)
elog(ERROR, "Cannot open temp WAL file \"%s\": %s", to_fullpath_part, strerror(errno));
}
part_opened:
elog(VERBOSE, "Temp WAL file successfully created: \"%s\"", to_fullpath_part);
/* Check if possible to skip copying */
if (fileExists(to_fullpath, FIO_BACKUP_HOST))
{
pg_crc32 crc32_src;
pg_crc32 crc32_dst;
crc32_src = fio_get_crc32(from_fullpath, FIO_DB_HOST, false);
crc32_dst = fio_get_crc32(to_fullpath, FIO_BACKUP_HOST, false);
if (crc32_src == crc32_dst)
{
elog(LOG, "WAL file already exists in archive with the same "
"checksum, skip pushing: \"%s\"", from_fullpath);
/* cleanup */
fclose(in);
fio_close(out);
fio_unlink(to_fullpath_part, FIO_BACKUP_HOST);
return 1;
}
else
{
if (overwrite)
elog(LOG, "WAL file already exists in archive with "
"different checksum, overwriting: \"%s\"", to_fullpath);
else
{
/* Overwriting is forbidden,
* so we must unlink partial file and exit with error.
*/
fio_unlink(to_fullpath_part, FIO_BACKUP_HOST);
elog(ERROR, "WAL file already exists in archive with "
"different checksum: \"%s\"", to_fullpath);
}
}
}
/* copy content */
errno = 0;
for (;;)
{
size_t read_len = 0;
read_len = fread(buf, 1, OUT_BUF_SIZE, in);
if (ferror(in))
{
fio_unlink(to_fullpath_part, FIO_BACKUP_HOST);
elog(ERROR, "Cannot read source file \"%s\": %s",
from_fullpath, strerror(errno));
}
if (read_len > 0 && fio_write_async(out, buf, read_len) != read_len)
{
fio_unlink(to_fullpath_part, FIO_BACKUP_HOST);
elog(ERROR, "Cannot write to destination temp file \"%s\": %s",
to_fullpath_part, strerror(errno));
}
if (feof(in))
break;
}
/* close source file */
fclose(in);
/* Writing is asynchronous in case of push in remote mode, so check agent status */
if (fio_check_error_fd(out, &errmsg))
{
fio_unlink(to_fullpath_part, FIO_BACKUP_HOST);
elog(ERROR, "Cannot write to the remote file \"%s\": %s",
to_fullpath_part, errmsg);
}
/* close temp file */
if (fio_close(out) != 0)
{
fio_unlink(to_fullpath_part, FIO_BACKUP_HOST);
elog(ERROR, "Cannot close temp WAL file \"%s\": %s",
to_fullpath_part, strerror(errno));
}
/* sync temp file to disk */
if (!no_sync)
{
if (fio_sync(to_fullpath_part, FIO_BACKUP_HOST) != 0)
elog(ERROR, "Failed to sync file \"%s\": %s",
to_fullpath_part, strerror(errno));
}
elog(VERBOSE, "Rename \"%s\" to \"%s\"", to_fullpath_part, to_fullpath);
//copy_file_attributes(from_path, FIO_DB_HOST, to_path_temp, FIO_BACKUP_HOST, true);
/* Rename temp file to destination file */
if (fio_rename(to_fullpath_part, to_fullpath, FIO_BACKUP_HOST) < 0)
{
fio_unlink(to_fullpath_part, FIO_BACKUP_HOST);
elog(ERROR, "Cannot rename file \"%s\" to \"%s\": %s",
to_fullpath_part, to_fullpath, strerror(errno));
}
pg_free(buf);
return 0;
}
#ifdef HAVE_LIBZ
/*
* Push WAL segment into archive and apply streaming compression to it.
* Returns:
* 0 - file was successfully pushed
* 1 - push was skipped because file already exists in the archive and
* has the same checksum
*/
int
push_file_internal_gz(const char *wal_file_name, const char *pg_xlog_dir,
const char *archive_dir, bool overwrite, bool no_sync,
int compress_level, uint32 archive_timeout, xlogFileType type)
{
FILE *in = NULL;
gzFile out = NULL;
char *buf = pgut_malloc(OUT_BUF_SIZE);
char from_fullpath[MAXPGPATH];
char to_fullpath[MAXPGPATH];
char to_fullpath_gz[MAXPGPATH];
char archive_subdir[MAXPGPATH];
/* partial handling */
struct stat st;
char to_fullpath_gz_part[MAXPGPATH];
int partial_try_count = 0;
int partial_file_size = 0;
bool partial_is_stale = true;
/* remote agent errormsg */
char *errmsg = NULL;
/* from path */
join_path_components(from_fullpath, pg_xlog_dir, wal_file_name);
canonicalize_path(from_fullpath);
/* calculate subdir in WAL archive */
get_archive_subdir(archive_subdir, archive_dir, wal_file_name, type);
/* to path */
join_path_components(to_fullpath, archive_subdir, wal_file_name);
canonicalize_path(to_fullpath);
/* destination file with .gz suffix */
snprintf(to_fullpath_gz, sizeof(to_fullpath_gz), "%s.gz", to_fullpath);
/* destination temp file */
snprintf(to_fullpath_gz_part, sizeof(to_fullpath_gz_part), "%s.part", to_fullpath_gz);
/* Open source file for read */
in = fopen(from_fullpath, PG_BINARY_R);
if (in == NULL)
elog(ERROR, "Cannot open source WAL file \"%s\": %s",
from_fullpath, strerror(errno));
/* disable stdio buffering for input file */
setvbuf(in, NULL, _IONBF, BUFSIZ);
/* Grab lock by creating temp file in exclusive mode */
out = fio_gzopen(to_fullpath_gz_part, PG_BINARY_W, compress_level, FIO_BACKUP_HOST);
if (out == NULL)
{
if (errno != EEXIST)
elog(ERROR, "Cannot open temp WAL file \"%s\": %s",
to_fullpath_gz_part, strerror(errno));
/* Already existing destination temp file is not an error condition */
}
else
goto part_opened;
/*
* Partial file already exists, it could have happened due to:
* 1. failed archive-push
* 2. concurrent archiving
*
* For ARCHIVE_TIMEOUT period we will try to create partial file
* and look for the size of already existing partial file, to
* determine if it is changing or not.
* If after ARCHIVE_TIMEOUT we still failed to create partial
* file, we will make a decision about discarding
* already existing partial file.
*/
while (partial_try_count < archive_timeout)
{
if (fio_stat(to_fullpath_gz_part, &st, false, FIO_BACKUP_HOST) < 0)
{
if (errno == ENOENT)
{
//part file is gone, lets try to grab it
out = fio_gzopen(to_fullpath_gz_part, PG_BINARY_W, compress_level, FIO_BACKUP_HOST);
if (out == NULL)
{
if (errno != EEXIST)
elog(ERROR, "Failed to open temp WAL file \"%s\": %s",
to_fullpath_gz_part, strerror(errno));
}
else
/* Successfully created partial file */
break;
}
else
elog(ERROR, "Cannot stat temp WAL file \"%s\": %s",
to_fullpath_gz_part, strerror(errno));
}
/* first round */
if (!partial_try_count)
{
elog(LOG, "Temp WAL file already exists, waiting on it %u seconds: \"%s\"",
archive_timeout, to_fullpath_gz_part);
partial_file_size = st.st_size;
}
/* file size is changing */
if (st.st_size > partial_file_size)
partial_is_stale = false;
sleep(1);
partial_try_count++;
}
/* The possible exit conditions:
* 1. File is grabbed
* 2. File is not grabbed, and it is not stale
* 2. File is not grabbed, and it is stale.
*/
/*
* If temp file was not grabbed for ARCHIVE_TIMEOUT and temp file is not stale,
* then exit with error.
*/
if (out == NULL)
{
if (!partial_is_stale)
elog(ERROR, "Failed to open temp WAL file \"%s\" in %i seconds",
to_fullpath_gz_part, archive_timeout);
/* Partial segment is considered stale, so reuse it */
elog(LOG, "Reusing stale temp WAL file \"%s\"", to_fullpath_gz_part);
fio_unlink(to_fullpath_gz_part, FIO_BACKUP_HOST);
out = fio_gzopen(to_fullpath_gz_part, PG_BINARY_W, compress_level, FIO_BACKUP_HOST);
if (out == NULL)
elog(ERROR, "Cannot open temp WAL file \"%s\": %s",
to_fullpath_gz_part, strerror(errno));
}
part_opened:
elog(VERBOSE, "Temp WAL file successfully created: \"%s\"", to_fullpath_gz_part);
/* Check if possible to skip copying,
*/
if (fileExists(to_fullpath_gz, FIO_BACKUP_HOST))
{
pg_crc32 crc32_src;
pg_crc32 crc32_dst;
/* TODO: what if one of them goes missing? */
crc32_src = fio_get_crc32(from_fullpath, FIO_DB_HOST, false);
crc32_dst = fio_get_crc32(to_fullpath_gz, FIO_BACKUP_HOST, true);
if (crc32_src == crc32_dst)
{
elog(LOG, "WAL file already exists in archive with the same "
"checksum, skip pushing: \"%s\"", from_fullpath);
/* cleanup */
fclose(in);
fio_gzclose(out);
fio_unlink(to_fullpath_gz_part, FIO_BACKUP_HOST);
return 1;
}
else
{
if (overwrite)
elog(LOG, "WAL file already exists in archive with "
"different checksum, overwriting: \"%s\"", to_fullpath_gz);
else
{
/* Overwriting is forbidden,
* so we must unlink partial file and exit with error.
*/
fio_unlink(to_fullpath_gz_part, FIO_BACKUP_HOST);
elog(ERROR, "WAL file already exists in archive with "
"different checksum: \"%s\"", to_fullpath_gz);
}
}
}
/* copy content */
/* TODO: move to separate function */
for (;;)
{
size_t read_len = 0;
read_len = fread(buf, 1, OUT_BUF_SIZE, in);
if (ferror(in))
{
fio_unlink(to_fullpath_gz_part, FIO_BACKUP_HOST);
elog(ERROR, "Cannot read from source file \"%s\": %s",
from_fullpath, strerror(errno));
}
if (read_len > 0 && fio_gzwrite(out, buf, read_len) != read_len)
{
fio_unlink(to_fullpath_gz_part, FIO_BACKUP_HOST);
elog(ERROR, "Cannot write to compressed temp WAL file \"%s\": %s",
to_fullpath_gz_part, get_gz_error(out, errno));
}
if (feof(in))
break;
}
/* close source file */
fclose(in);
/* Writing is asynchronous in case of push in remote mode, so check agent status */
if (fio_check_error_fd_gz(out, &errmsg))
{
fio_unlink(to_fullpath_gz_part, FIO_BACKUP_HOST);
elog(ERROR, "Cannot write to the remote compressed file \"%s\": %s",
to_fullpath_gz_part, errmsg);
}
/* close temp file, TODO: make it synchronous */
if (fio_gzclose(out) != 0)
{
fio_unlink(to_fullpath_gz_part, FIO_BACKUP_HOST);
elog(ERROR, "Cannot close compressed temp WAL file \"%s\": %s",
to_fullpath_gz_part, strerror(errno));
}
/* sync temp file to disk */
if (!no_sync)
{
if (fio_sync(to_fullpath_gz_part, FIO_BACKUP_HOST) != 0)
elog(ERROR, "Failed to sync file \"%s\": %s",
to_fullpath_gz_part, strerror(errno));
}
elog(VERBOSE, "Rename \"%s\" to \"%s\"",
to_fullpath_gz_part, to_fullpath_gz);
//copy_file_attributes(from_path, FIO_DB_HOST, to_path_temp, FIO_BACKUP_HOST, true);
/* Rename temp file to destination file */
if (fio_rename(to_fullpath_gz_part, to_fullpath_gz, FIO_BACKUP_HOST) < 0)
{
fio_unlink(to_fullpath_gz_part, FIO_BACKUP_HOST);
elog(ERROR, "Cannot rename file \"%s\" to \"%s\": %s",
to_fullpath_gz_part, to_fullpath_gz, strerror(errno));
}
pg_free(buf);
return 0;
}
#endif
#ifdef HAVE_LIBZ
/*
* Show error during work with compressed file
*/
static const char *
get_gz_error(gzFile gzf, int errnum)
{
int gz_errnum;
const char *errmsg;
errmsg = fio_gzerror(gzf, &gz_errnum);
if (gz_errnum == Z_ERRNO)
return strerror(errnum);
else
return errmsg;
}
#endif
/* Copy file attributes */
//static void
//copy_file_attributes(const char *from_path, fio_location from_location,
// const char *to_path, fio_location to_location,
// bool unlink_on_error)
//{
// struct stat st;
//
// if (fio_stat(from_path, &st, true, from_location) == -1)
// {
// if (unlink_on_error)
// fio_unlink(to_path, to_location);
// elog(ERROR, "Cannot stat file \"%s\": %s",
// from_path, strerror(errno));
// }
//
// if (fio_chmod(to_path, st.st_mode, to_location) == -1)
// {
// if (unlink_on_error)
// fio_unlink(to_path, to_location);
// elog(ERROR, "Cannot change mode of file \"%s\": %s",
// to_path, strerror(errno));
// }
//}
/* Look for files with '.ready' suffix in archive_status directory
* and pack such files into batch sized array.
*/
parray *
setup_push_filelist(const char *archive_status_dir, const char *first_file,
int batch_size)
{
int i;
WALSegno *xlogfile = NULL;
parray *status_files = NULL;
parray *batch_files = parray_new();
/* guarantee that first filename is in batch list */
xlogfile = palloc(sizeof(WALSegno));
pg_atomic_init_flag(&xlogfile->lock);
snprintf(xlogfile->name, MAXFNAMELEN, "%s", first_file);
parray_append(batch_files, xlogfile);
xlogfile->type = get_xlogFileType(xlogfile->name);
if (batch_size < 2)
return batch_files;
/* get list of files from archive_status */
status_files = parray_new();
dir_list_file(status_files, archive_status_dir, false, false, false, false, true, 0, FIO_DB_HOST);
parray_qsort(status_files, pgFileCompareName);
for (i = 0; i < parray_num(status_files); i++)
{
int result = 0;
char filename[MAXFNAMELEN];
char suffix[MAXFNAMELEN];
pgFile *file = (pgFile *) parray_get(status_files, i);
result = sscanf(file->name, "%[^.]%s", (char *) &filename, (char *) &suffix);
if (result != 2)
continue;