You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

rcube_cache_shared.php 19KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662
  1. <?php
  2. /**
  3. +-----------------------------------------------------------------------+
  4. | This file is part of the Roundcube Webmail client |
  5. | Copyright (C) 2011-2013, The Roundcube Dev Team |
  6. | Copyright (C) 2011-2013, Kolab Systems AG |
  7. | |
  8. | Licensed under the GNU General Public License version 3 or |
  9. | any later version with exceptions for skins & plugins. |
  10. | See the README file for a full license statement. |
  11. | |
  12. | PURPOSE: |
  13. | Shared (cross-user) caching engine |
  14. +-----------------------------------------------------------------------+
  15. | Author: Thomas Bruederli <roundcube@gmail.com> |
  16. | Author: Aleksander Machniak <alec@alec.pl> |
  17. +-----------------------------------------------------------------------+
  18. */
  19. /**
  20. * Interface class for accessing Roundcube shared cache
  21. *
  22. * @package Framework
  23. * @subpackage Cache
  24. * @author Thomas Bruederli <roundcube@gmail.com>
  25. * @author Aleksander Machniak <alec@alec.pl>
  26. */
  27. class rcube_cache_shared
  28. {
  29. /**
  30. * Instance of database handler
  31. *
  32. * @var rcube_db|Memcache|bool
  33. */
  34. private $db;
  35. private $type;
  36. private $prefix;
  37. private $ttl;
  38. private $packed;
  39. private $index;
  40. private $table;
  41. private $debug;
  42. private $index_changed = false;
  43. private $cache = array();
  44. private $cache_changes = array();
  45. private $cache_sums = array();
  46. private $max_packet = -1;
  47. /**
  48. * Object constructor.
  49. *
  50. * @param string $type Engine type ('db' or 'memcache' or 'apc')
  51. * @param string $prefix Key name prefix
  52. * @param string $ttl Expiration time of memcache/apc items
  53. * @param bool $packed Enables/disabled data serialization.
  54. * It's possible to disable data serialization if you're sure
  55. * stored data will be always a safe string
  56. */
  57. function __construct($type, $prefix='', $ttl=0, $packed=true)
  58. {
  59. $rcube = rcube::get_instance();
  60. $type = strtolower($type);
  61. if ($type == 'memcache') {
  62. $this->type = 'memcache';
  63. $this->db = $rcube->get_memcache();
  64. $this->debug = $rcube->config->get('memcache_debug');
  65. }
  66. else if ($type == 'apc') {
  67. $this->type = 'apc';
  68. $this->db = function_exists('apc_exists'); // APC 3.1.4 required
  69. $this->debug = $rcube->config->get('apc_debug');
  70. }
  71. else {
  72. $this->type = 'db';
  73. $this->db = $rcube->get_dbh();
  74. $this->table = $this->db->table_name('cache_shared', true);
  75. }
  76. // convert ttl string to seconds
  77. $ttl = get_offset_sec($ttl);
  78. if ($ttl > 2592000) $ttl = 2592000;
  79. $this->ttl = $ttl;
  80. $this->packed = $packed;
  81. $this->prefix = $prefix;
  82. }
  83. /**
  84. * Returns cached value.
  85. *
  86. * @param string $key Cache key name
  87. *
  88. * @return mixed Cached value
  89. */
  90. function get($key)
  91. {
  92. if (!array_key_exists($key, $this->cache)) {
  93. return $this->read_record($key);
  94. }
  95. return $this->cache[$key];
  96. }
  97. /**
  98. * Sets (add/update) value in cache.
  99. *
  100. * @param string $key Cache key name
  101. * @param mixed $data Cache data
  102. */
  103. function set($key, $data)
  104. {
  105. $this->cache[$key] = $data;
  106. $this->cache_changes[$key] = true;
  107. }
  108. /**
  109. * Returns cached value without storing it in internal memory.
  110. *
  111. * @param string $key Cache key name
  112. *
  113. * @return mixed Cached value
  114. */
  115. function read($key)
  116. {
  117. if (array_key_exists($key, $this->cache)) {
  118. return $this->cache[$key];
  119. }
  120. return $this->read_record($key, true);
  121. }
  122. /**
  123. * Sets (add/update) value in cache and immediately saves
  124. * it in the backend, no internal memory will be used.
  125. *
  126. * @param string $key Cache key name
  127. * @param mixed $data Cache data
  128. *
  129. * @param boolean True on success, False on failure
  130. */
  131. function write($key, $data)
  132. {
  133. return $this->write_record($key, $this->serialize($data));
  134. }
  135. /**
  136. * Clears the cache.
  137. *
  138. * @param string $key Cache key name or pattern
  139. * @param boolean $prefix_mode Enable it to clear all keys starting
  140. * with prefix specified in $key
  141. */
  142. function remove($key=null, $prefix_mode=false)
  143. {
  144. // Remove all keys
  145. if ($key === null) {
  146. $this->cache = array();
  147. $this->cache_changes = array();
  148. $this->cache_sums = array();
  149. }
  150. // Remove keys by name prefix
  151. else if ($prefix_mode) {
  152. foreach (array_keys($this->cache) as $k) {
  153. if (strpos($k, $key) === 0) {
  154. $this->cache[$k] = null;
  155. $this->cache_changes[$k] = false;
  156. unset($this->cache_sums[$k]);
  157. }
  158. }
  159. }
  160. // Remove one key by name
  161. else {
  162. $this->cache[$key] = null;
  163. $this->cache_changes[$key] = false;
  164. unset($this->cache_sums[$key]);
  165. }
  166. // Remove record(s) from the backend
  167. $this->remove_record($key, $prefix_mode);
  168. }
  169. /**
  170. * Remove cache records older than ttl
  171. */
  172. function expunge()
  173. {
  174. if ($this->type == 'db' && $this->db && $this->ttl) {
  175. $this->db->query(
  176. "DELETE FROM {$this->table}"
  177. . " WHERE `cache_key` LIKE ?"
  178. . " AND `expires` < " . $this->db->now(),
  179. $this->prefix . '.%');
  180. }
  181. }
  182. /**
  183. * Remove expired records of all caches
  184. */
  185. static function gc()
  186. {
  187. $rcube = rcube::get_instance();
  188. $db = $rcube->get_dbh();
  189. $db->query("DELETE FROM " . $db->table_name('cache_shared', true) . " WHERE `expires` < " . $db->now());
  190. }
  191. /**
  192. * Writes the cache back to the DB.
  193. */
  194. function close()
  195. {
  196. foreach ($this->cache as $key => $data) {
  197. // The key has been used
  198. if ($this->cache_changes[$key]) {
  199. // Make sure we're not going to write unchanged data
  200. // by comparing current md5 sum with the sum calculated on DB read
  201. $data = $this->serialize($data);
  202. if (!$this->cache_sums[$key] || $this->cache_sums[$key] != md5($data)) {
  203. $this->write_record($key, $data);
  204. }
  205. }
  206. }
  207. if ($this->index_changed) {
  208. $this->write_index();
  209. }
  210. // reset internal cache index, thanks to this we can force index reload
  211. $this->index = null;
  212. $this->index_changed = false;
  213. $this->cache = array();
  214. $this->cache_sums = array();
  215. $this->cache_changes = array();
  216. }
  217. /**
  218. * Reads cache entry.
  219. *
  220. * @param string $key Cache key name
  221. * @param boolean $nostore Enable to skip in-memory store
  222. *
  223. * @return mixed Cached value
  224. */
  225. private function read_record($key, $nostore=false)
  226. {
  227. if (!$this->db) {
  228. return null;
  229. }
  230. if ($this->type != 'db') {
  231. $this->load_index();
  232. // Consistency check (#1490390)
  233. if (!in_array($key, $this->index)) {
  234. // we always check if the key exist in the index
  235. // to have data in consistent state. Keeping the index consistent
  236. // is needed for keys delete operation when we delete all keys or by prefix.
  237. }
  238. else {
  239. $ckey = $this->ckey($key);
  240. if ($this->type == 'memcache') {
  241. $data = $this->db->get($ckey);
  242. }
  243. else if ($this->type == 'apc') {
  244. $data = apc_fetch($ckey);
  245. }
  246. if ($this->debug) {
  247. $this->debug('get', $ckey, $data);
  248. }
  249. }
  250. if ($data) {
  251. $md5sum = md5($data);
  252. $data = $this->unserialize($data);
  253. if ($nostore) {
  254. return $data;
  255. }
  256. $this->cache_sums[$key] = $md5sum;
  257. $this->cache[$key] = $data;
  258. }
  259. else {
  260. $this->cache[$key] = null;
  261. }
  262. }
  263. else {
  264. $sql_result = $this->db->limitquery(
  265. "SELECT `data`, `cache_key`".
  266. " FROM {$this->table}" .
  267. " WHERE `cache_key` = ?".
  268. // for better performance we allow more records for one key
  269. // get the newer one
  270. " ORDER BY `created` DESC",
  271. 0, 1, $this->prefix . '.' . $key);
  272. if ($sql_arr = $this->db->fetch_assoc($sql_result)) {
  273. $md5sum = $sql_arr['data'] ? md5($sql_arr['data']) : null;
  274. if ($sql_arr['data']) {
  275. $data = $this->unserialize($sql_arr['data']);
  276. }
  277. if ($nostore) {
  278. return $data;
  279. }
  280. $this->cache[$key] = $data;
  281. $this->cache_sums[$key] = $md5sum;
  282. }
  283. else {
  284. $this->cache[$key] = null;
  285. }
  286. }
  287. return $this->cache[$key];
  288. }
  289. /**
  290. * Writes single cache record into DB.
  291. *
  292. * @param string $key Cache key name
  293. * @param mixed $data Serialized cache data
  294. *
  295. * @param boolean True on success, False on failure
  296. */
  297. private function write_record($key, $data)
  298. {
  299. if (!$this->db) {
  300. return false;
  301. }
  302. // don't attempt to write too big data sets
  303. if (strlen($data) > $this->max_packet_size()) {
  304. trigger_error("rcube_cache: max_packet_size ($this->max_packet) exceeded for key $key. Tried to write " . strlen($data) . " bytes", E_USER_WARNING);
  305. return false;
  306. }
  307. if ($this->type == 'memcache' || $this->type == 'apc') {
  308. $result = $this->add_record($this->ckey($key), $data);
  309. // make sure index will be updated
  310. if ($result) {
  311. if (!array_key_exists($key, $this->cache_sums)) {
  312. $this->cache_sums[$key] = true;
  313. }
  314. $this->load_index();
  315. if (!$this->index_changed && !in_array($key, $this->index)) {
  316. $this->index_changed = true;
  317. }
  318. }
  319. return $result;
  320. }
  321. $key_exists = array_key_exists($key, $this->cache_sums);
  322. $key = $this->prefix . '.' . $key;
  323. // Remove NULL rows (here we don't need to check if the record exist)
  324. if ($data == 'N;') {
  325. $this->db->query("DELETE FROM {$this->table} WHERE `cache_key` = ?", $key);
  326. return true;
  327. }
  328. // update existing cache record
  329. if ($key_exists) {
  330. $result = $this->db->query(
  331. "UPDATE {$this->table}" .
  332. " SET `created` = " . $this->db->now() .
  333. ", `expires` = " . ($this->ttl ? $this->db->now($this->ttl) : 'NULL') .
  334. ", `data` = ?".
  335. " WHERE `cache_key` = ?",
  336. $data, $key);
  337. }
  338. // add new cache record
  339. else {
  340. // for better performance we allow more records for one key
  341. // so, no need to check if record exist (see rcube_cache::read_record())
  342. $result = $this->db->query(
  343. "INSERT INTO {$this->table}".
  344. " (`created`, `expires`, `cache_key`, `data`)".
  345. " VALUES (".$this->db->now().", " . ($this->ttl ? $this->db->now($this->ttl) : 'NULL') . ", ?, ?)",
  346. $key, $data);
  347. }
  348. return $this->db->affected_rows($result);
  349. }
  350. /**
  351. * Deletes the cache record(s).
  352. *
  353. * @param string $key Cache key name or pattern
  354. * @param boolean $prefix_mode Enable it to clear all keys starting
  355. * with prefix specified in $key
  356. */
  357. private function remove_record($key=null, $prefix_mode=false)
  358. {
  359. if (!$this->db) {
  360. return;
  361. }
  362. if ($this->type != 'db') {
  363. $this->load_index();
  364. // Remove all keys
  365. if ($key === null) {
  366. foreach ($this->index as $key) {
  367. $this->delete_record($this->ckey($key));
  368. }
  369. $this->index = array();
  370. }
  371. // Remove keys by name prefix
  372. else if ($prefix_mode) {
  373. foreach ($this->index as $idx => $k) {
  374. if (strpos($k, $key) === 0) {
  375. $this->delete_record($this->ckey($k));
  376. unset($this->index[$idx]);
  377. }
  378. }
  379. }
  380. // Remove one key by name
  381. else {
  382. $this->delete_record($this->ckey($key));
  383. if (($idx = array_search($key, $this->index)) !== false) {
  384. unset($this->index[$idx]);
  385. }
  386. }
  387. $this->index_changed = true;
  388. return;
  389. }
  390. // Remove all keys (in specified cache)
  391. if ($key === null) {
  392. $where = " WHERE `cache_key` LIKE " . $this->db->quote($this->prefix.'.%');
  393. }
  394. // Remove keys by name prefix
  395. else if ($prefix_mode) {
  396. $where = " WHERE `cache_key` LIKE " . $this->db->quote($this->prefix.'.'.$key.'%');
  397. }
  398. // Remove one key by name
  399. else {
  400. $where = " WHERE `cache_key` = " . $this->db->quote($this->prefix.'.'.$key);
  401. }
  402. $this->db->query("DELETE FROM " . $this->table . $where);
  403. }
  404. /**
  405. * Adds entry into memcache/apc DB.
  406. *
  407. * @param string $key Cache internal key name
  408. * @param mixed $data Serialized cache data
  409. *
  410. * @param boolean True on success, False on failure
  411. */
  412. private function add_record($key, $data)
  413. {
  414. if ($this->type == 'memcache') {
  415. $result = $this->db->replace($key, $data, MEMCACHE_COMPRESSED, $this->ttl);
  416. if (!$result) {
  417. $result = $this->db->set($key, $data, MEMCACHE_COMPRESSED, $this->ttl);
  418. }
  419. }
  420. else if ($this->type == 'apc') {
  421. if (apc_exists($key)) {
  422. apc_delete($key);
  423. }
  424. $result = apc_store($key, $data, $this->ttl);
  425. }
  426. if ($this->debug) {
  427. $this->debug('set', $key, $data, $result);
  428. }
  429. return $result;
  430. }
  431. /**
  432. * Deletes entry from memcache/apc DB.
  433. *
  434. * @param string $key Cache internal key name
  435. *
  436. * @param boolean True on success, False on failure
  437. */
  438. private function delete_record($key)
  439. {
  440. if ($this->type == 'memcache') {
  441. // #1488592: use 2nd argument
  442. $result = $this->db->delete($key, 0);
  443. }
  444. else {
  445. $result = apc_delete($key);
  446. }
  447. if ($this->debug) {
  448. $this->debug('delete', $key, null, $result);
  449. }
  450. return $result;
  451. }
  452. /**
  453. * Writes the index entry into memcache/apc DB.
  454. */
  455. private function write_index()
  456. {
  457. if (!$this->db || $this->type == 'db') {
  458. return;
  459. }
  460. $this->load_index();
  461. // Make sure index contains new keys
  462. foreach ($this->cache as $key => $value) {
  463. if ($value !== null && !in_array($key, $this->index)) {
  464. $this->index[] = $key;
  465. }
  466. }
  467. // new keys added using self::write()
  468. foreach ($this->cache_sums as $key => $value) {
  469. if ($value === true && !in_array($key, $this->index)) {
  470. $this->index[] = $key;
  471. }
  472. }
  473. $data = serialize($this->index);
  474. $this->add_record($this->ikey(), $data);
  475. }
  476. /**
  477. * Gets the index entry from memcache/apc DB.
  478. */
  479. private function load_index()
  480. {
  481. if (!$this->db || $this->type == 'db') {
  482. return;
  483. }
  484. if ($this->index !== null) {
  485. return;
  486. }
  487. $index_key = $this->ikey();
  488. if ($this->type == 'memcache') {
  489. $data = $this->db->get($index_key);
  490. }
  491. else if ($this->type == 'apc') {
  492. $data = apc_fetch($index_key);
  493. }
  494. if ($this->debug) {
  495. $this->debug('get', $index_key, $data);
  496. }
  497. $this->index = $data ? unserialize($data) : array();
  498. }
  499. /**
  500. * Creates cache key name (for memcache and apc)
  501. *
  502. * @param string $key Cache key name
  503. *
  504. * @return string Cache key
  505. */
  506. private function ckey($key)
  507. {
  508. return $this->prefix . ':' . $key;
  509. }
  510. /**
  511. * Creates index cache key name (for memcache and apc)
  512. *
  513. * @return string Cache key
  514. */
  515. private function ikey()
  516. {
  517. // This way each cache will have its own index
  518. return $this->prefix . 'INDEX';
  519. }
  520. /**
  521. * Serializes data for storing
  522. */
  523. private function serialize($data)
  524. {
  525. if ($this->type == 'db') {
  526. return $this->db->encode($data, $this->packed);
  527. }
  528. return $this->packed ? serialize($data) : $data;
  529. }
  530. /**
  531. * Unserializes serialized data
  532. */
  533. private function unserialize($data)
  534. {
  535. if ($this->type == 'db') {
  536. return $this->db->decode($data, $this->packed);
  537. }
  538. return $this->packed ? @unserialize($data) : $data;
  539. }
  540. /**
  541. * Determine the maximum size for cache data to be written
  542. */
  543. private function max_packet_size()
  544. {
  545. if ($this->max_packet < 0) {
  546. $this->max_packet = 2097152; // default/max is 2 MB
  547. if ($this->type == 'db') {
  548. if ($value = $this->db->get_variable('max_allowed_packet', $this->max_packet)) {
  549. $this->max_packet = $value;
  550. }
  551. $this->max_packet -= 2000;
  552. }
  553. else if ($this->type == 'memcache') {
  554. if ($stats = $this->db->getStats()) {
  555. $remaining = $stats['limit_maxbytes'] - $stats['bytes'];
  556. $this->max_packet = min($remaining / 5, $this->max_packet);
  557. }
  558. }
  559. else if ($this->type == 'apc' && function_exists('apc_sma_info')) {
  560. if ($stats = apc_sma_info()) {
  561. $this->max_packet = min($stats['avail_mem'] / 5, $this->max_packet);
  562. }
  563. }
  564. }
  565. return $this->max_packet;
  566. }
  567. /**
  568. * Write memcache/apc debug info to the log
  569. */
  570. private function debug($type, $key, $data = null, $result = null)
  571. {
  572. $line = strtoupper($type) . ' ' . $key;
  573. if ($data !== null) {
  574. $line .= ' ' . ($this->packed ? $data : serialize($data));
  575. }
  576. rcube::debug($this->type, $line, $result);
  577. }
  578. }