Merge pull request #13498 from francescbassas/patch-18
[civicrm-core.git] / CRM / Utils / Cache / Redis.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | CiviCRM version 5 |
5 +--------------------------------------------------------------------+
6 | Copyright CiviCRM LLC (c) 2004-2019 |
7 +--------------------------------------------------------------------+
8 | This file is a part of CiviCRM. |
9 | |
10 | CiviCRM is free software; you can copy, modify, and distribute it |
11 | under the terms of the GNU Affero General Public License |
12 | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
13 | |
14 | CiviCRM is distributed in the hope that it will be useful, but |
15 | WITHOUT ANY WARRANTY; without even the implied warranty of |
16 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
17 | See the GNU Affero General Public License for more details. |
18 | |
19 | You should have received a copy of the GNU Affero General Public |
20 | License and the CiviCRM Licensing Exception along |
21 | with this program; if not, contact CiviCRM LLC |
22 | at info[AT]civicrm[DOT]org. If you have questions about the |
23 | GNU Affero General Public License or the licensing of CiviCRM, |
24 | see the CiviCRM license FAQ at http://civicrm.org/licensing |
25 +--------------------------------------------------------------------+
26 */
27
28 /**
29 *
30 * @package CRM
31 * @copyright CiviCRM LLC (c) 2004-2019
32 * $Id$
33 *
34 */
35 class CRM_Utils_Cache_Redis implements CRM_Utils_Cache_Interface {
36
37 use CRM_Utils_Cache_NaiveMultipleTrait; // TODO Consider native implementation.
38 use CRM_Utils_Cache_NaiveHasTrait; // TODO Native implementation
39
40 const DEFAULT_HOST = 'localhost';
41 const DEFAULT_PORT = 6379;
42 const DEFAULT_TIMEOUT = 3600;
43 const DEFAULT_PREFIX = '';
44
45 /**
46 * The default timeout to use
47 *
48 * @var int
49 */
50 protected $_timeout = self::DEFAULT_TIMEOUT;
51
52 /**
53 * The prefix prepended to cache keys.
54 *
55 * If we are using the same redis instance for multiple CiviCRM
56 * installs, we must have a unique prefix for each install to prevent
57 * the keys from clobbering each other.
58 *
59 * @var string
60 */
61 protected $_prefix = self::DEFAULT_PREFIX;
62
63 /**
64 * The actual redis object
65 *
66 * @var Redis
67 */
68 protected $_cache;
69
70 /**
71 * Create a connection. If a connection already exists, re-use it.
72 *
73 * @param array $config
74 * @return Redis
75 */
76 public static function connect($config) {
77 $host = isset($config['host']) ? $config['host'] : self::DEFAULT_HOST;
78 $port = isset($config['port']) ? $config['port'] : self::DEFAULT_PORT;
79 $pass = CRM_Utils_Constant::value('CIVICRM_DB_CACHE_PASSWORD'); // Ugh.
80 $id = implode(':', ['connect', $host, $port /* $pass is constant */]);
81 if (!isset(Civi::$statics[__CLASS__][$id])) {
82 // Ideally, we'd track the connection in the service-container, but the
83 // cache connection is boot-critical.
84 $redis = new Redis();
85 if (!$redis->connect($host, $port)) {
86 // dont use fatal here since we can go in an infinite loop
87 echo 'Could not connect to redisd server';
88 CRM_Utils_System::civiExit();
89 }
90 if ($pass) {
91 $redis->auth($pass);
92 }
93 Civi::$statics[__CLASS__][$id] = $redis;
94 }
95 return Civi::$statics[__CLASS__][$id];
96 }
97
98 /**
99 * Constructor
100 *
101 * @param array $config
102 * An array of configuration params.
103 *
104 * @return \CRM_Utils_Cache_Redis
105 */
106 public function __construct($config) {
107 if (isset($config['timeout'])) {
108 $this->_timeout = $config['timeout'];
109 }
110 if (isset($config['prefix'])) {
111 $this->_prefix = $config['prefix'];
112 }
113
114 $this->_cache = self::connect($config);
115 }
116
117 /**
118 * @param $key
119 * @param $value
120 * @param null|int|\DateInterval $ttl
121 *
122 * @return bool
123 * @throws Exception
124 */
125 public function set($key, $value, $ttl = NULL) {
126 CRM_Utils_Cache::assertValidKey($key);
127 if (is_int($ttl) && $ttl <= 0) {
128 return $this->delete($key);
129 }
130 $ttl = CRM_Utils_Date::convertCacheTtl($ttl, self::DEFAULT_TIMEOUT);
131 if (!$this->_cache->setex($this->_prefix . $key, $ttl, serialize($value))) {
132 if (PHP_SAPI === 'cli' || (Civi\Core\Container::isContainerBooted() && CRM_Core_Permission::check('view debug output'))) {
133 throw new CRM_Utils_Cache_CacheException("Redis set ($key) failed: " . $this->_cache->getLastError());
134 }
135 else {
136 Civi::log()->error("Redis set ($key) failed: " . $this->_cache->getLastError());
137 throw new CRM_Utils_Cache_CacheException("Redis set ($key) failed");
138 }
139 return FALSE;
140 }
141 return TRUE;
142 }
143
144 /**
145 * @param $key
146 * @param mixed $default
147 *
148 * @return mixed
149 */
150 public function get($key, $default = NULL) {
151 CRM_Utils_Cache::assertValidKey($key);
152 $result = $this->_cache->get($this->_prefix . $key);
153 return ($result === FALSE) ? $default : unserialize($result);
154 }
155
156 /**
157 * @param $key
158 *
159 * @return bool
160 */
161 public function delete($key) {
162 CRM_Utils_Cache::assertValidKey($key);
163 $this->_cache->delete($this->_prefix . $key);
164 return TRUE;
165 }
166
167 /**
168 * @return bool
169 */
170 public function flush() {
171 // FIXME: Ideally, we'd map each prefix to a different 'hash' object in Redis,
172 // and this would be simpler. However, that needs to go in tandem with a
173 // more general rethink of cache expiration/TTL.
174
175 $keys = $this->_cache->keys($this->_prefix . '*');
176 $this->_cache->del($keys);
177 return TRUE;
178 }
179
180 public function clear() {
181 return $this->flush();
182 }
183
184 }