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.

313 lines
7.9 KiB

6 years ago
7 years ago
7 years ago
7 years ago
5 years ago
5 years ago
6 years ago
5 years ago
6 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
  1. package s3api
  2. import (
  3. "crypto/md5"
  4. "encoding/json"
  5. "encoding/xml"
  6. "fmt"
  7. "io"
  8. "io/ioutil"
  9. "net/http"
  10. "strings"
  11. "github.com/gorilla/mux"
  12. "github.com/chrislusf/seaweedfs/weed/glog"
  13. "github.com/chrislusf/seaweedfs/weed/pb/filer_pb"
  14. weed_server "github.com/chrislusf/seaweedfs/weed/server"
  15. "github.com/chrislusf/seaweedfs/weed/util"
  16. )
  17. var (
  18. client *http.Client
  19. )
  20. func init() {
  21. client = &http.Client{Transport: &http.Transport{
  22. MaxIdleConnsPerHost: 1024,
  23. }}
  24. }
  25. func (s3a *S3ApiServer) PutObjectHandler(w http.ResponseWriter, r *http.Request) {
  26. // http://docs.aws.amazon.com/AmazonS3/latest/dev/UploadingObjects.html
  27. bucket, object := getBucketAndObject(r)
  28. _, err := validateContentMd5(r.Header)
  29. if err != nil {
  30. writeErrorResponse(w, ErrInvalidDigest, r.URL)
  31. return
  32. }
  33. rAuthType := getRequestAuthType(r)
  34. dataReader := r.Body
  35. var s3ErrCode ErrorCode
  36. switch rAuthType {
  37. case authTypeStreamingSigned:
  38. dataReader, s3ErrCode = s3a.iam.newSignV4ChunkedReader(r)
  39. case authTypeSignedV2, authTypePresignedV2:
  40. _, s3ErrCode = s3a.iam.isReqAuthenticatedV2(r)
  41. case authTypePresigned, authTypeSigned:
  42. _, s3ErrCode = s3a.iam.reqSignatureV4Verify(r)
  43. }
  44. if s3ErrCode != ErrNone {
  45. writeErrorResponse(w, s3ErrCode, r.URL)
  46. return
  47. }
  48. defer dataReader.Close()
  49. uploadUrl := fmt.Sprintf("http://%s%s/%s%s", s3a.option.Filer, s3a.option.BucketsPath, bucket, object)
  50. etag, errCode := s3a.putToFiler(r, uploadUrl, dataReader)
  51. if errCode != ErrNone {
  52. writeErrorResponse(w, errCode, r.URL)
  53. return
  54. }
  55. setEtag(w, etag)
  56. writeSuccessResponseEmpty(w)
  57. }
  58. func (s3a *S3ApiServer) GetObjectHandler(w http.ResponseWriter, r *http.Request) {
  59. bucket, object := getBucketAndObject(r)
  60. if strings.HasSuffix(r.URL.Path, "/") {
  61. writeErrorResponse(w, ErrNotImplemented, r.URL)
  62. return
  63. }
  64. destUrl := fmt.Sprintf("http://%s%s/%s%s",
  65. s3a.option.Filer, s3a.option.BucketsPath, bucket, object)
  66. s3a.proxyToFiler(w, r, destUrl, passThroughResponse)
  67. }
  68. func (s3a *S3ApiServer) HeadObjectHandler(w http.ResponseWriter, r *http.Request) {
  69. bucket, object := getBucketAndObject(r)
  70. destUrl := fmt.Sprintf("http://%s%s/%s%s",
  71. s3a.option.Filer, s3a.option.BucketsPath, bucket, object)
  72. s3a.proxyToFiler(w, r, destUrl, passThroughResponse)
  73. }
  74. func (s3a *S3ApiServer) DeleteObjectHandler(w http.ResponseWriter, r *http.Request) {
  75. bucket, object := getBucketAndObject(r)
  76. destUrl := fmt.Sprintf("http://%s%s/%s%s?recursive=true",
  77. s3a.option.Filer, s3a.option.BucketsPath, bucket, object)
  78. s3a.proxyToFiler(w, r, destUrl, func(proxyResponse *http.Response, w http.ResponseWriter) {
  79. for k, v := range proxyResponse.Header {
  80. w.Header()[k] = v
  81. }
  82. w.WriteHeader(http.StatusNoContent)
  83. })
  84. }
  85. // / ObjectIdentifier carries key name for the object to delete.
  86. type ObjectIdentifier struct {
  87. ObjectName string `xml:"Key"`
  88. }
  89. // DeleteObjectsRequest - xml carrying the object key names which needs to be deleted.
  90. type DeleteObjectsRequest struct {
  91. // Element to enable quiet mode for the request
  92. Quiet bool
  93. // List of objects to be deleted
  94. Objects []ObjectIdentifier `xml:"Object"`
  95. }
  96. // DeleteError structure.
  97. type DeleteError struct {
  98. Code string
  99. Message string
  100. Key string
  101. }
  102. // DeleteObjectsResponse container for multiple object deletes.
  103. type DeleteObjectsResponse struct {
  104. XMLName xml.Name `xml:"http://s3.amazonaws.com/doc/2006-03-01/ DeleteResult" json:"-"`
  105. // Collection of all deleted objects
  106. DeletedObjects []ObjectIdentifier `xml:"Deleted,omitempty"`
  107. // Collection of errors deleting certain objects.
  108. Errors []DeleteError `xml:"Error,omitempty"`
  109. }
  110. // DeleteMultipleObjectsHandler - Delete multiple objects
  111. func (s3a *S3ApiServer) DeleteMultipleObjectsHandler(w http.ResponseWriter, r *http.Request) {
  112. bucket, _ := getBucketAndObject(r)
  113. deleteXMLBytes, err := ioutil.ReadAll(r.Body)
  114. if err != nil {
  115. writeErrorResponse(w, ErrInternalError, r.URL)
  116. return
  117. }
  118. deleteObjects := &DeleteObjectsRequest{}
  119. if err := xml.Unmarshal(deleteXMLBytes, deleteObjects); err != nil {
  120. writeErrorResponse(w, ErrMalformedXML, r.URL)
  121. return
  122. }
  123. var deletedObjects []ObjectIdentifier
  124. var deleteErrors []DeleteError
  125. s3a.WithFilerClient(func(client filer_pb.SeaweedFilerClient) error {
  126. for _, object := range deleteObjects.Objects {
  127. lastSeparator := strings.LastIndex(object.ObjectName, "/")
  128. parentDirectoryPath, entryName, isDeleteData, isRecursive := "/", object.ObjectName, true, true
  129. if lastSeparator > 0 && lastSeparator+1 < len(object.ObjectName) {
  130. entryName = object.ObjectName[lastSeparator+1:]
  131. parentDirectoryPath = "/" + object.ObjectName[:lastSeparator]
  132. }
  133. parentDirectoryPath = fmt.Sprintf("%s/%s%s", s3a.option.BucketsPath, bucket, parentDirectoryPath)
  134. err := doDeleteEntry(client, parentDirectoryPath, entryName, isDeleteData, isRecursive)
  135. if err == nil {
  136. deletedObjects = append(deletedObjects, object)
  137. } else {
  138. deleteErrors = append(deleteErrors, DeleteError{
  139. Code: "",
  140. Message: err.Error(),
  141. Key: object.ObjectName,
  142. })
  143. }
  144. }
  145. return nil
  146. })
  147. deleteResp := DeleteObjectsResponse{}
  148. if !deleteObjects.Quiet {
  149. deleteResp.DeletedObjects = deletedObjects
  150. }
  151. deleteResp.Errors = deleteErrors
  152. writeSuccessResponseXML(w, encodeResponse(deleteResp))
  153. }
  154. func (s3a *S3ApiServer) proxyToFiler(w http.ResponseWriter, r *http.Request, destUrl string, responseFn func(proxyResponse *http.Response, w http.ResponseWriter)) {
  155. glog.V(2).Infof("s3 proxying %s to %s", r.Method, destUrl)
  156. proxyReq, err := http.NewRequest(r.Method, destUrl, r.Body)
  157. if err != nil {
  158. glog.Errorf("NewRequest %s: %v", destUrl, err)
  159. writeErrorResponse(w, ErrInternalError, r.URL)
  160. return
  161. }
  162. proxyReq.Header.Set("Host", s3a.option.Filer)
  163. proxyReq.Header.Set("X-Forwarded-For", r.RemoteAddr)
  164. for header, values := range r.Header {
  165. for _, value := range values {
  166. proxyReq.Header.Add(header, value)
  167. }
  168. }
  169. resp, postErr := client.Do(proxyReq)
  170. if postErr != nil {
  171. glog.Errorf("post to filer: %v", postErr)
  172. writeErrorResponse(w, ErrInternalError, r.URL)
  173. return
  174. }
  175. defer util.CloseResponse(resp)
  176. responseFn(resp, w)
  177. }
  178. func passThroughResponse(proxyResponse *http.Response, w http.ResponseWriter) {
  179. for k, v := range proxyResponse.Header {
  180. w.Header()[k] = v
  181. }
  182. w.WriteHeader(proxyResponse.StatusCode)
  183. io.Copy(w, proxyResponse.Body)
  184. }
  185. func (s3a *S3ApiServer) putToFiler(r *http.Request, uploadUrl string, dataReader io.Reader) (etag string, code ErrorCode) {
  186. hash := md5.New()
  187. var body = io.TeeReader(dataReader, hash)
  188. proxyReq, err := http.NewRequest("PUT", uploadUrl, body)
  189. if err != nil {
  190. glog.Errorf("NewRequest %s: %v", uploadUrl, err)
  191. return "", ErrInternalError
  192. }
  193. proxyReq.Header.Set("Host", s3a.option.Filer)
  194. proxyReq.Header.Set("X-Forwarded-For", r.RemoteAddr)
  195. for header, values := range r.Header {
  196. for _, value := range values {
  197. proxyReq.Header.Add(header, value)
  198. }
  199. }
  200. resp, postErr := client.Do(proxyReq)
  201. if postErr != nil {
  202. glog.Errorf("post to filer: %v", postErr)
  203. return "", ErrInternalError
  204. }
  205. defer resp.Body.Close()
  206. etag = fmt.Sprintf("%x", hash.Sum(nil))
  207. resp_body, ra_err := ioutil.ReadAll(resp.Body)
  208. if ra_err != nil {
  209. glog.Errorf("upload to filer response read: %v", ra_err)
  210. return etag, ErrInternalError
  211. }
  212. var ret weed_server.FilerPostResult
  213. unmarshal_err := json.Unmarshal(resp_body, &ret)
  214. if unmarshal_err != nil {
  215. glog.Errorf("failing to read upload to %s : %v", uploadUrl, string(resp_body))
  216. return "", ErrInternalError
  217. }
  218. if ret.Error != "" {
  219. glog.Errorf("upload to filer error: %v", ret.Error)
  220. return "", ErrInternalError
  221. }
  222. return etag, ErrNone
  223. }
  224. func setEtag(w http.ResponseWriter, etag string) {
  225. if etag != "" {
  226. if strings.HasPrefix(etag, "\"") {
  227. w.Header().Set("ETag", etag)
  228. } else {
  229. w.Header().Set("ETag", "\""+etag+"\"")
  230. }
  231. }
  232. }
  233. func getBucketAndObject(r *http.Request) (bucket, object string) {
  234. vars := mux.Vars(r)
  235. bucket = vars["bucket"]
  236. object = vars["object"]
  237. if !strings.HasPrefix(object, "/") {
  238. object = "/" + object
  239. }
  240. return
  241. }