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.

342 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. "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/chrislusf/seaweedfs/weed/filer"
  17. "github.com/chrislusf/seaweedfs/weed/glog"
  18. "github.com/chrislusf/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. })
  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 x >= len(parts) {
  154. return
  155. }
  156. if parts[x].PartNumber != partNumber {
  157. return
  158. }
  159. y := 0
  160. for i, part := range parts[x:] {
  161. if part.PartNumber == partNumber {
  162. y = i
  163. } else {
  164. break
  165. }
  166. }
  167. return parts[x+y].ETag, true
  168. }
  169. func (s3a *S3ApiServer) abortMultipartUpload(input *s3.AbortMultipartUploadInput) (output *s3.AbortMultipartUploadOutput, code s3err.ErrorCode) {
  170. glog.V(2).Infof("abortMultipartUpload input %v", input)
  171. exists, err := s3a.exists(s3a.genUploadsFolder(*input.Bucket), *input.UploadId, true)
  172. if err != nil {
  173. glog.V(1).Infof("bucket %s abort upload %s: %v", *input.Bucket, *input.UploadId, err)
  174. return nil, s3err.ErrNoSuchUpload
  175. }
  176. if exists {
  177. err = s3a.rm(s3a.genUploadsFolder(*input.Bucket), *input.UploadId, true, true)
  178. }
  179. if err != nil {
  180. glog.V(1).Infof("bucket %s remove upload %s: %v", *input.Bucket, *input.UploadId, err)
  181. return nil, s3err.ErrInternalError
  182. }
  183. return &s3.AbortMultipartUploadOutput{}, s3err.ErrNone
  184. }
  185. type ListMultipartUploadsResult struct {
  186. XMLName xml.Name `xml:"http://s3.amazonaws.com/doc/2006-03-01/ ListMultipartUploadsResult"`
  187. // copied from s3.ListMultipartUploadsOutput, the Uploads is not converting to <Upload></Upload>
  188. Bucket *string `type:"string"`
  189. Delimiter *string `type:"string"`
  190. EncodingType *string `type:"string" enum:"EncodingType"`
  191. IsTruncated *bool `type:"boolean"`
  192. KeyMarker *string `type:"string"`
  193. MaxUploads *int64 `type:"integer"`
  194. NextKeyMarker *string `type:"string"`
  195. NextUploadIdMarker *string `type:"string"`
  196. Prefix *string `type:"string"`
  197. UploadIdMarker *string `type:"string"`
  198. Upload []*s3.MultipartUpload `locationName:"Upload" type:"list" flattened:"true"`
  199. }
  200. func (s3a *S3ApiServer) listMultipartUploads(input *s3.ListMultipartUploadsInput) (output *ListMultipartUploadsResult, code s3err.ErrorCode) {
  201. // https://docs.aws.amazon.com/AmazonS3/latest/API/API_ListMultipartUploads.html
  202. glog.V(2).Infof("listMultipartUploads input %v", input)
  203. output = &ListMultipartUploadsResult{
  204. Bucket: input.Bucket,
  205. Delimiter: input.Delimiter,
  206. EncodingType: input.EncodingType,
  207. KeyMarker: input.KeyMarker,
  208. MaxUploads: input.MaxUploads,
  209. Prefix: input.Prefix,
  210. }
  211. entries, _, err := s3a.list(s3a.genUploadsFolder(*input.Bucket), "", *input.UploadIdMarker, false, math.MaxInt32)
  212. if err != nil {
  213. glog.Errorf("listMultipartUploads %s error: %v", *input.Bucket, err)
  214. return
  215. }
  216. uploadsCount := int64(0)
  217. for _, entry := range entries {
  218. if entry.Extended != nil {
  219. key := string(entry.Extended["key"])
  220. if *input.KeyMarker != "" && *input.KeyMarker != key {
  221. continue
  222. }
  223. if *input.Prefix != "" && !strings.HasPrefix(key, *input.Prefix) {
  224. continue
  225. }
  226. output.Upload = append(output.Upload, &s3.MultipartUpload{
  227. Key: objectKey(aws.String(key)),
  228. UploadId: aws.String(entry.Name),
  229. })
  230. uploadsCount += 1
  231. }
  232. if uploadsCount >= *input.MaxUploads {
  233. output.IsTruncated = aws.Bool(true)
  234. output.NextUploadIdMarker = aws.String(entry.Name)
  235. break
  236. }
  237. }
  238. return
  239. }
  240. type ListPartsResult struct {
  241. XMLName xml.Name `xml:"http://s3.amazonaws.com/doc/2006-03-01/ ListPartsResult"`
  242. // copied from s3.ListPartsOutput, the Parts is not converting to <Part></Part>
  243. Bucket *string `type:"string"`
  244. IsTruncated *bool `type:"boolean"`
  245. Key *string `min:"1" type:"string"`
  246. MaxParts *int64 `type:"integer"`
  247. NextPartNumberMarker *int64 `type:"integer"`
  248. PartNumberMarker *int64 `type:"integer"`
  249. Part []*s3.Part `locationName:"Part" type:"list" flattened:"true"`
  250. StorageClass *string `type:"string" enum:"StorageClass"`
  251. UploadId *string `type:"string"`
  252. }
  253. func (s3a *S3ApiServer) listObjectParts(input *s3.ListPartsInput) (output *ListPartsResult, code s3err.ErrorCode) {
  254. // https://docs.aws.amazon.com/AmazonS3/latest/API/API_ListParts.html
  255. glog.V(2).Infof("listObjectParts input %v", input)
  256. output = &ListPartsResult{
  257. Bucket: input.Bucket,
  258. Key: objectKey(input.Key),
  259. UploadId: input.UploadId,
  260. MaxParts: input.MaxParts, // the maximum number of parts to return.
  261. PartNumberMarker: input.PartNumberMarker, // the part number starts after this, exclusive
  262. StorageClass: aws.String("STANDARD"),
  263. }
  264. entries, isLast, err := s3a.list(s3a.genUploadsFolder(*input.Bucket)+"/"+*input.UploadId, "", fmt.Sprintf("%04d.part", *input.PartNumberMarker), false, uint32(*input.MaxParts))
  265. if err != nil {
  266. glog.Errorf("listObjectParts %s %s error: %v", *input.Bucket, *input.UploadId, err)
  267. return nil, s3err.ErrNoSuchUpload
  268. }
  269. // Note: The upload directory is sort of a marker of the existence of an multipart upload request.
  270. // So can not just delete empty upload folders.
  271. output.IsTruncated = aws.Bool(!isLast)
  272. for _, entry := range entries {
  273. if strings.HasSuffix(entry.Name, ".part") && !entry.IsDirectory {
  274. partNumberString := entry.Name[:len(entry.Name)-len(".part")]
  275. partNumber, err := strconv.Atoi(partNumberString)
  276. if err != nil {
  277. glog.Errorf("listObjectParts %s %s parse %s: %v", *input.Bucket, *input.UploadId, entry.Name, err)
  278. continue
  279. }
  280. output.Part = append(output.Part, &s3.Part{
  281. PartNumber: aws.Int64(int64(partNumber)),
  282. LastModified: aws.Time(time.Unix(entry.Attributes.Mtime, 0).UTC()),
  283. Size: aws.Int64(int64(filer.FileSize(entry))),
  284. ETag: aws.String("\"" + filer.ETag(entry) + "\""),
  285. })
  286. if !isLast {
  287. output.NextPartNumberMarker = aws.Int64(int64(partNumber))
  288. }
  289. }
  290. }
  291. return
  292. }