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.

201 lines
6.0 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. for {
  49. // need to throttle used byte buffer
  50. bytesBufferLimitCond.L.Lock()
  51. for atomic.LoadInt64(&bytesBufferCounter) >= 4 {
  52. glog.V(4).Infof("waiting for byte buffer %d", bytesBufferCounter)
  53. bytesBufferLimitCond.Wait()
  54. }
  55. atomic.AddInt64(&bytesBufferCounter, 1)
  56. bytesBufferLimitCond.L.Unlock()
  57. bytesBuffer := bufPool.Get().(*bytes.Buffer)
  58. glog.V(4).Infof("received byte buffer %d", bytesBufferCounter)
  59. limitedReader := io.LimitReader(partReader, int64(chunkSize))
  60. bytesBuffer.Reset()
  61. dataSize, err := bytesBuffer.ReadFrom(limitedReader)
  62. // data, err := io.ReadAll(limitedReader)
  63. if err != nil || dataSize == 0 {
  64. bufPool.Put(bytesBuffer)
  65. atomic.AddInt64(&bytesBufferCounter, -1)
  66. bytesBufferLimitCond.Signal()
  67. uploadErr = err
  68. break
  69. }
  70. if chunkOffset == 0 && !isAppend {
  71. if dataSize < fs.option.SaveToFilerLimit {
  72. chunkOffset += dataSize
  73. smallContent = make([]byte, dataSize)
  74. bytesBuffer.Read(smallContent)
  75. bufPool.Put(bytesBuffer)
  76. atomic.AddInt64(&bytesBufferCounter, -1)
  77. bytesBufferLimitCond.Signal()
  78. stats.FilerRequestCounter.WithLabelValues(stats.ContentSaveToFiler).Inc()
  79. break
  80. }
  81. } else {
  82. stats.FilerRequestCounter.WithLabelValues(stats.AutoChunk).Inc()
  83. }
  84. wg.Add(1)
  85. go func(offset int64) {
  86. defer func() {
  87. bufPool.Put(bytesBuffer)
  88. atomic.AddInt64(&bytesBufferCounter, -1)
  89. bytesBufferLimitCond.Signal()
  90. wg.Done()
  91. }()
  92. chunk, toChunkErr := fs.dataToChunk(fileName, contentType, bytesBuffer.Bytes(), offset, so)
  93. if toChunkErr != nil {
  94. uploadErr = toChunkErr
  95. }
  96. if chunk != nil {
  97. fileChunksLock.Lock()
  98. fileChunks = append(fileChunks, chunk)
  99. fileChunksLock.Unlock()
  100. glog.V(4).Infof("uploaded %s chunk %d to %s [%d,%d)", fileName, len(fileChunks), chunk.FileId, offset, offset+int64(chunk.Size))
  101. }
  102. }(chunkOffset)
  103. // reset variables for the next chunk
  104. chunkOffset = chunkOffset + dataSize
  105. // if last chunk was not at full chunk size, but already exhausted the reader
  106. if dataSize < int64(chunkSize) {
  107. break
  108. }
  109. }
  110. wg.Wait()
  111. if uploadErr != nil {
  112. fs.filer.DeleteChunks(fileChunks)
  113. return nil, md5Hash, 0, uploadErr, nil
  114. }
  115. slices.SortFunc(fileChunks, func(a, b *filer_pb.FileChunk) bool {
  116. return a.Offset < b.Offset
  117. })
  118. return fileChunks, md5Hash, chunkOffset, nil, smallContent
  119. }
  120. func (fs *FilerServer) doUpload(urlLocation string, limitedReader io.Reader, fileName string, contentType string, pairMap map[string]string, auth security.EncodedJwt) (*operation.UploadResult, error, []byte) {
  121. stats.FilerRequestCounter.WithLabelValues(stats.ChunkUpload).Inc()
  122. start := time.Now()
  123. defer func() {
  124. stats.FilerRequestHistogram.WithLabelValues(stats.ChunkUpload).Observe(time.Since(start).Seconds())
  125. }()
  126. uploadOption := &operation.UploadOption{
  127. UploadUrl: urlLocation,
  128. Filename: fileName,
  129. Cipher: fs.option.Cipher,
  130. IsInputCompressed: false,
  131. MimeType: contentType,
  132. PairMap: pairMap,
  133. Jwt: auth,
  134. }
  135. uploadResult, err, data := operation.Upload(limitedReader, uploadOption)
  136. if uploadResult != nil && uploadResult.RetryCount > 0 {
  137. stats.FilerRequestCounter.WithLabelValues(stats.ChunkUploadRetry).Add(float64(uploadResult.RetryCount))
  138. }
  139. return uploadResult, err, data
  140. }
  141. func (fs *FilerServer) dataToChunk(fileName, contentType string, data []byte, chunkOffset int64, so *operation.StorageOption) (*filer_pb.FileChunk, error) {
  142. dataReader := util.NewBytesReader(data)
  143. // retry to assign a different file id
  144. var fileId, urlLocation string
  145. var auth security.EncodedJwt
  146. var uploadErr error
  147. var uploadResult *operation.UploadResult
  148. err := util.Retry("filerDataToChunk", func() error {
  149. // assign one file id for one chunk
  150. fileId, urlLocation, auth, uploadErr = fs.assignNewFileInfo(so)
  151. if uploadErr != nil {
  152. glog.V(4).Infof("retry later due to assign error: %v", uploadErr)
  153. stats.FilerRequestCounter.WithLabelValues(stats.ChunkAssignRetry).Inc()
  154. return uploadErr
  155. }
  156. // upload the chunk to the volume server
  157. uploadResult, uploadErr, _ = fs.doUpload(urlLocation, dataReader, fileName, contentType, nil, auth)
  158. if uploadErr != nil {
  159. glog.V(4).Infof("retry later due to upload error: %v", uploadErr)
  160. stats.FilerRequestCounter.WithLabelValues(stats.ChunkDoUploadRetry).Inc()
  161. return uploadErr
  162. }
  163. return nil
  164. })
  165. if err != nil {
  166. glog.Errorf("upload error: %v", err)
  167. return nil, err
  168. }
  169. // if last chunk exhausted the reader exactly at the border
  170. if uploadResult.Size == 0 {
  171. return nil, nil
  172. }
  173. return uploadResult.ToPbFileChunk(fileId, chunkOffset), nil
  174. }