MemcachedEngine.php 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * For full copyright and license information, please see the LICENSE.txt
  8. * Redistributions of files must retain the above copyright notice.
  9. *
  10. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  11. * @link http://cakephp.org CakePHP(tm) Project
  12. * @since CakePHP(tm) v 2.5.0
  13. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  14. */
  15. /**
  16. * Memcached storage engine for cache. Memcached has some limitations in the amount of
  17. * control you have over expire times far in the future. See MemcachedEngine::write() for
  18. * more information.
  19. *
  20. * Main advantage of this Memcached engine over the memcached engine is
  21. * support of binary protocol, and igbibnary serialization
  22. * (if memcached extension compiled with --enable-igbinary)
  23. * Compressed keys can also be incremented/decremented
  24. *
  25. * @package Cake.Cache.Engine
  26. */
  27. class MemcachedEngine extends CacheEngine {
  28. /**
  29. * memcached wrapper.
  30. *
  31. * @var Memcache
  32. */
  33. protected $_Memcached = null;
  34. /**
  35. * Settings
  36. *
  37. * - servers = string or array of memcached servers, default => 127.0.0.1. If an
  38. * array MemcacheEngine will use them as a pool.
  39. * - compress = boolean, default => false
  40. * - persistent = string The name of the persistent connection. All configurations using
  41. * the same persistent value will share a single underlying connection.
  42. * - serialize = string, default => php. The serializer engine used to serialize data.
  43. * Available engines are php, igbinary and json. Beside php, the memcached extension
  44. * must be compiled with the appropriate serializer support.
  45. *
  46. * @var array
  47. */
  48. public $settings = array();
  49. /**
  50. * List of available serializer engines
  51. *
  52. * Memcached must be compiled with json and igbinary support to use these engines
  53. *
  54. * @var array
  55. */
  56. protected $_serializers = array(
  57. 'igbinary' => Memcached::SERIALIZER_IGBINARY,
  58. 'json' => Memcached::SERIALIZER_JSON,
  59. 'php' => Memcached::SERIALIZER_PHP
  60. );
  61. /**
  62. * Initialize the Cache Engine
  63. *
  64. * Called automatically by the cache frontend
  65. * To reinitialize the settings call Cache::engine('EngineName', [optional] settings = array());
  66. *
  67. * @param array $settings array of setting for the engine
  68. * @return boolean True if the engine has been successfully initialized, false if not
  69. * @throws CacheException when you try use authentication without Memcached compiled with SASL support
  70. */
  71. public function init($settings = array()) {
  72. if (!class_exists('Memcached')) {
  73. return false;
  74. }
  75. if (!isset($settings['prefix'])) {
  76. $settings['prefix'] = Inflector::slug(APP_DIR) . '_';
  77. }
  78. $settings += array(
  79. 'engine' => 'Memcached',
  80. 'servers' => array('127.0.0.1'),
  81. 'compress' => false,
  82. 'persistent' => false,
  83. 'login' => null,
  84. 'password' => null,
  85. 'serialize' => 'php'
  86. );
  87. parent::init($settings);
  88. if (!is_array($this->settings['servers'])) {
  89. $this->settings['servers'] = array($this->settings['servers']);
  90. }
  91. if (isset($this->_Memcached)) {
  92. return true;
  93. }
  94. $this->_Memcached = new Memcached($this->settings['persistent'] ? (string)$this->settings['persistent'] : null);
  95. $this->_setOptions();
  96. if (count($this->_Memcached->getServerList())) {
  97. return true;
  98. }
  99. $servers = array();
  100. foreach ($this->settings['servers'] as $server) {
  101. $servers[] = $this->_parseServerString($server);
  102. }
  103. if (!$this->_Memcached->addServers($servers)) {
  104. return false;
  105. }
  106. if ($this->settings['login'] !== null && $this->settings['password'] !== null) {
  107. if (!method_exists($this->_Memcached, 'setSaslAuthData')) {
  108. throw new CacheException(
  109. __d('cake_dev', 'Memcached extension is not build with SASL support')
  110. );
  111. }
  112. $this->_Memcached->setSaslAuthData($this->settings['login'], $this->settings['password']);
  113. }
  114. return true;
  115. }
  116. /**
  117. * Settings the memcached instance
  118. *
  119. * @throws CacheException when the Memcached extension is not built with the desired serializer engine
  120. */
  121. protected function _setOptions() {
  122. $this->_Memcached->setOption(Memcached::OPT_LIBKETAMA_COMPATIBLE, true);
  123. $serializer = strtolower($this->settings['serialize']);
  124. if (!isset($this->_serializers[$serializer])) {
  125. throw new CacheException(
  126. __d('cake_dev', '%s is not a valid serializer engine for Memcached', $serializer)
  127. );
  128. }
  129. if ($serializer !== 'php' && !constant('Memcached::HAVE_' . strtoupper($serializer))) {
  130. throw new CacheException(
  131. __d('cake_dev', 'Memcached extension is not compiled with %s support', $serializer)
  132. );
  133. }
  134. $this->_Memcached->setOption(Memcached::OPT_SERIALIZER, $this->_serializers[$serializer]);
  135. // Check for Amazon ElastiCache instance
  136. if (defined('Memcached::OPT_CLIENT_MODE') && defined('Memcached::DYNAMIC_CLIENT_MODE')) {
  137. $this->_Memcached->setOption(Memcached::OPT_CLIENT_MODE, Memcached::DYNAMIC_CLIENT_MODE);
  138. }
  139. $this->_Memcached->setOption(Memcached::OPT_COMPRESSION, (bool)$this->settings['compress']);
  140. }
  141. /**
  142. * Parses the server address into the host/port. Handles both IPv6 and IPv4
  143. * addresses and Unix sockets
  144. *
  145. * @param string $server The server address string.
  146. * @return array Array containing host, port
  147. */
  148. protected function _parseServerString($server) {
  149. if ($server[0] === 'u') {
  150. return array($server, 0);
  151. }
  152. if (substr($server, 0, 1) === '[') {
  153. $position = strpos($server, ']:');
  154. if ($position !== false) {
  155. $position++;
  156. }
  157. } else {
  158. $position = strpos($server, ':');
  159. }
  160. $port = 11211;
  161. $host = $server;
  162. if ($position !== false) {
  163. $host = substr($server, 0, $position);
  164. $port = substr($server, $position + 1);
  165. }
  166. return array($host, (int)$port);
  167. }
  168. /**
  169. * Write data for key into cache. When using memcached as your cache engine
  170. * remember that the Memcached pecl extension does not support cache expiry times greater
  171. * than 30 days in the future. Any duration greater than 30 days will be treated as never expiring.
  172. *
  173. * @param string $key Identifier for the data
  174. * @param mixed $value Data to be cached
  175. * @param integer $duration How long to cache the data, in seconds
  176. * @return boolean True if the data was successfully cached, false on failure
  177. * @see http://php.net/manual/en/memcache.set.php
  178. */
  179. public function write($key, $value, $duration) {
  180. if ($duration > 30 * DAY) {
  181. $duration = 0;
  182. }
  183. return $this->_Memcached->set($key, $value, $duration);
  184. }
  185. /**
  186. * Read a key from the cache
  187. *
  188. * @param string $key Identifier for the data
  189. * @return mixed The cached data, or false if the data doesn't exist, has expired, or if there was an error fetching it
  190. */
  191. public function read($key) {
  192. return $this->_Memcached->get($key);
  193. }
  194. /**
  195. * Increments the value of an integer cached key
  196. *
  197. * @param string $key Identifier for the data
  198. * @param integer $offset How much to increment
  199. * @return New incremented value, false otherwise
  200. * @throws CacheException when you try to increment with compress = true
  201. */
  202. public function increment($key, $offset = 1) {
  203. return $this->_Memcached->increment($key, $offset);
  204. }
  205. /**
  206. * Decrements the value of an integer cached key
  207. *
  208. * @param string $key Identifier for the data
  209. * @param integer $offset How much to subtract
  210. * @return New decremented value, false otherwise
  211. * @throws CacheException when you try to decrement with compress = true
  212. */
  213. public function decrement($key, $offset = 1) {
  214. return $this->_Memcached->decrement($key, $offset);
  215. }
  216. /**
  217. * Delete a key from the cache
  218. *
  219. * @param string $key Identifier for the data
  220. * @return boolean True if the value was successfully deleted, false if it didn't exist or couldn't be removed
  221. */
  222. public function delete($key) {
  223. return $this->_Memcached->delete($key);
  224. }
  225. /**
  226. * Delete all keys from the cache
  227. *
  228. * @param boolean $check
  229. * @return boolean True if the cache was successfully cleared, false otherwise
  230. */
  231. public function clear($check) {
  232. if ($check) {
  233. return true;
  234. }
  235. $keys = $this->_Memcached->getAllKeys();
  236. foreach ($keys as $key) {
  237. if (strpos($key, $this->settings['prefix']) === 0) {
  238. $this->_Memcached->delete($key);
  239. }
  240. }
  241. return true;
  242. }
  243. /**
  244. * Returns the `group value` for each of the configured groups
  245. * If the group initial value was not found, then it initializes
  246. * the group accordingly.
  247. *
  248. * @return array
  249. */
  250. public function groups() {
  251. if (empty($this->_compiledGroupNames)) {
  252. foreach ($this->settings['groups'] as $group) {
  253. $this->_compiledGroupNames[] = $this->settings['prefix'] . $group;
  254. }
  255. }
  256. $groups = $this->_Memcached->getMulti($this->_compiledGroupNames);
  257. if (count($groups) !== count($this->settings['groups'])) {
  258. foreach ($this->_compiledGroupNames as $group) {
  259. if (!isset($groups[$group])) {
  260. $this->_Memcached->set($group, 1, 0);
  261. $groups[$group] = 1;
  262. }
  263. }
  264. ksort($groups);
  265. }
  266. $result = array();
  267. $groups = array_values($groups);
  268. foreach ($this->settings['groups'] as $i => $group) {
  269. $result[] = $group . $groups[$i];
  270. }
  271. return $result;
  272. }
  273. /**
  274. * Increments the group value to simulate deletion of all keys under a group
  275. * old values will remain in storage until they expire.
  276. *
  277. * @return boolean success
  278. */
  279. public function clearGroup($group) {
  280. return (bool)$this->_Memcached->increment($this->settings['prefix'] . $group);
  281. }
  282. }