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.

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