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.

245 lines
7.4 KiB

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