libcontainer

package
v0.13.1-dev Latest Latest
Warning

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

Go to latest
Published: Mar 16, 2015 License: Apache-2.0, Apache-2.0 Imports: 11 Imported by: 0

README

libcontainer - reference implementation for containers Build Status

Note on API changes:

Please bear with us while we work on making the libcontainer API stable and something that we can support long term. We are currently discussing the API with the community, therefore, if you currently depend on libcontainer please pin your dependency at a specific tag or commit id. Please join the discussion and help shape the API.

Background

libcontainer specifies configuration options for what a container is. It provides a native Go implementation for using Linux namespaces with no external dependencies. libcontainer provides many convenience functions for working with namespaces, networking, and management.

Container

A container is a self contained execution environment that shares the kernel of the host system and which is (optionally) isolated from other containers in the system.

libcontainer may be used to execute a process in a container. If a user tries to run a new process inside an existing container, the new process is added to the processes executing in the container.

Root file system

A container runs with a directory known as its root file system, or rootfs, mounted as the file system root. The rootfs is usually a full system tree.

Configuration

A container is initially configured by supplying configuration data when the container is created.

nsinit

nsinit is a cli application which demonstrates the use of libcontainer. It is able to spawn new containers or join existing containers, based on the current directory.

To use nsinit, cd into a Linux rootfs and copy a container.json file into the directory with your specified configuration. Environment, networking, and different capabilities for the container are specified in this file. The configuration is used for each process executed inside the container.

See the sample_configs folder for examples of what the container configuration should look like.

To execute /bin/bash in the current directory as a container just run the following as root:

nsinit exec /bin/bash

If you wish to spawn another process inside the container while your current bash session is running, run the same command again to get another bash shell (or change the command). If the original process (PID 1) dies, all other processes spawned inside the container will be killed and the namespace will be removed.

You can identify if a process is running in a container by looking to see if state.json is in the root of the directory.

You may also specify an alternate root place where the container.json file is read and where the state.json file will be saved.

Future

See the roadmap.

Code and documentation copyright 2014 Docker, inc. Code released under the Apache 2.0 license. Docs released under Creative commons.

Hacking on libcontainer

First of all, please familiarise yourself with the libcontainer Principles.

If you're a contributor or aspiring contributor, you should read the Contributors' Guide.

If you're a maintainer or aspiring maintainer, you should read the Maintainers' Guide and "How can I become a maintainer?" in the Contributors' Guide.

Documentation

Overview

Temporary API endpoint for libcontainer while the full API is finalized (api.go).

NOTE: The API is in flux and mainly not implemented. Proceed with caution until further notice.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func DeleteState

func DeleteState(basePath string) error

DeleteState deletes the state.json file

func NotifyOnOOM

func NotifyOnOOM(s *State) (<-chan struct{}, error)

NotifyOnOOM returns channel on which you can expect event about OOM, if process died without OOM this channel will be closed. s is current *libcontainer.State for container.

func SaveState

func SaveState(basePath string, state *State) error

SaveState writes the container's runtime state to a state.json file in the specified path

Types

type Config

type Config struct {
	// Mount specific options.
	MountConfig *MountConfig `json:"mount_config,omitempty"`

	// Pathname to container's root filesystem
	RootFs string `json:"root_fs,omitempty"`

	// Hostname optionally sets the container's hostname if provided
	Hostname string `json:"hostname,omitempty"`

	// User will set the uid and gid of the executing process running inside the container
	User string `json:"user,omitempty"`

	// WorkingDir will change the processes current working directory inside the container's rootfs
	WorkingDir string `json:"working_dir,omitempty"`

	// Env will populate the processes environment with the provided values
	// Any values from the parent processes will be cleared before the values
	// provided in Env are provided to the process
	Env []string `json:"environment,omitempty"`

	// Tty when true will allocate a pty slave on the host for access by the container's process
	// and ensure that it is mounted inside the container's rootfs
	Tty bool `json:"tty,omitempty"`

	// Namespaces specifies the container's namespaces that it should setup when cloning the init process
	// If a namespace is not provided that namespace is shared from the container's parent process
	Namespaces Namespaces `json:"namespaces,omitempty"`

	// Capabilities specify the capabilities to keep when executing the process inside the container
	// All capbilities not specified will be dropped from the processes capability mask
	Capabilities []string `json:"capabilities,omitempty"`

	// Networks specifies the container's network setup to be created
	Networks []*Network `json:"networks,omitempty"`

	// Routes can be specified to create entries in the route table as the container is started
	Routes []*Route `json:"routes,omitempty"`

	// Cgroups specifies specific cgroup settings for the various subsystems that the container is
	// placed into to limit the resources the container has available
	Cgroups *cgroups.Cgroup `json:"cgroups,omitempty"`

	// AppArmorProfile specifies the profile to apply to the process running in the container and is
	// change at the time the process is execed
	AppArmorProfile string `json:"apparmor_profile,omitempty"`

	// ProcessLabel specifies the label to apply to the process running in the container.  It is
	// commonly used by selinux
	ProcessLabel string `json:"process_label,omitempty"`

	// RestrictSys will remount /proc/sys, /sys, and mask over sysrq-trigger as well as /proc/irq and
	// /proc/bus
	RestrictSys bool `json:"restrict_sys,omitempty"`

	// Rlimits specifies the resource limits, such as max open files, to set in the container
	// If Rlimits are not set, the container will inherit rlimits from the parent process
	Rlimits []Rlimit `json:"rlimits,omitempty"`
}

Config defines configuration options for executing a process inside a contained environment.

type Container

type Container interface {
	// Returns the ID of the container
	ID() string

	// Returns the current run state of the container.
	//
	// Errors:
	// ContainerDestroyed - Container no longer exists,
	// SystemError - System error.
	RunState() (*RunState, Error)

	// Returns the current config of the container.
	Config() *Config

	// Start a process inside the container. Returns the PID of the new process (in the caller process's namespace) and a channel that will return the exit status of the process whenever it dies.
	//
	// Errors:
	// ContainerDestroyed - Container no longer exists,
	// ConfigInvalid - config is invalid,
	// ContainerPaused - Container is paused,
	// SystemError - System error.
	Start(config *ProcessConfig) (pid int, exitChan chan int, err Error)

	// Destroys the container after killing all running processes.
	//
	// Any event registrations are removed before the container is destroyed.
	// No error is returned if the container is already destroyed.
	//
	// Errors:
	// SystemError - System error.
	Destroy() Error

	// Returns the PIDs inside this container. The PIDs are in the namespace of the calling process.
	//
	// Errors:
	// ContainerDestroyed - Container no longer exists,
	// SystemError - System error.
	//
	// Some of the returned PIDs may no longer refer to processes in the Container, unless
	// the Container state is PAUSED in which case every PID in the slice is valid.
	Processes() ([]int, Error)

	// Returns statistics for the container.
	//
	// Errors:
	// ContainerDestroyed - Container no longer exists,
	// SystemError - System error.
	Stats() (*ContainerStats, Error)

	// If the Container state is RUNNING or PAUSING, sets the Container state to PAUSING and pauses
	// the execution of any user processes. Asynchronously, when the container finished being paused the
	// state is changed to PAUSED.
	// If the Container state is PAUSED, do nothing.
	//
	// Errors:
	// ContainerDestroyed - Container no longer exists,
	// SystemError - System error.
	Pause() Error

	// If the Container state is PAUSED, resumes the execution of any user processes in the
	// Container before setting the Container state to RUNNING.
	// If the Container state is RUNNING, do nothing.
	//
	// Errors:
	// ContainerDestroyed - Container no longer exists,
	// SystemError - System error.
	Resume() Error
}

A libcontainer container object.

Each container is thread-safe within the same process. Since a container can be destroyed by a separate process, any function may return that the container was not found.

type ContainerStats

type ContainerStats struct {
	NetworkStats *network.NetworkStats `json:"network_stats,omitempty"`
	CgroupStats  *cgroups.Stats        `json:"cgroup_stats,omitempty"`
}

func GetStats

func GetStats(container *Config, state *State) (stats *ContainerStats, err error)

TODO(vmarmol): Complete Stats() in final libcontainer API and move users to that. DEPRECATED: The below portions are only to be used during the transition to the official API. Returns all available stats for the given container.

type Error

type Error interface {
	error

	// Returns the stack trace, if any, which identifies the
	// point at which the error occurred.
	Stack() []byte

	// Returns a verbose string including the error message
	// and a representation of the stack trace suitable for
	// printing.
	Detail() string

	// Returns the error code for this error.
	Code() ErrorCode
}

API Error type.

type ErrorCode

type ErrorCode int

API error code type.

const (
	// Factory errors
	IdInUse ErrorCode = iota
	InvalidIdFormat

	// Container errors
	ContainerDestroyed
	ContainerPaused

	// Common errors
	ConfigInvalid
	SystemError
)

API error codes.

type Factory

type Factory interface {

	// Creates a new container with the given id and starts the initial process inside it.
	// id must be a string containing only letters, digits and underscores and must contain
	// between 1 and 1024 characters, inclusive.
	//
	// The id must not already be in use by an existing container. Containers created using
	// a factory with the same path (and file system) must have distinct ids.
	//
	// Returns the new container with a running process.
	//
	// Errors:
	// IdInUse - id is already in use by a container
	// InvalidIdFormat - id has incorrect format
	// ConfigInvalid - config is invalid
	// SystemError - System error
	//
	// On error, any partially created container parts are cleaned up (the operation is atomic).
	Create(id string, config *Config) (Container, Error)

	// Load takes an ID for an existing container and reconstructs the container
	// from the state.
	//
	// Errors:
	// Path does not exist
	// Container is stopped
	// System error
	// TODO: fix description
	Load(id string) (Container, Error)
}

type MountConfig

type MountConfig mount.MountConfig

type Namespace

type Namespace struct {
	Type NamespaceType `json:"type"`
	Path string        `json:"path,omitempty"`
}

Namespace defines configuration for each namespace. It specifies an alternate path that is able to be joined via setns.

type NamespaceType

type NamespaceType string
const (
	NEWNET  NamespaceType = "NEWNET"
	NEWPID  NamespaceType = "NEWPID"
	NEWNS   NamespaceType = "NEWNS"
	NEWUTS  NamespaceType = "NEWUTS"
	NEWIPC  NamespaceType = "NEWIPC"
	NEWUSER NamespaceType = "NEWUSER"
)

type Namespaces

type Namespaces []Namespace

func (*Namespaces) Add

func (n *Namespaces) Add(t NamespaceType, path string)

func (*Namespaces) Contains

func (n *Namespaces) Contains(t NamespaceType) bool

func (*Namespaces) Remove

func (n *Namespaces) Remove(t NamespaceType) bool

type Network

type Network network.Network

type ProcessConfig

type ProcessConfig struct {
	// The command to be run followed by any arguments.
	Args []string

	// Map of environment variables to their values.
	Env []string

	// Stdin is a pointer to a reader which provides the standard input stream.
	// Stdout is a pointer to a writer which receives the standard output stream.
	// Stderr is a pointer to a writer which receives the standard error stream.
	//
	// If a reader or writer is nil, the input stream is assumed to be empty and the output is
	// discarded.
	//
	// The readers and writers, if supplied, are closed when the process terminates. Their Close
	// methods should be idempotent.
	//
	// Stdout and Stderr may refer to the same writer in which case the output is interspersed.
	Stdin  io.ReadCloser
	Stdout io.WriteCloser
	Stderr io.WriteCloser
}

Configuration for a process to be run inside a container.

type Rlimit

type Rlimit struct {
	Type int    `json:"type,omitempty"`
	Hard uint64 `json:"hard,omitempty"`
	Soft uint64 `json:"soft,omitempty"`
}

type Route

type Route struct {
	// Sets the destination and mask, should be a CIDR.  Accepts IPv4 and IPv6
	Destination string `json:"destination,omitempty"`

	// Sets the source and mask, should be a CIDR.  Accepts IPv4 and IPv6
	Source string `json:"source,omitempty"`

	// Sets the gateway.  Accepts IPv4 and IPv6
	Gateway string `json:"gateway,omitempty"`

	// The device to set this route up for, for example: eth0
	InterfaceName string `json:"interface_name,omitempty"`
}

Routes can be specified to create entries in the route table as the container is started

All of destination, source, and gateway should be either IPv4 or IPv6. One of the three options must be present, and ommitted entries will use their IP family default for the route table. For IPv4 for example, setting the gateway to 1.2.3.4 and the interface to eth0 will set up a standard destination of 0.0.0.0(or *) when viewed in the route table.

type RunState

type RunState int

The running state of the container.

const (

	// The container exists and is running.
	Running RunState = iota

	// The container exists, it is in the process of being paused.
	Pausing

	// The container exists, but all its processes are paused.
	Paused

	// The container does not exist.
	Destroyed
)

type State

type State struct {
	// InitPid is the init process id in the parent namespace
	InitPid int `json:"init_pid,omitempty"`

	// InitStartTime is the init process start time
	InitStartTime string `json:"init_start_time,omitempty"`

	// Network runtime state.
	NetworkState network.NetworkState `json:"network_state,omitempty"`

	// Path to all the cgroups setup for a container. Key is cgroup subsystem name.
	CgroupPaths map[string]string `json:"cgroup_paths,omitempty"`
}

State represents a running container's state

func GetState

func GetState(basePath string) (*State, error)

GetState reads the state.json file for a running container

Directories

Path Synopsis
fs
integration is used for integration testing of libcontainer
integration is used for integration testing of libcontainer
Packet netlink provide access to low level Netlink sockets and messages.
Packet netlink provide access to low level Netlink sockets and messages.
security

Jump to

Keyboard shortcuts

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