Scanner.php 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  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\Utils;
  8. use OC\Files\Cache\Cache;
  9. use OC\Files\Filesystem;
  10. use OC\Files\Storage\FailedStorage;
  11. use OC\Files\Storage\Home;
  12. use OC\ForbiddenException;
  13. use OC\Hooks\PublicEmitter;
  14. use OC\Lock\DBLockingProvider;
  15. use OCA\Files_Sharing\SharedStorage;
  16. use OCP\EventDispatcher\IEventDispatcher;
  17. use OCP\Files\Events\BeforeFileScannedEvent;
  18. use OCP\Files\Events\BeforeFolderScannedEvent;
  19. use OCP\Files\Events\FileCacheUpdated;
  20. use OCP\Files\Events\FileScannedEvent;
  21. use OCP\Files\Events\FolderScannedEvent;
  22. use OCP\Files\Events\NodeAddedToCache;
  23. use OCP\Files\Events\NodeRemovedFromCache;
  24. use OCP\Files\NotFoundException;
  25. use OCP\Files\Storage\IStorage;
  26. use OCP\Files\StorageNotAvailableException;
  27. use OCP\IDBConnection;
  28. use OCP\Lock\ILockingProvider;
  29. use Psr\Log\LoggerInterface;
  30. /**
  31. * Class Scanner
  32. *
  33. * Hooks available in scope \OC\Utils\Scanner
  34. * - scanFile(string $absolutePath)
  35. * - scanFolder(string $absolutePath)
  36. *
  37. * @package OC\Files\Utils
  38. */
  39. class Scanner extends PublicEmitter {
  40. public const MAX_ENTRIES_TO_COMMIT = 10000;
  41. /** @var string $user */
  42. private $user;
  43. /** @var IDBConnection */
  44. protected $db;
  45. /** @var IEventDispatcher */
  46. private $dispatcher;
  47. protected LoggerInterface $logger;
  48. /**
  49. * Whether to use a DB transaction
  50. *
  51. * @var bool
  52. */
  53. protected $useTransaction;
  54. /**
  55. * Number of entries scanned to commit
  56. *
  57. * @var int
  58. */
  59. protected $entriesToCommit;
  60. /**
  61. * @param string $user
  62. * @param IDBConnection|null $db
  63. * @param IEventDispatcher $dispatcher
  64. */
  65. public function __construct($user, $db, IEventDispatcher $dispatcher, LoggerInterface $logger) {
  66. $this->user = $user;
  67. $this->db = $db;
  68. $this->dispatcher = $dispatcher;
  69. $this->logger = $logger;
  70. // when DB locking is used, no DB transactions will be used
  71. $this->useTransaction = !(\OC::$server->get(ILockingProvider::class) instanceof DBLockingProvider);
  72. }
  73. /**
  74. * get all storages for $dir
  75. *
  76. * @param string $dir
  77. * @return \OC\Files\Mount\MountPoint[]
  78. */
  79. protected function getMounts($dir) {
  80. //TODO: move to the node based fileapi once that's done
  81. \OC_Util::tearDownFS();
  82. \OC_Util::setupFS($this->user);
  83. $mountManager = Filesystem::getMountManager();
  84. $mounts = $mountManager->findIn($dir);
  85. $mounts[] = $mountManager->find($dir);
  86. $mounts = array_reverse($mounts); //start with the mount of $dir
  87. return $mounts;
  88. }
  89. /**
  90. * attach listeners to the scanner
  91. *
  92. * @param \OC\Files\Mount\MountPoint $mount
  93. */
  94. protected function attachListener($mount) {
  95. /** @var \OC\Files\Cache\Scanner $scanner */
  96. $scanner = $mount->getStorage()->getScanner();
  97. $scanner->listen('\OC\Files\Cache\Scanner', 'scanFile', function ($path) use ($mount) {
  98. $this->emit('\OC\Files\Utils\Scanner', 'scanFile', [$mount->getMountPoint() . $path]);
  99. $this->dispatcher->dispatchTyped(new BeforeFileScannedEvent($mount->getMountPoint() . $path));
  100. });
  101. $scanner->listen('\OC\Files\Cache\Scanner', 'scanFolder', function ($path) use ($mount) {
  102. $this->emit('\OC\Files\Utils\Scanner', 'scanFolder', [$mount->getMountPoint() . $path]);
  103. $this->dispatcher->dispatchTyped(new BeforeFolderScannedEvent($mount->getMountPoint() . $path));
  104. });
  105. $scanner->listen('\OC\Files\Cache\Scanner', 'postScanFile', function ($path) use ($mount) {
  106. $this->emit('\OC\Files\Utils\Scanner', 'postScanFile', [$mount->getMountPoint() . $path]);
  107. $this->dispatcher->dispatchTyped(new FileScannedEvent($mount->getMountPoint() . $path));
  108. });
  109. $scanner->listen('\OC\Files\Cache\Scanner', 'postScanFolder', function ($path) use ($mount) {
  110. $this->emit('\OC\Files\Utils\Scanner', 'postScanFolder', [$mount->getMountPoint() . $path]);
  111. $this->dispatcher->dispatchTyped(new FolderScannedEvent($mount->getMountPoint() . $path));
  112. });
  113. $scanner->listen('\OC\Files\Cache\Scanner', 'normalizedNameMismatch', function ($path) use ($mount) {
  114. $this->emit('\OC\Files\Utils\Scanner', 'normalizedNameMismatch', [$path]);
  115. });
  116. }
  117. /**
  118. * @param string $dir
  119. */
  120. public function backgroundScan($dir) {
  121. $mounts = $this->getMounts($dir);
  122. foreach ($mounts as $mount) {
  123. try {
  124. $storage = $mount->getStorage();
  125. if (is_null($storage)) {
  126. continue;
  127. }
  128. // don't bother scanning failed storages (shortcut for same result)
  129. if ($storage->instanceOfStorage(FailedStorage::class)) {
  130. continue;
  131. }
  132. /** @var \OC\Files\Cache\Scanner $scanner */
  133. $scanner = $storage->getScanner();
  134. $this->attachListener($mount);
  135. $scanner->listen('\OC\Files\Cache\Scanner', 'removeFromCache', function ($path) use ($storage) {
  136. $this->triggerPropagator($storage, $path);
  137. });
  138. $scanner->listen('\OC\Files\Cache\Scanner', 'updateCache', function ($path) use ($storage) {
  139. $this->triggerPropagator($storage, $path);
  140. });
  141. $scanner->listen('\OC\Files\Cache\Scanner', 'addToCache', function ($path) use ($storage) {
  142. $this->triggerPropagator($storage, $path);
  143. });
  144. $propagator = $storage->getPropagator();
  145. $propagator->beginBatch();
  146. $scanner->backgroundScan();
  147. $propagator->commitBatch();
  148. } catch (\Exception $e) {
  149. $this->logger->error("Error while trying to scan mount as {$mount->getMountPoint()}:" . $e->getMessage(), ['exception' => $e, 'app' => 'files']);
  150. }
  151. }
  152. }
  153. /**
  154. * @param string $dir
  155. * @param $recursive
  156. * @param callable|null $mountFilter
  157. * @throws ForbiddenException
  158. * @throws NotFoundException
  159. */
  160. public function scan($dir = '', $recursive = \OC\Files\Cache\Scanner::SCAN_RECURSIVE, ?callable $mountFilter = null) {
  161. if (!Filesystem::isValidPath($dir)) {
  162. throw new \InvalidArgumentException('Invalid path to scan');
  163. }
  164. $mounts = $this->getMounts($dir);
  165. foreach ($mounts as $mount) {
  166. if ($mountFilter && !$mountFilter($mount)) {
  167. continue;
  168. }
  169. $storage = $mount->getStorage();
  170. if (is_null($storage)) {
  171. continue;
  172. }
  173. // don't bother scanning failed storages (shortcut for same result)
  174. if ($storage->instanceOfStorage(FailedStorage::class)) {
  175. continue;
  176. }
  177. // if the home storage isn't writable then the scanner is run as the wrong user
  178. if ($storage->instanceOfStorage(Home::class)) {
  179. /** @var Home $storage */
  180. foreach (['', 'files'] as $path) {
  181. if (!$storage->isCreatable($path)) {
  182. $fullPath = $storage->getSourcePath($path);
  183. if (!$storage->is_dir($path) && $storage->getCache()->inCache($path)) {
  184. throw new NotFoundException("User folder $fullPath exists in cache but not on disk");
  185. } elseif ($storage->is_dir($path)) {
  186. $ownerUid = fileowner($fullPath);
  187. $owner = posix_getpwuid($ownerUid);
  188. $owner = $owner['name'] ?? $ownerUid;
  189. $permissions = decoct(fileperms($fullPath));
  190. throw new ForbiddenException("User folder $fullPath is not writable, folders is owned by $owner and has mode $permissions");
  191. } else {
  192. // if the root exists in neither the cache nor the storage the user isn't setup yet
  193. break 2;
  194. }
  195. }
  196. }
  197. }
  198. // don't scan received local shares, these can be scanned when scanning the owner's storage
  199. if ($storage->instanceOfStorage(SharedStorage::class)) {
  200. continue;
  201. }
  202. $relativePath = $mount->getInternalPath($dir);
  203. /** @var \OC\Files\Cache\Scanner $scanner */
  204. $scanner = $storage->getScanner();
  205. $scanner->setUseTransactions(false);
  206. $this->attachListener($mount);
  207. $scanner->listen('\OC\Files\Cache\Scanner', 'removeFromCache', function ($path) use ($storage) {
  208. $this->postProcessEntry($storage, $path);
  209. $this->dispatcher->dispatchTyped(new NodeRemovedFromCache($storage, $path));
  210. });
  211. $scanner->listen('\OC\Files\Cache\Scanner', 'updateCache', function ($path) use ($storage) {
  212. $this->postProcessEntry($storage, $path);
  213. $this->dispatcher->dispatchTyped(new FileCacheUpdated($storage, $path));
  214. });
  215. $scanner->listen('\OC\Files\Cache\Scanner', 'addToCache', function ($path, $storageId, $data, $fileId) use ($storage) {
  216. $this->postProcessEntry($storage, $path);
  217. if ($fileId) {
  218. $this->dispatcher->dispatchTyped(new FileCacheUpdated($storage, $path));
  219. } else {
  220. $this->dispatcher->dispatchTyped(new NodeAddedToCache($storage, $path));
  221. }
  222. });
  223. if (!$storage->file_exists($relativePath)) {
  224. throw new NotFoundException($dir);
  225. }
  226. if ($this->useTransaction) {
  227. $this->db->beginTransaction();
  228. }
  229. try {
  230. $propagator = $storage->getPropagator();
  231. $propagator->beginBatch();
  232. $scanner->scan($relativePath, $recursive, \OC\Files\Cache\Scanner::REUSE_ETAG | \OC\Files\Cache\Scanner::REUSE_SIZE);
  233. $cache = $storage->getCache();
  234. if ($cache instanceof Cache) {
  235. // only re-calculate for the root folder we scanned, anything below that is taken care of by the scanner
  236. $cache->correctFolderSize($relativePath);
  237. }
  238. $propagator->commitBatch();
  239. } catch (StorageNotAvailableException $e) {
  240. $this->logger->error('Storage ' . $storage->getId() . ' not available', ['exception' => $e]);
  241. $this->emit('\OC\Files\Utils\Scanner', 'StorageNotAvailable', [$e]);
  242. }
  243. if ($this->useTransaction) {
  244. $this->db->commit();
  245. }
  246. }
  247. }
  248. private function triggerPropagator(IStorage $storage, $internalPath) {
  249. $storage->getPropagator()->propagateChange($internalPath, time());
  250. }
  251. private function postProcessEntry(IStorage $storage, $internalPath) {
  252. $this->triggerPropagator($storage, $internalPath);
  253. if ($this->useTransaction) {
  254. $this->entriesToCommit++;
  255. if ($this->entriesToCommit >= self::MAX_ENTRIES_TO_COMMIT) {
  256. $propagator = $storage->getPropagator();
  257. $this->entriesToCommit = 0;
  258. $this->db->commit();
  259. $propagator->commitBatch();
  260. $this->db->beginTransaction();
  261. $propagator->beginBatch();
  262. }
  263. }
  264. }
  265. }