8000 [Cache] Unconditionally use PhpFilesAdapter for system pools by nicolas-grekas · Pull Request #27549 · symfony/symfony · GitHub
[go: up one dir, main page]

Skip to content

[Cache] Unconditionally use PhpFilesAdapter for system pools #27549

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jun 11, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
[Cache] Unconditionally use PhpFilesAdapter for system pools
  • Loading branch information
nicolas-grekas committed Jun 11, 2018
commit 51381e530a948af3162b4a29fede0843795c35c7
Original file line number Diff line number Diff line change
Expand Up @@ -1538,7 +1538,6 @@ private function registerCacheConfiguration(array $config, ContainerBuilder $con
{
$version = new Parameter('container.build_id');
$container->getDefinition('cache.adapter.apcu')->replaceArgument(2, $version);
$container->getDefinition('cache.adapter.system')->replaceArgument(2, $version);
$container->getDefinition('cache.adapter.filesystem')->replaceArgument(2, $config['directory']);

if (isset($config['prefix_seed'])) {
Expand Down
8 changes: 4 additions & 4 deletions src/Symfony/Bundle/FrameworkBundle/Resources/config/cache.xml
Original file line number Diff line number Diff line change
Expand Up @@ -35,15 +35,15 @@
<tag name="cache.pool" />
</service>

<service id="cache.adapter.system" class="Symfony\Component\Cache\Adapter\AdapterInterface" abstract="true">
<factory class="Symfony\Component\Cache\Adapter\AbstractAdapter" method="createSystemCache" />
<service id="cache.adapter.system" class="Symfony\Component\Cache\Adapter\PhpFilesAdapter" abstract="true">
<tag name="cache.pool" clearer="cache.system_clearer" />
<tag name="monolog.logger" channel="cache" />
<argument /> <!-- namespace -->
<argument>0</argument> <!-- default lifetime -->
<argument /> <!-- version -->
<argument>%kernel.cache_dir%/pools</argument>
<argument type="service" id="logger" on-invalid="ignore" />
<call method="setLogger">
<argument type="service" id="logger" on-invalid="ignore" />
</call>
</service>

<service id="cache.adapter.apcu" class="Symfony\Component\Cache\Adapter\ApcuAdapter" abstract="true">
Expand Down
4 changes: 4 additions & 0 deletions src/Symfony/Component/Cache/Adapter/AbstractAdapter.php
Original file line number Diff line number Diff line change
Expand Up @@ -102,9 +102,13 @@ function ($deferred, $namespace, &$expiredIds) use ($getId) {
* @param LoggerInterface|null $logger
*
* @return AdapterInterface
*
* @deprecated since Symfony 4.2
*/
public static function createSystemCache($namespace, $defaultLifetime, $version, $directory, LoggerInterface $logger = null)
{
@trigger_error(sprintf('The "%s()" method is deprecated since Symfony 4.2.', __CLASS__), E_USER_DEPRECATED);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

shouldn't it be __METHOD__ ?


if (null === self::$apcuSupported) {
self::$apcuSupported = ApcuAdapter::isSupported();
}
Expand Down
1 change: 0 additions & 1 deletion src/Symfony/Component/Cache/Adapter/PhpArrayAdapter.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,6 @@ public function __construct(string $file, AdapterInterface $fallbackPool)
{
$this->file = $file;
$this->pool = $fallbackPool;
$this->zendDetectUnicode = ini_get('zend.detect_unicode');
Copy link
Member Author
@nicolas-grekas nicolas-grekas Jun 8, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No need to deal with zend.detect_unicode anymore when this line is removed. Let's remove the related complexity and overhead.

$this->createCacheItem = \Closure::bind(
function ($key, $value, $isHit) {
$item = new CacheItem();
Expand Down
5 changes: 1 addition & 4 deletions src/Symfony/Component/Cache/Adapter/PhpFilesAdapter.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,14 +24,11 @@ class PhpFilesAdapter extends AbstractAdapter implements PruneableInterface
*/
public function __construct(string $namespace = '', int $defaultLifetime = 0, string $directory = null)
{
if (!static::isSupported()) {
throw new CacheException('OPcache is not enabled');
}
self::$startTime = self::$startTime ?? $_SERVER['REQUEST_TIME'] ?? time();
parent::__construct('', $defaultLifetime);
$this->init($namespace, $directory);

$e = new \Exception();
$this->includeHandler = function () use ($e) { throw $e; };
$this->zendDetectUnicode = ini_get('zend.detect_unicode');
}
}
1 change: 1 addition & 0 deletions src/Symfony/Component/Cache/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ CHANGELOG
* added `CacheInterface`, which provides stampede protection via probabilistic early expiration and should become the preferred way to use a cache
* throw `LogicException` when `CacheItem::tag()` is called on an item coming from a non tag-aware pool
* deprecated `CacheItem::getPreviousTags()`, use `CacheItem::getMetadata()` instead
* deprecated the `AbstractAdapter::createSystemCache()` method

3.4.0
-----
Expand Down
1 change: 0 additions & 1 deletion src/Symfony/Component/Cache/Simple/PhpArrayCache.php
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,6 @@ public function __construct(string $file, CacheInterface $fallbackPool)
{
$this->file = $file;
$this->pool = $fallbackPool;
$this->zendDetectUnicode = ini_get('zend.detect_unicode');
}

/**
Expand Down
5 changes: 1 addition & 4 deletions src/Symfony/Component/Cache/Simple/PhpFilesCache.php
Original file line number Diff line number Diff line change
Expand Up @@ -24,14 +24,11 @@ class PhpFilesCache extends AbstractCache implements PruneableInterface
*/
public function __construct(string $namespace = '', int $defaultLifetime = 0, string $directory = null)
{
if (!static::isSupported()) {
throw new CacheException('OPcache is not enabled');
}
self::$startTime = self::$startTime ?? $_SERVER['REQUEST_TIME'] ?? time();
parent::__construct('', $defaultLifetime);
$this->init($namespace, $directory);

$e = new \Exception();
$this->includeHandler = function () use ($e) { throw $e; };
$this->zendDetectUnicode = ini_get('zend.detect_unicode');
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ public function testLongKey()
$cache->expects($this->exactly(2))
->method('doHave')
->withConsecutive(
array($this->equalTo('----------:0GTYWa9n4ed8vqNlOT2iEr:')),
array($this->equalTo('----------:nWfzGiCgLczv3SSUzXL3kg:')),
array($this->equalTo('----------:---------------------------------------'))
);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,6 @@ class PhpFilesAdapterTest extends AdapterTestCase

public function createCachePool()
{
if (!PhpFilesAdapter::isSupported()) {
$this->markTestSkipped('OPcache extension is not enabled.');
}

return new PhpFilesAdapter('sf-cache');
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,6 @@ class PhpFilesCacheTest extends CacheTestCase

public function createSimpleCache()
{
if (!PhpFilesCache::isSupported()) {
$this->markTestSkipped('OPcache extension is not enabled.');
}

return new PhpFilesCache('sf-cache');
}

Expand Down
14 changes: 11 additions & 3 deletions src/Symfony/Component/Cache/Traits/AbstractTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ trait AbstractTrait
private $namespaceVersion = '';
private $versioningIsEnabled = false;
private $deferred = array();
private $ids = array();

/**
* @var int|null The maximum length to enforce for identifiers or null when no limit applies
Expand Down Expand Up @@ -198,6 +199,7 @@ public function reset()
$this->commit();
}
$this->namespaceVersion = '';
$this->ids = array();
}

/**
Expand Down Expand Up @@ -229,20 +231,26 @@ protected static function unserialize($value)

private function getId($key)
{
CacheItem::validateKey($key);

if ($this->versioningIsEnabled && '' === $this->namespaceVersion) {
$this->namespaceVersion = '1:';
foreach ($this->doFetch(array('@'.$this->namespace)) as $v) {
$this->namespaceVersion = $v;
}
}

if (\is_string($key) && isset($this->ids[$key])) {
return $this->namespace.$this->namespaceVersion.$this->ids[$key];
}
CacheItem::validateKey($key);
$this->ids[$key] = $key;

if (null === $this->maxIdLength) {
return $this->namespace.$this->namespaceVersion.$key;
}
if (\strlen($id = $this->namespace.$this->namespaceVersion.$key) > $this->maxIdLength) {
$id = $this->namespace.$this->namespaceVersion.substr_replace(base64_encode(hash('sha256', $key, true)), ':', -22);
// Use MD5 to favor speed over security, which is not an issue here
$this->ids[$key] = $id = substr_replace(base64_encode(hash('md5', $key, true)), ':', -2);
$id = $this->namespace.$this->namespaceVersion.$id;
}

return $id;
Expand Down
12 changes: 9 additions & 3 deletions src/Symfony/Component/Cache/Traits/FilesystemCommonTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ protected function doClear($namespace)
$ok = true;

foreach (new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($this->directory, \FilesystemIterator::SKIP_DOTS)) as $file) {
$ok = ($file->isDir() || @unlink($file) || !file_exists($file)) && $ok;
$ok = ($file->isDir() || $this->doUnlink($file) || !file_exists($file)) && $ok;
}

return $ok;
Expand All @@ -71,12 +71,17 @@ protected function doDelete(array $ids)

foreach ($ids as $id) {
$file = $this->getFile($id);
$ok = (!file_exists($file) || @unlink($file) || !file_exists($file)) && $ok;
$ok = (!file_exists($file) || $this->doUnlink($file) || !file_exists($file)) && $ok;
}

return $ok;
}

protected function doUnlink($file)
{
return @unlink($file);
}

private function write($file, $data, $expiresAt = null)
{
set_error_handler(__CLASS__.'::throwError');
Expand All @@ -98,7 +103,8 @@ private function write($file, $data, $expiresAt = null)

private function getFile($id, $mkdir = false)
{
$hash = str_replace('/', '-', base64_encode(hash('sha256', static::class.$id, true)));
// Use MD5 to favor speed over security, which is not an issue here
$hash = str_replace('/', '-', base64_encode(hash('md5', static::class.$id, true)));
$dir = $this->directory.strtoupper($hash[0].DIRECTORY_SEPARATOR.$hash[1].DIRECTORY_SEPARATOR);

if ($mkdir && !file_exists($dir)) {
Expand Down
13 changes: 1 addition & 12 deletions src/Symfony/Component/Cache/Traits/PhpArrayTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@ trait PhpArrayTrait

private $file;
private $values;
private $zendDetectUnicode;

/**
* Store an array of cached values.
Expand Down Expand Up @@ -98,7 +97,6 @@ public function warmUp(array $values)
}

$dump .= "\n);\n";
$dump = str_replace("' . \"\\0\" . '", "\0", $dump);

$tmpFile = uniqid($this->file, true);

Expand Down Expand Up @@ -128,15 +126,6 @@ public function clear()
*/
private function initialize()
{
if ($this->zendDetectUnicode) {
$zmb = ini_set('zend.detect_unicode', 0);
}
try {
$this->values = file_exists($this->file) ? (include $this->file ?: array()) : array();
} finally {
if ($this->zendDetectUnicode) {
ini_set('zend.detect_unicode', $zmb);
}
}
$this->values = file_exists($this->file) ? (include $this->file ?: array()) : array();
}
}
34 changes: 18 additions & 16 deletions src/Symfony/Component/Cache/Traits/PhpFilesTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,14 @@ trait PhpFilesTrait
use FilesystemCommonTrait;

private $includeHandler;
private $zendDetectUnicode;

private static $startTime;

public static function isSupported()
{
return function_exists('opcache_invalidate') && ini_get('opcache.enable');
self::$startTime = self::$startTime ?? $_SERVER['REQUEST_TIME'] ?? time();

return \function_exists('opcache_invalidate') && ini_get('opcache.enable') && ('cli' !== \PHP_SAPI || ini_get('opcache.enable_cli'));
}

/**
Expand All @@ -40,19 +43,14 @@ public function prune()
{
$time = time();
$pruned = true;
$allowCompile = 'cli' !== PHP_SAPI || ini_get('opcache.enable_cli');

set_error_handler($this->includeHandler);
try {
foreach (new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($this->directory, \FilesystemIterator::SKIP_DOTS), \RecursiveIteratorIterator::LEAVES_ONLY) as $file) {
list($expiresAt) = include $file;

if ($time >= $expiresAt) {
$pruned = @unlink($file) && !file_exists($file) && $pruned;

if ($allowCompile) {
@opcache_invalidate($file, true);
}
$pruned = $this->doUnlink($file) && !file_exists($file) && $pruned;
}
}
} finally {
Expand All @@ -70,9 +68,6 @@ protected function doFetch(array $ids)
$values = array();
$now = time();

if ($this->zendDetectUnicode) {
$zmb = ini_set('zend.detect_unicode', 0);
}
set_error_handler($this->includeHandler);
try {
foreach ($ids as $id) {
Expand All @@ -88,9 +83,6 @@ protected function doFetch(array $ids)
}
} finally {
restore_error_handler();
if ($this->zendDetectUnicode) {
ini_set('zend.detect_unicode', $zmb);
}
}

foreach ($values as $id => $value) {
Expand Down Expand Up @@ -119,7 +111,7 @@ protected function doSave(array $values, $lifetime)
{
$ok = true;
$data = array($lifetime ? time() + $lifetime : PHP_INT_MAX, '');
$allowCompile = 'cli' !== PHP_SAPI || ini_get('opcache.enable_cli');
$allowCompile = self::isSupported();

foreach ($values as $key => $value) {
if (null === $value || \is_object($value)) {
Expand All @@ -142,7 +134,8 @@ protected function doSave(array $values, $lifetime)

$data[1] = $value;
$file = $this->getFile($key, true);
$ok = $this->write($file, '<?php return '.var_export($data, true).';') && $ok;
// Since OPcache only compiles files older than the script execution start, set the file's mtime in the past
$ok = $this->write($file, '<?php return '.var_export($data, true).';', self::$startTime - 10) && $ok;

if ($allowCompile) {
@opcache_invalidate($file, true);
Expand All @@ -155,4 +148,13 @@ protected function doSave(array $values, $lifetime)

return $ok;
}

protected function doUnlink($file)
{
if (self::isSupported()) {
@opcache_invalidate($file, true);
}

return @unlink($file);
}
}
0