scan.php 8.5 KB

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