reader_at.go 6.6 KB

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