runc

package module
v1.1.2-deviation Latest Latest
Warning

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

Go to latest
Published: Sep 18, 2024 License: Apache-2.0 Imports: 22 Imported by: 0

README

go-runc

Build Status codecov

This is a package for consuming the runc binary in your Go applications. It tries to expose all the settings and features of the runc CLI. If there is something missing then add it, its opensource!

This needs runc @ a9610f2c0 or greater.

Docs

Docs can be found at godoc.org.

Project details

The go-runc is a containerd sub-project, licensed under the Apache 2.0 license. As a containerd sub-project, you will find the:

information in our containerd/project repository.

Documentation

Overview

Copyright The containerd Authors.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Index

Constants

This section is empty.

Variables

View Source
var DefaultCommand = "runc"

DefaultCommand is the default command for Runc

View Source
var ErrParseRuncVersion = errors.New("unable to parse runc version")

ErrParseRuncVersion is used when the runc version can't be parsed

Functions

func LeaveRunning

func LeaveRunning(args []string) []string

LeaveRunning keeps the container running after the checkpoint has been completed

func PreDump

func PreDump(args []string) []string

PreDump allows a pre-dump of the checkpoint to be made and completed later

func ReadPidFile

func ReadPidFile(path string) (int, error)

ReadPidFile reads the pid file at the provided path and returns the pid or an error if the read and conversion is unsuccessful

Types

type Blkio

type Blkio struct {
	IoServiceBytesRecursive []BlkioEntry `json:"ioServiceBytesRecursive,omitempty"`
	IoServicedRecursive     []BlkioEntry `json:"ioServicedRecursive,omitempty"`
	IoQueuedRecursive       []BlkioEntry `json:"ioQueueRecursive,omitempty"`
	IoServiceTimeRecursive  []BlkioEntry `json:"ioServiceTimeRecursive,omitempty"`
	IoWaitTimeRecursive     []BlkioEntry `json:"ioWaitTimeRecursive,omitempty"`
	IoMergedRecursive       []BlkioEntry `json:"ioMergedRecursive,omitempty"`
	IoTimeRecursive         []BlkioEntry `json:"ioTimeRecursive,omitempty"`
	SectorsRecursive        []BlkioEntry `json:"sectorsRecursive,omitempty"`
}

type BlkioEntry

type BlkioEntry struct {
	Major uint64 `json:"major,omitempty"`
	Minor uint64 `json:"minor,omitempty"`
	Op    string `json:"op,omitempty"`
	Value uint64 `json:"value,omitempty"`
}

type CPUSet

type CPUSet struct {
	CPUs                  []uint16 `json:"cpus,omitempty"`
	CPUExclusive          uint64   `json:"cpu_exclusive"`
	Mems                  []uint16 `json:"mems,omitempty"`
	MemHardwall           uint64   `json:"mem_hardwall"`
	MemExclusive          uint64   `json:"mem_exclusive"`
	MemoryMigrate         uint64   `json:"memory_migrate"`
	MemorySpreadPage      uint64   `json:"memory_spread_page"`
	MemorySpreadSlab      uint64   `json:"memory_spread_slab"`
	MemoryPressure        uint64   `json:"memory_pressure"`
	SchedLoadBalance      uint64   `json:"sched_load_balance"`
	SchedRelaxDomainLevel int64    `json:"sched_relax_domain_level"`
}

type CgroupMode

type CgroupMode string

CgroupMode defines the cgroup mode used for checkpointing

const (
	// Soft is the "soft" cgroup mode
	Soft CgroupMode = "soft"
	// Full is the "full" cgroup mode
	Full CgroupMode = "full"
	// Strict is the "strict" cgroup mode
	Strict CgroupMode = "strict"
)

type CheckpointAction

type CheckpointAction func([]string) []string

CheckpointAction represents specific actions executed during checkpoint/restore

type CheckpointOpts

type CheckpointOpts struct {
	// ImagePath is the path for saving the criu image file
	ImagePath string
	// WorkDir is the working directory for criu
	WorkDir string
	// ParentPath is the path for previous image files from a pre-dump
	ParentPath string
	// AllowOpenTCP allows open tcp connections to be checkpointed
	AllowOpenTCP bool
	// AllowExternalUnixSockets allows external unix sockets to be checkpointed
	AllowExternalUnixSockets bool
	// AllowTerminal allows the terminal(pty) to be checkpointed with a container
	AllowTerminal bool
	// CriuPageServer is the address:port for the criu page server
	CriuPageServer string
	// FileLocks handle file locks held by the container
	FileLocks bool
	// Cgroups is the cgroup mode for how to handle the checkpoint of a container's cgroups
	Cgroups CgroupMode
	// EmptyNamespaces creates a namespace for the container but does not save its properties
	// Provide the namespaces you wish to be checkpointed without their settings on restore
	EmptyNamespaces []string
	// LazyPages uses userfaultfd to lazily restore memory pages
	LazyPages bool
	// StatusFile is the file criu writes \0 to once lazy-pages is ready
	StatusFile *os.File
	ExtraArgs  []string
}

CheckpointOpts holds the options for performing a criu checkpoint using runc

type ConsoleSocket

type ConsoleSocket interface {
	Path() string
}

ConsoleSocket handles the path of the socket for console access

type Container

type Container struct {
	ID          string            `json:"id"`
	Pid         int               `json:"pid"`
	Status      string            `json:"status"`
	Bundle      string            `json:"bundle"`
	Rootfs      string            `json:"rootfs"`
	Created     time.Time         `json:"created"`
	Annotations map[string]string `json:"annotations"`
}

Container hold information for a runc container

type Cpu

type Cpu struct {
	Usage      CpuUsage   `json:"usage,omitempty"`
	Throttling Throttling `json:"throttling,omitempty"`
}

type CpuUsage

type CpuUsage struct {
	// Units: nanoseconds.
	Total        uint64   `json:"total,omitempty"`
	Percpu       []uint64 `json:"percpu,omitempty"`
	PercpuKernel []uint64 `json:"percpu_kernel,omitempty"`
	PercpuUser   []uint64 `json:"percpu_user,omitempty"`
	Kernel       uint64   `json:"kernel"`
	User         uint64   `json:"user"`
}

type CreateOpts

type CreateOpts struct {
	IO
	// PidFile is a path to where a pid file should be created
	PidFile       string
	ConsoleSocket ConsoleSocket
	Detach        bool
	NoPivot       bool
	NoNewKeyring  bool
	ExtraFiles    []*os.File
	Started       chan<- int
	ExtraArgs     []string
}

CreateOpts holds all the options information for calling runc with supported options

type DeleteOpts

type DeleteOpts struct {
	Force     bool
	ExtraArgs []string
}

DeleteOpts holds the deletion options for calling `runc delete`

type Event

type Event struct {
	// Type are the event type generated by runc
	// If the type is "error" then check the Err field on the event for
	// the actual error
	Type  string `json:"type"`
	ID    string `json:"id"`
	Stats *Stats `json:"data,omitempty"`
	// Err has a read error if we were unable to decode the event from runc
	Err error `json:"-"`
}

Event is a struct to pass runc event information

type ExecOpts

type ExecOpts struct {
	IO
	PidFile       string
	ConsoleSocket ConsoleSocket
	Detach        bool
	Started       chan<- int
	ExtraArgs     []string
}

ExecOpts holds optional settings when starting an exec process with runc

type Exit

type Exit struct {
	Timestamp time.Time
	Pid       int
	Status    int
}

Exit holds the exit information from a process

type ExitError

type ExitError struct {
	Status int
}

ExitError holds the status return code when a process exits with an error code

func (*ExitError) Error

func (e *ExitError) Error() string

type Format

type Format string

Format is the type of log formatting options available

const (

	// JSON represents the JSON format
	JSON Format = "json"
	// Text represents plain text format
	Text Format = "text"
)

type Hugetlb

type Hugetlb struct {
	Usage   uint64 `json:"usage,omitempty"`
	Max     uint64 `json:"max,omitempty"`
	Failcnt uint64 `json:"failcnt"`
}

type IO

type IO interface {
	io.Closer
	Stdin() io.WriteCloser
	Stdout() io.ReadCloser
	Stderr() io.ReadCloser
	Set(*exec.Cmd)
}

IO is the terminal IO interface

func NewNullIO

func NewNullIO() (IO, error)

NewNullIO returns IO setup for /dev/null use with runc

func NewPipeIO

func NewPipeIO(uid, gid int, opts ...IOOpt) (i IO, err error)

NewPipeIO creates pipe pairs to be used with runc. It is not implemented on Windows.

func NewSTDIO

func NewSTDIO() (IO, error)

NewSTDIO returns I/O setup for standard OS in/out/err usage

type IOOpt

type IOOpt func(*IOOption)

IOOpt sets I/O creation options

type IOOption

type IOOption struct {
	OpenStdin  bool
	OpenStdout bool
	OpenStderr bool
}

IOOption holds I/O creation options

type IntelRdt

type IntelRdt struct {
	// The read-only L3 cache information
	L3CacheInfo *L3CacheInfo `json:"l3_cache_info,omitempty"`

	// The read-only L3 cache schema in root
	L3CacheSchemaRoot string `json:"l3_cache_schema_root,omitempty"`

	// The L3 cache schema in 'container_id' group
	L3CacheSchema string `json:"l3_cache_schema,omitempty"`

	// The read-only memory bandwidth information
	MemBwInfo *MemBwInfo `json:"mem_bw_info,omitempty"`

	// The read-only memory bandwidth schema in root
	MemBwSchemaRoot string `json:"mem_bw_schema_root,omitempty"`

	// The memory bandwidth schema in 'container_id' group
	MemBwSchema string `json:"mem_bw_schema,omitempty"`

	// The memory bandwidth monitoring statistics from NUMA nodes in 'container_id' group
	MBMStats *[]intelrdt.MBMNumaNodeStats `json:"mbm_stats,omitempty"`

	// The cache monitoring technology statistics from NUMA nodes in 'container_id' group
	CMTStats *[]intelrdt.CMTNumaNodeStats `json:"cmt_stats,omitempty"`
}

type KillOpts

type KillOpts struct {
	All       bool
	ExtraArgs []string
}

KillOpts specifies options for killing a container and its processes

type L3CacheInfo

type L3CacheInfo struct {
	CbmMask    string `json:"cbm_mask,omitempty"`
	MinCbmBits uint64 `json:"min_cbm_bits,omitempty"`
	NumClosids uint64 `json:"num_closids,omitempty"`
}

type MemBwInfo

type MemBwInfo struct {
	BandwidthGran uint64 `json:"bandwidth_gran,omitempty"`
	DelayLinear   uint64 `json:"delay_linear,omitempty"`
	MinBandwidth  uint64 `json:"min_bandwidth,omitempty"`
	NumClosids    uint64 `json:"num_closids,omitempty"`
}

type Memory

type Memory struct {
	Cache     uint64            `json:"cache,omitempty"`
	Usage     MemoryEntry       `json:"usage,omitempty"`
	Swap      MemoryEntry       `json:"swap,omitempty"`
	Kernel    MemoryEntry       `json:"kernel,omitempty"`
	KernelTCP MemoryEntry       `json:"kernelTCP,omitempty"`
	Raw       map[string]uint64 `json:"raw,omitempty"`
}

type MemoryEntry

type MemoryEntry struct {
	Limit   uint64 `json:"limit"`
	Usage   uint64 `json:"usage,omitempty"`
	Max     uint64 `json:"max,omitempty"`
	Failcnt uint64 `json:"failcnt"`
}

type NetworkInterface

type NetworkInterface struct {
	// Name is the name of the network interface.
	Name string

	RxBytes   uint64
	RxPackets uint64
	RxErrors  uint64
	RxDropped uint64
	TxBytes   uint64
	TxPackets uint64
	TxErrors  uint64
	TxDropped uint64
}

type Pids

type Pids struct {
	Current uint64 `json:"current,omitempty"`
	Limit   uint64 `json:"limit,omitempty"`
}

type ProcessMonitor

type ProcessMonitor interface {
	Start(*exec.Cmd) (chan Exit, error)
	StartLocked(*exec.Cmd) (chan Exit, error)
	Wait(*exec.Cmd, chan Exit) (int, error)
}

ProcessMonitor is an interface for process monitoring.

It allows daemons using go-runc to have a SIGCHLD handler to handle exits without introducing races between the handler and go's exec.Cmd.

ProcessMonitor also provides a StartLocked method which is similar to Start, but locks the goroutine used to start the process to an OS thread (for example: when Pdeathsig is set).

var Monitor ProcessMonitor = &defaultMonitor{}

Monitor is the default ProcessMonitor for handling runc process exit

type RestoreOpts

type RestoreOpts struct {
	CheckpointOpts
	IO

	Detach        bool
	PidFile       string
	NoSubreaper   bool
	NoPivot       bool
	ConsoleSocket ConsoleSocket
	ExtraArgs     []string
}

RestoreOpts holds the options for performing a criu restore using runc

type Runc

type Runc struct {
	// Command overrides the name of the runc binary. If empty, DefaultCommand
	// is used.
	Command   string
	Root      string
	Debug     bool
	Log       string
	LogFormat Format
	// PdeathSignal sets a signal the child process will receive when the
	// parent dies.
	//
	// When Pdeathsig is set, command invocations will call runtime.LockOSThread
	// to prevent OS thread termination from spuriously triggering the
	// signal. See https://github.com/golang/go/issues/27505 and
	// https://github.com/golang/go/blob/126c22a09824a7b52c019ed9a1d198b4e7781676/src/syscall/exec_linux.go#L48-L51
	//
	// A program with GOMAXPROCS=1 might hang because of the use of
	// runtime.LockOSThread. Callers should ensure they retain at least one
	// unlocked thread.
	PdeathSignal syscall.Signal // using syscall.Signal to allow compilation on non-unix (unix.Syscall is an alias for syscall.Signal)
	Setpgid      bool

	// Criu sets the path to the criu binary used for checkpoint and restore.
	//
	// Deprecated: runc option --criu is now ignored (with a warning), and the
	// option will be removed entirely in a future release. Users who need a non-
	// standard criu binary should rely on the standard way of looking up binaries
	// in $PATH.
	Criu          string
	SystemdCgroup bool
	Rootless      *bool // nil stands for "auto"
	ExtraArgs     []string
}

Runc is the client to the runc cli

func (*Runc) Checkpoint

func (r *Runc) Checkpoint(context context.Context, id string, opts *CheckpointOpts, actions ...CheckpointAction) error

Checkpoint allows you to checkpoint a container using criu

func (*Runc) Create

func (r *Runc) Create(context context.Context, id, bundle string, opts *CreateOpts) error

Create creates a new container and returns its pid if it was created successfully

func (*Runc) Delete

func (r *Runc) Delete(context context.Context, id string, opts *DeleteOpts) error

Delete deletes the container

func (*Runc) Events

func (r *Runc) Events(context context.Context, id string, interval time.Duration) (chan *Event, error)

Events returns an event stream from runc for a container with stats and OOM notifications

func (*Runc) Exec

func (r *Runc) Exec(context context.Context, id string, spec specs.Process, opts *ExecOpts) error

Exec executes an additional process inside the container based on a full OCI Process specification

func (*Runc) Features

func (r *Runc) Features(context context.Context) (*features.Features, error)

Features shows the features implemented by the runtime.

Availability:

func (*Runc) Kill

func (r *Runc) Kill(context context.Context, id string, sig int, opts *KillOpts) error

Kill sends the specified signal to the container

func (*Runc) List

func (r *Runc) List(context context.Context) ([]*Container, error)

List returns all containers created inside the provided runc root directory

func (*Runc) Pause

func (r *Runc) Pause(context context.Context, id string) error

Pause the container with the provided id

func (*Runc) Ps

func (r *Runc) Ps(context context.Context, id string) ([]int, error)

Ps lists all the processes inside the container returning their pids

func (*Runc) Restore

func (r *Runc) Restore(context context.Context, id, bundle string, opts *RestoreOpts) (int, error)

Restore restores a container with the provide id from an existing checkpoint

func (*Runc) Resume

func (r *Runc) Resume(context context.Context, id string) error

Resume the container with the provided id

func (*Runc) Run

func (r *Runc) Run(context context.Context, id, bundle string, opts *CreateOpts) (int, error)

Run runs the create, start, delete lifecycle of the container and returns its exit status after it has exited

func (*Runc) Start

func (r *Runc) Start(context context.Context, id string) error

Start will start an already created container

func (*Runc) State

func (r *Runc) State(context context.Context, id string) (*Container, error)

State returns the state for the container provided by id

func (*Runc) Stats

func (r *Runc) Stats(context context.Context, id string) (*Stats, error)

Stats return the stats for a container like cpu, memory, and io

func (*Runc) Top

func (r *Runc) Top(context context.Context, id string, psOptions string) (*TopResults, error)

Top lists all the processes inside the container returning the full ps data

func (*Runc) Update

func (r *Runc) Update(context context.Context, id string, resources *specs.LinuxResources) error

Update updates the current container with the provided resource spec

func (*Runc) Version

func (r *Runc) Version(context context.Context) (Version, error)

Version returns the runc and runtime-spec versions

type Socket

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

Socket is a unix socket that accepts the pty master created by runc

func NewConsoleSocket

func NewConsoleSocket(path string) (*Socket, error)

NewConsoleSocket creates a new unix socket at the provided path to accept a pty master created by runc for use by the container

func NewTempConsoleSocket

func NewTempConsoleSocket() (*Socket, error)

NewTempConsoleSocket returns a temp console socket for use with a container On Close(), the socket is deleted

func (*Socket) Close

func (c *Socket) Close() error

Close closes the unix socket

func (*Socket) Path

func (c *Socket) Path() string

Path returns the path to the unix socket on disk

func (*Socket) ReceiveMaster

func (c *Socket) ReceiveMaster() (console.Console, error)

ReceiveMaster blocks until the socket receives the pty master

type StartCloser

type StartCloser interface {
	CloseAfterStart() error
}

StartCloser is an interface to handle IO closure after start

type Stats

type Stats struct {
	CPU               Cpu                 `json:"cpu"`
	CPUSet            CPUSet              `json:"cpuset"`
	Memory            Memory              `json:"memory"`
	Pids              Pids                `json:"pids"`
	Blkio             Blkio               `json:"blkio"`
	Hugetlb           map[string]Hugetlb  `json:"hugetlb"`
	IntelRdt          IntelRdt            `json:"intel_rdt"`
	NetworkInterfaces []*NetworkInterface `json:"network_interfaces"`
}

stats is the runc specific stats structure for stability when encoding and decoding stats.

type Throttling

type Throttling struct {
	Periods          uint64 `json:"periods,omitempty"`
	ThrottledPeriods uint64 `json:"throttledPeriods,omitempty"`
	ThrottledTime    uint64 `json:"throttledTime,omitempty"`
}

type TopResults

type TopResults struct {
	// Processes running in the container, where each is process is an array of values corresponding to the headers
	Processes [][]string `json:"Processes"`

	// Headers are the names of the columns
	Headers []string `json:"Headers"`
}

TopResults represents the structured data of the full ps output

func ParsePSOutput

func ParsePSOutput(output []byte) (*TopResults, error)

ParsePSOutput parses the runtime's ps raw output and returns a TopResults

type Version

type Version struct {
	Runc   string
	Commit string
	Spec   string
}

Version represents the runc version information

Jump to

Keyboard shortcuts

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