1
0

UserMountCache.php 16 KB

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