You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Scan.php 10KB

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