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.

220 lines
6.3 KiB

6 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
12 years ago
  1. package operation
  2. import (
  3. "bytes"
  4. "crypto/md5"
  5. "encoding/json"
  6. "errors"
  7. "fmt"
  8. "io"
  9. "io/ioutil"
  10. "mime"
  11. "mime/multipart"
  12. "net/http"
  13. "net/textproto"
  14. "path/filepath"
  15. "strings"
  16. "github.com/chrislusf/seaweedfs/weed/glog"
  17. "github.com/chrislusf/seaweedfs/weed/security"
  18. "github.com/chrislusf/seaweedfs/weed/util"
  19. )
  20. type UploadResult struct {
  21. Name string `json:"name,omitempty"`
  22. Size uint32 `json:"size,omitempty"`
  23. Error string `json:"error,omitempty"`
  24. ETag string `json:"eTag,omitempty"`
  25. CipherKey []byte `json:"cipherKey,omitempty"`
  26. Mime string `json:"mime,omitempty"`
  27. Gzip uint32 `json:"gzip,omitempty"`
  28. Md5 string `json:"md5,omitempty"`
  29. }
  30. var (
  31. client *http.Client
  32. )
  33. func init() {
  34. client = &http.Client{Transport: &http.Transport{
  35. MaxIdleConnsPerHost: 1024,
  36. }}
  37. }
  38. var fileNameEscaper = strings.NewReplacer("\\", "\\\\", "\"", "\\\"")
  39. // Upload sends a POST request to a volume server to upload the content with adjustable compression level
  40. func UploadData(uploadUrl string, filename string, cipher bool, data []byte, isInputGzipped bool, mtype string, pairMap map[string]string, jwt security.EncodedJwt) (uploadResult *UploadResult, err error) {
  41. hash := md5.New()
  42. hash.Write(data)
  43. uploadResult, err = doUploadData(uploadUrl, filename, cipher, data, isInputGzipped, mtype, pairMap, jwt)
  44. if uploadResult != nil {
  45. uploadResult.Md5 = fmt.Sprintf("%x", hash.Sum(nil))
  46. }
  47. return
  48. }
  49. // Upload sends a POST request to a volume server to upload the content with fast compression
  50. func Upload(uploadUrl string, filename string, cipher bool, reader io.Reader, isInputGzipped bool, mtype string, pairMap map[string]string, jwt security.EncodedJwt) (uploadResult *UploadResult, err error) {
  51. hash := md5.New()
  52. reader = io.TeeReader(reader, hash)
  53. uploadResult, err = doUpload(uploadUrl, filename, cipher, reader, isInputGzipped, mtype, pairMap, jwt)
  54. if uploadResult != nil {
  55. uploadResult.Md5 = fmt.Sprintf("%x", hash.Sum(nil))
  56. }
  57. return
  58. }
  59. func doUpload(uploadUrl string, filename string, cipher bool, reader io.Reader, isInputGzipped bool, mtype string, pairMap map[string]string, jwt security.EncodedJwt) (uploadResult *UploadResult, err error) {
  60. data, readErr := ioutil.ReadAll(reader)
  61. if readErr != nil {
  62. err = fmt.Errorf("read input: %v", readErr)
  63. return
  64. }
  65. return doUploadData(uploadUrl, filename, cipher, data, isInputGzipped, mtype, pairMap, jwt)
  66. }
  67. func doUploadData(uploadUrl string, filename string, cipher bool, data []byte, isInputGzipped bool, mtype string, pairMap map[string]string, jwt security.EncodedJwt) (uploadResult *UploadResult, err error) {
  68. contentIsGzipped := isInputGzipped
  69. shouldGzipNow := false
  70. if !isInputGzipped {
  71. if shouldBeZipped, iAmSure := util.IsGzippableFileType(filepath.Base(filename), mtype); mtype == "" || iAmSure && shouldBeZipped {
  72. shouldGzipNow = true
  73. contentIsGzipped = true
  74. }
  75. }
  76. var clearDataLen int
  77. // gzip if possible
  78. // this could be double copying
  79. clearDataLen = len(data)
  80. if shouldGzipNow {
  81. data, err = util.GzipData(data)
  82. } else if isInputGzipped {
  83. // just to get the clear data length
  84. clearData, err := util.UnGzipData(data)
  85. if err == nil {
  86. clearDataLen = len(clearData)
  87. }
  88. }
  89. if cipher {
  90. // encrypt(gzip(data))
  91. // encrypt
  92. cipherKey := util.GenCipherKey()
  93. encryptedData, encryptionErr := util.Encrypt(data, cipherKey)
  94. if encryptionErr != nil {
  95. err = fmt.Errorf("encrypt input: %v", encryptionErr)
  96. return
  97. }
  98. // upload data
  99. uploadResult, err = upload_content(uploadUrl, func(w io.Writer) (err error) {
  100. _, err = w.Write(encryptedData)
  101. return
  102. }, "", false, "", nil, jwt)
  103. if uploadResult != nil {
  104. uploadResult.Name = filename
  105. uploadResult.Mime = mtype
  106. uploadResult.CipherKey = cipherKey
  107. }
  108. } else {
  109. // upload data
  110. uploadResult, err = upload_content(uploadUrl, func(w io.Writer) (err error) {
  111. _, err = w.Write(data)
  112. return
  113. }, filename, contentIsGzipped, mtype, pairMap, jwt)
  114. }
  115. if uploadResult == nil {
  116. return
  117. }
  118. uploadResult.Size = uint32(clearDataLen)
  119. if contentIsGzipped {
  120. uploadResult.Gzip = 1
  121. }
  122. return uploadResult, err
  123. }
  124. func upload_content(uploadUrl string, fillBufferFunction func(w io.Writer) error, filename string, isGzipped bool, mtype string, pairMap map[string]string, jwt security.EncodedJwt) (*UploadResult, error) {
  125. body_buf := bytes.NewBufferString("")
  126. body_writer := multipart.NewWriter(body_buf)
  127. h := make(textproto.MIMEHeader)
  128. h.Set("Content-Disposition", fmt.Sprintf(`form-data; name="file"; filename="%s"`, fileNameEscaper.Replace(filename)))
  129. if mtype == "" {
  130. mtype = mime.TypeByExtension(strings.ToLower(filepath.Ext(filename)))
  131. }
  132. if mtype != "" {
  133. h.Set("Content-Type", mtype)
  134. }
  135. if isGzipped {
  136. h.Set("Content-Encoding", "gzip")
  137. }
  138. file_writer, cp_err := body_writer.CreatePart(h)
  139. if cp_err != nil {
  140. glog.V(0).Infoln("error creating form file", cp_err.Error())
  141. return nil, cp_err
  142. }
  143. if err := fillBufferFunction(file_writer); err != nil {
  144. glog.V(0).Infoln("error copying data", err)
  145. return nil, err
  146. }
  147. content_type := body_writer.FormDataContentType()
  148. if err := body_writer.Close(); err != nil {
  149. glog.V(0).Infoln("error closing body", err)
  150. return nil, err
  151. }
  152. req, postErr := http.NewRequest("POST", uploadUrl, body_buf)
  153. if postErr != nil {
  154. glog.V(0).Infoln("failing to upload to", uploadUrl, postErr.Error())
  155. return nil, postErr
  156. }
  157. req.Header.Set("Content-Type", content_type)
  158. for k, v := range pairMap {
  159. req.Header.Set(k, v)
  160. }
  161. if jwt != "" {
  162. req.Header.Set("Authorization", "BEARER "+string(jwt))
  163. }
  164. resp, post_err := client.Do(req)
  165. if post_err != nil {
  166. glog.V(0).Infoln("failing to upload to", uploadUrl, post_err.Error())
  167. return nil, post_err
  168. }
  169. defer resp.Body.Close()
  170. var ret UploadResult
  171. etag := getEtag(resp)
  172. if resp.StatusCode == http.StatusNoContent {
  173. ret.ETag = etag
  174. return &ret, nil
  175. }
  176. resp_body, ra_err := ioutil.ReadAll(resp.Body)
  177. if ra_err != nil {
  178. return nil, ra_err
  179. }
  180. unmarshal_err := json.Unmarshal(resp_body, &ret)
  181. if unmarshal_err != nil {
  182. glog.V(0).Infoln("failing to read upload response", uploadUrl, string(resp_body))
  183. return nil, unmarshal_err
  184. }
  185. if ret.Error != "" {
  186. return nil, errors.New(ret.Error)
  187. }
  188. ret.ETag = etag
  189. return &ret, nil
  190. }
  191. func getEtag(r *http.Response) (etag string) {
  192. etag = r.Header.Get("ETag")
  193. if strings.HasPrefix(etag, "\"") && strings.HasSuffix(etag, "\"") {
  194. etag = etag[1 : len(etag)-1]
  195. }
  196. return
  197. }