mirror of
https://github.com/moby/moby.git
synced 2022-11-09 12:21:53 -05:00
916eabd459
When daemon.ContainerLogs() is called with options.follow=true
(as in "docker logs --follow"), the "loggerutils.followLogs()"
function never returns (even then the logs consumer is gone).
As a result, all the resources associated with it (including
an opened file descriptor for the log file being read, two FDs
for a pipe, and two FDs for inotify watch) are never released.
If this is repeated (such as by running "docker logs --follow"
and pressing Ctrl-C a few times), this results in DoS caused by
either hitting the limit of inotify watches, or the limit of
opened files. The only cure is daemon restart.
Apparently, what happens is:
1. logs producer (a container) is gone, calling (*LogWatcher).Close()
for all its readers (daemon/logger/jsonfilelog/jsonfilelog.go:175).
2. WatchClose() is properly handled by a dedicated goroutine in
followLogs(), cancelling the context.
3. Upon receiving the ctx.Done(), the code in followLogs()
(daemon/logger/loggerutils/logfile.go#L626-L638) keeps to
send messages _synchronously_ (which is OK for now).
4. Logs consumer is gone (Ctrl-C is pressed on a terminal running
"docker logs --follow"). Method (*LogWatcher).Close() is properly
called (see daemon/logs.go:114). Since it was called before and
due to to once.Do(), nothing happens (which is kinda good, as
otherwise it will panic on closing a closed channel).
5. A goroutine (see item 3 above) keeps sending log messages
synchronously to the logWatcher.Msg channel. Since the
channel reader is gone, the channel send operation blocks forever,
and resource cleanup set up in defer statements at the beginning
of followLogs() never happens.
Alas, the fix is somewhat complicated:
1. Distinguish between close from logs producer and logs consumer.
To that effect,
- yet another channel is added to LogWatcher();
- {Watch,}Close() are renamed to {Watch,}ProducerGone();
- {Watch,}ConsumerGone() are added;
*NOTE* that ProducerGone()/WatchProducerGone() pair is ONLY needed
in order to stop ConsumerLogs(follow=true) when a container is stopped;
otherwise we're not interested in it. In other words, we're only
using it in followLogs().
2. Code that was doing (logWatcher*).Close() is modified to either call
ProducerGone() or ConsumerGone(), depending on the context.
3. Code that was waiting for WatchClose() is modified to wait for
either ConsumerGone() or ProducerGone(), or both, depending on the
context.
4. followLogs() are modified accordingly:
- context cancellation is happening on WatchProducerGone(),
and once it's received the FileWatcher is closed and waitRead()
returns errDone on EOF (i.e. log rotation handling logic is disabled);
- due to this, code that was writing synchronously to logWatcher.Msg
can be and is removed as the code above it handles this case;
- function returns once ConsumerGone is received, freeing all the
resources -- this is the bugfix itself.
While at it,
1. Let's also remove the ctx usage to simplify the code a bit.
It was introduced by commit a69a59ffc7
("Decouple removing the
fileWatcher from reading") in order to fix a bug. The bug was actually
a deadlock in fsnotify, and the fix was just a workaround. Since then
the fsnofify bug has been fixed, and a new fsnotify was vendored in.
For more details, please see
https://github.com/moby/moby/pull/27782#issuecomment-416794490
2. Since `(*filePoller).Close()` is fixed to remove all the files
being watched, there is no need to explicitly call
fileWatcher.Remove(name) anymore, so get rid of the extra code.
Should fix https://github.com/moby/moby/issues/37391
Signed-off-by: Kir Kolyshkin <kolyshkin@gmail.com>
187 lines
4.6 KiB
Go
187 lines
4.6 KiB
Go
package daemon // import "github.com/docker/docker/daemon"
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"io"
|
|
|
|
"github.com/docker/docker/api/types/backend"
|
|
"github.com/docker/docker/container"
|
|
"github.com/docker/docker/container/stream"
|
|
"github.com/docker/docker/daemon/logger"
|
|
"github.com/docker/docker/errdefs"
|
|
"github.com/docker/docker/pkg/stdcopy"
|
|
"github.com/docker/docker/pkg/term"
|
|
"github.com/pkg/errors"
|
|
"github.com/sirupsen/logrus"
|
|
)
|
|
|
|
// ContainerAttach attaches to logs according to the config passed in. See ContainerAttachConfig.
|
|
func (daemon *Daemon) ContainerAttach(prefixOrName string, c *backend.ContainerAttachConfig) error {
|
|
keys := []byte{}
|
|
var err error
|
|
if c.DetachKeys != "" {
|
|
keys, err = term.ToBytes(c.DetachKeys)
|
|
if err != nil {
|
|
return errdefs.InvalidParameter(errors.Errorf("Invalid detach keys (%s) provided", c.DetachKeys))
|
|
}
|
|
}
|
|
|
|
container, err := daemon.GetContainer(prefixOrName)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if container.IsPaused() {
|
|
err := fmt.Errorf("container %s is paused, unpause the container before attach", prefixOrName)
|
|
return errdefs.Conflict(err)
|
|
}
|
|
if container.IsRestarting() {
|
|
err := fmt.Errorf("container %s is restarting, wait until the container is running", prefixOrName)
|
|
return errdefs.Conflict(err)
|
|
}
|
|
|
|
cfg := stream.AttachConfig{
|
|
UseStdin: c.UseStdin,
|
|
UseStdout: c.UseStdout,
|
|
UseStderr: c.UseStderr,
|
|
TTY: container.Config.Tty,
|
|
CloseStdin: container.Config.StdinOnce,
|
|
DetachKeys: keys,
|
|
}
|
|
container.StreamConfig.AttachStreams(&cfg)
|
|
|
|
inStream, outStream, errStream, err := c.GetStreams()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer inStream.Close()
|
|
|
|
if !container.Config.Tty && c.MuxStreams {
|
|
errStream = stdcopy.NewStdWriter(errStream, stdcopy.Stderr)
|
|
outStream = stdcopy.NewStdWriter(outStream, stdcopy.Stdout)
|
|
}
|
|
|
|
if cfg.UseStdin {
|
|
cfg.Stdin = inStream
|
|
}
|
|
if cfg.UseStdout {
|
|
cfg.Stdout = outStream
|
|
}
|
|
if cfg.UseStderr {
|
|
cfg.Stderr = errStream
|
|
}
|
|
|
|
if err := daemon.containerAttach(container, &cfg, c.Logs, c.Stream); err != nil {
|
|
fmt.Fprintf(outStream, "Error attaching: %s\n", err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// ContainerAttachRaw attaches the provided streams to the container's stdio
|
|
func (daemon *Daemon) ContainerAttachRaw(prefixOrName string, stdin io.ReadCloser, stdout, stderr io.Writer, doStream bool, attached chan struct{}) error {
|
|
container, err := daemon.GetContainer(prefixOrName)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
cfg := stream.AttachConfig{
|
|
UseStdin: stdin != nil,
|
|
UseStdout: stdout != nil,
|
|
UseStderr: stderr != nil,
|
|
TTY: container.Config.Tty,
|
|
CloseStdin: container.Config.StdinOnce,
|
|
}
|
|
container.StreamConfig.AttachStreams(&cfg)
|
|
close(attached)
|
|
if cfg.UseStdin {
|
|
cfg.Stdin = stdin
|
|
}
|
|
if cfg.UseStdout {
|
|
cfg.Stdout = stdout
|
|
}
|
|
if cfg.UseStderr {
|
|
cfg.Stderr = stderr
|
|
}
|
|
|
|
return daemon.containerAttach(container, &cfg, false, doStream)
|
|
}
|
|
|
|
func (daemon *Daemon) containerAttach(c *container.Container, cfg *stream.AttachConfig, logs, doStream bool) error {
|
|
if logs {
|
|
logDriver, logCreated, err := daemon.getLogger(c)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if logCreated {
|
|
defer func() {
|
|
if err = logDriver.Close(); err != nil {
|
|
logrus.Errorf("Error closing logger: %v", err)
|
|
}
|
|
}()
|
|
}
|
|
cLog, ok := logDriver.(logger.LogReader)
|
|
if !ok {
|
|
return logger.ErrReadLogsNotSupported{}
|
|
}
|
|
logs := cLog.ReadLogs(logger.ReadConfig{Tail: -1})
|
|
defer logs.ConsumerGone()
|
|
|
|
LogLoop:
|
|
for {
|
|
select {
|
|
case msg, ok := <-logs.Msg:
|
|
if !ok {
|
|
break LogLoop
|
|
}
|
|
if msg.Source == "stdout" && cfg.Stdout != nil {
|
|
cfg.Stdout.Write(msg.Line)
|
|
}
|
|
if msg.Source == "stderr" && cfg.Stderr != nil {
|
|
cfg.Stderr.Write(msg.Line)
|
|
}
|
|
case err := <-logs.Err:
|
|
logrus.Errorf("Error streaming logs: %v", err)
|
|
break LogLoop
|
|
}
|
|
}
|
|
}
|
|
|
|
daemon.LogContainerEvent(c, "attach")
|
|
|
|
if !doStream {
|
|
return nil
|
|
}
|
|
|
|
if cfg.Stdin != nil {
|
|
r, w := io.Pipe()
|
|
go func(stdin io.ReadCloser) {
|
|
defer w.Close()
|
|
defer logrus.Debug("Closing buffered stdin pipe")
|
|
io.Copy(w, stdin)
|
|
}(cfg.Stdin)
|
|
cfg.Stdin = r
|
|
}
|
|
|
|
if !c.Config.OpenStdin {
|
|
cfg.Stdin = nil
|
|
}
|
|
|
|
if c.Config.StdinOnce && !c.Config.Tty {
|
|
// Wait for the container to stop before returning.
|
|
waitChan := c.Wait(context.Background(), container.WaitConditionNotRunning)
|
|
defer func() {
|
|
<-waitChan // Ignore returned exit code.
|
|
}()
|
|
}
|
|
|
|
ctx := c.InitAttachContext()
|
|
err := <-c.StreamConfig.CopyStreams(ctx, cfg)
|
|
if err != nil {
|
|
if _, ok := errors.Cause(err).(term.EscapeError); ok || err == context.Canceled {
|
|
daemon.LogContainerEvent(c, "detach")
|
|
} else {
|
|
logrus.Errorf("attach failed with error: %v", err)
|
|
}
|
|
}
|
|
|
|
return nil
|
|
}
|