3 namespace Friendica\Core\Lock;
5 use Friendica\Core\BaseLock;
6 use Friendica\Core\Cache\Duration;
7 use Friendica\Database\Database;
8 use Friendica\Util\DateTimeFormat;
11 * Locking driver that stores the locks in the database
13 class DatabaseLock extends BaseLock
16 * The current ID of the process
23 * @var Database The database connection of Friendica
28 * @param null|int $pid The Id of the current process (null means determine automatically)
30 public function __construct(Database $dba, $pid = null)
33 $this->pid = isset($pid) ? $pid : getmypid();
39 public function acquire($key, $timeout = 120, $ttl = Duration::FIVE_MINUTES)
45 $this->dba->lock('locks');
46 $lock = $this->dba->selectFirst('locks', ['locked', 'pid'], ['`name` = ? AND `expires` >= ?', $key, DateTimeFormat::utcNow()]);
48 if ($this->dba->isResult($lock)) {
49 if ($lock['locked']) {
50 // We want to lock something that was already locked by us? So we got the lock.
51 if ($lock['pid'] == $this->pid) {
55 if (!$lock['locked']) {
56 $this->dba->update('locks', ['locked' => true, 'pid' => $this->pid, 'expires' => DateTimeFormat::utc('now + ' . $ttl . 'seconds')], ['name' => $key]);
60 $this->dba->insert('locks', ['name' => $key, 'locked' => true, 'pid' => $this->pid, 'expires' => DateTimeFormat::utc('now + ' . $ttl . 'seconds')]);
62 $this->markAcquire($key);
67 if (!$got_lock && ($timeout > 0)) {
68 usleep(rand(100000, 2000000));
70 } while (!$got_lock && ((time() - $start) < $timeout));
78 public function release($key, $override = false)
81 $where = ['name' => $key];
83 $where = ['name' => $key, 'pid' => $this->pid];
86 if ($this->dba->exists('locks', $where)) {
87 $return = $this->dba->delete('locks', $where);
92 $this->markRelease($key);
100 public function releaseAll($override = false)
102 $success = parent::releaseAll($override);
107 $where = ['pid' => $this->pid];
109 $return = $this->dba->delete('locks', $where);
111 $this->acquiredLocks = [];
113 return $return && $success;
119 public function isLocked($key)
121 $lock = $this->dba->selectFirst('locks', ['locked'], ['`name` = ? AND `expires` >= ?', $key, DateTimeFormat::utcNow()]);
123 if ($this->dba->isResult($lock)) {
124 return $lock['locked'] !== false;
133 public function getName()
135 return Type::DATABASE;
141 public function getLocks(string $prefix = '')
143 if (empty($prefix)) {
144 $where = ['`expires` >= ?', DateTimeFormat::utcNow()];
146 $where = ['`expires` >= ? AND `name` LIKE CONCAT(?, \'%\')', DateTimeFormat::utcNow(), $prefix];
149 $stmt = $this->dba->select('locks', ['name'], $where);
152 while ($key = $this->dba->fetch($stmt)) {
153 array_push($keys, $key['name']);
155 $this->dba->close($stmt);