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.

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