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.

364 lines
11 KiB

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