log_buffer.go 11 KB

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