UserMountCache.php 17 KB

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