MemcachedTrait.php 13 KB

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