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.

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