Scanner.php 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Blaok <i@blaok.me>
  6. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  7. * @author Jörn Friedrich Dreyer <jfd@butonic.de>
  8. * @author Morris Jobke <hey@morrisjobke.de>
  9. * @author Olivier Paroz <github@oparoz.com>
  10. * @author Robin Appelman <robin@icewind.nl>
  11. * @author Roeland Jago Douma <roeland@famdouma.nl>
  12. * @author Thomas Müller <thomas.mueller@tmit.eu>
  13. * @author Vincent Petry <vincent@nextcloud.com>
  14. *
  15. * @license AGPL-3.0
  16. *
  17. * This code is free software: you can redistribute it and/or modify
  18. * it under the terms of the GNU Affero General Public License, version 3,
  19. * as published by the Free Software Foundation.
  20. *
  21. * This program is distributed in the hope that it will be useful,
  22. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  23. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  24. * GNU Affero General Public License for more details.
  25. *
  26. * You should have received a copy of the GNU Affero General Public License, version 3,
  27. * along with this program. If not, see <http://www.gnu.org/licenses/>
  28. *
  29. */
  30. namespace OC\Files\Utils;
  31. use OC\Files\Cache\Cache;
  32. use OC\Files\Filesystem;
  33. use OC\Files\Storage\FailedStorage;
  34. use OC\ForbiddenException;
  35. use OC\Hooks\PublicEmitter;
  36. use OC\Lock\DBLockingProvider;
  37. use OCA\Files_Sharing\SharedStorage;
  38. use OCP\EventDispatcher\IEventDispatcher;
  39. use OCP\Files\Events\BeforeFileScannedEvent;
  40. use OCP\Files\Events\BeforeFolderScannedEvent;
  41. use OCP\Files\Events\NodeAddedToCache;
  42. use OCP\Files\Events\FileCacheUpdated;
  43. use OCP\Files\Events\NodeRemovedFromCache;
  44. use OCP\Files\Events\FileScannedEvent;
  45. use OCP\Files\Events\FolderScannedEvent;
  46. use OCP\Files\NotFoundException;
  47. use OCP\Files\Storage\IStorage;
  48. use OCP\Files\StorageNotAvailableException;
  49. use OCP\IDBConnection;
  50. use Psr\Log\LoggerInterface;
  51. /**
  52. * Class Scanner
  53. *
  54. * Hooks available in scope \OC\Utils\Scanner
  55. * - scanFile(string $absolutePath)
  56. * - scanFolder(string $absolutePath)
  57. *
  58. * @package OC\Files\Utils
  59. */
  60. class Scanner extends PublicEmitter {
  61. public const MAX_ENTRIES_TO_COMMIT = 10000;
  62. /** @var string $user */
  63. private $user;
  64. /** @var IDBConnection */
  65. protected $db;
  66. /** @var IEventDispatcher */
  67. private $dispatcher;
  68. protected LoggerInterface $logger;
  69. /**
  70. * Whether to use a DB transaction
  71. *
  72. * @var bool
  73. */
  74. protected $useTransaction;
  75. /**
  76. * Number of entries scanned to commit
  77. *
  78. * @var int
  79. */
  80. protected $entriesToCommit;
  81. /**
  82. * @param string $user
  83. * @param IDBConnection|null $db
  84. * @param IEventDispatcher $dispatcher
  85. */
  86. public function __construct($user, $db, IEventDispatcher $dispatcher, LoggerInterface $logger) {
  87. $this->user = $user;
  88. $this->db = $db;
  89. $this->dispatcher = $dispatcher;
  90. $this->logger = $logger;
  91. // when DB locking is used, no DB transactions will be used
  92. $this->useTransaction = !(\OC::$server->getLockingProvider() instanceof DBLockingProvider);
  93. }
  94. /**
  95. * get all storages for $dir
  96. *
  97. * @param string $dir
  98. * @return \OC\Files\Mount\MountPoint[]
  99. */
  100. protected function getMounts($dir) {
  101. //TODO: move to the node based fileapi once that's done
  102. \OC_Util::tearDownFS();
  103. \OC_Util::setupFS($this->user);
  104. $mountManager = Filesystem::getMountManager();
  105. $mounts = $mountManager->findIn($dir);
  106. $mounts[] = $mountManager->find($dir);
  107. $mounts = array_reverse($mounts); //start with the mount of $dir
  108. return $mounts;
  109. }
  110. /**
  111. * attach listeners to the scanner
  112. *
  113. * @param \OC\Files\Mount\MountPoint $mount
  114. */
  115. protected function attachListener($mount) {
  116. $scanner = $mount->getStorage()->getScanner();
  117. $scanner->listen('\OC\Files\Cache\Scanner', 'scanFile', function ($path) use ($mount) {
  118. $this->emit('\OC\Files\Utils\Scanner', 'scanFile', [$mount->getMountPoint() . $path]);
  119. $this->dispatcher->dispatchTyped(new BeforeFileScannedEvent($mount->getMountPoint() . $path));
  120. });
  121. $scanner->listen('\OC\Files\Cache\Scanner', 'scanFolder', function ($path) use ($mount) {
  122. $this->emit('\OC\Files\Utils\Scanner', 'scanFolder', [$mount->getMountPoint() . $path]);
  123. $this->dispatcher->dispatchTyped(new BeforeFolderScannedEvent($mount->getMountPoint() . $path));
  124. });
  125. $scanner->listen('\OC\Files\Cache\Scanner', 'postScanFile', function ($path) use ($mount) {
  126. $this->emit('\OC\Files\Utils\Scanner', 'postScanFile', [$mount->getMountPoint() . $path]);
  127. $this->dispatcher->dispatchTyped(new FileScannedEvent($mount->getMountPoint() . $path));
  128. });
  129. $scanner->listen('\OC\Files\Cache\Scanner', 'postScanFolder', function ($path) use ($mount) {
  130. $this->emit('\OC\Files\Utils\Scanner', 'postScanFolder', [$mount->getMountPoint() . $path]);
  131. $this->dispatcher->dispatchTyped(new FolderScannedEvent($mount->getMountPoint() . $path));
  132. });
  133. $scanner->listen('\OC\Files\Cache\Scanner', 'normalizedNameMismatch', function ($path) use ($mount) {
  134. $this->emit('\OC\Files\Utils\Scanner', 'normalizedNameMismatch', [$path]);
  135. });
  136. }
  137. /**
  138. * @param string $dir
  139. */
  140. public function backgroundScan($dir) {
  141. $mounts = $this->getMounts($dir);
  142. foreach ($mounts as $mount) {
  143. $storage = $mount->getStorage();
  144. if (is_null($storage)) {
  145. continue;
  146. }
  147. // don't bother scanning failed storages (shortcut for same result)
  148. if ($storage->instanceOfStorage(FailedStorage::class)) {
  149. continue;
  150. }
  151. $scanner = $storage->getScanner();
  152. $this->attachListener($mount);
  153. $scanner->listen('\OC\Files\Cache\Scanner', 'removeFromCache', function ($path) use ($storage) {
  154. $this->triggerPropagator($storage, $path);
  155. });
  156. $scanner->listen('\OC\Files\Cache\Scanner', 'updateCache', function ($path) use ($storage) {
  157. $this->triggerPropagator($storage, $path);
  158. });
  159. $scanner->listen('\OC\Files\Cache\Scanner', 'addToCache', function ($path) use ($storage) {
  160. $this->triggerPropagator($storage, $path);
  161. });
  162. $propagator = $storage->getPropagator();
  163. $propagator->beginBatch();
  164. $scanner->backgroundScan();
  165. $propagator->commitBatch();
  166. }
  167. }
  168. /**
  169. * @param string $dir
  170. * @param $recursive
  171. * @param callable|null $mountFilter
  172. * @throws ForbiddenException
  173. * @throws NotFoundException
  174. */
  175. public function scan($dir = '', $recursive = \OC\Files\Cache\Scanner::SCAN_RECURSIVE, callable $mountFilter = null) {
  176. if (!Filesystem::isValidPath($dir)) {
  177. throw new \InvalidArgumentException('Invalid path to scan');
  178. }
  179. $mounts = $this->getMounts($dir);
  180. foreach ($mounts as $mount) {
  181. if ($mountFilter && !$mountFilter($mount)) {
  182. continue;
  183. }
  184. $storage = $mount->getStorage();
  185. if (is_null($storage)) {
  186. continue;
  187. }
  188. // don't bother scanning failed storages (shortcut for same result)
  189. if ($storage->instanceOfStorage(FailedStorage::class)) {
  190. continue;
  191. }
  192. // if the home storage isn't writable then the scanner is run as the wrong user
  193. if ($storage->instanceOfStorage('\OC\Files\Storage\Home') and
  194. (!$storage->isCreatable('') or !$storage->isCreatable('files'))
  195. ) {
  196. if ($storage->is_dir('files')) {
  197. throw new ForbiddenException();
  198. } else {// if the root exists in neither the cache nor the storage the user isn't setup yet
  199. break;
  200. }
  201. }
  202. // don't scan received local shares, these can be scanned when scanning the owner's storage
  203. if ($storage->instanceOfStorage(SharedStorage::class)) {
  204. continue;
  205. }
  206. $relativePath = $mount->getInternalPath($dir);
  207. $scanner = $storage->getScanner();
  208. $scanner->setUseTransactions(false);
  209. $this->attachListener($mount);
  210. $scanner->listen('\OC\Files\Cache\Scanner', 'removeFromCache', function ($path) use ($storage) {
  211. $this->postProcessEntry($storage, $path);
  212. $this->dispatcher->dispatchTyped(new NodeRemovedFromCache($storage, $path));
  213. });
  214. $scanner->listen('\OC\Files\Cache\Scanner', 'updateCache', function ($path) use ($storage) {
  215. $this->postProcessEntry($storage, $path);
  216. $this->dispatcher->dispatchTyped(new FileCacheUpdated($storage, $path));
  217. });
  218. $scanner->listen('\OC\Files\Cache\Scanner', 'addToCache', function ($path) use ($storage) {
  219. $this->postProcessEntry($storage, $path);
  220. $this->dispatcher->dispatchTyped(new NodeAddedToCache($storage, $path));
  221. });
  222. if (!$storage->file_exists($relativePath)) {
  223. throw new NotFoundException($dir);
  224. }
  225. if ($this->useTransaction) {
  226. $this->db->beginTransaction();
  227. }
  228. try {
  229. $propagator = $storage->getPropagator();
  230. $propagator->beginBatch();
  231. $scanner->scan($relativePath, $recursive, \OC\Files\Cache\Scanner::REUSE_ETAG | \OC\Files\Cache\Scanner::REUSE_SIZE);
  232. $cache = $storage->getCache();
  233. if ($cache instanceof Cache) {
  234. // only re-calculate for the root folder we scanned, anything below that is taken care of by the scanner
  235. $cache->correctFolderSize($relativePath);
  236. }
  237. $propagator->commitBatch();
  238. } catch (StorageNotAvailableException $e) {
  239. $this->logger->error('Storage ' . $storage->getId() . ' not available', ['exception' => $e]);
  240. $this->emit('\OC\Files\Utils\Scanner', 'StorageNotAvailable', [$e]);
  241. }
  242. if ($this->useTransaction) {
  243. $this->db->commit();
  244. }
  245. }
  246. }
  247. private function triggerPropagator(IStorage $storage, $internalPath) {
  248. $storage->getPropagator()->propagateChange($internalPath, time());
  249. }
  250. private function postProcessEntry(IStorage $storage, $internalPath) {
  251. $this->triggerPropagator($storage, $internalPath);
  252. if ($this->useTransaction) {
  253. $this->entriesToCommit++;
  254. if ($this->entriesToCommit >= self::MAX_ENTRIES_TO_COMMIT) {
  255. $propagator = $storage->getPropagator();
  256. $this->entriesToCommit = 0;
  257. $this->db->commit();
  258. $propagator->commitBatch();
  259. $this->db->beginTransaction();
  260. $propagator->beginBatch();
  261. }
  262. }
  263. }
  264. }