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\LockPersistenceException;
27 use Friendica\Database\Database;
28 use Friendica\Util\DateTimeFormat;
31 * Locking driver that stores the locks in the database
33 class DatabaseLock extends AbstractLock
36 * The current ID of the process
43 * @var Database The database connection of Friendica
48 * @param int|null $pid The id of the current process (null means determine automatically)
50 public function __construct(Database $dba, ?int $pid = null)
53 $this->pid = $pid ?? getmypid();
59 public function acquire(string $key, int $timeout = 120, int $ttl = Duration::FIVE_MINUTES): bool
66 $this->dba->lock('locks');
67 $lock = $this->dba->selectFirst('locks', ['locked', 'pid'], [
68 '`name` = ? AND `expires` >= ?', $key,DateTimeFormat::utcNow()
71 if ($this->dba->isResult($lock)) {
72 if ($lock['locked']) {
73 // We want to lock something that was already locked by us? So we got the lock.
74 if ($lock['pid'] == $this->pid) {
78 if (!$lock['locked']) {
79 $this->dba->update('locks', [
82 'expires' => DateTimeFormat::utc('now + ' . $ttl . 'seconds')
87 $this->dba->insert('locks', [
91 'expires' => DateTimeFormat::utc('now + ' . $ttl . 'seconds')]);
93 $this->markAcquire($key);
98 if (!$got_lock && ($timeout > 0)) {
99 usleep(rand(100000, 2000000));
101 } while (!$got_lock && ((time() - $start) < $timeout));
102 } catch (\Exception $exception) {
103 throw new LockPersistenceException(sprintf('Cannot acquire lock for key %s', $key), $exception);
112 public function release(string $key, bool $override = false): bool
115 $where = ['name' => $key];
117 $where = ['name' => $key, 'pid' => $this->pid];
121 if ($this->dba->exists('locks', $where)) {
122 $return = $this->dba->delete('locks', $where);
126 } catch (\Exception $exception) {
127 throw new LockPersistenceException(sprintf('Cannot release lock for key %s (override %b)', $key, $override), $exception);
130 $this->markRelease($key);
138 public function releaseAll(bool $override = false): bool
140 $success = parent::releaseAll($override);
145 $where = ['pid' => $this->pid];
149 $return = $this->dba->delete('locks', $where);
150 } catch (\Exception $exception) {
151 throw new LockPersistenceException(sprintf('Cannot release all lock (override %b)', $override), $exception);
154 $this->acquiredLocks = [];
156 return $return && $success;
162 public function isLocked(string $key): bool
165 $lock = $this->dba->selectFirst('locks', ['locked'], [
166 '`name` = ? AND `expires` >= ?', $key, DateTimeFormat::utcNow()]);
167 } catch (\Exception $exception) {
168 throw new LockPersistenceException(sprintf('Cannot check lock state for key %s', $key), $exception);
171 if ($this->dba->isResult($lock)) {
172 return $lock['locked'] !== false;
181 public function getName(): string
183 return Type::DATABASE;
189 public function getLocks(string $prefix = ''): array
192 if (empty($prefix)) {
193 $where = ['`expires` >= ?', DateTimeFormat::utcNow()];
195 $where = ['`expires` >= ? AND `name` LIKE CONCAT(?, \'%\')', DateTimeFormat::utcNow(), $prefix];
198 $stmt = $this->dba->select('locks', ['name'], $where);
201 while ($key = $this->dba->fetch($stmt)) {
202 array_push($keys, $key['name']);
204 } catch (\Exception $exception) {
205 throw new LockPersistenceException(sprintf('Cannot get lock with prefix %s', $prefix), $exception);
207 $this->dba->close($stmt);