id
int32
0
167k
repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
sequencelengths
21
1.41k
docstring
stringlengths
6
2.61k
docstring_tokens
sequencelengths
3
215
sha
stringlengths
40
40
url
stringlengths
85
252
164,500
opencontainers/runc
libcontainer/cgroups/utils.go
WriteCgroupProc
func WriteCgroupProc(dir string, pid int) error { // Normally dir should not be empty, one case is that cgroup subsystem // is not mounted, we will get empty dir, and we want it fail here. if dir == "" { return fmt.Errorf("no such directory for %s", CgroupProcesses) } // Dont attach any pid to the cgroup if -1 is specified as a pid if pid == -1 { return nil } cgroupProcessesFile, err := os.OpenFile(filepath.Join(dir, CgroupProcesses), os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0700) if err != nil { return fmt.Errorf("failed to write %v to %v: %v", pid, CgroupProcesses, err) } defer cgroupProcessesFile.Close() for i := 0; i < 5; i++ { _, err = cgroupProcessesFile.WriteString(strconv.Itoa(pid)) if err == nil { return nil } // EINVAL might mean that the task being added to cgroup.procs is in state // TASK_NEW. We should attempt to do so again. if isEINVAL(err) { time.Sleep(30 * time.Millisecond) continue } return fmt.Errorf("failed to write %v to %v: %v", pid, CgroupProcesses, err) } return err }
go
func WriteCgroupProc(dir string, pid int) error { // Normally dir should not be empty, one case is that cgroup subsystem // is not mounted, we will get empty dir, and we want it fail here. if dir == "" { return fmt.Errorf("no such directory for %s", CgroupProcesses) } // Dont attach any pid to the cgroup if -1 is specified as a pid if pid == -1 { return nil } cgroupProcessesFile, err := os.OpenFile(filepath.Join(dir, CgroupProcesses), os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0700) if err != nil { return fmt.Errorf("failed to write %v to %v: %v", pid, CgroupProcesses, err) } defer cgroupProcessesFile.Close() for i := 0; i < 5; i++ { _, err = cgroupProcessesFile.WriteString(strconv.Itoa(pid)) if err == nil { return nil } // EINVAL might mean that the task being added to cgroup.procs is in state // TASK_NEW. We should attempt to do so again. if isEINVAL(err) { time.Sleep(30 * time.Millisecond) continue } return fmt.Errorf("failed to write %v to %v: %v", pid, CgroupProcesses, err) } return err }
[ "func", "WriteCgroupProc", "(", "dir", "string", ",", "pid", "int", ")", "error", "{", "// Normally dir should not be empty, one case is that cgroup subsystem", "// is not mounted, we will get empty dir, and we want it fail here.", "if", "dir", "==", "\"", "\"", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "CgroupProcesses", ")", "\n", "}", "\n\n", "// Dont attach any pid to the cgroup if -1 is specified as a pid", "if", "pid", "==", "-", "1", "{", "return", "nil", "\n", "}", "\n\n", "cgroupProcessesFile", ",", "err", ":=", "os", ".", "OpenFile", "(", "filepath", ".", "Join", "(", "dir", ",", "CgroupProcesses", ")", ",", "os", ".", "O_WRONLY", "|", "os", ".", "O_CREATE", "|", "os", ".", "O_TRUNC", ",", "0700", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "pid", ",", "CgroupProcesses", ",", "err", ")", "\n", "}", "\n", "defer", "cgroupProcessesFile", ".", "Close", "(", ")", "\n\n", "for", "i", ":=", "0", ";", "i", "<", "5", ";", "i", "++", "{", "_", ",", "err", "=", "cgroupProcessesFile", ".", "WriteString", "(", "strconv", ".", "Itoa", "(", "pid", ")", ")", "\n", "if", "err", "==", "nil", "{", "return", "nil", "\n", "}", "\n\n", "// EINVAL might mean that the task being added to cgroup.procs is in state", "// TASK_NEW. We should attempt to do so again.", "if", "isEINVAL", "(", "err", ")", "{", "time", ".", "Sleep", "(", "30", "*", "time", ".", "Millisecond", ")", "\n", "continue", "\n", "}", "\n\n", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "pid", ",", "CgroupProcesses", ",", "err", ")", "\n", "}", "\n", "return", "err", "\n", "}" ]
// WriteCgroupProc writes the specified pid into the cgroup's cgroup.procs file
[ "WriteCgroupProc", "writes", "the", "specified", "pid", "into", "the", "cgroup", "s", "cgroup", ".", "procs", "file" ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/cgroups/utils.go#L460-L494
164,501
opencontainers/runc
libcontainer/configs/validate/rootless.go
rootlessEUIDMount
func rootlessEUIDMount(config *configs.Config) error { // XXX: We could whitelist allowed devices at this point, but I'm not // convinced that's a good idea. The kernel is the best arbiter of // access control. for _, mount := range config.Mounts { // Check that the options list doesn't contain any uid= or gid= entries // that don't resolve to root. for _, opt := range strings.Split(mount.Data, ",") { if strings.HasPrefix(opt, "uid=") { var uid int n, err := fmt.Sscanf(opt, "uid=%d", &uid) if n != 1 || err != nil { // Ignore unknown mount options. continue } if !hasIDMapping(uid, config.UidMappings) { return fmt.Errorf("cannot specify uid= mount options for unmapped uid in rootless containers") } } if strings.HasPrefix(opt, "gid=") { var gid int n, err := fmt.Sscanf(opt, "gid=%d", &gid) if n != 1 || err != nil { // Ignore unknown mount options. continue } if !hasIDMapping(gid, config.GidMappings) { return fmt.Errorf("cannot specify gid= mount options for unmapped gid in rootless containers") } } } } return nil }
go
func rootlessEUIDMount(config *configs.Config) error { // XXX: We could whitelist allowed devices at this point, but I'm not // convinced that's a good idea. The kernel is the best arbiter of // access control. for _, mount := range config.Mounts { // Check that the options list doesn't contain any uid= or gid= entries // that don't resolve to root. for _, opt := range strings.Split(mount.Data, ",") { if strings.HasPrefix(opt, "uid=") { var uid int n, err := fmt.Sscanf(opt, "uid=%d", &uid) if n != 1 || err != nil { // Ignore unknown mount options. continue } if !hasIDMapping(uid, config.UidMappings) { return fmt.Errorf("cannot specify uid= mount options for unmapped uid in rootless containers") } } if strings.HasPrefix(opt, "gid=") { var gid int n, err := fmt.Sscanf(opt, "gid=%d", &gid) if n != 1 || err != nil { // Ignore unknown mount options. continue } if !hasIDMapping(gid, config.GidMappings) { return fmt.Errorf("cannot specify gid= mount options for unmapped gid in rootless containers") } } } } return nil }
[ "func", "rootlessEUIDMount", "(", "config", "*", "configs", ".", "Config", ")", "error", "{", "// XXX: We could whitelist allowed devices at this point, but I'm not", "// convinced that's a good idea. The kernel is the best arbiter of", "// access control.", "for", "_", ",", "mount", ":=", "range", "config", ".", "Mounts", "{", "// Check that the options list doesn't contain any uid= or gid= entries", "// that don't resolve to root.", "for", "_", ",", "opt", ":=", "range", "strings", ".", "Split", "(", "mount", ".", "Data", ",", "\"", "\"", ")", "{", "if", "strings", ".", "HasPrefix", "(", "opt", ",", "\"", "\"", ")", "{", "var", "uid", "int", "\n", "n", ",", "err", ":=", "fmt", ".", "Sscanf", "(", "opt", ",", "\"", "\"", ",", "&", "uid", ")", "\n", "if", "n", "!=", "1", "||", "err", "!=", "nil", "{", "// Ignore unknown mount options.", "continue", "\n", "}", "\n", "if", "!", "hasIDMapping", "(", "uid", ",", "config", ".", "UidMappings", ")", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "\n\n", "if", "strings", ".", "HasPrefix", "(", "opt", ",", "\"", "\"", ")", "{", "var", "gid", "int", "\n", "n", ",", "err", ":=", "fmt", ".", "Sscanf", "(", "opt", ",", "\"", "\"", ",", "&", "gid", ")", "\n", "if", "n", "!=", "1", "||", "err", "!=", "nil", "{", "// Ignore unknown mount options.", "continue", "\n", "}", "\n", "if", "!", "hasIDMapping", "(", "gid", ",", "config", ".", "GidMappings", ")", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// mount verifies that the user isn't trying to set up any mounts they don't have // the rights to do. In addition, it makes sure that no mount has a `uid=` or // `gid=` option that doesn't resolve to root.
[ "mount", "verifies", "that", "the", "user", "isn", "t", "trying", "to", "set", "up", "any", "mounts", "they", "don", "t", "have", "the", "rights", "to", "do", ".", "In", "addition", "it", "makes", "sure", "that", "no", "mount", "has", "a", "uid", "=", "or", "gid", "=", "option", "that", "doesn", "t", "resolve", "to", "root", "." ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/configs/validate/rootless.go#L53-L89
164,502
opencontainers/runc
libcontainer/configs/config_linux.go
HostUID
func (c Config) HostUID(containerId int) (int, error) { if c.Namespaces.Contains(NEWUSER) { if c.UidMappings == nil { return -1, fmt.Errorf("User namespaces enabled, but no uid mappings found.") } id, found := c.hostIDFromMapping(containerId, c.UidMappings) if !found { return -1, fmt.Errorf("User namespaces enabled, but no user mapping found.") } return id, nil } // Return unchanged id. return containerId, nil }
go
func (c Config) HostUID(containerId int) (int, error) { if c.Namespaces.Contains(NEWUSER) { if c.UidMappings == nil { return -1, fmt.Errorf("User namespaces enabled, but no uid mappings found.") } id, found := c.hostIDFromMapping(containerId, c.UidMappings) if !found { return -1, fmt.Errorf("User namespaces enabled, but no user mapping found.") } return id, nil } // Return unchanged id. return containerId, nil }
[ "func", "(", "c", "Config", ")", "HostUID", "(", "containerId", "int", ")", "(", "int", ",", "error", ")", "{", "if", "c", ".", "Namespaces", ".", "Contains", "(", "NEWUSER", ")", "{", "if", "c", ".", "UidMappings", "==", "nil", "{", "return", "-", "1", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "id", ",", "found", ":=", "c", ".", "hostIDFromMapping", "(", "containerId", ",", "c", ".", "UidMappings", ")", "\n", "if", "!", "found", "{", "return", "-", "1", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "id", ",", "nil", "\n", "}", "\n", "// Return unchanged id.", "return", "containerId", ",", "nil", "\n", "}" ]
// HostUID gets the translated uid for the process on host which could be // different when user namespaces are enabled.
[ "HostUID", "gets", "the", "translated", "uid", "for", "the", "process", "on", "host", "which", "could", "be", "different", "when", "user", "namespaces", "are", "enabled", "." ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/configs/config_linux.go#L7-L20
164,503
opencontainers/runc
libcontainer/configs/config_linux.go
HostGID
func (c Config) HostGID(containerId int) (int, error) { if c.Namespaces.Contains(NEWUSER) { if c.GidMappings == nil { return -1, fmt.Errorf("User namespaces enabled, but no gid mappings found.") } id, found := c.hostIDFromMapping(containerId, c.GidMappings) if !found { return -1, fmt.Errorf("User namespaces enabled, but no group mapping found.") } return id, nil } // Return unchanged id. return containerId, nil }
go
func (c Config) HostGID(containerId int) (int, error) { if c.Namespaces.Contains(NEWUSER) { if c.GidMappings == nil { return -1, fmt.Errorf("User namespaces enabled, but no gid mappings found.") } id, found := c.hostIDFromMapping(containerId, c.GidMappings) if !found { return -1, fmt.Errorf("User namespaces enabled, but no group mapping found.") } return id, nil } // Return unchanged id. return containerId, nil }
[ "func", "(", "c", "Config", ")", "HostGID", "(", "containerId", "int", ")", "(", "int", ",", "error", ")", "{", "if", "c", ".", "Namespaces", ".", "Contains", "(", "NEWUSER", ")", "{", "if", "c", ".", "GidMappings", "==", "nil", "{", "return", "-", "1", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "id", ",", "found", ":=", "c", ".", "hostIDFromMapping", "(", "containerId", ",", "c", ".", "GidMappings", ")", "\n", "if", "!", "found", "{", "return", "-", "1", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "id", ",", "nil", "\n", "}", "\n", "// Return unchanged id.", "return", "containerId", ",", "nil", "\n", "}" ]
// HostGID gets the translated gid for the process on host which could be // different when user namespaces are enabled.
[ "HostGID", "gets", "the", "translated", "gid", "for", "the", "process", "on", "host", "which", "could", "be", "different", "when", "user", "namespaces", "are", "enabled", "." ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/configs/config_linux.go#L30-L43
164,504
opencontainers/runc
libcontainer/configs/config_linux.go
hostIDFromMapping
func (c Config) hostIDFromMapping(containerID int, uMap []IDMap) (int, bool) { for _, m := range uMap { if (containerID >= m.ContainerID) && (containerID <= (m.ContainerID + m.Size - 1)) { hostID := m.HostID + (containerID - m.ContainerID) return hostID, true } } return -1, false }
go
func (c Config) hostIDFromMapping(containerID int, uMap []IDMap) (int, bool) { for _, m := range uMap { if (containerID >= m.ContainerID) && (containerID <= (m.ContainerID + m.Size - 1)) { hostID := m.HostID + (containerID - m.ContainerID) return hostID, true } } return -1, false }
[ "func", "(", "c", "Config", ")", "hostIDFromMapping", "(", "containerID", "int", ",", "uMap", "[", "]", "IDMap", ")", "(", "int", ",", "bool", ")", "{", "for", "_", ",", "m", ":=", "range", "uMap", "{", "if", "(", "containerID", ">=", "m", ".", "ContainerID", ")", "&&", "(", "containerID", "<=", "(", "m", ".", "ContainerID", "+", "m", ".", "Size", "-", "1", ")", ")", "{", "hostID", ":=", "m", ".", "HostID", "+", "(", "containerID", "-", "m", ".", "ContainerID", ")", "\n", "return", "hostID", ",", "true", "\n", "}", "\n", "}", "\n", "return", "-", "1", ",", "false", "\n", "}" ]
// Utility function that gets a host ID for a container ID from user namespace map // if that ID is present in the map.
[ "Utility", "function", "that", "gets", "a", "host", "ID", "for", "a", "container", "ID", "from", "user", "namespace", "map", "if", "that", "ID", "is", "present", "in", "the", "map", "." ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/configs/config_linux.go#L53-L61
164,505
opencontainers/runc
libcontainer/configs/namespaces_linux.go
NsName
func NsName(ns NamespaceType) string { switch ns { case NEWNET: return "net" case NEWNS: return "mnt" case NEWPID: return "pid" case NEWIPC: return "ipc" case NEWUSER: return "user" case NEWUTS: return "uts" case NEWCGROUP: return "cgroup" } return "" }
go
func NsName(ns NamespaceType) string { switch ns { case NEWNET: return "net" case NEWNS: return "mnt" case NEWPID: return "pid" case NEWIPC: return "ipc" case NEWUSER: return "user" case NEWUTS: return "uts" case NEWCGROUP: return "cgroup" } return "" }
[ "func", "NsName", "(", "ns", "NamespaceType", ")", "string", "{", "switch", "ns", "{", "case", "NEWNET", ":", "return", "\"", "\"", "\n", "case", "NEWNS", ":", "return", "\"", "\"", "\n", "case", "NEWPID", ":", "return", "\"", "\"", "\n", "case", "NEWIPC", ":", "return", "\"", "\"", "\n", "case", "NEWUSER", ":", "return", "\"", "\"", "\n", "case", "NEWUTS", ":", "return", "\"", "\"", "\n", "case", "NEWCGROUP", ":", "return", "\"", "\"", "\n", "}", "\n", "return", "\"", "\"", "\n", "}" ]
// NsName converts the namespace type to its filename
[ "NsName", "converts", "the", "namespace", "type", "to", "its", "filename" ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/configs/namespaces_linux.go#L25-L43
164,506
opencontainers/runc
libcontainer/configs/namespaces_linux.go
IsNamespaceSupported
func IsNamespaceSupported(ns NamespaceType) bool { nsLock.Lock() defer nsLock.Unlock() supported, ok := supportedNamespaces[ns] if ok { return supported } nsFile := NsName(ns) // if the namespace type is unknown, just return false if nsFile == "" { return false } _, err := os.Stat(fmt.Sprintf("/proc/self/ns/%s", nsFile)) // a namespace is supported if it exists and we have permissions to read it supported = err == nil supportedNamespaces[ns] = supported return supported }
go
func IsNamespaceSupported(ns NamespaceType) bool { nsLock.Lock() defer nsLock.Unlock() supported, ok := supportedNamespaces[ns] if ok { return supported } nsFile := NsName(ns) // if the namespace type is unknown, just return false if nsFile == "" { return false } _, err := os.Stat(fmt.Sprintf("/proc/self/ns/%s", nsFile)) // a namespace is supported if it exists and we have permissions to read it supported = err == nil supportedNamespaces[ns] = supported return supported }
[ "func", "IsNamespaceSupported", "(", "ns", "NamespaceType", ")", "bool", "{", "nsLock", ".", "Lock", "(", ")", "\n", "defer", "nsLock", ".", "Unlock", "(", ")", "\n", "supported", ",", "ok", ":=", "supportedNamespaces", "[", "ns", "]", "\n", "if", "ok", "{", "return", "supported", "\n", "}", "\n", "nsFile", ":=", "NsName", "(", "ns", ")", "\n", "// if the namespace type is unknown, just return false", "if", "nsFile", "==", "\"", "\"", "{", "return", "false", "\n", "}", "\n", "_", ",", "err", ":=", "os", ".", "Stat", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "nsFile", ")", ")", "\n", "// a namespace is supported if it exists and we have permissions to read it", "supported", "=", "err", "==", "nil", "\n", "supportedNamespaces", "[", "ns", "]", "=", "supported", "\n", "return", "supported", "\n", "}" ]
// IsNamespaceSupported returns whether a namespace is available or // not
[ "IsNamespaceSupported", "returns", "whether", "a", "namespace", "is", "available", "or", "not" ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/configs/namespaces_linux.go#L47-L64
164,507
opencontainers/runc
libcontainer/notify_linux.go
notifyOnOOM
func notifyOnOOM(paths map[string]string) (<-chan struct{}, error) { dir := paths[oomCgroupName] if dir == "" { return nil, fmt.Errorf("path %q missing", oomCgroupName) } return registerMemoryEvent(dir, "memory.oom_control", "") }
go
func notifyOnOOM(paths map[string]string) (<-chan struct{}, error) { dir := paths[oomCgroupName] if dir == "" { return nil, fmt.Errorf("path %q missing", oomCgroupName) } return registerMemoryEvent(dir, "memory.oom_control", "") }
[ "func", "notifyOnOOM", "(", "paths", "map", "[", "string", "]", "string", ")", "(", "<-", "chan", "struct", "{", "}", ",", "error", ")", "{", "dir", ":=", "paths", "[", "oomCgroupName", "]", "\n", "if", "dir", "==", "\"", "\"", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "oomCgroupName", ")", "\n", "}", "\n\n", "return", "registerMemoryEvent", "(", "dir", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "}" ]
// notifyOnOOM returns channel on which you can expect event about OOM, // if process died without OOM this channel will be closed.
[ "notifyOnOOM", "returns", "channel", "on", "which", "you", "can", "expect", "event", "about", "OOM", "if", "process", "died", "without", "OOM", "this", "channel", "will", "be", "closed", "." ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/notify_linux.go#L69-L76
164,508
opencontainers/runc
libcontainer/cgroups/fs/apply_raw.go
getCgroupRoot
func getCgroupRoot() (string, error) { cgroupRootLock.Lock() defer cgroupRootLock.Unlock() if cgroupRoot != "" { return cgroupRoot, nil } root, err := cgroups.FindCgroupMountpointDir() if err != nil { return "", err } if _, err := os.Stat(root); err != nil { return "", err } cgroupRoot = root return cgroupRoot, nil }
go
func getCgroupRoot() (string, error) { cgroupRootLock.Lock() defer cgroupRootLock.Unlock() if cgroupRoot != "" { return cgroupRoot, nil } root, err := cgroups.FindCgroupMountpointDir() if err != nil { return "", err } if _, err := os.Stat(root); err != nil { return "", err } cgroupRoot = root return cgroupRoot, nil }
[ "func", "getCgroupRoot", "(", ")", "(", "string", ",", "error", ")", "{", "cgroupRootLock", ".", "Lock", "(", ")", "\n", "defer", "cgroupRootLock", ".", "Unlock", "(", ")", "\n\n", "if", "cgroupRoot", "!=", "\"", "\"", "{", "return", "cgroupRoot", ",", "nil", "\n", "}", "\n\n", "root", ",", "err", ":=", "cgroups", ".", "FindCgroupMountpointDir", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "if", "_", ",", "err", ":=", "os", ".", "Stat", "(", "root", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "cgroupRoot", "=", "root", "\n", "return", "cgroupRoot", ",", "nil", "\n", "}" ]
// Gets the cgroupRoot.
[ "Gets", "the", "cgroupRoot", "." ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/cgroups/fs/apply_raw.go#L77-L96
164,509
opencontainers/runc
libcontainer/cgroups/fs/apply_raw.go
Freeze
func (m *Manager) Freeze(state configs.FreezerState) error { paths := m.GetPaths() dir := paths["freezer"] prevState := m.Cgroups.Resources.Freezer m.Cgroups.Resources.Freezer = state freezer, err := subsystems.Get("freezer") if err != nil { return err } err = freezer.Set(dir, m.Cgroups) if err != nil { m.Cgroups.Resources.Freezer = prevState return err } return nil }
go
func (m *Manager) Freeze(state configs.FreezerState) error { paths := m.GetPaths() dir := paths["freezer"] prevState := m.Cgroups.Resources.Freezer m.Cgroups.Resources.Freezer = state freezer, err := subsystems.Get("freezer") if err != nil { return err } err = freezer.Set(dir, m.Cgroups) if err != nil { m.Cgroups.Resources.Freezer = prevState return err } return nil }
[ "func", "(", "m", "*", "Manager", ")", "Freeze", "(", "state", "configs", ".", "FreezerState", ")", "error", "{", "paths", ":=", "m", ".", "GetPaths", "(", ")", "\n", "dir", ":=", "paths", "[", "\"", "\"", "]", "\n", "prevState", ":=", "m", ".", "Cgroups", ".", "Resources", ".", "Freezer", "\n", "m", ".", "Cgroups", ".", "Resources", ".", "Freezer", "=", "state", "\n", "freezer", ",", "err", ":=", "subsystems", ".", "Get", "(", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "err", "=", "freezer", ".", "Set", "(", "dir", ",", "m", ".", "Cgroups", ")", "\n", "if", "err", "!=", "nil", "{", "m", ".", "Cgroups", ".", "Resources", ".", "Freezer", "=", "prevState", "\n", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Freeze toggles the container's freezer cgroup depending on the state // provided
[ "Freeze", "toggles", "the", "container", "s", "freezer", "cgroup", "depending", "on", "the", "state", "provided" ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/cgroups/fs/apply_raw.go#L264-L279
164,510
opencontainers/runc
libcontainer/seccomp/seccomp_linux.go
InitSeccomp
func InitSeccomp(config *configs.Seccomp) error { if config == nil { return fmt.Errorf("cannot initialize Seccomp - nil config passed") } defaultAction, err := getAction(config.DefaultAction) if err != nil { return fmt.Errorf("error initializing seccomp - invalid default action") } filter, err := libseccomp.NewFilter(defaultAction) if err != nil { return fmt.Errorf("error creating filter: %s", err) } // Add extra architectures for _, arch := range config.Architectures { scmpArch, err := libseccomp.GetArchFromString(arch) if err != nil { return fmt.Errorf("error validating Seccomp architecture: %s", err) } if err := filter.AddArch(scmpArch); err != nil { return fmt.Errorf("error adding architecture to seccomp filter: %s", err) } } // Unset no new privs bit if err := filter.SetNoNewPrivsBit(false); err != nil { return fmt.Errorf("error setting no new privileges: %s", err) } // Add a rule for each syscall for _, call := range config.Syscalls { if call == nil { return fmt.Errorf("encountered nil syscall while initializing Seccomp") } if err = matchCall(filter, call); err != nil { return err } } if err = filter.Load(); err != nil { return fmt.Errorf("error loading seccomp filter into kernel: %s", err) } return nil }
go
func InitSeccomp(config *configs.Seccomp) error { if config == nil { return fmt.Errorf("cannot initialize Seccomp - nil config passed") } defaultAction, err := getAction(config.DefaultAction) if err != nil { return fmt.Errorf("error initializing seccomp - invalid default action") } filter, err := libseccomp.NewFilter(defaultAction) if err != nil { return fmt.Errorf("error creating filter: %s", err) } // Add extra architectures for _, arch := range config.Architectures { scmpArch, err := libseccomp.GetArchFromString(arch) if err != nil { return fmt.Errorf("error validating Seccomp architecture: %s", err) } if err := filter.AddArch(scmpArch); err != nil { return fmt.Errorf("error adding architecture to seccomp filter: %s", err) } } // Unset no new privs bit if err := filter.SetNoNewPrivsBit(false); err != nil { return fmt.Errorf("error setting no new privileges: %s", err) } // Add a rule for each syscall for _, call := range config.Syscalls { if call == nil { return fmt.Errorf("encountered nil syscall while initializing Seccomp") } if err = matchCall(filter, call); err != nil { return err } } if err = filter.Load(); err != nil { return fmt.Errorf("error loading seccomp filter into kernel: %s", err) } return nil }
[ "func", "InitSeccomp", "(", "config", "*", "configs", ".", "Seccomp", ")", "error", "{", "if", "config", "==", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "defaultAction", ",", "err", ":=", "getAction", "(", "config", ".", "DefaultAction", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "filter", ",", "err", ":=", "libseccomp", ".", "NewFilter", "(", "defaultAction", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "// Add extra architectures", "for", "_", ",", "arch", ":=", "range", "config", ".", "Architectures", "{", "scmpArch", ",", "err", ":=", "libseccomp", ".", "GetArchFromString", "(", "arch", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "if", "err", ":=", "filter", ".", "AddArch", "(", "scmpArch", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}", "\n\n", "// Unset no new privs bit", "if", "err", ":=", "filter", ".", "SetNoNewPrivsBit", "(", "false", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "// Add a rule for each syscall", "for", "_", ",", "call", ":=", "range", "config", ".", "Syscalls", "{", "if", "call", "==", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "err", "=", "matchCall", "(", "filter", ",", "call", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n\n", "if", "err", "=", "filter", ".", "Load", "(", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Filters given syscalls in a container, preventing them from being used // Started in the container init process, and carried over to all child processes // Setns calls, however, require a separate invocation, as they are not children // of the init until they join the namespace
[ "Filters", "given", "syscalls", "in", "a", "container", "preventing", "them", "from", "being", "used", "Started", "in", "the", "container", "init", "process", "and", "carried", "over", "to", "all", "child", "processes", "Setns", "calls", "however", "require", "a", "separate", "invocation", "as", "they", "are", "not", "children", "of", "the", "init", "until", "they", "join", "the", "namespace" ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/seccomp/seccomp_linux.go#L34-L82
164,511
opencontainers/runc
libcontainer/seccomp/seccomp_linux.go
IsEnabled
func IsEnabled() bool { // Try to read from /proc/self/status for kernels > 3.8 s, err := parseStatusFile("/proc/self/status") if err != nil { // Check if Seccomp is supported, via CONFIG_SECCOMP. if err := unix.Prctl(unix.PR_GET_SECCOMP, 0, 0, 0, 0); err != unix.EINVAL { // Make sure the kernel has CONFIG_SECCOMP_FILTER. if err := unix.Prctl(unix.PR_SET_SECCOMP, unix.SECCOMP_MODE_FILTER, 0, 0, 0); err != unix.EINVAL { return true } } return false } _, ok := s["Seccomp"] return ok }
go
func IsEnabled() bool { // Try to read from /proc/self/status for kernels > 3.8 s, err := parseStatusFile("/proc/self/status") if err != nil { // Check if Seccomp is supported, via CONFIG_SECCOMP. if err := unix.Prctl(unix.PR_GET_SECCOMP, 0, 0, 0, 0); err != unix.EINVAL { // Make sure the kernel has CONFIG_SECCOMP_FILTER. if err := unix.Prctl(unix.PR_SET_SECCOMP, unix.SECCOMP_MODE_FILTER, 0, 0, 0); err != unix.EINVAL { return true } } return false } _, ok := s["Seccomp"] return ok }
[ "func", "IsEnabled", "(", ")", "bool", "{", "// Try to read from /proc/self/status for kernels > 3.8", "s", ",", "err", ":=", "parseStatusFile", "(", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "// Check if Seccomp is supported, via CONFIG_SECCOMP.", "if", "err", ":=", "unix", ".", "Prctl", "(", "unix", ".", "PR_GET_SECCOMP", ",", "0", ",", "0", ",", "0", ",", "0", ")", ";", "err", "!=", "unix", ".", "EINVAL", "{", "// Make sure the kernel has CONFIG_SECCOMP_FILTER.", "if", "err", ":=", "unix", ".", "Prctl", "(", "unix", ".", "PR_SET_SECCOMP", ",", "unix", ".", "SECCOMP_MODE_FILTER", ",", "0", ",", "0", ",", "0", ")", ";", "err", "!=", "unix", ".", "EINVAL", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}", "\n", "_", ",", "ok", ":=", "s", "[", "\"", "\"", "]", "\n", "return", "ok", "\n", "}" ]
// IsEnabled returns if the kernel has been configured to support seccomp.
[ "IsEnabled", "returns", "if", "the", "kernel", "has", "been", "configured", "to", "support", "seccomp", "." ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/seccomp/seccomp_linux.go#L85-L100
164,512
opencontainers/runc
libcontainer/seccomp/seccomp_linux.go
getAction
func getAction(act configs.Action) (libseccomp.ScmpAction, error) { switch act { case configs.Kill: return actKill, nil case configs.Errno: return actErrno, nil case configs.Trap: return actTrap, nil case configs.Allow: return actAllow, nil case configs.Trace: return actTrace, nil default: return libseccomp.ActInvalid, fmt.Errorf("invalid action, cannot use in rule") } }
go
func getAction(act configs.Action) (libseccomp.ScmpAction, error) { switch act { case configs.Kill: return actKill, nil case configs.Errno: return actErrno, nil case configs.Trap: return actTrap, nil case configs.Allow: return actAllow, nil case configs.Trace: return actTrace, nil default: return libseccomp.ActInvalid, fmt.Errorf("invalid action, cannot use in rule") } }
[ "func", "getAction", "(", "act", "configs", ".", "Action", ")", "(", "libseccomp", ".", "ScmpAction", ",", "error", ")", "{", "switch", "act", "{", "case", "configs", ".", "Kill", ":", "return", "actKill", ",", "nil", "\n", "case", "configs", ".", "Errno", ":", "return", "actErrno", ",", "nil", "\n", "case", "configs", ".", "Trap", ":", "return", "actTrap", ",", "nil", "\n", "case", "configs", ".", "Allow", ":", "return", "actAllow", ",", "nil", "\n", "case", "configs", ".", "Trace", ":", "return", "actTrace", ",", "nil", "\n", "default", ":", "return", "libseccomp", ".", "ActInvalid", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "}" ]
// Convert Libcontainer Action to Libseccomp ScmpAction
[ "Convert", "Libcontainer", "Action", "to", "Libseccomp", "ScmpAction" ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/seccomp/seccomp_linux.go#L103-L118
164,513
opencontainers/runc
libcontainer/seccomp/seccomp_linux.go
getOperator
func getOperator(op configs.Operator) (libseccomp.ScmpCompareOp, error) { switch op { case configs.EqualTo: return libseccomp.CompareEqual, nil case configs.NotEqualTo: return libseccomp.CompareNotEqual, nil case configs.GreaterThan: return libseccomp.CompareGreater, nil case configs.GreaterThanOrEqualTo: return libseccomp.CompareGreaterEqual, nil case configs.LessThan: return libseccomp.CompareLess, nil case configs.LessThanOrEqualTo: return libseccomp.CompareLessOrEqual, nil case configs.MaskEqualTo: return libseccomp.CompareMaskedEqual, nil default: return libseccomp.CompareInvalid, fmt.Errorf("invalid operator, cannot use in rule") } }
go
func getOperator(op configs.Operator) (libseccomp.ScmpCompareOp, error) { switch op { case configs.EqualTo: return libseccomp.CompareEqual, nil case configs.NotEqualTo: return libseccomp.CompareNotEqual, nil case configs.GreaterThan: return libseccomp.CompareGreater, nil case configs.GreaterThanOrEqualTo: return libseccomp.CompareGreaterEqual, nil case configs.LessThan: return libseccomp.CompareLess, nil case configs.LessThanOrEqualTo: return libseccomp.CompareLessOrEqual, nil case configs.MaskEqualTo: return libseccomp.CompareMaskedEqual, nil default: return libseccomp.CompareInvalid, fmt.Errorf("invalid operator, cannot use in rule") } }
[ "func", "getOperator", "(", "op", "configs", ".", "Operator", ")", "(", "libseccomp", ".", "ScmpCompareOp", ",", "error", ")", "{", "switch", "op", "{", "case", "configs", ".", "EqualTo", ":", "return", "libseccomp", ".", "CompareEqual", ",", "nil", "\n", "case", "configs", ".", "NotEqualTo", ":", "return", "libseccomp", ".", "CompareNotEqual", ",", "nil", "\n", "case", "configs", ".", "GreaterThan", ":", "return", "libseccomp", ".", "CompareGreater", ",", "nil", "\n", "case", "configs", ".", "GreaterThanOrEqualTo", ":", "return", "libseccomp", ".", "CompareGreaterEqual", ",", "nil", "\n", "case", "configs", ".", "LessThan", ":", "return", "libseccomp", ".", "CompareLess", ",", "nil", "\n", "case", "configs", ".", "LessThanOrEqualTo", ":", "return", "libseccomp", ".", "CompareLessOrEqual", ",", "nil", "\n", "case", "configs", ".", "MaskEqualTo", ":", "return", "libseccomp", ".", "CompareMaskedEqual", ",", "nil", "\n", "default", ":", "return", "libseccomp", ".", "CompareInvalid", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "}" ]
// Convert Libcontainer Operator to Libseccomp ScmpCompareOp
[ "Convert", "Libcontainer", "Operator", "to", "Libseccomp", "ScmpCompareOp" ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/seccomp/seccomp_linux.go#L121-L140
164,514
opencontainers/runc
libcontainer/seccomp/seccomp_linux.go
getCondition
func getCondition(arg *configs.Arg) (libseccomp.ScmpCondition, error) { cond := libseccomp.ScmpCondition{} if arg == nil { return cond, fmt.Errorf("cannot convert nil to syscall condition") } op, err := getOperator(arg.Op) if err != nil { return cond, err } return libseccomp.MakeCondition(arg.Index, op, arg.Value, arg.ValueTwo) }
go
func getCondition(arg *configs.Arg) (libseccomp.ScmpCondition, error) { cond := libseccomp.ScmpCondition{} if arg == nil { return cond, fmt.Errorf("cannot convert nil to syscall condition") } op, err := getOperator(arg.Op) if err != nil { return cond, err } return libseccomp.MakeCondition(arg.Index, op, arg.Value, arg.ValueTwo) }
[ "func", "getCondition", "(", "arg", "*", "configs", ".", "Arg", ")", "(", "libseccomp", ".", "ScmpCondition", ",", "error", ")", "{", "cond", ":=", "libseccomp", ".", "ScmpCondition", "{", "}", "\n\n", "if", "arg", "==", "nil", "{", "return", "cond", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "op", ",", "err", ":=", "getOperator", "(", "arg", ".", "Op", ")", "\n", "if", "err", "!=", "nil", "{", "return", "cond", ",", "err", "\n", "}", "\n\n", "return", "libseccomp", ".", "MakeCondition", "(", "arg", ".", "Index", ",", "op", ",", "arg", ".", "Value", ",", "arg", ".", "ValueTwo", ")", "\n", "}" ]
// Convert Libcontainer Arg to Libseccomp ScmpCondition
[ "Convert", "Libcontainer", "Arg", "to", "Libseccomp", "ScmpCondition" ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/seccomp/seccomp_linux.go#L143-L156
164,515
opencontainers/runc
libcontainer/seccomp/seccomp_linux.go
matchCall
func matchCall(filter *libseccomp.ScmpFilter, call *configs.Syscall) error { if call == nil || filter == nil { return fmt.Errorf("cannot use nil as syscall to block") } if len(call.Name) == 0 { return fmt.Errorf("empty string is not a valid syscall") } // If we can't resolve the syscall, assume it's not supported on this kernel // Ignore it, don't error out callNum, err := libseccomp.GetSyscallFromName(call.Name) if err != nil { return nil } // Convert the call's action to the libseccomp equivalent callAct, err := getAction(call.Action) if err != nil { return fmt.Errorf("action in seccomp profile is invalid: %s", err) } // Unconditional match - just add the rule if len(call.Args) == 0 { if err = filter.AddRule(callNum, callAct); err != nil { return fmt.Errorf("error adding seccomp filter rule for syscall %s: %s", call.Name, err) } } else { // If two or more arguments have the same condition, // Revert to old behavior, adding each condition as a separate rule argCounts := make([]uint, syscallMaxArguments) conditions := []libseccomp.ScmpCondition{} for _, cond := range call.Args { newCond, err := getCondition(cond) if err != nil { return fmt.Errorf("error creating seccomp syscall condition for syscall %s: %s", call.Name, err) } argCounts[cond.Index] += 1 conditions = append(conditions, newCond) } hasMultipleArgs := false for _, count := range argCounts { if count > 1 { hasMultipleArgs = true break } } if hasMultipleArgs { // Revert to old behavior // Add each condition attached to a separate rule for _, cond := range conditions { condArr := []libseccomp.ScmpCondition{cond} if err = filter.AddRuleConditional(callNum, callAct, condArr); err != nil { return fmt.Errorf("error adding seccomp rule for syscall %s: %s", call.Name, err) } } } else { // No conditions share same argument // Use new, proper behavior if err = filter.AddRuleConditional(callNum, callAct, conditions); err != nil { return fmt.Errorf("error adding seccomp rule for syscall %s: %s", call.Name, err) } } } return nil }
go
func matchCall(filter *libseccomp.ScmpFilter, call *configs.Syscall) error { if call == nil || filter == nil { return fmt.Errorf("cannot use nil as syscall to block") } if len(call.Name) == 0 { return fmt.Errorf("empty string is not a valid syscall") } // If we can't resolve the syscall, assume it's not supported on this kernel // Ignore it, don't error out callNum, err := libseccomp.GetSyscallFromName(call.Name) if err != nil { return nil } // Convert the call's action to the libseccomp equivalent callAct, err := getAction(call.Action) if err != nil { return fmt.Errorf("action in seccomp profile is invalid: %s", err) } // Unconditional match - just add the rule if len(call.Args) == 0 { if err = filter.AddRule(callNum, callAct); err != nil { return fmt.Errorf("error adding seccomp filter rule for syscall %s: %s", call.Name, err) } } else { // If two or more arguments have the same condition, // Revert to old behavior, adding each condition as a separate rule argCounts := make([]uint, syscallMaxArguments) conditions := []libseccomp.ScmpCondition{} for _, cond := range call.Args { newCond, err := getCondition(cond) if err != nil { return fmt.Errorf("error creating seccomp syscall condition for syscall %s: %s", call.Name, err) } argCounts[cond.Index] += 1 conditions = append(conditions, newCond) } hasMultipleArgs := false for _, count := range argCounts { if count > 1 { hasMultipleArgs = true break } } if hasMultipleArgs { // Revert to old behavior // Add each condition attached to a separate rule for _, cond := range conditions { condArr := []libseccomp.ScmpCondition{cond} if err = filter.AddRuleConditional(callNum, callAct, condArr); err != nil { return fmt.Errorf("error adding seccomp rule for syscall %s: %s", call.Name, err) } } } else { // No conditions share same argument // Use new, proper behavior if err = filter.AddRuleConditional(callNum, callAct, conditions); err != nil { return fmt.Errorf("error adding seccomp rule for syscall %s: %s", call.Name, err) } } } return nil }
[ "func", "matchCall", "(", "filter", "*", "libseccomp", ".", "ScmpFilter", ",", "call", "*", "configs", ".", "Syscall", ")", "error", "{", "if", "call", "==", "nil", "||", "filter", "==", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "len", "(", "call", ".", "Name", ")", "==", "0", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "// If we can't resolve the syscall, assume it's not supported on this kernel", "// Ignore it, don't error out", "callNum", ",", "err", ":=", "libseccomp", ".", "GetSyscallFromName", "(", "call", ".", "Name", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", "\n", "}", "\n\n", "// Convert the call's action to the libseccomp equivalent", "callAct", ",", "err", ":=", "getAction", "(", "call", ".", "Action", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "// Unconditional match - just add the rule", "if", "len", "(", "call", ".", "Args", ")", "==", "0", "{", "if", "err", "=", "filter", ".", "AddRule", "(", "callNum", ",", "callAct", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "call", ".", "Name", ",", "err", ")", "\n", "}", "\n", "}", "else", "{", "// If two or more arguments have the same condition,", "// Revert to old behavior, adding each condition as a separate rule", "argCounts", ":=", "make", "(", "[", "]", "uint", ",", "syscallMaxArguments", ")", "\n", "conditions", ":=", "[", "]", "libseccomp", ".", "ScmpCondition", "{", "}", "\n\n", "for", "_", ",", "cond", ":=", "range", "call", ".", "Args", "{", "newCond", ",", "err", ":=", "getCondition", "(", "cond", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "call", ".", "Name", ",", "err", ")", "\n", "}", "\n\n", "argCounts", "[", "cond", ".", "Index", "]", "+=", "1", "\n\n", "conditions", "=", "append", "(", "conditions", ",", "newCond", ")", "\n", "}", "\n\n", "hasMultipleArgs", ":=", "false", "\n", "for", "_", ",", "count", ":=", "range", "argCounts", "{", "if", "count", ">", "1", "{", "hasMultipleArgs", "=", "true", "\n", "break", "\n", "}", "\n", "}", "\n\n", "if", "hasMultipleArgs", "{", "// Revert to old behavior", "// Add each condition attached to a separate rule", "for", "_", ",", "cond", ":=", "range", "conditions", "{", "condArr", ":=", "[", "]", "libseccomp", ".", "ScmpCondition", "{", "cond", "}", "\n\n", "if", "err", "=", "filter", ".", "AddRuleConditional", "(", "callNum", ",", "callAct", ",", "condArr", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "call", ".", "Name", ",", "err", ")", "\n", "}", "\n", "}", "\n", "}", "else", "{", "// No conditions share same argument", "// Use new, proper behavior", "if", "err", "=", "filter", ".", "AddRuleConditional", "(", "callNum", ",", "callAct", ",", "conditions", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "call", ".", "Name", ",", "err", ")", "\n", "}", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Add a rule to match a single syscall
[ "Add", "a", "rule", "to", "match", "a", "single", "syscall" ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/seccomp/seccomp_linux.go#L159-L231
164,516
opencontainers/runc
libcontainer/configs/blkio_device.go
NewWeightDevice
func NewWeightDevice(major, minor int64, weight, leafWeight uint16) *WeightDevice { wd := &WeightDevice{} wd.Major = major wd.Minor = minor wd.Weight = weight wd.LeafWeight = leafWeight return wd }
go
func NewWeightDevice(major, minor int64, weight, leafWeight uint16) *WeightDevice { wd := &WeightDevice{} wd.Major = major wd.Minor = minor wd.Weight = weight wd.LeafWeight = leafWeight return wd }
[ "func", "NewWeightDevice", "(", "major", ",", "minor", "int64", ",", "weight", ",", "leafWeight", "uint16", ")", "*", "WeightDevice", "{", "wd", ":=", "&", "WeightDevice", "{", "}", "\n", "wd", ".", "Major", "=", "major", "\n", "wd", ".", "Minor", "=", "minor", "\n", "wd", ".", "Weight", "=", "weight", "\n", "wd", ".", "LeafWeight", "=", "leafWeight", "\n", "return", "wd", "\n", "}" ]
// NewWeightDevice returns a configured WeightDevice pointer
[ "NewWeightDevice", "returns", "a", "configured", "WeightDevice", "pointer" ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/configs/blkio_device.go#L23-L30
164,517
opencontainers/runc
libcontainer/configs/blkio_device.go
WeightString
func (wd *WeightDevice) WeightString() string { return fmt.Sprintf("%d:%d %d", wd.Major, wd.Minor, wd.Weight) }
go
func (wd *WeightDevice) WeightString() string { return fmt.Sprintf("%d:%d %d", wd.Major, wd.Minor, wd.Weight) }
[ "func", "(", "wd", "*", "WeightDevice", ")", "WeightString", "(", ")", "string", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "wd", ".", "Major", ",", "wd", ".", "Minor", ",", "wd", ".", "Weight", ")", "\n", "}" ]
// WeightString formats the struct to be writable to the cgroup specific file
[ "WeightString", "formats", "the", "struct", "to", "be", "writable", "to", "the", "cgroup", "specific", "file" ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/configs/blkio_device.go#L33-L35
164,518
opencontainers/runc
libcontainer/configs/blkio_device.go
LeafWeightString
func (wd *WeightDevice) LeafWeightString() string { return fmt.Sprintf("%d:%d %d", wd.Major, wd.Minor, wd.LeafWeight) }
go
func (wd *WeightDevice) LeafWeightString() string { return fmt.Sprintf("%d:%d %d", wd.Major, wd.Minor, wd.LeafWeight) }
[ "func", "(", "wd", "*", "WeightDevice", ")", "LeafWeightString", "(", ")", "string", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "wd", ".", "Major", ",", "wd", ".", "Minor", ",", "wd", ".", "LeafWeight", ")", "\n", "}" ]
// LeafWeightString formats the struct to be writable to the cgroup specific file
[ "LeafWeightString", "formats", "the", "struct", "to", "be", "writable", "to", "the", "cgroup", "specific", "file" ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/configs/blkio_device.go#L38-L40
164,519
opencontainers/runc
libcontainer/configs/blkio_device.go
NewThrottleDevice
func NewThrottleDevice(major, minor int64, rate uint64) *ThrottleDevice { td := &ThrottleDevice{} td.Major = major td.Minor = minor td.Rate = rate return td }
go
func NewThrottleDevice(major, minor int64, rate uint64) *ThrottleDevice { td := &ThrottleDevice{} td.Major = major td.Minor = minor td.Rate = rate return td }
[ "func", "NewThrottleDevice", "(", "major", ",", "minor", "int64", ",", "rate", "uint64", ")", "*", "ThrottleDevice", "{", "td", ":=", "&", "ThrottleDevice", "{", "}", "\n", "td", ".", "Major", "=", "major", "\n", "td", ".", "Minor", "=", "minor", "\n", "td", ".", "Rate", "=", "rate", "\n", "return", "td", "\n", "}" ]
// NewThrottleDevice returns a configured ThrottleDevice pointer
[ "NewThrottleDevice", "returns", "a", "configured", "ThrottleDevice", "pointer" ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/configs/blkio_device.go#L50-L56
164,520
opencontainers/runc
libcontainer/configs/blkio_device.go
String
func (td *ThrottleDevice) String() string { return fmt.Sprintf("%d:%d %d", td.Major, td.Minor, td.Rate) }
go
func (td *ThrottleDevice) String() string { return fmt.Sprintf("%d:%d %d", td.Major, td.Minor, td.Rate) }
[ "func", "(", "td", "*", "ThrottleDevice", ")", "String", "(", ")", "string", "{", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "td", ".", "Major", ",", "td", ".", "Minor", ",", "td", ".", "Rate", ")", "\n", "}" ]
// String formats the struct to be writable to the cgroup specific file
[ "String", "formats", "the", "struct", "to", "be", "writable", "to", "the", "cgroup", "specific", "file" ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/configs/blkio_device.go#L59-L61
164,521
opencontainers/runc
libcontainer/configs/namespaces_syscall.go
CloneFlags
func (n *Namespaces) CloneFlags() uintptr { var flag int for _, v := range *n { if v.Path != "" { continue } flag |= namespaceInfo[v.Type] } return uintptr(flag) }
go
func (n *Namespaces) CloneFlags() uintptr { var flag int for _, v := range *n { if v.Path != "" { continue } flag |= namespaceInfo[v.Type] } return uintptr(flag) }
[ "func", "(", "n", "*", "Namespaces", ")", "CloneFlags", "(", ")", "uintptr", "{", "var", "flag", "int", "\n", "for", "_", ",", "v", ":=", "range", "*", "n", "{", "if", "v", ".", "Path", "!=", "\"", "\"", "{", "continue", "\n", "}", "\n", "flag", "|=", "namespaceInfo", "[", "v", ".", "Type", "]", "\n", "}", "\n", "return", "uintptr", "(", "flag", ")", "\n", "}" ]
// CloneFlags parses the container's Namespaces options to set the correct // flags on clone, unshare. This function returns flags only for new namespaces.
[ "CloneFlags", "parses", "the", "container", "s", "Namespaces", "options", "to", "set", "the", "correct", "flags", "on", "clone", "unshare", ".", "This", "function", "returns", "flags", "only", "for", "new", "namespaces", "." ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/configs/namespaces_syscall.go#L23-L32
164,522
opencontainers/runc
libcontainer/apparmor/apparmor.go
changeOnExec
func changeOnExec(name string) error { value := "exec " + name if err := setprocattr("exec", value); err != nil { return fmt.Errorf("apparmor failed to apply profile: %s", err) } return nil }
go
func changeOnExec(name string) error { value := "exec " + name if err := setprocattr("exec", value); err != nil { return fmt.Errorf("apparmor failed to apply profile: %s", err) } return nil }
[ "func", "changeOnExec", "(", "name", "string", ")", "error", "{", "value", ":=", "\"", "\"", "+", "name", "\n", "if", "err", ":=", "setprocattr", "(", "\"", "\"", ",", "value", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// changeOnExec reimplements aa_change_onexec from libapparmor in Go
[ "changeOnExec", "reimplements", "aa_change_onexec", "from", "libapparmor", "in", "Go" ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/apparmor/apparmor.go#L38-L44
164,523
opencontainers/runc
libcontainer/console_linux.go
mountConsole
func mountConsole(slavePath string) error { oldMask := unix.Umask(0000) defer unix.Umask(oldMask) f, err := os.Create("/dev/console") if err != nil && !os.IsExist(err) { return err } if f != nil { f.Close() } return unix.Mount(slavePath, "/dev/console", "bind", unix.MS_BIND, "") }
go
func mountConsole(slavePath string) error { oldMask := unix.Umask(0000) defer unix.Umask(oldMask) f, err := os.Create("/dev/console") if err != nil && !os.IsExist(err) { return err } if f != nil { f.Close() } return unix.Mount(slavePath, "/dev/console", "bind", unix.MS_BIND, "") }
[ "func", "mountConsole", "(", "slavePath", "string", ")", "error", "{", "oldMask", ":=", "unix", ".", "Umask", "(", "0000", ")", "\n", "defer", "unix", ".", "Umask", "(", "oldMask", ")", "\n", "f", ",", "err", ":=", "os", ".", "Create", "(", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "&&", "!", "os", ".", "IsExist", "(", "err", ")", "{", "return", "err", "\n", "}", "\n", "if", "f", "!=", "nil", "{", "f", ".", "Close", "(", ")", "\n", "}", "\n", "return", "unix", ".", "Mount", "(", "slavePath", ",", "\"", "\"", ",", "\"", "\"", ",", "unix", ".", "MS_BIND", ",", "\"", "\"", ")", "\n", "}" ]
// mount initializes the console inside the rootfs mounting with the specified mount label // and applying the correct ownership of the console.
[ "mount", "initializes", "the", "console", "inside", "the", "rootfs", "mounting", "with", "the", "specified", "mount", "label", "and", "applying", "the", "correct", "ownership", "of", "the", "console", "." ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/console_linux.go#L11-L22
164,524
opencontainers/runc
libcontainer/console_linux.go
dupStdio
func dupStdio(slavePath string) error { fd, err := unix.Open(slavePath, unix.O_RDWR, 0) if err != nil { return &os.PathError{ Op: "open", Path: slavePath, Err: err, } } for _, i := range []int{0, 1, 2} { if err := unix.Dup3(fd, i, 0); err != nil { return err } } return nil }
go
func dupStdio(slavePath string) error { fd, err := unix.Open(slavePath, unix.O_RDWR, 0) if err != nil { return &os.PathError{ Op: "open", Path: slavePath, Err: err, } } for _, i := range []int{0, 1, 2} { if err := unix.Dup3(fd, i, 0); err != nil { return err } } return nil }
[ "func", "dupStdio", "(", "slavePath", "string", ")", "error", "{", "fd", ",", "err", ":=", "unix", ".", "Open", "(", "slavePath", ",", "unix", ".", "O_RDWR", ",", "0", ")", "\n", "if", "err", "!=", "nil", "{", "return", "&", "os", ".", "PathError", "{", "Op", ":", "\"", "\"", ",", "Path", ":", "slavePath", ",", "Err", ":", "err", ",", "}", "\n", "}", "\n", "for", "_", ",", "i", ":=", "range", "[", "]", "int", "{", "0", ",", "1", ",", "2", "}", "{", "if", "err", ":=", "unix", ".", "Dup3", "(", "fd", ",", "i", ",", "0", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// dupStdio opens the slavePath for the console and dups the fds to the current // processes stdio, fd 0,1,2.
[ "dupStdio", "opens", "the", "slavePath", "for", "the", "console", "and", "dups", "the", "fds", "to", "the", "current", "processes", "stdio", "fd", "0", "1", "2", "." ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/console_linux.go#L26-L41
164,525
opencontainers/runc
utils_linux.go
loadFactory
func loadFactory(context *cli.Context) (libcontainer.Factory, error) { root := context.GlobalString("root") abs, err := filepath.Abs(root) if err != nil { return nil, err } // We default to cgroupfs, and can only use systemd if the system is a // systemd box. cgroupManager := libcontainer.Cgroupfs rootlessCg, err := shouldUseRootlessCgroupManager(context) if err != nil { return nil, err } if rootlessCg { cgroupManager = libcontainer.RootlessCgroupfs } if context.GlobalBool("systemd-cgroup") { if systemd.UseSystemd() { cgroupManager = libcontainer.SystemdCgroups } else { return nil, fmt.Errorf("systemd cgroup flag passed, but systemd support for managing cgroups is not available") } } intelRdtManager := libcontainer.IntelRdtFs if !intelrdt.IsCatEnabled() && !intelrdt.IsMbaEnabled() { intelRdtManager = nil } // We resolve the paths for {newuidmap,newgidmap} from the context of runc, // to avoid doing a path lookup in the nsexec context. TODO: The binary // names are not currently configurable. newuidmap, err := exec.LookPath("newuidmap") if err != nil { newuidmap = "" } newgidmap, err := exec.LookPath("newgidmap") if err != nil { newgidmap = "" } return libcontainer.New(abs, cgroupManager, intelRdtManager, libcontainer.CriuPath(context.GlobalString("criu")), libcontainer.NewuidmapPath(newuidmap), libcontainer.NewgidmapPath(newgidmap)) }
go
func loadFactory(context *cli.Context) (libcontainer.Factory, error) { root := context.GlobalString("root") abs, err := filepath.Abs(root) if err != nil { return nil, err } // We default to cgroupfs, and can only use systemd if the system is a // systemd box. cgroupManager := libcontainer.Cgroupfs rootlessCg, err := shouldUseRootlessCgroupManager(context) if err != nil { return nil, err } if rootlessCg { cgroupManager = libcontainer.RootlessCgroupfs } if context.GlobalBool("systemd-cgroup") { if systemd.UseSystemd() { cgroupManager = libcontainer.SystemdCgroups } else { return nil, fmt.Errorf("systemd cgroup flag passed, but systemd support for managing cgroups is not available") } } intelRdtManager := libcontainer.IntelRdtFs if !intelrdt.IsCatEnabled() && !intelrdt.IsMbaEnabled() { intelRdtManager = nil } // We resolve the paths for {newuidmap,newgidmap} from the context of runc, // to avoid doing a path lookup in the nsexec context. TODO: The binary // names are not currently configurable. newuidmap, err := exec.LookPath("newuidmap") if err != nil { newuidmap = "" } newgidmap, err := exec.LookPath("newgidmap") if err != nil { newgidmap = "" } return libcontainer.New(abs, cgroupManager, intelRdtManager, libcontainer.CriuPath(context.GlobalString("criu")), libcontainer.NewuidmapPath(newuidmap), libcontainer.NewgidmapPath(newgidmap)) }
[ "func", "loadFactory", "(", "context", "*", "cli", ".", "Context", ")", "(", "libcontainer", ".", "Factory", ",", "error", ")", "{", "root", ":=", "context", ".", "GlobalString", "(", "\"", "\"", ")", "\n", "abs", ",", "err", ":=", "filepath", ".", "Abs", "(", "root", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// We default to cgroupfs, and can only use systemd if the system is a", "// systemd box.", "cgroupManager", ":=", "libcontainer", ".", "Cgroupfs", "\n", "rootlessCg", ",", "err", ":=", "shouldUseRootlessCgroupManager", "(", "context", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "rootlessCg", "{", "cgroupManager", "=", "libcontainer", ".", "RootlessCgroupfs", "\n", "}", "\n", "if", "context", ".", "GlobalBool", "(", "\"", "\"", ")", "{", "if", "systemd", ".", "UseSystemd", "(", ")", "{", "cgroupManager", "=", "libcontainer", ".", "SystemdCgroups", "\n", "}", "else", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "\n\n", "intelRdtManager", ":=", "libcontainer", ".", "IntelRdtFs", "\n", "if", "!", "intelrdt", ".", "IsCatEnabled", "(", ")", "&&", "!", "intelrdt", ".", "IsMbaEnabled", "(", ")", "{", "intelRdtManager", "=", "nil", "\n", "}", "\n\n", "// We resolve the paths for {newuidmap,newgidmap} from the context of runc,", "// to avoid doing a path lookup in the nsexec context. TODO: The binary", "// names are not currently configurable.", "newuidmap", ",", "err", ":=", "exec", ".", "LookPath", "(", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "newuidmap", "=", "\"", "\"", "\n", "}", "\n", "newgidmap", ",", "err", ":=", "exec", ".", "LookPath", "(", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "newgidmap", "=", "\"", "\"", "\n", "}", "\n\n", "return", "libcontainer", ".", "New", "(", "abs", ",", "cgroupManager", ",", "intelRdtManager", ",", "libcontainer", ".", "CriuPath", "(", "context", ".", "GlobalString", "(", "\"", "\"", ")", ")", ",", "libcontainer", ".", "NewuidmapPath", "(", "newuidmap", ")", ",", "libcontainer", ".", "NewgidmapPath", "(", "newgidmap", ")", ")", "\n", "}" ]
// loadFactory returns the configured factory instance for execing containers.
[ "loadFactory", "returns", "the", "configured", "factory", "instance", "for", "execing", "containers", "." ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/utils_linux.go#L32-L78
164,526
opencontainers/runc
utils_linux.go
getContainer
func getContainer(context *cli.Context) (libcontainer.Container, error) { id := context.Args().First() if id == "" { return nil, errEmptyID } factory, err := loadFactory(context) if err != nil { return nil, err } return factory.Load(id) }
go
func getContainer(context *cli.Context) (libcontainer.Container, error) { id := context.Args().First() if id == "" { return nil, errEmptyID } factory, err := loadFactory(context) if err != nil { return nil, err } return factory.Load(id) }
[ "func", "getContainer", "(", "context", "*", "cli", ".", "Context", ")", "(", "libcontainer", ".", "Container", ",", "error", ")", "{", "id", ":=", "context", ".", "Args", "(", ")", ".", "First", "(", ")", "\n", "if", "id", "==", "\"", "\"", "{", "return", "nil", ",", "errEmptyID", "\n", "}", "\n", "factory", ",", "err", ":=", "loadFactory", "(", "context", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "factory", ".", "Load", "(", "id", ")", "\n", "}" ]
// getContainer returns the specified container instance by loading it from state // with the default factory.
[ "getContainer", "returns", "the", "specified", "container", "instance", "by", "loading", "it", "from", "state", "with", "the", "default", "factory", "." ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/utils_linux.go#L82-L92
164,527
opencontainers/runc
utils_linux.go
newProcess
func newProcess(p specs.Process, init bool) (*libcontainer.Process, error) { lp := &libcontainer.Process{ Args: p.Args, Env: p.Env, // TODO: fix libcontainer's API to better support uid/gid in a typesafe way. User: fmt.Sprintf("%d:%d", p.User.UID, p.User.GID), Cwd: p.Cwd, Label: p.SelinuxLabel, NoNewPrivileges: &p.NoNewPrivileges, AppArmorProfile: p.ApparmorProfile, Init: init, } if p.ConsoleSize != nil { lp.ConsoleWidth = uint16(p.ConsoleSize.Width) lp.ConsoleHeight = uint16(p.ConsoleSize.Height) } if p.Capabilities != nil { lp.Capabilities = &configs.Capabilities{} lp.Capabilities.Bounding = p.Capabilities.Bounding lp.Capabilities.Effective = p.Capabilities.Effective lp.Capabilities.Inheritable = p.Capabilities.Inheritable lp.Capabilities.Permitted = p.Capabilities.Permitted lp.Capabilities.Ambient = p.Capabilities.Ambient } for _, gid := range p.User.AdditionalGids { lp.AdditionalGroups = append(lp.AdditionalGroups, strconv.FormatUint(uint64(gid), 10)) } for _, rlimit := range p.Rlimits { rl, err := createLibContainerRlimit(rlimit) if err != nil { return nil, err } lp.Rlimits = append(lp.Rlimits, rl) } return lp, nil }
go
func newProcess(p specs.Process, init bool) (*libcontainer.Process, error) { lp := &libcontainer.Process{ Args: p.Args, Env: p.Env, // TODO: fix libcontainer's API to better support uid/gid in a typesafe way. User: fmt.Sprintf("%d:%d", p.User.UID, p.User.GID), Cwd: p.Cwd, Label: p.SelinuxLabel, NoNewPrivileges: &p.NoNewPrivileges, AppArmorProfile: p.ApparmorProfile, Init: init, } if p.ConsoleSize != nil { lp.ConsoleWidth = uint16(p.ConsoleSize.Width) lp.ConsoleHeight = uint16(p.ConsoleSize.Height) } if p.Capabilities != nil { lp.Capabilities = &configs.Capabilities{} lp.Capabilities.Bounding = p.Capabilities.Bounding lp.Capabilities.Effective = p.Capabilities.Effective lp.Capabilities.Inheritable = p.Capabilities.Inheritable lp.Capabilities.Permitted = p.Capabilities.Permitted lp.Capabilities.Ambient = p.Capabilities.Ambient } for _, gid := range p.User.AdditionalGids { lp.AdditionalGroups = append(lp.AdditionalGroups, strconv.FormatUint(uint64(gid), 10)) } for _, rlimit := range p.Rlimits { rl, err := createLibContainerRlimit(rlimit) if err != nil { return nil, err } lp.Rlimits = append(lp.Rlimits, rl) } return lp, nil }
[ "func", "newProcess", "(", "p", "specs", ".", "Process", ",", "init", "bool", ")", "(", "*", "libcontainer", ".", "Process", ",", "error", ")", "{", "lp", ":=", "&", "libcontainer", ".", "Process", "{", "Args", ":", "p", ".", "Args", ",", "Env", ":", "p", ".", "Env", ",", "// TODO: fix libcontainer's API to better support uid/gid in a typesafe way.", "User", ":", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "p", ".", "User", ".", "UID", ",", "p", ".", "User", ".", "GID", ")", ",", "Cwd", ":", "p", ".", "Cwd", ",", "Label", ":", "p", ".", "SelinuxLabel", ",", "NoNewPrivileges", ":", "&", "p", ".", "NoNewPrivileges", ",", "AppArmorProfile", ":", "p", ".", "ApparmorProfile", ",", "Init", ":", "init", ",", "}", "\n\n", "if", "p", ".", "ConsoleSize", "!=", "nil", "{", "lp", ".", "ConsoleWidth", "=", "uint16", "(", "p", ".", "ConsoleSize", ".", "Width", ")", "\n", "lp", ".", "ConsoleHeight", "=", "uint16", "(", "p", ".", "ConsoleSize", ".", "Height", ")", "\n", "}", "\n\n", "if", "p", ".", "Capabilities", "!=", "nil", "{", "lp", ".", "Capabilities", "=", "&", "configs", ".", "Capabilities", "{", "}", "\n", "lp", ".", "Capabilities", ".", "Bounding", "=", "p", ".", "Capabilities", ".", "Bounding", "\n", "lp", ".", "Capabilities", ".", "Effective", "=", "p", ".", "Capabilities", ".", "Effective", "\n", "lp", ".", "Capabilities", ".", "Inheritable", "=", "p", ".", "Capabilities", ".", "Inheritable", "\n", "lp", ".", "Capabilities", ".", "Permitted", "=", "p", ".", "Capabilities", ".", "Permitted", "\n", "lp", ".", "Capabilities", ".", "Ambient", "=", "p", ".", "Capabilities", ".", "Ambient", "\n", "}", "\n", "for", "_", ",", "gid", ":=", "range", "p", ".", "User", ".", "AdditionalGids", "{", "lp", ".", "AdditionalGroups", "=", "append", "(", "lp", ".", "AdditionalGroups", ",", "strconv", ".", "FormatUint", "(", "uint64", "(", "gid", ")", ",", "10", ")", ")", "\n", "}", "\n", "for", "_", ",", "rlimit", ":=", "range", "p", ".", "Rlimits", "{", "rl", ",", "err", ":=", "createLibContainerRlimit", "(", "rlimit", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "lp", ".", "Rlimits", "=", "append", "(", "lp", ".", "Rlimits", ",", "rl", ")", "\n", "}", "\n", "return", "lp", ",", "nil", "\n", "}" ]
// newProcess returns a new libcontainer Process with the arguments from the // spec and stdio from the current process.
[ "newProcess", "returns", "a", "new", "libcontainer", "Process", "with", "the", "arguments", "from", "the", "spec", "and", "stdio", "from", "the", "current", "process", "." ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/utils_linux.go#L108-L145
164,528
opencontainers/runc
utils_linux.go
setupIO
func setupIO(process *libcontainer.Process, rootuid, rootgid int, createTTY, detach bool, sockpath string) (*tty, error) { if createTTY { process.Stdin = nil process.Stdout = nil process.Stderr = nil t := &tty{} if !detach { parent, child, err := utils.NewSockPair("console") if err != nil { return nil, err } process.ConsoleSocket = child t.postStart = append(t.postStart, parent, child) t.consoleC = make(chan error, 1) go func() { if err := t.recvtty(process, parent); err != nil { t.consoleC <- err } t.consoleC <- nil }() } else { // the caller of runc will handle receiving the console master conn, err := net.Dial("unix", sockpath) if err != nil { return nil, err } uc, ok := conn.(*net.UnixConn) if !ok { return nil, fmt.Errorf("casting to UnixConn failed") } t.postStart = append(t.postStart, uc) socket, err := uc.File() if err != nil { return nil, err } t.postStart = append(t.postStart, socket) process.ConsoleSocket = socket } return t, nil } // when runc will detach the caller provides the stdio to runc via runc's 0,1,2 // and the container's process inherits runc's stdio. if detach { if err := inheritStdio(process); err != nil { return nil, err } return &tty{}, nil } return setupProcessPipes(process, rootuid, rootgid) }
go
func setupIO(process *libcontainer.Process, rootuid, rootgid int, createTTY, detach bool, sockpath string) (*tty, error) { if createTTY { process.Stdin = nil process.Stdout = nil process.Stderr = nil t := &tty{} if !detach { parent, child, err := utils.NewSockPair("console") if err != nil { return nil, err } process.ConsoleSocket = child t.postStart = append(t.postStart, parent, child) t.consoleC = make(chan error, 1) go func() { if err := t.recvtty(process, parent); err != nil { t.consoleC <- err } t.consoleC <- nil }() } else { // the caller of runc will handle receiving the console master conn, err := net.Dial("unix", sockpath) if err != nil { return nil, err } uc, ok := conn.(*net.UnixConn) if !ok { return nil, fmt.Errorf("casting to UnixConn failed") } t.postStart = append(t.postStart, uc) socket, err := uc.File() if err != nil { return nil, err } t.postStart = append(t.postStart, socket) process.ConsoleSocket = socket } return t, nil } // when runc will detach the caller provides the stdio to runc via runc's 0,1,2 // and the container's process inherits runc's stdio. if detach { if err := inheritStdio(process); err != nil { return nil, err } return &tty{}, nil } return setupProcessPipes(process, rootuid, rootgid) }
[ "func", "setupIO", "(", "process", "*", "libcontainer", ".", "Process", ",", "rootuid", ",", "rootgid", "int", ",", "createTTY", ",", "detach", "bool", ",", "sockpath", "string", ")", "(", "*", "tty", ",", "error", ")", "{", "if", "createTTY", "{", "process", ".", "Stdin", "=", "nil", "\n", "process", ".", "Stdout", "=", "nil", "\n", "process", ".", "Stderr", "=", "nil", "\n", "t", ":=", "&", "tty", "{", "}", "\n", "if", "!", "detach", "{", "parent", ",", "child", ",", "err", ":=", "utils", ".", "NewSockPair", "(", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "process", ".", "ConsoleSocket", "=", "child", "\n", "t", ".", "postStart", "=", "append", "(", "t", ".", "postStart", ",", "parent", ",", "child", ")", "\n", "t", ".", "consoleC", "=", "make", "(", "chan", "error", ",", "1", ")", "\n", "go", "func", "(", ")", "{", "if", "err", ":=", "t", ".", "recvtty", "(", "process", ",", "parent", ")", ";", "err", "!=", "nil", "{", "t", ".", "consoleC", "<-", "err", "\n", "}", "\n", "t", ".", "consoleC", "<-", "nil", "\n", "}", "(", ")", "\n", "}", "else", "{", "// the caller of runc will handle receiving the console master", "conn", ",", "err", ":=", "net", ".", "Dial", "(", "\"", "\"", ",", "sockpath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "uc", ",", "ok", ":=", "conn", ".", "(", "*", "net", ".", "UnixConn", ")", "\n", "if", "!", "ok", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "t", ".", "postStart", "=", "append", "(", "t", ".", "postStart", ",", "uc", ")", "\n", "socket", ",", "err", ":=", "uc", ".", "File", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "t", ".", "postStart", "=", "append", "(", "t", ".", "postStart", ",", "socket", ")", "\n", "process", ".", "ConsoleSocket", "=", "socket", "\n", "}", "\n", "return", "t", ",", "nil", "\n", "}", "\n", "// when runc will detach the caller provides the stdio to runc via runc's 0,1,2", "// and the container's process inherits runc's stdio.", "if", "detach", "{", "if", "err", ":=", "inheritStdio", "(", "process", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "&", "tty", "{", "}", ",", "nil", "\n", "}", "\n", "return", "setupProcessPipes", "(", "process", ",", "rootuid", ",", "rootgid", ")", "\n", "}" ]
// setupIO modifies the given process config according to the options.
[ "setupIO", "modifies", "the", "given", "process", "config", "according", "to", "the", "options", "." ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/utils_linux.go#L154-L203
164,529
opencontainers/runc
libcontainer/cgroups/fs/utils.go
parseUint
func parseUint(s string, base, bitSize int) (uint64, error) { value, err := strconv.ParseUint(s, base, bitSize) if err != nil { intValue, intErr := strconv.ParseInt(s, base, bitSize) // 1. Handle negative values greater than MinInt64 (and) // 2. Handle negative values lesser than MinInt64 if intErr == nil && intValue < 0 { return 0, nil } else if intErr != nil && intErr.(*strconv.NumError).Err == strconv.ErrRange && intValue < 0 { return 0, nil } return value, err } return value, nil }
go
func parseUint(s string, base, bitSize int) (uint64, error) { value, err := strconv.ParseUint(s, base, bitSize) if err != nil { intValue, intErr := strconv.ParseInt(s, base, bitSize) // 1. Handle negative values greater than MinInt64 (and) // 2. Handle negative values lesser than MinInt64 if intErr == nil && intValue < 0 { return 0, nil } else if intErr != nil && intErr.(*strconv.NumError).Err == strconv.ErrRange && intValue < 0 { return 0, nil } return value, err } return value, nil }
[ "func", "parseUint", "(", "s", "string", ",", "base", ",", "bitSize", "int", ")", "(", "uint64", ",", "error", ")", "{", "value", ",", "err", ":=", "strconv", ".", "ParseUint", "(", "s", ",", "base", ",", "bitSize", ")", "\n", "if", "err", "!=", "nil", "{", "intValue", ",", "intErr", ":=", "strconv", ".", "ParseInt", "(", "s", ",", "base", ",", "bitSize", ")", "\n", "// 1. Handle negative values greater than MinInt64 (and)", "// 2. Handle negative values lesser than MinInt64", "if", "intErr", "==", "nil", "&&", "intValue", "<", "0", "{", "return", "0", ",", "nil", "\n", "}", "else", "if", "intErr", "!=", "nil", "&&", "intErr", ".", "(", "*", "strconv", ".", "NumError", ")", ".", "Err", "==", "strconv", ".", "ErrRange", "&&", "intValue", "<", "0", "{", "return", "0", ",", "nil", "\n", "}", "\n\n", "return", "value", ",", "err", "\n", "}", "\n\n", "return", "value", ",", "nil", "\n", "}" ]
// Saturates negative values at zero and returns a uint64. // Due to kernel bugs, some of the memory cgroup stats can be negative.
[ "Saturates", "negative", "values", "at", "zero", "and", "returns", "a", "uint64", ".", "Due", "to", "kernel", "bugs", "some", "of", "the", "memory", "cgroup", "stats", "can", "be", "negative", "." ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/cgroups/fs/utils.go#L20-L36
164,530
opencontainers/runc
libcontainer/cgroups/fs/utils.go
getCgroupParamKeyValue
func getCgroupParamKeyValue(t string) (string, uint64, error) { parts := strings.Fields(t) switch len(parts) { case 2: value, err := parseUint(parts[1], 10, 64) if err != nil { return "", 0, fmt.Errorf("unable to convert param value (%q) to uint64: %v", parts[1], err) } return parts[0], value, nil default: return "", 0, ErrNotValidFormat } }
go
func getCgroupParamKeyValue(t string) (string, uint64, error) { parts := strings.Fields(t) switch len(parts) { case 2: value, err := parseUint(parts[1], 10, 64) if err != nil { return "", 0, fmt.Errorf("unable to convert param value (%q) to uint64: %v", parts[1], err) } return parts[0], value, nil default: return "", 0, ErrNotValidFormat } }
[ "func", "getCgroupParamKeyValue", "(", "t", "string", ")", "(", "string", ",", "uint64", ",", "error", ")", "{", "parts", ":=", "strings", ".", "Fields", "(", "t", ")", "\n", "switch", "len", "(", "parts", ")", "{", "case", "2", ":", "value", ",", "err", ":=", "parseUint", "(", "parts", "[", "1", "]", ",", "10", ",", "64", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "0", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "parts", "[", "1", "]", ",", "err", ")", "\n", "}", "\n\n", "return", "parts", "[", "0", "]", ",", "value", ",", "nil", "\n", "default", ":", "return", "\"", "\"", ",", "0", ",", "ErrNotValidFormat", "\n", "}", "\n", "}" ]
// Parses a cgroup param and returns as name, value // i.e. "io_service_bytes 1234" will return as io_service_bytes, 1234
[ "Parses", "a", "cgroup", "param", "and", "returns", "as", "name", "value", "i", ".", "e", ".", "io_service_bytes", "1234", "will", "return", "as", "io_service_bytes", "1234" ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/cgroups/fs/utils.go#L40-L53
164,531
opencontainers/runc
libcontainer/cgroups/fs/utils.go
getCgroupParamUint
func getCgroupParamUint(cgroupPath, cgroupFile string) (uint64, error) { fileName := filepath.Join(cgroupPath, cgroupFile) contents, err := ioutil.ReadFile(fileName) if err != nil { return 0, err } res, err := parseUint(strings.TrimSpace(string(contents)), 10, 64) if err != nil { return res, fmt.Errorf("unable to parse %q as a uint from Cgroup file %q", string(contents), fileName) } return res, nil }
go
func getCgroupParamUint(cgroupPath, cgroupFile string) (uint64, error) { fileName := filepath.Join(cgroupPath, cgroupFile) contents, err := ioutil.ReadFile(fileName) if err != nil { return 0, err } res, err := parseUint(strings.TrimSpace(string(contents)), 10, 64) if err != nil { return res, fmt.Errorf("unable to parse %q as a uint from Cgroup file %q", string(contents), fileName) } return res, nil }
[ "func", "getCgroupParamUint", "(", "cgroupPath", ",", "cgroupFile", "string", ")", "(", "uint64", ",", "error", ")", "{", "fileName", ":=", "filepath", ".", "Join", "(", "cgroupPath", ",", "cgroupFile", ")", "\n", "contents", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "fileName", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n\n", "res", ",", "err", ":=", "parseUint", "(", "strings", ".", "TrimSpace", "(", "string", "(", "contents", ")", ")", ",", "10", ",", "64", ")", "\n", "if", "err", "!=", "nil", "{", "return", "res", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "string", "(", "contents", ")", ",", "fileName", ")", "\n", "}", "\n", "return", "res", ",", "nil", "\n", "}" ]
// Gets a single uint64 value from the specified cgroup file.
[ "Gets", "a", "single", "uint64", "value", "from", "the", "specified", "cgroup", "file", "." ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/cgroups/fs/utils.go#L56-L68
164,532
opencontainers/runc
libcontainer/cgroups/fs/utils.go
getCgroupParamString
func getCgroupParamString(cgroupPath, cgroupFile string) (string, error) { contents, err := ioutil.ReadFile(filepath.Join(cgroupPath, cgroupFile)) if err != nil { return "", err } return strings.TrimSpace(string(contents)), nil }
go
func getCgroupParamString(cgroupPath, cgroupFile string) (string, error) { contents, err := ioutil.ReadFile(filepath.Join(cgroupPath, cgroupFile)) if err != nil { return "", err } return strings.TrimSpace(string(contents)), nil }
[ "func", "getCgroupParamString", "(", "cgroupPath", ",", "cgroupFile", "string", ")", "(", "string", ",", "error", ")", "{", "contents", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "filepath", ".", "Join", "(", "cgroupPath", ",", "cgroupFile", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "return", "strings", ".", "TrimSpace", "(", "string", "(", "contents", ")", ")", ",", "nil", "\n", "}" ]
// Gets a string value from the specified cgroup file
[ "Gets", "a", "string", "value", "from", "the", "specified", "cgroup", "file" ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/cgroups/fs/utils.go#L71-L78
164,533
opencontainers/runc
libcontainer/intelrdt/intelrdt.go
findIntelRdtMountpointDir
func findIntelRdtMountpointDir() (string, error) { f, err := os.Open("/proc/self/mountinfo") if err != nil { return "", err } defer f.Close() s := bufio.NewScanner(f) for s.Scan() { text := s.Text() fields := strings.Split(text, " ") // Safe as mountinfo encodes mountpoints with spaces as \040. index := strings.Index(text, " - ") postSeparatorFields := strings.Fields(text[index+3:]) numPostFields := len(postSeparatorFields) // This is an error as we can't detect if the mount is for "Intel RDT" if numPostFields == 0 { return "", fmt.Errorf("Found no fields post '-' in %q", text) } if postSeparatorFields[0] == "resctrl" { // Check that the mount is properly formatted. if numPostFields < 3 { return "", fmt.Errorf("Error found less than 3 fields post '-' in %q", text) } // Check if MBA Software Controller is enabled through mount option "-o mba_MBps" if strings.Contains(postSeparatorFields[2], "mba_MBps") { isMbaScEnabled = true } return fields[4], nil } } if err := s.Err(); err != nil { return "", err } return "", NewNotFoundError("Intel RDT") }
go
func findIntelRdtMountpointDir() (string, error) { f, err := os.Open("/proc/self/mountinfo") if err != nil { return "", err } defer f.Close() s := bufio.NewScanner(f) for s.Scan() { text := s.Text() fields := strings.Split(text, " ") // Safe as mountinfo encodes mountpoints with spaces as \040. index := strings.Index(text, " - ") postSeparatorFields := strings.Fields(text[index+3:]) numPostFields := len(postSeparatorFields) // This is an error as we can't detect if the mount is for "Intel RDT" if numPostFields == 0 { return "", fmt.Errorf("Found no fields post '-' in %q", text) } if postSeparatorFields[0] == "resctrl" { // Check that the mount is properly formatted. if numPostFields < 3 { return "", fmt.Errorf("Error found less than 3 fields post '-' in %q", text) } // Check if MBA Software Controller is enabled through mount option "-o mba_MBps" if strings.Contains(postSeparatorFields[2], "mba_MBps") { isMbaScEnabled = true } return fields[4], nil } } if err := s.Err(); err != nil { return "", err } return "", NewNotFoundError("Intel RDT") }
[ "func", "findIntelRdtMountpointDir", "(", ")", "(", "string", ",", "error", ")", "{", "f", ",", "err", ":=", "os", ".", "Open", "(", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "defer", "f", ".", "Close", "(", ")", "\n\n", "s", ":=", "bufio", ".", "NewScanner", "(", "f", ")", "\n", "for", "s", ".", "Scan", "(", ")", "{", "text", ":=", "s", ".", "Text", "(", ")", "\n", "fields", ":=", "strings", ".", "Split", "(", "text", ",", "\"", "\"", ")", "\n", "// Safe as mountinfo encodes mountpoints with spaces as \\040.", "index", ":=", "strings", ".", "Index", "(", "text", ",", "\"", "\"", ")", "\n", "postSeparatorFields", ":=", "strings", ".", "Fields", "(", "text", "[", "index", "+", "3", ":", "]", ")", "\n", "numPostFields", ":=", "len", "(", "postSeparatorFields", ")", "\n\n", "// This is an error as we can't detect if the mount is for \"Intel RDT\"", "if", "numPostFields", "==", "0", "{", "return", "\"", "\"", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "text", ")", "\n", "}", "\n\n", "if", "postSeparatorFields", "[", "0", "]", "==", "\"", "\"", "{", "// Check that the mount is properly formatted.", "if", "numPostFields", "<", "3", "{", "return", "\"", "\"", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "text", ")", "\n", "}", "\n\n", "// Check if MBA Software Controller is enabled through mount option \"-o mba_MBps\"", "if", "strings", ".", "Contains", "(", "postSeparatorFields", "[", "2", "]", ",", "\"", "\"", ")", "{", "isMbaScEnabled", "=", "true", "\n", "}", "\n\n", "return", "fields", "[", "4", "]", ",", "nil", "\n", "}", "\n", "}", "\n", "if", "err", ":=", "s", ".", "Err", "(", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "return", "\"", "\"", ",", "NewNotFoundError", "(", "\"", "\"", ")", "\n", "}" ]
// Return the mount point path of Intel RDT "resource control" filesysem
[ "Return", "the", "mount", "point", "path", "of", "Intel", "RDT", "resource", "control", "filesysem" ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/intelrdt/intelrdt.go#L228-L268
164,534
opencontainers/runc
libcontainer/intelrdt/intelrdt.go
getIntelRdtRoot
func getIntelRdtRoot() (string, error) { intelRdtRootLock.Lock() defer intelRdtRootLock.Unlock() if intelRdtRoot != "" { return intelRdtRoot, nil } root, err := findIntelRdtMountpointDir() if err != nil { return "", err } if _, err := os.Stat(root); err != nil { return "", err } intelRdtRoot = root return intelRdtRoot, nil }
go
func getIntelRdtRoot() (string, error) { intelRdtRootLock.Lock() defer intelRdtRootLock.Unlock() if intelRdtRoot != "" { return intelRdtRoot, nil } root, err := findIntelRdtMountpointDir() if err != nil { return "", err } if _, err := os.Stat(root); err != nil { return "", err } intelRdtRoot = root return intelRdtRoot, nil }
[ "func", "getIntelRdtRoot", "(", ")", "(", "string", ",", "error", ")", "{", "intelRdtRootLock", ".", "Lock", "(", ")", "\n", "defer", "intelRdtRootLock", ".", "Unlock", "(", ")", "\n\n", "if", "intelRdtRoot", "!=", "\"", "\"", "{", "return", "intelRdtRoot", ",", "nil", "\n", "}", "\n\n", "root", ",", "err", ":=", "findIntelRdtMountpointDir", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "if", "_", ",", "err", ":=", "os", ".", "Stat", "(", "root", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "intelRdtRoot", "=", "root", "\n", "return", "intelRdtRoot", ",", "nil", "\n", "}" ]
// Gets the root path of Intel RDT "resource control" filesystem
[ "Gets", "the", "root", "path", "of", "Intel", "RDT", "resource", "control", "filesystem" ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/intelrdt/intelrdt.go#L271-L290
164,535
opencontainers/runc
libcontainer/intelrdt/intelrdt.go
getIntelRdtParamUint
func getIntelRdtParamUint(path, file string) (uint64, error) { fileName := filepath.Join(path, file) contents, err := ioutil.ReadFile(fileName) if err != nil { return 0, err } res, err := parseUint(strings.TrimSpace(string(contents)), 10, 64) if err != nil { return res, fmt.Errorf("unable to parse %q as a uint from file %q", string(contents), fileName) } return res, nil }
go
func getIntelRdtParamUint(path, file string) (uint64, error) { fileName := filepath.Join(path, file) contents, err := ioutil.ReadFile(fileName) if err != nil { return 0, err } res, err := parseUint(strings.TrimSpace(string(contents)), 10, 64) if err != nil { return res, fmt.Errorf("unable to parse %q as a uint from file %q", string(contents), fileName) } return res, nil }
[ "func", "getIntelRdtParamUint", "(", "path", ",", "file", "string", ")", "(", "uint64", ",", "error", ")", "{", "fileName", ":=", "filepath", ".", "Join", "(", "path", ",", "file", ")", "\n", "contents", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "fileName", ")", "\n", "if", "err", "!=", "nil", "{", "return", "0", ",", "err", "\n", "}", "\n\n", "res", ",", "err", ":=", "parseUint", "(", "strings", ".", "TrimSpace", "(", "string", "(", "contents", ")", ")", ",", "10", ",", "64", ")", "\n", "if", "err", "!=", "nil", "{", "return", "res", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "string", "(", "contents", ")", ",", "fileName", ")", "\n", "}", "\n", "return", "res", ",", "nil", "\n", "}" ]
// Gets a single uint64 value from the specified file.
[ "Gets", "a", "single", "uint64", "value", "from", "the", "specified", "file", "." ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/intelrdt/intelrdt.go#L356-L368
164,536
opencontainers/runc
libcontainer/intelrdt/intelrdt.go
getIntelRdtParamString
func getIntelRdtParamString(path, file string) (string, error) { contents, err := ioutil.ReadFile(filepath.Join(path, file)) if err != nil { return "", err } return strings.TrimSpace(string(contents)), nil }
go
func getIntelRdtParamString(path, file string) (string, error) { contents, err := ioutil.ReadFile(filepath.Join(path, file)) if err != nil { return "", err } return strings.TrimSpace(string(contents)), nil }
[ "func", "getIntelRdtParamString", "(", "path", ",", "file", "string", ")", "(", "string", ",", "error", ")", "{", "contents", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "filepath", ".", "Join", "(", "path", ",", "file", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "return", "strings", ".", "TrimSpace", "(", "string", "(", "contents", ")", ")", ",", "nil", "\n", "}" ]
// Gets a string value from the specified file
[ "Gets", "a", "string", "value", "from", "the", "specified", "file" ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/intelrdt/intelrdt.go#L371-L378
164,537
opencontainers/runc
libcontainer/intelrdt/intelrdt.go
getL3CacheInfo
func getL3CacheInfo() (*L3CacheInfo, error) { l3CacheInfo := &L3CacheInfo{} rootPath, err := getIntelRdtRoot() if err != nil { return l3CacheInfo, err } path := filepath.Join(rootPath, "info", "L3") cbmMask, err := getIntelRdtParamString(path, "cbm_mask") if err != nil { return l3CacheInfo, err } minCbmBits, err := getIntelRdtParamUint(path, "min_cbm_bits") if err != nil { return l3CacheInfo, err } numClosids, err := getIntelRdtParamUint(path, "num_closids") if err != nil { return l3CacheInfo, err } l3CacheInfo.CbmMask = cbmMask l3CacheInfo.MinCbmBits = minCbmBits l3CacheInfo.NumClosids = numClosids return l3CacheInfo, nil }
go
func getL3CacheInfo() (*L3CacheInfo, error) { l3CacheInfo := &L3CacheInfo{} rootPath, err := getIntelRdtRoot() if err != nil { return l3CacheInfo, err } path := filepath.Join(rootPath, "info", "L3") cbmMask, err := getIntelRdtParamString(path, "cbm_mask") if err != nil { return l3CacheInfo, err } minCbmBits, err := getIntelRdtParamUint(path, "min_cbm_bits") if err != nil { return l3CacheInfo, err } numClosids, err := getIntelRdtParamUint(path, "num_closids") if err != nil { return l3CacheInfo, err } l3CacheInfo.CbmMask = cbmMask l3CacheInfo.MinCbmBits = minCbmBits l3CacheInfo.NumClosids = numClosids return l3CacheInfo, nil }
[ "func", "getL3CacheInfo", "(", ")", "(", "*", "L3CacheInfo", ",", "error", ")", "{", "l3CacheInfo", ":=", "&", "L3CacheInfo", "{", "}", "\n\n", "rootPath", ",", "err", ":=", "getIntelRdtRoot", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "l3CacheInfo", ",", "err", "\n", "}", "\n\n", "path", ":=", "filepath", ".", "Join", "(", "rootPath", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "cbmMask", ",", "err", ":=", "getIntelRdtParamString", "(", "path", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "l3CacheInfo", ",", "err", "\n", "}", "\n", "minCbmBits", ",", "err", ":=", "getIntelRdtParamUint", "(", "path", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "l3CacheInfo", ",", "err", "\n", "}", "\n", "numClosids", ",", "err", ":=", "getIntelRdtParamUint", "(", "path", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "l3CacheInfo", ",", "err", "\n", "}", "\n\n", "l3CacheInfo", ".", "CbmMask", "=", "cbmMask", "\n", "l3CacheInfo", ".", "MinCbmBits", "=", "minCbmBits", "\n", "l3CacheInfo", ".", "NumClosids", "=", "numClosids", "\n\n", "return", "l3CacheInfo", ",", "nil", "\n", "}" ]
// Get the read-only L3 cache information
[ "Get", "the", "read", "-", "only", "L3", "cache", "information" ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/intelrdt/intelrdt.go#L403-L430
164,538
opencontainers/runc
libcontainer/intelrdt/intelrdt.go
getMemBwInfo
func getMemBwInfo() (*MemBwInfo, error) { memBwInfo := &MemBwInfo{} rootPath, err := getIntelRdtRoot() if err != nil { return memBwInfo, err } path := filepath.Join(rootPath, "info", "MB") bandwidthGran, err := getIntelRdtParamUint(path, "bandwidth_gran") if err != nil { return memBwInfo, err } delayLinear, err := getIntelRdtParamUint(path, "delay_linear") if err != nil { return memBwInfo, err } minBandwidth, err := getIntelRdtParamUint(path, "min_bandwidth") if err != nil { return memBwInfo, err } numClosids, err := getIntelRdtParamUint(path, "num_closids") if err != nil { return memBwInfo, err } memBwInfo.BandwidthGran = bandwidthGran memBwInfo.DelayLinear = delayLinear memBwInfo.MinBandwidth = minBandwidth memBwInfo.NumClosids = numClosids return memBwInfo, nil }
go
func getMemBwInfo() (*MemBwInfo, error) { memBwInfo := &MemBwInfo{} rootPath, err := getIntelRdtRoot() if err != nil { return memBwInfo, err } path := filepath.Join(rootPath, "info", "MB") bandwidthGran, err := getIntelRdtParamUint(path, "bandwidth_gran") if err != nil { return memBwInfo, err } delayLinear, err := getIntelRdtParamUint(path, "delay_linear") if err != nil { return memBwInfo, err } minBandwidth, err := getIntelRdtParamUint(path, "min_bandwidth") if err != nil { return memBwInfo, err } numClosids, err := getIntelRdtParamUint(path, "num_closids") if err != nil { return memBwInfo, err } memBwInfo.BandwidthGran = bandwidthGran memBwInfo.DelayLinear = delayLinear memBwInfo.MinBandwidth = minBandwidth memBwInfo.NumClosids = numClosids return memBwInfo, nil }
[ "func", "getMemBwInfo", "(", ")", "(", "*", "MemBwInfo", ",", "error", ")", "{", "memBwInfo", ":=", "&", "MemBwInfo", "{", "}", "\n\n", "rootPath", ",", "err", ":=", "getIntelRdtRoot", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "memBwInfo", ",", "err", "\n", "}", "\n\n", "path", ":=", "filepath", ".", "Join", "(", "rootPath", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "bandwidthGran", ",", "err", ":=", "getIntelRdtParamUint", "(", "path", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "memBwInfo", ",", "err", "\n", "}", "\n", "delayLinear", ",", "err", ":=", "getIntelRdtParamUint", "(", "path", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "memBwInfo", ",", "err", "\n", "}", "\n", "minBandwidth", ",", "err", ":=", "getIntelRdtParamUint", "(", "path", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "memBwInfo", ",", "err", "\n", "}", "\n", "numClosids", ",", "err", ":=", "getIntelRdtParamUint", "(", "path", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "memBwInfo", ",", "err", "\n", "}", "\n\n", "memBwInfo", ".", "BandwidthGran", "=", "bandwidthGran", "\n", "memBwInfo", ".", "DelayLinear", "=", "delayLinear", "\n", "memBwInfo", ".", "MinBandwidth", "=", "minBandwidth", "\n", "memBwInfo", ".", "NumClosids", "=", "numClosids", "\n\n", "return", "memBwInfo", ",", "nil", "\n", "}" ]
// Get the read-only memory bandwidth information
[ "Get", "the", "read", "-", "only", "memory", "bandwidth", "information" ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/intelrdt/intelrdt.go#L433-L465
164,539
opencontainers/runc
libcontainer/intelrdt/intelrdt.go
WriteIntelRdtTasks
func WriteIntelRdtTasks(dir string, pid int) error { if dir == "" { return fmt.Errorf("no such directory for %s", IntelRdtTasks) } // Don't attach any pid if -1 is specified as a pid if pid != -1 { if err := ioutil.WriteFile(filepath.Join(dir, IntelRdtTasks), []byte(strconv.Itoa(pid)), 0700); err != nil { return fmt.Errorf("failed to write %v to %v: %v", pid, IntelRdtTasks, err) } } return nil }
go
func WriteIntelRdtTasks(dir string, pid int) error { if dir == "" { return fmt.Errorf("no such directory for %s", IntelRdtTasks) } // Don't attach any pid if -1 is specified as a pid if pid != -1 { if err := ioutil.WriteFile(filepath.Join(dir, IntelRdtTasks), []byte(strconv.Itoa(pid)), 0700); err != nil { return fmt.Errorf("failed to write %v to %v: %v", pid, IntelRdtTasks, err) } } return nil }
[ "func", "WriteIntelRdtTasks", "(", "dir", "string", ",", "pid", "int", ")", "error", "{", "if", "dir", "==", "\"", "\"", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "IntelRdtTasks", ")", "\n", "}", "\n\n", "// Don't attach any pid if -1 is specified as a pid", "if", "pid", "!=", "-", "1", "{", "if", "err", ":=", "ioutil", ".", "WriteFile", "(", "filepath", ".", "Join", "(", "dir", ",", "IntelRdtTasks", ")", ",", "[", "]", "byte", "(", "strconv", ".", "Itoa", "(", "pid", ")", ")", ",", "0700", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "pid", ",", "IntelRdtTasks", ",", "err", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// WriteIntelRdtTasks writes the specified pid into the "tasks" file
[ "WriteIntelRdtTasks", "writes", "the", "specified", "pid", "into", "the", "tasks", "file" ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/intelrdt/intelrdt.go#L484-L496
164,540
opencontainers/runc
libcontainer/intelrdt/intelrdt.go
GetIntelRdtPath
func GetIntelRdtPath(id string) (string, error) { rootPath, err := getIntelRdtRoot() if err != nil { return "", err } path := filepath.Join(rootPath, id) return path, nil }
go
func GetIntelRdtPath(id string) (string, error) { rootPath, err := getIntelRdtRoot() if err != nil { return "", err } path := filepath.Join(rootPath, id) return path, nil }
[ "func", "GetIntelRdtPath", "(", "id", "string", ")", "(", "string", ",", "error", ")", "{", "rootPath", ",", "err", ":=", "getIntelRdtRoot", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "path", ":=", "filepath", ".", "Join", "(", "rootPath", ",", "id", ")", "\n", "return", "path", ",", "nil", "\n", "}" ]
// Get the 'container_id' path in Intel RDT "resource control" filesystem
[ "Get", "the", "container_id", "path", "in", "Intel", "RDT", "resource", "control", "filesystem" ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/intelrdt/intelrdt.go#L514-L522
164,541
opencontainers/runc
libcontainer/intelrdt/intelrdt.go
Apply
func (m *IntelRdtManager) Apply(pid int) (err error) { // If intelRdt is not specified in config, we do nothing if m.Config.IntelRdt == nil { return nil } d, err := getIntelRdtData(m.Config, pid) if err != nil && !IsNotFound(err) { return err } m.mu.Lock() defer m.mu.Unlock() path, err := d.join(m.Id) if err != nil { return err } m.Path = path return nil }
go
func (m *IntelRdtManager) Apply(pid int) (err error) { // If intelRdt is not specified in config, we do nothing if m.Config.IntelRdt == nil { return nil } d, err := getIntelRdtData(m.Config, pid) if err != nil && !IsNotFound(err) { return err } m.mu.Lock() defer m.mu.Unlock() path, err := d.join(m.Id) if err != nil { return err } m.Path = path return nil }
[ "func", "(", "m", "*", "IntelRdtManager", ")", "Apply", "(", "pid", "int", ")", "(", "err", "error", ")", "{", "// If intelRdt is not specified in config, we do nothing", "if", "m", ".", "Config", ".", "IntelRdt", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "d", ",", "err", ":=", "getIntelRdtData", "(", "m", ".", "Config", ",", "pid", ")", "\n", "if", "err", "!=", "nil", "&&", "!", "IsNotFound", "(", "err", ")", "{", "return", "err", "\n", "}", "\n\n", "m", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "m", ".", "mu", ".", "Unlock", "(", ")", "\n", "path", ",", "err", ":=", "d", ".", "join", "(", "m", ".", "Id", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "m", ".", "Path", "=", "path", "\n", "return", "nil", "\n", "}" ]
// Applies Intel RDT configuration to the process with the specified pid
[ "Applies", "Intel", "RDT", "configuration", "to", "the", "process", "with", "the", "specified", "pid" ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/intelrdt/intelrdt.go#L525-L544
164,542
opencontainers/runc
libcontainer/intelrdt/intelrdt.go
Destroy
func (m *IntelRdtManager) Destroy() error { m.mu.Lock() defer m.mu.Unlock() if err := os.RemoveAll(m.GetPath()); err != nil { return err } m.Path = "" return nil }
go
func (m *IntelRdtManager) Destroy() error { m.mu.Lock() defer m.mu.Unlock() if err := os.RemoveAll(m.GetPath()); err != nil { return err } m.Path = "" return nil }
[ "func", "(", "m", "*", "IntelRdtManager", ")", "Destroy", "(", ")", "error", "{", "m", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "m", ".", "mu", ".", "Unlock", "(", ")", "\n", "if", "err", ":=", "os", ".", "RemoveAll", "(", "m", ".", "GetPath", "(", ")", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "m", ".", "Path", "=", "\"", "\"", "\n", "return", "nil", "\n", "}" ]
// Destroys the Intel RDT 'container_id' group
[ "Destroys", "the", "Intel", "RDT", "container_id", "group" ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/intelrdt/intelrdt.go#L547-L555
164,543
opencontainers/runc
libcontainer/intelrdt/intelrdt.go
GetPath
func (m *IntelRdtManager) GetPath() string { if m.Path == "" { m.Path, _ = GetIntelRdtPath(m.Id) } return m.Path }
go
func (m *IntelRdtManager) GetPath() string { if m.Path == "" { m.Path, _ = GetIntelRdtPath(m.Id) } return m.Path }
[ "func", "(", "m", "*", "IntelRdtManager", ")", "GetPath", "(", ")", "string", "{", "if", "m", ".", "Path", "==", "\"", "\"", "{", "m", ".", "Path", ",", "_", "=", "GetIntelRdtPath", "(", "m", ".", "Id", ")", "\n", "}", "\n", "return", "m", ".", "Path", "\n", "}" ]
// Returns Intel RDT path to save in a state file and to be able to // restore the object later
[ "Returns", "Intel", "RDT", "path", "to", "save", "in", "a", "state", "file", "and", "to", "be", "able", "to", "restore", "the", "object", "later" ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/intelrdt/intelrdt.go#L559-L564
164,544
opencontainers/runc
libcontainer/intelrdt/intelrdt.go
GetStats
func (m *IntelRdtManager) GetStats() (*Stats, error) { // If intelRdt is not specified in config if m.Config.IntelRdt == nil { return nil, nil } m.mu.Lock() defer m.mu.Unlock() stats := NewStats() rootPath, err := getIntelRdtRoot() if err != nil { return nil, err } // The read-only L3 cache and memory bandwidth schemata in root tmpRootStrings, err := getIntelRdtParamString(rootPath, "schemata") if err != nil { return nil, err } schemaRootStrings := strings.Split(tmpRootStrings, "\n") // The L3 cache and memory bandwidth schemata in 'container_id' group tmpStrings, err := getIntelRdtParamString(m.GetPath(), "schemata") if err != nil { return nil, err } schemaStrings := strings.Split(tmpStrings, "\n") if IsCatEnabled() { // The read-only L3 cache information l3CacheInfo, err := getL3CacheInfo() if err != nil { return nil, err } stats.L3CacheInfo = l3CacheInfo // The read-only L3 cache schema in root for _, schemaRoot := range schemaRootStrings { if strings.Contains(schemaRoot, "L3") { stats.L3CacheSchemaRoot = strings.TrimSpace(schemaRoot) } } // The L3 cache schema in 'container_id' group for _, schema := range schemaStrings { if strings.Contains(schema, "L3") { stats.L3CacheSchema = strings.TrimSpace(schema) } } } if IsMbaEnabled() { // The read-only memory bandwidth information memBwInfo, err := getMemBwInfo() if err != nil { return nil, err } stats.MemBwInfo = memBwInfo // The read-only memory bandwidth information for _, schemaRoot := range schemaRootStrings { if strings.Contains(schemaRoot, "MB") { stats.MemBwSchemaRoot = strings.TrimSpace(schemaRoot) } } // The memory bandwidth schema in 'container_id' group for _, schema := range schemaStrings { if strings.Contains(schema, "MB") { stats.MemBwSchema = strings.TrimSpace(schema) } } } return stats, nil }
go
func (m *IntelRdtManager) GetStats() (*Stats, error) { // If intelRdt is not specified in config if m.Config.IntelRdt == nil { return nil, nil } m.mu.Lock() defer m.mu.Unlock() stats := NewStats() rootPath, err := getIntelRdtRoot() if err != nil { return nil, err } // The read-only L3 cache and memory bandwidth schemata in root tmpRootStrings, err := getIntelRdtParamString(rootPath, "schemata") if err != nil { return nil, err } schemaRootStrings := strings.Split(tmpRootStrings, "\n") // The L3 cache and memory bandwidth schemata in 'container_id' group tmpStrings, err := getIntelRdtParamString(m.GetPath(), "schemata") if err != nil { return nil, err } schemaStrings := strings.Split(tmpStrings, "\n") if IsCatEnabled() { // The read-only L3 cache information l3CacheInfo, err := getL3CacheInfo() if err != nil { return nil, err } stats.L3CacheInfo = l3CacheInfo // The read-only L3 cache schema in root for _, schemaRoot := range schemaRootStrings { if strings.Contains(schemaRoot, "L3") { stats.L3CacheSchemaRoot = strings.TrimSpace(schemaRoot) } } // The L3 cache schema in 'container_id' group for _, schema := range schemaStrings { if strings.Contains(schema, "L3") { stats.L3CacheSchema = strings.TrimSpace(schema) } } } if IsMbaEnabled() { // The read-only memory bandwidth information memBwInfo, err := getMemBwInfo() if err != nil { return nil, err } stats.MemBwInfo = memBwInfo // The read-only memory bandwidth information for _, schemaRoot := range schemaRootStrings { if strings.Contains(schemaRoot, "MB") { stats.MemBwSchemaRoot = strings.TrimSpace(schemaRoot) } } // The memory bandwidth schema in 'container_id' group for _, schema := range schemaStrings { if strings.Contains(schema, "MB") { stats.MemBwSchema = strings.TrimSpace(schema) } } } return stats, nil }
[ "func", "(", "m", "*", "IntelRdtManager", ")", "GetStats", "(", ")", "(", "*", "Stats", ",", "error", ")", "{", "// If intelRdt is not specified in config", "if", "m", ".", "Config", ".", "IntelRdt", "==", "nil", "{", "return", "nil", ",", "nil", "\n", "}", "\n\n", "m", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "m", ".", "mu", ".", "Unlock", "(", ")", "\n", "stats", ":=", "NewStats", "(", ")", "\n\n", "rootPath", ",", "err", ":=", "getIntelRdtRoot", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "// The read-only L3 cache and memory bandwidth schemata in root", "tmpRootStrings", ",", "err", ":=", "getIntelRdtParamString", "(", "rootPath", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "schemaRootStrings", ":=", "strings", ".", "Split", "(", "tmpRootStrings", ",", "\"", "\\n", "\"", ")", "\n\n", "// The L3 cache and memory bandwidth schemata in 'container_id' group", "tmpStrings", ",", "err", ":=", "getIntelRdtParamString", "(", "m", ".", "GetPath", "(", ")", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "schemaStrings", ":=", "strings", ".", "Split", "(", "tmpStrings", ",", "\"", "\\n", "\"", ")", "\n\n", "if", "IsCatEnabled", "(", ")", "{", "// The read-only L3 cache information", "l3CacheInfo", ",", "err", ":=", "getL3CacheInfo", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "stats", ".", "L3CacheInfo", "=", "l3CacheInfo", "\n\n", "// The read-only L3 cache schema in root", "for", "_", ",", "schemaRoot", ":=", "range", "schemaRootStrings", "{", "if", "strings", ".", "Contains", "(", "schemaRoot", ",", "\"", "\"", ")", "{", "stats", ".", "L3CacheSchemaRoot", "=", "strings", ".", "TrimSpace", "(", "schemaRoot", ")", "\n", "}", "\n", "}", "\n\n", "// The L3 cache schema in 'container_id' group", "for", "_", ",", "schema", ":=", "range", "schemaStrings", "{", "if", "strings", ".", "Contains", "(", "schema", ",", "\"", "\"", ")", "{", "stats", ".", "L3CacheSchema", "=", "strings", ".", "TrimSpace", "(", "schema", ")", "\n", "}", "\n", "}", "\n", "}", "\n\n", "if", "IsMbaEnabled", "(", ")", "{", "// The read-only memory bandwidth information", "memBwInfo", ",", "err", ":=", "getMemBwInfo", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "stats", ".", "MemBwInfo", "=", "memBwInfo", "\n\n", "// The read-only memory bandwidth information", "for", "_", ",", "schemaRoot", ":=", "range", "schemaRootStrings", "{", "if", "strings", ".", "Contains", "(", "schemaRoot", ",", "\"", "\"", ")", "{", "stats", ".", "MemBwSchemaRoot", "=", "strings", ".", "TrimSpace", "(", "schemaRoot", ")", "\n", "}", "\n", "}", "\n\n", "// The memory bandwidth schema in 'container_id' group", "for", "_", ",", "schema", ":=", "range", "schemaStrings", "{", "if", "strings", ".", "Contains", "(", "schema", ",", "\"", "\"", ")", "{", "stats", ".", "MemBwSchema", "=", "strings", ".", "TrimSpace", "(", "schema", ")", "\n", "}", "\n", "}", "\n", "}", "\n\n", "return", "stats", ",", "nil", "\n", "}" ]
// Returns statistics for Intel RDT
[ "Returns", "statistics", "for", "Intel", "RDT" ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/intelrdt/intelrdt.go#L567-L642
164,545
opencontainers/runc
libcontainer/intelrdt/intelrdt.go
Set
func (m *IntelRdtManager) Set(container *configs.Config) error { // About L3 cache schema: // It has allocation bitmasks/values for L3 cache on each socket, // which contains L3 cache id and capacity bitmask (CBM). // Format: "L3:<cache_id0>=<cbm0>;<cache_id1>=<cbm1>;..." // For example, on a two-socket machine, the schema line could be: // L3:0=ff;1=c0 // which means L3 cache id 0's CBM is 0xff, and L3 cache id 1's CBM // is 0xc0. // // The valid L3 cache CBM is a *contiguous bits set* and number of // bits that can be set is less than the max bit. The max bits in the // CBM is varied among supported Intel CPU models. Kernel will check // if it is valid when writing. e.g., default value 0xfffff in root // indicates the max bits of CBM is 20 bits, which mapping to entire // L3 cache capacity. Some valid CBM values to set in a group: // 0xf, 0xf0, 0x3ff, 0x1f00 and etc. // // // About memory bandwidth schema: // It has allocation values for memory bandwidth on each socket, which // contains L3 cache id and memory bandwidth. // Format: "MB:<cache_id0>=bandwidth0;<cache_id1>=bandwidth1;..." // For example, on a two-socket machine, the schema line could be: // "MB:0=20;1=70" // // The minimum bandwidth percentage value for each CPU model is // predefined and can be looked up through "info/MB/min_bandwidth". // The bandwidth granularity that is allocated is also dependent on // the CPU model and can be looked up at "info/MB/bandwidth_gran". // The available bandwidth control steps are: min_bw + N * bw_gran. // Intermediate values are rounded to the next control step available // on the hardware. // // If MBA Software Controller is enabled through mount option // "-o mba_MBps": mount -t resctrl resctrl -o mba_MBps /sys/fs/resctrl // We could specify memory bandwidth in "MBps" (Mega Bytes per second) // unit instead of "percentages". The kernel underneath would use a // software feedback mechanism or a "Software Controller" which reads // the actual bandwidth using MBM counters and adjust the memory // bandwidth percentages to ensure: // "actual memory bandwidth < user specified memory bandwidth". // // For example, on a two-socket machine, the schema line could be // "MB:0=5000;1=7000" which means 5000 MBps memory bandwidth limit on // socket 0 and 7000 MBps memory bandwidth limit on socket 1. if container.IntelRdt != nil { path := m.GetPath() l3CacheSchema := container.IntelRdt.L3CacheSchema memBwSchema := container.IntelRdt.MemBwSchema // Write a single joint schema string to schemata file if l3CacheSchema != "" && memBwSchema != "" { if err := writeFile(path, "schemata", l3CacheSchema+"\n"+memBwSchema); err != nil { return NewLastCmdError(err) } } // Write only L3 cache schema string to schemata file if l3CacheSchema != "" && memBwSchema == "" { if err := writeFile(path, "schemata", l3CacheSchema); err != nil { return NewLastCmdError(err) } } // Write only memory bandwidth schema string to schemata file if l3CacheSchema == "" && memBwSchema != "" { if err := writeFile(path, "schemata", memBwSchema); err != nil { return NewLastCmdError(err) } } } return nil }
go
func (m *IntelRdtManager) Set(container *configs.Config) error { // About L3 cache schema: // It has allocation bitmasks/values for L3 cache on each socket, // which contains L3 cache id and capacity bitmask (CBM). // Format: "L3:<cache_id0>=<cbm0>;<cache_id1>=<cbm1>;..." // For example, on a two-socket machine, the schema line could be: // L3:0=ff;1=c0 // which means L3 cache id 0's CBM is 0xff, and L3 cache id 1's CBM // is 0xc0. // // The valid L3 cache CBM is a *contiguous bits set* and number of // bits that can be set is less than the max bit. The max bits in the // CBM is varied among supported Intel CPU models. Kernel will check // if it is valid when writing. e.g., default value 0xfffff in root // indicates the max bits of CBM is 20 bits, which mapping to entire // L3 cache capacity. Some valid CBM values to set in a group: // 0xf, 0xf0, 0x3ff, 0x1f00 and etc. // // // About memory bandwidth schema: // It has allocation values for memory bandwidth on each socket, which // contains L3 cache id and memory bandwidth. // Format: "MB:<cache_id0>=bandwidth0;<cache_id1>=bandwidth1;..." // For example, on a two-socket machine, the schema line could be: // "MB:0=20;1=70" // // The minimum bandwidth percentage value for each CPU model is // predefined and can be looked up through "info/MB/min_bandwidth". // The bandwidth granularity that is allocated is also dependent on // the CPU model and can be looked up at "info/MB/bandwidth_gran". // The available bandwidth control steps are: min_bw + N * bw_gran. // Intermediate values are rounded to the next control step available // on the hardware. // // If MBA Software Controller is enabled through mount option // "-o mba_MBps": mount -t resctrl resctrl -o mba_MBps /sys/fs/resctrl // We could specify memory bandwidth in "MBps" (Mega Bytes per second) // unit instead of "percentages". The kernel underneath would use a // software feedback mechanism or a "Software Controller" which reads // the actual bandwidth using MBM counters and adjust the memory // bandwidth percentages to ensure: // "actual memory bandwidth < user specified memory bandwidth". // // For example, on a two-socket machine, the schema line could be // "MB:0=5000;1=7000" which means 5000 MBps memory bandwidth limit on // socket 0 and 7000 MBps memory bandwidth limit on socket 1. if container.IntelRdt != nil { path := m.GetPath() l3CacheSchema := container.IntelRdt.L3CacheSchema memBwSchema := container.IntelRdt.MemBwSchema // Write a single joint schema string to schemata file if l3CacheSchema != "" && memBwSchema != "" { if err := writeFile(path, "schemata", l3CacheSchema+"\n"+memBwSchema); err != nil { return NewLastCmdError(err) } } // Write only L3 cache schema string to schemata file if l3CacheSchema != "" && memBwSchema == "" { if err := writeFile(path, "schemata", l3CacheSchema); err != nil { return NewLastCmdError(err) } } // Write only memory bandwidth schema string to schemata file if l3CacheSchema == "" && memBwSchema != "" { if err := writeFile(path, "schemata", memBwSchema); err != nil { return NewLastCmdError(err) } } } return nil }
[ "func", "(", "m", "*", "IntelRdtManager", ")", "Set", "(", "container", "*", "configs", ".", "Config", ")", "error", "{", "// About L3 cache schema:", "// It has allocation bitmasks/values for L3 cache on each socket,", "// which contains L3 cache id and capacity bitmask (CBM).", "// \tFormat: \"L3:<cache_id0>=<cbm0>;<cache_id1>=<cbm1>;...\"", "// For example, on a two-socket machine, the schema line could be:", "// \tL3:0=ff;1=c0", "// which means L3 cache id 0's CBM is 0xff, and L3 cache id 1's CBM", "// is 0xc0.", "//", "// The valid L3 cache CBM is a *contiguous bits set* and number of", "// bits that can be set is less than the max bit. The max bits in the", "// CBM is varied among supported Intel CPU models. Kernel will check", "// if it is valid when writing. e.g., default value 0xfffff in root", "// indicates the max bits of CBM is 20 bits, which mapping to entire", "// L3 cache capacity. Some valid CBM values to set in a group:", "// 0xf, 0xf0, 0x3ff, 0x1f00 and etc.", "//", "//", "// About memory bandwidth schema:", "// It has allocation values for memory bandwidth on each socket, which", "// contains L3 cache id and memory bandwidth.", "// \tFormat: \"MB:<cache_id0>=bandwidth0;<cache_id1>=bandwidth1;...\"", "// For example, on a two-socket machine, the schema line could be:", "// \t\"MB:0=20;1=70\"", "//", "// The minimum bandwidth percentage value for each CPU model is", "// predefined and can be looked up through \"info/MB/min_bandwidth\".", "// The bandwidth granularity that is allocated is also dependent on", "// the CPU model and can be looked up at \"info/MB/bandwidth_gran\".", "// The available bandwidth control steps are: min_bw + N * bw_gran.", "// Intermediate values are rounded to the next control step available", "// on the hardware.", "//", "// If MBA Software Controller is enabled through mount option", "// \"-o mba_MBps\": mount -t resctrl resctrl -o mba_MBps /sys/fs/resctrl", "// We could specify memory bandwidth in \"MBps\" (Mega Bytes per second)", "// unit instead of \"percentages\". The kernel underneath would use a", "// software feedback mechanism or a \"Software Controller\" which reads", "// the actual bandwidth using MBM counters and adjust the memory", "// bandwidth percentages to ensure:", "// \"actual memory bandwidth < user specified memory bandwidth\".", "//", "// For example, on a two-socket machine, the schema line could be", "// \"MB:0=5000;1=7000\" which means 5000 MBps memory bandwidth limit on", "// socket 0 and 7000 MBps memory bandwidth limit on socket 1.", "if", "container", ".", "IntelRdt", "!=", "nil", "{", "path", ":=", "m", ".", "GetPath", "(", ")", "\n", "l3CacheSchema", ":=", "container", ".", "IntelRdt", ".", "L3CacheSchema", "\n", "memBwSchema", ":=", "container", ".", "IntelRdt", ".", "MemBwSchema", "\n\n", "// Write a single joint schema string to schemata file", "if", "l3CacheSchema", "!=", "\"", "\"", "&&", "memBwSchema", "!=", "\"", "\"", "{", "if", "err", ":=", "writeFile", "(", "path", ",", "\"", "\"", ",", "l3CacheSchema", "+", "\"", "\\n", "\"", "+", "memBwSchema", ")", ";", "err", "!=", "nil", "{", "return", "NewLastCmdError", "(", "err", ")", "\n", "}", "\n", "}", "\n\n", "// Write only L3 cache schema string to schemata file", "if", "l3CacheSchema", "!=", "\"", "\"", "&&", "memBwSchema", "==", "\"", "\"", "{", "if", "err", ":=", "writeFile", "(", "path", ",", "\"", "\"", ",", "l3CacheSchema", ")", ";", "err", "!=", "nil", "{", "return", "NewLastCmdError", "(", "err", ")", "\n", "}", "\n", "}", "\n\n", "// Write only memory bandwidth schema string to schemata file", "if", "l3CacheSchema", "==", "\"", "\"", "&&", "memBwSchema", "!=", "\"", "\"", "{", "if", "err", ":=", "writeFile", "(", "path", ",", "\"", "\"", ",", "memBwSchema", ")", ";", "err", "!=", "nil", "{", "return", "NewLastCmdError", "(", "err", ")", "\n", "}", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Set Intel RDT "resource control" filesystem as configured.
[ "Set", "Intel", "RDT", "resource", "control", "filesystem", "as", "configured", "." ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/intelrdt/intelrdt.go#L645-L719
164,546
opencontainers/runc
spec.go
loadSpec
func loadSpec(cPath string) (spec *specs.Spec, err error) { cf, err := os.Open(cPath) if err != nil { if os.IsNotExist(err) { return nil, fmt.Errorf("JSON specification file %s not found", cPath) } return nil, err } defer cf.Close() if err = json.NewDecoder(cf).Decode(&spec); err != nil { return nil, err } return spec, validateProcessSpec(spec.Process) }
go
func loadSpec(cPath string) (spec *specs.Spec, err error) { cf, err := os.Open(cPath) if err != nil { if os.IsNotExist(err) { return nil, fmt.Errorf("JSON specification file %s not found", cPath) } return nil, err } defer cf.Close() if err = json.NewDecoder(cf).Decode(&spec); err != nil { return nil, err } return spec, validateProcessSpec(spec.Process) }
[ "func", "loadSpec", "(", "cPath", "string", ")", "(", "spec", "*", "specs", ".", "Spec", ",", "err", "error", ")", "{", "cf", ",", "err", ":=", "os", ".", "Open", "(", "cPath", ")", "\n", "if", "err", "!=", "nil", "{", "if", "os", ".", "IsNotExist", "(", "err", ")", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "cPath", ")", "\n", "}", "\n", "return", "nil", ",", "err", "\n", "}", "\n", "defer", "cf", ".", "Close", "(", ")", "\n\n", "if", "err", "=", "json", ".", "NewDecoder", "(", "cf", ")", ".", "Decode", "(", "&", "spec", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "spec", ",", "validateProcessSpec", "(", "spec", ".", "Process", ")", "\n", "}" ]
// loadSpec loads the specification from the provided path.
[ "loadSpec", "loads", "the", "specification", "from", "the", "provided", "path", "." ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/spec.go#L119-L133
164,547
opencontainers/runc
libcontainer/process_linux.go
execSetns
func (p *setnsProcess) execSetns() error { status, err := p.cmd.Process.Wait() if err != nil { p.cmd.Wait() return newSystemErrorWithCause(err, "waiting on setns process to finish") } if !status.Success() { p.cmd.Wait() return newSystemError(&exec.ExitError{ProcessState: status}) } var pid *pid if err := json.NewDecoder(p.parentPipe).Decode(&pid); err != nil { p.cmd.Wait() return newSystemErrorWithCause(err, "reading pid from init pipe") } // Clean up the zombie parent process // On Unix systems FindProcess always succeeds. firstChildProcess, _ := os.FindProcess(pid.PidFirstChild) // Ignore the error in case the child has already been reaped for any reason _, _ = firstChildProcess.Wait() process, err := os.FindProcess(pid.Pid) if err != nil { return err } p.cmd.Process = process p.process.ops = p return nil }
go
func (p *setnsProcess) execSetns() error { status, err := p.cmd.Process.Wait() if err != nil { p.cmd.Wait() return newSystemErrorWithCause(err, "waiting on setns process to finish") } if !status.Success() { p.cmd.Wait() return newSystemError(&exec.ExitError{ProcessState: status}) } var pid *pid if err := json.NewDecoder(p.parentPipe).Decode(&pid); err != nil { p.cmd.Wait() return newSystemErrorWithCause(err, "reading pid from init pipe") } // Clean up the zombie parent process // On Unix systems FindProcess always succeeds. firstChildProcess, _ := os.FindProcess(pid.PidFirstChild) // Ignore the error in case the child has already been reaped for any reason _, _ = firstChildProcess.Wait() process, err := os.FindProcess(pid.Pid) if err != nil { return err } p.cmd.Process = process p.process.ops = p return nil }
[ "func", "(", "p", "*", "setnsProcess", ")", "execSetns", "(", ")", "error", "{", "status", ",", "err", ":=", "p", ".", "cmd", ".", "Process", ".", "Wait", "(", ")", "\n", "if", "err", "!=", "nil", "{", "p", ".", "cmd", ".", "Wait", "(", ")", "\n", "return", "newSystemErrorWithCause", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "if", "!", "status", ".", "Success", "(", ")", "{", "p", ".", "cmd", ".", "Wait", "(", ")", "\n", "return", "newSystemError", "(", "&", "exec", ".", "ExitError", "{", "ProcessState", ":", "status", "}", ")", "\n", "}", "\n", "var", "pid", "*", "pid", "\n", "if", "err", ":=", "json", ".", "NewDecoder", "(", "p", ".", "parentPipe", ")", ".", "Decode", "(", "&", "pid", ")", ";", "err", "!=", "nil", "{", "p", ".", "cmd", ".", "Wait", "(", ")", "\n", "return", "newSystemErrorWithCause", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "// Clean up the zombie parent process", "// On Unix systems FindProcess always succeeds.", "firstChildProcess", ",", "_", ":=", "os", ".", "FindProcess", "(", "pid", ".", "PidFirstChild", ")", "\n\n", "// Ignore the error in case the child has already been reaped for any reason", "_", ",", "_", "=", "firstChildProcess", ".", "Wait", "(", ")", "\n\n", "process", ",", "err", ":=", "os", ".", "FindProcess", "(", "pid", ".", "Pid", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "p", ".", "cmd", ".", "Process", "=", "process", "\n", "p", ".", "process", ".", "ops", "=", "p", "\n", "return", "nil", "\n", "}" ]
// execSetns runs the process that executes C code to perform the setns calls // because setns support requires the C process to fork off a child and perform the setns // before the go runtime boots, we wait on the process to die and receive the child's pid // over the provided pipe.
[ "execSetns", "runs", "the", "process", "that", "executes", "C", "code", "to", "perform", "the", "setns", "calls", "because", "setns", "support", "requires", "the", "C", "process", "to", "fork", "off", "a", "child", "and", "perform", "the", "setns", "before", "the", "go", "runtime", "boots", "we", "wait", "on", "the", "process", "to", "die", "and", "receive", "the", "child", "s", "pid", "over", "the", "provided", "pipe", "." ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/process_linux.go#L144-L174
164,548
opencontainers/runc
libcontainer/process_linux.go
terminate
func (p *setnsProcess) terminate() error { if p.cmd.Process == nil { return nil } err := p.cmd.Process.Kill() if _, werr := p.wait(); err == nil { err = werr } return err }
go
func (p *setnsProcess) terminate() error { if p.cmd.Process == nil { return nil } err := p.cmd.Process.Kill() if _, werr := p.wait(); err == nil { err = werr } return err }
[ "func", "(", "p", "*", "setnsProcess", ")", "terminate", "(", ")", "error", "{", "if", "p", ".", "cmd", ".", "Process", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "err", ":=", "p", ".", "cmd", ".", "Process", ".", "Kill", "(", ")", "\n", "if", "_", ",", "werr", ":=", "p", ".", "wait", "(", ")", ";", "err", "==", "nil", "{", "err", "=", "werr", "\n", "}", "\n", "return", "err", "\n", "}" ]
// terminate sends a SIGKILL to the forked process for the setns routine then waits to // avoid the process becoming a zombie.
[ "terminate", "sends", "a", "SIGKILL", "to", "the", "forked", "process", "for", "the", "setns", "routine", "then", "waits", "to", "avoid", "the", "process", "becoming", "a", "zombie", "." ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/process_linux.go#L178-L187
164,549
opencontainers/runc
libcontainer/process_linux.go
getChildPid
func (p *initProcess) getChildPid() (int, error) { var pid pid if err := json.NewDecoder(p.parentPipe).Decode(&pid); err != nil { p.cmd.Wait() return -1, err } // Clean up the zombie parent process // On Unix systems FindProcess always succeeds. firstChildProcess, _ := os.FindProcess(pid.PidFirstChild) // Ignore the error in case the child has already been reaped for any reason _, _ = firstChildProcess.Wait() return pid.Pid, nil }
go
func (p *initProcess) getChildPid() (int, error) { var pid pid if err := json.NewDecoder(p.parentPipe).Decode(&pid); err != nil { p.cmd.Wait() return -1, err } // Clean up the zombie parent process // On Unix systems FindProcess always succeeds. firstChildProcess, _ := os.FindProcess(pid.PidFirstChild) // Ignore the error in case the child has already been reaped for any reason _, _ = firstChildProcess.Wait() return pid.Pid, nil }
[ "func", "(", "p", "*", "initProcess", ")", "getChildPid", "(", ")", "(", "int", ",", "error", ")", "{", "var", "pid", "pid", "\n", "if", "err", ":=", "json", ".", "NewDecoder", "(", "p", ".", "parentPipe", ")", ".", "Decode", "(", "&", "pid", ")", ";", "err", "!=", "nil", "{", "p", ".", "cmd", ".", "Wait", "(", ")", "\n", "return", "-", "1", ",", "err", "\n", "}", "\n\n", "// Clean up the zombie parent process", "// On Unix systems FindProcess always succeeds.", "firstChildProcess", ",", "_", ":=", "os", ".", "FindProcess", "(", "pid", ".", "PidFirstChild", ")", "\n\n", "// Ignore the error in case the child has already been reaped for any reason", "_", ",", "_", "=", "firstChildProcess", ".", "Wait", "(", ")", "\n\n", "return", "pid", ".", "Pid", ",", "nil", "\n", "}" ]
// getChildPid receives the final child's pid over the provided pipe.
[ "getChildPid", "receives", "the", "final", "child", "s", "pid", "over", "the", "provided", "pipe", "." ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/process_linux.go#L231-L246
164,550
opencontainers/runc
libcontainer/init_linux.go
populateProcessEnvironment
func populateProcessEnvironment(env []string) error { for _, pair := range env { p := strings.SplitN(pair, "=", 2) if len(p) < 2 { return fmt.Errorf("invalid environment '%v'", pair) } if err := os.Setenv(p[0], p[1]); err != nil { return err } } return nil }
go
func populateProcessEnvironment(env []string) error { for _, pair := range env { p := strings.SplitN(pair, "=", 2) if len(p) < 2 { return fmt.Errorf("invalid environment '%v'", pair) } if err := os.Setenv(p[0], p[1]); err != nil { return err } } return nil }
[ "func", "populateProcessEnvironment", "(", "env", "[", "]", "string", ")", "error", "{", "for", "_", ",", "pair", ":=", "range", "env", "{", "p", ":=", "strings", ".", "SplitN", "(", "pair", ",", "\"", "\"", ",", "2", ")", "\n", "if", "len", "(", "p", ")", "<", "2", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "pair", ")", "\n", "}", "\n", "if", "err", ":=", "os", ".", "Setenv", "(", "p", "[", "0", "]", ",", "p", "[", "1", "]", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// populateProcessEnvironment loads the provided environment variables into the // current processes's environment.
[ "populateProcessEnvironment", "loads", "the", "provided", "environment", "variables", "into", "the", "current", "processes", "s", "environment", "." ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/init_linux.go#L106-L117
164,551
opencontainers/runc
libcontainer/init_linux.go
finalizeNamespace
func finalizeNamespace(config *initConfig) error { // Ensure that all unwanted fds we may have accidentally // inherited are marked close-on-exec so they stay out of the // container if err := utils.CloseExecFrom(config.PassedFilesCount + 3); err != nil { return errors.Wrap(err, "close exec fds") } capabilities := &configs.Capabilities{} if config.Capabilities != nil { capabilities = config.Capabilities } else if config.Config.Capabilities != nil { capabilities = config.Config.Capabilities } w, err := newContainerCapList(capabilities) if err != nil { return err } // drop capabilities in bounding set before changing user if err := w.ApplyBoundingSet(); err != nil { return errors.Wrap(err, "apply bounding set") } // preserve existing capabilities while we change users if err := system.SetKeepCaps(); err != nil { return errors.Wrap(err, "set keep caps") } if err := setupUser(config); err != nil { return errors.Wrap(err, "setup user") } if err := system.ClearKeepCaps(); err != nil { return errors.Wrap(err, "clear keep caps") } if err := w.ApplyCaps(); err != nil { return errors.Wrap(err, "apply caps") } if config.Cwd != "" { if err := unix.Chdir(config.Cwd); err != nil { return fmt.Errorf("chdir to cwd (%q) set in config.json failed: %v", config.Cwd, err) } } return nil }
go
func finalizeNamespace(config *initConfig) error { // Ensure that all unwanted fds we may have accidentally // inherited are marked close-on-exec so they stay out of the // container if err := utils.CloseExecFrom(config.PassedFilesCount + 3); err != nil { return errors.Wrap(err, "close exec fds") } capabilities := &configs.Capabilities{} if config.Capabilities != nil { capabilities = config.Capabilities } else if config.Config.Capabilities != nil { capabilities = config.Config.Capabilities } w, err := newContainerCapList(capabilities) if err != nil { return err } // drop capabilities in bounding set before changing user if err := w.ApplyBoundingSet(); err != nil { return errors.Wrap(err, "apply bounding set") } // preserve existing capabilities while we change users if err := system.SetKeepCaps(); err != nil { return errors.Wrap(err, "set keep caps") } if err := setupUser(config); err != nil { return errors.Wrap(err, "setup user") } if err := system.ClearKeepCaps(); err != nil { return errors.Wrap(err, "clear keep caps") } if err := w.ApplyCaps(); err != nil { return errors.Wrap(err, "apply caps") } if config.Cwd != "" { if err := unix.Chdir(config.Cwd); err != nil { return fmt.Errorf("chdir to cwd (%q) set in config.json failed: %v", config.Cwd, err) } } return nil }
[ "func", "finalizeNamespace", "(", "config", "*", "initConfig", ")", "error", "{", "// Ensure that all unwanted fds we may have accidentally", "// inherited are marked close-on-exec so they stay out of the", "// container", "if", "err", ":=", "utils", ".", "CloseExecFrom", "(", "config", ".", "PassedFilesCount", "+", "3", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n\n", "capabilities", ":=", "&", "configs", ".", "Capabilities", "{", "}", "\n", "if", "config", ".", "Capabilities", "!=", "nil", "{", "capabilities", "=", "config", ".", "Capabilities", "\n", "}", "else", "if", "config", ".", "Config", ".", "Capabilities", "!=", "nil", "{", "capabilities", "=", "config", ".", "Config", ".", "Capabilities", "\n", "}", "\n", "w", ",", "err", ":=", "newContainerCapList", "(", "capabilities", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "// drop capabilities in bounding set before changing user", "if", "err", ":=", "w", ".", "ApplyBoundingSet", "(", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "// preserve existing capabilities while we change users", "if", "err", ":=", "system", ".", "SetKeepCaps", "(", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "if", "err", ":=", "setupUser", "(", "config", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "if", "err", ":=", "system", ".", "ClearKeepCaps", "(", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "if", "err", ":=", "w", ".", "ApplyCaps", "(", ")", ";", "err", "!=", "nil", "{", "return", "errors", ".", "Wrap", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "if", "config", ".", "Cwd", "!=", "\"", "\"", "{", "if", "err", ":=", "unix", ".", "Chdir", "(", "config", ".", "Cwd", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "config", ".", "Cwd", ",", "err", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// finalizeNamespace drops the caps, sets the correct user // and working dir, and closes any leaked file descriptors // before executing the command inside the namespace
[ "finalizeNamespace", "drops", "the", "caps", "sets", "the", "correct", "user", "and", "working", "dir", "and", "closes", "any", "leaked", "file", "descriptors", "before", "executing", "the", "command", "inside", "the", "namespace" ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/init_linux.go#L122-L163
164,552
opencontainers/runc
libcontainer/init_linux.go
syncParentReady
func syncParentReady(pipe io.ReadWriter) error { // Tell parent. if err := writeSync(pipe, procReady); err != nil { return err } // Wait for parent to give the all-clear. return readSync(pipe, procRun) }
go
func syncParentReady(pipe io.ReadWriter) error { // Tell parent. if err := writeSync(pipe, procReady); err != nil { return err } // Wait for parent to give the all-clear. return readSync(pipe, procRun) }
[ "func", "syncParentReady", "(", "pipe", "io", ".", "ReadWriter", ")", "error", "{", "// Tell parent.", "if", "err", ":=", "writeSync", "(", "pipe", ",", "procReady", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Wait for parent to give the all-clear.", "return", "readSync", "(", "pipe", ",", "procRun", ")", "\n", "}" ]
// syncParentReady sends to the given pipe a JSON payload which indicates that // the init is ready to Exec the child process. It then waits for the parent to // indicate that it is cleared to Exec.
[ "syncParentReady", "sends", "to", "the", "given", "pipe", "a", "JSON", "payload", "which", "indicates", "that", "the", "init", "is", "ready", "to", "Exec", "the", "child", "process", ".", "It", "then", "waits", "for", "the", "parent", "to", "indicate", "that", "it", "is", "cleared", "to", "Exec", "." ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/init_linux.go#L216-L224
164,553
opencontainers/runc
libcontainer/init_linux.go
syncParentHooks
func syncParentHooks(pipe io.ReadWriter) error { // Tell parent. if err := writeSync(pipe, procHooks); err != nil { return err } // Wait for parent to give the all-clear. return readSync(pipe, procResume) }
go
func syncParentHooks(pipe io.ReadWriter) error { // Tell parent. if err := writeSync(pipe, procHooks); err != nil { return err } // Wait for parent to give the all-clear. return readSync(pipe, procResume) }
[ "func", "syncParentHooks", "(", "pipe", "io", ".", "ReadWriter", ")", "error", "{", "// Tell parent.", "if", "err", ":=", "writeSync", "(", "pipe", ",", "procHooks", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Wait for parent to give the all-clear.", "return", "readSync", "(", "pipe", ",", "procResume", ")", "\n", "}" ]
// syncParentHooks sends to the given pipe a JSON payload which indicates that // the parent should execute pre-start hooks. It then waits for the parent to // indicate that it is cleared to resume.
[ "syncParentHooks", "sends", "to", "the", "given", "pipe", "a", "JSON", "payload", "which", "indicates", "that", "the", "parent", "should", "execute", "pre", "-", "start", "hooks", ".", "It", "then", "waits", "for", "the", "parent", "to", "indicate", "that", "it", "is", "cleared", "to", "resume", "." ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/init_linux.go#L229-L237
164,554
opencontainers/runc
libcontainer/init_linux.go
setupUser
func setupUser(config *initConfig) error { // Set up defaults. defaultExecUser := user.ExecUser{ Uid: 0, Gid: 0, Home: "/", } passwdPath, err := user.GetPasswdPath() if err != nil { return err } groupPath, err := user.GetGroupPath() if err != nil { return err } execUser, err := user.GetExecUserPath(config.User, &defaultExecUser, passwdPath, groupPath) if err != nil { return err } var addGroups []int if len(config.AdditionalGroups) > 0 { addGroups, err = user.GetAdditionalGroupsPath(config.AdditionalGroups, groupPath) if err != nil { return err } } // Rather than just erroring out later in setuid(2) and setgid(2), check // that the user is mapped here. if _, err := config.Config.HostUID(execUser.Uid); err != nil { return fmt.Errorf("cannot set uid to unmapped user in user namespace") } if _, err := config.Config.HostGID(execUser.Gid); err != nil { return fmt.Errorf("cannot set gid to unmapped user in user namespace") } if config.RootlessEUID { // We cannot set any additional groups in a rootless container and thus // we bail if the user asked us to do so. TODO: We currently can't do // this check earlier, but if libcontainer.Process.User was typesafe // this might work. if len(addGroups) > 0 { return fmt.Errorf("cannot set any additional groups in a rootless container") } } // Before we change to the container's user make sure that the processes // STDIO is correctly owned by the user that we are switching to. if err := fixStdioPermissions(config, execUser); err != nil { return err } setgroups, err := ioutil.ReadFile("/proc/self/setgroups") if err != nil && !os.IsNotExist(err) { return err } // This isn't allowed in an unprivileged user namespace since Linux 3.19. // There's nothing we can do about /etc/group entries, so we silently // ignore setting groups here (since the user didn't explicitly ask us to // set the group). allowSupGroups := !config.RootlessEUID && strings.TrimSpace(string(setgroups)) != "deny" if allowSupGroups { suppGroups := append(execUser.Sgids, addGroups...) if err := unix.Setgroups(suppGroups); err != nil { return err } } if err := system.Setgid(execUser.Gid); err != nil { return err } if err := system.Setuid(execUser.Uid); err != nil { return err } // if we didn't get HOME already, set it based on the user's HOME if envHome := os.Getenv("HOME"); envHome == "" { if err := os.Setenv("HOME", execUser.Home); err != nil { return err } } return nil }
go
func setupUser(config *initConfig) error { // Set up defaults. defaultExecUser := user.ExecUser{ Uid: 0, Gid: 0, Home: "/", } passwdPath, err := user.GetPasswdPath() if err != nil { return err } groupPath, err := user.GetGroupPath() if err != nil { return err } execUser, err := user.GetExecUserPath(config.User, &defaultExecUser, passwdPath, groupPath) if err != nil { return err } var addGroups []int if len(config.AdditionalGroups) > 0 { addGroups, err = user.GetAdditionalGroupsPath(config.AdditionalGroups, groupPath) if err != nil { return err } } // Rather than just erroring out later in setuid(2) and setgid(2), check // that the user is mapped here. if _, err := config.Config.HostUID(execUser.Uid); err != nil { return fmt.Errorf("cannot set uid to unmapped user in user namespace") } if _, err := config.Config.HostGID(execUser.Gid); err != nil { return fmt.Errorf("cannot set gid to unmapped user in user namespace") } if config.RootlessEUID { // We cannot set any additional groups in a rootless container and thus // we bail if the user asked us to do so. TODO: We currently can't do // this check earlier, but if libcontainer.Process.User was typesafe // this might work. if len(addGroups) > 0 { return fmt.Errorf("cannot set any additional groups in a rootless container") } } // Before we change to the container's user make sure that the processes // STDIO is correctly owned by the user that we are switching to. if err := fixStdioPermissions(config, execUser); err != nil { return err } setgroups, err := ioutil.ReadFile("/proc/self/setgroups") if err != nil && !os.IsNotExist(err) { return err } // This isn't allowed in an unprivileged user namespace since Linux 3.19. // There's nothing we can do about /etc/group entries, so we silently // ignore setting groups here (since the user didn't explicitly ask us to // set the group). allowSupGroups := !config.RootlessEUID && strings.TrimSpace(string(setgroups)) != "deny" if allowSupGroups { suppGroups := append(execUser.Sgids, addGroups...) if err := unix.Setgroups(suppGroups); err != nil { return err } } if err := system.Setgid(execUser.Gid); err != nil { return err } if err := system.Setuid(execUser.Uid); err != nil { return err } // if we didn't get HOME already, set it based on the user's HOME if envHome := os.Getenv("HOME"); envHome == "" { if err := os.Setenv("HOME", execUser.Home); err != nil { return err } } return nil }
[ "func", "setupUser", "(", "config", "*", "initConfig", ")", "error", "{", "// Set up defaults.", "defaultExecUser", ":=", "user", ".", "ExecUser", "{", "Uid", ":", "0", ",", "Gid", ":", "0", ",", "Home", ":", "\"", "\"", ",", "}", "\n\n", "passwdPath", ",", "err", ":=", "user", ".", "GetPasswdPath", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "groupPath", ",", "err", ":=", "user", ".", "GetGroupPath", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "execUser", ",", "err", ":=", "user", ".", "GetExecUserPath", "(", "config", ".", "User", ",", "&", "defaultExecUser", ",", "passwdPath", ",", "groupPath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "var", "addGroups", "[", "]", "int", "\n", "if", "len", "(", "config", ".", "AdditionalGroups", ")", ">", "0", "{", "addGroups", ",", "err", "=", "user", ".", "GetAdditionalGroupsPath", "(", "config", ".", "AdditionalGroups", ",", "groupPath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n\n", "// Rather than just erroring out later in setuid(2) and setgid(2), check", "// that the user is mapped here.", "if", "_", ",", "err", ":=", "config", ".", "Config", ".", "HostUID", "(", "execUser", ".", "Uid", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "_", ",", "err", ":=", "config", ".", "Config", ".", "HostGID", "(", "execUser", ".", "Gid", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "config", ".", "RootlessEUID", "{", "// We cannot set any additional groups in a rootless container and thus", "// we bail if the user asked us to do so. TODO: We currently can't do", "// this check earlier, but if libcontainer.Process.User was typesafe", "// this might work.", "if", "len", "(", "addGroups", ")", ">", "0", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "\n\n", "// Before we change to the container's user make sure that the processes", "// STDIO is correctly owned by the user that we are switching to.", "if", "err", ":=", "fixStdioPermissions", "(", "config", ",", "execUser", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "setgroups", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "&&", "!", "os", ".", "IsNotExist", "(", "err", ")", "{", "return", "err", "\n", "}", "\n\n", "// This isn't allowed in an unprivileged user namespace since Linux 3.19.", "// There's nothing we can do about /etc/group entries, so we silently", "// ignore setting groups here (since the user didn't explicitly ask us to", "// set the group).", "allowSupGroups", ":=", "!", "config", ".", "RootlessEUID", "&&", "strings", ".", "TrimSpace", "(", "string", "(", "setgroups", ")", ")", "!=", "\"", "\"", "\n\n", "if", "allowSupGroups", "{", "suppGroups", ":=", "append", "(", "execUser", ".", "Sgids", ",", "addGroups", "...", ")", "\n", "if", "err", ":=", "unix", ".", "Setgroups", "(", "suppGroups", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n\n", "if", "err", ":=", "system", ".", "Setgid", "(", "execUser", ".", "Gid", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "system", ".", "Setuid", "(", "execUser", ".", "Uid", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// if we didn't get HOME already, set it based on the user's HOME", "if", "envHome", ":=", "os", ".", "Getenv", "(", "\"", "\"", ")", ";", "envHome", "==", "\"", "\"", "{", "if", "err", ":=", "os", ".", "Setenv", "(", "\"", "\"", ",", "execUser", ".", "Home", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// setupUser changes the groups, gid, and uid for the user inside the container
[ "setupUser", "changes", "the", "groups", "gid", "and", "uid", "for", "the", "user", "inside", "the", "container" ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/init_linux.go#L240-L328
164,555
opencontainers/runc
libcontainer/init_linux.go
fixStdioPermissions
func fixStdioPermissions(config *initConfig, u *user.ExecUser) error { var null unix.Stat_t if err := unix.Stat("/dev/null", &null); err != nil { return err } for _, fd := range []uintptr{ os.Stdin.Fd(), os.Stderr.Fd(), os.Stdout.Fd(), } { var s unix.Stat_t if err := unix.Fstat(int(fd), &s); err != nil { return err } // Skip chown of /dev/null if it was used as one of the STDIO fds. if s.Rdev == null.Rdev { continue } // We only change the uid owner (as it is possible for the mount to // prefer a different gid, and there's no reason for us to change it). // The reason why we don't just leave the default uid=X mount setup is // that users expect to be able to actually use their console. Without // this code, you couldn't effectively run as a non-root user inside a // container and also have a console set up. if err := unix.Fchown(int(fd), u.Uid, int(s.Gid)); err != nil { // If we've hit an EINVAL then s.Gid isn't mapped in the user // namespace. If we've hit an EPERM then the inode's current owner // is not mapped in our user namespace (in particular, // privileged_wrt_inode_uidgid() has failed). In either case, we // are in a configuration where it's better for us to just not // touch the stdio rather than bail at this point. if err == unix.EINVAL || err == unix.EPERM { continue } return err } } return nil }
go
func fixStdioPermissions(config *initConfig, u *user.ExecUser) error { var null unix.Stat_t if err := unix.Stat("/dev/null", &null); err != nil { return err } for _, fd := range []uintptr{ os.Stdin.Fd(), os.Stderr.Fd(), os.Stdout.Fd(), } { var s unix.Stat_t if err := unix.Fstat(int(fd), &s); err != nil { return err } // Skip chown of /dev/null if it was used as one of the STDIO fds. if s.Rdev == null.Rdev { continue } // We only change the uid owner (as it is possible for the mount to // prefer a different gid, and there's no reason for us to change it). // The reason why we don't just leave the default uid=X mount setup is // that users expect to be able to actually use their console. Without // this code, you couldn't effectively run as a non-root user inside a // container and also have a console set up. if err := unix.Fchown(int(fd), u.Uid, int(s.Gid)); err != nil { // If we've hit an EINVAL then s.Gid isn't mapped in the user // namespace. If we've hit an EPERM then the inode's current owner // is not mapped in our user namespace (in particular, // privileged_wrt_inode_uidgid() has failed). In either case, we // are in a configuration where it's better for us to just not // touch the stdio rather than bail at this point. if err == unix.EINVAL || err == unix.EPERM { continue } return err } } return nil }
[ "func", "fixStdioPermissions", "(", "config", "*", "initConfig", ",", "u", "*", "user", ".", "ExecUser", ")", "error", "{", "var", "null", "unix", ".", "Stat_t", "\n", "if", "err", ":=", "unix", ".", "Stat", "(", "\"", "\"", ",", "&", "null", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "for", "_", ",", "fd", ":=", "range", "[", "]", "uintptr", "{", "os", ".", "Stdin", ".", "Fd", "(", ")", ",", "os", ".", "Stderr", ".", "Fd", "(", ")", ",", "os", ".", "Stdout", ".", "Fd", "(", ")", ",", "}", "{", "var", "s", "unix", ".", "Stat_t", "\n", "if", "err", ":=", "unix", ".", "Fstat", "(", "int", "(", "fd", ")", ",", "&", "s", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// Skip chown of /dev/null if it was used as one of the STDIO fds.", "if", "s", ".", "Rdev", "==", "null", ".", "Rdev", "{", "continue", "\n", "}", "\n\n", "// We only change the uid owner (as it is possible for the mount to", "// prefer a different gid, and there's no reason for us to change it).", "// The reason why we don't just leave the default uid=X mount setup is", "// that users expect to be able to actually use their console. Without", "// this code, you couldn't effectively run as a non-root user inside a", "// container and also have a console set up.", "if", "err", ":=", "unix", ".", "Fchown", "(", "int", "(", "fd", ")", ",", "u", ".", "Uid", ",", "int", "(", "s", ".", "Gid", ")", ")", ";", "err", "!=", "nil", "{", "// If we've hit an EINVAL then s.Gid isn't mapped in the user", "// namespace. If we've hit an EPERM then the inode's current owner", "// is not mapped in our user namespace (in particular,", "// privileged_wrt_inode_uidgid() has failed). In either case, we", "// are in a configuration where it's better for us to just not", "// touch the stdio rather than bail at this point.", "if", "err", "==", "unix", ".", "EINVAL", "||", "err", "==", "unix", ".", "EPERM", "{", "continue", "\n", "}", "\n", "return", "err", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// fixStdioPermissions fixes the permissions of PID 1's STDIO within the container to the specified user. // The ownership needs to match because it is created outside of the container and needs to be // localized.
[ "fixStdioPermissions", "fixes", "the", "permissions", "of", "PID", "1", "s", "STDIO", "within", "the", "container", "to", "the", "specified", "user", ".", "The", "ownership", "needs", "to", "match", "because", "it", "is", "created", "outside", "of", "the", "container", "and", "needs", "to", "be", "localized", "." ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/init_linux.go#L333-L373
164,556
opencontainers/runc
libcontainer/init_linux.go
setupNetwork
func setupNetwork(config *initConfig) error { for _, config := range config.Networks { strategy, err := getStrategy(config.Type) if err != nil { return err } if err := strategy.initialize(config); err != nil { return err } } return nil }
go
func setupNetwork(config *initConfig) error { for _, config := range config.Networks { strategy, err := getStrategy(config.Type) if err != nil { return err } if err := strategy.initialize(config); err != nil { return err } } return nil }
[ "func", "setupNetwork", "(", "config", "*", "initConfig", ")", "error", "{", "for", "_", ",", "config", ":=", "range", "config", ".", "Networks", "{", "strategy", ",", "err", ":=", "getStrategy", "(", "config", ".", "Type", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "strategy", ".", "initialize", "(", "config", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// setupNetwork sets up and initializes any network interface inside the container.
[ "setupNetwork", "sets", "up", "and", "initializes", "any", "network", "interface", "inside", "the", "container", "." ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/init_linux.go#L376-L387
164,557
opencontainers/runc
libcontainer/init_linux.go
signalAllProcesses
func signalAllProcesses(m cgroups.Manager, s os.Signal) error { var procs []*os.Process if err := m.Freeze(configs.Frozen); err != nil { logrus.Warn(err) } pids, err := m.GetAllPids() if err != nil { m.Freeze(configs.Thawed) return err } for _, pid := range pids { p, err := os.FindProcess(pid) if err != nil { logrus.Warn(err) continue } procs = append(procs, p) if err := p.Signal(s); err != nil { logrus.Warn(err) } } if err := m.Freeze(configs.Thawed); err != nil { logrus.Warn(err) } subreaper, err := system.GetSubreaper() if err != nil { // The error here means that PR_GET_CHILD_SUBREAPER is not // supported because this code might run on a kernel older // than 3.4. We don't want to throw an error in that case, // and we simplify things, considering there is no subreaper // set. subreaper = 0 } for _, p := range procs { if s != unix.SIGKILL { if ok, err := isWaitable(p.Pid); err != nil { if !isNoChildren(err) { logrus.Warn("signalAllProcesses: ", p.Pid, err) } continue } else if !ok { // Not ready to report so don't wait continue } } // In case a subreaper has been setup, this code must not // wait for the process. Otherwise, we cannot be sure the // current process will be reaped by the subreaper, while // the subreaper might be waiting for this process in order // to retrieve its exit code. if subreaper == 0 { if _, err := p.Wait(); err != nil { if !isNoChildren(err) { logrus.Warn("wait: ", err) } } } } return nil }
go
func signalAllProcesses(m cgroups.Manager, s os.Signal) error { var procs []*os.Process if err := m.Freeze(configs.Frozen); err != nil { logrus.Warn(err) } pids, err := m.GetAllPids() if err != nil { m.Freeze(configs.Thawed) return err } for _, pid := range pids { p, err := os.FindProcess(pid) if err != nil { logrus.Warn(err) continue } procs = append(procs, p) if err := p.Signal(s); err != nil { logrus.Warn(err) } } if err := m.Freeze(configs.Thawed); err != nil { logrus.Warn(err) } subreaper, err := system.GetSubreaper() if err != nil { // The error here means that PR_GET_CHILD_SUBREAPER is not // supported because this code might run on a kernel older // than 3.4. We don't want to throw an error in that case, // and we simplify things, considering there is no subreaper // set. subreaper = 0 } for _, p := range procs { if s != unix.SIGKILL { if ok, err := isWaitable(p.Pid); err != nil { if !isNoChildren(err) { logrus.Warn("signalAllProcesses: ", p.Pid, err) } continue } else if !ok { // Not ready to report so don't wait continue } } // In case a subreaper has been setup, this code must not // wait for the process. Otherwise, we cannot be sure the // current process will be reaped by the subreaper, while // the subreaper might be waiting for this process in order // to retrieve its exit code. if subreaper == 0 { if _, err := p.Wait(); err != nil { if !isNoChildren(err) { logrus.Warn("wait: ", err) } } } } return nil }
[ "func", "signalAllProcesses", "(", "m", "cgroups", ".", "Manager", ",", "s", "os", ".", "Signal", ")", "error", "{", "var", "procs", "[", "]", "*", "os", ".", "Process", "\n", "if", "err", ":=", "m", ".", "Freeze", "(", "configs", ".", "Frozen", ")", ";", "err", "!=", "nil", "{", "logrus", ".", "Warn", "(", "err", ")", "\n", "}", "\n", "pids", ",", "err", ":=", "m", ".", "GetAllPids", "(", ")", "\n", "if", "err", "!=", "nil", "{", "m", ".", "Freeze", "(", "configs", ".", "Thawed", ")", "\n", "return", "err", "\n", "}", "\n", "for", "_", ",", "pid", ":=", "range", "pids", "{", "p", ",", "err", ":=", "os", ".", "FindProcess", "(", "pid", ")", "\n", "if", "err", "!=", "nil", "{", "logrus", ".", "Warn", "(", "err", ")", "\n", "continue", "\n", "}", "\n", "procs", "=", "append", "(", "procs", ",", "p", ")", "\n", "if", "err", ":=", "p", ".", "Signal", "(", "s", ")", ";", "err", "!=", "nil", "{", "logrus", ".", "Warn", "(", "err", ")", "\n", "}", "\n", "}", "\n", "if", "err", ":=", "m", ".", "Freeze", "(", "configs", ".", "Thawed", ")", ";", "err", "!=", "nil", "{", "logrus", ".", "Warn", "(", "err", ")", "\n", "}", "\n\n", "subreaper", ",", "err", ":=", "system", ".", "GetSubreaper", "(", ")", "\n", "if", "err", "!=", "nil", "{", "// The error here means that PR_GET_CHILD_SUBREAPER is not", "// supported because this code might run on a kernel older", "// than 3.4. We don't want to throw an error in that case,", "// and we simplify things, considering there is no subreaper", "// set.", "subreaper", "=", "0", "\n", "}", "\n\n", "for", "_", ",", "p", ":=", "range", "procs", "{", "if", "s", "!=", "unix", ".", "SIGKILL", "{", "if", "ok", ",", "err", ":=", "isWaitable", "(", "p", ".", "Pid", ")", ";", "err", "!=", "nil", "{", "if", "!", "isNoChildren", "(", "err", ")", "{", "logrus", ".", "Warn", "(", "\"", "\"", ",", "p", ".", "Pid", ",", "err", ")", "\n", "}", "\n", "continue", "\n", "}", "else", "if", "!", "ok", "{", "// Not ready to report so don't wait", "continue", "\n", "}", "\n", "}", "\n\n", "// In case a subreaper has been setup, this code must not", "// wait for the process. Otherwise, we cannot be sure the", "// current process will be reaped by the subreaper, while", "// the subreaper might be waiting for this process in order", "// to retrieve its exit code.", "if", "subreaper", "==", "0", "{", "if", "_", ",", "err", ":=", "p", ".", "Wait", "(", ")", ";", "err", "!=", "nil", "{", "if", "!", "isNoChildren", "(", "err", ")", "{", "logrus", ".", "Warn", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// signalAllProcesses freezes then iterates over all the processes inside the // manager's cgroups sending the signal s to them. // If s is SIGKILL then it will wait for each process to exit. // For all other signals it will check if the process is ready to report its // exit status and only if it is will a wait be performed.
[ "signalAllProcesses", "freezes", "then", "iterates", "over", "all", "the", "processes", "inside", "the", "manager", "s", "cgroups", "sending", "the", "signal", "s", "to", "them", ".", "If", "s", "is", "SIGKILL", "then", "it", "will", "wait", "for", "each", "process", "to", "exit", ".", "For", "all", "other", "signals", "it", "will", "check", "if", "the", "process", "is", "ready", "to", "report", "its", "exit", "status", "and", "only", "if", "it", "is", "will", "a", "wait", "be", "performed", "." ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/init_linux.go#L474-L536
164,558
opencontainers/runc
libcontainer/user/user.go
GetExecUserPath
func GetExecUserPath(userSpec string, defaults *ExecUser, passwdPath, groupPath string) (*ExecUser, error) { var passwd, group io.Reader if passwdFile, err := os.Open(passwdPath); err == nil { passwd = passwdFile defer passwdFile.Close() } if groupFile, err := os.Open(groupPath); err == nil { group = groupFile defer groupFile.Close() } return GetExecUser(userSpec, defaults, passwd, group) }
go
func GetExecUserPath(userSpec string, defaults *ExecUser, passwdPath, groupPath string) (*ExecUser, error) { var passwd, group io.Reader if passwdFile, err := os.Open(passwdPath); err == nil { passwd = passwdFile defer passwdFile.Close() } if groupFile, err := os.Open(groupPath); err == nil { group = groupFile defer groupFile.Close() } return GetExecUser(userSpec, defaults, passwd, group) }
[ "func", "GetExecUserPath", "(", "userSpec", "string", ",", "defaults", "*", "ExecUser", ",", "passwdPath", ",", "groupPath", "string", ")", "(", "*", "ExecUser", ",", "error", ")", "{", "var", "passwd", ",", "group", "io", ".", "Reader", "\n\n", "if", "passwdFile", ",", "err", ":=", "os", ".", "Open", "(", "passwdPath", ")", ";", "err", "==", "nil", "{", "passwd", "=", "passwdFile", "\n", "defer", "passwdFile", ".", "Close", "(", ")", "\n", "}", "\n\n", "if", "groupFile", ",", "err", ":=", "os", ".", "Open", "(", "groupPath", ")", ";", "err", "==", "nil", "{", "group", "=", "groupFile", "\n", "defer", "groupFile", ".", "Close", "(", ")", "\n", "}", "\n\n", "return", "GetExecUser", "(", "userSpec", ",", "defaults", ",", "passwd", ",", "group", ")", "\n", "}" ]
// GetExecUserPath is a wrapper for GetExecUser. It reads data from each of the // given file paths and uses that data as the arguments to GetExecUser. If the // files cannot be opened for any reason, the error is ignored and a nil // io.Reader is passed instead.
[ "GetExecUserPath", "is", "a", "wrapper", "for", "GetExecUser", ".", "It", "reads", "data", "from", "each", "of", "the", "given", "file", "paths", "and", "uses", "that", "data", "as", "the", "arguments", "to", "GetExecUser", ".", "If", "the", "files", "cannot", "be", "opened", "for", "any", "reason", "the", "error", "is", "ignored", "and", "a", "nil", "io", ".", "Reader", "is", "passed", "instead", "." ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/user/user.go#L260-L274
164,559
opencontainers/runc
libcontainer/user/user.go
GetAdditionalGroupsPath
func GetAdditionalGroupsPath(additionalGroups []string, groupPath string) ([]int, error) { var group io.Reader if groupFile, err := os.Open(groupPath); err == nil { group = groupFile defer groupFile.Close() } return GetAdditionalGroups(additionalGroups, group) }
go
func GetAdditionalGroupsPath(additionalGroups []string, groupPath string) ([]int, error) { var group io.Reader if groupFile, err := os.Open(groupPath); err == nil { group = groupFile defer groupFile.Close() } return GetAdditionalGroups(additionalGroups, group) }
[ "func", "GetAdditionalGroupsPath", "(", "additionalGroups", "[", "]", "string", ",", "groupPath", "string", ")", "(", "[", "]", "int", ",", "error", ")", "{", "var", "group", "io", ".", "Reader", "\n\n", "if", "groupFile", ",", "err", ":=", "os", ".", "Open", "(", "groupPath", ")", ";", "err", "==", "nil", "{", "group", "=", "groupFile", "\n", "defer", "groupFile", ".", "Close", "(", ")", "\n", "}", "\n", "return", "GetAdditionalGroups", "(", "additionalGroups", ",", "group", ")", "\n", "}" ]
// GetAdditionalGroupsPath is a wrapper around GetAdditionalGroups // that opens the groupPath given and gives it as an argument to // GetAdditionalGroups.
[ "GetAdditionalGroupsPath", "is", "a", "wrapper", "around", "GetAdditionalGroups", "that", "opens", "the", "groupPath", "given", "and", "gives", "it", "as", "an", "argument", "to", "GetAdditionalGroups", "." ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/user/user.go#L492-L500
164,560
opencontainers/runc
libcontainer/process.go
Wait
func (p Process) Wait() (*os.ProcessState, error) { if p.ops == nil { return nil, newGenericError(fmt.Errorf("invalid process"), NoProcessOps) } return p.ops.wait() }
go
func (p Process) Wait() (*os.ProcessState, error) { if p.ops == nil { return nil, newGenericError(fmt.Errorf("invalid process"), NoProcessOps) } return p.ops.wait() }
[ "func", "(", "p", "Process", ")", "Wait", "(", ")", "(", "*", "os", ".", "ProcessState", ",", "error", ")", "{", "if", "p", ".", "ops", "==", "nil", "{", "return", "nil", ",", "newGenericError", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ")", ",", "NoProcessOps", ")", "\n", "}", "\n", "return", "p", ".", "ops", ".", "wait", "(", ")", "\n", "}" ]
// Wait waits for the process to exit. // Wait releases any resources associated with the Process
[ "Wait", "waits", "for", "the", "process", "to", "exit", ".", "Wait", "releases", "any", "resources", "associated", "with", "the", "Process" ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/process.go#L83-L88
164,561
opencontainers/runc
libcontainer/cgroups/fs/cpuset.go
ensureParent
func (s *CpusetGroup) ensureParent(current, root string) error { parent := filepath.Dir(current) if libcontainerUtils.CleanPath(parent) == root { return nil } // Avoid infinite recursion. if parent == current { return fmt.Errorf("cpuset: cgroup parent path outside cgroup root") } if err := s.ensureParent(parent, root); err != nil { return err } if err := os.MkdirAll(current, 0755); err != nil { return err } return s.copyIfNeeded(current, parent) }
go
func (s *CpusetGroup) ensureParent(current, root string) error { parent := filepath.Dir(current) if libcontainerUtils.CleanPath(parent) == root { return nil } // Avoid infinite recursion. if parent == current { return fmt.Errorf("cpuset: cgroup parent path outside cgroup root") } if err := s.ensureParent(parent, root); err != nil { return err } if err := os.MkdirAll(current, 0755); err != nil { return err } return s.copyIfNeeded(current, parent) }
[ "func", "(", "s", "*", "CpusetGroup", ")", "ensureParent", "(", "current", ",", "root", "string", ")", "error", "{", "parent", ":=", "filepath", ".", "Dir", "(", "current", ")", "\n", "if", "libcontainerUtils", ".", "CleanPath", "(", "parent", ")", "==", "root", "{", "return", "nil", "\n", "}", "\n", "// Avoid infinite recursion.", "if", "parent", "==", "current", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "err", ":=", "s", ".", "ensureParent", "(", "parent", ",", "root", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "os", ".", "MkdirAll", "(", "current", ",", "0755", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "s", ".", "copyIfNeeded", "(", "current", ",", "parent", ")", "\n", "}" ]
// ensureParent makes sure that the parent directory of current is created // and populated with the proper cpus and mems files copied from // it's parent.
[ "ensureParent", "makes", "sure", "that", "the", "parent", "directory", "of", "current", "is", "created", "and", "populated", "with", "the", "proper", "cpus", "and", "mems", "files", "copied", "from", "it", "s", "parent", "." ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/cgroups/fs/cpuset.go#L103-L119
164,562
opencontainers/runc
libcontainer/cgroups/fs/cpuset.go
copyIfNeeded
func (s *CpusetGroup) copyIfNeeded(current, parent string) error { var ( err error currentCpus, currentMems []byte parentCpus, parentMems []byte ) if currentCpus, currentMems, err = s.getSubsystemSettings(current); err != nil { return err } if parentCpus, parentMems, err = s.getSubsystemSettings(parent); err != nil { return err } if s.isEmpty(currentCpus) { if err := writeFile(current, "cpuset.cpus", string(parentCpus)); err != nil { return err } } if s.isEmpty(currentMems) { if err := writeFile(current, "cpuset.mems", string(parentMems)); err != nil { return err } } return nil }
go
func (s *CpusetGroup) copyIfNeeded(current, parent string) error { var ( err error currentCpus, currentMems []byte parentCpus, parentMems []byte ) if currentCpus, currentMems, err = s.getSubsystemSettings(current); err != nil { return err } if parentCpus, parentMems, err = s.getSubsystemSettings(parent); err != nil { return err } if s.isEmpty(currentCpus) { if err := writeFile(current, "cpuset.cpus", string(parentCpus)); err != nil { return err } } if s.isEmpty(currentMems) { if err := writeFile(current, "cpuset.mems", string(parentMems)); err != nil { return err } } return nil }
[ "func", "(", "s", "*", "CpusetGroup", ")", "copyIfNeeded", "(", "current", ",", "parent", "string", ")", "error", "{", "var", "(", "err", "error", "\n", "currentCpus", ",", "currentMems", "[", "]", "byte", "\n", "parentCpus", ",", "parentMems", "[", "]", "byte", "\n", ")", "\n\n", "if", "currentCpus", ",", "currentMems", ",", "err", "=", "s", ".", "getSubsystemSettings", "(", "current", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "parentCpus", ",", "parentMems", ",", "err", "=", "s", ".", "getSubsystemSettings", "(", "parent", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "s", ".", "isEmpty", "(", "currentCpus", ")", "{", "if", "err", ":=", "writeFile", "(", "current", ",", "\"", "\"", ",", "string", "(", "parentCpus", ")", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "if", "s", ".", "isEmpty", "(", "currentMems", ")", "{", "if", "err", ":=", "writeFile", "(", "current", ",", "\"", "\"", ",", "string", "(", "parentMems", ")", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// copyIfNeeded copies the cpuset.cpus and cpuset.mems from the parent // directory to the current directory if the file's contents are 0
[ "copyIfNeeded", "copies", "the", "cpuset", ".", "cpus", "and", "cpuset", ".", "mems", "from", "the", "parent", "directory", "to", "the", "current", "directory", "if", "the", "file", "s", "contents", "are", "0" ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/cgroups/fs/cpuset.go#L123-L148
164,563
opencontainers/runc
libcontainer/container_linux.go
checkCriuVersion
func (c *linuxContainer) checkCriuVersion(minVersion int) error { // If the version of criu has already been determined there is no need // to ask criu for the version again. Use the value from c.criuVersion. if c.criuVersion != 0 { return compareCriuVersion(c.criuVersion, minVersion) } // First try if this version of CRIU support the version RPC. // The CRIU version RPC was introduced with CRIU 3.0. // First, reset the variable for the RPC answer to nil criuVersionRPC = nil var t criurpc.CriuReqType t = criurpc.CriuReqType_VERSION req := &criurpc.CriuReq{ Type: &t, } err := c.criuSwrk(nil, req, nil, false, nil) if err != nil { return fmt.Errorf("CRIU version check failed: %s", err) } if criuVersionRPC != nil { logrus.Debugf("CRIU version: %s", criuVersionRPC) // major and minor are always set c.criuVersion = int(*criuVersionRPC.Major) * 10000 c.criuVersion += int(*criuVersionRPC.Minor) * 100 if criuVersionRPC.Sublevel != nil { c.criuVersion += int(*criuVersionRPC.Sublevel) } if criuVersionRPC.Gitid != nil { // runc's convention is that a CRIU git release is // always the same as increasing the minor by 1 c.criuVersion -= (c.criuVersion % 100) c.criuVersion += 100 } return compareCriuVersion(c.criuVersion, minVersion) } // This is CRIU without the version RPC and therefore // older than 3.0. Parsing the output is required. // This can be remove once runc does not work with criu older than 3.0 c.criuVersion, err = parseCriuVersion(c.criuPath) if err != nil { return err } return compareCriuVersion(c.criuVersion, minVersion) }
go
func (c *linuxContainer) checkCriuVersion(minVersion int) error { // If the version of criu has already been determined there is no need // to ask criu for the version again. Use the value from c.criuVersion. if c.criuVersion != 0 { return compareCriuVersion(c.criuVersion, minVersion) } // First try if this version of CRIU support the version RPC. // The CRIU version RPC was introduced with CRIU 3.0. // First, reset the variable for the RPC answer to nil criuVersionRPC = nil var t criurpc.CriuReqType t = criurpc.CriuReqType_VERSION req := &criurpc.CriuReq{ Type: &t, } err := c.criuSwrk(nil, req, nil, false, nil) if err != nil { return fmt.Errorf("CRIU version check failed: %s", err) } if criuVersionRPC != nil { logrus.Debugf("CRIU version: %s", criuVersionRPC) // major and minor are always set c.criuVersion = int(*criuVersionRPC.Major) * 10000 c.criuVersion += int(*criuVersionRPC.Minor) * 100 if criuVersionRPC.Sublevel != nil { c.criuVersion += int(*criuVersionRPC.Sublevel) } if criuVersionRPC.Gitid != nil { // runc's convention is that a CRIU git release is // always the same as increasing the minor by 1 c.criuVersion -= (c.criuVersion % 100) c.criuVersion += 100 } return compareCriuVersion(c.criuVersion, minVersion) } // This is CRIU without the version RPC and therefore // older than 3.0. Parsing the output is required. // This can be remove once runc does not work with criu older than 3.0 c.criuVersion, err = parseCriuVersion(c.criuPath) if err != nil { return err } return compareCriuVersion(c.criuVersion, minVersion) }
[ "func", "(", "c", "*", "linuxContainer", ")", "checkCriuVersion", "(", "minVersion", "int", ")", "error", "{", "// If the version of criu has already been determined there is no need", "// to ask criu for the version again. Use the value from c.criuVersion.", "if", "c", ".", "criuVersion", "!=", "0", "{", "return", "compareCriuVersion", "(", "c", ".", "criuVersion", ",", "minVersion", ")", "\n", "}", "\n\n", "// First try if this version of CRIU support the version RPC.", "// The CRIU version RPC was introduced with CRIU 3.0.", "// First, reset the variable for the RPC answer to nil", "criuVersionRPC", "=", "nil", "\n\n", "var", "t", "criurpc", ".", "CriuReqType", "\n", "t", "=", "criurpc", ".", "CriuReqType_VERSION", "\n", "req", ":=", "&", "criurpc", ".", "CriuReq", "{", "Type", ":", "&", "t", ",", "}", "\n\n", "err", ":=", "c", ".", "criuSwrk", "(", "nil", ",", "req", ",", "nil", ",", "false", ",", "nil", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "if", "criuVersionRPC", "!=", "nil", "{", "logrus", ".", "Debugf", "(", "\"", "\"", ",", "criuVersionRPC", ")", "\n", "// major and minor are always set", "c", ".", "criuVersion", "=", "int", "(", "*", "criuVersionRPC", ".", "Major", ")", "*", "10000", "\n", "c", ".", "criuVersion", "+=", "int", "(", "*", "criuVersionRPC", ".", "Minor", ")", "*", "100", "\n", "if", "criuVersionRPC", ".", "Sublevel", "!=", "nil", "{", "c", ".", "criuVersion", "+=", "int", "(", "*", "criuVersionRPC", ".", "Sublevel", ")", "\n", "}", "\n", "if", "criuVersionRPC", ".", "Gitid", "!=", "nil", "{", "// runc's convention is that a CRIU git release is", "// always the same as increasing the minor by 1", "c", ".", "criuVersion", "-=", "(", "c", ".", "criuVersion", "%", "100", ")", "\n", "c", ".", "criuVersion", "+=", "100", "\n", "}", "\n", "return", "compareCriuVersion", "(", "c", ".", "criuVersion", ",", "minVersion", ")", "\n", "}", "\n\n", "// This is CRIU without the version RPC and therefore", "// older than 3.0. Parsing the output is required.", "// This can be remove once runc does not work with criu older than 3.0", "c", ".", "criuVersion", ",", "err", "=", "parseCriuVersion", "(", "c", ".", "criuPath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "return", "compareCriuVersion", "(", "c", ".", "criuVersion", ",", "minVersion", ")", "\n", "}" ]
// checkCriuVersion checks Criu version greater than or equal to minVersion
[ "checkCriuVersion", "checks", "Criu", "version", "greater", "than", "or", "equal", "to", "minVersion" ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/container_linux.go#L768-L821
164,564
opencontainers/runc
libcontainer/container_linux.go
makeCriuRestoreMountpoints
func (c *linuxContainer) makeCriuRestoreMountpoints(m *configs.Mount) error { switch m.Device { case "cgroup": // Do nothing for cgroup, CRIU should handle it case "bind": // The prepareBindMount() function checks if source // exists. So it cannot be used for other filesystem types. if err := prepareBindMount(m, c.config.Rootfs); err != nil { return err } default: // for all other file-systems just create the mountpoints dest, err := securejoin.SecureJoin(c.config.Rootfs, m.Destination) if err != nil { return err } if err := checkMountDestination(c.config.Rootfs, dest); err != nil { return err } m.Destination = dest if err := os.MkdirAll(dest, 0755); err != nil { return err } } return nil }
go
func (c *linuxContainer) makeCriuRestoreMountpoints(m *configs.Mount) error { switch m.Device { case "cgroup": // Do nothing for cgroup, CRIU should handle it case "bind": // The prepareBindMount() function checks if source // exists. So it cannot be used for other filesystem types. if err := prepareBindMount(m, c.config.Rootfs); err != nil { return err } default: // for all other file-systems just create the mountpoints dest, err := securejoin.SecureJoin(c.config.Rootfs, m.Destination) if err != nil { return err } if err := checkMountDestination(c.config.Rootfs, dest); err != nil { return err } m.Destination = dest if err := os.MkdirAll(dest, 0755); err != nil { return err } } return nil }
[ "func", "(", "c", "*", "linuxContainer", ")", "makeCriuRestoreMountpoints", "(", "m", "*", "configs", ".", "Mount", ")", "error", "{", "switch", "m", ".", "Device", "{", "case", "\"", "\"", ":", "// Do nothing for cgroup, CRIU should handle it", "case", "\"", "\"", ":", "// The prepareBindMount() function checks if source", "// exists. So it cannot be used for other filesystem types.", "if", "err", ":=", "prepareBindMount", "(", "m", ",", "c", ".", "config", ".", "Rootfs", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "default", ":", "// for all other file-systems just create the mountpoints", "dest", ",", "err", ":=", "securejoin", ".", "SecureJoin", "(", "c", ".", "config", ".", "Rootfs", ",", "m", ".", "Destination", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "checkMountDestination", "(", "c", ".", "config", ".", "Rootfs", ",", "dest", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "m", ".", "Destination", "=", "dest", "\n", "if", "err", ":=", "os", ".", "MkdirAll", "(", "dest", ",", "0755", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// makeCriuRestoreMountpoints makes the actual mountpoints for the // restore using CRIU. This function is inspired from the code in // rootfs_linux.go
[ "makeCriuRestoreMountpoints", "makes", "the", "actual", "mountpoints", "for", "the", "restore", "using", "CRIU", ".", "This", "function", "is", "inspired", "from", "the", "code", "in", "rootfs_linux", ".", "go" ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/container_linux.go#L1147-L1172
164,565
opencontainers/runc
libcontainer/container_linux.go
isPathInPrefixList
func isPathInPrefixList(path string, prefix []string) bool { for _, p := range prefix { if strings.HasPrefix(path, p+"/") { return false } } return true }
go
func isPathInPrefixList(path string, prefix []string) bool { for _, p := range prefix { if strings.HasPrefix(path, p+"/") { return false } } return true }
[ "func", "isPathInPrefixList", "(", "path", "string", ",", "prefix", "[", "]", "string", ")", "bool", "{", "for", "_", ",", "p", ":=", "range", "prefix", "{", "if", "strings", ".", "HasPrefix", "(", "path", ",", "p", "+", "\"", "\"", ")", "{", "return", "false", "\n", "}", "\n", "}", "\n", "return", "true", "\n", "}" ]
// isPathInPrefixList is a small function for CRIU restore to make sure // mountpoints, which are on a tmpfs, are not created in the roofs
[ "isPathInPrefixList", "is", "a", "small", "function", "for", "CRIU", "restore", "to", "make", "sure", "mountpoints", "which", "are", "on", "a", "tmpfs", "are", "not", "created", "in", "the", "roofs" ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/container_linux.go#L1176-L1183
164,566
opencontainers/runc
libcontainer/container_linux.go
prepareCriuRestoreMounts
func (c *linuxContainer) prepareCriuRestoreMounts(mounts []*configs.Mount) error { // First get a list of a all tmpfs mounts tmpfs := []string{} for _, m := range mounts { switch m.Device { case "tmpfs": tmpfs = append(tmpfs, m.Destination) } } // Now go through all mounts and create the mountpoints // if the mountpoints are not on a tmpfs, as CRIU will // restore the complete tmpfs content from its checkpoint. for _, m := range mounts { if isPathInPrefixList(m.Destination, tmpfs) { if err := c.makeCriuRestoreMountpoints(m); err != nil { return err } } } return nil }
go
func (c *linuxContainer) prepareCriuRestoreMounts(mounts []*configs.Mount) error { // First get a list of a all tmpfs mounts tmpfs := []string{} for _, m := range mounts { switch m.Device { case "tmpfs": tmpfs = append(tmpfs, m.Destination) } } // Now go through all mounts and create the mountpoints // if the mountpoints are not on a tmpfs, as CRIU will // restore the complete tmpfs content from its checkpoint. for _, m := range mounts { if isPathInPrefixList(m.Destination, tmpfs) { if err := c.makeCriuRestoreMountpoints(m); err != nil { return err } } } return nil }
[ "func", "(", "c", "*", "linuxContainer", ")", "prepareCriuRestoreMounts", "(", "mounts", "[", "]", "*", "configs", ".", "Mount", ")", "error", "{", "// First get a list of a all tmpfs mounts", "tmpfs", ":=", "[", "]", "string", "{", "}", "\n", "for", "_", ",", "m", ":=", "range", "mounts", "{", "switch", "m", ".", "Device", "{", "case", "\"", "\"", ":", "tmpfs", "=", "append", "(", "tmpfs", ",", "m", ".", "Destination", ")", "\n", "}", "\n", "}", "\n", "// Now go through all mounts and create the mountpoints", "// if the mountpoints are not on a tmpfs, as CRIU will", "// restore the complete tmpfs content from its checkpoint.", "for", "_", ",", "m", ":=", "range", "mounts", "{", "if", "isPathInPrefixList", "(", "m", ".", "Destination", ",", "tmpfs", ")", "{", "if", "err", ":=", "c", ".", "makeCriuRestoreMountpoints", "(", "m", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// prepareCriuRestoreMounts tries to set up the rootfs of the // container to be restored in the same way runc does it for // initial container creation. Even for a read-only rootfs container // runc modifies the rootfs to add mountpoints which do not exist. // This function also creates missing mountpoints as long as they // are not on top of a tmpfs, as CRIU will restore tmpfs content anyway.
[ "prepareCriuRestoreMounts", "tries", "to", "set", "up", "the", "rootfs", "of", "the", "container", "to", "be", "restored", "in", "the", "same", "way", "runc", "does", "it", "for", "initial", "container", "creation", ".", "Even", "for", "a", "read", "-", "only", "rootfs", "container", "runc", "modifies", "the", "rootfs", "to", "add", "mountpoints", "which", "do", "not", "exist", ".", "This", "function", "also", "creates", "missing", "mountpoints", "as", "long", "as", "they", "are", "not", "on", "top", "of", "a", "tmpfs", "as", "CRIU", "will", "restore", "tmpfs", "content", "anyway", "." ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/container_linux.go#L1191-L1211
164,567
opencontainers/runc
libcontainer/container_linux.go
lockNetwork
func lockNetwork(config *configs.Config) error { for _, config := range config.Networks { strategy, err := getStrategy(config.Type) if err != nil { return err } if err := strategy.detach(config); err != nil { return err } } return nil }
go
func lockNetwork(config *configs.Config) error { for _, config := range config.Networks { strategy, err := getStrategy(config.Type) if err != nil { return err } if err := strategy.detach(config); err != nil { return err } } return nil }
[ "func", "lockNetwork", "(", "config", "*", "configs", ".", "Config", ")", "error", "{", "for", "_", ",", "config", ":=", "range", "config", ".", "Networks", "{", "strategy", ",", "err", ":=", "getStrategy", "(", "config", ".", "Type", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "err", ":=", "strategy", ".", "detach", "(", "config", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// block any external network activity
[ "block", "any", "external", "network", "activity" ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/container_linux.go#L1610-L1622
164,568
opencontainers/runc
libcontainer/container_linux.go
refreshState
func (c *linuxContainer) refreshState() error { paused, err := c.isPaused() if err != nil { return err } if paused { return c.state.transition(&pausedState{c: c}) } t, err := c.runType() if err != nil { return err } switch t { case Created: return c.state.transition(&createdState{c: c}) case Running: return c.state.transition(&runningState{c: c}) } return c.state.transition(&stoppedState{c: c}) }
go
func (c *linuxContainer) refreshState() error { paused, err := c.isPaused() if err != nil { return err } if paused { return c.state.transition(&pausedState{c: c}) } t, err := c.runType() if err != nil { return err } switch t { case Created: return c.state.transition(&createdState{c: c}) case Running: return c.state.transition(&runningState{c: c}) } return c.state.transition(&stoppedState{c: c}) }
[ "func", "(", "c", "*", "linuxContainer", ")", "refreshState", "(", ")", "error", "{", "paused", ",", "err", ":=", "c", ".", "isPaused", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "paused", "{", "return", "c", ".", "state", ".", "transition", "(", "&", "pausedState", "{", "c", ":", "c", "}", ")", "\n", "}", "\n", "t", ",", "err", ":=", "c", ".", "runType", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "switch", "t", "{", "case", "Created", ":", "return", "c", ".", "state", ".", "transition", "(", "&", "createdState", "{", "c", ":", "c", "}", ")", "\n", "case", "Running", ":", "return", "c", ".", "state", ".", "transition", "(", "&", "runningState", "{", "c", ":", "c", "}", ")", "\n", "}", "\n", "return", "c", ".", "state", ".", "transition", "(", "&", "stoppedState", "{", "c", ":", "c", "}", ")", "\n", "}" ]
// refreshState needs to be called to verify that the current state on the // container is what is true. Because consumers of libcontainer can use it // out of process we need to verify the container's status based on runtime // information and not rely on our in process info.
[ "refreshState", "needs", "to", "be", "called", "to", "verify", "that", "the", "current", "state", "on", "the", "container", "is", "what", "is", "true", ".", "Because", "consumers", "of", "libcontainer", "can", "use", "it", "out", "of", "process", "we", "need", "to", "verify", "the", "container", "s", "status", "based", "on", "runtime", "information", "and", "not", "rely", "on", "our", "in", "process", "info", "." ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/container_linux.go#L1754-L1773
164,569
opencontainers/runc
libcontainer/container_linux.go
orderNamespacePaths
func (c *linuxContainer) orderNamespacePaths(namespaces map[configs.NamespaceType]string) ([]string, error) { paths := []string{} for _, ns := range configs.NamespaceTypes() { // Remove namespaces that we don't need to join. if !c.config.Namespaces.Contains(ns) { continue } if p, ok := namespaces[ns]; ok && p != "" { // check if the requested namespace is supported if !configs.IsNamespaceSupported(ns) { return nil, newSystemError(fmt.Errorf("namespace %s is not supported", ns)) } // only set to join this namespace if it exists if _, err := os.Lstat(p); err != nil { return nil, newSystemErrorWithCausef(err, "running lstat on namespace path %q", p) } // do not allow namespace path with comma as we use it to separate // the namespace paths if strings.ContainsRune(p, ',') { return nil, newSystemError(fmt.Errorf("invalid path %s", p)) } paths = append(paths, fmt.Sprintf("%s:%s", configs.NsName(ns), p)) } } return paths, nil }
go
func (c *linuxContainer) orderNamespacePaths(namespaces map[configs.NamespaceType]string) ([]string, error) { paths := []string{} for _, ns := range configs.NamespaceTypes() { // Remove namespaces that we don't need to join. if !c.config.Namespaces.Contains(ns) { continue } if p, ok := namespaces[ns]; ok && p != "" { // check if the requested namespace is supported if !configs.IsNamespaceSupported(ns) { return nil, newSystemError(fmt.Errorf("namespace %s is not supported", ns)) } // only set to join this namespace if it exists if _, err := os.Lstat(p); err != nil { return nil, newSystemErrorWithCausef(err, "running lstat on namespace path %q", p) } // do not allow namespace path with comma as we use it to separate // the namespace paths if strings.ContainsRune(p, ',') { return nil, newSystemError(fmt.Errorf("invalid path %s", p)) } paths = append(paths, fmt.Sprintf("%s:%s", configs.NsName(ns), p)) } } return paths, nil }
[ "func", "(", "c", "*", "linuxContainer", ")", "orderNamespacePaths", "(", "namespaces", "map", "[", "configs", ".", "NamespaceType", "]", "string", ")", "(", "[", "]", "string", ",", "error", ")", "{", "paths", ":=", "[", "]", "string", "{", "}", "\n", "for", "_", ",", "ns", ":=", "range", "configs", ".", "NamespaceTypes", "(", ")", "{", "// Remove namespaces that we don't need to join.", "if", "!", "c", ".", "config", ".", "Namespaces", ".", "Contains", "(", "ns", ")", "{", "continue", "\n", "}", "\n\n", "if", "p", ",", "ok", ":=", "namespaces", "[", "ns", "]", ";", "ok", "&&", "p", "!=", "\"", "\"", "{", "// check if the requested namespace is supported", "if", "!", "configs", ".", "IsNamespaceSupported", "(", "ns", ")", "{", "return", "nil", ",", "newSystemError", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "ns", ")", ")", "\n", "}", "\n", "// only set to join this namespace if it exists", "if", "_", ",", "err", ":=", "os", ".", "Lstat", "(", "p", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "newSystemErrorWithCausef", "(", "err", ",", "\"", "\"", ",", "p", ")", "\n", "}", "\n", "// do not allow namespace path with comma as we use it to separate", "// the namespace paths", "if", "strings", ".", "ContainsRune", "(", "p", ",", "','", ")", "{", "return", "nil", ",", "newSystemError", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "p", ")", ")", "\n", "}", "\n", "paths", "=", "append", "(", "paths", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "configs", ".", "NsName", "(", "ns", ")", ",", "p", ")", ")", "\n", "}", "\n\n", "}", "\n\n", "return", "paths", ",", "nil", "\n", "}" ]
// orderNamespacePaths sorts namespace paths into a list of paths that we // can setns in order.
[ "orderNamespacePaths", "sorts", "namespace", "paths", "into", "a", "list", "of", "paths", "that", "we", "can", "setns", "in", "order", "." ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/container_linux.go#L1881-L1910
164,570
opencontainers/runc
libcontainer/container_linux.go
ignoreTerminateErrors
func ignoreTerminateErrors(err error) error { if err == nil { return nil } s := err.Error() switch { case strings.Contains(s, "process already finished"), strings.Contains(s, "Wait was already called"): return nil } return err }
go
func ignoreTerminateErrors(err error) error { if err == nil { return nil } s := err.Error() switch { case strings.Contains(s, "process already finished"), strings.Contains(s, "Wait was already called"): return nil } return err }
[ "func", "ignoreTerminateErrors", "(", "err", "error", ")", "error", "{", "if", "err", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "s", ":=", "err", ".", "Error", "(", ")", "\n", "switch", "{", "case", "strings", ".", "Contains", "(", "s", ",", "\"", "\"", ")", ",", "strings", ".", "Contains", "(", "s", ",", "\"", "\"", ")", ":", "return", "nil", "\n", "}", "\n", "return", "err", "\n", "}" ]
// ignoreTerminateErrors returns nil if the given err matches an error known // to indicate that the terminate occurred successfully or err was nil, otherwise // err is returned unaltered.
[ "ignoreTerminateErrors", "returns", "nil", "if", "the", "given", "err", "matches", "an", "error", "known", "to", "indicate", "that", "the", "terminate", "occurred", "successfully", "or", "err", "was", "nil", "otherwise", "err", "is", "returned", "unaltered", "." ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/container_linux.go#L2017-L2027
164,571
opencontainers/runc
signals.go
newSignalHandler
func newSignalHandler(enableSubreaper bool, notifySocket *notifySocket) *signalHandler { if enableSubreaper { // set us as the subreaper before registering the signal handler for the container if err := system.SetSubreaper(1); err != nil { logrus.Warn(err) } } // ensure that we have a large buffer size so that we do not miss any signals // in case we are not processing them fast enough. s := make(chan os.Signal, signalBufferSize) // handle all signals for the process. signal.Notify(s) return &signalHandler{ signals: s, notifySocket: notifySocket, } }
go
func newSignalHandler(enableSubreaper bool, notifySocket *notifySocket) *signalHandler { if enableSubreaper { // set us as the subreaper before registering the signal handler for the container if err := system.SetSubreaper(1); err != nil { logrus.Warn(err) } } // ensure that we have a large buffer size so that we do not miss any signals // in case we are not processing them fast enough. s := make(chan os.Signal, signalBufferSize) // handle all signals for the process. signal.Notify(s) return &signalHandler{ signals: s, notifySocket: notifySocket, } }
[ "func", "newSignalHandler", "(", "enableSubreaper", "bool", ",", "notifySocket", "*", "notifySocket", ")", "*", "signalHandler", "{", "if", "enableSubreaper", "{", "// set us as the subreaper before registering the signal handler for the container", "if", "err", ":=", "system", ".", "SetSubreaper", "(", "1", ")", ";", "err", "!=", "nil", "{", "logrus", ".", "Warn", "(", "err", ")", "\n", "}", "\n", "}", "\n", "// ensure that we have a large buffer size so that we do not miss any signals", "// in case we are not processing them fast enough.", "s", ":=", "make", "(", "chan", "os", ".", "Signal", ",", "signalBufferSize", ")", "\n", "// handle all signals for the process.", "signal", ".", "Notify", "(", "s", ")", "\n", "return", "&", "signalHandler", "{", "signals", ":", "s", ",", "notifySocket", ":", "notifySocket", ",", "}", "\n", "}" ]
// newSignalHandler returns a signal handler for processing SIGCHLD and SIGWINCH signals // while still forwarding all other signals to the process. // If notifySocket is present, use it to read systemd notifications from the container and // forward them to notifySocketHost.
[ "newSignalHandler", "returns", "a", "signal", "handler", "for", "processing", "SIGCHLD", "and", "SIGWINCH", "signals", "while", "still", "forwarding", "all", "other", "signals", "to", "the", "process", ".", "If", "notifySocket", "is", "present", "use", "it", "to", "read", "systemd", "notifications", "from", "the", "container", "and", "forward", "them", "to", "notifySocketHost", "." ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/signals.go#L24-L40
164,572
opencontainers/runc
signals.go
forward
func (h *signalHandler) forward(process *libcontainer.Process, tty *tty, detach bool) (int, error) { // make sure we know the pid of our main process so that we can return // after it dies. if detach && h.notifySocket == nil { return 0, nil } pid1, err := process.Pid() if err != nil { return -1, err } if h.notifySocket != nil { if detach { h.notifySocket.run(pid1) return 0, nil } go h.notifySocket.run(0) } // Perform the initial tty resize. Always ignore errors resizing because // stdout might have disappeared (due to races with when SIGHUP is sent). _ = tty.resize() // Handle and forward signals. for s := range h.signals { switch s { case unix.SIGWINCH: // Ignore errors resizing, as above. _ = tty.resize() case unix.SIGCHLD: exits, err := h.reap() if err != nil { logrus.Error(err) } for _, e := range exits { logrus.WithFields(logrus.Fields{ "pid": e.pid, "status": e.status, }).Debug("process exited") if e.pid == pid1 { // call Wait() on the process even though we already have the exit // status because we must ensure that any of the go specific process // fun such as flushing pipes are complete before we return. process.Wait() if h.notifySocket != nil { h.notifySocket.Close() } return e.status, nil } } default: logrus.Debugf("sending signal to process %s", s) if err := unix.Kill(pid1, s.(syscall.Signal)); err != nil { logrus.Error(err) } } } return -1, nil }
go
func (h *signalHandler) forward(process *libcontainer.Process, tty *tty, detach bool) (int, error) { // make sure we know the pid of our main process so that we can return // after it dies. if detach && h.notifySocket == nil { return 0, nil } pid1, err := process.Pid() if err != nil { return -1, err } if h.notifySocket != nil { if detach { h.notifySocket.run(pid1) return 0, nil } go h.notifySocket.run(0) } // Perform the initial tty resize. Always ignore errors resizing because // stdout might have disappeared (due to races with when SIGHUP is sent). _ = tty.resize() // Handle and forward signals. for s := range h.signals { switch s { case unix.SIGWINCH: // Ignore errors resizing, as above. _ = tty.resize() case unix.SIGCHLD: exits, err := h.reap() if err != nil { logrus.Error(err) } for _, e := range exits { logrus.WithFields(logrus.Fields{ "pid": e.pid, "status": e.status, }).Debug("process exited") if e.pid == pid1 { // call Wait() on the process even though we already have the exit // status because we must ensure that any of the go specific process // fun such as flushing pipes are complete before we return. process.Wait() if h.notifySocket != nil { h.notifySocket.Close() } return e.status, nil } } default: logrus.Debugf("sending signal to process %s", s) if err := unix.Kill(pid1, s.(syscall.Signal)); err != nil { logrus.Error(err) } } } return -1, nil }
[ "func", "(", "h", "*", "signalHandler", ")", "forward", "(", "process", "*", "libcontainer", ".", "Process", ",", "tty", "*", "tty", ",", "detach", "bool", ")", "(", "int", ",", "error", ")", "{", "// make sure we know the pid of our main process so that we can return", "// after it dies.", "if", "detach", "&&", "h", ".", "notifySocket", "==", "nil", "{", "return", "0", ",", "nil", "\n", "}", "\n\n", "pid1", ",", "err", ":=", "process", ".", "Pid", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "-", "1", ",", "err", "\n", "}", "\n\n", "if", "h", ".", "notifySocket", "!=", "nil", "{", "if", "detach", "{", "h", ".", "notifySocket", ".", "run", "(", "pid1", ")", "\n", "return", "0", ",", "nil", "\n", "}", "\n", "go", "h", ".", "notifySocket", ".", "run", "(", "0", ")", "\n", "}", "\n\n", "// Perform the initial tty resize. Always ignore errors resizing because", "// stdout might have disappeared (due to races with when SIGHUP is sent).", "_", "=", "tty", ".", "resize", "(", ")", "\n", "// Handle and forward signals.", "for", "s", ":=", "range", "h", ".", "signals", "{", "switch", "s", "{", "case", "unix", ".", "SIGWINCH", ":", "// Ignore errors resizing, as above.", "_", "=", "tty", ".", "resize", "(", ")", "\n", "case", "unix", ".", "SIGCHLD", ":", "exits", ",", "err", ":=", "h", ".", "reap", "(", ")", "\n", "if", "err", "!=", "nil", "{", "logrus", ".", "Error", "(", "err", ")", "\n", "}", "\n", "for", "_", ",", "e", ":=", "range", "exits", "{", "logrus", ".", "WithFields", "(", "logrus", ".", "Fields", "{", "\"", "\"", ":", "e", ".", "pid", ",", "\"", "\"", ":", "e", ".", "status", ",", "}", ")", ".", "Debug", "(", "\"", "\"", ")", "\n", "if", "e", ".", "pid", "==", "pid1", "{", "// call Wait() on the process even though we already have the exit", "// status because we must ensure that any of the go specific process", "// fun such as flushing pipes are complete before we return.", "process", ".", "Wait", "(", ")", "\n", "if", "h", ".", "notifySocket", "!=", "nil", "{", "h", ".", "notifySocket", ".", "Close", "(", ")", "\n", "}", "\n", "return", "e", ".", "status", ",", "nil", "\n", "}", "\n", "}", "\n", "default", ":", "logrus", ".", "Debugf", "(", "\"", "\"", ",", "s", ")", "\n", "if", "err", ":=", "unix", ".", "Kill", "(", "pid1", ",", "s", ".", "(", "syscall", ".", "Signal", ")", ")", ";", "err", "!=", "nil", "{", "logrus", ".", "Error", "(", "err", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "-", "1", ",", "nil", "\n", "}" ]
// forward handles the main signal event loop forwarding, resizing, or reaping depending // on the signal received.
[ "forward", "handles", "the", "main", "signal", "event", "loop", "forwarding", "resizing", "or", "reaping", "depending", "on", "the", "signal", "received", "." ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/signals.go#L56-L114
164,573
opencontainers/runc
signals.go
reap
func (h *signalHandler) reap() (exits []exit, err error) { var ( ws unix.WaitStatus rus unix.Rusage ) for { pid, err := unix.Wait4(-1, &ws, unix.WNOHANG, &rus) if err != nil { if err == unix.ECHILD { return exits, nil } return nil, err } if pid <= 0 { return exits, nil } exits = append(exits, exit{ pid: pid, status: utils.ExitStatus(ws), }) } }
go
func (h *signalHandler) reap() (exits []exit, err error) { var ( ws unix.WaitStatus rus unix.Rusage ) for { pid, err := unix.Wait4(-1, &ws, unix.WNOHANG, &rus) if err != nil { if err == unix.ECHILD { return exits, nil } return nil, err } if pid <= 0 { return exits, nil } exits = append(exits, exit{ pid: pid, status: utils.ExitStatus(ws), }) } }
[ "func", "(", "h", "*", "signalHandler", ")", "reap", "(", ")", "(", "exits", "[", "]", "exit", ",", "err", "error", ")", "{", "var", "(", "ws", "unix", ".", "WaitStatus", "\n", "rus", "unix", ".", "Rusage", "\n", ")", "\n", "for", "{", "pid", ",", "err", ":=", "unix", ".", "Wait4", "(", "-", "1", ",", "&", "ws", ",", "unix", ".", "WNOHANG", ",", "&", "rus", ")", "\n", "if", "err", "!=", "nil", "{", "if", "err", "==", "unix", ".", "ECHILD", "{", "return", "exits", ",", "nil", "\n", "}", "\n", "return", "nil", ",", "err", "\n", "}", "\n", "if", "pid", "<=", "0", "{", "return", "exits", ",", "nil", "\n", "}", "\n", "exits", "=", "append", "(", "exits", ",", "exit", "{", "pid", ":", "pid", ",", "status", ":", "utils", ".", "ExitStatus", "(", "ws", ")", ",", "}", ")", "\n", "}", "\n", "}" ]
// reap runs wait4 in a loop until we have finished processing any existing exits // then returns all exits to the main event loop for further processing.
[ "reap", "runs", "wait4", "in", "a", "loop", "until", "we", "have", "finished", "processing", "any", "existing", "exits", "then", "returns", "all", "exits", "to", "the", "main", "event", "loop", "for", "further", "processing", "." ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/signals.go#L118-L139
164,574
opencontainers/runc
libcontainer/configs/validate/validator.go
rootfs
func (v *ConfigValidator) rootfs(config *configs.Config) error { if _, err := os.Stat(config.Rootfs); err != nil { if os.IsNotExist(err) { return fmt.Errorf("rootfs (%s) does not exist", config.Rootfs) } return err } cleaned, err := filepath.Abs(config.Rootfs) if err != nil { return err } if cleaned, err = filepath.EvalSymlinks(cleaned); err != nil { return err } if filepath.Clean(config.Rootfs) != cleaned { return fmt.Errorf("%s is not an absolute path or is a symlink", config.Rootfs) } return nil }
go
func (v *ConfigValidator) rootfs(config *configs.Config) error { if _, err := os.Stat(config.Rootfs); err != nil { if os.IsNotExist(err) { return fmt.Errorf("rootfs (%s) does not exist", config.Rootfs) } return err } cleaned, err := filepath.Abs(config.Rootfs) if err != nil { return err } if cleaned, err = filepath.EvalSymlinks(cleaned); err != nil { return err } if filepath.Clean(config.Rootfs) != cleaned { return fmt.Errorf("%s is not an absolute path or is a symlink", config.Rootfs) } return nil }
[ "func", "(", "v", "*", "ConfigValidator", ")", "rootfs", "(", "config", "*", "configs", ".", "Config", ")", "error", "{", "if", "_", ",", "err", ":=", "os", ".", "Stat", "(", "config", ".", "Rootfs", ")", ";", "err", "!=", "nil", "{", "if", "os", ".", "IsNotExist", "(", "err", ")", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "config", ".", "Rootfs", ")", "\n", "}", "\n", "return", "err", "\n", "}", "\n", "cleaned", ",", "err", ":=", "filepath", ".", "Abs", "(", "config", ".", "Rootfs", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "cleaned", ",", "err", "=", "filepath", ".", "EvalSymlinks", "(", "cleaned", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "filepath", ".", "Clean", "(", "config", ".", "Rootfs", ")", "!=", "cleaned", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "config", ".", "Rootfs", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// rootfs validates if the rootfs is an absolute path and is not a symlink // to the container's root filesystem.
[ "rootfs", "validates", "if", "the", "rootfs", "is", "an", "absolute", "path", "and", "is", "not", "a", "symlink", "to", "the", "container", "s", "root", "filesystem", "." ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/configs/validate/validator.go#L60-L78
164,575
opencontainers/runc
libcontainer/configs/validate/validator.go
checkHostNs
func checkHostNs(sysctlConfig string, path string) error { var currentProcessNetns = "/proc/self/ns/net" // readlink on the current processes network namespace destOfCurrentProcess, err := os.Readlink(currentProcessNetns) if err != nil { return fmt.Errorf("read soft link %q error", currentProcessNetns) } // First check if the provided path is a symbolic link symLink, err := isSymbolicLink(path) if err != nil { return fmt.Errorf("could not check that %q is a symlink: %v", path, err) } if symLink == false { // The provided namespace is not a symbolic link, // it is not the host namespace. return nil } // readlink on the path provided in the struct destOfContainer, err := os.Readlink(path) if err != nil { return fmt.Errorf("read soft link %q error", path) } if destOfContainer == destOfCurrentProcess { return fmt.Errorf("sysctl %q is not allowed in the hosts network namespace", sysctlConfig) } return nil }
go
func checkHostNs(sysctlConfig string, path string) error { var currentProcessNetns = "/proc/self/ns/net" // readlink on the current processes network namespace destOfCurrentProcess, err := os.Readlink(currentProcessNetns) if err != nil { return fmt.Errorf("read soft link %q error", currentProcessNetns) } // First check if the provided path is a symbolic link symLink, err := isSymbolicLink(path) if err != nil { return fmt.Errorf("could not check that %q is a symlink: %v", path, err) } if symLink == false { // The provided namespace is not a symbolic link, // it is not the host namespace. return nil } // readlink on the path provided in the struct destOfContainer, err := os.Readlink(path) if err != nil { return fmt.Errorf("read soft link %q error", path) } if destOfContainer == destOfCurrentProcess { return fmt.Errorf("sysctl %q is not allowed in the hosts network namespace", sysctlConfig) } return nil }
[ "func", "checkHostNs", "(", "sysctlConfig", "string", ",", "path", "string", ")", "error", "{", "var", "currentProcessNetns", "=", "\"", "\"", "\n", "// readlink on the current processes network namespace", "destOfCurrentProcess", ",", "err", ":=", "os", ".", "Readlink", "(", "currentProcessNetns", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "currentProcessNetns", ")", "\n", "}", "\n\n", "// First check if the provided path is a symbolic link", "symLink", ",", "err", ":=", "isSymbolicLink", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "path", ",", "err", ")", "\n", "}", "\n\n", "if", "symLink", "==", "false", "{", "// The provided namespace is not a symbolic link,", "// it is not the host namespace.", "return", "nil", "\n", "}", "\n\n", "// readlink on the path provided in the struct", "destOfContainer", ",", "err", ":=", "os", ".", "Readlink", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "path", ")", "\n", "}", "\n", "if", "destOfContainer", "==", "destOfCurrentProcess", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "sysctlConfig", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// checkHostNs checks whether network sysctl is used in host namespace.
[ "checkHostNs", "checks", "whether", "network", "sysctl", "is", "used", "in", "host", "namespace", "." ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/configs/validate/validator.go#L216-L245
164,576
opencontainers/runc
libcontainer/sync.go
writeSync
func writeSync(pipe io.Writer, sync syncType) error { return utils.WriteJSON(pipe, syncT{sync}) }
go
func writeSync(pipe io.Writer, sync syncType) error { return utils.WriteJSON(pipe, syncT{sync}) }
[ "func", "writeSync", "(", "pipe", "io", ".", "Writer", ",", "sync", "syncType", ")", "error", "{", "return", "utils", ".", "WriteJSON", "(", "pipe", ",", "syncT", "{", "sync", "}", ")", "\n", "}" ]
// writeSync is used to write to a synchronisation pipe. An error is returned // if there was a problem writing the payload.
[ "writeSync", "is", "used", "to", "write", "to", "a", "synchronisation", "pipe", ".", "An", "error", "is", "returned", "if", "there", "was", "a", "problem", "writing", "the", "payload", "." ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/sync.go#L43-L45
164,577
opencontainers/runc
libcontainer/sync.go
readSync
func readSync(pipe io.Reader, expected syncType) error { var procSync syncT if err := json.NewDecoder(pipe).Decode(&procSync); err != nil { if err == io.EOF { return fmt.Errorf("parent closed synchronisation channel") } if procSync.Type == procError { var ierr genericError if err := json.NewDecoder(pipe).Decode(&ierr); err != nil { return fmt.Errorf("failed reading error from parent: %v", err) } return &ierr } if procSync.Type != expected { return fmt.Errorf("invalid synchronisation flag from parent") } } return nil }
go
func readSync(pipe io.Reader, expected syncType) error { var procSync syncT if err := json.NewDecoder(pipe).Decode(&procSync); err != nil { if err == io.EOF { return fmt.Errorf("parent closed synchronisation channel") } if procSync.Type == procError { var ierr genericError if err := json.NewDecoder(pipe).Decode(&ierr); err != nil { return fmt.Errorf("failed reading error from parent: %v", err) } return &ierr } if procSync.Type != expected { return fmt.Errorf("invalid synchronisation flag from parent") } } return nil }
[ "func", "readSync", "(", "pipe", "io", ".", "Reader", ",", "expected", "syncType", ")", "error", "{", "var", "procSync", "syncT", "\n", "if", "err", ":=", "json", ".", "NewDecoder", "(", "pipe", ")", ".", "Decode", "(", "&", "procSync", ")", ";", "err", "!=", "nil", "{", "if", "err", "==", "io", ".", "EOF", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "procSync", ".", "Type", "==", "procError", "{", "var", "ierr", "genericError", "\n\n", "if", "err", ":=", "json", ".", "NewDecoder", "(", "pipe", ")", ".", "Decode", "(", "&", "ierr", ")", ";", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "return", "&", "ierr", "\n", "}", "\n\n", "if", "procSync", ".", "Type", "!=", "expected", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// readSync is used to read from a synchronisation pipe. An error is returned // if we got a genericError, the pipe was closed, or we got an unexpected flag.
[ "readSync", "is", "used", "to", "read", "from", "a", "synchronisation", "pipe", ".", "An", "error", "is", "returned", "if", "we", "got", "a", "genericError", "the", "pipe", "was", "closed", "or", "we", "got", "an", "unexpected", "flag", "." ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/sync.go#L49-L71
164,578
opencontainers/runc
libcontainer/sync.go
parseSync
func parseSync(pipe io.Reader, fn func(*syncT) error) error { dec := json.NewDecoder(pipe) for { var sync syncT if err := dec.Decode(&sync); err != nil { if err == io.EOF { break } return err } // We handle this case outside fn for cleanliness reasons. var ierr *genericError if sync.Type == procError { if err := dec.Decode(&ierr); err != nil && err != io.EOF { return newSystemErrorWithCause(err, "decoding proc error from init") } if ierr != nil { return ierr } // Programmer error. panic("No error following JSON procError payload.") } if err := fn(&sync); err != nil { return err } } return nil }
go
func parseSync(pipe io.Reader, fn func(*syncT) error) error { dec := json.NewDecoder(pipe) for { var sync syncT if err := dec.Decode(&sync); err != nil { if err == io.EOF { break } return err } // We handle this case outside fn for cleanliness reasons. var ierr *genericError if sync.Type == procError { if err := dec.Decode(&ierr); err != nil && err != io.EOF { return newSystemErrorWithCause(err, "decoding proc error from init") } if ierr != nil { return ierr } // Programmer error. panic("No error following JSON procError payload.") } if err := fn(&sync); err != nil { return err } } return nil }
[ "func", "parseSync", "(", "pipe", "io", ".", "Reader", ",", "fn", "func", "(", "*", "syncT", ")", "error", ")", "error", "{", "dec", ":=", "json", ".", "NewDecoder", "(", "pipe", ")", "\n", "for", "{", "var", "sync", "syncT", "\n", "if", "err", ":=", "dec", ".", "Decode", "(", "&", "sync", ")", ";", "err", "!=", "nil", "{", "if", "err", "==", "io", ".", "EOF", "{", "break", "\n", "}", "\n", "return", "err", "\n", "}", "\n\n", "// We handle this case outside fn for cleanliness reasons.", "var", "ierr", "*", "genericError", "\n", "if", "sync", ".", "Type", "==", "procError", "{", "if", "err", ":=", "dec", ".", "Decode", "(", "&", "ierr", ")", ";", "err", "!=", "nil", "&&", "err", "!=", "io", ".", "EOF", "{", "return", "newSystemErrorWithCause", "(", "err", ",", "\"", "\"", ")", "\n", "}", "\n", "if", "ierr", "!=", "nil", "{", "return", "ierr", "\n", "}", "\n", "// Programmer error.", "panic", "(", "\"", "\"", ")", "\n", "}", "\n\n", "if", "err", ":=", "fn", "(", "&", "sync", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// parseSync runs the given callback function on each syncT received from the // child. It will return once io.EOF is returned from the given pipe.
[ "parseSync", "runs", "the", "given", "callback", "function", "on", "each", "syncT", "received", "from", "the", "child", ".", "It", "will", "return", "once", "io", ".", "EOF", "is", "returned", "from", "the", "given", "pipe", "." ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/sync.go#L75-L104
164,579
opencontainers/runc
libcontainer/cgroups/systemd/apply_systemd.go
isUnitExists
func isUnitExists(err error) bool { if err != nil { if dbusError, ok := err.(dbus.Error); ok { return strings.Contains(dbusError.Name, "org.freedesktop.systemd1.UnitExists") } } return false }
go
func isUnitExists(err error) bool { if err != nil { if dbusError, ok := err.(dbus.Error); ok { return strings.Contains(dbusError.Name, "org.freedesktop.systemd1.UnitExists") } } return false }
[ "func", "isUnitExists", "(", "err", "error", ")", "bool", "{", "if", "err", "!=", "nil", "{", "if", "dbusError", ",", "ok", ":=", "err", ".", "(", "dbus", ".", "Error", ")", ";", "ok", "{", "return", "strings", ".", "Contains", "(", "dbusError", ".", "Name", ",", "\"", "\"", ")", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// isUnitExists returns true if the error is that a systemd unit already exists.
[ "isUnitExists", "returns", "true", "if", "the", "error", "is", "that", "a", "systemd", "unit", "already", "exists", "." ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/cgroups/systemd/apply_systemd.go#L555-L562
164,580
opencontainers/runc
libcontainer/system/proc.go
Stat
func Stat(pid int) (stat Stat_t, err error) { bytes, err := ioutil.ReadFile(filepath.Join("/proc", strconv.Itoa(pid), "stat")) if err != nil { return stat, err } return parseStat(string(bytes)) }
go
func Stat(pid int) (stat Stat_t, err error) { bytes, err := ioutil.ReadFile(filepath.Join("/proc", strconv.Itoa(pid), "stat")) if err != nil { return stat, err } return parseStat(string(bytes)) }
[ "func", "Stat", "(", "pid", "int", ")", "(", "stat", "Stat_t", ",", "err", "error", ")", "{", "bytes", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "filepath", ".", "Join", "(", "\"", "\"", ",", "strconv", ".", "Itoa", "(", "pid", ")", ",", "\"", "\"", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "stat", ",", "err", "\n", "}", "\n", "return", "parseStat", "(", "string", "(", "bytes", ")", ")", "\n", "}" ]
// Stat returns a Stat_t instance for the specified process.
[ "Stat", "returns", "a", "Stat_t", "instance", "for", "the", "specified", "process", "." ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/system/proc.go#L66-L72
164,581
opencontainers/runc
libcontainer/network_linux.go
getStrategy
func getStrategy(tpe string) (networkStrategy, error) { s, exists := strategies[tpe] if !exists { return nil, fmt.Errorf("unknown strategy type %q", tpe) } return s, nil }
go
func getStrategy(tpe string) (networkStrategy, error) { s, exists := strategies[tpe] if !exists { return nil, fmt.Errorf("unknown strategy type %q", tpe) } return s, nil }
[ "func", "getStrategy", "(", "tpe", "string", ")", "(", "networkStrategy", ",", "error", ")", "{", "s", ",", "exists", ":=", "strategies", "[", "tpe", "]", "\n", "if", "!", "exists", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "tpe", ")", "\n", "}", "\n", "return", "s", ",", "nil", "\n", "}" ]
// getStrategy returns the specific network strategy for the // provided type.
[ "getStrategy", "returns", "the", "specific", "network", "strategy", "for", "the", "provided", "type", "." ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/network_linux.go#L31-L37
164,582
opencontainers/runc
libcontainer/network_linux.go
getNetworkInterfaceStats
func getNetworkInterfaceStats(interfaceName string) (*NetworkInterface, error) { out := &NetworkInterface{Name: interfaceName} // This can happen if the network runtime information is missing - possible if the // container was created by an old version of libcontainer. if interfaceName == "" { return out, nil } type netStatsPair struct { // Where to write the output. Out *uint64 // The network stats file to read. File string } // Ingress for host veth is from the container. Hence tx_bytes stat on the host veth is actually number of bytes received by the container. netStats := []netStatsPair{ {Out: &out.RxBytes, File: "tx_bytes"}, {Out: &out.RxPackets, File: "tx_packets"}, {Out: &out.RxErrors, File: "tx_errors"}, {Out: &out.RxDropped, File: "tx_dropped"}, {Out: &out.TxBytes, File: "rx_bytes"}, {Out: &out.TxPackets, File: "rx_packets"}, {Out: &out.TxErrors, File: "rx_errors"}, {Out: &out.TxDropped, File: "rx_dropped"}, } for _, netStat := range netStats { data, err := readSysfsNetworkStats(interfaceName, netStat.File) if err != nil { return nil, err } *(netStat.Out) = data } return out, nil }
go
func getNetworkInterfaceStats(interfaceName string) (*NetworkInterface, error) { out := &NetworkInterface{Name: interfaceName} // This can happen if the network runtime information is missing - possible if the // container was created by an old version of libcontainer. if interfaceName == "" { return out, nil } type netStatsPair struct { // Where to write the output. Out *uint64 // The network stats file to read. File string } // Ingress for host veth is from the container. Hence tx_bytes stat on the host veth is actually number of bytes received by the container. netStats := []netStatsPair{ {Out: &out.RxBytes, File: "tx_bytes"}, {Out: &out.RxPackets, File: "tx_packets"}, {Out: &out.RxErrors, File: "tx_errors"}, {Out: &out.RxDropped, File: "tx_dropped"}, {Out: &out.TxBytes, File: "rx_bytes"}, {Out: &out.TxPackets, File: "rx_packets"}, {Out: &out.TxErrors, File: "rx_errors"}, {Out: &out.TxDropped, File: "rx_dropped"}, } for _, netStat := range netStats { data, err := readSysfsNetworkStats(interfaceName, netStat.File) if err != nil { return nil, err } *(netStat.Out) = data } return out, nil }
[ "func", "getNetworkInterfaceStats", "(", "interfaceName", "string", ")", "(", "*", "NetworkInterface", ",", "error", ")", "{", "out", ":=", "&", "NetworkInterface", "{", "Name", ":", "interfaceName", "}", "\n", "// This can happen if the network runtime information is missing - possible if the", "// container was created by an old version of libcontainer.", "if", "interfaceName", "==", "\"", "\"", "{", "return", "out", ",", "nil", "\n", "}", "\n", "type", "netStatsPair", "struct", "{", "// Where to write the output.", "Out", "*", "uint64", "\n", "// The network stats file to read.", "File", "string", "\n", "}", "\n", "// Ingress for host veth is from the container. Hence tx_bytes stat on the host veth is actually number of bytes received by the container.", "netStats", ":=", "[", "]", "netStatsPair", "{", "{", "Out", ":", "&", "out", ".", "RxBytes", ",", "File", ":", "\"", "\"", "}", ",", "{", "Out", ":", "&", "out", ".", "RxPackets", ",", "File", ":", "\"", "\"", "}", ",", "{", "Out", ":", "&", "out", ".", "RxErrors", ",", "File", ":", "\"", "\"", "}", ",", "{", "Out", ":", "&", "out", ".", "RxDropped", ",", "File", ":", "\"", "\"", "}", ",", "{", "Out", ":", "&", "out", ".", "TxBytes", ",", "File", ":", "\"", "\"", "}", ",", "{", "Out", ":", "&", "out", ".", "TxPackets", ",", "File", ":", "\"", "\"", "}", ",", "{", "Out", ":", "&", "out", ".", "TxErrors", ",", "File", ":", "\"", "\"", "}", ",", "{", "Out", ":", "&", "out", ".", "TxDropped", ",", "File", ":", "\"", "\"", "}", ",", "}", "\n", "for", "_", ",", "netStat", ":=", "range", "netStats", "{", "data", ",", "err", ":=", "readSysfsNetworkStats", "(", "interfaceName", ",", "netStat", ".", "File", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "*", "(", "netStat", ".", "Out", ")", "=", "data", "\n", "}", "\n", "return", "out", ",", "nil", "\n", "}" ]
// Returns the network statistics for the network interfaces represented by the NetworkRuntimeInfo.
[ "Returns", "the", "network", "statistics", "for", "the", "network", "interfaces", "represented", "by", "the", "NetworkRuntimeInfo", "." ]
dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf
https://github.com/opencontainers/runc/blob/dae70e8efea4199c8ac3d8c80eb23e1f75e60ebf/libcontainer/network_linux.go#L40-L73
164,583
go-redis/redis
commands.go
SMembersMap
func (c *cmdable) SMembersMap(key string) *StringStructMapCmd { cmd := NewStringStructMapCmd("smembers", key) c.process(cmd) return cmd }
go
func (c *cmdable) SMembersMap(key string) *StringStructMapCmd { cmd := NewStringStructMapCmd("smembers", key) c.process(cmd) return cmd }
[ "func", "(", "c", "*", "cmdable", ")", "SMembersMap", "(", "key", "string", ")", "*", "StringStructMapCmd", "{", "cmd", ":=", "NewStringStructMapCmd", "(", "\"", "\"", ",", "key", ")", "\n", "c", ".", "process", "(", "cmd", ")", "\n", "return", "cmd", "\n", "}" ]
// Redis `SMEMBERS key` command output as a map
[ "Redis", "SMEMBERS", "key", "command", "output", "as", "a", "map" ]
97e6ed817821d91977b51fdec185ca2dbb917fa6
https://github.com/go-redis/redis/blob/97e6ed817821d91977b51fdec185ca2dbb917fa6/commands.go#L1239-L1243
164,584
go-redis/redis
commands.go
SRandMemberN
func (c *cmdable) SRandMemberN(key string, count int64) *StringSliceCmd { cmd := NewStringSliceCmd("srandmember", key, count) c.process(cmd) return cmd }
go
func (c *cmdable) SRandMemberN(key string, count int64) *StringSliceCmd { cmd := NewStringSliceCmd("srandmember", key, count) c.process(cmd) return cmd }
[ "func", "(", "c", "*", "cmdable", ")", "SRandMemberN", "(", "key", "string", ",", "count", "int64", ")", "*", "StringSliceCmd", "{", "cmd", ":=", "NewStringSliceCmd", "(", "\"", "\"", ",", "key", ",", "count", ")", "\n", "c", ".", "process", "(", "cmd", ")", "\n", "return", "cmd", "\n", "}" ]
// Redis `SRANDMEMBER key count` command.
[ "Redis", "SRANDMEMBER", "key", "count", "command", "." ]
97e6ed817821d91977b51fdec185ca2dbb917fa6
https://github.com/go-redis/redis/blob/97e6ed817821d91977b51fdec185ca2dbb917fa6/commands.go#L1273-L1277
164,585
go-redis/redis
commands.go
ZIncrXX
func (c *cmdable) ZIncrXX(key string, member Z) *FloatCmd { const n = 4 a := make([]interface{}, n+2) a[0], a[1], a[2], a[3] = "zadd", key, "incr", "xx" return c.zIncr(a, n, member) }
go
func (c *cmdable) ZIncrXX(key string, member Z) *FloatCmd { const n = 4 a := make([]interface{}, n+2) a[0], a[1], a[2], a[3] = "zadd", key, "incr", "xx" return c.zIncr(a, n, member) }
[ "func", "(", "c", "*", "cmdable", ")", "ZIncrXX", "(", "key", "string", ",", "member", "Z", ")", "*", "FloatCmd", "{", "const", "n", "=", "4", "\n", "a", ":=", "make", "(", "[", "]", "interface", "{", "}", ",", "n", "+", "2", ")", "\n", "a", "[", "0", "]", ",", "a", "[", "1", "]", ",", "a", "[", "2", "]", ",", "a", "[", "3", "]", "=", "\"", "\"", ",", "key", ",", "\"", "\"", ",", "\"", "\"", "\n", "return", "c", ".", "zIncr", "(", "a", ",", "n", ",", "member", ")", "\n", "}" ]
// Redis `ZADD key XX INCR score member` command.
[ "Redis", "ZADD", "key", "XX", "INCR", "score", "member", "command", "." ]
97e6ed817821d91977b51fdec185ca2dbb917fa6
https://github.com/go-redis/redis/blob/97e6ed817821d91977b51fdec185ca2dbb917fa6/commands.go#L1706-L1711
164,586
go-redis/redis
commands.go
ClientSetName
func (c *statefulCmdable) ClientSetName(name string) *BoolCmd { cmd := NewBoolCmd("client", "setname", name) c.process(cmd) return cmd }
go
func (c *statefulCmdable) ClientSetName(name string) *BoolCmd { cmd := NewBoolCmd("client", "setname", name) c.process(cmd) return cmd }
[ "func", "(", "c", "*", "statefulCmdable", ")", "ClientSetName", "(", "name", "string", ")", "*", "BoolCmd", "{", "cmd", ":=", "NewBoolCmd", "(", "\"", "\"", ",", "\"", "\"", ",", "name", ")", "\n", "c", ".", "process", "(", "cmd", ")", "\n", "return", "cmd", "\n", "}" ]
// ClientSetName assigns a name to the connection.
[ "ClientSetName", "assigns", "a", "name", "to", "the", "connection", "." ]
97e6ed817821d91977b51fdec185ca2dbb917fa6
https://github.com/go-redis/redis/blob/97e6ed817821d91977b51fdec185ca2dbb917fa6/commands.go#L2093-L2097
164,587
go-redis/redis
commands.go
ClientGetName
func (c *cmdable) ClientGetName() *StringCmd { cmd := NewStringCmd("client", "getname") c.process(cmd) return cmd }
go
func (c *cmdable) ClientGetName() *StringCmd { cmd := NewStringCmd("client", "getname") c.process(cmd) return cmd }
[ "func", "(", "c", "*", "cmdable", ")", "ClientGetName", "(", ")", "*", "StringCmd", "{", "cmd", ":=", "NewStringCmd", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "c", ".", "process", "(", "cmd", ")", "\n", "return", "cmd", "\n", "}" ]
// ClientGetName returns the name of the connection.
[ "ClientGetName", "returns", "the", "name", "of", "the", "connection", "." ]
97e6ed817821d91977b51fdec185ca2dbb917fa6
https://github.com/go-redis/redis/blob/97e6ed817821d91977b51fdec185ca2dbb917fa6/commands.go#L2100-L2104
164,588
go-redis/redis
iterator.go
Err
func (it *ScanIterator) Err() error { it.mu.Lock() err := it.cmd.Err() it.mu.Unlock() return err }
go
func (it *ScanIterator) Err() error { it.mu.Lock() err := it.cmd.Err() it.mu.Unlock() return err }
[ "func", "(", "it", "*", "ScanIterator", ")", "Err", "(", ")", "error", "{", "it", ".", "mu", ".", "Lock", "(", ")", "\n", "err", ":=", "it", ".", "cmd", ".", "Err", "(", ")", "\n", "it", ".", "mu", ".", "Unlock", "(", ")", "\n", "return", "err", "\n", "}" ]
// Err returns the last iterator error, if any.
[ "Err", "returns", "the", "last", "iterator", "error", "if", "any", "." ]
97e6ed817821d91977b51fdec185ca2dbb917fa6
https://github.com/go-redis/redis/blob/97e6ed817821d91977b51fdec185ca2dbb917fa6/iterator.go#L14-L19
164,589
go-redis/redis
iterator.go
Next
func (it *ScanIterator) Next() bool { it.mu.Lock() defer it.mu.Unlock() // Instantly return on errors. if it.cmd.Err() != nil { return false } // Advance cursor, check if we are still within range. if it.pos < len(it.cmd.page) { it.pos++ return true } for { // Return if there is no more data to fetch. if it.cmd.cursor == 0 { return false } // Fetch next page. if it.cmd._args[0] == "scan" { it.cmd._args[1] = it.cmd.cursor } else { it.cmd._args[2] = it.cmd.cursor } err := it.cmd.process(it.cmd) if err != nil { return false } it.pos = 1 // Redis can occasionally return empty page. if len(it.cmd.page) > 0 { return true } } }
go
func (it *ScanIterator) Next() bool { it.mu.Lock() defer it.mu.Unlock() // Instantly return on errors. if it.cmd.Err() != nil { return false } // Advance cursor, check if we are still within range. if it.pos < len(it.cmd.page) { it.pos++ return true } for { // Return if there is no more data to fetch. if it.cmd.cursor == 0 { return false } // Fetch next page. if it.cmd._args[0] == "scan" { it.cmd._args[1] = it.cmd.cursor } else { it.cmd._args[2] = it.cmd.cursor } err := it.cmd.process(it.cmd) if err != nil { return false } it.pos = 1 // Redis can occasionally return empty page. if len(it.cmd.page) > 0 { return true } } }
[ "func", "(", "it", "*", "ScanIterator", ")", "Next", "(", ")", "bool", "{", "it", ".", "mu", ".", "Lock", "(", ")", "\n", "defer", "it", ".", "mu", ".", "Unlock", "(", ")", "\n\n", "// Instantly return on errors.", "if", "it", ".", "cmd", ".", "Err", "(", ")", "!=", "nil", "{", "return", "false", "\n", "}", "\n\n", "// Advance cursor, check if we are still within range.", "if", "it", ".", "pos", "<", "len", "(", "it", ".", "cmd", ".", "page", ")", "{", "it", ".", "pos", "++", "\n", "return", "true", "\n", "}", "\n\n", "for", "{", "// Return if there is no more data to fetch.", "if", "it", ".", "cmd", ".", "cursor", "==", "0", "{", "return", "false", "\n", "}", "\n\n", "// Fetch next page.", "if", "it", ".", "cmd", ".", "_args", "[", "0", "]", "==", "\"", "\"", "{", "it", ".", "cmd", ".", "_args", "[", "1", "]", "=", "it", ".", "cmd", ".", "cursor", "\n", "}", "else", "{", "it", ".", "cmd", ".", "_args", "[", "2", "]", "=", "it", ".", "cmd", ".", "cursor", "\n", "}", "\n\n", "err", ":=", "it", ".", "cmd", ".", "process", "(", "it", ".", "cmd", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", "\n", "}", "\n\n", "it", ".", "pos", "=", "1", "\n\n", "// Redis can occasionally return empty page.", "if", "len", "(", "it", ".", "cmd", ".", "page", ")", ">", "0", "{", "return", "true", "\n", "}", "\n", "}", "\n", "}" ]
// Next advances the cursor and returns true if more values can be read.
[ "Next", "advances", "the", "cursor", "and", "returns", "true", "if", "more", "values", "can", "be", "read", "." ]
97e6ed817821d91977b51fdec185ca2dbb917fa6
https://github.com/go-redis/redis/blob/97e6ed817821d91977b51fdec185ca2dbb917fa6/iterator.go#L22-L62
164,590
go-redis/redis
sentinel.go
NewFailoverClient
func NewFailoverClient(failoverOpt *FailoverOptions) *Client { opt := failoverOpt.options() opt.init() failover := &sentinelFailover{ masterName: failoverOpt.MasterName, sentinelAddrs: failoverOpt.SentinelAddrs, opt: opt, } c := Client{ baseClient: baseClient{ opt: opt, connPool: failover.Pool(), onClose: failover.Close, }, } c.baseClient.init() c.cmdable.setProcessor(c.Process) return &c }
go
func NewFailoverClient(failoverOpt *FailoverOptions) *Client { opt := failoverOpt.options() opt.init() failover := &sentinelFailover{ masterName: failoverOpt.MasterName, sentinelAddrs: failoverOpt.SentinelAddrs, opt: opt, } c := Client{ baseClient: baseClient{ opt: opt, connPool: failover.Pool(), onClose: failover.Close, }, } c.baseClient.init() c.cmdable.setProcessor(c.Process) return &c }
[ "func", "NewFailoverClient", "(", "failoverOpt", "*", "FailoverOptions", ")", "*", "Client", "{", "opt", ":=", "failoverOpt", ".", "options", "(", ")", "\n", "opt", ".", "init", "(", ")", "\n\n", "failover", ":=", "&", "sentinelFailover", "{", "masterName", ":", "failoverOpt", ".", "MasterName", ",", "sentinelAddrs", ":", "failoverOpt", ".", "SentinelAddrs", ",", "opt", ":", "opt", ",", "}", "\n\n", "c", ":=", "Client", "{", "baseClient", ":", "baseClient", "{", "opt", ":", "opt", ",", "connPool", ":", "failover", ".", "Pool", "(", ")", ",", "onClose", ":", "failover", ".", "Close", ",", "}", ",", "}", "\n", "c", ".", "baseClient", ".", "init", "(", ")", "\n", "c", ".", "cmdable", ".", "setProcessor", "(", "c", ".", "Process", ")", "\n\n", "return", "&", "c", "\n", "}" ]
// NewFailoverClient returns a Redis client that uses Redis Sentinel // for automatic failover. It's safe for concurrent use by multiple // goroutines.
[ "NewFailoverClient", "returns", "a", "Redis", "client", "that", "uses", "Redis", "Sentinel", "for", "automatic", "failover", ".", "It", "s", "safe", "for", "concurrent", "use", "by", "multiple", "goroutines", "." ]
97e6ed817821d91977b51fdec185ca2dbb917fa6
https://github.com/go-redis/redis/blob/97e6ed817821d91977b51fdec185ca2dbb917fa6/sentinel.go#L77-L100
164,591
go-redis/redis
sentinel.go
Failover
func (c *SentinelClient) Failover(name string) *StatusCmd { cmd := NewStatusCmd("sentinel", "failover", name) c.Process(cmd) return cmd }
go
func (c *SentinelClient) Failover(name string) *StatusCmd { cmd := NewStatusCmd("sentinel", "failover", name) c.Process(cmd) return cmd }
[ "func", "(", "c", "*", "SentinelClient", ")", "Failover", "(", "name", "string", ")", "*", "StatusCmd", "{", "cmd", ":=", "NewStatusCmd", "(", "\"", "\"", ",", "\"", "\"", ",", "name", ")", "\n", "c", ".", "Process", "(", "cmd", ")", "\n", "return", "cmd", "\n", "}" ]
// Failover forces a failover as if the master was not reachable, and without // asking for agreement to other Sentinels.
[ "Failover", "forces", "a", "failover", "as", "if", "the", "master", "was", "not", "reachable", "and", "without", "asking", "for", "agreement", "to", "other", "Sentinels", "." ]
97e6ed817821d91977b51fdec185ca2dbb917fa6
https://github.com/go-redis/redis/blob/97e6ed817821d91977b51fdec185ca2dbb917fa6/sentinel.go#L167-L171
164,592
go-redis/redis
sentinel.go
FlushConfig
func (c *SentinelClient) FlushConfig() *StatusCmd { cmd := NewStatusCmd("sentinel", "flushconfig") c.Process(cmd) return cmd }
go
func (c *SentinelClient) FlushConfig() *StatusCmd { cmd := NewStatusCmd("sentinel", "flushconfig") c.Process(cmd) return cmd }
[ "func", "(", "c", "*", "SentinelClient", ")", "FlushConfig", "(", ")", "*", "StatusCmd", "{", "cmd", ":=", "NewStatusCmd", "(", "\"", "\"", ",", "\"", "\"", ")", "\n", "c", ".", "Process", "(", "cmd", ")", "\n", "return", "cmd", "\n", "}" ]
// FlushConfig forces Sentinel to rewrite its configuration on disk, including // the current Sentinel state.
[ "FlushConfig", "forces", "Sentinel", "to", "rewrite", "its", "configuration", "on", "disk", "including", "the", "current", "Sentinel", "state", "." ]
97e6ed817821d91977b51fdec185ca2dbb917fa6
https://github.com/go-redis/redis/blob/97e6ed817821d91977b51fdec185ca2dbb917fa6/sentinel.go#L185-L189
164,593
go-redis/redis
sentinel.go
Master
func (c *SentinelClient) Master(name string) *StringStringMapCmd { cmd := NewStringStringMapCmd("sentinel", "master", name) c.Process(cmd) return cmd }
go
func (c *SentinelClient) Master(name string) *StringStringMapCmd { cmd := NewStringStringMapCmd("sentinel", "master", name) c.Process(cmd) return cmd }
[ "func", "(", "c", "*", "SentinelClient", ")", "Master", "(", "name", "string", ")", "*", "StringStringMapCmd", "{", "cmd", ":=", "NewStringStringMapCmd", "(", "\"", "\"", ",", "\"", "\"", ",", "name", ")", "\n", "c", ".", "Process", "(", "cmd", ")", "\n", "return", "cmd", "\n", "}" ]
// Master shows the state and info of the specified master.
[ "Master", "shows", "the", "state", "and", "info", "of", "the", "specified", "master", "." ]
97e6ed817821d91977b51fdec185ca2dbb917fa6
https://github.com/go-redis/redis/blob/97e6ed817821d91977b51fdec185ca2dbb917fa6/sentinel.go#L192-L196
164,594
go-redis/redis
internal/util/unsafe.go
StringToBytes
func StringToBytes(s string) []byte { return *(*[]byte)(unsafe.Pointer( &struct { string Cap int }{s, len(s)}, )) }
go
func StringToBytes(s string) []byte { return *(*[]byte)(unsafe.Pointer( &struct { string Cap int }{s, len(s)}, )) }
[ "func", "StringToBytes", "(", "s", "string", ")", "[", "]", "byte", "{", "return", "*", "(", "*", "[", "]", "byte", ")", "(", "unsafe", ".", "Pointer", "(", "&", "struct", "{", "string", "\n", "Cap", "int", "\n", "}", "{", "s", ",", "len", "(", "s", ")", "}", ",", ")", ")", "\n", "}" ]
// StringToBytes converts string to byte slice.
[ "StringToBytes", "converts", "string", "to", "byte", "slice", "." ]
97e6ed817821d91977b51fdec185ca2dbb917fa6
https://github.com/go-redis/redis/blob/97e6ed817821d91977b51fdec185ca2dbb917fa6/internal/util/unsafe.go#L15-L22
164,595
go-redis/redis
redis.go
WrapProcess
func (c *baseClient) WrapProcess( fn func(oldProcess func(cmd Cmder) error) func(cmd Cmder) error, ) { c.process = fn(c.process) }
go
func (c *baseClient) WrapProcess( fn func(oldProcess func(cmd Cmder) error) func(cmd Cmder) error, ) { c.process = fn(c.process) }
[ "func", "(", "c", "*", "baseClient", ")", "WrapProcess", "(", "fn", "func", "(", "oldProcess", "func", "(", "cmd", "Cmder", ")", "error", ")", "func", "(", "cmd", "Cmder", ")", "error", ",", ")", "{", "c", ".", "process", "=", "fn", "(", "c", ".", "process", ")", "\n", "}" ]
// WrapProcess wraps function that processes Redis commands.
[ "WrapProcess", "wraps", "function", "that", "processes", "Redis", "commands", "." ]
97e6ed817821d91977b51fdec185ca2dbb917fa6
https://github.com/go-redis/redis/blob/97e6ed817821d91977b51fdec185ca2dbb917fa6/redis.go#L167-L171
164,596
go-redis/redis
redis.go
Close
func (c *baseClient) Close() error { var firstErr error if c.onClose != nil { if err := c.onClose(); err != nil { firstErr = err } } if err := c.connPool.Close(); err != nil && firstErr == nil { firstErr = err } return firstErr }
go
func (c *baseClient) Close() error { var firstErr error if c.onClose != nil { if err := c.onClose(); err != nil { firstErr = err } } if err := c.connPool.Close(); err != nil && firstErr == nil { firstErr = err } return firstErr }
[ "func", "(", "c", "*", "baseClient", ")", "Close", "(", ")", "error", "{", "var", "firstErr", "error", "\n", "if", "c", ".", "onClose", "!=", "nil", "{", "if", "err", ":=", "c", ".", "onClose", "(", ")", ";", "err", "!=", "nil", "{", "firstErr", "=", "err", "\n", "}", "\n", "}", "\n", "if", "err", ":=", "c", ".", "connPool", ".", "Close", "(", ")", ";", "err", "!=", "nil", "&&", "firstErr", "==", "nil", "{", "firstErr", "=", "err", "\n", "}", "\n", "return", "firstErr", "\n", "}" ]
// Close closes the client, releasing any open resources. // // It is rare to Close a Client, as the Client is meant to be // long-lived and shared between many goroutines.
[ "Close", "closes", "the", "client", "releasing", "any", "open", "resources", ".", "It", "is", "rare", "to", "Close", "a", "Client", "as", "the", "Client", "is", "meant", "to", "be", "long", "-", "lived", "and", "shared", "between", "many", "goroutines", "." ]
97e6ed817821d91977b51fdec185ca2dbb917fa6
https://github.com/go-redis/redis/blob/97e6ed817821d91977b51fdec185ca2dbb917fa6/redis.go#L235-L246
164,597
go-redis/redis
redis.go
NewClient
func NewClient(opt *Options) *Client { opt.init() c := Client{ baseClient: baseClient{ opt: opt, connPool: newConnPool(opt), }, } c.baseClient.init() c.init() return &c }
go
func NewClient(opt *Options) *Client { opt.init() c := Client{ baseClient: baseClient{ opt: opt, connPool: newConnPool(opt), }, } c.baseClient.init() c.init() return &c }
[ "func", "NewClient", "(", "opt", "*", "Options", ")", "*", "Client", "{", "opt", ".", "init", "(", ")", "\n\n", "c", ":=", "Client", "{", "baseClient", ":", "baseClient", "{", "opt", ":", "opt", ",", "connPool", ":", "newConnPool", "(", "opt", ")", ",", "}", ",", "}", "\n", "c", ".", "baseClient", ".", "init", "(", ")", "\n", "c", ".", "init", "(", ")", "\n\n", "return", "&", "c", "\n", "}" ]
// NewClient returns a client to the Redis Server specified by Options.
[ "NewClient", "returns", "a", "client", "to", "the", "Redis", "Server", "specified", "by", "Options", "." ]
97e6ed817821d91977b51fdec185ca2dbb917fa6
https://github.com/go-redis/redis/blob/97e6ed817821d91977b51fdec185ca2dbb917fa6/redis.go#L394-L407
164,598
go-redis/redis
internal/pool/pool.go
Get
func (p *ConnPool) Get() (*Conn, error) { if p.closed() { return nil, ErrClosed } err := p.waitTurn() if err != nil { return nil, err } for { p.connsMu.Lock() cn := p.popIdle() p.connsMu.Unlock() if cn == nil { break } if p.isStaleConn(cn) { _ = p.CloseConn(cn) continue } atomic.AddUint32(&p.stats.Hits, 1) return cn, nil } atomic.AddUint32(&p.stats.Misses, 1) newcn, err := p._NewConn(true) if err != nil { p.freeTurn() return nil, err } return newcn, nil }
go
func (p *ConnPool) Get() (*Conn, error) { if p.closed() { return nil, ErrClosed } err := p.waitTurn() if err != nil { return nil, err } for { p.connsMu.Lock() cn := p.popIdle() p.connsMu.Unlock() if cn == nil { break } if p.isStaleConn(cn) { _ = p.CloseConn(cn) continue } atomic.AddUint32(&p.stats.Hits, 1) return cn, nil } atomic.AddUint32(&p.stats.Misses, 1) newcn, err := p._NewConn(true) if err != nil { p.freeTurn() return nil, err } return newcn, nil }
[ "func", "(", "p", "*", "ConnPool", ")", "Get", "(", ")", "(", "*", "Conn", ",", "error", ")", "{", "if", "p", ".", "closed", "(", ")", "{", "return", "nil", ",", "ErrClosed", "\n", "}", "\n\n", "err", ":=", "p", ".", "waitTurn", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "for", "{", "p", ".", "connsMu", ".", "Lock", "(", ")", "\n", "cn", ":=", "p", ".", "popIdle", "(", ")", "\n", "p", ".", "connsMu", ".", "Unlock", "(", ")", "\n\n", "if", "cn", "==", "nil", "{", "break", "\n", "}", "\n\n", "if", "p", ".", "isStaleConn", "(", "cn", ")", "{", "_", "=", "p", ".", "CloseConn", "(", "cn", ")", "\n", "continue", "\n", "}", "\n\n", "atomic", ".", "AddUint32", "(", "&", "p", ".", "stats", ".", "Hits", ",", "1", ")", "\n", "return", "cn", ",", "nil", "\n", "}", "\n\n", "atomic", ".", "AddUint32", "(", "&", "p", ".", "stats", ".", "Misses", ",", "1", ")", "\n\n", "newcn", ",", "err", ":=", "p", ".", "_NewConn", "(", "true", ")", "\n", "if", "err", "!=", "nil", "{", "p", ".", "freeTurn", "(", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "newcn", ",", "nil", "\n", "}" ]
// Get returns existed connection from the pool or creates a new one.
[ "Get", "returns", "existed", "connection", "from", "the", "pool", "or", "creates", "a", "new", "one", "." ]
97e6ed817821d91977b51fdec185ca2dbb917fa6
https://github.com/go-redis/redis/blob/97e6ed817821d91977b51fdec185ca2dbb917fa6/internal/pool/pool.go#L207-L244
164,599
go-redis/redis
internal/pool/pool.go
Len
func (p *ConnPool) Len() int { p.connsMu.Lock() n := len(p.conns) p.connsMu.Unlock() return n }
go
func (p *ConnPool) Len() int { p.connsMu.Lock() n := len(p.conns) p.connsMu.Unlock() return n }
[ "func", "(", "p", "*", "ConnPool", ")", "Len", "(", ")", "int", "{", "p", ".", "connsMu", ".", "Lock", "(", ")", "\n", "n", ":=", "len", "(", "p", ".", "conns", ")", "\n", "p", ".", "connsMu", ".", "Unlock", "(", ")", "\n", "return", "n", "\n", "}" ]
// Len returns total number of connections.
[ "Len", "returns", "total", "number", "of", "connections", "." ]
97e6ed817821d91977b51fdec185ca2dbb917fa6
https://github.com/go-redis/redis/blob/97e6ed817821d91977b51fdec185ca2dbb917fa6/internal/pool/pool.go#L337-L342