1
0

UserMountCache.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Dariusz Olszewski <starypatyk@users.noreply.github.com>
  6. * @author Joas Schilling <coding@schilljs.com>
  7. * @author Julius Härtl <jus@bitgrid.net>
  8. * @author Lukas Reschke <lukas@statuscode.ch>
  9. * @author Morris Jobke <hey@morrisjobke.de>
  10. * @author Robin Appelman <robin@icewind.nl>
  11. * @author Roeland Jago Douma <roeland@famdouma.nl>
  12. * @author Vincent Petry <vincent@nextcloud.com>
  13. *
  14. * @license AGPL-3.0
  15. *
  16. * This code is free software: you can redistribute it and/or modify
  17. * it under the terms of the GNU Affero General Public License, version 3,
  18. * as published by the Free Software Foundation.
  19. *
  20. * This program is distributed in the hope that it will be useful,
  21. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  22. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  23. * GNU Affero General Public License for more details.
  24. *
  25. * You should have received a copy of the GNU Affero General Public License, version 3,
  26. * along with this program. If not, see <http://www.gnu.org/licenses/>
  27. *
  28. */
  29. namespace OC\Files\Config;
  30. use OCP\Cache\CappedMemoryCache;
  31. use OCP\DB\QueryBuilder\IQueryBuilder;
  32. use OCP\Diagnostics\IEventLogger;
  33. use OCP\Files\Config\ICachedMountFileInfo;
  34. use OCP\Files\Config\ICachedMountInfo;
  35. use OCP\Files\Config\IUserMountCache;
  36. use OCP\Files\NotFoundException;
  37. use OCP\IDBConnection;
  38. use OCP\IUser;
  39. use OCP\IUserManager;
  40. use Psr\Log\LoggerInterface;
  41. /**
  42. * Cache mounts points per user in the cache so we can easily look them up
  43. */
  44. class UserMountCache implements IUserMountCache {
  45. private IDBConnection $connection;
  46. private IUserManager $userManager;
  47. /**
  48. * Cached mount info.
  49. * @var CappedMemoryCache<ICachedMountInfo[]>
  50. **/
  51. private CappedMemoryCache $mountsForUsers;
  52. private LoggerInterface $logger;
  53. /** @var CappedMemoryCache<array> */
  54. private CappedMemoryCache $cacheInfoCache;
  55. private IEventLogger $eventLogger;
  56. /**
  57. * UserMountCache constructor.
  58. */
  59. public function __construct(
  60. IDBConnection $connection,
  61. IUserManager $userManager,
  62. LoggerInterface $logger,
  63. IEventLogger $eventLogger
  64. ) {
  65. $this->connection = $connection;
  66. $this->userManager = $userManager;
  67. $this->logger = $logger;
  68. $this->eventLogger = $eventLogger;
  69. $this->cacheInfoCache = new CappedMemoryCache();
  70. $this->mountsForUsers = new CappedMemoryCache();
  71. }
  72. public function registerMounts(IUser $user, array $mounts, array $mountProviderClasses = null) {
  73. $this->eventLogger->start('fs:setup:user:register', 'Registering mounts for user');
  74. /** @var array<string, ICachedMountInfo> $newMounts */
  75. $newMounts = [];
  76. foreach ($mounts as $mount) {
  77. // filter out any storages which aren't scanned yet since we aren't interested in files from those storages (yet)
  78. if ($mount->getStorageRootId() !== -1) {
  79. $mountInfo = new LazyStorageMountInfo($user, $mount);
  80. $newMounts[$mountInfo->getKey()] = $mountInfo;
  81. }
  82. }
  83. $cachedMounts = $this->getMountsForUser($user);
  84. if (is_array($mountProviderClasses)) {
  85. $cachedMounts = array_filter($cachedMounts, function (ICachedMountInfo $mountInfo) use ($mountProviderClasses, $newMounts) {
  86. // for existing mounts that didn't have a mount provider set
  87. // we still want the ones that map to new mounts
  88. if ($mountInfo->getMountProvider() === '' && isset($newMounts[$mountInfo->getKey()])) {
  89. return true;
  90. }
  91. return in_array($mountInfo->getMountProvider(), $mountProviderClasses);
  92. });
  93. }
  94. $addedMounts = [];
  95. $removedMounts = [];
  96. foreach ($newMounts as $mountKey => $newMount) {
  97. if (!isset($cachedMounts[$mountKey])) {
  98. $addedMounts[] = $newMount;
  99. }
  100. }
  101. foreach ($cachedMounts as $mountKey => $cachedMount) {
  102. if (!isset($newMounts[$mountKey])) {
  103. $removedMounts[] = $cachedMount;
  104. }
  105. }
  106. $changedMounts = $this->findChangedMounts($newMounts, $cachedMounts);
  107. if ($addedMounts || $removedMounts || $changedMounts) {
  108. $this->connection->beginTransaction();
  109. $userUID = $user->getUID();
  110. try {
  111. foreach ($addedMounts as $mount) {
  112. $this->addToCache($mount);
  113. /** @psalm-suppress InvalidArgument */
  114. $this->mountsForUsers[$userUID][$mount->getKey()] = $mount;
  115. }
  116. foreach ($removedMounts as $mount) {
  117. $this->removeFromCache($mount);
  118. unset($this->mountsForUsers[$userUID][$mount->getKey()]);
  119. }
  120. foreach ($changedMounts as $mount) {
  121. $this->updateCachedMount($mount);
  122. /** @psalm-suppress InvalidArgument */
  123. $this->mountsForUsers[$userUID][$mount->getKey()] = $mount;
  124. }
  125. $this->connection->commit();
  126. } catch (\Throwable $e) {
  127. $this->connection->rollBack();
  128. throw $e;
  129. }
  130. }
  131. $this->eventLogger->end('fs:setup:user:register');
  132. }
  133. /**
  134. * @param array<string, ICachedMountInfo> $newMounts
  135. * @param array<string, ICachedMountInfo> $cachedMounts
  136. * @return ICachedMountInfo[]
  137. */
  138. private function findChangedMounts(array $newMounts, array $cachedMounts) {
  139. $changed = [];
  140. foreach ($cachedMounts as $key => $cachedMount) {
  141. if (isset($newMounts[$key])) {
  142. $newMount = $newMounts[$key];
  143. if (
  144. $newMount->getStorageId() !== $cachedMount->getStorageId() ||
  145. $newMount->getMountId() !== $cachedMount->getMountId() ||
  146. $newMount->getMountProvider() !== $cachedMount->getMountProvider()
  147. ) {
  148. $changed[] = $newMount;
  149. }
  150. }
  151. }
  152. return $changed;
  153. }
  154. private function addToCache(ICachedMountInfo $mount) {
  155. if ($mount->getStorageId() !== -1) {
  156. $this->connection->insertIfNotExist('*PREFIX*mounts', [
  157. 'storage_id' => $mount->getStorageId(),
  158. 'root_id' => $mount->getRootId(),
  159. 'user_id' => $mount->getUser()->getUID(),
  160. 'mount_point' => $mount->getMountPoint(),
  161. 'mount_id' => $mount->getMountId(),
  162. 'mount_provider_class' => $mount->getMountProvider(),
  163. ], ['root_id', 'user_id', 'mount_point']);
  164. } else {
  165. // in some cases this is legitimate, like orphaned shares
  166. $this->logger->debug('Could not get storage info for mount at ' . $mount->getMountPoint());
  167. }
  168. }
  169. private function updateCachedMount(ICachedMountInfo $mount) {
  170. $builder = $this->connection->getQueryBuilder();
  171. $query = $builder->update('mounts')
  172. ->set('storage_id', $builder->createNamedParameter($mount->getStorageId()))
  173. ->set('mount_point', $builder->createNamedParameter($mount->getMountPoint()))
  174. ->set('mount_id', $builder->createNamedParameter($mount->getMountId(), IQueryBuilder::PARAM_INT))
  175. ->set('mount_provider_class', $builder->createNamedParameter($mount->getMountProvider()))
  176. ->where($builder->expr()->eq('user_id', $builder->createNamedParameter($mount->getUser()->getUID())))
  177. ->andWhere($builder->expr()->eq('root_id', $builder->createNamedParameter($mount->getRootId(), IQueryBuilder::PARAM_INT)));
  178. $query->execute();
  179. }
  180. private function removeFromCache(ICachedMountInfo $mount) {
  181. $builder = $this->connection->getQueryBuilder();
  182. $query = $builder->delete('mounts')
  183. ->where($builder->expr()->eq('user_id', $builder->createNamedParameter($mount->getUser()->getUID())))
  184. ->andWhere($builder->expr()->eq('root_id', $builder->createNamedParameter($mount->getRootId(), IQueryBuilder::PARAM_INT)))
  185. ->andWhere($builder->expr()->eq('mount_point', $builder->createNamedParameter($mount->getMountPoint())));
  186. $query->execute();
  187. }
  188. private function dbRowToMountInfo(array $row) {
  189. $user = $this->userManager->get($row['user_id']);
  190. if (is_null($user)) {
  191. return null;
  192. }
  193. $mount_id = $row['mount_id'];
  194. if (!is_null($mount_id)) {
  195. $mount_id = (int)$mount_id;
  196. }
  197. return new CachedMountInfo(
  198. $user,
  199. (int)$row['storage_id'],
  200. (int)$row['root_id'],
  201. $row['mount_point'],
  202. $row['mount_provider_class'] ?? '',
  203. $mount_id,
  204. isset($row['path']) ? $row['path'] : '',
  205. );
  206. }
  207. /**
  208. * @param IUser $user
  209. * @return ICachedMountInfo[]
  210. */
  211. public function getMountsForUser(IUser $user) {
  212. $userUID = $user->getUID();
  213. if (!isset($this->mountsForUsers[$userUID])) {
  214. $builder = $this->connection->getQueryBuilder();
  215. $query = $builder->select('storage_id', 'root_id', 'user_id', 'mount_point', 'mount_id', 'f.path', 'mount_provider_class')
  216. ->from('mounts', 'm')
  217. ->innerJoin('m', 'filecache', 'f', $builder->expr()->eq('m.root_id', 'f.fileid'))
  218. ->where($builder->expr()->eq('user_id', $builder->createPositionalParameter($userUID)));
  219. $result = $query->execute();
  220. $rows = $result->fetchAll();
  221. $result->closeCursor();
  222. $this->mountsForUsers[$userUID] = [];
  223. /** @var array<string, ICachedMountInfo> $mounts */
  224. foreach ($rows as $row) {
  225. $mount = $this->dbRowToMountInfo($row);
  226. if ($mount !== null) {
  227. $this->mountsForUsers[$userUID][$mount->getKey()] = $mount;
  228. }
  229. }
  230. }
  231. return $this->mountsForUsers[$userUID];
  232. }
  233. /**
  234. * @param int $numericStorageId
  235. * @param string|null $user limit the results to a single user
  236. * @return CachedMountInfo[]
  237. */
  238. public function getMountsForStorageId($numericStorageId, $user = null) {
  239. $builder = $this->connection->getQueryBuilder();
  240. $query = $builder->select('storage_id', 'root_id', 'user_id', 'mount_point', 'mount_id', 'f.path', 'mount_provider_class')
  241. ->from('mounts', 'm')
  242. ->innerJoin('m', 'filecache', 'f', $builder->expr()->eq('m.root_id', 'f.fileid'))
  243. ->where($builder->expr()->eq('storage_id', $builder->createPositionalParameter($numericStorageId, IQueryBuilder::PARAM_INT)));
  244. if ($user) {
  245. $query->andWhere($builder->expr()->eq('user_id', $builder->createPositionalParameter($user)));
  246. }
  247. $result = $query->execute();
  248. $rows = $result->fetchAll();
  249. $result->closeCursor();
  250. return array_filter(array_map([$this, 'dbRowToMountInfo'], $rows));
  251. }
  252. /**
  253. * @param int $rootFileId
  254. * @return CachedMountInfo[]
  255. */
  256. public function getMountsForRootId($rootFileId) {
  257. $builder = $this->connection->getQueryBuilder();
  258. $query = $builder->select('storage_id', 'root_id', 'user_id', 'mount_point', 'mount_id', 'f.path', 'mount_provider_class')
  259. ->from('mounts', 'm')
  260. ->innerJoin('m', 'filecache', 'f', $builder->expr()->eq('m.root_id', 'f.fileid'))
  261. ->where($builder->expr()->eq('root_id', $builder->createPositionalParameter($rootFileId, IQueryBuilder::PARAM_INT)));
  262. $result = $query->execute();
  263. $rows = $result->fetchAll();
  264. $result->closeCursor();
  265. return array_filter(array_map([$this, 'dbRowToMountInfo'], $rows));
  266. }
  267. /**
  268. * @param $fileId
  269. * @return array{int, string, int}
  270. * @throws \OCP\Files\NotFoundException
  271. */
  272. private function getCacheInfoFromFileId($fileId): array {
  273. if (!isset($this->cacheInfoCache[$fileId])) {
  274. $builder = $this->connection->getQueryBuilder();
  275. $query = $builder->select('storage', 'path', 'mimetype')
  276. ->from('filecache')
  277. ->where($builder->expr()->eq('fileid', $builder->createNamedParameter($fileId, IQueryBuilder::PARAM_INT)));
  278. $result = $query->execute();
  279. $row = $result->fetch();
  280. $result->closeCursor();
  281. if (is_array($row)) {
  282. $this->cacheInfoCache[$fileId] = [
  283. (int)$row['storage'],
  284. (string)$row['path'],
  285. (int)$row['mimetype']
  286. ];
  287. } else {
  288. throw new NotFoundException('File with id "' . $fileId . '" not found');
  289. }
  290. }
  291. return $this->cacheInfoCache[$fileId];
  292. }
  293. /**
  294. * @param int $fileId
  295. * @param string|null $user optionally restrict the results to a single user
  296. * @return ICachedMountFileInfo[]
  297. * @since 9.0.0
  298. */
  299. public function getMountsForFileId($fileId, $user = null) {
  300. try {
  301. [$storageId, $internalPath] = $this->getCacheInfoFromFileId($fileId);
  302. } catch (NotFoundException $e) {
  303. return [];
  304. }
  305. $builder = $this->connection->getQueryBuilder();
  306. $query = $builder->select('storage_id', 'root_id', 'user_id', 'mount_point', 'mount_id', 'f.path', 'mount_provider_class')
  307. ->from('mounts', 'm')
  308. ->innerJoin('m', 'filecache', 'f', $builder->expr()->eq('m.root_id', 'f.fileid'))
  309. ->where($builder->expr()->eq('storage_id', $builder->createPositionalParameter($storageId, IQueryBuilder::PARAM_INT)));
  310. if ($user) {
  311. $query->andWhere($builder->expr()->eq('user_id', $builder->createPositionalParameter($user)));
  312. }
  313. $result = $query->execute();
  314. $rows = $result->fetchAll();
  315. $result->closeCursor();
  316. // filter mounts that are from the same storage but a different directory
  317. $filteredMounts = array_filter($rows, function (array $row) use ($internalPath, $fileId) {
  318. if ($fileId === (int)$row['root_id']) {
  319. return true;
  320. }
  321. $internalMountPath = $row['path'] ?? '';
  322. return $internalMountPath === '' || substr($internalPath, 0, strlen($internalMountPath) + 1) === $internalMountPath . '/';
  323. });
  324. $filteredMounts = array_filter(array_map([$this, 'dbRowToMountInfo'], $filteredMounts));
  325. return array_map(function (ICachedMountInfo $mount) use ($internalPath) {
  326. return new CachedMountFileInfo(
  327. $mount->getUser(),
  328. $mount->getStorageId(),
  329. $mount->getRootId(),
  330. $mount->getMountPoint(),
  331. $mount->getMountId(),
  332. $mount->getMountProvider(),
  333. $mount->getRootInternalPath(),
  334. $internalPath
  335. );
  336. }, $filteredMounts);
  337. }
  338. /**
  339. * Remove all cached mounts for a user
  340. *
  341. * @param IUser $user
  342. */
  343. public function removeUserMounts(IUser $user) {
  344. $builder = $this->connection->getQueryBuilder();
  345. $query = $builder->delete('mounts')
  346. ->where($builder->expr()->eq('user_id', $builder->createNamedParameter($user->getUID())));
  347. $query->execute();
  348. }
  349. public function removeUserStorageMount($storageId, $userId) {
  350. $builder = $this->connection->getQueryBuilder();
  351. $query = $builder->delete('mounts')
  352. ->where($builder->expr()->eq('user_id', $builder->createNamedParameter($userId)))
  353. ->andWhere($builder->expr()->eq('storage_id', $builder->createNamedParameter($storageId, IQueryBuilder::PARAM_INT)));
  354. $query->execute();
  355. }
  356. public function remoteStorageMounts($storageId) {
  357. $builder = $this->connection->getQueryBuilder();
  358. $query = $builder->delete('mounts')
  359. ->where($builder->expr()->eq('storage_id', $builder->createNamedParameter($storageId, IQueryBuilder::PARAM_INT)));
  360. $query->execute();
  361. }
  362. /**
  363. * @param array $users
  364. * @return array
  365. */
  366. public function getUsedSpaceForUsers(array $users) {
  367. $builder = $this->connection->getQueryBuilder();
  368. $slash = $builder->createNamedParameter('/');
  369. $mountPoint = $builder->func()->concat(
  370. $builder->func()->concat($slash, 'user_id'),
  371. $slash
  372. );
  373. $userIds = array_map(function (IUser $user) {
  374. return $user->getUID();
  375. }, $users);
  376. $query = $builder->select('m.user_id', 'f.size')
  377. ->from('mounts', 'm')
  378. ->innerJoin('m', 'filecache', 'f',
  379. $builder->expr()->andX(
  380. $builder->expr()->eq('m.storage_id', 'f.storage'),
  381. $builder->expr()->eq('f.path_hash', $builder->createNamedParameter(md5('files')))
  382. ))
  383. ->where($builder->expr()->eq('m.mount_point', $mountPoint))
  384. ->andWhere($builder->expr()->in('m.user_id', $builder->createNamedParameter($userIds, IQueryBuilder::PARAM_STR_ARRAY)));
  385. $result = $query->execute();
  386. $results = [];
  387. while ($row = $result->fetch()) {
  388. $results[$row['user_id']] = $row['size'];
  389. }
  390. $result->closeCursor();
  391. return $results;
  392. }
  393. public function clear(): void {
  394. $this->cacheInfoCache = new CappedMemoryCache();
  395. $this->mountsForUsers = new CappedMemoryCache();
  396. }
  397. public function getMountForPath(IUser $user, string $path): ICachedMountInfo {
  398. $mounts = $this->getMountsForUser($user);
  399. $mountPoints = array_map(function (ICachedMountInfo $mount) {
  400. return $mount->getMountPoint();
  401. }, $mounts);
  402. $mounts = array_combine($mountPoints, $mounts);
  403. $current = rtrim($path, '/');
  404. // walk up the directory tree until we find a path that has a mountpoint set
  405. // the loop will return if a mountpoint is found or break if none are found
  406. while (true) {
  407. $mountPoint = $current . '/';
  408. if (isset($mounts[$mountPoint])) {
  409. return $mounts[$mountPoint];
  410. } elseif ($current === '') {
  411. break;
  412. }
  413. $current = dirname($current);
  414. if ($current === '.' || $current === '/') {
  415. $current = '';
  416. }
  417. }
  418. throw new NotFoundException("No cached mount for path " . $path);
  419. }
  420. public function getMountsInPath(IUser $user, string $path): array {
  421. $path = rtrim($path, '/') . '/';
  422. $mounts = $this->getMountsForUser($user);
  423. return array_filter($mounts, function (ICachedMountInfo $mount) use ($path) {
  424. return $mount->getMountPoint() !== $path && strpos($mount->getMountPoint(), $path) === 0;
  425. });
  426. }
  427. }