1
0

S3ObjectTrait.php 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  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. $canSeek = fseek($stream, 0, SEEK_CUR) === 0;
  129. $psrStream = Utils::streamFor($stream);
  130. $size = $psrStream->getSize();
  131. if ($size === null || !$canSeek) {
  132. // The s3 single-part upload requires the size to be known for the stream.
  133. // So for input streams that don't have a known size, we need to copy (part of)
  134. // the input into a temporary stream so the size can be determined
  135. $buffer = new Psr7\Stream(fopen('php://temp', 'rw+'));
  136. Utils::copyToStream($psrStream, $buffer, $this->putSizeLimit);
  137. $buffer->seek(0);
  138. if ($buffer->getSize() < $this->putSizeLimit) {
  139. // buffer is fully seekable, so use it directly for the small upload
  140. $this->writeSingle($urn, $buffer, $mimetype);
  141. } else {
  142. $loadStream = new Psr7\AppendStream([$buffer, $psrStream]);
  143. $this->writeMultiPart($urn, $loadStream, $mimetype);
  144. }
  145. } else {
  146. if ($size < $this->putSizeLimit) {
  147. $this->writeSingle($urn, $psrStream, $mimetype);
  148. } else {
  149. $this->writeMultiPart($urn, $psrStream, $mimetype);
  150. }
  151. }
  152. $psrStream->close();
  153. }
  154. /**
  155. * @param string $urn the unified resource name used to identify the object
  156. * @return void
  157. * @throws \Exception when something goes wrong, message will be logged
  158. * @since 7.0.0
  159. */
  160. public function deleteObject($urn) {
  161. $this->getConnection()->deleteObject([
  162. 'Bucket' => $this->bucket,
  163. 'Key' => $urn,
  164. ]);
  165. }
  166. public function objectExists($urn) {
  167. return $this->getConnection()->doesObjectExist($this->bucket, $urn, $this->getSSECParameters());
  168. }
  169. public function copyObject($from, $to, array $options = []) {
  170. $sourceMetadata = $this->getConnection()->headObject([
  171. 'Bucket' => $this->getBucket(),
  172. 'Key' => $from,
  173. ] + $this->getSSECParameters());
  174. $size = (int)($sourceMetadata->get('Size') ?? $sourceMetadata->get('ContentLength'));
  175. if ($this->useMultipartCopy && $size > $this->copySizeLimit) {
  176. $copy = new MultipartCopy($this->getConnection(), [
  177. 'source_bucket' => $this->getBucket(),
  178. 'source_key' => $from
  179. ], array_merge([
  180. 'bucket' => $this->getBucket(),
  181. 'key' => $to,
  182. 'acl' => 'private',
  183. 'params' => $this->getSSECParameters() + $this->getSSECParameters(true),
  184. 'source_metadata' => $sourceMetadata
  185. ], $options));
  186. $copy->copy();
  187. } else {
  188. $this->getConnection()->copy($this->getBucket(), $from, $this->getBucket(), $to, 'private', array_merge([
  189. 'params' => $this->getSSECParameters() + $this->getSSECParameters(true),
  190. 'mup_threshold' => PHP_INT_MAX,
  191. ], $options));
  192. }
  193. }
  194. }