S3ObjectTrait.php 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2017 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-License-Identifier: AGPL-3.0-or-later
  5. */
  6. namespace OC\Files\ObjectStore;
  7. use Aws\S3\Exception\S3MultipartUploadException;
  8. use Aws\S3\MultipartCopy;
  9. use Aws\S3\MultipartUploader;
  10. use Aws\S3\S3Client;
  11. use GuzzleHttp\Psr7;
  12. use GuzzleHttp\Psr7\Utils;
  13. use OC\Files\Stream\SeekableHttpStream;
  14. use Psr\Http\Message\StreamInterface;
  15. trait S3ObjectTrait {
  16. use S3ConfigTrait;
  17. /**
  18. * Returns the connection
  19. *
  20. * @return S3Client connected client
  21. * @throws \Exception if connection could not be made
  22. */
  23. abstract protected function getConnection();
  24. abstract protected function getCertificateBundlePath(): ?string;
  25. abstract protected function getSSECParameters(bool $copy = false): array;
  26. /**
  27. * @param string $urn the unified resource name used to identify the object
  28. *
  29. * @return resource stream with the read data
  30. * @throws \Exception when something goes wrong, message will be logged
  31. * @since 7.0.0
  32. */
  33. public function readObject($urn) {
  34. $fh = SeekableHttpStream::open(function ($range) use ($urn) {
  35. $command = $this->getConnection()->getCommand('GetObject', [
  36. 'Bucket' => $this->bucket,
  37. 'Key' => $urn,
  38. 'Range' => 'bytes=' . $range,
  39. ] + $this->getSSECParameters());
  40. $request = \Aws\serialize($command);
  41. $headers = [];
  42. foreach ($request->getHeaders() as $key => $values) {
  43. foreach ($values as $value) {
  44. $headers[] = "$key: $value";
  45. }
  46. }
  47. $opts = [
  48. 'http' => [
  49. 'protocol_version' => $request->getProtocolVersion(),
  50. 'header' => $headers,
  51. ]
  52. ];
  53. $bundle = $this->getCertificateBundlePath();
  54. if ($bundle) {
  55. $opts['ssl'] = [
  56. 'cafile' => $bundle
  57. ];
  58. }
  59. if ($this->getProxy()) {
  60. $opts['http']['proxy'] = $this->getProxy();
  61. $opts['http']['request_fulluri'] = true;
  62. }
  63. $context = stream_context_create($opts);
  64. return fopen($request->getUri(), 'r', false, $context);
  65. });
  66. if (!$fh) {
  67. throw new \Exception("Failed to read object $urn");
  68. }
  69. return $fh;
  70. }
  71. /**
  72. * Single object put helper
  73. *
  74. * @param string $urn the unified resource name used to identify the object
  75. * @param StreamInterface $stream stream with the data to write
  76. * @param string|null $mimetype the mimetype to set for the remove object @since 22.0.0
  77. * @throws \Exception when something goes wrong, message will be logged
  78. */
  79. protected function writeSingle(string $urn, StreamInterface $stream, ?string $mimetype = null): void {
  80. $this->getConnection()->putObject([
  81. 'Bucket' => $this->bucket,
  82. 'Key' => $urn,
  83. 'Body' => $stream,
  84. 'ACL' => 'private',
  85. 'ContentType' => $mimetype,
  86. 'StorageClass' => $this->storageClass,
  87. ] + $this->getSSECParameters());
  88. }
  89. /**
  90. * Multipart upload helper that tries to avoid orphaned fragments in S3
  91. *
  92. * @param string $urn the unified resource name used to identify the object
  93. * @param StreamInterface $stream stream with the data to write
  94. * @param string|null $mimetype the mimetype to set for the remove object
  95. * @throws \Exception when something goes wrong, message will be logged
  96. */
  97. protected function writeMultiPart(string $urn, StreamInterface $stream, ?string $mimetype = null): void {
  98. $uploader = new MultipartUploader($this->getConnection(), $stream, [
  99. 'bucket' => $this->bucket,
  100. 'concurrency' => $this->concurrency,
  101. 'key' => $urn,
  102. 'part_size' => $this->uploadPartSize,
  103. 'params' => [
  104. 'ContentType' => $mimetype,
  105. 'StorageClass' => $this->storageClass,
  106. ] + $this->getSSECParameters(),
  107. ]);
  108. try {
  109. $uploader->upload();
  110. } catch (S3MultipartUploadException $e) {
  111. // if anything goes wrong with multipart, make sure that you don´t poison and
  112. // slow down s3 bucket with orphaned fragments
  113. $uploadInfo = $e->getState()->getId();
  114. if ($e->getState()->isInitiated() && (array_key_exists('UploadId', $uploadInfo))) {
  115. $this->getConnection()->abortMultipartUpload($uploadInfo);
  116. }
  117. throw new \OCA\DAV\Connector\Sabre\Exception\BadGateway('Error while uploading to S3 bucket', 0, $e);
  118. }
  119. }
  120. /**
  121. * @param string $urn the unified resource name used to identify the object
  122. * @param resource $stream stream with the data to write
  123. * @param string|null $mimetype the mimetype to set for the remove object @since 22.0.0
  124. * @throws \Exception when something goes wrong, message will be logged
  125. * @since 7.0.0
  126. */
  127. public function writeObject($urn, $stream, ?string $mimetype = null) {
  128. $psrStream = Utils::streamFor($stream);
  129. // ($psrStream->isSeekable() && $psrStream->getSize() !== null) evaluates to true for a On-Seekable stream
  130. // so the optimisation does not apply
  131. $buffer = new Psr7\Stream(fopen('php://memory', 'rwb+'));
  132. Utils::copyToStream($psrStream, $buffer, $this->putSizeLimit);
  133. $buffer->seek(0);
  134. if ($buffer->getSize() < $this->putSizeLimit) {
  135. // buffer is fully seekable, so use it directly for the small upload
  136. $this->writeSingle($urn, $buffer, $mimetype);
  137. } else {
  138. $loadStream = new Psr7\AppendStream([$buffer, $psrStream]);
  139. $this->writeMultiPart($urn, $loadStream, $mimetype);
  140. }
  141. }
  142. /**
  143. * @param string $urn the unified resource name used to identify the object
  144. * @return void
  145. * @throws \Exception when something goes wrong, message will be logged
  146. * @since 7.0.0
  147. */
  148. public function deleteObject($urn) {
  149. $this->getConnection()->deleteObject([
  150. 'Bucket' => $this->bucket,
  151. 'Key' => $urn,
  152. ]);
  153. }
  154. public function objectExists($urn) {
  155. return $this->getConnection()->doesObjectExist($this->bucket, $urn, $this->getSSECParameters());
  156. }
  157. public function copyObject($from, $to, array $options = []) {
  158. $sourceMetadata = $this->getConnection()->headObject([
  159. 'Bucket' => $this->getBucket(),
  160. 'Key' => $from,
  161. ] + $this->getSSECParameters());
  162. $size = (int)($sourceMetadata->get('Size') ?? $sourceMetadata->get('ContentLength'));
  163. if ($this->useMultipartCopy && $size > $this->copySizeLimit) {
  164. $copy = new MultipartCopy($this->getConnection(), [
  165. 'source_bucket' => $this->getBucket(),
  166. 'source_key' => $from
  167. ], array_merge([
  168. 'bucket' => $this->getBucket(),
  169. 'key' => $to,
  170. 'acl' => 'private',
  171. 'params' => $this->getSSECParameters() + $this->getSSECParameters(true),
  172. 'source_metadata' => $sourceMetadata
  173. ], $options));
  174. $copy->copy();
  175. } else {
  176. $this->getConnection()->copy($this->getBucket(), $from, $this->getBucket(), $to, 'private', array_merge([
  177. 'params' => $this->getSSECParameters() + $this->getSSECParameters(true),
  178. 'mup_threshold' => PHP_INT_MAX,
  179. ], $options));
  180. }
  181. }
  182. }