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.

274 lines
8.5 KiB

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