1
0

DBLockingProvider.php 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Individual IT Services <info@individual-it.net>
  6. * @author Lukas Reschke <lukas@statuscode.ch>
  7. * @author Morris Jobke <hey@morrisjobke.de>
  8. * @author Robin Appelman <robin@icewind.nl>
  9. * @author Roeland Jago Douma <roeland@famdouma.nl>
  10. *
  11. * @license AGPL-3.0
  12. *
  13. * This code is free software: you can redistribute it and/or modify
  14. * it under the terms of the GNU Affero General Public License, version 3,
  15. * as published by the Free Software Foundation.
  16. *
  17. * This program is distributed in the hope that it will be useful,
  18. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  19. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  20. * GNU Affero General Public License for more details.
  21. *
  22. * You should have received a copy of the GNU Affero General Public License, version 3,
  23. * along with this program. If not, see <http://www.gnu.org/licenses/>
  24. *
  25. */
  26. namespace OC\Lock;
  27. use Doctrine\DBAL\Exception\UniqueConstraintViolationException;
  28. use OC\DB\QueryBuilder\Literal;
  29. use OCP\AppFramework\Utility\ITimeFactory;
  30. use OCP\DB\QueryBuilder\IQueryBuilder;
  31. use OCP\IDBConnection;
  32. use OCP\ILogger;
  33. use OCP\Lock\ILockingProvider;
  34. use OCP\Lock\LockedException;
  35. /**
  36. * Locking provider that stores the locks in the database
  37. */
  38. class DBLockingProvider extends AbstractLockingProvider {
  39. /**
  40. * @var \OCP\IDBConnection
  41. */
  42. private $connection;
  43. /**
  44. * @var \OCP\ILogger
  45. */
  46. private $logger;
  47. /**
  48. * @var \OCP\AppFramework\Utility\ITimeFactory
  49. */
  50. private $timeFactory;
  51. private $sharedLocks = [];
  52. /**
  53. * @var bool
  54. */
  55. private $cacheSharedLocks;
  56. /**
  57. * Check if we have an open shared lock for a path
  58. *
  59. * @param string $path
  60. * @return bool
  61. */
  62. protected function isLocallyLocked(string $path): bool {
  63. return isset($this->sharedLocks[$path]) && $this->sharedLocks[$path];
  64. }
  65. /**
  66. * Mark a locally acquired lock
  67. *
  68. * @param string $path
  69. * @param int $type self::LOCK_SHARED or self::LOCK_EXCLUSIVE
  70. */
  71. protected function markAcquire(string $path, int $type) {
  72. parent::markAcquire($path, $type);
  73. if ($this->cacheSharedLocks) {
  74. if ($type === self::LOCK_SHARED) {
  75. $this->sharedLocks[$path] = true;
  76. }
  77. }
  78. }
  79. /**
  80. * Change the type of an existing tracked lock
  81. *
  82. * @param string $path
  83. * @param int $targetType self::LOCK_SHARED or self::LOCK_EXCLUSIVE
  84. */
  85. protected function markChange(string $path, int $targetType) {
  86. parent::markChange($path, $targetType);
  87. if ($this->cacheSharedLocks) {
  88. if ($targetType === self::LOCK_SHARED) {
  89. $this->sharedLocks[$path] = true;
  90. } else if ($targetType === self::LOCK_EXCLUSIVE) {
  91. $this->sharedLocks[$path] = false;
  92. }
  93. }
  94. }
  95. /**
  96. * @param \OCP\IDBConnection $connection
  97. * @param \OCP\ILogger $logger
  98. * @param \OCP\AppFramework\Utility\ITimeFactory $timeFactory
  99. * @param int $ttl
  100. * @param bool $cacheSharedLocks
  101. */
  102. public function __construct(
  103. IDBConnection $connection,
  104. ILogger $logger,
  105. ITimeFactory $timeFactory,
  106. int $ttl = 3600,
  107. $cacheSharedLocks = true
  108. ) {
  109. $this->connection = $connection;
  110. $this->logger = $logger;
  111. $this->timeFactory = $timeFactory;
  112. $this->ttl = $ttl;
  113. $this->cacheSharedLocks = $cacheSharedLocks;
  114. }
  115. /**
  116. * Insert a file locking row if it does not exists.
  117. *
  118. * @param string $path
  119. * @param int $lock
  120. * @return int number of inserted rows
  121. */
  122. protected function initLockField(string $path, int $lock = 0): int {
  123. $expire = $this->getExpireTime();
  124. return $this->connection->insertIgnoreConflict('file_locks', [
  125. 'key' => $path,
  126. 'lock' => $lock,
  127. 'ttl' => $expire
  128. ]);
  129. }
  130. /**
  131. * @return int
  132. */
  133. protected function getExpireTime(): int {
  134. return $this->timeFactory->getTime() + $this->ttl;
  135. }
  136. /**
  137. * @param string $path
  138. * @param int $type self::LOCK_SHARED or self::LOCK_EXCLUSIVE
  139. * @return bool
  140. */
  141. public function isLocked(string $path, int $type): bool {
  142. if ($this->hasAcquiredLock($path, $type)) {
  143. return true;
  144. }
  145. $query = $this->connection->prepare('SELECT `lock` from `*PREFIX*file_locks` WHERE `key` = ?');
  146. $query->execute([$path]);
  147. $lockValue = (int)$query->fetchColumn();
  148. if ($type === self::LOCK_SHARED) {
  149. if ($this->isLocallyLocked($path)) {
  150. // if we have a shared lock we kept open locally but it's released we always have at least 1 shared lock in the db
  151. return $lockValue > 1;
  152. } else {
  153. return $lockValue > 0;
  154. }
  155. } else if ($type === self::LOCK_EXCLUSIVE) {
  156. return $lockValue === -1;
  157. } else {
  158. return false;
  159. }
  160. }
  161. /**
  162. * @param string $path
  163. * @param int $type self::LOCK_SHARED or self::LOCK_EXCLUSIVE
  164. * @throws \OCP\Lock\LockedException
  165. */
  166. public function acquireLock(string $path, int $type) {
  167. $expire = $this->getExpireTime();
  168. if ($type === self::LOCK_SHARED) {
  169. if (!$this->isLocallyLocked($path)) {
  170. $result = $this->initLockField($path, 1);
  171. if ($result <= 0) {
  172. $result = $this->connection->executeUpdate(
  173. 'UPDATE `*PREFIX*file_locks` SET `lock` = `lock` + 1, `ttl` = ? WHERE `key` = ? AND `lock` >= 0',
  174. [$expire, $path]
  175. );
  176. }
  177. } else {
  178. $result = 1;
  179. }
  180. } else {
  181. $existing = 0;
  182. if ($this->hasAcquiredLock($path, ILockingProvider::LOCK_SHARED) === false && $this->isLocallyLocked($path)) {
  183. $existing = 1;
  184. }
  185. $result = $this->initLockField($path, -1);
  186. if ($result <= 0) {
  187. $result = $this->connection->executeUpdate(
  188. 'UPDATE `*PREFIX*file_locks` SET `lock` = -1, `ttl` = ? WHERE `key` = ? AND `lock` = ?',
  189. [$expire, $path, $existing]
  190. );
  191. }
  192. }
  193. if ($result !== 1) {
  194. throw new LockedException($path);
  195. }
  196. $this->markAcquire($path, $type);
  197. }
  198. /**
  199. * @param string $path
  200. * @param int $type self::LOCK_SHARED or self::LOCK_EXCLUSIVE
  201. *
  202. * @suppress SqlInjectionChecker
  203. */
  204. public function releaseLock(string $path, int $type) {
  205. $this->markRelease($path, $type);
  206. // we keep shared locks till the end of the request so we can re-use them
  207. if ($type === self::LOCK_EXCLUSIVE) {
  208. $this->connection->executeUpdate(
  209. 'UPDATE `*PREFIX*file_locks` SET `lock` = 0 WHERE `key` = ? AND `lock` = -1',
  210. [$path]
  211. );
  212. } else if (!$this->cacheSharedLocks) {
  213. $query = $this->connection->getQueryBuilder();
  214. $query->update('file_locks')
  215. ->set('lock', $query->func()->subtract('lock', $query->createNamedParameter(1)))
  216. ->where($query->expr()->eq('key', $query->createNamedParameter($path)))
  217. ->andWhere($query->expr()->gt('lock', $query->createNamedParameter(0)));
  218. $query->execute();
  219. }
  220. }
  221. /**
  222. * Change the type of an existing lock
  223. *
  224. * @param string $path
  225. * @param int $targetType self::LOCK_SHARED or self::LOCK_EXCLUSIVE
  226. * @throws \OCP\Lock\LockedException
  227. */
  228. public function changeLock(string $path, int $targetType) {
  229. $expire = $this->getExpireTime();
  230. if ($targetType === self::LOCK_SHARED) {
  231. $result = $this->connection->executeUpdate(
  232. 'UPDATE `*PREFIX*file_locks` SET `lock` = 1, `ttl` = ? WHERE `key` = ? AND `lock` = -1',
  233. [$expire, $path]
  234. );
  235. } else {
  236. // since we only keep one shared lock in the db we need to check if we have more then one shared lock locally manually
  237. if (isset($this->acquiredLocks['shared'][$path]) && $this->acquiredLocks['shared'][$path] > 1) {
  238. throw new LockedException($path);
  239. }
  240. $result = $this->connection->executeUpdate(
  241. 'UPDATE `*PREFIX*file_locks` SET `lock` = -1, `ttl` = ? WHERE `key` = ? AND `lock` = 1',
  242. [$expire, $path]
  243. );
  244. }
  245. if ($result !== 1) {
  246. throw new LockedException($path);
  247. }
  248. $this->markChange($path, $targetType);
  249. }
  250. /**
  251. * cleanup empty locks
  252. */
  253. public function cleanExpiredLocks() {
  254. $expire = $this->timeFactory->getTime();
  255. try {
  256. $this->connection->executeUpdate(
  257. 'DELETE FROM `*PREFIX*file_locks` WHERE `ttl` < ?',
  258. [$expire]
  259. );
  260. } catch (\Exception $e) {
  261. // If the table is missing, the clean up was successful
  262. if ($this->connection->tableExists('file_locks')) {
  263. throw $e;
  264. }
  265. }
  266. }
  267. /**
  268. * release all lock acquired by this instance which were marked using the mark* methods
  269. *
  270. * @suppress SqlInjectionChecker
  271. */
  272. public function releaseAll() {
  273. parent::releaseAll();
  274. if (!$this->cacheSharedLocks) {
  275. return;
  276. }
  277. // since we keep shared locks we need to manually clean those
  278. $lockedPaths = array_keys($this->sharedLocks);
  279. $lockedPaths = array_filter($lockedPaths, function ($path) {
  280. return $this->sharedLocks[$path];
  281. });
  282. $chunkedPaths = array_chunk($lockedPaths, 100);
  283. foreach ($chunkedPaths as $chunk) {
  284. $builder = $this->connection->getQueryBuilder();
  285. $query = $builder->update('file_locks')
  286. ->set('lock', $builder->func()->subtract('lock', $builder->expr()->literal(1)))
  287. ->where($builder->expr()->in('key', $builder->createNamedParameter($chunk, IQueryBuilder::PARAM_STR_ARRAY)))
  288. ->andWhere($builder->expr()->gt('lock', new Literal(0)));
  289. $query->execute();
  290. }
  291. }
  292. }