1SharedCache(3)        User Contributed Perl Documentation       SharedCache(3)
2
3
4

NAME

6       IPC::SharedCache - a Perl module to manage a cache in SysV IPC shared
7       memory.
8

SYNOPSIS

10         use IPC::SharedCache;
11
12         # the cache is accessed using a tied hash.
13         tie %cache, 'IPC::SharedCache', ipc_key => 'AKEY',
14                                         load_callback => \&load,
15                                         validate_callback => \&validate;
16
17         # get an item from the cache
18         $config_file = $cache{'/some/path/to/some.config'};
19

DESCRIPTION

21       This module provides a shared memory cache accessed as a tied hash.
22
23       Shared memory is an area of memory that is available to all processes.
24       It is accessed by choosing a key, the ipc_key arguement to tie.  Every
25       process that accesses shared memory with the same key gets access to
26       the same region of memory.  In some ways it resembles a file system,
27       but it is not hierarchical and it is resident in memory.  This makes it
28       harder to use than a filesystem but much faster.  The data in shared
29       memory persists until the machine is rebooted or it is explicitely
30       deleted.
31
32       This module attempts to make shared memory easy to use for one specific
33       application - a shared memory cache.  For other uses of shared memory
34       see the documentation to the excelent module I use, IPC::ShareLite
35       (IPC::ShareLite).
36
37       A cache is a place where processes can store the results of their com‐
38       putations for use at a later time, possibly by other instances of the
39       application.  A good example of the use of a cache is a web server.
40       When a web server receieves a request for an html page it goes to the
41       file system to read it.  This is pretty slow, so the web server will
42       probably save the file in memory and use the in memory copy the next
43       time a request for that file comes in, as long as the file hasn't
44       changed on disk.  This certainly speeds things up but web servers have
45       to serve multiple clients at once, and that means multiple copies of
46       the in-memory data.  If the web server uses a shared memory cache, like
47       the one this module provides, then all the servers can use the same
48       cache and much less memory is consumed.
49
50       This module handles all shared memory interaction using the IPC::Share‐
51       Lite module (version 0.06 and higher) and all data serialization using
52       Storable.  See IPC::ShareLite and Storable for details.
53

MOTIVATION

55       This module began its life as an internal piece of HTML::Template (see
56       HTML::Template).  HTML::Template has the ability to maintain a cache of
57       parsed template structures when running in a persistent environment
58       like Apache/mod_perl.  Since parsing a template from disk takes a fair
59       ammount of time this can provide a big performance gain.  Unfortunately
60       it can also consume large ammounts of memory since each web server
61       maintains its own cache in its own memory space.
62
63       By using IPC::ShareLite and Storable (IPC::ShareLite and Storable),
64       HTML::Template was able to maintain a single shared cache of templates.
65       The downside was that HTML::Template's cache routines became compli‐
66       cated by a lot of IPC code.  My solution is to break out the IPC cache
67       mechanisms into their own module, IPC::SharedCache.  Hopefully over
68       time it can become general enough to be usable by more than just
69       HTML::Template.
70

USAGE

72       This module allows you to store data in shared memory and have it load
73       automatically when needed.  You can also define a test to screen cached
74       data for vailidty - if the test fails the data will be reloaded.  This
75       is useful for defining a max-age for cached data or keeping cached data
76       in sync with other resources.  In the web server example above the val‐
77       idation test would look to see wether the file had changed on disk.
78
79       To initialize this module you provide two callback subroutines.  The
80       first is the "load_callback".  This gets called when a user of the
81       cache requests an item from that is not yet present or is stale.  It
82       must return a reference to the data structure that will be stored in
83       the cache.  The second is the "validate_callback".  This gets called on
84       every cache access - its job is to check the cached object for fresh‐
85       ness (and/or some other validity, of course).  It must return true or
86       false.  When it returns true, the cached object is valid and is
87       retained in the cache.  When it returns false, the object is re-loaded
88       using the "load_callback" and the result is stored in the cache.
89
90       To use the module you just request entries for the objects you need.
91       If the object is present in the cache and the "validate_callback"
92       returns true, then you get the object from the cache.  If not, the
93       object is loaded into the cache with the "load_callback" and returned
94       to you.
95
96       The cache can be used to store any perl data structures that can be
97       serialized by the Storable module.  See Storable for details.
98

EXAMPLE

100       In this example a shared cache of files is maintained.  The "load_call‐
101       back" reads the file from disk into the cache and the "validate_call‐
102       back" checks its modification time using stat().  Note that the
103       "load_callback" stores information into the cached object that "vali‐
104       date_callback" uses to check the freshness of the cache.
105
106         # the "load_callback", loads the file from disk, storing its stat()
107         # information along with the file into the cache.  The key in this
108         # case is the filename to load.
109         sub load_file {
110           my $key = shift;
111
112           open(FILE, $key) or die "Unable to open file named $key : $!");
113
114           # note the modification time of this file - the 9th element of a
115           # stat() is the modification time of the file.
116           my $mtime = (stat($key))[9];
117
118           # read the file into the variable $contents in 1k chunks
119           my ($buffer, $contents);
120           while(read(FILE, $buffer, 1024)) { $contents .= $buffer }
121           close(FILE);
122
123           # prepare the record to store in the cache
124           my %record = ( mtime => $mtime, contents => $contents );
125
126           # this record goes into the cache associated with $key, which is
127           # the filename.  Notice that we're returning a reference to the
128           # data structure here.
129           return \%record;
130         }
131
132         # the "validate" callback, checks the mtime of the file on disk and
133         # compares it to the cache value.  The $record is a reference to the
134         # cached values array returned from load_file above.
135         sub validate_file {
136           my ($key, $record) = @_;
137
138           # get the modification time out of the record
139           my $stored_mtime = $record->{mtime};
140
141           # get the current modification time from the filesystem - the 9th
142           # element of a stat() is the modification time of the file.
143           my $current_mtime = (stat($key))[9];
144
145           # compare and return the appropriate result.
146           if ($stored_mtime == $current_mtime) {
147             # the cached object is valid, return true
148             return 1;
149           } else {
150             # the cached object is stale, return false - load_callback will
151             # be called to load it afresh from disk.
152             return 0;
153           }
154         }
155
156         # now we can construct the IPC::SharedCache object, using as a root
157         # key 'SAMS'.
158
159         tie %cache 'IPC::SharedCache' ipc_key => 'SAMS',
160                                       load_callback => \&load_file,
161                                       validate_callback => \&validate_file;
162
163         # fetch an object from the cache - if it's already in the cache and
164         # validate_file() returns 1, then we'll get the cached file.  If it's
165         # not in the cache, or validate_file returns 0, then load_file is
166         # called to load the file into the cache.
167
168         $config_file = $cache{'/some/path/to/some.config'};
169

DETAILS

171       The module implements a full tied hash interface, meaning that you can
172       use exists(), delete(), keys() and each().  However, in normal usage
173       all you'll need to do is to fetch values from the cache and possible
174       delete keys.  Just in case you were wondering, exists() doesn't trigger
175       a cache load - it returns 1 if the given key is already in the cache
176       and 0 if it isn't.  Similarily, keys() and each() operate on key/value
177       pairs already loaded into the cache.
178
179       The most important thing to realize is that there is no need to
180       explicitely store into the cache since the load_callback is called
181       automatically when it is necessary to load new data.  If you find your‐
182       self using more than just ""$data = $cache{'key'};"" you need to make
183       sure you really know what you're doing!
184
185       OPTIONS
186
187       There are a number parameters to tie that can be used to control the
188       behavior of IPC::SharedCache.  Some of them are required, and some art
189       optional. Here's a preview:
190
191          tie %cache, 'IPC::SharedCache',
192
193             # required parameters
194             ipc_key => 'MYKI',
195             load_callback => \&load,
196             validate_callback => \&validate,
197
198             # optional parameters
199             ipc_mode => 0666,
200             ipc_segment_size => 1_000_000,
201             max_size => 50_000_000,
202             debug => 1;
203
204       ipc_key (required)
205
206       This is the unique identifier for the particular cache.  It can be
207       specified as either a four-character string or an integer value.  Any
208       script that wishes to access the cache must use the same ipc_key value.
209       You can use the ftok() function from IPC::SysV to generate this value,
210       see IPC::SysV for details.  Using an ipc_key value that's already in
211       use by a non-IPC::SharedCache application will cause an error.  Many
212       systems provide a utility called 'ipcs' to examine shared memory; you
213       can use it to check for existing shared memory usage before choosing
214       your ipc_key.
215
216       load_callback and validate_callback (required)
217
218       These parameters both specify callbacks for IPC::SharedCache to use
219       when the cache gets a request for a key.  When you access the cache
220       ("$data = $cache{$key}"), the cache first looks to see if it already
221       has an object for the given key.  If it doesn't, it calls the
222       load_callback and returns the result which is also stored in the cache.
223       Alternately, if it does have the object in the cache it calls the vali‐
224       date_callback to check if the object is still good.  If the vali‐
225       date_callback returns true then object is good and is returned.  If the
226       validate_callback returns false then the object is discarded and the
227       load_callback is called.
228
229       The load_callback recieves a single parameter - the requested key.  It
230       must return a reference to the data object be stored in the cache.
231       Returning something that is not a reference results in an error.
232
233       The validate_callback recieves two parameters - the key and the refer‐
234       ence to the stored object.  It must return true or false.
235
236       There are two ways to specify the callbacks.  The first is simply to
237       specify a subroutine reference.  This can be an anonymous subroutine or
238       a named one.  Example:
239
240         tie %cache, 'IPC::SharedCache',
241             ipc_key => 'TEST',
242             load_callback => sub { ... },
243             validate_callback => \&validate;
244
245       The second method allows parameters to be passed to the subroutine when
246       it is called.  This is done by specifying a reference to an array of
247       values, the first being the subroutine reference and the rest are
248       parameters for the subroutine.  The extra parameters are passed in
249       before the IPC::SharedCache provided parameters.  Example:
250
251         tie %cache, 'IPC::SharedCache',
252             ipc_key => 'TEST',
253             load_callback => [\&load, $arg1, $arg2, $arg3]
254             validate_callback => [\&validate, $self];
255
256       ipc_mode (optional)
257
258       This option specifies the access mode of the IPC cache.  It defaults to
259       0666.  See IPC::ShareLite for more information on IPC access modes.
260       The default should be fine for most applications.
261
262       ipc_segment_size (optional)
263
264       This option allows you to specify the "chunk size" of the IPC shared
265       memory segments.  The default is 65,536, which is 64K.  This is a good
266       default and is very portable.  If you know that your system supports
267       larger IPC segment sizes and you know that your cache will be storing
268       large data items you might get better performance by increasing this
269       value.
270
271       This value places no limit on the size of an object stored in the cache
272       - IPC::SharedCache automatically spreads large objects across multiple
273       IPC segments.
274
275       WARNING: setting this value too low (below 1024 in my experience) can
276       cause errors.
277
278       max_size (optional)
279
280       By setting this parameter you are setting a logical maximum to the
281       ammount of data stored in the cache.  When an item is stored in the
282       cache and this limit is exceded the oldest item (or items, as neces‐
283       sary) in the cache will be deleted to make room.  This value is speci‐
284       fied in bytes.  It defaults to 0, which specifies no limit on the size
285       of the cache.
286
287       Turning this feature on costs a fair ammount of performance - how much
288       depends largely on home much data is being stored into the cache versus
289       the size of max_cache.  In the worst case (where the max_size is set
290       much too low) this option can cause severe "thrashing" and negate the
291       benefit of maintaining a cache entirely.
292
293       NOTE: The size of the cache may in fact exceed this value - the book-
294       keeping data stored in the root segment is not counted towards the
295       total.  Also, extra padding imposed by the ipc_segment_size is not
296       counted.  This may change in the future if I learn that it would be
297       appropriate to count this padding as used memory.  It is not clear to
298       me that all IPC implementations will really waste this memory.
299
300       debug (optional)
301
302       Set this option to 1 to see a whole bunch of text on STDERR about what
303       IPC::SharedCache is doing.
304

UTILITIES

306       Two static functions are included in this package that are meant to be
307       used from the command-line.
308
309       walk
310
311       Walk prints out a detailed listing of the contents of a shared cache at
312       a given ipc_key.  It provides information the current keys stored and a
313       dump of the objects stored in each key.  Be warned, this can be quite a
314       lot of data!  Also, you'll need the Data::Dumper module installed to
315       use 'walk'.  You can get it on CPAN.
316
317       You can call walk like:
318
319          perl -MIPC::SharedCache -e 'IPC::SharedCache::walk AKEY'"
320
321       Example:
322
323          $ perl -MIPC::SharedCache -e 'IPC::SharedCache::walk MYKI'"
324          *===================*
325          IPC::SharedCache Root
326          *===================*
327          IPC_KEY: MYKI
328          ELEMENTS: 3
329          TOTAL SIZE: 99 bytes
330          KEYS: a, b, c
331
332          *=======*
333          Data List
334          *=======*
335
336          KEY: a
337          $CONTENTS = [
338                        950760892,
339                        950760892,
340                        950760892
341                      ];
342
343          KEY: b
344          $CONTENTS = [
345                        950760892,
346                        950760892,
347                        950760892
348                      ];
349
350          KEY: c
351          $CONTENTS = [
352                        950760892,
353                        950760892,
354                        950760892
355                      ];
356
357       remove
358
359       This function totally removes an entire cache given an ipc_key value.
360       This should not be done to a running system!  Still, it's an invaluable
361       tool during development when flawed data may become 'stuck' in the
362       cache.
363
364          $ perl -MIPC::SharedCache -e 'IPC::SharedCache::remove MYKI'
365
366       This function is silent and thus may be usefully called from within a
367       script if desired.
368

BUGS

370       I am aware of no bugs - if you find one please email me at sam@tre‐
371       gar.com.  When submitting bug reports, be sure to include full details,
372       including the VERSION of the module and a test script demonstrating the
373       problem.
374

CREDITS

376       I would like to thank Maurice Aubrey for making this module possible by
377       producing the excelent IPC::ShareLite.
378
379       The following people have contributed patches, ideas or new features:
380
381          Tim Bunce
382          Roland Mas
383          Drew Taylor
384          Ed Loehr
385          Maverick
386
387       Thanks everyone!
388

AUTHOR

390       Sam Tregar, sam@tregar.com (you can also find me on the mailing list
391       for HTML::Template at htmltmpl@lists.vm.com - join it by sending a
392       blank message to htmltmpl-subscribe@lists.vm.com).
393

LICENSE

395       IPC::SharedCache - a Perl module to manage a SysV IPC shared cache.
396       Copyright (C) 2000 Sam Tregar (sam@tregar.com)
397
398       This program is free software; you can redistribute it and/or modify it
399       under the terms of the GNU General Public License as published by the
400       Free Software Foundation; either version 2 of the License, or (at your
401       option) any later version.
402
403       This program is distributed in the hope that it will be useful, but
404       WITHOUT ANY WARRANTY; without even the implied warranty of MER‐
405       CHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General
406       Public License for more details.
407
408       You should have received a copy of the GNU General Public License along
409       with this program; if not, write to the Free Software Foundation, Inc.,
410       59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
411

AUTHOR

413       Sam Tregar, sam@tregar.com
414

SEE ALSO

416       perl(1).
417
418
419
420perl v5.8.8                       2000-03-23                    SharedCache(3)
Impressum