You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

S3ObjectTrait.php 7.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  1. <?php
  2. /**
  3. * @copyright Copyright (c) 2017 Robin Appelman <robin@icewind.nl>
  4. *
  5. * @author Christoph Wurst <christoph@winzerhof-wurst.at>
  6. * @author Florent <florent@coppint.com>
  7. * @author Morris Jobke <hey@morrisjobke.de>
  8. * @author Robin Appelman <robin@icewind.nl>
  9. * @author Roeland Jago Douma <roeland@famdouma.nl>
  10. *
  11. * @license GNU AGPL version 3 or any later version
  12. *
  13. * This program is free software: you can redistribute it and/or modify
  14. * it under the terms of the GNU Affero General Public License as
  15. * published by the Free Software Foundation, either version 3 of the
  16. * License, or (at your option) any later version.
  17. *
  18. * This program is distributed in the hope that it will be useful,
  19. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  20. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  21. * GNU Affero General Public License for more details.
  22. *
  23. * You should have received a copy of the GNU Affero General Public License
  24. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  25. *
  26. */
  27. namespace OC\Files\ObjectStore;
  28. use Aws\S3\Exception\S3MultipartUploadException;
  29. use Aws\S3\MultipartCopy;
  30. use Aws\S3\MultipartUploader;
  31. use Aws\S3\S3Client;
  32. use GuzzleHttp\Psr7;
  33. use GuzzleHttp\Psr7\Utils;
  34. use OC\Files\Stream\SeekableHttpStream;
  35. use Psr\Http\Message\StreamInterface;
  36. trait S3ObjectTrait {
  37. /**
  38. * Returns the connection
  39. *
  40. * @return S3Client connected client
  41. * @throws \Exception if connection could not be made
  42. */
  43. abstract protected function getConnection();
  44. abstract protected function getCertificateBundlePath(): ?string;
  45. abstract protected function getSSECParameters(bool $copy = false): array;
  46. /**
  47. * @param string $urn the unified resource name used to identify the object
  48. *
  49. * @return resource stream with the read data
  50. * @throws \Exception when something goes wrong, message will be logged
  51. * @since 7.0.0
  52. */
  53. public function readObject($urn) {
  54. $fh = SeekableHttpStream::open(function ($range) use ($urn) {
  55. $command = $this->getConnection()->getCommand('GetObject', [
  56. 'Bucket' => $this->bucket,
  57. 'Key' => $urn,
  58. 'Range' => 'bytes=' . $range,
  59. ] + $this->getSSECParameters());
  60. $request = \Aws\serialize($command);
  61. $headers = [];
  62. foreach ($request->getHeaders() as $key => $values) {
  63. foreach ($values as $value) {
  64. $headers[] = "$key: $value";
  65. }
  66. }
  67. $opts = [
  68. 'http' => [
  69. 'protocol_version' => $request->getProtocolVersion(),
  70. 'header' => $headers,
  71. ]
  72. ];
  73. $bundle = $this->getCertificateBundlePath();
  74. if ($bundle) {
  75. $opts['ssl'] = [
  76. 'cafile' => $bundle
  77. ];
  78. }
  79. if ($this->getProxy()) {
  80. $opts['http']['proxy'] = $this->getProxy();
  81. $opts['http']['request_fulluri'] = true;
  82. }
  83. $context = stream_context_create($opts);
  84. return fopen($request->getUri(), 'r', false, $context);
  85. });
  86. if (!$fh) {
  87. throw new \Exception("Failed to read object $urn");
  88. }
  89. return $fh;
  90. }
  91. /**
  92. * Single object put helper
  93. *
  94. * @param string $urn the unified resource name used to identify the object
  95. * @param StreamInterface $stream stream with the data to write
  96. * @param string|null $mimetype the mimetype to set for the remove object @since 22.0.0
  97. * @throws \Exception when something goes wrong, message will be logged
  98. */
  99. protected function writeSingle(string $urn, StreamInterface $stream, string $mimetype = null): void {
  100. $this->getConnection()->putObject([
  101. 'Bucket' => $this->bucket,
  102. 'Key' => $urn,
  103. 'Body' => $stream,
  104. 'ACL' => 'private',
  105. 'ContentType' => $mimetype,
  106. 'StorageClass' => $this->storageClass,
  107. ] + $this->getSSECParameters());
  108. }
  109. /**
  110. * Multipart upload helper that tries to avoid orphaned fragments in S3
  111. *
  112. * @param string $urn the unified resource name used to identify the object
  113. * @param StreamInterface $stream stream with the data to write
  114. * @param string|null $mimetype the mimetype to set for the remove object
  115. * @throws \Exception when something goes wrong, message will be logged
  116. */
  117. protected function writeMultiPart(string $urn, StreamInterface $stream, string $mimetype = null): void {
  118. $uploader = new MultipartUploader($this->getConnection(), $stream, [
  119. 'bucket' => $this->bucket,
  120. 'key' => $urn,
  121. 'part_size' => $this->uploadPartSize,
  122. 'params' => [
  123. 'ContentType' => $mimetype,
  124. 'StorageClass' => $this->storageClass,
  125. ] + $this->getSSECParameters(),
  126. ]);
  127. try {
  128. $uploader->upload();
  129. } catch (S3MultipartUploadException $e) {
  130. // if anything goes wrong with multipart, make sure that you don´t poison and
  131. // slow down s3 bucket with orphaned fragments
  132. $uploadInfo = $e->getState()->getId();
  133. if ($e->getState()->isInitiated() && (array_key_exists('UploadId', $uploadInfo))) {
  134. $this->getConnection()->abortMultipartUpload($uploadInfo);
  135. }
  136. throw new \OCA\DAV\Connector\Sabre\Exception\BadGateway("Error while uploading to S3 bucket", 0, $e);
  137. }
  138. }
  139. /**
  140. * @param string $urn the unified resource name used to identify the object
  141. * @param resource $stream stream with the data to write
  142. * @param string|null $mimetype the mimetype to set for the remove object @since 22.0.0
  143. * @throws \Exception when something goes wrong, message will be logged
  144. * @since 7.0.0
  145. */
  146. public function writeObject($urn, $stream, string $mimetype = null) {
  147. $psrStream = Utils::streamFor($stream);
  148. // ($psrStream->isSeekable() && $psrStream->getSize() !== null) evaluates to true for a On-Seekable stream
  149. // so the optimisation does not apply
  150. $buffer = new Psr7\Stream(fopen("php://memory", 'rwb+'));
  151. Utils::copyToStream($psrStream, $buffer, $this->putSizeLimit);
  152. $buffer->seek(0);
  153. if ($buffer->getSize() < $this->putSizeLimit) {
  154. // buffer is fully seekable, so use it directly for the small upload
  155. $this->writeSingle($urn, $buffer, $mimetype);
  156. } else {
  157. $loadStream = new Psr7\AppendStream([$buffer, $psrStream]);
  158. $this->writeMultiPart($urn, $loadStream, $mimetype);
  159. }
  160. }
  161. /**
  162. * @param string $urn the unified resource name used to identify the object
  163. * @return void
  164. * @throws \Exception when something goes wrong, message will be logged
  165. * @since 7.0.0
  166. */
  167. public function deleteObject($urn) {
  168. $this->getConnection()->deleteObject([
  169. 'Bucket' => $this->bucket,
  170. 'Key' => $urn,
  171. ]);
  172. }
  173. public function objectExists($urn) {
  174. return $this->getConnection()->doesObjectExist($this->bucket, $urn, $this->getSSECParameters());
  175. }
  176. public function copyObject($from, $to, array $options = []) {
  177. $sourceMetadata = $this->getConnection()->headObject([
  178. 'Bucket' => $this->getBucket(),
  179. 'Key' => $from,
  180. ] + $this->getSSECParameters());
  181. $size = (int)($sourceMetadata->get('Size') ?? $sourceMetadata->get('ContentLength'));
  182. if ($this->useMultipartCopy && $size > $this->copySizeLimit) {
  183. $copy = new MultipartCopy($this->getConnection(), [
  184. "source_bucket" => $this->getBucket(),
  185. "source_key" => $from
  186. ], array_merge([
  187. "bucket" => $this->getBucket(),
  188. "key" => $to,
  189. "acl" => "private",
  190. "params" => $this->getSSECParameters() + $this->getSSECParameters(true),
  191. "source_metadata" => $sourceMetadata
  192. ], $options));
  193. $copy->copy();
  194. } else {
  195. $this->getConnection()->copy($this->getBucket(), $from, $this->getBucket(), $to, 'private', array_merge([
  196. 'params' => $this->getSSECParameters() + $this->getSSECParameters(true),
  197. 'mup_threshold' => PHP_INT_MAX,
  198. ], $options));
  199. }
  200. }
  201. }