ObjectStoreStorage.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  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 OC\Files\Stream\CountReadStream;
  30. use OCP\Files\NotFoundException;
  31. use OCP\Files\ObjectStore\IObjectStore;
  32. class ObjectStoreStorage extends \OC\Files\Storage\Common {
  33. /**
  34. * @var \OCP\Files\ObjectStore\IObjectStore $objectStore
  35. */
  36. protected $objectStore;
  37. /**
  38. * @var string $id
  39. */
  40. protected $id;
  41. /**
  42. * @var \OC\User\User $user
  43. */
  44. protected $user;
  45. private $objectPrefix = 'urn:oid:';
  46. private $logger;
  47. public function __construct($params) {
  48. if (isset($params['objectstore']) && $params['objectstore'] instanceof IObjectStore) {
  49. $this->objectStore = $params['objectstore'];
  50. } else {
  51. throw new \Exception('missing IObjectStore instance');
  52. }
  53. if (isset($params['storageid'])) {
  54. $this->id = 'object::store:' . $params['storageid'];
  55. } else {
  56. $this->id = 'object::store:' . $this->objectStore->getStorageId();
  57. }
  58. if (isset($params['objectPrefix'])) {
  59. $this->objectPrefix = $params['objectPrefix'];
  60. }
  61. //initialize cache with root directory in cache
  62. if (!$this->is_dir('/')) {
  63. $this->mkdir('/');
  64. }
  65. $this->logger = \OC::$server->getLogger();
  66. }
  67. public function mkdir($path) {
  68. $path = $this->normalizePath($path);
  69. if ($this->file_exists($path)) {
  70. return false;
  71. }
  72. $mTime = time();
  73. $data = [
  74. 'mimetype' => 'httpd/unix-directory',
  75. 'size' => 0,
  76. 'mtime' => $mTime,
  77. 'storage_mtime' => $mTime,
  78. 'permissions' => \OCP\Constants::PERMISSION_ALL,
  79. ];
  80. if ($path === '') {
  81. //create root on the fly
  82. $data['etag'] = $this->getETag('');
  83. $this->getCache()->put('', $data);
  84. return true;
  85. } else {
  86. // if parent does not exist, create it
  87. $parent = $this->normalizePath(dirname($path));
  88. $parentType = $this->filetype($parent);
  89. if ($parentType === false) {
  90. if (!$this->mkdir($parent)) {
  91. // something went wrong
  92. return false;
  93. }
  94. } else if ($parentType === 'file') {
  95. // parent is a file
  96. return false;
  97. }
  98. // finally create the new dir
  99. $mTime = time(); // update mtime
  100. $data['mtime'] = $mTime;
  101. $data['storage_mtime'] = $mTime;
  102. $data['etag'] = $this->getETag($path);
  103. $this->getCache()->put($path, $data);
  104. return true;
  105. }
  106. }
  107. /**
  108. * @param string $path
  109. * @return string
  110. */
  111. private function normalizePath($path) {
  112. $path = trim($path, '/');
  113. //FIXME why do we sometimes get a path like 'files//username'?
  114. $path = str_replace('//', '/', $path);
  115. // dirname('/folder') returns '.' but internally (in the cache) we store the root as ''
  116. if (!$path || $path === '.') {
  117. $path = '';
  118. }
  119. return $path;
  120. }
  121. /**
  122. * Object Stores use a NoopScanner because metadata is directly stored in
  123. * the file cache and cannot really scan the filesystem. The storage passed in is not used anywhere.
  124. *
  125. * @param string $path
  126. * @param \OC\Files\Storage\Storage (optional) the storage to pass to the scanner
  127. * @return \OC\Files\ObjectStore\NoopScanner
  128. */
  129. public function getScanner($path = '', $storage = null) {
  130. if (!$storage) {
  131. $storage = $this;
  132. }
  133. if (!isset($this->scanner)) {
  134. $this->scanner = new NoopScanner($storage);
  135. }
  136. return $this->scanner;
  137. }
  138. public function getId() {
  139. return $this->id;
  140. }
  141. public function rmdir($path) {
  142. $path = $this->normalizePath($path);
  143. if (!$this->is_dir($path)) {
  144. return false;
  145. }
  146. $this->rmObjects($path);
  147. $this->getCache()->remove($path);
  148. return true;
  149. }
  150. private function rmObjects($path) {
  151. $children = $this->getCache()->getFolderContents($path);
  152. foreach ($children as $child) {
  153. if ($child['mimetype'] === 'httpd/unix-directory') {
  154. $this->rmObjects($child['path']);
  155. } else {
  156. $this->unlink($child['path']);
  157. }
  158. }
  159. }
  160. public function unlink($path) {
  161. $path = $this->normalizePath($path);
  162. $stat = $this->stat($path);
  163. if ($stat && isset($stat['fileid'])) {
  164. if ($stat['mimetype'] === 'httpd/unix-directory') {
  165. return $this->rmdir($path);
  166. }
  167. try {
  168. $this->objectStore->deleteObject($this->getURN($stat['fileid']));
  169. } catch (\Exception $ex) {
  170. if ($ex->getCode() !== 404) {
  171. $this->logger->logException($ex, [
  172. 'app' => 'objectstore',
  173. 'message' => 'Could not delete object ' . $this->getURN($stat['fileid']) . ' for ' . $path,
  174. ]);
  175. return false;
  176. }
  177. //removing from cache is ok as it does not exist in the objectstore anyway
  178. }
  179. $this->getCache()->remove($path);
  180. return true;
  181. }
  182. return false;
  183. }
  184. public function stat($path) {
  185. $path = $this->normalizePath($path);
  186. $cacheEntry = $this->getCache()->get($path);
  187. if ($cacheEntry instanceof CacheEntry) {
  188. return $cacheEntry->getData();
  189. } else {
  190. return false;
  191. }
  192. }
  193. /**
  194. * Override this method if you need a different unique resource identifier for your object storage implementation.
  195. * The default implementations just appends the fileId to 'urn:oid:'. Make sure the URN is unique over all users.
  196. * You may need a mapping table to store your URN if it cannot be generated from the fileid.
  197. *
  198. * @param int $fileId the fileid
  199. * @return null|string the unified resource name used to identify the object
  200. */
  201. protected function getURN($fileId) {
  202. if (is_numeric($fileId)) {
  203. return $this->objectPrefix . $fileId;
  204. }
  205. return null;
  206. }
  207. public function opendir($path) {
  208. $path = $this->normalizePath($path);
  209. try {
  210. $files = array();
  211. $folderContents = $this->getCache()->getFolderContents($path);
  212. foreach ($folderContents as $file) {
  213. $files[] = $file['name'];
  214. }
  215. return IteratorDirectory::wrap($files);
  216. } catch (\Exception $e) {
  217. $this->logger->logException($e);
  218. return false;
  219. }
  220. }
  221. public function filetype($path) {
  222. $path = $this->normalizePath($path);
  223. $stat = $this->stat($path);
  224. if ($stat) {
  225. if ($stat['mimetype'] === 'httpd/unix-directory') {
  226. return 'dir';
  227. }
  228. return 'file';
  229. } else {
  230. return false;
  231. }
  232. }
  233. public function fopen($path, $mode) {
  234. $path = $this->normalizePath($path);
  235. if (strrpos($path, '.') !== false) {
  236. $ext = substr($path, strrpos($path, '.'));
  237. } else {
  238. $ext = '';
  239. }
  240. switch ($mode) {
  241. case 'r':
  242. case 'rb':
  243. $stat = $this->stat($path);
  244. if (is_array($stat)) {
  245. try {
  246. return $this->objectStore->readObject($this->getURN($stat['fileid']));
  247. } catch (NotFoundException $e) {
  248. $this->logger->logException($e, [
  249. 'app' => 'objectstore',
  250. 'message' => 'Could not get object ' . $this->getURN($stat['fileid']) . ' for file ' . $path,
  251. ]);
  252. throw $e;
  253. } catch (\Exception $ex) {
  254. $this->logger->logException($ex, [
  255. 'app' => 'objectstore',
  256. 'message' => 'Could not get object ' . $this->getURN($stat['fileid']) . ' for file ' . $path,
  257. ]);
  258. return false;
  259. }
  260. } else {
  261. return false;
  262. }
  263. case 'w':
  264. case 'wb':
  265. case 'w+':
  266. case 'wb+':
  267. $tmpFile = \OC::$server->getTempManager()->getTemporaryFile($ext);
  268. $handle = fopen($tmpFile, $mode);
  269. return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
  270. $this->writeBack($tmpFile, $path);
  271. });
  272. case 'a':
  273. case 'ab':
  274. case 'r+':
  275. case 'a+':
  276. case 'x':
  277. case 'x+':
  278. case 'c':
  279. case 'c+':
  280. $tmpFile = \OC::$server->getTempManager()->getTemporaryFile($ext);
  281. if ($this->file_exists($path)) {
  282. $source = $this->fopen($path, 'r');
  283. file_put_contents($tmpFile, $source);
  284. }
  285. $handle = fopen($tmpFile, $mode);
  286. return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
  287. $this->writeBack($tmpFile, $path);
  288. });
  289. }
  290. return false;
  291. }
  292. public function file_exists($path) {
  293. $path = $this->normalizePath($path);
  294. return (bool)$this->stat($path);
  295. }
  296. public function rename($source, $target) {
  297. $source = $this->normalizePath($source);
  298. $target = $this->normalizePath($target);
  299. $this->remove($target);
  300. $this->getCache()->move($source, $target);
  301. $this->touch(dirname($target));
  302. return true;
  303. }
  304. public function getMimeType($path) {
  305. $path = $this->normalizePath($path);
  306. $stat = $this->stat($path);
  307. if (is_array($stat)) {
  308. return $stat['mimetype'];
  309. } else {
  310. return false;
  311. }
  312. }
  313. public function touch($path, $mtime = null) {
  314. if (is_null($mtime)) {
  315. $mtime = time();
  316. }
  317. $path = $this->normalizePath($path);
  318. $dirName = dirname($path);
  319. $parentExists = $this->is_dir($dirName);
  320. if (!$parentExists) {
  321. return false;
  322. }
  323. $stat = $this->stat($path);
  324. if (is_array($stat)) {
  325. // update existing mtime in db
  326. $stat['mtime'] = $mtime;
  327. $this->getCache()->update($stat['fileid'], $stat);
  328. } else {
  329. try {
  330. //create a empty file, need to have at least on char to make it
  331. // work with all object storage implementations
  332. $this->file_put_contents($path, ' ');
  333. $mimeType = \OC::$server->getMimeTypeDetector()->detectPath($path);
  334. $stat = array(
  335. 'etag' => $this->getETag($path),
  336. 'mimetype' => $mimeType,
  337. 'size' => 0,
  338. 'mtime' => $mtime,
  339. 'storage_mtime' => $mtime,
  340. 'permissions' => \OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_CREATE,
  341. );
  342. $this->getCache()->put($path, $stat);
  343. } catch (\Exception $ex) {
  344. $this->logger->logException($ex, [
  345. 'app' => 'objectstore',
  346. 'message' => 'Could not create object for ' . $path,
  347. ]);
  348. throw $ex;
  349. }
  350. }
  351. return true;
  352. }
  353. public function writeBack($tmpFile, $path) {
  354. $size = filesize($tmpFile);
  355. $this->writeStream($path, fopen($tmpFile, 'r'), $size);
  356. }
  357. /**
  358. * external changes are not supported, exclusive access to the object storage is assumed
  359. *
  360. * @param string $path
  361. * @param int $time
  362. * @return false
  363. */
  364. public function hasUpdated($path, $time) {
  365. return false;
  366. }
  367. public function needsPartFile() {
  368. return false;
  369. }
  370. public function file_put_contents($path, $data) {
  371. $stream = fopen('php://temp', 'r+');
  372. fwrite($stream, $data);
  373. rewind($stream);
  374. return $this->writeStream($path, $stream, strlen($data)) > 0;
  375. }
  376. public function writeStream(string $path, $stream, int $size = null): int {
  377. $stat = $this->stat($path);
  378. if (empty($stat)) {
  379. // create new file
  380. $stat = [
  381. 'permissions' => \OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_CREATE,
  382. ];
  383. }
  384. // update stat with new data
  385. $mTime = time();
  386. $stat['size'] = (int)$size;
  387. $stat['mtime'] = $mTime;
  388. $stat['storage_mtime'] = $mTime;
  389. $mimetypeDetector = \OC::$server->getMimeTypeDetector();
  390. $mimetype = $mimetypeDetector->detectPath($path);
  391. $stat['mimetype'] = $mimetype;
  392. $stat['etag'] = $this->getETag($path);
  393. $exists = $this->getCache()->inCache($path);
  394. $uploadPath = $exists ? $path : $path . '.part';
  395. $fileId = $this->getCache()->put($uploadPath, $stat);
  396. $urn = $this->getURN($fileId);
  397. try {
  398. //upload to object storage
  399. if ($size === null) {
  400. $countStream = CountReadStream::wrap($stream, function ($writtenSize) use ($fileId, &$size) {
  401. $this->getCache()->update($fileId, [
  402. 'size' => $writtenSize
  403. ]);
  404. $size = $writtenSize;
  405. });
  406. $this->objectStore->writeObject($urn, $countStream);
  407. if (is_resource($countStream)) {
  408. fclose($countStream);
  409. }
  410. } else {
  411. $this->objectStore->writeObject($urn, $stream);
  412. }
  413. } catch (\Exception $ex) {
  414. $this->getCache()->remove($uploadPath);
  415. $this->logger->logException($ex, [
  416. 'app' => 'objectstore',
  417. 'message' => 'Could not create object ' . $urn . ' for ' . $path,
  418. ]);
  419. throw $ex; // make this bubble up
  420. }
  421. if (!$exists) {
  422. if ($this->objectStore->objectExists($urn)) {
  423. $this->getCache()->move($uploadPath, $path);
  424. } else {
  425. $this->getCache()->remove($uploadPath);
  426. throw new \Exception("Object not found after writing (urn: $urn, path: $path)", 404);
  427. }
  428. }
  429. return $size;
  430. }
  431. }