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.

281 lines
6.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
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. lastTsNs int64
  32. sync.RWMutex
  33. }
  34. func NewLogBuffer(flushInterval time.Duration, flushFn func(startTime, stopTime time.Time, buf []byte), notifyFn func()) *LogBuffer {
  35. lb := &LogBuffer{
  36. prevBuffers: newSealedBuffers(PreviousBufferCount),
  37. buf: make([]byte, BufferSize),
  38. sizeBuf: make([]byte, 4),
  39. flushInterval: flushInterval,
  40. flushFn: flushFn,
  41. notifyFn: notifyFn,
  42. flushChan: make(chan *dataToFlush, 256),
  43. }
  44. go lb.loopFlush()
  45. go lb.loopInterval()
  46. return lb
  47. }
  48. func (m *LogBuffer) AddToBuffer(partitionKey, data []byte) {
  49. m.Lock()
  50. defer func() {
  51. m.Unlock()
  52. if m.notifyFn != nil {
  53. m.notifyFn()
  54. }
  55. }()
  56. // need to put the timestamp inside the lock
  57. ts := time.Now()
  58. tsNs := ts.UnixNano()
  59. if m.lastTsNs >= tsNs {
  60. // this is unlikely to happen, but just in case
  61. tsNs = m.lastTsNs + 1
  62. ts = time.Unix(0, tsNs)
  63. }
  64. m.lastTsNs = tsNs
  65. logEntry := &filer_pb.LogEntry{
  66. TsNs: tsNs,
  67. PartitionKeyHash: util.HashToInt32(partitionKey),
  68. Data: data,
  69. }
  70. logEntryData, _ := proto.Marshal(logEntry)
  71. size := len(logEntryData)
  72. if m.pos == 0 {
  73. m.startTime = ts
  74. }
  75. if m.startTime.Add(m.flushInterval).Before(ts) || len(m.buf)-m.pos < size+4 {
  76. m.flushChan <- m.copyToFlush()
  77. m.startTime = ts
  78. if len(m.buf) < size+4 {
  79. m.buf = make([]byte, 2*size+4)
  80. }
  81. }
  82. m.stopTime = ts
  83. m.idx = append(m.idx, m.pos)
  84. util.Uint32toBytes(m.sizeBuf, uint32(size))
  85. copy(m.buf[m.pos:m.pos+4], m.sizeBuf)
  86. copy(m.buf[m.pos+4:m.pos+4+size], logEntryData)
  87. m.pos += size + 4
  88. // fmt.Printf("entry size %d total %d count %d, buffer:%p\n", size, m.pos, len(m.idx), m)
  89. }
  90. func (m *LogBuffer) Shutdown() {
  91. m.Lock()
  92. defer m.Unlock()
  93. if m.isStopping {
  94. return
  95. }
  96. m.isStopping = true
  97. toFlush := m.copyToFlush()
  98. m.flushChan <- toFlush
  99. close(m.flushChan)
  100. }
  101. func (m *LogBuffer) loopFlush() {
  102. for d := range m.flushChan {
  103. if d != nil {
  104. // fmt.Printf("flush [%v, %v] size %d\n", d.startTime, d.stopTime, len(d.data.Bytes()))
  105. m.flushFn(d.startTime, d.stopTime, d.data.Bytes())
  106. d.releaseMemory()
  107. }
  108. }
  109. }
  110. func (m *LogBuffer) loopInterval() {
  111. for !m.isStopping {
  112. time.Sleep(m.flushInterval)
  113. m.Lock()
  114. if m.isStopping {
  115. m.Unlock()
  116. return
  117. }
  118. // println("loop interval")
  119. toFlush := m.copyToFlush()
  120. m.flushChan <- toFlush
  121. m.Unlock()
  122. }
  123. }
  124. func (m *LogBuffer) copyToFlush() *dataToFlush {
  125. if m.pos > 0 {
  126. // fmt.Printf("flush buffer %d pos %d empty space %d\n", len(m.buf), m.pos, len(m.buf)-m.pos)
  127. var d *dataToFlush
  128. if m.flushFn != nil {
  129. d = &dataToFlush{
  130. startTime: m.startTime,
  131. stopTime: m.stopTime,
  132. data: copiedBytes(m.buf[:m.pos]),
  133. }
  134. }
  135. // fmt.Printf("flusing [0,%d) with %d entries\n", m.pos, len(m.idx))
  136. m.buf = m.prevBuffers.SealBuffer(m.startTime, m.stopTime, m.buf, m.pos)
  137. m.pos = 0
  138. m.idx = m.idx[:0]
  139. return d
  140. }
  141. return nil
  142. }
  143. func (d *dataToFlush) releaseMemory() {
  144. d.data.Reset()
  145. bufferPool.Put(d.data)
  146. }
  147. func (m *LogBuffer) ReadFromBuffer(lastReadTime time.Time) (bufferCopy *bytes.Buffer) {
  148. m.RLock()
  149. defer m.RUnlock()
  150. /*
  151. 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))
  152. for i, prevBuf := range m.prevBuffers.buffers {
  153. fmt.Printf(" prev %d : %s\n", i, prevBuf.String())
  154. }
  155. */
  156. if lastReadTime.Equal(m.stopTime) {
  157. return nil
  158. }
  159. if lastReadTime.After(m.stopTime) {
  160. // glog.Fatalf("unexpected last read time %v, older than latest %v", lastReadTime, m.stopTime)
  161. return nil
  162. }
  163. if lastReadTime.Before(m.startTime) {
  164. // println("checking ", lastReadTime.UnixNano())
  165. for i, buf := range m.prevBuffers.buffers {
  166. if buf.startTime.After(lastReadTime) {
  167. if i == 0 {
  168. // println("return the earliest in memory", buf.startTime.UnixNano())
  169. return copiedBytes(buf.buf[:buf.size])
  170. }
  171. // println("return the", i, "th in memory", buf.startTime.UnixNano())
  172. return copiedBytes(buf.buf[:buf.size])
  173. }
  174. if !buf.startTime.After(lastReadTime) && buf.stopTime.After(lastReadTime) {
  175. pos := buf.locateByTs(lastReadTime)
  176. // fmt.Printf("locate buffer[%d] pos %d\n", i, pos)
  177. return copiedBytes(buf.buf[pos:buf.size])
  178. }
  179. }
  180. // println("return the current buf", lastReadTime.UnixNano())
  181. return copiedBytes(m.buf[:m.pos])
  182. }
  183. lastTs := lastReadTime.UnixNano()
  184. l, h := 0, len(m.idx)-1
  185. /*
  186. for i, pos := range m.idx {
  187. logEntry, ts := readTs(m.buf, pos)
  188. event := &filer_pb.SubscribeMetadataResponse{}
  189. proto.Unmarshal(logEntry.Data, event)
  190. entry := event.EventNotification.OldEntry
  191. if entry == nil {
  192. entry = event.EventNotification.NewEntry
  193. }
  194. fmt.Printf("entry %d ts: %v offset:%d dir:%s name:%s\n", i, time.Unix(0, ts), pos, event.Directory, entry.Name)
  195. }
  196. fmt.Printf("l=%d, h=%d\n", l, h)
  197. */
  198. for l <= h {
  199. mid := (l + h) / 2
  200. pos := m.idx[mid]
  201. _, t := readTs(m.buf, pos)
  202. if t <= lastTs {
  203. l = mid + 1
  204. } else if lastTs < t {
  205. var prevT int64
  206. if mid > 0 {
  207. _, prevT = readTs(m.buf, m.idx[mid-1])
  208. }
  209. if prevT <= lastTs {
  210. // 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)
  211. return copiedBytes(m.buf[pos:m.pos])
  212. }
  213. h = mid
  214. }
  215. // fmt.Printf("l=%d, h=%d\n", l, h)
  216. }
  217. // FIXME: this could be that the buffer has been flushed already
  218. return nil
  219. }
  220. func (m *LogBuffer) ReleaseMeory(b *bytes.Buffer) {
  221. bufferPool.Put(b)
  222. }
  223. var bufferPool = sync.Pool{
  224. New: func() interface{} {
  225. return new(bytes.Buffer)
  226. },
  227. }
  228. func copiedBytes(buf []byte) (copied *bytes.Buffer) {
  229. copied = bufferPool.Get().(*bytes.Buffer)
  230. copied.Reset()
  231. copied.Write(buf)
  232. return
  233. }
  234. func readTs(buf []byte, pos int) (size int, ts int64) {
  235. size = int(util.BytesToUint32(buf[pos : pos+4]))
  236. entryData := buf[pos+4 : pos+4+size]
  237. logEntry := &filer_pb.LogEntry{}
  238. err := proto.Unmarshal(entryData, logEntry)
  239. if err != nil {
  240. glog.Fatalf("unexpected unmarshal filer_pb.LogEntry: %v", err)
  241. }
  242. return size, logEntry.TsNs
  243. }