Merge pull request #19225 from colemanw/select2Tweak
[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();
58d1e21e
SL
114 $dsn = CRM_Utils_SQL::autoSwitchDSN($config->dsn);
115 $dsnArray = DB::parseDSN($dsn);
6a488035
TO
116 $database = $dsnArray['database'];
117 $domainID = CRM_Core_Config::domainID();
118 if ($serverWideLock) {
119 $this->_name = $name;
120 }
121 else {
122 $this->_name = $database . '.' . $domainID . '.' . $name;
123 }
8bf889ef
EM
124 // MySQL 5.7 doesn't like long lock names so creating a lock id
125 $this->_id = sha1($this->_name);
f2da77e6 126 if (defined('CIVICRM_LOCK_DEBUG')) {
8bf889ef 127 CRM_Core_Error::debug_log_message('trying to construct lock for ' . $this->_name . '(' . $this->_id . ')');
f2da77e6 128 }
6a488035 129 $this->_timeout = $timeout !== NULL ? $timeout : self::TIMEOUT;
6a488035
TO
130 }
131
00be9182 132 public function __destruct() {
6a488035
TO
133 $this->release();
134 }
135
a0ee3941 136 /**
ad37ac8e 137 * Acquire lock.
138 *
8bf889ef
EM
139 * The advantage of mysql locks is that they can be used across processes. However, only one
140 * can be used at once within a process. An attempt to use a second one within a process
141 * prior to mysql 5.7.5 results in the first being released.
142 *
143 * The process here is
144 * 1) first attempt to grab a lock for a mailing job - self::jobLog will be populated with the
145 * lock id & a mysql lock will be created for the ID.
146 *
147 * If a second function in the same process attempts to grab the lock it will enter the hackyHandleBrokenCode routine
148 * which says 'I won't break a mailing lock for you but if you are not a civimail send process I'll let you
149 * pretend you have a lock already and you can go ahead with whatever you were doing under the delusion you
150 * have a lock.
151 *
152 * @todo bypass hackyHandleBrokenCode for mysql version 5.7.5+
153 *
154 * If a second function in a separate process attempts to grab the lock already in use it should be rejected,
155 * but it appears it IS allowed to grab a different lock & unlike in the same process the first lock won't be released.
156 *
157 * All this means CiviMail locks are first class citizens & any other process gets a 'best effort lock'.
158 *
159 * @todo document naming convention for CiviMail locks as this is key to ensuring they work properly.
160 *
ad37ac8e 161 * @param int $timeout
162 *
a0ee3941 163 * @return bool
ad37ac8e 164 * @throws \CRM_Core_Exception
a0ee3941 165 */
10760fa1 166 public function acquire($timeout = NULL) {
6a488035 167 if (!$this->_hasLock) {
79ee443c 168 if (!CRM_Utils_SQL::supportsMultipleLocks() && self::$jobLog && CRM_Core_DAO::singleValueQuery("SELECT IS_USED_LOCK( '" . self::$jobLog . "')")) {
c1374ea1
TO
169 return $this->hackyHandleBrokenCode(self::$jobLog);
170 }
171
6a488035 172 $query = "SELECT GET_LOCK( %1, %2 )";
be2fb01f
CW
173 $params = [
174 1 => [$this->_id, 'String'],
175 2 => [$timeout ? $timeout : $this->_timeout, 'Integer'],
176 ];
6a488035
TO
177 $res = CRM_Core_DAO::singleValueQuery($query, $params);
178 if ($res) {
722ce4f9 179 if (defined('CIVICRM_LOCK_DEBUG')) {
8bf889ef 180 CRM_Core_Error::debug_log_message('acquire lock for ' . $this->_name . '(' . $this->_id . ')');
722ce4f9 181 }
6a488035 182 $this->_hasLock = TRUE;
c1374ea1 183 if (stristr($this->_name, 'data.mailing.job.')) {
8bf889ef 184 self::$jobLog = $this->_id;
c1374ea1 185 }
6a488035 186 }
722ce4f9
TO
187 else {
188 if (defined('CIVICRM_LOCK_DEBUG')) {
8bf889ef 189 CRM_Core_Error::debug_log_message('failed to acquire lock for ' . $this->_name . '(' . $this->_id . ')');
722ce4f9
TO
190 }
191 }
6a488035
TO
192 }
193 return $this->_hasLock;
194 }
195
a0ee3941
EM
196 /**
197 * @return null|string
198 */
00be9182 199 public function release() {
6a488035 200 if ($this->_hasLock) {
10760fa1 201 if (defined('CIVICRM_LOCK_DEBUG')) {
8bf889ef 202 CRM_Core_Error::debug_log_message('release lock for ' . $this->_name . '(' . $this->_id . ')');
10760fa1 203 }
6a488035
TO
204 $this->_hasLock = FALSE;
205
8bf889ef 206 if (self::$jobLog == $this->_id) {
722ce4f9
TO
207 self::$jobLog = FALSE;
208 }
209
6a488035 210 $query = "SELECT RELEASE_LOCK( %1 )";
be2fb01f 211 $params = [1 => [$this->_id, 'String']];
6a488035
TO
212 return CRM_Core_DAO::singleValueQuery($query, $params);
213 }
214 }
215
a0ee3941
EM
216 /**
217 * @return null|string
218 */
00be9182 219 public function isFree() {
6a488035 220 $query = "SELECT IS_FREE_LOCK( %1 )";
be2fb01f 221 $params = [1 => [$this->_id, 'String']];
6a488035
TO
222 return CRM_Core_DAO::singleValueQuery($query, $params);
223 }
224
a0ee3941
EM
225 /**
226 * @return bool
227 */
00be9182 228 public function isAcquired() {
6a488035
TO
229 return $this->_hasLock;
230 }
f877d534
E
231
232 /**
233 * CRM-12856 locks were originally set up for jobs, but the concept was extended to caching & groups without
234 * understanding that would undermine the job locks (because grabbing a lock implicitly releases existing ones)
235 * this is all a big hack to mitigate the impact of that - but should not be seen as a fix. Not sure correct fix
236 * but maybe locks should be used more selectively? Or else we need to handle is some cool way that Tim is yet to write :-)
237 * if we are running in the context of the cron log then we would rather die (or at least let our process die)
238 * than release that lock - so if the attempt is being made by setCache or something relatively trivial
239 * we'll just return TRUE, but if it's another job then we will crash as that seems 'safer'
240 *
241 * @param string $jobLog
242 * @throws CRM_Core_Exception
28a04ea9 243 * @return bool
f877d534 244 */
00be9182 245 public function hackyHandleBrokenCode($jobLog) {
e32e3c19 246 if (stristr($this->_name, 'job')) {
8bf889ef
EM
247 CRM_Core_Error::debug_log_message('lock acquisition for ' . $this->_name . '(' . $this->_id . ')' . ' attempted when ' . $jobLog . ' is not released');
248 throw new CRM_Core_Exception('lock acquisition for ' . $this->_name . '(' . $this->_id . ')' . ' attempted when ' . $jobLog . ' is not released');
f877d534 249 }
f2da77e6 250 if (defined('CIVICRM_LOCK_DEBUG')) {
8bf889ef 251 CRM_Core_Error::debug_log_message('(CRM-12856) faking lock for ' . $this->_name . '(' . $this->_id . ')');
f2da77e6 252 }
f877d534
E
253 $this->_hasLock = TRUE;
254 return TRUE;
255 }
96025800 256
6a488035 257}