MemcachedPlugin.php 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  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. private $_conn = null;
  45. /**
  46. * Initialize the plugin
  47. *
  48. * Note that onStartCacheGet() may have been called before this!
  49. *
  50. * @return bool flag value
  51. */
  52. public function initialize(): bool
  53. {
  54. if (self::$cacheInitialized) {
  55. $this->persistent = true;
  56. } else {
  57. // If we're a parent command-line process we need
  58. // to be able to close out the connection after
  59. // forking, so disable persistence.
  60. //
  61. // We'll turn it back on again the second time
  62. // through which will either be in a child process,
  63. // or a single-process script which is switching
  64. // configurations.
  65. $this->persistent = (php_sapi_name() == 'cli') ? false : true;
  66. }
  67. try {
  68. $this->_ensureConn();
  69. self::$cacheInitialized = true;
  70. } catch (MemcachedException $e) {
  71. common_log(LOG_ERR, 'Memcached encountered exception ' . get_class($e) . ': ' . $e->getMessage());
  72. }
  73. return true;
  74. }
  75. /**
  76. * Get a value associated with a key
  77. *
  78. * The value should have been set previously.
  79. *
  80. * @param string &$key in; Lookup key
  81. * @param mixed &$value out; value associated with key
  82. *
  83. * @return bool hook success
  84. */
  85. public function onStartCacheGet(&$key, &$value): bool
  86. {
  87. try {
  88. $this->_ensureConn();
  89. $value = $this->_conn->get($key);
  90. } catch (MemcachedException $e) {
  91. common_log(LOG_ERR, 'Memcached encountered exception ' . get_class($e) . ': ' . $e->getMessage());
  92. return true;
  93. }
  94. if ($value === false) {
  95. // If not found, let other plugins handle it
  96. return $this->_conn->getResultCode() === Memcached::RES_NOTFOUND;
  97. } else {
  98. return false;
  99. }
  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 Memcached::OPT_COMPRESSION (translated by the `flag` method)
  107. * @param integer &$expiry in; Expiry (passed through to Memcache)
  108. * @param bool &$success out; Whether the set was successful
  109. *
  110. * @return bool hook success
  111. */
  112. public function onStartCacheSet(&$key, &$value, &$flag, &$expiry, &$success): bool
  113. {
  114. if ($expiry === null) {
  115. $expiry = $this->defaultExpiry;
  116. }
  117. try {
  118. $this->_ensureConn();
  119. if (!empty($flag)) {
  120. $this->_conn->setOption(Memcached::OPT_COMPRESSION, $flag);
  121. }
  122. $success = $this->_conn->set($key, $value, $expiry);
  123. } catch (MemcachedException $e) {
  124. common_log(LOG_ERR, 'Memcached encountered exception ' . get_class($e) . ': ' . $e->getMessage());
  125. return true;
  126. }
  127. return !$success;
  128. }
  129. /**
  130. * Atomically increment an existing numeric key value.
  131. * Existing expiration time will not be changed.
  132. *
  133. * @param string &$key in; Key to use for lookups
  134. * @param int &$step in; Amount to increment (default 1)
  135. * @param mixed &$value out; Incremented value, or false if key not set.
  136. *
  137. * @return bool hook success
  138. */
  139. public function onStartCacheIncrement(&$key, &$step, &$value): bool
  140. {
  141. try {
  142. $this->_ensureConn();
  143. $value = $this->_conn->increment($key, $step);
  144. } catch (MemcachedException $e) {
  145. common_log(LOG_ERR, 'Memcached encountered exception ' . get_class($e) . ': ' . $e->getMessage());
  146. return true;
  147. }
  148. if ($value === false) {
  149. // If not found, let other plugins handle it
  150. return $this->_conn->getResultCode() === Memcached::RES_NOTFOUND;
  151. } else {
  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 bool &$success out; whether it worked
  160. *
  161. * @return bool hook success
  162. */
  163. public function onStartCacheDelete(&$key, &$success): bool
  164. {
  165. try {
  166. $this->_ensureConn();
  167. $success = $this->_conn->delete($key);
  168. } catch (MemcachedException $e) {
  169. common_log(LOG_ERR, 'Memcached encountered exception ' . get_class($e) . ': ' . $e->getMessage());
  170. return true;
  171. }
  172. return !$success;
  173. }
  174. /**
  175. * @param $success
  176. * @return bool
  177. */
  178. public function onStartCacheReconnect(&$success): bool
  179. {
  180. if (empty($this->_conn)) {
  181. // nothing to do
  182. return true;
  183. }
  184. if ($this->persistent) {
  185. common_log(LOG_ERR, "Cannot close persistent memcached connection");
  186. $success = false;
  187. } else {
  188. common_log(LOG_INFO, "Closing memcached connection");
  189. $success = $this->_conn->quit();
  190. $this->_conn = null;
  191. }
  192. return false;
  193. }
  194. /**
  195. * Ensure that a connection exists
  196. *
  197. * Checks the instance $_conn variable and connects
  198. * if it is empty.
  199. *
  200. * @return void
  201. */
  202. private function _ensureConn(): void
  203. {
  204. if (empty($this->_conn)) {
  205. $this->_conn = new Memcached(common_config('site', 'nickname'));
  206. if (!count($this->_conn->getServerList())) {
  207. if (is_array($this->servers)) {
  208. $servers = $this->servers;
  209. } else {
  210. $servers = [$this->servers];
  211. }
  212. foreach ($servers as $server) {
  213. if (is_array($server) && count($server) === 2) {
  214. list($host, $port) = $server;
  215. } else {
  216. $host = is_array($server) ? $server[0] : $server;
  217. $port = 11211;
  218. }
  219. $this->_conn->addServer($host, $port);
  220. }
  221. // Compress items stored in the cache.
  222. // Allows the cache to store objects larger than 1MB (if they
  223. // compress to less than 1MB), and improves cache memory efficiency.
  224. $this->_conn->setOption(Memcached::OPT_COMPRESSION, true);
  225. }
  226. }
  227. }
  228. /**
  229. * Translate general flags to Memcached-specific flags
  230. * @param int $flag
  231. * @return int
  232. */
  233. protected function flag(int $flag): int
  234. {
  235. $out = 0;
  236. if ($flag & Cache::COMPRESSED == Cache::COMPRESSED) {
  237. $out |= Memcached::OPT_COMPRESSION;
  238. }
  239. return $out;
  240. }
  241. public function onPluginVersion(array &$versions): bool
  242. {
  243. $versions[] = array('name' => 'Memcached',
  244. 'version' => self::PLUGIN_VERSION,
  245. 'author' => 'Evan Prodromou, Craig Andrews',
  246. 'homepage' => GNUSOCIAL_ENGINE_REPO_URL . 'tree/master/plugins/Memcached',
  247. 'rawdescription' =>
  248. // TRANS: Plugin description.
  249. _m('Use <a href="http://memcached.org/">Memcached</a> to cache query results.'));
  250. return true;
  251. }
  252. }