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.

151 lines
4.5 KiB

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