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.

314 lines
7.8 KiB

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