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.

293 lines
8.7 KiB

7 years ago
7 years ago
7 years ago
7 years ago
6 years ago
7 years ago
4 years ago
4 years ago
5 years ago
4 years ago
  1. package s3api
  2. import (
  3. "context"
  4. "encoding/xml"
  5. "fmt"
  6. "io"
  7. "net/http"
  8. "net/url"
  9. "path/filepath"
  10. "strconv"
  11. "strings"
  12. "time"
  13. "github.com/chrislusf/seaweedfs/weed/filer2"
  14. "github.com/chrislusf/seaweedfs/weed/pb/filer_pb"
  15. )
  16. type ListBucketResultV2 struct {
  17. XMLName xml.Name `xml:"http://s3.amazonaws.com/doc/2006-03-01/ ListBucketResult"`
  18. Name string `xml:"Name"`
  19. Prefix string `xml:"Prefix"`
  20. MaxKeys int `xml:"MaxKeys"`
  21. Delimiter string `xml:"Delimiter,omitempty"`
  22. IsTruncated bool `xml:"IsTruncated"`
  23. Contents []ListEntry `xml:"Contents,omitempty"`
  24. CommonPrefixes []PrefixEntry `xml:"CommonPrefixes,omitempty"`
  25. ContinuationToken string `xml:"ContinuationToken,omitempty"`
  26. NextContinuationToken string `xml:"NextContinuationToken,omitempty"`
  27. KeyCount int `xml:"KeyCount"`
  28. StartAfter string `xml:"StartAfter,omitempty"`
  29. }
  30. func (s3a *S3ApiServer) ListObjectsV2Handler(w http.ResponseWriter, r *http.Request) {
  31. // https://docs.aws.amazon.com/AmazonS3/latest/API/v2-RESTBucketGET.html
  32. // collect parameters
  33. bucket, _ := getBucketAndObject(r)
  34. originalPrefix, continuationToken, startAfter, delimiter, _, maxKeys := getListObjectsV2Args(r.URL.Query())
  35. if maxKeys < 0 {
  36. writeErrorResponse(w, ErrInvalidMaxKeys, r.URL)
  37. return
  38. }
  39. if delimiter != "" && delimiter != "/" {
  40. writeErrorResponse(w, ErrNotImplemented, r.URL)
  41. return
  42. }
  43. marker := continuationToken
  44. if continuationToken == "" {
  45. marker = startAfter
  46. }
  47. response, err := s3a.listFilerEntries(bucket, originalPrefix, maxKeys, marker, delimiter)
  48. if err != nil {
  49. writeErrorResponse(w, ErrInternalError, r.URL)
  50. return
  51. }
  52. responseV2 := &ListBucketResultV2{
  53. XMLName: response.XMLName,
  54. Name: response.Name,
  55. CommonPrefixes: response.CommonPrefixes,
  56. Contents: response.Contents,
  57. ContinuationToken: continuationToken,
  58. Delimiter: response.Delimiter,
  59. IsTruncated: response.IsTruncated,
  60. KeyCount: len(response.Contents),
  61. MaxKeys: response.MaxKeys,
  62. NextContinuationToken: response.NextMarker,
  63. Prefix: response.Prefix,
  64. StartAfter: startAfter,
  65. }
  66. writeSuccessResponseXML(w, encodeResponse(responseV2))
  67. }
  68. func (s3a *S3ApiServer) ListObjectsV1Handler(w http.ResponseWriter, r *http.Request) {
  69. // https://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketGET.html
  70. // collect parameters
  71. bucket, _ := getBucketAndObject(r)
  72. originalPrefix, marker, delimiter, maxKeys := getListObjectsV1Args(r.URL.Query())
  73. if maxKeys < 0 {
  74. writeErrorResponse(w, ErrInvalidMaxKeys, r.URL)
  75. return
  76. }
  77. if delimiter != "" && delimiter != "/" {
  78. writeErrorResponse(w, ErrNotImplemented, r.URL)
  79. return
  80. }
  81. response, err := s3a.listFilerEntries(bucket, originalPrefix, maxKeys, marker, delimiter)
  82. if err != nil {
  83. writeErrorResponse(w, ErrInternalError, r.URL)
  84. return
  85. }
  86. writeSuccessResponseXML(w, encodeResponse(response))
  87. }
  88. func (s3a *S3ApiServer) listFilerEntries(bucket string, originalPrefix string, maxKeys int, marker string, delimiter string) (response ListBucketResult, err error) {
  89. // convert full path prefix into directory name and prefix for entry name
  90. reqDir, prefix := filepath.Split(originalPrefix)
  91. if strings.HasPrefix(reqDir, "/") {
  92. reqDir = reqDir[1:]
  93. }
  94. if strings.HasSuffix(reqDir, "/") {
  95. // remove trailing "/"
  96. reqDir = reqDir[:len(reqDir)-1]
  97. }
  98. bucketPrefix := fmt.Sprintf("%s/%s/", s3a.option.BucketsPath, bucket)
  99. reqDir = fmt.Sprintf("%s%s", bucketPrefix, reqDir)
  100. var contents []ListEntry
  101. var commonPrefixes []PrefixEntry
  102. var isTruncated bool
  103. var doErr error
  104. var nextMarker string
  105. // check filer
  106. err = s3a.WithFilerClient(func(client filer_pb.SeaweedFilerClient) error {
  107. _, isTruncated, nextMarker, doErr = s3a.doListFilerEntries(client, reqDir, prefix, maxKeys, marker, delimiter, func(dir string, entry *filer_pb.Entry) {
  108. if entry.IsDirectory {
  109. if delimiter == "/" {
  110. prefix = fmt.Sprintf("%s%s/", dir, entry.Name)
  111. commonPrefixes = append(commonPrefixes, PrefixEntry{
  112. Prefix: prefix[len(bucketPrefix):],
  113. })
  114. }
  115. } else {
  116. contents = append(contents, ListEntry{
  117. Key: fmt.Sprintf("%s%s", dir[len(bucketPrefix):], entry.Name),
  118. LastModified: time.Unix(entry.Attributes.Mtime, 0).UTC(),
  119. ETag: "\"" + filer2.ETag(entry) + "\"",
  120. Size: int64(filer2.FileSize(entry)),
  121. Owner: CanonicalUser{
  122. ID: fmt.Sprintf("%x", entry.Attributes.Uid),
  123. DisplayName: entry.Attributes.UserName,
  124. },
  125. StorageClass: "STANDARD",
  126. })
  127. }
  128. })
  129. if doErr != nil {
  130. return doErr
  131. }
  132. if !isTruncated {
  133. nextMarker = ""
  134. }
  135. response = ListBucketResult{
  136. Name: bucket,
  137. Prefix: originalPrefix,
  138. Marker: marker,
  139. NextMarker: nextMarker,
  140. MaxKeys: maxKeys,
  141. Delimiter: delimiter,
  142. IsTruncated: isTruncated,
  143. Contents: contents,
  144. CommonPrefixes: commonPrefixes,
  145. }
  146. return nil
  147. })
  148. return
  149. }
  150. func (s3a *S3ApiServer) doListFilerEntries(client filer_pb.SeaweedFilerClient, dir, prefix string, maxKeys int, marker, delimiter string, eachEntryFn func(dir string, entry *filer_pb.Entry)) (counter int, isTruncated bool, nextMarker string, err error) {
  151. // invariants
  152. // prefix and marker should be under dir, marker may contain "/"
  153. // maxKeys should be updated for each recursion
  154. if prefix == "/" && delimiter == "/" {
  155. return
  156. }
  157. if maxKeys <= 0 {
  158. return
  159. }
  160. if strings.Contains(marker, "/") {
  161. sepIndex := strings.Index(marker, "/")
  162. subDir, subMarker := marker[0:sepIndex], marker[sepIndex+1:]
  163. // println("doListFilerEntries dir", dir+"/"+subDir, "subMarker", subMarker, "maxKeys", maxKeys)
  164. subCounter, _, subNextMarker, subErr := s3a.doListFilerEntries(client, dir+"/"+subDir, "", maxKeys, subMarker, delimiter, eachEntryFn)
  165. if subErr != nil {
  166. err = subErr
  167. return
  168. }
  169. maxKeys -= subCounter
  170. nextMarker = subDir + "/" + subNextMarker
  171. counter += subCounter
  172. // finished processing this sub directory
  173. marker = subDir
  174. }
  175. // now marker is also a direct child of dir
  176. request := &filer_pb.ListEntriesRequest{
  177. Directory: dir,
  178. Prefix: prefix,
  179. Limit: uint32(maxKeys + 1),
  180. StartFromFileName: marker,
  181. InclusiveStartFrom: false,
  182. }
  183. stream, listErr := client.ListEntries(context.Background(), request)
  184. if listErr != nil {
  185. err = fmt.Errorf("list entires %+v: %v", request, listErr)
  186. return
  187. }
  188. for {
  189. resp, recvErr := stream.Recv()
  190. if recvErr != nil {
  191. if recvErr == io.EOF {
  192. break
  193. } else {
  194. err = fmt.Errorf("iterating entires %+v: %v", request, recvErr)
  195. return
  196. }
  197. }
  198. if counter >= maxKeys {
  199. isTruncated = true
  200. return
  201. }
  202. entry := resp.Entry
  203. nextMarker = entry.Name
  204. if entry.IsDirectory {
  205. // println("ListEntries", dir, "dir:", entry.Name)
  206. if entry.Name != ".uploads" { // FIXME no need to apply to all directories. this extra also affects maxKeys
  207. eachEntryFn(dir, entry)
  208. if delimiter != "/" {
  209. // println("doListFilerEntries2 dir", dir+"/"+entry.Name, "maxKeys", maxKeys-counter)
  210. subCounter, subIsTruncated, subNextMarker, subErr := s3a.doListFilerEntries(client, dir+"/"+entry.Name, "", maxKeys-counter, "", delimiter, eachEntryFn)
  211. if subErr != nil {
  212. err = fmt.Errorf("doListFilerEntries2: %v", subErr)
  213. return
  214. }
  215. // println("doListFilerEntries2 dir", dir+"/"+entry.Name, "maxKeys", maxKeys-counter, "subCounter", subCounter, "subNextMarker", subNextMarker, "subIsTruncated", subIsTruncated)
  216. counter += subCounter
  217. nextMarker = entry.Name + "/" + subNextMarker
  218. if subIsTruncated {
  219. isTruncated = true
  220. return
  221. }
  222. } else {
  223. counter++
  224. }
  225. }
  226. } else {
  227. // println("ListEntries", dir, "file:", entry.Name)
  228. eachEntryFn(dir, entry)
  229. counter++
  230. }
  231. }
  232. return
  233. }
  234. func getListObjectsV2Args(values url.Values) (prefix, token, startAfter, delimiter string, fetchOwner bool, maxkeys int) {
  235. prefix = values.Get("prefix")
  236. token = values.Get("continuation-token")
  237. startAfter = values.Get("start-after")
  238. delimiter = values.Get("delimiter")
  239. if values.Get("max-keys") != "" {
  240. maxkeys, _ = strconv.Atoi(values.Get("max-keys"))
  241. } else {
  242. maxkeys = maxObjectListSizeLimit
  243. }
  244. fetchOwner = values.Get("fetch-owner") == "true"
  245. return
  246. }
  247. func getListObjectsV1Args(values url.Values) (prefix, marker, delimiter string, maxkeys int) {
  248. prefix = values.Get("prefix")
  249. marker = values.Get("marker")
  250. delimiter = values.Get("delimiter")
  251. if values.Get("max-keys") != "" {
  252. maxkeys, _ = strconv.Atoi(values.Get("max-keys"))
  253. } else {
  254. maxkeys = maxObjectListSizeLimit
  255. }
  256. return
  257. }