]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/Memcache/MemcachePlugin.php
Opps, PEAR sucks. Need to call find() before fetch() ... :-(
[quix0rs-gnu-social.git] / plugins / Memcache / 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 class MemcachePlugin extends Plugin
52 {
53     static $cacheInitialized = false;
54
55     private $_conn  = null;
56     public $servers = array('127.0.0.1;11211');
57
58     public $compressThreshold = 20480;
59     public $compressMinSaving = 0.2;
60
61     public $persistent = null;
62
63     public $defaultExpiry = 86400; // 24h
64
65     /**
66      * Initialize the plugin
67      *
68      * Note that onStartCacheGet() may have been called before this!
69      *
70      * @return boolean flag value
71      */
72     function onInitializePlugin()
73     {
74         if (self::$cacheInitialized) {
75             $this->persistent = true;
76         } else {
77             // If we're a parent command-line process we need
78             // to be able to close out the connection after
79             // forking, so disable persistence.
80             //
81             // We'll turn it back on again the second time
82             // through which will either be in a child process,
83             // or a single-process script which is switching
84             // configurations.
85             $this->persistent = (php_sapi_name() == 'cli') ? false : true;
86         }
87         $this->_ensureConn();
88         self::$cacheInitialized = true;
89         return true;
90     }
91
92     /**
93      * Get a value associated with a key
94      *
95      * The value should have been set previously.
96      *
97      * @param string &$key   in; Lookup key
98      * @param mixed  &$value out; value associated with key
99      *
100      * @return boolean hook success
101      */
102     function onStartCacheGet(&$key, &$value)
103     {
104         $this->_ensureConn();
105         $value = $this->_conn->get($key);
106         Event::handle('EndCacheGet', array($key, &$value));
107         return false;
108     }
109
110     /**
111      * Associate a value with a key
112      *
113      * @param string  &$key     in; Key to use for lookups
114      * @param mixed   &$value   in; Value to associate
115      * @param integer &$flag    in; Flag empty or Cache::COMPRESSED
116      * @param integer &$expiry  in; Expiry (passed through to Memcache)
117      * @param boolean &$success out; Whether the set was successful
118      *
119      * @return boolean hook success
120      */
121     function onStartCacheSet(&$key, &$value, &$flag, &$expiry, &$success)
122     {
123         $this->_ensureConn();
124         if ($expiry === null) {
125             $expiry = $this->defaultExpiry;
126         }
127         $success = $this->_conn->set($key, $value, $this->flag(intval($flag)), $expiry);
128         Event::handle('EndCacheSet', array($key, $value, $flag,
129                                            $expiry));
130         return false;
131     }
132
133     /**
134      * Atomically increment an existing numeric key value.
135      * Existing expiration time will not be changed.
136      *
137      * @param string &$key    in; Key to use for lookups
138      * @param int    &$step   in; Amount to increment (default 1)
139      * @param mixed  &$value  out; Incremented value, or false if key not set.
140      *
141      * @return boolean hook success
142      */
143     function onStartCacheIncrement(&$key, &$step, &$value)
144     {
145         $this->_ensureConn();
146         $value = $this->_conn->increment($key, $step);
147         Event::handle('EndCacheIncrement', array($key, $step, $value));
148         return false;
149     }
150
151     /**
152      * Delete a value associated with a key
153      *
154      * @param string  &$key     in; Key to lookup
155      * @param boolean &$success out; whether it worked
156      *
157      * @return boolean hook success
158      */
159     function onStartCacheDelete(&$key, &$success)
160     {
161         $this->_ensureConn();
162         $success = $this->_conn->delete($key);
163         Event::handle('EndCacheDelete', array($key));
164         return false;
165     }
166
167     function onStartCacheReconnect(&$success)
168     {
169         if (empty($this->_conn)) {
170             // nothing to do
171             return true;
172         }
173         if ($this->persistent) {
174             common_log(LOG_ERR, "Cannot close persistent memcached connection");
175             $success = false;
176         } else {
177             common_log(LOG_INFO, "Closing memcached connection");
178             $success = $this->_conn->close();
179             $this->_conn = null;
180         }
181         return false;
182     }
183
184     /**
185      * Ensure that a connection exists
186      *
187      * Checks the instance $_conn variable and connects
188      * if it is empty.
189      *
190      * @return void
191      */
192     private function _ensureConn()
193     {
194         if (empty($this->_conn)) {
195             $this->_conn = new Memcache();
196
197             if (is_array($this->servers)) {
198                 $servers = $this->servers;
199             } else {
200                 $servers = array($this->servers);
201             }
202             foreach ($servers as $server) {
203                 if (strpos($server, ';') !== false) {
204                     list($host, $port) = explode(';', $server);
205                 } else {
206                     $host = $server;
207                     $port = 11211;
208                 }
209
210                 $this->_conn->addServer($host, $port, $this->persistent);
211             }
212
213             // Compress items stored in the cache if they're over threshold in size
214             // (default 2KiB) and the compression would save more than min savings
215             // ratio (default 0.2).
216
217             // Allows the cache to store objects larger than 1MB (if they
218             // compress to less than 1MB), and improves cache memory efficiency.
219
220             $this->_conn->setCompressThreshold($this->compressThreshold,
221                                                $this->compressMinSaving);
222         }
223     }
224
225     /**
226      * Translate general flags to Memcached-specific flags
227      * @param int $flag
228      * @return int
229      */
230     protected function flag($flag)
231     {
232         $out = 0;
233         if ($flag & Cache::COMPRESSED == Cache::COMPRESSED) {
234             $out |= MEMCACHE_COMPRESSED;
235         }
236         return $out;
237     }
238
239     function onPluginVersion(array &$versions)
240     {
241         $versions[] = array('name' => 'Memcache',
242                             'version' => GNUSOCIAL_VERSION,
243                             'author' => 'Evan Prodromou, Craig Andrews',
244                             'homepage' => 'http://status.net/wiki/Plugin:Memcache',
245                             'rawdescription' =>
246                             // TRANS: Plugin description.
247                             _m('Use <a href="http://memcached.org/">Memcached</a> to cache query results.'));
248         return true;
249     }
250 }