upload_content.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. package operation
  2. import (
  3. "bytes"
  4. "compress/flate"
  5. "crypto/md5"
  6. "encoding/json"
  7. "errors"
  8. "fmt"
  9. "io"
  10. "io/ioutil"
  11. "mime"
  12. "mime/multipart"
  13. "net/http"
  14. "net/textproto"
  15. "path/filepath"
  16. "strings"
  17. "github.com/chrislusf/seaweedfs/weed/glog"
  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. Md5 string `json:"md5,omitempty"`
  30. }
  31. var (
  32. client *http.Client
  33. )
  34. func init() {
  35. client = &http.Client{Transport: &http.Transport{
  36. MaxIdleConnsPerHost: 1024,
  37. }}
  38. }
  39. var fileNameEscaper = strings.NewReplacer("\\", "\\\\", "\"", "\\\"")
  40. // Upload sends a POST request to a volume server to upload the content with adjustable compression level
  41. func UploadData(uploadUrl string, filename string, cipher bool, data []byte, isInputGzipped bool, mtype string, pairMap map[string]string, jwt security.EncodedJwt) (uploadResult *UploadResult, err error) {
  42. hash := md5.New()
  43. hash.Write(data)
  44. uploadResult, err = doUploadData(uploadUrl, filename, cipher, data, isInputGzipped, mtype, pairMap, jwt)
  45. if uploadResult != nil {
  46. uploadResult.Md5 = fmt.Sprintf("%x", hash.Sum(nil))
  47. }
  48. return
  49. }
  50. // Upload sends a POST request to a volume server to upload the content with fast compression
  51. func Upload(uploadUrl string, filename string, cipher bool, reader io.Reader, isInputGzipped bool, mtype string, pairMap map[string]string, jwt security.EncodedJwt) (uploadResult *UploadResult, err error) {
  52. hash := md5.New()
  53. reader = io.TeeReader(reader, hash)
  54. uploadResult, err = doUpload(uploadUrl, filename, cipher, reader, isInputGzipped, mtype, pairMap, flate.BestSpeed, jwt)
  55. if uploadResult != nil {
  56. uploadResult.Md5 = fmt.Sprintf("%x", hash.Sum(nil))
  57. }
  58. return
  59. }
  60. func doUploadData(uploadUrl string, filename string, cipher bool, data []byte, isInputGzipped bool, mtype string, pairMap map[string]string, jwt security.EncodedJwt) (uploadResult *UploadResult, err error) {
  61. contentIsGzipped := isInputGzipped
  62. shouldGzipNow := false
  63. if !isInputGzipped {
  64. if shouldBeZipped, iAmSure := util.IsGzippableFileType(filepath.Base(filename), mtype); mtype == "" || iAmSure && shouldBeZipped {
  65. shouldGzipNow = true
  66. contentIsGzipped = true
  67. }
  68. }
  69. var clearDataLen int
  70. // gzip if possible
  71. // this could be double copying
  72. clearDataLen = len(data)
  73. if shouldGzipNow {
  74. data, err = util.GzipData(data)
  75. } else if isInputGzipped {
  76. // just to get the clear data length
  77. clearData, err := util.UnGzipData(data)
  78. if err == nil {
  79. clearDataLen = len(clearData)
  80. }
  81. }
  82. if cipher {
  83. // encrypt(gzip(data))
  84. // encrypt
  85. cipherKey := util.GenCipherKey()
  86. encryptedData, encryptionErr := util.Encrypt(data, cipherKey)
  87. if encryptionErr != nil {
  88. err = fmt.Errorf("encrypt input: %v", encryptionErr)
  89. return
  90. }
  91. // upload data
  92. uploadResult, err = upload_content(uploadUrl, func(w io.Writer) (err error) {
  93. _, err = w.Write(encryptedData)
  94. return
  95. }, "", false, "", nil, jwt)
  96. if uploadResult != nil {
  97. uploadResult.Name = filename
  98. uploadResult.Mime = mtype
  99. uploadResult.CipherKey = cipherKey
  100. }
  101. } else {
  102. // upload data
  103. uploadResult, err = upload_content(uploadUrl, func(w io.Writer) (err error) {
  104. _, err = w.Write(data)
  105. return
  106. }, filename, contentIsGzipped, mtype, pairMap, jwt)
  107. }
  108. uploadResult.Size = uint32(clearDataLen)
  109. if contentIsGzipped {
  110. uploadResult.Gzip = 1
  111. }
  112. return uploadResult, err
  113. }
  114. func doUpload(uploadUrl string, filename string, cipher bool, reader io.Reader, isInputGzipped bool, mtype string, pairMap map[string]string, compression int, jwt security.EncodedJwt) (uploadResult *UploadResult, err error) {
  115. contentIsGzipped := isInputGzipped
  116. shouldGzipNow := false
  117. if !isInputGzipped {
  118. if shouldBeZipped, iAmSure := util.IsGzippableFileType(filepath.Base(filename), mtype); mtype == "" || iAmSure && shouldBeZipped {
  119. shouldGzipNow = true
  120. contentIsGzipped = true
  121. }
  122. }
  123. var clearDataLen int
  124. // gzip if possible
  125. // this could be double copying
  126. data, readErr := ioutil.ReadAll(reader)
  127. if readErr != nil {
  128. err = fmt.Errorf("read input: %v", readErr)
  129. return
  130. }
  131. clearDataLen = len(data)
  132. if shouldGzipNow {
  133. data, err = util.GzipData(data)
  134. } else if isInputGzipped {
  135. // just to get the clear data length
  136. clearData, err := util.UnGzipData(data)
  137. if err == nil {
  138. clearDataLen = len(clearData)
  139. }
  140. }
  141. if cipher {
  142. // encrypt(gzip(data))
  143. // encrypt
  144. cipherKey := util.GenCipherKey()
  145. encryptedData, encryptionErr := util.Encrypt(data, cipherKey)
  146. if encryptionErr != nil {
  147. err = fmt.Errorf("encrypt input: %v", encryptionErr)
  148. return
  149. }
  150. // upload data
  151. uploadResult, err = upload_content(uploadUrl, func(w io.Writer) (err error) {
  152. _, err = w.Write(encryptedData)
  153. return
  154. }, "", false, "", nil, jwt)
  155. if uploadResult != nil {
  156. uploadResult.Name = filename
  157. uploadResult.Mime = mtype
  158. uploadResult.CipherKey = cipherKey
  159. uploadResult.Size = uint32(clearDataLen)
  160. }
  161. } else {
  162. // upload data
  163. uploadResult, err = upload_content(uploadUrl, func(w io.Writer) (err error) {
  164. _, err = w.Write(data)
  165. return
  166. }, filename, contentIsGzipped, mtype, pairMap, jwt)
  167. }
  168. if uploadResult == nil {
  169. return
  170. }
  171. uploadResult.Size = uint32(clearDataLen)
  172. if contentIsGzipped {
  173. uploadResult.Gzip = 1
  174. }
  175. return uploadResult, err
  176. }
  177. func upload_content(uploadUrl string, fillBufferFunction func(w io.Writer) error, filename string, isGzipped bool, mtype string, pairMap map[string]string, jwt security.EncodedJwt) (*UploadResult, error) {
  178. body_buf := bytes.NewBufferString("")
  179. body_writer := multipart.NewWriter(body_buf)
  180. h := make(textproto.MIMEHeader)
  181. h.Set("Content-Disposition", fmt.Sprintf(`form-data; name="file"; filename="%s"`, fileNameEscaper.Replace(filename)))
  182. if mtype == "" {
  183. mtype = mime.TypeByExtension(strings.ToLower(filepath.Ext(filename)))
  184. }
  185. if mtype != "" {
  186. h.Set("Content-Type", mtype)
  187. }
  188. if isGzipped {
  189. h.Set("Content-Encoding", "gzip")
  190. }
  191. file_writer, cp_err := body_writer.CreatePart(h)
  192. if cp_err != nil {
  193. glog.V(0).Infoln("error creating form file", cp_err.Error())
  194. return nil, cp_err
  195. }
  196. if err := fillBufferFunction(file_writer); err != nil {
  197. glog.V(0).Infoln("error copying data", err)
  198. return nil, err
  199. }
  200. content_type := body_writer.FormDataContentType()
  201. if err := body_writer.Close(); err != nil {
  202. glog.V(0).Infoln("error closing body", err)
  203. return nil, err
  204. }
  205. req, postErr := http.NewRequest("POST", uploadUrl, body_buf)
  206. if postErr != nil {
  207. glog.V(0).Infoln("failing to upload to", uploadUrl, postErr.Error())
  208. return nil, postErr
  209. }
  210. req.Header.Set("Content-Type", content_type)
  211. for k, v := range pairMap {
  212. req.Header.Set(k, v)
  213. }
  214. if jwt != "" {
  215. req.Header.Set("Authorization", "BEARER "+string(jwt))
  216. }
  217. resp, post_err := client.Do(req)
  218. if post_err != nil {
  219. glog.V(0).Infoln("failing to upload to", uploadUrl, post_err.Error())
  220. return nil, post_err
  221. }
  222. defer resp.Body.Close()
  223. etag := getEtag(resp)
  224. resp_body, ra_err := ioutil.ReadAll(resp.Body)
  225. if ra_err != nil {
  226. return nil, ra_err
  227. }
  228. var ret UploadResult
  229. unmarshal_err := json.Unmarshal(resp_body, &ret)
  230. if unmarshal_err != nil {
  231. glog.V(0).Infoln("failing to read upload response", uploadUrl, string(resp_body))
  232. return nil, unmarshal_err
  233. }
  234. if ret.Error != "" {
  235. return nil, errors.New(ret.Error)
  236. }
  237. ret.ETag = etag
  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. }