StoragesService.php 15 KB

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