container/container.go
4f0d95fa
 package container // import "github.com/docker/docker/container"
a27b4b8c
 
 import (
a43be343
 	"bytes"
7d62e40f
 	"context"
a27b4b8c
 	"encoding/json"
7c57a4cf
 	"fmt"
46e05ed2
 	"io"
 	"os"
0fb507dc
 	"path/filepath"
f97fbba5
 	"runtime"
e8026d8a
 	"strings"
e2acca67
 	"sync"
46e05ed2
 	"syscall"
 	"time"
 
aa3ce07c
 	"github.com/containerd/containerd/cio"
91e197d6
 	containertypes "github.com/docker/docker/api/types/container"
fc7b904d
 	mounttypes "github.com/docker/docker/api/types/mount"
bebd472e
 	swarmtypes "github.com/docker/docker/api/types/swarm"
5ea75bb6
 	"github.com/docker/docker/container/stream"
9ca2e4e8
 	"github.com/docker/docker/daemon/exec"
47a6afb9
 	"github.com/docker/docker/daemon/logger"
 	"github.com/docker/docker/daemon/logger/jsonfilelog"
a351b38e
 	"github.com/docker/docker/daemon/logger/local"
e2ceb83a
 	"github.com/docker/docker/daemon/logger/loggerutils/cache"
53582321
 	"github.com/docker/docker/daemon/network"
a351b38e
 	"github.com/docker/docker/errdefs"
4352da78
 	"github.com/docker/docker/image"
 	"github.com/docker/docker/layer"
7a7357da
 	"github.com/docker/docker/pkg/containerfs"
799a6b94
 	"github.com/docker/docker/pkg/idtools"
ea3cbd32
 	"github.com/docker/docker/pkg/ioutils"
0e50d946
 	"github.com/docker/docker/pkg/signal"
f1545882
 	"github.com/docker/docker/pkg/system"
9c4570a9
 	"github.com/docker/docker/restartmanager"
81fa9feb
 	"github.com/docker/docker/volume"
6a70fd22
 	volumemounts "github.com/docker/docker/volume/mounts"
07ff4f1d
 	units "github.com/docker/go-units"
bebd472e
 	agentexec "github.com/docker/swarmkit/agent/exec"
dc3c382b
 	"github.com/moby/sys/symlink"
ebcb7d6b
 	"github.com/pkg/errors"
1009e6a4
 	"github.com/sirupsen/logrus"
a27b4b8c
 )
 
4352da78
 const configFileName = "config.v2.json"
 
ddae20c0
 // ExitStatus provides exit reasons for a container.
 type ExitStatus struct {
 	// The exit code with which the container exited.
 	ExitCode int
 
 	// Whether the container encountered an OOM.
 	OOMKilled bool
 
 	// Time at which the container died
 	ExitedAt time.Time
 }
 
55f8828e
 // Container holds the structure defining a container object.
 type Container struct {
5ea75bb6
 	StreamConfig *stream.Config
abd72d40
 	// embed for Container to support states directly.
7a7357da
 	*State          `json:"State"`          // Needed for Engine API version <= 1.11
 	Root            string                  `json:"-"` // Path to the "home" of the container, including metadata.
 	BaseFS          containerfs.ContainerFS `json:"-"` // interface containing graphdriver mount
 	RWLayer         layer.RWLayer           `json:"-"`
abd72d40
 	ID              string
 	Created         time.Time
534a90a9
 	Managed         bool
abd72d40
 	Path            string
 	Args            []string
7ac4232e
 	Config          *containertypes.Config
4352da78
 	ImageID         image.ID `json:"Image"`
abd72d40
 	NetworkSettings *network.Settings
 	LogPath         string
 	Name            string
 	Driver          string
0380fbff
 	OS              string
abd72d40
 	// MountLabel contains the options for the 'mount' command
 	MountLabel             string
 	ProcessLabel           string
 	RestartCount           int
 	HasBeenStartedBefore   bool
 	HasBeenManuallyStopped bool // used for unless-stopped restart policy
6a70fd22
 	MountPoints            map[string]*volumemounts.MountPoint
bebd472e
 	HostConfig             *containertypes.HostConfig `json:"-"` // do not serialize the host config in the json, otherwise we'll make the container unportable
 	ExecCommands           *exec.Store                `json:"-"`
9e9fc7b5
 	DependencyStore        agentexec.DependencyGetter `json:"-"`
bebd472e
 	SecretReferences       []*swarmtypes.SecretReference
c0217180
 	ConfigReferences       []*swarmtypes.ConfigReference
47a6afb9
 	// logDriver for closing
9c4570a9
 	LogDriver      logger.Logger  `json:"-"`
 	LogCopier      *logger.Copier `json:"-"`
 	restartManager restartmanager.RestartManager
 	attachContext  *attachContext
55f8828e
 
 	// Fields here are specific to Unix platforms
 	AppArmorProfile string
 	HostnamePath    string
 	HostsPath       string
 	ShmPath         string
 	ResolvConfPath  string
 	SeccompProfile  string
 	NoNewPrivileges bool
 
 	// Fields here are specific to Windows
e2ceb83a
 	NetworkSharedContainerID string            `json:"-"`
 	SharedEndpointList       []string          `json:"-"`
 	LocalLogCacheMeta        localLogCacheMeta `json:",omitempty"`
 }
 
 type localLogCacheMeta struct {
 	HaveNotifyEnabled bool
a27b4b8c
 }
 
6bb0d181
 // NewBaseContainer creates a new container with its
060f4ae6
 // basic configuration.
6bb0d181
 func NewBaseContainer(id, root string) *Container {
060f4ae6
 	return &Container{
55f8828e
 		ID:            id,
 		State:         NewState(),
 		ExecCommands:  exec.NewStore(),
 		Root:          root,
6a70fd22
 		MountPoints:   make(map[string]*volumemounts.MountPoint),
55f8828e
 		StreamConfig:  stream.NewConfig(),
 		attachContext: &attachContext{},
060f4ae6
 	}
 }
 
6bb0d181
 // FromDisk loads the container configuration stored in the host.
 func (container *Container) FromDisk() error {
 	pth, err := container.ConfigPath()
5c069940
 	if err != nil {
 		return err
 	}
 
4bc28f4e
 	jsonSource, err := os.Open(pth)
11b65a00
 	if err != nil {
 		return err
 	}
4bc28f4e
 	defer jsonSource.Close()
 
 	dec := json.NewDecoder(jsonSource)
 
7c57a4cf
 	// Load container settings
137c12f1
 	if err := dec.Decode(container); err != nil {
11b65a00
 		return err
 	}
46e05ed2
 
0380fbff
 	// Ensure the operating system is set if blank. Assume it is the OS of the
 	// host OS if not, to ensure containers created before multiple-OS
f97fbba5
 	// support are migrated
0380fbff
 	if container.OS == "" {
 		container.OS = runtime.GOOS
f97fbba5
 	}
 
31638ab2
 	return container.readHostConfig()
11b65a00
 }
 
a43be343
 // toDisk saves the container configuration on disk and returns a deep copy.
 func (container *Container) toDisk() (*Container, error) {
 	var (
 		buf      bytes.Buffer
 		deepCopy Container
 	)
6bb0d181
 	pth, err := container.ConfigPath()
a27b4b8c
 	if err != nil {
a43be343
 		return nil, err
a27b4b8c
 	}
5c069940
 
a43be343
 	// Save container settings
ae52cea3
 	f, err := ioutils.NewAtomicFileWriter(pth, 0600)
31638ab2
 	if err != nil {
a43be343
 		return nil, err
5c069940
 	}
a43be343
 	defer f.Close()
cf02b369
 
a43be343
 	w := io.MultiWriter(&buf, f)
 	if err := json.NewEncoder(w).Encode(container); err != nil {
 		return nil, err
 	}
5c069940
 
a43be343
 	if err := json.NewDecoder(&buf).Decode(&deepCopy); err != nil {
 		return nil, err
 	}
 	deepCopy.HostConfig, err = container.WriteHostConfig()
 	if err != nil {
 		return nil, err
31638ab2
 	}
5c069940
 
a43be343
 	return &deepCopy, nil
a27b4b8c
 }
 
edad5270
 // CheckpointTo makes the Container's current state visible to queries, and persists state.
aacddda8
 // Callers must hold a Container lock.
 func (container *Container) CheckpointTo(store ViewDB) error {
a43be343
 	deepCopy, err := container.toDisk()
 	if err != nil {
aacddda8
 		return err
 	}
a43be343
 	return store.Save(deepCopy)
aacddda8
 }
 
6bb0d181
 // readHostConfig reads the host configuration from disk for the container.
31638ab2
 func (container *Container) readHostConfig() error {
7ac4232e
 	container.HostConfig = &containertypes.HostConfig{}
31638ab2
 	// If the hostconfig file does not exist, do not read it.
6bb0d181
 	// (We still have to initialize container.HostConfig,
31638ab2
 	// but that's OK, since we just did that above.)
6bb0d181
 	pth, err := container.HostConfigPath()
5c069940
 	if err != nil {
 		return err
 	}
 
a3c4801c
 	f, err := os.Open(pth)
06b53e3f
 	if err != nil {
36a69bbc
 		if os.IsNotExist(err) {
 			return nil
 		}
31638ab2
 		return err
06b53e3f
 	}
a3c4801c
 	defer f.Close()
 
6bb0d181
 	if err := json.NewDecoder(f).Decode(&container.HostConfig); err != nil {
f1a74a89
 		return err
 	}
 
6bb0d181
 	container.InitDNSHostConfig()
f1a74a89
 
 	return nil
06b53e3f
 }
 
a43be343
 // WriteHostConfig saves the host configuration on disk for the container,
 // and returns a deep copy of the saved object. Callers must hold a Container lock.
 func (container *Container) WriteHostConfig() (*containertypes.HostConfig, error) {
 	var (
 		buf      bytes.Buffer
 		deepCopy containertypes.HostConfig
 	)
 
6bb0d181
 	pth, err := container.HostConfigPath()
06b53e3f
 	if err != nil {
a43be343
 		return nil, err
06b53e3f
 	}
5c069940
 
3ec8fed7
 	f, err := ioutils.NewAtomicFileWriter(pth, 0644)
5c069940
 	if err != nil {
a43be343
 		return nil, err
5c069940
 	}
cf1a6c08
 	defer f.Close()
5c069940
 
a43be343
 	w := io.MultiWriter(&buf, f)
 	if err := json.NewEncoder(w).Encode(&container.HostConfig); err != nil {
 		return nil, err
 	}
 
 	if err := json.NewDecoder(&buf).Decode(&deepCopy); err != nil {
 		return nil, err
 	}
 	return &deepCopy, nil
06b53e3f
 }
 
67912303
 // SetupWorkingDirectory sets up the container's working directory as set in container.Config.WorkingDir
763d8392
 func (container *Container) SetupWorkingDirectory(rootIdentity idtools.Identity) error {
89884487
 	// TODO: LCOW Support. This will need revisiting.
9fa44906
 	// We will need to do remote filesystem operations here.
0380fbff
 	if container.OS != runtime.GOOS {
9fa44906
 		return nil
 	}
 
67912303
 	if container.Config.WorkingDir == "" {
 		return nil
 	}
5849a553
 
6952135f
 	container.Config.WorkingDir = filepath.Clean(container.Config.WorkingDir)
67912303
 	pth, err := container.GetResourcePath(container.Config.WorkingDir)
 	if err != nil {
 		return err
 	}
 
763d8392
 	if err := idtools.MkdirAllAndChownNew(pth, 0755, rootIdentity); err != nil {
67912303
 		pthInfo, err2 := os.Stat(pth)
 		if err2 == nil && pthInfo != nil && !pthInfo.IsDir() {
ebcb7d6b
 			return errors.Errorf("Cannot mkdir: %s is not a directory", container.Config.WorkingDir)
67912303
 		}
 
 		return err
 	}
 
 	return nil
 }
 
6bb0d181
 // GetResourcePath evaluates `path` in the scope of the container's BaseFS, with proper path
 // sanitisation. Symlinks are all scoped to the BaseFS of the container, as
 // though the container's BaseFS was `/`.
4377ebd6
 //
6bb0d181
 // The BaseFS of a container is the host-facing path which is bind-mounted as
4377ebd6
 // `/` inside the container. This method is essentially used to access a
 // particular path inside the container as though you were a process in that
 // container.
 //
6bb0d181
 // NOTE: The returned path is *only* safely scoped inside the container's BaseFS
4377ebd6
 //       if no component of the returned path changes (such as a component
 //       symlinking to a different path) between using this method and using the
 //       path. See symlink.FollowSymlinkInScope for more details.
 func (container *Container) GetResourcePath(path string) (string, error) {
d6ea46ce
 	if container.BaseFS == nil {
 		return "", errors.New("GetResourcePath: BaseFS of container " + container.ID + " is unexpectedly nil")
 	}
3c177dc8
 	// IMPORTANT - These are paths on the OS where the daemon is running, hence
 	// any filepath operations must be done in an OS agnostic way.
7a7357da
 	r, e := container.BaseFS.ResolveScopedPath(path, false)
04338010
 
 	// Log this here on the daemon side as there's otherwise no indication apart
 	// from the error being propagated all the way back to the client. This makes
 	// debugging significantly easier and clearly indicates the error comes from the daemon.
 	if e != nil {
7a7357da
 		logrus.Errorf("Failed to ResolveScopedPath BaseFS %s path %s %s\n", container.BaseFS.Path(), path, e)
04338010
 	}
3c177dc8
 	return r, e
0fb507dc
 }
 
6bb0d181
 // GetRootResourcePath evaluates `path` in the scope of the container's root, with proper path
4377ebd6
 // sanitisation. Symlinks are all scoped to the root of the container, as
 // though the container's root was `/`.
 //
 // The root of a container is the host-facing configuration metadata directory.
 // Only use this method to safely access the container's `container.json` or
 // other metadata files. If in doubt, use container.GetResourcePath.
 //
 // NOTE: The returned path is *only* safely scoped inside the container's root
 //       if no component of the returned path changes (such as a component
 //       symlinking to a different path) between using this method and using the
 //       path. See symlink.FollowSymlinkInScope for more details.
6bb0d181
 func (container *Container) GetRootResourcePath(path string) (string, error) {
3c177dc8
 	// IMPORTANT - These are paths on the OS where the daemon is running, hence
 	// any filepath operations must be done in an OS agnostic way.
 	cleanPath := filepath.Join(string(os.PathSeparator), path)
6bb0d181
 	return symlink.FollowSymlinkInScope(filepath.Join(container.Root, cleanPath), container.Root)
0fb507dc
 }
 
4f2a5ba3
 // ExitOnNext signals to the monitor that it should not restart the container
 // after we send the kill signal.
 func (container *Container) ExitOnNext() {
606a245d
 	container.RestartManager().Cancel()
70d2123e
 }
 
6bb0d181
 // HostConfigPath returns the path to the container's JSON hostconfig
 func (container *Container) HostConfigPath() (string, error) {
 	return container.GetRootResourcePath("hostconfig.json")
7c57a4cf
 }
 
6bb0d181
 // ConfigPath returns the path to the container's JSON config
 func (container *Container) ConfigPath() (string, error) {
 	return container.GetRootResourcePath(configFileName)
7c57a4cf
 }
 
d8fef66b
 // CheckpointDir returns the directory checkpoints are stored in
 func (container *Container) CheckpointDir() string {
 	return filepath.Join(container.Root, "checkpoints")
 }
 
c412300d
 // StartLogger starts a new logger driver for the container.
58028a29
 func (container *Container) StartLogger() (logger.Logger, error) {
 	cfg := container.HostConfig.LogConfig
054abff3
 	initDriver, err := logger.GetLogDriver(cfg.Type)
3a8728b4
 	if err != nil {
ebcb7d6b
 		return nil, errors.Wrap(err, "failed to get logging factory")
3a8728b4
 	}
17ec911d
 	info := logger.Info{
96d06e10
 		Config:              cfg.Config,
 		ContainerID:         container.ID,
 		ContainerName:       container.Name,
 		ContainerEntrypoint: container.Path,
 		ContainerArgs:       container.Args,
4352da78
 		ContainerImageID:    container.ImageID.String(),
96d06e10
 		ContainerImageName:  container.Config.Image,
 		ContainerCreated:    container.Created,
656cdbb0
 		ContainerEnv:        container.Config.Env,
 		ContainerLabels:     container.Config.Labels,
38c49d99
 		DaemonName:          "docker",
3a8728b4
 	}
 
 	// Set logging file for "json-logger"
a351b38e
 	// TODO(@cpuguy83): Setup here based on log driver is a little weird.
 	switch cfg.Type {
 	case jsonfilelog.Name:
17ec911d
 		info.LogPath, err = container.GetRootResourcePath(fmt.Sprintf("%s-json.log", container.ID))
364287b7
 		if err != nil {
3a8728b4
 			return nil, err
364287b7
 		}
20ca612a
 
 		container.LogPath = info.LogPath
a351b38e
 	case local.Name:
 		// Do not set container.LogPath for the local driver
 		// This would expose the value to the API, which should not be done as it means
 		// that the log file implementation would become a stable API that cannot change.
 		logDir, err := container.GetRootResourcePath("local-logs")
 		if err != nil {
 			return nil, err
 		}
 		if err := os.MkdirAll(logDir, 0700); err != nil {
 			return nil, errdefs.System(errors.Wrap(err, "error creating local logs dir"))
 		}
 		info.LogPath = filepath.Join(logDir, "container.log")
3a8728b4
 	}
054abff3
 
 	l, err := initDriver(info)
 	if err != nil {
 		return nil, err
 	}
 
 	if containertypes.LogMode(cfg.Config["mode"]) == containertypes.LogModeNonBlock {
 		bufferSize := int64(-1)
 		if s, exists := cfg.Config["max-buffer-size"]; exists {
 			bufferSize, err = units.RAMInBytes(s)
 			if err != nil {
 				return nil, err
 			}
 		}
 		l = logger.NewRingLogger(l, info, bufferSize)
 	}
e2ceb83a
 
 	if _, ok := l.(logger.LogReader); !ok {
750f0d16
 		if cache.ShouldUseCache(cfg.Config) {
 			logPath, err := container.GetRootResourcePath("container-cached.log")
 			if err != nil {
 				return nil, err
 			}
e2ceb83a
 
750f0d16
 			if !container.LocalLogCacheMeta.HaveNotifyEnabled {
 				logrus.WithField("container", container.ID).WithField("driver", container.HostConfig.LogConfig.Type).Info("Configured log driver does not support reads, enabling local file cache for container logs")
 				container.LocalLogCacheMeta.HaveNotifyEnabled = true
 			}
 			info.LogPath = logPath
 			l, err = cache.WithLocalCache(l, info)
 			if err != nil {
 				return nil, errors.Wrap(err, "error setting up local container log cache")
 			}
e2ceb83a
 		}
 	}
054abff3
 	return l, nil
3a8728b4
 }
 
6bb0d181
 // GetProcessLabel returns the process label for the container.
 func (container *Container) GetProcessLabel() string {
1a5ffef6
 	// even if we have a process label return "" if we are running
 	// in privileged mode
6bb0d181
 	if container.HostConfig.Privileged {
1a5ffef6
 		return ""
 	}
 	return container.ProcessLabel
 }
 
6bb0d181
 // GetMountLabel returns the mounting label for the container.
 // This label is empty if the container is privileged.
 func (container *Container) GetMountLabel() string {
1a5ffef6
 	return container.MountLabel
 }
0b187b90
 
6bb0d181
 // GetExecIDs returns the list of exec commands running on the container.
 func (container *Container) GetExecIDs() []string {
 	return container.ExecCommands.List()
1be7a10b
 }
 
6bb0d181
 // ShouldRestart decides whether the daemon should restart the container or not.
 // This is based on the container's restart policy.
 func (container *Container) ShouldRestart() bool {
606a245d
 	shouldRestart, _, _ := container.RestartManager().ShouldRestart(uint32(container.ExitCode()), container.HasBeenManuallyStopped, container.FinishedAt.Sub(container.StartedAt))
51e42e6e
 	return shouldRestart
81fa9feb
 }
d592778f
 
6bb0d181
 // AddMountPointWithVolume adds a new mount point configured with a volume to the container.
 func (container *Container) AddMountPointWithVolume(destination string, vol volume.Volume, rw bool) {
0380fbff
 	operatingSystem := container.OS
e89b6e8c
 	if operatingSystem == "" {
 		operatingSystem = runtime.GOOS
 	}
6a70fd22
 	volumeParser := volumemounts.NewParser(operatingSystem)
 	container.MountPoints[destination] = &volumemounts.MountPoint{
fc7b904d
 		Type:        mounttypes.TypeVolume,
a7e686a7
 		Name:        vol.Name(),
 		Driver:      vol.DriverName(),
 		Destination: destination,
 		RW:          rw,
 		Volume:      vol,
e89b6e8c
 		CopyData:    volumeParser.DefaultCopyMode(),
a7e686a7
 	}
 }
 
9a2d0bc3
 // UnmountVolumes unmounts all volumes
 func (container *Container) UnmountVolumes(volumeEventLog func(name, action string, attributes map[string]string)) error {
 	var errors []string
 	for _, volumeMount := range container.MountPoints {
df0d317a
 		if volumeMount.Volume == nil {
 			continue
 		}
9a2d0bc3
 
df0d317a
 		if err := volumeMount.Cleanup(); err != nil {
 			errors = append(errors, err.Error())
 			continue
 		}
 
 		attributes := map[string]string{
 			"driver":    volumeMount.Volume.DriverName(),
 			"container": container.ID,
9a2d0bc3
 		}
df0d317a
 		volumeEventLog(volumeMount.Volume.Name(), "unmount", attributes)
9a2d0bc3
 	}
 	if len(errors) > 0 {
 		return fmt.Errorf("error while unmounting volumes for container %s: %s", container.ID, strings.Join(errors, "; "))
 	}
 	return nil
 }
 
927b334e
 // IsDestinationMounted checks whether a path is mounted on the container or not.
6bb0d181
 func (container *Container) IsDestinationMounted(destination string) bool {
a7e686a7
 	return container.MountPoints[destination] != nil
d592778f
 }
0e50d946
 
6bb0d181
 // StopSignal returns the signal used to stop the container.
 func (container *Container) StopSignal() int {
0e50d946
 	var stopSignal syscall.Signal
 	if container.Config.StopSignal != "" {
 		stopSignal, _ = signal.ParseSignal(container.Config.StopSignal)
 	}
 
 	if int(stopSignal) == 0 {
 		stopSignal, _ = signal.ParseSignal(signal.DefaultStopSignal)
 	}
 	return int(stopSignal)
 }
d7117a1b
 
e66d2108
 // StopTimeout returns the timeout (in seconds) used to stop the container.
 func (container *Container) StopTimeout() int {
 	if container.Config.StopTimeout != nil {
 		return *container.Config.StopTimeout
 	}
cc703784
 	return DefaultStopTimeout
e66d2108
 }
 
6bb0d181
 // InitDNSHostConfig ensures that the dns fields are never nil.
d7117a1b
 // New containers don't ever have those fields nil,
 // but pre created containers can still have those nil values.
 // The non-recommended host configuration in the start api can
 // make these fields nil again, this corrects that issue until
 // we remove that behavior for good.
 // See https://github.com/docker/docker/pull/17779
 // for a more detailed explanation on why we don't want that.
6bb0d181
 func (container *Container) InitDNSHostConfig() {
464eefd7
 	container.Lock()
 	defer container.Unlock()
6bb0d181
 	if container.HostConfig.DNS == nil {
 		container.HostConfig.DNS = make([]string, 0)
d7117a1b
 	}
 
6bb0d181
 	if container.HostConfig.DNSSearch == nil {
 		container.HostConfig.DNSSearch = make([]string, 0)
d7117a1b
 	}
 
6bb0d181
 	if container.HostConfig.DNSOptions == nil {
 		container.HostConfig.DNSOptions = make([]string, 0)
d7117a1b
 	}
 }
ff3ea4c9
 
 // UpdateMonitor updates monitor configure for running container
 func (container *Container) UpdateMonitor(restartPolicy containertypes.RestartPolicy) {
9c4570a9
 	type policySetter interface {
 		SetPolicy(containertypes.RestartPolicy)
 	}
 
606a245d
 	if rm, ok := container.RestartManager().(policySetter); ok {
9c4570a9
 		rm.SetPolicy(restartPolicy)
 	}
 }
 
 // FullHostname returns hostname and optional domain appended to it.
 func (container *Container) FullHostname() string {
 	fullHostname := container.Config.Hostname
 	if container.Config.Domainname != "" {
 		fullHostname = fmt.Sprintf("%s.%s", fullHostname, container.Config.Domainname)
ff3ea4c9
 	}
9c4570a9
 	return fullHostname
 }
ff3ea4c9
 
d0344731
 // RestartManager returns the current restartmanager instance connected to container.
606a245d
 func (container *Container) RestartManager() restartmanager.RestartManager {
9c4570a9
 	if container.restartManager == nil {
51e42e6e
 		container.restartManager = restartmanager.New(container.HostConfig.RestartPolicy, container.RestartCount)
ff3ea4c9
 	}
9c4570a9
 	return container.restartManager
ff3ea4c9
 }
7bb815e2
 
606a245d
 // ResetRestartManager initializes new restartmanager based on container config
 func (container *Container) ResetRestartManager(resetCount bool) {
 	if container.restartManager != nil {
 		container.restartManager.Cancel()
 	}
 	if resetCount {
 		container.RestartCount = 0
 	}
 	container.restartManager = nil
 }
 
7bb815e2
 type attachContext struct {
 	ctx    context.Context
 	cancel context.CancelFunc
 	mu     sync.Mutex
 }
 
9279a93f
 // InitAttachContext initializes or returns existing context for attach calls to
7bb815e2
 // track container liveness.
 func (container *Container) InitAttachContext() context.Context {
 	container.attachContext.mu.Lock()
 	defer container.attachContext.mu.Unlock()
 	if container.attachContext.ctx == nil {
 		container.attachContext.ctx, container.attachContext.cancel = context.WithCancel(context.Background())
 	}
 	return container.attachContext.ctx
 }
 
9279a93f
 // CancelAttachContext cancels attach context. All attach calls should detach
7bb815e2
 // after this call.
 func (container *Container) CancelAttachContext() {
 	container.attachContext.mu.Lock()
 	if container.attachContext.ctx != nil {
 		container.attachContext.cancel()
 		container.attachContext.ctx = nil
 	}
 	container.attachContext.mu.Unlock()
 }
37a3be24
 
 func (container *Container) startLogging() error {
 	if container.HostConfig.LogConfig.Type == "none" {
 		return nil // do not start logging routines
 	}
 
58028a29
 	l, err := container.StartLogger()
37a3be24
 	if err != nil {
58028a29
 		return fmt.Errorf("failed to initialize logging driver: %v", err)
37a3be24
 	}
 
 	copier := logger.NewCopier(map[string]io.Reader{"stdout": container.StdoutPipe(), "stderr": container.StderrPipe()}, l)
 	container.LogCopier = copier
 	copier.Run()
 	container.LogDriver = l
 
 	return nil
 }
 
5ea75bb6
 // StdinPipe gets the stdin stream of the container
 func (container *Container) StdinPipe() io.WriteCloser {
 	return container.StreamConfig.StdinPipe()
 }
 
 // StdoutPipe gets the stdout stream of the container
 func (container *Container) StdoutPipe() io.ReadCloser {
 	return container.StreamConfig.StdoutPipe()
 }
 
 // StderrPipe gets the stderr stream of the container
 func (container *Container) StderrPipe() io.ReadCloser {
 	return container.StreamConfig.StderrPipe()
 }
 
 // CloseStreams closes the container's stdio streams
 func (container *Container) CloseStreams() error {
 	return container.StreamConfig.CloseStreams()
 }
 
37a3be24
 // InitializeStdio is called by libcontainerd to connect the stdio.
3fec7c08
 func (container *Container) InitializeStdio(iop *cio.DirectIO) (cio.IO, error) {
37a3be24
 	if err := container.startLogging(); err != nil {
 		container.Reset(false)
ddae20c0
 		return nil, err
37a3be24
 	}
 
 	container.StreamConfig.CopyToPipe(iop)
 
5ea75bb6
 	if container.StreamConfig.Stdin() == nil && !container.Config.Tty {
37a3be24
 		if iop.Stdin != nil {
 			if err := iop.Stdin.Close(); err != nil {
aa01ee4a
 				logrus.Warnf("error closing stdin: %+v", err)
37a3be24
 			}
 		}
 	}
 
aa3ce07c
 	return &rio{IO: iop, sc: container.StreamConfig}, nil
37a3be24
 }
67d282a5
 
eaa51928
 // MountsResourcePath returns the path where mounts are stored for the given mount
 func (container *Container) MountsResourcePath(mount string) (string, error) {
 	return container.GetRootResourcePath(filepath.Join("mounts", mount))
 }
 
67d282a5
 // SecretMountPath returns the path of the secret mount for the container
eaa51928
 func (container *Container) SecretMountPath() (string, error) {
 	return container.MountsResourcePath("secrets")
67d282a5
 }
 
37ce91dd
 // SecretFilePath returns the path to the location of a secret on the host.
eaa51928
 func (container *Container) SecretFilePath(secretRef swarmtypes.SecretReference) (string, error) {
 	secrets, err := container.SecretMountPath()
 	if err != nil {
 		return "", err
 	}
 	return filepath.Join(secrets, secretRef.SecretID), nil
67d282a5
 }
 
 func getSecretTargetPath(r *swarmtypes.SecretReference) string {
 	if filepath.IsAbs(r.File.Name) {
 		return r.File.Name
 	}
 
 	return filepath.Join(containerSecretMountPath, r.File.Name)
 }
9e9fc7b5
 
f1545882
 // CreateDaemonEnvironment creates a new environment variable slice for this container.
 func (container *Container) CreateDaemonEnvironment(tty bool, linkedEnv []string) []string {
 	// Setup environment
0380fbff
 	os := container.OS
 	if os == "" {
 		os = runtime.GOOS
f1545882
 	}
5702a89d
 
 	// Figure out what size slice we need so we can allocate this all at once.
 	envSize := len(container.Config.Env)
0380fbff
 	if runtime.GOOS != "windows" || (runtime.GOOS == "windows" && os == "linux") {
5702a89d
 		envSize += 2 + len(linkedEnv)
 	}
 	if tty {
 		envSize++
 	}
 
 	env := make([]string, 0, envSize)
 	if runtime.GOOS != "windows" || (runtime.GOOS == "windows" && os == "linux") {
 		env = append(env, "PATH="+system.DefaultPathEnv(os))
 		env = append(env, "HOSTNAME="+container.Config.Hostname)
f1545882
 		if tty {
 			env = append(env, "TERM=xterm")
 		}
 		env = append(env, linkedEnv...)
 	}
 
 	// because the env on the container can override certain default values
 	// we need to replace the 'env' keys where they match and append anything
 	// else.
4ec9766a
 	env = ReplaceOrAppendEnvValues(env, container.Config.Env)
 	return env
f1545882
 }
ddae20c0
 
aa3ce07c
 type rio struct {
 	cio.IO
ddae20c0
 
 	sc *stream.Config
 }
 
aa3ce07c
 func (i *rio) Close() error {
ddae20c0
 	i.IO.Close()
 
 	return i.sc.CloseStreams()
 }
 
aa3ce07c
 func (i *rio) Wait() {
b5f28865
 	i.sc.Wait(context.Background())
ddae20c0
 
 	i.IO.Wait()
 }