Repair.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2020 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-License-Identifier: AGPL-3.0-or-later
  6. */
  7. namespace OC\Core\Command\Preview;
  8. use bantu\IniGetWrapper\IniGetWrapper;
  9. use OC\Preview\Storage\Root;
  10. use OCP\Files\Folder;
  11. use OCP\Files\IRootFolder;
  12. use OCP\Files\NotFoundException;
  13. use OCP\IConfig;
  14. use OCP\Lock\ILockingProvider;
  15. use OCP\Lock\LockedException;
  16. use Psr\Log\LoggerInterface;
  17. use Symfony\Component\Console\Command\Command;
  18. use Symfony\Component\Console\Helper\ProgressBar;
  19. use Symfony\Component\Console\Input\InputInterface;
  20. use Symfony\Component\Console\Input\InputOption;
  21. use Symfony\Component\Console\Output\OutputInterface;
  22. use Symfony\Component\Console\Question\ConfirmationQuestion;
  23. use function pcntl_signal;
  24. class Repair extends Command {
  25. private bool $stopSignalReceived = false;
  26. private int $memoryLimit;
  27. private int $memoryTreshold;
  28. public function __construct(
  29. protected IConfig $config,
  30. private IRootFolder $rootFolder,
  31. private LoggerInterface $logger,
  32. IniGetWrapper $phpIni,
  33. private ILockingProvider $lockingProvider,
  34. ) {
  35. $this->memoryLimit = (int)$phpIni->getBytes('memory_limit');
  36. $this->memoryTreshold = $this->memoryLimit - 25 * 1024 * 1024;
  37. parent::__construct();
  38. }
  39. protected function configure() {
  40. $this
  41. ->setName('preview:repair')
  42. ->setDescription('distributes the existing previews into subfolders')
  43. ->addOption('batch', 'b', InputOption::VALUE_NONE, 'Batch mode - will not ask to start the migration and start it right away.')
  44. ->addOption('dry', 'd', InputOption::VALUE_NONE, 'Dry mode - will not create, move or delete any files - in combination with the verbose mode one could check the operations.')
  45. ->addOption('delete', null, InputOption::VALUE_NONE, 'Delete instead of migrating them. Usefull if too many entries to migrate.');
  46. }
  47. protected function execute(InputInterface $input, OutputInterface $output): int {
  48. if ($this->memoryLimit !== -1) {
  49. $limitInMiB = round($this->memoryLimit / 1024 / 1024, 1);
  50. $thresholdInMiB = round($this->memoryTreshold / 1024 / 1024, 1);
  51. $output->writeln("Memory limit is $limitInMiB MiB");
  52. $output->writeln("Memory threshold is $thresholdInMiB MiB");
  53. $output->writeln("");
  54. $memoryCheckEnabled = true;
  55. } else {
  56. $output->writeln("No memory limit in place - disabled memory check. Set a PHP memory limit to automatically stop the execution of this migration script once memory consumption is close to this limit.");
  57. $output->writeln("");
  58. $memoryCheckEnabled = false;
  59. }
  60. $dryMode = $input->getOption('dry');
  61. $deleteMode = $input->getOption('delete');
  62. if ($dryMode) {
  63. $output->writeln("INFO: The migration is run in dry mode and will not modify anything.");
  64. $output->writeln("");
  65. } elseif ($deleteMode) {
  66. $output->writeln("WARN: The migration will _DELETE_ old previews.");
  67. $output->writeln("");
  68. }
  69. $instanceId = $this->config->getSystemValueString('instanceid');
  70. $output->writeln("This will migrate all previews from the old preview location to the new one.");
  71. $output->writeln('');
  72. $output->writeln('Fetching previews that need to be migrated …');
  73. /** @var \OCP\Files\Folder $currentPreviewFolder */
  74. $currentPreviewFolder = $this->rootFolder->get("appdata_$instanceId/preview");
  75. $directoryListing = $currentPreviewFolder->getDirectoryListing();
  76. $total = count($directoryListing);
  77. /**
  78. * by default there could be 0-9 a-f and the old-multibucket folder which are all fine
  79. */
  80. if ($total < 18) {
  81. $directoryListing = array_filter($directoryListing, function ($dir) {
  82. if ($dir->getName() === 'old-multibucket') {
  83. return false;
  84. }
  85. // a-f can't be a file ID -> removing from migration
  86. if (preg_match('!^[a-f]$!', $dir->getName())) {
  87. return false;
  88. }
  89. if (preg_match('!^[0-9]$!', $dir->getName())) {
  90. // ignore folders that only has folders in them
  91. if ($dir instanceof Folder) {
  92. foreach ($dir->getDirectoryListing() as $entry) {
  93. if (!$entry instanceof Folder) {
  94. return true;
  95. }
  96. }
  97. return false;
  98. }
  99. }
  100. return true;
  101. });
  102. $total = count($directoryListing);
  103. }
  104. if ($total === 0) {
  105. $output->writeln("All previews are already migrated.");
  106. return 0;
  107. }
  108. $output->writeln("A total of $total preview files need to be migrated.");
  109. $output->writeln("");
  110. $output->writeln("The migration will always migrate all previews of a single file in a batch. After each batch the process can be canceled by pressing CTRL-C. This will finish the current batch and then stop the migration. This migration can then just be started and it will continue.");
  111. if ($input->getOption('batch')) {
  112. $output->writeln('Batch mode active: migration is started right away.');
  113. } else {
  114. $helper = $this->getHelper('question');
  115. $question = new ConfirmationQuestion('<info>Should the migration be started? (y/[n]) </info>', false);
  116. if (!$helper->ask($input, $output, $question)) {
  117. return 0;
  118. }
  119. }
  120. // register the SIGINT listener late in here to be able to exit in the early process of this command
  121. pcntl_signal(SIGINT, [$this, 'sigIntHandler']);
  122. $output->writeln("");
  123. $output->writeln("");
  124. $section1 = $output->section();
  125. $section2 = $output->section();
  126. $progressBar = new ProgressBar($section2, $total);
  127. $progressBar->setFormat("%current%/%max% [%bar%] %percent:3s%% %elapsed:6s%/%estimated:-6s% Used Memory: %memory:6s%");
  128. $time = (new \DateTime())->format('H:i:s');
  129. $progressBar->setMessage("$time Starting …");
  130. $progressBar->maxSecondsBetweenRedraws(0.2);
  131. $progressBar->start();
  132. foreach ($directoryListing as $oldPreviewFolder) {
  133. pcntl_signal_dispatch();
  134. $name = $oldPreviewFolder->getName();
  135. $time = (new \DateTime())->format('H:i:s');
  136. $section1->writeln("$time Migrating previews of file with fileId $name …");
  137. $progressBar->display();
  138. if ($this->stopSignalReceived) {
  139. $section1->writeln("$time Stopping migration …");
  140. return 0;
  141. }
  142. if (!$oldPreviewFolder instanceof Folder) {
  143. $section1->writeln(" Skipping non-folder $name …");
  144. $progressBar->advance();
  145. continue;
  146. }
  147. if ($name === 'old-multibucket') {
  148. $section1->writeln(" Skipping fallback mount point $name …");
  149. $progressBar->advance();
  150. continue;
  151. }
  152. if (in_array($name, ['a', 'b', 'c', 'd', 'e', 'f'])) {
  153. $section1->writeln(" Skipping hex-digit folder $name …");
  154. $progressBar->advance();
  155. continue;
  156. }
  157. if (!preg_match('!^\d+$!', $name)) {
  158. $section1->writeln(" Skipping non-numeric folder $name …");
  159. $progressBar->advance();
  160. continue;
  161. }
  162. $newFoldername = Root::getInternalFolder($name);
  163. $memoryUsage = memory_get_usage();
  164. if ($memoryCheckEnabled && $memoryUsage > $this->memoryTreshold) {
  165. $section1->writeln("");
  166. $section1->writeln("");
  167. $section1->writeln("");
  168. $section1->writeln(" Stopped process 25 MB before reaching the memory limit to avoid a hard crash.");
  169. $time = (new \DateTime())->format('H:i:s');
  170. $section1->writeln("$time Reached memory limit and stopped to avoid hard crash.");
  171. return 1;
  172. }
  173. $lockName = 'occ preview:repair lock ' . $oldPreviewFolder->getId();
  174. try {
  175. $section1->writeln(" Locking \"$lockName\" …", OutputInterface::VERBOSITY_VERBOSE);
  176. $this->lockingProvider->acquireLock($lockName, ILockingProvider::LOCK_EXCLUSIVE);
  177. } catch (LockedException $e) {
  178. $section1->writeln(" Skipping because it is locked - another process seems to work on this …");
  179. continue;
  180. }
  181. $previews = $oldPreviewFolder->getDirectoryListing();
  182. if ($previews !== []) {
  183. try {
  184. $this->rootFolder->get("appdata_$instanceId/preview/$newFoldername");
  185. } catch (NotFoundException $e) {
  186. $section1->writeln(" Create folder preview/$newFoldername", OutputInterface::VERBOSITY_VERBOSE);
  187. if (!$dryMode) {
  188. $this->rootFolder->newFolder("appdata_$instanceId/preview/$newFoldername");
  189. }
  190. }
  191. foreach ($previews as $preview) {
  192. pcntl_signal_dispatch();
  193. $previewName = $preview->getName();
  194. if ($preview instanceof Folder) {
  195. $section1->writeln(" Skipping folder $name/$previewName …");
  196. $progressBar->advance();
  197. continue;
  198. }
  199. // Execute process
  200. if (!$dryMode) {
  201. // Delete preview instead of moving
  202. if ($deleteMode) {
  203. try {
  204. $section1->writeln(" Delete preview/$name/$previewName", OutputInterface::VERBOSITY_VERBOSE);
  205. $preview->delete();
  206. } catch (\Exception $e) {
  207. $this->logger->error("Failed to delete preview at preview/$name/$previewName", [
  208. 'app' => 'core',
  209. 'exception' => $e,
  210. ]);
  211. }
  212. } else {
  213. try {
  214. $section1->writeln(" Move preview/$name/$previewName to preview/$newFoldername", OutputInterface::VERBOSITY_VERBOSE);
  215. $preview->move("appdata_$instanceId/preview/$newFoldername/$previewName");
  216. } catch (\Exception $e) {
  217. $this->logger->error("Failed to move preview from preview/$name/$previewName to preview/$newFoldername", [
  218. 'app' => 'core',
  219. 'exception' => $e,
  220. ]);
  221. }
  222. }
  223. }
  224. }
  225. }
  226. if ($oldPreviewFolder->getDirectoryListing() === []) {
  227. $section1->writeln(" Delete empty folder preview/$name", OutputInterface::VERBOSITY_VERBOSE);
  228. if (!$dryMode) {
  229. try {
  230. $oldPreviewFolder->delete();
  231. } catch (\Exception $e) {
  232. $this->logger->error("Failed to delete empty folder preview/$name", [
  233. 'app' => 'core',
  234. 'exception' => $e,
  235. ]);
  236. }
  237. }
  238. }
  239. $this->lockingProvider->releaseLock($lockName, ILockingProvider::LOCK_EXCLUSIVE);
  240. $section1->writeln(" Unlocked", OutputInterface::VERBOSITY_VERBOSE);
  241. $section1->writeln(" Finished migrating previews of file with fileId $name …");
  242. $progressBar->advance();
  243. }
  244. $progressBar->finish();
  245. $output->writeln("");
  246. return 0;
  247. }
  248. protected function sigIntHandler() {
  249. echo "\nSignal received - will finish the step and then stop the migration.\n\n\n";
  250. $this->stopSignalReceived = true;
  251. }
  252. }