1
0

S3ObjectTrait.php 7.4 KB

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