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.

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