blib/lib/File/TinyLock.pm

filter: Statementstmt 79.5% 74 / 93 Branchbran 55.5% 30 / 54 Conditioncond 33.3% 2 / 6 MC/DCmcdc 25.0% 1 / 4 Subroutinesub 90.0% 9 / 10 Podpod 25.0% 1 / 4 totaltotal 68.4% 117 / 171 SCAR 41.2
CC
32
Cov
69%
new
36.8
checklock
9.7
lock
8.6
CRAP 61.7
↑ Summary
1 # File::TinyLock.pm
2 # $Id: TinyLock.pm,v 1.11 2014/09/12 20:15:33 jkister Exp $
3 # Copyright (c) 2006-2014 Jeremy Kister.
4 # Released under Perl's Artistic License.
5  
6 =head1 NAME
7  
8 File::TinyLock - Utility for process locking and unlocking.
9  
10 =head1 SYNOPSIS
11  
12 use File::TinyLock;
13  
14 my $LOCK = '/tmp/testing.lock';
15  
16 my $locksmith = File::TinyLock->new(lock => $LOCK);
17 if( $locksmith->lock() ){
18 warn "we have locked\n";
19 $locksmith->unlock();
20 warn "we have unlocked\n";
21 }else{
22 warn "could not lock..\n";
23 }
24
25 =head1 DESCRIPTION
26  
27 C<File::TinyLock> provides C<lock>, C<unlock>, and C<checklock> methods for
28 working with process locking. This utility attempts to be useful when you
29 require one of a process to be running at a time, but someone could possibly
30 try to spawn off a second (such as having a crontab where you are *hoping*
31 one job ends before the next starts).
32  
33 =head1 CONSTRUCTOR
34  
35 =over 4
36  
37 =item lock( [LOCK] [,OPTIONS] );
38  
39 C<LOCK> is a mandatory lock file.
40  
41 C<OPTIONS> are passed in a hash like fashion, using key and value
42 pairs. Possible options are:
43  
44 B<mylock> - Unique file to identify our process (Default: auto-generated)
45 - *must* be on the same filesystem as <LOCK>
46  
47 B<retries> - Number of times to retry getting a lock (Default: 5)
48  
49 B<retrydelay> - Number of seconds to wait between retries (Default: 60)
50  
51 B<debug> - Print debugging info to STDERR (0=Off, 1=On) (Default: 0).
52  
53 =head1 RETURN VALUE
54  
55 Here are a list of return codes of the C<lock> function and what they mean:
56  
57 =item 0 The process could not get a lock.
58  
59 =item 1 The process has obtained a lock.
60  
61 .. and for the C<checklock> function:
62  
63 =item 0 The process does not have a lock.
64  
65 =item 1 The process has a lock.
66  
67 .. and the C<unlock> function:
68  
69 =item Note: method will die if we cannot modify <LOCK>
70  
71 =head1 EXAMPLES
72  
73 # run the below code twice ( e.g. perl ./test.pl & ; perl ./test.pl )
74  
75 use strict;
76 use File::TinyLock;
77  
78 my $lock = '/tmp/testing.lock';
79 my $locksmith = File::TinyLock->new(lock => $lock, debug => 1);
80  
81 my $result = $locksmith->lock();
82 if($result){
83 print "We have obtained a lock\n";
84 }
85
86 # do stuff
87  
88 sleep 30;
89  
90 $locksmith->unlock();
91 exit;
92  
93  
94 =head1 CAVEATS
95  
96 If you leave lock files around (from not unlocking the file before
97 your code exits), C<File::TinyLock> will try its best to clean up
98 and/or determine if the lock files are stale or not. This is best
99 effort, and may yield false positives. For example, if your code
100 was running as pid 1234 and crashed without unlocking, stale
101 detection may fail if there is a new process running with pid 1234.
102  
103 =head1 RESTRICTIONS
104  
105 Locking will only remain successfull while your code is active. You
106 can not lock, let your code exit, and start your code again - doing
107 so will result in stale lock files left behind.
108  
109 start code -> get lock -> do stuff -> unlock -> exit;
110  
111 =head1 AUTHOR
112  
113 <a href="http://jeremy.kister.net./">Jeremy Kister</a>
114  
115 =cut
116  
117 package File::TinyLock;
118  
119 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
120 1 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
121  
122 1 my %_mylocks;
123  
124 1 our ($VERSION) = q$Revision: 1.11 $ =~ /(\d+\.\d+)/;
125  
126 sub new {
127 2 ▶ my $class = shift;
Subroutine new: called CC=13 SCAR=36.0
Pod undocumented
128 2 my %args;
129 2 ▶ if(@_ % 2){
Branch: 1 branch
BranchTrueFalseTotal
if (@_ % 2) { } 0 2 2
130 0 my $lock = shift;
131 0 %args = @_;
132 0 $args{lock} = $lock;
133 }else{
134 2 %args = @_;
135 }
136  
137 2 ▶ die "$class: must specify lock\n" unless($args{lock});
Branch: 1 branch
BranchTrueFalseTotal
unless $args{"lock"} 0 2 2
138 2 $ENV{PATH} .= '/bin:/usr/bin';
139  
140 2 my $self = bless(\%args, $class);
141  
142 2 $self->{class} = $class;
143 2 ▶ $self->{retries} = 5 unless(defined($args{retries}));
Branch: 1 branch
BranchTrueFalseTotal
unless defined $args{"retries"} 1 1 2
144 2 ▶ $self->{retrydelay} = 60 unless(defined($args{retrydelay}));
Branch: 1 branch
BranchTrueFalseTotal
unless defined $args{"retrydelay"} 0 2 2
145 2 $self->{_have_lock} = 0;
146  
147 2 ▶ if( $self->{mylock} ){
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{'mylock'}) { } 2 0 2
148 # must be on the same filesystem as {lock}
149 2 ▶ if($self->{lock} eq $self->{mylock}){
Branch: 3 branches
BranchTrueFalseTotal
if ($self->{'lock'} eq $self->{'mylock'}) { } 0 2 2
elsif ($_mylocks{$self->{'mylock'}}) { } 0 2 2
elsif (-f $self->{'mylock'}) { } 0 2 2
150 0 die "$class: lock and mylock may not be the same file\n";
151 }elsif( $_mylocks{ $self->{mylock} } ){
152 0 die "$class: already using mylock of $self->{mylock}\n";
153 }elsif( -f $self->{mylock} ){
154 0 die "$class: $self->{mylock} already exists\n";
155 }
156 }else{
157 # generate mylock - we could be used several times in the same code
158 0 for my $i (0 .. 10_000){ # could do while(1)...
159 0 my $mylock = $self->{lock} . $i . $$;
160 0 ▶ unless( $_mylocks{ $mylock } || -f $mylock ){
Branch: 1 branch
BranchTrueFalseTotal
unless ($_mylocks{$mylock} or -f $mylock) 0 0 0
Condition0%0/3
$_mylocks{$mylock} or -f $mylock
l!l&&r!l&&!r
000
MC/DC0%0/2
$_mylocks{$mylock} or -f $mylock
$_mylocks{$mylock} -f $mylock
Truth table0%0/3
A or B
A= $_mylocks{$mylock}B= -f $mylock
ABresult
1X1
011
000
161 0 $self->{mylock} = $mylock;
162 0 last;
163 }
164 }
165 0 ▶ die "$class: couldnt generate mylock: 10,000 found!\n" unless( $self->{mylock} );
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"mylock"} 0 0 0
166 }
167 2 $_mylocks{ $self->{mylock} } = 1;
168  
169 2 return($self);
170 }
171  
172 sub lock {
173 2 ▶ my $self = shift;
Subroutine lock: called CC=8 SCAR=21.5
Pod documented
174  
175 2 ▶ $SIG{HUP} = $SIG{QUIT} = $SIG{INT} = $SIG{TERM} = sub { $self->_debug( "caught SIG$_[0]" ); exit; };
Subroutine __ANON__: not called CC=1 SCAR=2.6
176  
177 2 ▶ if( open( my $fh, '>', $self->{mylock} ) ){
Branch: 1 branch
BranchTrueFalseTotal
if (open my $fh, '>', $self->{'mylock'}) { } 2 0 2
178 2 print $fh "$$:$self->{mylock}\n";
179 2 close $fh;
180  
181 2 for my $try (0 .. $self->{retries}){
182 4 ▶ unless( $self->checklock() ){
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->checklock) 1 3 4
183 1 ▶ if( link($self->{mylock}, $self->{lock}) ){
Branch: 1 branch
BranchTrueFalseTotal
if (link $self->{"mylock"}, $self->{"lock"}) 1 0 1
184 1 $self->{_have_lock} = 1;
185 1 $self->_debug( "got lock." );
186 1 return 1;
187 }
188 }
189 3 ▶ if($self->{retries} && ($try != $self->{retries})){
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"retries"} and $try != $self->{"retries"}) 2 1 3
Condition66%2/3
$self->{"retries"} and $try != $self->{"retries"}
!ll&&!rl&&r
012
MC/DC50%1/2
$self->{"retries"} and $try != $self->{"retries"}
$self->{"retries"} $try != $self->{"retries"}
Truth table66%2/3
A and B
A= $self->{"retries"}B= $try != $self->{"retries"}
ABresult
0X0
100
111
190 2 $self->_debug( "retrying in $self->{retrydelay} seconds" );
191 2 ▶ sleep $self->{retrydelay} unless($try == $self->{retries});
Branch: 1 branch
BranchTrueFalseTotal
unless $try == $self->{"retries"} 2 0 2
192 }
193 }
194 }else{
195 0 $self->_warn( "could not write to $self->{mylock}: $!" );
196 }
197 1 $self->_warn( "could not get lock" );
198 1 unlink( $self->{mylock} );
199 1 return 0;
200 }
201  
202 sub checklock {
203 4 ▶ my $self = shift;
Subroutine checklock: called CC=8 SCAR=22.7
Pod undocumented
204
205 4 ▶ if( open(my $fh, $self->{lock}) ){
Branch: 1 branch
BranchTrueFalseTotal
if (open my $fh, $self->{'lock'}) { } 3 1 4
206 3 chomp(my $line = <$fh>);
207 3 close $fh;
208 3 my($pid,$mylock) = split(/:/, $line, 2);
209  
210 3 $self->_debug( "found $pid in $self->{lock}" );
211 3 ▶ if( open(my $ps, "ps -e |") ){
Branch: 1 branch
BranchTrueFalseTotal
if (open my $ps, 'ps -e |') { } 3 0 3
212 3 my $stale = 1;
213 3 ▶ while(<$ps>){
Branch: 1 branch
BranchTrueFalseTotal
if (defined($_ = readline $ps)) 27 0 27
214 27 ▶ if(/^\s*${pid}\s*/){
Branch: 1 branch
BranchTrueFalseTotal
if (/^\s*$pid\s*/) 3 24 27
215 3 $stale = 0;
216 3 $self->_debug( "found $pid is running" );
217 3 last;
218 }
219 }
220 3 close $ps;
221  
222 3 ▶ if($stale){
Branch: 1 branch
BranchTrueFalseTotal
if ($stale) { } 0 3 3
223 0 ▶ unlink($mylock) || $self->_warn( "could not unlink $mylock: $!" );
Branch: 1 branch
BranchTrueFalseTotal
unlink $mylock or $self->_warn("could not unlink ${mylock}: $!") 0 0 0
224 0 ▶ unlink($self->{lock}) || die "could not unlink $self->{lock}: $!";
Branch: 1 branch
BranchTrueFalseTotal
unlink $self->{"lock"} or die qq[could not unlink $self->{"lock"}: $!] 0 0 0
225 0 $self->_debug( "found and cleaned stale lock." );
226 }else{
227 3 $self->_debug( "found valid existing lock." );
228 3 return 1;
229 }
230  
231 }else{
232 0 $self->_warn( "cannot tell if lock is stale - could not fork ps: $!" );
233 }
234 }else{
235 1 $self->_debug( "could not read $self->{lock}: $!" );
236 }
237 1 return 0;
238 }
239  
240  
241 sub unlock {
242 2 ▶ my $self = shift;
Subroutine unlock: called CC=5 SCAR=16.2
Pod undocumented
243  
244 2 ▶ if( -f $self->{mylock} ){
Branch: 1 branch
BranchTrueFalseTotal
if (-f $self->{"mylock"}) 1 1 2
245 1 ▶ unlink($self->{mylock}) || $self->_warn( "cannot unlink mylock ( $self->{mylock} ): $!" );
Branch: 1 branch
BranchTrueFalseTotal
unlink $self->{"mylock"} or $self->_warn(qq[cannot unlink mylock ( $self->{"mylock"} ): $!]) 0 1 1
246 }
247  
248 2 ▶ if($self->{_have_lock}){
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"_have_lock"}) 1 1 2
249 1 ▶ unlink($self->{lock}) || die "cannot unlink lock ( $self->{lock} ): $!\n";
Branch: 1 branch
BranchTrueFalseTotal
unlink $self->{"lock"} or die qq[cannot unlink lock ( $self->{"lock"} ): $!\n] 0 1 1
250 1 $self->{_have_lock} = 0;
251 }
252 }
253  
254 sub _warn {
255 15 ▶ my $self = shift;
Subroutine _warn: called CC=1 SCAR=0.0
256 15 my $msg = join('', @_);
257  
258 15 warn "$self->{class}: $msg\n";
259 }
260  
261 sub _debug {
262 14 ▶ my $self = shift;
Subroutine _debug: called CC=2 SCAR=7.2
263  
264 14 ▶ $self->_warn(@_) if($self->{debug});
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"debug"} 14 0 14
265 }
266  
267 sub DESTROY {
268 1 ▶ my $self = shift;
Subroutine DESTROY: called CC=1 SCAR=0.0
269  
270 1 $self->_debug( "cleaning up.." );
271 1 $self->unlock();
272  
273 }
274  
275 1 1;
↑ Summary