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.

479 lines
14 KiB

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
5 years ago
3 years 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/seaweedfs/seaweedfs/weed/glog"
  7. "github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
  8. "io"
  9. "net/http"
  10. "net/url"
  11. "strconv"
  12. "strings"
  13. "time"
  14. "github.com/seaweedfs/seaweedfs/weed/filer"
  15. "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
  16. "github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
  17. )
  18. const cutoffTimeNewEmptyDir = 3
  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. _, errCode := s3a.checkAccessForReadBucket(r, bucket, s3_constants.PermissionRead)
  39. if errCode != s3err.ErrNone {
  40. s3err.WriteErrorResponse(w, r, errCode)
  41. return
  42. }
  43. originalPrefix, continuationToken, startAfter, delimiter, _, maxKeys := getListObjectsV2Args(r.URL.Query())
  44. if maxKeys < 0 {
  45. s3err.WriteErrorResponse(w, r, s3err.ErrInvalidMaxKeys)
  46. return
  47. }
  48. if delimiter != "" && delimiter != "/" {
  49. s3err.WriteErrorResponse(w, r, s3err.ErrNotImplemented)
  50. return
  51. }
  52. marker := continuationToken
  53. if continuationToken == "" {
  54. marker = startAfter
  55. }
  56. response, err := s3a.listFilerEntries(bucket, originalPrefix, maxKeys, marker, delimiter)
  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. writeSuccessResponseXML(w, r, responseV2)
  82. }
  83. func (s3a *S3ApiServer) ListObjectsV1Handler(w http.ResponseWriter, r *http.Request) {
  84. // https://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketGET.html
  85. // collect parameters
  86. bucket, _ := s3_constants.GetBucketAndObject(r)
  87. glog.V(3).Infof("ListObjectsV1Handler %s", bucket)
  88. _, errCode := s3a.checkAccessForReadBucket(r, bucket, s3_constants.PermissionRead)
  89. if errCode != s3err.ErrNone {
  90. s3err.WriteErrorResponse(w, r, errCode)
  91. return
  92. }
  93. originalPrefix, marker, delimiter, maxKeys := getListObjectsV1Args(r.URL.Query())
  94. if maxKeys < 0 {
  95. s3err.WriteErrorResponse(w, r, s3err.ErrInvalidMaxKeys)
  96. return
  97. }
  98. if delimiter != "" && delimiter != "/" {
  99. s3err.WriteErrorResponse(w, r, s3err.ErrNotImplemented)
  100. return
  101. }
  102. response, err := s3a.listFilerEntries(bucket, originalPrefix, maxKeys, marker, delimiter)
  103. if err != nil {
  104. s3err.WriteErrorResponse(w, r, s3err.ErrInternalError)
  105. return
  106. }
  107. if len(response.Contents) == 0 {
  108. if exists, existErr := s3a.exists(s3a.option.BucketsPath, bucket, true); existErr == nil && !exists {
  109. s3err.WriteErrorResponse(w, r, s3err.ErrNoSuchBucket)
  110. return
  111. }
  112. }
  113. writeSuccessResponseXML(w, r, response)
  114. }
  115. func (s3a *S3ApiServer) listFilerEntries(bucket string, originalPrefix string, maxKeys int, originalMarker string, delimiter string) (response ListBucketResult, err error) {
  116. // convert full path prefix into directory name and prefix for entry name
  117. requestDir, prefix, marker := normalizePrefixMarker(originalPrefix, originalMarker)
  118. bucketPrefix := fmt.Sprintf("%s/%s/", s3a.option.BucketsPath, bucket)
  119. reqDir := bucketPrefix[:len(bucketPrefix)-1]
  120. if requestDir != "" {
  121. reqDir = fmt.Sprintf("%s%s", bucketPrefix, requestDir)
  122. }
  123. var contents []ListEntry
  124. var commonPrefixes []PrefixEntry
  125. var doErr error
  126. var nextMarker string
  127. cursor := &ListingCursor{
  128. maxKeys: maxKeys,
  129. }
  130. // check filer
  131. err = s3a.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
  132. for {
  133. empty := true
  134. nextMarker, doErr = s3a.doListFilerEntries(client, reqDir, prefix, cursor, marker, delimiter, false, func(dir string, entry *filer_pb.Entry) {
  135. empty = false
  136. if entry.IsDirectory {
  137. // https://docs.aws.amazon.com/AmazonS3/latest/API/API_ListObjectsV2.html
  138. if delimiter == "/" { // A response can contain CommonPrefixes only if you specify a delimiter.
  139. commonPrefixes = append(commonPrefixes, PrefixEntry{
  140. Prefix: fmt.Sprintf("%s/%s/", dir, entry.Name)[len(bucketPrefix):],
  141. })
  142. //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.
  143. cursor.maxKeys--
  144. } else if entry.IsDirectoryKeyObject() {
  145. contents = append(contents, ListEntry{
  146. Key: fmt.Sprintf("%s/%s/", dir, entry.Name)[len(bucketPrefix):],
  147. LastModified: time.Unix(entry.Attributes.Mtime, 0).UTC(),
  148. ETag: "\"" + filer.ETag(entry) + "\"",
  149. Owner: CanonicalUser{
  150. ID: fmt.Sprintf("%x", entry.Attributes.Uid),
  151. DisplayName: entry.Attributes.UserName,
  152. },
  153. StorageClass: "STANDARD",
  154. })
  155. cursor.maxKeys--
  156. }
  157. } else {
  158. storageClass := "STANDARD"
  159. if v, ok := entry.Extended[s3_constants.AmzStorageClass]; ok {
  160. storageClass = string(v)
  161. }
  162. contents = append(contents, ListEntry{
  163. Key: fmt.Sprintf("%s/%s", dir, entry.Name)[len(bucketPrefix):],
  164. LastModified: time.Unix(entry.Attributes.Mtime, 0).UTC(),
  165. ETag: "\"" + filer.ETag(entry) + "\"",
  166. Size: int64(filer.FileSize(entry)),
  167. Owner: CanonicalUser{
  168. ID: fmt.Sprintf("%x", entry.Attributes.Uid),
  169. DisplayName: entry.Attributes.UserName,
  170. },
  171. StorageClass: StorageClass(storageClass),
  172. })
  173. cursor.maxKeys--
  174. }
  175. })
  176. if doErr != nil {
  177. return doErr
  178. }
  179. if cursor.isTruncated {
  180. if requestDir != "" {
  181. nextMarker = requestDir + "/" + nextMarker
  182. }
  183. break
  184. } else if empty {
  185. nextMarker = ""
  186. break
  187. } else {
  188. // start next loop
  189. marker = nextMarker
  190. }
  191. }
  192. response = ListBucketResult{
  193. Name: bucket,
  194. Prefix: originalPrefix,
  195. Marker: originalMarker,
  196. NextMarker: nextMarker,
  197. MaxKeys: maxKeys,
  198. Delimiter: delimiter,
  199. IsTruncated: cursor.isTruncated,
  200. Contents: contents,
  201. CommonPrefixes: commonPrefixes,
  202. }
  203. return nil
  204. })
  205. return
  206. }
  207. type ListingCursor struct {
  208. maxKeys int
  209. isTruncated bool
  210. }
  211. // the prefix and marker may be in different directories
  212. // normalizePrefixMarker ensures the prefix and marker both starts from the same directory
  213. func normalizePrefixMarker(prefix, marker string) (alignedDir, alignedPrefix, alignedMarker string) {
  214. // alignedDir should not end with "/"
  215. // alignedDir, alignedPrefix, alignedMarker should only have "/" in middle
  216. prefix = strings.TrimLeft(prefix, "/")
  217. marker = strings.TrimLeft(marker, "/")
  218. if prefix == "" {
  219. return "", "", marker
  220. }
  221. if marker == "" {
  222. alignedDir, alignedPrefix = toDirAndName(prefix)
  223. return
  224. }
  225. if !strings.HasPrefix(marker, prefix) {
  226. // something wrong
  227. return "", prefix, marker
  228. }
  229. if strings.HasPrefix(marker, prefix+"/") {
  230. alignedDir = prefix
  231. alignedPrefix = ""
  232. alignedMarker = marker[len(alignedDir)+1:]
  233. return
  234. }
  235. alignedDir, alignedPrefix = toDirAndName(prefix)
  236. if alignedDir != "" {
  237. alignedMarker = marker[len(alignedDir)+1:]
  238. } else {
  239. alignedMarker = marker
  240. }
  241. return
  242. }
  243. func toDirAndName(dirAndName string) (dir, name string) {
  244. sepIndex := strings.LastIndex(dirAndName, "/")
  245. if sepIndex >= 0 {
  246. dir, name = dirAndName[0:sepIndex], dirAndName[sepIndex+1:]
  247. } else {
  248. name = dirAndName
  249. }
  250. return
  251. }
  252. func toParentAndDescendants(dirAndName string) (dir, name string) {
  253. sepIndex := strings.Index(dirAndName, "/")
  254. if sepIndex >= 0 {
  255. dir, name = dirAndName[0:sepIndex], dirAndName[sepIndex+1:]
  256. } else {
  257. name = dirAndName
  258. }
  259. return
  260. }
  261. 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) {
  262. // invariants
  263. // prefix and marker should be under dir, marker may contain "/"
  264. // maxKeys should be updated for each recursion
  265. if prefix == "/" && delimiter == "/" {
  266. return
  267. }
  268. if cursor.maxKeys <= 0 {
  269. return
  270. }
  271. if strings.Contains(marker, "/") {
  272. subDir, subMarker := toParentAndDescendants(marker)
  273. // println("doListFilerEntries dir", dir+"/"+subDir, "subMarker", subMarker)
  274. subNextMarker, subErr := s3a.doListFilerEntries(client, dir+"/"+subDir, "", cursor, subMarker, delimiter, false, eachEntryFn)
  275. if subErr != nil {
  276. err = subErr
  277. return
  278. }
  279. nextMarker = subDir + "/" + subNextMarker
  280. // finished processing this sub directory
  281. marker = subDir
  282. }
  283. if cursor.isTruncated {
  284. return
  285. }
  286. // now marker is also a direct child of dir
  287. request := &filer_pb.ListEntriesRequest{
  288. Directory: dir,
  289. Prefix: prefix,
  290. Limit: uint32(cursor.maxKeys + 2), // bucket root directory needs to skip additional s3_constants.MultipartUploadsFolder folder
  291. StartFromFileName: marker,
  292. InclusiveStartFrom: inclusiveStartFrom,
  293. }
  294. ctx, cancel := context.WithCancel(context.Background())
  295. defer cancel()
  296. stream, listErr := client.ListEntries(ctx, request)
  297. if listErr != nil {
  298. err = fmt.Errorf("list entires %+v: %v", request, listErr)
  299. return
  300. }
  301. for {
  302. resp, recvErr := stream.Recv()
  303. if recvErr != nil {
  304. if recvErr == io.EOF {
  305. break
  306. } else {
  307. err = fmt.Errorf("iterating entires %+v: %v", request, recvErr)
  308. return
  309. }
  310. }
  311. if cursor.maxKeys <= 0 {
  312. cursor.isTruncated = true
  313. return
  314. }
  315. entry := resp.Entry
  316. nextMarker = entry.Name
  317. if entry.IsDirectory {
  318. // println("ListEntries", dir, "dir:", entry.Name)
  319. if entry.Name == s3_constants.MultipartUploadsFolder { // FIXME no need to apply to all directories. this extra also affects maxKeys
  320. continue
  321. }
  322. if delimiter != "/" {
  323. eachEntryFn(dir, entry)
  324. subNextMarker, subErr := s3a.doListFilerEntries(client, dir+"/"+entry.Name, "", cursor, "", delimiter, false, eachEntryFn)
  325. if subErr != nil {
  326. err = fmt.Errorf("doListFilerEntries2: %v", subErr)
  327. return
  328. }
  329. // println("doListFilerEntries2 dir", dir+"/"+entry.Name, "subNextMarker", subNextMarker)
  330. nextMarker = entry.Name + "/" + subNextMarker
  331. if cursor.isTruncated {
  332. return
  333. }
  334. // println("doListFilerEntries2 nextMarker", nextMarker)
  335. } else {
  336. var isEmpty bool
  337. if !s3a.option.AllowEmptyFolder && !entry.IsDirectoryKeyObject() {
  338. if isEmpty, err = s3a.ensureDirectoryAllEmpty(client, dir, entry.Name); err != nil {
  339. glog.Errorf("check empty folder %s: %v", dir, err)
  340. }
  341. }
  342. if !isEmpty {
  343. eachEntryFn(dir, entry)
  344. }
  345. }
  346. } else {
  347. eachEntryFn(dir, entry)
  348. // println("ListEntries", dir, "file:", entry.Name, "maxKeys", cursor.maxKeys)
  349. }
  350. }
  351. return
  352. }
  353. func getListObjectsV2Args(values url.Values) (prefix, token, startAfter, delimiter string, fetchOwner bool, maxkeys int) {
  354. prefix = values.Get("prefix")
  355. token = values.Get("continuation-token")
  356. startAfter = values.Get("start-after")
  357. delimiter = values.Get("delimiter")
  358. if values.Get("max-keys") != "" {
  359. maxkeys, _ = strconv.Atoi(values.Get("max-keys"))
  360. } else {
  361. maxkeys = maxObjectListSizeLimit
  362. }
  363. fetchOwner = values.Get("fetch-owner") == "true"
  364. return
  365. }
  366. func getListObjectsV1Args(values url.Values) (prefix, marker, delimiter string, maxkeys int) {
  367. prefix = values.Get("prefix")
  368. marker = values.Get("marker")
  369. delimiter = values.Get("delimiter")
  370. if values.Get("max-keys") != "" {
  371. maxkeys, _ = strconv.Atoi(values.Get("max-keys"))
  372. } else {
  373. maxkeys = maxObjectListSizeLimit
  374. }
  375. return
  376. }
  377. func (s3a *S3ApiServer) ensureDirectoryAllEmpty(filerClient filer_pb.SeaweedFilerClient, parentDir, name string) (isEmpty bool, err error) {
  378. // println("+ ensureDirectoryAllEmpty", dir, name)
  379. glog.V(4).Infof("+ isEmpty %s/%s", parentDir, name)
  380. defer glog.V(4).Infof("- isEmpty %s/%s %v", parentDir, name, isEmpty)
  381. var fileCounter int
  382. var subDirs []string
  383. currentDir := parentDir + "/" + name
  384. var startFrom string
  385. var isExhausted bool
  386. var foundEntry bool
  387. cutOffTimeAtSec := time.Now().Unix() + cutoffTimeNewEmptyDir
  388. for fileCounter == 0 && !isExhausted && err == nil {
  389. err = filer_pb.SeaweedList(filerClient, currentDir, "", func(entry *filer_pb.Entry, isLast bool) error {
  390. foundEntry = true
  391. if entry.IsDirectory {
  392. if entry.Attributes != nil && cutOffTimeAtSec >= entry.Attributes.GetCrtime() {
  393. fileCounter++
  394. } else {
  395. subDirs = append(subDirs, entry.Name)
  396. }
  397. } else {
  398. fileCounter++
  399. }
  400. startFrom = entry.Name
  401. isExhausted = isExhausted || isLast
  402. glog.V(4).Infof(" * %s/%s isLast: %t", currentDir, startFrom, isLast)
  403. return nil
  404. }, startFrom, false, 8)
  405. if !foundEntry {
  406. break
  407. }
  408. }
  409. if err != nil {
  410. return false, err
  411. }
  412. if fileCounter > 0 {
  413. return false, nil
  414. }
  415. for _, subDir := range subDirs {
  416. isSubEmpty, subErr := s3a.ensureDirectoryAllEmpty(filerClient, currentDir, subDir)
  417. if subErr != nil {
  418. return false, subErr
  419. }
  420. if !isSubEmpty {
  421. return false, nil
  422. }
  423. }
  424. glog.V(1).Infof("deleting empty folder %s", currentDir)
  425. if err = doDeleteEntry(filerClient, parentDir, name, true, true); err != nil {
  426. return
  427. }
  428. return true, nil
  429. }