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
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
8 months ago
8 months ago
9 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
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
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. "sort"
  15. "strconv"
  16. "strings"
  17. )
  18. type OptionalString struct {
  19. string
  20. set bool
  21. }
  22. func (o OptionalString) MarshalXML(e *xml.Encoder, startElement xml.StartElement) error {
  23. if !o.set {
  24. return nil
  25. }
  26. return e.EncodeElement(o.string, startElement)
  27. }
  28. type ListBucketResultV2 struct {
  29. XMLName xml.Name `xml:"http://s3.amazonaws.com/doc/2006-03-01/ ListBucketResult"`
  30. Name string `xml:"Name"`
  31. Prefix string `xml:"Prefix"`
  32. MaxKeys uint16 `xml:"MaxKeys"`
  33. Delimiter string `xml:"Delimiter,omitempty"`
  34. IsTruncated bool `xml:"IsTruncated"`
  35. Contents []ListEntry `xml:"Contents,omitempty"`
  36. CommonPrefixes []PrefixEntry `xml:"CommonPrefixes,omitempty"`
  37. ContinuationToken OptionalString `xml:"ContinuationToken,omitempty"`
  38. NextContinuationToken string `xml:"NextContinuationToken,omitempty"`
  39. EncodingType string `xml:"EncodingType,omitempty"`
  40. KeyCount int `xml:"KeyCount"`
  41. StartAfter string `xml:"StartAfter,omitempty"`
  42. }
  43. func (s3a *S3ApiServer) ListObjectsV2Handler(w http.ResponseWriter, r *http.Request) {
  44. // https://docs.aws.amazon.com/AmazonS3/latest/API/v2-RESTBucketGET.html
  45. // collect parameters
  46. bucket, _ := s3_constants.GetBucketAndObject(r)
  47. glog.V(0).Infof("ListObjectsV2Handler %s query %+v", bucket, r.URL.Query())
  48. originalPrefix, startAfter, delimiter, continuationToken, encodingTypeUrl, fetchOwner, maxKeys := getListObjectsV2Args(r.URL.Query())
  49. if maxKeys < 0 {
  50. s3err.WriteErrorResponse(w, r, s3err.ErrInvalidMaxKeys)
  51. return
  52. }
  53. marker := continuationToken.string
  54. if !continuationToken.set {
  55. marker = startAfter
  56. }
  57. response, err := s3a.listFilerEntries(bucket, originalPrefix, maxKeys, marker, delimiter, encodingTypeUrl, fetchOwner)
  58. if err != nil {
  59. s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
  60. return
  61. }
  62. if len(response.Contents) == 0 {
  63. if exists, existErr := s3a.exists(s3a.option.BucketsPath, bucket, true); existErr == nil && !exists {
  64. s3err.WriteErrorResponse(w, r, s3err.ErrNoSuchBucket)
  65. return
  66. }
  67. }
  68. responseV2 := &ListBucketResultV2{
  69. XMLName: response.XMLName,
  70. Name: response.Name,
  71. CommonPrefixes: response.CommonPrefixes,
  72. Contents: response.Contents,
  73. ContinuationToken: continuationToken,
  74. Delimiter: response.Delimiter,
  75. IsTruncated: response.IsTruncated,
  76. KeyCount: len(response.Contents) + len(response.CommonPrefixes),
  77. MaxKeys: response.MaxKeys,
  78. NextContinuationToken: response.NextMarker,
  79. Prefix: response.Prefix,
  80. StartAfter: startAfter,
  81. }
  82. if encodingTypeUrl {
  83. responseV2.EncodingType = s3.EncodingTypeUrl
  84. }
  85. writeSuccessResponseXML(w, r, responseV2)
  86. }
  87. func (s3a *S3ApiServer) ListObjectsV1Handler(w http.ResponseWriter, r *http.Request) {
  88. // https://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketGET.html
  89. // collect parameters
  90. bucket, _ := s3_constants.GetBucketAndObject(r)
  91. glog.V(0).Infof("ListObjectsV1Handler %s query %+v", bucket, r.URL.Query())
  92. originalPrefix, marker, delimiter, encodingTypeUrl, maxKeys := getListObjectsV1Args(r.URL.Query())
  93. if maxKeys < 0 {
  94. s3err.WriteErrorResponse(w, r, s3err.ErrInvalidMaxKeys)
  95. return
  96. }
  97. response, err := s3a.listFilerEntries(bucket, originalPrefix, uint16(maxKeys), marker, delimiter, encodingTypeUrl, true)
  98. if err != nil {
  99. s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
  100. return
  101. }
  102. if len(response.Contents) == 0 {
  103. if exists, existErr := s3a.exists(s3a.option.BucketsPath, bucket, true); existErr == nil && !exists {
  104. s3err.WriteErrorResponse(w, r, s3err.ErrNoSuchBucket)
  105. return
  106. }
  107. }
  108. writeSuccessResponseXML(w, r, response)
  109. }
  110. func (s3a *S3ApiServer) listFilerEntries(bucket string, originalPrefix string, maxKeys uint16, originalMarker string, delimiter string, encodingTypeUrl bool, fetchOwner bool) (response ListBucketResult, err error) {
  111. // convert full path prefix into directory name and prefix for entry name
  112. requestDir, prefix, marker := normalizePrefixMarker(originalPrefix, originalMarker)
  113. bucketPrefix := fmt.Sprintf("%s/%s/", s3a.option.BucketsPath, bucket)
  114. reqDir := bucketPrefix[:len(bucketPrefix)-1]
  115. if requestDir != "" {
  116. reqDir = fmt.Sprintf("%s%s", bucketPrefix, requestDir)
  117. }
  118. var contents []ListEntry
  119. var commonPrefixes []PrefixEntry
  120. var doErr error
  121. var nextMarker string
  122. cursor := &ListingCursor{
  123. maxKeys: maxKeys,
  124. prefixEndsOnDelimiter: strings.HasSuffix(originalPrefix, "/") && len(originalMarker) == 0,
  125. }
  126. if s3a.option.AllowListRecursive && (delimiter == "" || delimiter == "/") {
  127. reqDir = bucketPrefix
  128. if idx := strings.LastIndex(originalPrefix, "/"); idx > 0 {
  129. reqDir += originalPrefix[:idx]
  130. prefix = originalPrefix[idx+1:]
  131. }
  132. // This is necessary for SQL request with WHERE `directory` || `name` > originalMarker
  133. if len(originalMarker) > 0 && originalMarker[0:1] != "/" {
  134. if idx := strings.LastIndex(originalMarker, "/"); idx == -1 {
  135. marker = "/" + originalMarker
  136. } else {
  137. marker = fmt.Sprintf("/%s%s", originalMarker[0:idx], originalMarker[idx+1:len(originalMarker)])
  138. }
  139. } else {
  140. marker = originalMarker
  141. }
  142. response = ListBucketResult{
  143. Name: bucket,
  144. Prefix: originalPrefix,
  145. Marker: originalMarker,
  146. MaxKeys: maxKeys,
  147. Delimiter: delimiter,
  148. }
  149. if encodingTypeUrl {
  150. response.EncodingType = s3.EncodingTypeUrl
  151. }
  152. if maxKeys == 0 {
  153. return
  154. }
  155. glog.V(0).Infof("listFilerEntries reqDir: %s, prefix: %s[%s], delimiter: %v, cursor: %+v, mmarker: %s[%s]", reqDir, prefix, originalPrefix, delimiter, cursor, marker, originalMarker)
  156. err = s3a.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
  157. doErr = s3a.doListFilerRecursiveEntries(client, reqDir, prefix, cursor, marker, delimiter, false,
  158. func(path string, entry *filer_pb.Entry) {
  159. isCommonDir := strings.Index(path[len(reqDir)+1:], "/") != -1
  160. key := path[len(bucketPrefix):]
  161. glog.V(0).Infof("doListFilerRecursiveEntries path %s, shortDir %s, key: %+v, cursor: %+v, marker: %s[%s], nextMarker: %s, isCommonDir %v", path, path[len(reqDir):], key, cursor, marker, originalMarker, cursor.nextMarker, isCommonDir)
  162. if cursor.isTruncated {
  163. nextMarker = cursor.nextMarker
  164. return
  165. }
  166. defer func() {
  167. if cursor.maxKeys == 0 {
  168. cursor.isTruncated = true
  169. if idx := strings.Index(key, "/"); idx == -1 {
  170. cursor.nextMarker = "/" + key
  171. } else {
  172. cursor.nextMarker = fmt.Sprintf("/%s%s", key[0:idx], key[idx+1:len(key)])
  173. }
  174. }
  175. }()
  176. if delimiter == "/" && entry.IsDirectory {
  177. commonPrefixes = append(commonPrefixes, PrefixEntry{
  178. Prefix: path[len(bucketPrefix):] + "/",
  179. })
  180. cursor.maxKeys--
  181. return
  182. }
  183. contents = append(contents, newListEntry(entry, key, "", "", bucketPrefix, fetchOwner, entry.IsDirectoryKeyObject()))
  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. glog.V(0).Infof("doListFilerEntries dir: %s entry: %+v", dir, entry)
  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))
  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))
  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. sort.Slice(response.CommonPrefixes, func(i, j int) bool {
  277. return response.CommonPrefixes[i].Prefix < response.CommonPrefixes[j].Prefix
  278. })
  279. response.EncodingType = s3.EncodingTypeUrl
  280. }
  281. return nil
  282. })
  283. return
  284. }
  285. type ListingCursor struct {
  286. maxKeys uint16
  287. isTruncated bool
  288. prefixEndsOnDelimiter bool
  289. nextMarker string
  290. }
  291. func (l *ListingCursor) Decrease() {
  292. l.maxKeys--
  293. if l.maxKeys == 0 {
  294. l.isTruncated = true
  295. }
  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(0).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. }