UserMountCache.php 17 KB

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