buffer.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. // Copyright (c) 2020 Tailscale Inc & AUTHORS All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package logtail
  5. import (
  6. "errors"
  7. "fmt"
  8. "sync"
  9. )
  10. type Buffer interface {
  11. // TryReadLine tries to read a log line from the ring buffer.
  12. // If no line is available it returns a nil slice.
  13. // If the ring buffer is closed it returns io.EOF.
  14. //
  15. // The returned slice may point to data that will be overwritten
  16. // by a subsequent call to TryReadLine.
  17. TryReadLine() ([]byte, error)
  18. // Write writes a log line into the ring buffer.
  19. //
  20. // Write takes ownership of the provided slice.
  21. Write([]byte) (int, error)
  22. }
  23. func NewMemoryBuffer(numEntries int) Buffer {
  24. return &memBuffer{
  25. pending: make(chan qentry, numEntries),
  26. }
  27. }
  28. type memBuffer struct {
  29. next []byte
  30. pending chan qentry
  31. dropMu sync.Mutex
  32. dropCount int
  33. }
  34. func (m *memBuffer) TryReadLine() ([]byte, error) {
  35. if m.next != nil {
  36. msg := m.next
  37. m.next = nil
  38. return msg, nil
  39. }
  40. select {
  41. case ent := <-m.pending:
  42. if ent.dropCount > 0 {
  43. m.next = ent.msg
  44. return fmt.Appendf(nil, "----------- %d logs dropped ----------", ent.dropCount), nil
  45. }
  46. return ent.msg, nil
  47. default:
  48. return nil, nil
  49. }
  50. }
  51. func (m *memBuffer) Write(b []byte) (int, error) {
  52. m.dropMu.Lock()
  53. defer m.dropMu.Unlock()
  54. ent := qentry{
  55. msg: b,
  56. dropCount: m.dropCount,
  57. }
  58. select {
  59. case m.pending <- ent:
  60. m.dropCount = 0
  61. return len(b), nil
  62. default:
  63. m.dropCount++
  64. return 0, errBufferFull
  65. }
  66. }
  67. type qentry struct {
  68. msg []byte
  69. dropCount int
  70. }
  71. var errBufferFull = errors.New("logtail: buffer full")