1
0

ScanAppData.php 7.1 KB

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