/backup-manager-upload

http://github.com/sukria/Backup-Manager · Perl · 1238 lines · 921 code · 184 blank · 133 comment · 112 complexity · 7f520a2b61382d37fcbb21133683b83e MD5 · raw file

  1. #!/usr/bin/perl
  2. # Backup Manager Upload - Multiprotocol uploader for backup-manager.
  3. # Copyright Š 2005-2016 The Backup Manager Authors
  4. #
  5. # See the AUTHORS file for details.
  6. use strict;
  7. use warnings;
  8. use BackupManager::Config;
  9. use BackupManager::Dialog;
  10. use POSIX qw(strftime);
  11. use File::Temp qw(tempfile);
  12. use File::Basename;
  13. use File::stat;
  14. use constant TRUE => 1;
  15. use constant FALSE => 0;
  16. use constant E_SUCCESS => 0;
  17. use constant E_INVALID => 10;
  18. use constant E_FTP_FAILED => 20;
  19. use constant E_SCP_FAILED => 21;
  20. use constant E_S3_FAILED => 22;
  21. use constant E_UNKNOWN => 23;
  22. # global vars
  23. my $scp = '/usr/bin/scp';
  24. my $ssh = '/usr/bin/ssh';
  25. my $gpg = '/usr/bin/gpg';
  26. my $split = '/usr/bin/split';
  27. my $g_list = 0;
  28. my $g_host = undef;
  29. my $g_user = undef;
  30. my $g_pass = undef;
  31. my $g_ftpclean = undef;
  32. my $g_ftptest = undef;
  33. my $g_s3clean = undef;
  34. my $g_s3max_size = 4*1024*1024*1024; # 4G
  35. my $g_sshclean = undef;
  36. my $g_protocol = 'scp';
  37. my $g_remote_dir= '/var/archives/uploads';
  38. my $g_bucket = undef;
  39. my $g_root_dir = '/var/archives';
  40. my $g_key_file = undef;
  41. my $g_gpg_recipient = undef;
  42. # first get the args
  43. BackupManager::Config::getopt("$0 -m=mode -h=host -u=user [options] date\n
  44. -v|--verbose : Print on STDOUT what happens.
  45. -m|--mode : Transfer mode to use : ftp, scp, s3, or ssh-gpg.
  46. -h|--host : Remote hosts to connect to (separated by commas).
  47. -u|--user : User to use for connection.
  48. -p|--password : remote user's password (needed for ftp and s3 uploads).
  49. -k|--key : SSH key file to use for opening the scp session (only needed for scp mode).
  50. -d|--directory : Directory on the remote host where files will go (default is /var/archives/uploads).
  51. -b|--bucket : Amazon S3 storage bucket to use
  52. -r|--root : Root directory of your archives (default /var/archives).
  53. -l|--list : Only prints which files would be uploaded.
  54. --gpg-recipient : Selects the public key used for gpg encryption (only for ssh-gpg mode).
  55. --ftp-purge : Purge the remote directory before uploading files in FTP mode.
  56. --ftp-test : Sends a test file before uploading archives in FTP mode.
  57. --s3-purge : Purge the remote directory before uploading files in S3 mode.
  58. --s3-maxsize : Maximum file size to upload. If file execeds this size, it will be `split`. Default is 4GB
  59. --ssh-purge : Purge the remote directory before uploading files in SSH mode.
  60. date : All files >= date will be uploaded. Either a valid date (YYYYMMDD) or one of this words : today, yesterday",
  61. 'verbose' => sub { init_dialog($_[1]) },
  62. 'mode|m=s' => \$g_protocol,
  63. 'host|h=s' => \$g_host,
  64. 'user|u=s' => \$g_user,
  65. 'password|p=s' => \$g_pass,
  66. 'directory|d=s' => \$g_remote_dir,
  67. 'bucket|b=s' => \$g_bucket,
  68. 'key|k=s' => \$g_key_file,
  69. 'root|r=s' => \$g_root_dir,
  70. 'gpg-recipient=s' => \$g_gpg_recipient,
  71. 'ftp-purge' => \$g_ftpclean,
  72. 'ftp-test' => \$g_ftptest,
  73. 's3-purge' => \$g_s3clean,
  74. 's3-maxsize=i' => \$g_s3max_size,
  75. 'ssh-purge' => \$g_sshclean,
  76. 'list' => \$g_list,
  77. );
  78. ##############################################################
  79. # Common subs (for all methods)
  80. ##############################################################
  81. # {{{
  82. sub get_formated_date($)
  83. {
  84. my $date = shift;
  85. unless (defined $date) {
  86. print_error "date is required, enter today, yesterday or YYYYMMDD";
  87. exit E_INVALID;
  88. }
  89. if ($date eq 'today') {
  90. return strftime ('%Y%m%d', localtime);
  91. }
  92. elsif ($date eq 'yesterday') {
  93. return strftime ('%Y%m%d', localtime(time - (24 * 3600)));
  94. }
  95. elsif ($date =~ /^\d{4}\d{2}\d{2}$/) {
  96. return $date;
  97. }
  98. else {
  99. print_error "date $date is not valid, enter today, yesterday or YYYYMMDD";
  100. exit E_INVALID;
  101. }
  102. }
  103. # The idea behind BM_UPLOADED_ARCHIVES is to have a database of what archives
  104. # have been uploaded so far. This allows multiple execution of upload actions
  105. # within a day without resending all archives of the day from the beginning.
  106. # Add one file,host pair to $BM_UPLOADED_ARCHIVES database.
  107. # Called immediately *after* successful uploading of an archive.
  108. sub appendto_uploaded_archives($$)
  109. {
  110. my $file = shift;
  111. my $host = shift;
  112. unless ( defined $file and defined $host ) {
  113. print_error "required args needed";
  114. return FALSE;
  115. }
  116. my $upload_fname = $ENV{BM_UPLOADED_ARCHIVES};
  117. unless ( defined $upload_fname ) {
  118. # Uncomment next line if you want the mandatory use
  119. # of BM_UPLOADED_ARCHIVES (ie always have it around).
  120. #print_error "BM_UPLOADED_ARCHIVES is not defined";
  121. return FALSE;
  122. }
  123. # if $file already in database, append host to that line;
  124. # else append a lines "$file $host" to the end.
  125. my $io_error = 0;
  126. if ( ! system( "grep -q \"^$file \" $upload_fname" ) ) {
  127. my $cmd = "sed -i \"s:^$file .*\$:\& $host:\" $upload_fname";
  128. $io_error = system("$cmd");
  129. }
  130. elsif ( open(my $fh, ">>", $upload_fname) ) {
  131. print($fh "$file $host\n") or $io_error = 1;
  132. close $fh;
  133. }
  134. else {
  135. $io_error = 2;
  136. }
  137. if ( $io_error ) {
  138. print_error "IO error: did not update $upload_fname with '$file $host'";
  139. return FALSE;
  140. }
  141. return TRUE;
  142. }
  143. # Get all files of the specified date; filter the list through
  144. # BM_UPLOADED_ARCHIVES if it is set in the environment.
  145. # NOTE: Doing the filtering here implies that the archive is considered
  146. # uploaded if a single upload to a host succeeds; that is even when there
  147. # are failures to other hosts (in case of multiple host uploading).
  148. # To consider it uploaded when all hosts succeed, the filtering must be
  149. # transfered to the individual upload subroutines (and check for existence
  150. # of file,host pair in the database).
  151. #
  152. sub get_files_list_from_date($)
  153. {
  154. my $date = shift;
  155. return [] unless defined $date;
  156. my $ra_files = [];
  157. unless (-d $g_root_dir) {
  158. my $msg = "root dir specified does not exists : $g_root_dir";
  159. print_error $msg;
  160. exit E_INVALID;
  161. }
  162. # make sure we can read the root dir, when the secure mode is
  163. # enabled, the repository might not be readable by us...
  164. unless (-r $g_root_dir) {
  165. print_error "The repository $g_root_dir is not readable by user \"$ENV{USER}\".";
  166. if ($ENV{BM_REPOSITORY_SECURE} eq "true") {
  167. print_error "The secure mode is enabled (BM_REPOSITORY_SECURE),";
  168. print_error "the upload user ($g_user) must be in the group \"BM_REPOSITORY_GROUP\".";
  169. }
  170. exit E_INVALID;
  171. }
  172. my $upload_fname = $ENV{BM_UPLOADED_ARCHIVES};
  173. if ( defined $upload_fname ) {
  174. # filter file list through the BM_UPLOADED_ARCHIVES database
  175. while (<$g_root_dir/*$date*>) {
  176. my $file = $_;
  177. my $cmd = "grep -q '$file' $upload_fname";
  178. if ( system ("$cmd") ) {
  179. push @{$ra_files}, $file;
  180. }
  181. }
  182. }
  183. else {
  184. while (<$g_root_dir/*$date*>) {
  185. push @{$ra_files}, $_;
  186. }
  187. }
  188. return $ra_files;
  189. }
  190. sub get_hosts_from_str($) {
  191. my ($hosts_str) = @_;
  192. return [] unless defined $hosts_str;
  193. my $ra_hosts = [];
  194. $hosts_str =~ s/\s//g;
  195. foreach my $host (split /,/, $hosts_str) {
  196. push @{$ra_hosts}, $host;
  197. }
  198. return $ra_hosts;
  199. }
  200. sub get_tempfile(;$) {
  201. my ($template) = @_;
  202. $template ||= 'bmu-XXXXXX';
  203. return tempfile(
  204. TEMPLATE => $template,
  205. DIR => $ENV{BM_TEMP_DIR},
  206. UNLINK => 1,
  207. );
  208. }
  209. # }}}
  210. ##############################################################
  211. # SSH Mode
  212. ##############################################################
  213. # {{{
  214. # returns all the ssh otpions needed for a valid SSH connection
  215. sub get_ssh_opts {
  216. # look for a port to use
  217. my $ssh_port_switch="";
  218. my $scp_port_switch="";
  219. if ($ENV{BM_UPLOAD_SSH_PORT}) {
  220. $ssh_port_switch = "-p ".$ENV{BM_UPLOAD_SSH_PORT};
  221. $scp_port_switch = "-P ".$ENV{BM_UPLOAD_SSH_PORT};
  222. }
  223. # look for keyfile to use
  224. my $keyfile_switch="";
  225. if (defined $g_key_file and (-e $g_key_file)) {
  226. $keyfile_switch = "-i $g_key_file";
  227. }
  228. elsif (! (-e $g_key_file)) {
  229. print_error "Unable to read the SSH identity key : $g_key_file";
  230. exit E_SCP_FAILED;
  231. }
  232. return {
  233. ssh => "$ssh_port_switch $keyfile_switch -o BatchMode=yes",
  234. scp => "$scp_port_switch $keyfile_switch -B"
  235. };
  236. }
  237. # Purge remote archives over SSH
  238. # Uses backup-manager-purge
  239. sub ssh_clean_directory
  240. {
  241. my ($user, $host, $location) = @_;
  242. return 0 unless defined $user and
  243. defined $host and
  244. defined $location;
  245. my $ssh_options = get_ssh_opts->{'ssh'};
  246. # the remote time to leave could be different as the local one.
  247. my $BM_ARCHIVE_TTL = $ENV{BM_ARCHIVE_TTL};
  248. if (defined $ENV{BM_UPLOAD_SSH_TTL} and
  249. length ($ENV{BM_UPLOAD_SSH_TTL})) {
  250. $BM_ARCHIVE_TTL = $ENV{BM_UPLOAD_SSH_TTL};
  251. }
  252. return 0 unless defined $BM_ARCHIVE_TTL;
  253. print_info "Cleaning remote directory through SSH";
  254. # First, create the list of existing archives
  255. my ($fh, $in) = get_tempfile('ssh-archives-XXXXXX');
  256. my $cmd = "$ssh $ssh_options $user".'@'.$host." ls $location/*";
  257. my $buffer = `$cmd`;
  258. print $fh $buffer;
  259. close $fh;
  260. my ($fh_out, $out) = get_tempfile('bm-purge-out-ssh-XXXXXX');
  261. system("/usr/bin/backup-manager-purge --ttl=$BM_ARCHIVE_TTL --files-from=$in > $out");
  262. open (STDOUT_CMD, $out);
  263. while (<STDOUT_CMD>) {
  264. chomp();
  265. print_info "Purging $_";
  266. $cmd = "$ssh $ssh_options $user".'@'.$host." rm -f $_";
  267. system ("$cmd");
  268. }
  269. close STDOUT_CMD;
  270. undef $fh_out;
  271. }
  272. # send one file with scp
  273. # since Net::SSH is a wrapper to a system call of ssh, I don't use it.
  274. sub send_file_with_scp($$$$$)
  275. {
  276. my ($file, $user, $host, $location, $g_gpg_recipient) = @_;
  277. return 0 unless defined $file and
  278. defined $user and
  279. defined $host and
  280. defined $location;
  281. my $opts = get_ssh_opts;
  282. my ($ssh_opts, $scp_opts) = ($opts->{'ssh'}, $opts->{'scp'});
  283. my $cmd = "";
  284. if ( defined $g_gpg_recipient ) {
  285. my $file_base = basename($file);
  286. $cmd = "$gpg --encrypt --recipient $g_gpg_recipient --output - --batch $file | ";
  287. $cmd .= "$ssh $ssh_opts -e none $user".'@'."$host ";
  288. $cmd .= "\"cat - > $location/$file_base.gpg\" >&2";
  289. }
  290. else {
  291. $cmd = "$scp $scp_opts $file $user".'@'.$host.':'.$location." >&2";
  292. }
  293. # we use eval here to avoid crash with bad keys
  294. my $ret = eval { system($cmd) };
  295. if ($@ or $ret) {
  296. print_error "$scp failed for $file : $@ (command was : $cmd). " if $@;
  297. print_error "$scp failed for $file (command was : $cmd)" if $ret;
  298. print_error ("Unable to upload \"$file\". ".($! || $@ || $ret));
  299. return 0;
  300. }
  301. else {
  302. # use same name in both cases (gpg encryption is done on the fly);
  303. # continue if writing to uploaded archives file fails.
  304. appendto_uploaded_archives($file, $host);
  305. }
  306. return 1;
  307. }
  308. # How to upload files with scp.
  309. # Note that Key Authentication is used, see man ssh-keygen.
  310. sub send_files_with_scp($$$$$)
  311. {
  312. # getting args
  313. my ($user, $ra_hosts, $repository, $ra_files, $g_gpg_recipient) = @_;
  314. unless (defined $user and
  315. defined $ra_hosts and
  316. defined $ra_files and
  317. defined $repository) {
  318. print_error "required args needed";
  319. return FALSE;
  320. }
  321. # is scp here ?
  322. unless (-x $scp) {
  323. print_error "$scp is not here, cannot use this mode for transfer.";
  324. return FALSE;
  325. }
  326. # if gpg requested, is it here?
  327. if (defined $g_gpg_recipient and (not -x $gpg)) {
  328. print_error "$gpg is not here, cannot use this mode for transfer.";
  329. return FALSE;
  330. }
  331. # if gpg requested, check whether given key is valid
  332. if (defined $g_gpg_recipient) {
  333. my $gpg_out = `$gpg --batch --list-keys '$g_gpg_recipient' 2>/dev/null`;
  334. if ($gpg_out !~ /^pub/mi) {
  335. print_error "gpg recipient $g_gpg_recipient is not a valid key, cannot use this mode for transfer.";
  336. return FALSE;
  337. }
  338. }
  339. my $opts = get_ssh_opts;
  340. my ($ssh_opts, $scp_opts) = ($opts->{'ssh'}, $opts->{'scp'});
  341. # loop on each hosts given and connect to them.
  342. foreach my $host (@{$ra_hosts}) {
  343. # make sure the target directory exists remotely
  344. my $ls_rep_cmd = "$ssh $ssh_opts $user\@$host \"ls $repository\" 2>/dev/null || echo notfound";
  345. my $out = `$ls_rep_cmd`;
  346. chomp $out;
  347. # if failed,
  348. if ($out eq 'notfound') {
  349. print_info "Creating $repository on $host";
  350. my $mkdir_rep_cmd = "$ssh $ssh_opts $user\@$host 'mkdir -p $repository' 2>/dev/null || echo failed";
  351. $out = `$mkdir_rep_cmd`;
  352. chomp $out;
  353. if ($out eq 'failed') {
  354. print_error "Unable to create $host:$repository";
  355. return FALSE;
  356. }
  357. }
  358. foreach my $file (@{$ra_files}) {
  359. chomp $file;
  360. if (-f $file and
  361. send_file_with_scp($file, $user, $host,
  362. $repository, $g_gpg_recipient)) {
  363. print_info "File $file uploaded successfully.";
  364. }
  365. elsif (! -f $file) {
  366. print_error "File $file cannot be uploaded, it does not exist locally.";
  367. return FALSE;
  368. }
  369. else {
  370. print_error "Error during the scp upload of $file";
  371. return FALSE;
  372. }
  373. }
  374. # cleaning the repo
  375. ssh_clean_directory ($user, $host, $repository) if ($g_sshclean);
  376. }
  377. return TRUE;
  378. }
  379. # }}}
  380. ##############################################################
  381. # FTP Mode
  382. ##############################################################
  383. # {{{
  384. # Function for testing upload before sending the archives
  385. # The test file is uploaded, and its size is compared to the local file.
  386. # If the size is correct, the test is successfull and we can continue
  387. # with the archives.
  388. sub ftp_upload_test_file($)
  389. {
  390. my $ftp = shift;
  391. my $BM_REPOSITORY_ROOT = $ENV{BM_REPOSITORY_ROOT};
  392. my $ftp_test_filename = "2mb_file.dat";
  393. my $file_to_send = $BM_REPOSITORY_ROOT . "/" . $ftp_test_filename;
  394. if (!ftp_put_file ($ftp, $file_to_send)) {
  395. print_error "Unable to transfer $file_to_send: " . $ftp->message;
  396. return FALSE;
  397. }
  398. else {
  399. my $remote_filesize = $ftp->size($ftp_test_filename);
  400. # Delete both test files
  401. system("rm -f $BM_REPOSITORY_ROOT/$ftp_test_filename");
  402. $ftp->delete($ftp_test_filename);
  403. # Test filesize (should be 2MB)
  404. if($remote_filesize == 2097152) {
  405. return TRUE;
  406. }
  407. else {
  408. print_error "Remote and local test files filesize mismatch";
  409. return FALSE;
  410. }
  411. }
  412. }
  413. sub ftptls_upload_test_file($)
  414. {
  415. my $ftp = shift;
  416. my $BM_REPOSITORY_ROOT = $ENV{BM_REPOSITORY_ROOT};
  417. my $ftp_test_filename = "2mb_file.dat";
  418. my $file_to_send = $BM_REPOSITORY_ROOT . "/" . $ftp_test_filename;
  419. if (!ftptls_put_file ($ftp, $file_to_send)) {
  420. print_error "Unable to transfer $file_to_send: " . $ftp->message;
  421. return FALSE;
  422. }
  423. else {
  424. my $remote_filesize = $ftp->size($ftp_test_filename);
  425. # Delete both test files
  426. system("rm -f $BM_REPOSITORY_ROOT/$ftp_test_filename");
  427. $ftp->delete($ftp_test_filename);
  428. # Test filesize (should be 2MB)
  429. if($remote_filesize == 2097152) {
  430. return TRUE;
  431. }
  432. else {
  433. print_error "Remote and local test files filesize mismatch";
  434. return FALSE;
  435. }
  436. }
  437. }
  438. # Function for purging a directory
  439. # over FTP, the same way as the repository is purged.
  440. # Every files with a date field too old according to BM_UPLOAD_FTP_TTL
  441. # will be deleted.
  442. sub ftp_clean_directory($)
  443. {
  444. my $ftp = shift;
  445. # the remote time to leave could be different as the local one.
  446. my $BM_ARCHIVE_TTL = $ENV{BM_ARCHIVE_TTL};
  447. if (defined $ENV{BM_UPLOAD_FTP_TTL} and
  448. length ($ENV{BM_UPLOAD_FTP_TTL})) {
  449. $BM_ARCHIVE_TTL = $ENV{BM_UPLOAD_FTP_TTL};
  450. }
  451. return 0 unless defined $BM_ARCHIVE_TTL;
  452. print_info "Cleaning remote directory through FTP";
  453. # First, create the list of existing archives
  454. my ($fh, $filename) = get_tempfile('ftp-archives-XXXXXX');
  455. my $BM_UPLOAD_FTP_SECURE = $ENV{"BM_UPLOAD_FTP_SECURE"};
  456. my $ra_files;
  457. if ($BM_UPLOAD_FTP_SECURE eq "true") {
  458. $ra_files = $ftp->list();
  459. }
  460. else {
  461. $ra_files = $ftp->ls();
  462. }
  463. foreach my $file (@$ra_files) {
  464. print $fh "$file\n";
  465. }
  466. close $fh;
  467. # Then delete every file listed as "outaded" by backup-manager-purge
  468. my ($fh_out, $out) = get_tempfile('bm-purge-out-ftp-XXXXXX');
  469. system ("/usr/bin/backup-manager-purge --ttl=$BM_ARCHIVE_TTL --files-from=$filename > $out");
  470. open (STDOUT_CMD, "<$out");
  471. while (<STDOUT_CMD>) {
  472. chomp();
  473. print_info "Purging $_";
  474. $ftp->delete ($_) or print_error "Unable to delete \"$_\".";
  475. }
  476. close STDOUT_CMD;
  477. undef $fh;
  478. return 1;
  479. }
  480. sub ftp_connect_to_host ($)
  481. {
  482. my ($host) = @_;
  483. my $ftp;
  484. # get the passive mode from the configuration
  485. # default is set to true.
  486. my $BM_UPLOAD_FTP_PASSIVE = $ENV{"BM_UPLOAD_FTP_PASSIVE"};
  487. unless (defined $BM_UPLOAD_FTP_PASSIVE) {
  488. $BM_UPLOAD_FTP_PASSIVE = "true";
  489. }
  490. if ($BM_UPLOAD_FTP_PASSIVE eq "true") {
  491. $BM_UPLOAD_FTP_PASSIVE="1";
  492. }
  493. elsif ($BM_UPLOAD_FTP_PASSIVE eq "false") {
  494. $BM_UPLOAD_FTP_PASSIVE="0";
  495. }
  496. else {
  497. print_error "Unsupported value for BM_UPLOAD_FTP_PASSIVE : $BM_UPLOAD_FTP_PASSIVE";
  498. return undef;
  499. }
  500. # get the log level from the configuration for debug mode
  501. my $BM_LOGGER_LEVEL = $ENV{"BM_LOGGER_LEVEL"};
  502. unless (defined $BM_LOGGER_LEVEL) {
  503. $BM_LOGGER_LEVEL = "warning";
  504. }
  505. if ($BM_LOGGER_LEVEL eq "debug") {
  506. $BM_LOGGER_LEVEL="1";
  507. }
  508. else {
  509. $BM_LOGGER_LEVEL="0";
  510. }
  511. # get the timeout from the configuration
  512. # default is set to 120.
  513. my $BM_UPLOAD_FTP_TIMEOUT = $ENV{"BM_UPLOAD_FTP_TIMEOUT"};
  514. unless (defined $BM_UPLOAD_FTP_TIMEOUT) {
  515. $BM_UPLOAD_FTP_TIMEOUT = 120;
  516. }
  517. # trying to get Net::FTP.
  518. eval "use Net::FTP";
  519. if ($@) {
  520. print_error "Net::FTP is not available, cannot use ftp transfer mode";
  521. return undef;
  522. }
  523. eval {
  524. $ftp = new Net::FTP (
  525. $host,
  526. Debug => $BM_LOGGER_LEVEL,
  527. Timeout => $BM_UPLOAD_FTP_TIMEOUT,
  528. Passive => $BM_UPLOAD_FTP_PASSIVE);
  529. };
  530. if ($@) {
  531. print_error "Unable to use the Net::FTP Perl module : $@";
  532. return undef;
  533. }
  534. return $ftp;
  535. }
  536. sub ftptls_connect_to_host ($)
  537. {
  538. my ($host) = @_;
  539. my $ftp;
  540. eval "use Net::Lite::FTP";
  541. if ($@) {
  542. print_error "Net::Lite::FTP is not available, cannot use ftp secured transfer mode";
  543. return undef;
  544. }
  545. eval {
  546. $ftp = Net::Lite::FTP->new ();
  547. $ftp->open ($host, "21");
  548. };
  549. if ($@) {
  550. print_error "Unable to use the Net::Lite::FTP Perl module : $@";
  551. return undef;
  552. }
  553. return $ftp;
  554. }
  555. # How to upload files with ftp.
  556. # We'll use the Net::FTP or the Net::Lite::FTP (for secured mode) module here.
  557. # Net::Lite::FTP can be found here :
  558. # http://search.cpan.org/~eyck/Net-Lite-FTP-0.61/lib/Net/Lite/FTP.pm
  559. sub send_files_with_ftp($$$$$)
  560. {
  561. # getting args
  562. my ($user, $passwd, $ra_hosts, $repository, $ra_files) = @_;
  563. unless (defined $user and
  564. defined $passwd and
  565. defined $ra_hosts and
  566. defined $ra_files and
  567. defined $repository) {
  568. print_error "required args needed";
  569. return FALSE;
  570. }
  571. # get the secure mode from the configuration
  572. # default is set to false.
  573. my $BM_UPLOAD_FTP_SECURE = $ENV{"BM_UPLOAD_FTP_SECURE"};
  574. unless (defined $BM_UPLOAD_FTP_SECURE) {
  575. $BM_UPLOAD_FTP_SECURE = "false";
  576. }
  577. if ($BM_UPLOAD_FTP_SECURE eq "true") {
  578. $BM_UPLOAD_FTP_SECURE="1";
  579. }
  580. elsif ($BM_UPLOAD_FTP_SECURE eq "false") {
  581. $BM_UPLOAD_FTP_SECURE="0";
  582. }
  583. else {
  584. print_error "Unsupported value for BM_UPLOAD_FTP_SECURE : $BM_UPLOAD_FTP_SECURE";
  585. return FALSE;
  586. }
  587. # loop on each hosts given and connect to them.
  588. foreach my $host (@{$ra_hosts}) {
  589. my $ftp;
  590. # The FTP over TLS transfer mode
  591. if ($BM_UPLOAD_FTP_SECURE) {
  592. $ftp = ftptls_connect_to_host ($host);
  593. unless (defined $ftp) {
  594. print_error "Unable to connect to host: $host";
  595. return FALSE;
  596. }
  597. unless (ftptls_login($ftp, $user, $passwd)) {
  598. print_error "Unable to login on ${host} in FTP TLS mode.";
  599. return FALSE;
  600. }
  601. unless (ftptls_cwd($ftp, $repository)) {
  602. print_info "The directory ${repository} does not exist, trying to create it.";
  603. unless (ftptls_mkdir($ftp, $repository)) {
  604. print_error "Unable to create directory ${repository} in FTP TLS mode: " . $ftp->message;
  605. return FALSE;
  606. }
  607. }
  608. print_info "Logged on $host, in $repository (FTP TLS mode)";
  609. }
  610. # The unencrypted FTP transfers
  611. else {
  612. $ftp = ftp_connect_to_host ($host);
  613. unless (defined $ftp) {
  614. print_error "Unable to connect to host: $host";
  615. return FALSE;
  616. }
  617. unless (ftp_login($ftp, $user, $passwd)) {
  618. print_error "Unable to login on ${host} in FTP mode.";
  619. return FALSE;
  620. }
  621. unless (ftp_cwd($ftp, $repository)) {
  622. print_info "The directory ${repository} does not exist, trying to create it.";
  623. unless (ftp_mkdir($ftp, $repository)) {
  624. print_error "Unable to create directory ${repository} in FTP mode: " . $ftp->message;
  625. return FALSE;
  626. }
  627. }
  628. print_info "Logged on $host, in $repository (FTP binary mode)";
  629. }
  630. # Now that we're connected and logged in, test an upload if needed
  631. if ($g_ftptest) {
  632. if ($BM_UPLOAD_FTP_SECURE) {
  633. if (!ftptls_upload_test_file($ftp)) {
  634. print_error "Unable to transfer test file";
  635. return FALSE;
  636. }
  637. else {
  638. print_info "Test file transferred\n";
  639. }
  640. }
  641. else {
  642. if (!ftp_upload_test_file($ftp)) {
  643. print_error "Unable to transfer test file";
  644. return FALSE;
  645. }
  646. else {
  647. print_info "Test file transferred\n";
  648. }
  649. }
  650. }
  651. # Now that we're connected and logged in, purge the repo if needed
  652. if ($g_ftpclean) {
  653. unless (ftp_clean_directory($ftp)) {
  654. print_error "Unable to clean the FTP directory.";
  655. }
  656. }
  657. # Put all the files over the connection
  658. foreach my $file (@{$ra_files}) {
  659. chomp $file;
  660. # continue if writing to uploaded archives file fails.
  661. if ($BM_UPLOAD_FTP_SECURE) {
  662. if (ftptls_put_file ($ftp, $file)) {
  663. appendto_uploaded_archives($file, $host);
  664. print_info "File $file transfered\n";
  665. }
  666. else {
  667. print_error "Unable to transfer $file";
  668. return FALSE;
  669. }
  670. }
  671. else {
  672. if (ftp_put_file ($ftp, $file)) {
  673. appendto_uploaded_archives($file, $host);
  674. print_info "File $file transfered\n";
  675. }
  676. else {
  677. print_error "Unable to transfer $file: " . $ftp->message;
  678. return FALSE;
  679. }
  680. }
  681. }
  682. print_info "All transfers done, logging out from $host\n";
  683. $ftp->quit;
  684. }
  685. return TRUE;
  686. }
  687. sub ftp_login ($$$)
  688. {
  689. my ($ftp, $user, $passwd) = @_;
  690. return ($ftp->login($user, $passwd) and
  691. $ftp->binary());
  692. }
  693. sub ftptls_login ($$$)
  694. {
  695. my ($ftp, $user, $passwd) = @_;
  696. return ($ftp->user($user) and
  697. $ftp->pass($passwd));
  698. }
  699. sub ftp_cwd ($$)
  700. {
  701. my ($ftp, $repository) = @_;
  702. return ($ftp->cwd($repository));
  703. }
  704. sub ftptls_cwd ($$)
  705. {
  706. my ($ftp, $repository) = @_;
  707. return ($ftp->cwd($repository));
  708. }
  709. sub ftp_mkdir ($$)
  710. {
  711. my ($ftp, $repository) = @_;
  712. return ($ftp->mkdir($repository));
  713. }
  714. sub ftptls_mkdir ($$)
  715. {
  716. my ($ftp, $repository) = @_;
  717. return ($ftp->mkdir($repository));
  718. }
  719. sub ftp_put_file ($$)
  720. {
  721. my ($ftp, $file) = @_;
  722. return $ftp->put ($file);
  723. }
  724. sub ftptls_put_file ($$)
  725. {
  726. my ($ftp, $file) = @_;
  727. my $basename = basename ($file);
  728. return $ftp->put ($basename, $file);
  729. }
  730. # }}}
  731. ##############################################################
  732. # Amazon S3 Mode
  733. ##############################################################
  734. # {{{
  735. # Function for purging a directory
  736. # from S3, the same way as the repository is purged.
  737. # Every files with a date field too old according to BM_ARCHIVE_TTL
  738. # will be deleted.
  739. sub s3_clean_directory($)
  740. {
  741. my ($bucket) = @_;
  742. my $BM_ARCHIVE_TTL = $ENV{BM_ARCHIVE_TTL};
  743. if (defined $ENV{BM_UPLOAD_S3_TTL} and
  744. length ($ENV{BM_UPLOAD_S3_TTL})) {
  745. $BM_ARCHIVE_TTL = $ENV{BM_UPLOAD_S3_TTL};
  746. }
  747. return 0 unless defined $BM_ARCHIVE_TTL;
  748. my $date_to_remove = `date +%Y%m%d --date "$BM_ARCHIVE_TTL days ago"`;
  749. chomp $date_to_remove;
  750. my $response = $bucket->list;
  751. my @keys = @{ $response->{keys} };
  752. foreach my $key (@keys) {
  753. my $date = undef;
  754. if ($key->{key} =~ /[\.\-](\d{8})\./) {
  755. $date = $1;
  756. if ($date and ($date <= $date_to_remove)) {
  757. print_info $key->{key} . " has to be deleted, too old ($date <= $date_to_remove).";
  758. $bucket->delete_key( $key->{key} );
  759. }
  760. }
  761. }
  762. return 1;
  763. }
  764. # How to upload files to s3.
  765. # We'll use the Net::Amazon::S3 module here.
  766. sub send_files_with_s3($$$$$$)
  767. {
  768. # trying to get Net::Amazon::S3.
  769. eval "use Net::Amazon::S3";
  770. if ($@) {
  771. print_error "Net::Amazon::S3 is not available, cannot use S3 service : $@";
  772. return FALSE;
  773. }
  774. if ($Net::Amazon::S3::VERSION < '0.39') {
  775. print_error "Net::Amazon::S3 >= 0.39 is required, but version ${Net::Amazon::S3::VERSION} was found, cannot use S3 service";
  776. return FALSE;
  777. }
  778. # getting args
  779. my ($user, $passwd, $bucket, $ra_hosts, $repository, $ra_files) = @_;
  780. unless (defined $user and
  781. defined $passwd and
  782. defined $bucket and
  783. defined $ra_hosts and
  784. defined $ra_files and
  785. defined $repository) {
  786. print_error "required args needed";
  787. return FALSE;
  788. }
  789. my $totalbytes = 0;
  790. my $starttime = time();
  791. my %uploaded;
  792. my $backup_bucket;
  793. # loop on each hosts given and connect to them.
  794. foreach my $host (@{$ra_hosts}) {
  795. my $s3 = Net::Amazon::S3->new(
  796. {
  797. aws_access_key_id => $user,
  798. aws_secret_access_key => $passwd,
  799. timeout => 300
  800. }
  801. );
  802. unless (defined $s3) {
  803. print_error "Unable to connect to $host : $@\n";
  804. return FALSE;
  805. }
  806. print_info "Connected to $host";
  807. my $bucket_obj = $s3->bucket($bucket);
  808. my $response = $bucket_obj->list;
  809. if (not ( $response->{bucket} ) ) {
  810. print_info "Bucket $bucket does not exist... creating";
  811. $bucket_obj = $s3->add_bucket( { bucket => $bucket } );
  812. print_error "Could not create bucket $bucket" if not ( $bucket_obj );
  813. }
  814. s3_clean_directory($bucket_obj) if ($g_s3clean);
  815. foreach my $file (@{$ra_files}) {
  816. chomp $file;
  817. my @splits = $file;
  818. if( stat($file)->size > $g_s3max_size ) {
  819. my $split_prefix = "$file-split-";
  820. my $cmd = "$split -b $g_s3max_size $file $split_prefix";
  821. if( system($cmd) != 0 ) {
  822. print_error "Could not run '$cmd' to split $file into chunks of size $g_s3max_size";
  823. next;
  824. } else {
  825. @splits = glob("$split_prefix*");
  826. }
  827. }
  828. for my $split (@splits) {
  829. my $filename = basename($split);
  830. my $file_length = stat($split)->size;
  831. print_info "opened $split of length $file_length and will name the key $filename";
  832. $totalbytes += $file_length;
  833. $bucket_obj->add_key_filename(
  834. $filename, $split,
  835. {
  836. content_type => "application/binary"
  837. }
  838. );
  839. $uploaded{$filename} = $file_length;
  840. }
  841. # For the S3 method, we assume success in any case.
  842. appendto_uploaded_archives($file, $host);
  843. }
  844. # get a list of files and confirm uploads
  845. $response = $bucket_obj->list;
  846. my @keys = @{ $response->{keys} };
  847. foreach my $key ( @keys ) {
  848. if (not defined $uploaded{$key->{key}}) {
  849. next;
  850. }
  851. if ($key->{size} == $uploaded{$key->{key}}) {
  852. print_info $key->{key} . " uploaded sucessfully";
  853. delete $uploaded{$key->{key}};
  854. }
  855. else {
  856. print_error $key->{key} . " did not upload sucessfully. S3 reports $key is " . $key->{size} . " bytes rather than " . $uploaded{$key->{key}};
  857. delete $uploaded{$key->{key}};
  858. return FALSE;
  859. }
  860. }
  861. }
  862. print_info ("Uploaded $totalbytes bytes of data to S3 in "
  863. . (time() - $starttime) . " seconds");
  864. return TRUE;
  865. }
  866. # }}}
  867. ##############################################################
  868. # Main
  869. ##############################################################
  870. # {{{
  871. # date is always the last args.
  872. my $date = $ARGV[$#ARGV];
  873. $date = 'today' if (not defined $date or $date =~ /^-/);
  874. # the really needed args !
  875. unless (defined $g_host and
  876. defined $g_user and
  877. defined $g_protocol) {
  878. print $BackupManager::Config::usage, "\n";
  879. exit E_INVALID;
  880. }
  881. if ($g_protocol eq 'ftp' and not defined $g_pass) {
  882. # try to read the password from the environment
  883. if (defined $ENV{BM_UPLOAD_FTP_PASSWORD}) {
  884. $g_pass = $ENV{BM_UPLOAD_FTP_PASSWORD};
  885. }
  886. else {
  887. print $BackupManager::Config::usage, "\n";
  888. exit E_INVALID;
  889. }
  890. }
  891. if ($g_protocol eq 's3' and (not defined $g_bucket or not defined $g_pass)) {
  892. if (! defined $g_pass && defined $ENV{BM_UPLOAD_S3_SECRET_KEY}) {
  893. $g_pass = $ENV{BM_UPLOAD_S3_SECRET_KEY};
  894. }
  895. else {
  896. print $BackupManager::Config::usage, "\n";
  897. exit E_INVALID;
  898. }
  899. }
  900. if ($g_protocol eq 'ssh-gpg' and (not defined $g_gpg_recipient)) {
  901. print $BackupManager::Config::usage, "\n";
  902. exit E_INVALID;
  903. }
  904. # storing hosts on memory
  905. my $ra_hosts = get_hosts_from_str($g_host);
  906. # where to store archives...
  907. $g_remote_dir = "/backup/uploads/" if (not defined $g_remote_dir);
  908. # let's find which files needs to be uploaded.
  909. my $ra_files = get_files_list_from_date(get_formated_date($date));
  910. # if user wants listing, just do it !
  911. if ($g_list) {
  912. print_info "files to upload ($date) :";
  913. foreach my $file (@{$ra_files}) {
  914. print "- $file\n";
  915. }
  916. exit E_SUCCESS;
  917. }
  918. # We'll now send the files with the appropriate transfer protocol
  919. $g_protocol = lc $g_protocol;
  920. # FTP
  921. if ($g_protocol eq 'ftp') {
  922. print_info "Trying to upload files with ftp";
  923. if (! send_files_with_ftp ($g_user,
  924. $g_pass,
  925. $ra_hosts,
  926. $g_remote_dir,
  927. $ra_files)) {
  928. print_error "The upload transfer \"$g_protocol\" failed.";
  929. exit E_FTP_FAILED;
  930. }
  931. }
  932. # SSH related tranfers
  933. elsif ($g_protocol eq 'scp' or
  934. $g_protocol eq 'ssh' or
  935. $g_protocol eq 'ssh-gpg') {
  936. if ($g_protocol eq 'ssh-gpg') {
  937. print_info "Trying to upload files with ssh-gpg";
  938. }
  939. else {
  940. $g_gpg_recipient = undef;
  941. print_info "Trying to upload files with scp";
  942. }
  943. if (! send_files_with_scp ($g_user,
  944. $ra_hosts,
  945. $g_remote_dir,
  946. $ra_files,
  947. $g_gpg_recipient)) {
  948. print_error "The upload transfer \"$g_protocol\" failed.";
  949. exit E_SCP_FAILED;
  950. }
  951. }
  952. # Amazon S3 WebService
  953. elsif ($g_protocol eq 's3') {
  954. print_info "Trying to upload files to s3 service";
  955. if (! send_files_with_s3 ($g_user,
  956. $g_pass,
  957. $g_bucket,
  958. $ra_hosts,
  959. $g_remote_dir,
  960. $ra_files)) {
  961. print_error "The upload transfer \"$g_protocol\" failed.";
  962. exit E_S3_FAILED;
  963. }
  964. }
  965. # Unknown protocol
  966. else {
  967. print STDERR "mode '$g_protocol' is not supported\n";
  968. exit E_UNKNOWN;
  969. }
  970. __END__
  971. =head1 NAME
  972. backup-manager-upload - Multiprotocol uploader for backup-manager.
  973. =head1 SYNOPSIS
  974. backup-manager-upload [options] date
  975. =head1 DESCRIPTION
  976. B<backup-manager-upload> will upload all the archives generated on the given
  977. date to the specified host with either ftp or scp.
  978. It's also possible to use this program for uploading data to an Amazon S3 account.
  979. Some metadates are available like "today" or "yesterday".
  980. =head1 REQUIRED ARGS
  981. =over 4
  982. =item B<--mode=>I<transfer-mode>
  983. Select the transfer mode to use : ftp, scp, or s3.
  984. =item B<--host=>I<hostname1,hostname2,...,hostnameN>
  985. Select a list of remote hosts to connect to.
  986. =item B<--user=>I<username>
  987. Select the user to use for connection.
  988. =back
  989. =head1 OPTIONAL ARGS
  990. =over 4
  991. =item B<--password=>I<password>
  992. Select the ftp user's password (only needed for ftp transfers).
  993. =item B<--key=>I<path_to_private_key>
  994. Select the ssh private key file to use when opening the ssh session for scp transfer.
  995. Obviously, this is only needed for scp transfer mode.
  996. If you don't specify a key file, the user's default private key will be used.
  997. =item B<--directory=>I<directory>
  998. Select the location on the remote host where files will be uploaded.
  999. Default is /backup/uploads.
  1000. =item B<--bucket=>I<bucket>
  1001. Sets the bucket name for the Amazon S3 service backup into.
  1002. =item B<--root=>I<directory>
  1003. Select the local directory where files are.
  1004. Default is /var/archives
  1005. =item B<--gpg-recipient=>I<gpg-recipient>
  1006. Select the gpg public key for encryptiong the archives when uploading
  1007. with the method ssh-gpg. This can be a short or long key id or a
  1008. descriptive name. The precise syntax is described in the gpg man page.
  1009. =item B<--list>
  1010. Just list the files to upload.
  1011. =item B<--ftp-purge>
  1012. Purge the remote directory before uploading files in FTP mode.
  1013. =item B<--s3-purge>
  1014. Purge the remote directory before uploading files in FTP mode.
  1015. =item B<--ssh-purge>
  1016. Purge the remote directory before uploading files in SSH mode.
  1017. =item B<--verbose>
  1018. Flag to enable verbose mode.
  1019. =item B<date>
  1020. Date pattern to select some files to upload, can be a valid date (YYYYMMDD) or 'today' or 'yesterday'.
  1021. =back
  1022. =head1 ERROR CODES
  1023. If something goes wrong during an upload, backup-manager-upload will exit
  1024. with a non null value. In such a case every error messages are sent to
  1025. STDERR.
  1026. Here are the possible error codes:
  1027. =over 4
  1028. =item bad command line (wrong arguments) : 10
  1029. =item FTP transfer failure : 20
  1030. =item SCP transfer failure : 21
  1031. =item S3 transfer failure : 22
  1032. =item Unknown upload method: 23
  1033. =back
  1034. =cut
  1035. =head1 SEE ALSO
  1036. L<backup-manager(3)>
  1037. =head1 AUTHORS
  1038. Alexis Sukrieh - main code and design
  1039. Brad Dixon - Amazon S3 upload method
  1040. Jan Metzger - ssh-gpg upload method
  1041. =cut