1
0

Notify.php 9.6 KB

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