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.

322 lines
10 KiB

4 years ago
6 years ago
6 years ago
4 years ago
4 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
6 years ago
6 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
  1. package s3api
  2. import (
  3. "encoding/xml"
  4. "fmt"
  5. "github.com/chrislusf/seaweedfs/weed/s3api/s3err"
  6. "path/filepath"
  7. "sort"
  8. "strconv"
  9. "strings"
  10. "time"
  11. "github.com/aws/aws-sdk-go/aws"
  12. "github.com/aws/aws-sdk-go/service/s3"
  13. "github.com/google/uuid"
  14. "github.com/chrislusf/seaweedfs/weed/filer"
  15. "github.com/chrislusf/seaweedfs/weed/glog"
  16. "github.com/chrislusf/seaweedfs/weed/pb/filer_pb"
  17. )
  18. type InitiateMultipartUploadResult struct {
  19. XMLName xml.Name `xml:"http://s3.amazonaws.com/doc/2006-03-01/ InitiateMultipartUploadResult"`
  20. s3.CreateMultipartUploadOutput
  21. }
  22. func (s3a *S3ApiServer) createMultipartUpload(input *s3.CreateMultipartUploadInput) (output *InitiateMultipartUploadResult, code s3err.ErrorCode) {
  23. glog.V(2).Infof("createMultipartUpload input %v", input)
  24. uploadId, _ := uuid.NewRandom()
  25. uploadIdString := uploadId.String()
  26. if err := s3a.mkdir(s3a.genUploadsFolder(*input.Bucket), uploadIdString, func(entry *filer_pb.Entry) {
  27. if entry.Extended == nil {
  28. entry.Extended = make(map[string][]byte)
  29. }
  30. entry.Extended["key"] = []byte(*input.Key)
  31. for k, v := range input.Metadata {
  32. entry.Extended[k] = []byte(*v)
  33. }
  34. if input.ContentType != nil {
  35. entry.Attributes.Mime = *input.ContentType
  36. }
  37. }); err != nil {
  38. glog.Errorf("NewMultipartUpload error: %v", err)
  39. return nil, s3err.ErrInternalError
  40. }
  41. output = &InitiateMultipartUploadResult{
  42. CreateMultipartUploadOutput: s3.CreateMultipartUploadOutput{
  43. Bucket: input.Bucket,
  44. Key: objectKey(input.Key),
  45. UploadId: aws.String(uploadIdString),
  46. },
  47. }
  48. return
  49. }
  50. type CompleteMultipartUploadResult struct {
  51. XMLName xml.Name `xml:"http://s3.amazonaws.com/doc/2006-03-01/ CompleteMultipartUploadResult"`
  52. s3.CompleteMultipartUploadOutput
  53. }
  54. func (s3a *S3ApiServer) completeMultipartUpload(input *s3.CompleteMultipartUploadInput, parts *CompleteMultipartUpload) (output *CompleteMultipartUploadResult, code s3err.ErrorCode) {
  55. glog.V(2).Infof("completeMultipartUpload input %v", input)
  56. completedParts := parts.Parts
  57. sort.Slice(completedParts, func(i, j int) bool {
  58. return completedParts[i].PartNumber < completedParts[j].PartNumber
  59. })
  60. uploadDirectory := s3a.genUploadsFolder(*input.Bucket) + "/" + *input.UploadId
  61. entries, _, err := s3a.list(uploadDirectory, "", "", false, maxPartsList)
  62. if err != nil || len(entries) == 0 {
  63. glog.Errorf("completeMultipartUpload %s %s error: %v, entries:%d", *input.Bucket, *input.UploadId, err, len(entries))
  64. return nil, s3err.ErrNoSuchUpload
  65. }
  66. pentry, err := s3a.getEntry(s3a.genUploadsFolder(*input.Bucket), *input.UploadId)
  67. if err != nil {
  68. glog.Errorf("completeMultipartUpload %s %s error: %v", *input.Bucket, *input.UploadId, err)
  69. return nil, s3err.ErrNoSuchUpload
  70. }
  71. mime := pentry.Attributes.Mime
  72. var finalParts []*filer_pb.FileChunk
  73. var offset int64
  74. for _, entry := range entries {
  75. if strings.HasSuffix(entry.Name, ".part") && !entry.IsDirectory {
  76. _, found := findByPartNumber(entry.Name, completedParts)
  77. if !found {
  78. continue
  79. }
  80. for _, chunk := range entry.Chunks {
  81. p := &filer_pb.FileChunk{
  82. FileId: chunk.GetFileIdString(),
  83. Offset: offset,
  84. Size: chunk.Size,
  85. Mtime: chunk.Mtime,
  86. CipherKey: chunk.CipherKey,
  87. ETag: chunk.ETag,
  88. }
  89. finalParts = append(finalParts, p)
  90. offset += int64(chunk.Size)
  91. }
  92. }
  93. }
  94. entryName := filepath.Base(*input.Key)
  95. dirName := filepath.Dir(*input.Key)
  96. if dirName == "." {
  97. dirName = ""
  98. }
  99. if strings.HasPrefix(dirName, "/") {
  100. dirName = dirName[1:]
  101. }
  102. dirName = fmt.Sprintf("%s/%s/%s", s3a.option.BucketsPath, *input.Bucket, dirName)
  103. // remove suffix '/'
  104. if strings.HasSuffix(dirName, "/") {
  105. dirName = dirName[:len(dirName)-1]
  106. }
  107. err = s3a.mkFile(dirName, entryName, finalParts, func(entry *filer_pb.Entry) {
  108. if entry.Extended == nil {
  109. entry.Extended = make(map[string][]byte)
  110. }
  111. for k, v := range pentry.Extended {
  112. if k != "key" {
  113. entry.Extended[k] = v
  114. }
  115. }
  116. if pentry.Attributes.Mime != "" {
  117. entry.Attributes.Mime = pentry.Attributes.Mime
  118. } else if mime != "" {
  119. entry.Attributes.Mime = mime
  120. }
  121. })
  122. if err != nil {
  123. glog.Errorf("completeMultipartUpload %s/%s error: %v", dirName, entryName, err)
  124. return nil, s3err.ErrInternalError
  125. }
  126. output = &CompleteMultipartUploadResult{
  127. CompleteMultipartUploadOutput: s3.CompleteMultipartUploadOutput{
  128. Location: aws.String(fmt.Sprintf("http://%s%s/%s", s3a.option.Filer.ToHttpAddress(), urlPathEscape(dirName), urlPathEscape(entryName))),
  129. Bucket: input.Bucket,
  130. ETag: aws.String("\"" + filer.ETagChunks(finalParts) + "\""),
  131. Key: objectKey(input.Key),
  132. },
  133. }
  134. if err = s3a.rm(s3a.genUploadsFolder(*input.Bucket), *input.UploadId, false, true); err != nil {
  135. glog.V(1).Infof("completeMultipartUpload cleanup %s upload %s: %v", *input.Bucket, *input.UploadId, err)
  136. }
  137. return
  138. }
  139. func findByPartNumber(fileName string, parts []CompletedPart) (etag string, found bool) {
  140. partNumber, formatErr := strconv.Atoi(fileName[:4])
  141. if formatErr != nil {
  142. return
  143. }
  144. x := sort.Search(len(parts), func(i int) bool {
  145. return parts[i].PartNumber >= partNumber
  146. })
  147. if parts[x].PartNumber != partNumber {
  148. return
  149. }
  150. return parts[x].ETag, true
  151. }
  152. func (s3a *S3ApiServer) abortMultipartUpload(input *s3.AbortMultipartUploadInput) (output *s3.AbortMultipartUploadOutput, code s3err.ErrorCode) {
  153. glog.V(2).Infof("abortMultipartUpload input %v", input)
  154. exists, err := s3a.exists(s3a.genUploadsFolder(*input.Bucket), *input.UploadId, true)
  155. if err != nil {
  156. glog.V(1).Infof("bucket %s abort upload %s: %v", *input.Bucket, *input.UploadId, err)
  157. return nil, s3err.ErrNoSuchUpload
  158. }
  159. if exists {
  160. err = s3a.rm(s3a.genUploadsFolder(*input.Bucket), *input.UploadId, true, true)
  161. }
  162. if err != nil {
  163. glog.V(1).Infof("bucket %s remove upload %s: %v", *input.Bucket, *input.UploadId, err)
  164. return nil, s3err.ErrInternalError
  165. }
  166. return &s3.AbortMultipartUploadOutput{}, s3err.ErrNone
  167. }
  168. type ListMultipartUploadsResult struct {
  169. XMLName xml.Name `xml:"http://s3.amazonaws.com/doc/2006-03-01/ ListMultipartUploadsResult"`
  170. // copied from s3.ListMultipartUploadsOutput, the Uploads is not converting to <Upload></Upload>
  171. Bucket *string `type:"string"`
  172. Delimiter *string `type:"string"`
  173. EncodingType *string `type:"string" enum:"EncodingType"`
  174. IsTruncated *bool `type:"boolean"`
  175. KeyMarker *string `type:"string"`
  176. MaxUploads *int64 `type:"integer"`
  177. NextKeyMarker *string `type:"string"`
  178. NextUploadIdMarker *string `type:"string"`
  179. Prefix *string `type:"string"`
  180. UploadIdMarker *string `type:"string"`
  181. Upload []*s3.MultipartUpload `locationName:"Upload" type:"list" flattened:"true"`
  182. }
  183. func (s3a *S3ApiServer) listMultipartUploads(input *s3.ListMultipartUploadsInput) (output *ListMultipartUploadsResult, code s3err.ErrorCode) {
  184. // https://docs.aws.amazon.com/AmazonS3/latest/API/API_ListMultipartUploads.html
  185. glog.V(2).Infof("listMultipartUploads input %v", input)
  186. output = &ListMultipartUploadsResult{
  187. Bucket: input.Bucket,
  188. Delimiter: input.Delimiter,
  189. EncodingType: input.EncodingType,
  190. KeyMarker: input.KeyMarker,
  191. MaxUploads: input.MaxUploads,
  192. Prefix: input.Prefix,
  193. }
  194. entries, isLast, err := s3a.list(s3a.genUploadsFolder(*input.Bucket), "", *input.UploadIdMarker, false, uint32(*input.MaxUploads))
  195. if err != nil {
  196. glog.Errorf("listMultipartUploads %s error: %v", *input.Bucket, err)
  197. return
  198. }
  199. output.IsTruncated = aws.Bool(!isLast)
  200. for _, entry := range entries {
  201. if entry.Extended != nil {
  202. key := string(entry.Extended["key"])
  203. if *input.KeyMarker != "" && *input.KeyMarker != key {
  204. continue
  205. }
  206. if *input.Prefix != "" && !strings.HasPrefix(key, *input.Prefix) {
  207. continue
  208. }
  209. output.Upload = append(output.Upload, &s3.MultipartUpload{
  210. Key: objectKey(aws.String(key)),
  211. UploadId: aws.String(entry.Name),
  212. })
  213. if !isLast {
  214. output.NextUploadIdMarker = aws.String(entry.Name)
  215. }
  216. }
  217. }
  218. return
  219. }
  220. type ListPartsResult struct {
  221. XMLName xml.Name `xml:"http://s3.amazonaws.com/doc/2006-03-01/ ListPartsResult"`
  222. // copied from s3.ListPartsOutput, the Parts is not converting to <Part></Part>
  223. Bucket *string `type:"string"`
  224. IsTruncated *bool `type:"boolean"`
  225. Key *string `min:"1" type:"string"`
  226. MaxParts *int64 `type:"integer"`
  227. NextPartNumberMarker *int64 `type:"integer"`
  228. PartNumberMarker *int64 `type:"integer"`
  229. Part []*s3.Part `locationName:"Part" type:"list" flattened:"true"`
  230. StorageClass *string `type:"string" enum:"StorageClass"`
  231. UploadId *string `type:"string"`
  232. }
  233. func (s3a *S3ApiServer) listObjectParts(input *s3.ListPartsInput) (output *ListPartsResult, code s3err.ErrorCode) {
  234. // https://docs.aws.amazon.com/AmazonS3/latest/API/API_ListParts.html
  235. glog.V(2).Infof("listObjectParts input %v", input)
  236. output = &ListPartsResult{
  237. Bucket: input.Bucket,
  238. Key: objectKey(input.Key),
  239. UploadId: input.UploadId,
  240. MaxParts: input.MaxParts, // the maximum number of parts to return.
  241. PartNumberMarker: input.PartNumberMarker, // the part number starts after this, exclusive
  242. StorageClass: aws.String("STANDARD"),
  243. }
  244. entries, isLast, err := s3a.list(s3a.genUploadsFolder(*input.Bucket)+"/"+*input.UploadId, "", fmt.Sprintf("%04d.part", *input.PartNumberMarker), false, uint32(*input.MaxParts))
  245. if err != nil {
  246. glog.Errorf("listObjectParts %s %s error: %v", *input.Bucket, *input.UploadId, err)
  247. return nil, s3err.ErrNoSuchUpload
  248. }
  249. // Note: The upload directory is sort of a marker of the existence of an multipart upload request.
  250. // So can not just delete empty upload folders.
  251. output.IsTruncated = aws.Bool(!isLast)
  252. for _, entry := range entries {
  253. if strings.HasSuffix(entry.Name, ".part") && !entry.IsDirectory {
  254. partNumberString := entry.Name[:len(entry.Name)-len(".part")]
  255. partNumber, err := strconv.Atoi(partNumberString)
  256. if err != nil {
  257. glog.Errorf("listObjectParts %s %s parse %s: %v", *input.Bucket, *input.UploadId, entry.Name, err)
  258. continue
  259. }
  260. output.Part = append(output.Part, &s3.Part{
  261. PartNumber: aws.Int64(int64(partNumber)),
  262. LastModified: aws.Time(time.Unix(entry.Attributes.Mtime, 0).UTC()),
  263. Size: aws.Int64(int64(filer.FileSize(entry))),
  264. ETag: aws.String("\"" + filer.ETag(entry) + "\""),
  265. })
  266. if !isLast {
  267. output.NextPartNumberMarker = aws.Int64(int64(partNumber))
  268. }
  269. }
  270. }
  271. return
  272. }