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.

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