ObjectStoreStorage.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Joas Schilling <coding@schilljs.com>
  6. * @author Jörn Friedrich Dreyer <jfd@butonic.de>
  7. * @author Morris Jobke <hey@morrisjobke.de>
  8. * @author Robin Appelman <robin@icewind.nl>
  9. *
  10. * @license AGPL-3.0
  11. *
  12. * This code is free software: you can redistribute it and/or modify
  13. * it under the terms of the GNU Affero General Public License, version 3,
  14. * as published by the Free Software Foundation.
  15. *
  16. * This program is distributed in the hope that it will be useful,
  17. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. * GNU Affero General Public License for more details.
  20. *
  21. * You should have received a copy of the GNU Affero General Public License, version 3,
  22. * along with this program. If not, see <http://www.gnu.org/licenses/>
  23. *
  24. */
  25. namespace OC\Files\ObjectStore;
  26. use Icewind\Streams\CallbackWrapper;
  27. use Icewind\Streams\IteratorDirectory;
  28. use OC\Files\Cache\CacheEntry;
  29. use OCP\Files\ObjectStore\IObjectStore;
  30. class ObjectStoreStorage extends \OC\Files\Storage\Common {
  31. /**
  32. * @var \OCP\Files\ObjectStore\IObjectStore $objectStore
  33. */
  34. protected $objectStore;
  35. /**
  36. * @var string $id
  37. */
  38. protected $id;
  39. /**
  40. * @var \OC\User\User $user
  41. */
  42. protected $user;
  43. private $objectPrefix = 'urn:oid:';
  44. private $logger;
  45. public function __construct($params) {
  46. if (isset($params['objectstore']) && $params['objectstore'] instanceof IObjectStore) {
  47. $this->objectStore = $params['objectstore'];
  48. } else {
  49. throw new \Exception('missing IObjectStore instance');
  50. }
  51. if (isset($params['storageid'])) {
  52. $this->id = 'object::store:' . $params['storageid'];
  53. } else {
  54. $this->id = 'object::store:' . $this->objectStore->getStorageId();
  55. }
  56. if (isset($params['objectPrefix'])) {
  57. $this->objectPrefix = $params['objectPrefix'];
  58. }
  59. //initialize cache with root directory in cache
  60. if (!$this->is_dir('/')) {
  61. $this->mkdir('/');
  62. }
  63. $this->logger = \OC::$server->getLogger();
  64. }
  65. public function mkdir($path) {
  66. $path = $this->normalizePath($path);
  67. if ($this->file_exists($path)) {
  68. return false;
  69. }
  70. $mTime = time();
  71. $data = [
  72. 'mimetype' => 'httpd/unix-directory',
  73. 'size' => 0,
  74. 'mtime' => $mTime,
  75. 'storage_mtime' => $mTime,
  76. 'permissions' => \OCP\Constants::PERMISSION_ALL,
  77. ];
  78. if ($path === '') {
  79. //create root on the fly
  80. $data['etag'] = $this->getETag('');
  81. $this->getCache()->put('', $data);
  82. return true;
  83. } else {
  84. // if parent does not exist, create it
  85. $parent = $this->normalizePath(dirname($path));
  86. $parentType = $this->filetype($parent);
  87. if ($parentType === false) {
  88. if (!$this->mkdir($parent)) {
  89. // something went wrong
  90. return false;
  91. }
  92. } else if ($parentType === 'file') {
  93. // parent is a file
  94. return false;
  95. }
  96. // finally create the new dir
  97. $mTime = time(); // update mtime
  98. $data['mtime'] = $mTime;
  99. $data['storage_mtime'] = $mTime;
  100. $data['etag'] = $this->getETag($path);
  101. $this->getCache()->put($path, $data);
  102. return true;
  103. }
  104. }
  105. /**
  106. * @param string $path
  107. * @return string
  108. */
  109. private function normalizePath($path) {
  110. $path = trim($path, '/');
  111. //FIXME why do we sometimes get a path like 'files//username'?
  112. $path = str_replace('//', '/', $path);
  113. // dirname('/folder') returns '.' but internally (in the cache) we store the root as ''
  114. if (!$path || $path === '.') {
  115. $path = '';
  116. }
  117. return $path;
  118. }
  119. /**
  120. * Object Stores use a NoopScanner because metadata is directly stored in
  121. * the file cache and cannot really scan the filesystem. The storage passed in is not used anywhere.
  122. *
  123. * @param string $path
  124. * @param \OC\Files\Storage\Storage (optional) the storage to pass to the scanner
  125. * @return \OC\Files\ObjectStore\NoopScanner
  126. */
  127. public function getScanner($path = '', $storage = null) {
  128. if (!$storage) {
  129. $storage = $this;
  130. }
  131. if (!isset($this->scanner)) {
  132. $this->scanner = new NoopScanner($storage);
  133. }
  134. return $this->scanner;
  135. }
  136. public function getId() {
  137. return $this->id;
  138. }
  139. public function rmdir($path) {
  140. $path = $this->normalizePath($path);
  141. if (!$this->is_dir($path)) {
  142. return false;
  143. }
  144. $this->rmObjects($path);
  145. $this->getCache()->remove($path);
  146. return true;
  147. }
  148. private function rmObjects($path) {
  149. $children = $this->getCache()->getFolderContents($path);
  150. foreach ($children as $child) {
  151. if ($child['mimetype'] === 'httpd/unix-directory') {
  152. $this->rmObjects($child['path']);
  153. } else {
  154. $this->unlink($child['path']);
  155. }
  156. }
  157. }
  158. public function unlink($path) {
  159. $path = $this->normalizePath($path);
  160. $stat = $this->stat($path);
  161. if ($stat && isset($stat['fileid'])) {
  162. if ($stat['mimetype'] === 'httpd/unix-directory') {
  163. return $this->rmdir($path);
  164. }
  165. try {
  166. $this->objectStore->deleteObject($this->getURN($stat['fileid']));
  167. } catch (\Exception $ex) {
  168. if ($ex->getCode() !== 404) {
  169. $this->logger->logException($ex, [
  170. 'app' => 'objectstore',
  171. 'message' => 'Could not delete object ' . $this->getURN($stat['fileid']) . ' for ' . $path,
  172. ]);
  173. return false;
  174. }
  175. //removing from cache is ok as it does not exist in the objectstore anyway
  176. }
  177. $this->getCache()->remove($path);
  178. return true;
  179. }
  180. return false;
  181. }
  182. public function stat($path) {
  183. $path = $this->normalizePath($path);
  184. $cacheEntry = $this->getCache()->get($path);
  185. if ($cacheEntry instanceof CacheEntry) {
  186. return $cacheEntry->getData();
  187. } else {
  188. return false;
  189. }
  190. }
  191. /**
  192. * Override this method if you need a different unique resource identifier for your object storage implementation.
  193. * The default implementations just appends the fileId to 'urn:oid:'. Make sure the URN is unique over all users.
  194. * You may need a mapping table to store your URN if it cannot be generated from the fileid.
  195. *
  196. * @param int $fileId the fileid
  197. * @return null|string the unified resource name used to identify the object
  198. */
  199. protected function getURN($fileId) {
  200. if (is_numeric($fileId)) {
  201. return $this->objectPrefix . $fileId;
  202. }
  203. return null;
  204. }
  205. public function opendir($path) {
  206. $path = $this->normalizePath($path);
  207. try {
  208. $files = array();
  209. $folderContents = $this->getCache()->getFolderContents($path);
  210. foreach ($folderContents as $file) {
  211. $files[] = $file['name'];
  212. }
  213. return IteratorDirectory::wrap($files);
  214. } catch (\Exception $e) {
  215. $this->logger->logException($e);
  216. return false;
  217. }
  218. }
  219. public function filetype($path) {
  220. $path = $this->normalizePath($path);
  221. $stat = $this->stat($path);
  222. if ($stat) {
  223. if ($stat['mimetype'] === 'httpd/unix-directory') {
  224. return 'dir';
  225. }
  226. return 'file';
  227. } else {
  228. return false;
  229. }
  230. }
  231. public function fopen($path, $mode) {
  232. $path = $this->normalizePath($path);
  233. if (strrpos($path, '.') !== false) {
  234. $ext = substr($path, strrpos($path, '.'));
  235. } else {
  236. $ext = '';
  237. }
  238. switch ($mode) {
  239. case 'r':
  240. case 'rb':
  241. $stat = $this->stat($path);
  242. if (is_array($stat)) {
  243. try {
  244. return $this->objectStore->readObject($this->getURN($stat['fileid']));
  245. } catch (\Exception $ex) {
  246. $this->logger->logException($ex, [
  247. 'app' => 'objectstore',
  248. 'message' => 'Count not get object ' . $this->getURN($stat['fileid']) . ' for file ' . $path,
  249. ]);
  250. return false;
  251. }
  252. } else {
  253. return false;
  254. }
  255. case 'w':
  256. case 'wb':
  257. case 'w+':
  258. case 'wb+':
  259. $tmpFile = \OC::$server->getTempManager()->getTemporaryFile($ext);
  260. $handle = fopen($tmpFile, $mode);
  261. return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
  262. $this->writeBack($tmpFile, $path);
  263. });
  264. case 'a':
  265. case 'ab':
  266. case 'r+':
  267. case 'a+':
  268. case 'x':
  269. case 'x+':
  270. case 'c':
  271. case 'c+':
  272. $tmpFile = \OC::$server->getTempManager()->getTemporaryFile($ext);
  273. if ($this->file_exists($path)) {
  274. $source = $this->fopen($path, 'r');
  275. file_put_contents($tmpFile, $source);
  276. }
  277. $handle = fopen($tmpFile, $mode);
  278. return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
  279. $this->writeBack($tmpFile, $path);
  280. });
  281. }
  282. return false;
  283. }
  284. public function file_exists($path) {
  285. $path = $this->normalizePath($path);
  286. return (bool)$this->stat($path);
  287. }
  288. public function rename($source, $target) {
  289. $source = $this->normalizePath($source);
  290. $target = $this->normalizePath($target);
  291. $this->remove($target);
  292. $this->getCache()->move($source, $target);
  293. $this->touch(dirname($target));
  294. return true;
  295. }
  296. public function getMimeType($path) {
  297. $path = $this->normalizePath($path);
  298. $stat = $this->stat($path);
  299. if (is_array($stat)) {
  300. return $stat['mimetype'];
  301. } else {
  302. return false;
  303. }
  304. }
  305. public function touch($path, $mtime = null) {
  306. if (is_null($mtime)) {
  307. $mtime = time();
  308. }
  309. $path = $this->normalizePath($path);
  310. $dirName = dirname($path);
  311. $parentExists = $this->is_dir($dirName);
  312. if (!$parentExists) {
  313. return false;
  314. }
  315. $stat = $this->stat($path);
  316. if (is_array($stat)) {
  317. // update existing mtime in db
  318. $stat['mtime'] = $mtime;
  319. $this->getCache()->update($stat['fileid'], $stat);
  320. } else {
  321. try {
  322. //create a empty file, need to have at least on char to make it
  323. // work with all object storage implementations
  324. $this->file_put_contents($path, ' ');
  325. $mimeType = \OC::$server->getMimeTypeDetector()->detectPath($path);
  326. $stat = array(
  327. 'etag' => $this->getETag($path),
  328. 'mimetype' => $mimeType,
  329. 'size' => 0,
  330. 'mtime' => $mtime,
  331. 'storage_mtime' => $mtime,
  332. 'permissions' => \OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_CREATE,
  333. );
  334. $this->getCache()->put($path, $stat);
  335. } catch (\Exception $ex) {
  336. $this->logger->logException($ex, [
  337. 'app' => 'objectstore',
  338. 'message' => 'Could not create object for ' . $path,
  339. ]);
  340. throw $ex;
  341. }
  342. }
  343. return true;
  344. }
  345. public function writeBack($tmpFile, $path) {
  346. $stat = $this->stat($path);
  347. if (empty($stat)) {
  348. // create new file
  349. $stat = array(
  350. 'permissions' => \OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_CREATE,
  351. );
  352. }
  353. // update stat with new data
  354. $mTime = time();
  355. $stat['size'] = filesize($tmpFile);
  356. $stat['mtime'] = $mTime;
  357. $stat['storage_mtime'] = $mTime;
  358. // run path based detection first, to use file extension because $tmpFile is only a random string
  359. $mimetypeDetector = \OC::$server->getMimeTypeDetector();
  360. $mimetype = $mimetypeDetector->detectPath($path);
  361. if ($mimetype === 'application/octet-stream') {
  362. $mimetype = $mimetypeDetector->detect($tmpFile);
  363. }
  364. $stat['mimetype'] = $mimetype;
  365. $stat['etag'] = $this->getETag($path);
  366. $fileId = $this->getCache()->put($path, $stat);
  367. try {
  368. //upload to object storage
  369. $this->objectStore->writeObject($this->getURN($fileId), fopen($tmpFile, 'r'));
  370. } catch (\Exception $ex) {
  371. $this->getCache()->remove($path);
  372. $this->logger->logException($ex, [
  373. 'app' => 'objectstore',
  374. 'message' => 'Could not create object ' . $this->getURN($fileId) . ' for ' . $path,
  375. ]);
  376. throw $ex; // make this bubble up
  377. }
  378. }
  379. /**
  380. * external changes are not supported, exclusive access to the object storage is assumed
  381. *
  382. * @param string $path
  383. * @param int $time
  384. * @return false
  385. */
  386. public function hasUpdated($path, $time) {
  387. return false;
  388. }
  389. public function needsPartFile() {
  390. return false;
  391. }
  392. }