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.

214 lines
4.7 KiB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
  1. package queue
  2. import (
  3. "sync"
  4. "time"
  5. "github.com/golang/protobuf/proto"
  6. "github.com/chrislusf/seaweedfs/weed/glog"
  7. "github.com/chrislusf/seaweedfs/weed/pb/filer_pb"
  8. "github.com/chrislusf/seaweedfs/weed/util"
  9. )
  10. type dataToFlush struct {
  11. startTime time.Time
  12. stopTime time.Time
  13. data []byte
  14. }
  15. type LogBuffer struct {
  16. buf []byte
  17. idx []int
  18. pos int
  19. startTime time.Time
  20. stopTime time.Time
  21. sizeBuf []byte
  22. flushInterval time.Duration
  23. flushFn func(startTime, stopTime time.Time, buf []byte)
  24. notifyFn func()
  25. isStopping bool
  26. flushChan chan *dataToFlush
  27. sync.RWMutex
  28. }
  29. func NewLogBuffer(flushInterval time.Duration, flushFn func(startTime, stopTime time.Time, buf []byte), notifyFn func()) *LogBuffer {
  30. lb := &LogBuffer{
  31. buf: make([]byte, 4*1024*1024),
  32. sizeBuf: make([]byte, 4),
  33. flushInterval: flushInterval,
  34. flushFn: flushFn,
  35. notifyFn: notifyFn,
  36. flushChan: make(chan *dataToFlush, 256),
  37. }
  38. go lb.loopFlush()
  39. go lb.loopInterval()
  40. return lb
  41. }
  42. func (m *LogBuffer) AddToBuffer(key, data []byte) {
  43. m.Lock()
  44. defer func() {
  45. m.Unlock()
  46. if m.notifyFn != nil {
  47. m.notifyFn()
  48. }
  49. }()
  50. // need to put the timestamp inside the lock
  51. ts := time.Now()
  52. logEntry := &filer_pb.LogEntry{
  53. TsNs: ts.UnixNano(),
  54. PartitionKeyHash: util.HashToInt32(key),
  55. Data: data,
  56. }
  57. logEntryData, _ := proto.Marshal(logEntry)
  58. size := len(logEntryData)
  59. if m.pos == 0 {
  60. m.startTime = ts
  61. }
  62. if m.startTime.Add(m.flushInterval).Before(ts) || len(m.buf)-m.pos < size+4 {
  63. m.flushChan <- m.copyToFlush()
  64. m.startTime = ts
  65. if len(m.buf) < size+4 {
  66. m.buf = make([]byte, 2*size+4)
  67. }
  68. }
  69. m.stopTime = ts
  70. m.idx = append(m.idx, m.pos)
  71. util.Uint32toBytes(m.sizeBuf, uint32(size))
  72. copy(m.buf[m.pos:m.pos+4], m.sizeBuf)
  73. copy(m.buf[m.pos+4:m.pos+4+size], logEntryData)
  74. m.pos += size + 4
  75. }
  76. func (m *LogBuffer) Shutdown() {
  77. if m.isStopping {
  78. return
  79. }
  80. m.isStopping = true
  81. m.Lock()
  82. toFlush := m.copyToFlush()
  83. m.Unlock()
  84. m.flushChan <- toFlush
  85. close(m.flushChan)
  86. }
  87. func (m *LogBuffer) loopFlush() {
  88. for d := range m.flushChan {
  89. if d != nil {
  90. m.flushFn(d.startTime, d.stopTime, d.data)
  91. }
  92. }
  93. }
  94. func (m *LogBuffer) loopInterval() {
  95. for !m.isStopping {
  96. m.Lock()
  97. toFlush := m.copyToFlush()
  98. m.Unlock()
  99. m.flushChan <- toFlush
  100. time.Sleep(m.flushInterval)
  101. }
  102. }
  103. func (m *LogBuffer) copyToFlush() *dataToFlush {
  104. if m.flushFn != nil && m.pos > 0 {
  105. // fmt.Printf("flush buffer %d pos %d empty space %d\n", len(m.buf), m.pos, len(m.buf)-m.pos)
  106. d := &dataToFlush{
  107. startTime: m.startTime,
  108. stopTime: m.stopTime,
  109. data: copiedBytes(m.buf[:m.pos]),
  110. }
  111. m.pos = 0
  112. m.idx = m.idx[:0]
  113. return d
  114. }
  115. return nil
  116. }
  117. func (m *LogBuffer) ReadFromBuffer(lastReadTime time.Time) (ts time.Time, bufferCopy []byte) {
  118. m.RLock()
  119. defer m.RUnlock()
  120. // fmt.Printf("read from buffer: %v\n", lastReadTime)
  121. if lastReadTime.Equal(m.stopTime) {
  122. return lastReadTime, nil
  123. }
  124. if lastReadTime.After(m.stopTime) {
  125. // glog.Fatalf("unexpected last read time %v, older than latest %v", lastReadTime, m.stopTime)
  126. return lastReadTime, nil
  127. }
  128. if lastReadTime.Before(m.startTime) {
  129. return m.stopTime, copiedBytes(m.buf[:m.pos])
  130. }
  131. lastTs := lastReadTime.UnixNano()
  132. l, h := 0, len(m.idx)-1
  133. /*
  134. for i, pos := range m.idx {
  135. logEntry, ts := readTs(m.buf, pos)
  136. event := &filer_pb.FullEventNotification{}
  137. proto.Unmarshal(logEntry.Data, event)
  138. entry := event.EventNotification.OldEntry
  139. if entry == nil {
  140. entry = event.EventNotification.NewEntry
  141. }
  142. fmt.Printf("entry %d ts: %v offset:%d dir:%s name:%s\n", i, time.Unix(0, ts), pos, event.Directory, entry.Name)
  143. }
  144. fmt.Printf("l=%d, h=%d\n", l, h)
  145. */
  146. for l <= h {
  147. mid := (l + h) / 2
  148. pos := m.idx[mid]
  149. _, t := readTs(m.buf, m.idx[mid])
  150. if t <= lastTs {
  151. l = mid + 1
  152. } else if lastTs < t {
  153. var prevT int64
  154. if mid > 0 {
  155. _, prevT = readTs(m.buf, m.idx[mid-1])
  156. }
  157. if prevT <= lastTs {
  158. // println("found mid = ", mid)
  159. return time.Unix(0, t), copiedBytes(m.buf[pos:m.pos])
  160. }
  161. h = mid - 1
  162. }
  163. // fmt.Printf("l=%d, h=%d\n", l, h)
  164. }
  165. // FIXME: this could be that the buffer has been flushed already
  166. // println("not found")
  167. return lastReadTime, nil
  168. }
  169. func copiedBytes(buf []byte) (copied []byte) {
  170. copied = make([]byte, len(buf))
  171. copy(copied, buf)
  172. return
  173. }
  174. func readTs(buf []byte, pos int) (*filer_pb.LogEntry, int64) {
  175. size := util.BytesToUint32(buf[pos : pos+4])
  176. entryData := buf[pos+4 : pos+4+int(size)]
  177. logEntry := &filer_pb.LogEntry{}
  178. err := proto.Unmarshal(entryData, logEntry)
  179. if err != nil {
  180. glog.Fatalf("unexpected unmarshal filer_pb.LogEntry: %v", err)
  181. }
  182. return logEntry, logEntry.TsNs
  183. }