MemcachedPlugin.php 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. <?php
  2. // This file is part of GNU social - https://www.gnu.org/software/social
  3. //
  4. // GNU social is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Affero General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // GNU social is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Affero General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Affero General Public License
  15. // along with GNU social. If not, see <http://www.gnu.org/licenses/>.
  16. /**
  17. * A plugin to use memcached for the interface with memcache
  18. *
  19. * @category Cache
  20. * @package GNUsocial
  21. * @author Evan Prodromou <evan@status.net>
  22. * @author Craig Andrews <candrews@integralblue.com>
  23. * @author Miguel Dantas <biodantas@gmail.com>
  24. * @copyright 2009, 2019 Free Software Foundation, Inc http://www.fsf.org
  25. * @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
  26. */
  27. defined('GNUSOCIAL') || die();
  28. /**
  29. * A plugin to use memcached for the cache interface
  30. *
  31. * This used to be encoded as config-variable options in the core code;
  32. * it's now broken out to a separate plugin. The same interface can be
  33. * implemented by other plugins.
  34. *
  35. * @copyright 2009, 2019 Free Software Foundation, Inc http://www.fsf.org
  36. * @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
  37. */
  38. class MemcachedPlugin extends Plugin
  39. {
  40. const PLUGIN_VERSION = '2.1.0';
  41. public static $cacheInitialized = false;
  42. public $servers = ['127.0.0.1'];
  43. public $defaultExpiry = 86400; // 24h
  44. protected $persistent = null;
  45. private $_conn = null;
  46. /**
  47. * Initialize the plugin
  48. *
  49. * Note that onStartCacheGet() may have been called before this!
  50. *
  51. * @return bool flag value
  52. */
  53. public function onInitializePlugin(): bool
  54. {
  55. if (self::$cacheInitialized) {
  56. $this->persistent = true;
  57. } else {
  58. // If we're a parent command-line process we need
  59. // to be able to close out the connection after
  60. // forking, so disable persistence.
  61. //
  62. // We'll turn it back on again the second time
  63. // through which will either be in a child process,
  64. // or a single-process script which is switching
  65. // configurations.
  66. $this->persistent = (php_sapi_name() == 'cli') ? false : true;
  67. }
  68. try {
  69. $this->_ensureConn();
  70. self::$cacheInitialized = true;
  71. } catch (MemcachedException $e) {
  72. common_log(LOG_ERR, 'Memcached encountered exception ' . get_class($e) . ': ' . $e->getMessage());
  73. }
  74. return true;
  75. }
  76. /**
  77. * Get a value associated with a key
  78. *
  79. * The value should have been set previously.
  80. *
  81. * @param string &$key in; Lookup key
  82. * @param mixed &$value out; value associated with key
  83. *
  84. * @return bool hook success
  85. */
  86. public function onStartCacheGet(&$key, &$value): bool
  87. {
  88. try {
  89. $this->_ensureConn();
  90. $value = $this->_conn->get($key);
  91. } catch (MemcachedException $e) {
  92. common_log(LOG_ERR, 'Memcached encountered exception ' . get_class($e) . ': ' . $e->getMessage());
  93. return true;
  94. }
  95. if ($value === false) {
  96. // If not found, let other plugins handle it
  97. return $this->_conn->getResultCode() === Memcached::RES_NOTFOUND;
  98. } else {
  99. return false;
  100. }
  101. }
  102. /**
  103. * Associate a value with a key
  104. *
  105. * @param string &$key in; Key to use for lookups
  106. * @param mixed &$value in; Value to associate
  107. * @param integer &$flag in; Flag empty or Memcached::OPT_COMPRESSION (translated by the `flag` method)
  108. * @param integer &$expiry in; Expiry (passed through to Memcache)
  109. * @param bool &$success out; Whether the set was successful
  110. *
  111. * @return bool hook success
  112. */
  113. public function onStartCacheSet(&$key, &$value, &$flag, &$expiry, &$success): bool
  114. {
  115. if ($expiry === null) {
  116. $expiry = $this->defaultExpiry;
  117. }
  118. try {
  119. $this->_ensureConn();
  120. if (!empty($flag)) {
  121. $this->_conn->setOption(Memcached::OPT_COMPRESSION, $flag);
  122. }
  123. $success = $this->_conn->set($key, $value, $expiry);
  124. } catch (MemcachedException $e) {
  125. common_log(LOG_ERR, 'Memcached encountered exception ' . get_class($e) . ': ' . $e->getMessage());
  126. return true;
  127. }
  128. return !$success;
  129. }
  130. /**
  131. * Atomically increment an existing numeric key value.
  132. * Existing expiration time will not be changed.
  133. *
  134. * @param string &$key in; Key to use for lookups
  135. * @param int &$step in; Amount to increment (default 1)
  136. * @param mixed &$value out; Incremented value, or false if key not set.
  137. *
  138. * @return bool hook success
  139. */
  140. public function onStartCacheIncrement(&$key, &$step, &$value): bool
  141. {
  142. try {
  143. $this->_ensureConn();
  144. $value = $this->_conn->increment($key, $step);
  145. } catch (MemcachedException $e) {
  146. common_log(LOG_ERR, 'Memcached encountered exception ' . get_class($e) . ': ' . $e->getMessage());
  147. return true;
  148. }
  149. if ($value === false) {
  150. // If not found, let other plugins handle it
  151. return $this->_conn->getResultCode() === Memcached::RES_NOTFOUND;
  152. } else {
  153. return false;
  154. }
  155. }
  156. /**
  157. * Delete a value associated with a key
  158. *
  159. * @param string &$key in; Key to lookup
  160. * @param bool &$success out; whether it worked
  161. *
  162. * @return bool hook success
  163. */
  164. public function onStartCacheDelete(&$key, &$success): bool
  165. {
  166. try {
  167. $this->_ensureConn();
  168. $success = $this->_conn->delete($key);
  169. } catch (MemcachedException $e) {
  170. common_log(LOG_ERR, 'Memcached encountered exception ' . get_class($e) . ': ' . $e->getMessage());
  171. return true;
  172. }
  173. return !$success;
  174. }
  175. /**
  176. * @param $success
  177. * @return bool
  178. */
  179. public function onStartCacheReconnect(&$success): bool
  180. {
  181. if (empty($this->_conn)) {
  182. // nothing to do
  183. return true;
  184. }
  185. if ($this->persistent) {
  186. common_log(LOG_ERR, "Cannot close persistent memcached connection");
  187. $success = false;
  188. } else {
  189. common_log(LOG_INFO, "Closing memcached connection");
  190. $success = $this->_conn->quit();
  191. $this->_conn = null;
  192. }
  193. return false;
  194. }
  195. /**
  196. * Ensure that a connection exists
  197. *
  198. * Checks the instance $_conn variable and connects
  199. * if it is empty.
  200. *
  201. * @return void
  202. */
  203. private function _ensureConn(): void
  204. {
  205. if (empty($this->_conn)) {
  206. if ($this->persistent) {
  207. $this->_conn = new Memcached(
  208. 'gnusocial:' . common_config('site', 'nickname')
  209. );
  210. } else {
  211. $this->_conn = new Memcached();
  212. }
  213. if (!count($this->_conn->getServerList())) {
  214. if (is_array($this->servers)) {
  215. $servers = $this->servers;
  216. } else {
  217. $servers = [$this->servers];
  218. }
  219. foreach ($servers as $server) {
  220. if (is_array($server) && count($server) === 2) {
  221. list($host, $port) = $server;
  222. } else {
  223. $host = is_array($server) ? $server[0] : $server;
  224. $port = 11211;
  225. }
  226. $this->_conn->addServer($host, $port);
  227. }
  228. // Compress items stored in the cache.
  229. // Allows the cache to store objects larger than 1MB (if they
  230. // compress to less than 1MB), and improves cache memory efficiency.
  231. $this->_conn->setOption(Memcached::OPT_COMPRESSION, true);
  232. }
  233. }
  234. }
  235. /**
  236. * Translate general flags to Memcached-specific flags
  237. * @param int $flag
  238. * @return int
  239. */
  240. protected function flag(int $flag): int
  241. {
  242. $out = 0;
  243. if ($flag & Cache::COMPRESSED == Cache::COMPRESSED) {
  244. $out |= Memcached::OPT_COMPRESSION;
  245. }
  246. return $out;
  247. }
  248. public function onPluginVersion(array &$versions): bool
  249. {
  250. $versions[] = array('name' => 'Memcached',
  251. 'version' => self::PLUGIN_VERSION,
  252. 'author' => 'Evan Prodromou, Craig Andrews',
  253. 'homepage' => GNUSOCIAL_ENGINE_REPO_URL . 'tree/master/plugins/Memcached',
  254. 'rawdescription' =>
  255. // TRANS: Plugin description.
  256. _m('Use <a href="http://memcached.org/">Memcached</a> to cache query results.'));
  257. return true;
  258. }
  259. }