Repair.php 11 KB

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