log_read.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. package log_buffer
  2. import (
  3. "bytes"
  4. "fmt"
  5. "time"
  6. "github.com/golang/protobuf/proto"
  7. "github.com/chrislusf/seaweedfs/weed/glog"
  8. "github.com/chrislusf/seaweedfs/weed/pb/filer_pb"
  9. "github.com/chrislusf/seaweedfs/weed/util"
  10. )
  11. var (
  12. ResumeError = fmt.Errorf("resume")
  13. ResumeFromDiskError = fmt.Errorf("resumeFromDisk")
  14. )
  15. func (logBuffer *LogBuffer) LoopProcessLogData(
  16. startTreadTime time.Time,
  17. waitForDataFn func() bool,
  18. eachLogDataFn func(logEntry *filer_pb.LogEntry) error) (lastReadTime time.Time, err error) {
  19. // loop through all messages
  20. var bytesBuf *bytes.Buffer
  21. lastReadTime = startTreadTime
  22. defer func() {
  23. if bytesBuf != nil {
  24. logBuffer.ReleaseMemory(bytesBuf)
  25. }
  26. }()
  27. for {
  28. if bytesBuf != nil {
  29. logBuffer.ReleaseMemory(bytesBuf)
  30. }
  31. bytesBuf, err = logBuffer.ReadFromBuffer(lastReadTime)
  32. if err == ResumeFromDiskError {
  33. return lastReadTime, ResumeFromDiskError
  34. }
  35. // fmt.Printf("ReadFromBuffer by %v\n", lastReadTime)
  36. if bytesBuf == nil {
  37. if waitForDataFn() {
  38. continue
  39. } else {
  40. return
  41. }
  42. }
  43. buf := bytesBuf.Bytes()
  44. // fmt.Printf("ReadFromBuffer by %v size %d\n", lastReadTime, len(buf))
  45. batchSize := 0
  46. var startReadTime time.Time
  47. for pos := 0; pos+4 < len(buf); {
  48. size := util.BytesToUint32(buf[pos : pos+4])
  49. if pos+4+int(size) > len(buf) {
  50. err = ResumeError
  51. glog.Errorf("LoopProcessLogData: read buffer %v read %d [%d,%d) from [0,%d)", lastReadTime, batchSize, pos, pos+int(size)+4, len(buf))
  52. return
  53. }
  54. entryData := buf[pos+4 : pos+4+int(size)]
  55. logEntry := &filer_pb.LogEntry{}
  56. if err = proto.Unmarshal(entryData, logEntry); err != nil {
  57. glog.Errorf("unexpected unmarshal messaging_pb.Message: %v", err)
  58. pos += 4 + int(size)
  59. continue
  60. }
  61. lastReadTime = time.Unix(0, logEntry.TsNs)
  62. if startReadTime.IsZero() {
  63. startReadTime = lastReadTime
  64. }
  65. if err = eachLogDataFn(logEntry); err != nil {
  66. return
  67. }
  68. pos += 4 + int(size)
  69. batchSize++
  70. }
  71. // fmt.Printf("sent message ts[%d,%d] size %d\n", startReadTime.UnixNano(), lastReadTime.UnixNano(), batchSize)
  72. }
  73. }