MemcachedEngine.php 9.6 KB

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