Propagator.php 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Joas Schilling <coding@schilljs.com>
  6. * @author Robin Appelman <robin@icewind.nl>
  7. * @author Roeland Jago Douma <roeland@famdouma.nl>
  8. *
  9. * @license AGPL-3.0
  10. *
  11. * This code is free software: you can redistribute it and/or modify
  12. * it under the terms of the GNU Affero General Public License, version 3,
  13. * as published by the Free Software Foundation.
  14. *
  15. * This program is distributed in the hope that it will be useful,
  16. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. * GNU Affero General Public License for more details.
  19. *
  20. * You should have received a copy of the GNU Affero General Public License, version 3,
  21. * along with this program. If not, see <http://www.gnu.org/licenses/>
  22. *
  23. */
  24. namespace OC\Files\Cache;
  25. use OC\DB\Exceptions\DbalException;
  26. use OC\Files\Storage\Wrapper\Encryption;
  27. use OCP\DB\QueryBuilder\IQueryBuilder;
  28. use OCP\Files\Cache\IPropagator;
  29. use OCP\Files\Storage\IReliableEtagStorage;
  30. use OCP\IDBConnection;
  31. use Psr\Log\LoggerInterface;
  32. /**
  33. * Propagate etags and mtimes within the storage
  34. */
  35. class Propagator implements IPropagator {
  36. public const MAX_RETRIES = 3;
  37. private $inBatch = false;
  38. private $batch = [];
  39. /**
  40. * @var \OC\Files\Storage\Storage
  41. */
  42. protected $storage;
  43. /**
  44. * @var IDBConnection
  45. */
  46. private $connection;
  47. /**
  48. * @var array
  49. */
  50. private $ignore = [];
  51. public function __construct(\OC\Files\Storage\Storage $storage, IDBConnection $connection, array $ignore = []) {
  52. $this->storage = $storage;
  53. $this->connection = $connection;
  54. $this->ignore = $ignore;
  55. }
  56. /**
  57. * @param string $internalPath
  58. * @param int $time
  59. * @param int $sizeDifference number of bytes the file has grown
  60. */
  61. public function propagateChange($internalPath, $time, $sizeDifference = 0) {
  62. // Do not propagate changes in ignored paths
  63. foreach ($this->ignore as $ignore) {
  64. if (str_starts_with($internalPath, $ignore)) {
  65. return;
  66. }
  67. }
  68. $storageId = (int)$this->storage->getStorageCache()->getNumericId();
  69. $parents = $this->getParents($internalPath);
  70. if ($this->inBatch) {
  71. foreach ($parents as $parent) {
  72. $this->addToBatch($parent, $time, $sizeDifference);
  73. }
  74. return;
  75. }
  76. $parentHashes = array_map('md5', $parents);
  77. $etag = uniqid(); // since we give all folders the same etag we don't ask the storage for the etag
  78. $builder = $this->connection->getQueryBuilder();
  79. $hashParams = array_map(function ($hash) use ($builder) {
  80. return $builder->expr()->literal($hash);
  81. }, $parentHashes);
  82. $builder->update('filecache')
  83. ->set('mtime', $builder->func()->greatest('mtime', $builder->createNamedParameter((int)$time, IQueryBuilder::PARAM_INT)))
  84. ->where($builder->expr()->eq('storage', $builder->createNamedParameter($storageId, IQueryBuilder::PARAM_INT)))
  85. ->andWhere($builder->expr()->in('path_hash', $hashParams));
  86. if (!$this->storage->instanceOfStorage(IReliableEtagStorage::class)) {
  87. $builder->set('etag', $builder->createNamedParameter($etag, IQueryBuilder::PARAM_STR));
  88. }
  89. if ($sizeDifference !== 0) {
  90. $hasCalculatedSize = $builder->expr()->gt('size', $builder->expr()->literal(-1, IQUeryBuilder::PARAM_INT));
  91. $sizeColumn = $builder->getColumnName('size');
  92. $newSize = $builder->func()->greatest(
  93. $builder->func()->add('size', $builder->createNamedParameter($sizeDifference)),
  94. $builder->createNamedParameter(-1, IQueryBuilder::PARAM_INT)
  95. );
  96. // Only update if row had a previously calculated size
  97. $builder->set('size', $builder->createFunction("CASE WHEN $hasCalculatedSize THEN $newSize ELSE $sizeColumn END"));
  98. if ($this->storage->instanceOfStorage(Encryption::class)) {
  99. // in case of encryption being enabled after some files are already uploaded, some entries will have an unencrypted_size of 0 and a non-zero size
  100. $hasUnencryptedSize = $builder->expr()->neq('unencrypted_size', $builder->expr()->literal(0, IQueryBuilder::PARAM_INT));
  101. $sizeColumn = $builder->getColumnName('size');
  102. $unencryptedSizeColumn = $builder->getColumnName('unencrypted_size');
  103. $newUnencryptedSize = $builder->func()->greatest(
  104. $builder->func()->add(
  105. $builder->createFunction("CASE WHEN $hasUnencryptedSize THEN $unencryptedSizeColumn ELSE $sizeColumn END"),
  106. $builder->createNamedParameter($sizeDifference)
  107. ),
  108. $builder->createNamedParameter(-1, IQueryBuilder::PARAM_INT)
  109. );
  110. // Only update if row had a previously calculated size
  111. $builder->set('unencrypted_size', $builder->createFunction("CASE WHEN $hasCalculatedSize THEN $newUnencryptedSize ELSE $unencryptedSizeColumn END"));
  112. }
  113. }
  114. for ($i = 0; $i < self::MAX_RETRIES; $i++) {
  115. try {
  116. $builder->executeStatement();
  117. break;
  118. } catch (DbalException $e) {
  119. if (!$e->isRetryable()) {
  120. throw $e;
  121. }
  122. /** @var LoggerInterface $loggerInterface */
  123. $loggerInterface = \OCP\Server::get(LoggerInterface::class);
  124. $loggerInterface->warning('Retrying propagation query after retryable exception.', [ 'exception' => $e ]);
  125. }
  126. }
  127. }
  128. protected function getParents($path) {
  129. $parts = explode('/', $path);
  130. $parent = '';
  131. $parents = [];
  132. foreach ($parts as $part) {
  133. $parents[] = $parent;
  134. $parent = trim($parent . '/' . $part, '/');
  135. }
  136. return $parents;
  137. }
  138. /**
  139. * Mark the beginning of a propagation batch
  140. *
  141. * Note that not all cache setups support propagation in which case this will be a noop
  142. *
  143. * Batching for cache setups that do support it has to be explicit since the cache state is not fully consistent
  144. * before the batch is committed.
  145. */
  146. public function beginBatch() {
  147. $this->inBatch = true;
  148. }
  149. private function addToBatch($internalPath, $time, $sizeDifference) {
  150. if (!isset($this->batch[$internalPath])) {
  151. $this->batch[$internalPath] = [
  152. 'hash' => md5($internalPath),
  153. 'time' => $time,
  154. 'size' => $sizeDifference,
  155. ];
  156. } else {
  157. $this->batch[$internalPath]['size'] += $sizeDifference;
  158. if ($time > $this->batch[$internalPath]['time']) {
  159. $this->batch[$internalPath]['time'] = $time;
  160. }
  161. }
  162. }
  163. /**
  164. * Commit the active propagation batch
  165. */
  166. public function commitBatch() {
  167. if (!$this->inBatch) {
  168. throw new \BadMethodCallException('Not in batch');
  169. }
  170. $this->inBatch = false;
  171. $this->connection->beginTransaction();
  172. $query = $this->connection->getQueryBuilder();
  173. $storageId = (int)$this->storage->getStorageCache()->getNumericId();
  174. $query->update('filecache')
  175. ->set('mtime', $query->func()->greatest('mtime', $query->createParameter('time')))
  176. ->set('etag', $query->expr()->literal(uniqid()))
  177. ->where($query->expr()->eq('storage', $query->expr()->literal($storageId, IQueryBuilder::PARAM_INT)))
  178. ->andWhere($query->expr()->eq('path_hash', $query->createParameter('hash')));
  179. $sizeQuery = $this->connection->getQueryBuilder();
  180. $sizeQuery->update('filecache')
  181. ->set('size', $sizeQuery->func()->add('size', $sizeQuery->createParameter('size')))
  182. ->where($query->expr()->eq('storage', $query->expr()->literal($storageId, IQueryBuilder::PARAM_INT)))
  183. ->andWhere($query->expr()->eq('path_hash', $query->createParameter('hash')))
  184. ->andWhere($sizeQuery->expr()->gt('size', $sizeQuery->expr()->literal(-1, IQueryBuilder::PARAM_INT)));
  185. foreach ($this->batch as $item) {
  186. $query->setParameter('time', $item['time'], IQueryBuilder::PARAM_INT);
  187. $query->setParameter('hash', $item['hash']);
  188. $query->execute();
  189. if ($item['size']) {
  190. $sizeQuery->setParameter('size', $item['size'], IQueryBuilder::PARAM_INT);
  191. $sizeQuery->setParameter('hash', $item['hash']);
  192. $sizeQuery->execute();
  193. }
  194. }
  195. $this->batch = [];
  196. $this->connection->commit();
  197. }
  198. }