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.

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