ScanAppData.php 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-License-Identifier: AGPL-3.0-or-later
  5. */
  6. namespace OCA\Files\Command;
  7. use OC\Core\Command\Base;
  8. use OC\Core\Command\InterruptedException;
  9. use OC\DB\Connection;
  10. use OC\DB\ConnectionAdapter;
  11. use OC\Files\Utils\Scanner;
  12. use OC\ForbiddenException;
  13. use OCP\EventDispatcher\IEventDispatcher;
  14. use OCP\Files\IRootFolder;
  15. use OCP\Files\Node;
  16. use OCP\Files\NotFoundException;
  17. use OCP\Files\StorageNotAvailableException;
  18. use OCP\IConfig;
  19. use Psr\Log\LoggerInterface;
  20. use Symfony\Component\Console\Helper\Table;
  21. use Symfony\Component\Console\Input\InputArgument;
  22. use Symfony\Component\Console\Input\InputInterface;
  23. use Symfony\Component\Console\Output\OutputInterface;
  24. class ScanAppData extends Base {
  25. protected float $execTime = 0;
  26. protected int $foldersCounter = 0;
  27. protected int $filesCounter = 0;
  28. public function __construct(
  29. protected IRootFolder $rootFolder,
  30. protected IConfig $config,
  31. ) {
  32. parent::__construct();
  33. }
  34. protected function configure(): void {
  35. parent::configure();
  36. $this
  37. ->setName('files:scan-app-data')
  38. ->setDescription('rescan the AppData folder');
  39. $this->addArgument('folder', InputArgument::OPTIONAL, 'The appdata subfolder to scan', '');
  40. }
  41. protected function scanFiles(OutputInterface $output, string $folder): int {
  42. try {
  43. /** @var \OCP\Files\Folder $appData */
  44. $appData = $this->getAppDataFolder();
  45. } catch (NotFoundException $e) {
  46. $output->writeln('<error>NoAppData folder found</error>');
  47. return self::FAILURE;
  48. }
  49. if ($folder !== '') {
  50. try {
  51. $appData = $appData->get($folder);
  52. } catch (NotFoundException $e) {
  53. $output->writeln('<error>Could not find folder: ' . $folder . '</error>');
  54. return self::FAILURE;
  55. }
  56. }
  57. $connection = $this->reconnectToDatabase($output);
  58. $scanner = new Scanner(
  59. null,
  60. new ConnectionAdapter($connection),
  61. \OC::$server->query(IEventDispatcher::class),
  62. \OC::$server->get(LoggerInterface::class)
  63. );
  64. # check on each file/folder if there was a user interrupt (ctrl-c) and throw an exception
  65. $scanner->listen('\OC\Files\Utils\Scanner', 'scanFile', function ($path) use ($output): void {
  66. $output->writeln("\tFile <info>$path</info>", OutputInterface::VERBOSITY_VERBOSE);
  67. ++$this->filesCounter;
  68. $this->abortIfInterrupted();
  69. });
  70. $scanner->listen('\OC\Files\Utils\Scanner', 'scanFolder', function ($path) use ($output): void {
  71. $output->writeln("\tFolder <info>$path</info>", OutputInterface::VERBOSITY_VERBOSE);
  72. ++$this->foldersCounter;
  73. $this->abortIfInterrupted();
  74. });
  75. $scanner->listen('\OC\Files\Utils\Scanner', 'StorageNotAvailable', function (StorageNotAvailableException $e) use ($output): void {
  76. $output->writeln('Error while scanning, storage not available (' . $e->getMessage() . ')', OutputInterface::VERBOSITY_VERBOSE);
  77. });
  78. $scanner->listen('\OC\Files\Utils\Scanner', 'normalizedNameMismatch', function ($fullPath) use ($output): void {
  79. $output->writeln("\t<error>Entry \"" . $fullPath . '" will not be accessible due to incompatible encoding</error>');
  80. });
  81. try {
  82. $scanner->scan($appData->getPath());
  83. } catch (ForbiddenException $e) {
  84. $output->writeln('<error>Storage not writable</error>');
  85. $output->writeln('<info>Make sure you\'re running the scan command only as the user the web server runs as</info>');
  86. return self::FAILURE;
  87. } catch (InterruptedException $e) {
  88. # exit the function if ctrl-c has been pressed
  89. $output->writeln('<info>Interrupted by user</info>');
  90. return self::FAILURE;
  91. } catch (NotFoundException $e) {
  92. $output->writeln('<error>Path not found: ' . $e->getMessage() . '</error>');
  93. return self::FAILURE;
  94. } catch (\Exception $e) {
  95. $output->writeln('<error>Exception during scan: ' . $e->getMessage() . '</error>');
  96. $output->writeln('<error>' . $e->getTraceAsString() . '</error>');
  97. return self::FAILURE;
  98. }
  99. return self::SUCCESS;
  100. }
  101. protected function execute(InputInterface $input, OutputInterface $output): int {
  102. # restrict the verbosity level to VERBOSITY_VERBOSE
  103. if ($output->getVerbosity() > OutputInterface::VERBOSITY_VERBOSE) {
  104. $output->setVerbosity(OutputInterface::VERBOSITY_VERBOSE);
  105. }
  106. $output->writeln('Scanning AppData for files');
  107. $output->writeln('');
  108. $folder = $input->getArgument('folder');
  109. $this->initTools();
  110. $exitCode = $this->scanFiles($output, $folder);
  111. if ($exitCode === 0) {
  112. $this->presentStats($output);
  113. }
  114. return $exitCode;
  115. }
  116. /**
  117. * Initialises some useful tools for the Command
  118. */
  119. protected function initTools(): void {
  120. // Start the timer
  121. $this->execTime = -microtime(true);
  122. // Convert PHP errors to exceptions
  123. set_error_handler([$this, 'exceptionErrorHandler'], E_ALL);
  124. }
  125. /**
  126. * Processes PHP errors as exceptions in order to be able to keep track of problems
  127. *
  128. * @see https://www.php.net/manual/en/function.set-error-handler.php
  129. *
  130. * @param int $severity the level of the error raised
  131. * @param string $message
  132. * @param string $file the filename that the error was raised in
  133. * @param int $line the line number the error was raised
  134. *
  135. * @throws \ErrorException
  136. */
  137. public function exceptionErrorHandler($severity, $message, $file, $line) {
  138. if (!(error_reporting() & $severity)) {
  139. // This error code is not included in error_reporting
  140. return;
  141. }
  142. throw new \ErrorException($message, 0, $severity, $file, $line);
  143. }
  144. protected function presentStats(OutputInterface $output): void {
  145. // Stop the timer
  146. $this->execTime += microtime(true);
  147. $headers = [
  148. 'Folders', 'Files', 'Elapsed time'
  149. ];
  150. $this->showSummary($headers, null, $output);
  151. }
  152. /**
  153. * Shows a summary of operations
  154. *
  155. * @param string[] $headers
  156. * @param string[] $rows
  157. */
  158. protected function showSummary($headers, $rows, OutputInterface $output): void {
  159. $niceDate = $this->formatExecTime();
  160. if (!$rows) {
  161. $rows = [
  162. $this->foldersCounter,
  163. $this->filesCounter,
  164. $niceDate,
  165. ];
  166. }
  167. $table = new Table($output);
  168. $table
  169. ->setHeaders($headers)
  170. ->setRows([$rows]);
  171. $table->render();
  172. }
  173. /**
  174. * Formats microtime into a human-readable format
  175. */
  176. protected function formatExecTime(): string {
  177. $secs = round($this->execTime);
  178. # convert seconds into HH:MM:SS form
  179. return sprintf('%02d:%02d:%02d', (int)($secs / 3600), ((int)($secs / 60) % 60), (int)$secs % 60);
  180. }
  181. protected function reconnectToDatabase(OutputInterface $output): Connection {
  182. /** @var Connection $connection */
  183. $connection = \OC::$server->get(Connection::class);
  184. try {
  185. $connection->close();
  186. } catch (\Exception $ex) {
  187. $output->writeln("<info>Error while disconnecting from database: {$ex->getMessage()}</info>");
  188. }
  189. while (!$connection->isConnected()) {
  190. try {
  191. $connection->connect();
  192. } catch (\Exception $ex) {
  193. $output->writeln("<info>Error while re-connecting to database: {$ex->getMessage()}</info>");
  194. sleep(60);
  195. }
  196. }
  197. return $connection;
  198. }
  199. /**
  200. * @throws NotFoundException
  201. */
  202. private function getAppDataFolder(): Node {
  203. $instanceId = $this->config->getSystemValue('instanceid', null);
  204. if ($instanceId === null) {
  205. throw new NotFoundException();
  206. }
  207. return $this->rootFolder->get('appdata_' . $instanceId);
  208. }
  209. }