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.

228 lines
6.6 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); iAmSure && shouldBeZipped {
  72. shouldGzipNow = true
  73. } else if len(data) > 128 {
  74. var compressed []byte
  75. compressed, err = util.GzipData(data[0:128])
  76. shouldGzipNow = len(compressed)*10 < 128*9 // can not compress to less than 90%
  77. }
  78. }
  79. var clearDataLen int
  80. // gzip if possible
  81. // this could be double copying
  82. clearDataLen = len(data)
  83. if shouldGzipNow {
  84. compressed, compressErr := util.GzipData(data)
  85. // fmt.Printf("data is compressed from %d ==> %d\n", len(data), len(compressed))
  86. if compressErr == nil {
  87. data = compressed
  88. contentIsGzipped = true
  89. }
  90. } else if isInputGzipped {
  91. // just to get the clear data length
  92. clearData, err := util.UnGzipData(data)
  93. if err == nil {
  94. clearDataLen = len(clearData)
  95. }
  96. }
  97. if cipher {
  98. // encrypt(gzip(data))
  99. // encrypt
  100. cipherKey := util.GenCipherKey()
  101. encryptedData, encryptionErr := util.Encrypt(data, cipherKey)
  102. if encryptionErr != nil {
  103. err = fmt.Errorf("encrypt input: %v", encryptionErr)
  104. return
  105. }
  106. // upload data
  107. uploadResult, err = upload_content(uploadUrl, func(w io.Writer) (err error) {
  108. _, err = w.Write(encryptedData)
  109. return
  110. }, "", false, "", nil, jwt)
  111. if uploadResult != nil {
  112. uploadResult.Name = filename
  113. uploadResult.Mime = mtype
  114. uploadResult.CipherKey = cipherKey
  115. }
  116. } else {
  117. // upload data
  118. uploadResult, err = upload_content(uploadUrl, func(w io.Writer) (err error) {
  119. _, err = w.Write(data)
  120. return
  121. }, filename, contentIsGzipped, mtype, pairMap, jwt)
  122. }
  123. if uploadResult == nil {
  124. return
  125. }
  126. uploadResult.Size = uint32(clearDataLen)
  127. if contentIsGzipped {
  128. uploadResult.Gzip = 1
  129. }
  130. return uploadResult, err
  131. }
  132. 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) {
  133. body_buf := bytes.NewBufferString("")
  134. body_writer := multipart.NewWriter(body_buf)
  135. h := make(textproto.MIMEHeader)
  136. h.Set("Content-Disposition", fmt.Sprintf(`form-data; name="file"; filename="%s"`, fileNameEscaper.Replace(filename)))
  137. if mtype == "" {
  138. mtype = mime.TypeByExtension(strings.ToLower(filepath.Ext(filename)))
  139. }
  140. if mtype != "" {
  141. h.Set("Content-Type", mtype)
  142. }
  143. if isGzipped {
  144. h.Set("Content-Encoding", "gzip")
  145. }
  146. file_writer, cp_err := body_writer.CreatePart(h)
  147. if cp_err != nil {
  148. glog.V(0).Infoln("error creating form file", cp_err.Error())
  149. return nil, cp_err
  150. }
  151. if err := fillBufferFunction(file_writer); err != nil {
  152. glog.V(0).Infoln("error copying data", err)
  153. return nil, err
  154. }
  155. content_type := body_writer.FormDataContentType()
  156. if err := body_writer.Close(); err != nil {
  157. glog.V(0).Infoln("error closing body", err)
  158. return nil, err
  159. }
  160. req, postErr := http.NewRequest("POST", uploadUrl, body_buf)
  161. if postErr != nil {
  162. glog.V(0).Infoln("failing to upload to", uploadUrl, postErr.Error())
  163. return nil, postErr
  164. }
  165. req.Header.Set("Content-Type", content_type)
  166. for k, v := range pairMap {
  167. req.Header.Set(k, v)
  168. }
  169. if jwt != "" {
  170. req.Header.Set("Authorization", "BEARER "+string(jwt))
  171. }
  172. resp, post_err := client.Do(req)
  173. if post_err != nil {
  174. glog.V(0).Infoln("failing to upload to", uploadUrl, post_err.Error())
  175. return nil, post_err
  176. }
  177. defer resp.Body.Close()
  178. var ret UploadResult
  179. etag := getEtag(resp)
  180. if resp.StatusCode == http.StatusNoContent {
  181. ret.ETag = etag
  182. return &ret, nil
  183. }
  184. resp_body, ra_err := ioutil.ReadAll(resp.Body)
  185. if ra_err != nil {
  186. return nil, ra_err
  187. }
  188. unmarshal_err := json.Unmarshal(resp_body, &ret)
  189. if unmarshal_err != nil {
  190. glog.V(0).Infoln("failing to read upload response", uploadUrl, string(resp_body))
  191. return nil, unmarshal_err
  192. }
  193. if ret.Error != "" {
  194. return nil, errors.New(ret.Error)
  195. }
  196. ret.ETag = etag
  197. return &ret, nil
  198. }
  199. func getEtag(r *http.Response) (etag string) {
  200. etag = r.Header.Get("ETag")
  201. if strings.HasPrefix(etag, "\"") && strings.HasSuffix(etag, "\"") {
  202. etag = etag[1 : len(etag)-1]
  203. }
  204. return
  205. }