3 +--------------------------------------------------------------------+
4 | Copyright CiviCRM LLC. All rights reserved. |
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 +--------------------------------------------------------------------+
15 * @copyright CiviCRM LLC https://civicrm.org/licensing
17 class CRM_Core_Lock
implements \Civi\Core\Lock\LockInterface
{
20 * This variable (despite it's name) roughly translates to 'lock that we actually care about'.
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'.
25 * See further comments on the aquire function.
29 public static $jobLog = FALSE;
32 * lets have a 3 second timeout for now
39 protected $_hasLock = FALSE;
46 * Use MySQL's GET_LOCK(). Locks are shared across all Civi instances
47 * on the same MySQL server.
50 * Symbolic name for the lock. Names generally look like
51 * "worker.mailing.EmailProcessor" ("{category}.{component}.{AdhocName}").
53 * Categories: worker|data|cache|...
54 * Component: core|mailing|member|contribute|...
55 * @return \Civi\Core\Lock\LockInterface
57 public static function createGlobalLock($name) {
58 return new static($name, NULL, TRUE);
62 * Use MySQL's GET_LOCK(), but apply prefixes to the lock names.
63 * Locks are unique to each instance of Civi.
66 * Symbolic name for the lock. Names generally look like
67 * "worker.mailing.EmailProcessor" ("{category}.{component}.{AdhocName}").
69 * Categories: worker|data|cache|...
70 * Component: core|mailing|member|contribute|...
71 * @return \Civi\Core\Lock\LockInterface
73 public static function createScopedLock($name) {
74 return new static($name);
78 * Use MySQL's GET_LOCK(), but conditionally apply prefixes to the lock names
79 * (if civimail_server_wide_lock is disabled).
82 * Symbolic name for the lock. Names generally look like
83 * "worker.mailing.EmailProcessor" ("{category}.{component}.{AdhocName}").
85 * Categories: worker|data|cache|...
86 * Component: core|mailing|member|contribute|...
87 * @return \Civi\Core\Lock\LockInterface
90 public static function createCivimailLock($name) {
91 $serverWideLock = \Civi
::settings()->get('civimail_server_wide_lock');
92 return new static($name, NULL, $serverWideLock);
96 * Initialize the constants used during lock acquire / release
99 * Symbolic name for the lock. Names generally look like
100 * "worker.mailing.EmailProcessor" ("{category}.{component}.{AdhocName}").
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
112 public function __construct($name, $timeout = NULL, $serverWideLock = FALSE) {
113 $config = CRM_Core_Config
::singleton();
114 $dsn = CRM_Utils_SQL
::autoSwitchDSN($config->dsn
);
115 $dsnArray = DB
::parseDSN($dsn);
116 $database = $dsnArray['database'];
117 $domainID = CRM_Core_Config
::domainID();
118 if ($serverWideLock) {
119 $this->_name
= $name;
122 $this->_name
= $database . '.' . $domainID . '.' . $name;
124 // MySQL 5.7 doesn't like long lock names so creating a lock id
125 $this->_id
= sha1($this->_name
);
126 if (defined('CIVICRM_LOCK_DEBUG')) {
127 CRM_Core_Error
::debug_log_message('trying to construct lock for ' . $this->_name
. '(' . $this->_id
. ')');
129 $this->_timeout
= $timeout !== NULL ?
$timeout : self
::TIMEOUT
;
132 public function __destruct() {
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.
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.
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
152 * @todo bypass hackyHandleBrokenCode for mysql version 5.7.5+
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.
157 * All this means CiviMail locks are first class citizens & any other process gets a 'best effort lock'.
159 * @todo document naming convention for CiviMail locks as this is key to ensuring they work properly.
161 * @param int $timeout
164 * @throws \CRM_Core_Exception
166 public function acquire($timeout = NULL) {
167 if (!$this->_hasLock
) {
168 if (!CRM_Utils_SQL
::supportsMultipleLocks() && self
::$jobLog && CRM_Core_DAO
::singleValueQuery("SELECT IS_USED_LOCK( '" . self
::$jobLog . "')")) {
169 return $this->hackyHandleBrokenCode(self
::$jobLog);
172 $query = "SELECT GET_LOCK( %1, %2 )";
174 1 => [$this->_id
, 'String'],
175 2 => [$timeout ?
$timeout : $this->_timeout
, 'Integer'],
177 $res = CRM_Core_DAO
::singleValueQuery($query, $params);
179 if (defined('CIVICRM_LOCK_DEBUG')) {
180 CRM_Core_Error
::debug_log_message('acquire lock for ' . $this->_name
. '(' . $this->_id
. ')');
182 $this->_hasLock
= TRUE;
183 if (stristr($this->_name
, 'data.mailing.job.')) {
184 self
::$jobLog = $this->_id
;
188 if (defined('CIVICRM_LOCK_DEBUG')) {
189 CRM_Core_Error
::debug_log_message('failed to acquire lock for ' . $this->_name
. '(' . $this->_id
. ')');
193 return $this->_hasLock
;
197 * @return null|string
199 public function release() {
200 if ($this->_hasLock
) {
201 if (defined('CIVICRM_LOCK_DEBUG')) {
202 CRM_Core_Error
::debug_log_message('release lock for ' . $this->_name
. '(' . $this->_id
. ')');
204 $this->_hasLock
= FALSE;
206 if (self
::$jobLog == $this->_id
) {
207 self
::$jobLog = FALSE;
210 $query = "SELECT RELEASE_LOCK( %1 )";
211 $params = [1 => [$this->_id
, 'String']];
212 return CRM_Core_DAO
::singleValueQuery($query, $params);
217 * @return null|string
219 public function isFree() {
220 $query = "SELECT IS_FREE_LOCK( %1 )";
221 $params = [1 => [$this->_id
, 'String']];
222 return CRM_Core_DAO
::singleValueQuery($query, $params);
228 public function isAcquired() {
229 return $this->_hasLock
;
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'
241 * @param string $jobLog
242 * @throws CRM_Core_Exception
245 public function hackyHandleBrokenCode($jobLog) {
246 if (stristr($this->_name
, 'job')) {
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');
250 if (defined('CIVICRM_LOCK_DEBUG')) {
251 CRM_Core_Error
::debug_log_message('(CRM-12856) faking lock for ' . $this->_name
. '(' . $this->_id
. ')');
253 $this->_hasLock
= TRUE;