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.

344 lines
11 KiB

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/seaweedfs/seaweedfs/weed/s3api/s3err"
  7. "golang.org/x/exp/slices"
  8. "math"
  9. "path/filepath"
  10. "sort"
  11. "strconv"
  12. "strings"
  13. "time"
  14. "github.com/aws/aws-sdk-go/aws"
  15. "github.com/aws/aws-sdk-go/service/s3"
  16. "github.com/seaweedfs/seaweedfs/weed/filer"
  17. "github.com/seaweedfs/seaweedfs/weed/glog"
  18. "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
  19. )
  20. type InitiateMultipartUploadResult struct {
  21. XMLName xml.Name `xml:"http://s3.amazonaws.com/doc/2006-03-01/ InitiateMultipartUploadResult"`
  22. s3.CreateMultipartUploadOutput
  23. }
  24. func (s3a *S3ApiServer) createMultipartUpload(input *s3.CreateMultipartUploadInput) (output *InitiateMultipartUploadResult, code s3err.ErrorCode) {
  25. glog.V(2).Infof("createMultipartUpload input %v", input)
  26. uploadIdString := s3a.generateUploadID(*input.Key)
  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. slices.SortFunc(completedParts, func(a, b CompletedPart) bool {
  59. return a.PartNumber < b.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. entry.Attributes.FileSize = uint64(offset)
  128. })
  129. if err != nil {
  130. glog.Errorf("completeMultipartUpload %s/%s error: %v", dirName, entryName, err)
  131. return nil, s3err.ErrInternalError
  132. }
  133. output = &CompleteMultipartUploadResult{
  134. CompleteMultipartUploadOutput: s3.CompleteMultipartUploadOutput{
  135. Location: aws.String(fmt.Sprintf("http://%s%s/%s", s3a.option.Filer.ToHttpAddress(), urlPathEscape(dirName), urlPathEscape(entryName))),
  136. Bucket: input.Bucket,
  137. ETag: aws.String("\"" + filer.ETagChunks(finalParts) + "\""),
  138. Key: objectKey(input.Key),
  139. },
  140. }
  141. if err = s3a.rm(s3a.genUploadsFolder(*input.Bucket), *input.UploadId, false, true); err != nil {
  142. glog.V(1).Infof("completeMultipartUpload cleanup %s upload %s: %v", *input.Bucket, *input.UploadId, err)
  143. }
  144. return
  145. }
  146. func findByPartNumber(fileName string, parts []CompletedPart) (etag string, found bool) {
  147. partNumber, formatErr := strconv.Atoi(fileName[:4])
  148. if formatErr != nil {
  149. return
  150. }
  151. x := sort.Search(len(parts), func(i int) bool {
  152. return parts[i].PartNumber >= partNumber
  153. })
  154. if x >= len(parts) {
  155. return
  156. }
  157. if parts[x].PartNumber != partNumber {
  158. return
  159. }
  160. y := 0
  161. for i, part := range parts[x:] {
  162. if part.PartNumber == partNumber {
  163. y = i
  164. } else {
  165. break
  166. }
  167. }
  168. return parts[x+y].ETag, true
  169. }
  170. func (s3a *S3ApiServer) abortMultipartUpload(input *s3.AbortMultipartUploadInput) (output *s3.AbortMultipartUploadOutput, code s3err.ErrorCode) {
  171. glog.V(2).Infof("abortMultipartUpload input %v", input)
  172. exists, err := s3a.exists(s3a.genUploadsFolder(*input.Bucket), *input.UploadId, true)
  173. if err != nil {
  174. glog.V(1).Infof("bucket %s abort upload %s: %v", *input.Bucket, *input.UploadId, err)
  175. return nil, s3err.ErrNoSuchUpload
  176. }
  177. if exists {
  178. err = s3a.rm(s3a.genUploadsFolder(*input.Bucket), *input.UploadId, true, true)
  179. }
  180. if err != nil {
  181. glog.V(1).Infof("bucket %s remove upload %s: %v", *input.Bucket, *input.UploadId, err)
  182. return nil, s3err.ErrInternalError
  183. }
  184. return &s3.AbortMultipartUploadOutput{}, s3err.ErrNone
  185. }
  186. type ListMultipartUploadsResult struct {
  187. XMLName xml.Name `xml:"http://s3.amazonaws.com/doc/2006-03-01/ ListMultipartUploadsResult"`
  188. // copied from s3.ListMultipartUploadsOutput, the Uploads is not converting to <Upload></Upload>
  189. Bucket *string `type:"string"`
  190. Delimiter *string `type:"string"`
  191. EncodingType *string `type:"string" enum:"EncodingType"`
  192. IsTruncated *bool `type:"boolean"`
  193. KeyMarker *string `type:"string"`
  194. MaxUploads *int64 `type:"integer"`
  195. NextKeyMarker *string `type:"string"`
  196. NextUploadIdMarker *string `type:"string"`
  197. Prefix *string `type:"string"`
  198. UploadIdMarker *string `type:"string"`
  199. Upload []*s3.MultipartUpload `locationName:"Upload" type:"list" flattened:"true"`
  200. }
  201. func (s3a *S3ApiServer) listMultipartUploads(input *s3.ListMultipartUploadsInput) (output *ListMultipartUploadsResult, code s3err.ErrorCode) {
  202. // https://docs.aws.amazon.com/AmazonS3/latest/API/API_ListMultipartUploads.html
  203. glog.V(2).Infof("listMultipartUploads input %v", input)
  204. output = &ListMultipartUploadsResult{
  205. Bucket: input.Bucket,
  206. Delimiter: input.Delimiter,
  207. EncodingType: input.EncodingType,
  208. KeyMarker: input.KeyMarker,
  209. MaxUploads: input.MaxUploads,
  210. Prefix: input.Prefix,
  211. IsTruncated: aws.Bool(false),
  212. }
  213. entries, _, err := s3a.list(s3a.genUploadsFolder(*input.Bucket), "", *input.UploadIdMarker, false, math.MaxInt32)
  214. if err != nil {
  215. glog.Errorf("listMultipartUploads %s error: %v", *input.Bucket, err)
  216. return
  217. }
  218. uploadsCount := int64(0)
  219. for _, entry := range entries {
  220. if entry.Extended != nil {
  221. key := string(entry.Extended["key"])
  222. if *input.KeyMarker != "" && *input.KeyMarker != key {
  223. continue
  224. }
  225. if *input.Prefix != "" && !strings.HasPrefix(key, *input.Prefix) {
  226. continue
  227. }
  228. output.Upload = append(output.Upload, &s3.MultipartUpload{
  229. Key: objectKey(aws.String(key)),
  230. UploadId: aws.String(entry.Name),
  231. })
  232. uploadsCount += 1
  233. }
  234. if uploadsCount >= *input.MaxUploads {
  235. output.IsTruncated = aws.Bool(true)
  236. output.NextUploadIdMarker = aws.String(entry.Name)
  237. break
  238. }
  239. }
  240. return
  241. }
  242. type ListPartsResult struct {
  243. XMLName xml.Name `xml:"http://s3.amazonaws.com/doc/2006-03-01/ ListPartsResult"`
  244. // copied from s3.ListPartsOutput, the Parts is not converting to <Part></Part>
  245. Bucket *string `type:"string"`
  246. IsTruncated *bool `type:"boolean"`
  247. Key *string `min:"1" type:"string"`
  248. MaxParts *int64 `type:"integer"`
  249. NextPartNumberMarker *int64 `type:"integer"`
  250. PartNumberMarker *int64 `type:"integer"`
  251. Part []*s3.Part `locationName:"Part" type:"list" flattened:"true"`
  252. StorageClass *string `type:"string" enum:"StorageClass"`
  253. UploadId *string `type:"string"`
  254. }
  255. func (s3a *S3ApiServer) listObjectParts(input *s3.ListPartsInput) (output *ListPartsResult, code s3err.ErrorCode) {
  256. // https://docs.aws.amazon.com/AmazonS3/latest/API/API_ListParts.html
  257. glog.V(2).Infof("listObjectParts input %v", input)
  258. output = &ListPartsResult{
  259. Bucket: input.Bucket,
  260. Key: objectKey(input.Key),
  261. UploadId: input.UploadId,
  262. MaxParts: input.MaxParts, // the maximum number of parts to return.
  263. PartNumberMarker: input.PartNumberMarker, // the part number starts after this, exclusive
  264. StorageClass: aws.String("STANDARD"),
  265. }
  266. entries, isLast, err := s3a.list(s3a.genUploadsFolder(*input.Bucket)+"/"+*input.UploadId, "", fmt.Sprintf("%04d.part", *input.PartNumberMarker), false, uint32(*input.MaxParts))
  267. if err != nil {
  268. glog.Errorf("listObjectParts %s %s error: %v", *input.Bucket, *input.UploadId, err)
  269. return nil, s3err.ErrNoSuchUpload
  270. }
  271. // Note: The upload directory is sort of a marker of the existence of an multipart upload request.
  272. // So can not just delete empty upload folders.
  273. output.IsTruncated = aws.Bool(!isLast)
  274. for _, entry := range entries {
  275. if strings.HasSuffix(entry.Name, ".part") && !entry.IsDirectory {
  276. partNumberString := entry.Name[:len(entry.Name)-len(".part")]
  277. partNumber, err := strconv.Atoi(partNumberString)
  278. if err != nil {
  279. glog.Errorf("listObjectParts %s %s parse %s: %v", *input.Bucket, *input.UploadId, entry.Name, err)
  280. continue
  281. }
  282. output.Part = append(output.Part, &s3.Part{
  283. PartNumber: aws.Int64(int64(partNumber)),
  284. LastModified: aws.Time(time.Unix(entry.Attributes.Mtime, 0).UTC()),
  285. Size: aws.Int64(int64(filer.FileSize(entry))),
  286. ETag: aws.String("\"" + filer.ETag(entry) + "\""),
  287. })
  288. if !isLast {
  289. output.NextPartNumberMarker = aws.Int64(int64(partNumber))
  290. }
  291. }
  292. }
  293. return
  294. }