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.

208 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. fileChunksLock.Unlock()
  107. glog.V(4).Infof("uploaded %s chunk %d to %s [%d,%d)", fileName, len(fileChunks), chunk.FileId, offset, offset+int64(chunk.Size))
  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.DeleteChunks(fileChunks)
  120. return nil, md5Hash, 0, uploadErr, nil
  121. }
  122. slices.SortFunc(fileChunks, func(a, b *filer_pb.FileChunk) bool {
  123. return 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.FilerRequestCounter.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. uploadResult, err, data := operation.Upload(limitedReader, uploadOption)
  143. if uploadResult != nil && uploadResult.RetryCount > 0 {
  144. stats.FilerRequestCounter.WithLabelValues(stats.ChunkUploadRetry).Add(float64(uploadResult.RetryCount))
  145. }
  146. return uploadResult, err, data
  147. }
  148. func (fs *FilerServer) dataToChunk(fileName, contentType string, data []byte, chunkOffset int64, so *operation.StorageOption) (*filer_pb.FileChunk, error) {
  149. dataReader := util.NewBytesReader(data)
  150. // retry to assign a different file id
  151. var fileId, urlLocation string
  152. var auth security.EncodedJwt
  153. var uploadErr error
  154. var uploadResult *operation.UploadResult
  155. err := util.Retry("filerDataToChunk", func() error {
  156. // assign one file id for one chunk
  157. fileId, urlLocation, auth, uploadErr = fs.assignNewFileInfo(so)
  158. if uploadErr != nil {
  159. glog.V(4).Infof("retry later due to assign error: %v", uploadErr)
  160. stats.FilerRequestCounter.WithLabelValues(stats.ChunkAssignRetry).Inc()
  161. return uploadErr
  162. }
  163. // upload the chunk to the volume server
  164. uploadResult, uploadErr, _ = fs.doUpload(urlLocation, dataReader, fileName, contentType, nil, auth)
  165. if uploadErr != nil {
  166. glog.V(4).Infof("retry later due to upload error: %v", uploadErr)
  167. stats.FilerRequestCounter.WithLabelValues(stats.ChunkDoUploadRetry).Inc()
  168. return uploadErr
  169. }
  170. return nil
  171. })
  172. if err != nil {
  173. glog.Errorf("upload error: %v", err)
  174. return nil, err
  175. }
  176. // if last chunk exhausted the reader exactly at the border
  177. if uploadResult.Size == 0 {
  178. return nil, nil
  179. }
  180. return uploadResult.ToPbFileChunk(fileId, chunkOffset), nil
  181. }