MemcachedAdapter.php 13 KB

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