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.

228 lines
7.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
2 months ago
4 years ago
2 months 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, buf *bytes.Buffer) {
  87. defer func() {
  88. bufPool.Put(buf)
  89. <-bytesBufferLimitChan
  90. wg.Done()
  91. }()
  92. chunks, toChunkErr := fs.dataToChunk(fileName, contentType, buf.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, bytesBuffer)
  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. glog.V(0).Infof("upload file %s error: %v", fileName, uploadErr)
  120. for _, chunk := range fileChunks {
  121. glog.V(4).Infof("purging failed uploaded %s chunk %s [%d,%d)", fileName, chunk.FileId, chunk.Offset, chunk.Offset+int64(chunk.Size))
  122. }
  123. fs.filer.DeleteUncommittedChunks(fileChunks)
  124. return nil, md5Hash, 0, uploadErr, nil
  125. }
  126. slices.SortFunc(fileChunks, func(a, b *filer_pb.FileChunk) int {
  127. return int(a.Offset - b.Offset)
  128. })
  129. return fileChunks, md5Hash, chunkOffset, nil, smallContent
  130. }
  131. func (fs *FilerServer) doUpload(urlLocation string, limitedReader io.Reader, fileName string, contentType string, pairMap map[string]string, auth security.EncodedJwt) (*operation.UploadResult, error, []byte) {
  132. stats.FilerHandlerCounter.WithLabelValues(stats.ChunkUpload).Inc()
  133. start := time.Now()
  134. defer func() {
  135. stats.FilerRequestHistogram.WithLabelValues(stats.ChunkUpload).Observe(time.Since(start).Seconds())
  136. }()
  137. uploadOption := &operation.UploadOption{
  138. UploadUrl: urlLocation,
  139. Filename: fileName,
  140. Cipher: fs.option.Cipher,
  141. IsInputCompressed: false,
  142. MimeType: contentType,
  143. PairMap: pairMap,
  144. Jwt: auth,
  145. }
  146. uploader, err := operation.NewUploader()
  147. if err != nil {
  148. return nil, err, []byte{}
  149. }
  150. uploadResult, err, data := uploader.Upload(limitedReader, uploadOption)
  151. if uploadResult != nil && uploadResult.RetryCount > 0 {
  152. stats.FilerHandlerCounter.WithLabelValues(stats.ChunkUploadRetry).Add(float64(uploadResult.RetryCount))
  153. }
  154. return uploadResult, err, data
  155. }
  156. func (fs *FilerServer) dataToChunk(fileName, contentType string, data []byte, chunkOffset int64, so *operation.StorageOption) ([]*filer_pb.FileChunk, error) {
  157. dataReader := util.NewBytesReader(data)
  158. // retry to assign a different file id
  159. var fileId, urlLocation string
  160. var auth security.EncodedJwt
  161. var uploadErr error
  162. var uploadResult *operation.UploadResult
  163. var failedFileChunks []*filer_pb.FileChunk
  164. err := util.Retry("filerDataToChunk", func() error {
  165. // assign one file id for one chunk
  166. fileId, urlLocation, auth, uploadErr = fs.assignNewFileInfo(so)
  167. if uploadErr != nil {
  168. glog.V(4).Infof("retry later due to assign error: %v", uploadErr)
  169. stats.FilerHandlerCounter.WithLabelValues(stats.ChunkAssignRetry).Inc()
  170. return uploadErr
  171. }
  172. // upload the chunk to the volume server
  173. uploadResult, uploadErr, _ = fs.doUpload(urlLocation, dataReader, fileName, contentType, nil, auth)
  174. if uploadErr != nil {
  175. glog.V(4).Infof("retry later due to upload error: %v", uploadErr)
  176. stats.FilerHandlerCounter.WithLabelValues(stats.ChunkDoUploadRetry).Inc()
  177. fid, _ := filer_pb.ToFileIdObject(fileId)
  178. fileChunk := filer_pb.FileChunk{
  179. FileId: fileId,
  180. Offset: chunkOffset,
  181. Fid: fid,
  182. }
  183. failedFileChunks = append(failedFileChunks, &fileChunk)
  184. return uploadErr
  185. }
  186. return nil
  187. })
  188. if err != nil {
  189. glog.Errorf("upload error: %v", err)
  190. return failedFileChunks, err
  191. }
  192. // if last chunk exhausted the reader exactly at the border
  193. if uploadResult.Size == 0 {
  194. return nil, nil
  195. }
  196. return []*filer_pb.FileChunk{uploadResult.ToPbFileChunk(fileId, chunkOffset, time.Now().UnixNano())}, nil
  197. }