logs.go 6.0 KB

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