/** * clear static cache with prefix, don't use except in clear-cache-watcher * * @internal */ public static function clear($cacheIdPrefix) { if (extension_loaded('apc')) { if (PHP_SAPI == 'cli') { Kwf_Util_Apc::callClearCacheByCli(array('clearCacheSimpleStatic' => $cacheIdPrefix)); } else { if (!class_exists('APCIterator')) { throw new Kwf_Exception_NotYetImplemented("We don't want to clear the whole"); } else { static $prefix; if (!isset($prefix)) { $prefix = Kwf_Cache_Simple::getUniquePrefix() . '-'; } $it = new APCIterator('user', '#^' . preg_quote($prefix . $cacheIdPrefix) . '#', APC_ITER_NONE); if ($it->getTotalCount() && !$it->current()) { //APCIterator is borked, delete everything //see https://bugs.php.net/bug.php?id=59938 if (extension_loaded('apcu')) { apc_clear_cache(); } else { apc_clear_cache('user'); } } else { //APCIterator seems to work, use it for deletion apc_delete($it); } } } } else { //don't use $cacheIdPrefix as filenames are base64 encoded foreach (glob('cache/simple/*') as $f) { unlink($f); } } }
public function index($arguments) { $news = new news(ConnectionFactory::get('mongo')); $articles = new articles(ConnectionFactory::get('mongo')); $notices = new notices(ConnectionFactory::get('redis')); $irc = new irc(ConnectionFactory::get('redis')); $quotes = new quotes(ConnectionFactory::get('mongo')); $forums = new forums(ConnectionFactory::get('redis')); // Set all site-wide notices. foreach ($notices->getAll() as $notice) { Error::set($notice, true); } // Fetch the easy data. $this->view['news'] = $news->getNewPosts(); $this->view['shortNews'] = $news->getNewPosts(true); $this->view['newArticles'] = $articles->getNewPosts('new', 1, 5); $this->view['ircOnline'] = $irc->getOnline(); $this->view['randomQuote'] = $quotes->getRandom(); $this->view['fPosts'] = $forums->getNew(); // Get online users. $apc = new APCIterator('user', '/' . Cache::PREFIX . 'user_.*/'); $this->view['onlineUsers'] = array(); while ($apc->valid()) { $current = $apc->current(); array_push($this->view['onlineUsers'], substr($current['key'], strlen(Cache::PREFIX) + 5)); $apc->next(); } // Set title. Layout::set('title', 'Home'); }
public static function ApcPurge($func, $id) { $apc = new APCIterator('user', '/' . Cache::PREFIX . 'data_' . get_called_class() . '_' . $func . '-' . $id . '.*/'); while ($apc->valid()) { $current = $apc->current(); apc_delete($current['key']); $apc->next(); } }
public function testWithTTL() { $backend = $this->getBackend(); $dep = new \Cachet\Dependency\TTL(300); $backend->set(new \Cachet\Item('cache', 'foo', 'bar', $dep)); $iter = new \APCIterator('user', "~^{$this->backendPrefix}cache/foo\$~"); $ttl = $iter->current()['ttl']; // surely not longer than 2 seconds! $this->assertTrue($ttl >= 298 && $ttl <= 300); }
/** * @param string $className * @depreciated */ public function clearClassCache($className = null) { $iterator = new \APCIterator('^user^'); while ($iterator->current()) { $tKey = $iterator->key(); if (mb_strpos($tKey, $className . '::') !== false) { apc_delete($tKey); } $iterator->next(); } }
public function index() { if (!CheckAcl::can('viewStats')) { return Error::set('You are not allowed to view stats!'); } $info = new APCIterator('user'); $redis = new redisInfo(ConnectionFactory::get('redis')); $redisInfo = $redis->info(); $this->view['apcNoKeys'] = $info->getTotalCount(); $this->view['apcSize'] = $info->getTotalSize(); $this->view['redisVersion'] = $redisInfo['redis_version']; $this->view['redisSIP'] = $redisInfo['bgsave_in_progress']; $this->view['redisNoChans'] = $redisInfo['pubsub_channels']; $this->view['redisMem'] = $redisInfo['used_memory']; $this->view['redisLastSave'] = $redisInfo['last_save_time']; $this->view['valid'] = true; }
public function __construct($namespace) { $normalNamespace = Key::normalKey($namespace); //get normal key $regexNamespace = str_replace('\\', '\\\\', $normalNamespace); //for regex, since \ is special char //find all where names starts with namespace parent::__construct('user', "/^{$regexNamespace}/"); }
/** * List of caches * * @return void */ public function indexAction() { $type = $this->params('type'); $cacheList = array('stat' => _a('File status cache'), 'apc' => _a('APC file cache'), 'file' => _a('System cache files'), 'persist' => _a('System persistent data'), 'module' => _a('Module cache'), 'comment' => _a('Comment cache')); if (!function_exists('apc_clear_cache')) { unset($cacheList['apc']); } elseif (class_exists('\\APCIterator')) { $apcIterator = new \APCIterator('file'); $size = $apcIterator->getTotalSize(); foreach (array('', 'K', 'M', 'G') as $i => $k) { if ($size < 1024) { break; } $size /= 1024; } $totalSize = sprintf("%5.1f %s", $size, $k); $totalCount = $apcIterator->getTotalCount(); $cacheList['apc'] .= ' (' . $totalCount . '-' . $totalSize . ')'; } $cacheStorageClass = get_class(Pi::service('cache')->storage()); $cacheStorageName = substr($cacheStorageClass, strrpos($cacheStorageClass, '\\') + 1); $cacheList['application'] = sprintf(_a('Application cache [%s]'), $cacheStorageName); $frontConfig = Pi::config()->load('application.front.php'); if (!empty($frontConfig['resource']['cache'])) { if (!empty($frontConfig['resource']['cache']['storage'])) { $cacheStorage = Pi::service('cache')->loadStorage($frontConfig['resource']['cache']['storage']); } else { $cacheStorage = Pi::service('cache')->storage(); } $cacheStorageClass = get_class($cacheStorage); $cacheStorageName = substr($cacheStorageClass, strrpos($cacheStorageClass, '\\') + 1); $page['title'] = sprintf(_a('Page cache [%s]'), $cacheStorageName); $modules = Pi::service('module')->meta(); $page['modules'] = array_keys($modules); $this->view()->assign('page', $page); } $registryList = Pi::service('registry')->getList(); sort($registryList); $this->view()->assign('type', $type); $this->view()->assign('list', $cacheList); $this->view()->assign('registry', $registryList); $this->view()->assign('title', _a('Cache list')); //$this->view()->setTemplate('cache-list'); }
public function __construct($search = null, $format = APC_ITER_ALL, $chunk_size = 100, $list = APC_LIST_ACTIVE) { parent::__construct('user', $search, $format, $chunk_size, $list); }
public static function iterate() { header('Content-Type: text/plain; charset=utf-8'); $requiredSpazi = 1024 * 1024 * 128; //128MB //$requiredSpazi = 1024*1024*300; $mem = apc_sma_info(true); $memSize = $mem['num_seg'] * $mem['seg_size']; $memAvailable = $mem['avail_mem']; if ($memAvailable > $requiredSpazi) { die; } $start = microtime(true); Kwf_Util_MemoryLimit::set(256); ini_set('display_errors', 'on'); set_time_limit(90); echo "size: " . round($memSize / (1024 * 1024)) . " MB\n"; echo "avail: " . round($memAvailable / (1024 * 1024)) . " MB\n"; echo "\nduration: " . round(microtime(true) - $start, 3) . " s\n"; $accessTime = array(); $it = new APCIterator('user', '#^[^-]+\\-[^-]+\\-(\\-cc|procI|url)-#', APC_ITER_KEY | APC_ITER_MEM_SIZE | APC_ITER_ATIME); echo "total count: " . $it->getTotalCount() . "\n"; echo "total hits: " . $it->getTotalHits() . "\n"; echo "total size: " . round($it->getTotalSize() / (1024 * 1024)) . " MB\n"; echo "\nduration: " . round(microtime(true) - $start, 3) . " s\n"; $webs = array(); foreach ($it as $i) { preg_match('#^([^-]+)\\-([^-]+)\\-+([a-zA-Z0-9]+)#', $i['key'], $m); $key = $m[1] . '-' . $m[2]; if (!isset($webs[$key])) { $webs[$key] = 0; } $webs[$key] += $i['mem_size']; $accessTime[] = time() - $i['access_time']; } echo "min lastAccess: " . min($accessTime) . "\n"; echo "max lastAccess: " . max($accessTime) . "\n"; echo "avg lastAccess: " . round(array_sum($accessTime) / count($accessTime)) . "\n"; echo "\nduration: " . round(microtime(true) - $start, 3) . " s\n"; unset($accessTime); echo "\n"; arsort($webs); foreach ($webs as $web => $items) { echo "{$web}: " . round($items / $it->getTotalSize() * 100) . "%\n"; } reset($webs); $web = key($webs); unset($it); unset($webs); echo "\nduration: " . round(microtime(true) - $start, 3) . " s\n"; $it = new APCIterator('user', '#^' . preg_quote($web) . '\\-(\\-cc|procI|url)-#', APC_ITER_KEY | APC_ITER_MEM_SIZE | APC_ITER_ATIME); echo "\n{$web}\n"; echo "total count: " . $it->getTotalCount() . "\n"; echo "total hits: " . $it->getTotalHits() . "\n"; echo "total size: " . round($it->getTotalSize() / (1024 * 1024)) . " MB\n"; echo "\nduration: " . round(microtime(true) - $start, 3) . " s\n"; $accessTime = array(); $size = array(); foreach ($it as $i) { $t = time() - $i['access_time']; $accessTime[$i['key']] = $t; $size[$i['key']] = $i['mem_size']; } unset($it); echo "min lastAccess: " . min($accessTime) . "\n"; echo "max lastAccess: " . max($accessTime) . "\n"; echo "avg lastAccess: " . round(array_sum($accessTime) / count($accessTime)) . "\n"; echo "\nduration: " . round(microtime(true) - $start, 3) . " s\n"; flush(); arsort($accessTime); $deletedBytes = 0; $deletedCount = 0; foreach ($accessTime as $key => $t) { $deletedBytes += $size[$key]; $memAvailable += $size[$key]; //echo "delete $key (".round($deletedBytes/(1024*1024))."MB)\n"; //flush(); apc_delete($key); $deletedCount++; if ($memAvailable > $requiredSpazi + 1024 * 1024 * 2) { break; } } echo "deleted {$deletedCount} entries\n"; echo "deleted " . round($deletedBytes / 1024) . " KB\n"; echo "\nduration: " . round(microtime(true) - $start, 3) . " s\n"; exit; }
<?php error_reporting(E_ALL & ~E_USER_NOTICE & ~E_NOTICE); echo "== No Search ==\n"; $it = new APCIterator('user'); apc_store('sample', 'x'); apc_store('another_sample', 'x'); foreach ($it as $key => $val) { // skip to end } var_dump($it->valid(), $it->key(), $it->current(), $it->next()); echo "== Search ==\n"; $it = new APCIterator('user', '/^b/'); // No elements, end? var_dump($it->valid(), $it->key(), $it->current(), $it->next());
public function current() { $data = parent::current(); return extension_loaded('apcu') && version_compare(phpversion('apcu'), '4.0.3') < 0 ? array('type' => 'user', 'key' => $data['key'], 'value' => $data['value'], 'num_hits' => $data['nhits'], 'mtime' => $data['mtime'], 'creation_time' => $data['ctime'], 'deletion_time' => $data['dtime'], 'access_time' => $data['atime'], 'ref_count' => $data['ref_count'], 'mem_size' => $data['mem_size'], 'ttl' => $data['ttl']) : $data; }
protected function del_old_cached() { $t = time(); $apc_user_info = apc_cache_info('user', true); if (!empty($apc_user_info['ttl'])) { $apc_ttl = $apc_user_info['ttl'] / 2; $check_period = $apc_ttl; } if (empty($check_period) || $check_period > 1800) { $check_period = 1800; } $ittl = new \APCIterator('user', '/^' . preg_quote($this->defragmentation_prefix) . '$/', APC_ITER_ATIME, 1); $cttl = $ittl->current(); $previous_cleaning = $cttl[self::apc_arr_atime]; if (empty($previous_cleaning) || $t - $previous_cleaning > $check_period) { apc_store($this->defragmentation_prefix, $t, $check_period); $this->del_old(); } return true; }
/** * Rewind the Iterator to the first element. * * @return void */ public function rewind() { return $this->baseIterator->rewind(); }
public function getStats() { $cinfo = apc_cache_info('user', true); $apcIt = new APCIterator('user'); $size = $apcIt->getTotalSize(); // support apc and old versions of apcu $hits = $misses = 0; if (!empty($cinfo['num_hits'])) { $hits = $cinfo['num_hits']; } else { if (!empty($cinfo['nhits'])) { $hits = $cinfo['nhits']; } } if (!empty($cinfo['num_misses'])) { $misses = $cinfo['num_misses']; } else { if (!empty($cinfo['nmisses'])) { $misses = $cinfo['nmisses']; } } $stats = array(); $stats['size'] = $size; $stats['hits'] = $hits; $stats['misses'] = $misses; $stats['more'] = 'r/w/d=' . self::$requestStats['get'] . '/' . self::$requestStats['set'] . '/' . self::$requestStats['del']; return $stats; }
/** * Get metadata of an item. * * @param string $normalizedKey * @return array|boolean Metadata on success, false on failure * @throws Exception\ExceptionInterface */ protected function internalGetMetadata(&$normalizedKey) { $options = $this->getOptions(); $prefix = $options->getNamespace() . $options->getNamespaceSeparator(); $internalKey = $prefix . $normalizedKey; // @see http://pecl.php.net/bugs/bug.php?id=22564 if (!apc_exists($internalKey)) { $metadata = false; } else { $format = \APC_ITER_ALL ^ \APC_ITER_VALUE ^ \APC_ITER_TYPE ^ \APC_ITER_REFCOUNT; $regexp = '/^' . preg_quote($internalKey, '/') . '$/'; $it = new BaseApcIterator('user', $regexp, $format, 100, \APC_LIST_ACTIVE); $metadata = $it->current(); } if (!$metadata) { return false; } $this->normalizeMetadata($metadata); return $metadata; }
echo "<pre>"; echo "<pre>"; //Example #1 apc_inc() example echo "Let's do something with success", PHP_EOL; apc_store('anumber', 42); echo apc_fetch('anumber'), PHP_EOL; echo apc_inc('anumber'), PHP_EOL; echo apc_inc('anumber', 10), PHP_EOL; echo apc_inc('anumber', 10, $success), PHP_EOL; var_dump($success); echo "Now, let's fail", PHP_EOL, PHP_EOL; apc_store('astring', 'foo'); $ret = apc_inc('astring', 1, $fail); var_dump($ret); var_dump($fail); ?> <?php echo "I am here <br/><br/>"; $oApcIt = new APCIterator('user', '/^[a-z]/'); echo "This total APC in mem: [" . $oApcIt->getTotalCount() . "]<br/><br/>"; echo "This total APC hits: [" . $oApcIt->getTotalHits() . "]<br/><br/>"; echo "This total size APC: [" . $oApcIt->getTotalSize() . "]<br/><br/>"; echo "WHILE "; print_r($oApcIt); echo "<br/>"; foreach ($oApcIt as $counter) { // print_r($counter) . PHP_EOL; echo "{$counter['key']}: {$counter['value']}<br/>"; //apc_dec($counter['key'], $counter['value']) . "<br/>"; }