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.

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