upload_content.go 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. package operation
  2. import (
  3. "bufio"
  4. "compress/flate"
  5. "compress/gzip"
  6. "crypto/rand"
  7. "encoding/json"
  8. "errors"
  9. "fmt"
  10. "io"
  11. "mime"
  12. "mime/multipart"
  13. "net/http"
  14. "net/textproto"
  15. "path/filepath"
  16. "strings"
  17. "github.com/valyala/fasthttp"
  18. "github.com/chrislusf/seaweedfs/weed/glog"
  19. "github.com/chrislusf/seaweedfs/weed/security"
  20. "github.com/chrislusf/seaweedfs/weed/util"
  21. )
  22. type UploadResult struct {
  23. Name string `json:"name,omitempty"`
  24. Size uint32 `json:"size,omitempty"`
  25. Error string `json:"error,omitempty"`
  26. ETag string `json:"eTag,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, 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, 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, reader io.Reader, isGzipped bool, mtype string, pairMap map[string]string, jwt security.EncodedJwt) (*UploadResult, error) {
  49. return doUpload(uploadUrl, filename, reader, isGzipped, mtype, pairMap, flate.BestSpeed, jwt)
  50. }
  51. func doUpload(uploadUrl string, filename string, 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. return upload_content(uploadUrl, func(w io.Writer) (err error) {
  61. if shouldGzipNow {
  62. gzWriter, _ := gzip.NewWriterLevel(w, compression)
  63. _, err = io.Copy(gzWriter, reader)
  64. gzWriter.Close()
  65. } else {
  66. _, err = io.Copy(w, reader)
  67. }
  68. return
  69. }, filename, contentIsGzipped, mtype, pairMap, jwt)
  70. }
  71. func randomBoundary() string {
  72. var buf [30]byte
  73. _, err := io.ReadFull(rand.Reader, buf[:])
  74. if err != nil {
  75. panic(err)
  76. }
  77. return fmt.Sprintf("%x", buf[:])
  78. }
  79. 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) {
  80. if mtype == "" {
  81. mtype = mime.TypeByExtension(strings.ToLower(filepath.Ext(filename)))
  82. }
  83. boundary := randomBoundary()
  84. contentType := "multipart/form-data; boundary=" + boundary
  85. var ret UploadResult
  86. var etag string
  87. var writeErr error
  88. err := util.PostContent(uploadUrl, func(w *bufio.Writer) {
  89. h := make(textproto.MIMEHeader)
  90. h.Set("Content-Disposition", fmt.Sprintf(`form-data; name="file"; filename="%s"`, fileNameEscaper.Replace(filename)))
  91. if mtype != "" {
  92. h.Set("Content-Type", mtype)
  93. }
  94. if isGzipped {
  95. h.Set("Content-Encoding", "gzip")
  96. }
  97. body_writer := multipart.NewWriter(w)
  98. body_writer.SetBoundary(boundary)
  99. file_writer, cp_err := body_writer.CreatePart(h)
  100. if cp_err != nil {
  101. glog.V(0).Infoln("error creating form file", cp_err.Error())
  102. writeErr = cp_err
  103. return
  104. }
  105. if err := fillBufferFunction(file_writer); err != nil {
  106. glog.V(0).Infoln("error copying data", err)
  107. writeErr = err
  108. return
  109. }
  110. if err := body_writer.Close(); err != nil {
  111. glog.V(0).Infoln("error closing body", err)
  112. writeErr = err
  113. return
  114. }
  115. w.Flush()
  116. }, func(header *fasthttp.RequestHeader) {
  117. header.Set("Content-Type", contentType)
  118. for k, v := range pairMap {
  119. header.Set(k, v)
  120. }
  121. if jwt != "" {
  122. header.Set("Authorization", "BEARER "+string(jwt))
  123. }
  124. }, func(resp *fasthttp.Response) error {
  125. etagBytes := resp.Header.Peek("ETag")
  126. lenEtagBytes := len(etagBytes)
  127. if lenEtagBytes > 2 && etagBytes[0] == '"' && etagBytes[lenEtagBytes-1] == '"' {
  128. etag = string(etagBytes[1 : len(etagBytes)-1])
  129. }
  130. unmarshal_err := json.Unmarshal(resp.Body(), &ret)
  131. if unmarshal_err != nil {
  132. glog.V(0).Infoln("failing to read upload response", uploadUrl, string(resp.Body()))
  133. return unmarshal_err
  134. }
  135. if ret.Error != "" {
  136. return errors.New(ret.Error)
  137. }
  138. return nil
  139. })
  140. if writeErr != nil {
  141. return nil, writeErr
  142. }
  143. ret.ETag = etag
  144. if err != nil {
  145. return nil, err
  146. }
  147. return &ret, nil
  148. }