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.

212 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
more solid weed mount (#4089) * compare chunks by timestamp * fix slab clearing error * fix test compilation * move oldest chunk to sealed, instead of by fullness * lock on fh.entryViewCache * remove verbose logs * revert slat clearing * less logs * less logs * track write and read by timestamp * remove useless logic * add entry lock on file handle release * use mem chunk only, swap file chunk has problems * comment out code that maybe used later * add debug mode to compare data read and write * more efficient readResolvedChunks with linked list * small optimization * fix test compilation * minor fix on writer * add SeparateGarbageChunks * group chunks into sections * turn off debug mode * fix tests * fix tests * tmp enable swap file chunk * Revert "tmp enable swap file chunk" This reverts commit 985137ec472924e4815f258189f6ca9f2168a0a7. * simple refactoring * simple refactoring * do not re-use swap file chunk. Sealed chunks should not be re-used. * comment out debugging facilities * either mem chunk or swap file chunk is fine now * remove orderedMutex as *semaphore.Weighted not found impactful * optimize size calculation for changing large files * optimize performance to avoid going through the long list of chunks * still problems with swap file chunk * rename * tiny optimization * swap file chunk save only successfully read data * fix * enable both mem and swap file chunk * resolve chunks with range * rename * fix chunk interval list * also change file handle chunk group when adding chunks * pick in-active chunk with time-decayed counter * fix compilation * avoid nil with empty fh.entry * refactoring * rename * rename * refactor visible intervals to *list.List * refactor chunkViews to *list.List * add IntervalList for generic interval list * change visible interval to use IntervalList in generics * cahnge chunkViews to *IntervalList[*ChunkView] * use NewFileChunkSection to create * rename variables * refactor * fix renaming leftover * renaming * renaming * add insert interval * interval list adds lock * incrementally add chunks to readers Fixes: 1. set start and stop offset for the value object 2. clone the value object 3. use pointer instead of copy-by-value when passing to interval.Value 4. use insert interval since adding chunk could be out of order * fix tests compilation * fix tests compilation
2 years ago
4 years ago
  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) 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) {
  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. md5Hash = md5.New()
  42. var partReader = io.NopCloser(io.TeeReader(reader, md5Hash))
  43. var wg sync.WaitGroup
  44. var bytesBufferCounter int64 = 4
  45. bytesBufferLimitChan := make(chan struct{}, bytesBufferCounter)
  46. var fileChunksLock sync.Mutex
  47. var uploadErrLock sync.Mutex
  48. for {
  49. // need to throttle used byte buffer
  50. bytesBufferLimitChan <- struct{}{}
  51. bytesBuffer := bufPool.Get().(*bytes.Buffer)
  52. limitedReader := io.LimitReader(partReader, int64(chunkSize))
  53. bytesBuffer.Reset()
  54. dataSize, err := bytesBuffer.ReadFrom(limitedReader)
  55. // data, err := io.ReadAll(limitedReader)
  56. if err != nil || dataSize == 0 {
  57. bufPool.Put(bytesBuffer)
  58. <-bytesBufferLimitChan
  59. if err != nil {
  60. uploadErrLock.Lock()
  61. if uploadErr == nil {
  62. uploadErr = err
  63. }
  64. uploadErrLock.Unlock()
  65. }
  66. break
  67. }
  68. if chunkOffset == 0 && !isAppend {
  69. if dataSize < fs.option.SaveToFilerLimit {
  70. chunkOffset += dataSize
  71. smallContent = make([]byte, dataSize)
  72. bytesBuffer.Read(smallContent)
  73. bufPool.Put(bytesBuffer)
  74. <-bytesBufferLimitChan
  75. stats.FilerHandlerCounter.WithLabelValues(stats.ContentSaveToFiler).Inc()
  76. break
  77. }
  78. } else {
  79. stats.FilerHandlerCounter.WithLabelValues(stats.AutoChunk).Inc()
  80. }
  81. wg.Add(1)
  82. go func(offset int64) {
  83. defer func() {
  84. bufPool.Put(bytesBuffer)
  85. <-bytesBufferLimitChan
  86. wg.Done()
  87. }()
  88. chunks, toChunkErr := fs.dataToChunk(fileName, contentType, bytesBuffer.Bytes(), offset, so)
  89. if toChunkErr != nil {
  90. uploadErrLock.Lock()
  91. if uploadErr == nil {
  92. uploadErr = toChunkErr
  93. }
  94. uploadErrLock.Unlock()
  95. }
  96. if chunks != nil {
  97. fileChunksLock.Lock()
  98. fileChunksSize := len(fileChunks) + len(chunks)
  99. for _, chunk := range chunks {
  100. fileChunks = append(fileChunks, chunk)
  101. glog.V(4).Infof("uploaded %s chunk %d to %s [%d,%d)", fileName, fileChunksSize, chunk.FileId, offset, offset+int64(chunk.Size))
  102. }
  103. fileChunksLock.Unlock()
  104. }
  105. }(chunkOffset)
  106. // reset variables for the next chunk
  107. chunkOffset = chunkOffset + dataSize
  108. // if last chunk was not at full chunk size, but already exhausted the reader
  109. if dataSize < int64(chunkSize) {
  110. break
  111. }
  112. }
  113. wg.Wait()
  114. if uploadErr != nil {
  115. fs.filer.DeleteChunks(fileChunks)
  116. return nil, md5Hash, 0, uploadErr, nil
  117. }
  118. slices.SortFunc(fileChunks, func(a, b *filer_pb.FileChunk) int {
  119. return int(a.Offset - b.Offset)
  120. })
  121. return fileChunks, md5Hash, chunkOffset, nil, smallContent
  122. }
  123. func (fs *FilerServer) doUpload(urlLocation string, limitedReader io.Reader, fileName string, contentType string, pairMap map[string]string, auth security.EncodedJwt) (*operation.UploadResult, error, []byte) {
  124. stats.FilerHandlerCounter.WithLabelValues(stats.ChunkUpload).Inc()
  125. start := time.Now()
  126. defer func() {
  127. stats.FilerRequestHistogram.WithLabelValues(stats.ChunkUpload).Observe(time.Since(start).Seconds())
  128. }()
  129. uploadOption := &operation.UploadOption{
  130. UploadUrl: urlLocation,
  131. Filename: fileName,
  132. Cipher: fs.option.Cipher,
  133. IsInputCompressed: false,
  134. MimeType: contentType,
  135. PairMap: pairMap,
  136. Jwt: auth,
  137. }
  138. uploadResult, err, data := operation.Upload(limitedReader, uploadOption)
  139. if uploadResult != nil && uploadResult.RetryCount > 0 {
  140. stats.FilerHandlerCounter.WithLabelValues(stats.ChunkUploadRetry).Add(float64(uploadResult.RetryCount))
  141. }
  142. return uploadResult, err, data
  143. }
  144. func (fs *FilerServer) dataToChunk(fileName, contentType string, data []byte, chunkOffset int64, so *operation.StorageOption) ([]*filer_pb.FileChunk, error) {
  145. dataReader := util.NewBytesReader(data)
  146. // retry to assign a different file id
  147. var fileId, urlLocation string
  148. var auth security.EncodedJwt
  149. var uploadErr error
  150. var uploadResult *operation.UploadResult
  151. var failedFileChunks []*filer_pb.FileChunk
  152. err := util.Retry("filerDataToChunk", func() error {
  153. // assign one file id for one chunk
  154. fileId, urlLocation, auth, uploadErr = fs.assignNewFileInfo(so)
  155. if uploadErr != nil {
  156. glog.V(4).Infof("retry later due to assign error: %v", uploadErr)
  157. stats.FilerHandlerCounter.WithLabelValues(stats.ChunkAssignRetry).Inc()
  158. return uploadErr
  159. }
  160. // upload the chunk to the volume server
  161. uploadResult, uploadErr, _ = fs.doUpload(urlLocation, dataReader, fileName, contentType, nil, auth)
  162. if uploadErr != nil {
  163. glog.V(4).Infof("retry later due to upload error: %v", uploadErr)
  164. stats.FilerHandlerCounter.WithLabelValues(stats.ChunkDoUploadRetry).Inc()
  165. fid, _ := filer_pb.ToFileIdObject(fileId)
  166. fileChunk := filer_pb.FileChunk{
  167. FileId: fileId,
  168. Offset: chunkOffset,
  169. Fid: fid,
  170. }
  171. failedFileChunks = append(failedFileChunks, &fileChunk)
  172. return uploadErr
  173. }
  174. return nil
  175. })
  176. if err != nil {
  177. glog.Errorf("upload error: %v", err)
  178. return failedFileChunks, err
  179. }
  180. // if last chunk exhausted the reader exactly at the border
  181. if uploadResult.Size == 0 {
  182. return nil, nil
  183. }
  184. return []*filer_pb.FileChunk{uploadResult.ToPbFileChunk(fileId, chunkOffset, time.Now().UnixNano())}, nil
  185. }