-
Notifications
You must be signed in to change notification settings - Fork 90
/
backup-manager-upload
executable file
·1219 lines (1024 loc) · 33.3 KB
/
backup-manager-upload
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
#!/usr/bin/perl
# Backup Manager Upload - Multiprotocol uploader for backup-manager.
# Copyright © 2005-2016 The Backup Manager Authors
#
# See the AUTHORS file for details.
use strict;
use warnings;
use BackupManager::Config;
use BackupManager::Dialog;
use POSIX qw(strftime);
use File::Temp qw(tempfile);
use File::Basename;
use File::stat;
use constant TRUE => 1;
use constant FALSE => 0;
use constant E_SUCCESS => 0;
use constant E_INVALID => 10;
use constant E_FTP_FAILED => 20;
use constant E_SCP_FAILED => 21;
use constant E_S3_FAILED => 22;
use constant E_UNKNOWN => 23;
# global vars
my $scp = '/usr/bin/scp';
my $ssh = '/usr/bin/ssh';
my $gpg = '/usr/bin/gpg';
my $split = '/usr/bin/split';
my $g_list = 0;
my $g_host = undef;
my $g_user = undef;
my $g_pass = undef;
my $g_ftpclean = undef;
my $g_ftptest = undef;
my $g_s3clean = undef;
my $g_s3max_size = 4*1024*1024*1024; # 4G
my $g_sshclean = undef;
my $g_protocol = 'scp';
my $g_remote_dir= '/var/archives/uploads';
my $g_bucket = undef;
my $g_root_dir = '/var/archives';
my $g_key_file = undef;
my $g_gpg_recipient = undef;
# first get the args
BackupManager::Config::getopt("$0 -m=mode -h=host -u=user [options] date\n
-v|--verbose : Print on STDOUT what happens.
-m|--mode : Transfer mode to use : ftp, scp, s3, or ssh-gpg.
-h|--host : Remote hosts to connect to (separated by commas).
-u|--user : User to use for connection.
-p|--password : remote user's password (needed for ftp and s3 uploads).
-k|--key : SSH key file to use for opening the scp session (only needed for scp mode).
-d|--directory : Directory on the remote host where files will go (default is /var/archives/uploads).
-b|--bucket : Amazon S3 storage bucket to use
-r|--root : Root directory of your archives (default /var/archives).
-l|--list : Only prints which files would be uploaded.
--gpg-recipient : Selects the public key used for gpg encryption (only for ssh-gpg mode).
--ftp-purge : Purge the remote directory before uploading files in FTP mode.
--ftp-test : Sends a test file before uploading archives in FTP mode.
--s3-purge : Purge the remote directory before uploading files in S3 mode.
--s3-maxsize : Maximum file size to upload. If file execeds this size, it will be `split`. Default is 4GB
--ssh-purge : Purge the remote directory before uploading files in SSH mode.
date : All files >= date will be uploaded. Either a valid date (YYYYMMDD) or one of this words : today, yesterday",
'verbose' => sub { init_dialog($_[1]) },
'mode|m=s' => \$g_protocol,
'host|h=s' => \$g_host,
'user|u=s' => \$g_user,
'password|p=s' => \$g_pass,
'directory|d=s' => \$g_remote_dir,
'bucket|b=s' => \$g_bucket,
'key|k=s' => \$g_key_file,
'root|r=s' => \$g_root_dir,
'gpg-recipient=s' => \$g_gpg_recipient,
'ftp-purge' => \$g_ftpclean,
'ftp-test' => \$g_ftptest,
's3-purge' => \$g_s3clean,
's3-maxsize=i' => \$g_s3max_size,
'ssh-purge' => \$g_sshclean,
'list' => \$g_list,
);
##############################################################
# Common subs (for all methods)
##############################################################
# {{{
sub get_formated_date($)
{
my $date = shift;
unless (defined $date) {
print_error "date is required, enter today, yesterday or YYYYMMDD";
exit E_INVALID;
}
if ($date eq 'today') {
return strftime ('%Y%m%d', localtime);
}
elsif ($date eq 'yesterday') {
return strftime ('%Y%m%d', localtime(time - (24 * 3600)));
}
elsif ($date =~ /^\d{4}\d{2}\d{2}$/) {
return $date;
}
else {
print_error "date $date is not valid, enter today, yesterday or YYYYMMDD";
exit E_INVALID;
}
}
# The idea behind BM_UPLOADED_ARCHIVES is to have a database of what archives
# have been uploaded so far. This allows multiple execution of upload actions
# within a day without resending all archives of the day from the beginning.
# Add one file,host pair to $BM_UPLOADED_ARCHIVES database.
# Called immediately *after* successful uploading of an archive.
sub appendto_uploaded_archives($$)
{
my $file = shift;
my $host = shift;
unless ( defined $file and defined $host ) {
print_error "required args needed";
return FALSE;
}
my $upload_fname = $ENV{BM_UPLOADED_ARCHIVES};
unless ( defined $upload_fname ) {
# Uncomment next line if you want the mandatory use
# of BM_UPLOADED_ARCHIVES (ie always have it around).
#print_error "BM_UPLOADED_ARCHIVES is not defined";
return FALSE;
}
# if $file already in database, append host to that line;
# else append a lines "$file $host" to the end.
my $io_error = 0;
if ( ! system( "grep -q \"^$file \" $upload_fname" ) ) {
my $cmd = "sed -i \"s:^$file .*\$:\& $host:\" $upload_fname";
$io_error = system("$cmd");
}
elsif ( open(my $fh, ">>", $upload_fname) ) {
print($fh "$file $host\n") or $io_error = 1;
close $fh;
}
else {
$io_error = 2;
}
if ( $io_error ) {
print_error "IO error: did not update $upload_fname with '$file $host'";
return FALSE;
}
return TRUE;
}
# Get all files of the specified date; filter the list through
# BM_UPLOADED_ARCHIVES if it is set in the environment.
# NOTE: Doing the filtering here implies that the archive is considered
# uploaded if a single upload to a host succeeds; that is even when there
# are failures to other hosts (in case of multiple host uploading).
# To consider it uploaded when all hosts succeed, the filtering must be
# transfered to the individual upload subroutines (and check for existence
# of file,host pair in the database).
#
sub get_files_list_from_date($)
{
my $date = shift;
return [] unless defined $date;
my $ra_files = [];
unless (-d $g_root_dir) {
my $msg = "root dir specified does not exists : $g_root_dir";
print_error $msg;
exit E_INVALID;
}
# make sure we can read the root dir, when the secure mode is
# enabled, the repository might not be readable by us...
unless (-r $g_root_dir) {
print_error "The repository $g_root_dir is not readable by user \"$ENV{USER}\".";
if ($ENV{BM_REPOSITORY_SECURE} eq "true") {
print_error "The secure mode is enabled (BM_REPOSITORY_SECURE),";
print_error "the upload user ($g_user) must be in the group \"BM_REPOSITORY_GROUP\".";
}
exit E_INVALID;
}
my $upload_fname = $ENV{BM_UPLOADED_ARCHIVES};
if ( defined $upload_fname ) {
# filter file list through the BM_UPLOADED_ARCHIVES database
while (<$g_root_dir/*$date*>) {
my $file = $_;
my $cmd = "grep -q '$file' $upload_fname";
if ( system ("$cmd") ) {
push @{$ra_files}, $file;
}
}
}
else {
while (<$g_root_dir/*$date*>) {
push @{$ra_files}, $_;
}
}
return $ra_files;
}
sub get_hosts_from_str($) {
my ($hosts_str) = @_;
return [] unless defined $hosts_str;
my $ra_hosts = [];
$hosts_str =~ s/\s//g;
foreach my $host (split /,/, $hosts_str) {
push @{$ra_hosts}, $host;
}
return $ra_hosts;
}
sub get_tempfile(;$) {
my ($template) = @_;
$template ||= 'bmu-XXXXXX';
return tempfile(
TEMPLATE => $template,
DIR => $ENV{BM_TEMP_DIR},
UNLINK => 1,
);
}
# }}}
##############################################################
# SSH Mode
##############################################################
# {{{
# returns all the ssh otpions needed for a valid SSH connection
sub get_ssh_opts {
# look for a port to use
my $ssh_port_switch="";
my $scp_port_switch="";
if ($ENV{BM_UPLOAD_SSH_PORT}) {
$ssh_port_switch = "-p ".$ENV{BM_UPLOAD_SSH_PORT};
$scp_port_switch = "-P ".$ENV{BM_UPLOAD_SSH_PORT};
}
# look for keyfile to use
my $keyfile_switch="";
if (defined $g_key_file and (-e $g_key_file)) {
$keyfile_switch = "-i $g_key_file";
}
elsif (! (-e $g_key_file)) {
print_error "Unable to read the SSH identity key : $g_key_file";
exit E_SCP_FAILED;
}
return {
ssh => "$ssh_port_switch $keyfile_switch -o BatchMode=yes",
scp => "$scp_port_switch $keyfile_switch -B"
};
}
# Purge remote archives over SSH
# Uses backup-manager-purge
sub ssh_clean_directory
{
my ($user, $host, $location) = @_;
return 0 unless defined $user and
defined $host and
defined $location;
my $ssh_options = get_ssh_opts->{'ssh'};
# the remote time to leave could be different as the local one.
my $BM_ARCHIVE_TTL = $ENV{BM_ARCHIVE_TTL};
if (defined $ENV{BM_UPLOAD_SSH_TTL} and
length ($ENV{BM_UPLOAD_SSH_TTL})) {
$BM_ARCHIVE_TTL = $ENV{BM_UPLOAD_SSH_TTL};
}
return 0 unless defined $BM_ARCHIVE_TTL;
print_info "Cleaning remote directory through SSH";
# First, create the list of existing archives
my ($fh, $in) = get_tempfile('ssh-archives-XXXXXX');
my $cmd = "$ssh $ssh_options $user".'@'.$host." ls $location/*";
my $buffer = `$cmd`;
print $fh $buffer;
close $fh;
my ($fh_out, $out) = get_tempfile('bm-purge-out-ssh-XXXXXX');
system("/usr/bin/backup-manager-purge --ttl=$BM_ARCHIVE_TTL --files-from=$in > $out");
open (STDOUT_CMD, $out);
while (<STDOUT_CMD>) {
chomp();
print_info "Purging $_";
$cmd = "$ssh $ssh_options $user".'@'.$host." rm -f $_";
system ("$cmd");
}
close STDOUT_CMD;
undef $fh_out;
}
# send one file with scp
# since Net::SSH is a wrapper to a system call of ssh, I don't use it.
sub send_file_with_scp($$$$$)
{
my ($file, $user, $host, $location, $g_gpg_recipient) = @_;
return 0 unless defined $file and
defined $user and
defined $host and
defined $location;
my $opts = get_ssh_opts;
my ($ssh_opts, $scp_opts) = ($opts->{'ssh'}, $opts->{'scp'});
my $cmd = "";
if ( defined $g_gpg_recipient ) {
my $file_base = basename($file);
$cmd = "$gpg --encrypt --recipient $g_gpg_recipient --output - --batch $file | ";
$cmd .= "$ssh $ssh_opts -e none $user".'@'."$host ";
$cmd .= "\"cat - > $location/$file_base.gpg\" >&2";
}
else {
$cmd = "$scp $scp_opts $file $user".'@'.$host.':'.$location." >&2";
}
# we use eval here to avoid crash with bad keys
my $ret = eval { system($cmd) };
if ($@ or $ret) {
print_error "$scp failed for $file : $@ (command was : $cmd). " if $@;
print_error "$scp failed for $file (command was : $cmd)" if $ret;
print_error ("Unable to upload \"$file\". ".($! || $@ || $ret));
return 0;
}
else {
# use same name in both cases (gpg encryption is done on the fly);
# continue if writing to uploaded archives file fails.
appendto_uploaded_archives($file, $host);
}
return 1;
}
# How to upload files with scp.
# Note that Key Authentication is used, see man ssh-keygen.
sub send_files_with_scp($$$$$)
{
# getting args
my ($user, $ra_hosts, $repository, $ra_files, $g_gpg_recipient) = @_;
unless (defined $user and
defined $ra_hosts and
defined $ra_files and
defined $repository) {
print_error "required args needed";
return FALSE;
}
# is scp here ?
unless (-x $scp) {
print_error "$scp is not here, cannot use this mode for transfer.";
return FALSE;
}
# if gpg requested, is it here?
if (defined $g_gpg_recipient and (not -x $gpg)) {
print_error "$gpg is not here, cannot use this mode for transfer.";
return FALSE;
}
# if gpg requested, check whether given key is valid
if (defined $g_gpg_recipient) {
my $gpg_out = `$gpg --batch --list-keys '$g_gpg_recipient' 2>/dev/null`;
if ($gpg_out !~ /^pub/mi) {
print_error "gpg recipient $g_gpg_recipient is not a valid key, cannot use this mode for transfer.";
return FALSE;
}
}
my $opts = get_ssh_opts;
my ($ssh_opts, $scp_opts) = ($opts->{'ssh'}, $opts->{'scp'});
# loop on each hosts given and connect to them.
foreach my $host (@{$ra_hosts}) {
# make sure the target directory exists remotely
my $ls_rep_cmd = "$ssh $ssh_opts $user\@$host \"ls $repository\" 2>/dev/null || echo notfound";
my $out = `$ls_rep_cmd`;
chomp $out;
# if failed,
if ($out eq 'notfound') {
print_info "Creating $repository on $host";
my $mkdir_rep_cmd = "$ssh $ssh_opts $user\@$host 'mkdir -p $repository' 2>/dev/null || echo failed";
$out = `$mkdir_rep_cmd`;
chomp $out;
if ($out eq 'failed') {
print_error "Unable to create $host:$repository";
return FALSE;
}
}
foreach my $file (@{$ra_files}) {
chomp $file;
if (-f $file and
send_file_with_scp($file, $user, $host,
$repository, $g_gpg_recipient)) {
print_info "File $file uploaded successfully.";
}
elsif (! -f $file) {
print_error "File $file cannot be uploaded, it does not exist locally.";
return FALSE;
}
else {
print_error "Error during the scp upload of $file";
return FALSE;
}
}
# cleaning the repo
ssh_clean_directory ($user, $host, $repository) if ($g_sshclean);
}
return TRUE;
}
# }}}
##############################################################
# FTP Mode
##############################################################
# {{{
# Function for testing upload before sending the archives
# The test file is uploaded, and its size is compared to the local file.
# If the size is correct, the test is successfull and we can continue
# with the archives.
sub ftp_upload_test_file($)
{
my $ftp = shift;
my $BM_REPOSITORY_ROOT = $ENV{BM_REPOSITORY_ROOT};
my $ftp_test_filename = "2mb_file.dat";
my $file_to_send = $BM_REPOSITORY_ROOT . "/" . $ftp_test_filename;
if (!ftp_put_file ($ftp, $file_to_send)) {
print_error "Unable to transfer $file_to_send: " . $ftp->message;
return FALSE;
}
else {
my $remote_filesize = $ftp->size($ftp_test_filename);
# Delete both test files
system("rm -f $BM_REPOSITORY_ROOT/$ftp_test_filename");
$ftp->delete($ftp_test_filename);
# Test filesize (should be 2MB)
if($remote_filesize == 2097152) {
return TRUE;
}
else {
print_error "Remote and local test files filesize mismatch";
return FALSE;
}
}
}
sub ftptls_upload_test_file($)
{
my $ftp = shift;
my $BM_REPOSITORY_ROOT = $ENV{BM_REPOSITORY_ROOT};
my $ftp_test_filename = "2mb_file.dat";
my $file_to_send = $BM_REPOSITORY_ROOT . "/" . $ftp_test_filename;
if (!ftptls_put_file ($ftp, $file_to_send)) {
print_error "Unable to transfer $file_to_send: " . $ftp->message;
return FALSE;
}
else {
my $remote_filesize = $ftp->size($ftp_test_filename);
# Delete both test files
system("rm -f $BM_REPOSITORY_ROOT/$ftp_test_filename");
$ftp->delete($ftp_test_filename);
# Test filesize (should be 2MB)
if($remote_filesize == 2097152) {
return TRUE;
}
else {
print_error "Remote and local test files filesize mismatch";
return FALSE;
}
}
}
# Function for purging a directory
# over FTP, the same way as the repository is purged.
# Every files with a date field too old according to BM_UPLOAD_FTP_TTL
# will be deleted.
sub ftp_clean_directory($)
{
my $ftp = shift;
# the remote time to leave could be different as the local one.
my $BM_ARCHIVE_TTL = $ENV{BM_ARCHIVE_TTL};
if (defined $ENV{BM_UPLOAD_FTP_TTL} and
length ($ENV{BM_UPLOAD_FTP_TTL})) {
$BM_ARCHIVE_TTL = $ENV{BM_UPLOAD_FTP_TTL};
}
return 0 unless defined $BM_ARCHIVE_TTL;
print_info "Cleaning remote directory through FTP";
# First, create the list of existing archives
my ($fh, $filename) = get_tempfile('ftp-archives-XXXXXX');
my $BM_UPLOAD_FTP_SECURE = $ENV{"BM_UPLOAD_FTP_SECURE"};
my $ra_files;
if ($BM_UPLOAD_FTP_SECURE eq "true") {
$ra_files = $ftp->list();
}
else {
$ra_files = $ftp->ls();
}
foreach my $file (@$ra_files) {
print $fh "$file\n";
}
close $fh;
# Then delete every file listed as "outaded" by backup-manager-purge
my ($fh_out, $out) = get_tempfile('bm-purge-out-ftp-XXXXXX');
system ("/usr/bin/backup-manager-purge --ttl=$BM_ARCHIVE_TTL --files-from=$filename > $out");
open (STDOUT_CMD, "<$out");
while (<STDOUT_CMD>) {
chomp();
print_info "Purging $_";
$ftp->delete ($_) or print_error "Unable to delete \"$_\".";
}
close STDOUT_CMD;
undef $fh;
return 1;
}
sub ftp_connect_to_host ($)
{
my ($host) = @_;
my $ftp;
# get the passive mode from the configuration
# default is set to true.
my $BM_UPLOAD_FTP_PASSIVE = $ENV{"BM_UPLOAD_FTP_PASSIVE"};
unless (defined $BM_UPLOAD_FTP_PASSIVE) {
$BM_UPLOAD_FTP_PASSIVE = "true";
}
if ($BM_UPLOAD_FTP_PASSIVE eq "true") {
$BM_UPLOAD_FTP_PASSIVE="1";
}
elsif ($BM_UPLOAD_FTP_PASSIVE eq "false") {
$BM_UPLOAD_FTP_PASSIVE="0";
}
else {
print_error "Unsupported value for BM_UPLOAD_FTP_PASSIVE : $BM_UPLOAD_FTP_PASSIVE";
return undef;
}
# get the log level from the configuration for debug mode
my $BM_LOGGER_LEVEL = $ENV{"BM_LOGGER_LEVEL"};
unless (defined $BM_LOGGER_LEVEL) {
$BM_LOGGER_LEVEL = "warning";
}
if ($BM_LOGGER_LEVEL eq "debug") {
$BM_LOGGER_LEVEL="1";
}
else {
$BM_LOGGER_LEVEL="0";
}
# get the timeout from the configuration
# default is set to 120.
my $BM_UPLOAD_FTP_TIMEOUT = $ENV{"BM_UPLOAD_FTP_TIMEOUT"};
unless (defined $BM_UPLOAD_FTP_TIMEOUT) {
$BM_UPLOAD_FTP_TIMEOUT = 120;
}
# trying to get Net::FTP.
eval "use Net::FTP";
if ($@) {
print_error "Net::FTP is not available, cannot use ftp transfer mode";
return undef;
}
eval {
$ftp = new Net::FTP (
$host,
Debug => $BM_LOGGER_LEVEL,
Timeout => $BM_UPLOAD_FTP_TIMEOUT,
Passive => $BM_UPLOAD_FTP_PASSIVE);
};
if ($@) {
print_error "Unable to use the Net::FTP Perl module : $@";
return undef;
}
return $ftp;
}
sub ftptls_connect_to_host ($)
{
my ($host) = @_;
my $ftp;
eval "use Net::Lite::FTP";
if ($@) {
print_error "Net::Lite::FTP is not available, cannot use ftp secured transfer mode";
return undef;
}
eval {
$ftp = Net::Lite::FTP->new ();
$ftp->open ($host, "21");
};
if ($@) {
print_error "Unable to use the Net::Lite::FTP Perl module : $@";
return undef;
}
return $ftp;
}
# How to upload files with ftp.
# We'll use the Net::FTP or the Net::Lite::FTP (for secured mode) module here.
# Net::Lite::FTP can be found here :
# http://search.cpan.org/~eyck/Net-Lite-FTP-0.61/lib/Net/Lite/FTP.pm
sub send_files_with_ftp($$$$$)
{
# getting args
my ($user, $passwd, $ra_hosts, $repository, $ra_files) = @_;
unless (defined $user and
defined $passwd and
defined $ra_hosts and
defined $ra_files and
defined $repository) {
print_error "required args needed";
return FALSE;
}
# get the secure mode from the configuration
# default is set to false.
my $BM_UPLOAD_FTP_SECURE = $ENV{"BM_UPLOAD_FTP_SECURE"};
unless (defined $BM_UPLOAD_FTP_SECURE) {
$BM_UPLOAD_FTP_SECURE = "false";
}
if ($BM_UPLOAD_FTP_SECURE eq "true") {
$BM_UPLOAD_FTP_SECURE="1";
}
elsif ($BM_UPLOAD_FTP_SECURE eq "false") {
$BM_UPLOAD_FTP_SECURE="0";
}
else {
print_error "Unsupported value for BM_UPLOAD_FTP_SECURE : $BM_UPLOAD_FTP_SECURE";
return FALSE;
}
# loop on each hosts given and connect to them.
foreach my $host (@{$ra_hosts}) {
my $ftp;
$ftp = ftp_connect_to_host ($host);
unless (defined $ftp) {
print_error "Unable to connect to host: $host";
return FALSE;
}
if ($BM_UPLOAD_FTP_SECURE) {
unless ($ftp->starttls()) {
print_error "Unable to start TLS connection on host: $host";
return FALSE;
}
}
unless (ftp_login($ftp, $user, $passwd)) {
print_error "Unable to login on ${host} in FTP mode.";
return FALSE;
}
unless (ftp_cwd($ftp, $repository)) {
print_info "The directory ${repository} does not exist, trying to create it.";
unless (ftp_mkdir($ftp, $repository)) {
print_error "Unable to create directory ${repository} in FTP mode: " . $ftp->message;
return FALSE;
}
}
print_info "Logged on $host, in $repository (FTP binary mode)";
# Now that we're connected and logged in, test an upload if needed
if ($g_ftptest) {
if ($BM_UPLOAD_FTP_SECURE) {
if (!ftptls_upload_test_file($ftp)) {
print_error "Unable to transfer test file";
return FALSE;
}
else {
print_info "Test file transferred\n";
}
}
else {
if (!ftp_upload_test_file($ftp)) {
print_error "Unable to transfer test file";
return FALSE;
}
else {
print_info "Test file transferred\n";
}
}
}
# Now that we're connected and logged in, purge the repo if needed
if ($g_ftpclean) {
unless (ftp_clean_directory($ftp)) {
print_error "Unable to clean the FTP directory.";
}
}
# Put all the files over the connection
foreach my $file (@{$ra_files}) {
chomp $file;
# continue if writing to uploaded archives file fails.
if ($BM_UPLOAD_FTP_SECURE) {
if (ftptls_put_file ($ftp, $file)) {
appendto_uploaded_archives($file, $host);
print_info "File $file transfered\n";
}
else {
print_error "Unable to transfer $file";
return FALSE;
}
}
else {
if (ftp_put_file ($ftp, $file)) {
appendto_uploaded_archives($file, $host);
print_info "File $file transfered\n";
}
else {
print_error "Unable to transfer $file: " . $ftp->message;
return FALSE;
}
}
}
print_info "All transfers done, logging out from $host\n";
$ftp->quit;
}
return TRUE;
}
sub ftp_login ($$$)
{
my ($ftp, $user, $passwd) = @_;
return ($ftp->login($user, $passwd) and
$ftp->binary());
}
sub ftptls_login ($$$)
{
my ($ftp, $user, $passwd) = @_;
return ($ftp->user($user) and
$ftp->pass($passwd));
}
sub ftp_cwd ($$)
{
my ($ftp, $repository) = @_;
return ($ftp->cwd($repository));
}
sub ftptls_cwd ($$)
{
my ($ftp, $repository) = @_;
return ($ftp->cwd($repository));
}
sub ftp_mkdir ($$)
{
my ($ftp, $repository) = @_;
return ($ftp->mkdir($repository));
}
sub ftptls_mkdir ($$)
{
my ($ftp, $repository) = @_;
return ($ftp->mkdir($repository));
}
sub ftp_put_file ($$)
{
my ($ftp, $file) = @_;
return $ftp->put ($file);
}
sub ftptls_put_file ($$)
{
my ($ftp, $file) = @_;
my $basename = basename ($file);
return $ftp->put ($basename, $file);
}
# }}}
##############################################################
# Amazon S3 Mode
##############################################################
# {{{
# Function for purging a directory
# from S3, the same way as the repository is purged.
# Every files with a date field too old according to BM_ARCHIVE_TTL
# will be deleted.
sub s3_clean_directory($)
{
my ($bucket) = @_;
my $BM_ARCHIVE_TTL = $ENV{BM_ARCHIVE_TTL};
if (defined $ENV{BM_UPLOAD_S3_TTL} and
length ($ENV{BM_UPLOAD_S3_TTL})) {
$BM_ARCHIVE_TTL = $ENV{BM_UPLOAD_S3_TTL};
}
return 0 unless defined $BM_ARCHIVE_TTL;
my $date_to_remove = `date +%Y%m%d --date "$BM_ARCHIVE_TTL days ago"`;
chomp $date_to_remove;
my $response = $bucket->list;
my @keys = @{ $response->{keys} };
foreach my $key (@keys) {
my $date = undef;
if ($key->{key} =~ /[\.\-](\d{8})\./) {
$date = $1;
if ($date and ($date <= $date_to_remove)) {
print_info $key->{key} . " has to be deleted, too old ($date <= $date_to_remove).";
$bucket->delete_key( $key->{key} );
}
}
}
return 1;
}
# How to upload files to s3.
# We'll use the Net::Amazon::S3 module here.
sub send_files_with_s3($$$$$$)
{
# trying to get Net::Amazon::S3.
eval "use Net::Amazon::S3";
if ($@) {
print_error "Net::Amazon::S3 is not available, cannot use S3 service : $@";
return FALSE;
}
if ($Net::Amazon::S3::VERSION < '0.39') {
print_error "Net::Amazon::S3 >= 0.39 is required, but version ${Net::Amazon::S3::VERSION} was found, cannot use S3 service";
return FALSE;
}
# getting args
my ($user, $passwd, $bucket, $ra_hosts, $repository, $ra_files) = @_;
unless (defined $user and
defined $passwd and
defined $bucket and
defined $ra_hosts and
defined $ra_files and
defined $repository) {
print_error "required args needed";
return FALSE;
}
my $totalbytes = 0;
my $starttime = time();
my %uploaded;
my $backup_bucket;
# loop on each hosts given and connect to them.
foreach my $host (@{$ra_hosts}) {
my $s3 = Net::Amazon::S3->new(
{
aws_access_key_id => $user,
aws_secret_access_key => $passwd,
timeout => 300
}
);
unless (defined $s3) {
print_error "Unable to connect to $host : $@\n";
return FALSE;
}
print_info "Connected to $host";
my $bucket_obj = $s3->bucket($bucket);
my $response = $bucket_obj->list;
if (not ( $response->{bucket} ) ) {
print_info "Bucket $bucket does not exist... creating";
$bucket_obj = $s3->add_bucket( { bucket => $bucket } );
print_error "Could not create bucket $bucket" if not ( $bucket_obj );
}
s3_clean_directory($bucket_obj) if ($g_s3clean);
foreach my $file (@{$ra_files}) {
chomp $file;
my @splits = $file;
if( stat($file)->size > $g_s3max_size ) {
my $split_prefix = "$file-split-";
my $cmd = "$split -b $g_s3max_size $file $split_prefix";
if( system($cmd) != 0 ) {
print_error "Could not run '$cmd' to split $file into chunks of size $g_s3max_size";
next;
} else {
@splits = glob("$split_prefix*");
}
}
for my $split (@splits) {
my $filename = basename($split);
my $file_length = stat($split)->size;
print_info "opened $split of length $file_length and will name the key $filename";
$totalbytes += $file_length;
$bucket_obj->add_key_filename(
$filename, $split,
{
content_type => "application/binary"
}
);
$uploaded{$filename} = $file_length;
}
# For the S3 method, we assume success in any case.
appendto_uploaded_archives($file, $host);
}
# get a list of files and confirm uploads
$response = $bucket_obj->list;
my @keys = @{ $response->{keys} };
foreach my $key ( @keys ) {
if (not defined $uploaded{$key->{key}}) {
next;
}
if ($key->{size} == $uploaded{$key->{key}}) {
print_info $key->{key} . " uploaded sucessfully";
delete $uploaded{$key->{key}};
}
else {
print_error $key->{key} . " did not upload sucessfully. S3 reports $key is " . $key->{size} . " bytes rather than " . $uploaded{$key->{key}};
delete $uploaded{$key->{key}};
return FALSE;
}
}
}
print_info ("Uploaded $totalbytes bytes of data to S3 in "
. (time() - $starttime) . " seconds");
return TRUE;
}
# }}}
##############################################################
# Main
##############################################################
# {{{
# date is always the last args.
my $date = $ARGV[$#ARGV];
$date = 'today' if (not defined $date or $date =~ /^-/);
# the really needed args !
unless (defined $g_host and
defined $g_user and
defined $g_protocol) {
print $BackupManager::Config::usage, "\n";
exit E_INVALID;
}
if ($g_protocol eq 'ftp' and not defined $g_pass) {
# try to read the password from the environment
if (defined $ENV{BM_UPLOAD_FTP_PASSWORD}) {
$g_pass = $ENV{BM_UPLOAD_FTP_PASSWORD};
}
else {
print $BackupManager::Config::usage, "\n";
exit E_INVALID;
}
}
if ($g_protocol eq 's3' and (not defined $g_bucket or not defined $g_pass)) {
if (! defined $g_pass && defined $ENV{BM_UPLOAD_S3_SECRET_KEY}) {
$g_pass = $ENV{BM_UPLOAD_S3_SECRET_KEY};
}
else {