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
tools/depsgen/main.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/tools/depsgen/main.go#L47-L54
go
train
// getAllDepTypes returns a sorted list of names of all dep type // commands.
func getAllDepTypes() []string
// getAllDepTypes returns a sorted list of names of all dep type // commands. func getAllDepTypes() []string
{ depTypes := make([]string, 0, len(cmds)) for depType := range cmds { depTypes = append(depTypes, depType) } sort.Strings(depTypes) return depTypes }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
rkt/image/io.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/image/io.go#L60-L87
go
train
// getIoProgressReader returns a reader that wraps the HTTP response // body, so it prints a pretty progress bar when reading data from it.
func getIoProgressReader(label string, res *http.Response) io.Reader
// getIoProgressReader returns a reader that wraps the HTTP response // body, so it prints a pretty progress bar when reading data from it. func getIoProgressReader(label string, res *http.Response) io.Reader
{ prefix := "Downloading " + label fmtBytesSize := 18 barSize := int64(80 - len(prefix) - fmtBytesSize) bar := ioprogress.DrawTextFormatBarForW(barSize, os.Stderr) fmtfunc := func(progress, total int64) string { // Content-Length is set to -1 when unknown. if total == -1 { return fmt.Sprintf( "%s: %v of an unknown total size", prefix, ioprogress.ByteUnitStr(progress), ) } return fmt.Sprintf( "%s: %s %s", prefix, bar(progress, total), ioprogress.DrawTextFormatBytes(progress, total), ) } return &ioprogress.Reader{ Reader: res.Body, Size: res.ContentLength, DrawFunc: ioprogress.DrawTerminalf(os.Stderr, fmtfunc), DrawInterval: time.Second, } }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
rkt/image/io.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/image/io.go#L107-L119
go
train
// Close closes the file and then removes it from disk. No error is // returned if the file did not exist at the point of removal.
func (f *removeOnClose) Close() error
// Close closes the file and then removes it from disk. No error is // returned if the file did not exist at the point of removal. func (f *removeOnClose) Close() error
{ if f == nil || f.File == nil { return nil } name := f.File.Name() if err := f.File.Close(); err != nil { return err } if err := os.Remove(name); err != nil && !os.IsNotExist(err) { return err } return nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
rkt/image/io.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/image/io.go#L124-L149
go
train
// getTmpROC returns a removeOnClose instance wrapping a temporary // file provided by the passed store. The actual file name is based on // a hash of the passed path.
func getTmpROC(s *imagestore.Store, path string) (*removeOnClose, error)
// getTmpROC returns a removeOnClose instance wrapping a temporary // file provided by the passed store. The actual file name is based on // a hash of the passed path. func getTmpROC(s *imagestore.Store, path string) (*removeOnClose, error)
{ h := sha512.New() h.Write([]byte(path)) pathHash := s.HashToKey(h) tmp, err := s.TmpNamedFile(pathHash) if err != nil { return nil, errwrap.Wrap(errors.New("error setting up temporary file"), err) } // let's lock the file to avoid concurrent writes to the temporary file, it // will go away when removing the temp file _, err = lock.TryExclusiveLock(tmp.Name(), lock.RegFile) if err != nil { if err != lock.ErrLocked { return nil, errwrap.Wrap(errors.New("failed to lock temporary file"), err) } log.Printf("another rkt instance is downloading this file, waiting...") _, err = lock.ExclusiveLock(tmp.Name(), lock.RegFile) if err != nil { return nil, errwrap.Wrap(errors.New("failed to lock temporary file"), err) } } return &removeOnClose{File: tmp}, nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
stage0/manifest.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage0/manifest.go#L50-L66
go
train
// supportsMutableEnvironment returns whether the given stage1 image supports mutable pod operations. // It introspects the stage1 manifest and checks the presence of app* entrypoints.
func supportsMutableEnvironment(cdir string) (bool, error)
// supportsMutableEnvironment returns whether the given stage1 image supports mutable pod operations. // It introspects the stage1 manifest and checks the presence of app* entrypoints. func supportsMutableEnvironment(cdir string) (bool, error)
{ b, err := ioutil.ReadFile(common.Stage1ManifestPath(cdir)) if err != nil { return false, errwrap.Wrap(errors.New("error reading pod manifest"), err) } s1m := schema.ImageManifest{} if err := json.Unmarshal(b, &s1m); err != nil { return false, errwrap.Wrap(errors.New("error unmarshaling stage1 manifest"), err) } _, appRmOk := s1m.Annotations.Get(appRmEntrypoint) _, appStartOk := s1m.Annotations.Get(appStartEntrypoint) _, appStopOk := s1m.Annotations.Get(appStopEntrypoint) return appRmOk && appStartOk && appStopOk, nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
stage0/manifest.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage0/manifest.go#L69-L85
go
train
// getStage1Entrypoint retrieves the named entrypoint from the stage1 manifest for a given pod
func getStage1Entrypoint(cdir string, entrypoint string) (string, error)
// getStage1Entrypoint retrieves the named entrypoint from the stage1 manifest for a given pod func getStage1Entrypoint(cdir string, entrypoint string) (string, error)
{ b, err := ioutil.ReadFile(common.Stage1ManifestPath(cdir)) if err != nil { return "", errwrap.Wrap(errors.New("error reading pod manifest"), err) } s1m := schema.ImageManifest{} if err := json.Unmarshal(b, &s1m); err != nil { return "", errwrap.Wrap(errors.New("error unmarshaling stage1 manifest"), err) } if ep, ok := s1m.Annotations.Get(entrypoint); ok { return ep, nil } return "", fmt.Errorf("entrypoint %q not found", entrypoint) }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
stage0/manifest.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage0/manifest.go#L89-L110
go
train
// getStage1InterfaceVersion retrieves the interface version from the stage1 // manifest for a given pod
func getStage1InterfaceVersion(cdir string) (int, error)
// getStage1InterfaceVersion retrieves the interface version from the stage1 // manifest for a given pod func getStage1InterfaceVersion(cdir string) (int, error)
{ b, err := ioutil.ReadFile(common.Stage1ManifestPath(cdir)) if err != nil { return -1, errwrap.Wrap(errors.New("error reading pod manifest"), err) } s1m := schema.ImageManifest{} if err := json.Unmarshal(b, &s1m); err != nil { return -1, errwrap.Wrap(errors.New("error unmarshaling stage1 manifest"), err) } if iv, ok := s1m.Annotations.Get(interfaceVersion); ok { v, err := strconv.Atoi(iv) if err != nil { return -1, errwrap.Wrap(errors.New("error parsing interface version"), err) } return v, nil } // "interface-version" annotation not found, assume version 1 return 1, nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
networking/podenv.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/networking/podenv.go#L75-L102
go
train
// Loads nets specified by user, both from a configurable user location and builtin from stage1. User supplied network // configs override what is built into stage1. // The order in which networks are applied to pods will be defined by their filenames.
func (e *podEnv) loadNets() ([]activeNet, error)
// Loads nets specified by user, both from a configurable user location and builtin from stage1. User supplied network // configs override what is built into stage1. // The order in which networks are applied to pods will be defined by their filenames. func (e *podEnv) loadNets() ([]activeNet, error)
{ if e.netsLoadList.None() { stderr.Printf("networking namespace with loopback only") return nil, nil } nets, err := e.newNetLoader().loadNets(e.netsLoadList) if err != nil { return nil, err } netSlice := make([]activeNet, 0, len(nets)) for _, net := range nets { netSlice = append(netSlice, net) } sort.Sort(byFilename(netSlice)) missing := missingNets(e.netsLoadList, netSlice) if len(missing) > 0 { return nil, fmt.Errorf("networks not found: %v", strings.Join(missing, ", ")) } // Add the runtime args to the network instances. // We don't do this earlier because we also load networks in other contexts for _, n := range nets { n.runtime.Args = e.netsLoadList.SpecificArgs(n.conf.Name) } return netSlice, nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
networking/podenv.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/networking/podenv.go#L109-L135
go
train
// Ensure the netns directory is mounted before adding new netns like `ip netns add <netns>` command does. // See https://github.com/kubernetes/kubernetes/issues/48427 // Make it possible for network namespace mounts to propagate between mount namespaces. // This makes it likely that an unmounting a network namespace file in one namespace will unmount the network namespace. // file in all namespaces allowing the network namespace to be freed sooner.
func (e *podEnv) mountNetnsDirectory() error
// Ensure the netns directory is mounted before adding new netns like `ip netns add <netns>` command does. // See https://github.com/kubernetes/kubernetes/issues/48427 // Make it possible for network namespace mounts to propagate between mount namespaces. // This makes it likely that an unmounting a network namespace file in one namespace will unmount the network namespace. // file in all namespaces allowing the network namespace to be freed sooner. func (e *podEnv) mountNetnsDirectory() error
{ err := os.MkdirAll(mountNetnsDirectory, 0755) if err != nil { return err } err = syscall.Mount("", mountNetnsDirectory, "none", syscall.MS_SHARED|syscall.MS_REC, "") if err != nil { // Fail unless we need to make the mount point if err != syscall.EINVAL { return fmt.Errorf("mount --make-rshared %s failed: %q", mountNetnsDirectory, err) } // Upgrade mountTarget to a mount point err = syscall.Mount(mountNetnsDirectory, mountNetnsDirectory, "none", syscall.MS_BIND|syscall.MS_REC, "") if err != nil { return fmt.Errorf("mount --rbind %s %s failed: %q", mountNetnsDirectory, mountNetnsDirectory, err) } // Remount after the Upgrade err = syscall.Mount("", mountNetnsDirectory, "none", syscall.MS_SHARED|syscall.MS_REC, "") if err != nil { return fmt.Errorf("mount --make-rshared %s failed: %q", mountNetnsDirectory, err) } } return nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
networking/podenv.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/networking/podenv.go#L140-L151
go
train
// podNSCreate creates the network namespace and saves a reference to its path. // NewNS will bind-mount the namespace in /run/netns, so we write that filename // to disk.
func (e *podEnv) podNSCreate() error
// podNSCreate creates the network namespace and saves a reference to its path. // NewNS will bind-mount the namespace in /run/netns, so we write that filename // to disk. func (e *podEnv) podNSCreate() error
{ podNS, err := ns.NewNS() if err != nil { return err } e.podNS = podNS if err := e.podNSPathSave(); err != nil { return err } return nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
networking/podenv.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/networking/podenv.go#L331-L338
go
train
// Build a Loader that looks first for custom (user provided) plugins, then builtin.
func (e *podEnv) newNetLoader() *netLoader
// Build a Loader that looks first for custom (user provided) plugins, then builtin. func (e *podEnv) newNetLoader() *netLoader
{ return &netLoader{ parent: &netLoader{ configPath: path.Join(common.Stage1RootfsPath(e.podRoot), BuiltinNetPath), }, configPath: filepath.Join(e.localConfig, UserNetPathSuffix), } }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
rkt/run.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/run.go#L597-L684
go
train
/* * Parse out the --hosts-entries, --dns, --dns-search, and --dns-opt flags * This includes decoding the "magic" values for hosts-entries and dns. * Try to detect any obvious insanity, namely invalid IPs or more than one * magic option */
func parseDNSFlags(flagHostsEntries, flagDNS, flagDNSSearch, flagDNSOpt []string, flagDNSDomain string) (stage0.DNSConfMode, cnitypes.DNS, *stage0.HostsEntries, error)
/* * Parse out the --hosts-entries, --dns, --dns-search, and --dns-opt flags * This includes decoding the "magic" values for hosts-entries and dns. * Try to detect any obvious insanity, namely invalid IPs or more than one * magic option */ func parseDNSFlags(flagHostsEntries, flagDNS, flagDNSSearch, flagDNSOpt []string, flagDNSDomain string) (stage0.DNSConfMode, cnitypes.DNS, *stage0.HostsEntries, error)
{ DNSConfMode := stage0.DNSConfMode{ Resolv: "default", Hosts: "default", } DNSConfig := cnitypes.DNS{} HostsEntries := make(stage0.HostsEntries) // Loop through --dns and look for magic option // Check for obvious insanity - only one magic option allowed for _, d := range flagDNS { // parse magic values if d == "host" || d == "none" { if len(flagDNS) > 1 { return DNSConfMode, DNSConfig, &HostsEntries, fmt.Errorf("no other --dns options allowed when --dns=%s is passed", d) } DNSConfMode.Resolv = d break } else { // parse list of IPS for _, d := range strings.Split(d, ",") { if net.ParseIP(d) == nil { return DNSConfMode, DNSConfig, &HostsEntries, fmt.Errorf("Invalid IP passed to --dns: %s", d) } DNSConfig.Nameservers = append(DNSConfig.Nameservers, d) } } } DNSConfig.Search = flagDNSSearch DNSConfig.Options = flagDNSOpt DNSConfig.Domain = flagDNSDomain if !common.IsDNSZero(&DNSConfig) { if DNSConfMode.Resolv == "default" { DNSConfMode.Resolv = "stage0" } if DNSConfMode.Resolv != "stage0" { return DNSConfMode, DNSConfig, &HostsEntries, fmt.Errorf("Cannot call --dns-opt, --dns-search, or --dns-domain with --dns=%v", DNSConfMode.Resolv) } } // Parse out --hosts-entries, also looking for the magic value "host" for _, entry := range flagHostsEntries { if entry == "host" { DNSConfMode.Hosts = "host" continue } for _, entry := range strings.Split(entry, ",") { vals := strings.SplitN(entry, "=", 2) if len(vals) != 2 { return DNSConfMode, DNSConfig, &HostsEntries, fmt.Errorf("Did not understand --hosts-entry %s", entry) } ipStr := vals[0] hostname := vals[1] // validate IP address ip := net.ParseIP(ipStr) if ip == nil { return DNSConfMode, DNSConfig, &HostsEntries, fmt.Errorf("Invalid IP passed to --hosts-entry: %s", ipStr) } _, exists := HostsEntries[ipStr] if !exists { HostsEntries[ipStr] = []string{hostname} } else { HostsEntries[ipStr] = append(HostsEntries[ipStr], hostname) } } } if len(HostsEntries) > 0 { if DNSConfMode.Hosts == "host" { return DNSConfMode, DNSConfig, &HostsEntries, errors.New("cannot pass --hosts-entry=host with multiple hosts-entries") } DNSConfMode.Hosts = "stage0" } return DNSConfMode, DNSConfig, &HostsEntries, nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
stage1/init/common/app.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage1/init/common/app.go#L98-L166
go
train
// prepareApp sets up the internal runtime context for a specific app.
func prepareApp(p *stage1commontypes.Pod, ra *schema.RuntimeApp) (*preparedApp, error)
// prepareApp sets up the internal runtime context for a specific app. func prepareApp(p *stage1commontypes.Pod, ra *schema.RuntimeApp) (*preparedApp, error)
{ pa := preparedApp{ app: ra, env: ra.App.Environment, noNewPrivileges: getAppNoNewPrivileges(ra.App.Isolators), } var err error // Determine numeric uid and gid u, g, err := ParseUserGroup(p, ra) if err != nil { return nil, errwrap.Wrap(errors.New("unable to determine app's uid and gid"), err) } if u < 0 || g < 0 { return nil, errors.New("Invalid uid or gid") } pa.uid = uint32(u) pa.gid = uint32(g) // Set some rkt-provided environment variables pa.env.Set("AC_APP_NAME", ra.Name.String()) if p.MetadataServiceURL != "" { pa.env.Set("AC_METADATA_URL", p.MetadataServiceURL) } // Determine capability set pa.capabilities, err = getAppCapabilities(ra.App.Isolators) if err != nil { return nil, errwrap.Wrap(errors.New("unable to construct capabilities"), err) } // Determine mounts cfd := ConvertedFromDocker(p.Images[ra.Name.String()]) pa.mounts, err = GenerateMounts(ra, p.Manifest.Volumes, cfd) if err != nil { return nil, errwrap.Wrap(errors.New("unable to compute mounts"), err) } // Compute resources pa.resources, err = computeAppResources(ra.App.Isolators) if err != nil { return nil, errwrap.Wrap(errors.New("unable to compute resources"), err) } // Protect kernel tunables by default if !p.InsecureOptions.DisablePaths { pa.roPaths = append(pa.roPaths, protectKernelROPaths...) pa.hiddenPaths = append(pa.hiddenDirs, protectKernelHiddenPaths...) pa.hiddenDirs = append(pa.hiddenDirs, protectKernelHiddenDirs...) } // Seccomp if !p.InsecureOptions.DisableSeccomp { pa.seccomp, err = generateSeccompFilter(p, &pa) if err != nil { return nil, err } if pa.seccomp != nil && pa.seccomp.forceNoNewPrivileges { pa.noNewPrivileges = true } } // Write the systemd-sysusers config file if err := generateSysusers(p, pa.app, int(pa.uid), int(pa.gid), &p.UidRange); err != nil { return nil, errwrap.Wrapf("unable to generate sysusers file", err) } return &pa, nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
stage1/init/common/app.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage1/init/common/app.go#L169-L229
go
train
// computeAppResources processes any isolators that manipulate cgroups.
func computeAppResources(isolators types.Isolators) (appResources, error)
// computeAppResources processes any isolators that manipulate cgroups. func computeAppResources(isolators types.Isolators) (appResources, error)
{ res := appResources{} var err error withIsolator := func(name string, f func() error) error { ok, err := cgroup.IsIsolatorSupported(name) if err != nil { return errwrap.Wrapf("could not check for isolator "+name, err) } if !ok { fmt.Fprintf(os.Stderr, "warning: resource/%s isolator set but support disabled in the kernel, skipping\n", name) return nil } return f() } for _, isolator := range isolators { if err != nil { return res, err } switch v := isolator.Value().(type) { case *types.ResourceMemory: err = withIsolator("memory", func() error { if v.Limit() == nil { return nil } val := uint64(v.Limit().Value()) res.MemoryLimit = &val return nil }) case *types.ResourceCPU: err = withIsolator("cpu", func() error { if v.Limit() == nil { return nil } if v.Limit().Value() > MaxMilliValue { return fmt.Errorf("cpu limit exceeds the maximum millivalue: %v", v.Limit().String()) } val := uint64(v.Limit().MilliValue() / 10) res.CPUQuota = &val return nil }) case *types.LinuxCPUShares: err = withIsolator("cpu", func() error { val := uint64(*v) res.LinuxCPUShares = &val return nil }) case *types.LinuxOOMScoreAdj: val := int(*v) res.LinuxOOMScoreAdjust = &val } } return res, err }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
stage1/init/common/app.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage1/init/common/app.go#L233-L239
go
train
// relAppPaths prepends the relative app path (/opt/stage1/rootfs/) to a list // of paths. Useful for systemd unit directives.
func (pa *preparedApp) relAppPaths(paths []string) []string
// relAppPaths prepends the relative app path (/opt/stage1/rootfs/) to a list // of paths. Useful for systemd unit directives. func (pa *preparedApp) relAppPaths(paths []string) []string
{ out := make([]string, 0, len(paths)) for _, p := range paths { out = append(out, filepath.Join(common.RelAppRootfsPath(pa.app.Name), p)) } return out }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
store/imagestore/aciinfo.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/store/imagestore/aciinfo.go#L68-L86
go
train
// GetAciInfosWithKeyPrefix returns all the ACIInfos with a blobkey starting with the given prefix.
func GetACIInfosWithKeyPrefix(tx *sql.Tx, prefix string) ([]*ACIInfo, error)
// GetAciInfosWithKeyPrefix returns all the ACIInfos with a blobkey starting with the given prefix. func GetACIInfosWithKeyPrefix(tx *sql.Tx, prefix string) ([]*ACIInfo, error)
{ var aciinfos []*ACIInfo rows, err := tx.Query("SELECT * from aciinfo WHERE hasPrefix(blobkey, $1)", prefix) if err != nil { return nil, err } defer rows.Close() for rows.Next() { aciinfo := &ACIInfo{} if err := aciinfoRowScan(rows, aciinfo); err != nil { return nil, err } aciinfos = append(aciinfos, aciinfo) } if err := rows.Err(); err != nil { return nil, err } return aciinfos, err }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
store/imagestore/aciinfo.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/store/imagestore/aciinfo.go#L90-L110
go
train
// GetAciInfosWithName returns all the ACIInfos for a given name. found will be // false if no aciinfo exists.
func GetACIInfosWithName(tx *sql.Tx, name string) ([]*ACIInfo, bool, error)
// GetAciInfosWithName returns all the ACIInfos for a given name. found will be // false if no aciinfo exists. func GetACIInfosWithName(tx *sql.Tx, name string) ([]*ACIInfo, bool, error)
{ var aciinfos []*ACIInfo found := false rows, err := tx.Query("SELECT * from aciinfo WHERE name == $1", name) if err != nil { return nil, false, err } defer rows.Close() for rows.Next() { found = true aciinfo := &ACIInfo{} if err := aciinfoRowScan(rows, aciinfo); err != nil { return nil, false, err } aciinfos = append(aciinfos, aciinfo) } if err := rows.Err(); err != nil { return nil, false, err } return aciinfos, found, err }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
store/imagestore/aciinfo.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/store/imagestore/aciinfo.go#L114-L134
go
train
// GetAciInfosWithBlobKey returns the ACIInfo with the given blobKey. found will be // false if no aciinfo exists.
func GetACIInfoWithBlobKey(tx *sql.Tx, blobKey string) (*ACIInfo, bool, error)
// GetAciInfosWithBlobKey returns the ACIInfo with the given blobKey. found will be // false if no aciinfo exists. func GetACIInfoWithBlobKey(tx *sql.Tx, blobKey string) (*ACIInfo, bool, error)
{ aciinfo := &ACIInfo{} found := false rows, err := tx.Query("SELECT * from aciinfo WHERE blobkey == $1", blobKey) if err != nil { return nil, false, err } defer rows.Close() for rows.Next() { found = true if err := aciinfoRowScan(rows, aciinfo); err != nil { return nil, false, err } // No more than one row for blobkey must exist. break } if err := rows.Err(); err != nil { return nil, false, err } return aciinfo, found, err }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
store/imagestore/aciinfo.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/store/imagestore/aciinfo.go#L138-L165
go
train
// GetAllACIInfos returns all the ACIInfos sorted by optional sortfields and // with ascending or descending order.
func GetAllACIInfos(tx *sql.Tx, sortfields []string, ascending bool) ([]*ACIInfo, error)
// GetAllACIInfos returns all the ACIInfos sorted by optional sortfields and // with ascending or descending order. func GetAllACIInfos(tx *sql.Tx, sortfields []string, ascending bool) ([]*ACIInfo, error)
{ var aciinfos []*ACIInfo query := "SELECT * from aciinfo" if len(sortfields) > 0 { query += fmt.Sprintf(" ORDER BY %s ", strings.Join(sortfields, ", ")) if ascending { query += "ASC" } else { query += "DESC" } } rows, err := tx.Query(query) if err != nil { return nil, err } defer rows.Close() for rows.Next() { aciinfo := &ACIInfo{} if err := aciinfoRowScan(rows, aciinfo); err != nil { return nil, err } aciinfos = append(aciinfos, aciinfo) } if err := rows.Err(); err != nil { return nil, err } return aciinfos, err }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
store/imagestore/aciinfo.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/store/imagestore/aciinfo.go#L168-L181
go
train
// WriteACIInfo adds or updates the provided aciinfo.
func WriteACIInfo(tx *sql.Tx, aciinfo *ACIInfo) error
// WriteACIInfo adds or updates the provided aciinfo. func WriteACIInfo(tx *sql.Tx, aciinfo *ACIInfo) 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 aciinfo where blobkey == $1", aciinfo.BlobKey) if err != nil { return err } _, err = tx.Exec("INSERT into aciinfo (blobkey, name, importtime, lastused, latest, size, treestoresize) VALUES ($1, $2, $3, $4, $5, $6, $7)", aciinfo.BlobKey, aciinfo.Name, aciinfo.ImportTime, aciinfo.LastUsed, aciinfo.Latest, aciinfo.Size, aciinfo.TreeStoreSize) if err != nil { return err } return nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
stage1/init/kvm/hypervisor/hvqemu/qemu_driver.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage1/init/kvm/hypervisor/hvqemu/qemu_driver.go#L29-L63
go
train
// StartCmd takes path to stage1, name of the machine, path to kernel, network describers, memory in megabytes // and quantity of cpus and prepares command line to run QEMU process
func StartCmd(wdPath, name, kernelPath string, nds []kvm.NetDescriber, cpu, mem int64, debug bool) []string
// StartCmd takes path to stage1, name of the machine, path to kernel, network describers, memory in megabytes // and quantity of cpus and prepares command line to run QEMU process func StartCmd(wdPath, name, kernelPath string, nds []kvm.NetDescriber, cpu, mem int64, debug bool) []string
{ var ( driverConfiguration = hypervisor.KvmHypervisor{ Bin: "./qemu", KernelParams: []string{ "root=/dev/root", "rootfstype=9p", "rootflags=trans=virtio,version=9p2000.L,cache=mmap", "rw", "systemd.default_standard_error=journal+console", "systemd.default_standard_output=journal+console", }, } ) driverConfiguration.InitKernelParams(debug) cmd := []string{ filepath.Join(wdPath, driverConfiguration.Bin), "-L", wdPath, "-no-reboot", "-display", "none", "-enable-kvm", "-smp", strconv.FormatInt(cpu, 10), "-m", strconv.FormatInt(mem, 10), "-kernel", kernelPath, "-fsdev", "local,id=root,path=stage1/rootfs,security_model=none", "-device", "virtio-9p-pci,fsdev=root,mount_tag=/dev/root", "-append", fmt.Sprintf("%s", strings.Join(driverConfiguration.KernelParams, " ")), "-chardev", "stdio,id=virtiocon0,signal=off", "-device", "virtio-serial", "-device", "virtconsole,chardev=virtiocon0", } return append(cmd, kvmNetArgs(nds)...) }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
stage1/init/kvm/hypervisor/hvqemu/qemu_driver.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage1/init/kvm/hypervisor/hvqemu/qemu_driver.go#L69-L79
go
train
// kvmNetArgs returns additional arguments that need to be passed // to qemu 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 qemu 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 qemuArgs []string for _, nd := range nds { qemuArgs = append(qemuArgs, []string{"-net", "nic,model=virtio"}...) qemuNic := fmt.Sprintf("tap,ifname=%s,script=no,downscript=no,vhost=on", nd.IfName()) qemuArgs = append(qemuArgs, []string{"-net", qemuNic}...) } return qemuArgs }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
stage1/init/kvm/hypervisor/hypervisor.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage1/init/kvm/hypervisor/hypervisor.go#L26-L54
go
train
// InitKernelParams sets debug and common parameters passed to the kernel
func (hv *KvmHypervisor) InitKernelParams(isDebug bool)
// InitKernelParams sets debug and common parameters passed to the kernel func (hv *KvmHypervisor) InitKernelParams(isDebug bool)
{ hv.KernelParams = append(hv.KernelParams, []string{ "console=hvc0", "init=/usr/lib/systemd/systemd", "no_timer_check", "noreplace-smp", "tsc=reliable"}...) if isDebug { hv.KernelParams = append(hv.KernelParams, []string{ "debug", "systemd.log_level=debug", "systemd.show_status=true", }...) } else { hv.KernelParams = append(hv.KernelParams, []string{ "systemd.show_status=false", "systemd.log_target=null", "rd.udev.log-priority=3", "quiet=vga", "quiet systemd.log_level=emerg", }...) } customKernelParams := os.Getenv("RKT_HYPERVISOR_EXTRA_KERNEL_PARAMS") if customKernelParams != "" { hv.KernelParams = append(hv.KernelParams, customKernelParams) } }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
rkt/image/dockerfetcher.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/image/dockerfetcher.go#L51-L59
go
train
// Hash uses docker2aci to download the image and convert it to // ACI, then stores it in the store and returns the hash.
func (f *dockerFetcher) Hash(u *url.URL) (string, error)
// Hash uses docker2aci to download the image and convert it to // ACI, then stores it in the store and returns the hash. func (f *dockerFetcher) Hash(u *url.URL) (string, error)
{ ensureLogger(f.Debug) dockerURL, err := d2acommon.ParseDockerURL(path.Join(u.Host, u.Path)) if err != nil { return "", fmt.Errorf(`invalid docker URL %q; expected syntax is "docker://[REGISTRY_HOST[:REGISTRY_PORT]/]IMAGE_NAME[:TAG]"`, u) } latest := dockerURL.Tag == "latest" return f.fetchImageFrom(u, latest) }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
stage0/registration.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage0/registration.go#L54-L109
go
train
// registerPod registers pod with metadata service. // Returns authentication token to be passed in the URL
func registerPod(root string, uuid *types.UUID, apps schema.AppList) (token string, rerr error)
// registerPod registers pod with metadata service. // Returns authentication token to be passed in the URL func registerPod(root string, uuid *types.UUID, apps schema.AppList) (token string, rerr error)
{ u := uuid.String() var err error token, err = generateMDSToken() if err != nil { rerr = errwrap.Wrap(errors.New("failed to generate MDS token"), err) return } pmfPath := common.PodManifestPath(root) pmf, err := os.Open(pmfPath) if err != nil { rerr = errwrap.Wrap(fmt.Errorf("failed to open runtime manifest (%v)", pmfPath), err) return } pth := fmt.Sprintf("/pods/%v?token=%v", u, token) err = httpRequest("PUT", pth, pmf) pmf.Close() if err != nil { rerr = errwrap.Wrap(errors.New("failed to register pod with metadata svc"), err) return } defer func() { if rerr != nil { unregisterPod(root, uuid) } }() rf, err := os.Create(filepath.Join(root, mdsRegisteredFile)) if err != nil { rerr = errwrap.Wrap(errors.New("failed to create mds-register file"), err) return } rf.Close() for _, app := range apps { ampath := common.ImageManifestPath(root, app.Name) amf, err := os.Open(ampath) if err != nil { rerr = errwrap.Wrap(fmt.Errorf("failed reading app manifest %q", ampath), err) return } err = registerApp(u, app.Name.String(), amf) amf.Close() if err != nil { rerr = errwrap.Wrap(errors.New("failed to register app with metadata svc"), err) return } } return }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
stage0/registration.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage0/registration.go#L112-L125
go
train
// unregisterPod unregisters pod with the metadata service.
func unregisterPod(root string, uuid *types.UUID) error
// unregisterPod unregisters pod with the metadata service. func unregisterPod(root string, uuid *types.UUID) error
{ _, err := os.Stat(filepath.Join(root, mdsRegisteredFile)) switch { case err == nil: pth := path.Join("/pods", uuid.String()) return httpRequest("DELETE", pth, nil) case os.IsNotExist(err): return nil default: return err } }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
stage0/registration.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage0/registration.go#L196-L203
go
train
// CheckMdsAvailability checks whether a local metadata service can be reached.
func CheckMdsAvailability() error
// CheckMdsAvailability checks whether a local metadata service can be reached. func CheckMdsAvailability() error
{ if conn, err := net.Dial("unix", common.MetadataServiceRegSock); err != nil { return errUnreachable } else { conn.Close() return nil } }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
networking/netinfo/netinfo.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/networking/netinfo/netinfo.go#L74-L80
go
train
// MergeCNIResult will incorporate the result of a CNI plugin's execution
func (ni *NetInfo) MergeCNIResult(result types.Result)
// MergeCNIResult will incorporate the result of a CNI plugin's execution func (ni *NetInfo) MergeCNIResult(result types.Result)
{ ni.IP = result.IP4.IP.IP ni.Mask = net.IP(result.IP4.IP.Mask) ni.HostIP = result.IP4.Gateway ni.IP4 = result.IP4 ni.DNS = result.DNS }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
pkg/multicall/multicall.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/multicall/multicall.go#L52-L58
go
train
// Add adds a new multicall command. name is the command name and fn is the // function that will be executed for the specified command. It returns the // related Entrypoint. // Packages adding new multicall commands should call Add in their init // function.
func Add(name string, fn commandFn) Entrypoint
// Add adds a new multicall command. name is the command name and fn is the // function that will be executed for the specified command. It returns the // related Entrypoint. // Packages adding new multicall commands should call Add in their init // function. func Add(name string, fn commandFn) Entrypoint
{ if _, ok := commands[name]; ok { panic(fmt.Errorf("command with name %q already exists", name)) } commands[name] = fn return Entrypoint(name) }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
pkg/multicall/multicall.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/multicall/multicall.go#L65-L74
go
train
// MaybeExec should be called at the start of the program, if the process argv[0] is // a name registered with multicall, the related function will be executed. // If the functions returns an error, it will be printed to stderr and will // exit with an exit status of 1, otherwise it will exit with a 0 exit // status.
func MaybeExec()
// MaybeExec should be called at the start of the program, if the process argv[0] is // a name registered with multicall, the related function will be executed. // If the functions returns an error, it will be printed to stderr and will // exit with an exit status of 1, otherwise it will exit with a 0 exit // status. func MaybeExec()
{ name := path.Base(os.Args[0]) if fn, ok := commands[name]; ok { if err := fn(); err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(254) } os.Exit(0) } }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
pkg/multicall/multicall.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/multicall/multicall.go#L78-L88
go
train
// Cmd will prepare the *exec.Cmd for the given entrypoint, configured with the // provided args.
func (e Entrypoint) Cmd(args ...string) *exec.Cmd
// Cmd will prepare the *exec.Cmd for the given entrypoint, configured with the // provided args. func (e Entrypoint) Cmd(args ...string) *exec.Cmd
{ // append the Entrypoint as argv[0] args = append([]string{string(e)}, args...) return &exec.Cmd{ Path: exePath, Args: args, SysProcAttr: &syscall.SysProcAttr{ Pdeathsig: syscall.SIGTERM, }, } }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
common/group.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/common/group.go#L28-L30
go
train
// LookupGid reads the group file and returns the gid of the group // specified by groupName.
func LookupGid(groupName string) (gid int, err error)
// LookupGid reads the group file and returns the gid of the group // specified by groupName. func LookupGid(groupName string) (gid int, err error)
{ return group.LookupGid(groupName) }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
rkt/stage1hash.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/stage1hash.go#L157-L165
go
train
// addStage1ImageFlags adds flags for specifying custom stage1 image
func addStage1ImageFlags(flags *pflag.FlagSet)
// addStage1ImageFlags adds flags for specifying custom stage1 image func addStage1ImageFlags(flags *pflag.FlagSet)
{ for _, data := range stage1FlagsData { wrapper := &stage1ImageLocationFlag{ loc: &overriddenStage1Location, kind: data.kind, } flags.Var(wrapper, data.flag, data.help) } }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
rkt/stage1hash.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/stage1hash.go#L217-L226
go
train
// getStage1Hash will try to get the hash of stage1 to use. // // Before getting inside this rats nest, let's try to write up the // expected behaviour. // // If the user passed --stage1-url, --stage1-path, --stage1-name, // --stage1-hash, or --stage1-from-dir then we take what was passed // and try to load it. If it failed, we bail out. No second chances // and whatnot. The details about how each flag type should be handled // are below. // // For --stage1-url, we do discovery, and try to fetch it directly into // the store. // // For --stage1-path, we do no discovery and try to fetch the image // directly from the given file path into the store. If the file is not // found, then we try to fetch the file in the same directory as the // rkt binary itself into the store. // // For --stage1-from-dir, we do no discovery and try to fetch the image // from the stage1 images directory by the name. // // For --stage1-name, we do discovery and fetch the discovered image // into the store. // // For --stage1-hash, we do no discovery and try to fetch the image // from the store by the hash. // // If the user passed none of the above flags, we try to get the name, // the version and the location from the configuration. The name and // the version must be defined in pair, that is - either both of them // are defined in configuration or none. Values from the configuration // override the values taken from the configure script. We search for // an image with the default name and version in the store. If it is // there, then woo, we are done. Otherwise we get the location and try // to load it. Depending on location type, we bail out immediately or // get a second chance. // // Details about the handling of different location types follow. // // If location is a URL, we do no discovery, just try to fetch it // directly into the store instead. // // If location is a path, we do no discovery, just try to fetch it // directly into the store instead. If the file is not found and we // have a second chance, we try to fetch the file in the same // directory as the rkt binary itself into the store. // // If location is an image hash then we make sure that it exists in // the store.
func getStage1Hash(s *imagestore.Store, ts *treestore.Store, c *config.Config) (*types.Hash, error)
// getStage1Hash will try to get the hash of stage1 to use. // // Before getting inside this rats nest, let's try to write up the // expected behaviour. // // If the user passed --stage1-url, --stage1-path, --stage1-name, // --stage1-hash, or --stage1-from-dir then we take what was passed // and try to load it. If it failed, we bail out. No second chances // and whatnot. The details about how each flag type should be handled // are below. // // For --stage1-url, we do discovery, and try to fetch it directly into // the store. // // For --stage1-path, we do no discovery and try to fetch the image // directly from the given file path into the store. If the file is not // found, then we try to fetch the file in the same directory as the // rkt binary itself into the store. // // For --stage1-from-dir, we do no discovery and try to fetch the image // from the stage1 images directory by the name. // // For --stage1-name, we do discovery and fetch the discovered image // into the store. // // For --stage1-hash, we do no discovery and try to fetch the image // from the store by the hash. // // If the user passed none of the above flags, we try to get the name, // the version and the location from the configuration. The name and // the version must be defined in pair, that is - either both of them // are defined in configuration or none. Values from the configuration // override the values taken from the configure script. We search for // an image with the default name and version in the store. If it is // there, then woo, we are done. Otherwise we get the location and try // to load it. Depending on location type, we bail out immediately or // get a second chance. // // Details about the handling of different location types follow. // // If location is a URL, we do no discovery, just try to fetch it // directly into the store instead. // // If location is a path, we do no discovery, just try to fetch it // directly into the store instead. If the file is not found and we // have a second chance, we try to fetch the file in the same // directory as the rkt binary itself into the store. // // If location is an image hash then we make sure that it exists in // the store. func getStage1Hash(s *imagestore.Store, ts *treestore.Store, c *config.Config) (*types.Hash, error)
{ imgDir := getStage1ImagesDirectory(c) if overriddenStage1Location.kind != stage1ImageLocationUnset { // we passed a --stage-{url,path,name,hash,from-dir} flag return getStage1HashFromFlag(s, ts, overriddenStage1Location, imgDir) } imgRef, imgLoc, imgFileName := getStage1DataFromConfig(c) return getConfiguredStage1Hash(s, ts, imgRef, imgLoc, imgFileName) }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
common/experiment.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/common/experiment.go#L35-L48
go
train
// IsExperimentEnabled returns true if the given rkt experiment is enabled. // The given name is converted to upper case and a bool RKT_EXPERIMENT_{NAME} // environment variable is retrieved. // If the experiment name is unknown, false is returned. // If the environment variable does not contain a valid bool value // according to strconv.ParseBool, false is returned.
func IsExperimentEnabled(name string) bool
// IsExperimentEnabled returns true if the given rkt experiment is enabled. // The given name is converted to upper case and a bool RKT_EXPERIMENT_{NAME} // environment variable is retrieved. // If the experiment name is unknown, false is returned. // If the environment variable does not contain a valid bool value // according to strconv.ParseBool, false is returned. func IsExperimentEnabled(name string) bool
{ if _, ok := stage0Experiments[name]; !ok { return false } v := os.Getenv("RKT_EXPERIMENT_" + strings.ToUpper(name)) enabled, err := strconv.ParseBool(v) if err != nil { return false // ignore errors from bool conversion } return enabled }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
pkg/sys/capability.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/sys/capability.go#L25-L35
go
train
// HasChrootCapability checks if the current process has the CAP_SYS_CHROOT // capability
func HasChrootCapability() bool
// HasChrootCapability checks if the current process has the CAP_SYS_CHROOT // capability func HasChrootCapability() bool
{ // Checking the capabilities should be enough, but in case there're // problem retrieving them, fallback checking for the effective uid // (hoping it hasn't dropped its CAP_SYS_CHROOT). caps, err := capability.NewPid(0) if err == nil { return caps.Get(capability.EFFECTIVE, capability.CAP_SYS_CHROOT) } else { return os.Geteuid() == 0 } }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
pkg/group/group.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/group/group.go#L43-L55
go
train
// LookupGid reads the group file specified by groupFile, and returns the gid of the group // specified by groupName.
func LookupGidFromFile(groupName, groupFile string) (gid int, err error)
// LookupGid reads the group file specified by groupFile, and returns the gid of the group // specified by groupName. func LookupGidFromFile(groupName, groupFile string) (gid int, err error)
{ groups, err := parseGroupFile(groupFile) if err != nil { return -1, errwrap.Wrap(fmt.Errorf("error parsing %q file", groupFile), err) } group, ok := groups[groupName] if !ok { return -1, fmt.Errorf("%q group not found", groupName) } return group.Gid, nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
pkg/group/group.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/group/group.go#L59-L61
go
train
// LookupGid reads the group file and returns the gid of the group // specified by groupName.
func LookupGid(groupName string) (gid int, err error)
// LookupGid reads the group file and returns the gid of the group // specified by groupName. func LookupGid(groupName string) (gid int, err error)
{ return LookupGidFromFile(groupName, groupFilePath) }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
pkg/lock/keylock.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/lock/keylock.go#L59-L76
go
train
// NewKeyLock returns a KeyLock for the specified key without acquisition. // lockdir is the directory where the lock file will be created. If lockdir // doesn't exists it will be created. // key value must be a valid file name (as the lock file is named after the key // value).
func NewKeyLock(lockDir string, key string) (*KeyLock, error)
// NewKeyLock returns a KeyLock for the specified key without acquisition. // lockdir is the directory where the lock file will be created. If lockdir // doesn't exists it will be created. // key value must be a valid file name (as the lock file is named after the key // value). func NewKeyLock(lockDir string, key string) (*KeyLock, error)
{ err := os.MkdirAll(lockDir, defaultDirPerm) if err != nil { return nil, err } keyLockFile := filepath.Join(lockDir, key) // create the file if it doesn't exists f, err := os.OpenFile(keyLockFile, os.O_RDONLY|os.O_CREATE, defaultFilePerm) if err != nil { return nil, errwrap.Wrap(errors.New("error creating key lock file"), err) } f.Close() keyLock, err := NewLock(keyLockFile, RegFile) if err != nil { return nil, errwrap.Wrap(errors.New("error opening key lock file"), err) } return &KeyLock{lockDir: lockDir, key: key, keyLock: keyLock}, nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
pkg/lock/keylock.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/lock/keylock.go#L94-L96
go
train
// TryExclusiveLock takes an exclusive lock on the key without blocking. // lockDir is the directory where the lock file will be created. // It will return ErrLocked if any lock is already held.
func TryExclusiveKeyLock(lockDir string, key string) (*KeyLock, error)
// TryExclusiveLock takes an exclusive lock on the key without blocking. // lockDir is the directory where the lock file will be created. // It will return ErrLocked if any lock is already held. func TryExclusiveKeyLock(lockDir string, key string) (*KeyLock, error)
{ return createAndLock(lockDir, key, keyLockExclusive|keyLockNonBlocking) }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
pkg/lock/keylock.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/lock/keylock.go#L109-L111
go
train
// ExclusiveLock takes an exclusive lock on a key. // lockDir is the directory where the lock file will be created. // It will block if an exclusive lock is already held on the key.
func ExclusiveKeyLock(lockDir string, key string) (*KeyLock, error)
// ExclusiveLock takes an exclusive lock on a key. // lockDir is the directory where the lock file will be created. // It will block if an exclusive lock is already held on the key. func ExclusiveKeyLock(lockDir string, key string) (*KeyLock, error)
{ return createAndLock(lockDir, key, keyLockExclusive) }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
pkg/lock/keylock.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/lock/keylock.go#L124-L126
go
train
// TrySharedLock takes a co-operative (shared) lock on a key without blocking. // lockDir is the directory where the lock file will be created. // It will return ErrLocked if an exclusive lock already exists on the key.
func TrySharedKeyLock(lockDir string, key string) (*KeyLock, error)
// TrySharedLock takes a co-operative (shared) lock on a key without blocking. // lockDir is the directory where the lock file will be created. // It will return ErrLocked if an exclusive lock already exists on the key. func TrySharedKeyLock(lockDir string, key string) (*KeyLock, error)
{ return createAndLock(lockDir, key, keyLockShared|keyLockNonBlocking) }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
pkg/lock/keylock.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/lock/keylock.go#L139-L141
go
train
// SharedLock takes a co-operative (shared) lock on a key. // lockDir is the directory where the lock file will be created. // It will block if an exclusive lock is already held on the key.
func SharedKeyLock(lockDir string, key string) (*KeyLock, error)
// SharedLock takes a co-operative (shared) lock on a key. // lockDir is the directory where the lock file will be created. // It will block if an exclusive lock is already held on the key. func SharedKeyLock(lockDir string, key string) (*KeyLock, error)
{ return createAndLock(lockDir, key, keyLockShared) }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
pkg/lock/keylock.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/lock/keylock.go#L170-L235
go
train
// lock is the base function to take a lock and handle changed lock files // As there's the need to remove unused (see CleanKeyLocks) lock files without // races, a changed file detection is needed. // // Without changed file detection this can happen: // // Process A takes exclusive lock on file01 // Process B waits for exclusive lock on file01. // Process A deletes file01 and then releases the lock. // Process B takes the lock on the removed file01 as it has the fd opened // Process C comes, creates the file as it doesn't exists, and it also takes an exclusive lock. // Now B and C thinks to own an exclusive lock. // // maxRetries can be passed, useful for testing.
func (l *KeyLock) lock(mode keyLockMode, maxRetries int) error
// lock is the base function to take a lock and handle changed lock files // As there's the need to remove unused (see CleanKeyLocks) lock files without // races, a changed file detection is needed. // // Without changed file detection this can happen: // // Process A takes exclusive lock on file01 // Process B waits for exclusive lock on file01. // Process A deletes file01 and then releases the lock. // Process B takes the lock on the removed file01 as it has the fd opened // Process C comes, creates the file as it doesn't exists, and it also takes an exclusive lock. // Now B and C thinks to own an exclusive lock. // // maxRetries can be passed, useful for testing. func (l *KeyLock) lock(mode keyLockMode, maxRetries int) error
{ retries := 0 for { var err error var isExclusive bool var isNonBlocking bool if mode&keyLockExclusive != 0 { isExclusive = true } if mode&keyLockNonBlocking != 0 { isNonBlocking = true } switch { case isExclusive && !isNonBlocking: err = l.keyLock.ExclusiveLock() case isExclusive && isNonBlocking: err = l.keyLock.TryExclusiveLock() case !isExclusive && !isNonBlocking: err = l.keyLock.SharedLock() case !isExclusive && isNonBlocking: err = l.keyLock.TrySharedLock() } if err != nil { return err } // Check that the file referenced by the lock fd is the same as // the current file on the filesystem var lockStat, curStat syscall.Stat_t lfd, err := l.keyLock.Fd() if err != nil { return err } err = syscall.Fstat(lfd, &lockStat) if err != nil { return err } keyLockFile := filepath.Join(l.lockDir, l.key) fd, err := syscall.Open(keyLockFile, syscall.O_RDONLY, 0) // If there's an error opening the file return an error if err != nil { return err } if err := syscall.Fstat(fd, &curStat); err != nil { syscall.Close(fd) return err } syscall.Close(fd) if lockStat.Ino == curStat.Ino && lockStat.Dev == curStat.Dev { return nil } if retries >= maxRetries { return fmt.Errorf("cannot acquire lock after %d retries", retries) } // If the file has changed discard this lock and try to take another lock. l.keyLock.Close() nl, err := NewKeyLock(l.lockDir, l.key) if err != nil { return err } l.keyLock = nl.keyLock retries++ } }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
pkg/lock/keylock.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/lock/keylock.go#L238-L244
go
train
// Unlock unlocks the key lock.
func (l *KeyLock) Unlock() error
// Unlock unlocks the key lock. func (l *KeyLock) Unlock() error
{ err := l.keyLock.Unlock() if err != nil { return err } return nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
pkg/lock/keylock.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/lock/keylock.go#L249-L277
go
train
// CleanKeyLocks remove lock files from the lockDir. // For every key it tries to take an Exclusive lock on it and skip it if it // fails with ErrLocked
func CleanKeyLocks(lockDir string) error
// CleanKeyLocks remove lock files from the lockDir. // For every key it tries to take an Exclusive lock on it and skip it if it // fails with ErrLocked func CleanKeyLocks(lockDir string) error
{ f, err := os.Open(lockDir) if err != nil { return errwrap.Wrap(errors.New("error opening lockDir"), err) } defer f.Close() files, err := f.Readdir(0) if err != nil { return errwrap.Wrap(errors.New("error getting lock files list"), err) } for _, f := range files { filename := filepath.Join(lockDir, f.Name()) keyLock, err := TryExclusiveKeyLock(lockDir, f.Name()) if err == ErrLocked { continue } if err != nil { return err } err = os.Remove(filename) if err != nil { keyLock.Close() return errwrap.Wrap(errors.New("error removing lock file"), err) } keyLock.Close() } return nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
rkt/pubkey/pubkey.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/pubkey/pubkey.go#L72-L88
go
train
// GetPubKeyLocations discovers locations at prefix
func (m *Manager) GetPubKeyLocations(prefix string) ([]string, error)
// GetPubKeyLocations discovers locations at prefix func (m *Manager) GetPubKeyLocations(prefix string) ([]string, error)
{ ensureLogger(m.Debug) if prefix == "" { return nil, fmt.Errorf("empty prefix") } kls, err := m.metaDiscoverPubKeyLocations(prefix) if err != nil { return nil, errwrap.Wrap(errors.New("prefix meta discovery error"), err) } if len(kls) == 0 { return nil, fmt.Errorf("meta discovery on %s resulted in no keys", prefix) } return kls, nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
rkt/pubkey/pubkey.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/pubkey/pubkey.go#L91-L155
go
train
// AddKeys adds the keys listed in pkls at prefix
func (m *Manager) AddKeys(pkls []string, prefix string, accept AcceptOption) error
// AddKeys adds the keys listed in pkls at prefix func (m *Manager) AddKeys(pkls []string, prefix string, accept AcceptOption) error
{ ensureLogger(m.Debug) if m.Ks == nil { return fmt.Errorf("no keystore available to add keys to") } for _, pkl := range pkls { u, err := url.Parse(pkl) if err != nil { return err } pk, err := m.getPubKey(u) if err != nil { return errwrap.Wrap(fmt.Errorf("error accessing the key %s", pkl), err) } defer pk.Close() err = displayKey(prefix, pkl, pk) if err != nil { return errwrap.Wrap(fmt.Errorf("error displaying the key %s", pkl), err) } if m.TrustKeysFromHTTPS && u.Scheme == "https" { accept = AcceptForce } if accept == AcceptAsk { if !terminal.IsTerminal(int(os.Stdin.Fd())) || !terminal.IsTerminal(int(os.Stderr.Fd())) { log.Printf("To trust the key for %q, do one of the following:", prefix) log.Printf(" - call rkt with --trust-keys-from-https") log.Printf(" - run: rkt trust --prefix %q", prefix) return fmt.Errorf("error reviewing key: unable to ask user to review fingerprint due to lack of tty") } accepted, err := reviewKey() if err != nil { return errwrap.Wrap(errors.New("error reviewing key"), err) } if !accepted { log.Printf("not trusting %q", pkl) continue } } if accept == AcceptForce { stdout.Printf("Trusting %q for prefix %q without fingerprint review.", pkl, prefix) } else { stdout.Printf("Trusting %q for prefix %q after fingerprint review.", pkl, prefix) } if prefix == "" { path, err := m.Ks.StoreTrustedKeyRoot(pk) if err != nil { return errwrap.Wrap(errors.New("error adding root key"), err) } stdout.Printf("Added root key at %q", path) } else { path, err := m.Ks.StoreTrustedKeyPrefix(prefix, pk) if err != nil { return errwrap.Wrap(fmt.Errorf("error adding key for prefix %q", prefix), err) } stdout.Printf("Added key for prefix %q at %q", prefix, path) } } return nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
rkt/pubkey/pubkey.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/pubkey/pubkey.go#L158-L181
go
train
// metaDiscoverPubKeyLocations discovers the locations of public keys through ACDiscovery by applying prefix as an ACApp
func (m *Manager) metaDiscoverPubKeyLocations(prefix string) ([]string, error)
// metaDiscoverPubKeyLocations discovers the locations of public keys through ACDiscovery by applying prefix as an ACApp func (m *Manager) metaDiscoverPubKeyLocations(prefix string) ([]string, error)
{ app, err := discovery.NewAppFromString(prefix) if err != nil { return nil, err } hostHeaders := config.ResolveAuthPerHost(m.AuthPerHost) insecure := discovery.InsecureNone if m.InsecureAllowHTTP { insecure = insecure | discovery.InsecureHTTP } if m.InsecureSkipTLSCheck { insecure = insecure | discovery.InsecureTLS } keys, attempts, err := discovery.DiscoverPublicKeys(*app, hostHeaders, insecure, 0) if err != nil && m.Debug { for _, a := range attempts { log.PrintE(fmt.Sprintf("meta tag 'ac-discovery-pubkeys' not found on %s", a.Prefix), a.Error) } } return keys, err }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
rkt/pubkey/pubkey.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/pubkey/pubkey.go#L184-L198
go
train
// getPubKey retrieves a public key (if remote), and verifies it's a gpg key
func (m *Manager) getPubKey(u *url.URL) (*os.File, error)
// getPubKey retrieves a public key (if remote), and verifies it's a gpg key func (m *Manager) getPubKey(u *url.URL) (*os.File, error)
{ switch u.Scheme { case "": return os.Open(u.Path) case "http": if !m.InsecureAllowHTTP { return nil, fmt.Errorf("--insecure-allow-http required for http URLs") } fallthrough case "https": return downloadKey(u, m.InsecureSkipTLSCheck) } return nil, fmt.Errorf("only local files and http or https URLs supported") }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
rkt/pubkey/pubkey.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/pubkey/pubkey.go#L201-L244
go
train
// downloadKey retrieves the file, storing it in a deleted tempfile
func downloadKey(u *url.URL, skipTLSCheck bool) (*os.File, error)
// downloadKey retrieves the file, storing it in a deleted tempfile func downloadKey(u *url.URL, skipTLSCheck bool) (*os.File, error)
{ tf, err := ioutil.TempFile("", "") if err != nil { return nil, errwrap.Wrap(errors.New("error creating tempfile"), err) } os.Remove(tf.Name()) // no need to keep the tempfile around defer func() { if tf != nil { tf.Close() } }() // TODO(krnowak): we should probably apply credential headers // from config here var client *http.Client if skipTLSCheck { client = insecureClient } else { client = secureClient } res, err := client.Get(u.String()) if err != nil { return nil, errwrap.Wrap(errors.New("error getting key"), err) } defer res.Body.Close() if res.StatusCode != http.StatusOK { return nil, fmt.Errorf("bad HTTP status code: %d", res.StatusCode) } if _, err := io.Copy(tf, res.Body); err != nil { return nil, errwrap.Wrap(errors.New("error copying key"), err) } if _, err = tf.Seek(0, os.SEEK_SET); err != nil { return nil, errwrap.Wrap(errors.New("error seeking"), err) } retTf := tf tf = nil return retTf, nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
rkt/pubkey/pubkey.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/pubkey/pubkey.go#L275-L296
go
train
// displayKey shows the key summary
func displayKey(prefix, location string, key *os.File) error
// displayKey shows the key summary func displayKey(prefix, location string, key *os.File) error
{ defer key.Seek(0, os.SEEK_SET) kr, err := openpgp.ReadArmoredKeyRing(key) if err != nil { return errwrap.Wrap(errors.New("error reading key"), err) } log.Printf("prefix: %q\nkey: %q", prefix, location) for _, k := range kr { stdout.Printf("gpg key fingerprint is: %s", fingerToString(k.PrimaryKey.Fingerprint)) for _, sk := range k.Subkeys { stdout.Printf(" Subkey fingerprint: %s", fingerToString(sk.PublicKey.Fingerprint)) } for n := range k.Identities { stdout.Printf("\t%s", n) } } return nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
rkt/pubkey/pubkey.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/pubkey/pubkey.go#L299-L316
go
train
// reviewKey asks the user to accept the key
func reviewKey() (bool, error)
// reviewKey asks the user to accept the key func reviewKey() (bool, error)
{ in := bufio.NewReader(os.Stdin) for { stdout.Printf("Are you sure you want to trust this key (yes/no)?") input, err := in.ReadString('\n') if err != nil { return false, errwrap.Wrap(errors.New("error reading input"), err) } switch input { case "yes\n": return true, nil case "no\n": return false, nil default: stdout.Printf("Please enter 'yes' or 'no'") } } }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
networking/kvm.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/networking/kvm.go#L59-L77
go
train
// setupTapDevice creates persistent tap device // and returns a newly created netlink.Link structure
func setupTapDevice(podID types.UUID) (netlink.Link, error)
// setupTapDevice creates persistent tap device // and returns a newly created netlink.Link structure func setupTapDevice(podID types.UUID) (netlink.Link, error)
{ // network device names are limited to 16 characters // the suffix %d will be replaced by the kernel with a suitable number nameTemplate := fmt.Sprintf("rkt-%s-tap%%d", podID.String()[0:4]) ifName, err := tuntap.CreatePersistentIface(nameTemplate, tuntap.Tap) if err != nil { return nil, errwrap.Wrap(errors.New("tuntap persist"), err) } link, err := netlink.LinkByName(ifName) if err != nil { return nil, errwrap.Wrap(fmt.Errorf("cannot find link %q", ifName), err) } if err := netlink.LinkSetUp(link); err != nil { return nil, errwrap.Wrap(fmt.Errorf("cannot set link up %q", ifName), err) } return link, nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
networking/kvm.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/networking/kvm.go#L92-L146
go
train
// setupTapDevice creates persistent macvtap device // and returns a newly created netlink.Link structure // using part of pod hash and interface number in interface name
func setupMacVTapDevice(podID types.UUID, config MacVTapNetConf, interfaceNumber int) (netlink.Link, error)
// setupTapDevice creates persistent macvtap device // and returns a newly created netlink.Link structure // using part of pod hash and interface number in interface name func setupMacVTapDevice(podID types.UUID, config MacVTapNetConf, interfaceNumber int) (netlink.Link, error)
{ master, err := netlink.LinkByName(config.Master) if err != nil { return nil, errwrap.Wrap(fmt.Errorf("cannot find master device '%v'", config.Master), err) } var mode netlink.MacvlanMode switch config.Mode { // if not set - defaults to bridge mode as in: // https://github.com/rkt/rkt/blob/master/Documentation/networking.md#macvlan case "", "bridge": mode = netlink.MACVLAN_MODE_BRIDGE case "private": mode = netlink.MACVLAN_MODE_PRIVATE case "vepa": mode = netlink.MACVLAN_MODE_VEPA case "passthru": mode = netlink.MACVLAN_MODE_PASSTHRU default: return nil, fmt.Errorf("unsupported macvtap mode: %v", config.Mode) } mtu := master.Attrs().MTU if config.MTU != 0 { mtu = config.MTU } interfaceName := fmt.Sprintf("rkt-%s-vtap%d", podID.String()[0:4], interfaceNumber) link := &netlink.Macvtap{ Macvlan: netlink.Macvlan{ LinkAttrs: netlink.LinkAttrs{ Name: interfaceName, MTU: mtu, ParentIndex: master.Attrs().Index, }, Mode: mode, }, } if err := netlink.LinkAdd(link); err != nil { return nil, errwrap.Wrap(errors.New("cannot create macvtap interface"), err) } // TODO: duplicate following lines for ipv6 support, when it will be added in other places ipv4SysctlValueName := fmt.Sprintf(IPv4InterfaceArpProxySysctlTemplate, interfaceName) if _, err := cnisysctl.Sysctl(ipv4SysctlValueName, "1"); err != nil { // remove the newly added link and ignore errors, because we already are in a failed state _ = netlink.LinkDel(link) return nil, errwrap.Wrap(fmt.Errorf("failed to set proxy_arp on newly added interface %q", interfaceName), err) } if err := netlink.LinkSetUp(link); err != nil { // remove the newly added link and ignore errors, because we already are in a failed state _ = netlink.LinkDel(link) return nil, errwrap.Wrap(errors.New("cannot set up macvtap interface"), err) } return link, nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
networking/kvm.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/networking/kvm.go#L151-L178
go
train
// kvmSetupNetAddressing calls IPAM plugin (with a hack) to reserve an IP to be // used by newly create tuntap pair // in result it updates activeNet.runtime configuration
func kvmSetupNetAddressing(network *Networking, n activeNet, ifName string) error
// kvmSetupNetAddressing calls IPAM plugin (with a hack) to reserve an IP to be // used by newly create tuntap pair // in result it updates activeNet.runtime configuration func kvmSetupNetAddressing(network *Networking, n activeNet, ifName string) error
{ // TODO: very ugly hack, that go through upper plugin, down to ipam plugin if err := ip.EnableIP4Forward(); err != nil { return errwrap.Wrap(errors.New("failed to enable forwarding"), err) } // patch plugin type only for single IPAM run time, then revert this change original_type := n.conf.Type n.conf.Type = n.conf.IPAM.Type output, err := network.execNetPlugin("ADD", &n, ifName) n.conf.Type = original_type if err != nil { return errwrap.Wrap(fmt.Errorf("problem executing network plugin %q (%q)", n.conf.IPAM.Type, ifName), err) } result := cnitypes.Result{} if err = json.Unmarshal(output, &result); err != nil { return errwrap.Wrap(fmt.Errorf("error parsing %q result", n.conf.Name), err) } if result.IP4 == nil { return fmt.Errorf("net-plugin returned no IPv4 configuration") } n.runtime.MergeCNIResult(result) return nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
networking/kvm.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/networking/kvm.go#L437-L642
go
train
// kvmSetup prepare new Networking to be used in kvm environment based on tuntap pair interfaces // to allow communication with virtual machine created by lkvm tool
func kvmSetup(podRoot string, podID types.UUID, fps []commonnet.ForwardedPort, netList common.NetList, localConfig string, noDNS bool) (*Networking, error)
// kvmSetup prepare new Networking to be used in kvm environment based on tuntap pair interfaces // to allow communication with virtual machine created by lkvm tool func kvmSetup(podRoot string, podID types.UUID, fps []commonnet.ForwardedPort, netList common.NetList, localConfig string, noDNS bool) (*Networking, error)
{ network := Networking{ podEnv: podEnv{ podRoot: podRoot, podID: podID, netsLoadList: netList, localConfig: localConfig, }, } var e error // If there's a network set as default in CNI configuration defaultGatewaySet := false _, defaultNet, err := net.ParseCIDR("0.0.0.0/0") if err != nil { return nil, errwrap.Wrap(errors.New("error when parsing net address"), err) } network.nets, e = network.loadNets() if e != nil { return nil, errwrap.Wrap(errors.New("error loading network definitions"), e) } // did stage0 already make /etc/rkt-resolv.conf (i.e. --dns passed) resolvPath := filepath.Join(common.Stage1RootfsPath(podRoot), "etc/rkt-resolv.conf") _, err = os.Stat(resolvPath) if err != nil && !os.IsNotExist(err) { return nil, errwrap.Wrap(fmt.Errorf("error statting /etc/rkt-resolv.conf"), err) } podHasResolvConf := err == nil for i, n := range network.nets { if n.conf.Type == "flannel" { if err := kvmTransformFlannelNetwork(&n); err != nil { return nil, errwrap.Wrap(errors.New("cannot transform flannel network into basic network"), err) } } switch n.conf.Type { case "ptp": link, err := setupTapDevice(podID) if err != nil { return nil, err } ifName := link.Attrs().Name n.runtime.IfName = ifName err = kvmSetupNetAddressing(&network, n, ifName) if err != nil { return nil, err } // add address to host tap device err = ensureHasAddr( link, &net.IPNet{ IP: n.runtime.IP4.Gateway, Mask: net.IPMask(n.runtime.Mask), }, ) if err != nil { return nil, errwrap.Wrap(fmt.Errorf("cannot add address to host tap device %q", ifName), err) } if err := removeAllRoutesOnLink(link); err != nil { return nil, errwrap.Wrap(fmt.Errorf("cannot remove route on host tap device %q", ifName), err) } if err := addRoute(link, n.runtime.IP); err != nil { return nil, errwrap.Wrap(errors.New("cannot add on host direct route to pod"), err) } case "bridge": config := BridgeNetConf{ NetConf: NetConf{ MTU: defaultMTU, }, BrName: defaultBrName, } if err := json.Unmarshal(n.confBytes, &config); err != nil { return nil, errwrap.Wrap(fmt.Errorf("error parsing %q result", n.conf.Name), err) } br, err := ensureBridgeIsUp(config.BrName, config.MTU) if err != nil { return nil, errwrap.Wrap(errors.New("error in time of bridge setup"), err) } link, err := setupTapDevice(podID) if err != nil { return nil, errwrap.Wrap(errors.New("can not setup tap device"), err) } err = netlink.LinkSetMaster(link, br) if err != nil { rErr := tuntap.RemovePersistentIface(n.runtime.IfName, tuntap.Tap) if rErr != nil { stderr.PrintE("warning: could not cleanup tap interface", rErr) } return nil, errwrap.Wrap(errors.New("can not add tap interface to bridge"), err) } ifName := link.Attrs().Name n.runtime.IfName = ifName err = kvmSetupNetAddressing(&network, n, ifName) if err != nil { return nil, err } if n.conf.IsDefaultGateway { n.runtime.IP4.Routes = append( n.runtime.IP4.Routes, cnitypes.Route{Dst: *defaultNet, GW: n.runtime.IP4.Gateway}, ) defaultGatewaySet = true config.IsGw = true } if config.IsGw { err = ensureHasAddr( br, &net.IPNet{ IP: n.runtime.IP4.Gateway, Mask: net.IPMask(n.runtime.Mask), }, ) if err != nil { return nil, errwrap.Wrap(fmt.Errorf("cannot add address to host bridge device %q", br.Name), err) } } case "macvlan": config := MacVTapNetConf{} if err := json.Unmarshal(n.confBytes, &config); err != nil { return nil, errwrap.Wrap(fmt.Errorf("error parsing %q result", n.conf.Name), err) } link, err := setupMacVTapDevice(podID, config, i) if err != nil { return nil, err } ifName := link.Attrs().Name n.runtime.IfName = ifName err = kvmSetupNetAddressing(&network, n, ifName) if err != nil { return nil, err } default: return nil, fmt.Errorf("network %q have unsupported type: %q", n.conf.Name, n.conf.Type) } // Check if there's any other network set as default gateway if defaultGatewaySet { for _, route := range n.runtime.IP4.Routes { if (defaultNet.String() == route.Dst.String()) && !n.conf.IsDefaultGateway { return nil, fmt.Errorf("flannel config enables default gateway and IPAM sets default gateway via %q", n.runtime.IP4.Gateway) } } } // Generate rkt-resolv.conf if it's not already there. // The first network plugin that supplies a non-empty // DNS response will win, unless noDNS is true (--dns passed to rkt run) if !common.IsDNSZero(&n.runtime.DNS) && !noDNS { if !podHasResolvConf { err := ioutil.WriteFile( resolvPath, []byte(common.MakeResolvConf(n.runtime.DNS, "Generated by rkt from network "+n.conf.Name)), 0644) if err != nil { return nil, errwrap.Wrap(fmt.Errorf("error creating resolv.conf"), err) } podHasResolvConf = true } else { stderr.Printf("Warning: network %v plugin specified DNS configuration, but DNS already supplied", n.conf.Name) } } if n.conf.IPMasq { chain := cniutils.FormatChainName(n.conf.Name, podID.String()) comment := cniutils.FormatComment(n.conf.Name, podID.String()) if err := ip.SetupIPMasq(&net.IPNet{ IP: n.runtime.IP, Mask: net.IPMask(n.runtime.Mask), }, chain, comment); err != nil { return nil, err } } network.nets[i] = n } podIP, err := network.GetForwardableNetPodIP() if err != nil { return nil, err } if err := network.setupForwarding(); err != nil { network.teardownForwarding() return nil, err } if err := network.forwardPorts(fps, podIP); err != nil { network.teardownForwarding() return nil, err } return &network, nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
networking/kvm.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/networking/kvm.go#L650-L701
go
train
/* extend Networking struct with methods to clean up kvm specific network configurations */ // teardownKvmNets teardown every active networking from networking by // removing tuntap interface and releasing its ip from IPAM plugin
func (n *Networking) teardownKvmNets()
/* extend Networking struct with methods to clean up kvm specific network configurations */ // teardownKvmNets teardown every active networking from networking by // removing tuntap interface and releasing its ip from IPAM plugin func (n *Networking) teardownKvmNets()
{ for _, an := range n.nets { if an.conf.Type == "flannel" { if err := kvmTransformFlannelNetwork(&an); err != nil { stderr.PrintE("error transforming flannel network", err) continue } } switch an.conf.Type { case "ptp", "bridge": // remove tuntap interface tuntap.RemovePersistentIface(an.runtime.IfName, tuntap.Tap) case "macvlan": link, err := netlink.LinkByName(an.runtime.IfName) if err != nil { stderr.PrintE(fmt.Sprintf("cannot find link `%v`", an.runtime.IfName), err) continue } else { err := netlink.LinkDel(link) if err != nil { stderr.PrintE(fmt.Sprintf("cannot remove link `%v`", an.runtime.IfName), err) continue } } default: stderr.Printf("unsupported network type: %q", an.conf.Type) continue } // ugly hack again to directly call IPAM plugin to release IP an.conf.Type = an.conf.IPAM.Type _, err := n.execNetPlugin("DEL", &an, an.runtime.IfName) if err != nil { stderr.PrintE("error executing network plugin", err) } // remove masquerading if it was prepared if an.conf.IPMasq { chain := cniutils.FormatChainName(an.conf.Name, n.podID.String()) comment := cniutils.FormatChainName(an.conf.Name, n.podID.String()) err := ip.TeardownIPMasq(&net.IPNet{ IP: an.runtime.IP, Mask: net.IPMask(an.runtime.Mask), }, chain, comment) if err != nil { stderr.PrintE("error on removing masquerading", err) } } } }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
networking/kvm.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/networking/kvm.go#L705-L711
go
train
// kvmTeardown network teardown for kvm flavor based pods // similar to Networking.Teardown but without host namespaces
func (n *Networking) kvmTeardown()
// kvmTeardown network teardown for kvm flavor based pods // similar to Networking.Teardown but without host namespaces func (n *Networking) kvmTeardown()
{ if err := n.teardownForwarding(); err != nil { stderr.PrintE("error removing forwarded ports (kvm)", err) } n.teardownKvmNets() }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
store/db/db.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/store/db/db.go#L51-L75
go
train
// Do Opens the db, executes DoTx and then Closes the DB // To support a multiprocess and multigoroutine model on a single file access // database like ql there's the need to exlusively lock, open, close, unlock the // db for every transaction. For this reason every db transaction should be // fast to not block other processes/goroutines.
func (db *DB) Do(fns ...txfunc) error
// Do Opens the db, executes DoTx and then Closes the DB // To support a multiprocess and multigoroutine model on a single file access // database like ql there's the need to exlusively lock, open, close, unlock the // db for every transaction. For this reason every db transaction should be // fast to not block other processes/goroutines. func (db *DB) Do(fns ...txfunc) error
{ l, err := lock.ExclusiveLock(db.dbdir, lock.Dir) if err != nil { return err } defer l.Close() sqldb, err := sql.Open("ql", filepath.Join(db.dbdir, DbFilename)) if err != nil { return err } defer sqldb.Close() tx, err := sqldb.Begin() if err != nil { return err } for _, fn := range fns { if err := fn(tx); err != nil { tx.Rollback() return err } } return tx.Commit() }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
rkt/image/filefetcher.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/image/filefetcher.go#L39-L61
go
train
// Hash opens a file, optionally verifies it against passed asc, // stores it in the store and returns the hash.
func (f *fileFetcher) Hash(aciPath string, a *asc) (string, error)
// Hash opens a file, optionally verifies it against passed asc, // stores it in the store and returns the hash. func (f *fileFetcher) Hash(aciPath string, a *asc) (string, error)
{ ensureLogger(f.Debug) absPath, err := filepath.Abs(aciPath) if err != nil { return "", errwrap.Wrap(fmt.Errorf("failed to get an absolute path for %q", aciPath), err) } aciPath = absPath aciFile, err := f.getFile(aciPath, a) if err != nil { return "", err } defer aciFile.Close() key, err := f.S.WriteACI(aciFile, imagestore.ACIFetchInfo{ Latest: false, }) if err != nil { return "", err } return key, nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
rkt/image/filefetcher.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/image/filefetcher.go#L82-L116
go
train
// fetch opens and verifies the ACI.
func (f *fileFetcher) getVerifiedFile(aciPath string, a *asc) (*os.File, error)
// fetch opens and verifies the ACI. func (f *fileFetcher) getVerifiedFile(aciPath string, a *asc) (*os.File, error)
{ var aciFile *os.File // closed on error var errClose error // error signaling to close aciFile f.maybeOverrideAsc(aciPath, a) ascFile, err := a.Get() if err != nil { return nil, errwrap.Wrap(errors.New("error opening signature file"), err) } defer ascFile.Close() aciFile, err = os.Open(aciPath) if err != nil { return nil, errwrap.Wrap(errors.New("error opening ACI file"), err) } defer func() { if errClose != nil { aciFile.Close() } }() validator, errClose := newValidator(aciFile) if errClose != nil { return nil, errClose } entity, errClose := validator.ValidateWithSignature(f.Ks, ascFile) if errClose != nil { return nil, errwrap.Wrap(fmt.Errorf("image %q verification failed", validator.ImageName()), errClose) } printIdentities(entity) return aciFile, nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
pkg/fs/mount.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/fs/mount.go#L56-L58
go
train
// NewLoggingMounter returns a MountUnmounter that logs mount events using the given logger func.
func NewLoggingMounter(m Mounter, um Unmounter, logf func(string, ...interface{})) MountUnmounter
// NewLoggingMounter returns a MountUnmounter that logs mount events using the given logger func. func NewLoggingMounter(m Mounter, um Unmounter, logf func(string, ...interface{})) MountUnmounter
{ return &loggingMounter{m, um, logf} }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
pkg/tpm/tpm.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/tpm/tpm.go#L29-L33
go
train
// Extend extends the TPM log with the provided string. Returns any error.
func Extend(description string) error
// Extend extends the TPM log with the provided string. Returns any error. func Extend(description string) error
{ connection := tpmclient.New("localhost:12041", timeout) err := connection.Extend(15, 0x1000, nil, description) return err }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
common/cgroup_util.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/common/cgroup_util.go#L43-L74
go
train
// cgEscape implements very minimal escaping for names to be used as file names // in the cgroup tree: any name which might conflict with a kernel name or is // prefixed with '_' is prefixed with a '_'. That way, when reading cgroup // names it is sufficient to remove a single prefixing underscore if there is // one.
func cgEscape(p string) string
// cgEscape implements very minimal escaping for names to be used as file names // in the cgroup tree: any name which might conflict with a kernel name or is // prefixed with '_' is prefixed with a '_'. That way, when reading cgroup // names it is sufficient to remove a single prefixing underscore if there is // one. func cgEscape(p string) string
{ needPrefix := false switch { case strings.HasPrefix(p, "_"): fallthrough case strings.HasPrefix(p, "."): fallthrough case p == "notify_on_release": fallthrough case p == "release_agent": fallthrough case p == "tasks": needPrefix = true case strings.Contains(p, "."): sp := strings.Split(p, ".") if sp[0] == "cgroup" { needPrefix = true } else { n := sp[0] if checkHierarchy(n) { needPrefix = true } } } if needPrefix { return "_" + p } return p }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
common/cgroup_util.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/common/cgroup_util.go#L133-L174
go
train
// SliceToPath explodes a slice name to its corresponding path in the cgroup // hierarchy. For example, a slice named "foo-bar-baz.slice" corresponds to the // path "foo.slice/foo-bar.slice/foo-bar-baz.slice". See systemd.slice(5)
func SliceToPath(unit string) (string, error)
// SliceToPath explodes a slice name to its corresponding path in the cgroup // hierarchy. For example, a slice named "foo-bar-baz.slice" corresponds to the // path "foo.slice/foo-bar.slice/foo-bar-baz.slice". See systemd.slice(5) func SliceToPath(unit string) (string, error)
{ if unit == "-.slice" { return "", nil } if !strings.HasSuffix(unit, ".slice") { return "", fmt.Errorf("not a slice") } if !sliceNameIsValid(unit) { return "", fmt.Errorf("invalid slice name") } prefix := unitnameToPrefix(unit) // don't allow initial dashes if prefix[0] == '-' { return "", fmt.Errorf("initial dash") } prefixParts := strings.Split(prefix, "-") var curSlice string var slicePath string for _, slicePart := range prefixParts { if slicePart == "" { return "", fmt.Errorf("trailing or double dash") } if curSlice != "" { curSlice = curSlice + "-" } curSlice = curSlice + slicePart curSliceDir := curSlice + ".slice" escaped := cgEscape(curSliceDir) slicePath = filepath.Join(slicePath, escaped) } return slicePath, nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
common/common.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/common/common.go#L101-L103
go
train
// Stage1RootfsPath returns the path to the stage1 rootfs
func Stage1RootfsPath(root string) string
// Stage1RootfsPath returns the path to the stage1 rootfs func Stage1RootfsPath(root string) string
{ return filepath.Join(Stage1ImagePath(root), aci.RootfsDir) }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
common/common.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/common/common.go#L106-L108
go
train
// Stage1ManifestPath returns the path to the stage1's manifest file inside the expanded ACI.
func Stage1ManifestPath(root string) string
// Stage1ManifestPath returns the path to the stage1's manifest file inside the expanded ACI. func Stage1ManifestPath(root string) string
{ return filepath.Join(Stage1ImagePath(root), aci.ManifestFile) }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
common/common.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/common/common.go#L140-L142
go
train
// AppStatusPath returns the path of the status file of an app.
func AppStatusPath(root, appName string) string
// AppStatusPath returns the path of the status file of an app. func AppStatusPath(root, appName string) string
{ return filepath.Join(AppsStatusesPath(root), appName) }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
common/common.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/common/common.go#L146-L148
go
train
// AppStatusPathFromStage1Rootfs returns the path of the status file of an app. // It receives the stage1 rootfs as parameter instead of the pod root.
func AppStatusPathFromStage1Rootfs(rootfs, appName string) string
// AppStatusPathFromStage1Rootfs returns the path of the status file of an app. // It receives the stage1 rootfs as parameter instead of the pod root. func AppStatusPathFromStage1Rootfs(rootfs, appName string) string
{ return filepath.Join(AppsStatusesPathFromStage1Rootfs(rootfs), appName) }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
common/common.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/common/common.go#L152-L154
go
train
// AppCreatedPath returns the path of the ${appname}-created file, which is used to record // the creation timestamp of the app.
func AppCreatedPath(root, appName string) string
// AppCreatedPath returns the path of the ${appname}-created file, which is used to record // the creation timestamp of the app. func AppCreatedPath(root, appName string) string
{ return filepath.Join(AppsStatusesPath(root), fmt.Sprintf("%s-created", appName)) }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
common/common.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/common/common.go#L159-L161
go
train
// AppCreatedPathFromStage1Rootfs returns the path of the ${appname}-created file, // which is used to record the creation timestamp of the app. // It receives the stage1 rootfs as parameter instead of the pod root.
func AppCreatedPathFromStage1Rootfs(rootfs, appName string) string
// AppCreatedPathFromStage1Rootfs returns the path of the ${appname}-created file, // which is used to record the creation timestamp of the app. // It receives the stage1 rootfs as parameter instead of the pod root. func AppCreatedPathFromStage1Rootfs(rootfs, appName string) string
{ return filepath.Join(AppsStatusesPathFromStage1Rootfs(rootfs), fmt.Sprintf("%s-created", appName)) }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
common/common.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/common/common.go#L182-L184
go
train
// AppPath returns the path to an app's rootfs.
func AppPath(root string, appName types.ACName) string
// AppPath returns the path to an app's rootfs. func AppPath(root string, appName types.ACName) string
{ return filepath.Join(AppsPath(root), appName.String()) }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
common/common.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/common/common.go#L187-L189
go
train
// AppRootfsPath returns the path to an app's rootfs.
func AppRootfsPath(root string, appName types.ACName) string
// AppRootfsPath returns the path to an app's rootfs. func AppRootfsPath(root string, appName types.ACName) string
{ return filepath.Join(AppPath(root, appName), aci.RootfsDir) }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
common/common.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/common/common.go#L192-L194
go
train
// RelAppPath returns the path of an app relative to the stage1 chroot.
func RelAppPath(appName types.ACName) string
// RelAppPath returns the path of an app relative to the stage1 chroot. func RelAppPath(appName types.ACName) string
{ return filepath.Join(stage2Dir, appName.String()) }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
common/common.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/common/common.go#L197-L199
go
train
// RelAppRootfsPath returns the path of an app's rootfs relative to the stage1 chroot.
func RelAppRootfsPath(appName types.ACName) string
// RelAppRootfsPath returns the path of an app's rootfs relative to the stage1 chroot. func RelAppRootfsPath(appName types.ACName) string
{ return filepath.Join(RelAppPath(appName), aci.RootfsDir) }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
common/common.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/common/common.go#L202-L204
go
train
// ImageManifestPath returns the path to the app's manifest file of a pod.
func ImageManifestPath(root string, appName types.ACName) string
// ImageManifestPath returns the path to the app's manifest file of a pod. func ImageManifestPath(root string, appName types.ACName) string
{ return filepath.Join(AppPath(root, appName), aci.ManifestFile) }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
common/common.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/common/common.go#L212-L214
go
train
// AppInfoPath returns the path to the app's appsinfo directory of a pod.
func AppInfoPath(root string, appName types.ACName) string
// AppInfoPath returns the path to the app's appsinfo directory of a pod. func AppInfoPath(root string, appName types.ACName) string
{ return filepath.Join(AppsInfoPath(root), appName.String()) }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
common/common.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/common/common.go#L217-L219
go
train
// AppTreeStoreIDPath returns the path to the app's treeStoreID file of a pod.
func AppTreeStoreIDPath(root string, appName types.ACName) string
// AppTreeStoreIDPath returns the path to the app's treeStoreID file of a pod. func AppTreeStoreIDPath(root string, appName types.ACName) string
{ return filepath.Join(AppInfoPath(root, appName), AppTreeStoreIDFilename) }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
common/common.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/common/common.go#L222-L224
go
train
// AppImageManifestPath returns the path to the app's ImageManifest file
func AppImageManifestPath(root string, appName types.ACName) string
// AppImageManifestPath returns the path to the app's ImageManifest file func AppImageManifestPath(root string, appName types.ACName) string
{ return filepath.Join(AppInfoPath(root, appName), aci.ManifestFile) }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
common/common.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/common/common.go#L233-L246
go
train
// CreateSharedVolumesPath ensures the sharedVolumePath for the pod root passed // in exists. It returns the shared volume path or an error.
func CreateSharedVolumesPath(root string) (string, error)
// CreateSharedVolumesPath ensures the sharedVolumePath for the pod root passed // in exists. It returns the shared volume path or an error. func CreateSharedVolumesPath(root string) (string, error)
{ sharedVolPath := SharedVolumesPath(root) if err := os.MkdirAll(sharedVolPath, SharedVolumePerm); err != nil { return "", errwrap.Wrap(errors.New("could not create shared volumes directory"), err) } // In case it already existed and we didn't make it, ensure permissions are // what the caller expects them to be. if err := os.Chmod(sharedVolPath, SharedVolumePerm); err != nil { return "", errwrap.Wrap(fmt.Errorf("could not change permissions of %q", sharedVolPath), err) } return sharedVolPath, nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
common/common.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/common/common.go#L249-L251
go
train
// MetadataServicePublicURL returns the public URL used to host the metadata service
func MetadataServicePublicURL(ip net.IP, token string) string
// MetadataServicePublicURL returns the public URL used to host the metadata service func MetadataServicePublicURL(ip net.IP, token string) string
{ return fmt.Sprintf("http://%v:%v/%v", ip, MetadataServicePort, token) }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
common/common.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/common/common.go#L375-L388
go
train
// LookupPath search for bin in paths. If found, it returns its absolute path, // if not, an error
func LookupPath(bin string, paths string) (string, error)
// LookupPath search for bin in paths. If found, it returns its absolute path, // if not, an error func LookupPath(bin string, paths string) (string, error)
{ pathsArr := filepath.SplitList(paths) for _, path := range pathsArr { binPath := filepath.Join(path, bin) binAbsPath, err := filepath.Abs(binPath) if err != nil { return "", fmt.Errorf("unable to find absolute path for %s", binPath) } if fileutil.IsExecutable(binAbsPath) { return binAbsPath, nil } } return "", fmt.Errorf("unable to find %q in %q", bin, paths) }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
common/common.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/common/common.go#L391-L404
go
train
// SystemdVersion parses and returns the version of a given systemd binary
func SystemdVersion(systemdBinaryPath string) (int, error)
// SystemdVersion parses and returns the version of a given systemd binary func SystemdVersion(systemdBinaryPath string) (int, error)
{ versionBytes, err := exec.Command(systemdBinaryPath, "--version").CombinedOutput() if err != nil { return -1, errwrap.Wrap(fmt.Errorf("unable to probe %s version", systemdBinaryPath), err) } versionStr := strings.SplitN(string(versionBytes), "\n", 2)[0] var version int n, err := fmt.Sscanf(versionStr, "systemd %d", &version) if err != nil || n != 1 { return -1, fmt.Errorf("cannot parse version: %q", versionStr) } return version, nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
common/common.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/common/common.go#L409-L430
go
train
// SupportsOverlay returns whether the operating system generally supports OverlayFS, // returning an instance of ErrOverlayUnsupported which encodes the reason. // It is sufficient to check for nil if the reason is not of interest.
func SupportsOverlay() error
// SupportsOverlay returns whether the operating system generally supports OverlayFS, // returning an instance of ErrOverlayUnsupported which encodes the reason. // It is sufficient to check for nil if the reason is not of interest. func SupportsOverlay() error
{ // ignore exec.Command error, modprobe may not be present on the system, // or the kernel module will fail to load. // we'll find out by reading the side effect in /proc/filesystems _ = exec.Command("modprobe", "overlay").Run() f, err := os.Open("/proc/filesystems") if err != nil { // don't use errwrap so consumers can type-check on ErrOverlayUnsupported return ErrOverlayUnsupported(fmt.Sprintf("cannot open /proc/filesystems: %v", err)) } defer f.Close() s := bufio.NewScanner(f) for s.Scan() { if s.Text() == "nodev\toverlay" { return nil } } return ErrOverlayUnsupported("overlay entry not present in /proc/filesystems") }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
common/common.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/common/common.go#L437-L486
go
train
// PathSupportsOverlay checks whether the given path is compatible with OverlayFS. // This method also calls SupportsOverlay(). // // It returns an instance of ErrOverlayUnsupported if OverlayFS is not supported // or any other error if determining overlay support failed.
func PathSupportsOverlay(path string) error
// PathSupportsOverlay checks whether the given path is compatible with OverlayFS. // This method also calls SupportsOverlay(). // // It returns an instance of ErrOverlayUnsupported if OverlayFS is not supported // or any other error if determining overlay support failed. func PathSupportsOverlay(path string) error
{ if err := SupportsOverlay(); err != nil { // don't wrap since SupportsOverlay already returns ErrOverlayUnsupported return err } var data syscall.Statfs_t if err := syscall.Statfs(path, &data); err != nil { return errwrap.Wrap(fmt.Errorf("cannot statfs %q", path), err) } switch data.Type { case FsMagicAUFS: return ErrOverlayUnsupported("unsupported filesystem: aufs") case FsMagicZFS: return ErrOverlayUnsupported("unsupported filesystem: zfs") } dir, err := os.OpenFile(path, syscall.O_RDONLY|syscall.O_DIRECTORY, 0755) if err != nil { return errwrap.Wrap(fmt.Errorf("cannot open %q", path), err) } defer dir.Close() buf := make([]byte, 4096) // ReadDirent forwards to the raw syscall getdents(3), // passing the buffer size. n, err := syscall.ReadDirent(int(dir.Fd()), buf) if err != nil { return errwrap.Wrap(fmt.Errorf("cannot read directory %q", path), err) } offset := 0 for offset < n { // offset overflow cannot happen, because Reclen // is being maintained by getdents(3), considering the buffer size. dirent := (*syscall.Dirent)(unsafe.Pointer(&buf[offset])) offset += int(dirent.Reclen) if dirent.Ino == 0 { // File absent in directory. continue } if dirent.Type == syscall.DT_UNKNOWN { return ErrOverlayUnsupported("unsupported filesystem: missing d_type support") } } return nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
common/common.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/common/common.go#L490-L500
go
train
// RemoveEmptyLines removes empty lines from the given string // and breaks it up into a list of strings at newline characters
func RemoveEmptyLines(str string) []string
// RemoveEmptyLines removes empty lines from the given string // and breaks it up into a list of strings at newline characters func RemoveEmptyLines(str string) []string
{ lines := make([]string, 0) for _, v := range strings.Split(str, "\n") { if len(v) > 0 { lines = append(lines, v) } } return lines }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
common/common.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/common/common.go#L504-L515
go
train
// GetExitStatus converts an error to an exit status. If it wasn't an exit // status != 0 it returns the same error that it was called with
func GetExitStatus(err error) (int, error)
// GetExitStatus converts an error to an exit status. If it wasn't an exit // status != 0 it returns the same error that it was called with func GetExitStatus(err error) (int, error)
{ if err == nil { return 0, nil } if exiterr, ok := err.(*exec.ExitError); ok { // the program has exited with an exit code != 0 if status, ok := exiterr.Sys().(syscall.WaitStatus); ok { return status.ExitStatus(), nil } } return -1, err }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
common/common.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/common/common.go#L545-L555
go
train
// ImageNameToAppName converts the full name of image to an app name without special // characters - we use it as a default app name when specyfing it is optional
func ImageNameToAppName(name types.ACIdentifier) (*types.ACName, error)
// ImageNameToAppName converts the full name of image to an app name without special // characters - we use it as a default app name when specyfing it is optional func ImageNameToAppName(name types.ACIdentifier) (*types.ACName, error)
{ parts := strings.Split(name.String(), "/") last := parts[len(parts)-1] sn, err := types.SanitizeACName(last) if err != nil { return nil, err } return types.MustACName(sn), nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
stage1/init/kvm/network.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage1/init/kvm/network.go#L32-L38
go
train
// GetNetworkDescriptions converts activeNets to netDescribers
func GetNetworkDescriptions(n *networking.Networking) []NetDescriber
// GetNetworkDescriptions converts activeNets to netDescribers func GetNetworkDescriptions(n *networking.Networking) []NetDescriber
{ var nds []NetDescriber for _, an := range n.GetActiveNetworks() { nds = append(nds, an) } return nds }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
stage1/init/kvm/network.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage1/init/kvm/network.go#L55-L66
go
train
// GetKVMNetArgs 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 GetKVMNetArgs(nds []NetDescriber) ([]string, error)
// GetKVMNetArgs 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 GetKVMNetArgs(nds []NetDescriber) ([]string, error)
{ var lkvmArgs []string for _, nd := range nds { lkvmArgs = append(lkvmArgs, "--network") lkvmArg := fmt.Sprintf("mode=tap,tapif=%s,host_ip=%s,guest_ip=%s", nd.IfName(), nd.Gateway(), nd.GuestIP()) lkvmArgs = append(lkvmArgs, lkvmArg) } return lkvmArgs, nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
stage1/init/kvm/network.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage1/init/kvm/network.go#L70-L83
go
train
// generateMacAddress returns net.HardwareAddr filled with fixed 3 byte prefix // complemented by 3 random bytes.
func generateMacAddress() (net.HardwareAddr, error)
// generateMacAddress returns net.HardwareAddr filled with fixed 3 byte prefix // complemented by 3 random bytes. func generateMacAddress() (net.HardwareAddr, error)
{ mac := []byte{ 2, // locally administered unicast 0x65, 0x02, // OUI (randomly chosen by jell) 0, 0, 0, // bytes to randomly overwrite } _, err := rand.Read(mac[3:6]) if err != nil { return nil, errwrap.Wrap(errors.New("cannot generate random mac address"), err) } return mac, nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
tools/depsgen/util.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/tools/depsgen/util.go#L30-L44
go
train
// toMap creates a map from passed strings. This function expects an // even number of strings, otherwise it will bail out. Odd (first, // third and so on) strings are keys, even (second, fourth and so on) // strings are values.
func toMap(kv ...string) map[string]string
// toMap creates a map from passed strings. This function expects an // even number of strings, otherwise it will bail out. Odd (first, // third and so on) strings are keys, even (second, fourth and so on) // strings are values. func toMap(kv ...string) map[string]string
{ if len(kv)%2 != 0 { common.Die("Expected even number of strings in toMap") } r := make(map[string]string, len(kv)) lastKey := "" for i, kv := range kv { if i%2 == 0 { lastKey = kv } else { r[lastKey] = kv } } return r }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
tools/depsgen/util.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/tools/depsgen/util.go#L54-L59
go
train
// replacePlaceholders replaces placeholders with values in kv in // initial str. Placeholders are in form of !!!FOO!!!, but those // passed here should be without exclamation marks.
func replacePlaceholders(str string, kv ...string) string
// replacePlaceholders replaces placeholders with values in kv in // initial str. Placeholders are in form of !!!FOO!!!, but those // passed here should be without exclamation marks. func replacePlaceholders(str string, kv ...string) string
{ for ph, value := range toMap(kv...) { str = strings.Replace(str, "!!!"+ph+"!!!", value, -1) } return str }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
tools/depsgen/util.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/tools/depsgen/util.go#L62-L66
go
train
// standardFlags returns a new flag set with target flag already set up
func standardFlags(cmd string) (*flag.FlagSet, *string)
// standardFlags returns a new flag set with target flag already set up func standardFlags(cmd string) (*flag.FlagSet, *string)
{ f := flag.NewFlagSet(appName()+" "+cmd, flag.ExitOnError) target := f.String("target", "", "Make target (example: $(FOO_BINARY))") return f, target }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
stage0/enter.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage0/enter.go#L34-L55
go
train
// Enter enters the pod/app by exec()ing the stage1's /enter similar to /init // /enter can expect to have its CWD set to the app root. // appName and command are supplied to /enter on argv followed by any arguments. // stage1Path is the path of the stage1 rootfs
func Enter(cdir string, podPID int, appName types.ACName, stage1Path string, cmdline []string) error
// Enter enters the pod/app by exec()ing the stage1's /enter similar to /init // /enter can expect to have its CWD set to the app root. // appName and command are supplied to /enter on argv followed by any arguments. // stage1Path is the path of the stage1 rootfs func Enter(cdir string, podPID int, appName types.ACName, stage1Path string, cmdline []string) error
{ if err := os.Chdir(cdir); err != nil { return errwrap.Wrap(errors.New("error changing to dir"), err) } ep, err := getStage1Entrypoint(cdir, enterEntrypoint) if err != nil { return errwrap.Wrap(errors.New("error determining 'enter' entrypoint"), err) } argv := []string{filepath.Join(stage1Path, ep)} argv = append(argv, fmt.Sprintf("--pid=%d", podPID)) argv = append(argv, fmt.Sprintf("--appname=%s", appName.String())) argv = append(argv, "--") argv = append(argv, cmdline...) if err := syscall.Exec(argv[0], argv, os.Environ()); err != nil { return errwrap.Wrap(errors.New("error execing enter"), err) } // never reached return nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
networking/net_plugin.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/networking/net_plugin.go#L54-L73
go
train
// Executes a given network plugin. If successful, mutates n.runtime with // the runtime information
func (e *podEnv) netPluginAdd(n *activeNet, netns string) error
// Executes a given network plugin. If successful, mutates n.runtime with // the runtime information func (e *podEnv) netPluginAdd(n *activeNet, netns string) error
{ output, err := e.execNetPlugin("ADD", n, netns) if err != nil { return pluginErr(err, output) } pr := cnitypes.Result{} if err = json.Unmarshal(output, &pr); err != nil { err = errwrap.Wrap(fmt.Errorf("parsing %q", string(output)), err) return errwrap.Wrap(fmt.Errorf("error parsing %q result", n.conf.Name), err) } if pr.IP4 == nil { return nil // TODO(casey) should this be an error? } // All is well - mutate the runtime n.runtime.MergeCNIResult(pr) return nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
rkt/api_service.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/api_service.go#L89-L104
go
train
// copyPod copies the immutable information of the pod into the new pod.
func copyPod(pod *v1alpha.Pod) *v1alpha.Pod
// copyPod copies the immutable information of the pod into the new pod. func copyPod(pod *v1alpha.Pod) *v1alpha.Pod
{ p := &v1alpha.Pod{ Id: pod.Id, Manifest: pod.Manifest, Annotations: pod.Annotations, } for _, app := range pod.Apps { p.Apps = append(p.Apps, &v1alpha.App{ Name: app.Name, Image: app.Image, Annotations: app.Annotations, }) } return p }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
rkt/api_service.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/api_service.go#L107-L119
go
train
// copyImage copies the image object to avoid modification on the original one.
func copyImage(img *v1alpha.Image) *v1alpha.Image
// copyImage copies the image object to avoid modification on the original one. func copyImage(img *v1alpha.Image) *v1alpha.Image
{ return &v1alpha.Image{ BaseFormat: img.BaseFormat, Id: img.Id, Name: img.Name, Version: img.Version, ImportTimestamp: img.ImportTimestamp, Manifest: img.Manifest, Size: img.Size, Annotations: img.Annotations, Labels: img.Labels, } }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
rkt/api_service.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/api_service.go#L154-L170
go
train
// GetInfo returns the information about the rkt, appc, api server version.
func (s *v1AlphaAPIServer) GetInfo(context.Context, *v1alpha.GetInfoRequest) (*v1alpha.GetInfoResponse, error)
// GetInfo returns the information about the rkt, appc, api server version. func (s *v1AlphaAPIServer) GetInfo(context.Context, *v1alpha.GetInfoRequest) (*v1alpha.GetInfoResponse, error)
{ return &v1alpha.GetInfoResponse{ Info: &v1alpha.Info{ RktVersion: version.Version, AppcVersion: schema.AppContainerVersion.String(), ApiVersion: supportedAPIVersion, GlobalFlags: &v1alpha.GlobalFlags{ Dir: getDataDir(), SystemConfigDir: globalFlags.SystemConfigDir, LocalConfigDir: globalFlags.LocalConfigDir, UserConfigDir: globalFlags.UserConfigDir, InsecureFlags: globalFlags.InsecureFlags.String(), TrustKeysFromHttps: globalFlags.TrustKeysFromHTTPS, }, }, }, nil }

Dataset Card for CodeSearchNet for CodeGen

This is a processed version of the CodeSearchNet dataset. Namely, I separated the doc (documentation/docstring), sign (function signature), and output (function body) into separate fields; doc and sign are concatenated (according to the correct order of the programming language) into the problem field, making it suitable for the code generation task.

Dataset Details

Dataset Description

  • Curated by: [More Information Needed]
  • Funded by [optional]: [More Information Needed]
  • Shared by [optional]: [More Information Needed]
  • Language(s) (NLP): code
  • License: apache-2.0

Dataset Sources [optional]

  • Repository: [More Information Needed]
  • Paper [optional]: [More Information Needed]
  • Demo [optional]: [More Information Needed]

Uses

Direct Use

[More Information Needed]

Out-of-Scope Use

[More Information Needed]

Dataset Structure

[More Information Needed]

Dataset Creation

Curation Rationale

[More Information Needed]

Source Data

Data Collection and Processing

During processing of the original dataset, 731 records were ignored due to various reasons:

  • python: no docstring at function begin: 651 cases
  • java: code cutoff at wrong end: 49 cases
  • php: multiple fields/methods: 17 cases
  • ruby: parse error: 7 cases
  • python: mixing spaces and tabs: 4 cases
  • go: no method body: 1 cases
  • php: code cutoff at wrong end: 1 cases
  • php: no method body: 1 cases

Who are the source data producers?

[More Information Needed]

Annotations [optional]

Annotation process

[More Information Needed]

Who are the annotators?

[More Information Needed]

Personal and Sensitive Information

[More Information Needed]

Bias, Risks, and Limitations

[More Information Needed]

Recommendations

Users should be made aware of the risks, biases and limitations of the dataset. More information needed for further recommendations.

Citation [optional]

BibTeX:

[More Information Needed]

APA:

[More Information Needed]

Glossary [optional]

[More Information Needed]

More Information [optional]

[More Information Needed]

Dataset Card Authors [optional]

Pengyu Nie [email protected]

Dataset Card Contact

[More Information Needed]

Downloads last month
59
Edit dataset card