blib/lib/File/SharedNFSLock.pm

filter: Statementstmt 80.5% 91 / 113 Branchbran 43.1% 19 / 44 Conditioncond 50.0% 3 / 6 MC/DCmcdc 25.0% 1 / 4 Subroutinesub 95.2% 20 / 21 Podpod 100% 6 / 6 totaltotal 72.1% 140 / 194 CC 25 SCAR 17.6
CC
25
Cov
69%
_is_stale_lock
20.0
lock
13.3
_write_lock_file
5.8
CRAP 5.8
↑ Summary
1 package File::SharedNFSLock;
2 2 ▶use 5.008001;
Subroutine BEGIN: called CC=1 SCAR=0.0
3 2 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 2 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 2 ▶use File::Spec;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 2 ▶use Sys::Hostname ();
Subroutine BEGIN: called CC=1 SCAR=0.0
7 2 ▶use Time::HiRes ();
Subroutine BEGIN: called CC=1 SCAR=0.0
8 2 ▶use Carp 'croak';
Subroutine BEGIN: called CC=1 SCAR=0.0
9  
10 2 ▶use constant STAT_NLINKS => 3;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 2 ▶use constant DEBUG => 0;
Subroutine BEGIN: called CC=1 SCAR=0.0
12  
13 2 our $VERSION = '0.04';
14  
15 =head1 NAME
16  
17 File::SharedNFSLock - Inter-machine advisory file locking on NFS volumes
18  
19 =head1 SYNOPSIS
20  
21 use File::SharedNFSLock;
22 my $flock = File::SharedNFSLock->new(
23 file => 'some_file_on_nfs',
24 );
25 my $got_lock = $flock->lock(); # blocks for $timeout_acquire seconds if necessary
26 if ($got_lock) {
27 # hack hack hack...
28 }
29 $flock->unlock;
30
31 # meanwhile, on another machine or in another process:
32 my $flock = File::SharedNFSLock->new(
33 file => 'some_file_on_nfs',
34 );
35 my $got_lock = $flock->lock(); # blocks for timeout or until first process is done
36 # ...
37  
38 =head1 DESCRIPTION
39  
40 This module implements advisory file locking on NFS (or non-NFS) filesystems.
41  
42 NFS (at least before v4) is evil. File locking on NFS volumes is worse. This
43 module attempts to implement file locking on NFS volumes using lock files and
44 hard links. It's in production use at our site, but if it doesn't work for you,
45 I'm not surprised!
46  
47 Note that the lock files are always written to the same directory as the original
48 file! There is always one lock file per process that tries to acquire the lock.
49 This module does B<NOT> do signal handling. You will have to do that yourself.
50  
51 =head2 ALGORITHM
52  
53 I use the fact that hard links are (err, appear to be) atomic even with NFS.
54 So I write a process-specific, unique lock file and then hard-link it to the
55 real thing. Afterwards, C<stat()> tells me the number of hard-linked instances
56 of the file (when polling my unique, private file). This indicates that I
57 have acquired the lock.
58  
59 The algorithm was snatched from a document called I<NFS Considered Harmful> by
60 I<Shane Kerr>. I found it at L<http://www.time-travellers.org/shane/papers/NFS_considered_harmful.html>.
61 Look for chapter III, I<List of Concerns>, concern I<d>: I<Exclusive File Creation>.
62 The described workaround is, I quote:
63  
64 The solution for performing atomic file locking using a lockfile
65 is to create a unique file on the same fs (e.g., incorporating
66 hostname and pid), use link(2) to make a link to the lockfile and
67 use stat(2) on the unique file to check if its link count has
68 increased to 2. Do not use the return value of the link() call.
69  
70 =head1 METHODS
71  
72 =head2 new
73  
74 Creates a new lock object but does B<NOT> attempt to acquire
75 the lock (see C<lock()> below). Takes named arguments.
76 All times in the parameters are in seconds and can
77 be floating point values, indicating a fraction of a second.
78  
79 Mandatory argument: I<file> pointing at the file that
80 is to be locked.
81  
82 Optional arguments: I<poll_interval> indicates
83 the number of seconds to wait between attempts to
84 acquire the lock. Defaults to 1 second.
85  
86 I<timeout_acquire> indicates the total
87 time that may be spent trying to acquire a lock when
88 C<lock()> is called. After this time has elapsed, we
89 bail out without having acquired a lock. Default: 60 seconds.
90 If set to 0, the lock acquisition effectively becomes non-blocking.
91  
92 I<timeout_stale> indicates the number of seconds since the creation of
93 an existing lock file, after which this alien lock file is to be considered stale.
94 A stale lock will be removed and replaced with our own lock (watch out!).
95 Default: 5 minutes. Set this to 0 to disable the feature.
96  
97 I<unique_token> is an optional parameter that will uniquely identify
98 the lock. If you want to attempt locking the same file from
99 the same process in different locations, they must set
100 a unique token (host name, process id and thread id are used additionally).
101 Set this to C<1> to have a random token auto-generated.
102  
103 =cut
104  
105 SCOPE: {
106 2 my @chars = ('a'..'z', 'A'..'Z', 0..9);
107 1 ▶ sub new {
Subroutine new: called CC=4 SCAR=16.3
Pod documented
108 1 my $class = shift;
109 1 my %args = @_;
110 croak("Need 'file' argument!")
111 1 ▶ if not defined $args{file};
Branch: 1 branch
BranchTrueFalseTotal
unless defined $args{"file"} 0 1 1
112  
113 1 my $uniquetoken = delete $args{unique_token};
114 1 ▶ if (defined $uniquetoken) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $uniquetoken) 0 1 1
115 0 ▶ if ($uniquetoken eq '1') {
Branch: 1 branch
BranchTrueFalseTotal
if ($uniquetoken eq '1') { } 0 0 0
116 0 $args{token} = join '', map $chars[rand @chars], (1..20);
117 }
118 else {
119 0 $args{token} = $uniquetoken;
120 }
121 }
122  
123 1 my $self = bless {
124 poll_interval => 1., # seconds
125 timeout_acquire => 60., # seconds
126 timeout_stale => 5*60., # seconds
127 token => '',
128 %args,
129 hostname => Sys::Hostname::hostname(),
130 } => $class;
131 1 if (DEBUG) {
132 warn "New lock for file '$self->{file}' (not acquired yet).\n"
133 ."Time out for acquisition: $self->{timeout_acquire}\n"
134 ."Time out for stale locks: $self->{timeout_stale}\n"
135 ."Poll interval : $self->{poll_interval}\n";
136 }
137 1 return $self;
138 }
139 } # end SCOPE
140  
141 =head2 lock
142  
143 Attempts to acquire a lock on the file.
144 Returns 1 on success, 0 on failure (time out).
145  
146 =cut
147  
148 2 ▶sub lock {
Subroutine lock: called CC=6 SCAR=25.8
Pod documented
149 1 my $self = shift;
150 1 warn "Getting lock on ".$self->{file}."\n" if DEBUG;
151  
152 1 ▶ return 1 if $self->got_lock;
Branch: 1 branch
BranchTrueFalseTotal
if $self->got_lock 0 1 1
153 1 warn "It is not locked already... ".$self->{file}."\n" if DEBUG;
154  
155 1 my $before_time = Time::HiRes::time();
156 1 warn "Before time is $before_time\n" if DEBUG;
157 1 while (1) {
158 1 ▶ if ($self->_write_lock_file()) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_write_lock_file) { } 1 0 1
159 1 return 1;
160 } else {
161 # check whether lock is stale
162 0 ▶ if ($self->_is_stale_lock) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_is_stale_lock) { } 0 0 0
163 0 unlink $self->_lock_file;
164 0 unlink $self->_unique_lock_file;
165 } else {
166 # hmm. lock valid, wait a bit or bail out
167 0 my $now = Time::HiRes::time();
168 0 warn "Time now is $now\n" if DEBUG;
169 0 ▶ if ($now-$before_time > $self->{timeout_acquire}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($now - $before_time > $self->{"timeout_acquire"}) 0 0 0
170 0 $self->_unlink_lock_file;
171 0 return 0;
172 }
173  
174 0 ▶ Time::HiRes::sleep($self->{poll_interval}) if $self->{poll_interval};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"poll_interval"} 0 0 0
175 }
176 }
177 } # end while(1)
178 }
179  
180 =head2 unlock
181  
182 Releases the lock, deletes the lock file.
183 This is automatically called on destruction of the
184 lock object!
185  
186 =cut
187  
188 2 ▶sub unlock {
Subroutine unlock: called CC=1 SCAR=0.0
Pod documented
189 2 my $self = shift;
190 2 $self->_unlink_lock_file;
191 }
192  
193 =head2 got_lock
194  
195 Checks whether we have the lock on the file. Prefer calling got_lock() instead
196 of its older form, locked().
197  
198 I<Note:> This is a fairly expensive operation requiring a C<stat> call.
199  
200 =cut
201  
202 8 ▶sub got_lock {
Subroutine got_lock: called CC=3 SCAR=11.0
Pod documented
203 8 my $self = shift;
204 # Check whether somebody else timed out the lock
205 8 my $nlinks = ( stat($self->_unique_lock_file) )[STAT_NLINKS];
206 8 ▶ if ( (defined $nlinks) and ($nlinks == 2) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $nlinks and $nlinks == 2) { } 3 5 8
Condition66%2/3
defined $nlinks and $nlinks == 2
!ll&&!rl&&r
503
MC/DC50%1/2
defined $nlinks and $nlinks == 2
defined $nlinks $nlinks == 2
Truth table66%2/3
A and B
A= defined $nlinksB= $nlinks == 2
ABresult
0X0
100
111
207 3 warn "got_lock: LOCKED with ".$self->_unique_lock_file."\n" if DEBUG;
208 3 return 1;
209 } else {
210 5 warn "got_lock: NOT LOCKED with ".$self->_unique_lock_file."\n" if DEBUG;
211 5 return 0;
212 }
213 }
214 2 *locked = \&got_lock;
215  
216 =head2 is_locked
217  
218 Checks file is currently locked by someone.
219  
220 =cut
221  
222 5 ▶sub is_locked {
Subroutine is_locked: called CC=2 SCAR=6.9
Pod documented
223 # Simply check for presence of lock_file
224 5 ▶ return (-f shift->_lock_file) ? 1 : 0;
Branch: 1 branch
BranchTrueFalseTotal
-f (shift())->_lock_file ? : 2 3 5
225 }
226  
227  
228 =head2 wait
229  
230 Wait until the file becomes free of any lock. This uses the I<poll_interval>
231 constructor passed to new().
232  
233 =cut
234  
235 1 ▶sub wait {
Subroutine wait: called CC=3 SCAR=14.2
Pod documented
236 1 my $self = shift;
237 1 ▶ while ( $self->is_locked ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->is_locked) 0 1 1
238 0 ▶ Time::HiRes::sleep($self->{poll_interval}) if $self->{poll_interval};
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"poll_interval"} 0 0 0
239 }
240 1 return 1;
241 }
242  
243 1 ▶sub DESTROY {
Subroutine DESTROY: called CC=1 SCAR=0.0
244 1 my $self = shift;
245 1 $self->unlock;
246 }
247  
248 2 ▶sub _unlink_lock_file {
Subroutine _unlink_lock_file: called CC=2 SCAR=6.9
249 2 my $self = shift;
250 2 ▶ if ($self->got_lock) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->got_lock) 1 1 2
251 1 warn "_unlink_lock_file: locked, removing main lock file\n" if DEBUG;
252 1 unlink($self->_lock_file);
253 }
254 2 warn "_unlink_lock_file: removing unique lock file\n" if DEBUG;
255 2 unlink($self->_unique_lock_file);
256 }
257  
258 1 ▶sub _write_lock_file {
Subroutine _write_lock_file: called CC=5 SCAR=17.6
259 1 my $self = shift;
260 1 my $unique_lock_file = $self->_unique_lock_file;
261 1 ▶ unlink($unique_lock_file) if -e $unique_lock_file;
Branch: 1 branch
BranchTrueFalseTotal
if -e $unique_lock_file 0 1 1
262  
263 # Create process-specific lock file
264 1 ▶ open my $fh, '>', $unique_lock_file
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, ">", $unique_lock_file or die "Could not open unique lock file for writing: $!" 1 0 1
265 or die "Could not open unique lock file for writing: $!";
266 1 print $fh Time::HiRes::time(), "\012", $unique_lock_file, "\012";
267 1 close $fh;
268  
269 # Attempt locking via linking
270 1 my $linked = link($unique_lock_file, $self->_lock_file);
271 1 ▶ if ( (not $linked) && ($! =~ m/not permitted/i) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $linked and $! =~ /not permitted/i) 0 1 1
Condition33%1/3
not $linked and $! =~ /not permitted/i
!ll&&!rl&&r
100
MC/DC0%0/2
not $linked and $! =~ /not permitted/i
not $linked $! =~ /not permitted/i
Truth table33%1/3
not(A) and B
A= not $linkedB= $! =~ /not permitted/i
ABresult
0X0
100
111
272 0 die "Error: The filesystem that holds file ".$self->{file}." does not ".
273 "support link().\n";
274 }
275  
276 1 return $self->got_lock
277 }
278  
279 11 ▶sub _unique_lock_file {
Subroutine _unique_lock_file: called CC=3 SCAR=11.0
280 11 my $self = shift;
281 11 ▶ return $self->{unique_lock_file} if defined $self->{unique_lock_file};
Branch: 1 branch
BranchTrueFalseTotal
if defined $self->{"unique_lock_file"} 10 1 11
282 1 ▶ my $thread_id = exists $INC{'threads.pm'} ? threads->tid : '';
Branch: 1 branch
BranchTrueFalseTotal
exists $INC{'threads.pm'} ? : 0 1 1
283 my $unique_lock_file = join( '.',
284 1 $self->_lock_file, $self->{hostname}, $$, $thread_id, $self->{token});
285 1 $self->{unique_lock_file} = $unique_lock_file;
286 1 return $self->{unique_lock_file};
287 }
288  
289 8 ▶sub _lock_file {
Subroutine _lock_file: called CC=2 SCAR=6.9
290 8 my $self = shift;
291 8 ▶ return $self->{lock_file} if defined $self->{lock_file};
Branch: 1 branch
BranchTrueFalseTotal
if defined $self->{"lock_file"} 7 1 8
292 1 my ($volume, $path, $lock_file) = File::Spec->splitpath( $self->{file} );
293 1 $lock_file .= '.lock';
294 1 $lock_file = File::Spec->catpath($volume, $path, $lock_file);
295 1 $self->{lock_file} = $lock_file;
296 1 return $lock_file;
297 }
298  
299 0 ▶sub _is_stale_lock {
Subroutine _is_stale_lock: not called CC=4 SCAR=30.0
300 0 my $self = shift;
301 0 ▶ return 0 if not $self->{timeout_stale};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"timeout_stale"} 0 0 0
302  
303 0 ▶ open my $fh, '<', $self->_lock_file # race?
Branch: 1 branch
BranchTrueFalseTotal
open my $fh, "<", $self->_lock_file or return 1 0 0 0
304 or return 1; # FIXME warning?
305  
306 0 local $/ = "\012";
307 0 my @lines = <$fh>;
308 0 ▶ if (Time::HiRes::time()-$lines[0] > $self->{timeout_stale}) {
Branch: 1 branch
BranchTrueFalseTotal
if (&Time::HiRes::time() - $lines[0] > $self->{"timeout_stale"}) 0 0 0
309 0 return 1;
310 }
311 0 return 0;
312 }
313  
314 2 1;
315  
316 __END__
↑ Summary