MemcachedTrait.php 12 KB

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