]> git.mxchange.org Git - friendica.git/blob - src/Core/Lock/Type/DatabaseLock.php
Merge pull request #11520 from annando/display-polls
[friendica.git] / src / Core / Lock / Type / DatabaseLock.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2022, the Friendica project
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
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.
11  *
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.
16  *
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/>.
19  *
20  */
21
22 namespace Friendica\Core\Lock\Type;
23
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;
29
30 /**
31  * Locking driver that stores the locks in the database
32  */
33 class DatabaseLock extends AbstractLock
34 {
35         /**
36          * The current ID of the process
37          *
38          * @var int
39          */
40         private $pid;
41
42         /**
43          * @var Database The database connection of Friendica
44          */
45         private $dba;
46
47         /**
48          * @param int|null $pid The id of the current process (null means determine automatically)
49          */
50         public function __construct(Database $dba, ?int $pid = null)
51         {
52                 $this->dba = $dba;
53                 $this->pid = $pid ?? getmypid();
54         }
55
56         /**
57          * (@inheritdoc)
58          */
59         public function acquire(string $key, int $timeout = 120, int $ttl = Duration::FIVE_MINUTES): bool
60         {
61                 $got_lock = false;
62                 $start    = time();
63
64                 try {
65                         do {
66                                 $this->dba->lock('locks');
67                                 $lock = $this->dba->selectFirst('locks', ['locked', 'pid'], [
68                                         '`name` = ? AND `expires` >= ?', $key,DateTimeFormat::utcNow()
69                                 ]);
70
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) {
75                                                         $got_lock = true;
76                                                 }
77                                         }
78                                         if (!$lock['locked']) {
79                                                 $this->dba->update('locks', [
80                                                         'locked'  => true,
81                                                         'pid'     => $this->pid,
82                                                         'expires' => DateTimeFormat::utc('now + ' . $ttl . 'seconds')
83                                                 ], ['name' => $key]);
84                                                 $got_lock = true;
85                                         }
86                                 } else {
87                                         $this->dba->insert('locks', [
88                                                 'name'    => $key,
89                                                 'locked'  => true,
90                                                 'pid'     => $this->pid,
91                                                 'expires' => DateTimeFormat::utc('now + ' . $ttl . 'seconds')]);
92                                         $got_lock = true;
93                                         $this->markAcquire($key);
94                                 }
95
96                                 $this->dba->unlock();
97
98                                 if (!$got_lock && ($timeout > 0)) {
99                                         usleep(rand(100000, 2000000));
100                                 }
101                         } while (!$got_lock && ((time() - $start) < $timeout));
102                 } catch (\Exception $exception) {
103                         throw new LockPersistenceException(sprintf('Cannot acquire lock for key %s', $key), $exception);
104                 }
105
106                 return $got_lock;
107         }
108
109         /**
110          * (@inheritdoc)
111          */
112         public function release(string $key, bool $override = false): bool
113         {
114                 if ($override) {
115                         $where = ['name' => $key];
116                 } else {
117                         $where = ['name' => $key, 'pid' => $this->pid];
118                 }
119
120                 try {
121                         if ($this->dba->exists('locks', $where)) {
122                                 $return = $this->dba->delete('locks', $where);
123                         } else {
124                                 $return = false;
125                         }
126                 } catch (\Exception $exception) {
127                         throw new LockPersistenceException(sprintf('Cannot release lock for key %s (override %b)', $key, $override), $exception);
128                 }
129
130                 $this->markRelease($key);
131
132                 return $return;
133         }
134
135         /**
136          * (@inheritdoc)
137          */
138         public function releaseAll(bool $override = false): bool
139         {
140                 $success = parent::releaseAll($override);
141
142                 if ($override) {
143                         $where = ['1 = 1'];
144                 } else {
145                         $where = ['pid' => $this->pid];
146                 }
147
148                 try {
149                         $return = $this->dba->delete('locks', $where);
150                 } catch (\Exception $exception) {
151                         throw new LockPersistenceException(sprintf('Cannot release all lock (override %b)', $override), $exception);
152                 }
153
154                 $this->acquiredLocks = [];
155
156                 return $return && $success;
157         }
158
159         /**
160          * (@inheritdoc)
161          */
162         public function isLocked(string $key): bool
163         {
164                 try {
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);
169                 }
170
171                 if ($this->dba->isResult($lock)) {
172                         return $lock['locked'] !== false;
173                 } else {
174                         return false;
175                 }
176         }
177
178         /**
179          * {@inheritDoc}
180          */
181         public function getName(): string
182         {
183                 return Type::DATABASE;
184         }
185
186         /**
187          * {@inheritDoc}
188          */
189         public function getLocks(string $prefix = ''): array
190         {
191                 try {
192                         if (empty($prefix)) {
193                                 $where = ['`expires` >= ?', DateTimeFormat::utcNow()];
194                         } else {
195                                 $where = ['`expires` >= ? AND `name` LIKE CONCAT(?, \'%\')', DateTimeFormat::utcNow(), $prefix];
196                         }
197
198                         $stmt = $this->dba->select('locks', ['name'], $where);
199
200                         $keys = [];
201                         while ($key = $this->dba->fetch($stmt)) {
202                                 array_push($keys, $key['name']);
203                         }
204                 } catch (\Exception $exception) {
205                         throw new LockPersistenceException(sprintf('Cannot get lock with prefix %s', $prefix), $exception);
206                 } finally {
207                         $this->dba->close($stmt);
208                 }
209
210                 return $keys;
211         }
212 }