logs.go 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  1. package daemon
  2. import (
  3. "errors"
  4. "strconv"
  5. "time"
  6. "golang.org/x/net/context"
  7. "github.com/Sirupsen/logrus"
  8. "github.com/docker/docker/api/types"
  9. "github.com/docker/docker/api/types/backend"
  10. containertypes "github.com/docker/docker/api/types/container"
  11. timetypes "github.com/docker/docker/api/types/time"
  12. "github.com/docker/docker/container"
  13. "github.com/docker/docker/daemon/logger"
  14. )
  15. // ContainerLogs copies the container's log channel to the channel provided in
  16. // the config. If ContainerLogs returns an error, no messages have been copied.
  17. // and the channel will be closed without data.
  18. //
  19. // if it returns nil, the config channel will be active and return log
  20. // messages until it runs out or the context is canceled.
  21. func (daemon *Daemon) ContainerLogs(ctx context.Context, containerName string, config *types.ContainerLogsOptions) (<-chan *backend.LogMessage, error) {
  22. lg := logrus.WithFields(logrus.Fields{
  23. "module": "daemon",
  24. "method": "(*Daemon).ContainerLogs",
  25. "container": containerName,
  26. })
  27. if !(config.ShowStdout || config.ShowStderr) {
  28. return nil, errors.New("You must choose at least one stream")
  29. }
  30. container, err := daemon.GetContainer(containerName)
  31. if err != nil {
  32. return nil, err
  33. }
  34. if container.RemovalInProgress || container.Dead {
  35. return nil, errors.New("can not get logs from container which is dead or marked for removal")
  36. }
  37. if container.HostConfig.LogConfig.Type == "none" {
  38. return nil, logger.ErrReadLogsNotSupported
  39. }
  40. cLog, cLogCreated, err := daemon.getLogger(container)
  41. if err != nil {
  42. return nil, err
  43. }
  44. if cLogCreated {
  45. defer func() {
  46. if err = cLog.Close(); err != nil {
  47. logrus.Errorf("Error closing logger: %v", err)
  48. }
  49. }()
  50. }
  51. logReader, ok := cLog.(logger.LogReader)
  52. if !ok {
  53. return nil, logger.ErrReadLogsNotSupported
  54. }
  55. follow := config.Follow && !cLogCreated
  56. tailLines, err := strconv.Atoi(config.Tail)
  57. if err != nil {
  58. tailLines = -1
  59. }
  60. var since time.Time
  61. if config.Since != "" {
  62. s, n, err := timetypes.ParseTimestamps(config.Since, 0)
  63. if err != nil {
  64. return nil, err
  65. }
  66. since = time.Unix(s, n)
  67. }
  68. readConfig := logger.ReadConfig{
  69. Since: since,
  70. Tail: tailLines,
  71. Follow: follow,
  72. }
  73. logs := logReader.ReadLogs(readConfig)
  74. // past this point, we can't possibly return any errors, so we can just
  75. // start a goroutine and return to tell the caller not to expect errors
  76. // (if the caller wants to give up on logs, they have to cancel the context)
  77. // this goroutine functions as a shim between the logger and the caller.
  78. messageChan := make(chan *backend.LogMessage, 1)
  79. go func() {
  80. // set up some defers
  81. defer logs.Close()
  82. // close the messages channel. closing is the only way to signal above
  83. // that we're doing with logs (other than context cancel i guess).
  84. defer close(messageChan)
  85. lg.Debug("begin logs")
  86. for {
  87. select {
  88. // i do not believe as the system is currently designed any error
  89. // is possible, but we should be prepared to handle it anyway. if
  90. // we do get an error, copy only the error field to a new object so
  91. // we don't end up with partial data in the other fields
  92. case err := <-logs.Err:
  93. lg.Errorf("Error streaming logs: %v", err)
  94. select {
  95. case <-ctx.Done():
  96. case messageChan <- &backend.LogMessage{Err: err}:
  97. }
  98. return
  99. case <-ctx.Done():
  100. lg.Debug("logs: end stream, ctx is done: %v", ctx.Err())
  101. return
  102. case msg, ok := <-logs.Msg:
  103. // there is some kind of pool or ring buffer in the logger that
  104. // produces these messages, and a possible future optimization
  105. // might be to use that pool and reuse message objects
  106. if !ok {
  107. lg.Debug("end logs")
  108. return
  109. }
  110. m := msg.AsLogMessage() // just a pointer conversion, does not copy data
  111. // there could be a case where the reader stops accepting
  112. // messages and the context is canceled. we need to check that
  113. // here, or otherwise we risk blocking forever on the message
  114. // send.
  115. select {
  116. case <-ctx.Done():
  117. return
  118. case messageChan <- m:
  119. }
  120. }
  121. }
  122. }()
  123. return messageChan, nil
  124. }
  125. func (daemon *Daemon) getLogger(container *container.Container) (l logger.Logger, created bool, err error) {
  126. container.Lock()
  127. if container.State.Running {
  128. l = container.LogDriver
  129. }
  130. container.Unlock()
  131. if l == nil {
  132. created = true
  133. l, err = container.StartLogger()
  134. }
  135. return
  136. }
  137. // mergeLogConfig merges the daemon log config to the container's log config if the container's log driver is not specified.
  138. func (daemon *Daemon) mergeAndVerifyLogConfig(cfg *containertypes.LogConfig) error {
  139. if cfg.Type == "" {
  140. cfg.Type = daemon.defaultLogConfig.Type
  141. }
  142. if cfg.Config == nil {
  143. cfg.Config = make(map[string]string)
  144. }
  145. if cfg.Type == daemon.defaultLogConfig.Type {
  146. for k, v := range daemon.defaultLogConfig.Config {
  147. if _, ok := cfg.Config[k]; !ok {
  148. cfg.Config[k] = v
  149. }
  150. }
  151. }
  152. return logger.ValidateLogOpts(cfg.Type, cfg.Config)
  153. }