You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

StoragesService.php 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2017-2024 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-FileCopyrightText: 2016 ownCloud, Inc.
  5. * SPDX-License-Identifier: AGPL-3.0-only
  6. */
  7. namespace OCA\Files_External\Service;
  8. use OC\Files\Filesystem;
  9. use OCA\Files_External\Lib\Auth\AuthMechanism;
  10. use OCA\Files_External\Lib\Auth\InvalidAuth;
  11. use OCA\Files_External\Lib\Backend\Backend;
  12. use OCA\Files_External\Lib\Backend\InvalidBackend;
  13. use OCA\Files_External\Lib\DefinitionParameter;
  14. use OCA\Files_External\Lib\StorageConfig;
  15. use OCA\Files_External\NotFoundException;
  16. use OCP\EventDispatcher\IEventDispatcher;
  17. use OCP\Files\Config\IUserMountCache;
  18. use OCP\Files\Events\InvalidateMountCacheEvent;
  19. use OCP\Files\StorageNotAvailableException;
  20. use Psr\Log\LoggerInterface;
  21. /**
  22. * Service class to manage external storage
  23. */
  24. abstract class StoragesService {
  25. /** @var BackendService */
  26. protected $backendService;
  27. /**
  28. * @var DBConfigService
  29. */
  30. protected $dbConfig;
  31. /**
  32. * @var IUserMountCache
  33. */
  34. protected $userMountCache;
  35. protected IEventDispatcher $eventDispatcher;
  36. /**
  37. * @param BackendService $backendService
  38. * @param DBConfigService $dbConfigService
  39. * @param IUserMountCache $userMountCache
  40. * @param IEventDispatcher $eventDispatcher
  41. */
  42. public function __construct(
  43. BackendService $backendService,
  44. DBConfigService $dbConfigService,
  45. IUserMountCache $userMountCache,
  46. IEventDispatcher $eventDispatcher
  47. ) {
  48. $this->backendService = $backendService;
  49. $this->dbConfig = $dbConfigService;
  50. $this->userMountCache = $userMountCache;
  51. $this->eventDispatcher = $eventDispatcher;
  52. }
  53. protected function readDBConfig() {
  54. return $this->dbConfig->getAdminMounts();
  55. }
  56. protected function getStorageConfigFromDBMount(array $mount) {
  57. $applicableUsers = array_filter($mount['applicable'], function ($applicable) {
  58. return $applicable['type'] === DBConfigService::APPLICABLE_TYPE_USER;
  59. });
  60. $applicableUsers = array_map(function ($applicable) {
  61. return $applicable['value'];
  62. }, $applicableUsers);
  63. $applicableGroups = array_filter($mount['applicable'], function ($applicable) {
  64. return $applicable['type'] === DBConfigService::APPLICABLE_TYPE_GROUP;
  65. });
  66. $applicableGroups = array_map(function ($applicable) {
  67. return $applicable['value'];
  68. }, $applicableGroups);
  69. try {
  70. $config = $this->createStorage(
  71. $mount['mount_point'],
  72. $mount['storage_backend'],
  73. $mount['auth_backend'],
  74. $mount['config'],
  75. $mount['options'],
  76. array_values($applicableUsers),
  77. array_values($applicableGroups),
  78. $mount['priority']
  79. );
  80. $config->setType($mount['type']);
  81. $config->setId((int)$mount['mount_id']);
  82. return $config;
  83. } catch (\UnexpectedValueException $e) {
  84. // don't die if a storage backend doesn't exist
  85. \OC::$server->get(LoggerInterface::class)->error('Could not load storage.', [
  86. 'app' => 'files_external',
  87. 'exception' => $e,
  88. ]);
  89. return null;
  90. } catch (\InvalidArgumentException $e) {
  91. \OC::$server->get(LoggerInterface::class)->error('Could not load storage.', [
  92. 'app' => 'files_external',
  93. 'exception' => $e,
  94. ]);
  95. return null;
  96. }
  97. }
  98. /**
  99. * Read the external storage config
  100. *
  101. * @return array map of storage id to storage config
  102. */
  103. protected function readConfig() {
  104. $mounts = $this->readDBConfig();
  105. $configs = array_map([$this, 'getStorageConfigFromDBMount'], $mounts);
  106. $configs = array_filter($configs, function ($config) {
  107. return $config instanceof StorageConfig;
  108. });
  109. $keys = array_map(function (StorageConfig $config) {
  110. return $config->getId();
  111. }, $configs);
  112. return array_combine($keys, $configs);
  113. }
  114. /**
  115. * Get a storage with status
  116. *
  117. * @param int $id storage id
  118. *
  119. * @return StorageConfig
  120. * @throws NotFoundException if the storage with the given id was not found
  121. */
  122. public function getStorage($id) {
  123. $mount = $this->dbConfig->getMountById($id);
  124. if (!is_array($mount)) {
  125. throw new NotFoundException('Storage with ID "' . $id . '" not found');
  126. }
  127. $config = $this->getStorageConfigFromDBMount($mount);
  128. if ($this->isApplicable($config)) {
  129. return $config;
  130. } else {
  131. throw new NotFoundException('Storage with ID "' . $id . '" not found');
  132. }
  133. }
  134. /**
  135. * Check whether this storage service should provide access to a storage
  136. *
  137. * @param StorageConfig $config
  138. * @return bool
  139. */
  140. abstract protected function isApplicable(StorageConfig $config);
  141. /**
  142. * Gets all storages, valid or not
  143. *
  144. * @return StorageConfig[] array of storage configs
  145. */
  146. public function getAllStorages() {
  147. return $this->readConfig();
  148. }
  149. /**
  150. * Gets all valid storages
  151. *
  152. * @return StorageConfig[]
  153. */
  154. public function getStorages() {
  155. return array_filter($this->getAllStorages(), [$this, 'validateStorage']);
  156. }
  157. /**
  158. * Validate storage
  159. * FIXME: De-duplicate with StoragesController::validate()
  160. *
  161. * @param StorageConfig $storage
  162. * @return bool
  163. */
  164. protected function validateStorage(StorageConfig $storage) {
  165. /** @var Backend */
  166. $backend = $storage->getBackend();
  167. /** @var AuthMechanism */
  168. $authMechanism = $storage->getAuthMechanism();
  169. if (!$backend->isVisibleFor($this->getVisibilityType())) {
  170. // not permitted to use backend
  171. return false;
  172. }
  173. if (!$authMechanism->isVisibleFor($this->getVisibilityType())) {
  174. // not permitted to use auth mechanism
  175. return false;
  176. }
  177. return true;
  178. }
  179. /**
  180. * Get the visibility type for this controller, used in validation
  181. *
  182. * @return int BackendService::VISIBILITY_* constants
  183. */
  184. abstract public function getVisibilityType();
  185. /**
  186. * @return integer
  187. */
  188. protected function getType() {
  189. return DBConfigService::MOUNT_TYPE_ADMIN;
  190. }
  191. /**
  192. * Add new storage to the configuration
  193. *
  194. * @param StorageConfig $newStorage storage attributes
  195. *
  196. * @return StorageConfig storage config, with added id
  197. */
  198. public function addStorage(StorageConfig $newStorage) {
  199. $allStorages = $this->readConfig();
  200. $configId = $this->dbConfig->addMount(
  201. $newStorage->getMountPoint(),
  202. $newStorage->getBackend()->getIdentifier(),
  203. $newStorage->getAuthMechanism()->getIdentifier(),
  204. $newStorage->getPriority(),
  205. $this->getType()
  206. );
  207. $newStorage->setId($configId);
  208. foreach ($newStorage->getApplicableUsers() as $user) {
  209. $this->dbConfig->addApplicable($configId, DBConfigService::APPLICABLE_TYPE_USER, $user);
  210. }
  211. foreach ($newStorage->getApplicableGroups() as $group) {
  212. $this->dbConfig->addApplicable($configId, DBConfigService::APPLICABLE_TYPE_GROUP, $group);
  213. }
  214. foreach ($newStorage->getBackendOptions() as $key => $value) {
  215. $this->dbConfig->setConfig($configId, $key, $value);
  216. }
  217. foreach ($newStorage->getMountOptions() as $key => $value) {
  218. $this->dbConfig->setOption($configId, $key, $value);
  219. }
  220. if (count($newStorage->getApplicableUsers()) === 0 && count($newStorage->getApplicableGroups()) === 0) {
  221. $this->dbConfig->addApplicable($configId, DBConfigService::APPLICABLE_TYPE_GLOBAL, null);
  222. }
  223. // add new storage
  224. $allStorages[$configId] = $newStorage;
  225. $this->triggerHooks($newStorage, Filesystem::signal_create_mount);
  226. $newStorage->setStatus(StorageNotAvailableException::STATUS_SUCCESS);
  227. return $newStorage;
  228. }
  229. /**
  230. * Create a storage from its parameters
  231. *
  232. * @param string $mountPoint storage mount point
  233. * @param string $backendIdentifier backend identifier
  234. * @param string $authMechanismIdentifier authentication mechanism identifier
  235. * @param array $backendOptions backend-specific options
  236. * @param array|null $mountOptions mount-specific options
  237. * @param array|null $applicableUsers users for which to mount the storage
  238. * @param array|null $applicableGroups groups for which to mount the storage
  239. * @param int|null $priority priority
  240. *
  241. * @return StorageConfig
  242. */
  243. public function createStorage(
  244. $mountPoint,
  245. $backendIdentifier,
  246. $authMechanismIdentifier,
  247. $backendOptions,
  248. $mountOptions = null,
  249. $applicableUsers = null,
  250. $applicableGroups = null,
  251. $priority = null
  252. ) {
  253. $backend = $this->backendService->getBackend($backendIdentifier);
  254. if (!$backend) {
  255. $backend = new InvalidBackend($backendIdentifier);
  256. }
  257. $authMechanism = $this->backendService->getAuthMechanism($authMechanismIdentifier);
  258. if (!$authMechanism) {
  259. $authMechanism = new InvalidAuth($authMechanismIdentifier);
  260. }
  261. $newStorage = new StorageConfig();
  262. $newStorage->setMountPoint($mountPoint);
  263. $newStorage->setBackend($backend);
  264. $newStorage->setAuthMechanism($authMechanism);
  265. $newStorage->setBackendOptions($backendOptions);
  266. if (isset($mountOptions)) {
  267. $newStorage->setMountOptions($mountOptions);
  268. }
  269. if (isset($applicableUsers)) {
  270. $newStorage->setApplicableUsers($applicableUsers);
  271. }
  272. if (isset($applicableGroups)) {
  273. $newStorage->setApplicableGroups($applicableGroups);
  274. }
  275. if (isset($priority)) {
  276. $newStorage->setPriority($priority);
  277. }
  278. return $newStorage;
  279. }
  280. /**
  281. * Triggers the given hook signal for all the applicables given
  282. *
  283. * @param string $signal signal
  284. * @param string $mountPoint hook mount point param
  285. * @param string $mountType hook mount type param
  286. * @param array $applicableArray array of applicable users/groups for which to trigger the hook
  287. */
  288. protected function triggerApplicableHooks($signal, $mountPoint, $mountType, $applicableArray): void {
  289. $this->eventDispatcher->dispatchTyped(new InvalidateMountCacheEvent(null));
  290. foreach ($applicableArray as $applicable) {
  291. \OCP\Util::emitHook(
  292. Filesystem::CLASSNAME,
  293. $signal,
  294. [
  295. Filesystem::signal_param_path => $mountPoint,
  296. Filesystem::signal_param_mount_type => $mountType,
  297. Filesystem::signal_param_users => $applicable,
  298. ]
  299. );
  300. }
  301. }
  302. /**
  303. * Triggers $signal for all applicable users of the given
  304. * storage
  305. *
  306. * @param StorageConfig $storage storage data
  307. * @param string $signal signal to trigger
  308. */
  309. abstract protected function triggerHooks(StorageConfig $storage, $signal);
  310. /**
  311. * Triggers signal_create_mount or signal_delete_mount to
  312. * accommodate for additions/deletions in applicableUsers
  313. * and applicableGroups fields.
  314. *
  315. * @param StorageConfig $oldStorage old storage data
  316. * @param StorageConfig $newStorage new storage data
  317. */
  318. abstract protected function triggerChangeHooks(StorageConfig $oldStorage, StorageConfig $newStorage);
  319. /**
  320. * Update storage to the configuration
  321. *
  322. * @param StorageConfig $updatedStorage storage attributes
  323. *
  324. * @return StorageConfig storage config
  325. * @throws NotFoundException if the given storage does not exist in the config
  326. */
  327. public function updateStorage(StorageConfig $updatedStorage) {
  328. $id = $updatedStorage->getId();
  329. $existingMount = $this->dbConfig->getMountById($id);
  330. if (!is_array($existingMount)) {
  331. throw new NotFoundException('Storage with ID "' . $id . '" not found while updating storage');
  332. }
  333. $oldStorage = $this->getStorageConfigFromDBMount($existingMount);
  334. if ($oldStorage->getBackend() instanceof InvalidBackend) {
  335. throw new NotFoundException('Storage with id "' . $id . '" cannot be edited due to missing backend');
  336. }
  337. $removedUsers = array_diff($oldStorage->getApplicableUsers(), $updatedStorage->getApplicableUsers());
  338. $removedGroups = array_diff($oldStorage->getApplicableGroups(), $updatedStorage->getApplicableGroups());
  339. $addedUsers = array_diff($updatedStorage->getApplicableUsers(), $oldStorage->getApplicableUsers());
  340. $addedGroups = array_diff($updatedStorage->getApplicableGroups(), $oldStorage->getApplicableGroups());
  341. $oldUserCount = count($oldStorage->getApplicableUsers());
  342. $oldGroupCount = count($oldStorage->getApplicableGroups());
  343. $newUserCount = count($updatedStorage->getApplicableUsers());
  344. $newGroupCount = count($updatedStorage->getApplicableGroups());
  345. $wasGlobal = ($oldUserCount + $oldGroupCount) === 0;
  346. $isGlobal = ($newUserCount + $newGroupCount) === 0;
  347. foreach ($removedUsers as $user) {
  348. $this->dbConfig->removeApplicable($id, DBConfigService::APPLICABLE_TYPE_USER, $user);
  349. }
  350. foreach ($removedGroups as $group) {
  351. $this->dbConfig->removeApplicable($id, DBConfigService::APPLICABLE_TYPE_GROUP, $group);
  352. }
  353. foreach ($addedUsers as $user) {
  354. $this->dbConfig->addApplicable($id, DBConfigService::APPLICABLE_TYPE_USER, $user);
  355. }
  356. foreach ($addedGroups as $group) {
  357. $this->dbConfig->addApplicable($id, DBConfigService::APPLICABLE_TYPE_GROUP, $group);
  358. }
  359. if ($wasGlobal && !$isGlobal) {
  360. $this->dbConfig->removeApplicable($id, DBConfigService::APPLICABLE_TYPE_GLOBAL, null);
  361. } elseif (!$wasGlobal && $isGlobal) {
  362. $this->dbConfig->addApplicable($id, DBConfigService::APPLICABLE_TYPE_GLOBAL, null);
  363. }
  364. $changedConfig = array_diff_assoc($updatedStorage->getBackendOptions(), $oldStorage->getBackendOptions());
  365. $changedOptions = array_diff_assoc($updatedStorage->getMountOptions(), $oldStorage->getMountOptions());
  366. foreach ($changedConfig as $key => $value) {
  367. if ($value !== DefinitionParameter::UNMODIFIED_PLACEHOLDER) {
  368. $this->dbConfig->setConfig($id, $key, $value);
  369. }
  370. }
  371. foreach ($changedOptions as $key => $value) {
  372. $this->dbConfig->setOption($id, $key, $value);
  373. }
  374. if ($updatedStorage->getMountPoint() !== $oldStorage->getMountPoint()) {
  375. $this->dbConfig->setMountPoint($id, $updatedStorage->getMountPoint());
  376. }
  377. if ($updatedStorage->getAuthMechanism()->getIdentifier() !== $oldStorage->getAuthMechanism()->getIdentifier()) {
  378. $this->dbConfig->setAuthBackend($id, $updatedStorage->getAuthMechanism()->getIdentifier());
  379. }
  380. $this->triggerChangeHooks($oldStorage, $updatedStorage);
  381. if (($wasGlobal && !$isGlobal) || count($removedGroups) > 0) { // to expensive to properly handle these on the fly
  382. $this->userMountCache->remoteStorageMounts($this->getStorageId($updatedStorage));
  383. } else {
  384. $storageId = $this->getStorageId($updatedStorage);
  385. foreach ($removedUsers as $userId) {
  386. $this->userMountCache->removeUserStorageMount($storageId, $userId);
  387. }
  388. }
  389. return $this->getStorage($id);
  390. }
  391. /**
  392. * Delete the storage with the given id.
  393. *
  394. * @param int $id storage id
  395. *
  396. * @throws NotFoundException if no storage was found with the given id
  397. */
  398. public function removeStorage($id) {
  399. $existingMount = $this->dbConfig->getMountById($id);
  400. if (!is_array($existingMount)) {
  401. throw new NotFoundException('Storage with ID "' . $id . '" not found');
  402. }
  403. $this->dbConfig->removeMount($id);
  404. $deletedStorage = $this->getStorageConfigFromDBMount($existingMount);
  405. $this->triggerHooks($deletedStorage, Filesystem::signal_delete_mount);
  406. // delete oc_storages entries and oc_filecache
  407. \OC\Files\Cache\Storage::cleanByMountId($id);
  408. }
  409. /**
  410. * Construct the storage implementation
  411. *
  412. * @param StorageConfig $storageConfig
  413. * @return int
  414. */
  415. private function getStorageId(StorageConfig $storageConfig) {
  416. try {
  417. $class = $storageConfig->getBackend()->getStorageClass();
  418. /** @var \OC\Files\Storage\Storage $storage */
  419. $storage = new $class($storageConfig->getBackendOptions());
  420. // auth mechanism should fire first
  421. $storage = $storageConfig->getBackend()->wrapStorage($storage);
  422. $storage = $storageConfig->getAuthMechanism()->wrapStorage($storage);
  423. /** @var \OC\Files\Storage\Storage $storage */
  424. return $storage->getStorageCache()->getNumericId();
  425. } catch (\Exception $e) {
  426. return -1;
  427. }
  428. }
  429. }