DBLockingProvider.php 7.8 KB

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