PageRenderTime 32ms CodeModel.GetById 0ms RepoModel.GetById 1ms app.codeStats 0ms

/libs/Zend/Cache/Backend/TwoLevels.php

https://github.com/quarkness/piwik
PHP | 536 lines | 248 code | 36 blank | 252 comment | 40 complexity | a0f3d47a82ca81aed51b7a29d86e7353 MD5 | raw file
  1. <?php
  2. /**
  3. * Zend Framework
  4. *
  5. * LICENSE
  6. *
  7. * This source file is subject to the new BSD license that is bundled
  8. * with this package in the file LICENSE.txt.
  9. * It is also available through the world-wide-web at this URL:
  10. * http://framework.zend.com/license/new-bsd
  11. * If you did not receive a copy of the license and are unable to
  12. * obtain it through the world-wide-web, please send an email
  13. * to license@zend.com so we can send you a copy immediately.
  14. *
  15. * @category Zend
  16. * @package Zend_Cache
  17. * @subpackage Zend_Cache_Backend
  18. * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
  19. * @license http://framework.zend.com/license/new-bsd New BSD License
  20. * @version $Id: TwoLevels.php 24254 2011-07-22 12:04:41Z mabe $
  21. */
  22. /**
  23. * @see Zend_Cache_Backend_ExtendedInterface
  24. */
  25. // require_once 'Zend/Cache/Backend/ExtendedInterface.php';
  26. /**
  27. * @see Zend_Cache_Backend
  28. */
  29. // require_once 'Zend/Cache/Backend.php';
  30. /**
  31. * @package Zend_Cache
  32. * @subpackage Zend_Cache_Backend
  33. * @copyright Copyright (c) 2005-2011 Zend Technologies USA Inc. (http://www.zend.com)
  34. * @license http://framework.zend.com/license/new-bsd New BSD License
  35. */
  36. class Zend_Cache_Backend_TwoLevels extends Zend_Cache_Backend implements Zend_Cache_Backend_ExtendedInterface
  37. {
  38. /**
  39. * Available options
  40. *
  41. * =====> (string) slow_backend :
  42. * - Slow backend name
  43. * - Must implement the Zend_Cache_Backend_ExtendedInterface
  44. * - Should provide a big storage
  45. *
  46. * =====> (string) fast_backend :
  47. * - Flow backend name
  48. * - Must implement the Zend_Cache_Backend_ExtendedInterface
  49. * - Must be much faster than slow_backend
  50. *
  51. * =====> (array) slow_backend_options :
  52. * - Slow backend options (see corresponding backend)
  53. *
  54. * =====> (array) fast_backend_options :
  55. * - Fast backend options (see corresponding backend)
  56. *
  57. * =====> (int) stats_update_factor :
  58. * - Disable / Tune the computation of the fast backend filling percentage
  59. * - When saving a record into cache :
  60. * 1 => systematic computation of the fast backend filling percentage
  61. * x (integer) > 1 => computation of the fast backend filling percentage randomly 1 times on x cache write
  62. *
  63. * =====> (boolean) slow_backend_custom_naming :
  64. * =====> (boolean) fast_backend_custom_naming :
  65. * =====> (boolean) slow_backend_autoload :
  66. * =====> (boolean) fast_backend_autoload :
  67. * - See Zend_Cache::factory() method
  68. *
  69. * =====> (boolean) auto_refresh_fast_cache
  70. * - If true, auto refresh the fast cache when a cache record is hit
  71. *
  72. * @var array available options
  73. */
  74. protected $_options = array(
  75. 'slow_backend' => 'File',
  76. 'fast_backend' => 'Apc',
  77. 'slow_backend_options' => array(),
  78. 'fast_backend_options' => array(),
  79. 'stats_update_factor' => 10,
  80. 'slow_backend_custom_naming' => false,
  81. 'fast_backend_custom_naming' => false,
  82. 'slow_backend_autoload' => false,
  83. 'fast_backend_autoload' => false,
  84. 'auto_refresh_fast_cache' => true
  85. );
  86. /**
  87. * Slow Backend
  88. *
  89. * @var Zend_Cache_Backend_ExtendedInterface
  90. */
  91. protected $_slowBackend;
  92. /**
  93. * Fast Backend
  94. *
  95. * @var Zend_Cache_Backend_ExtendedInterface
  96. */
  97. protected $_fastBackend;
  98. /**
  99. * Cache for the fast backend filling percentage
  100. *
  101. * @var int
  102. */
  103. protected $_fastBackendFillingPercentage = null;
  104. /**
  105. * Constructor
  106. *
  107. * @param array $options Associative array of options
  108. * @throws Zend_Cache_Exception
  109. * @return void
  110. */
  111. public function __construct(array $options = array())
  112. {
  113. parent::__construct($options);
  114. if ($this->_options['slow_backend'] === null) {
  115. Zend_Cache::throwException('slow_backend option has to set');
  116. } elseif ($this->_options['slow_backend'] instanceof Zend_Cache_Backend_ExtendedInterface) {
  117. $this->_slowBackend = $this->_options['slow_backend'];
  118. } else {
  119. $this->_slowBackend = Zend_Cache::_makeBackend(
  120. $this->_options['slow_backend'],
  121. $this->_options['slow_backend_options'],
  122. $this->_options['slow_backend_custom_naming'],
  123. $this->_options['slow_backend_autoload']
  124. );
  125. if (!in_array('Zend_Cache_Backend_ExtendedInterface', class_implements($this->_slowBackend))) {
  126. Zend_Cache::throwException('slow_backend must implement the Zend_Cache_Backend_ExtendedInterface interface');
  127. }
  128. }
  129. if ($this->_options['fast_backend'] === null) {
  130. Zend_Cache::throwException('fast_backend option has to set');
  131. } elseif ($this->_options['fast_backend'] instanceof Zend_Cache_Backend_ExtendedInterface) {
  132. $this->_fastBackend = $this->_options['fast_backend'];
  133. } else {
  134. $this->_fastBackend = Zend_Cache::_makeBackend(
  135. $this->_options['fast_backend'],
  136. $this->_options['fast_backend_options'],
  137. $this->_options['fast_backend_custom_naming'],
  138. $this->_options['fast_backend_autoload']
  139. );
  140. if (!in_array('Zend_Cache_Backend_ExtendedInterface', class_implements($this->_fastBackend))) {
  141. Zend_Cache::throwException('fast_backend must implement the Zend_Cache_Backend_ExtendedInterface interface');
  142. }
  143. }
  144. $this->_slowBackend->setDirectives($this->_directives);
  145. $this->_fastBackend->setDirectives($this->_directives);
  146. }
  147. /**
  148. * Test if a cache is available or not (for the given id)
  149. *
  150. * @param string $id cache id
  151. * @return mixed|false (a cache is not available) or "last modified" timestamp (int) of the available cache record
  152. */
  153. public function test($id)
  154. {
  155. $fastTest = $this->_fastBackend->test($id);
  156. if ($fastTest) {
  157. return $fastTest;
  158. } else {
  159. return $this->_slowBackend->test($id);
  160. }
  161. }
  162. /**
  163. * Save some string datas into a cache record
  164. *
  165. * Note : $data is always "string" (serialization is done by the
  166. * core not by the backend)
  167. *
  168. * @param string $data Datas to cache
  169. * @param string $id Cache id
  170. * @param array $tags Array of strings, the cache record will be tagged by each string entry
  171. * @param int $specificLifetime If != false, set a specific lifetime for this cache record (null => infinite lifetime)
  172. * @param int $priority integer between 0 (very low priority) and 10 (maximum priority) used by some particular backends
  173. * @return boolean true if no problem
  174. */
  175. public function save($data, $id, $tags = array(), $specificLifetime = false, $priority = 8)
  176. {
  177. $usage = $this->_getFastFillingPercentage('saving');
  178. $boolFast = true;
  179. $lifetime = $this->getLifetime($specificLifetime);
  180. $preparedData = $this->_prepareData($data, $lifetime, $priority);
  181. if (($priority > 0) && (10 * $priority >= $usage)) {
  182. $fastLifetime = $this->_getFastLifetime($lifetime, $priority);
  183. $boolFast = $this->_fastBackend->save($preparedData, $id, array(), $fastLifetime);
  184. $boolSlow = $this->_slowBackend->save($preparedData, $id, $tags, $lifetime);
  185. } else {
  186. $boolSlow = $this->_slowBackend->save($preparedData, $id, $tags, $lifetime);
  187. if ($boolSlow === true) {
  188. $boolFast = $this->_fastBackend->remove($id);
  189. if (!$boolFast && !$this->_fastBackend->test($id)) {
  190. // some backends return false on remove() even if the key never existed. (and it won't if fast is full)
  191. // all we care about is that the key doesn't exist now
  192. $boolFast = true;
  193. }
  194. }
  195. }
  196. return ($boolFast && $boolSlow);
  197. }
  198. /**
  199. * Test if a cache is available for the given id and (if yes) return it (false else)
  200. *
  201. * Note : return value is always "string" (unserialization is done by the core not by the backend)
  202. *
  203. * @param string $id Cache id
  204. * @param boolean $doNotTestCacheValidity If set to true, the cache validity won't be tested
  205. * @return string|false cached datas
  206. */
  207. public function load($id, $doNotTestCacheValidity = false)
  208. {
  209. $res = $this->_fastBackend->load($id, $doNotTestCacheValidity);
  210. if ($res === false) {
  211. $res = $this->_slowBackend->load($id, $doNotTestCacheValidity);
  212. if ($res === false) {
  213. // there is no cache at all for this id
  214. return false;
  215. }
  216. }
  217. $array = unserialize($res);
  218. // maybe, we have to refresh the fast cache ?
  219. if ($this->_options['auto_refresh_fast_cache']) {
  220. if ($array['priority'] == 10) {
  221. // no need to refresh the fast cache with priority = 10
  222. return $array['data'];
  223. }
  224. $newFastLifetime = $this->_getFastLifetime($array['lifetime'], $array['priority'], time() - $array['expire']);
  225. // we have the time to refresh the fast cache
  226. $usage = $this->_getFastFillingPercentage('loading');
  227. if (($array['priority'] > 0) && (10 * $array['priority'] >= $usage)) {
  228. // we can refresh the fast cache
  229. $preparedData = $this->_prepareData($array['data'], $array['lifetime'], $array['priority']);
  230. $this->_fastBackend->save($preparedData, $id, array(), $newFastLifetime);
  231. }
  232. }
  233. return $array['data'];
  234. }
  235. /**
  236. * Remove a cache record
  237. *
  238. * @param string $id Cache id
  239. * @return boolean True if no problem
  240. */
  241. public function remove($id)
  242. {
  243. $boolFast = $this->_fastBackend->remove($id);
  244. $boolSlow = $this->_slowBackend->remove($id);
  245. return $boolFast && $boolSlow;
  246. }
  247. /**
  248. * Clean some cache records
  249. *
  250. * Available modes are :
  251. * Zend_Cache::CLEANING_MODE_ALL (default) => remove all cache entries ($tags is not used)
  252. * Zend_Cache::CLEANING_MODE_OLD => remove too old cache entries ($tags is not used)
  253. * Zend_Cache::CLEANING_MODE_MATCHING_TAG => remove cache entries matching all given tags
  254. * ($tags can be an array of strings or a single string)
  255. * Zend_Cache::CLEANING_MODE_NOT_MATCHING_TAG => remove cache entries not {matching one of the given tags}
  256. * ($tags can be an array of strings or a single string)
  257. * Zend_Cache::CLEANING_MODE_MATCHING_ANY_TAG => remove cache entries matching any given tags
  258. * ($tags can be an array of strings or a single string)
  259. *
  260. * @param string $mode Clean mode
  261. * @param array $tags Array of tags
  262. * @throws Zend_Cache_Exception
  263. * @return boolean true if no problem
  264. */
  265. public function clean($mode = Zend_Cache::CLEANING_MODE_ALL, $tags = array())
  266. {
  267. switch($mode) {
  268. case Zend_Cache::CLEANING_MODE_ALL:
  269. $boolFast = $this->_fastBackend->clean(Zend_Cache::CLEANING_MODE_ALL);
  270. $boolSlow = $this->_slowBackend->clean(Zend_Cache::CLEANING_MODE_ALL);
  271. return $boolFast && $boolSlow;
  272. break;
  273. case Zend_Cache::CLEANING_MODE_OLD:
  274. return $this->_slowBackend->clean(Zend_Cache::CLEANING_MODE_OLD);
  275. case Zend_Cache::CLEANING_MODE_MATCHING_TAG:
  276. $ids = $this->_slowBackend->getIdsMatchingTags($tags);
  277. $res = true;
  278. foreach ($ids as $id) {
  279. $bool = $this->remove($id);
  280. $res = $res && $bool;
  281. }
  282. return $res;
  283. break;
  284. case Zend_Cache::CLEANING_MODE_NOT_MATCHING_TAG:
  285. $ids = $this->_slowBackend->getIdsNotMatchingTags($tags);
  286. $res = true;
  287. foreach ($ids as $id) {
  288. $bool = $this->remove($id);
  289. $res = $res && $bool;
  290. }
  291. return $res;
  292. break;
  293. case Zend_Cache::CLEANING_MODE_MATCHING_ANY_TAG:
  294. $ids = $this->_slowBackend->getIdsMatchingAnyTags($tags);
  295. $res = true;
  296. foreach ($ids as $id) {
  297. $bool = $this->remove($id);
  298. $res = $res && $bool;
  299. }
  300. return $res;
  301. break;
  302. default:
  303. Zend_Cache::throwException('Invalid mode for clean() method');
  304. break;
  305. }
  306. }
  307. /**
  308. * Return an array of stored cache ids
  309. *
  310. * @return array array of stored cache ids (string)
  311. */
  312. public function getIds()
  313. {
  314. return $this->_slowBackend->getIds();
  315. }
  316. /**
  317. * Return an array of stored tags
  318. *
  319. * @return array array of stored tags (string)
  320. */
  321. public function getTags()
  322. {
  323. return $this->_slowBackend->getTags();
  324. }
  325. /**
  326. * Return an array of stored cache ids which match given tags
  327. *
  328. * In case of multiple tags, a logical AND is made between tags
  329. *
  330. * @param array $tags array of tags
  331. * @return array array of matching cache ids (string)
  332. */
  333. public function getIdsMatchingTags($tags = array())
  334. {
  335. return $this->_slowBackend->getIdsMatchingTags($tags);
  336. }
  337. /**
  338. * Return an array of stored cache ids which don't match given tags
  339. *
  340. * In case of multiple tags, a logical OR is made between tags
  341. *
  342. * @param array $tags array of tags
  343. * @return array array of not matching cache ids (string)
  344. */
  345. public function getIdsNotMatchingTags($tags = array())
  346. {
  347. return $this->_slowBackend->getIdsNotMatchingTags($tags);
  348. }
  349. /**
  350. * Return an array of stored cache ids which match any given tags
  351. *
  352. * In case of multiple tags, a logical AND is made between tags
  353. *
  354. * @param array $tags array of tags
  355. * @return array array of any matching cache ids (string)
  356. */
  357. public function getIdsMatchingAnyTags($tags = array())
  358. {
  359. return $this->_slowBackend->getIdsMatchingAnyTags($tags);
  360. }
  361. /**
  362. * Return the filling percentage of the backend storage
  363. *
  364. * @return int integer between 0 and 100
  365. */
  366. public function getFillingPercentage()
  367. {
  368. return $this->_slowBackend->getFillingPercentage();
  369. }
  370. /**
  371. * Return an array of metadatas for the given cache id
  372. *
  373. * The array must include these keys :
  374. * - expire : the expire timestamp
  375. * - tags : a string array of tags
  376. * - mtime : timestamp of last modification time
  377. *
  378. * @param string $id cache id
  379. * @return array array of metadatas (false if the cache id is not found)
  380. */
  381. public function getMetadatas($id)
  382. {
  383. return $this->_slowBackend->getMetadatas($id);
  384. }
  385. /**
  386. * Give (if possible) an extra lifetime to the given cache id
  387. *
  388. * @param string $id cache id
  389. * @param int $extraLifetime
  390. * @return boolean true if ok
  391. */
  392. public function touch($id, $extraLifetime)
  393. {
  394. return $this->_slowBackend->touch($id, $extraLifetime);
  395. }
  396. /**
  397. * Return an associative array of capabilities (booleans) of the backend
  398. *
  399. * The array must include these keys :
  400. * - automatic_cleaning (is automating cleaning necessary)
  401. * - tags (are tags supported)
  402. * - expired_read (is it possible to read expired cache records
  403. * (for doNotTestCacheValidity option for example))
  404. * - priority does the backend deal with priority when saving
  405. * - infinite_lifetime (is infinite lifetime can work with this backend)
  406. * - get_list (is it possible to get the list of cache ids and the complete list of tags)
  407. *
  408. * @return array associative of with capabilities
  409. */
  410. public function getCapabilities()
  411. {
  412. $slowBackendCapabilities = $this->_slowBackend->getCapabilities();
  413. return array(
  414. 'automatic_cleaning' => $slowBackendCapabilities['automatic_cleaning'],
  415. 'tags' => $slowBackendCapabilities['tags'],
  416. 'expired_read' => $slowBackendCapabilities['expired_read'],
  417. 'priority' => $slowBackendCapabilities['priority'],
  418. 'infinite_lifetime' => $slowBackendCapabilities['infinite_lifetime'],
  419. 'get_list' => $slowBackendCapabilities['get_list']
  420. );
  421. }
  422. /**
  423. * Prepare a serialized array to store datas and metadatas informations
  424. *
  425. * @param string $data data to store
  426. * @param int $lifetime original lifetime
  427. * @param int $priority priority
  428. * @return string serialize array to store into cache
  429. */
  430. private function _prepareData($data, $lifetime, $priority)
  431. {
  432. $lt = $lifetime;
  433. if ($lt === null) {
  434. $lt = 9999999999;
  435. }
  436. return serialize(array(
  437. 'data' => $data,
  438. 'lifetime' => $lifetime,
  439. 'expire' => time() + $lt,
  440. 'priority' => $priority
  441. ));
  442. }
  443. /**
  444. * Compute and return the lifetime for the fast backend
  445. *
  446. * @param int $lifetime original lifetime
  447. * @param int $priority priority
  448. * @param int $maxLifetime maximum lifetime
  449. * @return int lifetime for the fast backend
  450. */
  451. private function _getFastLifetime($lifetime, $priority, $maxLifetime = null)
  452. {
  453. if ($lifetime <= 0) {
  454. // if no lifetime, we have an infinite lifetime
  455. // we need to use arbitrary lifetimes
  456. $fastLifetime = (int) (2592000 / (11 - $priority));
  457. } else {
  458. // prevent computed infinite lifetime (0) by ceil
  459. $fastLifetime = (int) ceil($lifetime / (11 - $priority));
  460. }
  461. if ($maxLifetime >= 0 && $fastLifetime > $maxLifetime) {
  462. return $maxLifetime;
  463. }
  464. return $fastLifetime;
  465. }
  466. /**
  467. * PUBLIC METHOD FOR UNIT TESTING ONLY !
  468. *
  469. * Force a cache record to expire
  470. *
  471. * @param string $id cache id
  472. */
  473. public function ___expire($id)
  474. {
  475. $this->_fastBackend->remove($id);
  476. $this->_slowBackend->___expire($id);
  477. }
  478. private function _getFastFillingPercentage($mode)
  479. {
  480. if ($mode == 'saving') {
  481. // mode saving
  482. if ($this->_fastBackendFillingPercentage === null) {
  483. $this->_fastBackendFillingPercentage = $this->_fastBackend->getFillingPercentage();
  484. } else {
  485. $rand = rand(1, $this->_options['stats_update_factor']);
  486. if ($rand == 1) {
  487. // we force a refresh
  488. $this->_fastBackendFillingPercentage = $this->_fastBackend->getFillingPercentage();
  489. }
  490. }
  491. } else {
  492. // mode loading
  493. // we compute the percentage only if it's not available in cache
  494. if ($this->_fastBackendFillingPercentage === null) {
  495. $this->_fastBackendFillingPercentage = $this->_fastBackend->getFillingPercentage();
  496. }
  497. }
  498. return $this->_fastBackendFillingPercentage;
  499. }
  500. }