PageRenderTime 43ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 0ms

/cache/stores/memcached/lib.php

https://bitbucket.org/synergylearning/campusconnect
PHP | 522 lines | 265 code | 43 blank | 214 comment | 41 complexity | 30b0290ecdf237ea0413f98b8087b712 MD5 | raw file
Possible License(s): MPL-2.0-no-copyleft-exception, LGPL-3.0, GPL-3.0, LGPL-2.1, Apache-2.0, BSD-3-Clause, AGPL-3.0
  1. <?php
  2. // This file is part of Moodle - http://moodle.org/
  3. //
  4. // Moodle is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU 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. // Moodle 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 General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU General Public License
  15. // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
  16. /**
  17. * The library file for the memcached cache store.
  18. *
  19. * This file is part of the memcached cache store, it contains the API for interacting with an instance of the store.
  20. *
  21. * @package cachestore_memcached
  22. * @copyright 2012 Sam Hemelryk
  23. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  24. */
  25. defined('MOODLE_INTERNAL') || die();
  26. /**
  27. * The memcached store.
  28. *
  29. * (Not to be confused with the memcache store)
  30. *
  31. * Configuration options:
  32. * servers: string: host:port:weight , ...
  33. * compression: true, false
  34. * serialiser: SERIALIZER_PHP, SERIALIZER_JSON, SERIALIZER_IGBINARY
  35. * prefix: string: defaults to instance name
  36. * hashmethod: HASH_DEFAULT, HASH_MD5, HASH_CRC, HASH_FNV1_64, HASH_FNV1A_64, HASH_FNV1_32,
  37. * HASH_FNV1A_32, HASH_HSIEH, HASH_MURMUR
  38. * bufferwrites: true, false
  39. *
  40. * @copyright 2012 Sam Hemelryk
  41. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  42. */
  43. class cachestore_memcached extends cache_store implements cache_is_configurable {
  44. /**
  45. * The name of the store
  46. * @var store
  47. */
  48. protected $name;
  49. /**
  50. * The memcached connection
  51. * @var Memcached
  52. */
  53. protected $connection;
  54. /**
  55. * An array of servers to use during connection
  56. * @var array
  57. */
  58. protected $servers = array();
  59. /**
  60. * The options used when establishing the connection
  61. * @var array
  62. */
  63. protected $options = array();
  64. /**
  65. * True when this instance is ready to be initialised.
  66. * @var bool
  67. */
  68. protected $isready = false;
  69. /**
  70. * Set to true when this store instance has been initialised.
  71. * @var bool
  72. */
  73. protected $isinitialised = false;
  74. /**
  75. * The cache definition this store was initialised with.
  76. * @var cache_definition
  77. */
  78. protected $definition;
  79. /**
  80. * Constructs the store instance.
  81. *
  82. * Noting that this function is not an initialisation. It is used to prepare the store for use.
  83. * The store will be initialised when required and will be provided with a cache_definition at that time.
  84. *
  85. * @param string $name
  86. * @param array $configuration
  87. */
  88. public function __construct($name, array $configuration = array()) {
  89. $this->name = $name;
  90. if (!array_key_exists('servers', $configuration) || empty($configuration['servers'])) {
  91. // Nothing configured.
  92. return;
  93. }
  94. if (!is_array($configuration['servers'])) {
  95. $configuration['servers'] = array($configuration['servers']);
  96. }
  97. $compression = array_key_exists('compression', $configuration) ? (bool)$configuration['compression'] : true;
  98. if (array_key_exists('serialiser', $configuration)) {
  99. $serialiser = (int)$configuration['serialiser'];
  100. } else {
  101. $serialiser = Memcached::SERIALIZER_PHP;
  102. }
  103. $prefix = (!empty($configuration['prefix'])) ? (string)$configuration['prefix'] : crc32($name);
  104. $hashmethod = (array_key_exists('hash', $configuration)) ? (int)$configuration['hash'] : Memcached::HASH_DEFAULT;
  105. $bufferwrites = array_key_exists('bufferwrites', $configuration) ? (bool)$configuration['bufferwrites'] : false;
  106. foreach ($configuration['servers'] as $server) {
  107. if (!is_array($server)) {
  108. $server = explode(':', $server, 3);
  109. }
  110. if (!array_key_exists(1, $server)) {
  111. $server[1] = 11211;
  112. $server[2] = 100;
  113. } else if (!array_key_exists(2, $server)) {
  114. $server[2] = 100;
  115. }
  116. $this->servers[] = $server;
  117. }
  118. $this->options[Memcached::OPT_COMPRESSION] = $compression;
  119. $this->options[Memcached::OPT_SERIALIZER] = $serialiser;
  120. $this->options[Memcached::OPT_PREFIX_KEY] = $prefix;
  121. $this->options[Memcached::OPT_HASH] = $hashmethod;
  122. $this->options[Memcached::OPT_BUFFER_WRITES] = $bufferwrites;
  123. $this->connection = new Memcached(crc32($this->name));
  124. $servers = $this->connection->getServerList();
  125. if (empty($servers)) {
  126. foreach ($this->options as $key => $value) {
  127. $this->connection->setOption($key, $value);
  128. }
  129. $this->connection->addServers($this->servers);
  130. }
  131. // Test the connection to the pool of servers.
  132. $this->isready = @$this->connection->set("ping", 'ping', 1);
  133. }
  134. /**
  135. * Initialises the cache.
  136. *
  137. * Once this has been done the cache is all set to be used.
  138. *
  139. * @param cache_definition $definition
  140. */
  141. public function initialise(cache_definition $definition) {
  142. if ($this->is_initialised()) {
  143. throw new coding_exception('This memcached instance has already been initialised.');
  144. }
  145. $this->definition = $definition;
  146. $this->isinitialised = true;
  147. }
  148. /**
  149. * Returns true once this instance has been initialised.
  150. *
  151. * @return bool
  152. */
  153. public function is_initialised() {
  154. return ($this->isinitialised);
  155. }
  156. /**
  157. * Returns true if this store instance is ready to be used.
  158. * @return bool
  159. */
  160. public function is_ready() {
  161. return $this->isready;
  162. }
  163. /**
  164. * Returns true if the store requirements are met.
  165. *
  166. * @return bool
  167. */
  168. public static function are_requirements_met() {
  169. return class_exists('Memcached');
  170. }
  171. /**
  172. * Returns true if the given mode is supported by this store.
  173. *
  174. * @param int $mode One of cache_store::MODE_*
  175. * @return bool
  176. */
  177. public static function is_supported_mode($mode) {
  178. return ($mode === self::MODE_APPLICATION || $mode === self::MODE_SESSION);
  179. }
  180. /**
  181. * Returns the supported features as a combined int.
  182. *
  183. * @param array $configuration
  184. * @return int
  185. */
  186. public static function get_supported_features(array $configuration = array()) {
  187. return self::SUPPORTS_NATIVE_TTL;
  188. }
  189. /**
  190. * Returns false as this store does not support multiple identifiers.
  191. * (This optional function is a performance optimisation; it must be
  192. * consistent with the value from get_supported_features.)
  193. *
  194. * @return bool False
  195. */
  196. public function supports_multiple_identifiers() {
  197. return false;
  198. }
  199. /**
  200. * Returns the supported modes as a combined int.
  201. *
  202. * @param array $configuration
  203. * @return int
  204. */
  205. public static function get_supported_modes(array $configuration = array()) {
  206. return self::MODE_APPLICATION;
  207. }
  208. /**
  209. * Retrieves an item from the cache store given its key.
  210. *
  211. * @param string $key The key to retrieve
  212. * @return mixed The data that was associated with the key, or false if the key did not exist.
  213. */
  214. public function get($key) {
  215. return $this->connection->get($key);
  216. }
  217. /**
  218. * Retrieves several items from the cache store in a single transaction.
  219. *
  220. * If not all of the items are available in the cache then the data value for those that are missing will be set to false.
  221. *
  222. * @param array $keys The array of keys to retrieve
  223. * @return array An array of items from the cache. There will be an item for each key, those that were not in the store will
  224. * be set to false.
  225. */
  226. public function get_many($keys) {
  227. $result = $this->connection->getMulti($keys);
  228. if (!is_array($result)) {
  229. $result = array();
  230. }
  231. foreach ($keys as $key) {
  232. if (!array_key_exists($key, $result)) {
  233. $result[$key] = false;
  234. }
  235. }
  236. return $result;
  237. }
  238. /**
  239. * Sets an item in the cache given its key and data value.
  240. *
  241. * @param string $key The key to use.
  242. * @param mixed $data The data to set.
  243. * @return bool True if the operation was a success false otherwise.
  244. */
  245. public function set($key, $data) {
  246. return $this->connection->set($key, $data, $this->definition->get_ttl());
  247. }
  248. /**
  249. * Sets many items in the cache in a single transaction.
  250. *
  251. * @param array $keyvaluearray An array of key value pairs. Each item in the array will be an associative array with two
  252. * keys, 'key' and 'value'.
  253. * @return int The number of items successfully set. It is up to the developer to check this matches the number of items
  254. * sent ... if they care that is.
  255. */
  256. public function set_many(array $keyvaluearray) {
  257. $pairs = array();
  258. foreach ($keyvaluearray as $pair) {
  259. $pairs[$pair['key']] = $pair['value'];
  260. }
  261. if ($this->connection->setMulti($pairs, $this->definition->get_ttl())) {
  262. return count($keyvaluearray);
  263. }
  264. return 0;
  265. }
  266. /**
  267. * Deletes an item from the cache store.
  268. *
  269. * @param string $key The key to delete.
  270. * @return bool Returns true if the operation was a success, false otherwise.
  271. */
  272. public function delete($key) {
  273. return $this->connection->delete($key);
  274. }
  275. /**
  276. * Deletes several keys from the cache in a single action.
  277. *
  278. * @param array $keys The keys to delete
  279. * @return int The number of items successfully deleted.
  280. */
  281. public function delete_many(array $keys) {
  282. $count = 0;
  283. foreach ($keys as $key) {
  284. if ($this->connection->delete($key)) {
  285. $count++;
  286. }
  287. }
  288. return $count;
  289. }
  290. /**
  291. * Purges the cache deleting all items within it.
  292. *
  293. * @return boolean True on success. False otherwise.
  294. */
  295. public function purge() {
  296. if ($this->isready) {
  297. $this->connection->flush();
  298. }
  299. return true;
  300. }
  301. /**
  302. * Gets an array of options to use as the serialiser.
  303. * @return array
  304. */
  305. public static function config_get_serialiser_options() {
  306. $options = array(
  307. Memcached::SERIALIZER_PHP => get_string('serialiser_php', 'cachestore_memcached')
  308. );
  309. if (Memcached::HAVE_JSON) {
  310. $options[Memcached::SERIALIZER_JSON] = get_string('serialiser_json', 'cachestore_memcached');
  311. }
  312. if (Memcached::HAVE_IGBINARY) {
  313. $options[Memcached::SERIALIZER_IGBINARY] = get_string('serialiser_igbinary', 'cachestore_memcached');
  314. }
  315. return $options;
  316. }
  317. /**
  318. * Gets an array of hash options available during configuration.
  319. * @return array
  320. */
  321. public static function config_get_hash_options() {
  322. $options = array(
  323. Memcached::HASH_DEFAULT => get_string('hash_default', 'cachestore_memcached'),
  324. Memcached::HASH_MD5 => get_string('hash_md5', 'cachestore_memcached'),
  325. Memcached::HASH_CRC => get_string('hash_crc', 'cachestore_memcached'),
  326. Memcached::HASH_FNV1_64 => get_string('hash_fnv1_64', 'cachestore_memcached'),
  327. Memcached::HASH_FNV1A_64 => get_string('hash_fnv1a_64', 'cachestore_memcached'),
  328. Memcached::HASH_FNV1_32 => get_string('hash_fnv1_32', 'cachestore_memcached'),
  329. Memcached::HASH_FNV1A_32 => get_string('hash_fnv1a_32', 'cachestore_memcached'),
  330. Memcached::HASH_HSIEH => get_string('hash_hsieh', 'cachestore_memcached'),
  331. Memcached::HASH_MURMUR => get_string('hash_murmur', 'cachestore_memcached'),
  332. );
  333. return $options;
  334. }
  335. /**
  336. * Given the data from the add instance form this function creates a configuration array.
  337. *
  338. * @param stdClass $data
  339. * @return array
  340. */
  341. public static function config_get_configuration_array($data) {
  342. $lines = explode("\n", $data->servers);
  343. $servers = array();
  344. foreach ($lines as $line) {
  345. // Trim surrounding colons and default whitespace.
  346. $line = trim(trim($line), ":");
  347. // Skip blank lines.
  348. if ($line === '') {
  349. continue;
  350. }
  351. $servers[] = explode(':', $line, 3);
  352. }
  353. return array(
  354. 'servers' => $servers,
  355. 'compression' => $data->compression,
  356. 'serialiser' => $data->serialiser,
  357. 'prefix' => $data->prefix,
  358. 'hash' => $data->hash,
  359. 'bufferwrites' => $data->bufferwrites,
  360. );
  361. }
  362. /**
  363. * Allows the cache store to set its data against the edit form before it is shown to the user.
  364. *
  365. * @param moodleform $editform
  366. * @param array $config
  367. */
  368. public static function config_set_edit_form_data(moodleform $editform, array $config) {
  369. $data = array();
  370. if (!empty($config['servers'])) {
  371. $servers = array();
  372. foreach ($config['servers'] as $server) {
  373. $servers[] = join(":", $server);
  374. }
  375. $data['servers'] = join("\n", $servers);
  376. }
  377. if (isset($config['compression'])) {
  378. $data['compression'] = (bool)$config['compression'];
  379. }
  380. if (!empty($config['serialiser'])) {
  381. $data['serialiser'] = $config['serialiser'];
  382. }
  383. if (!empty($config['prefix'])) {
  384. $data['prefix'] = $config['prefix'];
  385. }
  386. if (!empty($config['hash'])) {
  387. $data['hash'] = $config['hash'];
  388. }
  389. if (isset($config['bufferwrites'])) {
  390. $data['bufferwrites'] = (bool)$config['bufferwrites'];
  391. }
  392. $editform->set_data($data);
  393. }
  394. /**
  395. * Performs any necessary clean up when the store instance is being deleted.
  396. */
  397. public function instance_deleted() {
  398. if ($this->connection) {
  399. $connection = $this->connection;
  400. } else {
  401. $connection = new Memcached(crc32($this->name));
  402. $servers = $connection->getServerList();
  403. if (empty($servers)) {
  404. foreach ($this->options as $key => $value) {
  405. $connection->setOption($key, $value);
  406. }
  407. $connection->addServers($this->servers);
  408. }
  409. }
  410. @$connection->flush();
  411. unset($connection);
  412. unset($this->connection);
  413. }
  414. /**
  415. * Generates an instance of the cache store that can be used for testing.
  416. *
  417. * @param cache_definition $definition
  418. * @return cachestore_memcached|false
  419. */
  420. public static function initialise_test_instance(cache_definition $definition) {
  421. if (!self::are_requirements_met()) {
  422. return false;
  423. }
  424. $config = get_config('cachestore_memcached');
  425. if (empty($config->testservers)) {
  426. return false;
  427. }
  428. $configuration = array();
  429. $configuration['servers'] = $config->testservers;
  430. if (!empty($config->testcompression)) {
  431. $configuration['compression'] = $config->testcompression;
  432. }
  433. if (!empty($config->testserialiser)) {
  434. $configuration['serialiser'] = $config->testserialiser;
  435. }
  436. if (!empty($config->testprefix)) {
  437. $configuration['prefix'] = $config->testprefix;
  438. }
  439. if (!empty($config->testhash)) {
  440. $configuration['hash'] = $config->testhash;
  441. }
  442. if (!empty($config->testbufferwrites)) {
  443. $configuration['bufferwrites'] = $config->testbufferwrites;
  444. }
  445. $store = new cachestore_memcached('Test memcached', $configuration);
  446. $store->initialise($definition);
  447. return $store;
  448. }
  449. /**
  450. * Returns the name of this instance.
  451. * @return string
  452. */
  453. public function my_name() {
  454. return $this->name;
  455. }
  456. /**
  457. * Used to notify of configuration conflicts.
  458. *
  459. * The warnings returned here will be displayed on the cache configuration screen.
  460. *
  461. * @return string[] Returns an array of warnings (strings)
  462. */
  463. public function get_warnings() {
  464. global $CFG;
  465. $warnings = array();
  466. if (isset($CFG->session_memcached_save_path) && count($this->servers)) {
  467. $bits = explode(':', $CFG->session_memcached_save_path, 3);
  468. $host = array_shift($bits);
  469. $port = (count($bits)) ? array_shift($bits) : '11211';
  470. foreach ($this->servers as $server) {
  471. if ((string)$server[0] === $host && (string)$server[1] === $port) {
  472. $warnings[] = get_string('sessionhandlerconflict', 'cachestore_memcached', $this->my_name());
  473. break;
  474. }
  475. }
  476. }
  477. return $warnings;
  478. }
  479. }