log_buffer.go 8.0 KB

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