SharedMem.pm

filter: Statementstmt 86.6% 149 / 172 Branchbran 59.5% 25 / 42 Conditioncond 50.0% 6 / 12 MC/DCmcdc 12.5% 1 / 8 Subroutinesub 100% 27 / 27 Podpod 100% 10 / 10 totaltotal 80.4% 218 / 271 SCAR 34.6
CC
26
Cov
80%
_lock
16.3
DEMOLISH
9.1
_build_shm
5.8
CRAP 31.7
↑ Summary SharedMem/t/CHIDriverTests.pm »
1 package CHI::Driver::SharedMem;
2  
3 # There is an argument for mapping namespaces into keys and then putting
4 # different namespaces into different shared memory areas. I will think about
5 # that.
6  
7 5 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 5 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
9 5 ▶use CHI::Constants qw(CHI_Meta_Namespace);
Subroutine BEGIN: called CC=1 SCAR=0.0
10 5 ▶use Moose;
Subroutine BEGIN: called CC=1 SCAR=0.0
11 5 ▶use IPC::SysV qw(S_IRUSR S_IWUSR IPC_CREAT);
Subroutine BEGIN: called CC=1 SCAR=0.0
12 5 ▶use IPC::SharedMem;
Subroutine BEGIN: called CC=1 SCAR=0.0
13 5 ▶use JSON::MaybeXS;
Subroutine BEGIN: called CC=1 SCAR=0.0
14 5 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
15 5 ▶use Config;
Subroutine BEGIN: called CC=1 SCAR=0.0
16 5 ▶use Fcntl;
Subroutine BEGIN: called CC=1 SCAR=0.0
17  
18 5 extends 'CHI::Driver';
19  
20 5 has 'shm_key' => (is => 'ro', isa => 'Int');
21 5 has 'shm' => (is => 'ro', builder => '_build_shm', lazy => 1);
22 5 has 'shm_size' => (is => 'rw', isa => 'Int', default => 8 * 1024);
23 5 has 'lock' => (
24 is => 'ro',
25 builder => '_build_lock',
26 );
27 5 has 'lock_file' => (is => 'rw', isa => 'Str|Undef');
28 5 has '_data_size' => (
29 is => 'rw',
30 isa => 'Int',
31 reader => '_get_data_size',
32 writer => '_set_data_size'
33 );
34 5 has '_data' => (
35 is => 'rw',
36 # isa => 'ArrayRef[ArrayRef]', # For Storable, now using JSON
37 isa => 'Str',
38 reader => '_get_data',
39 writer => '_set_data'
40 );
41  
42 5 __PACKAGE__->meta->make_immutable();
43  
44 =head1 NAME
45  
46 CHI::Driver::SharedMem - Cache data in shared memory
47  
48 =head1 VERSION
49  
50 Version 0.18
51  
52 =cut
53  
54 5 our $VERSION = '0.18';
55  
56 # FIXME - get the pod documentation right so that the layout of the memory
57 # area looks correct in the man page
58  
59 =head1 SYNOPSIS
60  
61 L<CHI> driver which stores data in shared memory objects for persistence
62 over processes.
63 Size is an optional parameter containing the size of the shared memory area,
64 in bytes.
65 Shmkey is a mandatory parameter containing the IPC key for the shared memory
66 area.
67 See L<IPC::SharedMem> for more information.
68  
69 use CHI;
70 my $cache = CHI->new(
71 driver => 'SharedMem',
72 max_size => 2 * 1024, # Size of the cache
73 shm_size => 32 * 1024, # Size of the shared memory area
74 shm_key => 12344321, # Choose something unique, but the same across
75 # all caches so that namespaces will be shared,
76 # but we won't step on any other shm areas
77 );
78 # ...
79  
80 The shared memory area is stored thus:
81  
82 # Number of bytes in the cache [ int ]
83 'cache' => {
84 'namespace1' => {
85 'key1' => 'value1',
86 'key2' => 'value2',
87 # ...
88 },
89 'namespace2' => {
90 'key1' => 'value3',
91 'key3' => 'value2',
92 # ...
93 }
94 # ...
95 }
96  
97 =head1 SUBROUTINES/METHODS
98  
99 =head2 store
100  
101 Stores an object in the cache.
102 The data are serialized into JSON.
103  
104 =cut
105  
106 sub store {
107 548 ▶ my($self, $key, $value) = @_;
Subroutine store: called CC=1 SCAR=0.0
Pod documented
108  
109 548 $self->_lock(type => 'write');
110 548 my $h = $self->_data();
111 548 $h->{$self->namespace()}->{$key} = $value;
112 # if($self->{'is_size_aware'}) {
113 # $h->{CHI_Meta_Namespace()}->{'last_used_time'}->{$key} = time;
114 # }
115 548 $self->_data($h);
116 547 $self->_unlock();
117 }
118  
119 =head2 fetch
120  
121 Retrieves an object from the cache
122  
123 =cut
124  
125 sub fetch {
126 1784 ▶ my($self, $key) = @_;
Subroutine fetch: called CC=2 SCAR=6.9
Pod documented
127  
128 # open(my $tulip, '>>', '/tmp/tulip');
129 # print $tulip __LINE__, "\n";
130 1784 $self->_lock(type => 'read');
131 # print $tulip __LINE__, "\n";
132 1784 my $rc = $self->_data()->{$self->namespace()}->{$key};
133 # print $tulip __LINE__, "\n";
134 1784 ▶ if($self->{is_size_aware}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"is_size_aware"}) 367 1417 1784
135 367 $self->_lock(type => 'write');
136 367 my $h = $self->_data();
137 367 $h->{CHI_Meta_Namespace()}->{last_used_time}->{$key} = time;
138 367 $self->_data($h);
139 }
140 1784 $self->_unlock();
141 # print $tulip __LINE__, "\n";
142 # close $tulip;
143 1784 return $rc;
144 }
145  
146 =head2 remove
147  
148 Remove an object from the cache
149  
150 =cut
151  
152 sub remove {
153 132 ▶ my($self, $key) = @_;
Subroutine remove: called CC=1 SCAR=0.0
Pod documented
154  
155 132 $self->_lock(type => 'write');
156 132 my $h = $self->_data();
157 132 delete $h->{$self->namespace()}->{$key};
158 132 delete $h->{CHI_Meta_Namespace()}->{last_used_time}->{$key};
159 132 $self->_data($h);
160 132 $self->_unlock();
161  
162 # open(my $tulip, '>>', '/tmp/tulip');
163 # print $tulip "remove: $key\n";
164 }
165  
166 =head2 clear
167  
168 Removes all data from the current namespace
169  
170 =cut
171  
172 sub clear {
173 109 ▶ my $self = shift;
Subroutine clear: called CC=1 SCAR=0.0
Pod documented
174  
175 109 $self->_lock(type => 'write');
176 109 my $h = $self->_data();
177 109 delete $h->{$self->namespace()};
178 109 $self->_data($h);
179 109 $self->_unlock();
180  
181 # open(my $tulip, '>>', '/tmp/tulip');
182 # print $tulip "clear ", $self->namespace(), "\n";
183 }
184  
185 =head2 get_keys
186  
187 Gets a list of the keys in the current namespace
188  
189 =cut
190  
191 sub get_keys {
192 126 ▶ my $self = shift;
Subroutine get_keys: called CC=1 SCAR=0.0
Pod documented
193  
194 126 $self->_lock(type => 'read');
195 126 my $h = $self->_data();
196 126 $self->_unlock();
197 126 return(keys(%{$h->{$self->namespace()}}));
198 }
199  
200 =head2 get_namespaces
201  
202 Gets a list of the namespaces in the cache
203  
204 =cut
205  
206 sub get_namespaces {
207 12 ▶ my $self = shift;
Subroutine get_namespaces: called CC=1 SCAR=0.0
Pod documented
208  
209 12 $self->_lock(type => 'read');
210 12 my $rc = $self->_data();
211 12 $self->_unlock();
212 # Needs to be sorted for RT89892
213 12 my @rc = sort keys(%{$rc});
214 12 return @rc;
215 }
216  
217 =head2 default_discard_policy
218  
219 Use an LRU algorithm to discard items when the cache can't add anything
220  
221 =cut
222  
223 4 ▶sub default_discard_policy { 'lru' }
Subroutine default_discard_policy: called CC=1 SCAR=0.0
Pod documented
224  
225 =head2 discard_policy_lru
226  
227 When the Shared memory area is getting close to full, discard the least recently used objects
228  
229 =cut
230  
231 sub discard_policy_lru {
232 # return; # debugging why I get uninitialized values in the sort
233 14 ▶ my $self = shift;
Subroutine discard_policy_lru: called CC=1 SCAR=0.0
Pod documented
234  
235 14 $self->_lock(type => 'read');
236 14 my $last_used_time = $self->_data()->{CHI_Meta_Namespace()}->{last_used_time};
237 14 $self->_unlock();
238 my @keys_in_lru_order =
239 14 sort { $last_used_time->{$a} <=> $last_used_time->{$b} } $self->get_keys();
240 return sub {
241 36 ▶ shift(@keys_in_lru_order);
Subroutine __ANON__: called CC=1 SCAR=0.0
242 14 };
243 }
244  
245 # Internal routines
246  
247 # The area must be locked by the caller
248 sub _build_shm {
249 97 ▶ my $self = shift;
Subroutine _build_shm: called CC=5 SCAR=17.6
250 97 my $shm_size = $self->shm_size();
251  
252 97 ▶ if((!defined($shm_size)) || ($shm_size == 0)) {
Branch: 1 branch
BranchTrueFalseTotal
if (not defined $shm_size or $shm_size == 0) 0 97 97
Condition33%1/3
not defined $shm_size or $shm_size == 0
l!l&&r!l&&!r
0097
MC/DC0%0/2
not defined $shm_size or $shm_size == 0
not defined $shm_size $shm_size == 0
Truth table33%1/3
not(A) or B
A= not defined $shm_sizeB= $shm_size == 0
ABresult
1X1
011
000
253 # Probably some strange condition in cleanup
254 # croak 'Size == 0';
255 0 return;
256 }
257 97 my $shm = IPC::SharedMem->new($self->shm_key(), $shm_size, S_IRUSR|S_IWUSR);
258 97 ▶ unless($shm) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($shm) 4 93 97
259 4 $shm = IPC::SharedMem->new($self->shm_key(), $shm_size, S_IRUSR|S_IWUSR|IPC_CREAT);
260 4 ▶ unless($shm) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($shm) 0 4 4
261 0 croak "Couldn't create a shared memory area of $shm_size bytes with key ",
262 $self->shm_key(), ": $!";
263 0 return;
264 }
265 4 $shm->write(pack('I', 0), 0, $Config{intsize});
266 }
267 97 $shm->attach();
268 97 return $shm;
269 }
270  
271 sub _build_lock {
272 99 ▶ return;
Subroutine _build_lock: called CC=2 SCAR=15.1
273  
274 0 my $self = shift;
275  
276 # open(my $fd, '<', $0) || croak("$0: $!");
277 # FIXME: make it unique for each object, not a singleton
278 0 $self->lock_file('/tmp/' . __PACKAGE__);
279 # open(my $tulip, '>>', '/tmp/tulip');
280 # print $tulip "build_lock\n", $self->lock_file(), "\n";
281 0 ▶ open(my $fd, '>', $self->lock_file()) || croak($self->lock_file(), ": $!");
Branch: 1 branch
BranchTrueFalseTotal
open my $fd, ">", $self->lock_file or croak($self->lock_file, ": $!") 0 0 0
282 0 return $fd;
283 }
284  
285 sub _lock {
286 3189 ▶ return;
Subroutine _lock: called CC=4 SCAR=27.9
287  
288 0 my ($self, %params) = @_;
289  
290 # open(my $tulip, '>>', '/tmp/tulip');
291 # print $tulip $params{'type'}, ' lock ', $self->lock_file(), "\n";
292 # my $i = 0;
293 # while((my @call_details = (caller($i++)))) {
294 # print $tulip "\t", $call_details[1], ':', $call_details[2], ' in function ', $call_details[3], "\n";
295 # }
296 0 ▶ return unless $self->lock_file();
Branch: 1 branch
BranchTrueFalseTotal
unless $self->lock_file 0 0 0
297  
298 0 ▶ if(my $lock = $self->lock()) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $lock = $self->lock) { } 0 0 0
299 0 ▶ flock($lock, ($params{type} eq 'read') ? Fcntl::LOCK_SH : Fcntl::LOCK_EX);
Branch: 1 branch
BranchTrueFalseTotal
$params{'type'} eq 'read' ? : 0 0 0
300 } else {
301 # print $tulip 'lost lock ', $self->lock_file(), "\n";
302 0 croak('Lost lock: ', $self->lock_file());
303 }
304 }
305  
306 sub _unlock {
307 2821 ▶ return;
Subroutine _unlock: called CC=2 SCAR=15.1
308  
309 0 my $self = shift;
310  
311 # open(my $tulip, '>>', '/tmp/tulip');
312 # print $tulip 'unlock ', $self->lock_file(), "\n";
313 0 ▶ if(my $lock = $self->lock()) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $lock = $self->lock) { } 0 0 0
314 0 flock($lock, Fcntl::LOCK_UN);
315 } else {
316 # print $tulip 'lost lock for unlock ', $self->lock_file(), "\n";
317 0 croak('Lost lock for unlock: ', $self->lock_file());
318 }
319 }
320  
321 # The area must be locked by the caller
322 sub _data_size {
323 4344 ▶ my($self, $value) = @_;
Subroutine _data_size: called CC=4 SCAR=14.5
324  
325 4344 ▶ if(defined($value)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $value) 1155 3189 4344
326 1155 $self->shm()->write(pack('I', $value), 0, $Config{intsize});
327 1155 return $value;
328 }
329 3189 ▶ unless($self->shm()) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->shm) 0 3189 3189
330 0 return 0;
331 }
332 3189 my $size = $self->shm()->read(0, $Config{intsize});
333 3189 ▶ unless(defined($size)) {
Branch: 1 branch
BranchTrueFalseTotal
unless (defined $size) 0 3189 3189
334 0 return 0;
335 }
336 3189 return unpack('I', $size);
337 }
338  
339 # The area must be locked by the caller
340 sub _data {
341 4248 ▶ my($self, $h) = @_;
Subroutine _data: called CC=5 SCAR=16.2
342  
343 # open(my $tulip, '>>', '/tmp/tulip');
344 # print $tulip __LINE__, "\n";
345 4248 ▶ if(defined($h)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $h) 1156 3092 4248
346 1156 my $f = JSON::MaybeXS->new()->ascii()->encode($h);
347 1156 my $cur_size = length($f);
348 # print $tulip __LINE__, "cmp $cur_size > ", $self->size(), "\n";
349 1156 ▶ if($cur_size > ($self->shm_size() - $Config{intsize})) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cur_size > $self->shm_size - $CHI::Driver::SharedMem::Config{"intsize"}) 1 1155 1156
350 1 croak("sharedmem set failed - value too large? ($cur_size bytes) > ", $self->shm_size());
351 }
352 1155 $self->shm()->write($f, $Config{intsize}, $cur_size);
353 1155 $self->_data_size($cur_size);
354 # print $tulip "set: $cur_size bytes\n";
355 # close $tulip;
356 1155 return $h;
357 }
358 3092 my $cur_size = $self->_data_size();
359 # print $tulip "get: $cur_size bytes\n";
360 # close $tulip;
361 3092 ▶ if($cur_size) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cur_size) 3088 4 3092
362 3088 my $rc;
363 3088 eval {
364 3088 $rc = JSON::MaybeXS->new()->ascii()->decode($self->shm()->read($Config{intsize}, $cur_size));
365 };
366 3088 ▶ if($@) {
Branch: 1 branch
BranchTrueFalseTotal
if ($@) 0 3088 3088
367 0 $self->_data_size(0);
368 0 croak($@);
369 }
370 3088 return $rc;
371 # return JSON::MaybeXS->new()->ascii()->decode($self->shm()->read($Config{intsize}, $cur_size));
372 }
373 4 return {};
374 }
375  
376 =head2 BUILD
377  
378 Constructor - validate arguments
379  
380 =cut
381  
382 sub BUILD {
383 99 ▶ my $self = shift;
Subroutine BUILD: called CC=2 SCAR=6.9
Pod documented
384  
385 99 ▶ unless($self->shm_key()) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->shm_key) 2 97 99
386 2 croak 'CHI::Driver::SharedMem - no key given';
387 }
388 97 $| = 1;
389 }
390  
391 =head2 DEMOLISH
392  
393 If there is no data in the shared memory area, and no-one else is using it,
394 it's safe to remove it and reclaim the memory.
395  
396 =cut
397  
398 sub DEMOLISH {
399 # if(defined($^V) && ($^V ge 'v5.14.0')) {
400 # return if ${^GLOBAL_PHASE} eq 'DESTRUCT'; # >= 5.14.0 only
401 # }
402 99 ▶ my $self = shift;
Subroutine DEMOLISH: called CC=8 SCAR=22.1
Pod documented
403  
404 # open(my $tulip, '>>', '/tmp/tulip');
405 # print $tulip "DEMOLISH\n";
406 99 ▶ if($self->shm_key() && $self->shm()) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->shm_key and $self->shm) 97 2 99
Condition66%2/3
$self->shm_key and $self->shm
!ll&&!rl&&r
2097
MC/DC50%1/2
$self->shm_key and $self->shm
$self->shm_key $self->shm
Truth table66%2/3
A and B
A= $self->shm_keyB= $self->shm
ABresult
0X0
100
111
407 97 my $cur_size;
408 97 $self->_lock(type => 'write');
409 97 $cur_size = $self->_data_size();
410 # print $tulip "DEMOLISH: $cur_size bytes\n";
411 97 my $can_remove = 0;
412 97 my $stat = $self->shm()->stat();
413 97 ▶ if($cur_size == 0) {
Branch: 1 branch
BranchTrueFalseTotal
if ($cur_size == 0) { } 2 95 97
414 2 ▶ if(defined($stat) && ($stat->nattch() == 1)) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $stat and $stat->nattch == 1) 2 0 2
Condition33%1/3
defined $stat and $stat->nattch == 1
!ll&&!rl&&r
002
MC/DC0%0/2
defined $stat and $stat->nattch == 1
defined $stat $stat->nattch == 1
Truth table33%1/3
A and B
A= defined $statB= $stat->nattch == 1
ABresult
0X0
100
111
415 2 $self->shm()->detach();
416 2 $self->shm()->remove();
417 2 $can_remove = 1;
418 }
419 # } elsif(defined($stat) && ($stat->nattch() == 1)) {
420 # # Scan the cache and see if all has expired.
421 # # If it has, then the cache can be removed if nattch = 1
422 # $can_remove = 1;
423 # foreach my $namespace($self->get_namespaces()) {
424 # print $tulip "DEMOLISH: namespace = $namespace\n";
425 # foreach my $key($self->get_keys($namespace)) {
426 # # May give substr error in CHI
427 # print $tulip "DEMOLISH: key = $key\n";
428 # if($self->is_valid($key)) {
429 # print $tulip "DEMOLISH: is_valid\n";
430 # $can_remove = 0;
431 # last;
432 # }
433 # }
434 # }
435 # $self->shm()->detach();
436 # if($can_remove) {
437 # $self->shm()->remove();
438 # }
439 } else {
440 95 $self->shm()->detach();
441 }
442 97 $self->_unlock();
443 97 ▶ if($can_remove && (my $lock_file = $self->lock_file())) {
Branch: 1 branch
BranchTrueFalseTotal
if ($can_remove and my $lock_file = $self->lock_file) 0 97 97
Condition66%2/3
$can_remove and my $lock_file = $self->lock_file
!ll&&!rl&&r
9520
MC/DC0%0/2
$can_remove and my $lock_file = $self->lock_file
$can_remove my $lock_file = $self->lock_file
Truth table66%2/3
A and B
A= $can_removeB= my $lock_file = $self->lock_file
ABresult
0X0
100
111
444 0 $self->lock_file(undef);
445 0 close $self->lock();
446 0 unlink $lock_file;
447 # print $tulip "unlink $lock_file\n";
448 # close $tulip;
449 }
450 }
451 }
452  
453 =head1 AUTHOR
454  
455 Nigel Horne, C<< <njh at bandsman.co.uk> >>
456  
457 =head1 BUGS
458  
459 Please report any bugs or feature requests to C<bug-chi-driver-sharedmem at rt.cpan.org>, or through
460 the web interface at L<http://rt.cpan.org/NoAuth/ReportBug.html?Queue=CHI-Driver-SharedMem>. I will be notified, and then you'll
461 automatically be notified of progress on your bug as I make changes.
462  
463 Max_size is handled, but if you're not consistent across the calls to each cache,
464 the results are unpredictable because it's used to create the size of the shared memory
465 area.
466  
467 The shm_size argument should be deprecated and only the max_size argument used.
468  
469 =head1 SEE ALSO
470  
471 L<CHI>, L<IPC::SharedMem>
472  
473 =cut
474  
475 =head1 SUPPORT
476  
477 You can find documentation for this module with the perldoc command.
478  
479 perldoc CHI::Driver::SharedMemory
480  
481 You can also look for information at:
482  
483 =over 4
484  
485 =item * MetaCPAN
486  
487 L<https://metacpan.org/dist/CHI-Driver-SharedMem>
488  
489 =item * RT: CPAN's request tracker
490  
491 L<https://rt.cpan.org/NoAuth/Bugs.html?Dist=CHI-Driver-SharedMemory>
492  
493 =item * CPAN Testers' Matrix
494  
495 L<http://matrix.cpantesters.org/?dist=CHI-Driver-SharedMemory>
496  
497 =item * CPAN Testers Dependencies
498  
499 L<http://deps.cpantesters.org/?module=CHI::Driver::SharedMemory>
500  
501 =back
502  
503 =head1 LICENSE AND COPYRIGHT
504  
505 Copyright 2010-2023 Nigel Horne.
506  
507 This program is released under the following licence: GPL2
508  
509 =cut
510  
511 5 1;
↑ Summary SharedMem/t/CHIDriverTests.pm »