1
0

Propagator.php 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2016-2024 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  5. * SPDX-License-Identifier: AGPL-3.0-only
  6. */
  7. namespace OC\Files\Cache;
  8. use OC\DB\Exceptions\DbalException;
  9. use OC\Files\Storage\Wrapper\Encryption;
  10. use OCP\DB\QueryBuilder\IQueryBuilder;
  11. use OCP\Files\Cache\IPropagator;
  12. use OCP\Files\Storage\IReliableEtagStorage;
  13. use OCP\IDBConnection;
  14. use OCP\Server;
  15. use Psr\Clock\ClockInterface;
  16. use Psr\Log\LoggerInterface;
  17. /**
  18. * Propagate etags and mtimes within the storage
  19. */
  20. class Propagator implements IPropagator {
  21. public const MAX_RETRIES = 3;
  22. private $inBatch = false;
  23. private $batch = [];
  24. /**
  25. * @var \OC\Files\Storage\Storage
  26. */
  27. protected $storage;
  28. /**
  29. * @var IDBConnection
  30. */
  31. private $connection;
  32. /**
  33. * @var array
  34. */
  35. private $ignore = [];
  36. private ClockInterface $clock;
  37. public function __construct(\OC\Files\Storage\Storage $storage, IDBConnection $connection, array $ignore = []) {
  38. $this->storage = $storage;
  39. $this->connection = $connection;
  40. $this->ignore = $ignore;
  41. $this->clock = Server::get(ClockInterface::class);
  42. }
  43. /**
  44. * @param string $internalPath
  45. * @param int $time
  46. * @param int $sizeDifference number of bytes the file has grown
  47. */
  48. public function propagateChange($internalPath, $time, $sizeDifference = 0) {
  49. // Do not propagate changes in ignored paths
  50. foreach ($this->ignore as $ignore) {
  51. if (str_starts_with($internalPath, $ignore)) {
  52. return;
  53. }
  54. }
  55. $time = min((int)$time, $this->clock->now()->getTimestamp());
  56. $storageId = $this->storage->getStorageCache()->getNumericId();
  57. $parents = $this->getParents($internalPath);
  58. if ($this->inBatch) {
  59. foreach ($parents as $parent) {
  60. $this->addToBatch($parent, $time, $sizeDifference);
  61. }
  62. return;
  63. }
  64. $parentHashes = array_map('md5', $parents);
  65. $etag = uniqid(); // since we give all folders the same etag we don't ask the storage for the etag
  66. $builder = $this->connection->getQueryBuilder();
  67. $hashParams = array_map(function ($hash) use ($builder) {
  68. return $builder->expr()->literal($hash);
  69. }, $parentHashes);
  70. $builder->update('filecache')
  71. ->set('mtime', $builder->func()->greatest('mtime', $builder->createNamedParameter($time, IQueryBuilder::PARAM_INT)))
  72. ->where($builder->expr()->eq('storage', $builder->createNamedParameter($storageId, IQueryBuilder::PARAM_INT)))
  73. ->andWhere($builder->expr()->in('path_hash', $hashParams));
  74. if (!$this->storage->instanceOfStorage(IReliableEtagStorage::class)) {
  75. $builder->set('etag', $builder->createNamedParameter($etag, IQueryBuilder::PARAM_STR));
  76. }
  77. if ($sizeDifference !== 0) {
  78. $hasCalculatedSize = $builder->expr()->gt('size', $builder->expr()->literal(-1, IQUeryBuilder::PARAM_INT));
  79. $sizeColumn = $builder->getColumnName('size');
  80. $newSize = $builder->func()->greatest(
  81. $builder->func()->add('size', $builder->createNamedParameter($sizeDifference)),
  82. $builder->createNamedParameter(-1, IQueryBuilder::PARAM_INT)
  83. );
  84. // Only update if row had a previously calculated size
  85. $builder->set('size', $builder->createFunction("CASE WHEN $hasCalculatedSize THEN $newSize ELSE $sizeColumn END"));
  86. if ($this->storage->instanceOfStorage(Encryption::class)) {
  87. // 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
  88. $hasUnencryptedSize = $builder->expr()->neq('unencrypted_size', $builder->expr()->literal(0, IQueryBuilder::PARAM_INT));
  89. $sizeColumn = $builder->getColumnName('size');
  90. $unencryptedSizeColumn = $builder->getColumnName('unencrypted_size');
  91. $newUnencryptedSize = $builder->func()->greatest(
  92. $builder->func()->add(
  93. $builder->createFunction("CASE WHEN $hasUnencryptedSize THEN $unencryptedSizeColumn ELSE $sizeColumn END"),
  94. $builder->createNamedParameter($sizeDifference)
  95. ),
  96. $builder->createNamedParameter(-1, IQueryBuilder::PARAM_INT)
  97. );
  98. // Only update if row had a previously calculated size
  99. $builder->set('unencrypted_size', $builder->createFunction("CASE WHEN $hasCalculatedSize THEN $newUnencryptedSize ELSE $unencryptedSizeColumn END"));
  100. }
  101. }
  102. for ($i = 0; $i < self::MAX_RETRIES; $i++) {
  103. try {
  104. $builder->executeStatement();
  105. break;
  106. } catch (DbalException $e) {
  107. if (!$e->isRetryable()) {
  108. throw $e;
  109. }
  110. /** @var LoggerInterface $loggerInterface */
  111. $loggerInterface = \OCP\Server::get(LoggerInterface::class);
  112. $loggerInterface->warning('Retrying propagation query after retryable exception.', [ 'exception' => $e ]);
  113. }
  114. }
  115. }
  116. protected function getParents($path) {
  117. $parts = explode('/', $path);
  118. $parent = '';
  119. $parents = [];
  120. foreach ($parts as $part) {
  121. $parents[] = $parent;
  122. $parent = trim($parent . '/' . $part, '/');
  123. }
  124. return $parents;
  125. }
  126. /**
  127. * Mark the beginning of a propagation batch
  128. *
  129. * Note that not all cache setups support propagation in which case this will be a noop
  130. *
  131. * Batching for cache setups that do support it has to be explicit since the cache state is not fully consistent
  132. * before the batch is committed.
  133. */
  134. public function beginBatch() {
  135. $this->inBatch = true;
  136. }
  137. private function addToBatch($internalPath, $time, $sizeDifference) {
  138. if (!isset($this->batch[$internalPath])) {
  139. $this->batch[$internalPath] = [
  140. 'hash' => md5($internalPath),
  141. 'time' => $time,
  142. 'size' => $sizeDifference,
  143. ];
  144. } else {
  145. $this->batch[$internalPath]['size'] += $sizeDifference;
  146. if ($time > $this->batch[$internalPath]['time']) {
  147. $this->batch[$internalPath]['time'] = $time;
  148. }
  149. }
  150. }
  151. /**
  152. * Commit the active propagation batch
  153. */
  154. public function commitBatch() {
  155. if (!$this->inBatch) {
  156. throw new \BadMethodCallException('Not in batch');
  157. }
  158. $this->inBatch = false;
  159. $this->connection->beginTransaction();
  160. $query = $this->connection->getQueryBuilder();
  161. $storageId = (int)$this->storage->getStorageCache()->getNumericId();
  162. $query->update('filecache')
  163. ->set('mtime', $query->func()->greatest('mtime', $query->createParameter('time')))
  164. ->set('etag', $query->expr()->literal(uniqid()))
  165. ->where($query->expr()->eq('storage', $query->createNamedParameter($storageId, IQueryBuilder::PARAM_INT)))
  166. ->andWhere($query->expr()->eq('path_hash', $query->createParameter('hash')));
  167. $sizeQuery = $this->connection->getQueryBuilder();
  168. $sizeQuery->update('filecache')
  169. ->set('size', $sizeQuery->func()->add('size', $sizeQuery->createParameter('size')))
  170. ->where($query->expr()->eq('storage', $sizeQuery->createNamedParameter($storageId, IQueryBuilder::PARAM_INT)))
  171. ->andWhere($query->expr()->eq('path_hash', $sizeQuery->createParameter('hash')))
  172. ->andWhere($sizeQuery->expr()->gt('size', $sizeQuery->createNamedParameter(-1, IQueryBuilder::PARAM_INT)));
  173. foreach ($this->batch as $item) {
  174. $query->setParameter('time', $item['time'], IQueryBuilder::PARAM_INT);
  175. $query->setParameter('hash', $item['hash']);
  176. $query->executeStatement();
  177. if ($item['size']) {
  178. $sizeQuery->setParameter('size', $item['size'], IQueryBuilder::PARAM_INT);
  179. $sizeQuery->setParameter('hash', $item['hash']);
  180. $sizeQuery->executeStatement();
  181. }
  182. }
  183. $this->batch = [];
  184. $this->connection->commit();
  185. }
  186. }