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.

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