ScanAppData.php 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016 Roeland Jago Douma <roeland@famdouma.nl>
  4. *
  5. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  6. * @author Daniel Kesselberg <mail@danielkesselberg.de>
  7. * @author J0WI <J0WI@users.noreply.github.com>
  8. * @author Joas Schilling <coding@schilljs.com>
  9. * @author Joel S <joel.devbox@protonmail.com>
  10. * @author Morris Jobke <hey@morrisjobke.de>
  11. * @author Roeland Jago Douma <roeland@famdouma.nl>
  12. * @author Erik Wouters <6179932+EWouters@users.noreply.github.com>
  13. *
  14. * @license GNU AGPL version 3 or any later version
  15. *
  16. * This program is free software: you can redistribute it and/or modify
  17. * it under the terms of the GNU Affero General Public License as
  18. * published by the Free Software Foundation, either version 3 of the
  19. * License, or (at your option) any later version.
  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
  27. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  28. *
  29. */
  30. namespace OCA\Files\Command;
  31. use OC\Core\Command\Base;
  32. use OC\Core\Command\InterruptedException;
  33. use OC\DB\Connection;
  34. use OC\DB\ConnectionAdapter;
  35. use OC\ForbiddenException;
  36. use OCP\EventDispatcher\IEventDispatcher;
  37. use OCP\Files\IRootFolder;
  38. use OCP\Files\NotFoundException;
  39. use OCP\Files\StorageNotAvailableException;
  40. use OCP\IConfig;
  41. use Psr\Log\LoggerInterface;
  42. use Symfony\Component\Console\Helper\Table;
  43. use Symfony\Component\Console\Input\InputArgument;
  44. use Symfony\Component\Console\Input\InputInterface;
  45. use Symfony\Component\Console\Output\OutputInterface;
  46. class ScanAppData extends Base {
  47. /** @var IRootFolder */
  48. protected $root;
  49. /** @var IConfig */
  50. protected $config;
  51. /** @var float */
  52. protected $execTime = 0;
  53. /** @var int */
  54. protected $foldersCounter = 0;
  55. /** @var int */
  56. protected $filesCounter = 0;
  57. public function __construct(IRootFolder $rootFolder, IConfig $config) {
  58. parent::__construct();
  59. $this->root = $rootFolder;
  60. $this->config = $config;
  61. }
  62. protected function configure() {
  63. parent::configure();
  64. $this
  65. ->setName('files:scan-app-data')
  66. ->setDescription('rescan the AppData folder');
  67. $this->addArgument('folder', InputArgument::OPTIONAL, 'The appdata subfolder to scan', '');
  68. }
  69. protected function scanFiles(OutputInterface $output, string $folder): int {
  70. try {
  71. $appData = $this->getAppDataFolder();
  72. } catch (NotFoundException $e) {
  73. $output->writeln('<error>NoAppData folder found</error>');
  74. return 1;
  75. }
  76. if ($folder !== '') {
  77. try {
  78. $appData = $appData->get($folder);
  79. } catch (NotFoundException $e) {
  80. $output->writeln('<error>Could not find folder: ' . $folder . '</error>');
  81. return 1;
  82. }
  83. }
  84. $connection = $this->reconnectToDatabase($output);
  85. $scanner = new \OC\Files\Utils\Scanner(
  86. null,
  87. new ConnectionAdapter($connection),
  88. \OC::$server->query(IEventDispatcher::class),
  89. \OC::$server->get(LoggerInterface::class)
  90. );
  91. # check on each file/folder if there was a user interrupt (ctrl-c) and throw an exception
  92. $scanner->listen('\OC\Files\Utils\Scanner', 'scanFile', function ($path) use ($output) {
  93. $output->writeln("\tFile <info>$path</info>", OutputInterface::VERBOSITY_VERBOSE);
  94. ++$this->filesCounter;
  95. $this->abortIfInterrupted();
  96. });
  97. $scanner->listen('\OC\Files\Utils\Scanner', 'scanFolder', function ($path) use ($output) {
  98. $output->writeln("\tFolder <info>$path</info>", OutputInterface::VERBOSITY_VERBOSE);
  99. ++$this->foldersCounter;
  100. $this->abortIfInterrupted();
  101. });
  102. $scanner->listen('\OC\Files\Utils\Scanner', 'StorageNotAvailable', function (StorageNotAvailableException $e) use ($output) {
  103. $output->writeln('Error while scanning, storage not available (' . $e->getMessage() . ')', OutputInterface::VERBOSITY_VERBOSE);
  104. });
  105. $scanner->listen('\OC\Files\Utils\Scanner', 'normalizedNameMismatch', function ($fullPath) use ($output) {
  106. $output->writeln("\t<error>Entry \"" . $fullPath . '" will not be accessible due to incompatible encoding</error>');
  107. });
  108. try {
  109. $scanner->scan($appData->getPath());
  110. } catch (ForbiddenException $e) {
  111. $output->writeln('<error>Storage not writable</error>');
  112. $output->writeln('<info>Make sure you\'re running the scan command only as the user the web server runs as</info>');
  113. return 1;
  114. } catch (InterruptedException $e) {
  115. # exit the function if ctrl-c has been pressed
  116. $output->writeln('<info>Interrupted by user</info>');
  117. return 1;
  118. } catch (NotFoundException $e) {
  119. $output->writeln('<error>Path not found: ' . $e->getMessage() . '</error>');
  120. return 1;
  121. } catch (\Exception $e) {
  122. $output->writeln('<error>Exception during scan: ' . $e->getMessage() . '</error>');
  123. $output->writeln('<error>' . $e->getTraceAsString() . '</error>');
  124. return 1;
  125. }
  126. return 0;
  127. }
  128. protected function execute(InputInterface $input, OutputInterface $output): int {
  129. # restrict the verbosity level to VERBOSITY_VERBOSE
  130. if ($output->getVerbosity() > OutputInterface::VERBOSITY_VERBOSE) {
  131. $output->setVerbosity(OutputInterface::VERBOSITY_VERBOSE);
  132. }
  133. $output->writeln('Scanning AppData for files');
  134. $output->writeln('');
  135. $folder = $input->getArgument('folder');
  136. $this->initTools();
  137. $exitCode = $this->scanFiles($output, $folder);
  138. if ($exitCode === 0) {
  139. $this->presentStats($output);
  140. }
  141. return $exitCode;
  142. }
  143. /**
  144. * Initialises some useful tools for the Command
  145. */
  146. protected function initTools() {
  147. // Start the timer
  148. $this->execTime = -microtime(true);
  149. // Convert PHP errors to exceptions
  150. set_error_handler([$this, 'exceptionErrorHandler'], E_ALL);
  151. }
  152. /**
  153. * Processes PHP errors as exceptions in order to be able to keep track of problems
  154. *
  155. * @see https://www.php.net/manual/en/function.set-error-handler.php
  156. *
  157. * @param int $severity the level of the error raised
  158. * @param string $message
  159. * @param string $file the filename that the error was raised in
  160. * @param int $line the line number the error was raised
  161. *
  162. * @throws \ErrorException
  163. */
  164. public function exceptionErrorHandler($severity, $message, $file, $line) {
  165. if (!(error_reporting() & $severity)) {
  166. // This error code is not included in error_reporting
  167. return;
  168. }
  169. throw new \ErrorException($message, 0, $severity, $file, $line);
  170. }
  171. /**
  172. * @param OutputInterface $output
  173. */
  174. protected function presentStats(OutputInterface $output) {
  175. // Stop the timer
  176. $this->execTime += microtime(true);
  177. $headers = [
  178. 'Folders', 'Files', 'Elapsed time'
  179. ];
  180. $this->showSummary($headers, null, $output);
  181. }
  182. /**
  183. * Shows a summary of operations
  184. *
  185. * @param string[] $headers
  186. * @param string[] $rows
  187. * @param OutputInterface $output
  188. */
  189. protected function showSummary($headers, $rows, OutputInterface $output) {
  190. $niceDate = $this->formatExecTime();
  191. if (!$rows) {
  192. $rows = [
  193. $this->foldersCounter,
  194. $this->filesCounter,
  195. $niceDate,
  196. ];
  197. }
  198. $table = new Table($output);
  199. $table
  200. ->setHeaders($headers)
  201. ->setRows([$rows]);
  202. $table->render();
  203. }
  204. /**
  205. * Formats microtime into a human readable format
  206. *
  207. * @return string
  208. */
  209. protected function formatExecTime() {
  210. $secs = round($this->execTime);
  211. # convert seconds into HH:MM:SS form
  212. return sprintf('%02d:%02d:%02d', (int)($secs / 3600), ((int)($secs / 60) % 60), (int)$secs % 60);
  213. }
  214. protected function reconnectToDatabase(OutputInterface $output): Connection {
  215. /** @var Connection $connection*/
  216. $connection = \OC::$server->get(Connection::class);
  217. try {
  218. $connection->close();
  219. } catch (\Exception $ex) {
  220. $output->writeln("<info>Error while disconnecting from database: {$ex->getMessage()}</info>");
  221. }
  222. while (!$connection->isConnected()) {
  223. try {
  224. $connection->connect();
  225. } catch (\Exception $ex) {
  226. $output->writeln("<info>Error while re-connecting to database: {$ex->getMessage()}</info>");
  227. sleep(60);
  228. }
  229. }
  230. return $connection;
  231. }
  232. /**
  233. * @return \OCP\Files\Folder
  234. * @throws NotFoundException
  235. */
  236. private function getAppDataFolder() {
  237. $instanceId = $this->config->getSystemValue('instanceid', null);
  238. if ($instanceId === null) {
  239. throw new NotFoundException();
  240. }
  241. return $this->root->get('appdata_'.$instanceId);
  242. }
  243. }