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.

88 lines
2.2 KiB

4 years ago
4 years ago
4 years ago
5 years ago
  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. time.Sleep(1127 * time.Millisecond)
  31. return lastReadTime, ResumeFromDiskError
  32. }
  33. // glog.V(4).Infof("%s ReadFromBuffer by %v", readerName, lastReadTime)
  34. if bytesBuf == nil {
  35. if waitForDataFn() {
  36. continue
  37. } else {
  38. return
  39. }
  40. }
  41. buf := bytesBuf.Bytes()
  42. // fmt.Printf("ReadFromBuffer %s by %v size %d\n", readerName, lastReadTime, len(buf))
  43. batchSize := 0
  44. var startReadTime time.Time
  45. for pos := 0; pos+4 < len(buf); {
  46. size := util.BytesToUint32(buf[pos : pos+4])
  47. if pos+4+int(size) > len(buf) {
  48. err = ResumeError
  49. glog.Errorf("LoopProcessLogData: %s read buffer %v read %d [%d,%d) from [0,%d)", readerName, lastReadTime, batchSize, pos, pos+int(size)+4, len(buf))
  50. return
  51. }
  52. entryData := buf[pos+4 : pos+4+int(size)]
  53. logEntry := &filer_pb.LogEntry{}
  54. if err = proto.Unmarshal(entryData, logEntry); err != nil {
  55. glog.Errorf("unexpected unmarshal messaging_pb.Message: %v", err)
  56. pos += 4 + int(size)
  57. continue
  58. }
  59. lastReadTime = time.Unix(0, logEntry.TsNs)
  60. if startReadTime.IsZero() {
  61. startReadTime = lastReadTime
  62. }
  63. if err = eachLogDataFn(logEntry); err != nil {
  64. return
  65. }
  66. pos += 4 + int(size)
  67. batchSize++
  68. }
  69. // glog.V(4).Infof("%s sent messages ts[%+v,%+v] size %d\n", readerName, startReadTime, lastReadTime, batchSize)
  70. }
  71. }