api-put-object.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  1. /*
  2. * MinIO Go Library for Amazon S3 Compatible Cloud Storage
  3. * Copyright 2015-2017 MinIO, Inc.
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. package minio
  18. import (
  19. "bytes"
  20. "context"
  21. "encoding/base64"
  22. "errors"
  23. "fmt"
  24. "io"
  25. "net/http"
  26. "sort"
  27. "time"
  28. "github.com/minio/minio-go/v7/pkg/encrypt"
  29. "github.com/minio/minio-go/v7/pkg/s3utils"
  30. "golang.org/x/net/http/httpguts"
  31. )
  32. // ReplicationStatus represents replication status of object
  33. type ReplicationStatus string
  34. const (
  35. // ReplicationStatusPending indicates replication is pending
  36. ReplicationStatusPending ReplicationStatus = "PENDING"
  37. // ReplicationStatusComplete indicates replication completed ok
  38. ReplicationStatusComplete ReplicationStatus = "COMPLETE"
  39. // ReplicationStatusFailed indicates replication failed
  40. ReplicationStatusFailed ReplicationStatus = "FAILED"
  41. // ReplicationStatusReplica indicates object is a replica of a source
  42. ReplicationStatusReplica ReplicationStatus = "REPLICA"
  43. )
  44. // Empty returns true if no replication status set.
  45. func (r ReplicationStatus) Empty() bool {
  46. return r == ""
  47. }
  48. // AdvancedPutOptions for internal use - to be utilized by replication, ILM transition
  49. // implementation on MinIO server
  50. type AdvancedPutOptions struct {
  51. SourceVersionID string
  52. SourceETag string
  53. ReplicationStatus ReplicationStatus
  54. SourceMTime time.Time
  55. ReplicationRequest bool
  56. RetentionTimestamp time.Time
  57. TaggingTimestamp time.Time
  58. LegalholdTimestamp time.Time
  59. }
  60. // PutObjectOptions represents options specified by user for PutObject call
  61. type PutObjectOptions struct {
  62. UserMetadata map[string]string
  63. UserTags map[string]string
  64. Progress io.Reader
  65. ContentType string
  66. ContentEncoding string
  67. ContentDisposition string
  68. ContentLanguage string
  69. CacheControl string
  70. Mode RetentionMode
  71. RetainUntilDate time.Time
  72. ServerSideEncryption encrypt.ServerSide
  73. NumThreads uint
  74. StorageClass string
  75. WebsiteRedirectLocation string
  76. PartSize uint64
  77. LegalHold LegalHoldStatus
  78. SendContentMd5 bool
  79. DisableMultipart bool
  80. Internal AdvancedPutOptions
  81. }
  82. // getNumThreads - gets the number of threads to be used in the multipart
  83. // put object operation
  84. func (opts PutObjectOptions) getNumThreads() (numThreads int) {
  85. if opts.NumThreads > 0 {
  86. numThreads = int(opts.NumThreads)
  87. } else {
  88. numThreads = totalWorkers
  89. }
  90. return
  91. }
  92. // Header - constructs the headers from metadata entered by user in
  93. // PutObjectOptions struct
  94. func (opts PutObjectOptions) Header() (header http.Header) {
  95. header = make(http.Header)
  96. contentType := opts.ContentType
  97. if contentType == "" {
  98. contentType = "application/octet-stream"
  99. }
  100. header.Set("Content-Type", contentType)
  101. if opts.ContentEncoding != "" {
  102. header.Set("Content-Encoding", opts.ContentEncoding)
  103. }
  104. if opts.ContentDisposition != "" {
  105. header.Set("Content-Disposition", opts.ContentDisposition)
  106. }
  107. if opts.ContentLanguage != "" {
  108. header.Set("Content-Language", opts.ContentLanguage)
  109. }
  110. if opts.CacheControl != "" {
  111. header.Set("Cache-Control", opts.CacheControl)
  112. }
  113. if opts.Mode != "" {
  114. header.Set(amzLockMode, opts.Mode.String())
  115. }
  116. if !opts.RetainUntilDate.IsZero() {
  117. header.Set("X-Amz-Object-Lock-Retain-Until-Date", opts.RetainUntilDate.Format(time.RFC3339))
  118. }
  119. if opts.LegalHold != "" {
  120. header.Set(amzLegalHoldHeader, opts.LegalHold.String())
  121. }
  122. if opts.ServerSideEncryption != nil {
  123. opts.ServerSideEncryption.Marshal(header)
  124. }
  125. if opts.StorageClass != "" {
  126. header.Set(amzStorageClass, opts.StorageClass)
  127. }
  128. if opts.WebsiteRedirectLocation != "" {
  129. header.Set(amzWebsiteRedirectLocation, opts.WebsiteRedirectLocation)
  130. }
  131. if !opts.Internal.ReplicationStatus.Empty() {
  132. header.Set(amzBucketReplicationStatus, string(opts.Internal.ReplicationStatus))
  133. }
  134. if !opts.Internal.SourceMTime.IsZero() {
  135. header.Set(minIOBucketSourceMTime, opts.Internal.SourceMTime.Format(time.RFC3339Nano))
  136. }
  137. if opts.Internal.SourceETag != "" {
  138. header.Set(minIOBucketSourceETag, opts.Internal.SourceETag)
  139. }
  140. if opts.Internal.ReplicationRequest {
  141. header.Set(minIOBucketReplicationRequest, "")
  142. }
  143. if !opts.Internal.LegalholdTimestamp.IsZero() {
  144. header.Set(minIOBucketReplicationObjectLegalHoldTimestamp, opts.Internal.LegalholdTimestamp.Format(time.RFC3339Nano))
  145. }
  146. if !opts.Internal.RetentionTimestamp.IsZero() {
  147. header.Set(minIOBucketReplicationObjectRetentionTimestamp, opts.Internal.RetentionTimestamp.Format(time.RFC3339Nano))
  148. }
  149. if !opts.Internal.TaggingTimestamp.IsZero() {
  150. header.Set(minIOBucketReplicationTaggingTimestamp, opts.Internal.TaggingTimestamp.Format(time.RFC3339Nano))
  151. }
  152. if len(opts.UserTags) != 0 {
  153. header.Set(amzTaggingHeader, s3utils.TagEncode(opts.UserTags))
  154. }
  155. for k, v := range opts.UserMetadata {
  156. if isAmzHeader(k) || isStandardHeader(k) || isStorageClassHeader(k) {
  157. header.Set(k, v)
  158. } else {
  159. header.Set("x-amz-meta-"+k, v)
  160. }
  161. }
  162. return
  163. }
  164. // validate() checks if the UserMetadata map has standard headers or and raises an error if so.
  165. func (opts PutObjectOptions) validate() (err error) {
  166. for k, v := range opts.UserMetadata {
  167. if !httpguts.ValidHeaderFieldName(k) || isStandardHeader(k) || isSSEHeader(k) || isStorageClassHeader(k) {
  168. return errInvalidArgument(k + " unsupported user defined metadata name")
  169. }
  170. if !httpguts.ValidHeaderFieldValue(v) {
  171. return errInvalidArgument(v + " unsupported user defined metadata value")
  172. }
  173. }
  174. if opts.Mode != "" && !opts.Mode.IsValid() {
  175. return errInvalidArgument(opts.Mode.String() + " unsupported retention mode")
  176. }
  177. if opts.LegalHold != "" && !opts.LegalHold.IsValid() {
  178. return errInvalidArgument(opts.LegalHold.String() + " unsupported legal-hold status")
  179. }
  180. return nil
  181. }
  182. // completedParts is a collection of parts sortable by their part numbers.
  183. // used for sorting the uploaded parts before completing the multipart request.
  184. type completedParts []CompletePart
  185. func (a completedParts) Len() int { return len(a) }
  186. func (a completedParts) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
  187. func (a completedParts) Less(i, j int) bool { return a[i].PartNumber < a[j].PartNumber }
  188. // PutObject creates an object in a bucket.
  189. //
  190. // You must have WRITE permissions on a bucket to create an object.
  191. //
  192. // - For size smaller than 128MiB PutObject automatically does a
  193. // single atomic Put operation.
  194. // - For size larger than 128MiB PutObject automatically does a
  195. // multipart Put operation.
  196. // - For size input as -1 PutObject does a multipart Put operation
  197. // until input stream reaches EOF. Maximum object size that can
  198. // be uploaded through this operation will be 5TiB.
  199. func (c Client) PutObject(ctx context.Context, bucketName, objectName string, reader io.Reader, objectSize int64,
  200. opts PutObjectOptions) (info UploadInfo, err error) {
  201. if objectSize < 0 && opts.DisableMultipart {
  202. return UploadInfo{}, errors.New("object size must be provided with disable multipart upload")
  203. }
  204. err = opts.validate()
  205. if err != nil {
  206. return UploadInfo{}, err
  207. }
  208. return c.putObjectCommon(ctx, bucketName, objectName, reader, objectSize, opts)
  209. }
  210. func (c Client) putObjectCommon(ctx context.Context, bucketName, objectName string, reader io.Reader, size int64, opts PutObjectOptions) (info UploadInfo, err error) {
  211. // Check for largest object size allowed.
  212. if size > int64(maxMultipartPutObjectSize) {
  213. return UploadInfo{}, errEntityTooLarge(size, maxMultipartPutObjectSize, bucketName, objectName)
  214. }
  215. // NOTE: Streaming signature is not supported by GCS.
  216. if s3utils.IsGoogleEndpoint(*c.endpointURL) {
  217. return c.putObject(ctx, bucketName, objectName, reader, size, opts)
  218. }
  219. partSize := opts.PartSize
  220. if opts.PartSize == 0 {
  221. partSize = minPartSize
  222. }
  223. if c.overrideSignerType.IsV2() {
  224. if size >= 0 && size < int64(partSize) || opts.DisableMultipart {
  225. return c.putObject(ctx, bucketName, objectName, reader, size, opts)
  226. }
  227. return c.putObjectMultipart(ctx, bucketName, objectName, reader, size, opts)
  228. }
  229. if size < 0 {
  230. return c.putObjectMultipartStreamNoLength(ctx, bucketName, objectName, reader, opts)
  231. }
  232. if size < int64(partSize) || opts.DisableMultipart {
  233. return c.putObject(ctx, bucketName, objectName, reader, size, opts)
  234. }
  235. return c.putObjectMultipartStream(ctx, bucketName, objectName, reader, size, opts)
  236. }
  237. func (c Client) putObjectMultipartStreamNoLength(ctx context.Context, bucketName, objectName string, reader io.Reader, opts PutObjectOptions) (info UploadInfo, err error) {
  238. // Input validation.
  239. if err = s3utils.CheckValidBucketName(bucketName); err != nil {
  240. return UploadInfo{}, err
  241. }
  242. if err = s3utils.CheckValidObjectName(objectName); err != nil {
  243. return UploadInfo{}, err
  244. }
  245. // Total data read and written to server. should be equal to
  246. // 'size' at the end of the call.
  247. var totalUploadedSize int64
  248. // Complete multipart upload.
  249. var complMultipartUpload completeMultipartUpload
  250. // Calculate the optimal parts info for a given size.
  251. totalPartsCount, partSize, _, err := OptimalPartInfo(-1, opts.PartSize)
  252. if err != nil {
  253. return UploadInfo{}, err
  254. }
  255. // Initiate a new multipart upload.
  256. uploadID, err := c.newUploadID(ctx, bucketName, objectName, opts)
  257. if err != nil {
  258. return UploadInfo{}, err
  259. }
  260. defer func() {
  261. if err != nil {
  262. c.abortMultipartUpload(ctx, bucketName, objectName, uploadID)
  263. }
  264. }()
  265. // Part number always starts with '1'.
  266. partNumber := 1
  267. // Initialize parts uploaded map.
  268. partsInfo := make(map[int]ObjectPart)
  269. // Create a buffer.
  270. buf := make([]byte, partSize)
  271. for partNumber <= totalPartsCount {
  272. length, rerr := readFull(reader, buf)
  273. if rerr == io.EOF && partNumber > 1 {
  274. break
  275. }
  276. if rerr != nil && rerr != io.ErrUnexpectedEOF && rerr != io.EOF {
  277. return UploadInfo{}, rerr
  278. }
  279. var md5Base64 string
  280. if opts.SendContentMd5 {
  281. // Calculate md5sum.
  282. hash := c.md5Hasher()
  283. hash.Write(buf[:length])
  284. md5Base64 = base64.StdEncoding.EncodeToString(hash.Sum(nil))
  285. hash.Close()
  286. }
  287. // Update progress reader appropriately to the latest offset
  288. // as we read from the source.
  289. rd := newHook(bytes.NewReader(buf[:length]), opts.Progress)
  290. // Proceed to upload the part.
  291. objPart, uerr := c.uploadPart(ctx, bucketName, objectName, uploadID, rd, partNumber,
  292. md5Base64, "", int64(length), opts.ServerSideEncryption)
  293. if uerr != nil {
  294. return UploadInfo{}, uerr
  295. }
  296. // Save successfully uploaded part metadata.
  297. partsInfo[partNumber] = objPart
  298. // Save successfully uploaded size.
  299. totalUploadedSize += int64(length)
  300. // Increment part number.
  301. partNumber++
  302. // For unknown size, Read EOF we break away.
  303. // We do not have to upload till totalPartsCount.
  304. if rerr == io.EOF {
  305. break
  306. }
  307. }
  308. // Loop over total uploaded parts to save them in
  309. // Parts array before completing the multipart request.
  310. for i := 1; i < partNumber; i++ {
  311. part, ok := partsInfo[i]
  312. if !ok {
  313. return UploadInfo{}, errInvalidArgument(fmt.Sprintf("Missing part number %d", i))
  314. }
  315. complMultipartUpload.Parts = append(complMultipartUpload.Parts, CompletePart{
  316. ETag: part.ETag,
  317. PartNumber: part.PartNumber,
  318. })
  319. }
  320. // Sort all completed parts.
  321. sort.Sort(completedParts(complMultipartUpload.Parts))
  322. uploadInfo, err := c.completeMultipartUpload(ctx, bucketName, objectName, uploadID, complMultipartUpload, PutObjectOptions{})
  323. if err != nil {
  324. return UploadInfo{}, err
  325. }
  326. uploadInfo.Size = totalUploadedSize
  327. return uploadInfo, nil
  328. }