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