Passed
Push — master ( 785cca...ff6f10 )
by Morris
10:35
created

Notify::getStorageIds()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 7
nc 1
nop 1
dl 0
loc 8
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * @copyright Copyright (c) 2016 Robin Appelman <[email protected]>
4
 *
5
 * @author Ari Selseng <[email protected]>
6
 * @author Robin Appelman <[email protected]>
7
 * @author Roeland Jago Douma <[email protected]>
8
 *
9
 * @license GNU AGPL version 3 or any later version
10
 *
11
 * This program is free software: you can redistribute it and/or modify
12
 * it under the terms of the GNU Affero General Public License as
13
 * published by the Free Software Foundation, either version 3 of the
14
 * License, or (at your option) any later version.
15
 *
16
 * This program is distributed in the hope that it will be useful,
17
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19
 * GNU Affero General Public License for more details.
20
 *
21
 * You should have received a copy of the GNU Affero General Public License
22
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
23
 *
24
 */
25
26
namespace OCA\Files_External\Command;
27
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 Symfony\Component\Console\Input\InputArgument;
43
use Symfony\Component\Console\Input\InputInterface;
44
use Symfony\Component\Console\Input\InputOption;
45
use Symfony\Component\Console\Output\OutputInterface;
46
47
class Notify extends Base {
48
	/** @var GlobalStoragesService */
49
	private $globalService;
50
	/** @var IDBConnection */
51
	private $connection;
52
	/** @var ILogger */
53
	private $logger;
54
55
	function __construct(GlobalStoragesService $globalService, IDBConnection $connection, ILogger $logger) {
56
		parent::__construct();
57
		$this->globalService = $globalService;
58
		$this->connection = $connection;
59
		$this->logger = $logger;
60
	}
61
62
	protected function configure() {
63
		$this
64
			->setName('files_external:notify')
65
			->setDescription('Listen for active update notifications for a configured external mount')
66
			->addArgument(
67
				'mount_id',
68
				InputArgument::REQUIRED,
69
				'the mount id of the mount to listen to'
70
			)->addOption(
71
				'user',
72
				'u',
73
				InputOption::VALUE_REQUIRED,
74
				'The username for the remote mount (required only for some mount configuration that don\'t store credentials)'
75
			)->addOption(
76
				'password',
77
				'p',
78
				InputOption::VALUE_REQUIRED,
79
				'The password for the remote mount (required only for some mount configuration that don\'t store credentials)'
80
			)->addOption(
81
				'path',
82
				'',
83
				InputOption::VALUE_REQUIRED,
84
				'The directory in the storage to listen for updates in',
85
				'/'
86
			);
87
		parent::configure();
88
	}
89
90
	protected function execute(InputInterface $input, OutputInterface $output) {
91
		$mount = $this->globalService->getStorage($input->getArgument('mount_id'));
92
		if (is_null($mount)) {
93
			$output->writeln('<error>Mount not found</error>');
94
			return 1;
95
		}
96
		$noAuth = false;
97
		try {
98
			$authBackend = $mount->getAuthMechanism();
99
			$authBackend->manipulateStorageConfig($mount);
100
		} catch (InsufficientDataForMeaningfulAnswerException $e) {
101
			$noAuth = true;
102
		} catch (StorageNotAvailableException $e) {
103
			$noAuth = true;
104
		}
105
106
		if ($input->getOption('user')) {
107
			$mount->setBackendOption('user', $input->getOption('user'));
108
		} else if (isset($_ENV['NOTIFY_USER'])) {
109
			$mount->setBackendOption('user', $_ENV['NOTIFY_USER']);
110
		} else if (isset($_SERVER['NOTIFY_USER'])) {
111
			$mount->setBackendOption('user', $_SERVER['NOTIFY_USER']);
112
		}
113
		if ($input->getOption('password')) {
114
			$mount->setBackendOption('password', $input->getOption('password'));
115
		} else if (isset($_ENV['NOTIFY_PASSWORD'])) {
116
			$mount->setBackendOption('password', $_ENV['NOTIFY_PASSWORD']);
117
		} else if (isset($_SERVER['NOTIFY_PASSWORD'])) {
118
			$mount->setBackendOption('password', $_SERVER['NOTIFY_PASSWORD']);
119
		}
120
121
		try {
122
			$storage = $this->createStorage($mount);
123
		} catch (\Exception $e) {
124
			$output->writeln('<error>Error while trying to create storage</error>');
125
			if ($noAuth) {
126
				$output->writeln('<error>Username and/or password required</error>');
127
			}
128
			return 1;
129
		}
130
		if (!$storage instanceof INotifyStorage) {
131
			$output->writeln('<error>Mount of type "' . $mount->getBackend()->getText() . '" does not support active update notifications</error>');
132
			return 1;
133
		}
134
135
		$verbose = $input->getOption('verbose');
136
137
		$path = trim($input->getOption('path'), '/');
138
		$notifyHandler = $storage->notify($path);
139
		$this->selfTest($storage, $notifyHandler, $verbose, $output);
140
		$notifyHandler->listen(function (IChange $change) use ($mount, $verbose, $output) {
141
			if ($verbose) {
142
				$this->logUpdate($change, $output);
143
			}
144
			if ($change instanceof IRenameChange) {
145
				$this->markParentAsOutdated($mount->getId(), $change->getTargetPath(), $output);
146
			}
147
			$this->markParentAsOutdated($mount->getId(), $change->getPath(), $output);
148
		});
149
	}
150
151
	private function createStorage(StorageConfig $mount) {
152
		$class = $mount->getBackend()->getStorageClass();
153
		return new $class($mount->getBackendOptions());
154
	}
155
156
	private function markParentAsOutdated($mountId, $path, OutputInterface $output) {
157
		$parent = ltrim(dirname($path), '/');
158
		if ($parent === '.') {
159
			$parent = '';
160
		}
161
162
		try {
163
			$storageIds = $this->getStorageIds($mountId);
164
		} catch (DriverException $ex) {
165
			$this->logger->logException($ex, ['message' => 'Error while trying to find correct storage ids.', 'level' => ILogger::WARN]);
166
			$this->connection = $this->reconnectToDatabase($this->connection, $output);
167
			$output->writeln('<info>Needed to reconnect to the database</info>');
168
			$storageIds = $this->getStorageIds($mountId);
169
		}
170
		if (count($storageIds) === 0) {
171
			throw new StorageNotAvailableException('No storages found by mount ID ' . $mountId);
172
		}
173
		$storageIds = array_map('intval', $storageIds);
174
175
		$result = $this->updateParent($storageIds, $parent);
176
		if ($result === 0) {
177
			//TODO: Find existing parent further up the tree in the database and register that folder instead.
178
			$this->logger->info('Failed updating parent for "' . $path . '" while trying to register change. It may not exist in the filecache.');
179
		}
180
	}
181
182
	private function logUpdate(IChange $change, OutputInterface $output) {
183
		switch ($change->getType()) {
184
			case INotifyStorage::NOTIFY_ADDED:
185
				$text = 'added';
186
				break;
187
			case INotifyStorage::NOTIFY_MODIFIED:
188
				$text = 'modified';
189
				break;
190
			case INotifyStorage::NOTIFY_REMOVED:
191
				$text = 'removed';
192
				break;
193
			case INotifyStorage::NOTIFY_RENAMED:
194
				$text = 'renamed';
195
				break;
196
			default:
197
				return;
198
		}
199
200
		$text .= ' ' . $change->getPath();
201
		if ($change instanceof IRenameChange) {
202
			$text .= ' to ' . $change->getTargetPath();
203
		}
204
205
		$output->writeln($text);
206
	}
207
208
	/**
209
	 * @param int $mountId
210
	 * @return array
211
	*/
212
	private function getStorageIds($mountId) {
213
		$qb = $this->connection->getQueryBuilder();
214
		return $qb
215
			->select('storage_id')
216
			->from('mounts')
217
			->where($qb->expr()->eq('mount_id', $qb->createNamedParameter($mountId, IQueryBuilder::PARAM_INT)))
218
			->execute()
219
			->fetchAll(\PDO::FETCH_COLUMN);
220
	}
221
222
	/**
223
	 * @param array $storageIds
224
	 * @param string $parent
225
	 * @return int
226
	*/
227
	private function updateParent($storageIds, $parent) {
228
		$pathHash = md5(trim(\OC_Util::normalizeUnicode($parent), '/'));
229
		$qb = $this->connection->getQueryBuilder();
230
		return $qb
0 ignored issues
show
Bug Best Practice introduced by
The expression return $qb->update('file...PARAM_STR)))->execute() also could return the type Doctrine\DBAL\Driver\Statement which is incompatible with the documented return type integer.
Loading history...
231
			->update('filecache')
232
			->set('size', $qb->createNamedParameter(-1, IQueryBuilder::PARAM_INT))
233
			->where($qb->expr()->in('storage', $qb->createNamedParameter($storageIds, IQueryBuilder::PARAM_INT_ARRAY, ':storage_ids')))
234
			->andWhere($qb->expr()->eq('path_hash', $qb->createNamedParameter($pathHash, IQueryBuilder::PARAM_STR)))
235
			->execute();
236
	}
237
238
	/**
239
	 * @return \OCP\IDBConnection
240
	*/
241
	private function reconnectToDatabase(IDBConnection $connection, OutputInterface $output) {
242
		try {
243
			$connection->close();
244
		} catch (\Exception $ex) {
245
			$this->logger->logException($ex, ['app' => 'files_external', 'message' => 'Error while disconnecting from DB', 'level' => ILogger::WARN]);
246
			$output->writeln("<info>Error while disconnecting from database: {$ex->getMessage()}</info>");
247
		}
248
		while (!$connection->isConnected()) {
0 ignored issues
show
Bug introduced by
The method isConnected() does not exist on OCP\IDBConnection. Since it exists in all sub-types, consider adding an abstract or default implementation to OCP\IDBConnection. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

248
		while (!$connection->/** @scrutinizer ignore-call */ isConnected()) {
Loading history...
249
			try {
250
				$connection->connect();
251
			} catch (\Exception $ex) {
252
				$this->logger->logException($ex, ['app' => 'files_external', 'message' => 'Error while re-connecting to database', 'level' => ILogger::WARN]);
253
				$output->writeln("<info>Error while re-connecting to database: {$ex->getMessage()}</info>");
254
				sleep(60);
255
			}
256
		}
257
		return $connection;
258
	}
259
260
261
	private function selfTest(IStorage $storage, INotifyHandler $notifyHandler, $verbose, OutputInterface $output) {
262
		usleep(100 * 1000); //give time for the notify to start
263
		$storage->file_put_contents('/.nc_test_file.txt', 'test content');
264
		$storage->mkdir('/.nc_test_folder');
265
		$storage->file_put_contents('/.nc_test_folder/subfile.txt', 'test content');
266
267
		usleep(100 * 1000); //time for all changes to be processed
268
		$changes = $notifyHandler->getChanges();
269
270
		$storage->unlink('/.nc_test_file.txt');
271
		$storage->unlink('/.nc_test_folder/subfile.txt');
272
		$storage->rmdir('/.nc_test_folder');
273
274
		usleep(100 * 1000); //time for all changes to be processed
275
		$notifyHandler->getChanges(); // flush
276
277
		$foundRootChange = false;
278
		$foundSubfolderChange = false;
279
280
		foreach ($changes as $change) {
281
			if ($change->getPath() === '/.nc_test_file.txt' || $change->getPath() === '.nc_test_file.txt') {
282
				$foundRootChange = true;
283
			} else if ($change->getPath() === '/.nc_test_folder/subfile.txt' || $change->getPath() === '.nc_test_folder/subfile.txt') {
284
				$foundSubfolderChange = true;
285
			}
286
		}
287
288
		if ($foundRootChange && $foundSubfolderChange && $verbose) {
289
			$output->writeln('<info>Self-test successful</info>');
290
		} else if ($foundRootChange && !$foundSubfolderChange) {
291
			$output->writeln('<error>Error while running self-test, change is subfolder not detected</error>');
292
		} else if (!$foundRootChange) {
293
			$output->writeln('<error>Error while running self-test, no changes detected</error>');
294
		}
295
	}
296
}
297