filer_server_handlers_write_upload.go 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  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) {
  87. defer func() {
  88. bufPool.Put(bytesBuffer)
  89. <-bytesBufferLimitChan
  90. wg.Done()
  91. }()
  92. chunks, toChunkErr := fs.dataToChunk(fileName, contentType, bytesBuffer.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)
  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. fs.filer.DeleteUncommittedChunks(fileChunks)
  120. return nil, md5Hash, 0, uploadErr, nil
  121. }
  122. slices.SortFunc(fileChunks, func(a, b *filer_pb.FileChunk) int {
  123. return int(a.Offset - b.Offset)
  124. })
  125. return fileChunks, md5Hash, chunkOffset, nil, smallContent
  126. }
  127. func (fs *FilerServer) doUpload(urlLocation string, limitedReader io.Reader, fileName string, contentType string, pairMap map[string]string, auth security.EncodedJwt) (*operation.UploadResult, error, []byte) {
  128. stats.FilerHandlerCounter.WithLabelValues(stats.ChunkUpload).Inc()
  129. start := time.Now()
  130. defer func() {
  131. stats.FilerRequestHistogram.WithLabelValues(stats.ChunkUpload).Observe(time.Since(start).Seconds())
  132. }()
  133. uploadOption := &operation.UploadOption{
  134. UploadUrl: urlLocation,
  135. Filename: fileName,
  136. Cipher: fs.option.Cipher,
  137. IsInputCompressed: false,
  138. MimeType: contentType,
  139. PairMap: pairMap,
  140. Jwt: auth,
  141. }
  142. uploader, err := operation.NewUploader()
  143. if err != nil {
  144. return nil, err, []byte{}
  145. }
  146. uploadResult, err, data := uploader.Upload(limitedReader, uploadOption)
  147. if uploadResult != nil && uploadResult.RetryCount > 0 {
  148. stats.FilerHandlerCounter.WithLabelValues(stats.ChunkUploadRetry).Add(float64(uploadResult.RetryCount))
  149. }
  150. return uploadResult, err, data
  151. }
  152. func (fs *FilerServer) dataToChunk(fileName, contentType string, data []byte, chunkOffset int64, so *operation.StorageOption) ([]*filer_pb.FileChunk, error) {
  153. dataReader := util.NewBytesReader(data)
  154. // retry to assign a different file id
  155. var fileId, urlLocation string
  156. var auth security.EncodedJwt
  157. var uploadErr error
  158. var uploadResult *operation.UploadResult
  159. var failedFileChunks []*filer_pb.FileChunk
  160. err := util.Retry("filerDataToChunk", func() error {
  161. // assign one file id for one chunk
  162. fileId, urlLocation, auth, uploadErr = fs.assignNewFileInfo(so)
  163. if uploadErr != nil {
  164. glog.V(4).Infof("retry later due to assign error: %v", uploadErr)
  165. stats.FilerHandlerCounter.WithLabelValues(stats.ChunkAssignRetry).Inc()
  166. return uploadErr
  167. }
  168. // upload the chunk to the volume server
  169. uploadResult, uploadErr, _ = fs.doUpload(urlLocation, dataReader, fileName, contentType, nil, auth)
  170. if uploadErr != nil {
  171. glog.V(4).Infof("retry later due to upload error: %v", uploadErr)
  172. stats.FilerHandlerCounter.WithLabelValues(stats.ChunkDoUploadRetry).Inc()
  173. fid, _ := filer_pb.ToFileIdObject(fileId)
  174. fileChunk := filer_pb.FileChunk{
  175. FileId: fileId,
  176. Offset: chunkOffset,
  177. Fid: fid,
  178. }
  179. failedFileChunks = append(failedFileChunks, &fileChunk)
  180. return uploadErr
  181. }
  182. return nil
  183. })
  184. if err != nil {
  185. glog.Errorf("upload error: %v", err)
  186. return failedFileChunks, err
  187. }
  188. // if last chunk exhausted the reader exactly at the border
  189. if uploadResult.Size == 0 {
  190. return nil, nil
  191. }
  192. return []*filer_pb.FileChunk{uploadResult.ToPbFileChunk(fileId, chunkOffset, time.Now().UnixNano())}, nil
  193. }