Notify.php 12 KB

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