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