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.

260 lines
7.1 KiB

3 years ago
4 years ago
4 years ago
4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
5 years ago
5 years ago
  1. package filer
  2. import (
  3. "bytes"
  4. "fmt"
  5. "io"
  6. "math"
  7. "sort"
  8. "strings"
  9. "time"
  10. "github.com/chrislusf/seaweedfs/weed/glog"
  11. "github.com/chrislusf/seaweedfs/weed/pb/filer_pb"
  12. "github.com/chrislusf/seaweedfs/weed/stats"
  13. "github.com/chrislusf/seaweedfs/weed/util"
  14. "github.com/chrislusf/seaweedfs/weed/wdclient"
  15. )
  16. func StreamContent(masterClient wdclient.HasLookupFileIdFunction, writer io.Writer, chunks []*filer_pb.FileChunk, offset int64, size int64) error {
  17. glog.V(9).Infof("start to stream content for chunks: %+v\n", chunks)
  18. chunkViews := ViewFromChunks(masterClient.GetLookupFileIdFunction(), chunks, offset, size)
  19. fileId2Url := make(map[string][]string)
  20. for _, chunkView := range chunkViews {
  21. urlStrings, err := masterClient.GetLookupFileIdFunction()(chunkView.FileId)
  22. if err != nil {
  23. glog.V(1).Infof("operation LookupFileId %s failed, err: %v", chunkView.FileId, err)
  24. return err
  25. } else if len(urlStrings) == 0 {
  26. glog.Errorf("operation LookupFileId %s failed, err: urls not found", chunkView.FileId)
  27. return fmt.Errorf("operation LookupFileId %s failed, err: urls not found", chunkView.FileId)
  28. }
  29. fileId2Url[chunkView.FileId] = urlStrings
  30. }
  31. for _, chunkView := range chunkViews {
  32. urlStrings := fileId2Url[chunkView.FileId]
  33. start := time.Now()
  34. err := retriedStreamFetchChunkData(writer, urlStrings, chunkView.CipherKey, chunkView.IsGzipped, chunkView.IsFullChunk(), chunkView.Offset, int(chunkView.Size))
  35. stats.FilerRequestHistogram.WithLabelValues("chunkDownload").Observe(time.Since(start).Seconds())
  36. if err != nil {
  37. stats.FilerRequestCounter.WithLabelValues("chunkDownloadError").Inc()
  38. return fmt.Errorf("read chunk: %v", err)
  39. }
  40. stats.FilerRequestCounter.WithLabelValues("chunkDownload").Inc()
  41. }
  42. return nil
  43. }
  44. // ---------------- ReadAllReader ----------------------------------
  45. func ReadAll(masterClient *wdclient.MasterClient, chunks []*filer_pb.FileChunk) ([]byte, error) {
  46. buffer := bytes.Buffer{}
  47. lookupFileIdFn := func(fileId string) (targetUrls []string, err error) {
  48. return masterClient.LookupFileId(fileId)
  49. }
  50. chunkViews := ViewFromChunks(lookupFileIdFn, chunks, 0, math.MaxInt64)
  51. for _, chunkView := range chunkViews {
  52. urlStrings, err := lookupFileIdFn(chunkView.FileId)
  53. if err != nil {
  54. glog.V(1).Infof("operation LookupFileId %s failed, err: %v", chunkView.FileId, err)
  55. return nil, err
  56. }
  57. data, err := retriedFetchChunkData(urlStrings, chunkView.CipherKey, chunkView.IsGzipped, chunkView.IsFullChunk(), chunkView.Offset, int(chunkView.Size))
  58. if err != nil {
  59. return nil, err
  60. }
  61. buffer.Write(data)
  62. }
  63. return buffer.Bytes(), nil
  64. }
  65. // ---------------- ChunkStreamReader ----------------------------------
  66. type ChunkStreamReader struct {
  67. chunkViews []*ChunkView
  68. totalSize int64
  69. logicOffset int64
  70. buffer []byte
  71. bufferOffset int64
  72. bufferPos int
  73. nextChunkViewIndex int
  74. lookupFileId wdclient.LookupFileIdFunctionType
  75. }
  76. var _ = io.ReadSeeker(&ChunkStreamReader{})
  77. var _ = io.ReaderAt(&ChunkStreamReader{})
  78. func doNewChunkStreamReader(lookupFileIdFn wdclient.LookupFileIdFunctionType, chunks []*filer_pb.FileChunk) *ChunkStreamReader {
  79. chunkViews := ViewFromChunks(lookupFileIdFn, chunks, 0, math.MaxInt64)
  80. sort.Slice(chunkViews, func(i, j int) bool {
  81. return chunkViews[i].LogicOffset < chunkViews[j].LogicOffset
  82. })
  83. var totalSize int64
  84. for _, chunk := range chunkViews {
  85. totalSize += int64(chunk.Size)
  86. }
  87. return &ChunkStreamReader{
  88. chunkViews: chunkViews,
  89. lookupFileId: lookupFileIdFn,
  90. totalSize: totalSize,
  91. }
  92. }
  93. func NewChunkStreamReaderFromFiler(masterClient *wdclient.MasterClient, chunks []*filer_pb.FileChunk) *ChunkStreamReader {
  94. lookupFileIdFn := func(fileId string) (targetUrl []string, err error) {
  95. return masterClient.LookupFileId(fileId)
  96. }
  97. return doNewChunkStreamReader(lookupFileIdFn, chunks)
  98. }
  99. func NewChunkStreamReader(filerClient filer_pb.FilerClient, chunks []*filer_pb.FileChunk) *ChunkStreamReader {
  100. lookupFileIdFn := LookupFn(filerClient)
  101. return doNewChunkStreamReader(lookupFileIdFn, chunks)
  102. }
  103. func (c *ChunkStreamReader) ReadAt(p []byte, off int64) (n int, err error) {
  104. if err = c.prepareBufferFor(c.logicOffset); err != nil {
  105. return
  106. }
  107. return c.Read(p)
  108. }
  109. func (c *ChunkStreamReader) Read(p []byte) (n int, err error) {
  110. for n < len(p) {
  111. if c.isBufferEmpty() {
  112. if c.nextChunkViewIndex >= len(c.chunkViews) {
  113. return n, io.EOF
  114. }
  115. chunkView := c.chunkViews[c.nextChunkViewIndex]
  116. if err = c.fetchChunkToBuffer(chunkView); err != nil {
  117. return
  118. }
  119. c.nextChunkViewIndex++
  120. }
  121. t := copy(p[n:], c.buffer[c.bufferPos:])
  122. c.bufferPos += t
  123. n += t
  124. c.logicOffset += int64(t)
  125. }
  126. return
  127. }
  128. func (c *ChunkStreamReader) isBufferEmpty() bool {
  129. return len(c.buffer) <= c.bufferPos
  130. }
  131. func (c *ChunkStreamReader) Seek(offset int64, whence int) (int64, error) {
  132. var err error
  133. switch whence {
  134. case io.SeekStart:
  135. case io.SeekCurrent:
  136. offset += c.logicOffset
  137. case io.SeekEnd:
  138. offset = c.totalSize + offset
  139. }
  140. if offset > c.totalSize {
  141. err = io.ErrUnexpectedEOF
  142. } else {
  143. c.logicOffset = offset
  144. }
  145. return offset, err
  146. }
  147. func (c *ChunkStreamReader) prepareBufferFor(offset int64) (err error) {
  148. // stay in the same chunk
  149. if !c.isBufferEmpty() {
  150. if c.bufferOffset <= offset && offset < c.bufferOffset+int64(len(c.buffer)) {
  151. c.bufferPos = int(offset - c.bufferOffset)
  152. return nil
  153. }
  154. }
  155. // need to seek to a different chunk
  156. currentChunkIndex := sort.Search(len(c.chunkViews), func(i int) bool {
  157. return c.chunkViews[i].LogicOffset <= offset
  158. })
  159. if currentChunkIndex == len(c.chunkViews) {
  160. return io.EOF
  161. }
  162. // positioning within the new chunk
  163. chunk := c.chunkViews[currentChunkIndex]
  164. if chunk.LogicOffset <= offset && offset < chunk.LogicOffset+int64(chunk.Size) {
  165. if c.isBufferEmpty() || c.bufferOffset != chunk.LogicOffset {
  166. if err = c.fetchChunkToBuffer(chunk); err != nil {
  167. return
  168. }
  169. c.nextChunkViewIndex = currentChunkIndex + 1
  170. }
  171. c.bufferPos = int(offset - c.bufferOffset)
  172. }
  173. return
  174. }
  175. func (c *ChunkStreamReader) fetchChunkToBuffer(chunkView *ChunkView) error {
  176. urlStrings, err := c.lookupFileId(chunkView.FileId)
  177. if err != nil {
  178. glog.V(1).Infof("operation LookupFileId %s failed, err: %v", chunkView.FileId, err)
  179. return err
  180. }
  181. var buffer bytes.Buffer
  182. var shouldRetry bool
  183. for _, urlString := range urlStrings {
  184. shouldRetry, err = util.ReadUrlAsStream(urlString, chunkView.CipherKey, chunkView.IsGzipped, chunkView.IsFullChunk(), chunkView.Offset, int(chunkView.Size), func(data []byte) {
  185. buffer.Write(data)
  186. })
  187. if !shouldRetry {
  188. break
  189. }
  190. if err != nil {
  191. glog.V(1).Infof("read %s failed, err: %v", chunkView.FileId, err)
  192. buffer.Reset()
  193. } else {
  194. break
  195. }
  196. }
  197. if err != nil {
  198. return err
  199. }
  200. c.buffer = buffer.Bytes()
  201. c.bufferPos = 0
  202. c.bufferOffset = chunkView.LogicOffset
  203. // glog.V(0).Infof("read %s [%d,%d)", chunkView.FileId, chunkView.LogicOffset, chunkView.LogicOffset+int64(chunkView.Size))
  204. return nil
  205. }
  206. func (c *ChunkStreamReader) Close() {
  207. // TODO try to release and reuse buffer
  208. }
  209. func VolumeId(fileId string) string {
  210. lastCommaIndex := strings.LastIndex(fileId, ",")
  211. if lastCommaIndex > 0 {
  212. return fileId[:lastCommaIndex]
  213. }
  214. return fileId
  215. }