Merge pull request #17940 from eileenmcnaughton/abort
[civicrm-core.git] / CRM / Core / Lock.php
CommitLineData
6a488035
TO
1<?php
2/*
3 +--------------------------------------------------------------------+
bc77d7c0 4 | Copyright CiviCRM LLC. All rights reserved. |
6a488035 5 | |
bc77d7c0
TO
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 |
6a488035 9 +--------------------------------------------------------------------+
d25dd0ee 10 */
6a488035
TO
11
12/**
13 *
14 * @package CRM
ca5cec67 15 * @copyright CiviCRM LLC https://civicrm.org/licensing
6a488035 16 */
10760fa1 17class CRM_Core_Lock implements \Civi\Core\Lock\LockInterface {
6a488035 18
8bf889ef
EM
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 */
518fa0ee 29 public static $jobLog = FALSE;
722ce4f9 30
518fa0ee
SL
31 /**
32 * lets have a 3 second timeout for now
33 */
7da04cde 34 const TIMEOUT = 3;
6a488035 35
518fa0ee
SL
36 /**
37 * @var bool
38 */
6a488035
TO
39 protected $_hasLock = FALSE;
40
41 protected $_name;
42
8bf889ef
EM
43 protected $_id;
44
10760fa1
TO
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) {
aaffa79f 91 $serverWideLock = \Civi::settings()->get('civimail_server_wide_lock');
10760fa1
TO
92 return new static($name, NULL, $serverWideLock);
93 }
94
6a488035
TO
95 /**
96 * Initialize the constants used during lock acquire / release
97 *
6a0b768e 98 * @param string $name
10760fa1
TO
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|...
6a0b768e
TO
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.
10760fa1
TO
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
6a488035 111 */
00be9182 112 public function __construct($name, $timeout = NULL, $serverWideLock = FALSE) {
e32e3c19 113 $config = CRM_Core_Config::singleton();
6a488035
TO
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 }
8bf889ef
EM
123 // MySQL 5.7 doesn't like long lock names so creating a lock id
124 $this->_id = sha1($this->_name);
f2da77e6 125 if (defined('CIVICRM_LOCK_DEBUG')) {
8bf889ef 126 CRM_Core_Error::debug_log_message('trying to construct lock for ' . $this->_name . '(' . $this->_id . ')');
f2da77e6 127 }
6a488035 128 $this->_timeout = $timeout !== NULL ? $timeout : self::TIMEOUT;
6a488035
TO
129 }
130
00be9182 131 public function __destruct() {
6a488035
TO
132 $this->release();
133 }
134
a0ee3941 135 /**
ad37ac8e 136 * Acquire lock.
137 *
8bf889ef
EM
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 *
ad37ac8e 160 * @param int $timeout
161 *
a0ee3941 162 * @return bool
ad37ac8e 163 * @throws \CRM_Core_Exception
a0ee3941 164 */
10760fa1 165 public function acquire($timeout = NULL) {
6a488035 166 if (!$this->_hasLock) {
79ee443c 167 if (!CRM_Utils_SQL::supportsMultipleLocks() && self::$jobLog && CRM_Core_DAO::singleValueQuery("SELECT IS_USED_LOCK( '" . self::$jobLog . "')")) {
c1374ea1
TO
168 return $this->hackyHandleBrokenCode(self::$jobLog);
169 }
170
6a488035 171 $query = "SELECT GET_LOCK( %1, %2 )";
be2fb01f
CW
172 $params = [
173 1 => [$this->_id, 'String'],
174 2 => [$timeout ? $timeout : $this->_timeout, 'Integer'],
175 ];
6a488035
TO
176 $res = CRM_Core_DAO::singleValueQuery($query, $params);
177 if ($res) {
722ce4f9 178 if (defined('CIVICRM_LOCK_DEBUG')) {
8bf889ef 179 CRM_Core_Error::debug_log_message('acquire lock for ' . $this->_name . '(' . $this->_id . ')');
722ce4f9 180 }
6a488035 181 $this->_hasLock = TRUE;
c1374ea1 182 if (stristr($this->_name, 'data.mailing.job.')) {
8bf889ef 183 self::$jobLog = $this->_id;
c1374ea1 184 }
6a488035 185 }
722ce4f9
TO
186 else {
187 if (defined('CIVICRM_LOCK_DEBUG')) {
8bf889ef 188 CRM_Core_Error::debug_log_message('failed to acquire lock for ' . $this->_name . '(' . $this->_id . ')');
722ce4f9
TO
189 }
190 }
6a488035
TO
191 }
192 return $this->_hasLock;
193 }
194
a0ee3941
EM
195 /**
196 * @return null|string
197 */
00be9182 198 public function release() {
6a488035 199 if ($this->_hasLock) {
10760fa1 200 if (defined('CIVICRM_LOCK_DEBUG')) {
8bf889ef 201 CRM_Core_Error::debug_log_message('release lock for ' . $this->_name . '(' . $this->_id . ')');
10760fa1 202 }
6a488035
TO
203 $this->_hasLock = FALSE;
204
8bf889ef 205 if (self::$jobLog == $this->_id) {
722ce4f9
TO
206 self::$jobLog = FALSE;
207 }
208
6a488035 209 $query = "SELECT RELEASE_LOCK( %1 )";
be2fb01f 210 $params = [1 => [$this->_id, 'String']];
6a488035
TO
211 return CRM_Core_DAO::singleValueQuery($query, $params);
212 }
213 }
214
a0ee3941
EM
215 /**
216 * @return null|string
217 */
00be9182 218 public function isFree() {
6a488035 219 $query = "SELECT IS_FREE_LOCK( %1 )";
be2fb01f 220 $params = [1 => [$this->_id, 'String']];
6a488035
TO
221 return CRM_Core_DAO::singleValueQuery($query, $params);
222 }
223
a0ee3941
EM
224 /**
225 * @return bool
226 */
00be9182 227 public function isAcquired() {
6a488035
TO
228 return $this->_hasLock;
229 }
f877d534
E
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
28a04ea9 242 * @return bool
f877d534 243 */
00be9182 244 public function hackyHandleBrokenCode($jobLog) {
e32e3c19 245 if (stristr($this->_name, 'job')) {
8bf889ef
EM
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');
f877d534 248 }
f2da77e6 249 if (defined('CIVICRM_LOCK_DEBUG')) {
8bf889ef 250 CRM_Core_Error::debug_log_message('(CRM-12856) faking lock for ' . $this->_name . '(' . $this->_id . ')');
f2da77e6 251 }
f877d534
E
252 $this->_hasLock = TRUE;
253 return TRUE;
254 }
96025800 255
6a488035 256}