filer_server_handlers_write_upload.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  1. package weed_server
  2. import (
  3. "bytes"
  4. "crypto/md5"
  5. "fmt"
  6. "hash"
  7. "io"
  8. "net/http"
  9. "sort"
  10. "strconv"
  11. "strings"
  12. "sync"
  13. "sync/atomic"
  14. "time"
  15. "github.com/chrislusf/seaweedfs/weed/filer"
  16. "github.com/chrislusf/seaweedfs/weed/glog"
  17. "github.com/chrislusf/seaweedfs/weed/operation"
  18. "github.com/chrislusf/seaweedfs/weed/pb/filer_pb"
  19. "github.com/chrislusf/seaweedfs/weed/security"
  20. "github.com/chrislusf/seaweedfs/weed/stats"
  21. "github.com/chrislusf/seaweedfs/weed/util"
  22. )
  23. var bufPool = sync.Pool{
  24. New: func() interface{} {
  25. return new(bytes.Buffer)
  26. },
  27. }
  28. 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) {
  29. query := r.URL.Query()
  30. isAppend := query.Get("op") == "append"
  31. if query.Has("offset") {
  32. offset := query.Get("offset")
  33. offsetInt, err := strconv.ParseInt(offset, 10, 64)
  34. if err != nil || offsetInt < 0 {
  35. err = fmt.Errorf("invalid 'offset': '%s'", offset)
  36. return nil, nil, 0, err, nil
  37. }
  38. if isAppend && offsetInt > 0 {
  39. err = fmt.Errorf("cannot set offset when op=append")
  40. return nil, nil, 0, err, nil
  41. }
  42. chunkOffset = offsetInt
  43. }
  44. md5Hash = md5.New()
  45. var partReader = io.NopCloser(io.TeeReader(reader, md5Hash))
  46. var wg sync.WaitGroup
  47. var bytesBufferCounter int64
  48. bytesBufferLimitCond := sync.NewCond(new(sync.Mutex))
  49. var fileChunksLock sync.Mutex
  50. for {
  51. // need to throttle used byte buffer
  52. bytesBufferLimitCond.L.Lock()
  53. for atomic.LoadInt64(&bytesBufferCounter) >= 4 {
  54. glog.V(4).Infof("waiting for byte buffer %d", bytesBufferCounter)
  55. bytesBufferLimitCond.Wait()
  56. }
  57. atomic.AddInt64(&bytesBufferCounter, 1)
  58. bytesBufferLimitCond.L.Unlock()
  59. bytesBuffer := bufPool.Get().(*bytes.Buffer)
  60. glog.V(4).Infof("received byte buffer %d", bytesBufferCounter)
  61. limitedReader := io.LimitReader(partReader, int64(chunkSize))
  62. bytesBuffer.Reset()
  63. dataSize, err := bytesBuffer.ReadFrom(limitedReader)
  64. // data, err := io.ReadAll(limitedReader)
  65. if err != nil || dataSize == 0 {
  66. bufPool.Put(bytesBuffer)
  67. atomic.AddInt64(&bytesBufferCounter, -1)
  68. bytesBufferLimitCond.Signal()
  69. break
  70. }
  71. if chunkOffset == 0 && !isAppend {
  72. if dataSize < fs.option.SaveToFilerLimit || strings.HasPrefix(r.URL.Path, filer.DirectoryEtcRoot) {
  73. chunkOffset += dataSize
  74. smallContent = make([]byte, dataSize)
  75. bytesBuffer.Read(smallContent)
  76. bufPool.Put(bytesBuffer)
  77. atomic.AddInt64(&bytesBufferCounter, -1)
  78. bytesBufferLimitCond.Signal()
  79. break
  80. }
  81. }
  82. wg.Add(1)
  83. go func(offset int64) {
  84. defer func() {
  85. bufPool.Put(bytesBuffer)
  86. atomic.AddInt64(&bytesBufferCounter, -1)
  87. bytesBufferLimitCond.Signal()
  88. wg.Done()
  89. }()
  90. chunk, toChunkErr := fs.dataToChunk(fileName, contentType, bytesBuffer.Bytes(), offset, so)
  91. if toChunkErr != nil {
  92. uploadErr = toChunkErr
  93. }
  94. if chunk != nil {
  95. fileChunksLock.Lock()
  96. fileChunks = append(fileChunks, chunk)
  97. fileChunksLock.Unlock()
  98. glog.V(4).Infof("uploaded %s chunk %d to %s [%d,%d)", fileName, len(fileChunks), chunk.FileId, offset, offset+int64(chunk.Size))
  99. }
  100. }(chunkOffset)
  101. // reset variables for the next chunk
  102. chunkOffset = chunkOffset + dataSize
  103. // if last chunk was not at full chunk size, but already exhausted the reader
  104. if dataSize < int64(chunkSize) {
  105. break
  106. }
  107. }
  108. wg.Wait()
  109. if uploadErr != nil {
  110. return nil, md5Hash, 0, uploadErr, nil
  111. }
  112. sort.Slice(fileChunks, func(i, j int) bool {
  113. return fileChunks[i].Offset < fileChunks[j].Offset
  114. })
  115. return fileChunks, md5Hash, chunkOffset, nil, smallContent
  116. }
  117. func (fs *FilerServer) doUpload(urlLocation string, limitedReader io.Reader, fileName string, contentType string, pairMap map[string]string, auth security.EncodedJwt) (*operation.UploadResult, error, []byte) {
  118. stats.FilerRequestCounter.WithLabelValues("chunkUpload").Inc()
  119. start := time.Now()
  120. defer func() {
  121. stats.FilerRequestHistogram.WithLabelValues("chunkUpload").Observe(time.Since(start).Seconds())
  122. }()
  123. uploadOption := &operation.UploadOption{
  124. UploadUrl: urlLocation,
  125. Filename: fileName,
  126. Cipher: fs.option.Cipher,
  127. IsInputCompressed: false,
  128. MimeType: contentType,
  129. PairMap: pairMap,
  130. Jwt: auth,
  131. }
  132. uploadResult, err, data := operation.Upload(limitedReader, uploadOption)
  133. if uploadResult != nil && uploadResult.RetryCount > 0 {
  134. stats.FilerRequestCounter.WithLabelValues("chunkUploadRetry").Add(float64(uploadResult.RetryCount))
  135. }
  136. return uploadResult, err, data
  137. }
  138. func (fs *FilerServer) dataToChunk(fileName, contentType string, data []byte, chunkOffset int64, so *operation.StorageOption) (*filer_pb.FileChunk, error) {
  139. dataReader := util.NewBytesReader(data)
  140. // retry to assign a different file id
  141. var fileId, urlLocation string
  142. var auth security.EncodedJwt
  143. var uploadErr error
  144. var uploadResult *operation.UploadResult
  145. for i := 0; i < 3; i++ {
  146. // assign one file id for one chunk
  147. fileId, urlLocation, auth, uploadErr = fs.assignNewFileInfo(so)
  148. if uploadErr != nil {
  149. glog.V(4).Infof("retry later due to assign error: %v", uploadErr)
  150. time.Sleep(time.Duration(i+1) * 251 * time.Millisecond)
  151. continue
  152. }
  153. // upload the chunk to the volume server
  154. uploadResult, uploadErr, _ = fs.doUpload(urlLocation, dataReader, fileName, contentType, nil, auth)
  155. if uploadErr != nil {
  156. glog.V(4).Infof("retry later due to upload error: %v", uploadErr)
  157. time.Sleep(time.Duration(i+1) * 251 * time.Millisecond)
  158. continue
  159. }
  160. break
  161. }
  162. if uploadErr != nil {
  163. glog.Errorf("upload error: %v", uploadErr)
  164. return nil, uploadErr
  165. }
  166. // if last chunk exhausted the reader exactly at the border
  167. if uploadResult.Size == 0 {
  168. return nil, nil
  169. }
  170. return uploadResult.ToPbFileChunk(fileId, chunkOffset), nil
  171. }