File Coverage

blib/lib/IPC/SharedCache.pm
Criterion Covered Total %
statement 38 300 12.6
branch 6 138 4.3
condition 0 19 0.0
subroutine 8 28 28.5
pod 2 2 100.0
total 54 487 11.0


line stmt bran cond sub pod time code
1             package IPC::SharedCache;
2              
3             $IPC::SharedCache::VERSION = '1.3';
4              
5             =pod
6              
7             =head1 NAME
8              
9             IPC::SharedCache - a Perl module to manage a cache in SysV IPC shared memory.
10              
11             =head1 SYNOPSIS
12              
13             use IPC::SharedCache;
14              
15             # the cache is accessed using a tied hash.
16             tie %cache, 'IPC::SharedCache', ipc_key => 'AKEY',
17             load_callback => \&load,
18             validate_callback => \&validate;
19              
20             # get an item from the cache
21             $config_file = $cache{'/some/path/to/some.config'};
22              
23             =head1 DESCRIPTION
24              
25             This module provides a shared memory cache accessed as a tied hash.
26              
27             Shared memory is an area of memory that is available to all processes.
28             It is accessed by choosing a key, the ipc_key arguement to tie. Every
29             process that accesses shared memory with the same key gets access to
30             the same region of memory. In some ways it resembles a file system,
31             but it is not hierarchical and it is resident in memory. This makes
32             it harder to use than a filesystem but much faster. The data in
33             shared memory persists until the machine is rebooted or it is
34             explicitely deleted.
35              
36             This module attempts to make shared memory easy to use for one
37             specific application - a shared memory cache. For other uses of
38             shared memory see the documentation to the excelent module I use,
39             IPC::ShareLite (L).
40              
41             A cache is a place where processes can store the results of their
42             computations for use at a later time, possibly by other instances of
43             the application. A good example of the use of a cache is a web
44             server. When a web server receieves a request for an html page it
45             goes to the file system to read it. This is pretty slow, so the web
46             server will probably save the file in memory and use the in memory
47             copy the next time a request for that file comes in, as long as the
48             file hasn't changed on disk. This certainly speeds things up but web
49             servers have to serve multiple clients at once, and that means
50             multiple copies of the in-memory data. If the web server uses a
51             shared memory cache, like the one this module provides, then all the
52             servers can use the same cache and much less memory is consumed.
53              
54             This module handles all shared memory interaction using the
55             IPC::ShareLite module (version 0.06 and higher) and all data
56             serialization using Storable. See L and L
57             for details.
58              
59             =head1 MOTIVATION
60              
61             This module began its life as an internal piece of HTML::Template (see
62             L). HTML::Template has the ability to maintain a
63             cache of parsed template structures when running in a persistent
64             environment like Apache/mod_perl. Since parsing a template from disk
65             takes a fair ammount of time this can provide a big performance gain.
66             Unfortunately it can also consume large ammounts of memory since each
67             web server maintains its own cache in its own memory space.
68              
69             By using IPC::ShareLite and Storable (L and
70             L), HTML::Template was able to maintain a single shared
71             cache of templates. The downside was that HTML::Template's cache
72             routines became complicated by a lot of IPC code. My solution is to
73             break out the IPC cache mechanisms into their own module,
74             IPC::SharedCache. Hopefully over time it can become general enough to
75             be usable by more than just HTML::Template.
76              
77             =head1 USAGE
78              
79             This module allows you to store data in shared memory and have it load
80             automatically when needed. You can also define a test to screen
81             cached data for vailidty - if the test fails the data will be
82             reloaded. This is useful for defining a max-age for cached data or
83             keeping cached data in sync with other resources. In the web server
84             example above the validation test would look to see wether the file
85             had changed on disk.
86              
87             To initialize this module you provide two callback subroutines. The
88             first is the "load_callback". This gets called when a user of the
89             cache requests an item from that is not yet present or is stale. It
90             must return a reference to the data structure that will be stored in
91             the cache. The second is the "validate_callback". This gets called
92             on every cache access - its job is to check the cached object for
93             freshness (and/or some other validity, of course). It must return
94             true or false. When it returns true, the cached object is valid and
95             is retained in the cache. When it returns false, the object is
96             re-loaded using the "load_callback" and the result is stored in the
97             cache.
98              
99             To use the module you just request entries for the objects you need.
100             If the object is present in the cache and the "validate_callback"
101             returns true, then you get the object from the cache. If not, the
102             object is loaded into the cache with the "load_callback" and returned
103             to you.
104              
105             The cache can be used to store any perl data structures that can be
106             serialized by the Storable module. See L for details.
107              
108             =head1 EXAMPLE
109              
110             In this example a shared cache of files is maintained. The
111             "load_callback" reads the file from disk into the cache and the
112             "validate_callback" checks its modification time using stat(). Note
113             that the "load_callback" stores information into the cached object
114             that "validate_callback" uses to check the freshness of the cache.
115              
116             # the "load_callback", loads the file from disk, storing its stat()
117             # information along with the file into the cache. The key in this
118             # case is the filename to load.
119             sub load_file {
120             my $key = shift;
121              
122             open(FILE, $key) or die "Unable to open file named $key : $!");
123              
124             # note the modification time of this file - the 9th element of a
125             # stat() is the modification time of the file.
126             my $mtime = (stat($key))[9];
127              
128             # read the file into the variable $contents in 1k chunks
129             my ($buffer, $contents);
130             while(read(FILE, $buffer, 1024)) { $contents .= $buffer }
131             close(FILE);
132              
133             # prepare the record to store in the cache
134             my %record = ( mtime => $mtime, contents => $contents );
135            
136             # this record goes into the cache associated with $key, which is
137             # the filename. Notice that we're returning a reference to the
138             # data structure here.
139             return \%record;
140             }
141              
142             # the "validate" callback, checks the mtime of the file on disk and
143             # compares it to the cache value. The $record is a reference to the
144             # cached values array returned from load_file above.
145             sub validate_file {
146             my ($key, $record) = @_;
147              
148             # get the modification time out of the record
149             my $stored_mtime = $record->{mtime};
150              
151             # get the current modification time from the filesystem - the 9th
152             # element of a stat() is the modification time of the file.
153             my $current_mtime = (stat($key))[9];
154              
155             # compare and return the appropriate result.
156             if ($stored_mtime == $current_mtime) {
157             # the cached object is valid, return true
158             return 1;
159             } else {
160             # the cached object is stale, return false - load_callback will
161             # be called to load it afresh from disk.
162             return 0;
163             }
164             }
165              
166             # now we can construct the IPC::SharedCache object, using as a root
167             # key 'SAMS'.
168              
169             tie %cache 'IPC::SharedCache' ipc_key => 'SAMS',
170             load_callback => \&load_file,
171             validate_callback => \&validate_file;
172              
173             # fetch an object from the cache - if it's already in the cache and
174             # validate_file() returns 1, then we'll get the cached file. If it's
175             # not in the cache, or validate_file returns 0, then load_file is
176             # called to load the file into the cache.
177              
178             $config_file = $cache{'/some/path/to/some.config'};
179              
180             =head1 DETAILS
181              
182             The module implements a full tied hash interface, meaning that you can
183             use exists(), delete(), keys() and each(). However, in normal usage
184             all you'll need to do is to fetch values from the cache and possible
185             delete keys. Just in case you were wondering, exists() doesn't
186             trigger a cache load - it returns 1 if the given key is already in the
187             cache and 0 if it isn't. Similarily, keys() and each() operate on
188             key/value pairs already loaded into the cache.
189              
190             The most important thing to realize is that there is no need to
191             explicitely store into the cache since the load_callback is called
192             automatically when it is necessary to load new data. If you find
193             yourself using more than just "C<$data = $cache{'key'};>" you need to
194             make sure you really know what you're doing!
195              
196             =head2 OPTIONS
197              
198             There are a number parameters to tie that can be used to control the
199             behavior of IPC::SharedCache. Some of them are required, and some art
200             optional. Here's a preview:
201              
202             tie %cache, 'IPC::SharedCache',
203              
204             # required parameters
205             ipc_key => 'MYKI',
206             load_callback => \&load,
207             validate_callback => \&validate,
208              
209             # optional parameters
210             ipc_mode => 0666,
211             ipc_segment_size => 1_000_000,
212             max_size => 50_000_000,
213             debug => 1;
214              
215             =head2 ipc_key (required)
216              
217             This is the unique identifier for the particular cache. It can be
218             specified as either a four-character string or an integer value. Any
219             script that wishes to access the cache must use the same ipc_key
220             value. You can use the ftok() function from IPC::SysV to generate
221             this value, see L for details. Using an ipc_key value
222             that's already in use by a non-IPC::SharedCache application will cause
223             an error. Many systems provide a utility called 'ipcs' to examine
224             shared memory; you can use it to check for existing shared memory
225             usage before choosing your ipc_key.
226              
227             =head2 load_callback and validate_callback (required)
228              
229             These parameters both specify callbacks for IPC::SharedCache to use
230             when the cache gets a request for a key. When you access the cache
231             (C<$data = $cache{$key}>), the cache first looks to see if it already
232             has an object for the given key. If it doesn't, it calls the
233             load_callback and returns the result which is also stored in the
234             cache. Alternately, if it does have the object in the cache it calls
235             the validate_callback to check if the object is still good. If the
236             validate_callback returns true then object is good and is returned.
237             If the validate_callback returns false then the object is discarded
238             and the load_callback is called.
239              
240             The load_callback recieves a single parameter - the requested key. It
241             must return a reference to the data object be stored in the cache.
242             Returning something that is not a reference results in an error.
243              
244             The validate_callback recieves two parameters - the key and the
245             reference to the stored object. It must return true or false.
246              
247             There are two ways to specify the callbacks. The first is simply to
248             specify a subroutine reference. This can be an anonymous subroutine
249             or a named one. Example:
250              
251             tie %cache, 'IPC::SharedCache',
252             ipc_key => 'TEST',
253             load_callback => sub { ... },
254             validate_callback => \&validate;
255              
256             The second method allows parameters to be passed to the subroutine
257             when it is called. This is done by specifying a reference to an array
258             of values, the first being the subroutine reference and the rest are
259             parameters for the subroutine. The extra parameters are passed in
260             before the IPC::SharedCache provided parameters. Example:
261              
262             tie %cache, 'IPC::SharedCache',
263             ipc_key => 'TEST',
264             load_callback => [\&load, $arg1, $arg2, $arg3]
265             validate_callback => [\&validate, $self];
266              
267             =head2 ipc_mode (optional)
268              
269             This option specifies the access mode of the IPC cache. It defaults
270             to 0666. See L for more information on IPC access
271             modes. The default should be fine for most applications.
272              
273             =head2 ipc_segment_size (optional)
274              
275             This option allows you to specify the "chunk size" of the IPC shared
276             memory segments. The default is 65,536, which is 64K. This is a good
277             default and is very portable. If you know that your system supports
278             larger IPC segment sizes and you know that your cache will be storing
279             large data items you might get better performance by increasing this
280             value.
281              
282             This value places no limit on the size of an object stored in the
283             cache - IPC::SharedCache automatically spreads large objects across
284             multiple IPC segments.
285              
286             WARNING: setting this value too low (below 1024 in my experience) can
287             cause errors.
288              
289             =head2 max_size (optional)
290              
291             By setting this parameter you are setting a logical maximum to the
292             ammount of data stored in the cache. When an item is stored in the
293             cache and this limit is exceded the oldest item (or items, as
294             necessary) in the cache will be deleted to make room. This value is
295             specified in bytes. It defaults to 0, which specifies no limit on the
296             size of the cache.
297              
298             Turning this feature on costs a fair ammount of performance - how much
299             depends largely on home much data is being stored into the cache
300             versus the size of max_cache. In the worst case (where the max_size
301             is set much too low) this option can cause severe "thrashing" and
302             negate the benefit of maintaining a cache entirely.
303              
304             NOTE: The size of the cache may in fact exceed this value - the
305             book-keeping data stored in the root segment is not counted towards
306             the total. Also, extra padding imposed by the ipc_segment_size is not
307             counted. This may change in the future if I learn that it would be
308             appropriate to count this padding as used memory. It is not clear to
309             me that all IPC implementations will really waste this memory.
310              
311             =head2 debug (optional)
312              
313             Set this option to 1 to see a whole bunch of text on STDERR about what
314             IPC::SharedCache is doing.
315              
316             =head1 UTILITIES
317              
318             Two static functions are included in this package that are meant to be
319             used from the command-line.
320              
321             =head2 walk
322              
323             Walk prints out a detailed listing of the contents of a shared cache
324             at a given ipc_key. It provides information the current keys stored
325             and a dump of the objects stored in each key. Be warned, this can be
326             quite a lot of data! Also, you'll need the Data::Dumper module
327             installed to use 'walk'. You can get it on CPAN.
328              
329             You can call walk like:
330              
331             perl -MIPC::SharedCache -e 'IPC::SharedCache::walk AKEY'"
332              
333             Example:
334              
335             $ perl -MIPC::SharedCache -e 'IPC::SharedCache::walk MYKI'"
336             *===================*
337             IPC::SharedCache Root
338             *===================*
339             IPC_KEY: MYKI
340             ELEMENTS: 3
341             TOTAL SIZE: 99 bytes
342             KEYS: a, b, c
343              
344             *=======*
345             Data List
346             *=======*
347              
348             KEY: a
349             $CONTENTS = [
350             950760892,
351             950760892,
352             950760892
353             ];
354              
355              
356             KEY: b
357             $CONTENTS = [
358             950760892,
359             950760892,
360             950760892
361             ];
362              
363              
364             KEY: c
365             $CONTENTS = [
366             950760892,
367             950760892,
368             950760892
369             ];
370              
371             =head2 remove
372              
373             This function totally removes an entire cache given an ipc_key value.
374             This should not be done to a running system! Still, it's an
375             invaluable tool during development when flawed data may become 'stuck'
376             in the cache.
377              
378             $ perl -MIPC::SharedCache -e 'IPC::SharedCache::remove MYKI'
379              
380             This function is silent and thus may be usefully called from within a
381             script if desired.
382              
383             =head1 BUGS
384              
385             I am aware of no bugs - if you find one please email me at
386             sam@tregar.com. When submitting bug reports, be sure to include full
387             details, including the VERSION of the module and a test script
388             demonstrating the problem.
389              
390             =head1 CREDITS
391              
392             I would like to thank Maurice Aubrey for making this module possible
393             by producing the excelent IPC::ShareLite.
394              
395             The following people have contributed patches, ideas or new features:
396              
397             Tim Bunce
398             Roland Mas
399             Drew Taylor
400             Ed Loehr
401             Maverick
402              
403             Thanks everyone!
404              
405             =head1 AUTHOR
406              
407             Sam Tregar, sam@tregar.com (you can also find me on the mailing list
408             for HTML::Template at htmltmpl@lists.vm.com - join it by sending a
409             blank message to htmltmpl-subscribe@lists.vm.com).
410              
411             =head1 LICENSE
412              
413             IPC::SharedCache - a Perl module to manage a SysV IPC shared cache.
414             Copyright (C) 2000 Sam Tregar (sam@tregar.com)
415              
416             This program is free software; you can redistribute it and/or modify
417             it under the terms of the GNU General Public License as published by
418             the Free Software Foundation; either version 2 of the License, or (at
419             your option) any later version.
420              
421             This program is distributed in the hope that it will be useful, but
422             WITHOUT ANY WARRANTY; without even the implied warranty of
423             MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
424             General Public License for more details.
425              
426             You should have received a copy of the GNU General Public License
427             along with this program; if not, write to the Free Software
428             Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
429             USA
430              
431              
432             =cut
433              
434              
435 1     1   1048 use strict;
  1         2  
  1         42  
436 1     1   1017 use integer;
  1         11  
  1         6  
437              
438 1     1   29 use Carp;
  1         5  
  1         239  
439 1     1   1081 use Storable qw(freeze thaw);
  1         4465  
  1         96  
440 1     1   941 use IPC::ShareLite qw(LOCK_EX LOCK_SH);
  1         256834  
  1         248  
441              
442             # a local cache to store the root share
443 1     1   14 use vars qw(%ROOT_SHARE_CACHE);
  1         2  
  1         3629  
444              
445             ###############
446             # Constructor #
447             ###############
448              
449             sub TIEHASH {
450 1     1   84 my $pkg = shift;
451 1         4 my $self = bless({}, $pkg); # create the object with bless
452 1         2 my $options = {};
453 1         6 $self->{options} = $options;
454              
455 1 50       5 _debug("TIEHASH : " . join(', ', @_)) if $options->{debug};
456              
457             # set default parameters in options hash
458 1         11 %$options = (
459             ipc_key => undef,
460             ipc_mode => 0666,
461             ipc_segment_size => 65536,
462             load_callback => undef,
463             validate_callback => undef,
464             max_size => 0,
465             debug => 0
466             );
467            
468             # load in options supplied to new()
469 1 50       16 croak("$pkg object created with odd number of option parameters - should be of the form option => value")
470             if (@_ % 2);
471 1         10 for (my $x = 0; $x <= $#_; $x += 2) {
472 4 50       12 croak("Unknown parameter $_[$x] in $pkg object creation.")
473             unless exists($options->{lc($_[$x])});
474 4         13 $options->{lc($_[$x])} = $_[($x + 1)];
475             }
476              
477             # make sure the required ones are here.
478 1         2 foreach my $name (qw(ipc_key load_callback validate_callback)) {
479 3 50       10 croak("$pkg object creation missing $name paramter.")
480             unless defined($options->{$name});
481             }
482            
483 1 50       4 require "Data/Dumper.pm" if $options->{debug};
484              
485             # initialize the cache root
486 1         6 $self->_init_root;
487              
488 0         0 return $self;
489             }
490              
491             ##################
492             # Public Methods #
493             ##################
494              
495             # get a value from the cache
496             sub FETCH {
497 0     0   0 my ($self, $key) = @_;
498 0         0 my $options = $self->{options};
499 0         0 my $ipc_key = $options->{ipc_key};
500              
501 0 0       0 _debug("FETCH: $key") if $options->{debug};
502              
503             # predeclare my variables to avoid spending any more time than
504             # necessary inside shared locks.
505 0         0 my ($root_record, $obj_ipc_key, $object);
506            
507 0         0 my $root = $ROOT_SHARE_CACHE{$ipc_key};
508 0 0       0 confess("IPC::SharedCache : Undefined root share.")
509             unless defined $root;
510            
511 0         0 _lock($root, LOCK_SH);
512              
513             # look in the cache map for a record matching this key
514 0         0 $root_record = $self->_get_root_record($root);
515            
516             # if one exists, fetch the object from the cache
517 0 0       0 $object = $self->_get_share_object($root_record->{'map'}{$key})
518             if (exists $root_record->{'map'}{$key});
519              
520             # that's it - release the lock
521 0         0 _unlock($root);
522            
523             # test its validity with _validate, if not get it with _load and
524             # STORE it. Do the same if it wasn't there. If it passes, return it.
525 0 0       0 if (defined($object)) {
526 0         0 my $result;
527              
528 0         0 eval { $result = $self->_validate($key, $object); };
  0         0  
529 0 0       0 croak("Error occured during validate_callback: $@") if $@;
530              
531 0 0 0     0 _debug("VALIDATE RETURN TRUE FOR: $key") if $options->{debug} and $result;
532 0 0 0     0 _debug("VALIDATE RETURN FALSE FOR: $key") if $options->{debug} and not $result;
533 0 0       0 return $object if $result;
534             }
535              
536             # if it didn't pass, load it and STORE it. Then return it.
537 0         0 eval { $object = $self->_load($key); };
  0         0  
538 0 0       0 croak("Error occured during load_callback: $@") if $@;
539              
540 0 0       0 $self->STORE($key, $object) if defined $object;
541 0         0 return $object;
542             }
543              
544             # store a value from the cache. Generally not called from userland,
545             # but available none-the-less.
546             sub STORE {
547 0     0   0 my ($self, $key, $object) = @_;
548 0         0 my $options = $self->{options};
549 0         0 my $ipc_key = $options->{ipc_key};
550              
551 0 0       0 _debug("STORE: $key $object") if $options->{debug};
552              
553             # freeze the block to store in the cache
554 0         0 my $cache_block = freeze($object);
555              
556             # if max_size is set check to see if we can store this object at all,
557             # return if not.
558 0 0 0     0 if ($options->{max_size} and
559             length($cache_block) > $options->{max_size}) {
560 0 0       0 _debug("STORE: $key is too large for cache max_size ($options->{max_size})") if $options->{debug};
561 0         0 return;
562             }
563              
564             # predeclare my variables to avoid spending any more time than
565             # necessary inside shared locks.
566 0         0 my ($root_record, $obj_ipc_key);
567            
568 0         0 my $root = $ROOT_SHARE_CACHE{$ipc_key};
569 0 0       0 confess("IPC::SharedCache : Undefined root share.")
570             unless defined $root;
571            
572             # get an exclusive lock on the root cache - may need to write
573 0         0 _lock($root, LOCK_EX);
574              
575             # look in the cache map for a record matching this key
576 0         0 $root_record = $self->_get_root_record($root);
577            
578             # if a record already exists for this key, we can just go ahead and
579             # store the new object into the old slot.
580 0         0 my $share;
581 0 0       0 if (exists $root_record->{'map'}{$key}) {
582             # we've got a key, get the share and cache it
583 0         0 $share = IPC::ShareLite->new('-key' => $root_record->{'map'}{$key},
584             '-mode' => $options->{ipc_mode},
585             '-size' => $options->{ipc_segment_size},
586             '-create' => 0,
587             '-destroy' => 0);
588 0 0       0 confess("IPC::SharedCache: Unable to get shared cache block $root_record->{'map'}{$key} : $!") unless defined $share;
589              
590 0         0 $root_record->{'size'} -= $root_record->{'length_map'}{$key};
591 0         0 $root_record->{'size'} += length($cache_block);
592 0         0 $root_record->{'length_map'}{$key} = length($cache_block);
593             } else {
594             # otherwise we need to find a new segment
595 0   0     0 my $obj_ipc_key = $root_record->{'last_key'} || 1;
596 0         0 for ( my $end = $obj_ipc_key + 10000 ;
597             $obj_ipc_key != $end ;
598             $obj_ipc_key++ ) {
599 0         0 $share = IPC::ShareLite->new('-key' => $obj_ipc_key,
600             '-mode' => $options->{ipc_mode},
601             '-size' => $options->{ipc_segment_size},
602             '-create' => 1,
603             '-exclusive' => 1,
604             '-destroy' => 0,
605             );
606 0 0       0 last if defined $share;
607             }
608 0 0       0 croak("IPC::SharedCache : searched through 10,000 consecutive locations for a free shared memory segment, giving up : $!")
609             unless defined $share;
610              
611             # update the root record and store
612 0         0 $root_record->{'last_key'} = $obj_ipc_key;
613 0         0 $root_record->{'map'}{$key} = $obj_ipc_key;
614 0         0 $root_record->{'size'} += length($cache_block);
615 0         0 $root_record->{'length_map'}{$key} = length($cache_block);
616 0         0 push (@{$root_record->{'queue'}},$key);
  0         0  
617             }
618              
619             # if we're over max_size, delete off the queue until we're below the
620             # limit. We need to inline the delete to keep track of stats and
621             # delay the update.
622 0 0       0 if ($options->{max_size}) {
623 0   0     0 while($root_record->{'size'} > $options->{'max_size'} and
  0         0  
624             scalar(@{$root_record->{'queue'}})) {
625 0         0 my $delete_key = shift @{$root_record->{'queue'}};
  0         0  
626             # delete the segment for this object
627             {
628 0         0 my $share = IPC::ShareLite->new('-key' => $root_record->{map}{$delete_key},
  0         0  
629             '-mode' => $options->{ipc_mode},
630             '-size' => $options->{ipc_segment_size},
631             '-create' => 0,
632             '-destroy' => 1);
633 0 0       0 confess("IPC::SharedCache: Unable to get shared cache block $root_record->{'map'}{$key} : $!") unless defined $share;
634             # share is now deleted since destroy == 1 and $share goes out of scope
635             }
636             # remove the record members for this share
637 0         0 $root_record->{'last_key'} = $root_record->{map}{$delete_key};
638 0         0 delete($root_record->{'map'}{$delete_key});
639 0         0 $root_record->{'size'} -= $root_record->{'length_map'}{$delete_key};
640 0         0 delete($root_record->{'length_map'}{$delete_key});
641             }
642             }
643            
644             # store the block and the updated root record into the cache
645 0         0 eval { $root->store(freeze($root_record)); };
  0         0  
646 0 0       0 confess("IPC::SharedCache: Problem storing into root cache segment. IPC::ShareLite error: $@") if $@;
647              
648 0         0 eval { $share->store($cache_block); };
  0         0  
649 0 0       0 confess("IPC::SharedCache: Problem storing into cache segment $root_record->{'map'}{$key}. IPC::ShareLite error: $@") if $@;
650              
651             # that's it - release the lock
652 0         0 _unlock($root);
653              
654             # I suppose that chained assigments should work.
655 0         0 return $object;
656             }
657              
658             sub DELETE {
659 0     0   0 my ($self, $key) = @_;
660 0         0 my $options = $self->{options};
661 0         0 my $ipc_key = $options->{ipc_key};
662              
663 0 0       0 _debug("DELETE: $key") if $options->{debug};
664              
665             # predeclare my variables to avoid spending any more time than
666             # necessary inside shared locks.
667 0         0 my ($root_record, $obj_ipc_key);
668            
669 0         0 my $root = $ROOT_SHARE_CACHE{$ipc_key};
670 0 0       0 confess("IPC::SharedCache : Undefined root share.")
671             unless defined $root;
672            
673             # get an exclusive lock on the root cache
674 0         0 _lock($root, LOCK_EX);
675              
676             # look in the cache map for a record matching this key
677 0         0 $root_record = $self->_get_root_record($root);
678            
679 0 0       0 unless (exists $root_record->{'map'}{$key}) {
680 0         0 _unlock($root);
681 0         0 return 1;
682             }
683 0         0 $obj_ipc_key = $root_record->{'map'}{$key};
684              
685             # delete the segment for this object
686             {
687 0         0 my $share = IPC::ShareLite->new('-key' => $obj_ipc_key,
  0         0  
688             '-mode' => $options->{ipc_mode},
689             '-size' => $options->{ipc_segment_size},
690             '-create' => 0,
691             '-destroy' => 1);
692 0 0       0 confess("IPC::SharedCache: Unable to get shared cache block $root_record->{'map'}{$key} : $!") unless defined $share;
693             # share is now deleted since destroy == 1 and $share goes out of scope
694             }
695            
696             # remove the record members for this share
697 0         0 $root_record->{'last_key'} = $obj_ipc_key;
698 0         0 delete($root_record->{'map'}{$key});
699 0         0 $root_record->{'size'} -= $root_record->{'length_map'}{$key};
700 0         0 delete($root_record->{'length_map'}{$key});
701 0         0 @{$root_record->{'queue'}} = grep {$_ ne $key } @{$root_record->{'queue'}};
  0         0  
  0         0  
  0         0  
702              
703             # store the block and the updated root record into the cache
704 0         0 eval { $root->store(freeze($root_record)); };
  0         0  
705 0 0       0 confess("IPC::SharedCache: Problem storing into root cache segment. IPC::ShareLite error: $@") if $@;
706              
707             # that's it - release the lock
708 0         0 _unlock($root);
709 0         0 return 1;
710             }
711              
712             sub EXISTS {
713 0     0   0 my ($self, $key) = @_;
714 0         0 my $options = $self->{options};
715 0         0 my $ipc_key = $options->{ipc_key};
716              
717 0 0       0 _debug("EXISTS: $key") if $options->{debug};
718              
719             # predeclare my variables to avoid spending any more time than
720             # necessary inside shared locks.
721 0         0 my ($root_record, $obj_ipc_key);
722            
723 0         0 my $root = $ROOT_SHARE_CACHE{$ipc_key};
724 0 0       0 confess("IPC::SharedCache : Undefined root share.")
725             unless defined $root;
726            
727             # get an exclusive lock on the root cache
728 0         0 _lock($root, LOCK_SH);
729              
730             # look in the cache map for a record matching this key
731 0         0 $root_record = $self->_get_root_record($root);
732            
733 0         0 _unlock($root);
734              
735 0 0       0 return 1 if (exists $root_record->{'map'}{$key});
736 0         0 return 0;
737             }
738              
739             sub FIRSTKEY {
740 0     0   0 my ($self) = @_;
741 0         0 my $options = $self->{options};
742 0         0 my $ipc_key = $options->{ipc_key};
743              
744 0 0       0 _debug("FIRSTKEY") if $options->{debug};
745              
746             # predeclare my variables to avoid spending any more time than
747             # necessary inside shared locks.
748 0         0 my ($root_record, $obj_ipc_key, $first_key);
749            
750 0         0 my $root = $ROOT_SHARE_CACHE{$ipc_key};
751 0 0       0 confess("IPC::SharedCache : Undefined root share.")
752             unless defined $root;
753            
754             # get an exclusive lock on the root cache
755 0         0 _lock($root, LOCK_SH);
756              
757             # look in the cache map for a record matching this key
758 0         0 $root_record = $self->_get_root_record($root);
759              
760             # get the first key
761 0         0 $first_key = $root_record->{'queue'}[0];
762            
763 0         0 _unlock($root);
764              
765 0         0 return $first_key;
766             }
767              
768             sub NEXTKEY {
769 0     0   0 my ($self, $lastkey) = @_;
770 0         0 my $options = $self->{options};
771 0         0 my $ipc_key = $options->{ipc_key};
772              
773 0 0       0 _debug("NEXTKEY $lastkey") if $options->{debug};
774              
775             # predeclare my variables to avoid spending any more time than
776             # necessary inside shared locks.
777 0         0 my ($root_record, $obj_ipc_key, $next_key);
778            
779 0         0 my $root = $ROOT_SHARE_CACHE{$ipc_key};
780 0 0       0 confess("IPC::SharedCache : Undefined root share.")
781             unless defined $root;
782            
783             # get an exclusive lock on the root cache
784 0         0 _lock($root, LOCK_SH);
785              
786             # look in the cache map for a record matching this key
787 0         0 $root_record = $self->_get_root_record($root);
788              
789             # get the next key
790 0         0 for(my $x = 0; $x < $#{$root_record->{'queue'}}; $x++) {
  0         0  
791 0 0       0 $next_key = $root_record->{'queue'}[($x + 1)], last
792             if ($root_record->{'queue'}[$x] eq $lastkey);
793             }
794            
795 0         0 _unlock($root);
796              
797 0         0 return $next_key;
798             }
799              
800              
801             sub CLEAR {
802             # implementation from Tie::Hash
803 0     0   0 my $self = shift;
804 0         0 my $options = $self->{options};
805 0         0 my $key = $self->FIRSTKEY(@_);
806 0         0 my @keys;
807              
808 0 0       0 _debug("CLEAR") if $options->{debug};
809              
810 0         0 while (defined $key) {
811 0         0 push @keys, $key;
812 0         0 $key = $self->NEXTKEY(@_, $key);
813             }
814 0         0 foreach $key (@keys) {
815 0         0 $self->DELETE(@_, $key);
816             }
817             }
818              
819             ####################
820             # Static Functions #
821             ####################
822              
823             # call like "perl -MIPC::SharedCache -e 'IPC::SharedCache::walk AKEY'"
824             sub walk {
825 0     0 1 0 my ($key, $segment_size) = @_;
826 0 0       0 $segment_size = 65536 unless defined($segment_size);
827 0 0 0     0 print("Usage: IPC::SharedCache::list AKEY [segment_size]\n"), exit
828             if (not defined($key) or scalar(@_) > 2);
829              
830 0         0 require "Data/Dumper.pm";
831            
832             # make sure the cache actually exists here
833 0         0 my $test = IPC::ShareLite->new('-key' => $key,
834             '-mode' => 0666,
835             '-size' => $segment_size,
836             '-create' => 0,
837             '-destroy' => 0);
838 0 0       0 die "Unable to find a cache at key $key : $!" unless defined $test;
839              
840 0         0 my %self;
841             tie %self, 'IPC::SharedCache',
842             ipc_key => $key,
843             ipc_segment_size => $segment_size,
844 0     0   0 load_callback => sub {},
845 0     0   0 validate_callback => sub {};
  0         0  
846              
847 0         0 my $root = $ROOT_SHARE_CACHE{$key};
848 0 0       0 confess("IPC::SharedCache : Undefined root share.")
849             unless defined $root;
850            
851             # get a shared lock on the root cache
852 0         0 _lock($root, LOCK_SH);
853              
854             # look in the cache map for a record matching this key
855 0         0 my $root_record = _get_root_record(\%self, $root);
856              
857 0         0 my $elements = scalar(keys(%{$root_record->{'map'}}));
  0         0  
858 0         0 my $keys = join(', ', sort { $a <=> $b } keys(%{$root_record->{'map'}}));
  0         0  
  0         0  
859              
860 0         0 print STDERR <
861             *===================*
862             IPC::SharedCache Root
863             *===================*
864             IPC_KEY: $key
865             ELEMENTS: $elements
866             TOTAL SIZE: $root_record->{size} bytes
867             KEYS: $keys
868              
869             *=======*
870             Data List
871             *=======*
872              
873             END
874              
875 0         0 foreach my $key (sort { $a <=> $b } keys(%{$root_record->{'map'}})) {
  0         0  
  0         0  
876 0         0 my ($contents_block, $contents) = _get_share_object(\%self, $root_record->{'map'}{$key});
877 0         0 $contents = Data::Dumper->Dump([$contents],
878             [qw($CONTENTS)]);
879 0         0 print STDERR <
880             KEY: $key
881             IPC_KEY: $root_record->{'map'}{$key}
882             $contents
883              
884             END
885             }
886              
887             # that's it - release the lock
888 0         0 _unlock($root);
889             }
890              
891             # call like "perl -MIPC::SharedCache -e 'IPC::SharedCache::remove AKEY'"
892             sub remove {
893 0     0 1 0 my ($key, $segment_size) = @_;
894 0 0       0 $segment_size = 65536 unless defined($segment_size);
895 0 0 0     0 print("Usage: IPC::SharedCache::remove AKEY [segment_size]\n"), exit
896             if (not defined($key) or scalar(@_) > 2);
897              
898 0         0 my %self;
899             tie %self, 'IPC::SharedCache',
900             ipc_key => $key,
901             ipc_segment_size => $segment_size,
902 0     0   0 load_callback => sub {},
903 0     0   0 validate_callback => sub {};
  0         0  
904              
905             # remove all segments
906 0         0 %self = ();
907              
908             # this has to come first - dangeling references to the root will
909             # keep it from actually being deleted.
910 0         0 delete($ROOT_SHARE_CACHE{$key});
911            
912             # delete the root segment
913             {
914 0         0 my $share = IPC::ShareLite->new('-key' => $key,
  0         0  
915             '-size' => $segment_size,
916             '-create' => 0,
917             '-destroy' => 1);
918 0 0       0 confess("IPC::SharedCache: Unable to get shared cache block $key : $!") unless defined $share;
919             # share is now deleted since destroy == 1 and $share goes out of scope
920             }
921              
922 0         0 return;
923             }
924              
925              
926             #########################
927             # IPC Utility Functions #
928             #########################
929              
930             # initialize the cache root
931             sub _init_root {
932 1     1   2 my $self = shift;
933 1         4 my $options = $self->{options};
934 1         2 my $ipc_key = $options->{ipc_key};
935              
936             # do root initialization, check the cache first
937 1         2 my $root = $ROOT_SHARE_CACHE{$ipc_key};
938 1 50       3 return if defined $root;
939              
940             # try to get a handle on an existing root for this key
941 1         10 $root = IPC::ShareLite->new('-key' => $ipc_key,
942             '-mode' => $options->{ipc_mode},
943             '-size' => $options->{ipc_segment_size},
944             '-create' => 0,
945             '-destroy' => 0);
946 0 0         if (defined $root) {
947 0           $ROOT_SHARE_CACHE{$ipc_key} = $root;
948 0           return;
949             }
950              
951             # prepare empty root record for new root creation
952 0           my $record = { 'map' => {},
953             'size' => 0,
954             'last_key' => 0,
955             'queue' => [],
956             };
957 0           my $record_block = freeze($record);
958              
959             #print Data::Dumper->Dump([$record, $record_block],
960             # [qw($record $record_block)]), "\n"
961             # if $options->{debug};
962              
963             # try to create it if that didn't work (and do initialization)
964 0           $root = IPC::ShareLite->new('-key' => $options->{ipc_key},
965             '-mode' => $options->{ipc_mode},
966             '-size' => $options->{ipc_segment_size},
967             '-create' => 1,
968             '-exclusive' => 1,
969             '-destroy' => 0);
970 0 0         confess("IPC::SharedCache object initialization : Unable to initialize root ipc shared memory segment : $!")
971             unless defined($root);
972              
973 0           eval { $root->store($record_block); };
  0            
974 0 0         confess("IPC::SharedCache object initialization : Problem storeing inital root cache record. IPC::ShareLite error: $@") if $@;
975              
976            
977              
978 0 0         print STDERR "### IPC::SharedCache Debug ### ROOT INIT\n"
979             if $options->{debug};
980              
981             # put the share into the local memory cache
982 0           $ROOT_SHARE_CACHE{$ipc_key} = $root;
983             }
984              
985             # lock the root segment, specifying type of lock
986             sub _lock {
987 0     0     my ($root, $type) = @_;
988              
989             # get a lock
990 0           my $result = $root->lock($type);
991 0 0         confess("IPC::SharedCache: Can't lock on root cache segment.")
992             unless defined $result;
993              
994 0           return 1;
995             }
996              
997             # unlock the root segment
998             sub _unlock {
999 0     0     my ($root) = @_;
1000              
1001             # get a lock
1002 0           my $result = $root->unlock();
1003 0 0         confess("IPC::SharedCache: Can't unlock root cache segment.")
1004             unless defined $result;
1005              
1006 0           return 1;
1007             }
1008              
1009             # gets the root record given the root share - does no locking of its
1010             # own.
1011             sub _get_root_record {
1012 0     0     my ($self, $root) = @_;
1013 0           my ($root_block, $root_record);
1014              
1015             # fetch the root block
1016 0           eval { $root_block = $root->fetch(); };
  0            
1017 0 0         confess("IPC::SharedCache: Problem fetching root cache segment. IPC::ShareLite error: $@") if $@;
1018 0 0         confess("IPC::SharedCache: Problem fetching root cache segment. IPC::ShareLite error: $!") unless defined($root_block);
1019            
1020             # thaw the root block, recovering the cache map
1021 0           eval { $root_record = thaw($root_block) };
  0            
1022 0 0         confess("IPC::SharedCache: Invalid cache_map recieved from shared memory. Perhaps this key is in use by another application? Storable error: $@") if $@;
1023 0 0         confess("IPC::SharedCache: Invalid cache_map recieved from shared memory. Perhaps this key is in use by another application?") unless ref($root_record) eq 'HASH';
1024            
1025             # look in the cache map for a record matching this key
1026 0           return $root_record;
1027             }
1028              
1029             # gets a cached object from a share - no locking, just a single atomic fetch.
1030             sub _get_share_object {
1031 0     0     my ($self, $obj_ipc_key) = @_;
1032 0           my $options = $self->{options};
1033              
1034             # we've got a key, get the share and cache it
1035 0           my $share = IPC::ShareLite->new('-key' => $obj_ipc_key,
1036             '-mode' => $options->{ipc_mode},
1037             '-size' => $options->{ipc_segment_size},
1038             '-create' => 0,
1039             '-destroy' => 0);
1040 0 0         confess("IPC::SharedCache: Unable to get shared cache block $obj_ipc_key : $!") unless defined $share;
1041            
1042             # get the cache block
1043 0           my $cache_block;
1044 0           eval { $cache_block = $share->fetch(); };
  0            
1045 0 0         confess("IPC::SharedCache: Problem fetching cache segment $obj_ipc_key. IPC::ShareLite error: $@") if $@;
1046            
1047             # pull out object data
1048 0           my $object;
1049 0           eval { $object = thaw($cache_block); };
  0            
1050 0 0         confess("IPC::SharedCache: Invalid cache object recieved from shared memory on key $obj_ipc_key. Perhaps this key is in use by another application? Storable error: $@") if $@;
1051              
1052 0 0         return($cache_block, $object)
1053             if (wantarray);
1054 0           return $object;
1055             }
1056              
1057              
1058             #############################
1059             # General Utility Functions #
1060             #############################
1061              
1062             # wrapper to call validate_callback and return result
1063             sub _validate {
1064 0     0     my ($self, $key, $object) = @_;
1065 0           my $validate_callback = $self->{options}{validate_callback};
1066 0           my $validate_type = ref($validate_callback);
1067              
1068 0 0         if ($validate_type eq 'CODE') {
    0          
1069 0           return $validate_callback->($key, $object);
1070             } elsif ($validate_type eq 'ARRAY') {
1071 0           my ($real_callback,@params) = @$validate_callback;
1072 0 0         if (ref($real_callback) eq 'CODE') {
1073 0           return $real_callback->(@params, $key, $object);
1074             } else {
1075 0           croak("IPC::SharedCache : validate_callback set to bad value - when set to an array the first element must be a CODE ref.");
1076             }
1077             } else {
1078 0           croak("IPC::SharedCache : validate_callback must be set to either a CODE ref or an ref to an array where the first element is a CODE ref and the rest are parameters.");
1079             }
1080             }
1081              
1082             # wrapper to call load_callback and return result
1083             sub _load {
1084 0     0     my ($self, $key) = @_;
1085 0           my $load_callback = $self->{options}{load_callback};
1086 0           my $load_type = ref($load_callback);
1087 0           my $result;
1088            
1089 0 0         if ($load_type eq 'CODE') {
    0          
1090 0           return $load_callback->($key);
1091             } elsif ($load_type eq 'ARRAY') {
1092 0           my ($real_callback, @params) = @{$load_callback};
  0            
1093 0 0         if (ref($real_callback) eq 'CODE') {
1094 0           return $real_callback->(@params, $key);
1095             } else {
1096 0           croak("IPC::SharedCache : load_callback set to bad value - when set to an array the first element must be a CODE ref.");
1097             }
1098             } else {
1099 0           croak("IPC::SharedCache : load_callback must be set to either a CODE ref or an array where the first element is a CODE ref and the rest are extra parameters to the subroutine.");
1100             }
1101             }
1102              
1103             sub _debug {
1104 0     0     my ($msg) = @_;
1105 0           print STDERR "### IPC::SharedCache Debug ### $msg\n";
1106             }
1107              
1108             1;
1109             __END__