1
0

UserMountCache.php 16 KB

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