Repair.php 11 KB

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