log_read.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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(readerName string, startTreadTime time.Time, waitForDataFn func() bool, eachLogDataFn func(logEntry *filer_pb.LogEntry) error) (lastReadTime time.Time, err error) {
  16. // loop through all messages
  17. var bytesBuf *bytes.Buffer
  18. lastReadTime = startTreadTime
  19. defer func() {
  20. if bytesBuf != nil {
  21. logBuffer.ReleaseMemory(bytesBuf)
  22. }
  23. }()
  24. for {
  25. if bytesBuf != nil {
  26. logBuffer.ReleaseMemory(bytesBuf)
  27. }
  28. bytesBuf, err = logBuffer.ReadFromBuffer(lastReadTime)
  29. if err == ResumeFromDiskError {
  30. return lastReadTime, ResumeFromDiskError
  31. }
  32. // glog.V(4).Infof("%s ReadFromBuffer by %v", readerName, lastReadTime)
  33. if bytesBuf == nil {
  34. if waitForDataFn() {
  35. continue
  36. } else {
  37. return
  38. }
  39. }
  40. buf := bytesBuf.Bytes()
  41. // fmt.Printf("ReadFromBuffer %s by %v size %d\n", readerName, lastReadTime, len(buf))
  42. batchSize := 0
  43. var startReadTime time.Time
  44. for pos := 0; pos+4 < len(buf); {
  45. size := util.BytesToUint32(buf[pos : pos+4])
  46. if pos+4+int(size) > len(buf) {
  47. err = ResumeError
  48. glog.Errorf("LoopProcessLogData: %s read buffer %v read %d [%d,%d) from [0,%d)", readerName, lastReadTime, batchSize, pos, pos+int(size)+4, len(buf))
  49. return
  50. }
  51. entryData := buf[pos+4 : pos+4+int(size)]
  52. logEntry := &filer_pb.LogEntry{}
  53. if err = proto.Unmarshal(entryData, logEntry); err != nil {
  54. glog.Errorf("unexpected unmarshal messaging_pb.Message: %v", err)
  55. pos += 4 + int(size)
  56. continue
  57. }
  58. lastReadTime = time.Unix(0, logEntry.TsNs)
  59. if startReadTime.IsZero() {
  60. startReadTime = lastReadTime
  61. }
  62. if err = eachLogDataFn(logEntry); err != nil {
  63. return
  64. }
  65. pos += 4 + int(size)
  66. batchSize++
  67. }
  68. // glog.V(4).Infof("%s sent messages ts[%+v,%+v] size %d\n", readerName, startReadTime, lastReadTime, batchSize)
  69. }
  70. }