upload_content.go 11 KB

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