MemcachedAdapter.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Cache\Adapter;
  11. use Symfony\Component\Cache\Exception\CacheException;
  12. use Symfony\Component\Cache\Exception\InvalidArgumentException;
  13. use Symfony\Component\Cache\Marshaller\DefaultMarshaller;
  14. use Symfony\Component\Cache\Marshaller\MarshallerInterface;
  15. /**
  16. * @author Rob Frawley 2nd <rmf@src.run>
  17. * @author Nicolas Grekas <p@tchwork.com>
  18. */
  19. class MemcachedAdapter extends AbstractAdapter
  20. {
  21. protected $maxIdLength = 250;
  22. private static $defaultClientOptions = [
  23. 'persistent_id' => null,
  24. 'username' => null,
  25. 'password' => null,
  26. \Memcached::OPT_SERIALIZER => \Memcached::SERIALIZER_PHP,
  27. ];
  28. private $marshaller;
  29. private $client;
  30. private $lazyClient;
  31. /**
  32. * Using a MemcachedAdapter with a TagAwareAdapter for storing tags is discouraged.
  33. * Using a RedisAdapter is recommended instead. If you cannot do otherwise, be aware that:
  34. * - the Memcached::OPT_BINARY_PROTOCOL must be enabled
  35. * (that's the default when using MemcachedAdapter::createConnection());
  36. * - tags eviction by Memcached's LRU algorithm will break by-tags invalidation;
  37. * your Memcached memory should be large enough to never trigger LRU.
  38. *
  39. * Using a MemcachedAdapter as a pure items store is fine.
  40. */
  41. public function __construct(\Memcached $client, string $namespace = '', int $defaultLifetime = 0, MarshallerInterface $marshaller = null)
  42. {
  43. if (!static::isSupported()) {
  44. throw new CacheException('Memcached >= 2.2.0 is required');
  45. }
  46. if ('Memcached' === \get_class($client)) {
  47. $opt = $client->getOption(\Memcached::OPT_SERIALIZER);
  48. if (\Memcached::SERIALIZER_PHP !== $opt && \Memcached::SERIALIZER_IGBINARY !== $opt) {
  49. throw new CacheException('MemcachedAdapter: "serializer" option must be "php" or "igbinary".');
  50. }
  51. $this->maxIdLength -= \strlen($client->getOption(\Memcached::OPT_PREFIX_KEY));
  52. $this->client = $client;
  53. } else {
  54. $this->lazyClient = $client;
  55. }
  56. parent::__construct($namespace, $defaultLifetime);
  57. $this->enableVersioning();
  58. $this->marshaller = $marshaller ?? new DefaultMarshaller();
  59. }
  60. public static function isSupported()
  61. {
  62. return \extension_loaded('memcached') && version_compare(phpversion('memcached'), '2.2.0', '>=');
  63. }
  64. /**
  65. * Creates a Memcached instance.
  66. *
  67. * By default, the binary protocol, no block, and libketama compatible options are enabled.
  68. *
  69. * Examples for servers:
  70. * - 'memcached://user:pass@localhost?weight=33'
  71. * - [['localhost', 11211, 33]]
  72. *
  73. * @param array[]|string|string[] $servers An array of servers, a DSN, or an array of DSNs
  74. * @param array $options An array of options
  75. *
  76. * @return \Memcached
  77. *
  78. * @throws \ErrorException When invalid options or servers are provided
  79. */
  80. public static function createConnection($servers, array $options = [])
  81. {
  82. if (\is_string($servers)) {
  83. $servers = [$servers];
  84. } elseif (!\is_array($servers)) {
  85. throw new InvalidArgumentException(sprintf('MemcachedAdapter::createClient() expects array or string as first argument, %s given.', \gettype($servers)));
  86. }
  87. if (!static::isSupported()) {
  88. throw new CacheException('Memcached >= 2.2.0 is required');
  89. }
  90. set_error_handler(function ($type, $msg, $file, $line) { throw new \ErrorException($msg, 0, $type, $file, $line); });
  91. try {
  92. $options += static::$defaultClientOptions;
  93. $client = new \Memcached($options['persistent_id']);
  94. $username = $options['username'];
  95. $password = $options['password'];
  96. // parse any DSN in $servers
  97. foreach ($servers as $i => $dsn) {
  98. if (\is_array($dsn)) {
  99. continue;
  100. }
  101. if (0 !== strpos($dsn, 'memcached:')) {
  102. throw new InvalidArgumentException(sprintf('Invalid Memcached DSN: %s does not start with "memcached:"', $dsn));
  103. }
  104. $params = preg_replace_callback('#^memcached:(//)?(?:([^@]*+)@)?#', function ($m) use (&$username, &$password) {
  105. if (!empty($m[2])) {
  106. list($username, $password) = explode(':', $m[2], 2) + [1 => null];
  107. }
  108. return 'file:'.($m[1] ?? '');
  109. }, $dsn);
  110. if (false === $params = parse_url($params)) {
  111. throw new InvalidArgumentException(sprintf('Invalid Memcached DSN: %s', $dsn));
  112. }
  113. $query = $hosts = [];
  114. if (isset($params['query'])) {
  115. parse_str($params['query'], $query);
  116. if (isset($query['host'])) {
  117. if (!\is_array($hosts = $query['host'])) {
  118. throw new InvalidArgumentException(sprintf('Invalid Memcached DSN: %s', $dsn));
  119. }
  120. foreach ($hosts as $host => $weight) {
  121. if (false === $port = strrpos($host, ':')) {
  122. $hosts[$host] = [$host, 11211, (int) $weight];
  123. } else {
  124. $hosts[$host] = [substr($host, 0, $port), (int) substr($host, 1 + $port), (int) $weight];
  125. }
  126. }
  127. $hosts = array_values($hosts);
  128. unset($query['host']);
  129. }
  130. if ($hosts && !isset($params['host']) && !isset($params['path'])) {
  131. unset($servers[$i]);
  132. $servers = array_merge($servers, $hosts);
  133. continue;
  134. }
  135. }
  136. if (!isset($params['host']) && !isset($params['path'])) {
  137. throw new InvalidArgumentException(sprintf('Invalid Memcached DSN: %s', $dsn));
  138. }
  139. if (isset($params['path']) && preg_match('#/(\d+)$#', $params['path'], $m)) {
  140. $params['weight'] = $m[1];
  141. $params['path'] = substr($params['path'], 0, -\strlen($m[0]));
  142. }
  143. $params += [
  144. 'host' => isset($params['host']) ? $params['host'] : $params['path'],
  145. 'port' => isset($params['host']) ? 11211 : null,
  146. 'weight' => 0,
  147. ];
  148. if ($query) {
  149. $params += $query;
  150. $options = $query + $options;
  151. }
  152. $servers[$i] = [$params['host'], $params['port'], $params['weight']];
  153. if ($hosts) {
  154. $servers = array_merge($servers, $hosts);
  155. }
  156. }
  157. // set client's options
  158. unset($options['persistent_id'], $options['username'], $options['password'], $options['weight'], $options['lazy']);
  159. $options = array_change_key_case($options, CASE_UPPER);
  160. $client->setOption(\Memcached::OPT_BINARY_PROTOCOL, true);
  161. $client->setOption(\Memcached::OPT_NO_BLOCK, true);
  162. $client->setOption(\Memcached::OPT_TCP_NODELAY, true);
  163. if (!\array_key_exists('LIBKETAMA_COMPATIBLE', $options) && !\array_key_exists(\Memcached::OPT_LIBKETAMA_COMPATIBLE, $options)) {
  164. $client->setOption(\Memcached::OPT_LIBKETAMA_COMPATIBLE, true);
  165. }
  166. foreach ($options as $name => $value) {
  167. if (\is_int($name)) {
  168. continue;
  169. }
  170. if ('HASH' === $name || 'SERIALIZER' === $name || 'DISTRIBUTION' === $name) {
  171. $value = \constant('Memcached::'.$name.'_'.strtoupper($value));
  172. }
  173. $opt = \constant('Memcached::OPT_'.$name);
  174. unset($options[$name]);
  175. $options[$opt] = $value;
  176. }
  177. $client->setOptions($options);
  178. // set client's servers, taking care of persistent connections
  179. if (!$client->isPristine()) {
  180. $oldServers = [];
  181. foreach ($client->getServerList() as $server) {
  182. $oldServers[] = [$server['host'], $server['port']];
  183. }
  184. $newServers = [];
  185. foreach ($servers as $server) {
  186. if (1 < \count($server)) {
  187. $server = array_values($server);
  188. unset($server[2]);
  189. $server[1] = (int) $server[1];
  190. }
  191. $newServers[] = $server;
  192. }
  193. if ($oldServers !== $newServers) {
  194. $client->resetServerList();
  195. $client->addServers($servers);
  196. }
  197. } else {
  198. $client->addServers($servers);
  199. }
  200. if (null !== $username || null !== $password) {
  201. if (!method_exists($client, 'setSaslAuthData')) {
  202. trigger_error('Missing SASL support: the memcached extension must be compiled with --enable-memcached-sasl.');
  203. }
  204. $client->setSaslAuthData($username, $password);
  205. }
  206. return $client;
  207. } finally {
  208. restore_error_handler();
  209. }
  210. }
  211. /**
  212. * {@inheritdoc}
  213. */
  214. protected function doSave(array $values, int $lifetime)
  215. {
  216. if (!$values = $this->marshaller->marshall($values, $failed)) {
  217. return $failed;
  218. }
  219. if ($lifetime && $lifetime > 30 * 86400) {
  220. $lifetime += time();
  221. }
  222. $encodedValues = [];
  223. foreach ($values as $key => $value) {
  224. $encodedValues[rawurlencode($key)] = $value;
  225. }
  226. return $this->checkResultCode($this->getClient()->setMulti($encodedValues, $lifetime)) ? $failed : false;
  227. }
  228. /**
  229. * {@inheritdoc}
  230. */
  231. protected function doFetch(array $ids)
  232. {
  233. try {
  234. $encodedIds = array_map('rawurlencode', $ids);
  235. $encodedResult = $this->checkResultCode($this->getClient()->getMulti($encodedIds));
  236. $result = [];
  237. foreach ($encodedResult as $key => $value) {
  238. $result[rawurldecode($key)] = $this->marshaller->unmarshall($value);
  239. }
  240. return $result;
  241. } catch (\Error $e) {
  242. throw new \ErrorException($e->getMessage(), $e->getCode(), E_ERROR, $e->getFile(), $e->getLine());
  243. }
  244. }
  245. /**
  246. * {@inheritdoc}
  247. */
  248. protected function doHave(string $id)
  249. {
  250. return false !== $this->getClient()->get(rawurlencode($id)) || $this->checkResultCode(\Memcached::RES_SUCCESS === $this->client->getResultCode());
  251. }
  252. /**
  253. * {@inheritdoc}
  254. */
  255. protected function doDelete(array $ids)
  256. {
  257. $ok = true;
  258. $encodedIds = array_map('rawurlencode', $ids);
  259. foreach ($this->checkResultCode($this->getClient()->deleteMulti($encodedIds)) as $result) {
  260. if (\Memcached::RES_SUCCESS !== $result && \Memcached::RES_NOTFOUND !== $result) {
  261. $ok = false;
  262. }
  263. }
  264. return $ok;
  265. }
  266. /**
  267. * {@inheritdoc}
  268. */
  269. protected function doClear(string $namespace)
  270. {
  271. return '' === $namespace && $this->getClient()->flush();
  272. }
  273. private function checkResultCode($result)
  274. {
  275. $code = $this->client->getResultCode();
  276. if (\Memcached::RES_SUCCESS === $code || \Memcached::RES_NOTFOUND === $code) {
  277. return $result;
  278. }
  279. throw new CacheException(sprintf('MemcachedAdapter client error: %s.', strtolower($this->client->getResultMessage())));
  280. }
  281. private function getClient(): \Memcached
  282. {
  283. if ($this->client) {
  284. return $this->client;
  285. }
  286. $opt = $this->lazyClient->getOption(\Memcached::OPT_SERIALIZER);
  287. if (\Memcached::SERIALIZER_PHP !== $opt && \Memcached::SERIALIZER_IGBINARY !== $opt) {
  288. throw new CacheException('MemcachedAdapter: "serializer" option must be "php" or "igbinary".');
  289. }
  290. if ('' !== $prefix = (string) $this->lazyClient->getOption(\Memcached::OPT_PREFIX_KEY)) {
  291. throw new CacheException(sprintf('MemcachedAdapter: "prefix_key" option must be empty when using proxified connections, "%s" given.', $prefix));
  292. }
  293. return $this->client = $this->lazyClient;
  294. }
  295. }