S3ObjectTrait.php 6.4 KB

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