docker: Index | Files | Directories

package container

import ""


Package Files

archive.go container.go container_unix.go env.go health.go history.go memory_store.go monitor.go mounts_unix.go state.go store.go view.go


const (
    // DefaultStopTimeout sets the default time, in seconds, to wait
    // for the graceful container stop before forcefully terminating it.
    DefaultStopTimeout = 10


var (
    // ErrNameReserved is an error which is returned when a name is requested to be reserved that already is reserved
    ErrNameReserved = errors.New("name is reserved")
    // ErrNameNotReserved is an error which is returned when trying to find a name that is not reserved
    ErrNameNotReserved = errors.New("name is not reserved")

func IsValidHealthString Uses

func IsValidHealthString(s string) bool

IsValidHealthString checks if the provided string is a valid container health status or not.

func IsValidStateString Uses

func IsValidStateString(s string) bool

IsValidStateString checks if the provided string is a valid container state or not.

func ReplaceOrAppendEnvValues Uses

func ReplaceOrAppendEnvValues(defaults, overrides []string) []string

ReplaceOrAppendEnvValues returns the defaults with the overrides either replaced by env key or appended to the list

type Container Uses

type Container struct {
    StreamConfig *stream.Config
    // embed for Container to support states directly.
    *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:"-"`
    ID              string
    Created         time.Time
    Managed         bool
    Path            string
    Args            []string
    Config          *containertypes.Config
    ImageID         image.ID `json:"Image"`
    NetworkSettings *network.Settings
    LogPath         string
    Name            string
    Driver          string
    OS              string
    // MountLabel contains the options for the 'mount' command
    MountLabel             string
    ProcessLabel           string
    RestartCount           int
    HasBeenStartedBefore   bool
    HasBeenManuallyStopped bool // used for unless-stopped restart policy
    MountPoints            map[string]*volumemounts.MountPoint
    HostConfig             *containertypes.HostConfig `json:"-"` // do not serialize the host config in the json, otherwise we'll make the container unportable
    ExecCommands           *exec.Store                `json:"-"`
    DependencyStore        agentexec.DependencyGetter `json:"-"`
    SecretReferences       []*swarmtypes.SecretReference
    ConfigReferences       []*swarmtypes.ConfigReference
    // logDriver for closing
    LogDriver logger.Logger  `json:"-"`
    LogCopier *logger.Copier `json:"-"`

    // 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
    NetworkSharedContainerID string            `json:"-"`
    SharedEndpointList       []string          `json:"-"`
    LocalLogCacheMeta        localLogCacheMeta `json:",omitempty"`
    // contains filtered or unexported fields

Container holds the structure defining a container object.

func NewBaseContainer Uses

func NewBaseContainer(id, root string) *Container

NewBaseContainer creates a new container with its basic configuration.

func (*Container) AddMountPointWithVolume Uses

func (container *Container) AddMountPointWithVolume(destination string, vol volume.Volume, rw bool)

AddMountPointWithVolume adds a new mount point configured with a volume to the container.

func (*Container) BuildHostnameFile Uses

func (container *Container) BuildHostnameFile() error

BuildHostnameFile writes the container's hostname file.

func (*Container) CancelAttachContext Uses

func (container *Container) CancelAttachContext()

CancelAttachContext cancels attach context. All attach calls should detach after this call.

func (*Container) CheckpointDir Uses

func (container *Container) CheckpointDir() string

CheckpointDir returns the directory checkpoints are stored in

func (*Container) CheckpointTo Uses

func (container *Container) CheckpointTo(store ViewDB) error

CheckpointTo makes the Container's current state visible to queries, and persists state. Callers must hold a Container lock.

func (*Container) CloseStreams Uses

func (container *Container) CloseStreams() error

CloseStreams closes the container's stdio streams

func (*Container) ConfigFilePath Uses

func (container *Container) ConfigFilePath(configRef swarmtypes.ConfigReference) (string, error)

ConfigFilePath returns the path to the on-disk location of a config. On unix, configs are always considered secret

func (*Container) ConfigPath Uses

func (container *Container) ConfigPath() (string, error)

ConfigPath returns the path to the container's JSON config

func (*Container) CopyImagePathContent Uses

func (container *Container) CopyImagePathContent(v volume.Volume, destination string) error

CopyImagePathContent copies files in destination to the volume.

func (*Container) CreateDaemonEnvironment Uses

func (container *Container) CreateDaemonEnvironment(tty bool, linkedEnv []string) []string

CreateDaemonEnvironment creates a new environment variable slice for this container.

func (*Container) DetachAndUnmount Uses

func (container *Container) DetachAndUnmount(volumeEventLog func(name, action string, attributes map[string]string)) error

DetachAndUnmount uses a detached mount on all mount destinations, then unmounts each volume normally. This is used from daemon/archive for `docker cp`

func (*Container) ExitOnNext Uses

func (container *Container) ExitOnNext()

ExitOnNext signals to the monitor that it should not restart the container after we send the kill signal.

func (*Container) FromDisk Uses

func (container *Container) FromDisk() error

FromDisk loads the container configuration stored in the host.

func (*Container) FullHostname Uses

func (container *Container) FullHostname() string

FullHostname returns hostname and optional domain appended to it.

func (*Container) GetExecIDs Uses

func (container *Container) GetExecIDs() []string

GetExecIDs returns the list of exec commands running on the container.

func (*Container) GetMountLabel Uses

func (container *Container) GetMountLabel() string

GetMountLabel returns the mounting label for the container. This label is empty if the container is privileged.

func (*Container) GetMountPoints Uses

func (container *Container) GetMountPoints() []types.MountPoint

GetMountPoints gives a platform specific transformation to types.MountPoint. Callers must hold a Container lock.

func (*Container) GetProcessLabel Uses

func (container *Container) GetProcessLabel() string

GetProcessLabel returns the process label for the container.

func (*Container) GetResourcePath Uses

func (container *Container) GetResourcePath(path string) (string, error)

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 `/`.

The BaseFS of a container is the host-facing path which is bind-mounted as `/` 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.

NOTE: The returned path is *only* safely scoped inside the container's BaseFS

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) GetRootResourcePath Uses

func (container *Container) GetRootResourcePath(path string) (string, error)

GetRootResourcePath evaluates `path` in the scope of the container's root, with proper path 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.

func (*Container) HasMountFor Uses

func (container *Container) HasMountFor(path string) bool

HasMountFor checks if path is a mountpoint

func (*Container) HostConfigPath Uses

func (container *Container) HostConfigPath() (string, error)

HostConfigPath returns the path to the container's JSON hostconfig

func (*Container) InitAttachContext Uses

func (container *Container) InitAttachContext() context.Context

InitAttachContext initializes or returns existing context for attach calls to track container liveness.

func (*Container) InitDNSHostConfig Uses

func (container *Container) InitDNSHostConfig()

InitDNSHostConfig ensures that the dns fields are never nil. 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 for a more detailed explanation on why we don't want that.

func (*Container) InitializeStdio Uses

func (container *Container) InitializeStdio(iop *cio.DirectIO) (cio.IO, error)

InitializeStdio is called by libcontainerd to connect the stdio.

func (*Container) IpcMounts Uses

func (container *Container) IpcMounts() []Mount

IpcMounts returns the list of IPC mounts

func (*Container) IsDestinationMounted Uses

func (container *Container) IsDestinationMounted(destination string) bool

IsDestinationMounted checks whether a path is mounted on the container or not.

func (*Container) MountsResourcePath Uses

func (container *Container) MountsResourcePath(mount string) (string, error)

MountsResourcePath returns the path where mounts are stored for the given mount

func (*Container) NetworkMounts Uses

func (container *Container) NetworkMounts() []Mount

NetworkMounts returns the list of network mounts.

func (*Container) Reset Uses

func (container *Container) Reset(lock bool)

Reset puts a container into a state where it can be restarted again.

func (*Container) ResetRestartManager Uses

func (container *Container) ResetRestartManager(resetCount bool)

ResetRestartManager initializes new restartmanager based on container config

func (*Container) ResolvePath Uses

func (container *Container) ResolvePath(path string) (resolvedPath, absPath string, err error)

ResolvePath resolves the given path in the container to a resource on the host. Returns a resolved path (absolute path to the resource on the host), the absolute path to the resource relative to the container's rootfs, and an error if the path points to outside the container's rootfs.

func (*Container) RestartManager Uses

func (container *Container) RestartManager() restartmanager.RestartManager

RestartManager returns the current restartmanager instance connected to container.

func (*Container) SecretFilePath Uses

func (container *Container) SecretFilePath(secretRef swarmtypes.SecretReference) (string, error)

SecretFilePath returns the path to the location of a secret on the host.

func (*Container) SecretMountPath Uses

func (container *Container) SecretMountPath() (string, error)

SecretMountPath returns the path of the secret mount for the container

func (*Container) SecretMounts Uses

func (container *Container) SecretMounts() ([]Mount, error)

SecretMounts returns the mounts for the secret path.

func (*Container) SetupWorkingDirectory Uses

func (container *Container) SetupWorkingDirectory(rootIdentity idtools.Identity) error

SetupWorkingDirectory sets up the container's working directory as set in container.Config.WorkingDir

func (*Container) ShmResourcePath Uses

func (container *Container) ShmResourcePath() (string, error)

ShmResourcePath returns path to shm

func (*Container) ShouldRestart Uses

func (container *Container) ShouldRestart() bool

ShouldRestart decides whether the daemon should restart the container or not. This is based on the container's restart policy.

func (*Container) StartLogger Uses

func (container *Container) StartLogger() (logger.Logger, error)

StartLogger starts a new logger driver for the container.

func (*Container) StatPath Uses

func (container *Container) StatPath(resolvedPath, absPath string) (stat *types.ContainerPathStat, err error)

StatPath is the unexported version of StatPath. Locks and mounts should be acquired before calling this method and the given path should be fully resolved to a path on the host corresponding to the given absolute path inside the container.

func (*Container) StderrPipe Uses

func (container *Container) StderrPipe() io.ReadCloser

StderrPipe gets the stderr stream of the container

func (*Container) StdinPipe Uses

func (container *Container) StdinPipe() io.WriteCloser

StdinPipe gets the stdin stream of the container

func (*Container) StdoutPipe Uses

func (container *Container) StdoutPipe() io.ReadCloser

StdoutPipe gets the stdout stream of the container

func (*Container) StopSignal Uses

func (container *Container) StopSignal() int

StopSignal returns the signal used to stop the container.

func (*Container) StopTimeout Uses

func (container *Container) StopTimeout() int

StopTimeout returns the timeout (in seconds) used to stop the container.

func (*Container) TmpfsMounts Uses

func (container *Container) TmpfsMounts() ([]Mount, error)

TmpfsMounts returns the list of tmpfs mounts

func (*Container) TrySetNetworkMount Uses

func (container *Container) TrySetNetworkMount(destination string, path string) bool

TrySetNetworkMount attempts to set the network mounts given a provided destination and the path to use for it; return true if the given destination was a network mount file

func (*Container) UnmountIpcMount Uses

func (container *Container) UnmountIpcMount() error

UnmountIpcMount unmounts shm if it was mounted

func (*Container) UnmountSecrets Uses

func (container *Container) UnmountSecrets() error

UnmountSecrets unmounts the local tmpfs for secrets

func (*Container) UnmountVolumes Uses

func (container *Container) UnmountVolumes(volumeEventLog func(name, action string, attributes map[string]string)) error

UnmountVolumes unmounts all volumes

func (*Container) UpdateContainer Uses

func (container *Container) UpdateContainer(hostConfig *containertypes.HostConfig) error

UpdateContainer updates configuration of a container. Callers must hold a Lock on the Container.

func (*Container) UpdateMonitor Uses

func (container *Container) UpdateMonitor(restartPolicy containertypes.RestartPolicy)

UpdateMonitor updates monitor configure for running container

func (*Container) WriteHostConfig Uses

func (container *Container) WriteHostConfig() (*containertypes.HostConfig, error)

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.

type ExitStatus Uses

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

ExitStatus provides exit reasons for a container.

type Health Uses

type Health struct {
    // contains filtered or unexported fields

Health holds the current container health-check state

func (*Health) CloseMonitorChannel Uses

func (s *Health) CloseMonitorChannel()

CloseMonitorChannel closes any existing monitor channel.

func (*Health) OpenMonitorChannel Uses

func (s *Health) OpenMonitorChannel() chan struct{}

OpenMonitorChannel creates and returns a new monitor channel. If there already is one, it returns nil.

func (*Health) SetStatus Uses

func (s *Health) SetStatus(new string)

SetStatus writes the current status to the underlying health structure, obeying the locking semantics.

Status may be set directly if another lock is used.

func (*Health) Status Uses

func (s *Health) Status() string

Status returns the current health status.

Note that this takes a lock and the value may change after being read.

func (*Health) String Uses

func (s *Health) String() string

String returns a human-readable description of the health-check state

type History Uses

type History []*Container

History is a convenience type for storing a list of containers, sorted by creation date in descendant order.

func (*History) Len Uses

func (history *History) Len() int

Len returns the number of containers in the history.

func (*History) Less Uses

func (history *History) Less(i, j int) bool

Less compares two containers and returns true if the second one was created before the first one.

func (*History) Swap Uses

func (history *History) Swap(i, j int)

Swap switches containers i and j positions in the history.

type Mount Uses

type Mount struct {
    Source       string `json:"source"`
    Destination  string `json:"destination"`
    Writable     bool   `json:"writable"`
    Data         string `json:"data"`
    Propagation  string `json:"mountpropagation"`
    NonRecursive bool   `json:"nonrecursive"`

Mount contains information for a mount operation.

type NoSuchContainerError Uses

type NoSuchContainerError struct {
    // contains filtered or unexported fields

NoSuchContainerError indicates that the container wasn't found in the database.

func (NoSuchContainerError) Error Uses

func (e NoSuchContainerError) Error() string

Error satisfies the error interface.

type Snapshot Uses

type Snapshot struct {

    // additional info queries need to filter on
    // preserve nanosec resolution for queries
    CreatedAt    time.Time
    StartedAt    time.Time
    Name         string
    Pid          int
    ExitCode     int
    Running      bool
    Paused       bool
    Managed      bool
    ExposedPorts nat.PortSet
    PortBindings nat.PortSet
    Health       string
    HostConfig   struct {
        Isolation string

Snapshot is a read only view for Containers. It holds all information necessary to serve container queries in a versioned ACID in-memory store.

type State Uses

type State struct {
    // Note that `Running` and `Paused` are not mutually exclusive:
    // When pausing a container (on Linux), the freezer cgroup is used to suspend
    // all processes in the container. Freezing the process requires the process to
    // be running. As a result, paused containers are both `Running` _and_ `Paused`.
    Running           bool
    Paused            bool
    Restarting        bool
    OOMKilled         bool
    RemovalInProgress bool // Not need for this to be persistent on disk.
    Dead              bool
    Pid               int
    ExitCodeValue     int    `json:"ExitCode"`
    ErrorMsg          string `json:"Error"` // contains last known error during container start, stop, or remove
    StartedAt         time.Time
    FinishedAt        time.Time
    Health            *Health
    // contains filtered or unexported fields

State holds the current container state, and has methods to get and set the state. Container has an embed, which allows all of the functions defined against State to run against Container.

func NewState Uses

func NewState() *State

NewState creates a default state object with a fresh channel for state changes.

func (*State) Err Uses

func (s *State) Err() error

Err returns an error if there is one.

func (*State) ExitCode Uses

func (s *State) ExitCode() int

ExitCode returns current exitcode for the state. Take lock before if state may be shared.

func (*State) GetPID Uses

func (s *State) GetPID() int

GetPID holds the process id of a container.

func (*State) IsDead Uses

func (s *State) IsDead() bool

IsDead returns whether the Dead flag is set. Used by Container to check whether a container is dead.

func (*State) IsPaused Uses

func (s *State) IsPaused() bool

IsPaused returns whether the container is paused or not.

func (*State) IsRemovalInProgress Uses

func (s *State) IsRemovalInProgress() bool

IsRemovalInProgress returns whether the RemovalInProgress flag is set. Used by Container to check whether a container is being removed.

func (*State) IsRestarting Uses

func (s *State) IsRestarting() bool

IsRestarting returns whether the container is restarting or not.

func (*State) IsRunning Uses

func (s *State) IsRunning() bool

IsRunning returns whether the running flag is set. Used by Container to check whether a container is running.

func (*State) ResetRemovalInProgress Uses

func (s *State) ResetRemovalInProgress()

ResetRemovalInProgress makes the RemovalInProgress state to false.

func (*State) SetError Uses

func (s *State) SetError(err error)

SetError sets the container's error state. This is useful when we want to know the error that occurred when container transits to another state when inspecting it

func (*State) SetExitCode Uses

func (s *State) SetExitCode(ec int)

SetExitCode sets current exitcode for the state. Take lock before if state may be shared.

func (*State) SetRemovalError Uses

func (s *State) SetRemovalError(err error)

SetRemovalError is to be called in case a container remove failed. It sets an error and closes the internal waitRemove channel to unblock callers waiting for the container to be removed.

func (*State) SetRemovalInProgress Uses

func (s *State) SetRemovalInProgress() bool

SetRemovalInProgress sets the container state as being removed. It returns true if the container was already in that state.

func (*State) SetRemoved Uses

func (s *State) SetRemoved()

SetRemoved assumes this container is already in the "dead" state and closes the internal waitRemove channel to unblock callers waiting for a container to be removed.

func (*State) SetRestarting Uses

func (s *State) SetRestarting(exitStatus *ExitStatus)

SetRestarting sets the container state to "restarting" without locking. It also sets the container PID to 0.

func (*State) SetRunning Uses

func (s *State) SetRunning(pid int, initial bool)

SetRunning sets the state of the container to "running".

func (*State) SetStopped Uses

func (s *State) SetStopped(exitStatus *ExitStatus)

SetStopped sets the container state to "stopped" without locking.

func (*State) StateString Uses

func (s *State) StateString() string

StateString returns a single string to describe state

func (*State) String Uses

func (s *State) String() string

String returns a human-readable description of the state

func (*State) Wait Uses

func (s *State) Wait(ctx context.Context, condition WaitCondition) <-chan StateStatus

Wait waits until the container is in a certain state indicated by the given condition. A context must be used for cancelling the request, controlling timeouts, and avoiding goroutine leaks. Wait must be called without holding the state lock. Returns a channel from which the caller will receive the result. If the container exited on its own, the result's Err() method will be nil and its ExitCode() method will return the container's exit code, otherwise, the results Err() method will return an error indicating why the wait operation failed.

type StateStatus Uses

type StateStatus struct {
    // contains filtered or unexported fields

StateStatus is used to return container wait results. Implements exec.ExitCode interface. This type is needed as State include a sync.Mutex field which make copying it unsafe.

func (StateStatus) Err Uses

func (s StateStatus) Err() error

Err returns current error for the state. Returns nil if the container had exited on its own.

func (StateStatus) ExitCode Uses

func (s StateStatus) ExitCode() int

ExitCode returns current exitcode for the state.

type Store Uses

type Store interface {
    // Add appends a new container to the store.
    Add(string, *Container)
    // Get returns a container from the store by the identifier it was stored with.
    Get(string) *Container
    // Delete removes a container from the store by the identifier it was stored with.
    // List returns a list of containers from the store.
    List() []*Container
    // Size returns the number of containers in the store.
    Size() int
    // First returns the first container found in the store by a given filter.
    First(StoreFilter) *Container
    // ApplyAll calls the reducer function with every container in the store.

Store defines an interface that any container store must implement.

func NewMemoryStore Uses

func NewMemoryStore() Store

NewMemoryStore initializes a new memory store.

type StoreFilter Uses

type StoreFilter func(*Container) bool

StoreFilter defines a function to filter container in the store.

type StoreReducer Uses

type StoreReducer func(*Container)

StoreReducer defines a function to manipulate containers in the store

type View Uses

type View interface {
    All() ([]Snapshot, error)
    Get(id string) (*Snapshot, error)

    GetID(name string) (string, error)
    GetAllNames() map[string][]string

View can be used by readers to avoid locking

type ViewDB Uses

type ViewDB interface {
    Snapshot() View
    Save(*Container) error
    Delete(*Container) error

    ReserveName(name, containerID string) error
    ReleaseName(name string) error

ViewDB provides an in-memory transactional (ACID) container Store

func NewViewDB Uses

func NewViewDB() (ViewDB, error)

NewViewDB provides the default implementation, with the default schema

type WaitCondition Uses

type WaitCondition int

WaitCondition is an enum type for different states to wait for.

const (
    WaitConditionNotRunning WaitCondition = iota

Possible WaitCondition Values.

WaitConditionNotRunning (default) is used to wait for any of the non-running states: "created", "exited", "dead", "removing", or "removed".

WaitConditionNextExit is used to wait for the next time the state changes to a non-running state. If the state is currently "created" or "exited", this would cause Wait() to block until either the container runs and exits or is removed.

WaitConditionRemoved is used to wait for the container to be removed.



Package container imports 51 packages (graph) and is imported by 724 packages. Updated 2020-11-05. Refresh now. Tools for package owners.