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.

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