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.

ScanAppData.php 8.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  1. <?php
  2. /**
  3. *
  4. *
  5. * @author Morris Jobke <hey@morrisjobke.de>
  6. * @author Roeland Jago Douma <roeland@famdouma.nl>
  7. *
  8. * @license GNU AGPL version 3 or any later version
  9. *
  10. * This program is free software: you can redistribute it and/or modify
  11. * it under the terms of the GNU Affero General Public License as
  12. * published by the Free Software Foundation, either version 3 of the
  13. * License, or (at your option) any later version.
  14. *
  15. * This program is distributed in the hope that it will be useful,
  16. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. * GNU Affero General Public License for more details.
  19. *
  20. * You should have received a copy of the GNU Affero General Public License
  21. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. *
  23. */
  24. namespace OCA\Files\Command;
  25. use Doctrine\DBAL\Connection;
  26. use OC\Core\Command\Base;
  27. use OC\Core\Command\InterruptedException;
  28. use OC\ForbiddenException;
  29. use OCP\Files\IRootFolder;
  30. use OCP\Files\NotFoundException;
  31. use OCP\Files\StorageNotAvailableException;
  32. use OCP\IConfig;
  33. use OCP\IDBConnection;
  34. use Symfony\Component\Console\Input\InputInterface;
  35. use Symfony\Component\Console\Input\InputOption;
  36. use Symfony\Component\Console\Output\OutputInterface;
  37. use Symfony\Component\Console\Helper\Table;
  38. class ScanAppData extends Base {
  39. /** @var IRootFolder */
  40. protected $root;
  41. /** @var IConfig */
  42. protected $config;
  43. /** @var float */
  44. protected $execTime = 0;
  45. /** @var int */
  46. protected $foldersCounter = 0;
  47. /** @var int */
  48. protected $filesCounter = 0;
  49. public function __construct(IRootFolder $rootFolder, IConfig $config) {
  50. parent::__construct();
  51. $this->root = $rootFolder;
  52. $this->config = $config;
  53. }
  54. protected function configure() {
  55. parent::configure();
  56. $this
  57. ->setName('files:scan-app-data')
  58. ->setDescription('rescan the AppData folder')
  59. ->addOption(
  60. 'quiet',
  61. 'q',
  62. InputOption::VALUE_NONE,
  63. 'suppress any output'
  64. )
  65. ->addOption(
  66. 'verbose',
  67. '-v|vv|vvv',
  68. InputOption::VALUE_NONE,
  69. 'verbose the output'
  70. );
  71. }
  72. public function checkScanWarning($fullPath, OutputInterface $output) {
  73. $normalizedPath = basename(\OC\Files\Filesystem::normalizePath($fullPath));
  74. $path = basename($fullPath);
  75. if ($normalizedPath !== $path) {
  76. $output->writeln("\t<error>Entry \"" . $fullPath . '" will not be accessible due to incompatible encoding</error>');
  77. }
  78. }
  79. protected function scanFiles($verbose, OutputInterface $output) {
  80. try {
  81. $appData = $this->getAppDataFolder();
  82. } catch (NotFoundException $e) {
  83. $output->writeln('NoAppData folder found');
  84. return;
  85. }
  86. $connection = $this->reconnectToDatabase($output);
  87. $scanner = new \OC\Files\Utils\Scanner(null, $connection, \OC::$server->getLogger());
  88. # check on each file/folder if there was a user interrupt (ctrl-c) and throw an exception
  89. # printout and count
  90. if ($verbose) {
  91. $scanner->listen('\OC\Files\Utils\Scanner', 'scanFile', function ($path) use ($output) {
  92. $output->writeln("\tFile <info>$path</info>");
  93. $this->filesCounter += 1;
  94. if ($this->hasBeenInterrupted()) {
  95. throw new InterruptedException();
  96. }
  97. });
  98. $scanner->listen('\OC\Files\Utils\Scanner', 'scanFolder', function ($path) use ($output) {
  99. $output->writeln("\tFolder <info>$path</info>");
  100. $this->foldersCounter += 1;
  101. if ($this->hasBeenInterrupted()) {
  102. throw new InterruptedException();
  103. }
  104. });
  105. $scanner->listen('\OC\Files\Utils\Scanner', 'StorageNotAvailable', function (StorageNotAvailableException $e) use ($output) {
  106. $output->writeln("Error while scanning, storage not available (" . $e->getMessage() . ")");
  107. });
  108. # count only
  109. } else {
  110. $scanner->listen('\OC\Files\Utils\Scanner', 'scanFile', function () use ($output) {
  111. $this->filesCounter += 1;
  112. if ($this->hasBeenInterrupted()) {
  113. throw new InterruptedException();
  114. }
  115. });
  116. $scanner->listen('\OC\Files\Utils\Scanner', 'scanFolder', function () use ($output) {
  117. $this->foldersCounter += 1;
  118. if ($this->hasBeenInterrupted()) {
  119. throw new InterruptedException();
  120. }
  121. });
  122. }
  123. $scanner->listen('\OC\Files\Utils\Scanner', 'scanFile', function($path) use ($output) {
  124. $this->checkScanWarning($path, $output);
  125. });
  126. $scanner->listen('\OC\Files\Utils\Scanner', 'scanFolder', function($path) use ($output) {
  127. $this->checkScanWarning($path, $output);
  128. });
  129. try {
  130. $scanner->scan($appData->getPath());
  131. } catch (ForbiddenException $e) {
  132. $output->writeln("<error>Storage not writable</error>");
  133. $output->writeln("Make sure you're running the scan command only as the user the web server runs as");
  134. } catch (InterruptedException $e) {
  135. # exit the function if ctrl-c has been pressed
  136. $output->writeln('Interrupted by user');
  137. } catch (NotFoundException $e) {
  138. $output->writeln('<error>Path not found: ' . $e->getMessage() . '</error>');
  139. } catch (\Exception $e) {
  140. $output->writeln('<error>Exception during scan: ' . $e->getMessage() . '</error>');
  141. $output->writeln('<error>' . $e->getTraceAsString() . '</error>');
  142. }
  143. }
  144. protected function execute(InputInterface $input, OutputInterface $output) {
  145. # no messaging level option means: no full printout but statistics
  146. # $quiet means no print at all
  147. # $verbose means full printout including statistics
  148. # -q -v full stat
  149. # 0 0 no yes
  150. # 0 1 yes yes
  151. # 1 -- no no (quiet overrules verbose)
  152. $verbose = $input->getOption('verbose');
  153. $quiet = $input->getOption('quiet');
  154. # restrict the verbosity level to VERBOSITY_VERBOSE
  155. if ($output->getVerbosity() > OutputInterface::VERBOSITY_VERBOSE) {
  156. $output->setVerbosity(OutputInterface::VERBOSITY_VERBOSE);
  157. }
  158. if ($quiet) {
  159. $verbose = false;
  160. }
  161. $output->writeln("\nScanning AppData for files");
  162. $this->initTools();
  163. $this->scanFiles($verbose, $output);
  164. # stat: printout statistics if $quiet was not set
  165. if (!$quiet) {
  166. $this->presentStats($output);
  167. }
  168. }
  169. /**
  170. * Initialises some useful tools for the Command
  171. */
  172. protected function initTools() {
  173. // Start the timer
  174. $this->execTime = -microtime(true);
  175. // Convert PHP errors to exceptions
  176. set_error_handler([$this, 'exceptionErrorHandler'], E_ALL);
  177. }
  178. /**
  179. * Processes PHP errors as exceptions in order to be able to keep track of problems
  180. *
  181. * @see https://secure.php.net/manual/en/function.set-error-handler.php
  182. *
  183. * @param int $severity the level of the error raised
  184. * @param string $message
  185. * @param string $file the filename that the error was raised in
  186. * @param int $line the line number the error was raised
  187. *
  188. * @throws \ErrorException
  189. */
  190. public function exceptionErrorHandler($severity, $message, $file, $line) {
  191. if (!(error_reporting() & $severity)) {
  192. // This error code is not included in error_reporting
  193. return;
  194. }
  195. throw new \ErrorException($message, 0, $severity, $file, $line);
  196. }
  197. /**
  198. * @param OutputInterface $output
  199. */
  200. protected function presentStats(OutputInterface $output) {
  201. // Stop the timer
  202. $this->execTime += microtime(true);
  203. $output->writeln("");
  204. $headers = [
  205. 'Folders', 'Files', 'Elapsed time'
  206. ];
  207. $this->showSummary($headers, null, $output);
  208. }
  209. /**
  210. * Shows a summary of operations
  211. *
  212. * @param string[] $headers
  213. * @param string[] $rows
  214. * @param OutputInterface $output
  215. */
  216. protected function showSummary($headers, $rows, OutputInterface $output) {
  217. $niceDate = $this->formatExecTime();
  218. if (!$rows) {
  219. $rows = [
  220. $this->foldersCounter,
  221. $this->filesCounter,
  222. $niceDate,
  223. ];
  224. }
  225. $table = new Table($output);
  226. $table
  227. ->setHeaders($headers)
  228. ->setRows([$rows]);
  229. $table->render();
  230. }
  231. /**
  232. * Formats microtime into a human readable format
  233. *
  234. * @return string
  235. */
  236. protected function formatExecTime() {
  237. list($secs, $tens) = explode('.', sprintf("%.1f", ($this->execTime)));
  238. # if you want to have microseconds add this: . '.' . $tens;
  239. return date('H:i:s', $secs);
  240. }
  241. /**
  242. * @return \OCP\IDBConnection
  243. */
  244. protected function reconnectToDatabase(OutputInterface $output) {
  245. /** @var Connection | IDBConnection $connection*/
  246. $connection = \OC::$server->getDatabaseConnection();
  247. try {
  248. $connection->close();
  249. } catch (\Exception $ex) {
  250. $output->writeln("<info>Error while disconnecting from database: {$ex->getMessage()}</info>");
  251. }
  252. while (!$connection->isConnected()) {
  253. try {
  254. $connection->connect();
  255. } catch (\Exception $ex) {
  256. $output->writeln("<info>Error while re-connecting to database: {$ex->getMessage()}</info>");
  257. sleep(60);
  258. }
  259. }
  260. return $connection;
  261. }
  262. /**
  263. * @return \OCP\Files\Folder
  264. * @throws NotFoundException
  265. */
  266. private function getAppDataFolder() {
  267. $instanceId = $this->config->getSystemValue('instanceid', null);
  268. if ($instanceId === null) {
  269. throw new NotFoundException();
  270. }
  271. return $this->root->get('appdata_'.$instanceId);
  272. }
  273. }