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.

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