Notify.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  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 OC\Core\Command\Base;
  31. use OCA\Files_External\Lib\InsufficientDataForMeaningfulAnswerException;
  32. use OCA\Files_External\Lib\StorageConfig;
  33. use OCA\Files_External\Service\GlobalStoragesService;
  34. use OCP\DB\QueryBuilder\IQueryBuilder;
  35. use OCP\Files\Notify\IChange;
  36. use OCP\Files\Notify\INotifyHandler;
  37. use OCP\Files\Notify\IRenameChange;
  38. use OCP\Files\Storage\INotifyStorage;
  39. use OCP\Files\Storage\IStorage;
  40. use OCP\Files\StorageNotAvailableException;
  41. use OCP\IDBConnection;
  42. use OCP\IUserManager;
  43. use Psr\Log\LoggerInterface;
  44. use Symfony\Component\Console\Input\InputArgument;
  45. use Symfony\Component\Console\Input\InputInterface;
  46. use Symfony\Component\Console\Input\InputOption;
  47. use Symfony\Component\Console\Output\OutputInterface;
  48. class Notify extends Base {
  49. public function __construct(
  50. private GlobalStoragesService $globalService,
  51. private IDBConnection $connection,
  52. private LoggerInterface $logger,
  53. private IUserManager $userManager
  54. ) {
  55. parent::__construct();
  56. }
  57. protected function configure(): void {
  58. $this
  59. ->setName('files_external:notify')
  60. ->setDescription('Listen for active update notifications for a configured external mount')
  61. ->addArgument(
  62. 'mount_id',
  63. InputArgument::REQUIRED,
  64. 'the mount id of the mount to listen to'
  65. )->addOption(
  66. 'user',
  67. 'u',
  68. InputOption::VALUE_REQUIRED,
  69. 'The username for the remote mount (required only for some mount configuration that don\'t store credentials)'
  70. )->addOption(
  71. 'password',
  72. 'p',
  73. InputOption::VALUE_REQUIRED,
  74. 'The password for the remote mount (required only for some mount configuration that don\'t store credentials)'
  75. )->addOption(
  76. 'path',
  77. '',
  78. InputOption::VALUE_REQUIRED,
  79. 'The directory in the storage to listen for updates in',
  80. '/'
  81. )->addOption(
  82. 'no-self-check',
  83. '',
  84. InputOption::VALUE_NONE,
  85. 'Disable self check on startup'
  86. )->addOption(
  87. 'dry-run',
  88. '',
  89. InputOption::VALUE_NONE,
  90. 'Don\'t make any changes, only log detected changes'
  91. );
  92. parent::configure();
  93. }
  94. private function getUserOption(InputInterface $input): ?string {
  95. if ($input->getOption('user')) {
  96. return (string)$input->getOption('user');
  97. }
  98. return $_ENV['NOTIFY_USER'] ?? $_SERVER['NOTIFY_USER'] ?? null;
  99. }
  100. private function getPasswordOption(InputInterface $input): ?string {
  101. if ($input->getOption('password')) {
  102. return (string)$input->getOption('password');
  103. }
  104. return $_ENV['NOTIFY_PASSWORD'] ?? $_SERVER['NOTIFY_PASSWORD'] ?? null;
  105. }
  106. protected function execute(InputInterface $input, OutputInterface $output): int {
  107. $mount = $this->globalService->getStorage($input->getArgument('mount_id'));
  108. if (is_null($mount)) {
  109. $output->writeln('<error>Mount not found</error>');
  110. return self::FAILURE;
  111. }
  112. $noAuth = false;
  113. $userOption = $this->getUserOption($input);
  114. $passwordOption = $this->getPasswordOption($input);
  115. // if only the user is provided, we get the user object to pass along to the auth backend
  116. // this allows using saved user credentials
  117. $user = ($userOption && !$passwordOption) ? $this->userManager->get($userOption) : null;
  118. try {
  119. $authBackend = $mount->getAuthMechanism();
  120. $authBackend->manipulateStorageConfig($mount, $user);
  121. } catch (InsufficientDataForMeaningfulAnswerException $e) {
  122. $noAuth = true;
  123. } catch (StorageNotAvailableException $e) {
  124. $noAuth = true;
  125. }
  126. if ($userOption) {
  127. $mount->setBackendOption('user', $userOption);
  128. }
  129. if ($passwordOption) {
  130. $mount->setBackendOption('password', $passwordOption);
  131. }
  132. try {
  133. $backend = $mount->getBackend();
  134. $backend->manipulateStorageConfig($mount, $user);
  135. } catch (InsufficientDataForMeaningfulAnswerException $e) {
  136. $noAuth = true;
  137. } catch (StorageNotAvailableException $e) {
  138. $noAuth = true;
  139. }
  140. try {
  141. $storage = $this->createStorage($mount);
  142. } catch (\Exception $e) {
  143. $output->writeln('<error>Error while trying to create storage</error>');
  144. if ($noAuth) {
  145. $output->writeln('<error>Username and/or password required</error>');
  146. }
  147. return self::FAILURE;
  148. }
  149. if (!$storage instanceof INotifyStorage) {
  150. $output->writeln('<error>Mount of type "' . $mount->getBackend()->getText() . '" does not support active update notifications</error>');
  151. return self::FAILURE;
  152. }
  153. $dryRun = $input->getOption('dry-run');
  154. if ($dryRun && $output->getVerbosity() < OutputInterface::VERBOSITY_VERBOSE) {
  155. $output->setVerbosity(OutputInterface::VERBOSITY_VERBOSE);
  156. }
  157. $path = trim($input->getOption('path'), '/');
  158. $notifyHandler = $storage->notify($path);
  159. if (!$input->getOption('no-self-check')) {
  160. $this->selfTest($storage, $notifyHandler, $output);
  161. }
  162. $notifyHandler->listen(function (IChange $change) use ($mount, $output, $dryRun) {
  163. $this->logUpdate($change, $output);
  164. if ($change instanceof IRenameChange) {
  165. $this->markParentAsOutdated($mount->getId(), $change->getTargetPath(), $output, $dryRun);
  166. }
  167. $this->markParentAsOutdated($mount->getId(), $change->getPath(), $output, $dryRun);
  168. });
  169. return self::SUCCESS;
  170. }
  171. private function createStorage(StorageConfig $mount): IStorage {
  172. $class = $mount->getBackend()->getStorageClass();
  173. return new $class($mount->getBackendOptions());
  174. }
  175. private function markParentAsOutdated($mountId, $path, OutputInterface $output, bool $dryRun): void {
  176. $parent = ltrim(dirname($path), '/');
  177. if ($parent === '.') {
  178. $parent = '';
  179. }
  180. try {
  181. $storages = $this->getStorageIds($mountId, $parent);
  182. } catch (DriverException $ex) {
  183. $this->logger->warning('Error while trying to find correct storage ids.', ['exception' => $ex]);
  184. $this->connection = $this->reconnectToDatabase($this->connection, $output);
  185. $output->writeln('<info>Needed to reconnect to the database</info>');
  186. $storages = $this->getStorageIds($mountId, $path);
  187. }
  188. if (count($storages) === 0) {
  189. $output->writeln(" no users found with access to '$parent', skipping", OutputInterface::VERBOSITY_VERBOSE);
  190. return;
  191. }
  192. $users = array_map(function (array $storage) {
  193. return $storage['user_id'];
  194. }, $storages);
  195. $output->writeln(" marking '$parent' as outdated for " . implode(', ', $users), OutputInterface::VERBOSITY_VERBOSE);
  196. $storageIds = array_map(function (array $storage) {
  197. return intval($storage['storage_id']);
  198. }, $storages);
  199. $storageIds = array_values(array_unique($storageIds));
  200. if ($dryRun) {
  201. $output->writeln(" dry-run: skipping database write");
  202. } else {
  203. $result = $this->updateParent($storageIds, $parent);
  204. if ($result === 0) {
  205. //TODO: Find existing parent further up the tree in the database and register that folder instead.
  206. $this->logger->info('Failed updating parent for "' . $path . '" while trying to register change. It may not exist in the filecache.');
  207. }
  208. }
  209. }
  210. private function logUpdate(IChange $change, OutputInterface $output): void {
  211. $text = match ($change->getType()) {
  212. INotifyStorage::NOTIFY_ADDED => 'added',
  213. INotifyStorage::NOTIFY_MODIFIED => 'modified',
  214. INotifyStorage::NOTIFY_REMOVED => 'removed',
  215. INotifyStorage::NOTIFY_RENAMED => 'renamed',
  216. default => '',
  217. };
  218. if ($text === '') {
  219. return;
  220. }
  221. $text .= ' ' . $change->getPath();
  222. if ($change instanceof IRenameChange) {
  223. $text .= ' to ' . $change->getTargetPath();
  224. }
  225. $output->writeln($text, OutputInterface::VERBOSITY_VERBOSE);
  226. }
  227. private function getStorageIds(int $mountId, string $path): array {
  228. $pathHash = md5(trim((string)\OC_Util::normalizeUnicode($path), '/'));
  229. $qb = $this->connection->getQueryBuilder();
  230. return $qb
  231. ->select('storage_id', 'user_id')
  232. ->from('mounts', 'm')
  233. ->innerJoin('m', 'filecache', 'f', $qb->expr()->eq('m.storage_id', 'f.storage'))
  234. ->where($qb->expr()->eq('mount_id', $qb->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)))
  235. ->andWhere($qb->expr()->eq('path_hash', $qb->createNamedParameter($pathHash, IQueryBuilder::PARAM_STR)))
  236. ->execute()
  237. ->fetchAll();
  238. }
  239. private function updateParent(array $storageIds, string $parent): int {
  240. $pathHash = md5(trim((string)\OC_Util::normalizeUnicode($parent), '/'));
  241. $qb = $this->connection->getQueryBuilder();
  242. return $qb
  243. ->update('filecache')
  244. ->set('size', $qb->createNamedParameter(-1, IQueryBuilder::PARAM_INT))
  245. ->where($qb->expr()->in('storage', $qb->createNamedParameter($storageIds, IQueryBuilder::PARAM_INT_ARRAY, ':storage_ids')))
  246. ->andWhere($qb->expr()->eq('path_hash', $qb->createNamedParameter($pathHash, IQueryBuilder::PARAM_STR)))
  247. ->executeStatement();
  248. }
  249. private function reconnectToDatabase(IDBConnection $connection, OutputInterface $output): IDBConnection {
  250. try {
  251. $connection->close();
  252. } catch (\Exception $ex) {
  253. $this->logger->warning('Error while disconnecting from DB', ['exception' => $ex]);
  254. $output->writeln("<info>Error while disconnecting from database: {$ex->getMessage()}</info>");
  255. }
  256. $connected = false;
  257. while (!$connected) {
  258. try {
  259. $connected = $connection->connect();
  260. } catch (\Exception $ex) {
  261. $this->logger->warning('Error while re-connecting to database', ['exception' => $ex]);
  262. $output->writeln("<info>Error while re-connecting to database: {$ex->getMessage()}</info>");
  263. sleep(60);
  264. }
  265. }
  266. return $connection;
  267. }
  268. private function selfTest(IStorage $storage, INotifyHandler $notifyHandler, OutputInterface $output): void {
  269. usleep(100 * 1000); //give time for the notify to start
  270. if (!$storage->file_put_contents('/.nc_test_file.txt', 'test content')) {
  271. $output->writeln("Failed to create test file for self-test");
  272. return;
  273. }
  274. $storage->mkdir('/.nc_test_folder');
  275. $storage->file_put_contents('/.nc_test_folder/subfile.txt', 'test content');
  276. usleep(100 * 1000); //time for all changes to be processed
  277. $changes = $notifyHandler->getChanges();
  278. $storage->unlink('/.nc_test_file.txt');
  279. $storage->unlink('/.nc_test_folder/subfile.txt');
  280. $storage->rmdir('/.nc_test_folder');
  281. usleep(100 * 1000); //time for all changes to be processed
  282. $notifyHandler->getChanges(); // flush
  283. $foundRootChange = false;
  284. $foundSubfolderChange = false;
  285. foreach ($changes as $change) {
  286. if ($change->getPath() === '/.nc_test_file.txt' || $change->getPath() === '.nc_test_file.txt') {
  287. $foundRootChange = true;
  288. } elseif ($change->getPath() === '/.nc_test_folder/subfile.txt' || $change->getPath() === '.nc_test_folder/subfile.txt') {
  289. $foundSubfolderChange = true;
  290. }
  291. }
  292. if ($foundRootChange && $foundSubfolderChange) {
  293. $output->writeln('<info>Self-test successful</info>', OutputInterface::VERBOSITY_VERBOSE);
  294. } elseif ($foundRootChange) {
  295. $output->writeln('<error>Error while running self-test, change is subfolder not detected</error>');
  296. } else {
  297. $output->writeln('<error>Error while running self-test, no changes detected</error>');
  298. }
  299. }
  300. }