3 namespace Friendica\Core\Lock;
5 use Friendica\Core\Cache;
6 use Friendica\Database\Database;
7 use Friendica\Util\DateTimeFormat;
10 * Locking driver that stores the locks in the database
12 class DatabaseLock extends Lock
15 * The current ID of the process
22 * @var Database The database connection of Friendica
27 * @param null|int $pid The Id of the current process (null means determine automatically)
29 public function __construct(Database $dba, $pid = null)
32 $this->pid = isset($pid) ? $pid : getmypid();
38 public function acquireLock($key, $timeout = 120, $ttl = Cache::FIVE_MINUTES)
44 $this->dba->lock('locks');
45 $lock = $this->dba->selectFirst('locks', ['locked', 'pid'], ['`name` = ? AND `expires` >= ?', $key, DateTimeFormat::utcNow()]);
47 if ($this->dba->isResult($lock)) {
48 if ($lock['locked']) {
49 // We want to lock something that was already locked by us? So we got the lock.
50 if ($lock['pid'] == $this->pid) {
54 if (!$lock['locked']) {
55 $this->dba->update('locks', ['locked' => true, 'pid' => $this->pid, 'expires' => DateTimeFormat::utc('now + ' . $ttl . 'seconds')], ['name' => $key]);
59 $this->dba->insert('locks', ['name' => $key, 'locked' => true, 'pid' => $this->pid, 'expires' => DateTimeFormat::utc('now + ' . $ttl . 'seconds')]);
61 $this->markAcquire($key);
66 if (!$got_lock && ($timeout > 0)) {
67 usleep(rand(100000, 2000000));
69 } while (!$got_lock && ((time() - $start) < $timeout));
77 public function releaseLock($key, $override = false)
80 $where = ['name' => $key];
82 $where = ['name' => $key, 'pid' => $this->pid];
85 if ($this->dba->exists('locks', $where)) {
86 $return = $this->dba->delete('locks', $where);
91 $this->markRelease($key);
99 public function releaseAll($override = false)
101 $success = parent::releaseAll($override);
106 $where = ['pid' => $this->pid];
108 $return = $this->dba->delete('locks', $where);
110 $this->acquiredLocks = [];
112 return $return && $success;
118 public function isLocked($key)
120 $lock = $this->dba->selectFirst('locks', ['locked'], ['`name` = ? AND `expires` >= ?', $key, DateTimeFormat::utcNow()]);
122 if ($this->dba->isResult($lock)) {
123 return $lock['locked'] !== false;
132 public function getName()
134 return self::TYPE_DATABASE;
140 public function getLocks(string $prefix = '')
142 if (empty($prefix)) {
143 $where = ['`expires` >= ?', DateTimeFormat::utcNow()];
145 $where = ['`expires` >= ? AND `name` LIKE CONCAT(?, \'%\')', DateTimeFormat::utcNow(), $prefix];
148 $stmt = $this->dba->select('locks', ['name'], $where);
151 while ($key = $this->dba->fetch($stmt)) {
152 array_push($keys, $key['name']);
154 $this->dba->close($stmt);