Lite/Lock.pm

filter: Statementstmt 95.6% 66 / 69 Branchbran 77.2% 17 / 22 Conditioncond 66.6% 16 / 24 MC/DCmcdc 33.3% 4 / 12 Subroutinesub 100% 11 / 11 Podpod 0.0% 0 / 2 totaltotal 81.4% 114 / 140 CC 24 SCAR 18.3
CC
24
Cov
86%
new
10.1
_try_steal_if_stale
7.2
_try_create
6.3
CRAP 6.2
↑ Summary Lite/Logger.pm »
1 package Amazon::S3::Lite::Lock;
2  
3 # Mutual exclusion over an S3 object, built on Amazon::S3::Lite's
4 # conditional-header support (If-None-Match / If-Match) and last_status.
5 #
6 # The correctness rests on three server-side atomic operations:
7 # acquire PUT If-None-Match:* -> 200 win / 412 held
8 # steal-stale PUT If-Match:<stale-etag> -> 200 win / 412 someone-beat-me
9 # release DELETE If-Match:<my-etag> -> only ever deletes MY lock
10 #
11 # The lock object's body carries an expiry timestamp written by the
12 # holder, so "is it stale?" is judged against a deadline the holder
13 # set, not against each waiter's own clock.
14 #
15 # acquire() returns a guard object; when the guard goes out of scope
16 # (normal return OR die), DESTROY releases the lock. TTL/steal-stale
17 # is the backstop for hard kills where DESTROY never runs.
18  
19 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
20 1 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
21  
22 1 ▶use Carp qw(croak);
Subroutine BEGIN: called CC=1 SCAR=0.0
23 1 ▶use Data::Dumper;
Subroutine BEGIN: called CC=1 SCAR=0.0
24 1 ▶use English qw(-no_match_vars);
Subroutine BEGIN: called CC=1 SCAR=0.0
25 1 ▶use JSON qw(encode_json decode_json);
Subroutine BEGIN: called CC=1 SCAR=0.0
26  
27 1 our $VERSION = '1.3.3';
28  
29 ########################################################################
30 4 ▶sub new {
Subroutine new: called CC=9 SCAR=23.1
Pod undocumented
31 ########################################################################
32 4 my ( $class, %args ) = @_;
33  
34 my $self = bless {
35 s3 => $args{s3}, # Amazon::S3::Lite instance (required)
36 bucket => $args{bucket}, # required
37 key => $args{key} // 'locks/default.lock',
38 ttl => $args{ttl} // 120, # seconds a lock is considered fresh
39 owner => $args{owner} // sprintf( '%s@%s', $PID, $ENV{HOSTNAME} // 'unknown' ),
40 wait => $args{wait} // 0, # seconds to block waiting; 0 = no wait
41 4 ▶ poll => $args{poll} // 2, # seconds between acquire retries
Condition75%9/12
$args{"key"} // "locks/default.lock"
l!l
40
$args{"ttl"} // 120
l!l
13
$args{"owner"} // sprintf("%s\@%s", $Amazon::S3::Lite::Lock::PID, $ENV{"HOSTNAME"} // "unknown")
l!l
22
$ENV{"HOSTNAME"} // "unknown"
l!l
20
$args{"wait"} // 0
l!l
31
$args{"poll"} // 2
l!l
04
MC/DC0%0/1
$args{"key"} // "locks/default.lock"
$args{"key"}
MC/DC100%1/1
$args{"ttl"} // 120
$args{"ttl"}
MC/DC100%1/1
$args{"owner"} // sprintf("%s\@%s", $Amazon::S3::Lite::Lock::PID, $ENV{"HOSTNAME"} // "unknown")
$args{"owner"}
MC/DC0%0/1
$ENV{"HOSTNAME"} // "unknown"
$ENV{"HOSTNAME"}
MC/DC100%1/1
$args{"wait"} // 0
$args{"wait"}
MC/DC0%0/1
$args{"poll"} // 2
$args{"poll"}
Truth table50%1/2
A
A= $args{"key"}
Aresult
11
00
Truth table100%2/2
A
A= $args{"ttl"}
Aresult
11
00
Truth table100%2/2
A
A= $args{"owner"}
Aresult
11
00
Truth table50%1/2
A
A= $ENV{"HOSTNAME"}
Aresult
11
00
Truth table100%2/2
A
A= $args{"wait"}
Aresult
11
00
Truth table50%1/2
A
A= $args{"poll"}
Aresult
11
00
42 }, $class;
43  
44 croak 's3 is required'
45 4 ▶ if !$self->{s3};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"s3"} 0 4 4
46  
47 croak 'bucket is required'
48 4 ▶ if !$self->{bucket};
Branch: 1 branch
BranchTrueFalseTotal
unless $self->{"bucket"} 0 4 4
49  
50 4 return $self;
51 }
52  
53 ########################################################################
54 4 ▶sub acquire {
Subroutine acquire: called CC=5 SCAR=16.1
Pod undocumented
55 ########################################################################
56 4 my ($self) = @_;
57  
58 # Try to create the lock only if absent. On 412 the lock is held;
59 # decide whether it's stale and, if so, steal it. Optionally block
60 # up to {wait} seconds, polling every {poll}.
61 4 my $deadline = time + $self->{wait};
62  
63 4 while (1) {
64 {
65 5 my $etag = $self->_try_create; # 200 -> etag, 412 -> undef
66 5 ▶ return $self->_guard($etag) if $etag;
Branch: 1 branch
BranchTrueFalseTotal
if $etag 2 3 5
67 }
68  
69 # Held. Is it stale?
70 3 my ( $status, $etag ) = $self->_try_steal_if_stale;
71  
72 3 ▶ return $self->_guard($etag)
Branch: 1 branch
BranchTrueFalseTotal
if $status eq "stolen" 1 2 3
73 if $status eq 'stolen';
74  
75 next
76 2 ▶ if $status eq 'vanished';
Branch: 1 branch
BranchTrueFalseTotal
if $status eq "vanished" 1 1 2
77  
78 last
79 1 ▶ if time >= $deadline;
Branch: 1 branch
BranchTrueFalseTotal
if time >= $deadline 1 0 1
80  
81 0 sleep $self->{poll};
82 }
83  
84 1 return; # could not acquire (caller checks truthiness)
85 }
86  
87 ########################################################################
88 5 ▶sub _try_create {
Subroutine _try_create: called CC=6 SCAR=18.4
89 ########################################################################
90 5 my ($self) = @_;
91  
92 5 my $body = encode_json( { owner => $self->{owner}, expires => time + $self->{ttl} } );
93  
94 $self->{s3}
95 5 ->logger->debug( sprintf 'lock acquire: bucket=%s key=%s owner=%s', $self->{bucket}, $self->{key}, $self->{owner}, );
96  
97 5 my $etag = eval {
98 $self->{s3}->put_object(
99 5 $self->{bucket}, $self->{key}, $body,
100 content_type => 'application/json',
101 headers => { 'If-None-Match' => q{*} },
102 );
103 };
104  
105 5 my $err = $EVAL_ERROR;
106  
107 $self->{s3}->logger->debug(
108 sprintf 'lock create: status=%s etag=%s error=%s',
109 5 ▶ $self->{s3}->last_status // q{},
Condition66%4/6
$self->{"s3"}->last_status // ""
l!l
50
$etag // ""
l!l
23
$err // ""
l!l
50
MC/DC0%0/1
$self->{"s3"}->last_status // ""
$self->{"s3"}->last_status
MC/DC100%1/1
$etag // ""
$etag
MC/DC0%0/1
$err // ""
$err
Truth table50%1/2
A
A= $self->{"s3"}->last_status
Aresult
11
00
Truth table100%2/2
A
A= $etag
Aresult
11
00
Truth table50%1/2
A
A= $err
Aresult
11
00
110 $etag // q{},
111 $err // q{},
112 );
113  
114 return $etag
115 5 ▶ if $self->{s3}->last_status =~ /\A2/xsm; # acquired
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"s3"}->last_status =~ /\A2/msx 2 3 5
116  
117 return
118 3 ▶ if $self->{s3}->last_status == 412; # held by someone
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"s3"}->last_status == 412 3 0 3
119  
120 0 die $err; # real error
121 }
122  
123 ########################################################################
124 3 ▶sub _try_steal_if_stale {
Subroutine _try_steal_if_stale: called CC=7 SCAR=19.7
125 ########################################################################
126 3 my ($self) = @_;
127  
128 3 my $meta = eval { $self->{s3}->head_object( $self->{bucket}, $self->{key} ) };
129  
130 $self->{s3}->logger->debug(
131 3 Dumper(
132 [ error => $EVAL_ERROR,
133 meta => $meta
134 ]
135 )
136 );
137  
138 3 ▶ return ('vanished')
Branch: 1 branch
BranchTrueFalseTotal
unless $meta 1 2 3
139 if !$meta;
140  
141 2 my $current_etag = $meta->{etag};
142  
143 # Fetch body to read the holder's expiry (head doesn't carry it).
144 2 my $obj = eval { $self->{s3}->get_object( $self->{bucket}, $self->{key} ) };
145  
146 2 $self->{s3}->logger->debug( Dumper( [ error => $EVAL_ERROR, ] ) );
147  
148 2 ▶ my $data = eval { decode_json( $obj->{content} // '{}' ) } // {};
Condition50%2/4
eval { do { &decode_json(scalar($obj->{"content"} // "{}")) } } // {}
l!l
20
$obj->{"content"} // "{}"
l!l
20
MC/DC0%0/1
eval { do { &decode_json(scalar($obj->{"content"} // "{}")) } } // {}
eval { do { &decode_json(scalar($obj->{"content"} // "{}")) } }
MC/DC0%0/1
$obj->{"content"} // "{}"
$obj->{"content"}
Truth table50%1/2
A
A= eval { do { &decode_json(scalar($obj->{"content"} // "{}")) } }
Aresult
11
00
Truth table50%1/2
A
A= $obj->{"content"}
Aresult
11
00
149  
150 $self->{s3}->logger->debug(
151 2 Dumper(
152 [ error => $EVAL_ERROR,
153 data => $data,
154 ]
155 )
156 );
157  
158 return ('held')
159 2 ▶ if ( $data->{expires} // 0 ) > time;
Branch: 1 branch
BranchTrueFalseTotal
if ($data->{"expires"} // 0) > time 1 1 2
Condition50%1/2
$data->{"expires"} // 0
l!l
20
MC/DC0%0/1
$data->{"expires"} // 0
$data->{"expires"}
Truth table50%1/2
A
A= $data->{"expires"}
Aresult
11
00
160  
161 # Stale. Steal ONLY if the lock is still the exact one we judged stale.
162 1 my $body = encode_json( { owner => $self->{owner}, expires => time + $self->{ttl} } );
163  
164 1 my $etag = eval {
165  
166 $self->{s3}->put_object(
167 1 $self->{bucket}, $self->{key}, $body,
168 content_type => 'application/json',
169 headers => { 'If-Match' => sprintf '"%s"', $current_etag },
170 );
171 };
172  
173 1 $self->{s3}->logger->info( Dumper( [ error => $EVAL_ERROR, ] ) );
174  
175 return ( 'stolen', $etag )
176 1 ▶ if $self->{s3}->last_status =~ /\A2/xsm;
Branch: 1 branch
BranchTrueFalseTotal
if $self->{"s3"}->last_status =~ /\A2/msx 1 0 1
177  
178 0 return ('held');
179 }
180  
181 ########################################################################
182 3 ▶sub _guard {
Subroutine _guard: called CC=1 SCAR=0.0
183 ########################################################################
184 3 my ( $self, $etag ) = @_;
185  
186 3 require Amazon::S3::Lite::Lock::Guard;
187  
188 return Amazon::S3::Lite::Lock::Guard->new(
189 s3 => $self->{s3},
190 bucket => $self->{bucket},
191 key => $self->{key},
192 3 etag => $etag, # so release only deletes OUR lock
193 );
194 }
195  
196 1 1;
↑ Summary Lite/Logger.pm »