Notify.php 12 KB

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