repo
stringlengths
5
67
sha
stringlengths
40
40
path
stringlengths
4
234
url
stringlengths
85
339
language
stringclasses
6 values
split
stringclasses
3 values
doc
stringlengths
3
51.2k
sign
stringlengths
5
8.01k
problem
stringlengths
13
51.2k
output
stringlengths
0
3.87M
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
common/cgroup/v1/cgroup.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/common/cgroup/v1/cgroup.go#L149-L155
go
train
// GetOwnCgroupPath returns the cgroup path of this process in controller // hierarchy
func GetOwnCgroupPath(controller string) (string, error)
// GetOwnCgroupPath returns the cgroup path of this process in controller // hierarchy func GetOwnCgroupPath(controller string) (string, error)
{ parts, err := parseCgroupController("/proc/self/cgroup", controller) if err != nil { return "", err } return parts[2], nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
common/cgroup/v1/cgroup.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/common/cgroup/v1/cgroup.go#L159-L165
go
train
// GetCgroupPathByPid returns the cgroup path of the process with the given pid // and given controller.
func GetCgroupPathByPid(pid int, controller string) (string, error)
// GetCgroupPathByPid returns the cgroup path of the process with the given pid // and given controller. func GetCgroupPathByPid(pid int, controller string) (string, error)
{ parts, err := parseCgroupController(fmt.Sprintf("/proc/%d/cgroup", pid), controller) if err != nil { return "", err } return parts[2], nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
common/cgroup/v1/cgroup.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/common/cgroup/v1/cgroup.go#L169-L180
go
train
// JoinSubcgroup makes the calling process join the subcgroup hierarchy on a // particular controller
func JoinSubcgroup(controller string, subcgroup string) error
// JoinSubcgroup makes the calling process join the subcgroup hierarchy on a // particular controller func JoinSubcgroup(controller string, subcgroup string) error
{ subcgroupPath := filepath.Join("/sys/fs/cgroup", controller, subcgroup) if err := os.MkdirAll(subcgroupPath, 0600); err != nil { return errwrap.Wrap(fmt.Errorf("error creating %q subcgroup", subcgroup), err) } pidBytes := []byte(strconv.Itoa(os.Getpid())) if err := ioutil.WriteFile(filepath.Join(subcgroupPath, "cgroup.procs"), pidBytes, 0600); err != nil { return errwrap.Wrap(fmt.Errorf("error adding ourselves to the %q subcgroup", subcgroup), err) } return nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
common/cgroup/v1/cgroup.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/common/cgroup/v1/cgroup.go#L190-L234
go
train
// Ensure that the hierarchy has consistent cpu restrictions. // This may fail; since this is "fixup" code, we should ignore // the error and proceed. // // This was originally a workaround for https://github.com/rkt/rkt/issues/1210 // but is actually useful to have around // // cpuSetPath should be <stage1rootfs>/sys/fs/cgroup/cpuset
func fixCpusetKnobs(cpusetPath, subcgroup, knob string) error
// Ensure that the hierarchy has consistent cpu restrictions. // This may fail; since this is "fixup" code, we should ignore // the error and proceed. // // This was originally a workaround for https://github.com/rkt/rkt/issues/1210 // but is actually useful to have around // // cpuSetPath should be <stage1rootfs>/sys/fs/cgroup/cpuset func fixCpusetKnobs(cpusetPath, subcgroup, knob string) error
{ if err := os.MkdirAll(filepath.Join(cpusetPath, subcgroup), 0755); err != nil { return err } dirs := strings.Split(subcgroup, "/") // Loop over every entry in the hierarchy, putting in the parent's value // unless there is one already there. // Read from the root knob parentFile := filepath.Join(cpusetPath, knob) parentData, err := ioutil.ReadFile(parentFile) if err != nil { return errwrap.Wrapf("error reading cgroup "+parentFile, err) } // Loop over every directory in the subcgroup path currDir := cpusetPath for _, dir := range dirs { currDir = filepath.Join(currDir, dir) childFile := filepath.Join(currDir, knob) childData, err := ioutil.ReadFile(childFile) if err != nil { return errwrap.Wrapf("error reading cgroup "+childFile, err) } // If there is already a value, don't write - and propagate // this value to subsequent children if strings.TrimSpace(string(childData)) != "" { parentData = childData continue } // Workaround: just write twice to workaround the kernel bug fixed by this commit: // https://github.com/torvalds/linux/commit/24ee3cf89bef04e8bc23788aca4e029a3f0f06d9 if err := ioutil.WriteFile(childFile, parentData, 0644); err != nil { return errwrap.Wrapf("error writing cgroup "+childFile, err) } if err := ioutil.WriteFile(childFile, parentData, 0644); err != nil { return errwrap.Wrapf("error writing cgroup "+childFile, err) } } return nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
common/cgroup/v1/cgroup.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/common/cgroup/v1/cgroup.go#L238-L248
go
train
// IsControllerMounted returns whether a controller is mounted by checking that // cgroup.procs is accessible
func IsControllerMounted(c string) (bool, error)
// IsControllerMounted returns whether a controller is mounted by checking that // cgroup.procs is accessible func IsControllerMounted(c string) (bool, error)
{ cgroupProcsPath := filepath.Join("/sys/fs/cgroup", c, "cgroup.procs") if _, err := os.Stat(cgroupProcsPath); err != nil { if !os.IsNotExist(err) { return false, err } return false, nil } return true, nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
common/cgroup/v1/cgroup.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/common/cgroup/v1/cgroup.go#L252-L326
go
train
// CreateCgroups mounts the v1 cgroup controllers hierarchy in /sys/fs/cgroup // under root
func CreateCgroups(m fs.Mounter, root string, enabledCgroups map[int][]string, mountContext string) error
// CreateCgroups mounts the v1 cgroup controllers hierarchy in /sys/fs/cgroup // under root func CreateCgroups(m fs.Mounter, root string, enabledCgroups map[int][]string, mountContext string) error
{ controllers := GetControllerDirs(enabledCgroups) sys := filepath.Join(root, "/sys") if err := os.MkdirAll(sys, 0700); err != nil { return err } var sysfsFlags uintptr = syscall.MS_NOSUID | syscall.MS_NOEXEC | syscall.MS_NODEV // If we're mounting the host cgroups, /sys is probably mounted so we // ignore EBUSY if err := m.Mount("sysfs", sys, "sysfs", sysfsFlags, ""); err != nil && err != syscall.EBUSY { return errwrap.Wrap(fmt.Errorf("error mounting %q", sys), err) } cgroupTmpfs := filepath.Join(root, "/sys/fs/cgroup") if err := os.MkdirAll(cgroupTmpfs, 0700); err != nil { return err } var cgroupTmpfsFlags uintptr = syscall.MS_NOSUID | syscall.MS_NOEXEC | syscall.MS_NODEV | syscall.MS_STRICTATIME options := "mode=755" if mountContext != "" { options = fmt.Sprintf("mode=755,context=\"%s\"", mountContext) } if err := m.Mount("tmpfs", cgroupTmpfs, "tmpfs", cgroupTmpfsFlags, options); err != nil { return errwrap.Wrap(fmt.Errorf("error mounting %q", cgroupTmpfs), err) } // Mount controllers for _, c := range controllers { cPath := filepath.Join(root, "/sys/fs/cgroup", c) if err := os.MkdirAll(cPath, 0700); err != nil { return err } var flags uintptr = syscall.MS_NOSUID | syscall.MS_NOEXEC | syscall.MS_NODEV if err := m.Mount("cgroup", cPath, "cgroup", flags, c); err != nil { return errwrap.Wrap(fmt.Errorf("error mounting %q", cPath), err) } } // Create symlinks for combined controllers symlinks := getControllerSymlinks(enabledCgroups) for ln, tgt := range symlinks { lnPath := filepath.Join(cgroupTmpfs, ln) if err := os.Symlink(tgt, lnPath); err != nil { return errwrap.Wrap(errors.New("error creating symlink"), err) } } systemdControllerPath := filepath.Join(root, "/sys/fs/cgroup/systemd") if err := os.MkdirAll(systemdControllerPath, 0700); err != nil { return err } unifiedPath := filepath.Join(root, "/sys/fs/cgroup/unified") if err := os.MkdirAll(unifiedPath, 0700); err != nil { return err } // Bind-mount cgroup tmpfs filesystem read-only return mountFsRO(m, cgroupTmpfs, cgroupTmpfsFlags) }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
common/cgroup/v1/cgroup.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/common/cgroup/v1/cgroup.go#L335-L375
go
train
// RemountCgroups remounts the v1 cgroup hierarchy under root. // It mounts /sys/fs/cgroup/[controller] read-only, // but leaves needed knobs in the pod's subcgroup read-write, // such that systemd inside stage1 can apply isolators to them. // It leaves /sys read-write if the given readWrite parameter is true. // When this is done, <stage1>/sys/fs/cgroup/<controller> should be RO, and // <stage1>/sys/fs/cgroup/<cotroller>/.../machine-rkt/.../system.slice should be RW
func RemountCgroups(m fs.Mounter, root string, enabledCgroups map[int][]string, subcgroup string, readWrite bool) error
// RemountCgroups remounts the v1 cgroup hierarchy under root. // It mounts /sys/fs/cgroup/[controller] read-only, // but leaves needed knobs in the pod's subcgroup read-write, // such that systemd inside stage1 can apply isolators to them. // It leaves /sys read-write if the given readWrite parameter is true. // When this is done, <stage1>/sys/fs/cgroup/<controller> should be RO, and // <stage1>/sys/fs/cgroup/<cotroller>/.../machine-rkt/.../system.slice should be RW func RemountCgroups(m fs.Mounter, root string, enabledCgroups map[int][]string, subcgroup string, readWrite bool) error
{ controllers := GetControllerDirs(enabledCgroups) cgroupTmpfs := filepath.Join(root, "/sys/fs/cgroup") sysPath := filepath.Join(root, "/sys") var flags uintptr = syscall.MS_NOSUID | syscall.MS_NOEXEC | syscall.MS_NODEV // Mount RW the controllers for this pod for _, c := range controllers { cPath := filepath.Join(cgroupTmpfs, c) subcgroupPath := filepath.Join(cPath, subcgroup, "system.slice") if err := os.MkdirAll(subcgroupPath, 0755); err != nil { return err } if err := m.Mount(subcgroupPath, subcgroupPath, "", syscall.MS_BIND, ""); err != nil { return errwrap.Wrap(fmt.Errorf("error bind mounting %q", subcgroupPath), err) } // Workaround for https://github.com/rkt/rkt/issues/1210 // It is OK to ignore errors here. if c == "cpuset" { _ = fixCpusetKnobs(cPath, subcgroup, "cpuset.mems") _ = fixCpusetKnobs(cPath, subcgroup, "cpuset.cpus") } // Re-mount controller read-only to prevent the container modifying host controllers if err := mountFsRO(m, cPath, flags); err != nil { return err } } if readWrite { // leave sys r/w? return nil } // Bind-mount sys filesystem read-only return mountFsRO(m, sysPath, flags) }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
pkg/fileutil/fileutil_linux.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/fileutil/fileutil_linux.go#L58-L84
go
train
// Returns a nil slice and nil error if the xattr is not set
func Lgetxattr(path string, attr string) ([]byte, error)
// Returns a nil slice and nil error if the xattr is not set func Lgetxattr(path string, attr string) ([]byte, error)
{ pathBytes, err := syscall.BytePtrFromString(path) if err != nil { return nil, err } attrBytes, err := syscall.BytePtrFromString(attr) if err != nil { return nil, err } dest := make([]byte, 128) destBytes := unsafe.Pointer(&dest[0]) sz, _, errno := syscall.Syscall6(syscall.SYS_LGETXATTR, uintptr(unsafe.Pointer(pathBytes)), uintptr(unsafe.Pointer(attrBytes)), uintptr(destBytes), uintptr(len(dest)), 0, 0) if errno == syscall.ENODATA { return nil, nil } if errno == syscall.ERANGE { dest = make([]byte, sz) destBytes := unsafe.Pointer(&dest[0]) sz, _, errno = syscall.Syscall6(syscall.SYS_LGETXATTR, uintptr(unsafe.Pointer(pathBytes)), uintptr(unsafe.Pointer(attrBytes)), uintptr(destBytes), uintptr(len(dest)), 0, 0) } if errno != 0 { return nil, errno } return dest[:sz], nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
pkg/fileutil/fileutil_linux.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/fileutil/fileutil_linux.go#L113-L130
go
train
// GetDeviceInfo returns the type, major, and minor numbers of a device. // Kind is 'b' or 'c' for block and character devices, respectively. // This does not follow symlinks.
func GetDeviceInfo(path string) (kind rune, major uint64, minor uint64, err error)
// GetDeviceInfo returns the type, major, and minor numbers of a device. // Kind is 'b' or 'c' for block and character devices, respectively. // This does not follow symlinks. func GetDeviceInfo(path string) (kind rune, major uint64, minor uint64, err error)
{ d, err := os.Lstat(path) if err != nil { return } mode := d.Mode() if mode&os.ModeDevice == 0 { err = fmt.Errorf("not a device: %s", path) return } stat_t, ok := d.Sys().(*syscall.Stat_t) if !ok { err = fmt.Errorf("cannot determine device number") return } return getDeviceInfo(mode, stat_t.Rdev) }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
pkg/fileutil/fileutil_linux.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/fileutil/fileutil_linux.go#L133-L144
go
train
// Parse the device info out of the mode bits. Separate for testability.
func getDeviceInfo(mode os.FileMode, rdev uint64) (kind rune, major uint64, minor uint64, err error)
// Parse the device info out of the mode bits. Separate for testability. func getDeviceInfo(mode os.FileMode, rdev uint64) (kind rune, major uint64, minor uint64, err error)
{ kind = 'b' if mode&os.ModeCharDevice != 0 { kind = 'c' } major = (rdev >> 8) & 0xfff minor = (rdev & 0xff) | ((rdev >> 12) & 0xfff00) return }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
rkt/cli_apps.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/cli_apps.go#L41-L111
go
train
// parseApps looks through the args for support of per-app argument lists delimited with "--" and "---". // Between per-app argument lists flags.Parse() is called using the supplied FlagSet. // Anything not consumed by flags.Parse() and not found to be a per-app argument list is treated as an image. // allowAppArgs controls whether "--" prefixed per-app arguments will be accepted or not.
func parseApps(al *apps.Apps, args []string, flags *pflag.FlagSet, allowAppArgs bool) error
// parseApps looks through the args for support of per-app argument lists delimited with "--" and "---". // Between per-app argument lists flags.Parse() is called using the supplied FlagSet. // Anything not consumed by flags.Parse() and not found to be a per-app argument list is treated as an image. // allowAppArgs controls whether "--" prefixed per-app arguments will be accepted or not. func parseApps(al *apps.Apps, args []string, flags *pflag.FlagSet, allowAppArgs bool) error
{ nAppsLastAppArgs := al.Count() // valid args here may either be: // not-"--"; flags handled by *flags or an image specifier // "--"; app arguments begin // "---"; conclude app arguments // between "--" and "---" pairs anything is permitted. inAppArgs := false for i := 0; i < len(args); i++ { a := args[i] if len(a) == 0 { continue } if inAppArgs { switch a { case "---": // conclude this app's args inAppArgs = false default: // keep appending to this app's args app := al.Last() app.Args = append(app.Args, a) } } else { switch a { case "--": if !allowAppArgs { return fmt.Errorf("app arguments unsupported") } // begin app's args inAppArgs = true // catch some likely mistakes if nAppsLastAppArgs == al.Count() { if al.Count() == 0 { return fmt.Errorf("an image is required before any app arguments") } return fmt.Errorf("only one set of app arguments allowed per image") } nAppsLastAppArgs = al.Count() case "---": // ignore triple dashes since they aren't images // TODO(vc): I don't think ignoring this is appropriate, probably should error; it implies malformed argv. // "---" is not an image separator, it's an optional argument list terminator. // encountering it outside of inAppArgs is likely to be "--" typoed default: // consume any potential inter-app flags if err := flags.Parse(args[i:]); err != nil { return err } nInterFlags := (len(args[i:]) - flags.NArg()) if nInterFlags > 0 { // XXX(vc): flag.Parse() annoyingly consumes the "--", reclaim it here if necessary if args[i+nInterFlags-1] == "--" { nInterFlags-- } // advance past what flags.Parse() consumed i += nInterFlags - 1 // - 1 because of i++ } else { // flags.Parse() didn't want this arg, treat as image al.Create(a) } } } } return al.Validate() }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
common/cgroup/cgroup.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/common/cgroup/cgroup.go#L37-L56
go
train
// IsIsolatorSupported returns whether an isolator is supported in the kernel
func IsIsolatorSupported(isolator string) (bool, error)
// IsIsolatorSupported returns whether an isolator is supported in the kernel func IsIsolatorSupported(isolator string) (bool, error)
{ isUnified, err := IsCgroupUnified("/") if err != nil { return false, errwrap.Wrap(errors.New("error determining cgroup version"), err) } if isUnified { controllers, err := v2.GetEnabledControllers() if err != nil { return false, errwrap.Wrap(errors.New("error determining enabled controllers"), err) } for _, c := range controllers { if c == isolator { return true, nil } } return false, nil } return v1.IsControllerMounted(isolator) }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
common/cgroup/cgroup.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/common/cgroup/cgroup.go#L60-L68
go
train
// IsCgroupUnified checks if cgroup mounted at /sys/fs/cgroup is // the new unified version (cgroup v2)
func IsCgroupUnified(root string) (bool, error)
// IsCgroupUnified checks if cgroup mounted at /sys/fs/cgroup is // the new unified version (cgroup v2) func IsCgroupUnified(root string) (bool, error)
{ cgroupFsPath := filepath.Join(root, "/sys/fs/cgroup") var statfs syscall.Statfs_t if err := syscall.Statfs(cgroupFsPath, &statfs); err != nil { return false, err } return statfs.Type == Cgroup2fsMagicNumber, nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
pkg/backup/backup.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/backup/backup.go#L35-L55
go
train
// CreateBackup backs a directory up in a given directory. It basically // copies this directory into a given backups directory. The backups // directory has a simple structure - a directory inside named "0" is // the most recent backup. A directory name for oldest backup is // deduced from a given limit. For instance, for limit being 5 the // name for the oldest backup would be "4". If a backups number // exceeds the given limit then only newest ones are kept and the rest // is removed.
func CreateBackup(dir, backupsDir string, limit int) error
// CreateBackup backs a directory up in a given directory. It basically // copies this directory into a given backups directory. The backups // directory has a simple structure - a directory inside named "0" is // the most recent backup. A directory name for oldest backup is // deduced from a given limit. For instance, for limit being 5 the // name for the oldest backup would be "4". If a backups number // exceeds the given limit then only newest ones are kept and the rest // is removed. func CreateBackup(dir, backupsDir string, limit int) error
{ tmpBackupDir := filepath.Join(backupsDir, "tmp") if err := os.MkdirAll(backupsDir, 0750); err != nil { return err } if err := fileutil.CopyTree(dir, tmpBackupDir, user.NewBlankUidRange()); err != nil { return err } defer os.RemoveAll(tmpBackupDir) // prune backups if err := pruneOldBackups(backupsDir, limit-1); err != nil { return err } if err := shiftBackups(backupsDir, limit-2); err != nil { return err } if err := os.Rename(tmpBackupDir, filepath.Join(backupsDir, "0")); err != nil { return err } return nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
pkg/backup/backup.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/backup/backup.go#L59-L80
go
train
// pruneOldBackups removes old backups, that is - directories with // names greater or equal than given limit.
func pruneOldBackups(dir string, limit int) error
// pruneOldBackups removes old backups, that is - directories with // names greater or equal than given limit. func pruneOldBackups(dir string, limit int) error
{ if list, err := ioutil.ReadDir(dir); err != nil { return err } else { for _, fi := range list { if num, err := strconv.Atoi(fi.Name()); err != nil { // directory name is not a number, // leave it alone continue } else if num < limit { // directory name is a number lower // than a limit, leave it alone continue } path := filepath.Join(dir, fi.Name()) if err := os.RemoveAll(path); err != nil { return err } } } return nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
pkg/backup/backup.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/backup/backup.go#L84-L96
go
train
// shiftBackups renames all directories with names being numbers up to // oldest to names with numbers greater by one.
func shiftBackups(dir string, oldest int) error
// shiftBackups renames all directories with names being numbers up to // oldest to names with numbers greater by one. func shiftBackups(dir string, oldest int) error
{ if oldest < 0 { return nil } for i := oldest; i >= 0; i-- { current := filepath.Join(dir, strconv.Itoa(i)) inc := filepath.Join(dir, strconv.Itoa(i+1)) if err := os.Rename(current, inc); err != nil && !os.IsNotExist(err) { return err } } return nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
pkg/aci/aci.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/aci/aci.go#L52-L58
go
train
// NewImageWriter creates a new ArchiveWriter which will generate an App // Container Image based on the given manifest and write it to the given // tar.Writer // TODO(sgotti) this is a copy of appc/spec/aci.imageArchiveWriter with // addFileNow changed to create the file with the current user. needed for // testing as non root user.
func NewImageWriter(am schema.ImageManifest, w *tar.Writer) aci.ArchiveWriter
// NewImageWriter creates a new ArchiveWriter which will generate an App // Container Image based on the given manifest and write it to the given // tar.Writer // TODO(sgotti) this is a copy of appc/spec/aci.imageArchiveWriter with // addFileNow changed to create the file with the current user. needed for // testing as non root user. func NewImageWriter(am schema.ImageManifest, w *tar.Writer) aci.ArchiveWriter
{ aw := &imageArchiveWriter{ w, &am, } return aw }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
pkg/aci/aci.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/aci/aci.go#L109-L122
go
train
// NewBasicACI creates a new ACI in the given directory with the given name. // Used for testing.
func NewBasicACI(dir string, name string) (*os.File, error)
// NewBasicACI creates a new ACI in the given directory with the given name. // Used for testing. func NewBasicACI(dir string, name string) (*os.File, error)
{ manifest := schema.ImageManifest{ ACKind: schema.ImageManifestKind, ACVersion: schema.AppContainerVersion, Name: types.ACIdentifier(name), } b, err := manifest.MarshalJSON() if err != nil { return nil, err } return NewACI(dir, string(b), nil) }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
pkg/aci/aci.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/aci/aci.go#L127-L164
go
train
// NewACI creates a new ACI in the given directory with the given image // manifest and entries. // Used for testing.
func NewACI(dir string, manifest string, entries []*ACIEntry) (*os.File, error)
// NewACI creates a new ACI in the given directory with the given image // manifest and entries. // Used for testing. func NewACI(dir string, manifest string, entries []*ACIEntry) (*os.File, error)
{ var im schema.ImageManifest if err := im.UnmarshalJSON([]byte(manifest)); err != nil { return nil, errwrap.Wrap(errors.New("invalid image manifest"), err) } tf, err := ioutil.TempFile(dir, "") if err != nil { return nil, err } defer os.Remove(tf.Name()) tw := tar.NewWriter(tf) aw := NewImageWriter(im, tw) for _, entry := range entries { // Add default mode if entry.Header.Mode == 0 { if entry.Header.Typeflag == tar.TypeDir { entry.Header.Mode = 0755 } else { entry.Header.Mode = 0644 } } // Add calling user uid and gid or tests will fail entry.Header.Uid = os.Getuid() entry.Header.Gid = os.Getgid() sr := strings.NewReader(entry.Contents) if err := aw.AddFile(entry.Header, sr); err != nil { return nil, err } } if err := aw.Close(); err != nil { return nil, err } return tf, nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
pkg/aci/aci.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/aci/aci.go#L168-L181
go
train
// NewDetachedSignature creates a new openpgp armored detached signature for the given ACI // signed with armoredPrivateKey.
func NewDetachedSignature(armoredPrivateKey string, aci io.Reader) (io.Reader, error)
// NewDetachedSignature creates a new openpgp armored detached signature for the given ACI // signed with armoredPrivateKey. func NewDetachedSignature(armoredPrivateKey string, aci io.Reader) (io.Reader, error)
{ entityList, err := openpgp.ReadArmoredKeyRing(bytes.NewBufferString(armoredPrivateKey)) if err != nil { return nil, err } if len(entityList) < 1 { return nil, errors.New("empty entity list") } signature := &bytes.Buffer{} if err := openpgp.ArmoredDetachSign(signature, entityList[0], aci, nil); err != nil { return nil, err } return signature, nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
pkg/pod/sandbox.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/pod/sandbox.go#L37-L56
go
train
// SandboxManifest loads the underlying pod manifest and checks whether mutable operations are allowed. // It returns ErrImmutable if the pod does not allow mutable operations or any other error if the operation failed. // Upon success a reference to the pod manifest is returned and mutable operations are possible.
func (p *Pod) SandboxManifest() (*schema.PodManifest, error)
// SandboxManifest loads the underlying pod manifest and checks whether mutable operations are allowed. // It returns ErrImmutable if the pod does not allow mutable operations or any other error if the operation failed. // Upon success a reference to the pod manifest is returned and mutable operations are possible. func (p *Pod) SandboxManifest() (*schema.PodManifest, error)
{ _, pm, err := p.PodManifest() // this takes the lock fd to load the manifest, hence path is not needed here if err != nil { return nil, errwrap.Wrap(errors.New("error loading pod manifest"), err) } ms, ok := pm.Annotations.Get("coreos.com/rkt/stage1/mutable") if ok { p.mutable, err = strconv.ParseBool(ms) if err != nil { return nil, errwrap.Wrap(errors.New("error parsing mutable annotation"), err) } } if !p.mutable { return nil, ErrImmutable } return pm, nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
pkg/pod/sandbox.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/pod/sandbox.go#L60-L94
go
train
// UpdateManifest updates the given pod manifest in the given path atomically on the file system. // The pod manifest has to be locked using LockManifest first to avoid races in case of concurrent writes.
func (p *Pod) UpdateManifest(m *schema.PodManifest, path string) error
// UpdateManifest updates the given pod manifest in the given path atomically on the file system. // The pod manifest has to be locked using LockManifest first to avoid races in case of concurrent writes. func (p *Pod) UpdateManifest(m *schema.PodManifest, path string) error
{ if !p.mutable { return ErrImmutable } mpath := common.PodManifestPath(path) mstat, err := os.Stat(mpath) if err != nil { return err } tmpf, err := ioutil.TempFile(path, "") if err != nil { return err } defer func() { tmpf.Close() os.Remove(tmpf.Name()) }() if err := tmpf.Chmod(mstat.Mode().Perm()); err != nil { return err } if err := json.NewEncoder(tmpf).Encode(m); err != nil { return err } if err := os.Rename(tmpf.Name(), mpath); err != nil { return err } return nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
pkg/pod/sandbox.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/pod/sandbox.go#L98-L110
go
train
// ExclusiveLockManifest gets an exclusive lock on only the pod manifest in the app sandbox. // Since the pod might already be running, we can't just get an exclusive lock on the pod itself.
func (p *Pod) ExclusiveLockManifest() error
// ExclusiveLockManifest gets an exclusive lock on only the pod manifest in the app sandbox. // Since the pod might already be running, we can't just get an exclusive lock on the pod itself. func (p *Pod) ExclusiveLockManifest() error
{ if p.manifestLock != nil { return p.manifestLock.ExclusiveLock() // This is idempotent } l, err := lock.ExclusiveLock(common.PodManifestLockPath(p.Path()), lock.RegFile) if err != nil { return err } p.manifestLock = l return nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
pkg/pod/sandbox.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/pod/sandbox.go#L113-L123
go
train
// UnlockManifest unlocks the pod manifest lock.
func (p *Pod) UnlockManifest() error
// UnlockManifest unlocks the pod manifest lock. func (p *Pod) UnlockManifest() error
{ if p.manifestLock == nil { return nil } if err := p.manifestLock.Close(); err != nil { return err } p.manifestLock = nil return nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
store/imagestore/schema.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/store/imagestore/schema.go#L46-L63
go
train
// dbIsPopulated checks if the db is already populated (at any version) verifing if the "version" table exists
func dbIsPopulated(tx *sql.Tx) (bool, error)
// dbIsPopulated checks if the db is already populated (at any version) verifing if the "version" table exists func dbIsPopulated(tx *sql.Tx) (bool, error)
{ rows, err := tx.Query("SELECT Name FROM __Table where Name == $1", "version") if err != nil { return false, err } defer rows.Close() count := 0 for rows.Next() { count++ } if err := rows.Err(); err != nil { return false, err } if count > 0 { return true, nil } return false, nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
store/imagestore/schema.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/store/imagestore/schema.go#L66-L88
go
train
// getDBVersion retrieves the current db version
func getDBVersion(tx *sql.Tx) (int, error)
// getDBVersion retrieves the current db version func getDBVersion(tx *sql.Tx) (int, error)
{ var version int rows, err := tx.Query("SELECT version FROM version") if err != nil { return -1, err } defer rows.Close() found := false for rows.Next() { if err := rows.Scan(&version); err != nil { return -1, err } found = true break } if err := rows.Err(); err != nil { return -1, err } if !found { return -1, fmt.Errorf("db version table empty") } return version, nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
store/imagestore/schema.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/store/imagestore/schema.go#L91-L103
go
train
// updateDBVersion updates the db version
func updateDBVersion(tx *sql.Tx, version int) error
// updateDBVersion updates the db version func updateDBVersion(tx *sql.Tx, version int) error
{ // ql doesn't have an INSERT OR UPDATE function so // it's faster to remove and reinsert the row _, err := tx.Exec("DELETE FROM version") if err != nil { return err } _, err = tx.Exec("INSERT INTO version VALUES ($1)", version) if err != nil { return err } return nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
pkg/acl/acl.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/acl/acl.go#L220-L227
go
train
// InitACL dlopens libacl and returns an ACL object if successful.
func InitACL() (*ACL, error)
// InitACL dlopens libacl and returns an ACL object if successful. func InitACL() (*ACL, error)
{ h, err := getHandle() if err != nil { return nil, err } return &ACL{lib: h}, nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
pkg/acl/acl.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/acl/acl.go#L230-L246
go
train
// ParseACL parses a string representation of an ACL.
func (a *ACL) ParseACL(acl string) error
// ParseACL parses a string representation of an ACL. func (a *ACL) ParseACL(acl string) error
{ acl_from_text, err := getSymbolPointer(a.lib.handle, "acl_from_text") if err != nil { return err } cacl := C.CString(acl) defer C.free(unsafe.Pointer(cacl)) retACL, err := C.my_acl_from_text(acl_from_text, cacl) if retACL == nil { return errwrap.Wrap(errors.New("error calling acl_from_text"), err) } a.a = retACL return nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
pkg/acl/acl.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/acl/acl.go#L249-L261
go
train
// Free frees libacl's internal structures and closes libacl.
func (a *ACL) Free() error
// Free frees libacl's internal structures and closes libacl. func (a *ACL) Free() error
{ acl_free, err := getSymbolPointer(a.lib.handle, "acl_free") if err != nil { return err } ret, err := C.my_acl_free(acl_free, a.a) if ret < 0 { return errwrap.Wrap(errors.New("error calling acl_free"), err) } return a.lib.close() }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
pkg/acl/acl.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/acl/acl.go#L264-L279
go
train
// SetFileACLDefault sets the "default" ACL for path.
func (a *ACL) SetFileACLDefault(path string) error
// SetFileACLDefault sets the "default" ACL for path. func (a *ACL) SetFileACLDefault(path string) error
{ acl_set_file, err := getSymbolPointer(a.lib.handle, "acl_set_file") if err != nil { return err } cpath := C.CString(path) defer C.free(unsafe.Pointer(cpath)) ret, err := C.my_acl_set_file(acl_set_file, cpath, C.ACL_TYPE_DEFAULT, a.a) if ret < 0 { return errwrap.Wrap(errors.New("error calling acl_set_file"), err) } return nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
pkg/acl/acl.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/acl/acl.go#L282-L293
go
train
// Valid checks whether the ACL is valid.
func (a *ACL) Valid() error
// Valid checks whether the ACL is valid. func (a *ACL) Valid() error
{ acl_valid, err := getSymbolPointer(a.lib.handle, "acl_valid") if err != nil { return err } ret, err := C.my_acl_valid(acl_valid, a.a) if ret < 0 { return errwrap.Wrap(errors.New("invalid acl"), err) } return nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
pkg/acl/acl.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/acl/acl.go#L296-L329
go
train
// AddBaseEntries adds the base ACL entries from the file permissions.
func (a *ACL) AddBaseEntries(path string) error
// AddBaseEntries adds the base ACL entries from the file permissions. func (a *ACL) AddBaseEntries(path string) error
{ fi, err := os.Lstat(path) if err != nil { return err } mode := fi.Mode().Perm() var r, w, x bool // set USER_OBJ entry r = mode&userRead == userRead w = mode&userWrite == userWrite x = mode&userExec == userExec if err := a.addBaseEntryFromMode(TagUserObj, r, w, x); err != nil { return err } // set GROUP_OBJ entry r = mode&groupRead == groupRead w = mode&groupWrite == groupWrite x = mode&groupExec == groupExec if err := a.addBaseEntryFromMode(TagGroupObj, r, w, x); err != nil { return err } // set OTHER entry r = mode&otherRead == otherRead w = mode&otherWrite == otherWrite x = mode&otherExec == otherExec if err := a.addBaseEntryFromMode(TagOther, r, w, x); err != nil { return err } return nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
pkg/distribution/appc.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/distribution/appc.go#L52-L71
go
train
// NewAppc returns an Appc distribution from an Appc distribution URI
func NewAppc(u *url.URL) (Distribution, error)
// NewAppc returns an Appc distribution from an Appc distribution URI func NewAppc(u *url.URL) (Distribution, error)
{ c, err := parseCIMD(u) if err != nil { return nil, fmt.Errorf("cannot parse URI: %q: %v", u.String(), err) } if c.Type != TypeAppc { return nil, fmt.Errorf("wrong distribution type: %q", c.Type) } appcStr := c.Data for n, v := range u.Query() { appcStr += fmt.Sprintf(",%s=%s", n, v[0]) } app, err := discovery.NewAppFromString(appcStr) if err != nil { return nil, fmt.Errorf("wrong appc image string %q: %v", u.String(), err) } return NewAppcFromApp(app), nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
pkg/distribution/appc.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/distribution/appc.go#L74-L121
go
train
// NewAppcFromApp returns an Appc distribution from an appc App discovery string
func NewAppcFromApp(app *discovery.App) Distribution
// NewAppcFromApp returns an Appc distribution from an appc App discovery string func NewAppcFromApp(app *discovery.App) Distribution
{ rawuri := NewCIMDString(TypeAppc, distAppcVersion, url.QueryEscape(app.Name.String())) var version string labels := types.Labels{} for n, v := range app.Labels { if n == "version" { version = v } labels = append(labels, types.Label{Name: n, Value: v}) } if len(labels) > 0 { queries := make([]string, len(labels)) rawuri += "?" for i, l := range labels { queries[i] = fmt.Sprintf("%s=%s", l.Name, url.QueryEscape(l.Value)) } rawuri += strings.Join(queries, "&") } u, err := url.Parse(rawuri) if err != nil { panic(fmt.Errorf("cannot parse URI %q: %v", rawuri, err)) } // save the URI as sorted to make it ready for comparison purell.NormalizeURL(u, purell.FlagSortQuery) str := app.Name.String() if version != "" { str += fmt.Sprintf(":%s", version) } labelsort.By(labelsort.RankedName).Sort(labels) for _, l := range labels { if l.Name != "version" { str += fmt.Sprintf(",%s=%s", l.Name, l.Value) } } return &Appc{ cimd: u, app: app.Copy(), str: str, } }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
stage1/init/common/dns_config.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage1/init/common/dns_config.go#L32-L38
go
train
/* Bind-mount the hosts /etc/resolv.conf in to the stage1's /etc/rkt-resolv.conf. That file will then be bind-mounted in to the stage2 by perpare-app.c */
func UseHostResolv(mnt fs.MountUnmounter, podRoot string) error
/* Bind-mount the hosts /etc/resolv.conf in to the stage1's /etc/rkt-resolv.conf. That file will then be bind-mounted in to the stage2 by perpare-app.c */ func UseHostResolv(mnt fs.MountUnmounter, podRoot string) error
{ return BindMount( mnt, "/etc/resolv.conf", filepath.Join(_common.Stage1RootfsPath(podRoot), "etc/rkt-resolv.conf"), true) }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
stage1/init/common/dns_config.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage1/init/common/dns_config.go#L54-L97
go
train
// AddHostsEntry adds an entry to an *existing* hosts file, appending // to the existing IP if needed
func AddHostsEntry(filename string, ip string, hostname string) error
// AddHostsEntry adds an entry to an *existing* hosts file, appending // to the existing IP if needed func AddHostsEntry(filename string, ip string, hostname string) error
{ fp, err := os.OpenFile(filename, os.O_RDWR, 0644) if err != nil { return err } defer fp.Close() out := "" found := false scanner := bufio.NewScanner(fp) for scanner.Scan() { line := scanner.Text() words := strings.Fields(line) if !found && len(words) > 0 && words[0] == ip { found = true out += fmt.Sprintf("%s %s\n", line, hostname) } else { out += line out += "\n" } } if err := scanner.Err(); err != nil { return err } // If that IP was not found, add a new line if !found { out += fmt.Sprintf("%s\t%s\n", ip, hostname) } // Seek to the beginning, truncate, and write again if _, err := fp.Seek(0, 0); err != nil { return err } if err := fp.Truncate(0); err != nil { return err } if _, err := fp.Write([]byte(out)); err != nil { return err } return nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
pkg/sys/sys.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/sys/sys.go#L22-L32
go
train
// CloseOnExec sets or clears FD_CLOEXEC flag on a file descriptor
func CloseOnExec(fd int, set bool) error
// CloseOnExec sets or clears FD_CLOEXEC flag on a file descriptor func CloseOnExec(fd int, set bool) error
{ flag := uintptr(0) if set { flag = syscall.FD_CLOEXEC } _, _, err := syscall.RawSyscall(syscall.SYS_FCNTL, uintptr(fd), syscall.F_SETFD, flag) if err != 0 { return syscall.Errno(err) } return nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
common/cgroup/v2/cgroup.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/common/cgroup/v2/cgroup.go#L30-L45
go
train
// GetEnabledControllers returns a list of enabled cgroup controllers
func GetEnabledControllers() ([]string, error)
// GetEnabledControllers returns a list of enabled cgroup controllers func GetEnabledControllers() ([]string, error)
{ controllersFile, err := os.Open("/sys/fs/cgroup/cgroup.controllers") if err != nil { return nil, err } defer controllersFile.Close() sc := bufio.NewScanner(controllersFile) sc.Scan() if err := sc.Err(); err != nil { return nil, err } return strings.Split(sc.Text(), " "), nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
tools/depsgen/globcmd.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/tools/depsgen/globcmd.go#L76-L103
go
train
// globGetArgs parses given parameters and returns a target, a suffix // and a list of files.
func globGetArgs(args []string) globArgs
// globGetArgs parses given parameters and returns a target, a suffix // and a list of files. func globGetArgs(args []string) globArgs
{ f, target := standardFlags(globCmd) suffix := f.String("suffix", "", "File suffix (example: .go)") globbingMode := f.String("glob-mode", "all", "Which files to glob (normal, dot-files, all [default])") filelist := f.String("filelist", "", "Read all the files from this file") var mapTo []string mapToWrapper := common.StringSliceWrapper{Slice: &mapTo} f.Var(&mapToWrapper, "map-to", "Map contents of filelist to this directory, can be used multiple times") f.Parse(args) if *target == "" { common.Die("--target parameter must be specified and cannot be empty") } mode := globModeFromString(*globbingMode) if *filelist == "" { common.Die("--filelist parameter must be specified and cannot be empty") } if len(mapTo) < 1 { common.Die("--map-to parameter must be specified at least once") } return globArgs{ target: *target, suffix: *suffix, mode: mode, filelist: *filelist, mapTo: mapTo, } }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
tools/depsgen/globcmd.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/tools/depsgen/globcmd.go#L143-L155
go
train
// globGetMakeFunction returns a make snippet which calls wildcard // function in all directories where given files are and with a given // suffix.
func globGetMakeFunction(files []string, suffix string, mode globMode) string
// globGetMakeFunction returns a make snippet which calls wildcard // function in all directories where given files are and with a given // suffix. func globGetMakeFunction(files []string, suffix string, mode globMode) string
{ dirs := map[string]struct{}{} for _, file := range files { dirs[filepath.Dir(file)] = struct{}{} } makeWildcards := make([]string, 0, len(dirs)) wildcard := globGetMakeSnippet(mode) for dir := range dirs { str := replacePlaceholders(wildcard, "SUFFIX", suffix, "DIR", dir) makeWildcards = append(makeWildcards, str) } return replacePlaceholders(globMakeFunction, "WILDCARDS", strings.Join(makeWildcards, " ")) }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
pkg/pod/wait.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/pod/wait.go#L28-L61
go
train
// WaitFinished waits for a pod to finish by polling every 100 milliseconds // or until the given context is cancelled. This method refreshes the pod state. // It is the caller's responsibility to determine the actual terminal state.
func (p *Pod) WaitFinished(ctx context.Context) error
// WaitFinished waits for a pod to finish by polling every 100 milliseconds // or until the given context is cancelled. This method refreshes the pod state. // It is the caller's responsibility to determine the actual terminal state. func (p *Pod) WaitFinished(ctx context.Context) error
{ f := func() bool { switch err := p.TrySharedLock(); err { case nil: // the pod is now locked successfully, hence one of the running phases passed. // continue with unlocking the pod immediately below. case lock.ErrLocked: // pod is still locked, hence we are still in a running phase. // i.e. in pepare, run, exitedGarbage, garbage state. return false default: // some error occurred, bail out. return true } // unlock immediately if err := p.Unlock(); err != nil { return true } if err := p.refreshState(); err != nil { return true } // if we're in the gap between preparing and running in a split prepare/run-prepared usage, take a nap if p.isPrepared { time.Sleep(time.Second) } return p.IsFinished() } return retry(ctx, f, 100*time.Millisecond) }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
pkg/pod/wait.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/pod/wait.go#L65-L75
go
train
// WaitReady blocks until the pod is ready by polling the readiness state every 100 milliseconds // or until the given context is cancelled. This method refreshes the pod state.
func (p *Pod) WaitReady(ctx context.Context) error
// WaitReady blocks until the pod is ready by polling the readiness state every 100 milliseconds // or until the given context is cancelled. This method refreshes the pod state. func (p *Pod) WaitReady(ctx context.Context) error
{ f := func() bool { if err := p.refreshState(); err != nil { return false } return p.IsSupervisorReady() } return retry(ctx, f, 100*time.Millisecond) }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
pkg/pod/wait.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/pod/wait.go#L80-L105
go
train
// retry calls function f indefinitely with the given delay between invocations // until f returns true or the given context is cancelled. // It returns immediately without delay in case function f immediately returns true.
func retry(ctx context.Context, f func() bool, delay time.Duration) error
// retry calls function f indefinitely with the given delay between invocations // until f returns true or the given context is cancelled. // It returns immediately without delay in case function f immediately returns true. func retry(ctx context.Context, f func() bool, delay time.Duration) error
{ if f() { return nil } ticker := time.NewTicker(delay) errChan := make(chan error) go func() { defer close(errChan) for { select { case <-ctx.Done(): errChan <- ctx.Err() return case <-ticker.C: if f() { return } } } }() return <-errChan }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
pkg/fileutil/fileutil.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/fileutil/fileutil.go#L199-L205
go
train
// TODO(sgotti) use UTIMES_OMIT on linux if Time.IsZero ?
func TimeToTimespec(time time.Time) (ts syscall.Timespec)
// TODO(sgotti) use UTIMES_OMIT on linux if Time.IsZero ? func TimeToTimespec(time time.Time) (ts syscall.Timespec)
{ nsec := int64(0) if !time.IsZero() { nsec = time.UnixNano() } return syscall.NsecToTimespec(nsec) }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
pkg/fileutil/fileutil.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/fileutil/fileutil.go#L208-L229
go
train
// DirSize takes a path and returns its size in bytes
func DirSize(path string) (int64, error)
// DirSize takes a path and returns its size in bytes func DirSize(path string) (int64, error)
{ seenInode := make(map[uint64]struct{}) if _, err := os.Stat(path); err == nil { var sz int64 err := filepath.Walk(path, func(path string, info os.FileInfo, err error) error { if hasHardLinks(info) { ino := getInode(info) if _, ok := seenInode[ino]; !ok { seenInode[ino] = struct{}{} sz += info.Size() } } else { sz += info.Size() } return err }) return sz, err } return 0, nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
pkg/fileutil/fileutil.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/fileutil/fileutil.go#L233-L240
go
train
// IsExecutable checks if the given path points to an executable file by // checking the executable bit. Inspired by os.exec.LookPath()
func IsExecutable(path string) bool
// IsExecutable checks if the given path points to an executable file by // checking the executable bit. Inspired by os.exec.LookPath() func IsExecutable(path string) bool
{ d, err := os.Stat(path) if err == nil { m := d.Mode() return !m.IsDir() && m&0111 != 0 } return false }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
pkg/fileutil/fileutil.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/fileutil/fileutil.go#L244-L251
go
train
// IsDeviceNode checks if the given path points to a block or char device. // It doesn't follow symlinks.
func IsDeviceNode(path string) bool
// IsDeviceNode checks if the given path points to a block or char device. // It doesn't follow symlinks. func IsDeviceNode(path string) bool
{ d, err := os.Lstat(path) if err == nil { m := d.Mode() return m&os.ModeDevice == os.ModeDevice } return false }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
stage1/init/kvm/hypervisor/hvlkvm/lkvm_driver.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage1/init/kvm/hypervisor/hvlkvm/lkvm_driver.go#L30-L56
go
train
// StartCmd takes path to stage1, UUID of the pod, path to kernel, network // describers, memory in megabytes and quantity of cpus and prepares command // line to run LKVM process
func StartCmd(wdPath, uuid, kernelPath string, nds []kvm.NetDescriber, cpu, mem int64, debug bool) []string
// StartCmd takes path to stage1, UUID of the pod, path to kernel, network // describers, memory in megabytes and quantity of cpus and prepares command // line to run LKVM process func StartCmd(wdPath, uuid, kernelPath string, nds []kvm.NetDescriber, cpu, mem int64, debug bool) []string
{ machineID := strings.Replace(uuid, "-", "", -1) driverConfiguration := hypervisor.KvmHypervisor{ Bin: "./lkvm", KernelParams: []string{ "systemd.default_standard_error=journal+console", "systemd.default_standard_output=journal+console", "systemd.machine_id=" + machineID, }, } driverConfiguration.InitKernelParams(debug) startCmd := []string{ filepath.Join(wdPath, driverConfiguration.Bin), "run", "--name", "rkt-" + uuid, "--no-dhcp", "--cpu", strconv.Itoa(int(cpu)), "--mem", strconv.Itoa(int(mem)), "--console=virtio", "--kernel", kernelPath, "--disk", "stage1/rootfs", // relative to run/pods/uuid dir this is a place where systemd resides "--params", strings.Join(driverConfiguration.KernelParams, " "), } return append(startCmd, kvmNetArgs(nds)...) }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
stage1/init/kvm/hypervisor/hvlkvm/lkvm_driver.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage1/init/kvm/hypervisor/hvlkvm/lkvm_driver.go#L62-L74
go
train
// kvmNetArgs returns additional arguments that need to be passed // to lkvm tool to configure networks properly. Logic is based on // network configuration extracted from Networking struct // and essentially from activeNets that expose NetDescriber behavior
func kvmNetArgs(nds []kvm.NetDescriber) []string
// kvmNetArgs returns additional arguments that need to be passed // to lkvm tool to configure networks properly. Logic is based on // network configuration extracted from Networking struct // and essentially from activeNets that expose NetDescriber behavior func kvmNetArgs(nds []kvm.NetDescriber) []string
{ var lkvmArgs []string for _, nd := range nds { lkvmArgs = append(lkvmArgs, "--network") lkvmArgs = append( lkvmArgs, fmt.Sprintf("mode=tap,tapif=%s,host_ip=%s,guest_ip=%s", nd.IfName(), nd.Gateway(), nd.GuestIP()), ) } return lkvmArgs }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
pkg/flag/optionlist.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/flag/optionlist.go#L38-L55
go
train
// NewOptionList initializes an OptionList. PermissibleOptions is the complete // set of allowable options. It will set all options specified in defaultOptions // as provided; they will all be cleared if this flag is passed in the CLI
func NewOptionList(permissibleOptions []string, defaultOptions string) (*OptionList, error)
// NewOptionList initializes an OptionList. PermissibleOptions is the complete // set of allowable options. It will set all options specified in defaultOptions // as provided; they will all be cleared if this flag is passed in the CLI func NewOptionList(permissibleOptions []string, defaultOptions string) (*OptionList, error)
{ permissible := make(map[string]struct{}) ol := &OptionList{ allOptions: permissibleOptions, permissible: permissible, typeName: "OptionList", } for _, o := range permissibleOptions { ol.permissible[o] = struct{}{} } if err := ol.Set(defaultOptions); err != nil { return nil, errwrap.Wrap(errors.New("problem setting defaults"), err) } return ol, nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
rkt/image_gc.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/image_gc.go#L82-L111
go
train
// gcTreeStore removes all treeStoreIDs not referenced by any non garbage // collected pod from the store.
func gcTreeStore(ts *treestore.Store) error
// gcTreeStore removes all treeStoreIDs not referenced by any non garbage // collected pod from the store. func gcTreeStore(ts *treestore.Store) error
{ // Take an exclusive lock to block other pods being created. // This is needed to avoid races between the below steps (getting the // list of referenced treeStoreIDs, getting the list of treeStoreIDs // from the store, removal of unreferenced treeStoreIDs) and new // pods/treeStores being created/referenced keyLock, err := lock.ExclusiveKeyLock(lockDir(), common.PrepareLock) if err != nil { return errwrap.Wrap(errors.New("cannot get exclusive prepare lock"), err) } defer keyLock.Close() referencedTreeStoreIDs, err := getReferencedTreeStoreIDs() if err != nil { return errwrap.Wrap(errors.New("cannot get referenced treestoreIDs"), err) } treeStoreIDs, err := ts.GetIDs() if err != nil { return errwrap.Wrap(errors.New("cannot get treestoreIDs from the store"), err) } for _, treeStoreID := range treeStoreIDs { if _, ok := referencedTreeStoreIDs[treeStoreID]; !ok { if err := ts.Remove(treeStoreID); err != nil { stderr.PrintE(fmt.Sprintf("error removing treestore %q", treeStoreID), err) } else { stderr.Printf("removed treestore %q", treeStoreID) } } } return nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
rkt/image_gc.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/image_gc.go#L167-L195
go
train
// getRunningImages will return the image IDs used to create any of the // currently running pods
func getRunningImages() ([]string, error)
// getRunningImages will return the image IDs used to create any of the // currently running pods func getRunningImages() ([]string, error)
{ var runningImages []string var errors []error err := pkgPod.WalkPods(getDataDir(), pkgPod.IncludeMostDirs, func(p *pkgPod.Pod) { var pm schema.PodManifest if p.State() != pkgPod.Running { return } if !p.PodManifestAvailable() { return } _, manifest, err := p.PodManifest() if err != nil { errors = append(errors, newPodListReadError(p, err)) return } pm = *manifest for _, app := range pm.Apps { runningImages = append(runningImages, app.Image.ID.String()) } }) if err != nil { return nil, err } if len(errors) > 0 { return nil, errors[0] } return runningImages, nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
stage0/run.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage0/run.go#L150-L157
go
train
// mergeEnvs merges environment variables from env into the current appEnv // if override is set to true, then variables with the same name will be set to the value in env // env is expected to be in the os.Environ() key=value format
func mergeEnvs(appEnv *types.Environment, env []string, override bool)
// mergeEnvs merges environment variables from env into the current appEnv // if override is set to true, then variables with the same name will be set to the value in env // env is expected to be in the os.Environ() key=value format func mergeEnvs(appEnv *types.Environment, env []string, override bool)
{ for _, ev := range env { pair := strings.SplitN(ev, "=", 2) if _, exists := appEnv.Get(pair[0]); override || !exists { appEnv.Set(pair[0], pair[1]) } } }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
stage0/run.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage0/run.go#L161-L172
go
train
// deduplicateMPs removes Mounts with duplicated paths. If there's more than // one Mount with the same path, it keeps the first one encountered.
func deduplicateMPs(mounts []schema.Mount) []schema.Mount
// deduplicateMPs removes Mounts with duplicated paths. If there's more than // one Mount with the same path, it keeps the first one encountered. func deduplicateMPs(mounts []schema.Mount) []schema.Mount
{ var res []schema.Mount seen := make(map[string]struct{}) for _, m := range mounts { cleanPath := path.Clean(m.Path) if _, ok := seen[cleanPath]; !ok { res = append(res, m) seen[cleanPath] = struct{}{} } } return res }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
stage0/run.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage0/run.go#L175-L178
go
train
// MergeMounts combines the global and per-app mount slices
func MergeMounts(mounts []schema.Mount, appMounts []schema.Mount) []schema.Mount
// MergeMounts combines the global and per-app mount slices func MergeMounts(mounts []schema.Mount, appMounts []schema.Mount) []schema.Mount
{ ml := append(appMounts, mounts...) return deduplicateMPs(ml) }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
stage0/run.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage0/run.go#L183-L278
go
train
// generatePodManifest creates the pod manifest from the command line input. // It returns the pod manifest as []byte on success. // This is invoked if no pod manifest is specified at the command line.
func generatePodManifest(cfg PrepareConfig, dir string) ([]byte, error)
// generatePodManifest creates the pod manifest from the command line input. // It returns the pod manifest as []byte on success. // This is invoked if no pod manifest is specified at the command line. func generatePodManifest(cfg PrepareConfig, dir string) ([]byte, error)
{ pm := schema.PodManifest{ ACKind: "PodManifest", Apps: make(schema.AppList, 0), } v, err := types.NewSemVer(version.Version) if err != nil { return nil, errwrap.Wrap(errors.New("error creating version"), err) } pm.ACVersion = *v if err := cfg.Apps.Walk(func(app *apps.App) error { img := app.ImageID am, err := cfg.Store.GetImageManifest(img.String()) if err != nil { return errwrap.Wrap(errors.New("error getting the manifest"), err) } if app.Name == "" { appName, err := common.ImageNameToAppName(am.Name) if err != nil { return errwrap.Wrap(errors.New("error converting image name to app name"), err) } app.Name = appName.String() } appName, err := types.NewACName(app.Name) if err != nil { return errwrap.Wrap(errors.New("invalid app name format"), err) } if _, err := prepareAppImage(cfg, *appName, img, dir, cfg.UseOverlay); err != nil { return errwrap.Wrap(fmt.Errorf("error preparing image %s", img), err) } if pm.Apps.Get(*appName) != nil { return fmt.Errorf("error: multiple apps with name %s", app.Name) } if am.App == nil && app.Exec == "" { return fmt.Errorf("error: image %s has no app section and --exec argument is not provided", img) } ra, err := generateRuntimeApp(app, am, cfg.Apps.Mounts) if err != nil { return err } // loading the environment from the lowest priority to highest if cfg.InheritEnv { // Inherit environment does not override app image environment mergeEnvs(&ra.App.Environment, os.Environ(), false) } mergeEnvs(&ra.App.Environment, cfg.EnvFromFile, true) mergeEnvs(&ra.App.Environment, cfg.ExplicitEnv, true) pm.Apps = append(pm.Apps, ra) return nil }); err != nil { return nil, err } // TODO(jonboulle): check that app mountpoint expectations are // satisfied here, rather than waiting for stage1 pm.Volumes = cfg.Apps.Volumes // Check to see if ports have any errors pm.Ports = cfg.Ports if _, err := commonnet.ForwardedPorts(&pm); err != nil { return nil, err } pm.Annotations = append(pm.Annotations, types.Annotation{ Name: "coreos.com/rkt/stage1/mutable", Value: strconv.FormatBool(cfg.Mutable), }) pm.UserAnnotations = cfg.UserAnnotations pm.UserLabels = cfg.UserLabels // Add internal annotations for rkt experiments for k, v := range cfg.Annotations { if _, ok := pm.Annotations.Get(k.String()); ok { continue } pm.Annotations.Set(k, v) } pmb, err := json.Marshal(pm) if err != nil { return nil, errwrap.Wrap(errors.New("error marshalling pod manifest"), err) } return pmb, nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
stage0/run.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage0/run.go#L281-L361
go
train
// prepareIsolators merges the CLI app parameters with the manifest's app
func prepareIsolators(setup *apps.App, app *types.App) error
// prepareIsolators merges the CLI app parameters with the manifest's app func prepareIsolators(setup *apps.App, app *types.App) error
{ if memoryOverride := setup.MemoryLimit; memoryOverride != nil { isolator := memoryOverride.AsIsolator() app.Isolators = append(app.Isolators, isolator) } if cpuOverride := setup.CPULimit; cpuOverride != nil { isolator := cpuOverride.AsIsolator() app.Isolators = append(app.Isolators, isolator) } if cpuSharesOverride := setup.CPUShares; cpuSharesOverride != nil { isolator := cpuSharesOverride.AsIsolator() app.Isolators.ReplaceIsolatorsByName(isolator, []types.ACIdentifier{types.LinuxCPUSharesName}) } if oomAdjOverride := setup.OOMScoreAdj; oomAdjOverride != nil { app.Isolators.ReplaceIsolatorsByName(oomAdjOverride.AsIsolator(), []types.ACIdentifier{types.LinuxOOMScoreAdjName}) } if setup.CapsRetain != nil && setup.CapsRemove != nil { return fmt.Errorf("error: cannot use both --caps-retain and --caps-remove on the same image") } // Delete existing caps isolators if the user wants to override // them with either --caps-retain or --caps-remove if setup.CapsRetain != nil || setup.CapsRemove != nil { for i := len(app.Isolators) - 1; i >= 0; i-- { isolator := app.Isolators[i] if _, ok := isolator.Value().(types.LinuxCapabilitiesSet); ok { app.Isolators = append(app.Isolators[:i], app.Isolators[i+1:]...) } } } if capsRetain := setup.CapsRetain; capsRetain != nil { isolator, err := capsRetain.AsIsolator() if err != nil { return err } app.Isolators = append(app.Isolators, *isolator) } else if capsRemove := setup.CapsRemove; capsRemove != nil { isolator, err := capsRemove.AsIsolator() if err != nil { return err } app.Isolators = append(app.Isolators, *isolator) } // Override seccomp isolators via --seccomp CLI switch if setup.SeccompFilter != "" { var is *types.Isolator mode, errno, set, err := setup.SeccompOverride() if err != nil { return err } switch mode { case "retain": lss, err := types.NewLinuxSeccompRetainSet(errno, set...) if err != nil { return err } if is, err = lss.AsIsolator(); err != nil { return err } case "remove": lss, err := types.NewLinuxSeccompRemoveSet(errno, set...) if err != nil { return err } if is, err = lss.AsIsolator(); err != nil { return err } default: return apps.ErrInvalidSeccompMode } app.Isolators.ReplaceIsolatorsByName(*is, []types.ACIdentifier{types.LinuxSeccompRemoveSetName, types.LinuxSeccompRetainSetName}) } return nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
stage0/run.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage0/run.go#L367-L405
go
train
// validatePodManifest reads the user-specified pod manifest, prepares the app images // and validates the pod manifest. If the pod manifest passes validation, it returns // the manifest as []byte. // TODO(yifan): More validation in the future.
func validatePodManifest(cfg PrepareConfig, dir string) ([]byte, error)
// validatePodManifest reads the user-specified pod manifest, prepares the app images // and validates the pod manifest. If the pod manifest passes validation, it returns // the manifest as []byte. // TODO(yifan): More validation in the future. func validatePodManifest(cfg PrepareConfig, dir string) ([]byte, error)
{ pmb, err := ioutil.ReadFile(cfg.PodManifest) if err != nil { return nil, errwrap.Wrap(errors.New("error reading pod manifest"), err) } var pm schema.PodManifest if err := json.Unmarshal(pmb, &pm); err != nil { return nil, errwrap.Wrap(errors.New("error unmarshaling pod manifest"), err) } appNames := make(map[types.ACName]struct{}) for _, ra := range pm.Apps { img := ra.Image if img.ID.Empty() { return nil, fmt.Errorf("no image ID for app %q", ra.Name) } am, err := cfg.Store.GetImageManifest(img.ID.String()) if err != nil { return nil, errwrap.Wrap(errors.New("error getting the image manifest from store"), err) } if _, err := prepareAppImage(cfg, ra.Name, img.ID, dir, cfg.UseOverlay); err != nil { return nil, errwrap.Wrap(fmt.Errorf("error preparing image %s", img), err) } if _, ok := appNames[ra.Name]; ok { return nil, fmt.Errorf("multiple apps with same name %s", ra.Name) } appNames[ra.Name] = struct{}{} if ra.App == nil && am.App == nil { return nil, fmt.Errorf("no app section in the pod manifest or the image manifest") } } // Validate forwarded ports if _, err := commonnet.ForwardedPorts(&pm); err != nil { return nil, err } return pmb, nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
stage0/run.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage0/run.go#L408-L468
go
train
// Prepare sets up a pod based on the given config.
func Prepare(cfg PrepareConfig, dir string, uuid *types.UUID) error
// Prepare sets up a pod based on the given config. func Prepare(cfg PrepareConfig, dir string, uuid *types.UUID) error
{ if err := os.MkdirAll(common.AppsInfoPath(dir), common.DefaultRegularDirPerm); err != nil { return errwrap.Wrap(errors.New("error creating apps info directory"), err) } debug("Preparing stage1") if err := prepareStage1Image(cfg, dir); err != nil { return errwrap.Wrap(errors.New("error preparing stage1"), err) } var pmb []byte var err error if len(cfg.PodManifest) > 0 { pmb, err = validatePodManifest(cfg, dir) } else { pmb, err = generatePodManifest(cfg, dir) } if err != nil { return err } cfg.CommonConfig.ManifestData = string(pmb) // create pod lock file for app add/rm operations. f, err := os.OpenFile(common.PodManifestLockPath(dir), os.O_CREATE|os.O_RDWR, 0600) if err != nil { return err } f.Close() debug("Writing pod manifest") fn := common.PodManifestPath(dir) if err := ioutil.WriteFile(fn, pmb, common.DefaultRegularFilePerm); err != nil { return errwrap.Wrap(errors.New("error writing pod manifest"), err) } f, err = os.OpenFile(common.PodCreatedPath(dir), os.O_CREATE|os.O_RDWR, common.DefaultRegularFilePerm) if err != nil { return err } f.Close() if cfg.UseOverlay { // mark the pod as prepared with overlay f, err := os.Create(filepath.Join(dir, common.OverlayPreparedFilename)) if err != nil { return errwrap.Wrap(errors.New("error writing overlay marker file"), err) } defer f.Close() } if cfg.PrivateUsers.Shift > 0 { // mark the pod as prepared for user namespaces uidrangeBytes := cfg.PrivateUsers.Serialize() if err := ioutil.WriteFile(filepath.Join(dir, common.PrivateUsersPreparedFilename), uidrangeBytes, common.DefaultRegularFilePerm); err != nil { return errwrap.Wrap(errors.New("error writing userns marker file"), err) } } return nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
stage0/run.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage0/run.go#L488-L509
go
train
// writeResolvConf will generate <stage1>/etc/rkt-resolv.conf if needed
func writeResolvConf(cfg *RunConfig, rootfs string)
// writeResolvConf will generate <stage1>/etc/rkt-resolv.conf if needed func writeResolvConf(cfg *RunConfig, rootfs string)
{ if cfg.DNSConfMode.Resolv != "stage0" { return } if err := os.Mkdir(filepath.Join(rootfs, "etc"), common.DefaultRegularDirPerm); err != nil { if !os.IsExist(err) { log.Fatalf("error creating dir %q: %v\n", "/etc", err) } } resolvPath := filepath.Join(rootfs, "etc/rkt-resolv.conf") f, err := os.Create(resolvPath) if err != nil { log.Fatalf("error writing etc/rkt-resolv.conf: %v\n", err) } defer f.Close() _, err = f.WriteString(common.MakeResolvConf(cfg.DNSConfig, "Generated by rkt run")) if err != nil { log.Fatalf("error writing etc/rkt-resolv.conf: %v\n", err) } }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
stage0/run.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage0/run.go#L514-L549
go
train
// writeEtcHosts writes the file /etc/rkt-hosts into the stage1 rootfs. // This will read defaults from <rootfs>/etc/hosts-fallback if it exists. // Therefore, this should be called after the stage1 is mounted
func writeEtcHosts(cfg *RunConfig, rootfs string)
// writeEtcHosts writes the file /etc/rkt-hosts into the stage1 rootfs. // This will read defaults from <rootfs>/etc/hosts-fallback if it exists. // Therefore, this should be called after the stage1 is mounted func writeEtcHosts(cfg *RunConfig, rootfs string)
{ if cfg.DNSConfMode.Hosts != "stage0" { return } // Read <stage1>/rootfs/etc/hosts-fallback to get some sane defaults hostsTextb, err := ioutil.ReadFile(filepath.Join(rootfs, "etc/hosts-fallback")) if err != nil { // fallback-fallback :-) hostsTextb = []byte("#created by rkt stage0\n127.0.0.1 localhost localhost.localdomain\n") } hostsText := string(hostsTextb) hostsText += "\n\n# Added by rkt run --hosts-entry\n" for ip, hostnames := range cfg.HostsEntries { hostsText = fmt.Sprintf("%s%s %s\n", hostsText, ip, strings.Join(hostnames, " ")) } // Create /etc if it does not exist etcPath := filepath.Join(rootfs, "etc") if _, err := os.Stat(etcPath); err != nil && os.IsNotExist(err) { err = os.Mkdir(etcPath, 0755) if err != nil { log.FatalE("failed to make stage1 etc directory", err) } } else if err != nil { log.FatalE("Failed to stat stage1 etc", err) } hostsPath := filepath.Join(etcPath, "rkt-hosts") err = ioutil.WriteFile(hostsPath, []byte(hostsText), 0644) if err != nil { log.FatalE("failed to write etc/rkt-hosts", err) } }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
stage0/run.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage0/run.go#L553-L695
go
train
// Run mounts the right overlay filesystems and actually runs the prepared // pod by exec()ing the stage1 init inside the pod filesystem.
func Run(cfg RunConfig, dir string, dataDir string)
// Run mounts the right overlay filesystems and actually runs the prepared // pod by exec()ing the stage1 init inside the pod filesystem. func Run(cfg RunConfig, dir string, dataDir string)
{ privateUsers, err := preparedWithPrivateUsers(dir) if err != nil { log.FatalE("error preparing private users", err) } debug("Setting up stage1") if err := setupStage1Image(cfg, dir, cfg.UseOverlay); err != nil { log.FatalE("error setting up stage1", err) } debug("Wrote filesystem to %s\n", dir) for _, app := range cfg.Apps { if err := setupAppImage(cfg, app.Name, app.Image.ID, dir, cfg.UseOverlay); err != nil { log.FatalE("error setting up app image", err) } } destRootfs := common.Stage1RootfsPath(dir) writeDnsConfig(&cfg, destRootfs) if err := os.Setenv(common.EnvLockFd, fmt.Sprintf("%v", cfg.LockFd)); err != nil { log.FatalE("setting lock fd environment", err) } if err := os.Setenv(common.EnvSELinuxContext, fmt.Sprintf("%v", cfg.ProcessLabel)); err != nil { log.FatalE("setting SELinux context environment", err) } if err := os.Setenv(common.EnvSELinuxMountContext, fmt.Sprintf("%v", cfg.MountLabel)); err != nil { log.FatalE("setting SELinux mount context environment", err) } debug("Pivoting to filesystem %s", dir) if err := os.Chdir(dir); err != nil { log.FatalE("failed changing to dir", err) } ep, err := getStage1Entrypoint(dir, runEntrypoint) if err != nil { log.FatalE("error determining 'run' entrypoint", err) } args := []string{filepath.Join(destRootfs, ep)} if cfg.Debug { args = append(args, "--debug") } args = append(args, "--net="+cfg.Net.String()) if cfg.Interactive { args = append(args, "--interactive") } if len(privateUsers) > 0 { args = append(args, "--private-users="+privateUsers) } if cfg.MDSRegister { mdsToken, err := registerPod(".", cfg.UUID, cfg.Apps) if err != nil { log.FatalE("failed to register the pod", err) } args = append(args, "--mds-token="+mdsToken) } if cfg.LocalConfig != "" { args = append(args, "--local-config="+cfg.LocalConfig) } s1v, err := getStage1InterfaceVersion(dir) if err != nil { log.FatalE("error determining stage1 interface version", err) } if cfg.Hostname != "" { if interfaceVersionSupportsHostname(s1v) { args = append(args, "--hostname="+cfg.Hostname) } else { log.Printf("warning: --hostname option is not supported by stage1") } } if cfg.DNSConfMode.Hosts != "default" || cfg.DNSConfMode.Resolv != "default" { if interfaceVersionSupportsDNSConfMode(s1v) { args = append(args, fmt.Sprintf("--dns-conf-mode=resolv=%s,hosts=%s", cfg.DNSConfMode.Resolv, cfg.DNSConfMode.Hosts)) } else { log.Printf("warning: --dns-conf-mode option not supported by stage1") } } if interfaceVersionSupportsInsecureOptions(s1v) { if cfg.InsecureCapabilities { args = append(args, "--disable-capabilities-restriction") } if cfg.InsecurePaths { args = append(args, "--disable-paths") } if cfg.InsecureSeccomp { args = append(args, "--disable-seccomp") } } if cfg.Mutable { mutable, err := supportsMutableEnvironment(dir) switch { case err != nil: log.FatalE("error determining stage1 mutable support", err) case !mutable: log.Fatalln("stage1 does not support mutable pods") } args = append(args, "--mutable") } if cfg.IPCMode != "" { if interfaceVersionSupportsIPCMode(s1v) { args = append(args, "--ipc="+cfg.IPCMode) } else { log.Printf("warning: --ipc option is not supported by stage1") } } args = append(args, cfg.UUID.String()) // make sure the lock fd stays open across exec if err := sys.CloseOnExec(cfg.LockFd, false); err != nil { log.Fatalf("error clearing FD_CLOEXEC on lock fd") } tpmEvent := fmt.Sprintf("rkt: Rootfs: %s Manifest: %s Stage1 args: %s", cfg.CommonConfig.RootHash, cfg.CommonConfig.ManifestData, strings.Join(args, " ")) // If there's no TPM available or there's a failure for some other // reason, ignore it and continue anyway. Long term we'll want policy // that enforces TPM behaviour, but we don't have any infrastructure // around that yet. _ = tpm.Extend(tpmEvent) debug("Execing %s", args) if err := syscall.Exec(args[0], args, os.Environ()); err != nil { log.FatalE("error execing init", err) } }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
stage0/run.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage0/run.go#L701-L767
go
train
// prepareAppImage renders and verifies the tree cache of the app image that // corresponds to the given app name. // When useOverlay is false, it attempts to render and expand the app image. // It returns the tree store ID if overlay is being used.
func prepareAppImage(cfg PrepareConfig, appName types.ACName, img types.Hash, cdir string, useOverlay bool) (string, error)
// prepareAppImage renders and verifies the tree cache of the app image that // corresponds to the given app name. // When useOverlay is false, it attempts to render and expand the app image. // It returns the tree store ID if overlay is being used. func prepareAppImage(cfg PrepareConfig, appName types.ACName, img types.Hash, cdir string, useOverlay bool) (string, error)
{ debug("Loading image %s", img.String()) am, err := cfg.Store.GetImageManifest(img.String()) if err != nil { return "", errwrap.Wrap(errors.New("error getting the manifest"), err) } if _, hasOS := am.Labels.Get("os"); !hasOS { return "", fmt.Errorf("missing os label in the image manifest") } if _, hasArch := am.Labels.Get("arch"); !hasArch { return "", fmt.Errorf("missing arch label in the image manifest") } if err := types.IsValidOSArch(am.Labels.ToMap(), ValidOSArch); err != nil { return "", err } appInfoDir := common.AppInfoPath(cdir, appName) if err := os.MkdirAll(appInfoDir, common.DefaultRegularDirPerm); err != nil { return "", errwrap.Wrap(errors.New("error creating apps info directory"), err) } var treeStoreID string if useOverlay { if cfg.PrivateUsers.Shift > 0 { return "", fmt.Errorf("cannot use both overlay and user namespace: not implemented yet. (Try --no-overlay)") } treeStoreID, _, err = cfg.TreeStore.Render(img.String(), false) if err != nil { return "", errwrap.Wrap(errors.New("error rendering tree image"), err) } if err := ioutil.WriteFile(common.AppTreeStoreIDPath(cdir, appName), []byte(treeStoreID), common.DefaultRegularFilePerm); err != nil { return "", errwrap.Wrap(errors.New("error writing app treeStoreID"), err) } } else { ad := common.AppPath(cdir, appName) err := os.MkdirAll(ad, common.DefaultRegularDirPerm) if err != nil { return "", errwrap.Wrap(errors.New("error creating image directory"), err) } shiftedUid, shiftedGid, err := cfg.PrivateUsers.ShiftRange(uint32(os.Getuid()), uint32(os.Getgid())) if err != nil { return "", errwrap.Wrap(errors.New("error getting uid, gid"), err) } if err := os.Chown(ad, int(shiftedUid), int(shiftedGid)); err != nil { return "", errwrap.Wrap(fmt.Errorf("error shifting app %q's stage2 dir", appName), err) } if err := aci.RenderACIWithImageID(img, ad, cfg.Store, cfg.PrivateUsers); err != nil { return "", errwrap.Wrap(errors.New("error rendering ACI"), err) } } if err := writeManifest(*cfg.CommonConfig, img, appInfoDir); err != nil { return "", errwrap.Wrap(errors.New("error writing manifest"), err) } return treeStoreID, nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
stage0/run.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage0/run.go#L773-L792
go
train
// setupAppImage mounts the overlay filesystem for the app image that // corresponds to the given hash if useOverlay is true. // It also creates an mtab file in the application's rootfs if one is not // present.
func setupAppImage(cfg RunConfig, appName types.ACName, img types.Hash, cdir string, useOverlay bool) error
// setupAppImage mounts the overlay filesystem for the app image that // corresponds to the given hash if useOverlay is true. // It also creates an mtab file in the application's rootfs if one is not // present. func setupAppImage(cfg RunConfig, appName types.ACName, img types.Hash, cdir string, useOverlay bool) error
{ ad := common.AppPath(cdir, appName) if useOverlay { err := os.MkdirAll(ad, common.DefaultRegularDirPerm) if err != nil { return errwrap.Wrap(errors.New("error creating image directory"), err) } treeStoreID, err := ioutil.ReadFile(common.AppTreeStoreIDPath(cdir, appName)) if err != nil { return err } if err := copyAppManifest(cdir, appName, ad); err != nil { return err } if err := overlayRender(cfg, string(treeStoreID), cdir, ad, appName.String()); err != nil { return errwrap.Wrap(errors.New("error rendering overlay filesystem"), err) } } return ensureMtabExists(filepath.Join(ad, "rootfs")) }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
stage0/run.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage0/run.go#L798-L825
go
train
// ensureMtabExists creates a symlink from /etc/mtab -> /proc/self/mounts if // nothing exists at /etc/mtab. // Various tools, such as mount from util-linux 2.25, expect the mtab file to // be populated.
func ensureMtabExists(rootfs string) error
// ensureMtabExists creates a symlink from /etc/mtab -> /proc/self/mounts if // nothing exists at /etc/mtab. // Various tools, such as mount from util-linux 2.25, expect the mtab file to // be populated. func ensureMtabExists(rootfs string) error
{ stat, err := os.Stat(filepath.Join(rootfs, "etc")) if os.IsNotExist(err) { // If your image has no /etc you don't get /etc/mtab either return nil } if err != nil { return errwrap.Wrap(errors.New("error determining if /etc existed in the image"), err) } if !stat.IsDir() { return nil } mtabPath := filepath.Join(rootfs, "etc", "mtab") if _, err = os.Lstat(mtabPath); err == nil { // If the image already has an mtab, don't replace it return nil } if !os.IsNotExist(err) { return errwrap.Wrap(errors.New("error determining if /etc/mtab exists in the image"), err) } target := "../proc/self/mounts" err = os.Symlink(target, mtabPath) if err != nil { return errwrap.Wrap(errors.New("error creating mtab symlink"), err) } return nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
stage0/run.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage0/run.go#L830-L858
go
train
// prepareStage1Image renders and verifies tree cache of the given hash // when using overlay. // When useOverlay is false, it attempts to render and expand the stage1.
func prepareStage1Image(cfg PrepareConfig, cdir string) error
// prepareStage1Image renders and verifies tree cache of the given hash // when using overlay. // When useOverlay is false, it attempts to render and expand the stage1. func prepareStage1Image(cfg PrepareConfig, cdir string) error
{ s1 := common.Stage1ImagePath(cdir) if err := os.MkdirAll(s1, common.DefaultRegularDirPerm); err != nil { return errwrap.Wrap(errors.New("error creating stage1 directory"), err) } treeStoreID, _, err := cfg.TreeStore.Render(cfg.Stage1Image.String(), false) if err != nil { return errwrap.Wrap(errors.New("error rendering tree image"), err) } if err := writeManifest(*cfg.CommonConfig, cfg.Stage1Image, s1); err != nil { return errwrap.Wrap(errors.New("error writing manifest"), err) } if !cfg.UseOverlay { destRootfs := filepath.Join(s1, "rootfs") cachedTreePath := cfg.TreeStore.GetRootFS(treeStoreID) if err := fileutil.CopyTree(cachedTreePath, destRootfs, cfg.PrivateUsers); err != nil { return errwrap.Wrap(errors.New("error rendering ACI"), err) } } fn := path.Join(cdir, common.Stage1TreeStoreIDFilename) if err := ioutil.WriteFile(fn, []byte(treeStoreID), common.DefaultRegularFilePerm); err != nil { return errwrap.Wrap(errors.New("error writing stage1 treeStoreID"), err) } return nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
stage0/run.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage0/run.go#L862-L884
go
train
// setupStage1Image mounts the overlay filesystem for stage1. // When useOverlay is false it is a noop
func setupStage1Image(cfg RunConfig, cdir string, useOverlay bool) error
// setupStage1Image mounts the overlay filesystem for stage1. // When useOverlay is false it is a noop func setupStage1Image(cfg RunConfig, cdir string, useOverlay bool) error
{ s1 := common.Stage1ImagePath(cdir) if useOverlay { treeStoreID, err := ioutil.ReadFile(filepath.Join(cdir, common.Stage1TreeStoreIDFilename)) if err != nil { return err } // pass an empty appName if err := overlayRender(cfg, string(treeStoreID), cdir, s1, ""); err != nil { return errwrap.Wrap(errors.New("error rendering overlay filesystem"), err) } // we will later read the status from the upper layer of the overlay fs // force the status directory to be there by touching it statusPath := filepath.Join(s1, "rootfs", "rkt", "status") if err := os.Chtimes(statusPath, time.Now(), time.Now()); err != nil { return errwrap.Wrap(errors.New("error touching status dir"), err) } } return nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
stage0/run.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage0/run.go#L887-L899
go
train
// writeManifest takes an img ID and writes the corresponding manifest in dest
func writeManifest(cfg CommonConfig, img types.Hash, dest string) error
// writeManifest takes an img ID and writes the corresponding manifest in dest func writeManifest(cfg CommonConfig, img types.Hash, dest string) error
{ mb, err := cfg.Store.GetImageManifestJSON(img.String()) if err != nil { return err } debug("Writing image manifest") if err := ioutil.WriteFile(filepath.Join(dest, "manifest"), mb, common.DefaultRegularFilePerm); err != nil { return errwrap.Wrap(errors.New("error writing image manifest"), err) } return nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
stage0/run.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage0/run.go#L903-L911
go
train
// copyAppManifest copies to saved image manifest for the given appName and // writes it in the dest directory.
func copyAppManifest(cdir string, appName types.ACName, dest string) error
// copyAppManifest copies to saved image manifest for the given appName and // writes it in the dest directory. func copyAppManifest(cdir string, appName types.ACName, dest string) error
{ appInfoDir := common.AppInfoPath(cdir, appName) sourceFn := filepath.Join(appInfoDir, "manifest") destFn := filepath.Join(dest, "manifest") if err := fileutil.CopyRegularFile(sourceFn, destFn); err != nil { return errwrap.Wrap(errors.New("error copying image manifest"), err) } return nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
stage0/run.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage0/run.go#L916-L928
go
train
// overlayRender renders the image that corresponds to the given hash using the // overlay filesystem. It mounts an overlay filesystem from the cached tree of // the image as rootfs.
func overlayRender(cfg RunConfig, treeStoreID string, cdir string, dest string, appName string) error
// overlayRender renders the image that corresponds to the given hash using the // overlay filesystem. It mounts an overlay filesystem from the cached tree of // the image as rootfs. func overlayRender(cfg RunConfig, treeStoreID string, cdir string, dest string, appName string) error
{ cachedTreePath := cfg.TreeStore.GetRootFS(treeStoreID) mc, err := prepareOverlay(cachedTreePath, treeStoreID, cdir, dest, appName, cfg.MountLabel, cfg.RktGid, common.DefaultRegularDirPerm) if err != nil { return errwrap.Wrap(errors.New("problem preparing overlay directories"), err) } if err = overlay.Mount(mc); err != nil { return errwrap.Wrap(errors.New("problem mounting overlay filesystem"), err) } return nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
stage0/run.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage0/run.go#L932-L987
go
train
// prepateOverlay sets up the needed directories, files and permissions for the // overlay-rendered pods
func prepareOverlay(lower, treeStoreID, cdir, dest, appName, lbl string, gid int, fm os.FileMode) (*overlay.MountCfg, error)
// prepateOverlay sets up the needed directories, files and permissions for the // overlay-rendered pods func prepareOverlay(lower, treeStoreID, cdir, dest, appName, lbl string, gid int, fm os.FileMode) (*overlay.MountCfg, error)
{ fi, err := os.Stat(lower) if err != nil { return nil, err } imgMode := fi.Mode() dst := path.Join(dest, "rootfs") if err := os.MkdirAll(dst, imgMode); err != nil { return nil, err } overlayDir := path.Join(cdir, "overlay") if err := os.MkdirAll(overlayDir, fm); err != nil { return nil, err } // Since the parent directory (rkt/pods/$STATE/$POD_UUID) has the 'S_ISGID' bit, here // we need to explicitly turn the bit off when creating this overlay // directory so that it won't inherit the bit. Otherwise the files // created by users within the pod will inherit the 'S_ISGID' bit // as well. if err := os.Chmod(overlayDir, fm); err != nil { return nil, err } imgDir := path.Join(overlayDir, treeStoreID) if err := os.MkdirAll(imgDir, fm); err != nil { return nil, err } // Also make 'rkt/pods/$STATE/$POD_UUID/overlay/$IMAGE_ID' to be readable by 'rkt' group // As 'rkt' status will read the 'rkt/pods/$STATE/$POD_UUID/overlay/$IMAGE_ID/upper/rkt/status/$APP' // to get exgid if err := os.Chown(imgDir, -1, gid); err != nil { return nil, err } upper := path.Join(imgDir, "upper", appName) if err := os.MkdirAll(upper, imgMode); err != nil { return nil, err } if err := label.SetFileLabel(upper, lbl); err != nil { return nil, err } work := path.Join(imgDir, "work", appName) if err := os.MkdirAll(work, fm); err != nil { return nil, err } if err := label.SetFileLabel(work, lbl); err != nil { return nil, err } return &overlay.MountCfg{lower, upper, work, dst, lbl}, nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
store/treestore/tree.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/store/treestore/tree.go#L73-L82
go
train
// NewStore creates a Store for managing filesystem trees, including the dependency graph resolution of the underlying image layers.
func NewStore(dir string, store *imagestore.Store) (*Store, error)
// NewStore creates a Store for managing filesystem trees, including the dependency graph resolution of the underlying image layers. func NewStore(dir string, store *imagestore.Store) (*Store, error)
{ // TODO(sgotti) backward compatibility with the current tree store paths. Needs a migration path to better paths. ts := &Store{dir: filepath.Join(dir, "tree"), store: store} ts.lockDir = filepath.Join(dir, "treestorelocks") if err := os.MkdirAll(ts.lockDir, 0755); err != nil { return nil, err } return ts, nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
store/treestore/tree.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/store/treestore/tree.go#L88-L106
go
train
// GetID calculates the treestore ID for the given image key. // The treeStoreID is computed as an hash of the flattened dependency tree // image keys. In this way the ID may change for the same key if the image's // dependencies change.
func (ts *Store) GetID(key string) (string, error)
// GetID calculates the treestore ID for the given image key. // The treeStoreID is computed as an hash of the flattened dependency tree // image keys. In this way the ID may change for the same key if the image's // dependencies change. func (ts *Store) GetID(key string) (string, error)
{ hash, err := types.NewHash(key) if err != nil { return "", err } images, err := acirenderer.CreateDepListFromImageID(*hash, ts.store) if err != nil { return "", err } var keys []string for _, image := range images { keys = append(keys, image.Key) } imagesString := strings.Join(keys, ",") h := sha512.New() h.Write([]byte(imagesString)) return "deps-" + hashToKey(h), nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
store/treestore/tree.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/store/treestore/tree.go#L114-L147
go
train
// Render renders a treestore for the given image key if it's not // already fully rendered. // Users of treestore should call s.Render before using it to ensure // that the treestore is completely rendered. // Returns the id and hash of the rendered treestore if it is newly rendered, // and only the id if it is already rendered.
func (ts *Store) Render(key string, rebuild bool) (id string, hash string, err error)
// Render renders a treestore for the given image key if it's not // already fully rendered. // Users of treestore should call s.Render before using it to ensure // that the treestore is completely rendered. // Returns the id and hash of the rendered treestore if it is newly rendered, // and only the id if it is already rendered. func (ts *Store) Render(key string, rebuild bool) (id string, hash string, err error)
{ id, err = ts.GetID(key) if err != nil { return "", "", errwrap.Wrap(errors.New("cannot calculate treestore id"), err) } // this lock references the treestore dir for the specified id. treeStoreKeyLock, err := lock.ExclusiveKeyLock(ts.lockDir, id) if err != nil { return "", "", errwrap.Wrap(errors.New("error locking tree store"), err) } defer treeStoreKeyLock.Close() if !rebuild { rendered, err := ts.IsRendered(id) if err != nil { return "", "", errwrap.Wrap(errors.New("cannot determine if tree is already rendered"), err) } if rendered { return id, "", nil } } // Firstly remove a possible partial treestore if existing. // This is needed as a previous ACI removal operation could have failed // cleaning the tree store leaving some stale files. if err := ts.remove(id); err != nil { return "", "", err } if hash, err = ts.render(id, key); err != nil { return "", "", err } return id, hash, nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
store/treestore/tree.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/store/treestore/tree.go#L150-L158
go
train
// Check verifies the treestore consistency for the specified id.
func (ts *Store) Check(id string) (string, error)
// Check verifies the treestore consistency for the specified id. func (ts *Store) Check(id string) (string, error)
{ treeStoreKeyLock, err := lock.SharedKeyLock(ts.lockDir, id) if err != nil { return "", errwrap.Wrap(errors.New("error locking tree store"), err) } defer treeStoreKeyLock.Close() return ts.check(id) }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
store/treestore/tree.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/store/treestore/tree.go#L161-L173
go
train
// Remove removes the rendered image in tree store with the given id.
func (ts *Store) Remove(id string) error
// Remove removes the rendered image in tree store with the given id. func (ts *Store) Remove(id string) error
{ treeStoreKeyLock, err := lock.ExclusiveKeyLock(ts.lockDir, id) if err != nil { return errwrap.Wrap(errors.New("error locking tree store"), err) } defer treeStoreKeyLock.Close() if err := ts.remove(id); err != nil { return errwrap.Wrap(errors.New("error removing the tree store"), err) } return nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
store/treestore/tree.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/store/treestore/tree.go#L177-L193
go
train
// GetIDs returns a slice containing all the treeStore's IDs available // (both fully or partially rendered).
func (ts *Store) GetIDs() ([]string, error)
// GetIDs returns a slice containing all the treeStore's IDs available // (both fully or partially rendered). func (ts *Store) GetIDs() ([]string, error)
{ var treeStoreIDs []string ls, err := ioutil.ReadDir(ts.dir) if err != nil { if !os.IsNotExist(err) { return nil, errwrap.Wrap(errors.New("cannot read treestore directory"), err) } } for _, p := range ls { if p.IsDir() { id := filepath.Base(p.Name()) treeStoreIDs = append(treeStoreIDs, id) } } return treeStoreIDs, nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
store/treestore/tree.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/store/treestore/tree.go#L200-L267
go
train
// render renders the ACI with the provided key in the treestore. id references // that specific tree store rendered image. // render, to avoid having a rendered ACI with old stale files, requires that // the destination directory doesn't exist (usually remove should be called // before render)
func (ts *Store) render(id string, key string) (string, error)
// render renders the ACI with the provided key in the treestore. id references // that specific tree store rendered image. // render, to avoid having a rendered ACI with old stale files, requires that // the destination directory doesn't exist (usually remove should be called // before render) func (ts *Store) render(id string, key string) (string, error)
{ treepath := ts.GetPath(id) fi, _ := os.Stat(treepath) if fi != nil { return "", fmt.Errorf("path %s already exists", treepath) } imageID, err := types.NewHash(key) if err != nil { return "", errwrap.Wrap(errors.New("cannot convert key to imageID"), err) } if err := os.MkdirAll(treepath, 0755); err != nil { return "", errwrap.Wrap(fmt.Errorf("cannot create treestore directory %s", treepath), err) } err = aci.RenderACIWithImageID(*imageID, treepath, ts.store, user.NewBlankUidRange()) if err != nil { return "", errwrap.Wrap(errors.New("cannot render aci"), err) } hash, err := ts.Hash(id) if err != nil { return "", errwrap.Wrap(errors.New("cannot calculate tree hash"), err) } err = ioutil.WriteFile(filepath.Join(treepath, hashfilename), []byte(hash), 0644) if err != nil { return "", errwrap.Wrap(errors.New("cannot write hash file"), err) } // before creating the "rendered" flag file we need to ensure that all data is fsynced dfd, err := syscall.Open(treepath, syscall.O_RDONLY, 0) if err != nil { return "", err } defer syscall.Close(dfd) if err := sys.Syncfs(dfd); err != nil { return "", errwrap.Wrap(errors.New("failed to sync data"), err) } // Create rendered file f, err := os.Create(filepath.Join(treepath, renderedfilename)) if err != nil { return "", errwrap.Wrap(errors.New("failed to write rendered file"), err) } f.Close() // Write the hash of the image that will use this tree store err = ioutil.WriteFile(filepath.Join(treepath, imagefilename), []byte(key), 0644) if err != nil { return "", errwrap.Wrap(errors.New("cannot write image file"), err) } if err := syscall.Fsync(dfd); err != nil { return "", errwrap.Wrap(errors.New("failed to sync tree store directory"), err) } // TODO(sgotti) this is wrong for various reasons: // * Doesn't consider that can there can be multiple treestore per ACI // (and fixing this adding/subtracting sizes is bad since cannot be // atomic and could bring to duplicated/missing subtractions causing // wrong sizes) // * ImageStore and TreeStore are decoupled (TreeStore should just use acirenderer.ACIRegistry interface) treeSize, err := ts.Size(id) if err != nil { return "", err } if err := ts.store.UpdateTreeStoreSize(key, treeSize); err != nil { return "", err } return string(hash), nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
store/treestore/tree.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/store/treestore/tree.go#L270-L316
go
train
// remove cleans the directory for the provided id
func (ts *Store) remove(id string) error
// remove cleans the directory for the provided id func (ts *Store) remove(id string) error
{ treepath := ts.GetPath(id) // If tree path doesn't exist we're done _, err := os.Stat(treepath) if err != nil && os.IsNotExist(err) { return nil } if err != nil { return errwrap.Wrap(errors.New("failed to open tree store directory"), err) } renderedFilePath := filepath.Join(treepath, renderedfilename) // The "rendered" flag file should be the firstly removed file. So if // the removal ends with some error leaving some stale files IsRendered() // will return false. _, err = os.Stat(renderedFilePath) if err != nil && !os.IsNotExist(err) { return err } if !os.IsNotExist(err) { err := os.Remove(renderedFilePath) // Ensure that the treepath directory is fsynced after removing the // "rendered" flag file f, err := os.Open(treepath) if err != nil { return errwrap.Wrap(errors.New("failed to open tree store directory"), err) } defer f.Close() err = f.Sync() if err != nil { return errwrap.Wrap(errors.New("failed to sync tree store directory"), err) } } // Ignore error retrieving image hash key, _ := ts.GetImageHash(id) if err := os.RemoveAll(treepath); err != nil { return err } if key != "" { return ts.store.UpdateTreeStoreSize(key, 0) } return nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
store/treestore/tree.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/store/treestore/tree.go#L319-L331
go
train
// IsRendered checks if the tree store with the provided id is fully rendered
func (ts *Store) IsRendered(id string) (bool, error)
// IsRendered checks if the tree store with the provided id is fully rendered func (ts *Store) IsRendered(id string) (bool, error)
{ // if the "rendered" flag file exists, assume that the store is already // fully rendered. treepath := ts.GetPath(id) _, err := os.Stat(filepath.Join(treepath, renderedfilename)) if os.IsNotExist(err) { return false, nil } if err != nil { return false, err } return true, nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
store/treestore/tree.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/store/treestore/tree.go#L336-L338
go
train
// GetPath returns the absolute path of the treestore for the provided id. // It doesn't ensure that the path exists and is fully rendered. This should // be done calling IsRendered()
func (ts *Store) GetPath(id string) string
// GetPath returns the absolute path of the treestore for the provided id. // It doesn't ensure that the path exists and is fully rendered. This should // be done calling IsRendered() func (ts *Store) GetPath(id string) string
{ return filepath.Join(ts.dir, id) }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
store/treestore/tree.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/store/treestore/tree.go#L343-L345
go
train
// GetRootFS returns the absolute path of the rootfs for the provided id. // It doesn't ensure that the rootfs exists and is fully rendered. This should // be done calling IsRendered()
func (ts *Store) GetRootFS(id string) string
// GetRootFS returns the absolute path of the rootfs for the provided id. // It doesn't ensure that the rootfs exists and is fully rendered. This should // be done calling IsRendered() func (ts *Store) GetRootFS(id string) string
{ return filepath.Join(ts.GetPath(id), "rootfs") }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
store/treestore/tree.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/store/treestore/tree.go#L350-L363
go
train
// Hash calculates an hash of the rendered ACI. It uses the same functions // used to create a tar but instead of writing the full archive is just // computes the sha512 sum of the file infos and contents.
func (ts *Store) Hash(id string) (string, error)
// Hash calculates an hash of the rendered ACI. It uses the same functions // used to create a tar but instead of writing the full archive is just // computes the sha512 sum of the file infos and contents. func (ts *Store) Hash(id string) (string, error)
{ treepath := ts.GetPath(id) hash := sha512.New() iw := newHashWriter(hash) err := filepath.Walk(treepath, buildWalker(treepath, iw)) if err != nil { return "", errwrap.Wrap(errors.New("error walking rootfs"), err) } hashstring := hashToKey(hash) return hashstring, nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
store/treestore/tree.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/store/treestore/tree.go#L367-L381
go
train
// check calculates the actual rendered ACI's hash and verifies that it matches // the saved value. Returns the calculated hash.
func (ts *Store) check(id string) (string, error)
// check calculates the actual rendered ACI's hash and verifies that it matches // the saved value. Returns the calculated hash. func (ts *Store) check(id string) (string, error)
{ treepath := ts.GetPath(id) hash, err := ioutil.ReadFile(filepath.Join(treepath, hashfilename)) if err != nil { return "", errwrap.Wrap(ErrReadHashfile, err) } curhash, err := ts.Hash(id) if err != nil { return "", errwrap.Wrap(errors.New("cannot calculate tree hash"), err) } if curhash != string(hash) { return "", fmt.Errorf("wrong tree hash: %s, expected: %s", curhash, hash) } return curhash, nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
store/treestore/tree.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/store/treestore/tree.go#L385-L391
go
train
// Size returns the size of the rootfs for the provided id. It is a relatively // expensive operation, it goes through all the files and adds up their size.
func (ts *Store) Size(id string) (int64, error)
// Size returns the size of the rootfs for the provided id. It is a relatively // expensive operation, it goes through all the files and adds up their size. func (ts *Store) Size(id string) (int64, error)
{ sz, err := fileutil.DirSize(ts.GetPath(id)) if err != nil { return -1, errwrap.Wrap(errors.New("error calculating size"), err) } return sz, nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
store/treestore/tree.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/store/treestore/tree.go#L395-L404
go
train
// GetImageHash returns the hash of the image that uses the tree store // identified by id.
func (ts *Store) GetImageHash(id string) (string, error)
// GetImageHash returns the hash of the image that uses the tree store // identified by id. func (ts *Store) GetImageHash(id string) (string, error)
{ treepath := ts.GetPath(id) imgHash, err := ioutil.ReadFile(filepath.Join(treepath, imagefilename)) if err != nil { return "", errwrap.Wrap(errors.New("cannot read image file"), err) } return string(imgHash), nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
store/treestore/tree.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/store/treestore/tree.go#L460-L526
go
train
// TODO(sgotti) this func is copied from appcs/spec/aci/build.go but also // removes the hash, rendered and image files. Find a way to reuse it.
func buildWalker(root string, aw specaci.ArchiveWriter) filepath.WalkFunc
// TODO(sgotti) this func is copied from appcs/spec/aci/build.go but also // removes the hash, rendered and image files. Find a way to reuse it. func buildWalker(root string, aw specaci.ArchiveWriter) filepath.WalkFunc
{ // cache of inode -> filepath, used to leverage hard links in the archive inos := map[uint64]string{} return func(path string, info os.FileInfo, err error) error { if err != nil { return err } relpath, err := filepath.Rel(root, path) if err != nil { return err } if relpath == "." { return nil } if relpath == specaci.ManifestFile || relpath == hashfilename || relpath == renderedfilename || relpath == imagefilename { // ignore; this will be written by the archive writer // TODO(jonboulle): does this make sense? maybe just remove from archivewriter? return nil } link := "" var r io.Reader switch info.Mode() & os.ModeType { case os.ModeSocket: return nil case os.ModeNamedPipe: case os.ModeCharDevice: case os.ModeDevice: case os.ModeDir: case os.ModeSymlink: target, err := os.Readlink(path) if err != nil { return err } link = target default: file, err := os.Open(path) if err != nil { return err } defer file.Close() r = file } hdr, err := tar.FileInfoHeader(info, link) if err != nil { panic(err) } // Because os.FileInfo's Name method returns only the base // name of the file it describes, it may be necessary to // modify the Name field of the returned header to provide the // full path name of the file. hdr.Name = relpath tarheader.Populate(hdr, info, inos) // If the file is a hard link to a file we've already seen, we // don't need the contents if hdr.Typeflag == tar.TypeLink { hdr.Size = 0 r = nil } return aw.AddFile(hdr, r) } }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
pkg/mountinfo/mountinfo.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/mountinfo/mountinfo.go#L32-L36
go
train
// HasPrefix returns a FilterFunc which returns true if // the mountpoint of a given mount has prefix p, else false.
func HasPrefix(p string) FilterFunc
// HasPrefix returns a FilterFunc which returns true if // the mountpoint of a given mount has prefix p, else false. func HasPrefix(p string) FilterFunc
{ return FilterFunc(func(m *Mount) bool { return strings.HasPrefix(m.MountPoint, p) }) }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
pkg/mountinfo/mountinfo.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/mountinfo/mountinfo.go#L40-L55
go
train
// ParseMounts returns all mountpoints associated with a process mount namespace. // The special value 0 as pid argument is used to specify the current process.
func ParseMounts(pid uint) (Mounts, error)
// ParseMounts returns all mountpoints associated with a process mount namespace. // The special value 0 as pid argument is used to specify the current process. func ParseMounts(pid uint) (Mounts, error)
{ var procPath string if pid == 0 { procPath = "/proc/self/mountinfo" } else { procPath = fmt.Sprintf("/proc/%d/mountinfo", pid) } mi, err := os.Open(procPath) if err != nil { return nil, err } defer mi.Close() return parseMountinfo(mi) }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
pkg/mountinfo/mountinfo.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/mountinfo/mountinfo.go#L59-L141
go
train
// parseMountinfo parses mi (/proc/<pid>/mountinfo) and returns mounts information // according to https://www.kernel.org/doc/Documentation/filesystems/proc.txt
func parseMountinfo(mi io.Reader) (Mounts, error)
// parseMountinfo parses mi (/proc/<pid>/mountinfo) and returns mounts information // according to https://www.kernel.org/doc/Documentation/filesystems/proc.txt func parseMountinfo(mi io.Reader) (Mounts, error)
{ var podMounts Mounts sc := bufio.NewScanner(mi) var ( mountID int parentID int major int minor int root string mountPoint string opt map[string]struct{} ) for sc.Scan() { line := sc.Text() columns := strings.Split(line, " ") if len(columns) < 7 { return nil, fmt.Errorf("Not enough fields from line %q: %+v", line, columns) } opt = map[string]struct{}{} for i, col := range columns { if col == "-" { // separator: a single hyphen "-" marks the end of "optional fields" break } var err error switch i { case 0: mountID, err = strconv.Atoi(col) case 1: parentID, err = strconv.Atoi(col) case 2: split := strings.Split(col, ":") if len(split) != 2 { err = fmt.Errorf("found unexpected key:value field with more than two colons: %s", col) break } major, err = strconv.Atoi(split[0]) if err != nil { break } minor, err = strconv.Atoi(split[1]) if err != nil { break } case 3: root = col case 4: mountPoint = col default: split := strings.Split(col, ":") switch len(split) { case 1: // we ignore modes like rw, relatime, etc. case 2: opt[split[0]] = struct{}{} default: err = fmt.Errorf("found unexpected key:value field with more than two colons: %s", col) } } if err != nil { return nil, errwrap.Wrap(fmt.Errorf("could not parse mountinfo line %q", line), err) } } mnt := &Mount{ ID: mountID, Parent: parentID, Major: major, Minor: minor, Root: root, MountPoint: mountPoint, Opts: opt, } podMounts = append(podMounts, mnt) } if err := sc.Err(); err != nil { return nil, errwrap.Wrap(errors.New("problem parsing mountinfo"), err) } sort.Sort(podMounts) return podMounts, nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
pkg/user/resolver.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/user/resolver.go#L45-L51
go
train
// IDsFromEtc returns a new UID/GID resolver by parsing etc/passwd, and etc/group // relative from the given rootPath looking for the given username, or group. // If username is empty string the etc/passwd lookup will be omitted. // If group is empty string the etc/group lookup will be omitted.
func IDsFromEtc(rootPath, username, group string) (Resolver, error)
// IDsFromEtc returns a new UID/GID resolver by parsing etc/passwd, and etc/group // relative from the given rootPath looking for the given username, or group. // If username is empty string the etc/passwd lookup will be omitted. // If group is empty string the etc/group lookup will be omitted. func IDsFromEtc(rootPath, username, group string) (Resolver, error)
{ return idsFromEtc{ rootPath: rootPath, username: username, group: group, }, nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
pkg/user/resolver.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/user/resolver.go#L85-L91
go
train
// IDsFromStat returns a new UID/GID resolver deriving the UID/GID from file attributes // and unshifts the UID/GID if the given range is not nil. // If the given id does not start with a slash "/" an error is returned.
func IDsFromStat(rootPath, file string, r *UidRange) (Resolver, error)
// IDsFromStat returns a new UID/GID resolver deriving the UID/GID from file attributes // and unshifts the UID/GID if the given range is not nil. // If the given id does not start with a slash "/" an error is returned. func IDsFromStat(rootPath, file string, r *UidRange) (Resolver, error)
{ if strings.HasPrefix(file, "/") { return idsFromStat{filepath.Join(rootPath, file), r}, nil } return nil, fmt.Errorf("invalid filename %q", file) }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
pkg/user/resolver.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/user/resolver.go#L129-L139
go
train
// NumericIDs returns a resolver that will resolve constant UID/GID values. // If the given id equals to "root" the resolver always resolves UID=0 and GID=0. // If the given id is a numeric literal i it always resolves UID=i and GID=i. // If the given id is neither "root" nor a numeric literal an error is returned.
func NumericIDs(id string) (Resolver, error)
// NumericIDs returns a resolver that will resolve constant UID/GID values. // If the given id equals to "root" the resolver always resolves UID=0 and GID=0. // If the given id is a numeric literal i it always resolves UID=i and GID=i. // If the given id is neither "root" nor a numeric literal an error is returned. func NumericIDs(id string) (Resolver, error)
{ if id == "root" { return numericIDs{0}, nil } if i, err := strconv.Atoi(id); err == nil { return numericIDs{i}, nil } return nil, fmt.Errorf("invalid id %q", id) }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
stage1/init/kvm/resources.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage1/init/kvm/resources.go#L42-L54
go
train
// findResources finds value of last isolator for particular type.
func findResources(isolators types.Isolators) (mem, cpus int64)
// findResources finds value of last isolator for particular type. func findResources(isolators types.Isolators) (mem, cpus int64)
{ for _, i := range isolators { switch v := i.Value().(type) { case *types.ResourceMemory: mem = v.Limit().Value() // Convert bytes into megabytes mem /= 1024 * 1024 case *types.ResourceCPU: cpus = v.Limit().Value() } } return mem, cpus }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
stage1/init/kvm/resources.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage1/init/kvm/resources.go#L59-L86
go
train
// GetAppsResources returns values specified by user in pod-manifest. // Function expects a podmanifest apps. // Return aggregate quantity of mem (in MB) and cpus.
func GetAppsResources(apps schema.AppList) (totalCpus, totalMem int64)
// GetAppsResources returns values specified by user in pod-manifest. // Function expects a podmanifest apps. // Return aggregate quantity of mem (in MB) and cpus. func GetAppsResources(apps schema.AppList) (totalCpus, totalMem int64)
{ cpusSpecified := false for i := range apps { ra := &apps[i] app := ra.App mem, cpus := findResources(app.Isolators) cpusSpecified = cpusSpecified || cpus != 0 totalCpus += cpus totalMem += mem } // In case when number of specified cpus is greater than // number or when cpus aren't specified, we set number // of logical cpus as a limit. availableCpus := int64(runtime.NumCPU()) if !cpusSpecified || totalCpus > availableCpus { totalCpus = availableCpus } // Add an overhead for the VM system totalMem += systemMemOverhead // Always ensure we have at least the minimum RAM needed if totalMem < minMem { totalMem = minMem } return totalCpus, totalMem }
go-playground/validator
e25e66164b537d7b3161dfede38466880534e783
struct_level.go
https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/struct_level.go#L16-L20
go
train
// wrapStructLevelFunc wraps normal StructLevelFunc makes it compatible with StructLevelFuncCtx
func wrapStructLevelFunc(fn StructLevelFunc) StructLevelFuncCtx
// wrapStructLevelFunc wraps normal StructLevelFunc makes it compatible with StructLevelFuncCtx func wrapStructLevelFunc(fn StructLevelFunc) StructLevelFuncCtx
{ return func(ctx context.Context, sl StructLevel) { fn(sl) } }
go-playground/validator
e25e66164b537d7b3161dfede38466880534e783
struct_level.go
https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/struct_level.go#L104-L106
go
train
// ExtractType gets the actual underlying type of field value.
func (v *validate) ExtractType(field reflect.Value) (reflect.Value, reflect.Kind, bool)
// ExtractType gets the actual underlying type of field value. func (v *validate) ExtractType(field reflect.Value) (reflect.Value, reflect.Kind, bool)
{ return v.extractTypeInternal(field, false) }
go-playground/validator
e25e66164b537d7b3161dfede38466880534e783
struct_level.go
https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/struct_level.go#L109-L158
go
train
// ReportError reports an error just by passing the field and tag information
func (v *validate) ReportError(field interface{}, fieldName, structFieldName, tag, param string)
// ReportError reports an error just by passing the field and tag information func (v *validate) ReportError(field interface{}, fieldName, structFieldName, tag, param string)
{ fv, kind, _ := v.extractTypeInternal(reflect.ValueOf(field), false) if len(structFieldName) == 0 { structFieldName = fieldName } v.str1 = string(append(v.ns, fieldName...)) if v.v.hasTagNameFunc || fieldName != structFieldName { v.str2 = string(append(v.actualNs, structFieldName...)) } else { v.str2 = v.str1 } if kind == reflect.Invalid { v.errs = append(v.errs, &fieldError{ v: v.v, tag: tag, actualTag: tag, ns: v.str1, structNs: v.str2, fieldLen: uint8(len(fieldName)), structfieldLen: uint8(len(structFieldName)), param: param, kind: kind, }, ) return } v.errs = append(v.errs, &fieldError{ v: v.v, tag: tag, actualTag: tag, ns: v.str1, structNs: v.str2, fieldLen: uint8(len(fieldName)), structfieldLen: uint8(len(structFieldName)), value: fv.Interface(), param: param, kind: kind, typ: fv.Type(), }, ) }
go-playground/validator
e25e66164b537d7b3161dfede38466880534e783
struct_level.go
https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/struct_level.go#L163-L175
go
train
// ReportValidationErrors reports ValidationErrors obtained from running validations within the Struct Level validation. // // NOTE: this function prepends the current namespace to the relative ones.
func (v *validate) ReportValidationErrors(relativeNamespace, relativeStructNamespace string, errs ValidationErrors)
// ReportValidationErrors reports ValidationErrors obtained from running validations within the Struct Level validation. // // NOTE: this function prepends the current namespace to the relative ones. func (v *validate) ReportValidationErrors(relativeNamespace, relativeStructNamespace string, errs ValidationErrors)
{ var err *fieldError for i := 0; i < len(errs); i++ { err = errs[i].(*fieldError) err.ns = string(append(append(v.ns, relativeNamespace...), err.ns...)) err.structNs = string(append(append(v.actualNs, relativeStructNamespace...), err.structNs...)) v.errs = append(v.errs, err) } }