1
0

StoragesService.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518
  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 OCP\ILogger;
  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->getLogger()->logException($e, [
  112. 'message' => 'Could not load storage.',
  113. 'level' => ILogger::ERROR,
  114. 'app' => 'files_external',
  115. ]);
  116. return null;
  117. } catch (\InvalidArgumentException $e) {
  118. \OC::$server->getLogger()->logException($e, [
  119. 'message' => 'Could not load storage.',
  120. 'level' => ILogger::ERROR,
  121. 'app' => 'files_external',
  122. ]);
  123. return null;
  124. }
  125. }
  126. /**
  127. * Read the external storage config
  128. *
  129. * @return array map of storage id to storage config
  130. */
  131. protected function readConfig() {
  132. $mounts = $this->readDBConfig();
  133. $configs = array_map([$this, 'getStorageConfigFromDBMount'], $mounts);
  134. $configs = array_filter($configs, function ($config) {
  135. return $config instanceof StorageConfig;
  136. });
  137. $keys = array_map(function (StorageConfig $config) {
  138. return $config->getId();
  139. }, $configs);
  140. return array_combine($keys, $configs);
  141. }
  142. /**
  143. * Get a storage with status
  144. *
  145. * @param int $id storage id
  146. *
  147. * @return StorageConfig
  148. * @throws NotFoundException if the storage with the given id was not found
  149. */
  150. public function getStorage($id) {
  151. $mount = $this->dbConfig->getMountById($id);
  152. if (!is_array($mount)) {
  153. throw new NotFoundException('Storage with ID "' . $id . '" not found');
  154. }
  155. $config = $this->getStorageConfigFromDBMount($mount);
  156. if ($this->isApplicable($config)) {
  157. return $config;
  158. } else {
  159. throw new NotFoundException('Storage with ID "' . $id . '" not found');
  160. }
  161. }
  162. /**
  163. * Check whether this storage service should provide access to a storage
  164. *
  165. * @param StorageConfig $config
  166. * @return bool
  167. */
  168. abstract protected function isApplicable(StorageConfig $config);
  169. /**
  170. * Gets all storages, valid or not
  171. *
  172. * @return StorageConfig[] array of storage configs
  173. */
  174. public function getAllStorages() {
  175. return $this->readConfig();
  176. }
  177. /**
  178. * Gets all valid storages
  179. *
  180. * @return StorageConfig[]
  181. */
  182. public function getStorages() {
  183. return array_filter($this->getAllStorages(), [$this, 'validateStorage']);
  184. }
  185. /**
  186. * Validate storage
  187. * FIXME: De-duplicate with StoragesController::validate()
  188. *
  189. * @param StorageConfig $storage
  190. * @return bool
  191. */
  192. protected function validateStorage(StorageConfig $storage) {
  193. /** @var Backend */
  194. $backend = $storage->getBackend();
  195. /** @var AuthMechanism */
  196. $authMechanism = $storage->getAuthMechanism();
  197. if (!$backend->isVisibleFor($this->getVisibilityType())) {
  198. // not permitted to use backend
  199. return false;
  200. }
  201. if (!$authMechanism->isVisibleFor($this->getVisibilityType())) {
  202. // not permitted to use auth mechanism
  203. return false;
  204. }
  205. return true;
  206. }
  207. /**
  208. * Get the visibility type for this controller, used in validation
  209. *
  210. * @return string BackendService::VISIBILITY_* constants
  211. */
  212. abstract public function getVisibilityType();
  213. /**
  214. * @return integer
  215. */
  216. protected function getType() {
  217. return DBConfigService::MOUNT_TYPE_ADMIN;
  218. }
  219. /**
  220. * Add new storage to the configuration
  221. *
  222. * @param StorageConfig $newStorage storage attributes
  223. *
  224. * @return StorageConfig storage config, with added id
  225. */
  226. public function addStorage(StorageConfig $newStorage) {
  227. $allStorages = $this->readConfig();
  228. $configId = $this->dbConfig->addMount(
  229. $newStorage->getMountPoint(),
  230. $newStorage->getBackend()->getIdentifier(),
  231. $newStorage->getAuthMechanism()->getIdentifier(),
  232. $newStorage->getPriority(),
  233. $this->getType()
  234. );
  235. $newStorage->setId($configId);
  236. foreach ($newStorage->getApplicableUsers() as $user) {
  237. $this->dbConfig->addApplicable($configId, DBConfigService::APPLICABLE_TYPE_USER, $user);
  238. }
  239. foreach ($newStorage->getApplicableGroups() as $group) {
  240. $this->dbConfig->addApplicable($configId, DBConfigService::APPLICABLE_TYPE_GROUP, $group);
  241. }
  242. foreach ($newStorage->getBackendOptions() as $key => $value) {
  243. $this->dbConfig->setConfig($configId, $key, $value);
  244. }
  245. foreach ($newStorage->getMountOptions() as $key => $value) {
  246. $this->dbConfig->setOption($configId, $key, $value);
  247. }
  248. if (count($newStorage->getApplicableUsers()) === 0 && count($newStorage->getApplicableGroups()) === 0) {
  249. $this->dbConfig->addApplicable($configId, DBConfigService::APPLICABLE_TYPE_GLOBAL, null);
  250. }
  251. // add new storage
  252. $allStorages[$configId] = $newStorage;
  253. $this->triggerHooks($newStorage, Filesystem::signal_create_mount);
  254. $newStorage->setStatus(StorageNotAvailableException::STATUS_SUCCESS);
  255. return $newStorage;
  256. }
  257. /**
  258. * Create a storage from its parameters
  259. *
  260. * @param string $mountPoint storage mount point
  261. * @param string $backendIdentifier backend identifier
  262. * @param string $authMechanismIdentifier authentication mechanism identifier
  263. * @param array $backendOptions backend-specific options
  264. * @param array|null $mountOptions mount-specific options
  265. * @param array|null $applicableUsers users for which to mount the storage
  266. * @param array|null $applicableGroups groups for which to mount the storage
  267. * @param int|null $priority priority
  268. *
  269. * @return StorageConfig
  270. */
  271. public function createStorage(
  272. $mountPoint,
  273. $backendIdentifier,
  274. $authMechanismIdentifier,
  275. $backendOptions,
  276. $mountOptions = null,
  277. $applicableUsers = null,
  278. $applicableGroups = null,
  279. $priority = null
  280. ) {
  281. $backend = $this->backendService->getBackend($backendIdentifier);
  282. if (!$backend) {
  283. $backend = new InvalidBackend($backendIdentifier);
  284. }
  285. $authMechanism = $this->backendService->getAuthMechanism($authMechanismIdentifier);
  286. if (!$authMechanism) {
  287. $authMechanism = new InvalidAuth($authMechanismIdentifier);
  288. }
  289. $newStorage = new StorageConfig();
  290. $newStorage->setMountPoint($mountPoint);
  291. $newStorage->setBackend($backend);
  292. $newStorage->setAuthMechanism($authMechanism);
  293. $newStorage->setBackendOptions($backendOptions);
  294. if (isset($mountOptions)) {
  295. $newStorage->setMountOptions($mountOptions);
  296. }
  297. if (isset($applicableUsers)) {
  298. $newStorage->setApplicableUsers($applicableUsers);
  299. }
  300. if (isset($applicableGroups)) {
  301. $newStorage->setApplicableGroups($applicableGroups);
  302. }
  303. if (isset($priority)) {
  304. $newStorage->setPriority($priority);
  305. }
  306. return $newStorage;
  307. }
  308. /**
  309. * Triggers the given hook signal for all the applicables given
  310. *
  311. * @param string $signal signal
  312. * @param string $mountPoint hook mount point param
  313. * @param string $mountType hook mount type param
  314. * @param array $applicableArray array of applicable users/groups for which to trigger the hook
  315. */
  316. protected function triggerApplicableHooks($signal, $mountPoint, $mountType, $applicableArray): void {
  317. $this->eventDispatcher->dispatchTyped(new InvalidateMountCacheEvent(null));
  318. foreach ($applicableArray as $applicable) {
  319. \OCP\Util::emitHook(
  320. Filesystem::CLASSNAME,
  321. $signal,
  322. [
  323. Filesystem::signal_param_path => $mountPoint,
  324. Filesystem::signal_param_mount_type => $mountType,
  325. Filesystem::signal_param_users => $applicable,
  326. ]
  327. );
  328. }
  329. }
  330. /**
  331. * Triggers $signal for all applicable users of the given
  332. * storage
  333. *
  334. * @param StorageConfig $storage storage data
  335. * @param string $signal signal to trigger
  336. */
  337. abstract protected function triggerHooks(StorageConfig $storage, $signal);
  338. /**
  339. * Triggers signal_create_mount or signal_delete_mount to
  340. * accommodate for additions/deletions in applicableUsers
  341. * and applicableGroups fields.
  342. *
  343. * @param StorageConfig $oldStorage old storage data
  344. * @param StorageConfig $newStorage new storage data
  345. */
  346. abstract protected function triggerChangeHooks(StorageConfig $oldStorage, StorageConfig $newStorage);
  347. /**
  348. * Update storage to the configuration
  349. *
  350. * @param StorageConfig $updatedStorage storage attributes
  351. *
  352. * @return StorageConfig storage config
  353. * @throws NotFoundException if the given storage does not exist in the config
  354. */
  355. public function updateStorage(StorageConfig $updatedStorage) {
  356. $id = $updatedStorage->getId();
  357. $existingMount = $this->dbConfig->getMountById($id);
  358. if (!is_array($existingMount)) {
  359. throw new NotFoundException('Storage with ID "' . $id . '" not found while updating storage');
  360. }
  361. $oldStorage = $this->getStorageConfigFromDBMount($existingMount);
  362. if ($oldStorage->getBackend() instanceof InvalidBackend) {
  363. throw new NotFoundException('Storage with id "' . $id . '" cannot be edited due to missing backend');
  364. }
  365. $removedUsers = array_diff($oldStorage->getApplicableUsers(), $updatedStorage->getApplicableUsers());
  366. $removedGroups = array_diff($oldStorage->getApplicableGroups(), $updatedStorage->getApplicableGroups());
  367. $addedUsers = array_diff($updatedStorage->getApplicableUsers(), $oldStorage->getApplicableUsers());
  368. $addedGroups = array_diff($updatedStorage->getApplicableGroups(), $oldStorage->getApplicableGroups());
  369. $oldUserCount = count($oldStorage->getApplicableUsers());
  370. $oldGroupCount = count($oldStorage->getApplicableGroups());
  371. $newUserCount = count($updatedStorage->getApplicableUsers());
  372. $newGroupCount = count($updatedStorage->getApplicableGroups());
  373. $wasGlobal = ($oldUserCount + $oldGroupCount) === 0;
  374. $isGlobal = ($newUserCount + $newGroupCount) === 0;
  375. foreach ($removedUsers as $user) {
  376. $this->dbConfig->removeApplicable($id, DBConfigService::APPLICABLE_TYPE_USER, $user);
  377. }
  378. foreach ($removedGroups as $group) {
  379. $this->dbConfig->removeApplicable($id, DBConfigService::APPLICABLE_TYPE_GROUP, $group);
  380. }
  381. foreach ($addedUsers as $user) {
  382. $this->dbConfig->addApplicable($id, DBConfigService::APPLICABLE_TYPE_USER, $user);
  383. }
  384. foreach ($addedGroups as $group) {
  385. $this->dbConfig->addApplicable($id, DBConfigService::APPLICABLE_TYPE_GROUP, $group);
  386. }
  387. if ($wasGlobal && !$isGlobal) {
  388. $this->dbConfig->removeApplicable($id, DBConfigService::APPLICABLE_TYPE_GLOBAL, null);
  389. } elseif (!$wasGlobal && $isGlobal) {
  390. $this->dbConfig->addApplicable($id, DBConfigService::APPLICABLE_TYPE_GLOBAL, null);
  391. }
  392. $changedConfig = array_diff_assoc($updatedStorage->getBackendOptions(), $oldStorage->getBackendOptions());
  393. $changedOptions = array_diff_assoc($updatedStorage->getMountOptions(), $oldStorage->getMountOptions());
  394. foreach ($changedConfig as $key => $value) {
  395. if ($value !== DefinitionParameter::UNMODIFIED_PLACEHOLDER) {
  396. $this->dbConfig->setConfig($id, $key, $value);
  397. }
  398. }
  399. foreach ($changedOptions as $key => $value) {
  400. $this->dbConfig->setOption($id, $key, $value);
  401. }
  402. if ($updatedStorage->getMountPoint() !== $oldStorage->getMountPoint()) {
  403. $this->dbConfig->setMountPoint($id, $updatedStorage->getMountPoint());
  404. }
  405. if ($updatedStorage->getAuthMechanism()->getIdentifier() !== $oldStorage->getAuthMechanism()->getIdentifier()) {
  406. $this->dbConfig->setAuthBackend($id, $updatedStorage->getAuthMechanism()->getIdentifier());
  407. }
  408. $this->triggerChangeHooks($oldStorage, $updatedStorage);
  409. if (($wasGlobal && !$isGlobal) || count($removedGroups) > 0) { // to expensive to properly handle these on the fly
  410. $this->userMountCache->remoteStorageMounts($this->getStorageId($updatedStorage));
  411. } else {
  412. $storageId = $this->getStorageId($updatedStorage);
  413. foreach ($removedUsers as $userId) {
  414. $this->userMountCache->removeUserStorageMount($storageId, $userId);
  415. }
  416. }
  417. return $this->getStorage($id);
  418. }
  419. /**
  420. * Delete the storage with the given id.
  421. *
  422. * @param int $id storage id
  423. *
  424. * @throws NotFoundException if no storage was found with the given id
  425. */
  426. public function removeStorage($id) {
  427. $existingMount = $this->dbConfig->getMountById($id);
  428. if (!is_array($existingMount)) {
  429. throw new NotFoundException('Storage with ID "' . $id . '" not found');
  430. }
  431. $this->dbConfig->removeMount($id);
  432. $deletedStorage = $this->getStorageConfigFromDBMount($existingMount);
  433. $this->triggerHooks($deletedStorage, Filesystem::signal_delete_mount);
  434. // delete oc_storages entries and oc_filecache
  435. \OC\Files\Cache\Storage::cleanByMountId($id);
  436. }
  437. /**
  438. * Construct the storage implementation
  439. *
  440. * @param StorageConfig $storageConfig
  441. * @return int
  442. */
  443. private function getStorageId(StorageConfig $storageConfig) {
  444. try {
  445. $class = $storageConfig->getBackend()->getStorageClass();
  446. /** @var \OC\Files\Storage\Storage $storage */
  447. $storage = new $class($storageConfig->getBackendOptions());
  448. // auth mechanism should fire first
  449. $storage = $storageConfig->getBackend()->wrapStorage($storage);
  450. $storage = $storageConfig->getAuthMechanism()->wrapStorage($storage);
  451. return $storage->getStorageCache()->getNumericId();
  452. } catch (\Exception $e) {
  453. return -1;
  454. }
  455. }
  456. }