Merge in 5.28
[civicrm-core.git] / CRM / Core / Lock.php
1 <?php
2 /*
3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
5 | |
6 | This work is published under the GNU AGPLv3 license with some |
7 | permitted exceptions and without any warranty. For full license |
8 | and copyright information, see https://civicrm.org/licensing |
9 +--------------------------------------------------------------------+
10 */
11
12 /**
13 *
14 * @package CRM
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
16 */
17 class CRM_Core_Lock implements \Civi\Core\Lock\LockInterface {
18
19 /**
20 * This variable (despite it's name) roughly translates to 'lock that we actually care about'.
21 *
22 * Prior to version 5.7.5 mysql only supports a single named lock. This variable is
23 * part of the skullduggery involved in 'say it's no so Frank'.
24 *
25 * See further comments on the aquire function.
26 *
27 * @var bool
28 */
29 public static $jobLog = FALSE;
30
31 /**
32 * lets have a 3 second timeout for now
33 */
34 const TIMEOUT = 3;
35
36 /**
37 * @var bool
38 */
39 protected $_hasLock = FALSE;
40
41 protected $_name;
42
43 protected $_id;
44
45 /**
46 * Use MySQL's GET_LOCK(). Locks are shared across all Civi instances
47 * on the same MySQL server.
48 *
49 * @param string $name
50 * Symbolic name for the lock. Names generally look like
51 * "worker.mailing.EmailProcessor" ("{category}.{component}.{AdhocName}").
52 *
53 * Categories: worker|data|cache|...
54 * Component: core|mailing|member|contribute|...
55 * @return \Civi\Core\Lock\LockInterface
56 */
57 public static function createGlobalLock($name) {
58 return new static($name, NULL, TRUE);
59 }
60
61 /**
62 * Use MySQL's GET_LOCK(), but apply prefixes to the lock names.
63 * Locks are unique to each instance of Civi.
64 *
65 * @param string $name
66 * Symbolic name for the lock. Names generally look like
67 * "worker.mailing.EmailProcessor" ("{category}.{component}.{AdhocName}").
68 *
69 * Categories: worker|data|cache|...
70 * Component: core|mailing|member|contribute|...
71 * @return \Civi\Core\Lock\LockInterface
72 */
73 public static function createScopedLock($name) {
74 return new static($name);
75 }
76
77 /**
78 * Use MySQL's GET_LOCK(), but conditionally apply prefixes to the lock names
79 * (if civimail_server_wide_lock is disabled).
80 *
81 * @param string $name
82 * Symbolic name for the lock. Names generally look like
83 * "worker.mailing.EmailProcessor" ("{category}.{component}.{AdhocName}").
84 *
85 * Categories: worker|data|cache|...
86 * Component: core|mailing|member|contribute|...
87 * @return \Civi\Core\Lock\LockInterface
88 * @deprecated
89 */
90 public static function createCivimailLock($name) {
91 $serverWideLock = \Civi::settings()->get('civimail_server_wide_lock');
92 return new static($name, NULL, $serverWideLock);
93 }
94
95 /**
96 * Initialize the constants used during lock acquire / release
97 *
98 * @param string $name
99 * Symbolic name for the lock. Names generally look like
100 * "worker.mailing.EmailProcessor" ("{category}.{component}.{AdhocName}").
101 *
102 * Categories: worker|data|cache|...
103 * Component: core|mailing|member|contribute|...
104 * @param int $timeout
105 * The number of seconds to wait to get the lock. 1 if not set.
106 * @param bool $serverWideLock
107 * Should this lock be applicable across your entire mysql server.
108 * this is useful if you have multiple sites running on the same
109 * mysql server and you want to limit the number of parallel cron
110 * jobs - CRM-91XX
111 */
112 public function __construct($name, $timeout = NULL, $serverWideLock = FALSE) {
113 $config = CRM_Core_Config::singleton();
114 $dsnArray = DB::parseDSN($config->dsn);
115 $database = $dsnArray['database'];
116 $domainID = CRM_Core_Config::domainID();
117 if ($serverWideLock) {
118 $this->_name = $name;
119 }
120 else {
121 $this->_name = $database . '.' . $domainID . '.' . $name;
122 }
123 // MySQL 5.7 doesn't like long lock names so creating a lock id
124 $this->_id = sha1($this->_name);
125 if (defined('CIVICRM_LOCK_DEBUG')) {
126 CRM_Core_Error::debug_log_message('trying to construct lock for ' . $this->_name . '(' . $this->_id . ')');
127 }
128 $this->_timeout = $timeout !== NULL ? $timeout : self::TIMEOUT;
129 }
130
131 public function __destruct() {
132 $this->release();
133 }
134
135 /**
136 * Acquire lock.
137 *
138 * The advantage of mysql locks is that they can be used across processes. However, only one
139 * can be used at once within a process. An attempt to use a second one within a process
140 * prior to mysql 5.7.5 results in the first being released.
141 *
142 * The process here is
143 * 1) first attempt to grab a lock for a mailing job - self::jobLog will be populated with the
144 * lock id & a mysql lock will be created for the ID.
145 *
146 * If a second function in the same process attempts to grab the lock it will enter the hackyHandleBrokenCode routine
147 * which says 'I won't break a mailing lock for you but if you are not a civimail send process I'll let you
148 * pretend you have a lock already and you can go ahead with whatever you were doing under the delusion you
149 * have a lock.
150 *
151 * @todo bypass hackyHandleBrokenCode for mysql version 5.7.5+
152 *
153 * If a second function in a separate process attempts to grab the lock already in use it should be rejected,
154 * but it appears it IS allowed to grab a different lock & unlike in the same process the first lock won't be released.
155 *
156 * All this means CiviMail locks are first class citizens & any other process gets a 'best effort lock'.
157 *
158 * @todo document naming convention for CiviMail locks as this is key to ensuring they work properly.
159 *
160 * @param int $timeout
161 *
162 * @return bool
163 * @throws \CRM_Core_Exception
164 */
165 public function acquire($timeout = NULL) {
166 if (!$this->_hasLock) {
167 if (!CRM_Utils_SQL::supportsMultipleLocks() && self::$jobLog && CRM_Core_DAO::singleValueQuery("SELECT IS_USED_LOCK( '" . self::$jobLog . "')")) {
168 return $this->hackyHandleBrokenCode(self::$jobLog);
169 }
170
171 $query = "SELECT GET_LOCK( %1, %2 )";
172 $params = [
173 1 => [$this->_id, 'String'],
174 2 => [$timeout ? $timeout : $this->_timeout, 'Integer'],
175 ];
176 $res = CRM_Core_DAO::singleValueQuery($query, $params);
177 if ($res) {
178 if (defined('CIVICRM_LOCK_DEBUG')) {
179 CRM_Core_Error::debug_log_message('acquire lock for ' . $this->_name . '(' . $this->_id . ')');
180 }
181 $this->_hasLock = TRUE;
182 if (stristr($this->_name, 'data.mailing.job.')) {
183 self::$jobLog = $this->_id;
184 }
185 }
186 else {
187 if (defined('CIVICRM_LOCK_DEBUG')) {
188 CRM_Core_Error::debug_log_message('failed to acquire lock for ' . $this->_name . '(' . $this->_id . ')');
189 }
190 }
191 }
192 return $this->_hasLock;
193 }
194
195 /**
196 * @return null|string
197 */
198 public function release() {
199 if ($this->_hasLock) {
200 if (defined('CIVICRM_LOCK_DEBUG')) {
201 CRM_Core_Error::debug_log_message('release lock for ' . $this->_name . '(' . $this->_id . ')');
202 }
203 $this->_hasLock = FALSE;
204
205 if (self::$jobLog == $this->_id) {
206 self::$jobLog = FALSE;
207 }
208
209 $query = "SELECT RELEASE_LOCK( %1 )";
210 $params = [1 => [$this->_id, 'String']];
211 return CRM_Core_DAO::singleValueQuery($query, $params);
212 }
213 }
214
215 /**
216 * @return null|string
217 */
218 public function isFree() {
219 $query = "SELECT IS_FREE_LOCK( %1 )";
220 $params = [1 => [$this->_id, 'String']];
221 return CRM_Core_DAO::singleValueQuery($query, $params);
222 }
223
224 /**
225 * @return bool
226 */
227 public function isAcquired() {
228 return $this->_hasLock;
229 }
230
231 /**
232 * CRM-12856 locks were originally set up for jobs, but the concept was extended to caching & groups without
233 * understanding that would undermine the job locks (because grabbing a lock implicitly releases existing ones)
234 * this is all a big hack to mitigate the impact of that - but should not be seen as a fix. Not sure correct fix
235 * but maybe locks should be used more selectively? Or else we need to handle is some cool way that Tim is yet to write :-)
236 * if we are running in the context of the cron log then we would rather die (or at least let our process die)
237 * than release that lock - so if the attempt is being made by setCache or something relatively trivial
238 * we'll just return TRUE, but if it's another job then we will crash as that seems 'safer'
239 *
240 * @param string $jobLog
241 * @throws CRM_Core_Exception
242 * @return bool
243 */
244 public function hackyHandleBrokenCode($jobLog) {
245 if (stristr($this->_name, 'job')) {
246 CRM_Core_Error::debug_log_message('lock acquisition for ' . $this->_name . '(' . $this->_id . ')' . ' attempted when ' . $jobLog . ' is not released');
247 throw new CRM_Core_Exception('lock acquisition for ' . $this->_name . '(' . $this->_id . ')' . ' attempted when ' . $jobLog . ' is not released');
248 }
249 if (defined('CIVICRM_LOCK_DEBUG')) {
250 CRM_Core_Error::debug_log_message('(CRM-12856) faking lock for ' . $this->_name . '(' . $this->_id . ')');
251 }
252 $this->_hasLock = TRUE;
253 return TRUE;
254 }
255
256 }