ObjectStoreStorage.php 21 KB

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