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.

224 lines
6.7 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
6 months 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) uploadRequestToChunks(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. return fs.uploadReaderToChunks(reader, chunkOffset, chunkSize, fileName, contentType, isAppend, so)
  42. }
  43. func (fs *FilerServer) uploadReaderToChunks(reader io.Reader, startOffset int64, chunkSize int32, fileName, contentType string, isAppend bool, so *operation.StorageOption) (fileChunks []*filer_pb.FileChunk, md5Hash hash.Hash, chunkOffset int64, uploadErr error, smallContent []byte) {
  44. md5Hash = md5.New()
  45. chunkOffset = startOffset
  46. var partReader = io.NopCloser(io.TeeReader(reader, md5Hash))
  47. var wg sync.WaitGroup
  48. var bytesBufferCounter int64 = 4
  49. bytesBufferLimitChan := make(chan struct{}, bytesBufferCounter)
  50. var fileChunksLock sync.Mutex
  51. var uploadErrLock sync.Mutex
  52. for {
  53. // need to throttle used byte buffer
  54. bytesBufferLimitChan <- struct{}{}
  55. bytesBuffer := bufPool.Get().(*bytes.Buffer)
  56. limitedReader := io.LimitReader(partReader, int64(chunkSize))
  57. bytesBuffer.Reset()
  58. dataSize, err := bytesBuffer.ReadFrom(limitedReader)
  59. // data, err := io.ReadAll(limitedReader)
  60. if err != nil || dataSize == 0 {
  61. bufPool.Put(bytesBuffer)
  62. <-bytesBufferLimitChan
  63. if err != nil {
  64. uploadErrLock.Lock()
  65. if uploadErr == nil {
  66. uploadErr = err
  67. }
  68. uploadErrLock.Unlock()
  69. }
  70. break
  71. }
  72. if chunkOffset == 0 && !isAppend {
  73. if dataSize < fs.option.SaveToFilerLimit {
  74. chunkOffset += dataSize
  75. smallContent = make([]byte, dataSize)
  76. bytesBuffer.Read(smallContent)
  77. bufPool.Put(bytesBuffer)
  78. <-bytesBufferLimitChan
  79. stats.FilerHandlerCounter.WithLabelValues(stats.ContentSaveToFiler).Inc()
  80. break
  81. }
  82. } else {
  83. stats.FilerHandlerCounter.WithLabelValues(stats.AutoChunk).Inc()
  84. }
  85. wg.Add(1)
  86. go func(offset int64) {
  87. defer func() {
  88. bufPool.Put(bytesBuffer)
  89. <-bytesBufferLimitChan
  90. wg.Done()
  91. }()
  92. chunks, toChunkErr := fs.dataToChunk(fileName, contentType, bytesBuffer.Bytes(), offset, so)
  93. if toChunkErr != nil {
  94. uploadErrLock.Lock()
  95. if uploadErr == nil {
  96. uploadErr = toChunkErr
  97. }
  98. uploadErrLock.Unlock()
  99. }
  100. if chunks != nil {
  101. fileChunksLock.Lock()
  102. fileChunksSize := len(fileChunks) + len(chunks)
  103. for _, chunk := range chunks {
  104. fileChunks = append(fileChunks, chunk)
  105. glog.V(4).Infof("uploaded %s chunk %d to %s [%d,%d)", fileName, fileChunksSize, chunk.FileId, offset, offset+int64(chunk.Size))
  106. }
  107. fileChunksLock.Unlock()
  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.DeleteUncommittedChunks(fileChunks)
  120. return nil, md5Hash, 0, uploadErr, nil
  121. }
  122. slices.SortFunc(fileChunks, func(a, b *filer_pb.FileChunk) int {
  123. return int(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.FilerHandlerCounter.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. uploader, err := operation.NewUploader()
  143. if err != nil {
  144. return nil, err, []byte{}
  145. }
  146. uploadResult, err, data := uploader.Upload(limitedReader, uploadOption)
  147. if uploadResult != nil && uploadResult.RetryCount > 0 {
  148. stats.FilerHandlerCounter.WithLabelValues(stats.ChunkUploadRetry).Add(float64(uploadResult.RetryCount))
  149. }
  150. return uploadResult, err, data
  151. }
  152. func (fs *FilerServer) dataToChunk(fileName, contentType string, data []byte, chunkOffset int64, so *operation.StorageOption) ([]*filer_pb.FileChunk, error) {
  153. dataReader := util.NewBytesReader(data)
  154. // retry to assign a different file id
  155. var fileId, urlLocation string
  156. var auth security.EncodedJwt
  157. var uploadErr error
  158. var uploadResult *operation.UploadResult
  159. var failedFileChunks []*filer_pb.FileChunk
  160. err := util.Retry("filerDataToChunk", func() error {
  161. // assign one file id for one chunk
  162. fileId, urlLocation, auth, uploadErr = fs.assignNewFileInfo(so)
  163. if uploadErr != nil {
  164. glog.V(4).Infof("retry later due to assign error: %v", uploadErr)
  165. stats.FilerHandlerCounter.WithLabelValues(stats.ChunkAssignRetry).Inc()
  166. return uploadErr
  167. }
  168. // upload the chunk to the volume server
  169. uploadResult, uploadErr, _ = fs.doUpload(urlLocation, dataReader, fileName, contentType, nil, auth)
  170. if uploadErr != nil {
  171. glog.V(4).Infof("retry later due to upload error: %v", uploadErr)
  172. stats.FilerHandlerCounter.WithLabelValues(stats.ChunkDoUploadRetry).Inc()
  173. fid, _ := filer_pb.ToFileIdObject(fileId)
  174. fileChunk := filer_pb.FileChunk{
  175. FileId: fileId,
  176. Offset: chunkOffset,
  177. Fid: fid,
  178. }
  179. failedFileChunks = append(failedFileChunks, &fileChunk)
  180. return uploadErr
  181. }
  182. return nil
  183. })
  184. if err != nil {
  185. glog.Errorf("upload error: %v", err)
  186. return failedFileChunks, err
  187. }
  188. // if last chunk exhausted the reader exactly at the border
  189. if uploadResult.Size == 0 {
  190. return nil, nil
  191. }
  192. return []*filer_pb.FileChunk{uploadResult.ToPbFileChunk(fileId, chunkOffset, time.Now().UnixNano())}, nil
  193. }