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.

276 lines
8.6 KiB

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