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.

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