Console Lock

WIP
This commit is contained in:
Philipp Holzer 2019-08-13 21:20:41 +02:00
parent 425876316f
commit 41e2031e6b
No known key found for this signature in database
GPG key ID: D8365C3D36B77D90
9 changed files with 420 additions and 25 deletions

View file

@ -20,9 +20,7 @@ class SemaphoreLock extends Lock
*/
private static function semaphoreKey($key)
{
$temp = get_temppath();
$file = $temp . '/' . $key . '.sem';
$file = self::keyToFile($key);
if (!file_exists($file)) {
file_put_contents($file, $key);
@ -31,10 +29,24 @@ class SemaphoreLock extends Lock
return ftok($file, 'f');
}
/**
* Returns the full path to the semaphore file
*
* @param string $key The key of the semaphore
*
* @return string The full path
*/
private static function keyToFile($key)
{
$temp = get_temppath();
return $temp . '/' . $key . '.sem';
}
/**
* (@inheritdoc)
*/
public function acquireLock($key, $timeout = 120, $ttl = Cache::FIVE_MINUTES)
public function acquireLock($key, $timeout = 120, $ttl = Cache\Cache::FIVE_MINUTES)
{
self::$semaphore[$key] = sem_get(self::semaphoreKey($key));
if (self::$semaphore[$key]) {
@ -52,14 +64,24 @@ class SemaphoreLock extends Lock
*/
public function releaseLock($key, $override = false)
{
if (empty(self::$semaphore[$key])) {
return false;
} else {
$success = @sem_release(self::$semaphore[$key]);
unset(self::$semaphore[$key]);
$this->markRelease($key);
return $success;
$success = false;
if (!empty(self::$semaphore[$key])) {
try {
$success = @sem_release(self::$semaphore[$key]) &&
unlink(self::keyToFile($key));
unset(self::$semaphore[$key]);
$this->markRelease($key);
} catch (\Exception $exception) {
$success = false;
}
} else if ($override) {
if ($this->acquireLock($key)) {
$success = $this->releaseLock($key, true);
}
}
return $success;
}
/**
@ -69,4 +91,47 @@ class SemaphoreLock extends Lock
{
return isset(self::$semaphore[$key]);
}
/**
* {@inheritDoc}
*/
public function getName()
{
return self::TYPE_SEMAPHORE;
}
/**
* {@inheritDoc}
*/
public function getLocks(string $prefix = '')
{
$temp = get_temppath();
$locks = [];
foreach (glob(sprintf('%s/%s*.sem', $temp, $prefix)) as $lock) {
$lock = pathinfo($lock, PATHINFO_FILENAME);
if(sem_get(self::semaphoreKey($lock))) {
$locks[] = $lock;
}
}
return $locks;
}
/**
* {@inheritDoc}
*/
public function releaseAll($override = false)
{
$success = parent::releaseAll($override);
$temp = get_temppath();
foreach (glob(sprintf('%s/*.sem', $temp)) as $lock) {
$lock = pathinfo($lock, PATHINFO_FILENAME);
if (!$this->releaseLock($lock, true)) {
$success = false;
}
}
return $success;
}
}