ObjectStoreStorage.php 20 KB

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