MemcachePlugin.php 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  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. if (!defined('STATUSNET')) {
  31. // This check helps protect against security problems;
  32. // your code file can't be executed directly from the web.
  33. exit(1);
  34. }
  35. /**
  36. * A plugin to use memcache for the cache interface
  37. *
  38. * This used to be encoded as config-variable options in the core code;
  39. * it's now broken out to a separate plugin. The same interface can be
  40. * implemented by other plugins.
  41. *
  42. * @category Cache
  43. * @package StatusNet
  44. * @author Evan Prodromou <evan@status.net>
  45. * @copyright 2009 StatusNet, Inc.
  46. * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
  47. * @link http://status.net/
  48. */
  49. class MemcachePlugin extends Plugin
  50. {
  51. static $cacheInitialized = false;
  52. private $_conn = null;
  53. public $servers = array('127.0.0.1;11211');
  54. public $compressThreshold = 20480;
  55. public $compressMinSaving = 0.2;
  56. public $persistent = null;
  57. public $defaultExpiry = 86400; // 24h
  58. /**
  59. * Initialize the plugin
  60. *
  61. * Note that onStartCacheGet() may have been called before this!
  62. *
  63. * @return boolean flag value
  64. */
  65. function onInitializePlugin()
  66. {
  67. if (self::$cacheInitialized) {
  68. $this->persistent = true;
  69. } else {
  70. // If we're a parent command-line process we need
  71. // to be able to close out the connection after
  72. // forking, so disable persistence.
  73. //
  74. // We'll turn it back on again the second time
  75. // through which will either be in a child process,
  76. // or a single-process script which is switching
  77. // configurations.
  78. $this->persistent = (php_sapi_name() == 'cli') ? false : true;
  79. }
  80. $this->_ensureConn();
  81. self::$cacheInitialized = true;
  82. return true;
  83. }
  84. /**
  85. * Get a value associated with a key
  86. *
  87. * The value should have been set previously.
  88. *
  89. * @param string &$key in; Lookup key
  90. * @param mixed &$value out; value associated with key
  91. *
  92. * @return boolean hook success
  93. */
  94. function onStartCacheGet(&$key, &$value)
  95. {
  96. $this->_ensureConn();
  97. $value = $this->_conn->get($key);
  98. Event::handle('EndCacheGet', array($key, &$value));
  99. return false;
  100. }
  101. /**
  102. * Associate a value with a key
  103. *
  104. * @param string &$key in; Key to use for lookups
  105. * @param mixed &$value in; Value to associate
  106. * @param integer &$flag in; Flag empty or Cache::COMPRESSED
  107. * @param integer &$expiry in; Expiry (passed through to Memcache)
  108. * @param boolean &$success out; Whether the set was successful
  109. *
  110. * @return boolean hook success
  111. */
  112. function onStartCacheSet(&$key, &$value, &$flag, &$expiry, &$success)
  113. {
  114. $this->_ensureConn();
  115. if ($expiry === null) {
  116. $expiry = $this->defaultExpiry;
  117. }
  118. $success = $this->_conn->set($key, $value, $this->flag(intval($flag)), $expiry);
  119. Event::handle('EndCacheSet', array($key, $value, $flag,
  120. $expiry));
  121. return false;
  122. }
  123. /**
  124. * Atomically increment an existing numeric key value.
  125. * Existing expiration time will not be changed.
  126. *
  127. * @param string &$key in; Key to use for lookups
  128. * @param int &$step in; Amount to increment (default 1)
  129. * @param mixed &$value out; Incremented value, or false if key not set.
  130. *
  131. * @return boolean hook success
  132. */
  133. function onStartCacheIncrement(&$key, &$step, &$value)
  134. {
  135. $this->_ensureConn();
  136. $value = $this->_conn->increment($key, $step);
  137. Event::handle('EndCacheIncrement', array($key, $step, $value));
  138. return false;
  139. }
  140. /**
  141. * Delete a value associated with a key
  142. *
  143. * @param string &$key in; Key to lookup
  144. * @param boolean &$success out; whether it worked
  145. *
  146. * @return boolean hook success
  147. */
  148. function onStartCacheDelete(&$key, &$success)
  149. {
  150. $this->_ensureConn();
  151. $success = $this->_conn->delete($key);
  152. Event::handle('EndCacheDelete', array($key));
  153. return false;
  154. }
  155. function onStartCacheReconnect(&$success)
  156. {
  157. if (empty($this->_conn)) {
  158. // nothing to do
  159. return true;
  160. }
  161. if ($this->persistent) {
  162. common_log(LOG_ERR, "Cannot close persistent memcached connection");
  163. $success = false;
  164. } else {
  165. common_log(LOG_INFO, "Closing memcached connection");
  166. $success = $this->_conn->close();
  167. $this->_conn = null;
  168. }
  169. return false;
  170. }
  171. /**
  172. * Ensure that a connection exists
  173. *
  174. * Checks the instance $_conn variable and connects
  175. * if it is empty.
  176. *
  177. * @return void
  178. */
  179. private function _ensureConn()
  180. {
  181. if (empty($this->_conn)) {
  182. $this->_conn = new Memcache();
  183. if (is_array($this->servers)) {
  184. $servers = $this->servers;
  185. } else {
  186. $servers = array($this->servers);
  187. }
  188. foreach ($servers as $server) {
  189. if (strpos($server, ';') !== false) {
  190. list($host, $port) = explode(';', $server);
  191. } else {
  192. $host = $server;
  193. $port = 11211;
  194. }
  195. $this->_conn->addServer($host, $port, $this->persistent);
  196. }
  197. // Compress items stored in the cache if they're over threshold in size
  198. // (default 2KiB) and the compression would save more than min savings
  199. // ratio (default 0.2).
  200. // Allows the cache to store objects larger than 1MB (if they
  201. // compress to less than 1MB), and improves cache memory efficiency.
  202. $this->_conn->setCompressThreshold($this->compressThreshold,
  203. $this->compressMinSaving);
  204. }
  205. }
  206. /**
  207. * Translate general flags to Memcached-specific flags
  208. * @param int $flag
  209. * @return int
  210. */
  211. protected function flag($flag)
  212. {
  213. $out = 0;
  214. if ($flag & Cache::COMPRESSED == Cache::COMPRESSED) {
  215. $out |= MEMCACHE_COMPRESSED;
  216. }
  217. return $out;
  218. }
  219. function onPluginVersion(&$versions)
  220. {
  221. $versions[] = array('name' => 'Memcache',
  222. 'version' => GNUSOCIAL_VERSION,
  223. 'author' => 'Evan Prodromou, Craig Andrews',
  224. 'homepage' => 'http://status.net/wiki/Plugin:Memcache',
  225. 'rawdescription' =>
  226. // TRANS: Plugin description.
  227. _m('Use <a href="http://memcached.org/">Memcached</a> to cache query results.'));
  228. return true;
  229. }
  230. }