9598807ed1e30df3e6a25d7fb47bf48462f55fde
[Packages/TYPO3.CMS.git] / typo3 / sysext / core / Classes / Cache / Backend / RedisBackend.php
1 <?php
2 namespace TYPO3\CMS\Core\Cache\Backend;
3
4 /*
5 * This file is part of the TYPO3 CMS project.
6 *
7 * It is free software; you can redistribute it and/or modify it under
8 * the terms of the GNU General Public License, either version 2
9 * of the License, or any later version.
10 *
11 * For the full copyright and license information, please read the
12 * LICENSE.txt file that was distributed with this source code.
13 *
14 * The TYPO3 project - inspiring people to share!
15 */
16
17 use TYPO3\CMS\Core\Utility\StringUtility;
18
19 /**
20 * A caching backend which stores cache entries by using Redis with phpredis
21 * PHP module. Redis is a noSQL database with very good scaling characteristics
22 * in proportion to the amount of entries and data size.
23 *
24 * @see http://code.google.com/p/redis/
25 * @see http://github.com/owlient/phpredis
26 * @api
27 */
28 class RedisBackend extends AbstractBackend implements TaggableBackendInterface
29 {
30 /**
31 * Faked unlimited lifetime = 31536000 (1 Year).
32 * In redis an entry does not have a lifetime by default (it's not "volatile").
33 * Entries can be made volatile either with EXPIRE after it has been SET,
34 * or with SETEX, which is a combined SET and EXPIRE command.
35 * But an entry can not be made "unvolatile" again. To set a volatile entry to
36 * not volatile again, it must be DELeted and SET without a following EXPIRE.
37 * To save these additional calls on every set(),
38 * we just make every entry volatile and treat a high number as "unlimited"
39 *
40 * @see http://code.google.com/p/redis/wiki/ExpireCommand
41 * @var int Faked unlimited lifetime
42 */
43 const FAKED_UNLIMITED_LIFETIME = 31536000;
44 /**
45 * Key prefix for identifier->data entries
46 *
47 * @var string
48 */
49 const IDENTIFIER_DATA_PREFIX = 'identData:';
50 /**
51 * Key prefix for identifier->tags sets
52 *
53 * @var string
54 */
55 const IDENTIFIER_TAGS_PREFIX = 'identTags:';
56 /**
57 * Key prefix for tag->identifiers sets
58 *
59 * @var string
60 */
61 const TAG_IDENTIFIERS_PREFIX = 'tagIdents:';
62 /**
63 * Instance of the PHP redis class
64 *
65 * @var \Redis
66 */
67 protected $redis;
68
69 /**
70 * Indicates whether the server is connected
71 *
72 * @var bool
73 */
74 protected $connected = false;
75
76 /**
77 * Persistent connection
78 *
79 * @var bool
80 */
81 protected $persistentConnection = false;
82
83 /**
84 * Hostname / IP of the Redis server, defaults to 127.0.0.1.
85 *
86 * @var string
87 */
88 protected $hostname = '127.0.0.1';
89
90 /**
91 * Port of the Redis server, defaults to 6379
92 *
93 * @var int
94 */
95 protected $port = 6379;
96
97 /**
98 * Number of selected database, defaults to 0
99 *
100 * @var int
101 */
102 protected $database = 0;
103
104 /**
105 * Password for redis authentication
106 *
107 * @var string
108 */
109 protected $password = '';
110
111 /**
112 * Indicates whether data is compressed or not (requires php zlib)
113 *
114 * @var bool
115 */
116 protected $compression = false;
117
118 /**
119 * -1 to 9, indicates zlib compression level: -1 = default level 6, 0 = no compression, 9 maximum compression
120 *
121 * @var int
122 */
123 protected $compressionLevel = -1;
124
125 /**
126 * limit in seconds (default is 0 meaning unlimited)
127 *
128 * @var int
129 */
130 protected $connectionTimeout = 0;
131
132 /**
133 * Construct this backend
134 *
135 * @param string $context Unused, for backward compatibility only
136 * @param array $options Configuration options
137 * @throws \TYPO3\CMS\Core\Cache\Exception if php redis module is not loaded
138 */
139 public function __construct($context, array $options = [])
140 {
141 if (!extension_loaded('redis')) {
142 throw new \TYPO3\CMS\Core\Cache\Exception('The PHP extension "redis" must be installed and loaded in order to use the redis backend.', 1279462933);
143 }
144 parent::__construct($context, $options);
145 }
146
147 /**
148 * Initializes the redis backend
149 *
150 * @throws \TYPO3\CMS\Core\Cache\Exception if access to redis with password is denied or if database selection fails
151 */
152 public function initializeObject()
153 {
154 $this->redis = new \Redis();
155 try {
156 if ($this->persistentConnection) {
157 $this->connected = $this->redis->pconnect($this->hostname, $this->port, $this->connectionTimeout);
158 } else {
159 $this->connected = $this->redis->connect($this->hostname, $this->port, $this->connectionTimeout);
160 }
161 } catch (\Exception $e) {
162 $this->logger->alert('Could not connect to redis server.', ['exception' => $e]);
163 }
164 if ($this->connected) {
165 if ($this->password !== '') {
166 $success = $this->redis->auth($this->password);
167 if (!$success) {
168 throw new \TYPO3\CMS\Core\Cache\Exception('The given password was not accepted by the redis server.', 1279765134);
169 }
170 }
171 if ($this->database >= 0) {
172 $success = $this->redis->select($this->database);
173 if (!$success) {
174 throw new \TYPO3\CMS\Core\Cache\Exception('The given database "' . $this->database . '" could not be selected.', 1279765144);
175 }
176 }
177 }
178 }
179
180 /**
181 * Setter for persistent connection
182 *
183 * @param bool $persistentConnection
184 * @api
185 */
186 public function setPersistentConnection($persistentConnection)
187 {
188 $this->persistentConnection = $persistentConnection;
189 }
190
191 /**
192 * Setter for server hostname
193 *
194 * @param string $hostname Hostname
195 * @api
196 */
197 public function setHostname($hostname)
198 {
199 $this->hostname = $hostname;
200 }
201
202 /**
203 * Setter for server port
204 *
205 * @param int $port Port
206 * @api
207 */
208 public function setPort($port)
209 {
210 $this->port = $port;
211 }
212
213 /**
214 * Setter for database number
215 *
216 * @param int $database Database
217 * @throws \InvalidArgumentException if database number is not valid
218 * @api
219 */
220 public function setDatabase($database)
221 {
222 if (!is_int($database)) {
223 throw new \InvalidArgumentException('The specified database number is of type "' . gettype($database) . '" but an integer is expected.', 1279763057);
224 }
225 if ($database < 0) {
226 throw new \InvalidArgumentException('The specified database "' . $database . '" must be greater or equal than zero.', 1279763534);
227 }
228 $this->database = $database;
229 }
230
231 /**
232 * Setter for authentication password
233 *
234 * @param string $password Password
235 * @api
236 */
237 public function setPassword($password)
238 {
239 $this->password = $password;
240 }
241
242 /**
243 * Enable data compression
244 *
245 * @param bool $compression TRUE to enable compression
246 * @throws \InvalidArgumentException if compression parameter is not of type boolean
247 * @api
248 */
249 public function setCompression($compression)
250 {
251 if (!is_bool($compression)) {
252 throw new \InvalidArgumentException('The specified compression of type "' . gettype($compression) . '" but a boolean is expected.', 1289679153);
253 }
254 $this->compression = $compression;
255 }
256
257 /**
258 * Set data compression level.
259 * If compression is enabled and this is not set,
260 * gzcompress default level will be used.
261 *
262 * @param int $compressionLevel -1 to 9: Compression level
263 * @throws \InvalidArgumentException if compressionLevel parameter is not within allowed bounds
264 * @api
265 */
266 public function setCompressionLevel($compressionLevel)
267 {
268 if (!is_int($compressionLevel)) {
269 throw new \InvalidArgumentException('The specified compression of type "' . gettype($compressionLevel) . '" but an integer is expected.', 1289679154);
270 }
271 if ($compressionLevel >= -1 && $compressionLevel <= 9) {
272 $this->compressionLevel = $compressionLevel;
273 } else {
274 throw new \InvalidArgumentException('The specified compression level must be an integer between -1 and 9.', 1289679155);
275 }
276 }
277
278 /**
279 * Set connection timeout.
280 * This value in seconds is used as a maximum number
281 * of seconds to wait if a connection can be established.
282 *
283 * @param int $connectionTimeout limit in seconds, a value greater or equal than 0
284 * @throws \InvalidArgumentException if compressionLevel parameter is not within allowed bounds
285 * @api
286 */
287 public function setConnectionTimeout($connectionTimeout)
288 {
289 if (!is_int($connectionTimeout)) {
290 throw new \InvalidArgumentException('The specified connection timeout is of type "' . gettype($connectionTimeout) . '" but an integer is expected.', 1487849315);
291 }
292
293 if ($connectionTimeout < 0) {
294 throw new \InvalidArgumentException('The specified connection timeout "' . $connectionTimeout . '" must be greater or equal than zero.', 1487849326);
295 }
296
297 $this->connectionTimeout = $connectionTimeout;
298 }
299
300 /**
301 * Save data in the cache
302 *
303 * Scales O(1) with number of cache entries
304 * Scales O(n) with number of tags
305 *
306 * @param string $entryIdentifier Identifier for this specific cache entry
307 * @param string $data Data to be stored
308 * @param array $tags Tags to associate with this cache entry
309 * @param int $lifetime Lifetime of this cache entry in seconds. If NULL is specified, default lifetime is used. "0" means unlimited lifetime.
310 * @throws \InvalidArgumentException if identifier is not valid
311 * @throws \TYPO3\CMS\Core\Cache\Exception\InvalidDataException if data is not a string
312 * @api
313 */
314 public function set($entryIdentifier, $data, array $tags = [], $lifetime = null)
315 {
316 if (!$this->canBeUsedInStringContext($entryIdentifier)) {
317 throw new \InvalidArgumentException('The specified identifier is of type "' . gettype($entryIdentifier) . '" which can\'t be converted to string.', 1377006651);
318 }
319 if (!is_string($data)) {
320 throw new \TYPO3\CMS\Core\Cache\Exception\InvalidDataException('The specified data is of type "' . gettype($data) . '" but a string is expected.', 1279469941);
321 }
322 $lifetime = $lifetime ?? $this->defaultLifetime;
323 if (!is_int($lifetime)) {
324 throw new \InvalidArgumentException('The specified lifetime is of type "' . gettype($lifetime) . '" but an integer or NULL is expected.', 1279488008);
325 }
326 if ($lifetime < 0) {
327 throw new \InvalidArgumentException('The specified lifetime "' . $lifetime . '" must be greater or equal than zero.', 1279487573);
328 }
329 if ($this->connected) {
330 $expiration = $lifetime === 0 ? self::FAKED_UNLIMITED_LIFETIME : $lifetime;
331 if ($this->compression) {
332 $data = gzcompress($data, $this->compressionLevel);
333 }
334 $this->redis->setex(self::IDENTIFIER_DATA_PREFIX . $entryIdentifier, $expiration, $data);
335 $addTags = $tags;
336 $removeTags = [];
337 $existingTags = $this->redis->sMembers(self::IDENTIFIER_TAGS_PREFIX . $entryIdentifier);
338 if (!empty($existingTags)) {
339 $addTags = array_diff($tags, $existingTags);
340 $removeTags = array_diff($existingTags, $tags);
341 }
342 if (!empty($removeTags) || !empty($addTags)) {
343 $queue = $this->redis->multi(\Redis::PIPELINE);
344 foreach ($removeTags as $tag) {
345 $queue->sRemove(self::IDENTIFIER_TAGS_PREFIX . $entryIdentifier, $tag);
346 $queue->sRemove(self::TAG_IDENTIFIERS_PREFIX . $tag, $entryIdentifier);
347 }
348 foreach ($addTags as $tag) {
349 $queue->sAdd(self::IDENTIFIER_TAGS_PREFIX . $entryIdentifier, $tag);
350 $queue->sAdd(self::TAG_IDENTIFIERS_PREFIX . $tag, $entryIdentifier);
351 }
352 $queue->exec();
353 }
354 }
355 }
356
357 /**
358 * Loads data from the cache.
359 *
360 * Scales O(1) with number of cache entries
361 *
362 * @param string $entryIdentifier An identifier which describes the cache entry to load
363 * @return mixed The cache entry's content as a string or FALSE if the cache entry could not be loaded
364 * @throws \InvalidArgumentException if identifier is not a string
365 * @api
366 */
367 public function get($entryIdentifier)
368 {
369 if (!$this->canBeUsedInStringContext($entryIdentifier)) {
370 throw new \InvalidArgumentException('The specified identifier is of type "' . gettype($entryIdentifier) . '" which can\'t be converted to string.', 1377006652);
371 }
372 $storedEntry = false;
373 if ($this->connected) {
374 $storedEntry = $this->redis->get(self::IDENTIFIER_DATA_PREFIX . $entryIdentifier);
375 }
376 if ($this->compression && (string)$storedEntry !== '') {
377 $storedEntry = gzuncompress($storedEntry);
378 }
379 return $storedEntry;
380 }
381
382 /**
383 * Checks if a cache entry with the specified identifier exists.
384 *
385 * Scales O(1) with number of cache entries
386 *
387 * @param string $entryIdentifier Identifier specifying the cache entry
388 * @return bool TRUE if such an entry exists, FALSE if not
389 * @throws \InvalidArgumentException if identifier is not a string
390 * @api
391 */
392 public function has($entryIdentifier)
393 {
394 if (!$this->canBeUsedInStringContext($entryIdentifier)) {
395 throw new \InvalidArgumentException('The specified identifier is of type "' . gettype($entryIdentifier) . '" which can\'t be converted to string.', 1377006653);
396 }
397 return $this->connected && $this->redis->exists(self::IDENTIFIER_DATA_PREFIX . $entryIdentifier);
398 }
399
400 /**
401 * Removes all cache entries matching the specified identifier.
402 *
403 * Scales O(1) with number of cache entries
404 * Scales O(n) with number of tags
405 *
406 * @param string $entryIdentifier Specifies the cache entry to remove
407 * @return bool TRUE if (at least) an entry could be removed or FALSE if no entry was found
408 * @throws \InvalidArgumentException if identifier is not a string
409 * @api
410 */
411 public function remove($entryIdentifier)
412 {
413 if (!$this->canBeUsedInStringContext($entryIdentifier)) {
414 throw new \InvalidArgumentException('The specified identifier is of type "' . gettype($entryIdentifier) . '" which can\'t be converted to string.', 1377006654);
415 }
416 $elementsDeleted = false;
417 if ($this->connected) {
418 if ($this->redis->exists(self::IDENTIFIER_DATA_PREFIX . $entryIdentifier)) {
419 $assignedTags = $this->redis->sMembers(self::IDENTIFIER_TAGS_PREFIX . $entryIdentifier);
420 $queue = $this->redis->multi(\Redis::PIPELINE);
421 foreach ($assignedTags as $tag) {
422 $queue->sRemove(self::TAG_IDENTIFIERS_PREFIX . $tag, $entryIdentifier);
423 }
424 $queue->delete(self::IDENTIFIER_DATA_PREFIX . $entryIdentifier, self::IDENTIFIER_TAGS_PREFIX . $entryIdentifier);
425 $queue->exec();
426 $elementsDeleted = true;
427 }
428 }
429 return $elementsDeleted;
430 }
431
432 /**
433 * Finds and returns all cache entry identifiers which are tagged by the
434 * specified tag.
435 *
436 * Scales O(1) with number of cache entries
437 * Scales O(n) with number of tag entries
438 *
439 * @param string $tag The tag to search for
440 * @return array An array of entries with all matching entries. An empty array if no entries matched
441 * @throws \InvalidArgumentException if tag is not a string
442 * @api
443 */
444 public function findIdentifiersByTag($tag)
445 {
446 if (!$this->canBeUsedInStringContext($tag)) {
447 throw new \InvalidArgumentException('The specified tag is of type "' . gettype($tag) . '" which can\'t be converted to string.', 1377006655);
448 }
449 $foundIdentifiers = [];
450 if ($this->connected) {
451 $foundIdentifiers = $this->redis->sMembers(self::TAG_IDENTIFIERS_PREFIX . $tag);
452 }
453 return $foundIdentifiers;
454 }
455
456 /**
457 * Removes all cache entries of this cache.
458 *
459 * Scales O(1) with number of cache entries
460 *
461 * @api
462 */
463 public function flush()
464 {
465 if ($this->connected) {
466 $this->redis->flushDB();
467 }
468 }
469
470 /**
471 * Removes all cache entries of this cache which are tagged with the specified tag.
472 *
473 * Scales O(1) with number of cache entries
474 * Scales O(n^2) with number of tag entries
475 *
476 * @param string $tag Tag the entries must have
477 * @throws \InvalidArgumentException if identifier is not a string
478 * @api
479 */
480 public function flushByTag($tag)
481 {
482 if (!$this->canBeUsedInStringContext($tag)) {
483 throw new \InvalidArgumentException('The specified tag is of type "' . gettype($tag) . '" which can\'t be converted to string.', 1377006656);
484 }
485 if ($this->connected) {
486 $identifiers = $this->redis->sMembers(self::TAG_IDENTIFIERS_PREFIX . $tag);
487 if (!empty($identifiers)) {
488 $this->removeIdentifierEntriesAndRelations($identifiers, [$tag]);
489 }
490 }
491 }
492
493 /**
494 * With the current internal structure, only the identifier to data entries
495 * have a redis internal lifetime. If an entry expires, attached
496 * identifier to tags and tag to identifiers entries will be left over.
497 * This methods finds those entries and cleans them up.
498 *
499 * Scales O(n*m) with number of cache entries (n) and number of tags (m)
500 *
501 * @api
502 */
503 public function collectGarbage()
504 {
505 $identifierToTagsKeys = $this->redis->getKeys(self::IDENTIFIER_TAGS_PREFIX . '*');
506 foreach ($identifierToTagsKeys as $identifierToTagsKey) {
507 list(, $identifier) = explode(':', $identifierToTagsKey);
508 // Check if the data entry still exists
509 if (!$this->redis->exists(self::IDENTIFIER_DATA_PREFIX . $identifier)) {
510 $tagsToRemoveIdentifierFrom = $this->redis->sMembers($identifierToTagsKey);
511 $queue = $this->redis->multi(\Redis::PIPELINE);
512 $queue->delete($identifierToTagsKey);
513 foreach ($tagsToRemoveIdentifierFrom as $tag) {
514 $queue->sRemove(self::TAG_IDENTIFIERS_PREFIX . $tag, $identifier);
515 }
516 $queue->exec();
517 }
518 }
519 }
520
521 /**
522 * Helper method for flushByTag()
523 * Gets list of identifiers and tags and removes all relations of those tags
524 *
525 * Scales O(1) with number of cache entries
526 * Scales O(n^2) with number of tags
527 *
528 * @param array $identifiers List of identifiers to remove
529 * @param array $tags List of tags to be handled
530 */
531 protected function removeIdentifierEntriesAndRelations(array $identifiers, array $tags)
532 {
533 // Set a temporary entry which holds all identifiers that need to be removed from
534 // the tag to identifiers sets
535 $uniqueTempKey = 'temp:' . StringUtility::getUniqueId();
536 $prefixedKeysToDelete = [$uniqueTempKey];
537 $prefixedIdentifierToTagsKeysToDelete = [];
538 foreach ($identifiers as $identifier) {
539 $prefixedKeysToDelete[] = self::IDENTIFIER_DATA_PREFIX . $identifier;
540 $prefixedIdentifierToTagsKeysToDelete[] = self::IDENTIFIER_TAGS_PREFIX . $identifier;
541 }
542 foreach ($tags as $tag) {
543 $prefixedKeysToDelete[] = self::TAG_IDENTIFIERS_PREFIX . $tag;
544 }
545 $tagToIdentifiersSetsToRemoveIdentifiersFrom = $this->redis->sUnion($prefixedIdentifierToTagsKeysToDelete);
546 // Remove the tag to identifier set of the given tags, they will be removed anyway
547 $tagToIdentifiersSetsToRemoveIdentifiersFrom = array_diff($tagToIdentifiersSetsToRemoveIdentifiersFrom, $tags);
548 // Diff all identifiers that must be removed from tag to identifiers sets off from a
549 // tag to identifiers set and store result in same tag to identifiers set again
550 $queue = $this->redis->multi(\Redis::PIPELINE);
551 foreach ($identifiers as $identifier) {
552 $queue->sAdd($uniqueTempKey, $identifier);
553 }
554 foreach ($tagToIdentifiersSetsToRemoveIdentifiersFrom as $tagToIdentifiersSet) {
555 $queue->sDiffStore(self::TAG_IDENTIFIERS_PREFIX . $tagToIdentifiersSet, self::TAG_IDENTIFIERS_PREFIX . $tagToIdentifiersSet, $uniqueTempKey);
556 }
557 $queue->delete(array_merge($prefixedKeysToDelete, $prefixedIdentifierToTagsKeysToDelete));
558 $queue->exec();
559 }
560
561 /**
562 * Helper method to catch invalid identifiers and tags
563 *
564 * @param mixed $variable Variable to be checked
565 * @return bool
566 */
567 protected function canBeUsedInStringContext($variable)
568 {
569 return is_scalar($variable) || (is_object($variable) && method_exists($variable, '__toString'));
570 }
571 }