blib/lib/IPC/Lock/WithTTL.pm

filter: Statementstmt 98.6% 71 / 72 Branchbran 80.7% 21 / 26 Conditioncond 60.0% 3 / 5 MC/DCmcdc 33.3% 1 / 3 Subroutinesub 100% 11 / 11 Podpod 75.0% 3 / 4 totaltotal 90.9% 110 / 121 CC 16 SCAR 21.3
CC
16
Cov
92%
acquire
14.3
_fh
3.0
BEGIN
1.0
CRAP 8.4
↑ Summary
1 package IPC::Lock::WithTTL;
2  
3 6 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 6 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 6 our $VERSION = '0.01';
7  
8 6 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 6 ▶use Smart::Args;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 use Class::Accessor::Lite (
11 6 rw => [qw(ttl)],
12 ro => [qw(file kill_old_proc)],
13 6 ▶ );
Subroutine BEGIN: called CC=1 SCAR=0.0
14 6 ▶use Fcntl qw(:DEFAULT :flock :seek);
Subroutine BEGIN: called CC=1 SCAR=0.0
15  
16 sub new {
17 5 ▶ args(my $class,
Subroutine new: called CC=1 SCAR=0.0
Pod documented
18 my $file => { isa => 'Str' },
19 my $ttl => { isa => 'Int', default => 0 },
20 my $kill_old_proc => { isa => 'Bool', default => 0 },
21 );
22  
23 5 my $self = bless {
24 file => $file,
25 ttl => $ttl,
26 kill_old_proc => $kill_old_proc,
27 #
28 _fh => undef,
29 }, $class;
30  
31 5 return $self;
32 }
33  
34 sub _fh {
35 17 ▶ args(my $self);
Subroutine _fh: called CC=3 SCAR=11.0
36  
37 17 ▶ unless ($self->{_fh}) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->{"_fh"}) 5 12 17
38 5 ▶ open $self->{_fh}, '+>>', $self->file or croak $!;
Branch: 1 branch
BranchTrueFalseTotal
open $self->{"_fh"}, "+>>", $self->file or croak($!) 0 5 5
39 }
40  
41 17 return $self->{_fh};
42 }
43  
44 sub acquire {
45 9 ▶ args(my $self,
Subroutine acquire: called CC=14 SCAR=26.6
Pod documented
46 my $ttl => { isa => 'Int', optional => 1 },
47 );
48 9 ▶ $self->ttl($ttl) if $ttl;
Branch: 1 branch
BranchTrueFalseTotal
if $ttl 0 9 9
49  
50 9 my $fh = $self->_fh;
51 9 ▶ flock $fh, LOCK_EX or return;
Branch: 1 branch
BranchTrueFalseTotal
flock $fh, 2 or return 0 9 9
52  
53 9 seek $fh, 0, SEEK_SET;
54 9 my($heartbeat) = <$fh>;
55 9 ▶ $heartbeat ||= "0 0";
Condition100%2/2
$heartbeat ||= "0 0"
l!l
63
MC/DC100%1/1
$heartbeat ||= "0 0"
$heartbeat
Truth table100%2/2
A
A= $heartbeat
Aresult
11
00
56 9 my($pid, $expiration) = split /\s+/, $heartbeat;
57 9 $pid += 0; $expiration += 0;
58  
59 9 my $now = time();
60 9 my $new_expiration;
61 9 my $acquired = 0;
62 9 ▶ if ($pid == 0) {
Branch: 2 branches
BranchTrueFalseTotal
if ($pid == 0) { } 5 4 9
elsif ($pid != $$) { } 2 2 4
63 # Previous task finished successfully
64 5 ▶ if ($now >= $expiration) {
Branch: 1 branch
BranchTrueFalseTotal
if ($now >= $expiration) { } 4 1 5
65 # expired
66 4 $new_expiration = $self->update_heartbeat;
67 4 $acquired = 1;
68 } else {
69 # not expired
70 1 $acquired = 0;
71 }
72 } elsif ($pid != $$) {
73 # Other task is in process?
74 2 ▶ if ($now >= $expiration) {
Branch: 1 branch
BranchTrueFalseTotal
if ($now >= $expiration) { } 1 1 2
75 # expired (Last task may have terminated abnormally)
76 1 $new_expiration = $self->update_heartbeat;
77  
78 1 ▶ if ($self->kill_old_proc && $pid > 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->kill_old_proc and $pid > 0) 0 1 1
Condition33%1/3
$self->kill_old_proc and $pid > 0
!ll&&!rl&&r
100
MC/DC0%0/2
$self->kill_old_proc and $pid > 0
$self->kill_old_proc $pid > 0
Truth table33%1/3
A and B
A= $self->kill_old_procB= $pid > 0
ABresult
0X0
100
111
79 0 kill 'KILL', $pid;
80 }
81 1 $acquired = 1;
82 } else {
83 # not expired (Still running)
84 1 $acquired = 0;
85 }
86 } else {
87 # Previous task done by this process
88 2 ▶ if ($now >= $expiration) {
Branch: 1 branch
BranchTrueFalseTotal
if ($now >= $expiration) { } 1 1 2
89 # expired (Last task may have terminated abnormally)
90 1 $new_expiration = $self->update_heartbeat;
91 1 $acquired = 1;
92 } else {
93 # not expired (Last task may have terminated abnormally)
94 1 $new_expiration = $self->update_heartbeat;
95 1 $acquired = 1;
96 }
97 }
98  
99 9 flock $fh, LOCK_UN;
100 9 ▶ if ($acquired) {
Branch: 1 branch
BranchTrueFalseTotal
if ($acquired) { } 7 2 9
101 7 ▶ return wantarray ? (1, { pid => $$, expiration => $new_expiration })
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 6 1 7
102 : 1;
103 } else {
104 2 ▶ return wantarray ? (0, { pid => $pid, expiration => $expiration })
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 2 0 2
105 : 0;
106 }
107 }
108  
109 sub release {
110 1 ▶ args(my $self);
Subroutine release: called CC=1 SCAR=0.0
Pod documented
111  
112 1 $self->update_heartbeat(pid => 0);
113 1 undef $self->{_fh};
114  
115 1 return 1;
116 }
117  
118 sub update_heartbeat {
119 8 ▶ args(my $self,
Subroutine update_heartbeat: called CC=1 SCAR=0.0
Pod undocumented
120 my $pid => { isa => 'Int', default => $$ },
121 );
122  
123 8 my $fh = $self->_fh;
124  
125 8 my $expiration = time() + $self->ttl;
126  
127 8 seek $fh, 0, SEEK_SET;
128 8 truncate $fh, 0;
129 8 print {$fh} join(' ', $pid, $expiration)."\n";
130  
131 8 return $expiration;
132 }
133  
134 6 1;
135  
136 __END__
137  
138 =encoding utf-8
139  
140 =head1 NAME
141  
142 IPC::Lock::WithTTL - run only one process up to given timeout
143  
144 =head1 SYNOPSIS
145  
146 use IPC::Lock::WithTTL;
147
148 my $lock = IPC::Lock::WithTTL->new(
149 file => '/tmp/lockme',
150 ttl => 5,
151 kill_old_proc => 0,
152 );
153
154 my($r, $hb) = $lock->acquire;
155
156 if ($r) {
157 infof("Got lock! yay!!");
158 } else {
159 critf("Cannot get lock. Try after at %d", $hb->{expiration});
160 exit 1;
161 }
162
163 $lock->release;
164  
165 =head1 DESCRIPTION
166  
167 IPC::Lock::WithTTL provides inter process locking feature.
168 This locking has timeout feature, so we can use following cases:
169  
170 * Once send an alert email, don't send same kind of alert email within 10 minutes.
171 * We want to prevent the situation that script for failover some system is invoked more than one processes at same time and invoked many times in short time.
172  
173 =head1 DETAIL
174  
175 =head2 SEQUENCE
176  
177 1. flock a heartbeat file (specified by file param in new) with LOCK_EX
178 return if failed to flock.
179 2. read a heartbeat file and examine PID and expiration (describe later)
180 return if I should not go ahead.
181 3. update a heartbeat file with my PID and new expiration.
182 4. ACQUIRED LOCK
183 5. unlock a lock file.
184 6. process main logic.
185 7. RELEASE LOCK with calling $lock->release method.
186 In that method update a heartbeat file with PID=0 and new expiration.
187  
188 =head2 DETAIL OF EXAMINATION OF PID AND EXPIRATION
189  
190 Format of a heartbeat file (lock file) is:
191  
192 PID EXPIRATION
193  
194 Next action table by PID and expiration
195  
196 PID expired? Next action Description
197 =========================================================================
198 not mine yes acquired lock*1 Another process is running or
199 - - - - - - - - - - - - - - - - - - exited abnormally (without leseasing
200 not mine no return lock).
201 -------------------------------------------------------------------------
202 mine yes acquired lock Previously myself acquired lock but
203 - - - - - - - - - - - - - - - - - - does not release lock.
204 mine no acquired lock
205 -------------------------------------------------------------------------
206 0 yes acquired lock Previously someone acquired and
207 - - - - - - - - - - - - - - - - - - released lock successfully.
208 0 no return
209 -------------------------------------------------------------------------
210
211 *1 try to kill another process if you enable kill_old_proc option in new().
212  
213 =head1 METHODS
214  
215 =over 4
216  
217 =item B<new>($args:Hash)
218  
219 file => Str (required)
220 File path of heartbeat file. IPC::Lock::WithTTL also flock this file.
221
222 ttl => Int (default is 0)
223 TTL to exipire. expiration time set to now + TTL.
224
225 kill_old_proc => Boolean (default is 0)
226 Try to kill old process which might exit abnormally.
227  
228 =item B<acquire>(ttl => $TTL:Int)
229  
230 Try to acquire lock. ttl option set TTL to expire (override ttl in new())
231  
232 This method returns scalar or list by context.
233  
234 Scalar context
235 =========================================================================
236 Acquired lock successfully
237 1
238 -----------------------------------------------------------------------
239 Failed to acquire lock
240 0
241
242 List context
243 =========================================================================
244 Acquired lock successfully
245 (1, { pid => PID, expiration => time_to_expire })
246 PID is mine. expiration is setted by me.
247 -----------------------------------------------------------------------
248 Failed to acquire lock
249 (0, { pid => PID, expiration => time_to_expire })
250 PID is another process. expiration is setted by another process.
251  
252 =item B<release>()
253  
254 Update a heartbeat file (PID=0 and new expiration) and release lock.
255  
256 =back
257  
258 =head1 AUTHOR
259  
260 HIROSE Masaaki E<lt>hirose31 _at_ gmail.comE<gt>
261  
262 =head1 REPOSITORY
263  
264 L<https://github.com/hirose31/IPC-Lock-WithTTL>
265  
266 git clone git://github.com/hirose31/IPC-Lock-WithTTL.git
267  
268 patches and collaborators are welcome.
269  
270 =head1 SEE ALSO
271  
272 L<IPC::Lock|IPC::Lock>
273  
274 =head1 LICENSE
275  
276 This library is free software; you can redistribute it and/or modify
277 it under the same terms as Perl itself.
278  
279 =cut
280  
281 # for Emacsen
282 # Local Variables:
283 # mode: cperl
284 # cperl-indent-level: 4
285 # indent-tabs-mode: nil
286 # coding: utf-8
287 # End:
288  
289 # vi: set ts=4 sw=4 sts=0 :
↑ Summary