1
0

ScanAppData.php 7.1 KB

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