cgroups
packagemoduleThis package is not in the latest version of its module.
Details
Validgo.mod file
The Go module system was introduced in Go 1.11 and is the official dependency management solution for Go.
Redistributable license
Redistributable licenses place minimal restrictions on how software can be used, modified, and redistributed.
Tagged version
Modules with tagged versions give importers more predictable builds.
Stable version
When a project reaches major version v1 it is considered stable.
- Learn more about best practices
Repository
Links
README¶
OCI Project Template
Useful boilerplate and organizational information for all OCI projects.
Documentation¶
Index¶
- Constants
- Variables
- func ConvertBlkIOToIOWeightValue(blkIoWeight uint16) uint64
- func ConvertCPUSharesToCgroupV2Value(cpuShares uint64) uint64
- func ConvertMemorySwapToCgroupV2Value(memorySwap, memory int64) (int64, error)
- func FindCgroupMountpoint(cgroupPath, subsystem string) (string, error)
- func FindCgroupMountpointAndRoot(cgroupPath, subsystem string) (string, string, error)
- func GetAllPids(path string) ([]int, error)
- func GetAllSubsystems() ([]string, error)
- func GetOwnCgroup(subsystem string) (string, error)
- func GetOwnCgroupPath(subsystem string) (string, error)
- func GetPids(dir string) ([]int, error)
- func HugePageSizes() []string
- func IsCgroup2HybridMode() bool
- func IsCgroup2UnifiedMode() bool
- func IsNotFound(err error) bool
- func NewNotFoundError(sub string) error
- func OpenFile(dir, file string, flags int) (*os.File, error)
- func ParseCgroupFile(path string) (map[string]string, error)
- func PathExists(path string) bool
- func ReadFile(dir, file string) (string, error)
- func RemovePath(path string) error
- func RemovePaths(paths map[string]string) (err error)
- func WriteCgroupProc(dir string, pid int) error
- func WriteFile(dir, file, data string) error
- func WriteFileByLine(dir, file, data string) error
- type BlkioStatEntry
- type BlkioStats
- type BlockIODevice
- type BurstData
- type CPUSetStats
- type Cgroup
- type CpuStats
- type CpuUsage
- type FreezerState
- type HugepageLimit
- type HugetlbStats
- type IfPrioMap
- type LinuxRdma
- type Manager
- type MemoryData
- type MemoryStats
- type MiscStats
- type Mount
- type NotFoundError
- type PSIData
- type PSIStats
- type PageStats
- type PageUsageByNUMA
- type PageUsageByNUMAInner
- type PidsStats
- type RdmaEntry
- type RdmaStats
- type Resources
- type Stats
- type ThrottleDevice
- type ThrottlingData
- type WeightDevice
Constants¶
const (CgroupNamePrefix = "name=")
const (CgroupProcesses = "cgroup.procs")
Variables¶
var (// ErrDevicesUnsupported is an error returned when a cgroup manager// is not configured to set device rules.ErrDevicesUnsupported =errors.New("cgroup manager is not configured to set device rules")// ErrRootless is returned by [Manager.Apply] when there is an error// creating cgroup directory, and cgroup.Rootless is set. In general,// this error is to be ignored.ErrRootless =errors.New("cgroup manager can not access cgroup (rootless container)")// DevicesSetV1 and DevicesSetV2 are functions to set devices for// cgroup v1 and v2, respectively. Unless// [github.com/opencontainers/cgroups/devices]// package is imported, it is set to nil, so cgroup managers can't// manage devices.DevicesSetV1 func(pathstring, r *Resources)errorDevicesSetV2 func(pathstring, r *Resources)error)
var (ErrV1NoUnified =errors.New("invalid configuration: cannot use unified on cgroup v1"))
var (// TestMode is set to true by unit tests that need "fake" cgroupfs.TestModebool)
Functions¶
funcConvertBlkIOToIOWeightValue¶
Since the OCI spec is designed for cgroup v1, in some casesthere is need to convert from the cgroup v1 configuration to cgroup v2the formula for BlkIOWeight to IOWeight is y = (1 + (x - 10) * 9999 / 990)convert linearly from [10-1000] to [1-10000]
funcConvertCPUSharesToCgroupV2Value¶
ConvertCPUSharesToCgroupV2Value converts CPU shares, used by cgroup v1,to CPU weight, used by cgroup v2.
Cgroup v1 CPU shares has a range of [2^1...2^18], i.e. [2...262144],and the default value is 1024.
Cgroup v2 CPU weight has a range of [10^0...10^4], i.e. [1...10000],and the default value is 100.
funcConvertMemorySwapToCgroupV2Value¶
ConvertMemorySwapToCgroupV2Value converts MemorySwap value from OCI specfor use by cgroup v2 drivers. A conversion is needed since Resources.MemorySwapis defined as memory+swap combined, while in cgroup v2 swap is a separate value,so we need to subtract memory from it where it makes sense.
funcGetAllPids¶
GetAllPids returns all pids from the cgroup identified by path, and all itssub-cgroups.
funcGetAllSubsystems¶
GetAllSubsystems returns all the cgroup subsystems supported by the kernel
funcGetOwnCgroup¶
GetOwnCgroup returns the relative path to the cgroup docker is running in.
funcHugePageSizes¶
func HugePageSizes() []string
funcIsCgroup2HybridMode¶
func IsCgroup2HybridMode()bool
IsCgroup2HybridMode returns whether we are running in cgroup v2 hybrid mode.
funcIsCgroup2UnifiedMode¶
func IsCgroup2UnifiedMode()bool
IsCgroup2UnifiedMode returns whether we are running in cgroup v2 unified mode.
funcIsNotFound¶
funcOpenFile¶
OpenFile opens a cgroup file in a given dir with given flags.It is supposed to be used for cgroup files only, and returnsan error if the file is not a cgroup file.
Arguments dir and file are joined together to form an absolute pathto a file being opened.
funcParseCgroupFile¶
ParseCgroupFile parses the given cgroup file, typically /proc/self/cgroupor /proc/<pid>/cgroup, into a map of subsystems to cgroup paths, e.g.
"cpu": "/user.slice/user-1000.slice""pids": "/user.slice/user-1000.slice"
etc.
Note that for cgroup v2 unified hierarchy, there are no per-controllercgroup paths, so the resulting map will have a single element where the keyis empty string ("") and the value is the cgroup path the <pid> is in.
funcPathExists¶
funcReadFile¶
ReadFile reads data from a cgroup file in dir.It is supposed to be used for cgroup files only.
funcRemovePath¶
RemovePath aims to remove cgroup path. It does so recursively,by removing any subdirectories (sub-cgroups) first.
funcRemovePaths¶
RemovePaths iterates over the provided paths removing them.
funcWriteCgroupProc¶
WriteCgroupProc writes the specified pid into the cgroup's cgroup.procs file
funcWriteFile¶
WriteFile writes data to a cgroup file in dir.It is supposed to be used for cgroup files only.
funcWriteFileByLine¶
WriteFileByLine is the same as WriteFile, except if data contains newlines,it is written line by line.
Types¶
typeBlkioStatEntry¶
typeBlkioStats¶
type BlkioStats struct {// number of bytes transferred to and from the block deviceIoServiceBytesRecursive []BlkioStatEntry `json:"io_service_bytes_recursive,omitempty"`IoServicedRecursive []BlkioStatEntry `json:"io_serviced_recursive,omitempty"`IoQueuedRecursive []BlkioStatEntry `json:"io_queue_recursive,omitempty"`IoServiceTimeRecursive []BlkioStatEntry `json:"io_service_time_recursive,omitempty"`IoWaitTimeRecursive []BlkioStatEntry `json:"io_wait_time_recursive,omitempty"`IoMergedRecursive []BlkioStatEntry `json:"io_merged_recursive,omitempty"`IoTimeRecursive []BlkioStatEntry `json:"io_time_recursive,omitempty"`SectorsRecursive []BlkioStatEntry `json:"sectors_recursive,omitempty"`PSI *PSIStats `json:"psi,omitempty"`}
typeBlockIODevice¶
type BlockIODevice struct {// Major is the device's major numberMajorint64 `json:"major"`// Minor is the device's minor numberMinorint64 `json:"minor"`}
BlockIODevice holds major:minor format supported in blkio cgroup.
typeCPUSetStats¶
type CPUSetStats struct {// List of the physical numbers of the CPUs on which processes// in that cpuset are allowed to executeCPUs []uint16 `json:"cpus,omitempty"`// cpu_exclusive flagCPUExclusiveuint64 `json:"cpu_exclusive"`// List of memory nodes on which processes in that cpuset// are allowed to allocate memoryMems []uint16 `json:"mems,omitempty"`// mem_hardwall flagMemHardwalluint64 `json:"mem_hardwall"`// mem_exclusive flagMemExclusiveuint64 `json:"mem_exclusive"`// memory_migrate flagMemoryMigrateuint64 `json:"memory_migrate"`// memory_spread page flagMemorySpreadPageuint64 `json:"memory_spread_page"`// memory_spread slab flagMemorySpreadSlabuint64 `json:"memory_spread_slab"`// memory_pressureMemoryPressureuint64 `json:"memory_pressure"`// sched_load balance flagSchedLoadBalanceuint64 `json:"sched_load_balance"`// sched_relax_domain_levelSchedRelaxDomainLevelint64 `json:"sched_relax_domain_level"`}
typeCgroup¶
type Cgroup struct {// Name specifies the name of the cgroupNamestring `json:"name,omitempty"`// Parent specifies the name of parent of cgroup or sliceParentstring `json:"parent,omitempty"`// Path specifies the path to cgroups that are created and/or joined by the container.// The path is assumed to be relative to the host system cgroup mountpoint.Pathstring `json:"path,omitempty"`// ScopePrefix describes prefix for the scope name.ScopePrefixstring `json:"scope_prefix,omitempty"`// Resources contains various cgroups settings to apply.*Resources// Systemd tells if systemd should be used to manage cgroups.Systemdbool `json:"Systemd,omitempty"`// SystemdProps are any additional properties for systemd,// derived from org.systemd.property.xxx annotations.// Ignored unless systemd is used for managing cgroups.SystemdProps []systemdDbus.Property `json:"-"`// Rootless tells if rootless cgroups should be used.Rootlessbool `json:"Rootless,omitempty"`// The host UID that should own the cgroup, or nil to accept// the default ownership. This should only be set when the// cgroupfs is to be mounted read/write.// Not all cgroup manager implementations support changing// the ownership.OwnerUID *int `json:"owner_uid,omitempty"`}
Cgroup holds properties of a cgroup on Linux.
typeCpuStats¶
type CpuStats struct {CpuUsageCpuUsage `json:"cpu_usage,omitempty"`ThrottlingDataThrottlingData `json:"throttling_data,omitempty"`PSI *PSIStats `json:"psi,omitempty"`BurstDataBurstData `json:"burst_data,omitempty"`}
typeCpuUsage¶
type CpuUsage struct {// Total CPU time consumed.// Units: nanoseconds.TotalUsageuint64 `json:"total_usage,omitempty"`// Total CPU time consumed per core.// Units: nanoseconds.PercpuUsage []uint64 `json:"percpu_usage,omitempty"`// CPU time consumed per core in kernel mode// Units: nanoseconds.PercpuUsageInKernelmode []uint64 `json:"percpu_usage_in_kernelmode"`// CPU time consumed per core in user mode// Units: nanoseconds.PercpuUsageInUsermode []uint64 `json:"percpu_usage_in_usermode"`// Time spent by tasks of the cgroup in kernel mode.// Units: nanoseconds.UsageInKernelmodeuint64 `json:"usage_in_kernelmode"`// Time spent by tasks of the cgroup in user mode.// Units: nanoseconds.UsageInUsermodeuint64 `json:"usage_in_usermode"`}
CpuUsage denotes the usage of a CPU.All CPU stats are aggregate since container inception.
typeFreezerState¶
type FreezerStatestring
const (UndefinedFreezerState = ""FrozenFreezerState = "FROZEN"ThawedFreezerState = "THAWED")
typeHugepageLimit¶
typeHugetlbStats¶
typeIfPrioMap¶
func (*IfPrioMap)CgroupString¶
typeLinuxRdma¶
type LinuxRdma struct {// Maximum number of HCA handles that can be opened. Default is "no limit".HcaHandles *uint32 `json:"hca_handles,omitempty"`// Maximum number of HCA objects that can be created. Default is "no limit".HcaObjects *uint32 `json:"hca_objects,omitempty"`}
LinuxRdma for Linux cgroup 'rdma' resource management (Linux 4.11)
typeManager¶
type Manager interface {// Apply creates a cgroup, if not yet created, and adds a process// with the specified pid into that cgroup. A special value of -1// can be used to merely create a cgroup.Apply(pidint)error// GetPids returns the PIDs of all processes inside the cgroup.GetPids() ([]int,error)// GetAllPids returns the PIDs of all processes inside the cgroup// any all its sub-cgroups.GetAllPids() ([]int,error)// GetStats returns cgroups statistics.GetStats() (*Stats,error)// Freeze sets the freezer cgroup to the specified state.Freeze(stateFreezerState)error// Destroy removes cgroup.Destroy()error// Path returns a cgroup path to the specified controller/subsystem.// For cgroupv2, the argument is unused and can be empty.Path(string)string// Set sets cgroup resources parameters/limits. If the argument is nil,// the resources specified during Manager creation (or the previous call// to Set) are used.Set(r *Resources)error// GetPaths returns cgroup path(s) to save in a state file in order to// restore later.//// For cgroup v1, a key is cgroup subsystem name, and the value is the// path to the cgroup for this subsystem.//// For cgroup v2 unified hierarchy, a key is "", and the value is the// unified path.GetPaths() map[string]string// GetCgroups returns the cgroup data as configured.GetCgroups() (*Cgroup,error)// GetFreezerState retrieves the current FreezerState of the cgroup.GetFreezerState() (FreezerState,error)// Exists returns whether the cgroup path exists or not.Exists()bool// OOMKillCount reports OOM kill count for the cgroup.OOMKillCount() (uint64,error)}
typeMemoryData¶
typeMemoryStats¶
type MemoryStats struct {// memory used for cacheCacheuint64 `json:"cache,omitempty"`// usage of memoryUsageMemoryData `json:"usage,omitempty"`// usage of memory + swapSwapUsageMemoryData `json:"swap_usage,omitempty"`// usage of swap onlySwapOnlyUsageMemoryData `json:"swap_only_usage,omitempty"`// usage of kernel memoryKernelUsageMemoryData `json:"kernel_usage,omitempty"`// usage of kernel TCP memoryKernelTCPUsageMemoryData `json:"kernel_tcp_usage,omitempty"`// usage of memory pages by NUMA node// see chapter 5.6 of memory controller documentationPageUsageByNUMAPageUsageByNUMA `json:"page_usage_by_numa,omitempty"`// if true, memory usage is accounted for throughout a hierarchy of cgroups.UseHierarchybool `json:"use_hierarchy"`Stats map[string]uint64 `json:"stats,omitempty"`PSI *PSIStats `json:"psi,omitempty"`}
typeMount¶
funcGetCgroupMounts¶
GetCgroupMounts returns the mounts for the cgroup subsystems.all indicates whether to return just the first instance or all the mounts.This function should not be used from cgroupv2 code, as in this caseall the controllers are available under the constant unifiedMountpoint.
typeNotFoundError¶
type NotFoundError struct {Subsystemstring}
func (*NotFoundError)Error¶
func (e *NotFoundError) Error()string
typePageUsageByNUMA¶
type PageUsageByNUMA struct {// Embedding is used as types can't be recursive.PageUsageByNUMAInnerHierarchicalPageUsageByNUMAInner `json:"hierarchical,omitempty"`}
typeResources¶
type Resources struct {// Devices is the set of access rules for devices in the container.Devices []*devices.Rule `json:"devices,omitempty"`// Memory limit (in bytes).Memoryint64 `json:"memory,omitempty"`// Memory reservation or soft_limit (in bytes).MemoryReservationint64 `json:"memory_reservation,omitempty"`// Total memory usage (memory+swap); use -1 for unlimited swap.MemorySwapint64 `json:"memory_swap,omitempty"`// CPU shares (relative weight vs. other containers).CpuSharesuint64 `json:"cpu_shares,omitempty"`//nolint:revive // Suppress "var-naming: struct field CpuShares should be CPUShares".// CPU hardcap limit (in usecs). Allowed cpu time in a given period.CpuQuotaint64 `json:"cpu_quota,omitempty"`//nolint:revive // Suppress "var-naming: struct field CpuQuota should be CPUQuota".// CPU hardcap burst limit (in usecs). Allowed accumulated cpu time additionally for burst in a given period.CpuBurst *uint64 `json:"cpu_burst,omitempty"`//nolint:revive // Suppress "var-naming: struct field CpuBurst should be CPUBurst".// CPU period to be used for hardcapping (in usecs). 0 to use system default.CpuPerioduint64 `json:"cpu_period,omitempty"`//nolint:revive // Suppress "var-naming: struct field CpuPeriod should be CPUPeriod".// How many time CPU will use in realtime scheduling (in usecs).CpuRtRuntimeint64 `json:"cpu_rt_quota,omitempty"`//nolint:revive // Suppress "var-naming: struct field CpuRtRuntime should be CPURtRuntime".// CPU period to be used for realtime scheduling (in usecs).CpuRtPerioduint64 `json:"cpu_rt_period,omitempty"`//nolint:revive // Suppress "var-naming: struct field CpuQuota should be CPUQuota".// Cpuset CPUs to use.CpusetCpusstring `json:"cpuset_cpus,omitempty"`// Cpuset memory nodes to use.CpusetMemsstring `json:"cpuset_mems,omitempty"`// Cgroup's SCHED_IDLE value.CPUIdle *int64 `json:"cpu_idle,omitempty"`// Process limit; set <= `0' to disable limit.PidsLimitint64 `json:"pids_limit,omitempty"`// Specifies per cgroup weight, range is from 10 to 1000.BlkioWeightuint16 `json:"blkio_weight,omitempty"`// Tasks' weight in the given cgroup while competing with the cgroup's child cgroups, range is from 10 to 1000, cfq scheduler only.BlkioLeafWeightuint16 `json:"blkio_leaf_weight,omitempty"`// Weight per cgroup per device, can override BlkioWeight.BlkioWeightDevice []*WeightDevice `json:"blkio_weight_device,omitempty"`// IO read rate limit per cgroup per device, bytes per second.BlkioThrottleReadBpsDevice []*ThrottleDevice `json:"blkio_throttle_read_bps_device,omitempty"`// IO write rate limit per cgroup per device, bytes per second.BlkioThrottleWriteBpsDevice []*ThrottleDevice `json:"blkio_throttle_write_bps_device,omitempty"`// IO read rate limit per cgroup per device, IO per second.BlkioThrottleReadIOPSDevice []*ThrottleDevice `json:"blkio_throttle_read_iops_device,omitempty"`// IO write rate limit per cgroup per device, IO per second.BlkioThrottleWriteIOPSDevice []*ThrottleDevice `json:"blkio_throttle_write_iops_device,omitempty"`// Freeze value for the process.FreezerFreezerState `json:"freezer,omitempty"`// Hugetlb limit (in bytes).HugetlbLimit []*HugepageLimit `json:"hugetlb_limit,omitempty"`// Whether to disable OOM killer.OomKillDisablebool `json:"oom_kill_disable,omitempty"`// Tuning swappiness behaviour per cgroup.MemorySwappiness *uint64 `json:"memory_swappiness,omitempty"`// Set priority of network traffic for container.NetPrioIfpriomap []*IfPrioMap `json:"net_prio_ifpriomap,omitempty"`// Set class identifier for container's network packets.NetClsClassiduint32 `json:"net_cls_classid_u,omitempty"`// Rdma resource restriction configuration.Rdma map[string]LinuxRdma `json:"rdma,omitempty"`// CpuWeight sets a proportional bandwidth limit.CpuWeightuint64 `json:"cpu_weight,omitempty"`//nolint:revive // Suppress "var-naming: struct field CpuWeight should be CPUWeight".// Unified is cgroupv2-only key-value map.Unified map[string]string `json:"unified,omitempty"`// SkipDevices allows to skip configuring device permissions.// Used by e.g. kubelet while creating a parent cgroup (kubepods)// common for many containers, and by runc update.//// NOTE it is impossible to start a container which has this flag set.SkipDevicesbool `json:"-"`// SkipFreezeOnSet is a flag for cgroup manager to skip the cgroup// freeze when setting resources. Only applicable to systemd legacy// (i.e. cgroup v1) manager (which uses freeze by default to avoid// spurious permission errors caused by systemd inability to update// device rules in a non-disruptive manner).//// If not set, a few methods (such as looking into cgroup's// devices.list and querying the systemd unit properties) are used// during Set() to figure out whether the freeze is required. Those// methods may be relatively slow, thus this flag.SkipFreezeOnSetbool `json:"-"`// MemoryCheckBeforeUpdate is a flag for cgroup v2 managers to check// if the new memory limits (Memory and MemorySwap) being set are lower// than the current memory usage, and reject if so.MemoryCheckBeforeUpdatebool `json:"memory_check_before_update,omitempty"`}
typeStats¶
type Stats struct {CpuStatsCpuStats `json:"cpu_stats,omitempty"`CPUSetStatsCPUSetStats `json:"cpuset_stats,omitempty"`MemoryStatsMemoryStats `json:"memory_stats,omitempty"`PidsStatsPidsStats `json:"pids_stats,omitempty"`BlkioStatsBlkioStats `json:"blkio_stats,omitempty"`// the map is in the format "size of hugepage: stats of the hugepage"HugetlbStats map[string]HugetlbStats `json:"hugetlb_stats,omitempty"`RdmaStatsRdmaStats `json:"rdma_stats,omitempty"`// the map is in the format "misc resource name: stats of the key"MiscStats map[string]MiscStats `json:"misc_stats,omitempty"`}
typeThrottleDevice¶
type ThrottleDevice struct {BlockIODevice// Rate is the IO rate limit per cgroup per deviceRateuint64 `json:"rate"`}
ThrottleDevice struct holds a `major:minor rate_per_second` pair
funcNewThrottleDevice¶
func NewThrottleDevice(major, minorint64, rateuint64) *ThrottleDevice
NewThrottleDevice returns a configured ThrottleDevice pointer
func (*ThrottleDevice)String¶
func (td *ThrottleDevice) String()string
String formats the struct to be writable to the cgroup specific file
func (*ThrottleDevice)StringName¶
func (td *ThrottleDevice) StringName(namestring)string
StringName formats the struct to be writable to the cgroup specific file
typeThrottlingData¶
type ThrottlingData struct {// Number of periods with throttling activePeriodsuint64 `json:"periods,omitempty"`// Number of periods when the container hit its throttling limit.ThrottledPeriodsuint64 `json:"throttled_periods,omitempty"`// Aggregate time the container was throttled for in nanoseconds.ThrottledTimeuint64 `json:"throttled_time,omitempty"`}
typeWeightDevice¶
type WeightDevice struct {BlockIODevice// Weight is the bandwidth rate for the device, range is from 10 to 1000Weightuint16 `json:"weight"`// LeafWeight is the bandwidth rate for the device while competing with the cgroup's child cgroups, range is from 10 to 1000, cfq scheduler onlyLeafWeightuint16 `json:"leafWeight"`}
WeightDevice struct holds a `major:minor weight`|`major:minor leaf_weight` pair
funcNewWeightDevice¶
func NewWeightDevice(major, minorint64, weight, leafWeightuint16) *WeightDevice
NewWeightDevice returns a configured WeightDevice pointer
func (*WeightDevice)LeafWeightString¶
func (wd *WeightDevice) LeafWeightString()string
LeafWeightString formats the struct to be writable to the cgroup specific file
func (*WeightDevice)WeightString¶
func (wd *WeightDevice) WeightString()string
WeightString formats the struct to be writable to the cgroup specific file