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.

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