upload_content.go 12 KB

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