ObjectStoreStorage.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2016, ownCloud, Inc.
  4. *
  5. * @author Bjoern Schiessle <bjoern@schiessle.org>
  6. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  7. * @author Joas Schilling <coding@schilljs.com>
  8. * @author Jörn Friedrich Dreyer <jfd@butonic.de>
  9. * @author Marcel Klehr <mklehr@gmx.net>
  10. * @author Morris Jobke <hey@morrisjobke.de>
  11. * @author Robin Appelman <robin@icewind.nl>
  12. * @author Roeland Jago Douma <roeland@famdouma.nl>
  13. * @author Tigran Mkrtchyan <tigran.mkrtchyan@desy.de>
  14. *
  15. * @license AGPL-3.0
  16. *
  17. * This code is free software: you can redistribute it and/or modify
  18. * it under the terms of the GNU Affero General Public License, version 3,
  19. * as published by the Free Software Foundation.
  20. *
  21. * This program is distributed in the hope that it will be useful,
  22. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  23. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  24. * GNU Affero General Public License for more details.
  25. *
  26. * You should have received a copy of the GNU Affero General Public License, version 3,
  27. * along with this program. If not, see <http://www.gnu.org/licenses/>
  28. *
  29. */
  30. namespace OC\Files\ObjectStore;
  31. use Aws\S3\Exception\S3Exception;
  32. use Aws\S3\Exception\S3MultipartUploadException;
  33. use Icewind\Streams\CallbackWrapper;
  34. use Icewind\Streams\CountWrapper;
  35. use Icewind\Streams\IteratorDirectory;
  36. use OC\Files\Cache\Cache;
  37. use OC\Files\Cache\CacheEntry;
  38. use OC\Files\Storage\PolyFill\CopyDirectory;
  39. use OCP\Files\Cache\ICache;
  40. use OCP\Files\Cache\ICacheEntry;
  41. use OCP\Files\FileInfo;
  42. use OCP\Files\GenericFileException;
  43. use OCP\Files\NotFoundException;
  44. use OCP\Files\ObjectStore\IObjectStore;
  45. use OCP\Files\ObjectStore\IObjectStoreMultiPartUpload;
  46. use OCP\Files\Storage\IChunkedFileWrite;
  47. use OCP\Files\Storage\IStorage;
  48. use Psr\Log\LoggerInterface;
  49. class ObjectStoreStorage extends \OC\Files\Storage\Common implements IChunkedFileWrite {
  50. use CopyDirectory;
  51. protected IObjectStore $objectStore;
  52. protected string $id;
  53. private string $objectPrefix = 'urn:oid:';
  54. private LoggerInterface $logger;
  55. private bool $handleCopiesAsOwned;
  56. protected bool $validateWrites = true;
  57. /**
  58. * @param array $params
  59. * @throws \Exception
  60. */
  61. public function __construct($params) {
  62. if (isset($params['objectstore']) && $params['objectstore'] instanceof IObjectStore) {
  63. $this->objectStore = $params['objectstore'];
  64. } else {
  65. throw new \Exception('missing IObjectStore instance');
  66. }
  67. if (isset($params['storageid'])) {
  68. $this->id = 'object::store:' . $params['storageid'];
  69. } else {
  70. $this->id = 'object::store:' . $this->objectStore->getStorageId();
  71. }
  72. if (isset($params['objectPrefix'])) {
  73. $this->objectPrefix = $params['objectPrefix'];
  74. }
  75. if (isset($params['validateWrites'])) {
  76. $this->validateWrites = (bool)$params['validateWrites'];
  77. }
  78. $this->handleCopiesAsOwned = (bool)($params['handleCopiesAsOwned'] ?? false);
  79. $this->logger = \OCP\Server::get(LoggerInterface::class);
  80. }
  81. public function mkdir($path, bool $force = false) {
  82. $path = $this->normalizePath($path);
  83. if (!$force && $this->file_exists($path)) {
  84. $this->logger->warning("Tried to create an object store folder that already exists: $path");
  85. return false;
  86. }
  87. $mTime = time();
  88. $data = [
  89. 'mimetype' => 'httpd/unix-directory',
  90. 'size' => 0,
  91. 'mtime' => $mTime,
  92. 'storage_mtime' => $mTime,
  93. 'permissions' => \OCP\Constants::PERMISSION_ALL,
  94. ];
  95. if ($path === '') {
  96. //create root on the fly
  97. $data['etag'] = $this->getETag('');
  98. $this->getCache()->put('', $data);
  99. return true;
  100. } else {
  101. // if parent does not exist, create it
  102. $parent = $this->normalizePath(dirname($path));
  103. $parentType = $this->filetype($parent);
  104. if ($parentType === false) {
  105. if (!$this->mkdir($parent)) {
  106. // something went wrong
  107. $this->logger->warning("Parent folder ($parent) doesn't exist and couldn't be created");
  108. return false;
  109. }
  110. } elseif ($parentType === 'file') {
  111. // parent is a file
  112. $this->logger->warning("Parent ($parent) is a file");
  113. return false;
  114. }
  115. // finally create the new dir
  116. $mTime = time(); // update mtime
  117. $data['mtime'] = $mTime;
  118. $data['storage_mtime'] = $mTime;
  119. $data['etag'] = $this->getETag($path);
  120. $this->getCache()->put($path, $data);
  121. return true;
  122. }
  123. }
  124. /**
  125. * @param string $path
  126. * @return string
  127. */
  128. private function normalizePath($path) {
  129. $path = trim($path, '/');
  130. //FIXME why do we sometimes get a path like 'files//username'?
  131. $path = str_replace('//', '/', $path);
  132. // dirname('/folder') returns '.' but internally (in the cache) we store the root as ''
  133. if (!$path || $path === '.') {
  134. $path = '';
  135. }
  136. return $path;
  137. }
  138. /**
  139. * Object Stores use a NoopScanner because metadata is directly stored in
  140. * the file cache and cannot really scan the filesystem. The storage passed in is not used anywhere.
  141. *
  142. * @param string $path
  143. * @param \OC\Files\Storage\Storage (optional) the storage to pass to the scanner
  144. * @return \OC\Files\ObjectStore\ObjectStoreScanner
  145. */
  146. public function getScanner($path = '', $storage = null) {
  147. if (!$storage) {
  148. $storage = $this;
  149. }
  150. if (!isset($this->scanner)) {
  151. $this->scanner = new ObjectStoreScanner($storage);
  152. }
  153. return $this->scanner;
  154. }
  155. public function getId() {
  156. return $this->id;
  157. }
  158. public function rmdir($path) {
  159. $path = $this->normalizePath($path);
  160. $entry = $this->getCache()->get($path);
  161. if (!$entry || $entry->getMimeType() !== ICacheEntry::DIRECTORY_MIMETYPE) {
  162. return false;
  163. }
  164. return $this->rmObjects($entry);
  165. }
  166. private function rmObjects(ICacheEntry $entry): bool {
  167. $children = $this->getCache()->getFolderContentsById($entry->getId());
  168. foreach ($children as $child) {
  169. if ($child->getMimeType() === ICacheEntry::DIRECTORY_MIMETYPE) {
  170. if (!$this->rmObjects($child)) {
  171. return false;
  172. }
  173. } else {
  174. if (!$this->rmObject($child)) {
  175. return false;
  176. }
  177. }
  178. }
  179. $this->getCache()->remove($entry->getPath());
  180. return true;
  181. }
  182. public function unlink($path) {
  183. $path = $this->normalizePath($path);
  184. $entry = $this->getCache()->get($path);
  185. if ($entry instanceof ICacheEntry) {
  186. if ($entry->getMimeType() === ICacheEntry::DIRECTORY_MIMETYPE) {
  187. return $this->rmObjects($entry);
  188. } else {
  189. return $this->rmObject($entry);
  190. }
  191. }
  192. return false;
  193. }
  194. public function rmObject(ICacheEntry $entry): bool {
  195. try {
  196. $this->objectStore->deleteObject($this->getURN($entry->getId()));
  197. } catch (\Exception $ex) {
  198. if ($ex->getCode() !== 404) {
  199. $this->logger->error(
  200. 'Could not delete object ' . $this->getURN($entry->getId()) . ' for ' . $entry->getPath(),
  201. [
  202. 'app' => 'objectstore',
  203. 'exception' => $ex,
  204. ]
  205. );
  206. return false;
  207. }
  208. //removing from cache is ok as it does not exist in the objectstore anyway
  209. }
  210. $this->getCache()->remove($entry->getPath());
  211. return true;
  212. }
  213. public function stat($path) {
  214. $path = $this->normalizePath($path);
  215. $cacheEntry = $this->getCache()->get($path);
  216. if ($cacheEntry instanceof CacheEntry) {
  217. return $cacheEntry->getData();
  218. } else {
  219. if ($path === '') {
  220. $this->mkdir('', true);
  221. $cacheEntry = $this->getCache()->get($path);
  222. if ($cacheEntry instanceof CacheEntry) {
  223. return $cacheEntry->getData();
  224. }
  225. }
  226. return false;
  227. }
  228. }
  229. public function getPermissions($path) {
  230. $stat = $this->stat($path);
  231. if (is_array($stat) && isset($stat['permissions'])) {
  232. return $stat['permissions'];
  233. }
  234. return parent::getPermissions($path);
  235. }
  236. /**
  237. * Override this method if you need a different unique resource identifier for your object storage implementation.
  238. * The default implementations just appends the fileId to 'urn:oid:'. Make sure the URN is unique over all users.
  239. * You may need a mapping table to store your URN if it cannot be generated from the fileid.
  240. *
  241. * @param int $fileId the fileid
  242. * @return null|string the unified resource name used to identify the object
  243. */
  244. public function getURN($fileId) {
  245. if (is_numeric($fileId)) {
  246. return $this->objectPrefix . $fileId;
  247. }
  248. return null;
  249. }
  250. public function opendir($path) {
  251. $path = $this->normalizePath($path);
  252. try {
  253. $files = [];
  254. $folderContents = $this->getCache()->getFolderContents($path);
  255. foreach ($folderContents as $file) {
  256. $files[] = $file['name'];
  257. }
  258. return IteratorDirectory::wrap($files);
  259. } catch (\Exception $e) {
  260. $this->logger->error($e->getMessage(), ['exception' => $e]);
  261. return false;
  262. }
  263. }
  264. public function filetype($path) {
  265. $path = $this->normalizePath($path);
  266. $stat = $this->stat($path);
  267. if ($stat) {
  268. if ($stat['mimetype'] === 'httpd/unix-directory') {
  269. return 'dir';
  270. }
  271. return 'file';
  272. } else {
  273. return false;
  274. }
  275. }
  276. public function fopen($path, $mode) {
  277. $path = $this->normalizePath($path);
  278. if (strrpos($path, '.') !== false) {
  279. $ext = substr($path, strrpos($path, '.'));
  280. } else {
  281. $ext = '';
  282. }
  283. switch ($mode) {
  284. case 'r':
  285. case 'rb':
  286. $stat = $this->stat($path);
  287. if (is_array($stat)) {
  288. $filesize = $stat['size'] ?? 0;
  289. // Reading 0 sized files is a waste of time
  290. if ($filesize === 0) {
  291. return fopen('php://memory', $mode);
  292. }
  293. try {
  294. $handle = $this->objectStore->readObject($this->getURN($stat['fileid']));
  295. if ($handle === false) {
  296. return false; // keep backward compatibility
  297. }
  298. $streamStat = fstat($handle);
  299. $actualSize = $streamStat['size'] ?? -1;
  300. if ($actualSize > -1 && $actualSize !== $filesize) {
  301. $this->getCache()->update((int)$stat['fileid'], ['size' => $actualSize]);
  302. }
  303. return $handle;
  304. } catch (NotFoundException $e) {
  305. $this->logger->error(
  306. 'Could not get object ' . $this->getURN($stat['fileid']) . ' for file ' . $path,
  307. [
  308. 'app' => 'objectstore',
  309. 'exception' => $e,
  310. ]
  311. );
  312. throw $e;
  313. } catch (\Exception $e) {
  314. $this->logger->error(
  315. 'Could not get object ' . $this->getURN($stat['fileid']) . ' for file ' . $path,
  316. [
  317. 'app' => 'objectstore',
  318. 'exception' => $e,
  319. ]
  320. );
  321. return false;
  322. }
  323. } else {
  324. return false;
  325. }
  326. // no break
  327. case 'w':
  328. case 'wb':
  329. case 'w+':
  330. case 'wb+':
  331. $dirName = dirname($path);
  332. $parentExists = $this->is_dir($dirName);
  333. if (!$parentExists) {
  334. return false;
  335. }
  336. $tmpFile = \OC::$server->getTempManager()->getTemporaryFile($ext);
  337. $handle = fopen($tmpFile, $mode);
  338. return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
  339. $this->writeBack($tmpFile, $path);
  340. unlink($tmpFile);
  341. });
  342. case 'a':
  343. case 'ab':
  344. case 'r+':
  345. case 'a+':
  346. case 'x':
  347. case 'x+':
  348. case 'c':
  349. case 'c+':
  350. $tmpFile = \OC::$server->getTempManager()->getTemporaryFile($ext);
  351. if ($this->file_exists($path)) {
  352. $source = $this->fopen($path, 'r');
  353. file_put_contents($tmpFile, $source);
  354. }
  355. $handle = fopen($tmpFile, $mode);
  356. return CallbackWrapper::wrap($handle, null, null, function () use ($path, $tmpFile) {
  357. $this->writeBack($tmpFile, $path);
  358. unlink($tmpFile);
  359. });
  360. }
  361. return false;
  362. }
  363. public function file_exists($path) {
  364. $path = $this->normalizePath($path);
  365. return (bool)$this->stat($path);
  366. }
  367. public function rename($source, $target) {
  368. $source = $this->normalizePath($source);
  369. $target = $this->normalizePath($target);
  370. $this->remove($target);
  371. $this->getCache()->move($source, $target);
  372. $this->touch(dirname($target));
  373. return true;
  374. }
  375. public function getMimeType($path) {
  376. $path = $this->normalizePath($path);
  377. return parent::getMimeType($path);
  378. }
  379. public function touch($path, $mtime = null) {
  380. if (is_null($mtime)) {
  381. $mtime = time();
  382. }
  383. $path = $this->normalizePath($path);
  384. $dirName = dirname($path);
  385. $parentExists = $this->is_dir($dirName);
  386. if (!$parentExists) {
  387. return false;
  388. }
  389. $stat = $this->stat($path);
  390. if (is_array($stat)) {
  391. // update existing mtime in db
  392. $stat['mtime'] = $mtime;
  393. $this->getCache()->update($stat['fileid'], $stat);
  394. } else {
  395. try {
  396. //create a empty file, need to have at least on char to make it
  397. // work with all object storage implementations
  398. $this->file_put_contents($path, ' ');
  399. $mimeType = \OC::$server->getMimeTypeDetector()->detectPath($path);
  400. $stat = [
  401. 'etag' => $this->getETag($path),
  402. 'mimetype' => $mimeType,
  403. 'size' => 0,
  404. 'mtime' => $mtime,
  405. 'storage_mtime' => $mtime,
  406. 'permissions' => \OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_CREATE,
  407. ];
  408. $this->getCache()->put($path, $stat);
  409. } catch (\Exception $ex) {
  410. $this->logger->error(
  411. 'Could not create object for ' . $path,
  412. [
  413. 'app' => 'objectstore',
  414. 'exception' => $ex,
  415. ]
  416. );
  417. throw $ex;
  418. }
  419. }
  420. return true;
  421. }
  422. public function writeBack($tmpFile, $path) {
  423. $size = filesize($tmpFile);
  424. $this->writeStream($path, fopen($tmpFile, 'r'), $size);
  425. }
  426. /**
  427. * external changes are not supported, exclusive access to the object storage is assumed
  428. *
  429. * @param string $path
  430. * @param int $time
  431. * @return false
  432. */
  433. public function hasUpdated($path, $time) {
  434. return false;
  435. }
  436. public function needsPartFile() {
  437. return false;
  438. }
  439. public function file_put_contents($path, $data) {
  440. $handle = $this->fopen($path, 'w+');
  441. if (!$handle) {
  442. return false;
  443. }
  444. $result = fwrite($handle, $data);
  445. fclose($handle);
  446. return $result;
  447. }
  448. public function writeStream(string $path, $stream, int $size = null): int {
  449. $stat = $this->stat($path);
  450. if (empty($stat)) {
  451. // create new file
  452. $stat = [
  453. 'permissions' => \OCP\Constants::PERMISSION_ALL - \OCP\Constants::PERMISSION_CREATE,
  454. ];
  455. }
  456. // update stat with new data
  457. $mTime = time();
  458. $stat['size'] = (int)$size;
  459. $stat['mtime'] = $mTime;
  460. $stat['storage_mtime'] = $mTime;
  461. $mimetypeDetector = \OC::$server->getMimeTypeDetector();
  462. $mimetype = $mimetypeDetector->detectPath($path);
  463. $stat['mimetype'] = $mimetype;
  464. $stat['etag'] = $this->getETag($path);
  465. $stat['checksum'] = '';
  466. $exists = $this->getCache()->inCache($path);
  467. $uploadPath = $exists ? $path : $path . '.part';
  468. if ($exists) {
  469. $fileId = $stat['fileid'];
  470. } else {
  471. $fileId = $this->getCache()->put($uploadPath, $stat);
  472. }
  473. $urn = $this->getURN($fileId);
  474. try {
  475. //upload to object storage
  476. if ($size === null) {
  477. $countStream = CountWrapper::wrap($stream, function ($writtenSize) use ($fileId, &$size) {
  478. $this->getCache()->update($fileId, [
  479. 'size' => $writtenSize,
  480. ]);
  481. $size = $writtenSize;
  482. });
  483. $this->objectStore->writeObject($urn, $countStream, $mimetype);
  484. if (is_resource($countStream)) {
  485. fclose($countStream);
  486. }
  487. $stat['size'] = $size;
  488. } else {
  489. $this->objectStore->writeObject($urn, $stream, $mimetype);
  490. if (is_resource($stream)) {
  491. fclose($stream);
  492. }
  493. }
  494. } catch (\Exception $ex) {
  495. if (!$exists) {
  496. /*
  497. * Only remove the entry if we are dealing with a new file.
  498. * Else people lose access to existing files
  499. */
  500. $this->getCache()->remove($uploadPath);
  501. $this->logger->error(
  502. 'Could not create object ' . $urn . ' for ' . $path,
  503. [
  504. 'app' => 'objectstore',
  505. 'exception' => $ex,
  506. ]
  507. );
  508. } else {
  509. $this->logger->error(
  510. 'Could not update object ' . $urn . ' for ' . $path,
  511. [
  512. 'app' => 'objectstore',
  513. 'exception' => $ex,
  514. ]
  515. );
  516. }
  517. throw $ex; // make this bubble up
  518. }
  519. if ($exists) {
  520. // Always update the unencrypted size, for encryption the Encryption wrapper will update this afterwards anyways
  521. $stat['unencrypted_size'] = $stat['size'];
  522. $this->getCache()->update($fileId, $stat);
  523. } else {
  524. if (!$this->validateWrites || $this->objectStore->objectExists($urn)) {
  525. $this->getCache()->move($uploadPath, $path);
  526. } else {
  527. $this->getCache()->remove($uploadPath);
  528. throw new \Exception("Object not found after writing (urn: $urn, path: $path)", 404);
  529. }
  530. }
  531. return $size;
  532. }
  533. public function getObjectStore(): IObjectStore {
  534. return $this->objectStore;
  535. }
  536. public function copyFromStorage(
  537. IStorage $sourceStorage,
  538. $sourceInternalPath,
  539. $targetInternalPath,
  540. $preserveMtime = false
  541. ) {
  542. if ($sourceStorage->instanceOfStorage(ObjectStoreStorage::class)) {
  543. /** @var ObjectStoreStorage $sourceStorage */
  544. if ($sourceStorage->getObjectStore()->getStorageId() === $this->getObjectStore()->getStorageId()) {
  545. /** @var CacheEntry $sourceEntry */
  546. $sourceEntry = $sourceStorage->getCache()->get($sourceInternalPath);
  547. $sourceEntryData = $sourceEntry->getData();
  548. // $sourceEntry['permissions'] here is the permissions from the jailed storage for the current
  549. // user. Instead we use $sourceEntryData['scan_permissions'] that are the permissions from the
  550. // unjailed storage.
  551. if (is_array($sourceEntryData) && array_key_exists('scan_permissions', $sourceEntryData)) {
  552. $sourceEntry['permissions'] = $sourceEntryData['scan_permissions'];
  553. }
  554. $this->copyInner($sourceStorage->getCache(), $sourceEntry, $targetInternalPath);
  555. return true;
  556. }
  557. }
  558. return parent::copyFromStorage($sourceStorage, $sourceInternalPath, $targetInternalPath);
  559. }
  560. public function copy($source, $target) {
  561. $source = $this->normalizePath($source);
  562. $target = $this->normalizePath($target);
  563. $cache = $this->getCache();
  564. $sourceEntry = $cache->get($source);
  565. if (!$sourceEntry) {
  566. throw new NotFoundException('Source object not found');
  567. }
  568. $this->copyInner($cache, $sourceEntry, $target);
  569. return true;
  570. }
  571. private function copyInner(ICache $sourceCache, ICacheEntry $sourceEntry, string $to) {
  572. $cache = $this->getCache();
  573. if ($sourceEntry->getMimeType() === FileInfo::MIMETYPE_FOLDER) {
  574. if ($cache->inCache($to)) {
  575. $cache->remove($to);
  576. }
  577. $this->mkdir($to);
  578. foreach ($sourceCache->getFolderContentsById($sourceEntry->getId()) as $child) {
  579. $this->copyInner($sourceCache, $child, $to . '/' . $child->getName());
  580. }
  581. } else {
  582. $this->copyFile($sourceEntry, $to);
  583. }
  584. }
  585. private function copyFile(ICacheEntry $sourceEntry, string $to) {
  586. $cache = $this->getCache();
  587. $sourceUrn = $this->getURN($sourceEntry->getId());
  588. if (!$cache instanceof Cache) {
  589. throw new \Exception("Invalid source cache for object store copy");
  590. }
  591. $targetId = $cache->copyFromCache($cache, $sourceEntry, $to);
  592. $targetUrn = $this->getURN($targetId);
  593. try {
  594. $this->objectStore->copyObject($sourceUrn, $targetUrn);
  595. if ($this->handleCopiesAsOwned) {
  596. // Copied the file thus we gain all permissions as we are the owner now ! warning while this aligns with local storage it should not be used and instead fix local storage !
  597. $cache->update($targetId, ['permissions' => \OCP\Constants::PERMISSION_ALL]);
  598. }
  599. } catch (\Exception $e) {
  600. $cache->remove($to);
  601. throw $e;
  602. }
  603. }
  604. public function startChunkedWrite(string $targetPath): string {
  605. if (!$this->objectStore instanceof IObjectStoreMultiPartUpload) {
  606. throw new GenericFileException('Object store does not support multipart upload');
  607. }
  608. $cacheEntry = $this->getCache()->get($targetPath);
  609. $urn = $this->getURN($cacheEntry->getId());
  610. return $this->objectStore->initiateMultipartUpload($urn);
  611. }
  612. /**
  613. *
  614. * @throws GenericFileException
  615. */
  616. public function putChunkedWritePart(
  617. string $targetPath,
  618. string $writeToken,
  619. string $chunkId,
  620. $data,
  621. $size = null
  622. ): ?array {
  623. if (!$this->objectStore instanceof IObjectStoreMultiPartUpload) {
  624. throw new GenericFileException('Object store does not support multipart upload');
  625. }
  626. $cacheEntry = $this->getCache()->get($targetPath);
  627. $urn = $this->getURN($cacheEntry->getId());
  628. $result = $this->objectStore->uploadMultipartPart($urn, $writeToken, (int)$chunkId, $data, $size);
  629. $parts[$chunkId] = [
  630. 'PartNumber' => $chunkId,
  631. 'ETag' => trim($result->get('ETag'), '"'),
  632. ];
  633. return $parts[$chunkId];
  634. }
  635. public function completeChunkedWrite(string $targetPath, string $writeToken): int {
  636. if (!$this->objectStore instanceof IObjectStoreMultiPartUpload) {
  637. throw new GenericFileException('Object store does not support multipart upload');
  638. }
  639. $cacheEntry = $this->getCache()->get($targetPath);
  640. $urn = $this->getURN($cacheEntry->getId());
  641. $parts = $this->objectStore->getMultipartUploads($urn, $writeToken);
  642. $sortedParts = array_values($parts);
  643. sort($sortedParts);
  644. try {
  645. $size = $this->objectStore->completeMultipartUpload($urn, $writeToken, $sortedParts);
  646. $stat = $this->stat($targetPath);
  647. $mtime = time();
  648. if (is_array($stat)) {
  649. $stat['size'] = $size;
  650. $stat['mtime'] = $mtime;
  651. $stat['mimetype'] = $this->getMimeType($targetPath);
  652. $this->getCache()->update($stat['fileid'], $stat);
  653. }
  654. } catch (S3MultipartUploadException|S3Exception $e) {
  655. $this->objectStore->abortMultipartUpload($urn, $writeToken);
  656. $this->logger->error(
  657. 'Could not compete multipart upload ' . $urn . ' with uploadId ' . $writeToken,
  658. [
  659. 'app' => 'objectstore',
  660. 'exception' => $e,
  661. ]
  662. );
  663. throw new GenericFileException('Could not write chunked file');
  664. }
  665. return $size;
  666. }
  667. public function cancelChunkedWrite(string $targetPath, string $writeToken): void {
  668. if (!$this->objectStore instanceof IObjectStoreMultiPartUpload) {
  669. throw new GenericFileException('Object store does not support multipart upload');
  670. }
  671. $cacheEntry = $this->getCache()->get($targetPath);
  672. $urn = $this->getURN($cacheEntry->getId());
  673. $this->objectStore->abortMultipartUpload($urn, $writeToken);
  674. }
  675. }