-
Notifications
You must be signed in to change notification settings - Fork 639
/
MemcachedBackend.php
465 lines (431 loc) · 16 KB
/
MemcachedBackend.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
<?php
namespace TYPO3\CMS\Core\Cache\Backend;
/*
* This file is part of the TYPO3 CMS project.
*
* It is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, either version 2
* of the License, or any later version.
*
* For the full copyright and license information, please read the
* LICENSE.txt file that was distributed with this source code.
*
* The TYPO3 project - inspiring people to share!
*/
use TYPO3\CMS\Core\Cache\Exception;
use TYPO3\CMS\Core\Cache\Frontend\FrontendInterface;
/**
* A caching backend which stores cache entries by using Memcached.
*
* This backend uses the following types of Memcache keys:
* - tag_xxx
* xxx is tag name, value is array of associated identifiers identifier. This
* is "forward" tag index. It is mainly used for obtaining content by tag
* (get identifier by tag -> get content by identifier)
* - ident_xxx
* xxx is identifier, value is array of associated tags. This is "reverse" tag
* index. It provides quick access for all tags associated with this identifier
* and used when removing the identifier
*
* Each key is prepended with a prefix. By default prefix consists from two parts
* separated by underscore character and ends in yet another underscore character:
* - "TYPO3"
* - Current site path obtained from the PATH_site constant
* This prefix makes sure that keys from the different installations do not
* conflict.
*
* Note: When using the Memcached backend to store values of more than ~1 MB,
* the data will be split into chunks to make them fit into the memcached limits.
*
* @api
*/
class MemcachedBackend extends AbstractBackend implements TaggableBackendInterface, TransientBackendInterface
{
/**
* Max bucket size, (1024*1024)-42 bytes
*
* @var int
*/
const MAX_BUCKET_SIZE = 1048534;
/**
* Instance of the PHP Memcache class
*
* @var \Memcache|\Memcached
*/
protected $memcache;
/**
* Used PECL module for memcached
*
* @var string
*/
protected $usedPeclModule = '';
/**
* Array of Memcache server configurations
*
* @var array
*/
protected $servers = [];
/**
* Indicates whether the memcache uses compression or not (requires zlib),
* either 0 or \Memcached::OPT_COMPRESSION / MEMCACHE_COMPRESSED
*
* @var int
*/
protected $flags;
/**
* A prefix to separate stored data from other data possibly stored in the memcache
*
* @var string
*/
protected $identifierPrefix;
/**
* Constructs this backend
*
* @param string $context Unused, for backward compatibility only
* @param array $options Configuration options - depends on the actual backend
* @throws Exception if memcache is not installed
*/
public function __construct($context, array $options = [])
{
if (!extension_loaded('memcache') && !extension_loaded('memcached')) {
throw new Exception('The PHP extension "memcache" or "memcached" must be installed and loaded in ' . 'order to use the Memcached backend.', 1213987706);
}
parent::__construct($context, $options);
if ($this->usedPeclModule === '') {
if (extension_loaded('memcache')) {
$this->usedPeclModule = 'memcache';
} elseif (extension_loaded('memcached')) {
$this->usedPeclModule = 'memcached';
}
}
}
/**
* Setter for servers to be used. Expects an array, the values are expected
* to be formatted like "<host>[:<port>]" or "unix://<path>"
*
* @param array $servers An array of servers to add.
* @api
*/
protected function setServers(array $servers)
{
$this->servers = $servers;
}
/**
* Setter for compression flags bit
*
* @param bool $useCompression
* @api
*/
protected function setCompression($useCompression)
{
$compressionFlag = $this->usedPeclModule === 'memcache' ? MEMCACHE_COMPRESSED : \Memcached::OPT_COMPRESSION;
if ($useCompression === true) {
$this->flags ^= $compressionFlag;
} else {
$this->flags &= ~$compressionFlag;
}
}
/**
* Getter for compression flag
*
* @return bool
* @api
*/
protected function getCompression()
{
return $this->flags !== 0;
}
/**
* Initializes the identifier prefix
*
* @throws Exception
*/
public function initializeObject()
{
if (empty($this->servers)) {
throw new Exception('No servers were given to Memcache', 1213115903);
}
$memcachedPlugin = '\\' . ucfirst($this->usedPeclModule);
$this->memcache = new $memcachedPlugin;
$defaultPort = $this->usedPeclModule === 'memcache' ? ini_get('memcache.default_port') : 11211;
foreach ($this->servers as $server) {
if (substr($server, 0, 7) === 'unix://') {
$host = $server;
$port = 0;
} else {
if (substr($server, 0, 6) === 'tcp://') {
$server = substr($server, 6);
}
if (strpos($server, ':') !== false) {
list($host, $port) = explode(':', $server, 2);
} else {
$host = $server;
$port = $defaultPort;
}
}
$this->memcache->addserver($host, $port);
}
if ($this->usedPeclModule === 'memcached') {
$this->memcache->setOption(\Memcached::OPT_COMPRESSION, $this->getCompression());
}
}
/**
* Sets the preferred PECL module
*
* @param string $peclModule
* @throws Exception
*/
public function setPeclModule($peclModule)
{
if ($peclModule !== 'memcache' && $peclModule !== 'memcached') {
throw new Exception('PECL module must be either "memcache" or "memcached".', 1442239768);
}
$this->usedPeclModule = $peclModule;
}
/**
* Initializes the identifier prefix when setting the cache.
*
* @param FrontendInterface $cache The frontend for this backend
*/
public function setCache(FrontendInterface $cache)
{
parent::setCache($cache);
$identifierHash = substr(md5(PATH_site . $this->context . $this->cacheIdentifier), 0, 12);
$this->identifierPrefix = 'TYPO3_' . $identifierHash . '_';
}
/**
* Saves data in the cache.
*
* @param string $entryIdentifier An identifier for this specific cache entry
* @param string $data The data to be stored
* @param array $tags Tags to associate with this cache entry
* @param int $lifetime Lifetime of this cache entry in seconds. If NULL is specified, the default lifetime is used. "0" means unlimited lifetime.
* @throws Exception if no cache frontend has been set.
* @throws \InvalidArgumentException if the identifier is not valid or the final memcached key is longer than 250 characters
* @throws Exception\InvalidDataException if $data is not a string
* @api
*/
public function set($entryIdentifier, $data, array $tags = [], $lifetime = null)
{
if (strlen($this->identifierPrefix . $entryIdentifier) > 250) {
throw new \InvalidArgumentException('Could not set value. Key more than 250 characters (' . $this->identifierPrefix . $entryIdentifier . ').', 1232969508);
}
if (!$this->cache instanceof FrontendInterface) {
throw new Exception('No cache frontend has been set yet via setCache().', 1207149215);
}
$tags[] = '%MEMCACHEBE%' . $this->cacheIdentifier;
$expiration = $lifetime ?? $this->defaultLifetime;
// Memcached consideres values over 2592000 sec (30 days) as UNIX timestamp
// thus $expiration should be converted from lifetime to UNIX timestamp
if ($expiration > 2592000) {
$expiration += $GLOBALS['EXEC_TIME'];
}
try {
if (is_string($data) && strlen($data) > self::MAX_BUCKET_SIZE) {
$data = str_split($data, 1024 * 1000);
$success = true;
$chunkNumber = 1;
foreach ($data as $chunk) {
$success = $success && $this->setInternal($entryIdentifier . '_chunk_' . $chunkNumber, $chunk, $expiration);
$chunkNumber++;
}
$success = $success && $this->setInternal($entryIdentifier, 'TYPO3*chunked:' . $chunkNumber, $expiration);
} else {
$success = $this->setInternal($entryIdentifier, $data, $expiration);
}
if ($success === true) {
$this->removeIdentifierFromAllTags($entryIdentifier);
$this->addIdentifierToTags($entryIdentifier, $tags);
} else {
throw new Exception('Could not set data to memcache server.', 1275830266);
}
} catch (\Exception $exception) {
$this->logger->alert('Memcache: could not set value.', ['exception' => $exception]);
}
}
/**
* Stores the actual data inside memcache/memcached
*
* @param string $entryIdentifier
* @param mixed $data
* @param int $expiration
* @return bool
*/
protected function setInternal($entryIdentifier, $data, $expiration)
{
if ($this->usedPeclModule === 'memcache') {
return $this->memcache->set($this->identifierPrefix . $entryIdentifier, $data, $this->flags, $expiration);
}
return $this->memcache->set($this->identifierPrefix . $entryIdentifier, $data, $expiration);
}
/**
* Loads data from the cache.
*
* @param string $entryIdentifier An identifier which describes the cache entry to load
* @return mixed The cache entry's content as a string or FALSE if the cache entry could not be loaded
* @api
*/
public function get($entryIdentifier)
{
$value = $this->memcache->get($this->identifierPrefix . $entryIdentifier);
if (is_string($value) && substr($value, 0, 14) === 'TYPO3*chunked:') {
list(, $chunkCount) = explode(':', $value);
$value = '';
for ($chunkNumber = 1; $chunkNumber < $chunkCount; $chunkNumber++) {
$value .= $this->memcache->get($this->identifierPrefix . $entryIdentifier . '_chunk_' . $chunkNumber);
}
}
return $value;
}
/**
* Checks if a cache entry with the specified identifier exists.
*
* @param string $entryIdentifier An identifier specifying the cache entry
* @return bool TRUE if such an entry exists, FALSE if not
* @api
*/
public function has($entryIdentifier)
{
if ($this->usedPeclModule === 'memcache') {
return $this->memcache->get($this->identifierPrefix . $entryIdentifier) !== false;
}
// pecl-memcached supports storing literal FALSE
$this->memcache->get($this->identifierPrefix . $entryIdentifier);
return $this->memcache->getResultCode() !== \Memcached::RES_NOTFOUND;
}
/**
* Removes all cache entries matching the specified identifier.
* Usually this only affects one entry but if - for what reason ever -
* old entries for the identifier still exist, they are removed as well.
*
* @param string $entryIdentifier Specifies the cache entry to remove
* @return bool TRUE if (at least) an entry could be removed or FALSE if no entry was found
* @api
*/
public function remove($entryIdentifier)
{
$this->removeIdentifierFromAllTags($entryIdentifier);
return $this->memcache->delete($this->identifierPrefix . $entryIdentifier, 0);
}
/**
* Finds and returns all cache entry identifiers which are tagged by the
* specified tag.
*
* @param string $tag The tag to search for
* @return array An array of entries with all matching entries. An empty array if no entries matched
* @api
*/
public function findIdentifiersByTag($tag)
{
$identifiers = $this->memcache->get($this->identifierPrefix . 'tag_' . $tag);
if ($identifiers !== false) {
return (array)$identifiers;
}
return [];
}
/**
* Removes all cache entries of this cache.
*
* @throws Exception
* @api
*/
public function flush()
{
if (!$this->cache instanceof FrontendInterface) {
throw new Exception('No cache frontend has been set via setCache() yet.', 1204111376);
}
$this->flushByTag('%MEMCACHEBE%' . $this->cacheIdentifier);
}
/**
* Removes all cache entries of this cache which are tagged by the specified tag.
*
* @param string $tag The tag the entries must have
* @api
*/
public function flushByTag($tag)
{
$identifiers = $this->findIdentifiersByTag($tag);
foreach ($identifiers as $identifier) {
$this->remove($identifier);
}
}
/**
* Associates the identifier with the given tags
*
* @param string $entryIdentifier
* @param array $tags
*/
protected function addIdentifierToTags($entryIdentifier, array $tags)
{
// Get identifier-to-tag index to look for updates
$existingTags = $this->findTagsByIdentifier($entryIdentifier);
$existingTagsUpdated = false;
foreach ($tags as $tag) {
// Update tag-to-identifier index
$identifiers = $this->findIdentifiersByTag($tag);
if (!in_array($entryIdentifier, $identifiers, true)) {
$identifiers[] = $entryIdentifier;
$this->memcache->set($this->identifierPrefix . 'tag_' . $tag, $identifiers);
}
// Test if identifier-to-tag index needs update
if (!in_array($tag, $existingTags, true)) {
$existingTags[] = $tag;
$existingTagsUpdated = true;
}
}
// Update identifier-to-tag index if needed
if ($existingTagsUpdated) {
$this->memcache->set($this->identifierPrefix . 'ident_' . $entryIdentifier, $existingTags);
}
}
/**
* Removes association of the identifier with the given tags
*
* @param string $entryIdentifier
*/
protected function removeIdentifierFromAllTags($entryIdentifier)
{
// Get tags for this identifier
$tags = $this->findTagsByIdentifier($entryIdentifier);
// De-associate tags with this identifier
foreach ($tags as $tag) {
$identifiers = $this->findIdentifiersByTag($tag);
// Formally array_search() below should never return FALSE due to
// the behavior of findTagsByIdentifier(). But if reverse index is
// corrupted, we still can get 'FALSE' from array_search(). This is
// not a problem because we are removing this identifier from
// anywhere.
if (($key = array_search($entryIdentifier, $identifiers)) !== false) {
unset($identifiers[$key]);
if (!empty($identifiers)) {
$this->memcache->set($this->identifierPrefix . 'tag_' . $tag, $identifiers);
} else {
$this->memcache->delete($this->identifierPrefix . 'tag_' . $tag, 0);
}
}
}
// Clear reverse tag index for this identifier
$this->memcache->delete($this->identifierPrefix . 'ident_' . $entryIdentifier, 0);
}
/**
* Finds all tags for the given identifier. This function uses reverse tag
* index to search for tags.
*
* @param string $identifier Identifier to find tags by
* @return array
* @api
*/
protected function findTagsByIdentifier($identifier)
{
$tags = $this->memcache->get($this->identifierPrefix . 'ident_' . $identifier);
return $tags === false ? [] : (array)$tags;
}
/**
* Does nothing, as memcached does GC itself
*
* @api
*/
public function collectGarbage()
{
}
}