Bug 17823: Add label for MARC 583 - Action note
[koha.git] / Koha / Cache.pm
blob80ff1cad0eb66bc83b85b0a102af47ecf363d760
1 package Koha::Cache;
3 # Copyright 2009 Chris Cormack and The Koha Dev Team
4 # Parts copyright 2012-2013 C & P Bibliography Services
6 # This file is part of Koha.
8 # Koha is free software; you can redistribute it and/or modify it
9 # under the terms of the GNU General Public License as published by
10 # the Free Software Foundation; either version 3 of the License, or
11 # (at your option) any later version.
13 # Koha is distributed in the hope that it will be useful, but
14 # WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
18 # You should have received a copy of the GNU General Public License
19 # along with Koha; if not, see <http://www.gnu.org/licenses>.
21 =head1 NAME
23 Koha::Cache - Handling caching of html and Objects for Koha
25 =head1 SYNOPSIS
27 use Koha::Cache;
28 my $cache = Koha::Cache->new({cache_type => $cache_type, %params});
30 =head1 DESCRIPTION
32 Koha caching routines. This class provides two interfaces for cache access.
33 The first, traditional OO interface provides the following functions:
35 =head1 FUNCTIONS
37 =cut
38 use strict;
39 use warnings;
40 use Carp;
41 use Module::Load::Conditional qw(can_load);
42 use Sereal::Encoder;
43 use Sereal::Decoder;
45 use Koha::Cache::Object;
46 use Koha::Config;
48 use base qw(Class::Accessor);
50 __PACKAGE__->mk_ro_accessors(
51 qw( cache memcached_cache fastmmap_cache memory_cache ));
53 our %L1_cache;
54 our $L1_encoder = Sereal::Encoder->new;
55 our $L1_decoder = Sereal::Decoder->new;
57 =head2 get_instance
59 my $cache = Koha::Caches->get_instance();
61 This gets a shared instance of the cache, set up in a very default way. This is
62 the recommended way to fetch a cache object. If possible, it'll be
63 persistent across multiple instances.
65 =cut
67 =head2 new
69 Create a new Koha::Cache object. This is required for all cache-related functionality.
71 =cut
73 sub new {
74 my ( $class, $self, $params ) = @_;
75 $self->{'default_type'} =
76 $self->{cache_type}
77 || $ENV{CACHING_SYSTEM} # DELME What about this?
78 || 'memcached';
80 my $subnamespace = $params->{subnamespace} // '';
82 $ENV{DEBUG} && carp "Default caching system: $self->{'default_type'}";
84 $self->{'timeout'} ||= 0;
85 # Should we continue to support MEMCACHED ENV vars?
86 $self->{'namespace'} ||= $ENV{MEMCACHED_NAMESPACE};
87 my @servers = split /,/, $ENV{MEMCACHED_SERVERS} || '';
88 unless ( $self->{namespace} and @servers ) {
89 my $koha_config = Koha::Config->read_from_file( Koha::Config->guess_koha_conf() );
90 $self->{namespace} ||= $koha_config->{config}{memcached_namespace} || 'koha';
91 @servers = split /,/, $koha_config->{config}{memcached_servers} // ''
92 unless @servers;
94 $self->{namespace} .= ":$subnamespace:";
96 if ( $self->{'default_type'} eq 'memcached'
97 && can_load( modules => { 'Cache::Memcached::Fast' => undef } )
98 && _initialize_memcached($self, @servers)
99 && defined( $self->{'memcached_cache'} ) )
101 $self->{'cache'} = $self->{'memcached_cache'};
104 if ( $self->{'default_type'} eq 'fastmmap'
105 && defined( $ENV{GATEWAY_INTERFACE} )
106 && can_load( modules => { 'Cache::FastMmap' => undef } )
107 && _initialize_fastmmap($self)
108 && defined( $self->{'fastmmap_cache'} ) )
110 $self->{'cache'} = $self->{'fastmmap_cache'};
113 # Unless memcache or fastmmap has already been picked, use memory_cache
114 unless ( defined( $self->{'cache'} ) ) {
115 if ( can_load( modules => { 'Cache::Memory' => undef } )
116 && _initialize_memory($self) )
118 $self->{'cache'} = $self->{'memory_cache'};
122 $ENV{DEBUG} && carp "Selected caching system: " . ($self->{'cache'} // 'none');
124 return
125 bless $self,
126 $class;
129 sub _initialize_memcached {
130 my ($self, @servers) = @_;
132 return unless @servers;
134 $ENV{DEBUG}
135 && carp "Memcached server settings: "
136 . join( ', ', @servers )
137 . " with "
138 . $self->{'namespace'};
139 # Cache::Memcached::Fast doesn't allow a default expire time to be set
140 # so we force it on setting.
141 my $memcached = Cache::Memcached::Fast->new(
143 servers => \@servers,
144 compress_threshold => 10_000,
145 namespace => $self->{'namespace'},
146 utf8 => 1,
149 # Ensure we can actually talk to the memcached server
150 my $ismemcached = $memcached->set('ismemcached','1');
151 return $self unless $ismemcached;
152 $self->{'memcached_cache'} = $memcached;
153 return $self;
156 sub _initialize_fastmmap {
157 my ($self) = @_;
158 my ($cache, $share_file);
160 # Temporary workaround to catch fatal errors when: C4::Context module
161 # is not loaded beforehand, or Cache::FastMmap init fails for whatever
162 # other reason (e.g. due to permission issues - see Bug 13431)
163 eval {
164 $share_file = join( '-',
165 "/tmp/sharefile-koha", $self->{'namespace'},
166 C4::Context->config('hostname'), C4::Context->config('database') );
168 $cache = Cache::FastMmap->new(
169 'share_file' => $share_file,
170 'expire_time' => $self->{'timeout'},
171 'unlink_on_exit' => 0,
174 if ( $@ ) {
175 warn "FastMmap cache initialization failed: $@";
176 return;
178 return unless defined $cache;
179 $self->{'fastmmap_cache'} = $cache;
180 return $self;
183 sub _initialize_memory {
184 my ($self) = @_;
186 # Default cache time for memory is _always_ short unless it's specially
187 # defined, to allow it to work reliably in a persistent environment.
188 my $cache = Cache::Memory->new(
189 'namespace' => $self->{'namespace'},
190 'default_expires' => "$self->{'timeout'} sec" || "10 sec",
192 $self->{'memory_cache'} = $cache;
193 # Memory cache can't handle complex types for some reason, so we use its
194 # freeze and thaw functions.
195 $self->{ref($cache) . '_set'} = sub {
196 my ($key, $val, $exp) = @_;
197 # Refer to set_expiry in Cache::Entry for why we do this 'sec' thing.
198 $exp = "$exp sec" if defined $exp;
199 # Because we need to use freeze, it must be a reference type.
200 $cache->freeze($key, [$val], $exp);
202 $self->{ref($cache) . '_get'} = sub {
203 my $res = $cache->thaw(shift);
204 return unless defined $res;
205 return $res->[0];
207 return $self;
210 =head2 is_cache_active
212 Routine that checks whether or not a default caching method is active on this
213 object.
215 =cut
217 sub is_cache_active {
218 my $self = shift;
219 return $self->{'cache'} ? 1 : 0;
222 =head2 set_in_cache
224 $cache->set_in_cache($key, $value, [$options]);
226 Save a value to the specified key in the cache. A hashref of options may be
227 specified.
229 The possible options are:
231 =over
233 =item expiry
235 Expiry time of this cached entry in seconds.
237 =item cache
239 The cache object to use if you want to provide your own. It should be an
240 instance of C<Cache::*> and follow the same interface as L<Cache::Memcache>.
242 =back
244 =cut
246 sub set_in_cache {
247 my ( $self, $key, $value, $options ) = @_;
249 my $unsafe = $options->{unsafe} || 0;
251 # the key mustn't contain whitespace (or control characters) for memcache
252 # but shouldn't be any harm in applying it globally.
253 $key =~ s/[\x00-\x20]/_/g;
255 my $cache = $options->{cache} || 'cache';
256 croak "No key" unless $key;
257 $ENV{DEBUG} && carp "set_in_cache for $key";
259 return unless ( $self->{$cache} && ref( $self->{$cache} ) =~ m/^Cache::/ );
260 my $expiry = $options->{expiry};
261 $expiry //= $self->{timeout};
262 my $set_sub = $self->{ref($self->{$cache}) . "_set"};
264 my $flag = '-CF0'; # 0: scalar, 1: frozen data structure
265 if (ref($value)) {
266 # Set in L1 cache as a data structure
267 # We only save the frozen form: we do want to save $value in L1
268 # directly in order to protect it. And thawing now may not be
269 # needed, so improves performance.
270 $value = $L1_encoder->encode($value);
271 $L1_cache{$self->{namespace}}{$key}->{frozen} = $value;
272 $flag = '-CF1';
273 } else {
274 # Set in L1 cache as a scalar; exit if we are caching an undef
275 $L1_cache{$self->{namespace}}{$key} = $value;
276 return if !defined $value;
279 $value .= $flag;
280 # We consider an expiry of 0 to be infinite
281 if ( $expiry ) {
282 return $set_sub
283 ? $set_sub->( $key, $value, $expiry )
284 : $self->{$cache}->set( $key, $value, $expiry );
286 else {
287 return $set_sub
288 ? $set_sub->( $key, $value )
289 : $self->{$cache}->set( $key, $value );
293 =head2 get_from_cache
295 my $value = $cache->get_from_cache($key, [ $options ]);
297 Retrieve the value stored under the specified key in the cache.
299 The possible options are:
301 =over
303 =item unsafe
305 If set, this will avoid performing a deep copy of the item. This
306 means that it won't be safe if something later modifies the result of the
307 function. It should be used with caution, and could save processing time
308 in some situations where is safe to use it. Make sure you know what you are doing!
310 =item cache
312 The cache object to use if you want to provide your own. It should be an
313 instance of C<Cache::*> and follow the same interface as L<Cache::Memcache>.
315 =back
317 =cut
319 sub get_from_cache {
320 my ( $self, $key, $options ) = @_;
321 my $cache = $options->{cache} || 'cache';
322 my $unsafe = $options->{unsafe} || 0;
323 $key =~ s/[\x00-\x20]/_/g;
324 croak "No key" unless $key;
325 $ENV{DEBUG} && carp "get_from_cache for $key";
326 return unless ( $self->{$cache} && ref( $self->{$cache} ) =~ m/^Cache::/ );
328 # Return L1 cache value if exists
329 if ( exists $L1_cache{$self->{namespace}}{$key} ) {
330 if (ref($L1_cache{$self->{namespace}}{$key})) {
331 if ($unsafe) {
332 # ONLY use thawed for unsafe calls !!!
333 $L1_cache{$self->{namespace}}{$key}->{thawed} ||= $L1_decoder->decode($L1_cache{$self->{namespace}}{$key}->{frozen});
334 return $L1_cache{$self->{namespace}}{$key}->{thawed};
335 } else {
336 return $L1_decoder->decode($L1_cache{$self->{namespace}}{$key}->{frozen});
338 } else {
339 # No need to thaw if it's a scalar
340 return $L1_cache{$self->{namespace}}{$key};
344 my $get_sub = $self->{ref($self->{$cache}) . "_get"};
345 my $L2_value = $get_sub ? $get_sub->($key) : $self->{$cache}->get($key);
347 return if ref($L2_value);
348 return unless (defined($L2_value) && length($L2_value) >= 4);
350 my $flag = substr($L2_value, -4, 4, '');
351 if ($flag eq '-CF0') {
352 # it's a scalar
353 $L1_cache{$self->{namespace}}{$key} = $L2_value;
354 return $L2_value;
355 } elsif ($flag eq '-CF1') {
356 # it's a frozen data structure
357 my $thawed;
358 eval { $thawed = $L1_decoder->decode($L2_value); };
359 return if $@;
360 $L1_cache{$self->{namespace}}{$key}->{frozen} = $L2_value;
361 # ONLY save thawed for unsafe calls !!!
362 $L1_cache{$self->{namespace}}{$key}->{thawed} = $thawed if $unsafe;
363 return $thawed;
366 # Unknown value / data type returned from L2 cache
367 return;
370 =head2 clear_from_cache
372 $cache->clear_from_cache($key);
374 Remove the value identified by the specified key from the default cache.
376 =cut
378 sub clear_from_cache {
379 my ( $self, $key, $cache ) = @_;
380 $key =~ s/[\x00-\x20]/_/g;
381 $cache ||= 'cache';
382 croak "No key" unless $key;
383 return unless ( $self->{$cache} && ref( $self->{$cache} ) =~ m/^Cache::/ );
385 # Clear from L1 cache
386 delete $L1_cache{$self->{namespace}}{$key};
388 return $self->{$cache}->delete($key)
389 if ( ref( $self->{$cache} ) =~ m'^Cache::Memcached' );
390 return $self->{$cache}->remove($key);
393 =head2 flush_all
395 $cache->flush_all();
397 Clear the entire default cache.
399 =cut
401 sub flush_all {
402 my ( $self, $cache ) = shift;
403 $cache ||= 'cache';
404 return unless ( $self->{$cache} && ref( $self->{$cache} ) =~ m/^Cache::/ );
406 $self->flush_L1_cache();
408 return $self->{$cache}->flush_all()
409 if ( ref( $self->{$cache} ) =~ m'^Cache::Memcached' );
410 return $self->{$cache}->clear();
413 sub flush_L1_cache {
414 my( $self ) = @_;
415 delete $L1_cache{$self->{namespace}};
418 =head1 TIED INTERFACE
420 Koha::Cache also provides a tied interface which enables users to provide a
421 constructor closure and (after creation) treat cached data like normal reference
422 variables and rely on the cache Just Working and getting updated when it
423 expires, etc.
425 my $cache = Koha::Cache->new();
426 my $data = 'whatever';
427 my $scalar = Koha::Cache->create_scalar(
429 'key' => 'whatever',
430 'timeout' => 2,
431 'constructor' => sub { return $data; },
434 print "$$scalar\n"; # Prints "whatever"
435 $data = 'somethingelse';
436 print "$$scalar\n"; # Prints "whatever" because it is cached
437 sleep 2; # Wait until the cache entry has expired
438 print "$$scalar\n"; # Prints "somethingelse"
440 my $hash = Koha::Cache->create_hash(
442 'key' => 'whatever',
443 'timeout' => 2,
444 'constructor' => sub { return $data; },
447 print "$$variable\n"; # Prints "whatever"
449 The gotcha with this interface, of course, is that the variable returned by
450 create_scalar and create_hash is a I<reference> to a tied variable and not a
451 tied variable itself.
453 The tied variable is configured by means of a hashref passed in to the
454 create_scalar and create_hash methods. The following parameters are supported:
456 =over
458 =item I<key>
460 Required. The key to use for identifying the variable in the cache.
462 =item I<constructor>
464 Required. A closure (or reference to a function) that will return the value that
465 needs to be stored in the cache.
467 =item I<preload>
469 Optional. A closure (or reference to a function) that gets run to initialize
470 the cache when creating the tied variable.
472 =item I<arguments>
474 Optional. Array reference with the arguments that should be passed to the
475 constructor function.
477 =item I<timeout>
479 Optional. The cache timeout in seconds for the variable. Defaults to 600
480 (ten minutes).
482 =item I<cache_type>
484 Optional. Which type of cache to use for the variable. Defaults to whatever is
485 set in the environment variable CACHING_SYSTEM. If set to 'null', disables
486 caching for the tied variable.
488 =item I<allowupdate>
490 Optional. Boolean flag to allow the variable to be updated directly. When this
491 is set and the variable is used as an l-value, the cache will be updated
492 immediately with the new value. Using this is probably a bad idea on a
493 multi-threaded system. When I<allowupdate> is not set to true, using the
494 tied variable as an l-value will have no effect.
496 =item I<destructor>
498 Optional. A closure (or reference to a function) that should be called when the
499 tied variable is destroyed.
501 =item I<unset>
503 Optional. Boolean flag to tell the object to remove the variable from the cache
504 when it is destroyed or goes out of scope.
506 =item I<inprocess>
508 Optional. Boolean flag to tell the object not to refresh the variable from the
509 cache every time the value is desired, but rather only when the I<local> copy
510 of the variable is older than the timeout.
512 =back
514 =head2 create_scalar
516 my $scalar = Koha::Cache->create_scalar(\%params);
518 Create scalar tied to the cache.
520 =cut
522 sub create_scalar {
523 my ( $self, $args ) = @_;
525 $self->_set_tied_defaults($args);
527 tie my $scalar, 'Koha::Cache::Object', $args;
528 return \$scalar;
531 sub create_hash {
532 my ( $self, $args ) = @_;
534 $self->_set_tied_defaults($args);
536 tie my %hash, 'Koha::Cache::Object', $args;
537 return \%hash;
540 sub _set_tied_defaults {
541 my ( $self, $args ) = @_;
543 $args->{'timeout'} = '600' unless defined( $args->{'timeout'} );
544 $args->{'inprocess'} = '0' unless defined( $args->{'inprocess'} );
545 unless ( $args->{cache_type} and lc( $args->{cache_type} ) eq 'null' ) {
546 $args->{'cache'} = $self;
547 $args->{'cache_type'} ||= $ENV{'CACHING_SYSTEM'};
550 return $args;
553 =head1 EXPORT
555 None by default.
557 =head1 SEE ALSO
559 Koha::Cache::Object
561 =head1 AUTHOR
563 Chris Cormack, E<lt>chris@bigballofwax.co.nzE<gt>
564 Paul Poulain, E<lt>paul.poulain@biblibre.comE<gt>
565 Jared Camins-Esakov, E<lt>jcamins@cpbibliography.comE<gt>
567 =cut
571 __END__