]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/MemcachePlugin.php
Merge branch 'master' of gitorious.org:statusnet/mainline into testing
[quix0rs-gnu-social.git] / plugins / MemcachePlugin.php
1 <?php
2 /**
3  * StatusNet - the distributed open-source microblogging tool
4  * Copyright (C) 2009, StatusNet, Inc.
5  *
6  * Plugin to implement cache interface for memcache
7  *
8  * PHP version 5
9  *
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.
14  *
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.
19  *
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/>.
22  *
23  * @category  Cache
24  * @package   StatusNet
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/
29  */
30
31 if (!defined('STATUSNET')) {
32     // This check helps protect against security problems;
33     // your code file can't be executed directly from the web.
34     exit(1);
35 }
36
37 /**
38  * A plugin to use memcache for the cache interface
39  *
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.
43  *
44  * @category  Cache
45  * @package   StatusNet
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/
50  */
51
52 class MemcachePlugin extends Plugin
53 {
54     static $cacheInitialized = false;
55
56     private $_conn  = null;
57     public $servers = array('127.0.0.1;11211');
58
59     public $compressThreshold = 20480;
60     public $compressMinSaving = 0.2;
61
62     public $persistent = null;
63
64     public $defaultExpiry = 86400; // 24h
65
66     /**
67      * Initialize the plugin
68      *
69      * Note that onStartCacheGet() may have been called before this!
70      *
71      * @return boolean flag value
72      */
73
74     function onInitializePlugin()
75     {
76         if (self::$cacheInitialized) {
77             $this->persistent = true;
78         } else {
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.
82             //
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
86             // configurations.
87             $this->persistent = (php_sapi_name() == 'cli') ? false : true;
88         }
89         $this->_ensureConn();
90         self::$cacheInitialized = true;
91         return true;
92     }
93
94     /**
95      * Get a value associated with a key
96      *
97      * The value should have been set previously.
98      *
99      * @param string &$key   in; Lookup key
100      * @param mixed  &$value out; value associated with key
101      *
102      * @return boolean hook success
103      */
104
105     function onStartCacheGet(&$key, &$value)
106     {
107         $this->_ensureConn();
108         $value = $this->_conn->get($key);
109         Event::handle('EndCacheGet', array($key, &$value));
110         return false;
111     }
112
113     /**
114      * Associate a value with a key
115      *
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
121      *
122      * @return boolean hook success
123      */
124
125     function onStartCacheSet(&$key, &$value, &$flag, &$expiry, &$success)
126     {
127         $this->_ensureConn();
128         if ($expiry === null) {
129             $expiry = $this->defaultExpiry;
130         }
131         $success = $this->_conn->set($key, $value, $this->flag(intval($flag)), $expiry);
132         Event::handle('EndCacheSet', array($key, $value, $flag,
133                                            $expiry));
134         return false;
135     }
136
137     /**
138      * Atomically increment an existing numeric key value.
139      * Existing expiration time will not be changed.
140      *
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.
144      *
145      * @return boolean hook success
146      */
147     function onStartCacheIncrement(&$key, &$step, &$value)
148     {
149         $this->_ensureConn();
150         $value = $this->_conn->increment($key, $step);
151         Event::handle('EndCacheIncrement', array($key, $step, $value));
152         return false;
153     }
154
155     /**
156      * Delete a value associated with a key
157      *
158      * @param string  &$key     in; Key to lookup
159      * @param boolean &$success out; whether it worked
160      *
161      * @return boolean hook success
162      */
163
164     function onStartCacheDelete(&$key, &$success)
165     {
166         $this->_ensureConn();
167         $success = $this->_conn->delete($key);
168         Event::handle('EndCacheDelete', array($key));
169         return false;
170     }
171
172     function onStartCacheReconnect(&$success)
173     {
174         if (empty($this->_conn)) {
175             // nothing to do
176             return true;
177         }
178         if ($this->persistent) {
179             common_log(LOG_ERR, "Cannot close persistent memcached connection");
180             $success = false;
181         } else {
182             common_log(LOG_INFO, "Closing memcached connection");
183             $success = $this->_conn->close();
184             $this->_conn = null;
185         }
186         return false;
187     }
188
189     /**
190      * Ensure that a connection exists
191      *
192      * Checks the instance $_conn variable and connects
193      * if it is empty.
194      *
195      * @return void
196      */
197
198     private function _ensureConn()
199     {
200         if (empty($this->_conn)) {
201             $this->_conn = new Memcache();
202
203             if (is_array($this->servers)) {
204                 $servers = $this->servers;
205             } else {
206                 $servers = array($this->servers);
207             }
208             foreach ($servers as $server) {
209                 if (strpos($server, ';') !== false) {
210                     list($host, $port) = explode(';', $server);
211                 } else {
212                     $host = $server;
213                     $port = 11211;
214                 }
215
216                 $this->_conn->addServer($host, $port, $this->persistent);
217             }
218
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).
222
223             // Allows the cache to store objects larger than 1MB (if they
224             // compress to less than 1MB), and improves cache memory efficiency.
225
226             $this->_conn->setCompressThreshold($this->compressThreshold,
227                                                $this->compressMinSaving);
228         }
229     }
230
231     /**
232      * Translate general flags to Memcached-specific flags
233      * @param int $flag
234      * @return int
235      */
236     protected function flag($flag)
237     {
238         $out = 0;
239         if ($flag & Cache::COMPRESSED == Cache::COMPRESSED) {
240             $out |= MEMCACHE_COMPRESSED;
241         }
242         return $out;
243     }
244
245     function onPluginVersion(&$versions)
246     {
247         $versions[] = array('name' => 'Memcache',
248                             'version' => STATUSNET_VERSION,
249                             'author' => 'Evan Prodromou, Craig Andrews',
250                             'homepage' => 'http://status.net/wiki/Plugin:Memcache',
251                             'rawdescription' =>
252                             _m('Use <a href="http://memcached.org/">Memcached</a> to cache query results.'));
253         return true;
254     }
255 }
256