View source
<?php
namespace Drupal\ultimate_cron\Lock;
class LockMemcache {
private static $locks = NULL;
public static function shutdown() {
if (self::$locks) {
foreach (array_keys(self::$locks) as $lock_id) {
self::unlock($lock_id);
}
}
}
public static function persist($lock_id) {
if (isset(self::$locks)) {
unset(self::$locks[$lock_id]);
}
}
public static function lock($name, $timeout = 30.0) {
if (!isset(self::$locks)) {
self::$locks = array();
ultimate_cron_register_shutdown_function(array(
'Drupal\\ultimate_cron\\Lock\\LockMemcache',
'shutdown',
));
}
$timeout = (int) max($timeout, 1);
$bin = variable_get('ultimate_cron_lock_memcache_bin', 'semaphore');
$lock_id = $name . ':' . uniqid('memcache-lock', TRUE);
if (dmemcache_add($name, $lock_id, $timeout, $bin)) {
self::$locks[$lock_id] = $lock_id;
return $lock_id;
}
return FALSE;
}
public static function expire($name) {
}
public static function unlock($lock_id) {
if (!preg_match('/(.*):memcache-lock.*/', $lock_id, $matches)) {
return FALSE;
}
$name = $matches[1];
$result = FALSE;
if (!($semaphore = self::lock("lock-{$name}"))) {
return FALSE;
}
if (self::isLocked($name) == $lock_id) {
$result = self::unlockRaw($name);
unset(self::$locks[$lock_id]);
}
else {
unset(self::$locks[$lock_id]);
}
self::unlockRaw("lock-{$name}", $semaphore);
return $result;
}
private static function unlockRaw($name, $lock_id = NULL) {
$bin = variable_get('ultimate_cron_lock_memcache_bin', 'semaphore');
if ($lock_id) {
unset(self::$locks[$lock_id]);
}
return dmemcache_delete($name, $bin);
}
public static function reLock($lock_id, $timeout = 30.0) {
if (!preg_match('/(.*):memcache-lock.*/', $lock_id, $matches)) {
return FALSE;
}
$name = $matches[1];
if (!($semaphore = self::lock("lock-{$name}"))) {
return FALSE;
}
$bin = variable_get('ultimate_cron_lock_memcache_bin', 'semaphore');
$current_lock_id = self::isLocked($name);
if ($current_lock_id === FALSE || $current_lock_id === $lock_id) {
if (dmemcache_set($name, $lock_id, $timeout, $bin)) {
self::unlockRaw("lock-{$name}", $semaphore);
self::$locks[$lock_id] = TRUE;
return self::$locks[$lock_id];
}
}
self::unlockRaw("lock-{$name}", $semaphore);
return FALSE;
}
public static function isLocked($name, $ignore_expiration = FALSE) {
$bin = variable_get('ultimate_cron_lock_memcache_bin', 'semaphore');
$result = dmemcache_get($name, $bin);
return $result ? $result : FALSE;
}
public static function isLockedMultiple($names) {
$bin = variable_get('ultimate_cron_lock_memcache_bin', 'semaphore');
$locks = dmemcache_get_multi($names, $bin);
foreach ($names as $name) {
if (!isset($locks[$name])) {
$locks[$name] = FALSE;
}
}
return $locks;
}
public static function cleanup() {
}
}