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.

258 lines
7.1 KiB

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