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.

209 lines
6.2 KiB

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