logs.go 6.0 KB

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