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.

411 lines
12 KiB

7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 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. "github.com/chrislusf/seaweedfs/weed/s3api/s3_constants"
  8. "io"
  9. "net/http"
  10. "net/url"
  11. "path/filepath"
  12. "strconv"
  13. "strings"
  14. "time"
  15. "github.com/chrislusf/seaweedfs/weed/filer"
  16. "github.com/chrislusf/seaweedfs/weed/pb/filer_pb"
  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, _ := s3_constants.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, r, s3err.ErrInvalidMaxKeys)
  41. return
  42. }
  43. if delimiter != "" && delimiter != "/" {
  44. s3err.WriteErrorResponse(w, r, s3err.ErrNotImplemented)
  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, r, s3err.ErrInternalError)
  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, r, s3err.ErrNoSuchBucket)
  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, r, 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, _ := s3_constants.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, r, s3err.ErrInvalidMaxKeys)
  86. return
  87. }
  88. if delimiter != "" && delimiter != "/" {
  89. s3err.WriteErrorResponse(w, r, s3err.ErrNotImplemented)
  90. return
  91. }
  92. response, err := s3a.listFilerEntries(bucket, originalPrefix, maxKeys, marker, delimiter)
  93. if err != nil {
  94. s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
  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, r, s3err.ErrNoSuchBucket)
  100. return
  101. }
  102. }
  103. writeSuccessResponseXML(w, r, 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. reqDir = strings.TrimSuffix(reqDir, "/")
  115. }
  116. var contents []ListEntry
  117. var commonPrefixes []PrefixEntry
  118. var isTruncated bool
  119. var doErr error
  120. var nextMarker string
  121. // check filer
  122. err = s3a.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
  123. _, isTruncated, nextMarker, doErr = s3a.doListFilerEntries(client, reqDir, prefix, maxKeys, marker, delimiter, false, func(dir string, entry *filer_pb.Entry) {
  124. if entry.IsDirectory {
  125. if delimiter == "/" {
  126. commonPrefixes = append(commonPrefixes, PrefixEntry{
  127. Prefix: fmt.Sprintf("%s/%s/", dir, entry.Name)[len(bucketPrefix):],
  128. })
  129. }
  130. return
  131. }
  132. storageClass := "STANDARD"
  133. if v, ok := entry.Extended[s3_constants.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. if doErr != nil {
  149. return doErr
  150. }
  151. if !isTruncated {
  152. nextMarker = ""
  153. }
  154. if len(contents) == 0 && maxKeys > 0 {
  155. if strings.HasSuffix(originalPrefix, "/") && prefix == "" {
  156. reqDir, prefix = filepath.Split(strings.TrimSuffix(reqDir, "/"))
  157. reqDir = strings.TrimSuffix(reqDir, "/")
  158. }
  159. _, _, _, doErr = s3a.doListFilerEntries(client, reqDir, prefix, 1, prefix, delimiter, true, func(dir string, entry *filer_pb.Entry) {
  160. if entry.IsDirectory && entry.Attributes.Mime != "" && entry.Name == prefix {
  161. storageClass := "STANDARD"
  162. if v, ok := entry.Extended[s3_constants.AmzStorageClass]; ok {
  163. storageClass = string(v)
  164. }
  165. contents = append(contents, ListEntry{
  166. Key: fmt.Sprintf("%s/%s", dir, entry.Name+"/")[len(bucketPrefix):],
  167. LastModified: time.Unix(entry.Attributes.Mtime, 0).UTC(),
  168. ETag: "\"" + filer.ETag(entry) + "\"",
  169. Size: int64(filer.FileSize(entry)),
  170. Owner: CanonicalUser{
  171. ID: fmt.Sprintf("%x", entry.Attributes.Uid),
  172. DisplayName: entry.Attributes.UserName,
  173. },
  174. StorageClass: StorageClass(storageClass),
  175. })
  176. }
  177. })
  178. }
  179. response = ListBucketResult{
  180. Name: bucket,
  181. Prefix: originalPrefix,
  182. Marker: marker,
  183. NextMarker: nextMarker,
  184. MaxKeys: maxKeys,
  185. Delimiter: delimiter,
  186. IsTruncated: isTruncated,
  187. Contents: contents,
  188. CommonPrefixes: commonPrefixes,
  189. }
  190. return nil
  191. })
  192. return
  193. }
  194. func (s3a *S3ApiServer) doListFilerEntries(client filer_pb.SeaweedFilerClient, dir, prefix string, maxKeys int, marker, delimiter string, inclusiveStartFrom bool, eachEntryFn func(dir string, entry *filer_pb.Entry)) (counter int, isTruncated bool, nextMarker string, err error) {
  195. // invariants
  196. // prefix and marker should be under dir, marker may contain "/"
  197. // maxKeys should be updated for each recursion
  198. if prefix == "/" && delimiter == "/" {
  199. return
  200. }
  201. if maxKeys <= 0 {
  202. return
  203. }
  204. if strings.Contains(marker, "/") {
  205. sepIndex := strings.Index(marker, "/")
  206. subDir, subMarker := marker[0:sepIndex], marker[sepIndex+1:]
  207. glog.V(4).Infoln("doListFilerEntries dir", dir+"/"+subDir, "subMarker", subMarker, "maxKeys", maxKeys)
  208. subCounter, subIsTruncated, subNextMarker, subErr := s3a.doListFilerEntries(client, dir+"/"+subDir, "", maxKeys, subMarker, delimiter, false, eachEntryFn)
  209. if subErr != nil {
  210. err = subErr
  211. return
  212. }
  213. counter += subCounter
  214. isTruncated = isTruncated || subIsTruncated
  215. maxKeys -= subCounter
  216. nextMarker = subDir + "/" + subNextMarker
  217. // finished processing this sub directory
  218. marker = subDir
  219. }
  220. if maxKeys <= 0 {
  221. return
  222. }
  223. // now marker is also a direct child of dir
  224. request := &filer_pb.ListEntriesRequest{
  225. Directory: dir,
  226. Prefix: prefix,
  227. Limit: uint32(maxKeys + 1),
  228. StartFromFileName: marker,
  229. InclusiveStartFrom: inclusiveStartFrom,
  230. }
  231. ctx, cancel := context.WithCancel(context.Background())
  232. defer cancel()
  233. stream, listErr := client.ListEntries(ctx, request)
  234. if listErr != nil {
  235. err = fmt.Errorf("list entires %+v: %v", request, listErr)
  236. return
  237. }
  238. for {
  239. resp, recvErr := stream.Recv()
  240. if recvErr != nil {
  241. if recvErr == io.EOF {
  242. break
  243. } else {
  244. err = fmt.Errorf("iterating entires %+v: %v", request, recvErr)
  245. return
  246. }
  247. }
  248. if counter >= maxKeys {
  249. isTruncated = true
  250. return
  251. }
  252. entry := resp.Entry
  253. nextMarker = entry.Name
  254. if entry.IsDirectory {
  255. // println("ListEntries", dir, "dir:", entry.Name)
  256. if entry.Name == ".uploads" { // FIXME no need to apply to all directories. this extra also affects maxKeys
  257. continue
  258. }
  259. if delimiter != "/" {
  260. eachEntryFn(dir, entry)
  261. // println("doListFilerEntries2 dir", dir+"/"+entry.Name, "maxKeys", maxKeys-counter)
  262. subCounter, subIsTruncated, subNextMarker, subErr := s3a.doListFilerEntries(client, dir+"/"+entry.Name, "", maxKeys-counter, "", delimiter, false, eachEntryFn)
  263. if subErr != nil {
  264. err = fmt.Errorf("doListFilerEntries2: %v", subErr)
  265. return
  266. }
  267. // println("doListFilerEntries2 dir", dir+"/"+entry.Name, "maxKeys", maxKeys-counter, "subCounter", subCounter, "subNextMarker", subNextMarker, "subIsTruncated", subIsTruncated)
  268. counter += subCounter
  269. nextMarker = entry.Name + "/" + subNextMarker
  270. if subIsTruncated {
  271. isTruncated = true
  272. return
  273. }
  274. } else {
  275. var isEmpty bool
  276. if !s3a.option.AllowEmptyFolder {
  277. if isEmpty, err = s3a.isDirectoryAllEmpty(client, dir, entry.Name); err != nil {
  278. glog.Errorf("check empty folder %s: %v", dir, err)
  279. }
  280. }
  281. if !isEmpty {
  282. eachEntryFn(dir, entry)
  283. counter++
  284. }
  285. }
  286. } else {
  287. // println("ListEntries", dir, "file:", entry.Name)
  288. eachEntryFn(dir, entry)
  289. counter++
  290. }
  291. }
  292. return
  293. }
  294. func getListObjectsV2Args(values url.Values) (prefix, token, startAfter, delimiter string, fetchOwner bool, maxkeys int) {
  295. prefix = values.Get("prefix")
  296. token = values.Get("continuation-token")
  297. startAfter = values.Get("start-after")
  298. delimiter = values.Get("delimiter")
  299. if values.Get("max-keys") != "" {
  300. maxkeys, _ = strconv.Atoi(values.Get("max-keys"))
  301. } else {
  302. maxkeys = maxObjectListSizeLimit
  303. }
  304. fetchOwner = values.Get("fetch-owner") == "true"
  305. return
  306. }
  307. func getListObjectsV1Args(values url.Values) (prefix, marker, delimiter string, maxkeys int) {
  308. prefix = values.Get("prefix")
  309. marker = values.Get("marker")
  310. delimiter = values.Get("delimiter")
  311. if values.Get("max-keys") != "" {
  312. maxkeys, _ = strconv.Atoi(values.Get("max-keys"))
  313. } else {
  314. maxkeys = maxObjectListSizeLimit
  315. }
  316. return
  317. }
  318. func (s3a *S3ApiServer) isDirectoryAllEmpty(filerClient filer_pb.SeaweedFilerClient, parentDir, name string) (isEmpty bool, err error) {
  319. // println("+ isDirectoryAllEmpty", dir, name)
  320. glog.V(4).Infof("+ isEmpty %s/%s", parentDir, name)
  321. defer glog.V(4).Infof("- isEmpty %s/%s %v", parentDir, name, isEmpty)
  322. var fileCounter int
  323. var subDirs []string
  324. currentDir := parentDir + "/" + name
  325. var startFrom string
  326. var isExhausted bool
  327. var foundEntry bool
  328. for fileCounter == 0 && !isExhausted && err == nil {
  329. err = filer_pb.SeaweedList(filerClient, currentDir, "", func(entry *filer_pb.Entry, isLast bool) error {
  330. foundEntry = true
  331. if entry.IsDirectory {
  332. subDirs = append(subDirs, entry.Name)
  333. } else {
  334. fileCounter++
  335. }
  336. startFrom = entry.Name
  337. isExhausted = isExhausted || isLast
  338. glog.V(4).Infof(" * %s/%s isLast: %t", currentDir, startFrom, isLast)
  339. return nil
  340. }, startFrom, false, 8)
  341. if !foundEntry {
  342. break
  343. }
  344. }
  345. if err != nil {
  346. return false, err
  347. }
  348. if fileCounter > 0 {
  349. return false, nil
  350. }
  351. for _, subDir := range subDirs {
  352. isSubEmpty, subErr := s3a.isDirectoryAllEmpty(filerClient, currentDir, subDir)
  353. if subErr != nil {
  354. return false, subErr
  355. }
  356. if !isSubEmpty {
  357. return false, nil
  358. }
  359. }
  360. glog.V(1).Infof("deleting empty folder %s", currentDir)
  361. if err = doDeleteEntry(filerClient, parentDir, name, true, true); err != nil {
  362. return
  363. }
  364. return true, nil
  365. }