3 * @copyright Copyright (C) 2010-2022, the Friendica project
5 * @license GNU AGPL version 3 or any later version
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as
9 * published by the Free Software Foundation, either version 3 of the
10 * License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 namespace Friendica\Core\Lock\Type;
24 use Friendica\Core\Cache\Enum\Duration;
25 use Friendica\Core\Lock\Enum\Type;
26 use Friendica\Core\Lock\Exception\InvalidLockDriverException;
27 use Friendica\Core\System;
29 class SemaphoreLock extends AbstractLock
31 private static $semaphore = [];
33 public function __construct()
35 if (!function_exists('sem_get')) {
36 throw new InvalidLockDriverException('Semaphore lock not supported');
43 private static function semaphoreKey($key)
47 $temp = System::getTempPath();
49 $file = $temp . '/' . $key . '.sem';
51 if (!file_exists($file)) {
52 $success = !empty(file_put_contents($file, $key));
55 return $success ? ftok($file, 'f') : false;
61 public function acquire(string $key, int $timeout = 120, int $ttl = Duration::FIVE_MINUTES): bool
63 self::$semaphore[$key] = sem_get(self::semaphoreKey($key));
64 if (!empty(self::$semaphore[$key])) {
65 if (sem_acquire(self::$semaphore[$key], ($timeout === 0))) {
66 $this->markAcquire($key);
77 * @param bool $override not necessary parameter for semaphore locks since the lock lives as long as the execution
78 * of the using function
80 public function release(string $key, bool $override = false): bool
84 if (!empty(self::$semaphore[$key])) {
86 $success = @sem_release(self::$semaphore[$key]);
87 unset(self::$semaphore[$key]);
88 $this->markRelease($key);
89 } catch (\Exception $exception) {
100 public function isLocked(string $key): bool
102 return isset(self::$semaphore[$key]);
108 public function getName(): string
110 return Type::SEMAPHORE;
116 public function getLocks(string $prefix = ''): array
118 // We can just return our own semaphore keys, since we don't know
119 // the state of other semaphores, even if the .sem files exists
120 $keys = array_keys(self::$semaphore);
122 if (empty($prefix)) {
127 foreach ($keys as $key) {
128 if (strpos($key, $prefix) === 0) {
129 array_push($result, $key);
140 public function releaseAll(bool $override = false): bool
142 // Semaphores are just alive during a run, so there is no need to release
143 // You can just release your own locks
144 return parent::releaseAll($override);