You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

296 lines
9.6 KiB

3 years ago
  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 <pvince81@owncloud.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 OCP\ILogger;
  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. /** @var ILogger */
  69. protected $logger;
  70. /**
  71. * Whether to use a DB transaction
  72. *
  73. * @var bool
  74. */
  75. protected $useTransaction;
  76. /**
  77. * Number of entries scanned to commit
  78. *
  79. * @var int
  80. */
  81. protected $entriesToCommit;
  82. /**
  83. * @param string $user
  84. * @param IDBConnection|null $db
  85. * @param IEventDispatcher $dispatcher
  86. * @param ILogger $logger
  87. */
  88. public function __construct($user, $db, IEventDispatcher $dispatcher, ILogger $logger) {
  89. $this->user = $user;
  90. $this->db = $db;
  91. $this->dispatcher = $dispatcher;
  92. $this->logger = $logger;
  93. // when DB locking is used, no DB transactions will be used
  94. $this->useTransaction = !(\OC::$server->getLockingProvider() instanceof DBLockingProvider);
  95. }
  96. /**
  97. * get all storages for $dir
  98. *
  99. * @param string $dir
  100. * @return \OC\Files\Mount\MountPoint[]
  101. */
  102. protected function getMounts($dir) {
  103. //TODO: move to the node based fileapi once that's done
  104. \OC_Util::tearDownFS();
  105. \OC_Util::setupFS($this->user);
  106. $mountManager = Filesystem::getMountManager();
  107. $mounts = $mountManager->findIn($dir);
  108. $mounts[] = $mountManager->find($dir);
  109. $mounts = array_reverse($mounts); //start with the mount of $dir
  110. return $mounts;
  111. }
  112. /**
  113. * attach listeners to the scanner
  114. *
  115. * @param \OC\Files\Mount\MountPoint $mount
  116. */
  117. protected function attachListener($mount) {
  118. $scanner = $mount->getStorage()->getScanner();
  119. $scanner->listen('\OC\Files\Cache\Scanner', 'scanFile', function ($path) use ($mount) {
  120. $this->emit('\OC\Files\Utils\Scanner', 'scanFile', [$mount->getMountPoint() . $path]);
  121. $this->dispatcher->dispatchTyped(new BeforeFileScannedEvent($mount->getMountPoint() . $path));
  122. });
  123. $scanner->listen('\OC\Files\Cache\Scanner', 'scanFolder', function ($path) use ($mount) {
  124. $this->emit('\OC\Files\Utils\Scanner', 'scanFolder', [$mount->getMountPoint() . $path]);
  125. $this->dispatcher->dispatchTyped(new BeforeFolderScannedEvent($mount->getMountPoint() . $path));
  126. });
  127. $scanner->listen('\OC\Files\Cache\Scanner', 'postScanFile', function ($path) use ($mount) {
  128. $this->emit('\OC\Files\Utils\Scanner', 'postScanFile', [$mount->getMountPoint() . $path]);
  129. $this->dispatcher->dispatchTyped(new FileScannedEvent($mount->getMountPoint() . $path));
  130. });
  131. $scanner->listen('\OC\Files\Cache\Scanner', 'postScanFolder', function ($path) use ($mount) {
  132. $this->emit('\OC\Files\Utils\Scanner', 'postScanFolder', [$mount->getMountPoint() . $path]);
  133. $this->dispatcher->dispatchTyped(new FolderScannedEvent($mount->getMountPoint() . $path));
  134. });
  135. }
  136. /**
  137. * @param string $dir
  138. */
  139. public function backgroundScan($dir) {
  140. $mounts = $this->getMounts($dir);
  141. foreach ($mounts as $mount) {
  142. $storage = $mount->getStorage();
  143. if (is_null($storage)) {
  144. continue;
  145. }
  146. // don't bother scanning failed storages (shortcut for same result)
  147. if ($storage->instanceOfStorage(FailedStorage::class)) {
  148. continue;
  149. }
  150. // don't scan received local shares, these can be scanned when scanning the owner's storage
  151. if ($storage->instanceOfStorage(SharedStorage::class)) {
  152. continue;
  153. }
  154. $scanner = $storage->getScanner();
  155. $this->attachListener($mount);
  156. $scanner->listen('\OC\Files\Cache\Scanner', 'removeFromCache', function ($path) use ($storage) {
  157. $this->triggerPropagator($storage, $path);
  158. });
  159. $scanner->listen('\OC\Files\Cache\Scanner', 'updateCache', function ($path) use ($storage) {
  160. $this->triggerPropagator($storage, $path);
  161. });
  162. $scanner->listen('\OC\Files\Cache\Scanner', 'addToCache', function ($path) use ($storage) {
  163. $this->triggerPropagator($storage, $path);
  164. });
  165. $propagator = $storage->getPropagator();
  166. $propagator->beginBatch();
  167. $scanner->backgroundScan();
  168. $propagator->commitBatch();
  169. }
  170. }
  171. /**
  172. * @param string $dir
  173. * @param $recursive
  174. * @param callable|null $mountFilter
  175. * @throws ForbiddenException
  176. * @throws NotFoundException
  177. */
  178. public function scan($dir = '', $recursive = \OC\Files\Cache\Scanner::SCAN_RECURSIVE, callable $mountFilter = null) {
  179. if (!Filesystem::isValidPath($dir)) {
  180. throw new \InvalidArgumentException('Invalid path to scan');
  181. }
  182. $mounts = $this->getMounts($dir);
  183. foreach ($mounts as $mount) {
  184. if ($mountFilter && !$mountFilter($mount)) {
  185. continue;
  186. }
  187. $storage = $mount->getStorage();
  188. if (is_null($storage)) {
  189. continue;
  190. }
  191. // don't bother scanning failed storages (shortcut for same result)
  192. if ($storage->instanceOfStorage(FailedStorage::class)) {
  193. continue;
  194. }
  195. // if the home storage isn't writable then the scanner is run as the wrong user
  196. if ($storage->instanceOfStorage('\OC\Files\Storage\Home') and
  197. (!$storage->isCreatable('') or !$storage->isCreatable('files'))
  198. ) {
  199. if ($storage->file_exists('') or $storage->getCache()->inCache('')) {
  200. throw new ForbiddenException();
  201. } else {// if the root exists in neither the cache nor the storage the user isn't setup yet
  202. break;
  203. }
  204. }
  205. // don't scan received local shares, these can be scanned when scanning the owner's storage
  206. if ($storage->instanceOfStorage(SharedStorage::class)) {
  207. continue;
  208. }
  209. $relativePath = $mount->getInternalPath($dir);
  210. $scanner = $storage->getScanner();
  211. $scanner->setUseTransactions(false);
  212. $this->attachListener($mount);
  213. $scanner->listen('\OC\Files\Cache\Scanner', 'removeFromCache', function ($path) use ($storage) {
  214. $this->postProcessEntry($storage, $path);
  215. $this->dispatcher->dispatchTyped(new NodeRemovedFromCache($storage, $path));
  216. });
  217. $scanner->listen('\OC\Files\Cache\Scanner', 'updateCache', function ($path) use ($storage) {
  218. $this->postProcessEntry($storage, $path);
  219. $this->dispatcher->dispatchTyped(new FileCacheUpdated($storage, $path));
  220. });
  221. $scanner->listen('\OC\Files\Cache\Scanner', 'addToCache', function ($path) use ($storage) {
  222. $this->postProcessEntry($storage, $path);
  223. $this->dispatcher->dispatchTyped(new NodeAddedToCache($storage, $path));
  224. });
  225. if (!$storage->file_exists($relativePath)) {
  226. throw new NotFoundException($dir);
  227. }
  228. if ($this->useTransaction) {
  229. $this->db->beginTransaction();
  230. }
  231. try {
  232. $propagator = $storage->getPropagator();
  233. $propagator->beginBatch();
  234. $scanner->scan($relativePath, $recursive, \OC\Files\Cache\Scanner::REUSE_ETAG | \OC\Files\Cache\Scanner::REUSE_SIZE);
  235. $cache = $storage->getCache();
  236. if ($cache instanceof Cache) {
  237. // only re-calculate for the root folder we scanned, anything below that is taken care of by the scanner
  238. $cache->correctFolderSize($relativePath);
  239. }
  240. $propagator->commitBatch();
  241. } catch (StorageNotAvailableException $e) {
  242. $this->logger->error('Storage ' . $storage->getId() . ' not available');
  243. $this->logger->logException($e);
  244. $this->emit('\OC\Files\Utils\Scanner', 'StorageNotAvailable', [$e]);
  245. }
  246. if ($this->useTransaction) {
  247. $this->db->commit();
  248. }
  249. }
  250. }
  251. private function triggerPropagator(IStorage $storage, $internalPath) {
  252. $storage->getPropagator()->propagateChange($internalPath, time());
  253. }
  254. private function postProcessEntry(IStorage $storage, $internalPath) {
  255. $this->triggerPropagator($storage, $internalPath);
  256. if ($this->useTransaction) {
  257. $this->entriesToCommit++;
  258. if ($this->entriesToCommit >= self::MAX_ENTRIES_TO_COMMIT) {
  259. $propagator = $storage->getPropagator();
  260. $this->entriesToCommit = 0;
  261. $this->db->commit();
  262. $propagator->commitBatch();
  263. $this->db->beginTransaction();
  264. $propagator->beginBatch();
  265. }
  266. }
  267. }
  268. }