StoragesService.php 17 KB

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