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.1 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. uploadErrLock.Lock()
  60. uploadErr = err
  61. uploadErrLock.Unlock()
  62. break
  63. }
  64. if chunkOffset == 0 && !isAppend {
  65. if dataSize < fs.option.SaveToFilerLimit {
  66. chunkOffset += dataSize
  67. smallContent = make([]byte, dataSize)
  68. bytesBuffer.Read(smallContent)
  69. bufPool.Put(bytesBuffer)
  70. <-bytesBufferLimitChan
  71. stats.FilerRequestCounter.WithLabelValues(stats.ContentSaveToFiler).Inc()
  72. break
  73. }
  74. } else {
  75. stats.FilerRequestCounter.WithLabelValues(stats.AutoChunk).Inc()
  76. }
  77. wg.Add(1)
  78. go func(offset int64) {
  79. defer func() {
  80. bufPool.Put(bytesBuffer)
  81. <-bytesBufferLimitChan
  82. wg.Done()
  83. }()
  84. chunks, toChunkErr := fs.dataToChunk(fileName, contentType, bytesBuffer.Bytes(), offset, so)
  85. if toChunkErr != nil {
  86. uploadErrLock.Lock()
  87. if uploadErr == nil {
  88. uploadErr = toChunkErr
  89. }
  90. uploadErrLock.Unlock()
  91. }
  92. if chunks != nil {
  93. fileChunksLock.Lock()
  94. fileChunksSize := len(fileChunks) + len(chunks)
  95. for _, chunk := range chunks {
  96. fileChunks = append(fileChunks, chunk)
  97. glog.V(4).Infof("uploaded %s chunk %d to %s [%d,%d)", fileName, fileChunksSize, chunk.FileId, offset, offset+int64(chunk.Size))
  98. }
  99. fileChunksLock.Unlock()
  100. }
  101. }(chunkOffset)
  102. // reset variables for the next chunk
  103. chunkOffset = chunkOffset + dataSize
  104. // if last chunk was not at full chunk size, but already exhausted the reader
  105. if dataSize < int64(chunkSize) {
  106. break
  107. }
  108. }
  109. wg.Wait()
  110. if uploadErr != nil {
  111. fs.filer.DeleteChunks(fileChunks)
  112. return nil, md5Hash, 0, uploadErr, nil
  113. }
  114. slices.SortFunc(fileChunks, func(a, b *filer_pb.FileChunk) bool {
  115. return a.Offset < b.Offset
  116. })
  117. return fileChunks, md5Hash, chunkOffset, nil, smallContent
  118. }
  119. func (fs *FilerServer) doUpload(urlLocation string, limitedReader io.Reader, fileName string, contentType string, pairMap map[string]string, auth security.EncodedJwt) (*operation.UploadResult, error, []byte) {
  120. stats.FilerRequestCounter.WithLabelValues(stats.ChunkUpload).Inc()
  121. start := time.Now()
  122. defer func() {
  123. stats.FilerRequestHistogram.WithLabelValues(stats.ChunkUpload).Observe(time.Since(start).Seconds())
  124. }()
  125. uploadOption := &operation.UploadOption{
  126. UploadUrl: urlLocation,
  127. Filename: fileName,
  128. Cipher: fs.option.Cipher,
  129. IsInputCompressed: false,
  130. MimeType: contentType,
  131. PairMap: pairMap,
  132. Jwt: auth,
  133. }
  134. uploadResult, err, data := operation.Upload(limitedReader, uploadOption)
  135. if uploadResult != nil && uploadResult.RetryCount > 0 {
  136. stats.FilerRequestCounter.WithLabelValues(stats.ChunkUploadRetry).Add(float64(uploadResult.RetryCount))
  137. }
  138. return uploadResult, err, data
  139. }
  140. func (fs *FilerServer) dataToChunk(fileName, contentType string, data []byte, chunkOffset int64, so *operation.StorageOption) ([]*filer_pb.FileChunk, error) {
  141. dataReader := util.NewBytesReader(data)
  142. // retry to assign a different file id
  143. var fileId, urlLocation string
  144. var auth security.EncodedJwt
  145. var uploadErr error
  146. var uploadResult *operation.UploadResult
  147. var failedFileChunks []*filer_pb.FileChunk
  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. fid, _ := filer_pb.ToFileIdObject(fileId)
  162. fileChunk := filer_pb.FileChunk{
  163. FileId: fileId,
  164. Offset: chunkOffset,
  165. Fid: fid,
  166. }
  167. failedFileChunks = append(failedFileChunks, &fileChunk)
  168. return uploadErr
  169. }
  170. return nil
  171. })
  172. if err != nil {
  173. glog.Errorf("upload error: %v", err)
  174. return failedFileChunks, 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 []*filer_pb.FileChunk{uploadResult.ToPbFileChunk(fileId, chunkOffset, time.Now().UnixNano())}, nil
  181. }