blib/lib/IPC/LeaderBoard.pm

filter: Statementstmt 99.0% 100 / 101 Branchbran 76.1% 32 / 42 Conditioncond 50.0% 6 / 12 MC/DCmcdc 12.5% 1 / 8 Subroutinesub 100% 16 / 16 Podpod 16.6% 1 / 6 totaltotal 84.3% 156 / 185 CC 27 SCAR 20.9
CC
27
Cov
89%
update
14.9
BUILD
10.3
read_slot
3.1
CRAP 8.1
↑ Summary
1 package IPC::LeaderBoard;
2  
3 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 1 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
5  
6 1 ▶use Fcntl ':flock'; # import LOCK_* constants
Subroutine BEGIN: called CC=1 SCAR=0.0
7 1 ▶use Guard;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 1 ▶use IPC::ScoreBoard;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 1 ▶use Moo;
Subroutine BEGIN: called CC=1 SCAR=0.0
10 1 ▶use Path::Tiny;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 1 ▶use namespace::clean;
Subroutine BEGIN: called CC=1 SCAR=0.0
12  
13 1 our $VERSION = '0.01_1';
14  
15 =head1 NAME
16  
17 IPC::LeaderBoard - fast per-symbol online get/update information
18  
19 =head1 VERSION
20  
21 0.01_1
22  
23 =head1 STATUS
24  
25 =begin HTML
26  
27 <p>
28 <a href="https://travis-ci.org/binary-com/perl-IPC-LeaderBoard"><img src="https://travis-ci.org/binary-com/perl-IPC-LeaderBoard.svg" /></a>
29 </p>
30  
31 =end HTML
32  
33  
34 =head1 SYNOPSIS
35  
36 use IPC::LeaderBoard;
37  
38 # in master-process
39 my $master = IPC::LeaderBoard::create(
40 n_slots => 2, # number of symbols
41 slot_shared_size => 4, # number integers per slot, concurrent access
42 slot_private_size => 2, # number integers per slot, non-concurrent access
43 mmaped_file => "/var/run/data/my.scores", # mmaped file
44 );
45 # ... initialize data here
46  
47 # in slave processes
48 my $slave = IPC::LeaderBoard::attach(
49 # exactly the same parameters as for master
50 );
51  
52 my $leader_board = $slave; # or $master, does not matter
53  
54 # get shared and private arrays of integers for the 0-th slot
55 my ($shared, $private) = $leader_board->read_slot(0);
56  
57 # update shared integers with values 1,2,3,4 and 0-th private integer
58 # with value 6
59 my $success = $leader_board->update(0, [1, 2, 3, 4], 0 => 6, 1 => 8)
60  
61 # $shared = [1, 2, 3, 4], $private = [6, 8]
62 ($shared, $private) = $leader_board->read_slot(0);
63  
64 # update just private integer with index 1 with value 2
65 $leader_board->update(0, 1 => 2);
66  
67 # update just shared values of 0-th slot
68 my $success = $leader_board->update(0, [1, 2, 3, 4]);
69  
70 =head1 DESCRIPTION
71  
72 LeaderBoard uses shared memory IPC to fast set/get integers on arbitrary row,
73 (slot) defined by it's index.
74  
75 There are the following assumptions:
76  
77 =over 2
78  
79 =item * only one master is present
80  
81 C<create> method dies, if it founds that some other master ownes shared
82 memory (file lock is used for that).
83  
84 =item * master is launched before slaves
85  
86 C<attach> dies, if slave finds, that master-owner isn't present, or,
87 if it presents, the masters provider/symbol information isn't actual.
88 In the last case master should be restarted first.
89  
90 =item * there is no hot-deploy mechanism
91  
92 Just restart master/slaves
93  
94 =item * read slot before update it
95  
96 The vesion/generation pattern is used do detect, whether update
97 has been successfull or not. Update failure means, some other
98 C<LeaderBoard> instance updated the slot; you should re-read it
99 and try uptate it again (if the update will be still actual after
100 data refresh)
101  
102 =item * no semantical difference between slave and master
103  
104 Master was introduced to lock leadear board to prevent other masters
105 connect to it and re-initialize (corrupt) data. After attach slave validates,
106 that LeaderBoard is valid (i.e. number of slots, as well as the sizes
107 of private and shared areas match to the declared).
108  
109 Hence, master can be presented only by one instance, while slaves
110 can be presented by multiple instances.
111  
112 =item * slot data organization and consistency
113  
114 A leaderboard is an array of slots of the same size:
115  
116 +------------------------------------------------------------------------+
117 | slot 1 |
118 +------------------------------------------------------------------------+
119 | slot 2 |
120 +------------------------------------------------------------------------+
121 | ... |
122 +------------------------------------------------------------------------+
123 | slot N |
124 +------------------------------------------------------------------------+
125  
126 A slot is addressed by its index.
127  
128 Each slot contains a spin-lock, a shared part, a generation field and a private part like
129  
130 It is supposed, that only leader (independent for each slot) will update the shared part,
131 while other competitors will update only own private parts, i.e.:
132  
133 | | shared part | | private part |
134 | spin | | gene- | process1 | process2 | process3 |
135 | lock | shr1 | shr2 | ... | shrN | ration | p1 | p2 | ... | pN | p1 | p2 | ... | pN | p1 | p2 | ... | pN |
136  
137 All values (shrX and pX) in the leaderboard are integer numbers. Only the current leader updates
138 the shared part, and does that in safe manner (i.e. protected by spin-lock and generation). Each process can
139 update its own private part of a slot.
140  
141 Read or write for integer values (shr1, p1, ..) read/write B<atomicity> is guaranteed
142 by L<IPC::ScoreBoard>, which in the final, uses special CPU-instructions for that.
143  
144 The SpinLock pattern guarantees the safety of shared part update, i.e. in
145 the case of two or more concurrent write request, they will be done in
146 sequential manner.
147  
148 The Generation pattern guarantees that you update the most recent values
149 in the shared part of the slot, i.e. if some process updated shared
150 part of the slot, between slot read and update operations of the
151 current process, than, the update request of the current process
152 would fail. You have re-read the slot, and try to update it again, but
153 after re-read the update might be not required.
154  
155 Both SpinLock and Generation patterns guarantee, that you'll never
156 can made inconsistent C<update>, or updating non-actual data.
157  
158 In the same time, you might end up with the inconsistent C<read_slot>
159 of the shared data: the individual values (integer) are consistent (atomic),
160 but you they might belong to the different generations. There is an assumption
161 in the C<LeaderBoard> design, that it is B<fine>: would you try to update
162 the shared data, the C<update> will fail, hence, no any harm will occur. If
163 you need to handle that, just check return value C<update>.
164  
165 There are no any guarantees for slot private data; but it isn't needed.
166 The shared data should store information about leader, hence when a
167 new leader arrives, it updates the information; or the current leader update
168 it's information on the LeaderBoard in the appropriate slot. No data loss might
169 occur.
170  
171 When competitor (i.e. some process) updates private data, nobody else
172 can update it (i.e. you shouldn't write progam such a way, that one
173 process-competitor updates data of the other process-competitor), hence,
174 private data cannot be corrupted if used properly.
175  
176 The private data might be inconsistent on read (e.g. competitor1 reads
177 private data of competitor2, while it is half-updated by competitor2);
178 but that shoudl be B<insignificant for the sake of speed>. If it is
179 significant, use shared memory for that, re-design your approach (e.g
180 use additional slots) or use some other module.
181  
182 =back
183  
184 The update process should be rather simple: C<killall $slave_1, $slave_2, ... $master>
185 and then start all together. C<create> / C<attach> should be wrappend into
186 C<eval> (or C<Try::Tiny> & friends), to repeat seveal attempts with some delay.
187  
188 The C<update> method might fail, (i.e. it does not returns true), when it detects,
189 that somebody else already has changed an row. It is assumed that no any harm
190 in it. If needed the row can be refreshed (re-read), and the next update
191 might be successfull.
192  
193 It is assumed, that if C<read> returs outdated data and the C<update> decision
194 has been taken, than update will silently fail (return false), without any
195 loud exceptions; so, the next read-update cycle might be successful, but
196 probably, the updated values are already correct, so, no immediate update
197 would occur.
198  
199 =cut
200  
201 1 has mmaped_file => (
202 is => 'ro',
203 required => 1
204 );
205  
206 1 has n_slots => (
207 is => 'ro',
208 required => 1
209 );
210  
211 1 has slot_shared_size => (
212 is => 'ro',
213 required => 1
214 );
215  
216 1 has slot_private_size => (
217 is => 'ro',
218 required => 1
219 );
220  
221 1 has _mode => (
222 is => 'ro',
223 required => 1
224 );
225  
226 1 has _score_board => (is => 'rw');
227 1 has _fd => (is => 'rw');
228 1 has _generation_idx => (is => 'rw');
229 1 has _last_generation => (is => 'rw');
230 has _last_idx => (
231 is => 'rw',
232 9 ▶ default => sub { -1 });
Subroutine __ANON__: called CC=1 SCAR=0.0
233  
234 sub BUILD {
235 9 ▶ my $self = shift;
Subroutine BUILD: called CC=10 SCAR=23.3
Pod undocumented
236 9 my $mode = $self->_mode;
237 9 ▶ die("unknown mode '$mode'") unless $mode =~ /(slave)|(master)/;
Branch: 1 branch
BranchTrueFalseTotal
unless $mode =~ /(slave)|(master)/ 0 9 9
238  
239 # construct ids (number, actually the order) for all symbols
240 # and providers. Should be sorted to guaranttee the same
241 # ids in different proccess
242 # There is an assumption, that processes, using LeaderBoard, should
243 # restarte in case of symbols/providers change.
244  
245 9 my $filename = $self->mmaped_file;
246 9 ▶ if (!(-e $filename) && ($mode eq 'slave')) {
Branch: 1 branch
BranchTrueFalseTotal
if (not -e $filename and $mode eq "slave") 0 9 9
Condition66%2/3
not -e $filename and $mode eq "slave"
!ll&&!rl&&r
810
MC/DC0%0/2
not -e $filename and $mode eq "slave"
not -e $filename $mode eq "slave"
Truth table66%2/3
not(A) and B
A= not -e $filenameB= $mode eq "slave"
ABresult
0X0
100
111
247 0 die("LeaderBoard ($filename) is abandoned, cannot attach to it (file not exists)");
248 }
249  
250 9 my $scoreboard_path = path($filename);
251 9 ▶ $scoreboard_path->touch if !-e $filename;
Branch: 1 branch
BranchTrueFalseTotal
unless -e $filename 1 8 9
252 9 my $fd = $scoreboard_path->filehandle('<');
253  
254 9 my $score_board;
255 9 ▶ if ($mode eq 'slave') {
Branch: 1 branch
BranchTrueFalseTotal
if ($mode eq 'slave') { } 5 4 9
256 # die, if slave was able to lock it, that means, that master
257 # didn't accquired the exclusive lock, i.e. no master
258 5 ▶ flock($fd, LOCK_SH | LOCK_NB)
Branch: 1 branch
BranchTrueFalseTotal
flock($fd, 5) and die "LeaderBoard ($filename) is abandoned, cannot attach to it (shared lock obtained)" 1 4 5
259 && die("LeaderBoard ($filename) is abandoned, cannot attach to it (shared lock obtained)");
260 4 my ($sb, $nslots, $slotsize, $extra) = IPC::ScoreBoard->open($filename);
261 # just additional check, that providers/symbols information is actual
262 4 my $declared_size = $self->slot_shared_size + $self->slot_private_size + 2;
263 4 ▶ die("number of slots mismatch") unless $nslots == $self->n_slots;
Branch: 1 branch
BranchTrueFalseTotal
unless $nslots == $self->n_slots 0 4 4
264 4 ▶ die("slot size mismatch") unless $slotsize == $declared_size;
Branch: 1 branch
BranchTrueFalseTotal
unless $slotsize == $declared_size 0 4 4
265 4 $score_board = $sb;
266 } else {
267 # die if we can't lock it, that means, another master-process
268 # already acquired it
269 4 ▶ flock($fd, LOCK_EX | LOCK_NB)
Branch: 1 branch
BranchTrueFalseTotal
flock($fd, 6) or die "LeaderBoard ($filename) is owned by some other process, cannot lock it exclusively" 1 3 4
270 || die("LeaderBoard ($filename) is owned by some other process, cannot lock it exclusively");
271 # we use the addtitional fields: for spinlock and generation
272 3 my $declared_size = $self->slot_shared_size + $self->slot_private_size + 2;
273 3 $score_board = IPC::ScoreBoard->named($filename, $self->n_slots, $declared_size, 0);
274 3 $self->_fd($fd);
275 }
276 7 $self->_generation_idx($self->slot_shared_size + 1); # [spin_lock | shared_data | generation | private_data ]
277 7 $self->_score_board($score_board);
278 7 return;
279 }
280  
281 sub DEMOLISH {
282 9 ▶ my $self = shift;
Subroutine DEMOLISH: called CC=3 SCAR=11.0
Pod undocumented
283 # actually we need that only for tests
284 9 ▶ if ($self->_mode eq 'master') {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->_mode eq "master") 4 5 9
285 4 ▶ flock($self->_fd, LOCK_UN) if ($self->_fd);
Branch: 1 branch
BranchTrueFalseTotal
if $self->_fd 3 1 4
286 }
287 9 return;
288 }
289  
290 sub attach {
291 5 ▶ return IPC::LeaderBoard->new({
Subroutine attach: called CC=1 SCAR=0.0
Pod undocumented
292 _mode => 'slave',
293 @_,
294 });
295 }
296  
297 sub create {
298 4 ▶ return IPC::LeaderBoard->new({
Subroutine create: called CC=1 SCAR=0.0
Pod undocumented
299 _mode => 'master',
300 @_,
301 });
302 }
303  
304 # our use-case implies, that if we read a bit outdated data, this is OK, because
305 # the generation field will be outdated, hence, no update would occur
306 sub read_slot {
307 9 ▶ my ($self, $idx) = @_;
Subroutine read_slot: called CC=3 SCAR=11.2
Pod undocumented
308 9 ▶ die("wrong index") if ($idx >= $self->n_slots) || $idx < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $idx >= $self->n_slots or $idx < 0 0 9 9
Condition33%1/3
$idx >= $self->n_slots or $idx < 0
l!l&&r!l&&!r
009
MC/DC0%0/2
$idx >= $self->n_slots or $idx < 0
$idx >= $self->n_slots $idx < 0
Truth table33%1/3
A or B
A= $idx >= $self->n_slotsB= $idx < 0
ABresult
1X1
011
000
309  
310 9 my @all_values = $self->_score_board->get_all($idx);
311 # drop spinlock and generation
312 9 my $generation = splice @all_values, $self->_generation_idx, 1;
313 9 splice @all_values, 0, 1;
314  
315 # record generation + index for further possible update
316 9 $self->_last_idx($idx);
317 9 $self->_last_generation($generation);
318  
319 # separate shared and private data
320 9 my $shared_size = $self->slot_shared_size;
321 9 my @shared_values = @all_values[0 .. $shared_size - 1];
322 9 my @private_values = @all_values[$shared_size .. $shared_size + $self->slot_private_size - 1];
323  
324 9 return \@shared_values, \@private_values;
325 }
326  
327 sub update {
328 5 ▶ my ($self, $idx, @rest) = @_;
Subroutine update: called CC=14 SCAR=27.0
Pod documented
329 5 ▶ my $values = (@rest && ref($rest[0]) eq 'ARRAY') ? shift(@rest) : undef;
Branch: 1 branch
BranchTrueFalseTotal
@rest && ref $rest[0] eq 'ARRAY' ? : 4 1 5
Condition66%2/3
@rest and ref $rest[0] eq "ARRAY"
!ll&&!rl&&r
014
MC/DC50%1/2
@rest and ref $rest[0] eq "ARRAY"
@rest ref $rest[0] eq "ARRAY"
Truth table66%2/3
A and B
A= @restB= ref $rest[0] eq "ARRAY"
ABresult
0X0
100
111
330 5 my %private_values = @rest;
331 5 my $operation_result = 0;
332 5 ▶ die("wrong index") if ($idx >= $self->n_slots) || $idx < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $idx >= $self->n_slots or $idx < 0 0 5 5
Condition33%1/3
$idx >= $self->n_slots or $idx < 0
l!l&&r!l&&!r
005
MC/DC0%0/2
$idx >= $self->n_slots or $idx < 0
$idx >= $self->n_slots $idx < 0
Truth table33%1/3
A or B
A= $idx >= $self->n_slotsB= $idx < 0
ABresult
1X1
011
000
333 5 ▶ die("update for only last read index is allowed") if $idx != $self->_last_idx;
Branch: 1 branch
BranchTrueFalseTotal
if $idx != $self->_last_idx 0 5 5
334  
335 5 my $sb = $self->_score_board;
336  
337 # updating shared values
338 5 ▶ if ($values) {
Branch: 1 branch
BranchTrueFalseTotal
if ($values) 4 1 5
339 4 ▶ die("values size mismatch slot size") if @$values != $self->slot_shared_size;
Branch: 1 branch
BranchTrueFalseTotal
if @$values != $self->slot_shared_size 0 4 4
340 # obtain spin-lock
341 4 ▶ $sb->decr($idx, 0) until $sb->incr($idx, 0) == 1;
Branch: 1 branch
BranchTrueFalseTotal
$sb->incr($idx, 0) == 1 or do { $sb->decr($idx, 0) } 0 4 4
342 # release the lock at the end of the scope
343 4 ▶ scope_guard { $sb->decr($idx, 0) };
Subroutine __ANON__: called CC=1 SCAR=0.0
344  
345 # now we hold the record, nobody else can update it
346 4 my $actual_generation = $sb->get($idx, $self->_generation_idx);
347 4 ▶ if ($actual_generation == $self->_last_generation) {
Branch: 1 branch
BranchTrueFalseTotal
if ($actual_generation == $self->_last_generation) 2 2 4
348 # now we are sure, that nobody else updated the record since our last read
349 # so we can safely update it
350  
351 # +1 because the 1st field is spinlock
352 2 $sb->set($idx, $_ + 1, $values->[$_]) for (0 .. @$values - 1);
353 # increment the generation field
354 2 $sb->incr($idx, $self->_generation_idx);
355 # success
356 2 $operation_result = 1;
357 }
358 }
359  
360 # updating private values
361 5 ▶ if (%private_values) {
Branch: 1 branch
BranchTrueFalseTotal
if (%private_values) 4 1 5
362 4 my $idx_delta = $self->_generation_idx + 1;
363 4 ▶ while (my ($private_idx, $value) = each %private_values) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = each %private_values) 5 4 9
364 5 ▶ die("wrong private index") if $private_idx >= $self->slot_private_size;
Branch: 1 branch
BranchTrueFalseTotal
if $private_idx >= $self->slot_private_size 0 5 5
365 5 $sb->set($idx, $private_idx + $idx_delta, $value);
366 }
367 }
368  
369 5 return $operation_result;
370 }
371  
372  
373  
374 =head1 AUTHOR
375  
376 binary.com, C<< <perl at binary.com> >>
377  
378 =head1 BUGS
379  
380 Please report any bugs or feature requests to
381 L<https://github.com/binary-com/perl-CSV-HistoryPlayer/issues>.
382  
383 =head1 LICENSE AND COPYRIGHT
384  
385 Copyright (C) 2016 binary.com
386  
387 This program is free software; you can redistribute it and/or modify it
388 under the terms of the the Artistic License (2.0). You may obtain a
389 copy of the full license at:
390  
391 L<http://www.perlfoundation.org/artistic_license_2_0>
392  
393 Any use, modification, and distribution of the Standard or Modified
394 Versions is governed by this Artistic License. By using, modifying or
395 distributing the Package, you accept this license. Do not use, modify,
396 or distribute the Package, if you do not accept this license.
397  
398 If your Modified Version has been derived from a Modified Version made
399 by someone other than you, you are nevertheless required to ensure that
400 your Modified Version complies with the requirements of this license.
401  
402 This license does not grant you the right to use any trademark, service
403 mark, tradename, or logo of the Copyright Holder.
404  
405 This license includes the non-exclusive, worldwide, free-of-charge
406 patent license to make, have made, use, offer to sell, sell, import and
407 otherwise transfer the Package with respect to any patent claims
408 licensable by the Copyright Holder that are necessarily infringed by the
409 Package. If you institute patent litigation (including a cross-claim or
410 counterclaim) against any party alleging that the Package constitutes
411 direct or contributory patent infringement, then this Artistic License
412 to you shall terminate on the date that such litigation is filed.
413  
414 Disclaimer of Warranty: THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER
415 AND CONTRIBUTORS "AS IS' AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES.
416 THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
417 PURPOSE, OR NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY
418 YOUR LOCAL LAW. UNLESS REQUIRED BY LAW, NO COPYRIGHT HOLDER OR
419 CONTRIBUTOR WILL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, OR
420 CONSEQUENTIAL DAMAGES ARISING IN ANY WAY OUT OF THE USE OF THE PACKAGE,
421 EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
422  
423 =cut
424  
425 1 1;
↑ Summary