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.

174 lines
5.1 KiB

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