reader_at.go 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  1. package filer
  2. import (
  3. "context"
  4. "fmt"
  5. "io"
  6. "math/rand"
  7. "sync"
  8. "github.com/seaweedfs/seaweedfs/weed/glog"
  9. "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
  10. "github.com/seaweedfs/seaweedfs/weed/util"
  11. "github.com/seaweedfs/seaweedfs/weed/wdclient"
  12. )
  13. type ChunkReadAt struct {
  14. masterClient *wdclient.MasterClient
  15. chunkViews *IntervalList[*ChunkView]
  16. fileSize int64
  17. readerCache *ReaderCache
  18. readerPattern *ReaderPattern
  19. lastChunkFid string
  20. }
  21. var _ = io.ReaderAt(&ChunkReadAt{})
  22. var _ = io.Closer(&ChunkReadAt{})
  23. func LookupFn(filerClient filer_pb.FilerClient) wdclient.LookupFileIdFunctionType {
  24. vidCache := make(map[string]*filer_pb.Locations)
  25. var vicCacheLock sync.RWMutex
  26. return func(fileId string) (targetUrls []string, err error) {
  27. vid := VolumeId(fileId)
  28. vicCacheLock.RLock()
  29. locations, found := vidCache[vid]
  30. vicCacheLock.RUnlock()
  31. if !found {
  32. util.Retry("lookup volume "+vid, func() error {
  33. err = filerClient.WithFilerClient(false, func(client filer_pb.SeaweedFilerClient) error {
  34. resp, err := client.LookupVolume(context.Background(), &filer_pb.LookupVolumeRequest{
  35. VolumeIds: []string{vid},
  36. })
  37. if err != nil {
  38. return err
  39. }
  40. locations = resp.LocationsMap[vid]
  41. if locations == nil || len(locations.Locations) == 0 {
  42. glog.V(0).Infof("failed to locate %s", fileId)
  43. return fmt.Errorf("failed to locate %s", fileId)
  44. }
  45. vicCacheLock.Lock()
  46. vidCache[vid] = locations
  47. vicCacheLock.Unlock()
  48. return nil
  49. })
  50. return err
  51. })
  52. }
  53. if err != nil {
  54. return nil, err
  55. }
  56. fcDataCenter := filerClient.GetDataCenter()
  57. var sameDcTargetUrls, otherTargetUrls []string
  58. for _, loc := range locations.Locations {
  59. volumeServerAddress := filerClient.AdjustedUrl(loc)
  60. targetUrl := fmt.Sprintf("http://%s/%s", volumeServerAddress, fileId)
  61. if fcDataCenter == "" || fcDataCenter != loc.DataCenter {
  62. otherTargetUrls = append(otherTargetUrls, targetUrl)
  63. } else {
  64. sameDcTargetUrls = append(sameDcTargetUrls, targetUrl)
  65. }
  66. }
  67. rand.Shuffle(len(sameDcTargetUrls), func(i, j int) {
  68. sameDcTargetUrls[i], sameDcTargetUrls[j] = sameDcTargetUrls[j], sameDcTargetUrls[i]
  69. })
  70. rand.Shuffle(len(otherTargetUrls), func(i, j int) {
  71. otherTargetUrls[i], otherTargetUrls[j] = otherTargetUrls[j], otherTargetUrls[i]
  72. })
  73. // Prefer same data center
  74. targetUrls = append(sameDcTargetUrls, otherTargetUrls...)
  75. return
  76. }
  77. }
  78. func NewChunkReaderAtFromClient(readerCache *ReaderCache, chunkViews *IntervalList[*ChunkView], fileSize int64) *ChunkReadAt {
  79. return &ChunkReadAt{
  80. chunkViews: chunkViews,
  81. fileSize: fileSize,
  82. readerCache: readerCache,
  83. readerPattern: NewReaderPattern(),
  84. }
  85. }
  86. func (c *ChunkReadAt) Size() int64 {
  87. return c.fileSize
  88. }
  89. func (c *ChunkReadAt) Close() error {
  90. c.readerCache.destroy()
  91. return nil
  92. }
  93. func (c *ChunkReadAt) ReadAt(p []byte, offset int64) (n int, err error) {
  94. c.readerPattern.MonitorReadAt(offset, len(p))
  95. c.chunkViews.Lock.RLock()
  96. defer c.chunkViews.Lock.RUnlock()
  97. // glog.V(4).Infof("ReadAt [%d,%d) of total file size %d bytes %d chunk views", offset, offset+int64(len(p)), c.fileSize, len(c.chunkViews))
  98. n, _, err = c.doReadAt(p, offset)
  99. return
  100. }
  101. func (c *ChunkReadAt) ReadAtWithTime(p []byte, offset int64) (n int, ts int64, err error) {
  102. c.readerPattern.MonitorReadAt(offset, len(p))
  103. c.chunkViews.Lock.RLock()
  104. defer c.chunkViews.Lock.RUnlock()
  105. // glog.V(4).Infof("ReadAt [%d,%d) of total file size %d bytes %d chunk views", offset, offset+int64(len(p)), c.fileSize, len(c.chunkViews))
  106. return c.doReadAt(p, offset)
  107. }
  108. func (c *ChunkReadAt) doReadAt(p []byte, offset int64) (n int, ts int64, err error) {
  109. startOffset, remaining := offset, int64(len(p))
  110. var nextChunks *Interval[*ChunkView]
  111. for x := c.chunkViews.Front(); x != nil; x = x.Next {
  112. chunk := x.Value
  113. if remaining <= 0 {
  114. break
  115. }
  116. if x.Next != nil {
  117. nextChunks = x.Next
  118. }
  119. if startOffset < chunk.ViewOffset {
  120. gap := chunk.ViewOffset - startOffset
  121. glog.V(4).Infof("zero [%d,%d)", startOffset, chunk.ViewOffset)
  122. n += zero(p, startOffset-offset, gap)
  123. startOffset, remaining = chunk.ViewOffset, remaining-gap
  124. if remaining <= 0 {
  125. break
  126. }
  127. }
  128. // fmt.Printf(">>> doReadAt [%d,%d), chunk[%d,%d)\n", offset, offset+int64(len(p)), chunk.ViewOffset, chunk.ViewOffset+int64(chunk.ViewSize))
  129. chunkStart, chunkStop := max(chunk.ViewOffset, startOffset), min(chunk.ViewOffset+int64(chunk.ViewSize), startOffset+remaining)
  130. if chunkStart >= chunkStop {
  131. continue
  132. }
  133. // glog.V(4).Infof("read [%d,%d), %d/%d chunk %s [%d,%d)", chunkStart, chunkStop, i, len(c.chunkViews), chunk.FileId, chunk.ViewOffset-chunk.Offset, chunk.ViewOffset-chunk.Offset+int64(chunk.ViewSize))
  134. bufferOffset := chunkStart - chunk.ViewOffset + chunk.OffsetInChunk
  135. ts = chunk.ModifiedTsNs
  136. copied, err := c.readChunkSliceAt(p[startOffset-offset:chunkStop-chunkStart+startOffset-offset], chunk, nextChunks, uint64(bufferOffset))
  137. if err != nil {
  138. glog.Errorf("fetching chunk %+v: %v\n", chunk, err)
  139. return copied, ts, err
  140. }
  141. n += copied
  142. startOffset, remaining = startOffset+int64(copied), remaining-int64(copied)
  143. }
  144. // glog.V(4).Infof("doReadAt [%d,%d), n:%v, err:%v", offset, offset+int64(len(p)), n, err)
  145. // zero the remaining bytes if a gap exists at the end of the last chunk (or a fully sparse file)
  146. if err == nil && remaining > 0 {
  147. var delta int64
  148. if c.fileSize >= startOffset {
  149. delta = min(remaining, c.fileSize-startOffset)
  150. startOffset -= offset
  151. }
  152. if delta > 0 {
  153. glog.V(4).Infof("zero2 [%d,%d) of file size %d bytes", startOffset, startOffset+delta, c.fileSize)
  154. n += zero(p, startOffset, delta)
  155. }
  156. }
  157. if err == nil && offset+int64(len(p)) >= c.fileSize {
  158. err = io.EOF
  159. }
  160. // fmt.Printf("~~~ filled %d, err: %v\n\n", n, err)
  161. return
  162. }
  163. func (c *ChunkReadAt) readChunkSliceAt(buffer []byte, chunkView *ChunkView, nextChunkViews *Interval[*ChunkView], offset uint64) (n int, err error) {
  164. if c.readerPattern.IsRandomMode() {
  165. n, err := c.readerCache.chunkCache.ReadChunkAt(buffer, chunkView.FileId, offset)
  166. if n > 0 {
  167. return n, err
  168. }
  169. return fetchChunkRange(buffer, c.readerCache.lookupFileIdFn, chunkView.FileId, chunkView.CipherKey, chunkView.IsGzipped, int64(offset))
  170. }
  171. shouldCache := (uint64(chunkView.ViewOffset) + chunkView.ChunkSize) <= c.readerCache.chunkCache.GetMaxFilePartSizeInCache()
  172. n, err = c.readerCache.ReadChunkAt(buffer, chunkView.FileId, chunkView.CipherKey, chunkView.IsGzipped, int64(offset), int(chunkView.ChunkSize), shouldCache)
  173. if c.lastChunkFid != chunkView.FileId {
  174. if chunkView.OffsetInChunk == 0 { // start of a new chunk
  175. if c.lastChunkFid != "" {
  176. c.readerCache.UnCache(c.lastChunkFid)
  177. }
  178. if nextChunkViews != nil {
  179. c.readerCache.MaybeCache(nextChunkViews) // just read the next chunk if at the very beginning
  180. }
  181. }
  182. }
  183. c.lastChunkFid = chunkView.FileId
  184. return
  185. }
  186. func zero(buffer []byte, start, length int64) int {
  187. if length <= 0 {
  188. return 0
  189. }
  190. end := min(start+length, int64(len(buffer)))
  191. start = max(start, 0)
  192. // zero the bytes
  193. for o := start; o < end; o++ {
  194. buffer[o] = 0
  195. }
  196. return int(end - start)
  197. }