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.

381 lines
11 KiB

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