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.

367 lines
12 KiB

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