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.

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