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.

631 lines
20 KiB

7 years ago
7 years ago
7 years ago
8 months ago
3 years ago
3 years ago
3 years ago
3 years ago
8 months ago
3 years ago
8 months ago
3 years ago
3 years ago
3 years ago
8 months ago
8 months ago
8 months ago
8 months ago
9 months ago
8 months ago
8 months ago
8 months ago
8 months ago
8 months ago
9 months ago
8 months ago
9 months ago
8 months ago
8 months ago
9 months ago
8 months ago
9 months ago
8 months ago
9 months ago
8 months ago
9 months ago
8 months ago
9 months ago
8 months ago
9 months ago
8 months ago
9 months ago
1 year ago
8 months ago
8 months ago
8 months ago
8 months ago
3 years ago
4 years ago
4 years ago
3 years ago
  1. package s3api
  2. import (
  3. "context"
  4. "encoding/xml"
  5. "fmt"
  6. "github.com/aws/aws-sdk-go/service/s3"
  7. "github.com/seaweedfs/seaweedfs/weed/glog"
  8. "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
  9. "github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
  10. "github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
  11. "io"
  12. "net/http"
  13. "net/url"
  14. "strconv"
  15. "strings"
  16. )
  17. type OptionalString struct {
  18. string
  19. set bool
  20. }
  21. func (o OptionalString) MarshalXML(e *xml.Encoder, startElement xml.StartElement) error {
  22. if !o.set {
  23. return nil
  24. }
  25. return e.EncodeElement(o.string, startElement)
  26. }
  27. type ListBucketResultV2 struct {
  28. XMLName xml.Name `xml:"http://s3.amazonaws.com/doc/2006-03-01/ ListBucketResult"`
  29. Name string `xml:"Name"`
  30. Prefix string `xml:"Prefix"`
  31. MaxKeys uint16 `xml:"MaxKeys"`
  32. Delimiter string `xml:"Delimiter,omitempty"`
  33. IsTruncated bool `xml:"IsTruncated"`
  34. Contents []ListEntry `xml:"Contents,omitempty"`
  35. CommonPrefixes []PrefixEntry `xml:"CommonPrefixes,omitempty"`
  36. ContinuationToken OptionalString `xml:"ContinuationToken,omitempty"`
  37. NextContinuationToken string `xml:"NextContinuationToken,omitempty"`
  38. EncodingType string `xml:"EncodingType,omitempty"`
  39. KeyCount int `xml:"KeyCount"`
  40. StartAfter string `xml:"StartAfter,omitempty"`
  41. }
  42. func (s3a *S3ApiServer) ListObjectsV2Handler(w http.ResponseWriter, r *http.Request) {
  43. // https://docs.aws.amazon.com/AmazonS3/latest/API/v2-RESTBucketGET.html
  44. // collect parameters
  45. bucket, _ := s3_constants.GetBucketAndObject(r)
  46. glog.V(3).Infof("ListObjectsV2Handler %s", bucket)
  47. originalPrefix, startAfter, delimiter, continuationToken, encodingTypeUrl, fetchOwner, maxKeys := getListObjectsV2Args(r.URL.Query())
  48. if maxKeys < 0 {
  49. s3err.WriteErrorResponse(w, r, s3err.ErrInvalidMaxKeys)
  50. return
  51. }
  52. marker := continuationToken.string
  53. if !continuationToken.set {
  54. marker = startAfter
  55. }
  56. response, err := s3a.listFilerEntries(bucket, originalPrefix, maxKeys, marker, delimiter, encodingTypeUrl, fetchOwner)
  57. if err != nil {
  58. s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
  59. return
  60. }
  61. if len(response.Contents) == 0 {
  62. if exists, existErr := s3a.exists(s3a.option.BucketsPath, bucket, true); existErr == nil && !exists {
  63. s3err.WriteErrorResponse(w, r, s3err.ErrNoSuchBucket)
  64. return
  65. }
  66. }
  67. responseV2 := &ListBucketResultV2{
  68. XMLName: response.XMLName,
  69. Name: response.Name,
  70. CommonPrefixes: response.CommonPrefixes,
  71. Contents: response.Contents,
  72. ContinuationToken: continuationToken,
  73. Delimiter: response.Delimiter,
  74. IsTruncated: response.IsTruncated,
  75. KeyCount: len(response.Contents) + len(response.CommonPrefixes),
  76. MaxKeys: response.MaxKeys,
  77. NextContinuationToken: response.NextMarker,
  78. Prefix: response.Prefix,
  79. StartAfter: startAfter,
  80. }
  81. if encodingTypeUrl {
  82. responseV2.EncodingType = s3.EncodingTypeUrl
  83. }
  84. writeSuccessResponseXML(w, r, responseV2)
  85. }
  86. func (s3a *S3ApiServer) ListObjectsV1Handler(w http.ResponseWriter, r *http.Request) {
  87. // https://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketGET.html
  88. // collect parameters
  89. bucket, _ := s3_constants.GetBucketAndObject(r)
  90. glog.V(3).Infof("ListObjectsV1Handler %s", bucket)
  91. originalPrefix, marker, delimiter, encodingTypeUrl, maxKeys := getListObjectsV1Args(r.URL.Query())
  92. if maxKeys < 0 {
  93. s3err.WriteErrorResponse(w, r, s3err.ErrInvalidMaxKeys)
  94. return
  95. }
  96. response, err := s3a.listFilerEntries(bucket, originalPrefix, uint16(maxKeys), marker, delimiter, encodingTypeUrl, true)
  97. if err != nil {
  98. s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
  99. return
  100. }
  101. if len(response.Contents) == 0 {
  102. if exists, existErr := s3a.exists(s3a.option.BucketsPath, bucket, true); existErr == nil && !exists {
  103. s3err.WriteErrorResponse(w, r, s3err.ErrNoSuchBucket)
  104. return
  105. }
  106. }
  107. writeSuccessResponseXML(w, r, response)
  108. }
  109. func (s3a *S3ApiServer) listFilerEntries(bucket string, originalPrefix string, maxKeys uint16, originalMarker string, delimiter string, encodingTypeUrl bool, fetchOwner bool) (response ListBucketResult, err error) {
  110. // convert full path prefix into directory name and prefix for entry name
  111. requestDir, prefix, marker := normalizePrefixMarker(originalPrefix, originalMarker)
  112. bucketPrefix := fmt.Sprintf("%s/%s/", s3a.option.BucketsPath, bucket)
  113. reqDir := bucketPrefix[:len(bucketPrefix)-1]
  114. if requestDir != "" {
  115. reqDir = fmt.Sprintf("%s%s", bucketPrefix, requestDir)
  116. }
  117. var contents []ListEntry
  118. var commonPrefixes []PrefixEntry
  119. var doErr error
  120. var nextMarker string
  121. cursor := &ListingCursor{
  122. maxKeys: maxKeys,
  123. prefixEndsOnDelimiter: strings.HasSuffix(originalPrefix, "/") && len(originalMarker) == 0,
  124. }
  125. if s3a.option.AllowListRecursive && (delimiter == "" || delimiter == "/") {
  126. reqDir = bucketPrefix
  127. if idx := strings.LastIndex(originalPrefix, "/"); idx > 0 {
  128. reqDir += originalPrefix[:idx]
  129. prefix = originalPrefix[idx+1:]
  130. }
  131. // This is necessary for SQL request with WHERE `directory` || `name` > originalMarker
  132. if len(originalMarker) > 0 && originalMarker[0:1] != "/" {
  133. marker = getStartFileFromKey(originalMarker)
  134. } else {
  135. marker = originalMarker
  136. }
  137. response = ListBucketResult{
  138. Name: bucket,
  139. Prefix: originalPrefix,
  140. Marker: originalMarker,
  141. MaxKeys: maxKeys,
  142. Delimiter: delimiter,
  143. }
  144. if encodingTypeUrl {
  145. response.EncodingType = s3.EncodingTypeUrl
  146. }
  147. if maxKeys == 0 {
  148. return
  149. }
  150. err = s3a.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
  151. doErr = s3a.doListFilerRecursiveEntries(client, reqDir, prefix, cursor, marker, delimiter, false,
  152. func(path string, entry *filer_pb.Entry) {
  153. key := path[len(bucketPrefix):]
  154. if cursor.isTruncated {
  155. nextMarker = cursor.nextMarker
  156. return
  157. }
  158. defer func() {
  159. if cursor.maxKeys == 0 {
  160. cursor.isTruncated = true
  161. cursor.nextMarker = getStartFileFromKey(key)
  162. }
  163. }()
  164. if delimiter == "/" {
  165. if entry.IsDirectoryKeyObject() {
  166. contents = append(contents, newListEntry(entry, key+"/", "", "", bucketPrefix, fetchOwner, false, encodingTypeUrl))
  167. cursor.maxKeys--
  168. return
  169. }
  170. if entry.IsDirectory {
  171. var prefixKey string
  172. if encodingTypeUrl {
  173. prefixKey = urlPathEscape(key + "/")
  174. } else {
  175. prefixKey = key + "/"
  176. }
  177. commonPrefixes = append(commonPrefixes, PrefixEntry{
  178. Prefix: prefixKey,
  179. })
  180. cursor.maxKeys--
  181. return
  182. }
  183. }
  184. contents = append(contents, newListEntry(entry, key, "", "", bucketPrefix, fetchOwner, false, encodingTypeUrl))
  185. cursor.maxKeys--
  186. },
  187. )
  188. return nil
  189. })
  190. response.NextMarker = nextMarker
  191. response.IsTruncated = len(nextMarker) != 0
  192. response.Contents = contents
  193. response.CommonPrefixes = commonPrefixes
  194. return
  195. }
  196. // check filer
  197. err = s3a.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
  198. for {
  199. empty := true
  200. nextMarker, doErr = s3a.doListFilerEntries(client, reqDir, prefix, cursor, marker, delimiter, false, func(dir string, entry *filer_pb.Entry) {
  201. empty = false
  202. dirName, entryName, prefixName := entryUrlEncode(dir, entry.Name, encodingTypeUrl)
  203. if entry.IsDirectory {
  204. if entry.IsDirectoryKeyObject() {
  205. contents = append(contents, newListEntry(entry, "", dirName, entryName, bucketPrefix, fetchOwner, true, false))
  206. cursor.maxKeys--
  207. // https://docs.aws.amazon.com/AmazonS3/latest/API/API_ListObjectsV2.html
  208. } else if delimiter == "/" { // A response can contain CommonPrefixes only if you specify a delimiter.
  209. commonPrefixes = append(commonPrefixes, PrefixEntry{
  210. Prefix: fmt.Sprintf("%s/%s/", dirName, prefixName)[len(bucketPrefix):],
  211. })
  212. //All of the keys (up to 1,000) rolled up into a common prefix count as a single return when calculating the number of returns.
  213. cursor.maxKeys--
  214. }
  215. } else {
  216. var delimiterFound bool
  217. if delimiter != "" {
  218. // keys that contain the same string between the prefix and the first occurrence of the delimiter are grouped together as a commonPrefix.
  219. // extract the string between the prefix and the delimiter and add it to the commonPrefixes if it's unique.
  220. undelimitedPath := fmt.Sprintf("%s/%s", dir, entry.Name)[len(bucketPrefix):]
  221. // take into account a prefix if supplied while delimiting.
  222. undelimitedPath = strings.TrimPrefix(undelimitedPath, originalPrefix)
  223. delimitedPath := strings.SplitN(undelimitedPath, delimiter, 2)
  224. if len(delimitedPath) == 2 {
  225. // S3 clients expect the delimited prefix to contain the delimiter and prefix.
  226. delimitedPrefix := originalPrefix + delimitedPath[0] + delimiter
  227. for i := range commonPrefixes {
  228. if commonPrefixes[i].Prefix == delimitedPrefix {
  229. delimiterFound = true
  230. break
  231. }
  232. }
  233. if !delimiterFound {
  234. commonPrefixes = append(commonPrefixes, PrefixEntry{
  235. Prefix: delimitedPrefix,
  236. })
  237. cursor.maxKeys--
  238. delimiterFound = true
  239. }
  240. }
  241. }
  242. if !delimiterFound {
  243. contents = append(contents, newListEntry(entry, "", dirName, entryName, bucketPrefix, fetchOwner, false, false))
  244. cursor.maxKeys--
  245. }
  246. }
  247. })
  248. if doErr != nil {
  249. return doErr
  250. }
  251. if cursor.isTruncated {
  252. if requestDir != "" {
  253. nextMarker = requestDir + "/" + nextMarker
  254. }
  255. break
  256. } else if empty || strings.HasSuffix(originalPrefix, "/") {
  257. nextMarker = ""
  258. break
  259. } else {
  260. // start next loop
  261. marker = nextMarker
  262. }
  263. }
  264. response = ListBucketResult{
  265. Name: bucket,
  266. Prefix: originalPrefix,
  267. Marker: originalMarker,
  268. NextMarker: nextMarker,
  269. MaxKeys: maxKeys,
  270. Delimiter: delimiter,
  271. IsTruncated: cursor.isTruncated,
  272. Contents: contents,
  273. CommonPrefixes: commonPrefixes,
  274. }
  275. if encodingTypeUrl {
  276. // Todo used for pass test_bucket_listv2_encoding_basic
  277. // sort.Slice(response.CommonPrefixes, func(i, j int) bool { return response.CommonPrefixes[i].Prefix < response.CommonPrefixes[j].Prefix })
  278. response.EncodingType = s3.EncodingTypeUrl
  279. }
  280. return nil
  281. })
  282. return
  283. }
  284. type ListingCursor struct {
  285. maxKeys uint16
  286. isTruncated bool
  287. prefixEndsOnDelimiter bool
  288. nextMarker string
  289. }
  290. func (s3a *S3ApiServer) getStartFileFromKey(key string) string {
  291. idx := strings.LastIndex(key, "/")
  292. if idx == -1 {
  293. return "/" + key
  294. }
  295. return fmt.Sprintf("/%s%s", key[0:idx], key[idx+1:len(key)])
  296. }
  297. // the prefix and marker may be in different directories
  298. // normalizePrefixMarker ensures the prefix and marker both starts from the same directory
  299. func normalizePrefixMarker(prefix, marker string) (alignedDir, alignedPrefix, alignedMarker string) {
  300. // alignedDir should not end with "/"
  301. // alignedDir, alignedPrefix, alignedMarker should only have "/" in middle
  302. if len(marker) == 0 {
  303. prefix = strings.Trim(prefix, "/")
  304. } else {
  305. prefix = strings.TrimLeft(prefix, "/")
  306. }
  307. marker = strings.TrimLeft(marker, "/")
  308. if prefix == "" {
  309. return "", "", marker
  310. }
  311. if marker == "" {
  312. alignedDir, alignedPrefix = toDirAndName(prefix)
  313. return
  314. }
  315. if !strings.HasPrefix(marker, prefix) {
  316. // something wrong
  317. return "", prefix, marker
  318. }
  319. if strings.HasPrefix(marker, prefix+"/") {
  320. alignedDir = prefix
  321. alignedPrefix = ""
  322. alignedMarker = marker[len(alignedDir)+1:]
  323. return
  324. }
  325. alignedDir, alignedPrefix = toDirAndName(prefix)
  326. if alignedDir != "" {
  327. alignedMarker = marker[len(alignedDir)+1:]
  328. } else {
  329. alignedMarker = marker
  330. }
  331. return
  332. }
  333. func toDirAndName(dirAndName string) (dir, name string) {
  334. sepIndex := strings.LastIndex(dirAndName, "/")
  335. if sepIndex >= 0 {
  336. dir, name = dirAndName[0:sepIndex], dirAndName[sepIndex+1:]
  337. } else {
  338. name = dirAndName
  339. }
  340. return
  341. }
  342. func toParentAndDescendants(dirAndName string) (dir, name string) {
  343. sepIndex := strings.Index(dirAndName, "/")
  344. if sepIndex >= 0 {
  345. dir, name = dirAndName[0:sepIndex], dirAndName[sepIndex+1:]
  346. } else {
  347. name = dirAndName
  348. }
  349. return
  350. }
  351. func (s3a *S3ApiServer) doListFilerRecursiveEntries(client filer_pb.SeaweedFilerClient, dir, prefix string, cursor *ListingCursor, marker, delimiter string, inclusiveStartFrom bool, eachEntryFn func(dir string, entry *filer_pb.Entry)) (err error) {
  352. if prefix == "/" && delimiter == "/" {
  353. return
  354. }
  355. request := &filer_pb.ListEntriesRequest{
  356. Directory: dir,
  357. Prefix: prefix,
  358. Limit: uint32(cursor.maxKeys) + 1,
  359. StartFromFileName: marker,
  360. InclusiveStartFrom: inclusiveStartFrom,
  361. Recursive: true,
  362. Delimiter: delimiter == "/",
  363. }
  364. ctx, cancel := context.WithCancel(context.Background())
  365. defer cancel()
  366. stream, listErr := client.ListEntries(ctx, request)
  367. if listErr != nil {
  368. return fmt.Errorf("list entires %+v: %v", request, listErr)
  369. }
  370. for {
  371. resp, recvErr := stream.Recv()
  372. if recvErr != nil {
  373. if recvErr == io.EOF {
  374. break
  375. } else {
  376. return fmt.Errorf("iterating entires %+v: %v", request, recvErr)
  377. }
  378. }
  379. eachEntryFn(resp.Path, resp.Entry)
  380. }
  381. return
  382. }
  383. func (s3a *S3ApiServer) doListFilerEntries(client filer_pb.SeaweedFilerClient, dir, prefix string, cursor *ListingCursor, marker, delimiter string, inclusiveStartFrom bool, eachEntryFn func(dir string, entry *filer_pb.Entry)) (nextMarker string, err error) {
  384. // invariants
  385. // prefix and marker should be under dir, marker may contain "/"
  386. // maxKeys should be updated for each recursion
  387. // glog.V(4).Infof("doListFilerEntries dir: %s, prefix: %s, marker %s, maxKeys: %d, prefixEndsOnDelimiter: %+v", dir, prefix, marker, cursor.maxKeys, cursor.prefixEndsOnDelimiter)
  388. if prefix == "/" && delimiter == "/" {
  389. return
  390. }
  391. if cursor.maxKeys <= 0 {
  392. return
  393. }
  394. if strings.Contains(marker, "/") {
  395. subDir, subMarker := toParentAndDescendants(marker)
  396. // println("doListFilerEntries dir", dir+"/"+subDir, "subMarker", subMarker)
  397. subNextMarker, subErr := s3a.doListFilerEntries(client, dir+"/"+subDir, "", cursor, subMarker, delimiter, false, eachEntryFn)
  398. if subErr != nil {
  399. err = subErr
  400. return
  401. }
  402. nextMarker = subDir + "/" + subNextMarker
  403. // finished processing this subdirectory
  404. marker = subDir
  405. }
  406. if cursor.isTruncated {
  407. return
  408. }
  409. // now marker is also a direct child of dir
  410. request := &filer_pb.ListEntriesRequest{
  411. Directory: dir,
  412. Prefix: prefix,
  413. Limit: uint32(cursor.maxKeys + 2), // bucket root directory needs to skip additional s3_constants.MultipartUploadsFolder folder
  414. StartFromFileName: marker,
  415. InclusiveStartFrom: inclusiveStartFrom,
  416. }
  417. if cursor.prefixEndsOnDelimiter {
  418. request.Limit = uint32(1)
  419. }
  420. ctx, cancel := context.WithCancel(context.Background())
  421. defer cancel()
  422. stream, listErr := client.ListEntries(ctx, request)
  423. if listErr != nil {
  424. err = fmt.Errorf("list entires %+v: %v", request, listErr)
  425. return
  426. }
  427. for {
  428. resp, recvErr := stream.Recv()
  429. if recvErr != nil {
  430. if recvErr == io.EOF {
  431. break
  432. } else {
  433. err = fmt.Errorf("iterating entires %+v: %v", request, recvErr)
  434. return
  435. }
  436. }
  437. if cursor.maxKeys <= 0 {
  438. cursor.isTruncated = true
  439. continue
  440. }
  441. entry := resp.Entry
  442. nextMarker = entry.Name
  443. if cursor.prefixEndsOnDelimiter {
  444. if entry.Name == prefix && entry.IsDirectory {
  445. if delimiter != "/" {
  446. cursor.prefixEndsOnDelimiter = false
  447. }
  448. } else {
  449. continue
  450. }
  451. }
  452. if entry.IsDirectory {
  453. // glog.V(4).Infof("List Dir Entries %s, file: %s, maxKeys %d", dir, entry.Name, cursor.maxKeys)
  454. if entry.Name == s3_constants.MultipartUploadsFolder { // FIXME no need to apply to all directories. this extra also affects maxKeys
  455. continue
  456. }
  457. if delimiter != "/" || cursor.prefixEndsOnDelimiter {
  458. if cursor.prefixEndsOnDelimiter {
  459. cursor.prefixEndsOnDelimiter = false
  460. if entry.IsDirectoryKeyObject() {
  461. eachEntryFn(dir, entry)
  462. }
  463. } else {
  464. eachEntryFn(dir, entry)
  465. }
  466. subNextMarker, subErr := s3a.doListFilerEntries(client, dir+"/"+entry.Name, "", cursor, "", delimiter, false, eachEntryFn)
  467. if subErr != nil {
  468. err = fmt.Errorf("doListFilerEntries2: %v", subErr)
  469. return
  470. }
  471. // println("doListFilerEntries2 dir", dir+"/"+entry.Name, "subNextMarker", subNextMarker)
  472. nextMarker = entry.Name + "/" + subNextMarker
  473. if cursor.isTruncated {
  474. return
  475. }
  476. // println("doListFilerEntries2 nextMarker", nextMarker)
  477. } else {
  478. var isEmpty bool
  479. if !s3a.option.AllowEmptyFolder && entry.IsOlderDir() {
  480. //if isEmpty, err = s3a.ensureDirectoryAllEmpty(client, dir, entry.Name); err != nil {
  481. // glog.Errorf("check empty folder %s: %v", dir, err)
  482. //}
  483. }
  484. if !isEmpty {
  485. eachEntryFn(dir, entry)
  486. }
  487. }
  488. } else {
  489. eachEntryFn(dir, entry)
  490. // glog.V(4).Infof("List File Entries %s, file: %s, maxKeys %d", dir, entry.Name, cursor.maxKeys)
  491. }
  492. if cursor.prefixEndsOnDelimiter {
  493. cursor.prefixEndsOnDelimiter = false
  494. }
  495. }
  496. return
  497. }
  498. func getListObjectsV2Args(values url.Values) (prefix, startAfter, delimiter string, token OptionalString, encodingTypeUrl bool, fetchOwner bool, maxkeys uint16) {
  499. prefix = values.Get("prefix")
  500. token = OptionalString{set: values.Has("continuation-token"), string: values.Get("continuation-token")}
  501. startAfter = values.Get("start-after")
  502. delimiter = values.Get("delimiter")
  503. encodingTypeUrl = values.Get("encoding-type") == s3.EncodingTypeUrl
  504. if values.Get("max-keys") != "" {
  505. if maxKeys, err := strconv.ParseUint(values.Get("max-keys"), 10, 16); err == nil {
  506. maxkeys = uint16(maxKeys)
  507. }
  508. } else {
  509. maxkeys = maxObjectListSizeLimit
  510. }
  511. fetchOwner = values.Get("fetch-owner") == "true"
  512. return
  513. }
  514. func getListObjectsV1Args(values url.Values) (prefix, marker, delimiter string, encodingTypeUrl bool, maxkeys int16) {
  515. prefix = values.Get("prefix")
  516. marker = values.Get("marker")
  517. delimiter = values.Get("delimiter")
  518. encodingTypeUrl = values.Get("encoding-type") == "url"
  519. if values.Get("max-keys") != "" {
  520. if maxKeys, err := strconv.ParseInt(values.Get("max-keys"), 10, 16); err == nil {
  521. maxkeys = int16(maxKeys)
  522. }
  523. } else {
  524. maxkeys = maxObjectListSizeLimit
  525. }
  526. return
  527. }
  528. func (s3a *S3ApiServer) ensureDirectoryAllEmpty(filerClient filer_pb.SeaweedFilerClient, parentDir, name string) (isEmpty bool, err error) {
  529. // println("+ ensureDirectoryAllEmpty", dir, name)
  530. glog.V(4).Infof("+ isEmpty %s/%s", parentDir, name)
  531. defer glog.V(4).Infof("- isEmpty %s/%s %v", parentDir, name, isEmpty)
  532. var fileCounter int
  533. var subDirs []string
  534. currentDir := parentDir + "/" + name
  535. var startFrom string
  536. var isExhausted bool
  537. var foundEntry bool
  538. for fileCounter == 0 && !isExhausted && err == nil {
  539. err = filer_pb.SeaweedList(filerClient, currentDir, "", func(entry *filer_pb.Entry, isLast bool) error {
  540. foundEntry = true
  541. if entry.IsOlderDir() {
  542. subDirs = append(subDirs, entry.Name)
  543. } else {
  544. fileCounter++
  545. }
  546. startFrom = entry.Name
  547. isExhausted = isExhausted || isLast
  548. glog.V(4).Infof(" * %s/%s isLast: %t", currentDir, startFrom, isLast)
  549. return nil
  550. }, startFrom, false, 8)
  551. if !foundEntry {
  552. break
  553. }
  554. }
  555. if err != nil {
  556. return false, err
  557. }
  558. if fileCounter > 0 {
  559. return false, nil
  560. }
  561. for _, subDir := range subDirs {
  562. isSubEmpty, subErr := s3a.ensureDirectoryAllEmpty(filerClient, currentDir, subDir)
  563. if subErr != nil {
  564. return false, subErr
  565. }
  566. if !isSubEmpty {
  567. return false, nil
  568. }
  569. }
  570. glog.V(1).Infof("deleting empty folder %s", currentDir)
  571. if err = doDeleteEntry(filerClient, parentDir, name, true, false); err != nil {
  572. return
  573. }
  574. return true, nil
  575. }