container

package
v0.0.0-...-5477640 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 17, 2024 License: Apache-2.0, MIT Imports: 42 Imported by: 7

Documentation

Overview

Package container creates and manipulates containers.

Index

Constants

View Source
const (
	// Created indicates "the runtime has finished the create operation and
	// the container process has neither exited nor executed the
	// user-specified program"
	Created = specs.StateCreated

	// Creating indicates "the container is being created".
	Creating = specs.StateCreating

	// Running indicates "the container process has executed the
	// user-specified program but has not exited".
	Running = specs.StateRunning

	// Stopped indicates "the container process has exited".
	Stopped = specs.StateStopped

	// Paused indicates that the process within the container has been
	// suspended. This is a local status, not part of the spec.
	Paused = Status("paused")
)

Variables

View Source
var ErrStateFileLocked = errors.New("state file locked")

ErrStateFileLocked is returned by Load() when the state file is locked and TryLock is enabled.

Functions

func Run

func Run(conf *config.Config, args Args) (unix.WaitStatus, error)

Run is a helper that calls Create + Start + Wait.

Types

type Args

type Args struct {
	// ID is the container unique identifier.
	ID string

	// Spec is the OCI spec that describes the container.
	Spec *specs.Spec

	// BundleDir is the directory containing the container bundle.
	BundleDir string

	// ConsoleSocket is the path to a unix domain socket that will receive
	// the console FD. It may be empty.
	ConsoleSocket string

	// PIDFile is the filename where the container's root process PID will be
	// written to. It may be empty.
	PIDFile string

	// UserLog is the filename to send user-visible logs to. It may be empty.
	//
	// It only applies for the init container.
	UserLog string

	// Attached indicates that the sandbox lifecycle is attached with the caller.
	// If the caller exits, the sandbox should exit too.
	//
	// It only applies for the init container.
	Attached bool

	// PassFiles are user-supplied files from the host to be exposed to the
	// sandboxed app.
	PassFiles map[int]*os.File

	// ExecFile is the host file used for program execution.
	ExecFile *os.File
}

Args is used to configure a new container.

type Container

type Container struct {
	// ID is the container ID.
	ID string `json:"id"`

	// Spec is the OCI runtime spec that configures this container.
	Spec *specs.Spec `json:"spec"`

	// BundleDir is the directory containing the container bundle.
	BundleDir string `json:"bundleDir"`

	// CreatedAt is the time the container was created.
	CreatedAt time.Time `json:"createdAt"`

	// Owner is the container owner.
	Owner string `json:"owner"`

	// ConsoleSocket is the path to a unix domain socket that will receive
	// the console FD.
	ConsoleSocket string `json:"consoleSocket"`

	// Status is the current container Status.
	Status Status `json:"status"`

	// GoferPid is the PID of the gofer running along side the sandbox. May
	// be 0 if the gofer has been killed.
	GoferPid int `json:"goferPid"`

	// Sandbox is the sandbox this container is running in. It's set when the
	// container is created and reset when the sandbox is destroyed.
	Sandbox *sandbox.Sandbox `json:"sandbox"`

	// CompatCgroup has the cgroup configuration for the container. For the single
	// container case, container cgroup is set in `c.Sandbox` only. CompactCgroup
	// is only set for multi-container, where the `c.Sandbox` cgroup represents
	// the entire pod.
	//
	// Note that CompatCgroup is created only for compatibility with tools
	// that expect container cgroups to exist. Setting limits here makes no change
	// to the container in question.
	CompatCgroup cgroup.CgroupJSON `json:"compatCgroup"`

	// Saver handles load from/save to the state file safely from multiple
	// processes.
	Saver StateFile `json:"saver"`

	// GoferMountConfs contains information about how the gofer mounts have been
	// overlaid (with tmpfs or overlayfs). The first entry is for rootfs and the
	// following entries are for bind mounts in Spec.Mounts (in the same order).
	GoferMountConfs boot.GoferMountConfFlags `json:"goferMountConfs"`
	// contains filtered or unexported fields
}

Container represents a containerized application. When running, the container is associated with a single Sandbox.

Container metadata can be saved and loaded to disk. Within a root directory, we maintain subdirectories for each container named with the container id. The container metadata is stored as a json within the container directory in a file named "meta.json". This metadata format is defined by us and is not part of the OCI spec.

Containers must write their metadata files after any change to their internal states. The entire container directory is deleted when the container is destroyed.

When the container is stopped, all processes that belong to the container must be stopped before Destroy() returns. containerd makes roughly the following calls to stop a container:

  • First it attempts to kill the container process with 'runsc kill SIGTERM'. After some time, it escalates to SIGKILL. In a separate thread, it's waiting on the container. As soon as the wait returns, it moves on to the next step:
  • It calls 'runsc kill --all SIGKILL' to stop every process that belongs to the container. 'kill --all SIGKILL' waits for all processes before returning.
  • Containerd waits for stdin, stdout and stderr to drain and be closed.
  • It calls 'runsc delete'. runc implementation kills --all SIGKILL once again just to be sure, waits, and then proceeds with remaining teardown.

Container is thread-unsafe.

func Load

func Load(rootDir string, id FullID, opts LoadOpts) (*Container, error)

Load loads a container with the given id from a metadata file. "id" may be an abbreviation of the full container id in case LoadOpts.Exact if not set. It also checks if the container is still running, in order to return an error to the caller earlier. This check is skipped if LoadOpts.SkipCheck is set.

Returns ErrNotExist if no container is found. Returns error in case more than one containers matching the ID prefix is found.

func LoadSandbox

func LoadSandbox(rootDir, id string, opts LoadOpts) ([]*Container, error)

LoadSandbox loads all containers that belong to the sandbox with the given ID.

func New

func New(conf *config.Config, args Args) (*Container, error)

New creates the container in a new Sandbox process, unless the metadata indicates that an existing Sandbox should be used. The caller must call Destroy() on the container.

func (*Container) CheckStopped

func (c *Container) CheckStopped()

CheckStopped checks if the container is stopped and updates its status.

func (*Container) Checkpoint

func (c *Container) Checkpoint(imagePath string, direct bool, sfOpts statefile.Options, mfOpts pgalloc.SaveOpts) error

Checkpoint sends the checkpoint call to the container. The statefile will be written to f, the file at the specified image-path.

func (*Container) Destroy

func (c *Container) Destroy() error

Destroy stops all processes and frees all resources associated with the container.

func (*Container) Event

func (c *Container) Event() (*boot.EventOut, error)

Event returns events for the container.

func (*Container) Execute

func (c *Container) Execute(conf *config.Config, args *control.ExecArgs) (int32, error)

Execute runs the specified command in the container. It returns the PID of the newly created process.

func (*Container) ForwardSignals

func (c *Container) ForwardSignals(pid int32, fgProcess bool) func()

ForwardSignals forwards all signals received by the current process to the container process inside the sandbox. It returns a function that will stop forwarding signals.

func (*Container) HasCapabilityInAnySet

func (c *Container) HasCapabilityInAnySet(capability linux.Capability) bool

HasCapabilityInAnySet returns true if the given capability is in any of the capability sets of the container process.

func (*Container) IsSandboxRoot

func (c *Container) IsSandboxRoot() bool

IsSandboxRoot returns true if this container is its sandbox's root container.

func (*Container) IsSandboxRunning

func (c *Container) IsSandboxRunning() bool

IsSandboxRunning returns true if the sandbox exists and is running.

func (*Container) Pause

func (c *Container) Pause() error

Pause suspends the container and its kernel. The call only succeeds if the container's status is created or running.

func (*Container) PortForward

func (c *Container) PortForward(opts *boot.PortForwardOpts) error

PortForward starts port forwarding to the container.

func (*Container) Processes

func (c *Container) Processes() ([]*control.Process, error)

Processes retrieves the list of processes and associated metadata inside a container.

func (*Container) Restore

func (c *Container) Restore(conf *config.Config, imagePath string, direct, background bool) error

Restore takes a container and replaces its kernel and file system to restore a container from its state file.

func (*Container) Resume

func (c *Container) Resume() error

Resume unpauses the container and its kernel. The call only succeeds if the container's status is paused.

func (*Container) RunsAsUID0

func (c *Container) RunsAsUID0() bool

RunsAsUID0 returns true if the container process runs with UID 0 (root).

func (*Container) SandboxPid

func (c *Container) SandboxPid() int

SandboxPid returns the Getpid of the sandbox the container is running in, or -1 if the container is not running.

func (*Container) SignalContainer

func (c *Container) SignalContainer(sig unix.Signal, all bool) error

SignalContainer sends the signal to the container. If all is true and signal is SIGKILL, then waits for all processes to exit before returning. SignalContainer returns an error if the container is already stopped. TODO(b/113680494): Distinguish different error types.

func (*Container) SignalProcess

func (c *Container) SignalProcess(sig unix.Signal, pid int32) error

SignalProcess sends sig to a specific process in the container.

func (*Container) Start

func (c *Container) Start(conf *config.Config) error

Start starts running the containerized process inside the sandbox.

func (*Container) State

func (c *Container) State() specs.State

State returns the metadata of the container.

func (*Container) Wait

func (c *Container) Wait() (unix.WaitStatus, error)

Wait waits for the container to exit, and returns its WaitStatus. Call to wait on a stopped container is needed to retrieve the exit status and wait returns immediately.

func (*Container) WaitCheckpoint

func (c *Container) WaitCheckpoint(n uint32) error

WaitCheckpoint waits for the Kernel to have been successfully checkpointed n-1 times, then waits for either the n-th successful checkpoint (in which case it returns nil) or any number of failed checkpoints (in which case it returns an error returned by any such failure).

func (*Container) WaitPID

func (c *Container) WaitPID(pid int32) (unix.WaitStatus, error)

WaitPID waits for process 'pid' in the container's PID namespace and returns its WaitStatus.

func (*Container) WaitRootPID

func (c *Container) WaitRootPID(pid int32) (unix.WaitStatus, error)

WaitRootPID waits for process 'pid' in the sandbox's PID namespace and returns its WaitStatus.

type FullID

type FullID struct {
	SandboxID   string `json:"sandboxId"`
	ContainerID string `json:"containerId"`
}

FullID combines sandbox and container ID to identify a container. Sandbox ID is used to allow all containers for a given sandbox to be loaded by matching sandbox ID in the file name.

func List

func List(rootDir string) ([]FullID, error)

List returns all container ids in the given root directory.

func ListSandboxes

func ListSandboxes(rootDir string) ([]FullID, error)

ListSandboxes returns all sandbox ids in the given root directory.

func (*FullID) String

func (f *FullID) String() string

type LoadOpts

type LoadOpts struct {
	// Exact tells whether the search should be exact. See Load() for more.
	Exact bool

	// SkipCheck tells Load() to skip checking if container is runnning.
	SkipCheck bool

	// TryLock tells Load() to fail if the container state file cannot be locked,
	// as opposed to blocking until it is available.
	// When the state file cannot be locked, it will error with ErrStateFileLocked.
	TryLock TryLock

	// RootContainer when true matches the search only with the root container of
	// a sandbox. This is used when looking for a sandbox given that root
	// container and sandbox share the same ID.
	RootContainer bool
}

LoadOpts provides options for Load()ing a container.

type OpenMountResult

type OpenMountResult struct {
	urpc.FilePayload
}

OpenMountResult is a result of the rpcp.OpenMount call.

type StateFile

type StateFile struct {
	// RootDir is the directory containing the container metadata file.
	RootDir string `json:"rootDir"`

	// ID is the sandbox+container ID.
	ID FullID `json:"id"`
	// contains filtered or unexported fields
}

StateFile handles load from/save to container state safely from multiple processes. It uses a lock file to provide synchronization between operations.

The lock file is located at: "${s.RootDir}/${containerd-id}_sand:{sandbox-id}.lock". The state file is located at: "${s.RootDir}/${containerd-id}_sand:{sandbox-id}.state".

func (*StateFile) Destroy

func (s *StateFile) Destroy() error

Destroy deletes all state created by the stateFile. It may be called with the lock file held. In that case, the lock file must still be unlocked and properly closed after destroy returns.

func (*StateFile) LockForNew

func (s *StateFile) LockForNew() error

LockForNew acquires the lock and checks if the state file doesn't exist. This is done to ensure that more than one creation didn't race to create containers with the same ID.

func (*StateFile) SaveLocked

func (s *StateFile) SaveLocked(v any) error

SaveLocked saves 'v' to the state file.

Preconditions: lock(*) must been called before.

func (*StateFile) Stat

func (s *StateFile) Stat() (os.FileInfo, error)

Stat returns the result of calling stat() on the state file. Doing so does not require locking.

func (*StateFile) UnlockOrDie

func (s *StateFile) UnlockOrDie()

UnlockOrDie is the same as unlock() but panics in case of failure.

type Status

type Status = specs.ContainerState

Status is a local type alias.

type TryLock

type TryLock bool

TryLock represents whether we should block waiting for the lock to be acquired or not.

const (
	// BlockAcquire means we will block until the lock can be acquired.
	BlockAcquire TryLock = false

	// TryAcquire means we will fail fast if the lock cannot be acquired.
	TryAcquire TryLock = true
)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL