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.

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