DBLockingProvider.php 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  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 OC\DB\QueryBuilder\Literal;
  28. use OCP\AppFramework\Utility\ITimeFactory;
  29. use OCP\DB\QueryBuilder\IQueryBuilder;
  30. use OCP\IDBConnection;
  31. use OCP\ILogger;
  32. use OCP\Lock\ILockingProvider;
  33. use OCP\Lock\LockedException;
  34. /**
  35. * Locking provider that stores the locks in the database
  36. */
  37. class DBLockingProvider extends AbstractLockingProvider {
  38. /**
  39. * @var \OCP\IDBConnection
  40. */
  41. private $connection;
  42. /**
  43. * @var \OCP\ILogger
  44. */
  45. private $logger;
  46. /**
  47. * @var \OCP\AppFramework\Utility\ITimeFactory
  48. */
  49. private $timeFactory;
  50. private $sharedLocks = [];
  51. /**
  52. * @var bool
  53. */
  54. private $cacheSharedLocks;
  55. /**
  56. * Check if we have an open shared lock for a path
  57. *
  58. * @param string $path
  59. * @return bool
  60. */
  61. protected function isLocallyLocked(string $path): bool {
  62. return isset($this->sharedLocks[$path]) && $this->sharedLocks[$path];
  63. }
  64. /**
  65. * Mark a locally acquired lock
  66. *
  67. * @param string $path
  68. * @param int $type self::LOCK_SHARED or self::LOCK_EXCLUSIVE
  69. */
  70. protected function markAcquire(string $path, int $type) {
  71. parent::markAcquire($path, $type);
  72. if ($this->cacheSharedLocks) {
  73. if ($type === self::LOCK_SHARED) {
  74. $this->sharedLocks[$path] = true;
  75. }
  76. }
  77. }
  78. /**
  79. * Change the type of an existing tracked lock
  80. *
  81. * @param string $path
  82. * @param int $targetType self::LOCK_SHARED or self::LOCK_EXCLUSIVE
  83. */
  84. protected function markChange(string $path, int $targetType) {
  85. parent::markChange($path, $targetType);
  86. if ($this->cacheSharedLocks) {
  87. if ($targetType === self::LOCK_SHARED) {
  88. $this->sharedLocks[$path] = true;
  89. } else if ($targetType === self::LOCK_EXCLUSIVE) {
  90. $this->sharedLocks[$path] = false;
  91. }
  92. }
  93. }
  94. /**
  95. * @param \OCP\IDBConnection $connection
  96. * @param \OCP\ILogger $logger
  97. * @param \OCP\AppFramework\Utility\ITimeFactory $timeFactory
  98. * @param int $ttl
  99. * @param bool $cacheSharedLocks
  100. */
  101. public function __construct(
  102. IDBConnection $connection,
  103. ILogger $logger,
  104. ITimeFactory $timeFactory,
  105. int $ttl = 3600,
  106. $cacheSharedLocks = true
  107. ) {
  108. $this->connection = $connection;
  109. $this->logger = $logger;
  110. $this->timeFactory = $timeFactory;
  111. $this->ttl = $ttl;
  112. $this->cacheSharedLocks = $cacheSharedLocks;
  113. }
  114. /**
  115. * Insert a file locking row if it does not exists.
  116. *
  117. * @param string $path
  118. * @param int $lock
  119. * @return int number of inserted rows
  120. */
  121. protected function initLockField(string $path, int $lock = 0): int {
  122. $expire = $this->getExpireTime();
  123. return $this->connection->insertIfNotExist('*PREFIX*file_locks', ['key' => $path, 'lock' => $lock, 'ttl' => $expire], ['key']);
  124. }
  125. /**
  126. * @return int
  127. */
  128. protected function getExpireTime(): int {
  129. return $this->timeFactory->getTime() + $this->ttl;
  130. }
  131. /**
  132. * @param string $path
  133. * @param int $type self::LOCK_SHARED or self::LOCK_EXCLUSIVE
  134. * @return bool
  135. */
  136. public function isLocked(string $path, int $type): bool {
  137. if ($this->hasAcquiredLock($path, $type)) {
  138. return true;
  139. }
  140. $query = $this->connection->prepare('SELECT `lock` from `*PREFIX*file_locks` WHERE `key` = ?');
  141. $query->execute([$path]);
  142. $lockValue = (int)$query->fetchColumn();
  143. if ($type === self::LOCK_SHARED) {
  144. if ($this->isLocallyLocked($path)) {
  145. // 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
  146. return $lockValue > 1;
  147. } else {
  148. return $lockValue > 0;
  149. }
  150. } else if ($type === self::LOCK_EXCLUSIVE) {
  151. return $lockValue === -1;
  152. } else {
  153. return false;
  154. }
  155. }
  156. /**
  157. * @param string $path
  158. * @param int $type self::LOCK_SHARED or self::LOCK_EXCLUSIVE
  159. * @throws \OCP\Lock\LockedException
  160. */
  161. public function acquireLock(string $path, int $type) {
  162. $expire = $this->getExpireTime();
  163. if ($type === self::LOCK_SHARED) {
  164. if (!$this->isLocallyLocked($path)) {
  165. $result = $this->initLockField($path, 1);
  166. if ($result <= 0) {
  167. $result = $this->connection->executeUpdate(
  168. 'UPDATE `*PREFIX*file_locks` SET `lock` = `lock` + 1, `ttl` = ? WHERE `key` = ? AND `lock` >= 0',
  169. [$expire, $path]
  170. );
  171. }
  172. } else {
  173. $result = 1;
  174. }
  175. } else {
  176. $existing = 0;
  177. if ($this->hasAcquiredLock($path, ILockingProvider::LOCK_SHARED) === false && $this->isLocallyLocked($path)) {
  178. $existing = 1;
  179. }
  180. $result = $this->initLockField($path, -1);
  181. if ($result <= 0) {
  182. $result = $this->connection->executeUpdate(
  183. 'UPDATE `*PREFIX*file_locks` SET `lock` = -1, `ttl` = ? WHERE `key` = ? AND `lock` = ?',
  184. [$expire, $path, $existing]
  185. );
  186. }
  187. }
  188. if ($result !== 1) {
  189. throw new LockedException($path);
  190. }
  191. $this->markAcquire($path, $type);
  192. }
  193. /**
  194. * @param string $path
  195. * @param int $type self::LOCK_SHARED or self::LOCK_EXCLUSIVE
  196. *
  197. * @suppress SqlInjectionChecker
  198. */
  199. public function releaseLock(string $path, int $type) {
  200. $this->markRelease($path, $type);
  201. // we keep shared locks till the end of the request so we can re-use them
  202. if ($type === self::LOCK_EXCLUSIVE) {
  203. $this->connection->executeUpdate(
  204. 'UPDATE `*PREFIX*file_locks` SET `lock` = 0 WHERE `key` = ? AND `lock` = -1',
  205. [$path]
  206. );
  207. } else if (!$this->cacheSharedLocks) {
  208. $query = $this->connection->getQueryBuilder();
  209. $query->update('file_locks')
  210. ->set('lock', $query->func()->subtract('lock', $query->createNamedParameter(1)))
  211. ->where($query->expr()->eq('key', $query->createNamedParameter($path)))
  212. ->andWhere($query->expr()->gt('lock', $query->createNamedParameter(0)));
  213. $query->execute();
  214. }
  215. }
  216. /**
  217. * Change the type of an existing lock
  218. *
  219. * @param string $path
  220. * @param int $targetType self::LOCK_SHARED or self::LOCK_EXCLUSIVE
  221. * @throws \OCP\Lock\LockedException
  222. */
  223. public function changeLock(string $path, int $targetType) {
  224. $expire = $this->getExpireTime();
  225. if ($targetType === self::LOCK_SHARED) {
  226. $result = $this->connection->executeUpdate(
  227. 'UPDATE `*PREFIX*file_locks` SET `lock` = 1, `ttl` = ? WHERE `key` = ? AND `lock` = -1',
  228. [$expire, $path]
  229. );
  230. } else {
  231. // since we only keep one shared lock in the db we need to check if we have more then one shared lock locally manually
  232. if (isset($this->acquiredLocks['shared'][$path]) && $this->acquiredLocks['shared'][$path] > 1) {
  233. throw new LockedException($path);
  234. }
  235. $result = $this->connection->executeUpdate(
  236. 'UPDATE `*PREFIX*file_locks` SET `lock` = -1, `ttl` = ? WHERE `key` = ? AND `lock` = 1',
  237. [$expire, $path]
  238. );
  239. }
  240. if ($result !== 1) {
  241. throw new LockedException($path);
  242. }
  243. $this->markChange($path, $targetType);
  244. }
  245. /**
  246. * cleanup empty locks
  247. */
  248. public function cleanExpiredLocks() {
  249. $expire = $this->timeFactory->getTime();
  250. try {
  251. $this->connection->executeUpdate(
  252. 'DELETE FROM `*PREFIX*file_locks` WHERE `ttl` < ?',
  253. [$expire]
  254. );
  255. } catch (\Exception $e) {
  256. // If the table is missing, the clean up was successful
  257. if ($this->connection->tableExists('file_locks')) {
  258. throw $e;
  259. }
  260. }
  261. }
  262. /**
  263. * release all lock acquired by this instance which were marked using the mark* methods
  264. *
  265. * @suppress SqlInjectionChecker
  266. */
  267. public function releaseAll() {
  268. parent::releaseAll();
  269. if (!$this->cacheSharedLocks) {
  270. return;
  271. }
  272. // since we keep shared locks we need to manually clean those
  273. $lockedPaths = array_keys($this->sharedLocks);
  274. $lockedPaths = array_filter($lockedPaths, function ($path) {
  275. return $this->sharedLocks[$path];
  276. });
  277. $chunkedPaths = array_chunk($lockedPaths, 100);
  278. foreach ($chunkedPaths as $chunk) {
  279. $builder = $this->connection->getQueryBuilder();
  280. $query = $builder->update('file_locks')
  281. ->set('lock', $builder->createFunction('`lock` -1'))
  282. ->where($builder->expr()->in('key', $builder->createNamedParameter($chunk, IQueryBuilder::PARAM_STR_ARRAY)))
  283. ->andWhere($builder->expr()->gt('lock', new Literal(0)));
  284. $query->execute();
  285. }
  286. }
  287. }