BlockSync.pm

filter: Statementstmt 37.3% 53 / 142 Branchbran 2.1% 1 / 46 Conditioncond 0.0% 0 / 27 MC/DCmcdc 0.0% 0 / 14 Subroutinesub 54.1% 13 / 24 Podpod 100% 2 / 2 totaltotal 27.0% 69 / 255 CC 33 SCAR 59.1
CC
33
Cov
25%
__ANON__
756.0
__ANON__
20.0
_getFh
20.0
CRAP 367.9
↑ Summary BlockSync/App.pm »
1 package IO::BlockSync;
2  
3 # Basic
4 1 ▶use 5.010;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 1 ▶use warnings FATAL => 'all';
Subroutine BEGIN: called CC=1 SCAR=0.0
7  
8 # Build in
9 1 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 1 ▶use Fcntl qw(:DEFAULT :seek);
Subroutine BEGIN: called CC=1 SCAR=0.0
11 1 ▶use POSIX qw(ceil);
Subroutine BEGIN: called CC=1 SCAR=0.0
12 1 ▶use Scalar::Util qw(reftype);
Subroutine BEGIN: called CC=1 SCAR=0.0
13  
14 # CPAN
15 1 ▶use Log::Log4perl;
Subroutine BEGIN: called CC=1 SCAR=0.0
16 1 ▶use Log::Log4perl::Level;
Subroutine BEGIN: called CC=1 SCAR=0.0
17 1 ▶use Moo;
Subroutine BEGIN: called CC=1 SCAR=0.0
18 1 ▶use Try::Tiny;
Subroutine BEGIN: called CC=1 SCAR=0.0
19  
20 # These two come last - in that order
21 1 ▶use namespace::clean;
Subroutine BEGIN: called CC=1 SCAR=0.0
22 1 ▶use Exporter qw(import);
Subroutine BEGIN: called CC=1 SCAR=0.0
23  
24 ################################################################
25  
26 # Moo roles to implement
27 1 with('MooseX::Log::Log4perl');
28  
29 # Make sure log4perl doesn't come with errors
30 1 ▶if ( not Log::Log4perl->initialized() ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ("Log::Log4perl"->initialized) 1 0 1
31 1 Log::Log4perl->easy_init( Log::Log4perl::Level::to_priority('OFF') );
32 }
33  
34 ################################################################
35  
36 =head1 NAME
37  
38 IO::BlockSync - Syncronize changed blocks
39  
40 =head1 VERSION
41  
42 Version 0.002
43  
44 =cut
45  
46 1 our $VERSION = '0.002';
47  
48 ################################################################
49  
50 =head1 SYNOPSIS
51  
52 BlockSync can some of the same stuff that bigsync (by Egor Egorov) can
53 - it's just written in perl.
54  
55 BlockSync copies data from source file to destination file (can be a block
56 device) and calculates checksum on each block it copies.
57 On all runs after the first only the changed blocks will be copied.
58  
59 use IO::BlockSync;
60  
61 # OOP way
62 my $bs = IO::BlockSync->new(
63 src => '/path/to/source/file',
64 dst => '/path/to/destination/file',
65 chk => '/path/to/chk/file',
66 );
67 $bs->run;
68  
69 # Non OOP way
70 BlockSync(
71 src => '/path/to/source/file',
72 dst => '/path/to/destination/file',
73 chk => '/path/to/chk/file',
74 );
75  
76 =cut
77  
78 ################################################################
79  
80 =head1 INSTALLATION
81  
82 Look in C<README.pod>
83  
84 Can also be found on
85 L<GitHub|https://github.com/thordreier/perl-IO-BlockSync/blob/master/README.pod>
86 or L<meta::cpan|https://metacpan.org/pod/distribution/IO-BlockSync/README.pod>
87  
88 =cut
89  
90 ################################################################
91  
92 =head1 EXPORT
93  
94 =cut
95  
96 1 our @EXPORT = qw(BlockSync);
97  
98 ################################################################
99  
100 =head2 BlockSync
101  
102 Run BlockSync non-object-oriented
103  
104 =cut
105  
106 0 ▶sub BlockSync {
Subroutine BlockSync: not called CC=1 SCAR=6.9
Pod documented
107 0 return __PACKAGE__->new(@_)->run;
108 }
109  
110 ################################################################
111  
112 =head1 ATTRIBUTES
113  
114 =cut
115  
116 ################################################################
117  
118 =head2 src
119  
120 Path to source file.
121  
122 mandatory - string (containing path) or filehandle
123  
124 =cut
125  
126 1 has 'src' => (
127 is => 'ro',
128 required => 1,
129 );
130  
131 ################################################################
132  
133 =head2 dst
134  
135 Destination file. If not set, then only checksum file will be updated.
136  
137 optional - string (containing path) or filehandle
138  
139 =cut
140  
141 1 has 'dst' => ( is => 'ro', );
142  
143 ################################################################
144  
145 =head2 chk
146  
147 Path to checksum file.
148  
149 mandatory - string (containing path) or filehandle
150  
151 =cut
152  
153 1 has 'chk' => (
154 is => 'ro',
155 required => 1,
156 );
157  
158 ################################################################
159  
160 =head2 bs
161  
162 Block size to use in bytes.
163  
164 optional - integer - defaults to 1_048_576 B (1 MB)
165  
166 =cut
167  
168 1 has 'bs' => (
169 is => 'ro',
170 default => 1_048_576,
171 );
172  
173 ################################################################
174  
175 =head2 hash
176  
177 Sub that retrurn hashed data.
178  
179 optional - sub - defaults to sub that return MD5 hash followed by newline
180  
181 =cut
182  
183 has 'hash' => (
184 is => 'ro',
185 0 ▶ default => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
186 0 require Digest::MD5;
187 0 ▶ sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
188 0 Digest::MD5::md5_hex(shift) . "\n";
189 }
190 0 },
191 1 );
192  
193 ################################################################
194  
195 =head2 sparse
196  
197 Seek in dst file, instead of writing blocks only containing \0
198  
199 optional - boolean - defaults to 0 (false)
200  
201 =cut
202  
203 1 has 'sparse' => (
204 is => 'ro',
205 default => 0,
206 );
207  
208 ################################################################
209  
210 =head2 truncate
211  
212 Truncate the destination file to same size as source file. Does not work on block devices. Will only be tried if C<data> has default value (whole file is copied).
213  
214 optional - boolean - defaults to 0 (false)
215  
216 =cut
217  
218 1 has 'truncate' => (
219 is => 'ro',
220 default => 0,
221 );
222  
223 ################################################################
224  
225 =head2 data
226  
227 List of areas (in bytes) inside the source file that should be looked at.
228 Usefull if you know excactly which blocks in src that could have changed.
229  
230 data => [
231 {start => 0, end => 9999},
232 {start => 88888, end => 777777},
233 ]
234  
235 optional - array of hashes - defaults to "whole file"
236  
237 =cut
238  
239 has 'data' => (
240 is => 'ro',
241 0 ▶ default => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
242 [
243 {
244 0 start => 0,
245 end => 0
246 }
247 ]
248 },
249 1 );
250  
251 ################################################################
252  
253 =head2 status
254  
255 Sub that will be run everytime a block has been read (and written).
256  
257 optional - sub - default to sub doing nothing
258  
259 =cut
260  
261 has 'status' => (
262 is => 'ro',
263 0 ▶ default => sub {
Subroutine __ANON__: not called CC=1 SCAR=6.9
264 0 ▶ sub { }
Subroutine __ANON__: not called CC=1 SCAR=0.0
265 0 },
266 1 );
267  
268 ################################################################
269  
270 =head1 METHODS
271  
272 =cut
273  
274 ################################################################
275  
276 =head2 run
277  
278 This is the method that starts copying data.
279  
280 =cut
281  
282 0 ▶sub run { ## no critic (Subroutines::ProhibitExcessComplexity)
Subroutine run: not called CC=1 SCAR=6.9
Pod documented
283 0 my $self = shift;
284  
285 0 my ( $srcFh, $srcClose, $dstFh, $dstClose, $chkFh, $chkClose );
286  
287 0 ▶ try {
Subroutine __ANON__: not called CC=27 SCAR=66.3
288 # Get file handles for source, destination and checksum files
289 0 $srcFh = $self->_getFh( 'src', $self->src, \$srcClose, O_RDONLY );
290 0 $chkFh =
291 $self->_getFh( 'chk', $self->chk, \$chkClose, O_RDWR | O_CREAT );
292 0 ▶ if ( $self->dst ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->dst) { } 0 0 0
293 0 $dstFh = $self->_getFh( 'dst', $self->dst, \$dstClose,
294 O_WRONLY | O_CREAT );
295 }
296 else {
297 0 $self->logger->debug('No dst file, only calculating checksums');
298 }
299  
300 # Calculate hash for a block only containing ASCII 0
301 0 my $nullHash = &{ $self->hash }( "\0" x $self->bs );
302  
303 # Get number of bytes that a hash takes up
304 0 my $hashSize = length($nullHash);
305  
306 0 my $srcSeek;
307  
308 # Loop through "areas" that should be copied
309 # Default i one area containing the whole source file
310 0 foreach my $dataBlocks ( @{ $self->data } ) {
311  
312 # Start and end of this "area" (default is $start=0, $end=0)
313 0 my $start = $dataBlocks->{start};
314 0 my $end = $dataBlocks->{end};
315  
316 0 $self->logger->debug(
317 "Going to process data from <$start> to <$end>");
318  
319 # Seek to $start
320 # (or the beginning of the block that $start is in,
321 # if $start is not aligned with bs)
322 0 $srcSeek = int( $start / $self->bs ) * $self->bs;
323 0 ▶ sysseek( $srcFh, $srcSeek, SEEK_SET )
Branch: 1 branch
BranchTrueFalseTotal
sysseek $srcFh, $srcSeek, 0 or $self->logger->logcroak("Cannot seek to block <$srcSeek> in src file") 0 0 0
324 || $self->logger->logcroak(
325 "Cannot seek to block <$srcSeek> in src file");
326  
327 # Just die! Muhahaha. Or not
328 0 my $die = 0;
329  
330 # Can be either sparse, new, unchanged or changed
331 0 my $status;
332  
333 # Read block from source
334 0 ▶ while ( my $srcReadSize = sysread( $srcFh, my $data, $self->bs ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $srcReadSize = sysread($srcFh, my $data, $self->bs)) 0 0 0
335  
336 # It's ok to read a block smaller than bs if it's the last
337 # block. But it's not ok if it's not the last.
338 0 ▶ if ($die) {
Branch: 1 branch
BranchTrueFalseTotal
if ($die) 0 0 0
339 0 croak 'not reading full block';
340 }
341 0 $die = $srcReadSize != $self->bs;
342  
343 # $block = block number in source with the specified block size
344 0 my $block = $srcSeek / $self->bs;
345  
346 # We start by assuming that we should write to dst
347 # - if dst is set (= we are not just calculating checksum)
348 0 my $writeData = 1 && $dstFh;
349  
350 # We start be assuming that we should write checksum to chk
351 0 my $writeHash = 1;
352  
353 # Calculate hash for data read from src
354 0 my $newHash = &{ $self->hash }($data);
355  
356 # Get old hash for the same block
357 0 ▶ sysseek( $chkFh, $block * $hashSize, SEEK_SET )
Branch: 1 branch
BranchTrueFalseTotal
sysseek $chkFh, $block * $hashSize, 0 or $self->logger->logcroak("Cannot seek in chk file") 0 0 0
358 || $self->logger->logcroak('Cannot seek in chk file');
359 0 my $oldHashSize = sysread( $chkFh, my $oldHash, $hashSize );
360  
361 # Test source against checksum
362 0 ▶ if ( $oldHashSize != $hashSize || $oldHash eq "\0" x $hashSize )
Branch: 2 branches
BranchTrueFalseTotal
if ($oldHashSize != $hashSize or $oldHash eq "\000" x $hashSize) { } 0 0 0
elsif ($newHash eq $oldHash) { } 0 0 0
Condition0%0/3
$oldHashSize != $hashSize or $oldHash eq "\0" x $hashSize
l!l&&r!l&&!r
000
MC/DC0%0/2
$oldHashSize != $hashSize or $oldHash eq "\0" x $hashSize
$oldHashSize != $hashSize $oldHash eq "\0" x $hashSize
Truth table0%0/3
A or B
A= $oldHashSize != $hashSizeB= $oldHash eq "\0" x $hashSize
ABresult
1X1
011
000
363 {
364 0 ▶ if ( $self->sparse && $newHash eq $nullHash ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->sparse and $newHash eq $nullHash) { } 0 0 0
Condition0%0/3
$self->sparse and $newHash eq $nullHash
!ll&&!rl&&r
000
MC/DC0%0/2
$self->sparse and $newHash eq $nullHash
$self->sparse $newHash eq $nullHash
Truth table0%0/3
A and B
A= $self->sparseB= $newHash eq $nullHash
ABresult
0X0
100
111
365  
366 # Sparse is only for new blocks
367 # Blocks that have been nulled out in source will
368 # also get nulled out in destination
369 0 $status = 'sparse';
370 0 $writeData = 0;
371 }
372 else {
373 0 $status = 'new';
374 }
375 }
376 elsif ( $newHash eq $oldHash ) {
377 0 $status = 'unchanged';
378 0 $writeData = 0;
379 0 $writeHash = 0;
380 }
381 else {
382 0 $status = 'changed';
383 }
384  
385 # Write data to destination
386 0 ▶ if ($writeData) {
Branch: 1 branch
BranchTrueFalseTotal
if ($writeData) 0 0 0
387 0 ▶ sysseek( $dstFh, $srcSeek, SEEK_SET )
Branch: 1 branch
BranchTrueFalseTotal
sysseek $dstFh, $srcSeek, 0 or $self->logger->logcroak("Cannot seek in dst file") 0 0 0
388 || $self->logger->logcroak('Cannot seek in dst file');
389 0 syswrite( $dstFh, $data );
390 }
391  
392 # Update hash in checksum
393 0 ▶ if ($writeHash) {
Branch: 1 branch
BranchTrueFalseTotal
if ($writeHash) 0 0 0
394 0 ▶ sysseek( $chkFh, $block * $hashSize, SEEK_SET )
Branch: 1 branch
BranchTrueFalseTotal
sysseek $chkFh, $block * $hashSize, 0 or $self->logger->logcroak("Cannot seek in chk file") 0 0 0
395 || $self->logger->logcroak('Cannot seek in chk file');
396 0 syswrite( $chkFh, $newHash );
397 }
398  
399 $self->logger->debug(
400 0 sprintf 'Block <%u> was <%s> (<%u> to <%u>)',
401 $block, $status, $srcSeek, $srcSeek + $srcReadSize - 1 );
402 0 &{ $self->status }
403 ( $block, $status, $srcSeek, $srcSeek + $srcReadSize - 1 );
404  
405 # Next block will start here
406 0 $srcSeek += $srcReadSize;
407  
408 # Was this the last block in this batch
409 0 ▶ if ( $end && $srcSeek > $end ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($end and $srcSeek > $end) 0 0 0
Condition0%0/3
$end and $srcSeek > $end
!ll&&!rl&&r
000
MC/DC0%0/2
$end and $srcSeek > $end
$end $srcSeek > $end
Truth table0%0/3
A and B
A= $endB= $srcSeek > $end
ABresult
0X0
100
111
410 0 last;
411 }
412 }
413  
414 # If last block is sparse, it is not enough to seek to where the
415 # EOF should be. We need to at least write a single \0
416 0 ▶ if ( $dstFh && $status eq 'sparse' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($dstFh and $status eq "sparse") 0 0 0
Condition0%0/3
$dstFh and $status eq "sparse"
!ll&&!rl&&r
000
MC/DC0%0/2
$dstFh and $status eq "sparse"
$dstFh $status eq "sparse"
Truth table0%0/3
A and B
A= $dstFhB= $status eq "sparse"
ABresult
0X0
100
111
417 0 ▶ sysseek( $dstFh, $srcSeek - 1, SEEK_SET )
Branch: 1 branch
BranchTrueFalseTotal
sysseek $dstFh, $srcSeek - 1, 0 or $self->logger->logcroak("Cannot seek in dst file") 0 0 0
418 || $self->logger->logcroak('Cannot seek in dst file');
419 0 syswrite( $dstFh, "\0" );
420 }
421 }
422  
423 0 ▶ if ( $self->truncate
Branch: 1 branch
BranchTrueFalseTotal
if ($self->truncate and $dstFh and $srcSeek and @{$self->data;} == 1 and $self->data->[0]{"start"} == 0 and $self->data->[0]{"end"} == 0) 0 0 0
Condition0%0/15
$self->truncate and $dstFh and $srcSeek and @{$self->data;} == 1 and $self->data->[0]{"start"} == 0 and $self->data->[0]{"end"} == 0
!ll&&!rl&&r
000
$self->truncate and $dstFh and $srcSeek and @{$self->data;} == 1 and $self->data->[0]{"start"} == 0
!ll&&!rl&&r
000
$self->truncate and $dstFh and $srcSeek and @{$self->data;} == 1
!ll&&!rl&&r
000
$self->truncate and $dstFh and $srcSeek
!ll&&!rl&&r
000
$self->truncate and $dstFh
!ll&&!rl&&r
000
MC/DC0%0/6
$self->truncate and $dstFh and $srcSeek and @{$self->data;} == 1 and $self->data->[0]{"start"} == 0 and $self->data->[0]{"end"} == 0
$self->truncate $dstFh $srcSeek @{$self->data;} == 1 $self->data->[0]{"start"} == 0 $self->data->[0]{"end"} == 0
Truth table0%0/7
A and B and C and D and E and F
A= $self->truncateB= $dstFhC= $srcSeekD= @{$self->data;} == 1E= $self->data->[0]{"start"} == 0F= $self->data->[0]{"end"} == 0
ABCDEFresult
0XXXXX0
10XXXX0
110XXX0
1110XX0
11110X0
1111100
1111111
424 && $dstFh
425 && $srcSeek
426 0 && @{ $self->data } == 1
427 && $self->data->[0]->{start} == 0
428 && $self->data->[0]->{end} == 0 )
429 {
430 0 $self->logger->debug("Truncating dst file at <$srcSeek>");
431 0 truncate( $dstFh, $srcSeek );
432  
433 0 my $chkSeek = ceil( $srcSeek / $self->bs ) * $hashSize;
434 0 $self->logger->debug("Truncating chk file at <$chkSeek>");
435 0 truncate( $chkFh, $chkSeek );
436 }
437  
438 }
439 0 ▶ catch {
Subroutine __ANON__: not called CC=1 SCAR=6.9
440 0 croak $_;
441 }
442 0 ▶ finally {
Subroutine __ANON__: not called CC=4 SCAR=30.0
443 # If we opened the files (we got string with path), then we close them
444 # if we got a filehandle then we do nothing
445 0 ▶ if ($srcClose) {
Branch: 1 branch
BranchTrueFalseTotal
if ($srcClose) 0 0 0
446 0 $self->logger->debug( sprintf 'closing src file <%s>', $self->src );
447 }
448 0 ▶ if ($dstClose) {
Branch: 1 branch
BranchTrueFalseTotal
if ($dstClose) 0 0 0
449 0 $self->logger->debug( sprintf 'closing dst file <%s>', $self->dst );
450 }
451 0 ▶ if ($chkClose) {
Branch: 1 branch
BranchTrueFalseTotal
if ($chkClose) 0 0 0
452 0 $self->logger->debug( sprintf 'closing chk file <%s>', $self->chk );
453 }
454 0 };
455  
456 # Make Perl::Critic happy
457 0 return;
458 }
459  
460 ################################################################
461  
462 =begin comment
463  
464 Private
465 Get file handle
466  
467 =end comment
468  
469 =cut
470  
471 0 ▶sub _getFh {
Subroutine _getFh: not called CC=4 SCAR=30.0
472 0 my ( $self, $name, $file, $closeFile, $mode ) = @_;
473  
474 0 ▶ if ( my $t = reftype($file) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $t = builtin::reftype($file)) { } 0 0 0
475 0 ▶ if ( $t eq 'GLOB' ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($t eq 'GLOB') { } 0 0 0
476 0 $self->logger->debug(
477 sprintf '%s is a file handle, using that directly', $name );
478 0 return $file;
479 }
480 else {
481 0 $self->logger->logcroak(
482 sprintf '<%s> is not a supported type for %s',
483 $t, $name );
484 }
485 }
486 else {
487 0 $self->logger->debug( sprintf 'opening %s file <%s>', $name, $file );
488 0 ▶ sysopen( my $fh, $file, $mode )
Branch: 1 branch
BranchTrueFalseTotal
sysopen my $fh, $file, $mode or $self->logger->logcroak(sprintf('error opening <%s>', $file)) 0 0 0
489 || $self->logger->logcroak( sprintf 'error opening <%s>', $file );
490 0 ${$closeFile} = 1;
491 0 return $fh;
492 }
493  
494 # Make Perl::Critic happy
495 0 croak 'We should never end here!';
496 }
497  
498 ################################################################
499  
500 =head1 LICENSE AND COPYRIGHT
501  
502 This software is copyright (c) 2019 by Thor Dreier-Hansen.
503  
504 This is free software; you can redistribute it and/or modify it under
505 the same terms as the Perl 5 programming language system itself.
506  
507 Terms of the Perl programming language system itself:
508  
509 =over
510  
511 =item * the
512 L<GNU General Public License|http://dev.perl.org/licenses/gpl1.html>
513 as published by the Free Software Foundation; either
514 L<version 1|http://dev.perl.org/licenses/gpl1.html>,
515 or (at your option) any later version, or
516  
517 =item * the L<"Artistic License"|http://dev.perl.org/licenses/artistic.html>
518  
519 =back
520  
521 See L<http://dev.perl.org/licenses/> for more information.
522  
523 =cut
524  
525 1 1; # End of IO::BlockSync
↑ Summary BlockSync/App.pm »