reader_at.go 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. package filer
  2. import (
  3. "context"
  4. "fmt"
  5. "io"
  6. "math/rand"
  7. "sync"
  8. "github.com/chrislusf/seaweedfs/weed/glog"
  9. "github.com/chrislusf/seaweedfs/weed/pb/filer_pb"
  10. "github.com/chrislusf/seaweedfs/weed/util"
  11. "github.com/chrislusf/seaweedfs/weed/util/chunk_cache"
  12. "github.com/chrislusf/seaweedfs/weed/wdclient"
  13. "github.com/golang/groupcache/singleflight"
  14. )
  15. type ChunkReadAt struct {
  16. masterClient *wdclient.MasterClient
  17. chunkViews []*ChunkView
  18. lookupFileId wdclient.LookupFileIdFunctionType
  19. readerLock sync.Mutex
  20. fileSize int64
  21. fetchGroup singleflight.Group
  22. chunkCache chunk_cache.ChunkCache
  23. lastChunkFileId string
  24. lastChunkData []byte
  25. }
  26. var _ = io.ReaderAt(&ChunkReadAt{})
  27. var _ = io.Closer(&ChunkReadAt{})
  28. func LookupFn(filerClient filer_pb.FilerClient) wdclient.LookupFileIdFunctionType {
  29. vidCache := make(map[string]*filer_pb.Locations)
  30. var vicCacheLock sync.RWMutex
  31. return func(fileId string) (targetUrls []string, err error) {
  32. vid := VolumeId(fileId)
  33. vicCacheLock.RLock()
  34. locations, found := vidCache[vid]
  35. vicCacheLock.RUnlock()
  36. if !found {
  37. util.Retry("lookup volume "+vid, func() error {
  38. err = filerClient.WithFilerClient(func(client filer_pb.SeaweedFilerClient) error {
  39. resp, err := client.LookupVolume(context.Background(), &filer_pb.LookupVolumeRequest{
  40. VolumeIds: []string{vid},
  41. })
  42. if err != nil {
  43. return err
  44. }
  45. locations = resp.LocationsMap[vid]
  46. if locations == nil || len(locations.Locations) == 0 {
  47. glog.V(0).Infof("failed to locate %s", fileId)
  48. return fmt.Errorf("failed to locate %s", fileId)
  49. }
  50. vicCacheLock.Lock()
  51. vidCache[vid] = locations
  52. vicCacheLock.Unlock()
  53. return nil
  54. })
  55. return err
  56. })
  57. }
  58. if err != nil {
  59. return nil, err
  60. }
  61. for _, loc := range locations.Locations {
  62. volumeServerAddress := filerClient.AdjustedUrl(loc)
  63. targetUrl := fmt.Sprintf("http://%s/%s", volumeServerAddress, fileId)
  64. targetUrls = append(targetUrls, targetUrl)
  65. }
  66. for i := len(targetUrls) - 1; i > 0; i-- {
  67. j := rand.Intn(i + 1)
  68. targetUrls[i], targetUrls[j] = targetUrls[j], targetUrls[i]
  69. }
  70. return
  71. }
  72. }
  73. func NewChunkReaderAtFromClient(lookupFn wdclient.LookupFileIdFunctionType, chunkViews []*ChunkView, chunkCache chunk_cache.ChunkCache, fileSize int64) *ChunkReadAt {
  74. return &ChunkReadAt{
  75. chunkViews: chunkViews,
  76. lookupFileId: lookupFn,
  77. chunkCache: chunkCache,
  78. fileSize: fileSize,
  79. }
  80. }
  81. func (c *ChunkReadAt) Close() error {
  82. c.lastChunkData = nil
  83. c.lastChunkFileId = ""
  84. return nil
  85. }
  86. func (c *ChunkReadAt) ReadAt(p []byte, offset int64) (n int, err error) {
  87. c.readerLock.Lock()
  88. defer c.readerLock.Unlock()
  89. 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))
  90. return c.doReadAt(p, offset)
  91. }
  92. func (c *ChunkReadAt) doReadAt(p []byte, offset int64) (n int, err error) {
  93. startOffset, remaining := offset, int64(len(p))
  94. var nextChunk *ChunkView
  95. for i, chunk := range c.chunkViews {
  96. if remaining <= 0 {
  97. break
  98. }
  99. if i+1 < len(c.chunkViews) {
  100. nextChunk = c.chunkViews[i+1]
  101. } else {
  102. nextChunk = nil
  103. }
  104. if startOffset < chunk.LogicOffset {
  105. gap := int(chunk.LogicOffset - startOffset)
  106. glog.V(4).Infof("zero [%d,%d)", startOffset, startOffset+int64(gap))
  107. n += int(min(int64(gap), remaining))
  108. startOffset, remaining = chunk.LogicOffset, remaining-int64(gap)
  109. if remaining <= 0 {
  110. break
  111. }
  112. }
  113. // fmt.Printf(">>> doReadAt [%d,%d), chunk[%d,%d)\n", offset, offset+int64(len(p)), chunk.LogicOffset, chunk.LogicOffset+int64(chunk.Size))
  114. chunkStart, chunkStop := max(chunk.LogicOffset, startOffset), min(chunk.LogicOffset+int64(chunk.Size), startOffset+remaining)
  115. if chunkStart >= chunkStop {
  116. continue
  117. }
  118. 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))
  119. var buffer []byte
  120. buffer, err = c.readFromWholeChunkData(chunk, nextChunk)
  121. if err != nil {
  122. glog.Errorf("fetching chunk %+v: %v\n", chunk, err)
  123. return
  124. }
  125. bufferOffset := chunkStart - chunk.LogicOffset + chunk.Offset
  126. copied := copy(p[startOffset-offset:chunkStop-chunkStart+startOffset-offset], buffer[bufferOffset:bufferOffset+chunkStop-chunkStart])
  127. n += copied
  128. startOffset, remaining = startOffset+int64(copied), remaining-int64(copied)
  129. }
  130. glog.V(4).Infof("doReadAt [%d,%d), n:%v, err:%v", offset, offset+int64(len(p)), n, err)
  131. if err == nil && remaining > 0 && c.fileSize > startOffset {
  132. delta := int(min(remaining, c.fileSize-startOffset))
  133. glog.V(4).Infof("zero2 [%d,%d) of file size %d bytes", startOffset, startOffset+int64(delta), c.fileSize)
  134. n += delta
  135. }
  136. if err == nil && offset+int64(len(p)) >= c.fileSize {
  137. err = io.EOF
  138. }
  139. // fmt.Printf("~~~ filled %d, err: %v\n\n", n, err)
  140. return
  141. }
  142. func (c *ChunkReadAt) readFromWholeChunkData(chunkView *ChunkView, nextChunkViews ...*ChunkView) (chunkData []byte, err error) {
  143. if c.lastChunkFileId == chunkView.FileId {
  144. return c.lastChunkData, nil
  145. }
  146. v, doErr := c.readOneWholeChunk(chunkView)
  147. if doErr != nil {
  148. return nil, doErr
  149. }
  150. chunkData = v.([]byte)
  151. c.lastChunkData = chunkData
  152. c.lastChunkFileId = chunkView.FileId
  153. for _, nextChunkView := range nextChunkViews {
  154. if c.chunkCache != nil && nextChunkView != nil {
  155. go c.readOneWholeChunk(nextChunkView)
  156. }
  157. }
  158. return
  159. }
  160. func (c *ChunkReadAt) readOneWholeChunk(chunkView *ChunkView) (interface{}, error) {
  161. var err error
  162. return c.fetchGroup.Do(chunkView.FileId, func() (interface{}, error) {
  163. glog.V(4).Infof("readFromWholeChunkData %s offset %d [%d,%d) size at least %d", chunkView.FileId, chunkView.Offset, chunkView.LogicOffset, chunkView.LogicOffset+int64(chunkView.Size), chunkView.ChunkSize)
  164. data := c.chunkCache.GetChunk(chunkView.FileId, chunkView.ChunkSize)
  165. if data != nil {
  166. glog.V(4).Infof("cache hit %s [%d,%d)", chunkView.FileId, chunkView.LogicOffset-chunkView.Offset, chunkView.LogicOffset-chunkView.Offset+int64(len(data)))
  167. } else {
  168. var err error
  169. data, err = c.doFetchFullChunkData(chunkView)
  170. if err != nil {
  171. return data, err
  172. }
  173. c.chunkCache.SetChunk(chunkView.FileId, data)
  174. }
  175. return data, err
  176. })
  177. }
  178. func (c *ChunkReadAt) doFetchFullChunkData(chunkView *ChunkView) ([]byte, error) {
  179. glog.V(4).Infof("+ doFetchFullChunkData %s", chunkView.FileId)
  180. data, err := fetchChunk(c.lookupFileId, chunkView.FileId, chunkView.CipherKey, chunkView.IsGzipped)
  181. glog.V(4).Infof("- doFetchFullChunkData %s", chunkView.FileId)
  182. return data, err
  183. }