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