StoragesService.php 16 KB

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