DBLockingProvider.php 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  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. try {
  125. $builder = $this->connection->getQueryBuilder();
  126. return $builder->insert('file_locks')
  127. ->setValue('key', $builder->createNamedParameter($path))
  128. ->setValue('lock', $builder->createNamedParameter($lock))
  129. ->setValue('ttl', $builder->createNamedParameter($expire))
  130. ->execute();
  131. } catch(UniqueConstraintViolationException $e) {
  132. return 0;
  133. }
  134. }
  135. /**
  136. * @return int
  137. */
  138. protected function getExpireTime(): int {
  139. return $this->timeFactory->getTime() + $this->ttl;
  140. }
  141. /**
  142. * @param string $path
  143. * @param int $type self::LOCK_SHARED or self::LOCK_EXCLUSIVE
  144. * @return bool
  145. */
  146. public function isLocked(string $path, int $type): bool {
  147. if ($this->hasAcquiredLock($path, $type)) {
  148. return true;
  149. }
  150. $query = $this->connection->prepare('SELECT `lock` from `*PREFIX*file_locks` WHERE `key` = ?');
  151. $query->execute([$path]);
  152. $lockValue = (int)$query->fetchColumn();
  153. if ($type === self::LOCK_SHARED) {
  154. if ($this->isLocallyLocked($path)) {
  155. // 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
  156. return $lockValue > 1;
  157. } else {
  158. return $lockValue > 0;
  159. }
  160. } else if ($type === self::LOCK_EXCLUSIVE) {
  161. return $lockValue === -1;
  162. } else {
  163. return false;
  164. }
  165. }
  166. /**
  167. * @param string $path
  168. * @param int $type self::LOCK_SHARED or self::LOCK_EXCLUSIVE
  169. * @throws \OCP\Lock\LockedException
  170. */
  171. public function acquireLock(string $path, int $type) {
  172. $expire = $this->getExpireTime();
  173. if ($type === self::LOCK_SHARED) {
  174. if (!$this->isLocallyLocked($path)) {
  175. $result = $this->initLockField($path, 1);
  176. if ($result <= 0) {
  177. $result = $this->connection->executeUpdate(
  178. 'UPDATE `*PREFIX*file_locks` SET `lock` = `lock` + 1, `ttl` = ? WHERE `key` = ? AND `lock` >= 0',
  179. [$expire, $path]
  180. );
  181. }
  182. } else {
  183. $result = 1;
  184. }
  185. } else {
  186. $existing = 0;
  187. if ($this->hasAcquiredLock($path, ILockingProvider::LOCK_SHARED) === false && $this->isLocallyLocked($path)) {
  188. $existing = 1;
  189. }
  190. $result = $this->initLockField($path, -1);
  191. if ($result <= 0) {
  192. $result = $this->connection->executeUpdate(
  193. 'UPDATE `*PREFIX*file_locks` SET `lock` = -1, `ttl` = ? WHERE `key` = ? AND `lock` = ?',
  194. [$expire, $path, $existing]
  195. );
  196. }
  197. }
  198. if ($result !== 1) {
  199. throw new LockedException($path);
  200. }
  201. $this->markAcquire($path, $type);
  202. }
  203. /**
  204. * @param string $path
  205. * @param int $type self::LOCK_SHARED or self::LOCK_EXCLUSIVE
  206. *
  207. * @suppress SqlInjectionChecker
  208. */
  209. public function releaseLock(string $path, int $type) {
  210. $this->markRelease($path, $type);
  211. // we keep shared locks till the end of the request so we can re-use them
  212. if ($type === self::LOCK_EXCLUSIVE) {
  213. $this->connection->executeUpdate(
  214. 'UPDATE `*PREFIX*file_locks` SET `lock` = 0 WHERE `key` = ? AND `lock` = -1',
  215. [$path]
  216. );
  217. } else if (!$this->cacheSharedLocks) {
  218. $query = $this->connection->getQueryBuilder();
  219. $query->update('file_locks')
  220. ->set('lock', $query->func()->subtract('lock', $query->createNamedParameter(1)))
  221. ->where($query->expr()->eq('key', $query->createNamedParameter($path)))
  222. ->andWhere($query->expr()->gt('lock', $query->createNamedParameter(0)));
  223. $query->execute();
  224. }
  225. }
  226. /**
  227. * Change the type of an existing lock
  228. *
  229. * @param string $path
  230. * @param int $targetType self::LOCK_SHARED or self::LOCK_EXCLUSIVE
  231. * @throws \OCP\Lock\LockedException
  232. */
  233. public function changeLock(string $path, int $targetType) {
  234. $expire = $this->getExpireTime();
  235. if ($targetType === self::LOCK_SHARED) {
  236. $result = $this->connection->executeUpdate(
  237. 'UPDATE `*PREFIX*file_locks` SET `lock` = 1, `ttl` = ? WHERE `key` = ? AND `lock` = -1',
  238. [$expire, $path]
  239. );
  240. } else {
  241. // since we only keep one shared lock in the db we need to check if we have more then one shared lock locally manually
  242. if (isset($this->acquiredLocks['shared'][$path]) && $this->acquiredLocks['shared'][$path] > 1) {
  243. throw new LockedException($path);
  244. }
  245. $result = $this->connection->executeUpdate(
  246. 'UPDATE `*PREFIX*file_locks` SET `lock` = -1, `ttl` = ? WHERE `key` = ? AND `lock` = 1',
  247. [$expire, $path]
  248. );
  249. }
  250. if ($result !== 1) {
  251. throw new LockedException($path);
  252. }
  253. $this->markChange($path, $targetType);
  254. }
  255. /**
  256. * cleanup empty locks
  257. */
  258. public function cleanExpiredLocks() {
  259. $expire = $this->timeFactory->getTime();
  260. try {
  261. $this->connection->executeUpdate(
  262. 'DELETE FROM `*PREFIX*file_locks` WHERE `ttl` < ?',
  263. [$expire]
  264. );
  265. } catch (\Exception $e) {
  266. // If the table is missing, the clean up was successful
  267. if ($this->connection->tableExists('file_locks')) {
  268. throw $e;
  269. }
  270. }
  271. }
  272. /**
  273. * release all lock acquired by this instance which were marked using the mark* methods
  274. *
  275. * @suppress SqlInjectionChecker
  276. */
  277. public function releaseAll() {
  278. parent::releaseAll();
  279. if (!$this->cacheSharedLocks) {
  280. return;
  281. }
  282. // since we keep shared locks we need to manually clean those
  283. $lockedPaths = array_keys($this->sharedLocks);
  284. $lockedPaths = array_filter($lockedPaths, function ($path) {
  285. return $this->sharedLocks[$path];
  286. });
  287. $chunkedPaths = array_chunk($lockedPaths, 100);
  288. foreach ($chunkedPaths as $chunk) {
  289. $builder = $this->connection->getQueryBuilder();
  290. $query = $builder->update('file_locks')
  291. ->set('lock', $builder->func()->subtract('lock', $builder->expr()->literal(1)))
  292. ->where($builder->expr()->in('key', $builder->createNamedParameter($chunk, IQueryBuilder::PARAM_STR_ARRAY)))
  293. ->andWhere($builder->expr()->gt('lock', new Literal(0)));
  294. $query->execute();
  295. }
  296. }
  297. }