log_buffer.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. package log_buffer
  2. import (
  3. "bytes"
  4. "sync"
  5. "sync/atomic"
  6. "time"
  7. "google.golang.org/protobuf/proto"
  8. "github.com/seaweedfs/seaweedfs/weed/glog"
  9. "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
  10. "github.com/seaweedfs/seaweedfs/weed/util"
  11. )
  12. const BufferSize = 4 * 1024 * 1024
  13. const PreviousBufferCount = 3
  14. type dataToFlush struct {
  15. startTime time.Time
  16. stopTime time.Time
  17. data *bytes.Buffer
  18. }
  19. type LogBuffer struct {
  20. name string
  21. prevBuffers *SealedBuffers
  22. buf []byte
  23. idx []int
  24. pos int
  25. startTime time.Time
  26. stopTime time.Time
  27. lastFlushTime time.Time
  28. sizeBuf []byte
  29. flushInterval time.Duration
  30. flushFn func(startTime, stopTime time.Time, buf []byte)
  31. notifyFn func()
  32. isStopping *atomic.Bool
  33. flushChan chan *dataToFlush
  34. lastTsNs int64
  35. sync.RWMutex
  36. }
  37. func NewLogBuffer(name string, flushInterval time.Duration, flushFn func(startTime, stopTime time.Time, buf []byte), notifyFn func()) *LogBuffer {
  38. lb := &LogBuffer{
  39. name: name,
  40. prevBuffers: newSealedBuffers(PreviousBufferCount),
  41. buf: make([]byte, BufferSize),
  42. sizeBuf: make([]byte, 4),
  43. flushInterval: flushInterval,
  44. flushFn: flushFn,
  45. notifyFn: notifyFn,
  46. flushChan: make(chan *dataToFlush, 256),
  47. isStopping: new(atomic.Bool),
  48. }
  49. go lb.loopFlush()
  50. go lb.loopInterval()
  51. return lb
  52. }
  53. func (m *LogBuffer) AddToBuffer(partitionKey, data []byte, processingTsNs int64) {
  54. var toFlush *dataToFlush
  55. m.Lock()
  56. defer func() {
  57. m.Unlock()
  58. if toFlush != nil {
  59. m.flushChan <- toFlush
  60. }
  61. if m.notifyFn != nil {
  62. m.notifyFn()
  63. }
  64. }()
  65. // need to put the timestamp inside the lock
  66. var ts time.Time
  67. if processingTsNs == 0 {
  68. ts = time.Now()
  69. processingTsNs = ts.UnixNano()
  70. } else {
  71. ts = time.Unix(0, processingTsNs)
  72. }
  73. if m.lastTsNs >= processingTsNs {
  74. // this is unlikely to happen, but just in case
  75. processingTsNs = m.lastTsNs + 1
  76. ts = time.Unix(0, processingTsNs)
  77. }
  78. m.lastTsNs = processingTsNs
  79. logEntry := &filer_pb.LogEntry{
  80. TsNs: processingTsNs,
  81. PartitionKeyHash: util.HashToInt32(partitionKey),
  82. Data: data,
  83. }
  84. logEntryData, _ := proto.Marshal(logEntry)
  85. size := len(logEntryData)
  86. if m.pos == 0 {
  87. m.startTime = ts
  88. }
  89. if m.startTime.Add(m.flushInterval).Before(ts) || len(m.buf)-m.pos < size+4 {
  90. // glog.V(4).Infof("%s copyToFlush1 start time %v, ts %v, remaining %d bytes", m.name, m.startTime, ts, len(m.buf)-m.pos)
  91. toFlush = m.copyToFlush()
  92. m.startTime = ts
  93. if len(m.buf) < size+4 {
  94. m.buf = make([]byte, 2*size+4)
  95. }
  96. }
  97. m.stopTime = ts
  98. m.idx = append(m.idx, m.pos)
  99. util.Uint32toBytes(m.sizeBuf, uint32(size))
  100. copy(m.buf[m.pos:m.pos+4], m.sizeBuf)
  101. copy(m.buf[m.pos+4:m.pos+4+size], logEntryData)
  102. m.pos += size + 4
  103. // fmt.Printf("entry size %d total %d count %d, buffer:%p\n", size, m.pos, len(m.idx), m)
  104. }
  105. func (m *LogBuffer) IsStopping() bool {
  106. return m.isStopping.Load()
  107. }
  108. func (m *LogBuffer) Shutdown() {
  109. isAlreadyStopped := m.isStopping.Swap(true)
  110. if isAlreadyStopped {
  111. return
  112. }
  113. toFlush := m.copyToFlush()
  114. m.flushChan <- toFlush
  115. close(m.flushChan)
  116. }
  117. func (m *LogBuffer) loopFlush() {
  118. for d := range m.flushChan {
  119. if d != nil {
  120. // glog.V(4).Infof("%s flush [%v, %v] size %d", m.name, d.startTime, d.stopTime, len(d.data.Bytes()))
  121. m.flushFn(d.startTime, d.stopTime, d.data.Bytes())
  122. d.releaseMemory()
  123. // local logbuffer is different from aggregate logbuffer here
  124. m.lastFlushTime = d.stopTime
  125. }
  126. }
  127. }
  128. func (m *LogBuffer) loopInterval() {
  129. for !m.IsStopping() {
  130. time.Sleep(m.flushInterval)
  131. if m.IsStopping() {
  132. return
  133. }
  134. m.Lock()
  135. toFlush := m.copyToFlush()
  136. m.Unlock()
  137. if toFlush != nil {
  138. m.flushChan <- toFlush
  139. }
  140. }
  141. }
  142. func (m *LogBuffer) copyToFlush() *dataToFlush {
  143. if m.pos > 0 {
  144. // fmt.Printf("flush buffer %d pos %d empty space %d\n", len(m.buf), m.pos, len(m.buf)-m.pos)
  145. var d *dataToFlush
  146. if m.flushFn != nil {
  147. d = &dataToFlush{
  148. startTime: m.startTime,
  149. stopTime: m.stopTime,
  150. data: copiedBytes(m.buf[:m.pos]),
  151. }
  152. // glog.V(4).Infof("%s flushing [0,%d) with %d entries [%v, %v]", m.name, m.pos, len(m.idx), m.startTime, m.stopTime)
  153. } else {
  154. // glog.V(4).Infof("%s removed from memory [0,%d) with %d entries [%v, %v]", m.name, m.pos, len(m.idx), m.startTime, m.stopTime)
  155. m.lastFlushTime = m.stopTime
  156. }
  157. m.buf = m.prevBuffers.SealBuffer(m.startTime, m.stopTime, m.buf, m.pos)
  158. m.startTime = time.Unix(0, 0)
  159. m.stopTime = time.Unix(0, 0)
  160. m.pos = 0
  161. m.idx = m.idx[:0]
  162. return d
  163. }
  164. return nil
  165. }
  166. func (d *dataToFlush) releaseMemory() {
  167. d.data.Reset()
  168. bufferPool.Put(d.data)
  169. }
  170. func (m *LogBuffer) ReadFromBuffer(lastReadTime time.Time) (bufferCopy *bytes.Buffer, err error) {
  171. m.RLock()
  172. defer m.RUnlock()
  173. // Read from disk and memory
  174. // 1. read from disk, last time is = td
  175. // 2. in memory, the earliest time = tm
  176. // if tm <= td, case 2.1
  177. // read from memory
  178. // if tm is empty, case 2.2
  179. // read from memory
  180. // if td < tm, case 2.3
  181. // read from disk again
  182. var tsMemory time.Time
  183. if !m.startTime.IsZero() {
  184. tsMemory = m.startTime
  185. }
  186. for _, prevBuf := range m.prevBuffers.buffers {
  187. if !prevBuf.startTime.IsZero() && prevBuf.startTime.Before(tsMemory) {
  188. tsMemory = prevBuf.startTime
  189. }
  190. }
  191. if tsMemory.IsZero() { // case 2.2
  192. return nil, nil
  193. } else if lastReadTime.Before(tsMemory) { // case 2.3
  194. if !m.lastFlushTime.IsZero() {
  195. glog.V(0).Infof("resume with last flush time: %v", m.lastFlushTime)
  196. return nil, ResumeFromDiskError
  197. }
  198. }
  199. // the following is case 2.1
  200. if lastReadTime.Equal(m.stopTime) {
  201. return nil, nil
  202. }
  203. if lastReadTime.After(m.stopTime) {
  204. // glog.Fatalf("unexpected last read time %v, older than latest %v", lastReadTime, m.stopTime)
  205. return nil, nil
  206. }
  207. if lastReadTime.Before(m.startTime) {
  208. // println("checking ", lastReadTime.UnixNano())
  209. for _, buf := range m.prevBuffers.buffers {
  210. if buf.startTime.After(lastReadTime) {
  211. // glog.V(4).Infof("%s return the %d sealed buffer %v", m.name, i, buf.startTime)
  212. // println("return the", i, "th in memory", buf.startTime.UnixNano())
  213. return copiedBytes(buf.buf[:buf.size]), nil
  214. }
  215. if !buf.startTime.After(lastReadTime) && buf.stopTime.After(lastReadTime) {
  216. pos := buf.locateByTs(lastReadTime)
  217. // fmt.Printf("locate buffer[%d] pos %d\n", i, pos)
  218. return copiedBytes(buf.buf[pos:buf.size]), nil
  219. }
  220. }
  221. // glog.V(4).Infof("%s return the current buf %v", m.name, lastReadTime)
  222. return copiedBytes(m.buf[:m.pos]), nil
  223. }
  224. lastTs := lastReadTime.UnixNano()
  225. l, h := 0, len(m.idx)-1
  226. /*
  227. for i, pos := range m.idx {
  228. logEntry, ts := readTs(m.buf, pos)
  229. event := &filer_pb.SubscribeMetadataResponse{}
  230. proto.Unmarshal(logEntry.Data, event)
  231. entry := event.EventNotification.OldEntry
  232. if entry == nil {
  233. entry = event.EventNotification.NewEntry
  234. }
  235. fmt.Printf("entry %d ts: %v offset:%d dir:%s name:%s\n", i, time.Unix(0, ts), pos, event.Directory, entry.Name)
  236. }
  237. fmt.Printf("l=%d, h=%d\n", l, h)
  238. */
  239. for l <= h {
  240. mid := (l + h) / 2
  241. pos := m.idx[mid]
  242. _, t := readTs(m.buf, pos)
  243. if t <= lastTs {
  244. l = mid + 1
  245. } else if lastTs < t {
  246. var prevT int64
  247. if mid > 0 {
  248. _, prevT = readTs(m.buf, m.idx[mid-1])
  249. }
  250. if prevT <= lastTs {
  251. // 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)
  252. return copiedBytes(m.buf[pos:m.pos]), nil
  253. }
  254. h = mid
  255. }
  256. // fmt.Printf("l=%d, h=%d\n", l, h)
  257. }
  258. // FIXME: this could be that the buffer has been flushed already
  259. return nil, nil
  260. }
  261. func (m *LogBuffer) ReleaseMemory(b *bytes.Buffer) {
  262. bufferPool.Put(b)
  263. }
  264. var bufferPool = sync.Pool{
  265. New: func() interface{} {
  266. return new(bytes.Buffer)
  267. },
  268. }
  269. func copiedBytes(buf []byte) (copied *bytes.Buffer) {
  270. copied = bufferPool.Get().(*bytes.Buffer)
  271. copied.Reset()
  272. copied.Write(buf)
  273. return
  274. }
  275. func readTs(buf []byte, pos int) (size int, ts int64) {
  276. size = int(util.BytesToUint32(buf[pos : pos+4]))
  277. entryData := buf[pos+4 : pos+4+size]
  278. logEntry := &filer_pb.LogEntry{}
  279. err := proto.Unmarshal(entryData, logEntry)
  280. if err != nil {
  281. glog.Fatalf("unexpected unmarshal filer_pb.LogEntry: %v", err)
  282. }
  283. return size, logEntry.TsNs
  284. }