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.

265 lines
6.4 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
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. // fmt.Printf("entry size %d total %d count %d, buffer:%p\n", size, m.pos, len(m.idx), m)
  81. }
  82. func (m *LogBuffer) Shutdown() {
  83. if m.isStopping {
  84. return
  85. }
  86. m.isStopping = true
  87. m.Lock()
  88. toFlush := m.copyToFlush()
  89. m.Unlock()
  90. m.flushChan <- toFlush
  91. close(m.flushChan)
  92. }
  93. func (m *LogBuffer) loopFlush() {
  94. for d := range m.flushChan {
  95. if d != nil {
  96. // fmt.Printf("flush [%v, %v] size %d\n", d.startTime, d.stopTime, len(d.data.Bytes()))
  97. m.flushFn(d.startTime, d.stopTime, d.data.Bytes())
  98. d.releaseMemory()
  99. }
  100. }
  101. }
  102. func (m *LogBuffer) loopInterval() {
  103. for !m.isStopping {
  104. time.Sleep(m.flushInterval)
  105. m.Lock()
  106. // println("loop interval")
  107. toFlush := m.copyToFlush()
  108. m.Unlock()
  109. m.flushChan <- toFlush
  110. }
  111. }
  112. func (m *LogBuffer) copyToFlush() *dataToFlush {
  113. if m.flushFn != nil && m.pos > 0 {
  114. // fmt.Printf("flush buffer %d pos %d empty space %d\n", len(m.buf), m.pos, len(m.buf)-m.pos)
  115. d := &dataToFlush{
  116. startTime: m.startTime,
  117. stopTime: m.stopTime,
  118. data: copiedBytes(m.buf[:m.pos]),
  119. }
  120. // fmt.Printf("flusing [0,%d) with %d entries\n", m.pos, len(m.idx))
  121. m.buf = m.prevBuffers.SealBuffer(m.startTime, m.stopTime, m.buf, m.pos)
  122. m.pos = 0
  123. m.idx = m.idx[:0]
  124. return d
  125. }
  126. return nil
  127. }
  128. func (d *dataToFlush) releaseMemory() {
  129. d.data.Reset()
  130. bufferPool.Put(d.data)
  131. }
  132. func (m *LogBuffer) ReadFromBuffer(lastReadTime time.Time) (bufferCopy *bytes.Buffer) {
  133. m.RLock()
  134. defer m.RUnlock()
  135. /*
  136. fmt.Printf("read buffer %p: %v last stop time: [%v,%v], pos %d, entries:%d, prevBufs:%d\n", m, lastReadTime, m.startTime, m.stopTime, m.pos, len(m.idx), len(m.prevBuffers.buffers))
  137. for i, prevBuf := range m.prevBuffers.buffers {
  138. fmt.Printf(" prev %d : %s\n", i, prevBuf.String())
  139. }
  140. */
  141. if lastReadTime.Equal(m.stopTime) {
  142. return nil
  143. }
  144. if lastReadTime.After(m.stopTime) {
  145. // glog.Fatalf("unexpected last read time %v, older than latest %v", lastReadTime, m.stopTime)
  146. return nil
  147. }
  148. if lastReadTime.Before(m.startTime) {
  149. // println("checking ", lastReadTime.UnixNano())
  150. for i, buf := range m.prevBuffers.buffers {
  151. if buf.startTime.After(lastReadTime) {
  152. if i == 0 {
  153. // println("return the earliest in memory", buf.startTime.UnixNano())
  154. return copiedBytes(buf.buf[:buf.size])
  155. }
  156. // println("return the", i, "th in memory", buf.startTime.UnixNano())
  157. return copiedBytes(buf.buf[:buf.size])
  158. }
  159. if !buf.startTime.After(lastReadTime) && buf.stopTime.After(lastReadTime) {
  160. pos := buf.locateByTs(lastReadTime)
  161. // fmt.Printf("locate buffer[%d] pos %d\n", i, pos)
  162. return copiedBytes(buf.buf[pos:buf.size])
  163. }
  164. }
  165. // println("return the current buf", lastReadTime.UnixNano())
  166. return copiedBytes(m.buf[:m.pos])
  167. }
  168. lastTs := lastReadTime.UnixNano()
  169. l, h := 0, len(m.idx)-1
  170. /*
  171. for i, pos := range m.idx {
  172. logEntry, ts := readTs(m.buf, pos)
  173. event := &filer_pb.SubscribeMetadataResponse{}
  174. proto.Unmarshal(logEntry.Data, event)
  175. entry := event.EventNotification.OldEntry
  176. if entry == nil {
  177. entry = event.EventNotification.NewEntry
  178. }
  179. fmt.Printf("entry %d ts: %v offset:%d dir:%s name:%s\n", i, time.Unix(0, ts), pos, event.Directory, entry.Name)
  180. }
  181. fmt.Printf("l=%d, h=%d\n", l, h)
  182. */
  183. for l <= h {
  184. mid := (l + h) / 2
  185. pos := m.idx[mid]
  186. _, t := readTs(m.buf, pos)
  187. if t <= lastTs {
  188. l = mid + 1
  189. } else if lastTs < t {
  190. var prevT int64
  191. if mid > 0 {
  192. _, prevT = readTs(m.buf, m.idx[mid-1])
  193. }
  194. if prevT <= lastTs {
  195. // 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)
  196. return copiedBytes(m.buf[pos:m.pos])
  197. }
  198. h = mid
  199. }
  200. // fmt.Printf("l=%d, h=%d\n", l, h)
  201. }
  202. // FIXME: this could be that the buffer has been flushed already
  203. return nil
  204. }
  205. func (m *LogBuffer) ReleaseMeory(b *bytes.Buffer) {
  206. bufferPool.Put(b)
  207. }
  208. var bufferPool = sync.Pool{
  209. New: func() interface{} {
  210. return new(bytes.Buffer)
  211. },
  212. }
  213. func copiedBytes(buf []byte) (copied *bytes.Buffer) {
  214. copied = bufferPool.Get().(*bytes.Buffer)
  215. copied.Reset()
  216. copied.Write(buf)
  217. return
  218. }
  219. func readTs(buf []byte, pos int) (size int, ts int64) {
  220. size = int(util.BytesToUint32(buf[pos : pos+4]))
  221. entryData := buf[pos+4 : pos+4+size]
  222. logEntry := &filer_pb.LogEntry{}
  223. err := proto.Unmarshal(entryData, logEntry)
  224. if err != nil {
  225. glog.Fatalf("unexpected unmarshal filer_pb.LogEntry: %v", err)
  226. }
  227. return size, logEntry.TsNs
  228. }