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.

304 lines
8.7 KiB

6 years ago
3 years ago
4 years ago
4 years ago
3 years ago
3 years ago
3 years ago
5 years ago
3 years ago
5 years ago
3 years ago
3 years ago
4 years ago
3 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
5 years ago
3 years ago
3 years ago
3 years ago
5 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
12 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
  1. package operation
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "fmt"
  6. "io"
  7. "mime"
  8. "mime/multipart"
  9. "net/http"
  10. "net/textproto"
  11. "path/filepath"
  12. "strings"
  13. "time"
  14. "github.com/chrislusf/seaweedfs/weed/glog"
  15. "github.com/chrislusf/seaweedfs/weed/pb/filer_pb"
  16. "github.com/chrislusf/seaweedfs/weed/security"
  17. "github.com/chrislusf/seaweedfs/weed/util"
  18. )
  19. type UploadOption struct {
  20. UploadUrl string
  21. Filename string
  22. Cipher bool
  23. IsInputCompressed bool
  24. MimeType string
  25. PairMap map[string]string
  26. Jwt security.EncodedJwt
  27. }
  28. type UploadResult struct {
  29. Name string `json:"name,omitempty"`
  30. Size uint32 `json:"size,omitempty"`
  31. Error string `json:"error,omitempty"`
  32. ETag string `json:"eTag,omitempty"`
  33. CipherKey []byte `json:"cipherKey,omitempty"`
  34. Mime string `json:"mime,omitempty"`
  35. Gzip uint32 `json:"gzip,omitempty"`
  36. ContentMd5 string `json:"contentMd5,omitempty"`
  37. RetryCount int `json:"-"`
  38. }
  39. func (uploadResult *UploadResult) ToPbFileChunk(fileId string, offset int64) *filer_pb.FileChunk {
  40. fid, _ := filer_pb.ToFileIdObject(fileId)
  41. return &filer_pb.FileChunk{
  42. FileId: fileId,
  43. Offset: offset,
  44. Size: uint64(uploadResult.Size),
  45. Mtime: time.Now().UnixNano(),
  46. ETag: uploadResult.ContentMd5,
  47. CipherKey: uploadResult.CipherKey,
  48. IsCompressed: uploadResult.Gzip > 0,
  49. Fid: fid,
  50. }
  51. }
  52. // HTTPClient interface for testing
  53. type HTTPClient interface {
  54. Do(req *http.Request) (*http.Response, error)
  55. }
  56. var (
  57. HttpClient HTTPClient
  58. )
  59. func init() {
  60. HttpClient = &http.Client{Transport: &http.Transport{
  61. MaxIdleConns: 1024,
  62. MaxIdleConnsPerHost: 1024,
  63. }}
  64. }
  65. var fileNameEscaper = strings.NewReplacer(`\`, `\\`, `"`, `\"`)
  66. // Upload sends a POST request to a volume server to upload the content with adjustable compression level
  67. func UploadData(data []byte, option *UploadOption) (uploadResult *UploadResult, err error) {
  68. uploadResult, err = retriedUploadData(data, option)
  69. return
  70. }
  71. // Upload sends a POST request to a volume server to upload the content with fast compression
  72. func Upload(reader io.Reader, option *UploadOption) (uploadResult *UploadResult, err error, data []byte) {
  73. uploadResult, err, data = doUpload(reader, option)
  74. return
  75. }
  76. func doUpload(reader io.Reader, option *UploadOption) (uploadResult *UploadResult, err error, data []byte) {
  77. bytesReader, ok := reader.(*util.BytesReader)
  78. if ok {
  79. data = bytesReader.Bytes
  80. } else {
  81. data, err = io.ReadAll(reader)
  82. if err != nil {
  83. err = fmt.Errorf("read input: %v", err)
  84. return
  85. }
  86. }
  87. uploadResult, uploadErr := retriedUploadData(data, option)
  88. return uploadResult, uploadErr, data
  89. }
  90. func retriedUploadData(data []byte, option *UploadOption) (uploadResult *UploadResult, err error) {
  91. for i := 0; i < 3; i++ {
  92. uploadResult, err = doUploadData(data, option)
  93. if err == nil {
  94. uploadResult.RetryCount = i
  95. return
  96. } else {
  97. glog.Warningf("uploading to %s: %v", option.UploadUrl, err)
  98. }
  99. time.Sleep(time.Millisecond * time.Duration(237*(i+1)))
  100. }
  101. return
  102. }
  103. func doUploadData(data []byte, option *UploadOption) (uploadResult *UploadResult, err error) {
  104. contentIsGzipped := option.IsInputCompressed
  105. shouldGzipNow := false
  106. if !option.IsInputCompressed {
  107. if option.MimeType == "" {
  108. option.MimeType = http.DetectContentType(data)
  109. // println("detect1 mimetype to", MimeType)
  110. if option.MimeType == "application/octet-stream" {
  111. option.MimeType = ""
  112. }
  113. }
  114. if shouldBeCompressed, iAmSure := util.IsCompressableFileType(filepath.Base(option.Filename), option.MimeType); iAmSure && shouldBeCompressed {
  115. shouldGzipNow = true
  116. } else if !iAmSure && option.MimeType == "" && len(data) > 16*1024 {
  117. var compressed []byte
  118. compressed, err = util.GzipData(data[0:128])
  119. shouldGzipNow = len(compressed)*10 < 128*9 // can not compress to less than 90%
  120. }
  121. }
  122. var clearDataLen int
  123. // gzip if possible
  124. // this could be double copying
  125. clearDataLen = len(data)
  126. clearData := data
  127. if shouldGzipNow && !option.Cipher {
  128. compressed, compressErr := util.GzipData(data)
  129. // fmt.Printf("data is compressed from %d ==> %d\n", len(data), len(compressed))
  130. if compressErr == nil {
  131. data = compressed
  132. contentIsGzipped = true
  133. }
  134. } else if option.IsInputCompressed {
  135. // just to get the clear data length
  136. clearData, err = util.DecompressData(data)
  137. if err == nil {
  138. clearDataLen = len(clearData)
  139. }
  140. }
  141. if option.Cipher {
  142. // encrypt(gzip(data))
  143. // encrypt
  144. cipherKey := util.GenCipherKey()
  145. encryptedData, encryptionErr := util.Encrypt(clearData, cipherKey)
  146. if encryptionErr != nil {
  147. err = fmt.Errorf("encrypt input: %v", encryptionErr)
  148. return
  149. }
  150. // upload data
  151. uploadResult, err = upload_content(func(w io.Writer) (err error) {
  152. _, err = w.Write(encryptedData)
  153. return
  154. }, len(encryptedData), &UploadOption{
  155. UploadUrl: option.UploadUrl,
  156. Filename: "",
  157. Cipher: false,
  158. IsInputCompressed: false,
  159. MimeType: "",
  160. PairMap: nil,
  161. Jwt: option.Jwt,
  162. })
  163. if uploadResult == nil {
  164. return
  165. }
  166. uploadResult.Name = option.Filename
  167. uploadResult.Mime = option.MimeType
  168. uploadResult.CipherKey = cipherKey
  169. uploadResult.Size = uint32(clearDataLen)
  170. } else {
  171. // upload data
  172. uploadResult, err = upload_content(func(w io.Writer) (err error) {
  173. _, err = w.Write(data)
  174. return
  175. }, len(data), &UploadOption{
  176. UploadUrl: option.UploadUrl,
  177. Filename: option.Filename,
  178. Cipher: false,
  179. IsInputCompressed: contentIsGzipped,
  180. MimeType: option.MimeType,
  181. PairMap: option.PairMap,
  182. Jwt: option.Jwt,
  183. })
  184. if uploadResult == nil {
  185. return
  186. }
  187. uploadResult.Size = uint32(clearDataLen)
  188. if contentIsGzipped {
  189. uploadResult.Gzip = 1
  190. }
  191. }
  192. return uploadResult, err
  193. }
  194. func upload_content(fillBufferFunction func(w io.Writer) error, originalDataSize int, option *UploadOption) (*UploadResult, error) {
  195. buf := GetBuffer()
  196. defer PutBuffer(buf)
  197. body_writer := multipart.NewWriter(buf)
  198. h := make(textproto.MIMEHeader)
  199. h.Set("Content-Disposition", fmt.Sprintf(`form-data; name="file"; filename="%s"`, fileNameEscaper.Replace(option.Filename)))
  200. h.Set("Idempotency-Key", option.UploadUrl)
  201. if option.MimeType == "" {
  202. option.MimeType = mime.TypeByExtension(strings.ToLower(filepath.Ext(option.Filename)))
  203. }
  204. if option.MimeType != "" {
  205. h.Set("Content-Type", option.MimeType)
  206. }
  207. if option.IsInputCompressed {
  208. h.Set("Content-Encoding", "gzip")
  209. }
  210. file_writer, cp_err := body_writer.CreatePart(h)
  211. if cp_err != nil {
  212. glog.V(0).Infoln("error creating form file", cp_err.Error())
  213. return nil, cp_err
  214. }
  215. if err := fillBufferFunction(file_writer); err != nil {
  216. glog.V(0).Infoln("error copying data", err)
  217. return nil, err
  218. }
  219. content_type := body_writer.FormDataContentType()
  220. if err := body_writer.Close(); err != nil {
  221. glog.V(0).Infoln("error closing body", err)
  222. return nil, err
  223. }
  224. req, postErr := http.NewRequest("POST", option.UploadUrl, bytes.NewReader(buf.Bytes()))
  225. if postErr != nil {
  226. glog.V(1).Infof("create upload request %s: %v", option.UploadUrl, postErr)
  227. return nil, fmt.Errorf("create upload request %s: %v", option.UploadUrl, postErr)
  228. }
  229. req.Header.Set("Content-Type", content_type)
  230. for k, v := range option.PairMap {
  231. req.Header.Set(k, v)
  232. }
  233. if option.Jwt != "" {
  234. req.Header.Set("Authorization", "BEARER "+string(option.Jwt))
  235. }
  236. // print("+")
  237. resp, post_err := HttpClient.Do(req)
  238. if post_err != nil {
  239. if strings.Contains(post_err.Error(), "connection reset by peer") ||
  240. strings.Contains(post_err.Error(), "use of closed network connection") {
  241. resp, post_err = HttpClient.Do(req)
  242. }
  243. }
  244. if post_err != nil {
  245. return nil, fmt.Errorf("upload %s %d bytes to %v: %v", option.Filename, originalDataSize, option.UploadUrl, post_err)
  246. }
  247. // print("-")
  248. defer util.CloseResponse(resp)
  249. var ret UploadResult
  250. etag := getEtag(resp)
  251. if resp.StatusCode == http.StatusNoContent {
  252. ret.ETag = etag
  253. return &ret, nil
  254. }
  255. resp_body, ra_err := io.ReadAll(resp.Body)
  256. if ra_err != nil {
  257. return nil, fmt.Errorf("read response body %v: %v", option.UploadUrl, ra_err)
  258. }
  259. unmarshal_err := json.Unmarshal(resp_body, &ret)
  260. if unmarshal_err != nil {
  261. glog.Errorf("unmarshal %s: %v", option.UploadUrl, string(resp_body))
  262. return nil, fmt.Errorf("unmarshal %v: %v", option.UploadUrl, unmarshal_err)
  263. }
  264. if ret.Error != "" {
  265. return nil, fmt.Errorf("unmarshalled error %v: %v", option.UploadUrl, ret.Error)
  266. }
  267. ret.ETag = etag
  268. ret.ContentMd5 = resp.Header.Get("Content-MD5")
  269. return &ret, nil
  270. }
  271. func getEtag(r *http.Response) (etag string) {
  272. etag = r.Header.Get("ETag")
  273. if strings.HasPrefix(etag, "\"") && strings.HasSuffix(etag, "\"") {
  274. etag = etag[1 : len(etag)-1]
  275. }
  276. return
  277. }