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.4 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. 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. bytesReader, ok := reader.(*util.BytesReader)
  70. if ok {
  71. data = bytesReader.Bytes
  72. } else {
  73. buf := bytebufferpool.Get()
  74. _, err = buf.ReadFrom(reader)
  75. defer bytebufferpool.Put(buf)
  76. if err != nil {
  77. err = fmt.Errorf("read input: %v", err)
  78. return
  79. }
  80. data = buf.Bytes()
  81. }
  82. uploadResult, uploadErr := retriedUploadData(uploadUrl, filename, cipher, data, isInputCompressed, mtype, pairMap, jwt)
  83. return uploadResult, uploadErr, data
  84. }
  85. 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) {
  86. for i := 0; i < 1; i++ {
  87. uploadResult, err = doUploadData(uploadUrl, filename, cipher, data, isInputCompressed, mtype, pairMap, jwt)
  88. if err == nil {
  89. return
  90. } else {
  91. glog.Warningf("uploading to %s: %v", uploadUrl, err)
  92. }
  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. if shouldGzipNow {
  120. compressed, compressErr := util.GzipData(data)
  121. // fmt.Printf("data is compressed from %d ==> %d\n", len(data), len(compressed))
  122. if compressErr == nil {
  123. data = compressed
  124. contentIsGzipped = true
  125. }
  126. } else if isInputCompressed {
  127. // just to get the clear data length
  128. clearData, err := util.DecompressData(data)
  129. if err == nil {
  130. clearDataLen = len(clearData)
  131. }
  132. }
  133. if cipher {
  134. // encrypt(gzip(data))
  135. // encrypt
  136. cipherKey := util.GenCipherKey()
  137. encryptedData, encryptionErr := util.Encrypt(data, cipherKey)
  138. if encryptionErr != nil {
  139. err = fmt.Errorf("encrypt input: %v", encryptionErr)
  140. return
  141. }
  142. // upload data
  143. uploadResult, err = upload_content(uploadUrl, func(w io.Writer) (err error) {
  144. _, err = w.Write(encryptedData)
  145. return
  146. }, "", false, len(encryptedData), "", nil, jwt)
  147. if uploadResult != nil {
  148. uploadResult.Name = filename
  149. uploadResult.Mime = mtype
  150. uploadResult.CipherKey = cipherKey
  151. }
  152. } else {
  153. // upload data
  154. uploadResult, err = upload_content(uploadUrl, func(w io.Writer) (err error) {
  155. _, err = w.Write(data)
  156. return
  157. }, filename, contentIsGzipped, 0, mtype, pairMap, jwt)
  158. }
  159. if uploadResult == nil {
  160. return
  161. }
  162. uploadResult.Size = uint32(clearDataLen)
  163. if contentIsGzipped {
  164. uploadResult.Gzip = 1
  165. }
  166. return uploadResult, err
  167. }
  168. 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) {
  169. buf := bytebufferpool.Get()
  170. defer bytebufferpool.Put(buf)
  171. body_writer := multipart.NewWriter(buf)
  172. h := make(textproto.MIMEHeader)
  173. h.Set("Content-Disposition", fmt.Sprintf(`form-data; name="file"; filename="%s"`, fileNameEscaper.Replace(filename)))
  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. }