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.

173 lines
5.0 KiB

6 years ago
6 years ago
12 years ago
  1. package operation
  2. import (
  3. "bytes"
  4. "compress/flate"
  5. "compress/gzip"
  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. }
  28. var (
  29. client *http.Client
  30. )
  31. func init() {
  32. client = &http.Client{Transport: &http.Transport{
  33. MaxIdleConnsPerHost: 1024,
  34. }}
  35. }
  36. var fileNameEscaper = strings.NewReplacer("\\", "\\\\", "\"", "\\\"")
  37. // Upload sends a POST request to a volume server to upload the content with adjustable compression level
  38. func UploadWithLocalCompressionLevel(uploadUrl string, filename string, cipher bool, reader io.Reader, isGzipped bool, mtype string, pairMap map[string]string, jwt security.EncodedJwt, compressionLevel int) (*UploadResult, error) {
  39. if compressionLevel < 1 {
  40. compressionLevel = 1
  41. }
  42. if compressionLevel > 9 {
  43. compressionLevel = 9
  44. }
  45. return doUpload(uploadUrl, filename, cipher, reader, isGzipped, mtype, pairMap, compressionLevel, jwt)
  46. }
  47. // Upload sends a POST request to a volume server to upload the content with fast compression
  48. func Upload(uploadUrl string, filename string, cipher bool, reader io.Reader, isGzipped bool, mtype string, pairMap map[string]string, jwt security.EncodedJwt) (*UploadResult, error) {
  49. return doUpload(uploadUrl, filename, cipher, reader, isGzipped, mtype, pairMap, flate.BestSpeed, jwt)
  50. }
  51. func doUpload(uploadUrl string, filename string, cipher bool, reader io.Reader, isGzipped bool, mtype string, pairMap map[string]string, compression int, jwt security.EncodedJwt) (*UploadResult, error) {
  52. contentIsGzipped := isGzipped
  53. shouldGzipNow := false
  54. if !isGzipped {
  55. if shouldBeZipped, iAmSure := util.IsGzippableFileType(filepath.Base(filename), mtype); iAmSure && shouldBeZipped {
  56. shouldGzipNow = true
  57. contentIsGzipped = true
  58. }
  59. }
  60. // encrypt data
  61. var cipherKey util.CipherKey
  62. var clearDataLen int
  63. var err error
  64. if cipher {
  65. cipherKey, reader, clearDataLen, _, err = util.EncryptReader(reader)
  66. if err != nil {
  67. return nil, err
  68. }
  69. }
  70. // upload data
  71. uploadResult, err := upload_content(uploadUrl, func(w io.Writer) (err error) {
  72. if shouldGzipNow {
  73. gzWriter, _ := gzip.NewWriterLevel(w, compression)
  74. _, err = io.Copy(gzWriter, reader)
  75. gzWriter.Close()
  76. } else {
  77. _, err = io.Copy(w, reader)
  78. }
  79. return
  80. }, filename, contentIsGzipped, mtype, pairMap, jwt)
  81. // remember cipher key
  82. if uploadResult != nil && cipherKey != nil {
  83. uploadResult.CipherKey = cipherKey
  84. uploadResult.Size = uint32(clearDataLen)
  85. }
  86. return uploadResult, err
  87. }
  88. 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) {
  89. body_buf := bytes.NewBufferString("")
  90. body_writer := multipart.NewWriter(body_buf)
  91. h := make(textproto.MIMEHeader)
  92. h.Set("Content-Disposition", fmt.Sprintf(`form-data; name="file"; filename="%s"`, fileNameEscaper.Replace(filename)))
  93. if mtype == "" {
  94. mtype = mime.TypeByExtension(strings.ToLower(filepath.Ext(filename)))
  95. }
  96. if mtype != "" {
  97. h.Set("Content-Type", mtype)
  98. }
  99. if isGzipped {
  100. h.Set("Content-Encoding", "gzip")
  101. }
  102. file_writer, cp_err := body_writer.CreatePart(h)
  103. if cp_err != nil {
  104. glog.V(0).Infoln("error creating form file", cp_err.Error())
  105. return nil, cp_err
  106. }
  107. if err := fillBufferFunction(file_writer); err != nil {
  108. glog.V(0).Infoln("error copying data", err)
  109. return nil, err
  110. }
  111. content_type := body_writer.FormDataContentType()
  112. if err := body_writer.Close(); err != nil {
  113. glog.V(0).Infoln("error closing body", err)
  114. return nil, err
  115. }
  116. req, postErr := http.NewRequest("POST", uploadUrl, body_buf)
  117. if postErr != nil {
  118. glog.V(0).Infoln("failing to upload to", uploadUrl, postErr.Error())
  119. return nil, postErr
  120. }
  121. req.Header.Set("Content-Type", content_type)
  122. for k, v := range pairMap {
  123. req.Header.Set(k, v)
  124. }
  125. if jwt != "" {
  126. req.Header.Set("Authorization", "BEARER "+string(jwt))
  127. }
  128. resp, post_err := client.Do(req)
  129. if post_err != nil {
  130. glog.V(0).Infoln("failing to upload to", uploadUrl, post_err.Error())
  131. return nil, post_err
  132. }
  133. defer resp.Body.Close()
  134. etag := getEtag(resp)
  135. resp_body, ra_err := ioutil.ReadAll(resp.Body)
  136. if ra_err != nil {
  137. return nil, ra_err
  138. }
  139. var ret UploadResult
  140. unmarshal_err := json.Unmarshal(resp_body, &ret)
  141. if unmarshal_err != nil {
  142. glog.V(0).Infoln("failing to read upload response", uploadUrl, string(resp_body))
  143. return nil, unmarshal_err
  144. }
  145. if ret.Error != "" {
  146. return nil, errors.New(ret.Error)
  147. }
  148. ret.ETag = etag
  149. return &ret, nil
  150. }
  151. func getEtag(r *http.Response) (etag string) {
  152. etag = r.Header.Get("ETag")
  153. if strings.HasPrefix(etag, "\"") && strings.HasSuffix(etag, "\"") {
  154. etag = etag[1 : len(etag)-1]
  155. }
  156. return
  157. }