copier.go 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  1. package logger // import "github.com/docker/docker/daemon/logger"
  2. import (
  3. "bytes"
  4. "io"
  5. "sync"
  6. "time"
  7. types "github.com/docker/docker/api/types/backend"
  8. "github.com/docker/docker/pkg/stringid"
  9. "github.com/sirupsen/logrus"
  10. )
  11. const (
  12. // readSize is the maximum bytes read during a single read
  13. // operation.
  14. readSize = 2 * 1024
  15. // defaultBufSize provides a reasonable default for loggers that do
  16. // not have an external limit to impose on log line size.
  17. defaultBufSize = 16 * 1024
  18. )
  19. // Copier can copy logs from specified sources to Logger and attach Timestamp.
  20. // Writes are concurrent, so you need implement some sync in your logger.
  21. type Copier struct {
  22. // srcs is map of name -> reader pairs, for example "stdout", "stderr"
  23. srcs map[string]io.Reader
  24. dst Logger
  25. copyJobs sync.WaitGroup
  26. closeOnce sync.Once
  27. closed chan struct{}
  28. }
  29. // NewCopier creates a new Copier
  30. func NewCopier(srcs map[string]io.Reader, dst Logger) *Copier {
  31. return &Copier{
  32. srcs: srcs,
  33. dst: dst,
  34. closed: make(chan struct{}),
  35. }
  36. }
  37. // Run starts logs copying
  38. func (c *Copier) Run() {
  39. for src, w := range c.srcs {
  40. c.copyJobs.Add(1)
  41. go c.copySrc(src, w)
  42. }
  43. }
  44. func (c *Copier) copySrc(name string, src io.Reader) {
  45. defer c.copyJobs.Done()
  46. bufSize := defaultBufSize
  47. if sizedLogger, ok := c.dst.(SizedLogger); ok {
  48. size := sizedLogger.BufSize()
  49. // Loggers that wrap another loggers would have BufSize(), but cannot return the size
  50. // when the wrapped loggers doesn't have BufSize().
  51. if size > 0 {
  52. bufSize = size
  53. }
  54. }
  55. buf := make([]byte, bufSize)
  56. n := 0
  57. eof := false
  58. var partialid string
  59. var partialTS time.Time
  60. var ordinal int
  61. firstPartial := true
  62. hasMorePartial := false
  63. for {
  64. select {
  65. case <-c.closed:
  66. return
  67. default:
  68. // Work out how much more data we are okay with reading this time.
  69. upto := n + readSize
  70. if upto > cap(buf) {
  71. upto = cap(buf)
  72. }
  73. // Try to read that data.
  74. if upto > n {
  75. read, err := src.Read(buf[n:upto])
  76. if err != nil {
  77. if err != io.EOF {
  78. logReadsFailedCount.Inc(1)
  79. logrus.Errorf("Error scanning log stream: %s", err)
  80. return
  81. }
  82. eof = true
  83. }
  84. n += read
  85. }
  86. // If we have no data to log, and there's no more coming, we're done.
  87. if n == 0 && eof {
  88. return
  89. }
  90. // Break up the data that we've buffered up into lines, and log each in turn.
  91. p := 0
  92. for q := bytes.IndexByte(buf[p:n], '\n'); q >= 0; q = bytes.IndexByte(buf[p:n], '\n') {
  93. select {
  94. case <-c.closed:
  95. return
  96. default:
  97. msg := NewMessage()
  98. msg.Source = name
  99. msg.Line = append(msg.Line, buf[p:p+q]...)
  100. if hasMorePartial {
  101. msg.PLogMetaData = &types.PartialLogMetaData{ID: partialid, Ordinal: ordinal, Last: true}
  102. // reset
  103. partialid = ""
  104. ordinal = 0
  105. firstPartial = true
  106. hasMorePartial = false
  107. }
  108. if msg.PLogMetaData == nil {
  109. msg.Timestamp = time.Now().UTC()
  110. } else {
  111. msg.Timestamp = partialTS
  112. }
  113. if logErr := c.dst.Log(msg); logErr != nil {
  114. logDriverError(c.dst.Name(), string(msg.Line), logErr)
  115. }
  116. }
  117. p += q + 1
  118. }
  119. // If there's no more coming, or the buffer is full but
  120. // has no newlines, log whatever we haven't logged yet,
  121. // noting that it's a partial log line.
  122. if eof || (p == 0 && n == len(buf)) {
  123. if p < n {
  124. msg := NewMessage()
  125. msg.Source = name
  126. msg.Line = append(msg.Line, buf[p:n]...)
  127. // Generate unique partialID for first partial. Use it across partials.
  128. // Record timestamp for first partial. Use it across partials.
  129. // Initialize Ordinal for first partial. Increment it across partials.
  130. if firstPartial {
  131. msg.Timestamp = time.Now().UTC()
  132. partialTS = msg.Timestamp
  133. partialid = stringid.GenerateRandomID()
  134. ordinal = 1
  135. firstPartial = false
  136. totalPartialLogs.Inc(1)
  137. } else {
  138. msg.Timestamp = partialTS
  139. }
  140. msg.PLogMetaData = &types.PartialLogMetaData{ID: partialid, Ordinal: ordinal, Last: false}
  141. ordinal++
  142. hasMorePartial = true
  143. if logErr := c.dst.Log(msg); logErr != nil {
  144. logDriverError(c.dst.Name(), string(msg.Line), logErr)
  145. }
  146. p = 0
  147. n = 0
  148. }
  149. if eof {
  150. return
  151. }
  152. }
  153. // Move any unlogged data to the front of the buffer in preparation for another read.
  154. if p > 0 {
  155. copy(buf[0:], buf[p:n])
  156. n -= p
  157. }
  158. }
  159. }
  160. }
  161. // Wait waits until all copying is done
  162. func (c *Copier) Wait() {
  163. c.copyJobs.Wait()
  164. }
  165. // Close closes the copier
  166. func (c *Copier) Close() {
  167. c.closeOnce.Do(func() {
  168. close(c.closed)
  169. })
  170. }