3 * StatusNet - the distributed open-source microblogging tool
4 * Copyright (C) 2009, StatusNet, Inc.
6 * Plugin to implement cache interface for memcache
10 * This program is free software: you can redistribute it and/or modify
11 * it under the terms of the GNU Affero General Public License as published by
12 * the Free Software Foundation, either version 3 of the License, or
13 * (at your option) any later version.
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU Affero General Public License for more details.
20 * You should have received a copy of the GNU Affero General Public License
21 * along with this program. If not, see <http://www.gnu.org/licenses/>.
25 * @author Evan Prodromou <evan@status.net>
26 * @copyright 2009 StatusNet, Inc.
27 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
28 * @link http://status.net/
31 if (!defined('STATUSNET')) {
32 // This check helps protect against security problems;
33 // your code file can't be executed directly from the web.
38 * A plugin to use memcache for the cache interface
40 * This used to be encoded as config-variable options in the core code;
41 * it's now broken out to a separate plugin. The same interface can be
42 * implemented by other plugins.
46 * @author Evan Prodromou <evan@status.net>
47 * @copyright 2009 StatusNet, Inc.
48 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
49 * @link http://status.net/
52 class MemcachePlugin extends Plugin
54 static $cacheInitialized = false;
56 private $_conn = null;
57 public $servers = array('127.0.0.1;11211');
59 public $compressThreshold = 20480;
60 public $compressMinSaving = 0.2;
62 public $persistent = null;
64 public $defaultExpiry = 86400; // 24h
67 * Initialize the plugin
69 * Note that onStartCacheGet() may have been called before this!
71 * @return boolean flag value
74 function onInitializePlugin()
76 if (self::$cacheInitialized) {
77 $this->persistent = true;
79 // If we're a parent command-line process we need
80 // to be able to close out the connection after
81 // forking, so disable persistence.
83 // We'll turn it back on again the second time
84 // through which will either be in a child process,
85 // or a single-process script which is switching
87 $this->persistent = (php_sapi_name() == 'cli') ? false : true;
90 self::$cacheInitialized = true;
95 * Get a value associated with a key
97 * The value should have been set previously.
99 * @param string &$key in; Lookup key
100 * @param mixed &$value out; value associated with key
102 * @return boolean hook success
105 function onStartCacheGet(&$key, &$value)
107 $this->_ensureConn();
108 $value = $this->_conn->get($key);
109 Event::handle('EndCacheGet', array($key, &$value));
114 * Associate a value with a key
116 * @param string &$key in; Key to use for lookups
117 * @param mixed &$value in; Value to associate
118 * @param integer &$flag in; Flag empty or Cache::COMPRESSED
119 * @param integer &$expiry in; Expiry (passed through to Memcache)
120 * @param boolean &$success out; Whether the set was successful
122 * @return boolean hook success
125 function onStartCacheSet(&$key, &$value, &$flag, &$expiry, &$success)
127 $this->_ensureConn();
128 if ($expiry === null) {
129 $expiry = $this->defaultExpiry;
131 $success = $this->_conn->set($key, $value, $this->flag(intval($flag)), $expiry);
132 Event::handle('EndCacheSet', array($key, $value, $flag,
138 * Atomically increment an existing numeric key value.
139 * Existing expiration time will not be changed.
141 * @param string &$key in; Key to use for lookups
142 * @param int &$step in; Amount to increment (default 1)
143 * @param mixed &$value out; Incremented value, or false if key not set.
145 * @return boolean hook success
147 function onStartCacheIncrement(&$key, &$step, &$value)
149 $this->_ensureConn();
150 $value = $this->_conn->increment($key, $step);
151 Event::handle('EndCacheIncrement', array($key, $step, $value));
156 * Delete a value associated with a key
158 * @param string &$key in; Key to lookup
159 * @param boolean &$success out; whether it worked
161 * @return boolean hook success
164 function onStartCacheDelete(&$key, &$success)
166 $this->_ensureConn();
167 $success = $this->_conn->delete($key);
168 Event::handle('EndCacheDelete', array($key));
172 function onStartCacheReconnect(&$success)
174 if (empty($this->_conn)) {
178 if ($this->persistent) {
179 common_log(LOG_ERR, "Cannot close persistent memcached connection");
182 common_log(LOG_INFO, "Closing memcached connection");
183 $success = $this->_conn->close();
190 * Ensure that a connection exists
192 * Checks the instance $_conn variable and connects
198 private function _ensureConn()
200 if (empty($this->_conn)) {
201 $this->_conn = new Memcache();
203 if (is_array($this->servers)) {
204 $servers = $this->servers;
206 $servers = array($this->servers);
208 foreach ($servers as $server) {
209 if (strpos($server, ';') !== false) {
210 list($host, $port) = explode(';', $server);
216 $this->_conn->addServer($host, $port, $this->persistent);
219 // Compress items stored in the cache if they're over threshold in size
220 // (default 2KiB) and the compression would save more than min savings
221 // ratio (default 0.2).
223 // Allows the cache to store objects larger than 1MB (if they
224 // compress to less than 1MB), and improves cache memory efficiency.
226 $this->_conn->setCompressThreshold($this->compressThreshold,
227 $this->compressMinSaving);
232 * Translate general flags to Memcached-specific flags
236 protected function flag($flag)
239 if ($flag & Cache::COMPRESSED == Cache::COMPRESSED) {
240 $out |= MEMCACHE_COMPRESSED;
245 function onPluginVersion(&$versions)
247 $versions[] = array('name' => 'Memcache',
248 'version' => STATUSNET_VERSION,
249 'author' => 'Evan Prodromou, Craig Andrews',
250 'homepage' => 'http://status.net/wiki/Plugin:Memcache',
252 _m('Use <a href="http://memcached.org/">Memcached</a> to cache query results.'));