mgr

package
v0.0.0-...-bc5839e Latest Latest
Warning

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

Go to latest
Published: Sep 7, 2020 License: Apache-2.0 Imports: 103 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// DefaultStopTimeout is the timeout (in seconds) for the syscall signal used to stop a container.
	DefaultStopTimeout = 10

	// RuntimeDir is specified name keeps runtime path script.
	RuntimeDir = "runtimes"
)
View Source
const (
	// ProfileNamePrefix is the prefix for loading profiles on a localhost. Eg. localhost/profileName.
	ProfileNamePrefix = "localhost/"
	// ProfileRuntimeDefault indicates that we should use or create a runtime default profile.
	ProfileRuntimeDefault = "runtime/default"
	// ProfileDockerDefault indicates that we should use or create a docker default profile.
	ProfileDockerDefault = "docker/default"
	// ProfilePouchDefault indicates that we should use or create a pouch default profile.
	ProfilePouchDefault = "pouch/default"
	// ProfileNameUnconfined is a string indicating one should run a pod/containerd without a security profile.
	ProfileNameUnconfined = "unconfined"
)

FIXME: these variables have no relation with spec, move them.

View Source
const (
	// RPrivatePropagationMode represents mount propagation rprivate.
	RPrivatePropagationMode = "rprivate"
	// PrivatePropagationMode represents mount propagation private.
	PrivatePropagationMode = "private"
	// RSharedPropagationMode represents mount propagation rshared.
	RSharedPropagationMode = "rshared"
	// SharedPropagationMode represents mount propagation shared.
	SharedPropagationMode = "shared"
	// RSlavePropagationMode represents mount propagation rslave.
	RSlavePropagationMode = "rslave"
	// SlavePropagationMode represents mount propagation slave.
	SlavePropagationMode = "slave"
)
View Source
const (
	// EvExit represents container's exit event.
	EvExit = iota
)

Variables

View Source
var (
	// GCExecProcessTick is the time interval to trigger gc unused exec config,
	// time unit is minute.
	GCExecProcessTick = 5

	// MinMemory is minimal memory container should has.
	MinMemory int64 = 4194304

	// DefaultStatsInterval is the interval configured for stats.
	DefaultStatsInterval = time.Duration(time.Second)

	// ProfileUnconfined means run a container without the default seccomp profile.
	ProfileUnconfined = "unconfined"
)
View Source
var (
	// MemoryWarn is warning for flag --memory
	MemoryWarn = "Current Kernel does not support memory limit, discard --memory"

	// MemoryReservationWarn is warning for flag --memory-reservation
	MemoryReservationWarn = "Current Kernel does not support memory soft limit, discard --memory-reservation"

	// MemorySwapWarn is warning for flag --memory-swap
	MemorySwapWarn = "Current Kernel does not support memory swap, discard --memory-swap"

	// MemorySwappinessWarn is warning for flag --memory-swappiness
	MemorySwappinessWarn = "Current Kernel does not support memory swappiness , discard --memory-swappiness"

	//OOMKillWarn is warning for flag --oom-kill-disable
	OOMKillWarn = "Current Kernel does not support disable oom kill, discard --oom-kill-disable"

	// CpusetCpusWarn is warning for flag --cpuset-cpus
	CpusetCpusWarn = "Current Kernel does not support cpuset cpus, discard --cpuset-cpus"

	// CpusetMemsWarn is warning for flag --cpuset-mems
	CpusetMemsWarn = "Current Kernel does not support cpuset mems, discard --cpuset-mems"

	// CPUSharesWarn is warning for flag --cpu-shares
	CPUSharesWarn = "Current Kernel does not support cpu shares, discard --cpu-shares"

	// CPUQuotaWarn is warning for flag --cpu-quota
	CPUQuotaWarn = "Current Kernel does not support cpu quota, discard --cpu-quota"

	// CPUPeriodWarn is warning for flag --cpu-period
	CPUPeriodWarn = "Current Kernel does not support cpu period, discard --cpu-period"

	// BlkioWeightWarn is warning for flag --blkio-weight
	BlkioWeightWarn = "Current Kernel does not support blkio weight, discard --blkio-weight"

	// BlkioWeightDeviceWarn is warning for flag --blkio-weight-device
	BlkioWeightDeviceWarn = "Current Kernel does not support blkio weight device, discard --blkio-weight-device"

	// BlkioDeviceReadBpsWarn is warning for flag --device-read-bps
	BlkioDeviceReadBpsWarn = "Current Kernel does not support blkio device throttle read bps, discard --device-read-bps"

	// BlkioDeviceWriteBpsWarn is warning for flag --device-write-bps
	BlkioDeviceWriteBpsWarn = "Current Kernel does not support blkio device throttle write bps, discard --device-write-bps"

	// BlkioDeviceReadIOpsWarn is warning for flag --device-read-iops
	BlkioDeviceReadIOpsWarn = "Current Kernel does not support blkio device throttle read iops, discard --device-read-iops"

	// BlkioDeviceWriteIOpsWarn is warning for flag --device-write-iops
	BlkioDeviceWriteIOpsWarn = "Current Kernel does not support blkio device throttle, discard --device-write-iops"

	// PidsLimitWarn is warning for flag --pids-limit
	PidsLimitWarn = "Current Kernel does not support pids cgroup, discard --pids-limit"
)

Functions

func BuildContainerEndpoint

func BuildContainerEndpoint(c *Container) *networktypes.Endpoint

BuildContainerEndpoint is used to build container's endpoint config.

func IsBridge

func IsBridge(mode string) bool

IsBridge is used to check if network mode is bridge mode.

func IsContainer

func IsContainer(mode string) bool

IsContainer is used to check if network mode is container mode.

func IsDefault

func IsDefault(mode string) bool

IsDefault indicates whether container uses the default network stack.

func IsHost

func IsHost(mode string) bool

IsHost is used to check if network mode is host mode.

func IsNetNS

func IsNetNS(mode string) bool

IsNetNS is used to check if network mode is netns mode.

func IsNone

func IsNone(mode string) bool

IsNone is used to check if network mode is none mode.

func IsPrivate

func IsPrivate(mode string) bool

IsPrivate indicates whether container uses its private network stack.

func IsSeccompEnable

func IsSeccompEnable() bool

IsSeccompEnable return false since pouch do not support seccomp in build

func IsUserDefined

func IsUserDefined(mode string) bool

IsUserDefined is used to check if network mode is user-created.

Types

type AttachConfig

type AttachConfig struct {
	Stdin  bool
	Stdout bool
	Stderr bool

	// For IO backend like http, we need to mux stdout & stderr
	// if terminal is disabled.
	// But for other IO backend, it is not necessary.
	// So we should make it configurable.
	MuxDisabled bool

	// Attach using http.
	Hijack  http.Hijacker
	Upgrade bool

	// Attach using pipe.
	Pipe *io.PipeWriter

	// Attach using streams.
	Streams *remotecommand.Streams

	// Attach to the container to get its log.
	CriLogFile *os.File
}

AttachConfig wraps some infos of attaching.

type Container

type Container struct {
	sync.Mutex

	// app armor profile
	AppArmorProfile string `json:"AppArmorProfile,omitempty"`

	// seccomp profile
	SeccompProfile string `json:"SeccompProfile,omitempty"`

	// no new privileges
	NoNewPrivileges bool `json:"NoNewPrivileges,omitempty"`

	// The arguments to the command being run
	Args []string `json:"Args"`

	// config
	Config *types.ContainerConfig `json:"Config,omitempty"`

	// The time the container was created
	Created string `json:"Created,omitempty"`

	// driver
	Driver string `json:"Driver,omitempty"`

	// exec ids
	ExecIds []string `json:"-"`

	// Snapshotter, GraphDriver is same, keep both
	// just for compatibility
	// snapshotter informations of container
	Snapshotter *types.SnapshotterData `json:"Snapshotter,omitempty"`

	// graph driver
	GraphDriver *types.GraphDriverData `json:"GraphDriver,omitempty"`

	// host config
	HostConfig *types.HostConfig `json:"HostConfig,omitempty"`

	// hostname path
	HostnamePath string `json:"HostnamePath,omitempty"`

	// hosts path
	HostsPath string `json:"HostsPath,omitempty"`

	// The ID of the container
	ID string `json:"Id,omitempty"`

	// The container's image
	Image string `json:"Image,omitempty"`

	// log path
	LogPath string `json:"LogPath,omitempty"`

	// mount label
	MountLabel string `json:"MountLabel,omitempty"`

	// mounts
	Mounts []*types.MountPoint `json:"Mounts"`

	// name
	Name string `json:"Name,omitempty"`

	// network settings
	NetworkSettings *types.NetworkSettings `json:"NetworkSettings,omitempty"`

	Node interface{} `json:"Node,omitempty"`

	// The path to the command being run
	Path string `json:"Path,omitempty"`

	// process label
	ProcessLabel string `json:"ProcessLabel,omitempty"`

	// resolv conf path
	ResolvConfPath string `json:"ResolvConfPath,omitempty"`

	// restart count
	RestartCount int64 `json:"RestartCount,omitempty"`

	// The total size of all the files in this container.
	SizeRootFs int64 `json:"SizeRootFs,omitempty"`

	// The size of files that have been created or changed by this container.
	SizeRw int64 `json:"SizeRw,omitempty"`

	// state
	State *types.ContainerState `json:"State,omitempty"`

	// BaseFS
	BaseFS string `json:"BaseFS,omitempty"`

	// Escape keys for detach
	DetachKeys string

	// RootFSProvided is a flag to point the container is created by specify rootfs
	RootFSProvided bool

	// MountFS is used to mark the directory of mount overlayfs for pouch daemon to operate the image.
	MountFS string `json:"-"`

	// SnapshotID specify id of the snapshot that container using.
	SnapshotID string
}

Container represents the container's meta data.

func (*Container) CleanRootfsSnapshotDirs

func (c *Container) CleanRootfsSnapshotDirs() error

CleanRootfsSnapshotDirs deletes container's rootfs snapshot MergedDir, UpperDir and WorkDir. Since the snapshot of container created by containerd will be cleaned by containerd, so we only clean rootfs that is RootFSProvided.

func (*Container) ExitCode

func (c *Container) ExitCode() int64

ExitCode returns container's ExitCode.

func (*Container) FormatStatus

func (c *Container) FormatStatus() (string, error)

FormatStatus format container status

func (*Container) GetResourcePath

func (c *Container) GetResourcePath(baseFS, path string) string

GetResourcePath is to determine the real host path of dir inside a container. If the dir has no volume covered, then just return BaseFS/dir, else we should return the real path inside volume.

func (*Container) GetSpecificBasePath

func (c *Container) GetSpecificBasePath(path string) string

GetSpecificBasePath accepts a given path, look for whether the path is exist within container, if has, returns container base path like BaseFS, if not, return empty string

func (*Container) IsCreated

func (c *Container) IsCreated() bool

IsCreated returns container is created or not.

func (*Container) IsDead

func (c *Container) IsDead() bool

IsDead returns container is dead or not. NOTE: ContainerMgmt.Remove action will set Dead to container's meta config before removing the meta config json file.

func (*Container) IsRemoving

func (c *Container) IsRemoving() bool

IsRemoving returns container is removing or not. TODO: actually the pouchd do not set removing status for a container.

func (*Container) IsRunning

func (c *Container) IsRunning() bool

IsRunning returns container is running or not.

func (*Container) IsRunningOrPaused

func (c *Container) IsRunningOrPaused() bool

IsRunningOrPaused returns true of container is running or paused.

func (*Container) Key

func (c *Container) Key() string

Key returns container's id.

func (*Container) SetSnapshotterMeta

func (c *Container) SetSnapshotterMeta(mounts []mount.Mount)

SetSnapshotterMeta sets snapshotter for container

func (*Container) SetStatusDead

func (c *Container) SetStatusDead()

SetStatusDead sets a container to be status dead.

func (*Container) SetStatusExited

func (c *Container) SetStatusExited(exitCode int64, errMsg string)

SetStatusExited sets a container to be status exited.

func (*Container) SetStatusOOM

func (c *Container) SetStatusOOM()

SetStatusOOM sets a container to be status exit because of OOM.

func (*Container) SetStatusPaused

func (c *Container) SetStatusPaused()

SetStatusPaused sets a container to be status paused.

func (*Container) SetStatusRunning

func (c *Container) SetStatusRunning(pid int64)

SetStatusRunning sets a container to be status running. When a container's status turns to StatusStopped, the following fields need updated: Status -> StatusRunning StartAt -> time.Now() Pid -> input param ExitCode -> 0

func (*Container) SetStatusStopped

func (c *Container) SetStatusStopped(exitCode int64, errMsg string)

SetStatusStopped sets a container to be status stopped. When a container's status turns to StatusStopped, the following fields need updated: Status -> StatusStopped FinishedAt -> time.Now() Pid -> 0 ExitCode -> input param Error -> input param

func (*Container) SetStatusUnpaused

func (c *Container) SetStatusUnpaused()

SetStatusUnpaused sets a container to be status running. Unpaused is treated running.

func (*Container) SnapshotKey

func (c *Container) SnapshotKey() string

SnapshotKey returns id of container's snapshot

func (*Container) StopTimeout

func (c *Container) StopTimeout() int64

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

func (*Container) UnsetMergedDir

func (c *Container) UnsetMergedDir()

UnsetMergedDir unsets Snapshot MergedDir. Stop a container will delete the containerd container, the merged dir will also be deleted, so we should unset the container's MergedDir.

func (*Container) Write

func (c *Container) Write(store *meta.Store) error

Write writes container's meta data into meta store.

type ContainerEvent

type ContainerEvent struct {
	Kind int
	// contains filtered or unexported fields
}

ContainerEvent represents the container's events.

func ContainerExitEvent

func ContainerExitEvent(c *Container) *ContainerEvent

ContainerExitEvent represents container's exit event.

func (*ContainerEvent) String

func (e *ContainerEvent) String() string

String returns container's event type as a string.

func (*ContainerEvent) WithHandle

func (e *ContainerEvent) WithHandle(handle func(*Container) error) *ContainerEvent

WithHandle sets the event's handler.

type ContainerExecConfig

type ContainerExecConfig struct {
	sync.Mutex

	// ExecID identifies the ID of this exec
	ExecID string

	// contains the config of this exec
	types.ExecCreateConfig

	// Save the container's id into exec config.
	ContainerID string

	// ExitCode records the exit code of a exec process.
	ExitCode int64

	// Running represents whether the exec process is running inside container.
	Running bool

	// Error represents the exec process response error.
	Error error

	// WaitForClean means exec process can be removed.
	WaitForClean bool

	// Environment variables
	Env []string

	// Used means execConfig has been seen by user
	Used bool

	// Exited means exec process exit or not
	Exited bool
}

ContainerExecConfig is the config a process exec.

type ContainerFilter

type ContainerFilter func(*Container) bool

ContainerFilter defines a function to filter container in the store.

type ContainerListOption

type ContainerListOption struct {
	All        bool
	Filter     map[string][]string
	FilterFunc ContainerFilter
}

ContainerListOption wraps the container list interface params.

type ContainerManager

type ContainerManager struct {
	// Store stores containers in Backend store.
	// Element operated in store must has a type of *Container.
	// By default, Store will use local filesystem with json format to store containers.
	Store *meta.Store

	// Client is used to interact with containerd.
	Client ctrd.APIClient

	// NameToID stores relations between container's name and ID.
	// It is used to get container ID via container name.
	NameToID *collect.SafeMap

	ImageMgr      ImageMgr
	VolumeMgr     VolumeMgr
	NetworkMgr    NetworkMgr
	IOs           *containerio.Cache
	ExecProcesses *collect.SafeMap

	Config *daemon_config.Config
	// contains filtered or unexported fields
}

ContainerManager is the default implement of interface ContainerMgr.

func NewContainerManager

func NewContainerManager(ctx context.Context, store *meta.Store, cli ctrd.APIClient, imgMgr ImageMgr, volMgr VolumeMgr, cfg *daemon_config.Config, contPlugin hookplugins.ContainerPlugin, eventsService *events.Events) (*ContainerManager, error)

NewContainerManager creates a brand new container manager.

func (*ContainerManager) ArchivePath

func (mgr *ContainerManager) ArchivePath(ctx context.Context, name, path string) (content io.ReadCloser, stat *types.ContainerPathStat, err0 error)

ArchivePath return an archive and dir info at the specified path in the container.

func (*ContainerManager) AttachCRILog

func (mgr *ContainerManager) AttachCRILog(ctx context.Context, name string, logPath string) error

AttachCRILog adds cri log to a container.

func (*ContainerManager) AttachContainerIO

func (mgr *ContainerManager) AttachContainerIO(ctx context.Context, name string, cfg *streams.AttachConfig) error

AttachContainerIO attachs a container's io.

func (*ContainerManager) CheckExecExist

func (mgr *ContainerManager) CheckExecExist(ctx context.Context, name string) error

CheckExecExist check if exec process `name` exist

func (*ContainerManager) Commit

Commit commits an image from a container.

func (*ContainerManager) Connect

func (mgr *ContainerManager) Connect(ctx context.Context, name string, networkIDOrName string, epConfig *types.EndpointSettings) error

Connect is used to connect a container to a network.

func (*ContainerManager) Create

func (mgr *ContainerManager) Create(ctx context.Context, name string, config *types.ContainerCreateConfig) (resp *types.ContainerCreateResp, err error)

Create checks passed in parameters and create a Container object whose status is set at Created.

func (*ContainerManager) CreateCheckpoint

func (mgr *ContainerManager) CreateCheckpoint(ctx context.Context, name string, options *types.CheckpointCreateOptions) (err0 error)

CreateCheckpoint creates a checkpoint from a running container

func (*ContainerManager) CreateExec

func (mgr *ContainerManager) CreateExec(ctx context.Context, name string, config *types.ExecCreateConfig) (string, error)

CreateExec creates exec process's meta data.

func (*ContainerManager) DeleteCheckpoint

func (mgr *ContainerManager) DeleteCheckpoint(ctx context.Context, name string, options *types.CheckpointDeleteOptions) error

DeleteCheckpoint deletes a checkpoint from a container

func (*ContainerManager) Disconnect

func (mgr *ContainerManager) Disconnect(ctx context.Context, containerName, networkName string, force bool) error

Disconnect disconnects the given container from given network

func (*ContainerManager) ExtractToDir

func (mgr *ContainerManager) ExtractToDir(ctx context.Context, name, path string, copyUIDGID, noOverwriteDirNonDir bool, content io.Reader) error

ExtractToDir extracts the given archive at the specified path in the container.

func (*ContainerManager) Get

func (mgr *ContainerManager) Get(ctx context.Context, name string) (*Container, error)

Get the detailed information of container.

func (*ContainerManager) GetExecConfig

func (mgr *ContainerManager) GetExecConfig(ctx context.Context, execid string) (*ContainerExecConfig, error)

GetExecConfig returns execonfig of a exec process inside container.

func (*ContainerManager) InspectExec

func (mgr *ContainerManager) InspectExec(ctx context.Context, execid string) (*types.ContainerExecInspect, error)

InspectExec returns low-level information about exec command.

func (*ContainerManager) List

func (mgr *ContainerManager) List(ctx context.Context, option *ContainerListOption) ([]*Container, error)

List returns the container's list.

func (*ContainerManager) ListCheckpoint

func (mgr *ContainerManager) ListCheckpoint(ctx context.Context, name string, options *types.CheckpointListOptions) ([]string, error)

ListCheckpoint lists checkpoints from a container

func (*ContainerManager) Load

func (mgr *ContainerManager) Load(ctx context.Context) error

Load containers from meta store to memory.

func (*ContainerManager) LogContainerEvent

func (mgr *ContainerManager) LogContainerEvent(ctx context.Context, container *Container, action string)

LogContainerEvent generates an event related to a container with only the default attributes.

func (*ContainerManager) LogContainerEventWithAttributes

func (mgr *ContainerManager) LogContainerEventWithAttributes(ctx context.Context, container *Container, action string, attributes map[string]string)

LogContainerEventWithAttributes generates an event related to a container with specific given attributes.

func (*ContainerManager) LogNetworkEventWithAttributes

func (mgr *ContainerManager) LogNetworkEventWithAttributes(ctx context.Context, nw libnetwork.Network, action string, attributes map[string]string)

LogNetworkEventWithAttributes generates an event related to a network with specific given attributes Use ContainerManager to publish network event may be a little bit ugly now

func (*ContainerManager) Logs

func (mgr *ContainerManager) Logs(ctx context.Context, name string, logOpt *types.ContainerLogsOptions) (<-chan *logger.LogMessage, bool, error)

Logs is used to return log created by the container.

func (*ContainerManager) Mount

func (mgr *ContainerManager) Mount(ctx context.Context, c *Container) error

Mount sets the container rootfs

func (*ContainerManager) NewSnapshotsSyncer

func (mgr *ContainerManager) NewSnapshotsSyncer(snapshotStore *SnapshotStore, duration time.Duration) *SnapshotsSyncer

NewSnapshotsSyncer creates a snapshot syncer.

func (*ContainerManager) Pause

func (mgr *ContainerManager) Pause(ctx context.Context, name string) error

Pause pauses a running container.

func (*ContainerManager) Remove

func (mgr *ContainerManager) Remove(ctx context.Context, name string, options *types.ContainerRemoveOptions) error

Remove removes a container, it may be running or stopped and so on.

func (*ContainerManager) Rename

func (mgr *ContainerManager) Rename(ctx context.Context, oldName, newName string) error

Rename renames a container.

func (*ContainerManager) Resize

func (mgr *ContainerManager) Resize(ctx context.Context, name string, opts types.ResizeOptions) error

Resize resizes the size of a container tty.

func (*ContainerManager) ResizeExec

func (mgr *ContainerManager) ResizeExec(ctx context.Context, execid string, opts types.ResizeOptions) error

ResizeExec resizes the size of exec process's tty.

func (*ContainerManager) Restart

func (mgr *ContainerManager) Restart(ctx context.Context, name string, timeout int64) error

Restart restarts a running container.

func (*ContainerManager) Restore

func (mgr *ContainerManager) Restore(ctx context.Context) error

Restore tries to recover those alive containers

func (*ContainerManager) SetContainerLogPath

func (mgr *ContainerManager) SetContainerLogPath(c *Container)

SetContainerLogPath sets the log path of container. LogPath would be as a field in `Inspect` response.

func (*ContainerManager) SetupWorkingDirectory

func (mgr *ContainerManager) SetupWorkingDirectory(ctx context.Context, c *Container) error

SetupWorkingDirectory setup working directory for container

func (*ContainerManager) Start

func (mgr *ContainerManager) Start(ctx context.Context, id string, options *types.ContainerStartOptions) (err error)

Start a pre created Container.

func (*ContainerManager) StartExec

func (mgr *ContainerManager) StartExec(ctx context.Context, execid string, cfg *streams.AttachConfig, timeout int) (err0 error)

StartExec executes a new process in container. timeout = 0 means no timeout

func (*ContainerManager) StatPath

func (mgr *ContainerManager) StatPath(ctx context.Context, name, path string) (stat *types.ContainerPathStat, err error)

StatPath stats the dir info at the specified path in the container.

func (*ContainerManager) Stats

Stats gets the stat of a container.

func (*ContainerManager) Stop

func (mgr *ContainerManager) Stop(ctx context.Context, name string, timeout int64) error

Stop stops a running container.

func (*ContainerManager) StreamStats

func (mgr *ContainerManager) StreamStats(ctx context.Context, name string, config *ContainerStatsConfig) error

StreamStats gets the stats from containerd side and send back to caller as a stream.

func (*ContainerManager) Top

func (mgr *ContainerManager) Top(ctx context.Context, name string, psArgs string) (*types.ContainerProcessList, error)

Top lists the processes running inside of the given container

func (*ContainerManager) Unmount

func (mgr *ContainerManager) Unmount(ctx context.Context, c *Container) error

Unmount unsets the container rootfs cleanup decides whether to clean up the dir or not

func (*ContainerManager) Unpause

func (mgr *ContainerManager) Unpause(ctx context.Context, name string) error

Unpause unpauses a paused container.

func (*ContainerManager) Update

func (mgr *ContainerManager) Update(ctx context.Context, name string, config *types.UpdateConfig) error

Update updates the configurations of a container.

func (*ContainerManager) Upgrade

func (mgr *ContainerManager) Upgrade(ctx context.Context, name string, config *types.ContainerUpgradeConfig) error

Upgrade a container with new image and args. when upgrade a container, we only support specify cmd and entrypoint. if you want to change other parameters of the container, you should think about the update API first.

func (*ContainerManager) Wait

Wait stops processing until the given container is stopped.

type ContainerMgr

type ContainerMgr interface {

	// Load containers from meta store to memory. Split used Restore feature into two function:
	// Load: just load all containers information into memory, it will be called before network
	// manager being initialized.
	// Restore: recover all running containers, it will be called after network manager being
	// initialized so that we can call network functions in the recover procedures.
	Load(ctx context.Context) error

	// Restore recover those alive containers.
	Restore(ctx context.Context) error

	// Create a new container.
	Create(ctx context.Context, name string, config *types.ContainerCreateConfig) (*types.ContainerCreateResp, error)

	// Get the detailed information of container.
	Get(ctx context.Context, name string) (*Container, error)

	// List returns the list of containers.
	List(ctx context.Context, option *ContainerListOption) ([]*Container, error)

	// Start a container.
	Start(ctx context.Context, id string, options *types.ContainerStartOptions) error

	// Stop a container.
	Stop(ctx context.Context, name string, timeout int64) error

	// Restart restart a running container.
	Restart(ctx context.Context, name string, timeout int64) error

	// Pause a container.
	Pause(ctx context.Context, name string) error

	// Unpause a container.
	Unpause(ctx context.Context, name string) error

	// Using a stream to get stats of a container.
	StreamStats(ctx context.Context, name string, config *ContainerStatsConfig) error

	// Stats of a container.
	Stats(ctx context.Context, name string) (*containerdtypes.Metric, *cgroups.Metrics, error)

	// AttachContainerIO attach stream to container IO.
	AttachContainerIO(ctx context.Context, name string, cfg *streams.AttachConfig) error

	// AttachCRILog attach cri log to container IO.
	AttachCRILog(ctx context.Context, name string, path string) error

	// Rename renames a container.
	Rename(ctx context.Context, oldName string, newName string) error

	// Update updates the configurations of a container.
	Update(ctx context.Context, name string, config *types.UpdateConfig) error

	// Upgrade upgrades a container with new image and args.
	Upgrade(ctx context.Context, name string, config *types.ContainerUpgradeConfig) error

	// Top lists the processes running inside of the given container
	Top(ctx context.Context, name string, psArgs string) (*types.ContainerProcessList, error)

	// Resize resizes the size of container tty.
	Resize(ctx context.Context, name string, opts types.ResizeOptions) error

	// Remove removes a container, it may be running or stopped and so on.
	Remove(ctx context.Context, name string, option *types.ContainerRemoveOptions) error

	// Wait stops processing until the given container is stopped.
	Wait(ctx context.Context, name string) (types.ContainerWaitOKBody, error)

	// CreateExec creates exec process's environment.
	CreateExec(ctx context.Context, name string, config *types.ExecCreateConfig) (string, error)

	// StartExec executes a new process in container.
	StartExec(ctx context.Context, execid string, cfg *streams.AttachConfig, timeout int) error

	// InspectExec returns low-level information about exec command.
	InspectExec(ctx context.Context, execid string) (*types.ContainerExecInspect, error)

	// GetExecConfig returns execonfig of a exec process inside container.
	GetExecConfig(ctx context.Context, execid string) (*ContainerExecConfig, error)

	// CheckExecExist check if exec process `name` exist
	CheckExecExist(ctx context.Context, name string) error

	// ResizeExec resizes the size of exec process's tty.
	ResizeExec(ctx context.Context, execid string, opts types.ResizeOptions) error

	// Connect is used to connect a container to a network.
	Connect(ctx context.Context, name string, networkIDOrName string, epConfig *types.EndpointSettings) error

	// Disconnect disconnects the given container from
	// given network
	Disconnect(ctx context.Context, containerName, networkName string, force bool) error

	// Logs is used to return log created by the container.
	Logs(ctx context.Context, name string, logsOpt *types.ContainerLogsOptions) (<-chan *logger.LogMessage, bool, error)

	// NewSnapshotsSyncer creates a snapshot syncer.
	NewSnapshotsSyncer(snapshotStore *SnapshotStore, duration time.Duration) *SnapshotsSyncer

	// CreateCheckpoint creates a checkpoint from a running container
	CreateCheckpoint(ctx context.Context, name string, options *types.CheckpointCreateOptions) error

	// ListCheckpoint lists checkpoints from a container
	ListCheckpoint(ctx context.Context, name string, options *types.CheckpointListOptions) ([]string, error)

	// DeleteCheckpoint deletes a checkpoint from a container
	DeleteCheckpoint(ctx context.Context, name string, options *types.CheckpointDeleteOptions) error

	// Commit commits an image from a container.
	Commit(ctx context.Context, name string, options *types.ContainerCommitOptions) (*types.ContainerCommitResp, error)

	// StatPath stats the dir info at the specified path in the container.
	StatPath(ctx context.Context, name, path string) (stat *types.ContainerPathStat, err error)

	// ArchivePath return an archive and dir info at the specified path in the container.
	ArchivePath(ctx context.Context, name, path string) (content io.ReadCloser, stat *types.ContainerPathStat, err error)

	// ExtractToDir extracts the given archive at the specified path in the container.
	ExtractToDir(ctx context.Context, name, path string, copyUIDGID, noOverwriteDirNonDir bool, content io.Reader) error
}

ContainerMgr as an interface defines all operations against container. ContainerMgr's functionality could be divided into three parts: 1. regular container management; 2. container exec management; 3. container network management. 4. container copy management

type ContainerMonitor

type ContainerMonitor struct {
	// contains filtered or unexported fields
}

ContainerMonitor is used to monitor contianer's event.

func NewContainerMonitor

func NewContainerMonitor() *ContainerMonitor

NewContainerMonitor returns one ContainerMonitor object.

func (*ContainerMonitor) PostEvent

func (m *ContainerMonitor) PostEvent(ev *ContainerEvent)

PostEvent sends a event to monitor.

type ContainerRestartPolicy

type ContainerRestartPolicy types.RestartPolicy

ContainerRestartPolicy represents the policy is used to manage container.

func (ContainerRestartPolicy) IsAlways

func (p ContainerRestartPolicy) IsAlways() bool

IsAlways returns the container need to be restarted or not.

func (ContainerRestartPolicy) IsNone

func (p ContainerRestartPolicy) IsNone() bool

IsNone returns the container don't need to be restarted or not.

type ContainerStatsConfig

type ContainerStatsConfig struct {
	Stream    bool
	OutStream io.Writer
}

ContainerStatsConfig contains all configs on stats interface. This struct is only used in daemon side.

type CtrdImageInfo

type CtrdImageInfo struct {
	ID      digest.Digest
	Size    int64
	OCISpec ocispec.Image
}

CtrdImageInfo is used to cache the id, size and oci image information.

type ImageManager

type ImageManager struct {
	// DefaultRegistry is the default registry of daemon.
	// When users do not specify image repo in image name,
	// daemon will automatically pull images with DefaultRegistry and DefaultNamespace.
	DefaultRegistry string

	// DefaultNamespace is the default namespace used in DefaultRegistry.
	DefaultNamespace string

	// RegistryMirrors is a list of registry URLs that act as a mirror for the default registry.
	RegistryMirrors []string
	// contains filtered or unexported fields
}

ImageManager is an implementation of interface ImageMgr.

func NewImageManager

func NewImageManager(cfg *config.Config, client ctrd.APIClient, eventsService *events.Events, imagePlugin hookplugins.ImagePlugin) (*ImageManager, error)

NewImageManager initializes a brand new image manager.

func (*ImageManager) AddTag

func (mgr *ImageManager) AddTag(ctx context.Context, sourceImage string, targetTag string) error

AddTag adds the tag reference to the source image.

NOTE(fuwei): AddTag hacks the containerd metadata boltdb, which we add the reference into the containerd metadata boltdb with the existing image content. It means that the "tag" is primary reference in the pouchd.

For example,

pouch tag A B
pouch rmi A

The B is still there.

func (*ImageManager) CheckReference

func (mgr *ImageManager) CheckReference(ctx context.Context, idOrRef string) (actualID digest.Digest, actualRef reference.Named, primaryRef reference.Named, err error)

CheckReference returns image ID and actual reference.

func (*ImageManager) GetImage

func (mgr *ImageManager) GetImage(ctx context.Context, idOrRef string) (*types.ImageInfo, error)

GetImage returns imageInfo by reference.

func (*ImageManager) GetOCIImageConfig

func (mgr *ImageManager) GetOCIImageConfig(ctx context.Context, image string) (ocispec.ImageConfig, error)

GetOCIImageConfig returns the image config of OCI

func (*ImageManager) ImageHistory

func (mgr *ImageManager) ImageHistory(ctx context.Context, idOrRef string) ([]types.HistoryResultItem, error)

ImageHistory returns image history by reference.

func (*ImageManager) ListImages

func (mgr *ImageManager) ListImages(ctx context.Context, filter filters.Args) ([]types.ImageInfo, error)

ListImages lists images stored by containerd.

func (*ImageManager) ListReferences

func (mgr *ImageManager) ListReferences(ctx context.Context, imageID digest.Digest) ([]reference.Named, error)

ListReferences returns all references

func (*ImageManager) LoadImage

func (mgr *ImageManager) LoadImage(ctx context.Context, imageName string, tarstream io.ReadCloser) error

LoadImage loads images by the oci.v1 format tarstream.

func (*ImageManager) LogImageEvent

func (mgr *ImageManager) LogImageEvent(ctx context.Context, imageID, refName, action string)

LogImageEvent generates an event related to an image with only the default attributes

func (*ImageManager) LogImageEventWithAttributes

func (mgr *ImageManager) LogImageEventWithAttributes(ctx context.Context, imageID, refName, action string, attributes map[string]string)

LogImageEventWithAttributes generates an event related to an image with specific given attributes

func (*ImageManager) LookupImageReferences

func (mgr *ImageManager) LookupImageReferences(ref string) []string

LookupImageReferences find possible image reference list.

func (*ImageManager) PullImage

func (mgr *ImageManager) PullImage(ctx context.Context, ref string, authConfig *types.AuthConfig, out io.Writer) error

PullImage pulls images from specified registry.

func (*ImageManager) PushImage

func (mgr *ImageManager) PushImage(ctx context.Context, name, tag string, authConfig *types.AuthConfig, out io.Writer) error

PushImage pushes image to specified registry.

func (*ImageManager) RemoveImage

func (mgr *ImageManager) RemoveImage(ctx context.Context, idOrRef string, force bool) error

RemoveImage deletes a reference.

NOTE: if the reference is short ID or ID, should remove all the references.

func (*ImageManager) SaveImage

func (mgr *ImageManager) SaveImage(ctx context.Context, idOrRef string) (io.ReadCloser, error)

SaveImage saves image to the oci.v1 format tarstream.

func (*ImageManager) SearchImages

func (mgr *ImageManager) SearchImages(ctx context.Context, name, registry string, auth *types.AuthConfig) ([]types.SearchResultItem, error)

SearchImages searches imaged from specified registry.

func (*ImageManager) StoreImageReference

func (mgr *ImageManager) StoreImageReference(ctx context.Context, img containerd.Image) error

StoreImageReference updates image reference in memory store.

type ImageMgr

type ImageMgr interface {
	// LookupImageReferences find possible image reference list.
	LookupImageReferences(ref string) []string

	// PullImage pulls images from specified registry.
	PullImage(ctx context.Context, ref string, authConfig *types.AuthConfig, out io.Writer) error

	// PushImage pushes image to specified registry.
	PushImage(ctx context.Context, name, tag string, authConfig *types.AuthConfig, out io.Writer) error

	// GetImage returns imageInfo by reference or id.
	GetImage(ctx context.Context, idOrRef string) (*types.ImageInfo, error)

	// ListImages lists images stored by containerd.
	ListImages(ctx context.Context, filter filters.Args) ([]types.ImageInfo, error)

	// Search Images from specified registry.
	SearchImages(ctx context.Context, name, registry string, authConfig *types.AuthConfig) ([]types.SearchResultItem, error)

	// RemoveImage deletes an image by reference.
	RemoveImage(ctx context.Context, idOrRef string, force bool) error

	// AddTag creates target ref for source image.
	AddTag(ctx context.Context, sourceImage string, targetRef string) error

	// CheckReference returns imageID, actual reference and primary reference.
	CheckReference(ctx context.Context, idOrRef string) (digest.Digest, reference.Named, reference.Named, error)

	// ListReferences returns all references
	ListReferences(ctx context.Context, imageID digest.Digest) ([]reference.Named, error)

	// LoadImage creates a set of images by tarstream.
	LoadImage(ctx context.Context, imageName string, tarstream io.ReadCloser) error

	// SaveImage saves image to tarstream.
	SaveImage(ctx context.Context, idOrRef string) (io.ReadCloser, error)

	// ImageHistory returns image history by reference.
	ImageHistory(ctx context.Context, idOrRef string) ([]types.HistoryResultItem, error)

	// StoreImageReference update image reference.
	StoreImageReference(ctx context.Context, img containerd.Image) error

	// GetOCIImageConfig returns the image config of OCI
	GetOCIImageConfig(ctx context.Context, image string) (ocispec.ImageConfig, error)
}

ImageMgr as an interface defines all operations against images.

type ImageRemoveOption

type ImageRemoveOption struct {
	Force bool
}

ImageRemoveOption wraps the image remove interface params.

type NetworkManager

type NetworkManager struct {
	// contains filtered or unexported fields
}

NetworkManager is the default implement of interface NetworkMgr.

func NewNetworkManager

func NewNetworkManager(cfg *config.Config, store *meta.Store, ctrMgr ContainerMgr, eventsService *events.Events) (*NetworkManager, error)

NewNetworkManager creates a brand new network manager.

func (*NetworkManager) Controller

func (nm *NetworkManager) Controller() libnetwork.NetworkController

Controller returns the network controller.

func (*NetworkManager) Create

Create is used to create network.

func (*NetworkManager) EndpointCreate

func (nm *NetworkManager) EndpointCreate(ctx context.Context, endpoint *types.Endpoint) (string, error)

EndpointCreate is used to create network endpoint.

func (*NetworkManager) EndpointInfo

func (nm *NetworkManager) EndpointInfo(ctx context.Context, name string) (*types.Endpoint, error)

EndpointInfo returns the information of endpoint that specified name/id.

func (*NetworkManager) EndpointList

func (nm *NetworkManager) EndpointList(ctx context.Context) ([]*types.Endpoint, error)

EndpointList returns all endpoints.

func (*NetworkManager) EndpointRemove

func (nm *NetworkManager) EndpointRemove(ctx context.Context, endpoint *types.Endpoint) error

EndpointRemove is used to remove network endpoint.

func (*NetworkManager) Get

func (nm *NetworkManager) Get(ctx context.Context, idName string) (*types.Network, error)

Get returns the information of network for specified string that represent network name or ID. If network name is given, the network with same name is returned. If prefix of network ID is given, the network with same prefix is returned.

func (*NetworkManager) GetNetworkByName

func (nm *NetworkManager) GetNetworkByName(name string) (*types.Network, error)

GetNetworkByName returns the information of network that specified name.

func (*NetworkManager) GetNetworkByPartialID

func (nm *NetworkManager) GetNetworkByPartialID(partialID string) (*types.Network, error)

GetNetworkByPartialID returns the information of network that ID starts with the given prefix. If there are not matching networks, it fails with ErrNotfound. If there are multiple matching networks, it fails with ErrTooMany.

func (*NetworkManager) GetNetworkStats

func (nm *NetworkManager) GetNetworkStats(sandboxID string) (map[string]apitypes.NetworkStats, error)

GetNetworkStats returns the network stats of specific sandbox

func (*NetworkManager) GetNetworksByPartialID

func (nm *NetworkManager) GetNetworksByPartialID(partialID string) []*types.Network

GetNetworksByPartialID returns a list of networks that ID starts with the given prefix.

func (*NetworkManager) List

func (nm *NetworkManager) List(ctx context.Context, labels map[string]string) ([]*types.Network, error)

List returns all networks on this host.

func (*NetworkManager) LogNetworkEvent

func (nm *NetworkManager) LogNetworkEvent(ctx context.Context, nw libnetwork.Network, action string)

LogNetworkEvent generates an event related to a network with only the default attributes

func (*NetworkManager) Remove

func (nm *NetworkManager) Remove(ctx context.Context, name string) error

Remove is used to delete an existing network.

type NetworkMgr

type NetworkMgr interface {
	// Create is used to create network.
	Create(ctx context.Context, create apitypes.NetworkCreateConfig) (*types.Network, error)

	// Get returns the information of network that specified name/id.
	Get(ctx context.Context, name string) (*types.Network, error)

	// List returns all networks on this host.
	List(ctx context.Context, labels map[string]string) ([]*types.Network, error)

	// NetworkRemove is used to delete an existing network.
	Remove(ctx context.Context, name string) error

	// EndpointCreate is used to create network endpoint.
	EndpointCreate(ctx context.Context, endpoint *types.Endpoint) (string, error)

	// EndpointInfo returns the information of endpoint that specified name/id.
	EndpointInfo(ctx context.Context, name string) (*types.Endpoint, error)

	// EndpointList returns all endpoints.
	EndpointList(ctx context.Context) ([]*types.Endpoint, error)

	// EndpointRemove is used to remove network endpoint.
	EndpointRemove(ctx context.Context, endpoint *types.Endpoint) error

	// Controller returns the network controller.
	Controller() libnetwork.NetworkController

	// GetNetworkStats returns the network stats of specific sandbox
	GetNetworkStats(sandboxID string) (map[string]apitypes.NetworkStats, error)
}

NetworkMgr defines interface to manage container network.

type Snapshot

type Snapshot struct {
	// Key is the key of the snapshot
	Key string
	// Kind is the kind of the snapshot (active, committed, view)
	Kind snapshots.Kind
	// Size is the size of the snapshot in bytes.
	Size uint64
	// Inodes is the number of inodes used by the snapshot
	Inodes uint64
	// Timestamp is latest update time (in nanoseconds) of the snapshot
	// information.
	Timestamp int64
}

Snapshot contains the information about the snapshot.

type SnapshotStore

type SnapshotStore struct {
	// contains filtered or unexported fields
}

SnapshotStore stores all snapshots.

func NewSnapshotStore

func NewSnapshotStore() *SnapshotStore

NewSnapshotStore create a new snapshot store.

func (*SnapshotStore) Add

func (s *SnapshotStore) Add(sn Snapshot)

Add a snapshot into the store.

func (*SnapshotStore) Delete

func (s *SnapshotStore) Delete(key string)

Delete deletes the snapshot with specified key.

func (*SnapshotStore) Get

func (s *SnapshotStore) Get(key string) (Snapshot, error)

Get returns the snapshot with specified key. Returns error if the snapshot doesn't exist.

func (*SnapshotStore) List

func (s *SnapshotStore) List() []Snapshot

List lists all snapshots.

type SnapshotsSyncer

type SnapshotsSyncer struct {
	// contains filtered or unexported fields
}

SnapshotsSyncer syncs snapshot stats periodically.

func (*SnapshotsSyncer) Start

func (s *SnapshotsSyncer) Start()

Start starts the snapshots syncer.

func (*SnapshotsSyncer) Sync

func (s *SnapshotsSyncer) Sync() error

Sync updates the snapshots in the snapshot store.

type SpecWrapper

type SpecWrapper struct {
	// contains filtered or unexported fields
}

SpecWrapper wraps the container's specs and add manager operations.

type SystemManager

type SystemManager struct {
	// contains filtered or unexported fields
}

SystemManager is an instance of system management.

func NewSystemManager

func NewSystemManager(cfg *config.Config, store *meta.Store, imageManager ImageMgr, eventsService *events.Events) (*SystemManager, error)

NewSystemManager creates a brand new system manager.

func (*SystemManager) Auth

func (mgr *SystemManager) Auth(auth *types.AuthConfig) (string, error)

Auth to log in to a registry.

func (*SystemManager) Info

func (mgr *SystemManager) Info() (types.SystemInfo, error)

Info shows system information of daemon.

func (*SystemManager) SubscribeToEvents

func (mgr *SystemManager) SubscribeToEvents(ctx context.Context, since, until time.Time, filter filters.Args) ([]types.EventsMessage, <-chan *types.EventsMessage, <-chan error)

SubscribeToEvents returns to events on the exchange. Events are sent through the returned channel ch. If an error is encountered, it will be sent on channel errs and errs will be closed. To end the subscription, cancel the provided context.

func (*SystemManager) UpdateDaemon

func (mgr *SystemManager) UpdateDaemon(cfg *types.DaemonUpdateConfig) error

UpdateDaemon updates config of daemon, only label and image proxy are allowed.

func (*SystemManager) Version

func (mgr *SystemManager) Version() (types.SystemVersion, error)

Version shows version of daemon.

type SystemMgr

type SystemMgr interface {
	Info() (types.SystemInfo, error)
	Version() (types.SystemVersion, error)
	Auth(*types.AuthConfig) (string, error)
	UpdateDaemon(*types.DaemonUpdateConfig) error
	SubscribeToEvents(ctx context.Context, since, until time.Time, ef filters.Args) ([]types.EventsMessage, <-chan *types.EventsMessage, <-chan error)
}

SystemMgr as an interface defines all operations against host.

type VolumeManager

type VolumeManager struct {
	// contains filtered or unexported fields
}

VolumeManager is the default implement of interface VolumeMgr.

func NewVolumeManager

func NewVolumeManager(cfg volume.Config, eventsService *events.Events) (*VolumeManager, error)

NewVolumeManager creates a brand new volume manager.

func (*VolumeManager) Attach

func (vm *VolumeManager) Attach(ctx context.Context, name string, options map[string]string) (*types.Volume, error)

Attach is used to bind a volume to container.

func (*VolumeManager) Create

func (vm *VolumeManager) Create(ctx context.Context, name, driver string, options, labels map[string]string) (*types.Volume, error)

Create is used to create volume.

func (*VolumeManager) Detach

func (vm *VolumeManager) Detach(ctx context.Context, name string, options map[string]string) (*types.Volume, error)

Detach is used to unbind a volume from container.

func (*VolumeManager) Get

func (vm *VolumeManager) Get(ctx context.Context, name string) (*types.Volume, error)

Get returns the information of volume that specified name/id.

func (*VolumeManager) List

func (vm *VolumeManager) List(ctx context.Context, filter filters.Args) ([]*types.Volume, error)

List returns all volumes on this host.

func (*VolumeManager) LogVolumeEvent

func (vm *VolumeManager) LogVolumeEvent(ctx context.Context, volumeID, action string, attributes map[string]string)

LogVolumeEvent generates an event related to a volume

func (*VolumeManager) Path

func (vm *VolumeManager) Path(ctx context.Context, name string) (string, error)

Path returns the mount path of volume.

func (*VolumeManager) Remove

func (vm *VolumeManager) Remove(ctx context.Context, name string) error

Remove is used to delete an existing volume.

type VolumeMgr

type VolumeMgr interface {
	// Create is used to create volume.
	Create(ctx context.Context, name, driver string, options, labels map[string]string) (*types.Volume, error)

	// Get returns the information of volume that specified name/id.
	Get(ctx context.Context, name string) (*types.Volume, error)

	// List returns all volumes on this host.
	List(ctx context.Context, filter filters.Args) ([]*types.Volume, error)

	// Remove is used to delete an existing volume.
	Remove(ctx context.Context, name string) error

	// Path returns the mount path of volume.
	Path(ctx context.Context, name string) (string, error)

	// Attach is used to bind a volume to container.
	Attach(ctx context.Context, name string, options map[string]string) (*types.Volume, error)

	// Detach is used to unbind a volume from container.
	Detach(ctx context.Context, name string, options map[string]string) (*types.Volume, error)
}

VolumeMgr defines interface to manage container volume.

Jump to

Keyboard shortcuts

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