MemcachedTrait.php 12 KB

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