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.

352 lines
10 KiB

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