Scan.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Bart Visscher <bartv@thisnet.nl>
  6. * @author Blaok <i@blaok.me>
  7. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  8. * @author Daniel Kesselberg <mail@danielkesselberg.de>
  9. * @author J0WI <J0WI@users.noreply.github.com>
  10. * @author Joas Schilling <coding@schilljs.com>
  11. * @author Joel S <joel.devbox@protonmail.com>
  12. * @author Jörn Friedrich Dreyer <jfd@butonic.de>
  13. * @author martin.mattel@diemattels.at <martin.mattel@diemattels.at>
  14. * @author Maxence Lange <maxence@artificial-owl.com>
  15. * @author Robin Appelman <robin@icewind.nl>
  16. * @author Roeland Jago Douma <roeland@famdouma.nl>
  17. * @author Thomas Müller <thomas.mueller@tmit.eu>
  18. * @author Vincent Petry <vincent@nextcloud.com>
  19. *
  20. * @license AGPL-3.0
  21. *
  22. * This code is free software: you can redistribute it and/or modify
  23. * it under the terms of the GNU Affero General Public License, version 3,
  24. * as published by the Free Software Foundation.
  25. *
  26. * This program is distributed in the hope that it will be useful,
  27. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  28. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  29. * GNU Affero General Public License for more details.
  30. *
  31. * You should have received a copy of the GNU Affero General Public License, version 3,
  32. * along with this program. If not, see <http://www.gnu.org/licenses/>
  33. *
  34. */
  35. namespace OCA\Files\Command;
  36. use OC\Core\Command\Base;
  37. use OC\Core\Command\InterruptedException;
  38. use OC\DB\Connection;
  39. use OC\DB\ConnectionAdapter;
  40. use OC\FilesMetadata\FilesMetadataManager;
  41. use OC\ForbiddenException;
  42. use OCP\EventDispatcher\IEventDispatcher;
  43. use OCP\Files\Events\FileCacheUpdated;
  44. use OCP\Files\Events\NodeAddedToCache;
  45. use OCP\Files\Events\NodeRemovedFromCache;
  46. use OCP\Files\IRootFolder;
  47. use OCP\Files\Mount\IMountPoint;
  48. use OCP\Files\NotFoundException;
  49. use OCP\Files\StorageNotAvailableException;
  50. use OCP\FilesMetadata\IFilesMetadataManager;
  51. use OCP\IUserManager;
  52. use Psr\Log\LoggerInterface;
  53. use Symfony\Component\Console\Helper\Table;
  54. use Symfony\Component\Console\Input\InputArgument;
  55. use Symfony\Component\Console\Input\InputInterface;
  56. use Symfony\Component\Console\Input\InputOption;
  57. use Symfony\Component\Console\Output\OutputInterface;
  58. class Scan extends Base {
  59. protected float $execTime = 0;
  60. protected int $foldersCounter = 0;
  61. protected int $filesCounter = 0;
  62. protected int $errorsCounter = 0;
  63. protected int $newCounter = 0;
  64. protected int $updatedCounter = 0;
  65. protected int $removedCounter = 0;
  66. public function __construct(
  67. private IUserManager $userManager,
  68. private IRootFolder $rootFolder,
  69. private FilesMetadataManager $filesMetadataManager,
  70. private IEventDispatcher $eventDispatcher,
  71. private LoggerInterface $logger,
  72. ) {
  73. parent::__construct();
  74. }
  75. protected function configure(): void {
  76. parent::configure();
  77. $this
  78. ->setName('files:scan')
  79. ->setDescription('rescan filesystem')
  80. ->addArgument(
  81. 'user_id',
  82. InputArgument::OPTIONAL | InputArgument::IS_ARRAY,
  83. 'will rescan all files of the given user(s)'
  84. )
  85. ->addOption(
  86. 'path',
  87. 'p',
  88. InputArgument::OPTIONAL,
  89. 'limit rescan to this path, eg. --path="/alice/files/Music", the user_id is determined by the path and the user_id parameter and --all are ignored'
  90. )
  91. ->addOption(
  92. 'generate-metadata',
  93. null,
  94. InputOption::VALUE_NONE,
  95. 'Generate metadata for all scanned files'
  96. )
  97. ->addOption(
  98. 'all',
  99. null,
  100. InputOption::VALUE_NONE,
  101. 'will rescan all files of all known users'
  102. )->addOption(
  103. 'unscanned',
  104. null,
  105. InputOption::VALUE_NONE,
  106. 'only scan files which are marked as not fully scanned'
  107. )->addOption(
  108. 'shallow',
  109. null,
  110. InputOption::VALUE_NONE,
  111. 'do not scan folders recursively'
  112. )->addOption(
  113. 'home-only',
  114. null,
  115. InputOption::VALUE_NONE,
  116. 'only scan the home storage, ignoring any mounted external storage or share'
  117. );
  118. }
  119. protected function scanFiles(string $user, string $path, bool $scanMetadata, OutputInterface $output, bool $backgroundScan = false, bool $recursive = true, bool $homeOnly = false): void {
  120. $connection = $this->reconnectToDatabase($output);
  121. $scanner = new \OC\Files\Utils\Scanner(
  122. $user,
  123. new ConnectionAdapter($connection),
  124. \OC::$server->get(IEventDispatcher::class),
  125. \OC::$server->get(LoggerInterface::class)
  126. );
  127. # check on each file/folder if there was a user interrupt (ctrl-c) and throw an exception
  128. $scanner->listen('\OC\Files\Utils\Scanner', 'scanFile', function (string $path) use ($output, $scanMetadata) {
  129. $output->writeln("\tFile\t<info>$path</info>", OutputInterface::VERBOSITY_VERBOSE);
  130. ++$this->filesCounter;
  131. $this->abortIfInterrupted();
  132. if ($scanMetadata) {
  133. $node = $this->rootFolder->get($path);
  134. $this->filesMetadataManager->refreshMetadata(
  135. $node,
  136. IFilesMetadataManager::PROCESS_LIVE | IFilesMetadataManager::PROCESS_BACKGROUND
  137. );
  138. }
  139. });
  140. $scanner->listen('\OC\Files\Utils\Scanner', 'scanFolder', function ($path) use ($output) {
  141. $output->writeln("\tFolder\t<info>$path</info>", OutputInterface::VERBOSITY_VERBOSE);
  142. ++$this->foldersCounter;
  143. $this->abortIfInterrupted();
  144. });
  145. $scanner->listen('\OC\Files\Utils\Scanner', 'StorageNotAvailable', function (StorageNotAvailableException $e) use ($output) {
  146. $output->writeln('Error while scanning, storage not available (' . $e->getMessage() . ')', OutputInterface::VERBOSITY_VERBOSE);
  147. ++$this->errorsCounter;
  148. });
  149. $scanner->listen('\OC\Files\Utils\Scanner', 'normalizedNameMismatch', function ($fullPath) use ($output) {
  150. $output->writeln("\t<error>Entry \"" . $fullPath . '" will not be accessible due to incompatible encoding</error>');
  151. ++$this->errorsCounter;
  152. });
  153. $this->eventDispatcher->addListener(NodeAddedToCache::class, function() {
  154. ++$this->newCounter;
  155. });
  156. $this->eventDispatcher->addListener(FileCacheUpdated::class, function() {
  157. ++$this->updatedCounter;
  158. });
  159. $this->eventDispatcher->addListener(NodeRemovedFromCache::class, function() {
  160. ++$this->removedCounter;
  161. });
  162. try {
  163. if ($backgroundScan) {
  164. $scanner->backgroundScan($path);
  165. } else {
  166. $scanner->scan($path, $recursive, $homeOnly ? [$this, 'filterHomeMount'] : null);
  167. }
  168. } catch (ForbiddenException $e) {
  169. $output->writeln("<error>Home storage for user $user not writable or 'files' subdirectory missing</error>");
  170. $output->writeln(' ' . $e->getMessage());
  171. $output->writeln('Make sure you\'re running the scan command only as the user the web server runs as');
  172. ++$this->errorsCounter;
  173. } catch (InterruptedException $e) {
  174. # exit the function if ctrl-c has been pressed
  175. $output->writeln('Interrupted by user');
  176. } catch (NotFoundException $e) {
  177. $output->writeln('<error>Path not found: ' . $e->getMessage() . '</error>');
  178. ++$this->errorsCounter;
  179. } catch (\Exception $e) {
  180. $output->writeln('<error>Exception during scan: ' . $e->getMessage() . '</error>');
  181. $output->writeln('<error>' . $e->getTraceAsString() . '</error>');
  182. ++$this->errorsCounter;
  183. }
  184. }
  185. public function filterHomeMount(IMountPoint $mountPoint): bool {
  186. // any mountpoint inside '/$user/files/'
  187. return substr_count($mountPoint->getMountPoint(), '/') <= 3;
  188. }
  189. protected function execute(InputInterface $input, OutputInterface $output): int {
  190. $inputPath = $input->getOption('path');
  191. if ($inputPath) {
  192. $inputPath = '/' . trim($inputPath, '/');
  193. [, $user,] = explode('/', $inputPath, 3);
  194. $users = [$user];
  195. } elseif ($input->getOption('all')) {
  196. $users = $this->userManager->search('');
  197. } else {
  198. $users = $input->getArgument('user_id');
  199. }
  200. # check quantity of users to be process and show it on the command line
  201. $users_total = count($users);
  202. if ($users_total === 0) {
  203. $output->writeln('<error>Please specify the user id to scan, --all to scan for all users or --path=...</error>');
  204. return self::FAILURE;
  205. }
  206. $this->initTools($output);
  207. $user_count = 0;
  208. foreach ($users as $user) {
  209. if (is_object($user)) {
  210. $user = $user->getUID();
  211. }
  212. $path = $inputPath ?: '/' . $user;
  213. ++$user_count;
  214. if ($this->userManager->userExists($user)) {
  215. $output->writeln("Starting scan for user $user_count out of $users_total ($user)");
  216. $this->scanFiles($user, $path, $input->getOption('generate-metadata'), $output, $input->getOption('unscanned'), !$input->getOption('shallow'), $input->getOption('home-only'));
  217. $output->writeln('', OutputInterface::VERBOSITY_VERBOSE);
  218. } else {
  219. $output->writeln("<error>Unknown user $user_count $user</error>");
  220. $output->writeln('', OutputInterface::VERBOSITY_VERBOSE);
  221. }
  222. try {
  223. $this->abortIfInterrupted();
  224. } catch (InterruptedException $e) {
  225. break;
  226. }
  227. }
  228. $this->presentStats($output);
  229. return self::SUCCESS;
  230. }
  231. /**
  232. * Initialises some useful tools for the Command
  233. */
  234. protected function initTools(OutputInterface $output): void {
  235. // Start the timer
  236. $this->execTime = -microtime(true);
  237. // Convert PHP errors to exceptions
  238. set_error_handler(
  239. fn (int $severity, string $message, string $file, int $line): bool =>
  240. $this->exceptionErrorHandler($output, $severity, $message, $file, $line),
  241. E_ALL
  242. );
  243. }
  244. /**
  245. * Processes PHP errors in order to be able to show them in the output
  246. *
  247. * @see https://www.php.net/manual/en/function.set-error-handler.php
  248. *
  249. * @param int $severity the level of the error raised
  250. * @param string $message
  251. * @param string $file the filename that the error was raised in
  252. * @param int $line the line number the error was raised
  253. */
  254. public function exceptionErrorHandler(OutputInterface $output, int $severity, string $message, string $file, int $line): bool {
  255. if (($severity === E_DEPRECATED) || ($severity === E_USER_DEPRECATED)) {
  256. // Do not show deprecation warnings
  257. return false;
  258. }
  259. $e = new \ErrorException($message, 0, $severity, $file, $line);
  260. $output->writeln('<error>Error during scan: ' . $e->getMessage() . '</error>');
  261. $output->writeln('<error>' . $e->getTraceAsString() . '</error>', OutputInterface::VERBOSITY_VERY_VERBOSE);
  262. ++$this->errorsCounter;
  263. return true;
  264. }
  265. protected function presentStats(OutputInterface $output): void {
  266. // Stop the timer
  267. $this->execTime += microtime(true);
  268. $this->logger->info("Completed scan of {$this->filesCounter} files in {$this->foldersCounter} folder. Found {$this->newCounter} new, {$this->updatedCounter} updated and {$this->removedCounter} removed items");
  269. $headers = [
  270. 'Folders',
  271. 'Files',
  272. 'New',
  273. 'Updated',
  274. 'Removed',
  275. 'Errors',
  276. 'Elapsed time',
  277. ];
  278. $niceDate = $this->formatExecTime();
  279. $rows = [
  280. $this->foldersCounter,
  281. $this->filesCounter,
  282. $this->newCounter,
  283. $this->updatedCounter,
  284. $this->removedCounter,
  285. $this->errorsCounter,
  286. $niceDate,
  287. ];
  288. $table = new Table($output);
  289. $table
  290. ->setHeaders($headers)
  291. ->setRows([$rows]);
  292. $table->render();
  293. }
  294. /**
  295. * Formats microtime into a human-readable format
  296. */
  297. protected function formatExecTime(): string {
  298. $secs = (int)round($this->execTime);
  299. # convert seconds into HH:MM:SS form
  300. return sprintf('%02d:%02d:%02d', (int)($secs / 3600), ((int)($secs / 60) % 60), $secs % 60);
  301. }
  302. protected function reconnectToDatabase(OutputInterface $output): Connection {
  303. /** @var Connection $connection */
  304. $connection = \OC::$server->get(Connection::class);
  305. try {
  306. $connection->close();
  307. } catch (\Exception $ex) {
  308. $output->writeln("<info>Error while disconnecting from database: {$ex->getMessage()}</info>");
  309. }
  310. while (!$connection->isConnected()) {
  311. try {
  312. $connection->connect();
  313. } catch (\Exception $ex) {
  314. $output->writeln("<info>Error while re-connecting to database: {$ex->getMessage()}</info>");
  315. sleep(60);
  316. }
  317. }
  318. return $connection;
  319. }
  320. }