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.

392 lines
11 KiB

4 years ago
3 years ago
3 years ago
3 years ago
3 years ago
4 years ago
4 years ago
3 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
3 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
3 years ago
4 years ago
4 years ago
5 years ago
5 years ago
  1. package filer
  2. import (
  3. "bytes"
  4. "fmt"
  5. "golang.org/x/exp/slices"
  6. "io"
  7. "math"
  8. "sort"
  9. "strings"
  10. "sync"
  11. "time"
  12. "github.com/seaweedfs/seaweedfs/weed/glog"
  13. "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
  14. "github.com/seaweedfs/seaweedfs/weed/stats"
  15. "github.com/seaweedfs/seaweedfs/weed/util"
  16. "github.com/seaweedfs/seaweedfs/weed/wdclient"
  17. )
  18. var getLookupFileIdBackoffSchedule = []time.Duration{
  19. 150 * time.Millisecond,
  20. 600 * time.Millisecond,
  21. 1800 * time.Millisecond,
  22. }
  23. func HasData(entry *filer_pb.Entry) bool {
  24. if len(entry.Content) > 0 {
  25. return true
  26. }
  27. return len(entry.Chunks) > 0
  28. }
  29. func IsSameData(a, b *filer_pb.Entry) bool {
  30. if len(a.Content) > 0 || len(b.Content) > 0 {
  31. return bytes.Equal(a.Content, b.Content)
  32. }
  33. return isSameChunks(a.Chunks, b.Chunks)
  34. }
  35. func isSameChunks(a, b []*filer_pb.FileChunk) bool {
  36. if len(a) != len(b) {
  37. return false
  38. }
  39. slices.SortFunc(a, func(i, j *filer_pb.FileChunk) bool {
  40. return strings.Compare(i.ETag, j.ETag) < 0
  41. })
  42. slices.SortFunc(b, func(i, j *filer_pb.FileChunk) bool {
  43. return strings.Compare(i.ETag, j.ETag) < 0
  44. })
  45. for i := 0; i < len(a); i++ {
  46. if a[i].ETag != b[i].ETag {
  47. return false
  48. }
  49. }
  50. return true
  51. }
  52. func NewFileReader(filerClient filer_pb.FilerClient, entry *filer_pb.Entry) io.Reader {
  53. if len(entry.Content) > 0 {
  54. return bytes.NewReader(entry.Content)
  55. }
  56. return NewChunkStreamReader(filerClient, entry.Chunks)
  57. }
  58. func StreamContent(masterClient wdclient.HasLookupFileIdFunction, writer io.Writer, chunks []*filer_pb.FileChunk, offset int64, size int64) error {
  59. return StreamContentWithThrottler(masterClient, writer, chunks, offset, size, 0)
  60. }
  61. func StreamContentWithThrottler(masterClient wdclient.HasLookupFileIdFunction, writer io.Writer, chunks []*filer_pb.FileChunk, offset int64, size int64, downloadMaxBytesPs int64) error {
  62. glog.V(4).Infof("start to stream content for chunks: %+v", chunks)
  63. chunkViews := ViewFromChunks(masterClient.GetLookupFileIdFunction(), chunks, offset, size)
  64. fileId2Url := make(map[string][]string)
  65. for _, chunkView := range chunkViews {
  66. var urlStrings []string
  67. var err error
  68. for _, backoff := range getLookupFileIdBackoffSchedule {
  69. urlStrings, err = masterClient.GetLookupFileIdFunction()(chunkView.FileId)
  70. if err == nil && len(urlStrings) > 0 {
  71. break
  72. }
  73. time.Sleep(backoff)
  74. }
  75. if err != nil {
  76. glog.V(1).Infof("operation LookupFileId %s failed, err: %v", chunkView.FileId, err)
  77. return err
  78. } else if len(urlStrings) == 0 {
  79. errUrlNotFound := fmt.Errorf("operation LookupFileId %s failed, err: urls not found", chunkView.FileId)
  80. glog.Error(errUrlNotFound)
  81. return errUrlNotFound
  82. }
  83. fileId2Url[chunkView.FileId] = urlStrings
  84. }
  85. downloadThrottler := util.NewWriteThrottler(downloadMaxBytesPs)
  86. remaining := size
  87. for _, chunkView := range chunkViews {
  88. if offset < chunkView.LogicOffset {
  89. gap := chunkView.LogicOffset - offset
  90. remaining -= gap
  91. glog.V(4).Infof("zero [%d,%d)", offset, chunkView.LogicOffset)
  92. err := writeZero(writer, gap)
  93. if err != nil {
  94. return fmt.Errorf("write zero [%d,%d)", offset, chunkView.LogicOffset)
  95. }
  96. offset = chunkView.LogicOffset
  97. }
  98. urlStrings := fileId2Url[chunkView.FileId]
  99. start := time.Now()
  100. err := retriedStreamFetchChunkData(writer, urlStrings, chunkView.CipherKey, chunkView.IsGzipped, chunkView.IsFullChunk(), chunkView.Offset, int(chunkView.Size))
  101. offset += int64(chunkView.Size)
  102. remaining -= int64(chunkView.Size)
  103. stats.FilerRequestHistogram.WithLabelValues("chunkDownload").Observe(time.Since(start).Seconds())
  104. if err != nil {
  105. stats.FilerRequestCounter.WithLabelValues("chunkDownloadError").Inc()
  106. return fmt.Errorf("read chunk: %v", err)
  107. }
  108. stats.FilerRequestCounter.WithLabelValues("chunkDownload").Inc()
  109. downloadThrottler.MaybeSlowdown(int64(chunkView.Size))
  110. }
  111. if remaining > 0 {
  112. glog.V(4).Infof("zero [%d,%d)", offset, offset+remaining)
  113. err := writeZero(writer, remaining)
  114. if err != nil {
  115. return fmt.Errorf("write zero [%d,%d)", offset, offset+remaining)
  116. }
  117. }
  118. return nil
  119. }
  120. // ---------------- ReadAllReader ----------------------------------
  121. func writeZero(w io.Writer, size int64) (err error) {
  122. zeroPadding := make([]byte, 1024)
  123. var written int
  124. for size > 0 {
  125. if size > 1024 {
  126. written, err = w.Write(zeroPadding)
  127. } else {
  128. written, err = w.Write(zeroPadding[:size])
  129. }
  130. size -= int64(written)
  131. if err != nil {
  132. return
  133. }
  134. }
  135. return
  136. }
  137. func ReadAll(buffer []byte, masterClient *wdclient.MasterClient, chunks []*filer_pb.FileChunk) error {
  138. lookupFileIdFn := func(fileId string) (targetUrls []string, err error) {
  139. return masterClient.LookupFileId(fileId)
  140. }
  141. chunkViews := ViewFromChunks(lookupFileIdFn, chunks, 0, int64(len(buffer)))
  142. idx := 0
  143. for _, chunkView := range chunkViews {
  144. urlStrings, err := lookupFileIdFn(chunkView.FileId)
  145. if err != nil {
  146. glog.V(1).Infof("operation LookupFileId %s failed, err: %v", chunkView.FileId, err)
  147. return err
  148. }
  149. n, err := retriedFetchChunkData(buffer[idx:idx+int(chunkView.Size)], urlStrings, chunkView.CipherKey, chunkView.IsGzipped, chunkView.IsFullChunk(), chunkView.Offset)
  150. if err != nil {
  151. return err
  152. }
  153. idx += n
  154. }
  155. return nil
  156. }
  157. // ---------------- ChunkStreamReader ----------------------------------
  158. type ChunkStreamReader struct {
  159. chunkViews []*ChunkView
  160. totalSize int64
  161. logicOffset int64
  162. buffer []byte
  163. bufferOffset int64
  164. bufferLock sync.Mutex
  165. chunk string
  166. lookupFileId wdclient.LookupFileIdFunctionType
  167. }
  168. var _ = io.ReadSeeker(&ChunkStreamReader{})
  169. var _ = io.ReaderAt(&ChunkStreamReader{})
  170. func doNewChunkStreamReader(lookupFileIdFn wdclient.LookupFileIdFunctionType, chunks []*filer_pb.FileChunk) *ChunkStreamReader {
  171. chunkViews := ViewFromChunks(lookupFileIdFn, chunks, 0, math.MaxInt64)
  172. slices.SortFunc(chunkViews, func(a, b *ChunkView) bool {
  173. return a.LogicOffset < b.LogicOffset
  174. })
  175. var totalSize int64
  176. for _, chunk := range chunkViews {
  177. totalSize += int64(chunk.Size)
  178. }
  179. return &ChunkStreamReader{
  180. chunkViews: chunkViews,
  181. lookupFileId: lookupFileIdFn,
  182. totalSize: totalSize,
  183. }
  184. }
  185. func NewChunkStreamReaderFromFiler(masterClient *wdclient.MasterClient, chunks []*filer_pb.FileChunk) *ChunkStreamReader {
  186. lookupFileIdFn := func(fileId string) (targetUrl []string, err error) {
  187. return masterClient.LookupFileId(fileId)
  188. }
  189. return doNewChunkStreamReader(lookupFileIdFn, chunks)
  190. }
  191. func NewChunkStreamReader(filerClient filer_pb.FilerClient, chunks []*filer_pb.FileChunk) *ChunkStreamReader {
  192. lookupFileIdFn := LookupFn(filerClient)
  193. return doNewChunkStreamReader(lookupFileIdFn, chunks)
  194. }
  195. func (c *ChunkStreamReader) ReadAt(p []byte, off int64) (n int, err error) {
  196. c.bufferLock.Lock()
  197. defer c.bufferLock.Unlock()
  198. if err = c.prepareBufferFor(off); err != nil {
  199. return
  200. }
  201. c.logicOffset = off
  202. return c.doRead(p)
  203. }
  204. func (c *ChunkStreamReader) Read(p []byte) (n int, err error) {
  205. c.bufferLock.Lock()
  206. defer c.bufferLock.Unlock()
  207. return c.doRead(p)
  208. }
  209. func (c *ChunkStreamReader) doRead(p []byte) (n int, err error) {
  210. // fmt.Printf("do read [%d,%d) at %s[%d,%d)\n", c.logicOffset, c.logicOffset+int64(len(p)), c.chunk, c.bufferOffset, c.bufferOffset+int64(len(c.buffer)))
  211. for n < len(p) {
  212. // println("read", c.logicOffset)
  213. if err = c.prepareBufferFor(c.logicOffset); err != nil {
  214. return
  215. }
  216. t := copy(p[n:], c.buffer[c.logicOffset-c.bufferOffset:])
  217. n += t
  218. c.logicOffset += int64(t)
  219. }
  220. return
  221. }
  222. func (c *ChunkStreamReader) isBufferEmpty() bool {
  223. return len(c.buffer) <= int(c.logicOffset-c.bufferOffset)
  224. }
  225. func (c *ChunkStreamReader) Seek(offset int64, whence int) (int64, error) {
  226. c.bufferLock.Lock()
  227. defer c.bufferLock.Unlock()
  228. var err error
  229. switch whence {
  230. case io.SeekStart:
  231. case io.SeekCurrent:
  232. offset += c.logicOffset
  233. case io.SeekEnd:
  234. offset = c.totalSize + offset
  235. }
  236. if offset > c.totalSize {
  237. err = io.ErrUnexpectedEOF
  238. } else {
  239. c.logicOffset = offset
  240. }
  241. return offset, err
  242. }
  243. func insideChunk(offset int64, chunk *ChunkView) bool {
  244. return chunk.LogicOffset <= offset && offset < chunk.LogicOffset+int64(chunk.Size)
  245. }
  246. func (c *ChunkStreamReader) prepareBufferFor(offset int64) (err error) {
  247. // stay in the same chunk
  248. if c.bufferOffset <= offset && offset < c.bufferOffset+int64(len(c.buffer)) {
  249. return nil
  250. }
  251. // fmt.Printf("fetch for offset %d\n", offset)
  252. // need to seek to a different chunk
  253. currentChunkIndex := sort.Search(len(c.chunkViews), func(i int) bool {
  254. return offset < c.chunkViews[i].LogicOffset
  255. })
  256. if currentChunkIndex == len(c.chunkViews) {
  257. // not found
  258. if insideChunk(offset, c.chunkViews[0]) {
  259. // fmt.Printf("select0 chunk %d %s\n", currentChunkIndex, c.chunkViews[currentChunkIndex].FileId)
  260. currentChunkIndex = 0
  261. } else if insideChunk(offset, c.chunkViews[len(c.chunkViews)-1]) {
  262. currentChunkIndex = len(c.chunkViews) - 1
  263. // fmt.Printf("select last chunk %d %s\n", currentChunkIndex, c.chunkViews[currentChunkIndex].FileId)
  264. } else {
  265. return io.EOF
  266. }
  267. } else if currentChunkIndex > 0 {
  268. if insideChunk(offset, c.chunkViews[currentChunkIndex]) {
  269. // good hit
  270. } else if insideChunk(offset, c.chunkViews[currentChunkIndex-1]) {
  271. currentChunkIndex -= 1
  272. // fmt.Printf("select -1 chunk %d %s\n", currentChunkIndex, c.chunkViews[currentChunkIndex].FileId)
  273. } else {
  274. // glog.Fatalf("unexpected1 offset %d", offset)
  275. return fmt.Errorf("unexpected1 offset %d", offset)
  276. }
  277. } else {
  278. // glog.Fatalf("unexpected2 offset %d", offset)
  279. return fmt.Errorf("unexpected2 offset %d", offset)
  280. }
  281. // positioning within the new chunk
  282. chunk := c.chunkViews[currentChunkIndex]
  283. if insideChunk(offset, chunk) {
  284. if c.isBufferEmpty() || c.bufferOffset != chunk.LogicOffset {
  285. if err = c.fetchChunkToBuffer(chunk); err != nil {
  286. return
  287. }
  288. }
  289. } else {
  290. // glog.Fatalf("unexpected3 offset %d in %s [%d,%d)", offset, chunk.FileId, chunk.LogicOffset, chunk.LogicOffset+int64(chunk.Size))
  291. return fmt.Errorf("unexpected3 offset %d in %s [%d,%d)", offset, chunk.FileId, chunk.LogicOffset, chunk.LogicOffset+int64(chunk.Size))
  292. }
  293. return
  294. }
  295. func (c *ChunkStreamReader) fetchChunkToBuffer(chunkView *ChunkView) error {
  296. urlStrings, err := c.lookupFileId(chunkView.FileId)
  297. if err != nil {
  298. glog.V(1).Infof("operation LookupFileId %s failed, err: %v", chunkView.FileId, err)
  299. return err
  300. }
  301. var buffer bytes.Buffer
  302. var shouldRetry bool
  303. for _, urlString := range urlStrings {
  304. shouldRetry, err = util.ReadUrlAsStream(urlString+"?readDeleted=true", chunkView.CipherKey, chunkView.IsGzipped, chunkView.IsFullChunk(), chunkView.Offset, int(chunkView.Size), func(data []byte) {
  305. buffer.Write(data)
  306. })
  307. if !shouldRetry {
  308. break
  309. }
  310. if err != nil {
  311. glog.V(1).Infof("read %s failed, err: %v", chunkView.FileId, err)
  312. buffer.Reset()
  313. } else {
  314. break
  315. }
  316. }
  317. if err != nil {
  318. return err
  319. }
  320. c.buffer = buffer.Bytes()
  321. c.bufferOffset = chunkView.LogicOffset
  322. c.chunk = chunkView.FileId
  323. // glog.V(0).Infof("fetched %s [%d,%d)", chunkView.FileId, chunkView.LogicOffset, chunkView.LogicOffset+int64(chunkView.Size))
  324. return nil
  325. }
  326. func (c *ChunkStreamReader) Close() {
  327. // TODO try to release and reuse buffer
  328. }
  329. func VolumeId(fileId string) string {
  330. lastCommaIndex := strings.LastIndex(fileId, ",")
  331. if lastCommaIndex > 0 {
  332. return fileId[:lastCommaIndex]
  333. }
  334. return fileId
  335. }