Brackup/Target/Sftp.pm untested

filter: Statementstmt 0.0% 0 / 168 Branchbran 0.0% 0 / 34 Conditioncond 0.0% 0 / 52 MC/DCmcdc 0.0% 0 / 28 Subroutinesub 0.0% 0 / 32 Podpod 0.0% 0 / 26 totaltotal 0.0% 0 / 340 CC 18 SCAR 19.8
CC
18
Cov
0%
_ls
30.0
new_from_backup_header
12.0
new
6.0
CRAP 7.3
1 package Brackup::Target::Sftp;
2 use strict;
3 use warnings;
4 use base 'Brackup::Target::Filebased';
5 use File::Basename;
6 use Net::SFTP::Foreign 1.57; # versions <= 1.56 emit warnings
7 use Net::SFTP::Foreign::Constants qw(:flags);
8  
9 sub new {
10 my ($class, $confsec) = @_;
11 my $self = $class->SUPER::new($confsec);
12  
13 $self->{path} = $confsec->value("path") or die 'No path specified';
14 $self->{nocolons} = $confsec->value("no_filename_colons");
15 $self->{nocolons} = $self->_default_nocolons unless defined $self->{nocolons};
16  
17 $self->{sftp_host} = $confsec->value("sftp_host") or die 'No "sftp_host"';
18 $self->{sftp_port} = $confsec->value("sftp_port");
19 $self->{sftp_user} = $confsec->value("sftp_user") || (getpwuid($<))[0]
20 or die "No sftp_user specified";
21  
22 $self->_common_new;
23  
24 return $self;
25 }
26  
27 sub new_from_backup_header {
28 my ($class, $header) = @_;
29 my $self = bless {}, $class;
30  
31 $self->{sftp_host} = $header->{'SftpHost'};
32 $self->{sftp_user} = $header->{'SftpUser'};
33 $self->{sftp_port} = $header->{'SftpPort'} if $header->{'SftpPort'};
34 $self->{path} = $header->{'BackupPath'} or
35 die "No BackupPath specified in the backup metafile.\n";
36 $self->{nocolons} = $header->{"NoColons"};
37 $self->{nocolons} = $self->_default_nocolons unless defined $self->{nocolons};
38  
39 $self->_common_new;
40  
41 return $self;
42 }
43  
44 sub _common_new {
45 my ($self) = @_;
46 $self->{retry_wait} = int($ENV{SFTP_RETRY_WAIT} || 10);
47 $self->_connect();
48 }
49  
50 sub backup_header {
51 my ($self) = @_;
52 return {
53 "BackupPath" => $self->{path},
54 "SftpHost" => $self->{sftp_host},
55 "SftpUser" => $self->{sftp_user},
56 "NoColons" => $self->nocolons,
57 $self->{sftp_port} ? ("SftpPort" => $self->{sftp_port}) : (),
58 };
59 }
60  
61 sub _default_nocolons {
62 return 1; # Can't assume remote OS allows colons
63 }
64  
65 sub nocolons {
66 my ($self) = @_;
67 return defined $self->{nocolons} ? $self->{nocolons} : $self->_default_nocolons;
68 }
69  
70 sub _connect {
71 my ($self) = @_;
72  
73 $self->{sftp} = Net::SFTP::Foreign->new(
74 $self->{sftp_host},
75 user => $self->{sftp_user},
76 $self->{sftp_port} ? (port => $self->{sftp_port}) : (),
77 );
78 $self->{sftp}->error and die $self->{sftp}->error;
79 }
80  
81 sub _autoretry {
82 my ($self, $code) = @_;
83 my $result = $code->();
84  
85 if (!defined($result) && !$self->{sftp}->{_connected}) {
86 warn "Error in SFTP connection: " . $self->{sftp}->error . "\n";
87 sleep $self->{retry_wait};
88 warn "Trying to reconnect ...\n";
89 $self->_connect();
90 $result = $code->();
91 }
92  
93 return $result;
94 }
95  
96 sub _ls {
97 my ($self, $path) = @_;
98 my $result = $self->_autoretry(sub {
99 if (my $ls = $self->{sftp}->ls($path,
100 names_only => 1, no_wanted => qr/^\.\.?$/ )) {
101 die "Bad ls results $ls" unless ref $ls && ref $ls eq 'ARRAY';
102 return [ map { $path . '/' . $_ } @$ls ];
103 }
104 });
105 unless (defined($result)) {
106 die "Listing failed for $path: " . $self->{sftp}->error;
107 }
108 return wantarray ? @$result : $result;
109 }
110  
111 sub size {
112 my ($self, $path) = @_;
113 my $size = $self->_autoretry(sub {
114 my $attr = $self->{sftp}->stat($path)
115 or die "Cannot stat path '$path'";
116 return $attr->size;
117 });
118 unless (defined($size)) {
119 die "Getting size for $path failed: " . $self->{sftp}->error;
120 }
121 return $size;
122 }
123  
124 sub _mtime {
125 my ($self, $path) = @_;
126 my $mtime = $self->_autoretry(sub {
127 my $attr = $self->{sftp}->stat($path)
128 or die "Cannot stat path '$path'";
129 return $attr->mtime;
130 });
131 unless (defined $mtime) {
132 die "Getting mtime of $_ failed: " . $self->{sftp}->error;
133 }
134 return $mtime;
135 }
136  
137 sub _mkdir {
138 my ($self, $dir) = @_;
139 return if ! $dir || $dir eq '/';
140  
141 my $parent = dirname($dir);
142 $self->_autoretry(sub {
143 $self->{sftp}->stat($parent) or $self->_mkdir($parent);
144 $self->{sftp}->stat($dir) or $self->{sftp}->mkdir($dir);
145 }) or die "Creating directory $dir failed: " . $self->{sftp}->error;
146 }
147  
148 sub _put_chunk {
149 my ($self, $path, $content) = @_;
150  
151 $self->_mkdir(dirname($path));
152  
153 $self->_autoretry(sub {
154 my $fh = $self->{sftp}->open($path, SSH2_FXF_WRITE|SSH2_FXF_CREAT)
155 or die "Failed to open";
156 my $result = $self->{sftp}->write($fh, $content);
157 $self->{sftp}->close($fh) or die "Failed to close";
158 return $result;
159 }) or die "Writing file $path failed: " . $self->{sftp}->error;
160 }
161  
162 sub _put_fh {
163 my ($self, $path, $fh) = @_;
164  
165 $self->_mkdir(dirname($path));
166  
167 $self->_autoretry(sub { $self->{sftp}->put($fh, $path) })
168 or die "Doing a put to path $path failed: " . $self->{sftp}->error;
169 }
170  
171 sub _get {
172 my ($self, $path) = @_;
173 my $content;
174  
175 $self->_autoretry(sub {
176 $content = $self->{sftp}->get_content($path);
177 }) or die "Reading file $path failed: " . $self->{sftp}->error;
178  
179 return \$content;
180 }
181  
182 sub _delete {
183 my ($self, $path) = @_;
184 $self->_autoretry(sub {
185 return $self->{sftp}->remove($path);
186 }) or die "Removing file $path failed: " . $self->{sftp}->error;
187 }
188  
189 sub chunkpath {
190 my ($self, $dig) = @_;
191 return $self->{path} . '/' . $self->SUPER::chunkpath($dig);
192 }
193  
194 sub metapath {
195 my ($self, $name) = @_;
196 return $self->{path} . '/' . $self->SUPER::metapath($name);
197 }
198  
199 sub load_chunk {
200 my ($self, $dig) = @_;
201 return $self->_get($self->chunkpath($dig));
202 }
203  
204 sub store_chunk {
205 my ($self, $chunk) = @_;
206 my $dig = $chunk->backup_digest;
207 my $path = $self->chunkpath($dig);
208  
209 $self->_put_fh($path, $chunk->chunkref);
210  
211 my $actual_size = $self->size($path);
212 my $expected_size = $chunk->backup_length;
213 unless ($actual_size == $expected_size) {
214 die "Chunk $path incompletely written to disk: size is " .
215 "$actual_size, expecting $expected_size\n";
216 }
217  
218 return 1;
219 }
220  
221 sub delete_chunk {
222 my ($self, $dig) = @_;
223 $self->_delete($self->chunkpath($dig));
224 }
225  
226 # returns a list of names of all chunks
227 sub chunks {
228 my $self = shift;
229  
230 my @chunks = ();
231 for ($self->{sftp}->find( $self->{path},
232 wanted => qr/\.chunk$/, no_descend => qr/^backups$/ )) {
233 my $chunk_name = basename($_->{filename});
234 $chunk_name =~ s/\.chunk$//;
235 $chunk_name =~ s/\./:/g if $self->nocolons;
236 push @chunks, $chunk_name;
237 }
238 return @chunks;
239 }
240  
241 sub store_backup_meta {
242 my ($self, $name, $fh) = @_;
243 $self->_put_fh($self->metapath("$name.brackup"), $fh);
244 return 1;
245 }
246  
247 sub backups {
248 my ($self) = @_;
249 my $list = $self->_ls($self->metapath());
250  
251 my @ret = ();
252 foreach (@$list) {
253 my $fn = basename($_);
254 next unless $fn =~ m/\.brackup$/;
255  
256 (my $bn = $fn) =~ s/\.brackup$//;
257  
258 my $path = $self->metapath($fn);
259 my $size = $self->size($path);
260 my $mtime = $self->_mtime($path);
261  
262 push @ret, Brackup::TargetBackupStatInfo->new($self, $bn,
263 time => $mtime,
264 size => $size);
265 }
266  
267 return @ret;
268 }
269  
270 # downloads the given backup name to the current directory (with
271 # *.brackup extension) or to the specified location
272 sub get_backup {
273 my ($self, $name, $output_file) = @_;
274 my $path = $self->metapath("$name.brackup");
275  
276 $output_file ||= "$name.brackup";
277  
278 $self->_autoretry(sub {
279 return $self->{sftp}->get($path, $output_file);
280 }) or die "Reading file $path failed: " . $self->{ftp}->error;
281  
282 return 1;
283 }
284  
285 sub delete_backup {
286 my ($self, $name) = @_;
287 $self->_delete($self->metapath("$name.brackup"));
288 return 1;
289 }
290  
291 1;
292  
293  
294 =head1 NAME
295  
296 Brackup::Target::Sftp - backup to an SSH/SFTP server
297  
298 =head1 DESCRIPTION
299  
300 Backup to an SSH/SFTP server, using the L<Net::SFTP::Foreign> perl module.
301  
302 =head1 EXAMPLE
303  
304 In your ~/.brackup.conf file:
305  
306 [TARGET:server_sftp]
307 type = Sftp
308 path = /path/on/server
309 sftp_host = server.example.com
310 sftp_user = user
311  
312 At this time there is no 'sftp_password' setting - you are encouraged
313 to use ssh keys for authentication instead of passwords. Alternatively,
314 you can enter your password interactively when prompted.
315  
316 =head1 CONFIG OPTIONS
317  
318 =over
319  
320 =item B<type>
321  
322 I<(Mandatory.)> Must be "B<Sftp>".
323  
324 =item B<path>
325  
326 I<(Mandatory).> Server-side path to write backups to (may be ".").
327  
328 =item B<sftp_host>
329  
330 I<(Mandatory).> SSH/SFTP server hostname.
331  
332 =item B<sftp_port>
333  
334 Port on which to connect to remote SSH/SFTP server.
335  
336 =item B<sftp_user>
337  
338 Username to use to connect.
339  
340 =item B<no_filename_colons>
341  
342 Flag - set to false (0/false/no) to indicate that the remote filesystem supports
343 colons (':') in filenames. Default: 1.
344  
345 =back
346  
347 =head1 SEE ALSO
348  
349 L<Brackup::Target>
350  
351 L<Brackup::Target::Ftp>
352  
353 L<Net::SFTP::Foreign>
354  
355 =head1 AUTHOR
356  
357 Gavin Carr E<lt>gavin@openfusion.com.auE<gt>.
358  
359 Copyright (c) 2008 Gavin Carr.
360  
361 This module is free software. You may use, modify, and/or redistribute
362 this software under the same terms as perl itself.
363  
364 =cut
365  
366 # vim:sw=4:et
367