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.

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