MemcachedEngine.php 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  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. if (defined('Memcached::HAVE_MSGPACK') && Memcached::HAVE_MSGPACK) {
  79. $this->_serializers['msgpack'] = Memcached::SERIALIZER_MSGPACK;
  80. }
  81. $settings += array(
  82. 'engine' => 'Memcached',
  83. 'servers' => array('127.0.0.1'),
  84. 'compress' => false,
  85. 'persistent' => false,
  86. 'login' => null,
  87. 'password' => null,
  88. 'serialize' => 'php'
  89. );
  90. parent::init($settings);
  91. if (!is_array($this->settings['servers'])) {
  92. $this->settings['servers'] = array($this->settings['servers']);
  93. }
  94. if (isset($this->_Memcached)) {
  95. return true;
  96. }
  97. $this->_Memcached = new Memcached($this->settings['persistent'] ? (string)$this->settings['persistent'] : null);
  98. $this->_setOptions();
  99. if (count($this->_Memcached->getServerList())) {
  100. return true;
  101. }
  102. $servers = array();
  103. foreach ($this->settings['servers'] as $server) {
  104. $servers[] = $this->_parseServerString($server);
  105. }
  106. if (!$this->_Memcached->addServers($servers)) {
  107. return false;
  108. }
  109. if ($this->settings['login'] !== null && $this->settings['password'] !== null) {
  110. if (!method_exists($this->_Memcached, 'setSaslAuthData')) {
  111. throw new CacheException(
  112. __d('cake_dev', 'Memcached extension is not build with SASL support')
  113. );
  114. }
  115. $this->_Memcached->setSaslAuthData($this->settings['login'], $this->settings['password']);
  116. }
  117. return true;
  118. }
  119. /**
  120. * Settings the memcached instance
  121. *
  122. * @throws CacheException when the Memcached extension is not built with the desired serializer engine
  123. */
  124. protected function _setOptions() {
  125. $this->_Memcached->setOption(Memcached::OPT_LIBKETAMA_COMPATIBLE, true);
  126. $serializer = strtolower($this->settings['serialize']);
  127. if (!isset($this->_serializers[$serializer])) {
  128. throw new CacheException(
  129. __d('cake_dev', '%s is not a valid serializer engine for Memcached', $serializer)
  130. );
  131. }
  132. if ($serializer !== 'php' && !constant('Memcached::HAVE_' . strtoupper($serializer))) {
  133. throw new CacheException(
  134. __d('cake_dev', 'Memcached extension is not compiled with %s support', $serializer)
  135. );
  136. }
  137. $this->_Memcached->setOption(Memcached::OPT_SERIALIZER, $this->_serializers[$serializer]);
  138. // Check for Amazon ElastiCache instance
  139. if (defined('Memcached::OPT_CLIENT_MODE') && defined('Memcached::DYNAMIC_CLIENT_MODE')) {
  140. $this->_Memcached->setOption(Memcached::OPT_CLIENT_MODE, Memcached::DYNAMIC_CLIENT_MODE);
  141. }
  142. $this->_Memcached->setOption(Memcached::OPT_COMPRESSION, (bool)$this->settings['compress']);
  143. }
  144. /**
  145. * Parses the server address into the host/port. Handles both IPv6 and IPv4
  146. * addresses and Unix sockets
  147. *
  148. * @param string $server The server address string.
  149. * @return array Array containing host, port
  150. */
  151. protected function _parseServerString($server) {
  152. if ($server[0] === 'u') {
  153. return array($server, 0);
  154. }
  155. if (substr($server, 0, 1) === '[') {
  156. $position = strpos($server, ']:');
  157. if ($position !== false) {
  158. $position++;
  159. }
  160. } else {
  161. $position = strpos($server, ':');
  162. }
  163. $port = 11211;
  164. $host = $server;
  165. if ($position !== false) {
  166. $host = substr($server, 0, $position);
  167. $port = substr($server, $position + 1);
  168. }
  169. return array($host, (int)$port);
  170. }
  171. /**
  172. * Write data for key into cache. When using memcached as your cache engine
  173. * remember that the Memcached pecl extension does not support cache expiry times greater
  174. * than 30 days in the future. Any duration greater than 30 days will be treated as never expiring.
  175. *
  176. * @param string $key Identifier for the data
  177. * @param mixed $value Data to be cached
  178. * @param integer $duration How long to cache the data, in seconds
  179. * @return boolean True if the data was successfully cached, false on failure
  180. * @see http://php.net/manual/en/memcache.set.php
  181. */
  182. public function write($key, $value, $duration) {
  183. if ($duration > 30 * DAY) {
  184. $duration = 0;
  185. }
  186. return $this->_Memcached->set($key, $value, $duration);
  187. }
  188. /**
  189. * Read a key from the cache
  190. *
  191. * @param string $key Identifier for the data
  192. * @return mixed The cached data, or false if the data doesn't exist, has expired, or if there was an error fetching it
  193. */
  194. public function read($key) {
  195. return $this->_Memcached->get($key);
  196. }
  197. /**
  198. * Increments the value of an integer cached key
  199. *
  200. * @param string $key Identifier for the data
  201. * @param integer $offset How much to increment
  202. * @return New incremented value, false otherwise
  203. * @throws CacheException when you try to increment with compress = true
  204. */
  205. public function increment($key, $offset = 1) {
  206. return $this->_Memcached->increment($key, $offset);
  207. }
  208. /**
  209. * Decrements the value of an integer cached key
  210. *
  211. * @param string $key Identifier for the data
  212. * @param integer $offset How much to subtract
  213. * @return New decremented value, false otherwise
  214. * @throws CacheException when you try to decrement with compress = true
  215. */
  216. public function decrement($key, $offset = 1) {
  217. return $this->_Memcached->decrement($key, $offset);
  218. }
  219. /**
  220. * Delete a key from the cache
  221. *
  222. * @param string $key Identifier for the data
  223. * @return boolean True if the value was successfully deleted, false if it didn't exist or couldn't be removed
  224. */
  225. public function delete($key) {
  226. return $this->_Memcached->delete($key);
  227. }
  228. /**
  229. * Delete all keys from the cache
  230. *
  231. * @param boolean $check
  232. * @return boolean True if the cache was successfully cleared, false otherwise
  233. */
  234. public function clear($check) {
  235. if ($check) {
  236. return true;
  237. }
  238. $keys = $this->_Memcached->getAllKeys();
  239. foreach ($keys as $key) {
  240. if (strpos($key, $this->settings['prefix']) === 0) {
  241. $this->_Memcached->delete($key);
  242. }
  243. }
  244. return true;
  245. }
  246. /**
  247. * Returns the `group value` for each of the configured groups
  248. * If the group initial value was not found, then it initializes
  249. * the group accordingly.
  250. *
  251. * @return array
  252. */
  253. public function groups() {
  254. if (empty($this->_compiledGroupNames)) {
  255. foreach ($this->settings['groups'] as $group) {
  256. $this->_compiledGroupNames[] = $this->settings['prefix'] . $group;
  257. }
  258. }
  259. $groups = $this->_Memcached->getMulti($this->_compiledGroupNames);
  260. if (count($groups) !== count($this->settings['groups'])) {
  261. foreach ($this->_compiledGroupNames as $group) {
  262. if (!isset($groups[$group])) {
  263. $this->_Memcached->set($group, 1, 0);
  264. $groups[$group] = 1;
  265. }
  266. }
  267. ksort($groups);
  268. }
  269. $result = array();
  270. $groups = array_values($groups);
  271. foreach ($this->settings['groups'] as $i => $group) {
  272. $result[] = $group . $groups[$i];
  273. }
  274. return $result;
  275. }
  276. /**
  277. * Increments the group value to simulate deletion of all keys under a group
  278. * old values will remain in storage until they expire.
  279. *
  280. * @return boolean success
  281. */
  282. public function clearGroup($group) {
  283. return (bool)$this->_Memcached->increment($this->settings['prefix'] . $group);
  284. }
  285. }