Notify.php 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * SPDX-FileCopyrightText: 2016 Nextcloud GmbH and Nextcloud contributors
  5. * SPDX-License-Identifier: AGPL-3.0-or-later
  6. */
  7. namespace OCA\Files_External\Command;
  8. use Doctrine\DBAL\Exception\DriverException;
  9. use OCA\Files_External\Service\GlobalStoragesService;
  10. use OCP\DB\QueryBuilder\IQueryBuilder;
  11. use OCP\Files\Notify\IChange;
  12. use OCP\Files\Notify\INotifyHandler;
  13. use OCP\Files\Notify\IRenameChange;
  14. use OCP\Files\Storage\INotifyStorage;
  15. use OCP\Files\Storage\IStorage;
  16. use OCP\IDBConnection;
  17. use OCP\IUserManager;
  18. use Psr\Log\LoggerInterface;
  19. use Symfony\Component\Console\Input\InputArgument;
  20. use Symfony\Component\Console\Input\InputInterface;
  21. use Symfony\Component\Console\Input\InputOption;
  22. use Symfony\Component\Console\Output\OutputInterface;
  23. class Notify extends StorageAuthBase {
  24. public function __construct(
  25. private IDBConnection $connection,
  26. private LoggerInterface $logger,
  27. GlobalStoragesService $globalService,
  28. IUserManager $userManager,
  29. ) {
  30. parent::__construct($globalService, $userManager);
  31. }
  32. protected function configure(): void {
  33. $this
  34. ->setName('files_external:notify')
  35. ->setDescription('Listen for active update notifications for a configured external mount')
  36. ->addArgument(
  37. 'mount_id',
  38. InputArgument::REQUIRED,
  39. 'the mount id of the mount to listen to'
  40. )->addOption(
  41. 'user',
  42. 'u',
  43. InputOption::VALUE_REQUIRED,
  44. 'The username for the remote mount (required only for some mount configuration that don\'t store credentials)'
  45. )->addOption(
  46. 'password',
  47. 'p',
  48. InputOption::VALUE_REQUIRED,
  49. 'The password for the remote mount (required only for some mount configuration that don\'t store credentials)'
  50. )->addOption(
  51. 'path',
  52. '',
  53. InputOption::VALUE_REQUIRED,
  54. 'The directory in the storage to listen for updates in',
  55. '/'
  56. )->addOption(
  57. 'no-self-check',
  58. '',
  59. InputOption::VALUE_NONE,
  60. 'Disable self check on startup'
  61. )->addOption(
  62. 'dry-run',
  63. '',
  64. InputOption::VALUE_NONE,
  65. 'Don\'t make any changes, only log detected changes'
  66. );
  67. parent::configure();
  68. }
  69. protected function execute(InputInterface $input, OutputInterface $output): int {
  70. [$mount, $storage] = $this->createStorage($input, $output);
  71. if ($storage === null) {
  72. return self::FAILURE;
  73. }
  74. if (!$storage instanceof INotifyStorage) {
  75. $output->writeln('<error>Mount of type "' . $mount->getBackend()->getText() . '" does not support active update notifications</error>');
  76. return self::FAILURE;
  77. }
  78. $dryRun = $input->getOption('dry-run');
  79. if ($dryRun && $output->getVerbosity() < OutputInterface::VERBOSITY_VERBOSE) {
  80. $output->setVerbosity(OutputInterface::VERBOSITY_VERBOSE);
  81. }
  82. $path = trim($input->getOption('path'), '/');
  83. $notifyHandler = $storage->notify($path);
  84. if (!$input->getOption('no-self-check')) {
  85. $this->selfTest($storage, $notifyHandler, $output);
  86. }
  87. $notifyHandler->listen(function (IChange $change) use ($mount, $output, $dryRun) {
  88. $this->logUpdate($change, $output);
  89. if ($change instanceof IRenameChange) {
  90. $this->markParentAsOutdated($mount->getId(), $change->getTargetPath(), $output, $dryRun);
  91. }
  92. $this->markParentAsOutdated($mount->getId(), $change->getPath(), $output, $dryRun);
  93. });
  94. return self::SUCCESS;
  95. }
  96. private function markParentAsOutdated($mountId, $path, OutputInterface $output, bool $dryRun): void {
  97. $parent = ltrim(dirname($path), '/');
  98. if ($parent === '.') {
  99. $parent = '';
  100. }
  101. try {
  102. $storages = $this->getStorageIds($mountId, $parent);
  103. } catch (DriverException $ex) {
  104. $this->logger->warning('Error while trying to find correct storage ids.', ['exception' => $ex]);
  105. $this->connection = $this->reconnectToDatabase($this->connection, $output);
  106. $output->writeln('<info>Needed to reconnect to the database</info>');
  107. $storages = $this->getStorageIds($mountId, $path);
  108. }
  109. if (count($storages) === 0) {
  110. $output->writeln(" no users found with access to '$parent', skipping", OutputInterface::VERBOSITY_VERBOSE);
  111. return;
  112. }
  113. $users = array_map(function (array $storage) {
  114. return $storage['user_id'];
  115. }, $storages);
  116. $output->writeln(" marking '$parent' as outdated for " . implode(', ', $users), OutputInterface::VERBOSITY_VERBOSE);
  117. $storageIds = array_map(function (array $storage) {
  118. return intval($storage['storage_id']);
  119. }, $storages);
  120. $storageIds = array_values(array_unique($storageIds));
  121. if ($dryRun) {
  122. $output->writeln(" dry-run: skipping database write");
  123. } else {
  124. $result = $this->updateParent($storageIds, $parent);
  125. if ($result === 0) {
  126. //TODO: Find existing parent further up the tree in the database and register that folder instead.
  127. $this->logger->info('Failed updating parent for "' . $path . '" while trying to register change. It may not exist in the filecache.');
  128. }
  129. }
  130. }
  131. private function logUpdate(IChange $change, OutputInterface $output): void {
  132. $text = match ($change->getType()) {
  133. INotifyStorage::NOTIFY_ADDED => 'added',
  134. INotifyStorage::NOTIFY_MODIFIED => 'modified',
  135. INotifyStorage::NOTIFY_REMOVED => 'removed',
  136. INotifyStorage::NOTIFY_RENAMED => 'renamed',
  137. default => '',
  138. };
  139. if ($text === '') {
  140. return;
  141. }
  142. $text .= ' ' . $change->getPath();
  143. if ($change instanceof IRenameChange) {
  144. $text .= ' to ' . $change->getTargetPath();
  145. }
  146. $output->writeln($text, OutputInterface::VERBOSITY_VERBOSE);
  147. }
  148. private function getStorageIds(int $mountId, string $path): array {
  149. $pathHash = md5(trim((string)\OC_Util::normalizeUnicode($path), '/'));
  150. $qb = $this->connection->getQueryBuilder();
  151. return $qb
  152. ->select('storage_id', 'user_id')
  153. ->from('mounts', 'm')
  154. ->innerJoin('m', 'filecache', 'f', $qb->expr()->eq('m.storage_id', 'f.storage'))
  155. ->where($qb->expr()->eq('mount_id', $qb->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)))
  156. ->andWhere($qb->expr()->eq('path_hash', $qb->createNamedParameter($pathHash, IQueryBuilder::PARAM_STR)))
  157. ->execute()
  158. ->fetchAll();
  159. }
  160. private function updateParent(array $storageIds, string $parent): int {
  161. $pathHash = md5(trim((string)\OC_Util::normalizeUnicode($parent), '/'));
  162. $qb = $this->connection->getQueryBuilder();
  163. return $qb
  164. ->update('filecache')
  165. ->set('size', $qb->createNamedParameter(-1, IQueryBuilder::PARAM_INT))
  166. ->where($qb->expr()->in('storage', $qb->createNamedParameter($storageIds, IQueryBuilder::PARAM_INT_ARRAY, ':storage_ids')))
  167. ->andWhere($qb->expr()->eq('path_hash', $qb->createNamedParameter($pathHash, IQueryBuilder::PARAM_STR)))
  168. ->executeStatement();
  169. }
  170. private function reconnectToDatabase(IDBConnection $connection, OutputInterface $output): IDBConnection {
  171. try {
  172. $connection->close();
  173. } catch (\Exception $ex) {
  174. $this->logger->warning('Error while disconnecting from DB', ['exception' => $ex]);
  175. $output->writeln("<info>Error while disconnecting from database: {$ex->getMessage()}</info>");
  176. }
  177. $connected = false;
  178. while (!$connected) {
  179. try {
  180. $connected = $connection->connect();
  181. } catch (\Exception $ex) {
  182. $this->logger->warning('Error while re-connecting to database', ['exception' => $ex]);
  183. $output->writeln("<info>Error while re-connecting to database: {$ex->getMessage()}</info>");
  184. sleep(60);
  185. }
  186. }
  187. return $connection;
  188. }
  189. private function selfTest(IStorage $storage, INotifyHandler $notifyHandler, OutputInterface $output): void {
  190. usleep(100 * 1000); //give time for the notify to start
  191. if (!$storage->file_put_contents('/.nc_test_file.txt', 'test content')) {
  192. $output->writeln("Failed to create test file for self-test");
  193. return;
  194. }
  195. $storage->mkdir('/.nc_test_folder');
  196. $storage->file_put_contents('/.nc_test_folder/subfile.txt', 'test content');
  197. usleep(100 * 1000); //time for all changes to be processed
  198. $changes = $notifyHandler->getChanges();
  199. $storage->unlink('/.nc_test_file.txt');
  200. $storage->unlink('/.nc_test_folder/subfile.txt');
  201. $storage->rmdir('/.nc_test_folder');
  202. usleep(100 * 1000); //time for all changes to be processed
  203. $notifyHandler->getChanges(); // flush
  204. $foundRootChange = false;
  205. $foundSubfolderChange = false;
  206. foreach ($changes as $change) {
  207. if ($change->getPath() === '/.nc_test_file.txt' || $change->getPath() === '.nc_test_file.txt') {
  208. $foundRootChange = true;
  209. } elseif ($change->getPath() === '/.nc_test_folder/subfile.txt' || $change->getPath() === '.nc_test_folder/subfile.txt') {
  210. $foundSubfolderChange = true;
  211. }
  212. }
  213. if ($foundRootChange && $foundSubfolderChange) {
  214. $output->writeln('<info>Self-test successful</info>', OutputInterface::VERBOSITY_VERBOSE);
  215. } elseif ($foundRootChange) {
  216. $output->writeln('<error>Error while running self-test, change is subfolder not detected</error>');
  217. } else {
  218. $output->writeln('<error>Error while running self-test, no changes detected</error>');
  219. }
  220. }
  221. }