ObjectStoreStorage.php 20 KB

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