s3api_objects_list_handlers.go 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  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. }