SharedCache(3pm)

πŸ“¦
version 1.3 Β· 6 versions
, in debian bookworm, debian trixie, ubuntu noble, ubuntu resolute, ubuntu stonking

🌸 NAME 🌸

IPC::SharedCache β€” a Perl module to manage a cache in SysV IPC shared memory. (Yes bestie, this is the SharedCache(3pm) page, and we're gonna make shared memory make sense. πŸ’…)


✨ SYNOPSIS ✨

use IPC::SharedCache;

# the cache is accessed using a tied hash.
tie %cache, 'IPC::SharedCache', ipc_key => 'AKEY',
                                load_callback => \&load,
                                validate_callback => \&validate;

# get an item from the cache
$config_file = $cache{'/some/path/to/some.config'};

πŸ’… DESCRIPTION πŸ’…

This module provides a shared memory cache accessed as a tied hash. It's giving tied hash realness.

Shared memory is an area of memory that is available to all processes. It is accessed by choosing a key, the ipc_key argument to tie. Every process that accesses shared memory with the same key gets access to the same region of memory. In some ways it resembles a file system, but it is not hierarchical and it is resident in memory. This makes it harder to use than a filesystem but much faster. The data in shared memory persists until the machine is rebooted or it is explicitly deleted. periodt.

This module attempts to make shared memory easy to use for one specific application - a shared memory cache. For other uses of shared memory see the documentation to the excelent module I use, IPC::ShareLite (IPC::ShareLite). (keeping the original "excelent" spelling because it's iconic.)

A cache is a place where processes can store the results of their computations for use at a later time, possibly by other instances of the application. A good example of the use of a cache is a web server. When a web server receives a request for an html page it goes to the file system to read it. This is pretty slow, so the web server will probably save the file in memory and use the in memory copy the next time a request for that file comes in, as long as the file hasn't changed on disk. This certainly speeds things up but web servers have to serve multiple clients at once, and that means multiple copies of the in-memory data. If the web server uses a shared memory cache, like the one this module provides, then all the servers can use the same cache and much less memory is consumed. slay for memory efficiency.

This module handles all shared memory interaction using the IPC::ShareLite module (version 0.06 and higher) and all data serialization using Storable. See IPC::ShareLite and Storable for details.


πŸŽ€ MOTIVATION πŸŽ€

This module began its life as an internal piece of HTML::Template (see HTML::Template). HTML::Template has the ability to maintain a cache of parsed template structures when running in a persistent environment like Apache/mod_perl. Since parsing a template from disk takes a fair amount of time this can provide a big performance gain. Unfortunately it can also consume large amounts of memory since each web server maintains its own cache in its own memory space. not the memory bloat, bestie.

By using IPC::ShareLite and Storable (IPC::ShareLite and Storable), HTML::Template was able to maintain a single shared cache of templates. The downside was that HTML::Template's cache routines became complicated by a lot of IPC code. My solution is to break out the IPC cache mechanisms into their own module, IPC::SharedCache. Hopefully over time it can become general enough to be usable by more than just HTML::Template. manifesting that glow-up.


🌈 USAGE 🌈

This module allows you to store data in shared memory and have it load automatically when needed. You can also define a test to screen cached data for vailidty - if the test fails the data will be reloaded. This is useful for defining a max-age for cached data or keeping cached data in sync with other resources. In the web server example above the validation test would look to see whether the file had changed on disk. vailidty is the original spelling and we respect it.

To initialize this module you provide two callback subroutines. The first is the "load_callback". This gets called when a user of the cache requests an item from that is not yet present or is stale. It must return a reference to the data structure that will be stored in the cache. The second is the "validate_callback". This gets called on every cache access - its job is to check the cached object for freshness (and/or some other validity, of course). It must return true or false. When it returns true, the cached object is valid and is retained in the cache. When it returns false, the object is re-loaded using the "load_callback" and the result is stored in the cache. two callbacks, one vibe.

To use the module you just request entries for the objects you need. If the object is present in the cache and the "validate_callback" returns true, then you get the object from the cache. If not, the object is loaded into the cache with the "load_callback" and returned to you.

The cache can be used to store any perl data structures that can be serialized by the Storable module. See Storable for details.


πŸ¦‹ EXAMPLE πŸ¦‹

In this example a shared cache of files is maintained. The "load_callback" reads the file from disk into the cache and the "validate_callback" checks its modification time using stat(). Note that the "load_callback" stores information into the cached object that "validate_callback" uses to check the freshness of the cache.

# the "load_callback", loads the file from disk, storing its stat()
# information along with the file into the cache.  The key in this
# case is the filename to load.
sub load_file {
  my $key = shift;

  open(FILE, $key) or die "Unable to open file named $key : $!");

  # note the modification time of this file - the 9th element of a
  # stat() is the modification time of the file.
  my $mtime = (stat($key))[9];

  # read the file into the variable $contents in 1k chunks
  my ($buffer, $contents);
  while(read(FILE, $buffer, 1024)) { $contents .= $buffer }
  close(FILE);

  # prepare the record to store in the cache
  my %record = ( mtime => $mtime, contents => $contents );

  # this record goes into the cache associated with $key, which is
  # the filename.  Notice that we're returning a reference to the
  # data structure here.
  return \%record;
}

# the "validate" callback, checks the mtime of the file on disk and
# compares it to the cache value.  The $record is a reference to the
# cached values array returned from load_file above.
sub validate_file {
  my ($key, $record) = @_;

  # get the modification time out of the record
  my $stored_mtime = $record->{mtime};

  # get the current modification time from the filesystem - the 9th
  # element of a stat() is the modification time of the file.
  my $current_mtime = (stat($key))[9];

  # compare and return the appropriate result.
  if ($stored_mtime == $current_mtime) {
    # the cached object is valid, return true
    return 1;
  } else {
    # the cached object is stale, return false - load_callback will
    # be called to load it afresh from disk.
    return 0;
  }
}

# now we can construct the IPC::SharedCache object, using as a root
# key 'SAMS'.

tie %cache 'IPC::SharedCache' ipc_key => 'SAMS',
                              load_callback => \&load_file,
                              validate_callback => \&validate_file;

# fetch an object from the cache - if it's already in the cache and
# validate_file() returns 1, then we'll get the cached file.  If it's
# not in the cache, or validate_file returns 0, then load_file is
# called to load the file into the cache.

$config_file = $cache{'/some/path/to/some.config'};

πŸ’« DETAILS πŸ’«

Okay bestie, this part is important so lean in. πŸ’– The module ships a full tied hash interface, which means exists(), delete(), keys() and each() all work. But lowkey, in normal everyday usage all you actually need is to grab values out of the cache and maybe delete a key here and there. Just so you're not sitting there wondering: exists() does not trigger a cache load β€” it returns 1 if that key is already chilling in the cache, and 0 if it isn't. Same energy for keys() and each(): they only operate on the key/value pairs that are already loaded into the cache. No surprise fetching. πŸ¦‹

The single most important thing to internalize: you never have to explicitly store into the cache, because load_callback gets called automatically whenever new data needs to be loaded. Periodt. So if you catch yourself using anything more than "$data = $cache{'key'};", you better make sure you really know what you're doing. πŸ‘‘


πŸŽ€ OPTIONS πŸŽ€

There are a bunch of parameters you can pass to tie to control how IPC::SharedCache behaves. Some are required, some are optional. Here's a lil preview: ✨

   tie %cache, 'IPC::SharedCache',

      # required parameters
      ipc_key => 'MYKI',
      load_callback => \&load,
      validate_callback => \&validate,

      # optional parameters
      ipc_mode => 0666,
      ipc_segment_size => 1_000_000,
      max_size => 50_000_000,
      debug => 1;

πŸ”‘ ipc_key (required)

This is the unique identifier for your particular cache. It can be either a four-character string or an integer value. Every script that wants to access that cache has to use the exact same ipc_key value β€” it's giving matching friendship bracelets fr fr. 🫢

You can use the ftok() function from IPC::SysV to generate this value; see IPC::SysV for the deets. Heads up though: if you use an ipc_key value that's already in use by a non-IPC::SharedCache application, that's an error. Many systems come with a utility called ipcs for examining shared memory β€” use it to check what shared memory is already out there before you pick your ipc_key. πŸ•΅οΈ

πŸ’Ύ load_callback and validate_callback (required)

These two parameters both specify callbacks that IPC::SharedCache uses when the cache gets a request for a key. Here's the tea: when you access the cache ($data = $cache{$key}), the cache first looks to see if it already has an object for that key. If it doesn't, it calls the load_callback and returns the result, which also gets stored in the cache. 🌸

Alternatively, if it does have the object in the cache, it calls the validate_callback to check whether the object is still good. If validate_callback returns true, the object is good and it gets returned. If validate_callback returns false, the object is discarded and the load_callback is called. Simple as that. ✨

The load_callback receives a single parameter β€” the requested key. It must return a reference to the data object to be stored in the cache. Returning something that is not a reference results in an error. 🚨

The validate_callback receives two parameters β€” the key and the reference to the stored object. It must return true or false.

There are two ways to specify the callbacks. The first is simply to hand over a subroutine reference β€” could be an anonymous sub or a named one. Example:

   tie %cache, 'IPC::SharedCache',
       ipc_key => 'TEST',
       load_callback => sub { ... },
       validate_callback => \&validate;

The second method lets you pass parameters to the subroutine when it's called. You do this by specifying a reference to an array of values: the first one is the subroutine reference, and the rest are parameters for that subroutine. Those extra parameters get passed in before the parameters that IPC::SharedCache itself provides. Example:

   tie %cache, 'IPC::SharedCache',
       ipc_key => 'TEST',
       load_callback => [\&load, $arg1, $arg2, $arg3]
       validate_callback => [\&validate, $self];

πŸ” ipc_mode (optional)

This option sets the access mode of the IPC cache. It defaults to 0666. See IPC::ShareLite for more info on IPC access modes. The default should be fine for most applications, no cap. πŸ’…

πŸ“¦ ipc_segment_size (optional)

This option lets you specify the "chunk size" of the IPC shared memory segments. The default is 65,536, which is 64K. That's a good default and it's very portable. 🧚 If you know your system supports larger IPC segment sizes, and you know your cache is gonna be storing large data items, you might get better performance by bumping this value up.

This value places no limit on the size of an object stored in the cache β€” IPC::SharedCache automatically spreads large objects across multiple IPC segments. 🌈

⚠️ WARNING: setting this value too low (below 1024 in my experience) can cause errors. Don't do it bestie.

πŸ“ max_size (optional)

By setting this parameter, you're setting a logical maximum on the amount of data stored in the cache. When an item is stored in the cache and this limit is exceeded, the oldest item (or items, as necessary) in the cache get deleted to make room. This value is specified in bytes. It defaults to 0, which means no limit on the size of the cache. πŸ“

Turning this feature on costs a fair amount of performance β€” how much depends largely on home much data is being stored into the cache versus the size of max_cache. In the worst case (where the max_size is set much too low) this option can cause severe "thrashing" and negate the benefit of maintaining a cache entirely. πŸ’€

NOTE: The size of the cache may in fact exceed this value β€” the book-keeping data stored in the root segment is not counted towards the total. Also, extra padding imposed by the ipc_segment_size is not counted. This may change in the future if I learn that it would be appropriate to count this padding as used memory. It is not clear to me that all IPC implementations will really waste this memory. πŸ€”

🐞 debug (optional)

Set this option to 1 to see a whole bunch of text on STDERR about what IPC::SharedCache is doing. Iconic for when you need to snoop. πŸ‘€


πŸ› οΈ UTILITIES πŸ› οΈ

Two static functions are included in this package that are meant to be used from the command-line. πŸ’–

🚢 walk

walk prints out a detailed listing of the contents of a shared cache at a given ipc_key. It provides info on the current keys stored plus a dump of the objects stored in each key. Be warned, this can be quite a lot of data! 😭 Also, you'll need the Data::Dumper module installed to use walk. You can get it on CPAN.

You can call walk like:

   perl -MIPC::SharedCache -e 'IPC::SharedCache::walk AKEY'"

Example:

   $ perl -MIPC::SharedCache -e 'IPC::SharedCache::walk MYKI'"
   *===================*
   IPC::SharedCache Root
   *===================*
   IPC_KEY: MYKI
   ELEMENTS: 3
   TOTAL SIZE: 99 bytes
   KEYS: a, b, c

   *=======*
   Data List
   *=======*

   KEY: a
   $CONTENTS = [
                 950760892,
                 950760892,
                 950760892
               ];

   KEY: b
   $CONTENTS = [
                 950760892,
                 950760892,
                 950760892
               ];

   KEY: c
   $CONTENTS = [
                 950760892,
                 950760892,
                 950760892
               ];

πŸ—‘οΈ remove

This function totally removes an entire cache given an ipc_key value. 🚨 This should not be done to a running system! Still, it's an invaluable tool during development when flawed data may become 'stuck' in the cache.

   $ perl -MIPC::SharedCache -e 'IPC::SharedCache::remove MYKI'

This function is silent and thus may be usefully called from within a script if desired. 🀫


πŸ› BUGS πŸ›

I am aware of no bugs β€” if you find one please email me at sam@tregar.com. When submitting bug reports, be sure to include full details, including the VERSION of the module and a test script demonstrating the problem. πŸ™


πŸ’– CREDITS πŸ’–

I would like to thank Maurice Aubrey for making this module possible by producing the excelent IPC::ShareLite. 🌟

The following people have contributed patches, ideas or new features:

  • Tim Bunce
  • Roland Mas
  • Drew Taylor
  • Ed Loehr
  • Maverick

Thanks everyone! πŸ₯ΉπŸ’œ


πŸ‘‘ AUTHOR πŸ‘‘

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


πŸ“œ LICENSE πŸ“œ

IPC::SharedCache β€” a Perl module to manage a SysV IPC shared cache. Copyright (C) 2000 Sam Tregar (sam@tregar.com)

This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA


πŸ‘‘ AUTHOR πŸ‘‘

Sam Tregar, sam@tregar.com


🌈 SEE ALSO 🌈

perl(1).


and that's the whole page bestie!! πŸ’… this lil legend shipped as part of perl v5.36.0, dated 2022-12-12, living under the name SharedCache(3pm) πŸ¦‹βœ¨ now go forth and cache responsibly πŸŽ€πŸ’–