filer_server_handlers_write_upload.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  1. package weed_server
  2. import (
  3. "bytes"
  4. "crypto/md5"
  5. "fmt"
  6. "hash"
  7. "io"
  8. "net/http"
  9. "strconv"
  10. "sync"
  11. "time"
  12. "golang.org/x/exp/slices"
  13. "github.com/seaweedfs/seaweedfs/weed/glog"
  14. "github.com/seaweedfs/seaweedfs/weed/operation"
  15. "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
  16. "github.com/seaweedfs/seaweedfs/weed/security"
  17. "github.com/seaweedfs/seaweedfs/weed/stats"
  18. "github.com/seaweedfs/seaweedfs/weed/util"
  19. )
  20. var bufPool = sync.Pool{
  21. New: func() interface{} {
  22. return new(bytes.Buffer)
  23. },
  24. }
  25. func (fs *FilerServer) uploadRequestToChunks(w http.ResponseWriter, r *http.Request, reader io.Reader, chunkSize int32, fileName, contentType string, contentLength int64, so *operation.StorageOption) (fileChunks []*filer_pb.FileChunk, md5Hash hash.Hash, chunkOffset int64, uploadErr error, smallContent []byte) {
  26. query := r.URL.Query()
  27. isAppend := isAppend(r)
  28. if query.Has("offset") {
  29. offset := query.Get("offset")
  30. offsetInt, err := strconv.ParseInt(offset, 10, 64)
  31. if err != nil || offsetInt < 0 {
  32. err = fmt.Errorf("invalid 'offset': '%s'", offset)
  33. return nil, nil, 0, err, nil
  34. }
  35. if isAppend && offsetInt > 0 {
  36. err = fmt.Errorf("cannot set offset when op=append")
  37. return nil, nil, 0, err, nil
  38. }
  39. chunkOffset = offsetInt
  40. }
  41. return fs.uploadReaderToChunks(reader, chunkOffset, chunkSize, fileName, contentType, isAppend, so)
  42. }
  43. func (fs *FilerServer) uploadReaderToChunks(reader io.Reader, startOffset int64, chunkSize int32, fileName, contentType string, isAppend bool, so *operation.StorageOption) (fileChunks []*filer_pb.FileChunk, md5Hash hash.Hash, chunkOffset int64, uploadErr error, smallContent []byte) {
  44. md5Hash = md5.New()
  45. chunkOffset = startOffset
  46. var partReader = io.NopCloser(io.TeeReader(reader, md5Hash))
  47. var wg sync.WaitGroup
  48. var bytesBufferCounter int64 = 4
  49. bytesBufferLimitChan := make(chan struct{}, bytesBufferCounter)
  50. var fileChunksLock sync.Mutex
  51. var uploadErrLock sync.Mutex
  52. for {
  53. // need to throttle used byte buffer
  54. bytesBufferLimitChan <- struct{}{}
  55. bytesBuffer := bufPool.Get().(*bytes.Buffer)
  56. limitedReader := io.LimitReader(partReader, int64(chunkSize))
  57. bytesBuffer.Reset()
  58. dataSize, err := bytesBuffer.ReadFrom(limitedReader)
  59. // data, err := io.ReadAll(limitedReader)
  60. if err != nil || dataSize == 0 {
  61. bufPool.Put(bytesBuffer)
  62. <-bytesBufferLimitChan
  63. if err != nil {
  64. uploadErrLock.Lock()
  65. if uploadErr == nil {
  66. uploadErr = err
  67. }
  68. uploadErrLock.Unlock()
  69. }
  70. break
  71. }
  72. if chunkOffset == 0 && !isAppend {
  73. if dataSize < fs.option.SaveToFilerLimit {
  74. chunkOffset += dataSize
  75. smallContent = make([]byte, dataSize)
  76. bytesBuffer.Read(smallContent)
  77. bufPool.Put(bytesBuffer)
  78. <-bytesBufferLimitChan
  79. stats.FilerHandlerCounter.WithLabelValues(stats.ContentSaveToFiler).Inc()
  80. break
  81. }
  82. } else {
  83. stats.FilerHandlerCounter.WithLabelValues(stats.AutoChunk).Inc()
  84. }
  85. wg.Add(1)
  86. go func(offset int64, buf *bytes.Buffer) {
  87. defer func() {
  88. bufPool.Put(buf)
  89. <-bytesBufferLimitChan
  90. wg.Done()
  91. }()
  92. chunks, toChunkErr := fs.dataToChunk(fileName, contentType, buf.Bytes(), offset, so)
  93. if toChunkErr != nil {
  94. uploadErrLock.Lock()
  95. if uploadErr == nil {
  96. uploadErr = toChunkErr
  97. }
  98. uploadErrLock.Unlock()
  99. }
  100. if chunks != nil {
  101. fileChunksLock.Lock()
  102. fileChunksSize := len(fileChunks) + len(chunks)
  103. for _, chunk := range chunks {
  104. fileChunks = append(fileChunks, chunk)
  105. glog.V(4).Infof("uploaded %s chunk %d to %s [%d,%d)", fileName, fileChunksSize, chunk.FileId, offset, offset+int64(chunk.Size))
  106. }
  107. fileChunksLock.Unlock()
  108. }
  109. }(chunkOffset, bytesBuffer)
  110. // reset variables for the next chunk
  111. chunkOffset = chunkOffset + dataSize
  112. // if last chunk was not at full chunk size, but already exhausted the reader
  113. if dataSize < int64(chunkSize) {
  114. break
  115. }
  116. }
  117. wg.Wait()
  118. if uploadErr != nil {
  119. glog.V(0).Infof("upload file %s error: %v", fileName, uploadErr)
  120. for _, chunk := range fileChunks {
  121. glog.V(4).Infof("purging failed uploaded %s chunk %s [%d,%d)", fileName, chunk.FileId, chunk.Offset, chunk.Offset+int64(chunk.Size))
  122. }
  123. fs.filer.DeleteUncommittedChunks(fileChunks)
  124. return nil, md5Hash, 0, uploadErr, nil
  125. }
  126. slices.SortFunc(fileChunks, func(a, b *filer_pb.FileChunk) int {
  127. return int(a.Offset - b.Offset)
  128. })
  129. return fileChunks, md5Hash, chunkOffset, nil, smallContent
  130. }
  131. func (fs *FilerServer) doUpload(urlLocation string, limitedReader io.Reader, fileName string, contentType string, pairMap map[string]string, auth security.EncodedJwt) (*operation.UploadResult, error, []byte) {
  132. stats.FilerHandlerCounter.WithLabelValues(stats.ChunkUpload).Inc()
  133. start := time.Now()
  134. defer func() {
  135. stats.FilerRequestHistogram.WithLabelValues(stats.ChunkUpload).Observe(time.Since(start).Seconds())
  136. }()
  137. uploadOption := &operation.UploadOption{
  138. UploadUrl: urlLocation,
  139. Filename: fileName,
  140. Cipher: fs.option.Cipher,
  141. IsInputCompressed: false,
  142. MimeType: contentType,
  143. PairMap: pairMap,
  144. Jwt: auth,
  145. }
  146. uploader, err := operation.NewUploader()
  147. if err != nil {
  148. return nil, err, []byte{}
  149. }
  150. uploadResult, err, data := uploader.Upload(limitedReader, uploadOption)
  151. if uploadResult != nil && uploadResult.RetryCount > 0 {
  152. stats.FilerHandlerCounter.WithLabelValues(stats.ChunkUploadRetry).Add(float64(uploadResult.RetryCount))
  153. }
  154. return uploadResult, err, data
  155. }
  156. func (fs *FilerServer) dataToChunk(fileName, contentType string, data []byte, chunkOffset int64, so *operation.StorageOption) ([]*filer_pb.FileChunk, error) {
  157. dataReader := util.NewBytesReader(data)
  158. // retry to assign a different file id
  159. var fileId, urlLocation string
  160. var auth security.EncodedJwt
  161. var uploadErr error
  162. var uploadResult *operation.UploadResult
  163. var failedFileChunks []*filer_pb.FileChunk
  164. err := util.Retry("filerDataToChunk", func() error {
  165. // assign one file id for one chunk
  166. fileId, urlLocation, auth, uploadErr = fs.assignNewFileInfo(so)
  167. if uploadErr != nil {
  168. glog.V(4).Infof("retry later due to assign error: %v", uploadErr)
  169. stats.FilerHandlerCounter.WithLabelValues(stats.ChunkAssignRetry).Inc()
  170. return uploadErr
  171. }
  172. // upload the chunk to the volume server
  173. uploadResult, uploadErr, _ = fs.doUpload(urlLocation, dataReader, fileName, contentType, nil, auth)
  174. if uploadErr != nil {
  175. glog.V(4).Infof("retry later due to upload error: %v", uploadErr)
  176. stats.FilerHandlerCounter.WithLabelValues(stats.ChunkDoUploadRetry).Inc()
  177. fid, _ := filer_pb.ToFileIdObject(fileId)
  178. fileChunk := filer_pb.FileChunk{
  179. FileId: fileId,
  180. Offset: chunkOffset,
  181. Fid: fid,
  182. }
  183. failedFileChunks = append(failedFileChunks, &fileChunk)
  184. return uploadErr
  185. }
  186. return nil
  187. })
  188. if err != nil {
  189. glog.Errorf("upload error: %v", err)
  190. return failedFileChunks, err
  191. }
  192. // if last chunk exhausted the reader exactly at the border
  193. if uploadResult.Size == 0 {
  194. return nil, nil
  195. }
  196. return []*filer_pb.FileChunk{uploadResult.ToPbFileChunk(fileId, chunkOffset, time.Now().UnixNano())}, nil
  197. }