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.

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