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.

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