Scan.php 9.8 KB

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