repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
sequence
docstring
stringlengths
6
2.61k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
85
252
partition
stringclasses
1 value
rkt/rkt
tools/depsgen/main.go
getAllDepTypes
func getAllDepTypes() []string { depTypes := make([]string, 0, len(cmds)) for depType := range cmds { depTypes = append(depTypes, depType) } sort.Strings(depTypes) return depTypes }
go
func getAllDepTypes() []string { depTypes := make([]string, 0, len(cmds)) for depType := range cmds { depTypes = append(depTypes, depType) } sort.Strings(depTypes) return depTypes }
[ "func", "getAllDepTypes", "(", ")", "[", "]", "string", "{", "depTypes", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "len", "(", "cmds", ")", ")", "\n", "for", "depType", ":=", "range", "cmds", "{", "depTypes", "=", "append", "(", "depTypes", ",", "depType", ")", "\n", "}", "\n", "sort", ".", "Strings", "(", "depTypes", ")", "\n", "return", "depTypes", "\n", "}" ]
// getAllDepTypes returns a sorted list of names of all dep type // commands.
[ "getAllDepTypes", "returns", "a", "sorted", "list", "of", "names", "of", "all", "dep", "type", "commands", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/tools/depsgen/main.go#L47-L54
train
rkt/rkt
rkt/image/io.go
getIoProgressReader
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, } }
go
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, } }
[ "func", "getIoProgressReader", "(", "label", "string", ",", "res", "*", "http", ".", "Response", ")", "io", ".", "Reader", "{", "prefix", ":=", "\"Downloading \"", "+", "label", "\n", "fmtBytesSize", ":=", "18", "\n", "barSize", ":=", "int64", "(", "80", "-", "len", "(", "prefix", ")", "-", "fmtBytesSize", ")", "\n", "bar", ":=", "ioprogress", ".", "DrawTextFormatBarForW", "(", "barSize", ",", "os", ".", "Stderr", ")", "\n", "fmtfunc", ":=", "func", "(", "progress", ",", "total", "int64", ")", "string", "{", "if", "total", "==", "-", "1", "{", "return", "fmt", ".", "Sprintf", "(", "\"%s: %v of an unknown total size\"", ",", "prefix", ",", "ioprogress", ".", "ByteUnitStr", "(", "progress", ")", ",", ")", "\n", "}", "\n", "return", "fmt", ".", "Sprintf", "(", "\"%s: %s %s\"", ",", "prefix", ",", "bar", "(", "progress", ",", "total", ")", ",", "ioprogress", ".", "DrawTextFormatBytes", "(", "progress", ",", "total", ")", ",", ")", "\n", "}", "\n", "return", "&", "ioprogress", ".", "Reader", "{", "Reader", ":", "res", ".", "Body", ",", "Size", ":", "res", ".", "ContentLength", ",", "DrawFunc", ":", "ioprogress", ".", "DrawTerminalf", "(", "os", ".", "Stderr", ",", "fmtfunc", ")", ",", "DrawInterval", ":", "time", ".", "Second", ",", "}", "\n", "}" ]
// getIoProgressReader returns a reader that wraps the HTTP response // body, so it prints a pretty progress bar when reading data from it.
[ "getIoProgressReader", "returns", "a", "reader", "that", "wraps", "the", "HTTP", "response", "body", "so", "it", "prints", "a", "pretty", "progress", "bar", "when", "reading", "data", "from", "it", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/image/io.go#L60-L87
train
rkt/rkt
rkt/image/io.go
Close
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 }
go
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 }
[ "func", "(", "f", "*", "removeOnClose", ")", "Close", "(", ")", "error", "{", "if", "f", "==", "nil", "||", "f", ".", "File", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "name", ":=", "f", ".", "File", ".", "Name", "(", ")", "\n", "if", "err", ":=", "f", ".", "File", ".", "Close", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "os", ".", "Remove", "(", "name", ")", ";", "err", "!=", "nil", "&&", "!", "os", ".", "IsNotExist", "(", "err", ")", "{", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// 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.
[ "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", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/image/io.go#L107-L119
train
rkt/rkt
rkt/image/io.go
getTmpROC
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 }
go
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 }
[ "func", "getTmpROC", "(", "s", "*", "imagestore", ".", "Store", ",", "path", "string", ")", "(", "*", "removeOnClose", ",", "error", ")", "{", "h", ":=", "sha512", ".", "New", "(", ")", "\n", "h", ".", "Write", "(", "[", "]", "byte", "(", "path", ")", ")", "\n", "pathHash", ":=", "s", ".", "HashToKey", "(", "h", ")", "\n", "tmp", ",", "err", ":=", "s", ".", "TmpNamedFile", "(", "pathHash", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"error setting up temporary file\"", ")", ",", "err", ")", "\n", "}", "\n", "_", ",", "err", "=", "lock", ".", "TryExclusiveLock", "(", "tmp", ".", "Name", "(", ")", ",", "lock", ".", "RegFile", ")", "\n", "if", "err", "!=", "nil", "{", "if", "err", "!=", "lock", ".", "ErrLocked", "{", "return", "nil", ",", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"failed to lock temporary file\"", ")", ",", "err", ")", "\n", "}", "\n", "log", ".", "Printf", "(", "\"another rkt instance is downloading this file, waiting...\"", ")", "\n", "_", ",", "err", "=", "lock", ".", "ExclusiveLock", "(", "tmp", ".", "Name", "(", ")", ",", "lock", ".", "RegFile", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"failed to lock temporary file\"", ")", ",", "err", ")", "\n", "}", "\n", "}", "\n", "return", "&", "removeOnClose", "{", "File", ":", "tmp", "}", ",", "nil", "\n", "}" ]
// 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.
[ "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", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/image/io.go#L124-L149
train
rkt/rkt
stage0/manifest.go
getStage1Entrypoint
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) }
go
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) }
[ "func", "getStage1Entrypoint", "(", "cdir", "string", ",", "entrypoint", "string", ")", "(", "string", ",", "error", ")", "{", "b", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "common", ".", "Stage1ManifestPath", "(", "cdir", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"\"", ",", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"error reading pod manifest\"", ")", ",", "err", ")", "\n", "}", "\n", "s1m", ":=", "schema", ".", "ImageManifest", "{", "}", "\n", "if", "err", ":=", "json", ".", "Unmarshal", "(", "b", ",", "&", "s1m", ")", ";", "err", "!=", "nil", "{", "return", "\"\"", ",", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"error unmarshaling stage1 manifest\"", ")", ",", "err", ")", "\n", "}", "\n", "if", "ep", ",", "ok", ":=", "s1m", ".", "Annotations", ".", "Get", "(", "entrypoint", ")", ";", "ok", "{", "return", "ep", ",", "nil", "\n", "}", "\n", "return", "\"\"", ",", "fmt", ".", "Errorf", "(", "\"entrypoint %q not found\"", ",", "entrypoint", ")", "\n", "}" ]
// getStage1Entrypoint retrieves the named entrypoint from the stage1 manifest for a given pod
[ "getStage1Entrypoint", "retrieves", "the", "named", "entrypoint", "from", "the", "stage1", "manifest", "for", "a", "given", "pod" ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage0/manifest.go#L69-L85
train
rkt/rkt
stage0/manifest.go
getStage1InterfaceVersion
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 }
go
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 }
[ "func", "getStage1InterfaceVersion", "(", "cdir", "string", ")", "(", "int", ",", "error", ")", "{", "b", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "common", ".", "Stage1ManifestPath", "(", "cdir", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "-", "1", ",", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"error reading pod manifest\"", ")", ",", "err", ")", "\n", "}", "\n", "s1m", ":=", "schema", ".", "ImageManifest", "{", "}", "\n", "if", "err", ":=", "json", ".", "Unmarshal", "(", "b", ",", "&", "s1m", ")", ";", "err", "!=", "nil", "{", "return", "-", "1", ",", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"error unmarshaling stage1 manifest\"", ")", ",", "err", ")", "\n", "}", "\n", "if", "iv", ",", "ok", ":=", "s1m", ".", "Annotations", ".", "Get", "(", "interfaceVersion", ")", ";", "ok", "{", "v", ",", "err", ":=", "strconv", ".", "Atoi", "(", "iv", ")", "\n", "if", "err", "!=", "nil", "{", "return", "-", "1", ",", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"error parsing interface version\"", ")", ",", "err", ")", "\n", "}", "\n", "return", "v", ",", "nil", "\n", "}", "\n", "return", "1", ",", "nil", "\n", "}" ]
// getStage1InterfaceVersion retrieves the interface version from the stage1 // manifest for a given pod
[ "getStage1InterfaceVersion", "retrieves", "the", "interface", "version", "from", "the", "stage1", "manifest", "for", "a", "given", "pod" ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage0/manifest.go#L89-L110
train
rkt/rkt
networking/podenv.go
loadNets
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 }
go
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 }
[ "func", "(", "e", "*", "podEnv", ")", "loadNets", "(", ")", "(", "[", "]", "activeNet", ",", "error", ")", "{", "if", "e", ".", "netsLoadList", ".", "None", "(", ")", "{", "stderr", ".", "Printf", "(", "\"networking namespace with loopback only\"", ")", "\n", "return", "nil", ",", "nil", "\n", "}", "\n", "nets", ",", "err", ":=", "e", ".", "newNetLoader", "(", ")", ".", "loadNets", "(", "e", ".", "netsLoadList", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "netSlice", ":=", "make", "(", "[", "]", "activeNet", ",", "0", ",", "len", "(", "nets", ")", ")", "\n", "for", "_", ",", "net", ":=", "range", "nets", "{", "netSlice", "=", "append", "(", "netSlice", ",", "net", ")", "\n", "}", "\n", "sort", ".", "Sort", "(", "byFilename", "(", "netSlice", ")", ")", "\n", "missing", ":=", "missingNets", "(", "e", ".", "netsLoadList", ",", "netSlice", ")", "\n", "if", "len", "(", "missing", ")", ">", "0", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"networks not found: %v\"", ",", "strings", ".", "Join", "(", "missing", ",", "\", \"", ")", ")", "\n", "}", "\n", "for", "_", ",", "n", ":=", "range", "nets", "{", "n", ".", "runtime", ".", "Args", "=", "e", ".", "netsLoadList", ".", "SpecificArgs", "(", "n", ".", "conf", ".", "Name", ")", "\n", "}", "\n", "return", "netSlice", ",", "nil", "\n", "}" ]
// 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.
[ "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", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/networking/podenv.go#L75-L102
train
rkt/rkt
stage1/init/common/app.go
prepareApp
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 }
go
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 }
[ "func", "prepareApp", "(", "p", "*", "stage1commontypes", ".", "Pod", ",", "ra", "*", "schema", ".", "RuntimeApp", ")", "(", "*", "preparedApp", ",", "error", ")", "{", "pa", ":=", "preparedApp", "{", "app", ":", "ra", ",", "env", ":", "ra", ".", "App", ".", "Environment", ",", "noNewPrivileges", ":", "getAppNoNewPrivileges", "(", "ra", ".", "App", ".", "Isolators", ")", ",", "}", "\n", "var", "err", "error", "\n", "u", ",", "g", ",", "err", ":=", "ParseUserGroup", "(", "p", ",", "ra", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"unable to determine app's uid and gid\"", ")", ",", "err", ")", "\n", "}", "\n", "if", "u", "<", "0", "||", "g", "<", "0", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"Invalid uid or gid\"", ")", "\n", "}", "\n", "pa", ".", "uid", "=", "uint32", "(", "u", ")", "\n", "pa", ".", "gid", "=", "uint32", "(", "g", ")", "\n", "pa", ".", "env", ".", "Set", "(", "\"AC_APP_NAME\"", ",", "ra", ".", "Name", ".", "String", "(", ")", ")", "\n", "if", "p", ".", "MetadataServiceURL", "!=", "\"\"", "{", "pa", ".", "env", ".", "Set", "(", "\"AC_METADATA_URL\"", ",", "p", ".", "MetadataServiceURL", ")", "\n", "}", "\n", "pa", ".", "capabilities", ",", "err", "=", "getAppCapabilities", "(", "ra", ".", "App", ".", "Isolators", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"unable to construct capabilities\"", ")", ",", "err", ")", "\n", "}", "\n", "cfd", ":=", "ConvertedFromDocker", "(", "p", ".", "Images", "[", "ra", ".", "Name", ".", "String", "(", ")", "]", ")", "\n", "pa", ".", "mounts", ",", "err", "=", "GenerateMounts", "(", "ra", ",", "p", ".", "Manifest", ".", "Volumes", ",", "cfd", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"unable to compute mounts\"", ")", ",", "err", ")", "\n", "}", "\n", "pa", ".", "resources", ",", "err", "=", "computeAppResources", "(", "ra", ".", "App", ".", "Isolators", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"unable to compute resources\"", ")", ",", "err", ")", "\n", "}", "\n", "if", "!", "p", ".", "InsecureOptions", ".", "DisablePaths", "{", "pa", ".", "roPaths", "=", "append", "(", "pa", ".", "roPaths", ",", "protectKernelROPaths", "...", ")", "\n", "pa", ".", "hiddenPaths", "=", "append", "(", "pa", ".", "hiddenDirs", ",", "protectKernelHiddenPaths", "...", ")", "\n", "pa", ".", "hiddenDirs", "=", "append", "(", "pa", ".", "hiddenDirs", ",", "protectKernelHiddenDirs", "...", ")", "\n", "}", "\n", "if", "!", "p", ".", "InsecureOptions", ".", "DisableSeccomp", "{", "pa", ".", "seccomp", ",", "err", "=", "generateSeccompFilter", "(", "p", ",", "&", "pa", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "pa", ".", "seccomp", "!=", "nil", "&&", "pa", ".", "seccomp", ".", "forceNoNewPrivileges", "{", "pa", ".", "noNewPrivileges", "=", "true", "\n", "}", "\n", "}", "\n", "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", ")", "\n", "}", "\n", "return", "&", "pa", ",", "nil", "\n", "}" ]
// prepareApp sets up the internal runtime context for a specific app.
[ "prepareApp", "sets", "up", "the", "internal", "runtime", "context", "for", "a", "specific", "app", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage1/init/common/app.go#L98-L166
train
rkt/rkt
stage1/init/common/app.go
computeAppResources
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 }
go
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 }
[ "func", "computeAppResources", "(", "isolators", "types", ".", "Isolators", ")", "(", "appResources", ",", "error", ")", "{", "res", ":=", "appResources", "{", "}", "\n", "var", "err", "error", "\n", "withIsolator", ":=", "func", "(", "name", "string", ",", "f", "func", "(", ")", "error", ")", "error", "{", "ok", ",", "err", ":=", "cgroup", ".", "IsIsolatorSupported", "(", "name", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errwrap", ".", "Wrapf", "(", "\"could not check for isolator \"", "+", "name", ",", "err", ")", "\n", "}", "\n", "if", "!", "ok", "{", "fmt", ".", "Fprintf", "(", "os", ".", "Stderr", ",", "\"warning: resource/%s isolator set but support disabled in the kernel, skipping\\n\"", ",", "\\n", ")", "\n", "name", "\n", "}", "\n", "return", "nil", "\n", "}", "\n", "return", "f", "(", ")", "\n", "for", "_", ",", "isolator", ":=", "range", "isolators", "{", "if", "err", "!=", "nil", "{", "return", "res", ",", "err", "\n", "}", "\n", "switch", "v", ":=", "isolator", ".", "Value", "(", ")", ".", "(", "type", ")", "{", "case", "*", "types", ".", "ResourceMemory", ":", "err", "=", "withIsolator", "(", "\"memory\"", ",", "func", "(", ")", "error", "{", "if", "v", ".", "Limit", "(", ")", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "val", ":=", "uint64", "(", "v", ".", "Limit", "(", ")", ".", "Value", "(", ")", ")", "\n", "res", ".", "MemoryLimit", "=", "&", "val", "\n", "return", "nil", "\n", "}", ")", "\n", "case", "*", "types", ".", "ResourceCPU", ":", "err", "=", "withIsolator", "(", "\"cpu\"", ",", "func", "(", ")", "error", "{", "if", "v", ".", "Limit", "(", ")", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "if", "v", ".", "Limit", "(", ")", ".", "Value", "(", ")", ">", "MaxMilliValue", "{", "return", "fmt", ".", "Errorf", "(", "\"cpu limit exceeds the maximum millivalue: %v\"", ",", "v", ".", "Limit", "(", ")", ".", "String", "(", ")", ")", "\n", "}", "\n", "val", ":=", "uint64", "(", "v", ".", "Limit", "(", ")", ".", "MilliValue", "(", ")", "/", "10", ")", "\n", "res", ".", "CPUQuota", "=", "&", "val", "\n", "return", "nil", "\n", "}", ")", "\n", "case", "*", "types", ".", "LinuxCPUShares", ":", "err", "=", "withIsolator", "(", "\"cpu\"", ",", "func", "(", ")", "error", "{", "val", ":=", "uint64", "(", "*", "v", ")", "\n", "res", ".", "LinuxCPUShares", "=", "&", "val", "\n", "return", "nil", "\n", "}", ")", "\n", "case", "*", "types", ".", "LinuxOOMScoreAdj", ":", "val", ":=", "int", "(", "*", "v", ")", "\n", "res", ".", "LinuxOOMScoreAdjust", "=", "&", "val", "\n", "}", "\n", "}", "\n", "}" ]
// computeAppResources processes any isolators that manipulate cgroups.
[ "computeAppResources", "processes", "any", "isolators", "that", "manipulate", "cgroups", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage1/init/common/app.go#L169-L229
train
rkt/rkt
store/imagestore/aciinfo.go
GetACIInfosWithKeyPrefix
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 }
go
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 }
[ "func", "GetACIInfosWithKeyPrefix", "(", "tx", "*", "sql", ".", "Tx", ",", "prefix", "string", ")", "(", "[", "]", "*", "ACIInfo", ",", "error", ")", "{", "var", "aciinfos", "[", "]", "*", "ACIInfo", "\n", "rows", ",", "err", ":=", "tx", ".", "Query", "(", "\"SELECT * from aciinfo WHERE hasPrefix(blobkey, $1)\"", ",", "prefix", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "defer", "rows", ".", "Close", "(", ")", "\n", "for", "rows", ".", "Next", "(", ")", "{", "aciinfo", ":=", "&", "ACIInfo", "{", "}", "\n", "if", "err", ":=", "aciinfoRowScan", "(", "rows", ",", "aciinfo", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "aciinfos", "=", "append", "(", "aciinfos", ",", "aciinfo", ")", "\n", "}", "\n", "if", "err", ":=", "rows", ".", "Err", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "aciinfos", ",", "err", "\n", "}" ]
// GetAciInfosWithKeyPrefix returns all the ACIInfos with a blobkey starting with the given prefix.
[ "GetAciInfosWithKeyPrefix", "returns", "all", "the", "ACIInfos", "with", "a", "blobkey", "starting", "with", "the", "given", "prefix", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/store/imagestore/aciinfo.go#L68-L86
train
rkt/rkt
store/imagestore/aciinfo.go
GetACIInfosWithName
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 }
go
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 }
[ "func", "GetACIInfosWithName", "(", "tx", "*", "sql", ".", "Tx", ",", "name", "string", ")", "(", "[", "]", "*", "ACIInfo", ",", "bool", ",", "error", ")", "{", "var", "aciinfos", "[", "]", "*", "ACIInfo", "\n", "found", ":=", "false", "\n", "rows", ",", "err", ":=", "tx", ".", "Query", "(", "\"SELECT * from aciinfo WHERE name == $1\"", ",", "name", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "false", ",", "err", "\n", "}", "\n", "defer", "rows", ".", "Close", "(", ")", "\n", "for", "rows", ".", "Next", "(", ")", "{", "found", "=", "true", "\n", "aciinfo", ":=", "&", "ACIInfo", "{", "}", "\n", "if", "err", ":=", "aciinfoRowScan", "(", "rows", ",", "aciinfo", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "false", ",", "err", "\n", "}", "\n", "aciinfos", "=", "append", "(", "aciinfos", ",", "aciinfo", ")", "\n", "}", "\n", "if", "err", ":=", "rows", ".", "Err", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "false", ",", "err", "\n", "}", "\n", "return", "aciinfos", ",", "found", ",", "err", "\n", "}" ]
// GetAciInfosWithName returns all the ACIInfos for a given name. found will be // false if no aciinfo exists.
[ "GetAciInfosWithName", "returns", "all", "the", "ACIInfos", "for", "a", "given", "name", ".", "found", "will", "be", "false", "if", "no", "aciinfo", "exists", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/store/imagestore/aciinfo.go#L90-L110
train
rkt/rkt
store/imagestore/aciinfo.go
GetACIInfoWithBlobKey
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 }
go
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 }
[ "func", "GetACIInfoWithBlobKey", "(", "tx", "*", "sql", ".", "Tx", ",", "blobKey", "string", ")", "(", "*", "ACIInfo", ",", "bool", ",", "error", ")", "{", "aciinfo", ":=", "&", "ACIInfo", "{", "}", "\n", "found", ":=", "false", "\n", "rows", ",", "err", ":=", "tx", ".", "Query", "(", "\"SELECT * from aciinfo WHERE blobkey == $1\"", ",", "blobKey", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "false", ",", "err", "\n", "}", "\n", "defer", "rows", ".", "Close", "(", ")", "\n", "for", "rows", ".", "Next", "(", ")", "{", "found", "=", "true", "\n", "if", "err", ":=", "aciinfoRowScan", "(", "rows", ",", "aciinfo", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "false", ",", "err", "\n", "}", "\n", "break", "\n", "}", "\n", "if", "err", ":=", "rows", ".", "Err", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "false", ",", "err", "\n", "}", "\n", "return", "aciinfo", ",", "found", ",", "err", "\n", "}" ]
// GetAciInfosWithBlobKey returns the ACIInfo with the given blobKey. found will be // false if no aciinfo exists.
[ "GetAciInfosWithBlobKey", "returns", "the", "ACIInfo", "with", "the", "given", "blobKey", ".", "found", "will", "be", "false", "if", "no", "aciinfo", "exists", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/store/imagestore/aciinfo.go#L114-L134
train
rkt/rkt
store/imagestore/aciinfo.go
GetAllACIInfos
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 }
go
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 }
[ "func", "GetAllACIInfos", "(", "tx", "*", "sql", ".", "Tx", ",", "sortfields", "[", "]", "string", ",", "ascending", "bool", ")", "(", "[", "]", "*", "ACIInfo", ",", "error", ")", "{", "var", "aciinfos", "[", "]", "*", "ACIInfo", "\n", "query", ":=", "\"SELECT * from aciinfo\"", "\n", "if", "len", "(", "sortfields", ")", ">", "0", "{", "query", "+=", "fmt", ".", "Sprintf", "(", "\" ORDER BY %s \"", ",", "strings", ".", "Join", "(", "sortfields", ",", "\", \"", ")", ")", "\n", "if", "ascending", "{", "query", "+=", "\"ASC\"", "\n", "}", "else", "{", "query", "+=", "\"DESC\"", "\n", "}", "\n", "}", "\n", "rows", ",", "err", ":=", "tx", ".", "Query", "(", "query", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "defer", "rows", ".", "Close", "(", ")", "\n", "for", "rows", ".", "Next", "(", ")", "{", "aciinfo", ":=", "&", "ACIInfo", "{", "}", "\n", "if", "err", ":=", "aciinfoRowScan", "(", "rows", ",", "aciinfo", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "aciinfos", "=", "append", "(", "aciinfos", ",", "aciinfo", ")", "\n", "}", "\n", "if", "err", ":=", "rows", ".", "Err", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "aciinfos", ",", "err", "\n", "}" ]
// GetAllACIInfos returns all the ACIInfos sorted by optional sortfields and // with ascending or descending order.
[ "GetAllACIInfos", "returns", "all", "the", "ACIInfos", "sorted", "by", "optional", "sortfields", "and", "with", "ascending", "or", "descending", "order", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/store/imagestore/aciinfo.go#L138-L165
train
rkt/rkt
store/imagestore/aciinfo.go
WriteACIInfo
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 }
go
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 }
[ "func", "WriteACIInfo", "(", "tx", "*", "sql", ".", "Tx", ",", "aciinfo", "*", "ACIInfo", ")", "error", "{", "_", ",", "err", ":=", "tx", ".", "Exec", "(", "\"DELETE from aciinfo where blobkey == $1\"", ",", "aciinfo", ".", "BlobKey", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "_", ",", "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", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// WriteACIInfo adds or updates the provided aciinfo.
[ "WriteACIInfo", "adds", "or", "updates", "the", "provided", "aciinfo", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/store/imagestore/aciinfo.go#L168-L181
train
rkt/rkt
stage1/init/kvm/hypervisor/hvqemu/qemu_driver.go
StartCmd
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)...) }
go
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)...) }
[ "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\"", ",", "}", ",", "}", "\n", ")", "\n", "driverConfiguration", ".", "InitKernelParams", "(", "debug", ")", "\n", "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\"", ",", "}", "\n", "return", "append", "(", "cmd", ",", "kvmNetArgs", "(", "nds", ")", "...", ")", "\n", "}" ]
// 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
[ "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" ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage1/init/kvm/hypervisor/hvqemu/qemu_driver.go#L29-L63
train
rkt/rkt
stage1/init/kvm/hypervisor/hvqemu/qemu_driver.go
kvmNetArgs
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 }
go
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 }
[ "func", "kvmNetArgs", "(", "nds", "[", "]", "kvm", ".", "NetDescriber", ")", "[", "]", "string", "{", "var", "qemuArgs", "[", "]", "string", "\n", "for", "_", ",", "nd", ":=", "range", "nds", "{", "qemuArgs", "=", "append", "(", "qemuArgs", ",", "[", "]", "string", "{", "\"-net\"", ",", "\"nic,model=virtio\"", "}", "...", ")", "\n", "qemuNic", ":=", "fmt", ".", "Sprintf", "(", "\"tap,ifname=%s,script=no,downscript=no,vhost=on\"", ",", "nd", ".", "IfName", "(", ")", ")", "\n", "qemuArgs", "=", "append", "(", "qemuArgs", ",", "[", "]", "string", "{", "\"-net\"", ",", "qemuNic", "}", "...", ")", "\n", "}", "\n", "return", "qemuArgs", "\n", "}" ]
// 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
[ "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" ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage1/init/kvm/hypervisor/hvqemu/qemu_driver.go#L69-L79
train
rkt/rkt
stage1/init/kvm/hypervisor/hypervisor.go
InitKernelParams
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) } }
go
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) } }
[ "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\"", "}", "...", ")", "\n", "if", "isDebug", "{", "hv", ".", "KernelParams", "=", "append", "(", "hv", ".", "KernelParams", ",", "[", "]", "string", "{", "\"debug\"", ",", "\"systemd.log_level=debug\"", ",", "\"systemd.show_status=true\"", ",", "}", "...", ")", "\n", "}", "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\"", ",", "}", "...", ")", "\n", "}", "\n", "customKernelParams", ":=", "os", ".", "Getenv", "(", "\"RKT_HYPERVISOR_EXTRA_KERNEL_PARAMS\"", ")", "\n", "if", "customKernelParams", "!=", "\"\"", "{", "hv", ".", "KernelParams", "=", "append", "(", "hv", ".", "KernelParams", ",", "customKernelParams", ")", "\n", "}", "\n", "}" ]
// InitKernelParams sets debug and common parameters passed to the kernel
[ "InitKernelParams", "sets", "debug", "and", "common", "parameters", "passed", "to", "the", "kernel" ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage1/init/kvm/hypervisor/hypervisor.go#L26-L54
train
rkt/rkt
rkt/image/dockerfetcher.go
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) }
go
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) }
[ "func", "(", "f", "*", "dockerFetcher", ")", "Hash", "(", "u", "*", "url", ".", "URL", ")", "(", "string", ",", "error", ")", "{", "ensureLogger", "(", "f", ".", "Debug", ")", "\n", "dockerURL", ",", "err", ":=", "d2acommon", ".", "ParseDockerURL", "(", "path", ".", "Join", "(", "u", ".", "Host", ",", "u", ".", "Path", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"\"", ",", "fmt", ".", "Errorf", "(", "`invalid docker URL %q; expected syntax is \"docker://[REGISTRY_HOST[:REGISTRY_PORT]/]IMAGE_NAME[:TAG]\"`", ",", "u", ")", "\n", "}", "\n", "latest", ":=", "dockerURL", ".", "Tag", "==", "\"latest\"", "\n", "return", "f", ".", "fetchImageFrom", "(", "u", ",", "latest", ")", "\n", "}" ]
// Hash uses docker2aci to download the image and convert it to // ACI, then stores it in the store and returns the hash.
[ "Hash", "uses", "docker2aci", "to", "download", "the", "image", "and", "convert", "it", "to", "ACI", "then", "stores", "it", "in", "the", "store", "and", "returns", "the", "hash", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/image/dockerfetcher.go#L51-L59
train
rkt/rkt
stage0/registration.go
registerPod
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 }
go
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 }
[ "func", "registerPod", "(", "root", "string", ",", "uuid", "*", "types", ".", "UUID", ",", "apps", "schema", ".", "AppList", ")", "(", "token", "string", ",", "rerr", "error", ")", "{", "u", ":=", "uuid", ".", "String", "(", ")", "\n", "var", "err", "error", "\n", "token", ",", "err", "=", "generateMDSToken", "(", ")", "\n", "if", "err", "!=", "nil", "{", "rerr", "=", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"failed to generate MDS token\"", ")", ",", "err", ")", "\n", "return", "\n", "}", "\n", "pmfPath", ":=", "common", ".", "PodManifestPath", "(", "root", ")", "\n", "pmf", ",", "err", ":=", "os", ".", "Open", "(", "pmfPath", ")", "\n", "if", "err", "!=", "nil", "{", "rerr", "=", "errwrap", ".", "Wrap", "(", "fmt", ".", "Errorf", "(", "\"failed to open runtime manifest (%v)\"", ",", "pmfPath", ")", ",", "err", ")", "\n", "return", "\n", "}", "\n", "pth", ":=", "fmt", ".", "Sprintf", "(", "\"/pods/%v?token=%v\"", ",", "u", ",", "token", ")", "\n", "err", "=", "httpRequest", "(", "\"PUT\"", ",", "pth", ",", "pmf", ")", "\n", "pmf", ".", "Close", "(", ")", "\n", "if", "err", "!=", "nil", "{", "rerr", "=", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"failed to register pod with metadata svc\"", ")", ",", "err", ")", "\n", "return", "\n", "}", "\n", "defer", "func", "(", ")", "{", "if", "rerr", "!=", "nil", "{", "unregisterPod", "(", "root", ",", "uuid", ")", "\n", "}", "\n", "}", "(", ")", "\n", "rf", ",", "err", ":=", "os", ".", "Create", "(", "filepath", ".", "Join", "(", "root", ",", "mdsRegisteredFile", ")", ")", "\n", "if", "err", "!=", "nil", "{", "rerr", "=", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"failed to create mds-register file\"", ")", ",", "err", ")", "\n", "return", "\n", "}", "\n", "rf", ".", "Close", "(", ")", "\n", "for", "_", ",", "app", ":=", "range", "apps", "{", "ampath", ":=", "common", ".", "ImageManifestPath", "(", "root", ",", "app", ".", "Name", ")", "\n", "amf", ",", "err", ":=", "os", ".", "Open", "(", "ampath", ")", "\n", "if", "err", "!=", "nil", "{", "rerr", "=", "errwrap", ".", "Wrap", "(", "fmt", ".", "Errorf", "(", "\"failed reading app manifest %q\"", ",", "ampath", ")", ",", "err", ")", "\n", "return", "\n", "}", "\n", "err", "=", "registerApp", "(", "u", ",", "app", ".", "Name", ".", "String", "(", ")", ",", "amf", ")", "\n", "amf", ".", "Close", "(", ")", "\n", "if", "err", "!=", "nil", "{", "rerr", "=", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"failed to register app with metadata svc\"", ")", ",", "err", ")", "\n", "return", "\n", "}", "\n", "}", "\n", "return", "\n", "}" ]
// registerPod registers pod with metadata service. // Returns authentication token to be passed in the URL
[ "registerPod", "registers", "pod", "with", "metadata", "service", ".", "Returns", "authentication", "token", "to", "be", "passed", "in", "the", "URL" ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage0/registration.go#L54-L109
train
rkt/rkt
stage0/registration.go
unregisterPod
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 } }
go
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 } }
[ "func", "unregisterPod", "(", "root", "string", ",", "uuid", "*", "types", ".", "UUID", ")", "error", "{", "_", ",", "err", ":=", "os", ".", "Stat", "(", "filepath", ".", "Join", "(", "root", ",", "mdsRegisteredFile", ")", ")", "\n", "switch", "{", "case", "err", "==", "nil", ":", "pth", ":=", "path", ".", "Join", "(", "\"/pods\"", ",", "uuid", ".", "String", "(", ")", ")", "\n", "return", "httpRequest", "(", "\"DELETE\"", ",", "pth", ",", "nil", ")", "\n", "case", "os", ".", "IsNotExist", "(", "err", ")", ":", "return", "nil", "\n", "default", ":", "return", "err", "\n", "}", "\n", "}" ]
// unregisterPod unregisters pod with the metadata service.
[ "unregisterPod", "unregisters", "pod", "with", "the", "metadata", "service", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage0/registration.go#L112-L125
train
rkt/rkt
stage0/registration.go
CheckMdsAvailability
func CheckMdsAvailability() error { if conn, err := net.Dial("unix", common.MetadataServiceRegSock); err != nil { return errUnreachable } else { conn.Close() return nil } }
go
func CheckMdsAvailability() error { if conn, err := net.Dial("unix", common.MetadataServiceRegSock); err != nil { return errUnreachable } else { conn.Close() return nil } }
[ "func", "CheckMdsAvailability", "(", ")", "error", "{", "if", "conn", ",", "err", ":=", "net", ".", "Dial", "(", "\"unix\"", ",", "common", ".", "MetadataServiceRegSock", ")", ";", "err", "!=", "nil", "{", "return", "errUnreachable", "\n", "}", "else", "{", "conn", ".", "Close", "(", ")", "\n", "return", "nil", "\n", "}", "\n", "}" ]
// CheckMdsAvailability checks whether a local metadata service can be reached.
[ "CheckMdsAvailability", "checks", "whether", "a", "local", "metadata", "service", "can", "be", "reached", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage0/registration.go#L196-L203
train
rkt/rkt
networking/netinfo/netinfo.go
MergeCNIResult
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 }
go
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 }
[ "func", "(", "ni", "*", "NetInfo", ")", "MergeCNIResult", "(", "result", "types", ".", "Result", ")", "{", "ni", ".", "IP", "=", "result", ".", "IP4", ".", "IP", ".", "IP", "\n", "ni", ".", "Mask", "=", "net", ".", "IP", "(", "result", ".", "IP4", ".", "IP", ".", "Mask", ")", "\n", "ni", ".", "HostIP", "=", "result", ".", "IP4", ".", "Gateway", "\n", "ni", ".", "IP4", "=", "result", ".", "IP4", "\n", "ni", ".", "DNS", "=", "result", ".", "DNS", "\n", "}" ]
// MergeCNIResult will incorporate the result of a CNI plugin's execution
[ "MergeCNIResult", "will", "incorporate", "the", "result", "of", "a", "CNI", "plugin", "s", "execution" ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/networking/netinfo/netinfo.go#L74-L80
train
rkt/rkt
pkg/multicall/multicall.go
Add
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) }
go
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) }
[ "func", "Add", "(", "name", "string", ",", "fn", "commandFn", ")", "Entrypoint", "{", "if", "_", ",", "ok", ":=", "commands", "[", "name", "]", ";", "ok", "{", "panic", "(", "fmt", ".", "Errorf", "(", "\"command with name %q already exists\"", ",", "name", ")", ")", "\n", "}", "\n", "commands", "[", "name", "]", "=", "fn", "\n", "return", "Entrypoint", "(", "name", ")", "\n", "}" ]
// 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.
[ "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", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/multicall/multicall.go#L52-L58
train
rkt/rkt
rkt/stage1hash.go
addStage1ImageFlags
func addStage1ImageFlags(flags *pflag.FlagSet) { for _, data := range stage1FlagsData { wrapper := &stage1ImageLocationFlag{ loc: &overriddenStage1Location, kind: data.kind, } flags.Var(wrapper, data.flag, data.help) } }
go
func addStage1ImageFlags(flags *pflag.FlagSet) { for _, data := range stage1FlagsData { wrapper := &stage1ImageLocationFlag{ loc: &overriddenStage1Location, kind: data.kind, } flags.Var(wrapper, data.flag, data.help) } }
[ "func", "addStage1ImageFlags", "(", "flags", "*", "pflag", ".", "FlagSet", ")", "{", "for", "_", ",", "data", ":=", "range", "stage1FlagsData", "{", "wrapper", ":=", "&", "stage1ImageLocationFlag", "{", "loc", ":", "&", "overriddenStage1Location", ",", "kind", ":", "data", ".", "kind", ",", "}", "\n", "flags", ".", "Var", "(", "wrapper", ",", "data", ".", "flag", ",", "data", ".", "help", ")", "\n", "}", "\n", "}" ]
// addStage1ImageFlags adds flags for specifying custom stage1 image
[ "addStage1ImageFlags", "adds", "flags", "for", "specifying", "custom", "stage1", "image" ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/stage1hash.go#L157-L165
train
rkt/rkt
pkg/sys/capability.go
HasChrootCapability
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 } }
go
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 } }
[ "func", "HasChrootCapability", "(", ")", "bool", "{", "caps", ",", "err", ":=", "capability", ".", "NewPid", "(", "0", ")", "\n", "if", "err", "==", "nil", "{", "return", "caps", ".", "Get", "(", "capability", ".", "EFFECTIVE", ",", "capability", ".", "CAP_SYS_CHROOT", ")", "\n", "}", "else", "{", "return", "os", ".", "Geteuid", "(", ")", "==", "0", "\n", "}", "\n", "}" ]
// HasChrootCapability checks if the current process has the CAP_SYS_CHROOT // capability
[ "HasChrootCapability", "checks", "if", "the", "current", "process", "has", "the", "CAP_SYS_CHROOT", "capability" ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/sys/capability.go#L25-L35
train
rkt/rkt
pkg/group/group.go
LookupGidFromFile
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 }
go
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 }
[ "func", "LookupGidFromFile", "(", "groupName", ",", "groupFile", "string", ")", "(", "gid", "int", ",", "err", "error", ")", "{", "groups", ",", "err", ":=", "parseGroupFile", "(", "groupFile", ")", "\n", "if", "err", "!=", "nil", "{", "return", "-", "1", ",", "errwrap", ".", "Wrap", "(", "fmt", ".", "Errorf", "(", "\"error parsing %q file\"", ",", "groupFile", ")", ",", "err", ")", "\n", "}", "\n", "group", ",", "ok", ":=", "groups", "[", "groupName", "]", "\n", "if", "!", "ok", "{", "return", "-", "1", ",", "fmt", ".", "Errorf", "(", "\"%q group not found\"", ",", "groupName", ")", "\n", "}", "\n", "return", "group", ".", "Gid", ",", "nil", "\n", "}" ]
// LookupGid reads the group file specified by groupFile, and returns the gid of the group // specified by groupName.
[ "LookupGid", "reads", "the", "group", "file", "specified", "by", "groupFile", "and", "returns", "the", "gid", "of", "the", "group", "specified", "by", "groupName", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/group/group.go#L43-L55
train
rkt/rkt
pkg/lock/keylock.go
TryExclusiveKeyLock
func TryExclusiveKeyLock(lockDir string, key string) (*KeyLock, error) { return createAndLock(lockDir, key, keyLockExclusive|keyLockNonBlocking) }
go
func TryExclusiveKeyLock(lockDir string, key string) (*KeyLock, error) { return createAndLock(lockDir, key, keyLockExclusive|keyLockNonBlocking) }
[ "func", "TryExclusiveKeyLock", "(", "lockDir", "string", ",", "key", "string", ")", "(", "*", "KeyLock", ",", "error", ")", "{", "return", "createAndLock", "(", "lockDir", ",", "key", ",", "keyLockExclusive", "|", "keyLockNonBlocking", ")", "\n", "}" ]
// 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.
[ "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", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/lock/keylock.go#L94-L96
train
rkt/rkt
pkg/lock/keylock.go
ExclusiveKeyLock
func ExclusiveKeyLock(lockDir string, key string) (*KeyLock, error) { return createAndLock(lockDir, key, keyLockExclusive) }
go
func ExclusiveKeyLock(lockDir string, key string) (*KeyLock, error) { return createAndLock(lockDir, key, keyLockExclusive) }
[ "func", "ExclusiveKeyLock", "(", "lockDir", "string", ",", "key", "string", ")", "(", "*", "KeyLock", ",", "error", ")", "{", "return", "createAndLock", "(", "lockDir", ",", "key", ",", "keyLockExclusive", ")", "\n", "}" ]
// 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.
[ "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", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/lock/keylock.go#L109-L111
train
rkt/rkt
pkg/lock/keylock.go
Unlock
func (l *KeyLock) Unlock() error { err := l.keyLock.Unlock() if err != nil { return err } return nil }
go
func (l *KeyLock) Unlock() error { err := l.keyLock.Unlock() if err != nil { return err } return nil }
[ "func", "(", "l", "*", "KeyLock", ")", "Unlock", "(", ")", "error", "{", "err", ":=", "l", ".", "keyLock", ".", "Unlock", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Unlock unlocks the key lock.
[ "Unlock", "unlocks", "the", "key", "lock", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/lock/keylock.go#L238-L244
train
rkt/rkt
pkg/lock/keylock.go
CleanKeyLocks
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 }
go
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 }
[ "func", "CleanKeyLocks", "(", "lockDir", "string", ")", "error", "{", "f", ",", "err", ":=", "os", ".", "Open", "(", "lockDir", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"error opening lockDir\"", ")", ",", "err", ")", "\n", "}", "\n", "defer", "f", ".", "Close", "(", ")", "\n", "files", ",", "err", ":=", "f", ".", "Readdir", "(", "0", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"error getting lock files list\"", ")", ",", "err", ")", "\n", "}", "\n", "for", "_", ",", "f", ":=", "range", "files", "{", "filename", ":=", "filepath", ".", "Join", "(", "lockDir", ",", "f", ".", "Name", "(", ")", ")", "\n", "keyLock", ",", "err", ":=", "TryExclusiveKeyLock", "(", "lockDir", ",", "f", ".", "Name", "(", ")", ")", "\n", "if", "err", "==", "ErrLocked", "{", "continue", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "err", "=", "os", ".", "Remove", "(", "filename", ")", "\n", "if", "err", "!=", "nil", "{", "keyLock", ".", "Close", "(", ")", "\n", "return", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"error removing lock file\"", ")", ",", "err", ")", "\n", "}", "\n", "keyLock", ".", "Close", "(", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// 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
[ "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" ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/lock/keylock.go#L249-L277
train
rkt/rkt
rkt/pubkey/pubkey.go
GetPubKeyLocations
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 }
go
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 }
[ "func", "(", "m", "*", "Manager", ")", "GetPubKeyLocations", "(", "prefix", "string", ")", "(", "[", "]", "string", ",", "error", ")", "{", "ensureLogger", "(", "m", ".", "Debug", ")", "\n", "if", "prefix", "==", "\"\"", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"empty prefix\"", ")", "\n", "}", "\n", "kls", ",", "err", ":=", "m", ".", "metaDiscoverPubKeyLocations", "(", "prefix", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"prefix meta discovery error\"", ")", ",", "err", ")", "\n", "}", "\n", "if", "len", "(", "kls", ")", "==", "0", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"meta discovery on %s resulted in no keys\"", ",", "prefix", ")", "\n", "}", "\n", "return", "kls", ",", "nil", "\n", "}" ]
// GetPubKeyLocations discovers locations at prefix
[ "GetPubKeyLocations", "discovers", "locations", "at", "prefix" ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/pubkey/pubkey.go#L72-L88
train
rkt/rkt
rkt/pubkey/pubkey.go
AddKeys
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 }
go
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 }
[ "func", "(", "m", "*", "Manager", ")", "AddKeys", "(", "pkls", "[", "]", "string", ",", "prefix", "string", ",", "accept", "AcceptOption", ")", "error", "{", "ensureLogger", "(", "m", ".", "Debug", ")", "\n", "if", "m", ".", "Ks", "==", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"no keystore available to add keys to\"", ")", "\n", "}", "\n", "for", "_", ",", "pkl", ":=", "range", "pkls", "{", "u", ",", "err", ":=", "url", ".", "Parse", "(", "pkl", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "pk", ",", "err", ":=", "m", ".", "getPubKey", "(", "u", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errwrap", ".", "Wrap", "(", "fmt", ".", "Errorf", "(", "\"error accessing the key %s\"", ",", "pkl", ")", ",", "err", ")", "\n", "}", "\n", "defer", "pk", ".", "Close", "(", ")", "\n", "err", "=", "displayKey", "(", "prefix", ",", "pkl", ",", "pk", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errwrap", ".", "Wrap", "(", "fmt", ".", "Errorf", "(", "\"error displaying the key %s\"", ",", "pkl", ")", ",", "err", ")", "\n", "}", "\n", "if", "m", ".", "TrustKeysFromHTTPS", "&&", "u", ".", "Scheme", "==", "\"https\"", "{", "accept", "=", "AcceptForce", "\n", "}", "\n", "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", ")", "\n", "log", ".", "Printf", "(", "\" - call rkt with --trust-keys-from-https\"", ")", "\n", "log", ".", "Printf", "(", "\" - run: rkt trust --prefix %q\"", ",", "prefix", ")", "\n", "return", "fmt", ".", "Errorf", "(", "\"error reviewing key: unable to ask user to review fingerprint due to lack of tty\"", ")", "\n", "}", "\n", "accepted", ",", "err", ":=", "reviewKey", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"error reviewing key\"", ")", ",", "err", ")", "\n", "}", "\n", "if", "!", "accepted", "{", "log", ".", "Printf", "(", "\"not trusting %q\"", ",", "pkl", ")", "\n", "continue", "\n", "}", "\n", "}", "\n", "if", "accept", "==", "AcceptForce", "{", "stdout", ".", "Printf", "(", "\"Trusting %q for prefix %q without fingerprint review.\"", ",", "pkl", ",", "prefix", ")", "\n", "}", "else", "{", "stdout", ".", "Printf", "(", "\"Trusting %q for prefix %q after fingerprint review.\"", ",", "pkl", ",", "prefix", ")", "\n", "}", "\n", "if", "prefix", "==", "\"\"", "{", "path", ",", "err", ":=", "m", ".", "Ks", ".", "StoreTrustedKeyRoot", "(", "pk", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"error adding root key\"", ")", ",", "err", ")", "\n", "}", "\n", "stdout", ".", "Printf", "(", "\"Added root key at %q\"", ",", "path", ")", "\n", "}", "else", "{", "path", ",", "err", ":=", "m", ".", "Ks", ".", "StoreTrustedKeyPrefix", "(", "prefix", ",", "pk", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errwrap", ".", "Wrap", "(", "fmt", ".", "Errorf", "(", "\"error adding key for prefix %q\"", ",", "prefix", ")", ",", "err", ")", "\n", "}", "\n", "stdout", ".", "Printf", "(", "\"Added key for prefix %q at %q\"", ",", "prefix", ",", "path", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// AddKeys adds the keys listed in pkls at prefix
[ "AddKeys", "adds", "the", "keys", "listed", "in", "pkls", "at", "prefix" ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/pubkey/pubkey.go#L91-L155
train
rkt/rkt
rkt/pubkey/pubkey.go
metaDiscoverPubKeyLocations
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 }
go
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 }
[ "func", "(", "m", "*", "Manager", ")", "metaDiscoverPubKeyLocations", "(", "prefix", "string", ")", "(", "[", "]", "string", ",", "error", ")", "{", "app", ",", "err", ":=", "discovery", ".", "NewAppFromString", "(", "prefix", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "hostHeaders", ":=", "config", ".", "ResolveAuthPerHost", "(", "m", ".", "AuthPerHost", ")", "\n", "insecure", ":=", "discovery", ".", "InsecureNone", "\n", "if", "m", ".", "InsecureAllowHTTP", "{", "insecure", "=", "insecure", "|", "discovery", ".", "InsecureHTTP", "\n", "}", "\n", "if", "m", ".", "InsecureSkipTLSCheck", "{", "insecure", "=", "insecure", "|", "discovery", ".", "InsecureTLS", "\n", "}", "\n", "keys", ",", "attempts", ",", "err", ":=", "discovery", ".", "DiscoverPublicKeys", "(", "*", "app", ",", "hostHeaders", ",", "insecure", ",", "0", ")", "\n", "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", ")", "\n", "}", "\n", "}", "\n", "return", "keys", ",", "err", "\n", "}" ]
// metaDiscoverPubKeyLocations discovers the locations of public keys through ACDiscovery by applying prefix as an ACApp
[ "metaDiscoverPubKeyLocations", "discovers", "the", "locations", "of", "public", "keys", "through", "ACDiscovery", "by", "applying", "prefix", "as", "an", "ACApp" ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/pubkey/pubkey.go#L158-L181
train
rkt/rkt
rkt/pubkey/pubkey.go
downloadKey
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 }
go
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 }
[ "func", "downloadKey", "(", "u", "*", "url", ".", "URL", ",", "skipTLSCheck", "bool", ")", "(", "*", "os", ".", "File", ",", "error", ")", "{", "tf", ",", "err", ":=", "ioutil", ".", "TempFile", "(", "\"\"", ",", "\"\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"error creating tempfile\"", ")", ",", "err", ")", "\n", "}", "\n", "os", ".", "Remove", "(", "tf", ".", "Name", "(", ")", ")", "\n", "defer", "func", "(", ")", "{", "if", "tf", "!=", "nil", "{", "tf", ".", "Close", "(", ")", "\n", "}", "\n", "}", "(", ")", "\n", "var", "client", "*", "http", ".", "Client", "\n", "if", "skipTLSCheck", "{", "client", "=", "insecureClient", "\n", "}", "else", "{", "client", "=", "secureClient", "\n", "}", "\n", "res", ",", "err", ":=", "client", ".", "Get", "(", "u", ".", "String", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"error getting key\"", ")", ",", "err", ")", "\n", "}", "\n", "defer", "res", ".", "Body", ".", "Close", "(", ")", "\n", "if", "res", ".", "StatusCode", "!=", "http", ".", "StatusOK", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"bad HTTP status code: %d\"", ",", "res", ".", "StatusCode", ")", "\n", "}", "\n", "if", "_", ",", "err", ":=", "io", ".", "Copy", "(", "tf", ",", "res", ".", "Body", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"error copying key\"", ")", ",", "err", ")", "\n", "}", "\n", "if", "_", ",", "err", "=", "tf", ".", "Seek", "(", "0", ",", "os", ".", "SEEK_SET", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"error seeking\"", ")", ",", "err", ")", "\n", "}", "\n", "retTf", ":=", "tf", "\n", "tf", "=", "nil", "\n", "return", "retTf", ",", "nil", "\n", "}" ]
// downloadKey retrieves the file, storing it in a deleted tempfile
[ "downloadKey", "retrieves", "the", "file", "storing", "it", "in", "a", "deleted", "tempfile" ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/pubkey/pubkey.go#L201-L244
train
rkt/rkt
rkt/pubkey/pubkey.go
displayKey
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 }
go
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 }
[ "func", "displayKey", "(", "prefix", ",", "location", "string", ",", "key", "*", "os", ".", "File", ")", "error", "{", "defer", "key", ".", "Seek", "(", "0", ",", "os", ".", "SEEK_SET", ")", "\n", "kr", ",", "err", ":=", "openpgp", ".", "ReadArmoredKeyRing", "(", "key", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"error reading key\"", ")", ",", "err", ")", "\n", "}", "\n", "log", ".", "Printf", "(", "\"prefix: %q\\nkey: %q\"", ",", "\\n", ",", "prefix", ")", "\n", "location", "\n", "for", "_", ",", "k", ":=", "range", "kr", "{", "stdout", ".", "Printf", "(", "\"gpg key fingerprint is: %s\"", ",", "fingerToString", "(", "k", ".", "PrimaryKey", ".", "Fingerprint", ")", ")", "\n", "for", "_", ",", "sk", ":=", "range", "k", ".", "Subkeys", "{", "stdout", ".", "Printf", "(", "\" Subkey fingerprint: %s\"", ",", "fingerToString", "(", "sk", ".", "PublicKey", ".", "Fingerprint", ")", ")", "\n", "}", "\n", "for", "n", ":=", "range", "k", ".", "Identities", "{", "stdout", ".", "Printf", "(", "\"\\t%s\"", ",", "\\t", ")", "\n", "}", "\n", "}", "\n", "}" ]
// displayKey shows the key summary
[ "displayKey", "shows", "the", "key", "summary" ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/pubkey/pubkey.go#L275-L296
train
rkt/rkt
rkt/pubkey/pubkey.go
reviewKey
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'") } } }
go
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'") } } }
[ "func", "reviewKey", "(", ")", "(", "bool", ",", "error", ")", "{", "in", ":=", "bufio", ".", "NewReader", "(", "os", ".", "Stdin", ")", "\n", "for", "{", "stdout", ".", "Printf", "(", "\"Are you sure you want to trust this key (yes/no)?\"", ")", "\n", "input", ",", "err", ":=", "in", ".", "ReadString", "(", "'\\n'", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"error reading input\"", ")", ",", "err", ")", "\n", "}", "\n", "switch", "input", "{", "case", "\"yes\\n\"", ":", "\\n", "\n", "return", "true", ",", "nil", "case", "\"no\\n\"", ":", "\\n", "\n", "}", "\n", "}", "\n", "}" ]
// reviewKey asks the user to accept the key
[ "reviewKey", "asks", "the", "user", "to", "accept", "the", "key" ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/pubkey/pubkey.go#L299-L316
train
rkt/rkt
networking/kvm.go
setupTapDevice
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 }
go
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 }
[ "func", "setupTapDevice", "(", "podID", "types", ".", "UUID", ")", "(", "netlink", ".", "Link", ",", "error", ")", "{", "nameTemplate", ":=", "fmt", ".", "Sprintf", "(", "\"rkt-%s-tap%%d\"", ",", "podID", ".", "String", "(", ")", "[", "0", ":", "4", "]", ")", "\n", "ifName", ",", "err", ":=", "tuntap", ".", "CreatePersistentIface", "(", "nameTemplate", ",", "tuntap", ".", "Tap", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"tuntap persist\"", ")", ",", "err", ")", "\n", "}", "\n", "link", ",", "err", ":=", "netlink", ".", "LinkByName", "(", "ifName", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errwrap", ".", "Wrap", "(", "fmt", ".", "Errorf", "(", "\"cannot find link %q\"", ",", "ifName", ")", ",", "err", ")", "\n", "}", "\n", "if", "err", ":=", "netlink", ".", "LinkSetUp", "(", "link", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errwrap", ".", "Wrap", "(", "fmt", ".", "Errorf", "(", "\"cannot set link up %q\"", ",", "ifName", ")", ",", "err", ")", "\n", "}", "\n", "return", "link", ",", "nil", "\n", "}" ]
// setupTapDevice creates persistent tap device // and returns a newly created netlink.Link structure
[ "setupTapDevice", "creates", "persistent", "tap", "device", "and", "returns", "a", "newly", "created", "netlink", ".", "Link", "structure" ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/networking/kvm.go#L59-L77
train
rkt/rkt
networking/kvm.go
setupMacVTapDevice
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 }
go
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 }
[ "func", "setupMacVTapDevice", "(", "podID", "types", ".", "UUID", ",", "config", "MacVTapNetConf", ",", "interfaceNumber", "int", ")", "(", "netlink", ".", "Link", ",", "error", ")", "{", "master", ",", "err", ":=", "netlink", ".", "LinkByName", "(", "config", ".", "Master", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errwrap", ".", "Wrap", "(", "fmt", ".", "Errorf", "(", "\"cannot find master device '%v'\"", ",", "config", ".", "Master", ")", ",", "err", ")", "\n", "}", "\n", "var", "mode", "netlink", ".", "MacvlanMode", "\n", "switch", "config", ".", "Mode", "{", "case", "\"\"", ",", "\"bridge\"", ":", "mode", "=", "netlink", ".", "MACVLAN_MODE_BRIDGE", "\n", "case", "\"private\"", ":", "mode", "=", "netlink", ".", "MACVLAN_MODE_PRIVATE", "\n", "case", "\"vepa\"", ":", "mode", "=", "netlink", ".", "MACVLAN_MODE_VEPA", "\n", "case", "\"passthru\"", ":", "mode", "=", "netlink", ".", "MACVLAN_MODE_PASSTHRU", "\n", "default", ":", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"unsupported macvtap mode: %v\"", ",", "config", ".", "Mode", ")", "\n", "}", "\n", "mtu", ":=", "master", ".", "Attrs", "(", ")", ".", "MTU", "\n", "if", "config", ".", "MTU", "!=", "0", "{", "mtu", "=", "config", ".", "MTU", "\n", "}", "\n", "interfaceName", ":=", "fmt", ".", "Sprintf", "(", "\"rkt-%s-vtap%d\"", ",", "podID", ".", "String", "(", ")", "[", "0", ":", "4", "]", ",", "interfaceNumber", ")", "\n", "link", ":=", "&", "netlink", ".", "Macvtap", "{", "Macvlan", ":", "netlink", ".", "Macvlan", "{", "LinkAttrs", ":", "netlink", ".", "LinkAttrs", "{", "Name", ":", "interfaceName", ",", "MTU", ":", "mtu", ",", "ParentIndex", ":", "master", ".", "Attrs", "(", ")", ".", "Index", ",", "}", ",", "Mode", ":", "mode", ",", "}", ",", "}", "\n", "if", "err", ":=", "netlink", ".", "LinkAdd", "(", "link", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"cannot create macvtap interface\"", ")", ",", "err", ")", "\n", "}", "\n", "ipv4SysctlValueName", ":=", "fmt", ".", "Sprintf", "(", "IPv4InterfaceArpProxySysctlTemplate", ",", "interfaceName", ")", "\n", "if", "_", ",", "err", ":=", "cnisysctl", ".", "Sysctl", "(", "ipv4SysctlValueName", ",", "\"1\"", ")", ";", "err", "!=", "nil", "{", "_", "=", "netlink", ".", "LinkDel", "(", "link", ")", "\n", "return", "nil", ",", "errwrap", ".", "Wrap", "(", "fmt", ".", "Errorf", "(", "\"failed to set proxy_arp on newly added interface %q\"", ",", "interfaceName", ")", ",", "err", ")", "\n", "}", "\n", "if", "err", ":=", "netlink", ".", "LinkSetUp", "(", "link", ")", ";", "err", "!=", "nil", "{", "_", "=", "netlink", ".", "LinkDel", "(", "link", ")", "\n", "return", "nil", ",", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"cannot set up macvtap interface\"", ")", ",", "err", ")", "\n", "}", "\n", "return", "link", ",", "nil", "\n", "}" ]
// setupTapDevice creates persistent macvtap device // and returns a newly created netlink.Link structure // using part of pod hash and interface number in interface name
[ "setupTapDevice", "creates", "persistent", "macvtap", "device", "and", "returns", "a", "newly", "created", "netlink", ".", "Link", "structure", "using", "part", "of", "pod", "hash", "and", "interface", "number", "in", "interface", "name" ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/networking/kvm.go#L92-L146
train
rkt/rkt
networking/kvm.go
kvmTeardown
func (n *Networking) kvmTeardown() { if err := n.teardownForwarding(); err != nil { stderr.PrintE("error removing forwarded ports (kvm)", err) } n.teardownKvmNets() }
go
func (n *Networking) kvmTeardown() { if err := n.teardownForwarding(); err != nil { stderr.PrintE("error removing forwarded ports (kvm)", err) } n.teardownKvmNets() }
[ "func", "(", "n", "*", "Networking", ")", "kvmTeardown", "(", ")", "{", "if", "err", ":=", "n", ".", "teardownForwarding", "(", ")", ";", "err", "!=", "nil", "{", "stderr", ".", "PrintE", "(", "\"error removing forwarded ports (kvm)\"", ",", "err", ")", "\n", "}", "\n", "n", ".", "teardownKvmNets", "(", ")", "\n", "}" ]
// kvmTeardown network teardown for kvm flavor based pods // similar to Networking.Teardown but without host namespaces
[ "kvmTeardown", "network", "teardown", "for", "kvm", "flavor", "based", "pods", "similar", "to", "Networking", ".", "Teardown", "but", "without", "host", "namespaces" ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/networking/kvm.go#L705-L711
train
rkt/rkt
rkt/image/filefetcher.go
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 }
go
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 }
[ "func", "(", "f", "*", "fileFetcher", ")", "Hash", "(", "aciPath", "string", ",", "a", "*", "asc", ")", "(", "string", ",", "error", ")", "{", "ensureLogger", "(", "f", ".", "Debug", ")", "\n", "absPath", ",", "err", ":=", "filepath", ".", "Abs", "(", "aciPath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"\"", ",", "errwrap", ".", "Wrap", "(", "fmt", ".", "Errorf", "(", "\"failed to get an absolute path for %q\"", ",", "aciPath", ")", ",", "err", ")", "\n", "}", "\n", "aciPath", "=", "absPath", "\n", "aciFile", ",", "err", ":=", "f", ".", "getFile", "(", "aciPath", ",", "a", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"\"", ",", "err", "\n", "}", "\n", "defer", "aciFile", ".", "Close", "(", ")", "\n", "key", ",", "err", ":=", "f", ".", "S", ".", "WriteACI", "(", "aciFile", ",", "imagestore", ".", "ACIFetchInfo", "{", "Latest", ":", "false", ",", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"\"", ",", "err", "\n", "}", "\n", "return", "key", ",", "nil", "\n", "}" ]
// Hash opens a file, optionally verifies it against passed asc, // stores it in the store and returns the hash.
[ "Hash", "opens", "a", "file", "optionally", "verifies", "it", "against", "passed", "asc", "stores", "it", "in", "the", "store", "and", "returns", "the", "hash", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/image/filefetcher.go#L39-L61
train
rkt/rkt
rkt/image/filefetcher.go
getVerifiedFile
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 }
go
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 }
[ "func", "(", "f", "*", "fileFetcher", ")", "getVerifiedFile", "(", "aciPath", "string", ",", "a", "*", "asc", ")", "(", "*", "os", ".", "File", ",", "error", ")", "{", "var", "aciFile", "*", "os", ".", "File", "\n", "var", "errClose", "error", "\n", "f", ".", "maybeOverrideAsc", "(", "aciPath", ",", "a", ")", "\n", "ascFile", ",", "err", ":=", "a", ".", "Get", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"error opening signature file\"", ")", ",", "err", ")", "\n", "}", "\n", "defer", "ascFile", ".", "Close", "(", ")", "\n", "aciFile", ",", "err", "=", "os", ".", "Open", "(", "aciPath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"error opening ACI file\"", ")", ",", "err", ")", "\n", "}", "\n", "defer", "func", "(", ")", "{", "if", "errClose", "!=", "nil", "{", "aciFile", ".", "Close", "(", ")", "\n", "}", "\n", "}", "(", ")", "\n", "validator", ",", "errClose", ":=", "newValidator", "(", "aciFile", ")", "\n", "if", "errClose", "!=", "nil", "{", "return", "nil", ",", "errClose", "\n", "}", "\n", "entity", ",", "errClose", ":=", "validator", ".", "ValidateWithSignature", "(", "f", ".", "Ks", ",", "ascFile", ")", "\n", "if", "errClose", "!=", "nil", "{", "return", "nil", ",", "errwrap", ".", "Wrap", "(", "fmt", ".", "Errorf", "(", "\"image %q verification failed\"", ",", "validator", ".", "ImageName", "(", ")", ")", ",", "errClose", ")", "\n", "}", "\n", "printIdentities", "(", "entity", ")", "\n", "return", "aciFile", ",", "nil", "\n", "}" ]
// fetch opens and verifies the ACI.
[ "fetch", "opens", "and", "verifies", "the", "ACI", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/image/filefetcher.go#L82-L116
train
rkt/rkt
pkg/fs/mount.go
NewLoggingMounter
func NewLoggingMounter(m Mounter, um Unmounter, logf func(string, ...interface{})) MountUnmounter { return &loggingMounter{m, um, logf} }
go
func NewLoggingMounter(m Mounter, um Unmounter, logf func(string, ...interface{})) MountUnmounter { return &loggingMounter{m, um, logf} }
[ "func", "NewLoggingMounter", "(", "m", "Mounter", ",", "um", "Unmounter", ",", "logf", "func", "(", "string", ",", "...", "interface", "{", "}", ")", ")", "MountUnmounter", "{", "return", "&", "loggingMounter", "{", "m", ",", "um", ",", "logf", "}", "\n", "}" ]
// NewLoggingMounter returns a MountUnmounter that logs mount events using the given logger func.
[ "NewLoggingMounter", "returns", "a", "MountUnmounter", "that", "logs", "mount", "events", "using", "the", "given", "logger", "func", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/fs/mount.go#L56-L58
train
rkt/rkt
pkg/tpm/tpm.go
Extend
func Extend(description string) error { connection := tpmclient.New("localhost:12041", timeout) err := connection.Extend(15, 0x1000, nil, description) return err }
go
func Extend(description string) error { connection := tpmclient.New("localhost:12041", timeout) err := connection.Extend(15, 0x1000, nil, description) return err }
[ "func", "Extend", "(", "description", "string", ")", "error", "{", "connection", ":=", "tpmclient", ".", "New", "(", "\"localhost:12041\"", ",", "timeout", ")", "\n", "err", ":=", "connection", ".", "Extend", "(", "15", ",", "0x1000", ",", "nil", ",", "description", ")", "\n", "return", "err", "\n", "}" ]
// Extend extends the TPM log with the provided string. Returns any error.
[ "Extend", "extends", "the", "TPM", "log", "with", "the", "provided", "string", ".", "Returns", "any", "error", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/tpm/tpm.go#L29-L33
train
rkt/rkt
common/common.go
Stage1RootfsPath
func Stage1RootfsPath(root string) string { return filepath.Join(Stage1ImagePath(root), aci.RootfsDir) }
go
func Stage1RootfsPath(root string) string { return filepath.Join(Stage1ImagePath(root), aci.RootfsDir) }
[ "func", "Stage1RootfsPath", "(", "root", "string", ")", "string", "{", "return", "filepath", ".", "Join", "(", "Stage1ImagePath", "(", "root", ")", ",", "aci", ".", "RootfsDir", ")", "\n", "}" ]
// Stage1RootfsPath returns the path to the stage1 rootfs
[ "Stage1RootfsPath", "returns", "the", "path", "to", "the", "stage1", "rootfs" ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/common/common.go#L101-L103
train
rkt/rkt
common/common.go
Stage1ManifestPath
func Stage1ManifestPath(root string) string { return filepath.Join(Stage1ImagePath(root), aci.ManifestFile) }
go
func Stage1ManifestPath(root string) string { return filepath.Join(Stage1ImagePath(root), aci.ManifestFile) }
[ "func", "Stage1ManifestPath", "(", "root", "string", ")", "string", "{", "return", "filepath", ".", "Join", "(", "Stage1ImagePath", "(", "root", ")", ",", "aci", ".", "ManifestFile", ")", "\n", "}" ]
// Stage1ManifestPath returns the path to the stage1's manifest file inside the expanded ACI.
[ "Stage1ManifestPath", "returns", "the", "path", "to", "the", "stage1", "s", "manifest", "file", "inside", "the", "expanded", "ACI", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/common/common.go#L106-L108
train
rkt/rkt
common/common.go
AppStatusPath
func AppStatusPath(root, appName string) string { return filepath.Join(AppsStatusesPath(root), appName) }
go
func AppStatusPath(root, appName string) string { return filepath.Join(AppsStatusesPath(root), appName) }
[ "func", "AppStatusPath", "(", "root", ",", "appName", "string", ")", "string", "{", "return", "filepath", ".", "Join", "(", "AppsStatusesPath", "(", "root", ")", ",", "appName", ")", "\n", "}" ]
// AppStatusPath returns the path of the status file of an app.
[ "AppStatusPath", "returns", "the", "path", "of", "the", "status", "file", "of", "an", "app", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/common/common.go#L140-L142
train
rkt/rkt
common/common.go
AppStatusPathFromStage1Rootfs
func AppStatusPathFromStage1Rootfs(rootfs, appName string) string { return filepath.Join(AppsStatusesPathFromStage1Rootfs(rootfs), appName) }
go
func AppStatusPathFromStage1Rootfs(rootfs, appName string) string { return filepath.Join(AppsStatusesPathFromStage1Rootfs(rootfs), appName) }
[ "func", "AppStatusPathFromStage1Rootfs", "(", "rootfs", ",", "appName", "string", ")", "string", "{", "return", "filepath", ".", "Join", "(", "AppsStatusesPathFromStage1Rootfs", "(", "rootfs", ")", ",", "appName", ")", "\n", "}" ]
// AppStatusPathFromStage1Rootfs returns the path of the status file of an app. // It receives the stage1 rootfs as parameter instead of the pod root.
[ "AppStatusPathFromStage1Rootfs", "returns", "the", "path", "of", "the", "status", "file", "of", "an", "app", ".", "It", "receives", "the", "stage1", "rootfs", "as", "parameter", "instead", "of", "the", "pod", "root", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/common/common.go#L146-L148
train
rkt/rkt
common/common.go
AppPath
func AppPath(root string, appName types.ACName) string { return filepath.Join(AppsPath(root), appName.String()) }
go
func AppPath(root string, appName types.ACName) string { return filepath.Join(AppsPath(root), appName.String()) }
[ "func", "AppPath", "(", "root", "string", ",", "appName", "types", ".", "ACName", ")", "string", "{", "return", "filepath", ".", "Join", "(", "AppsPath", "(", "root", ")", ",", "appName", ".", "String", "(", ")", ")", "\n", "}" ]
// AppPath returns the path to an app's rootfs.
[ "AppPath", "returns", "the", "path", "to", "an", "app", "s", "rootfs", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/common/common.go#L182-L184
train
rkt/rkt
common/common.go
AppRootfsPath
func AppRootfsPath(root string, appName types.ACName) string { return filepath.Join(AppPath(root, appName), aci.RootfsDir) }
go
func AppRootfsPath(root string, appName types.ACName) string { return filepath.Join(AppPath(root, appName), aci.RootfsDir) }
[ "func", "AppRootfsPath", "(", "root", "string", ",", "appName", "types", ".", "ACName", ")", "string", "{", "return", "filepath", ".", "Join", "(", "AppPath", "(", "root", ",", "appName", ")", ",", "aci", ".", "RootfsDir", ")", "\n", "}" ]
// AppRootfsPath returns the path to an app's rootfs.
[ "AppRootfsPath", "returns", "the", "path", "to", "an", "app", "s", "rootfs", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/common/common.go#L187-L189
train
rkt/rkt
common/common.go
RelAppPath
func RelAppPath(appName types.ACName) string { return filepath.Join(stage2Dir, appName.String()) }
go
func RelAppPath(appName types.ACName) string { return filepath.Join(stage2Dir, appName.String()) }
[ "func", "RelAppPath", "(", "appName", "types", ".", "ACName", ")", "string", "{", "return", "filepath", ".", "Join", "(", "stage2Dir", ",", "appName", ".", "String", "(", ")", ")", "\n", "}" ]
// RelAppPath returns the path of an app relative to the stage1 chroot.
[ "RelAppPath", "returns", "the", "path", "of", "an", "app", "relative", "to", "the", "stage1", "chroot", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/common/common.go#L192-L194
train
rkt/rkt
common/common.go
RelAppRootfsPath
func RelAppRootfsPath(appName types.ACName) string { return filepath.Join(RelAppPath(appName), aci.RootfsDir) }
go
func RelAppRootfsPath(appName types.ACName) string { return filepath.Join(RelAppPath(appName), aci.RootfsDir) }
[ "func", "RelAppRootfsPath", "(", "appName", "types", ".", "ACName", ")", "string", "{", "return", "filepath", ".", "Join", "(", "RelAppPath", "(", "appName", ")", ",", "aci", ".", "RootfsDir", ")", "\n", "}" ]
// RelAppRootfsPath returns the path of an app's rootfs relative to the stage1 chroot.
[ "RelAppRootfsPath", "returns", "the", "path", "of", "an", "app", "s", "rootfs", "relative", "to", "the", "stage1", "chroot", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/common/common.go#L197-L199
train
rkt/rkt
common/common.go
ImageManifestPath
func ImageManifestPath(root string, appName types.ACName) string { return filepath.Join(AppPath(root, appName), aci.ManifestFile) }
go
func ImageManifestPath(root string, appName types.ACName) string { return filepath.Join(AppPath(root, appName), aci.ManifestFile) }
[ "func", "ImageManifestPath", "(", "root", "string", ",", "appName", "types", ".", "ACName", ")", "string", "{", "return", "filepath", ".", "Join", "(", "AppPath", "(", "root", ",", "appName", ")", ",", "aci", ".", "ManifestFile", ")", "\n", "}" ]
// ImageManifestPath returns the path to the app's manifest file of a pod.
[ "ImageManifestPath", "returns", "the", "path", "to", "the", "app", "s", "manifest", "file", "of", "a", "pod", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/common/common.go#L202-L204
train
rkt/rkt
common/common.go
AppInfoPath
func AppInfoPath(root string, appName types.ACName) string { return filepath.Join(AppsInfoPath(root), appName.String()) }
go
func AppInfoPath(root string, appName types.ACName) string { return filepath.Join(AppsInfoPath(root), appName.String()) }
[ "func", "AppInfoPath", "(", "root", "string", ",", "appName", "types", ".", "ACName", ")", "string", "{", "return", "filepath", ".", "Join", "(", "AppsInfoPath", "(", "root", ")", ",", "appName", ".", "String", "(", ")", ")", "\n", "}" ]
// AppInfoPath returns the path to the app's appsinfo directory of a pod.
[ "AppInfoPath", "returns", "the", "path", "to", "the", "app", "s", "appsinfo", "directory", "of", "a", "pod", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/common/common.go#L212-L214
train
rkt/rkt
common/common.go
AppTreeStoreIDPath
func AppTreeStoreIDPath(root string, appName types.ACName) string { return filepath.Join(AppInfoPath(root, appName), AppTreeStoreIDFilename) }
go
func AppTreeStoreIDPath(root string, appName types.ACName) string { return filepath.Join(AppInfoPath(root, appName), AppTreeStoreIDFilename) }
[ "func", "AppTreeStoreIDPath", "(", "root", "string", ",", "appName", "types", ".", "ACName", ")", "string", "{", "return", "filepath", ".", "Join", "(", "AppInfoPath", "(", "root", ",", "appName", ")", ",", "AppTreeStoreIDFilename", ")", "\n", "}" ]
// AppTreeStoreIDPath returns the path to the app's treeStoreID file of a pod.
[ "AppTreeStoreIDPath", "returns", "the", "path", "to", "the", "app", "s", "treeStoreID", "file", "of", "a", "pod", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/common/common.go#L217-L219
train
rkt/rkt
common/common.go
AppImageManifestPath
func AppImageManifestPath(root string, appName types.ACName) string { return filepath.Join(AppInfoPath(root, appName), aci.ManifestFile) }
go
func AppImageManifestPath(root string, appName types.ACName) string { return filepath.Join(AppInfoPath(root, appName), aci.ManifestFile) }
[ "func", "AppImageManifestPath", "(", "root", "string", ",", "appName", "types", ".", "ACName", ")", "string", "{", "return", "filepath", ".", "Join", "(", "AppInfoPath", "(", "root", ",", "appName", ")", ",", "aci", ".", "ManifestFile", ")", "\n", "}" ]
// AppImageManifestPath returns the path to the app's ImageManifest file
[ "AppImageManifestPath", "returns", "the", "path", "to", "the", "app", "s", "ImageManifest", "file" ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/common/common.go#L222-L224
train
rkt/rkt
common/common.go
CreateSharedVolumesPath
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 }
go
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 }
[ "func", "CreateSharedVolumesPath", "(", "root", "string", ")", "(", "string", ",", "error", ")", "{", "sharedVolPath", ":=", "SharedVolumesPath", "(", "root", ")", "\n", "if", "err", ":=", "os", ".", "MkdirAll", "(", "sharedVolPath", ",", "SharedVolumePerm", ")", ";", "err", "!=", "nil", "{", "return", "\"\"", ",", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"could not create shared volumes directory\"", ")", ",", "err", ")", "\n", "}", "\n", "if", "err", ":=", "os", ".", "Chmod", "(", "sharedVolPath", ",", "SharedVolumePerm", ")", ";", "err", "!=", "nil", "{", "return", "\"\"", ",", "errwrap", ".", "Wrap", "(", "fmt", ".", "Errorf", "(", "\"could not change permissions of %q\"", ",", "sharedVolPath", ")", ",", "err", ")", "\n", "}", "\n", "return", "sharedVolPath", ",", "nil", "\n", "}" ]
// CreateSharedVolumesPath ensures the sharedVolumePath for the pod root passed // in exists. It returns the shared volume path or an error.
[ "CreateSharedVolumesPath", "ensures", "the", "sharedVolumePath", "for", "the", "pod", "root", "passed", "in", "exists", ".", "It", "returns", "the", "shared", "volume", "path", "or", "an", "error", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/common/common.go#L233-L246
train
rkt/rkt
common/common.go
MetadataServicePublicURL
func MetadataServicePublicURL(ip net.IP, token string) string { return fmt.Sprintf("http://%v:%v/%v", ip, MetadataServicePort, token) }
go
func MetadataServicePublicURL(ip net.IP, token string) string { return fmt.Sprintf("http://%v:%v/%v", ip, MetadataServicePort, token) }
[ "func", "MetadataServicePublicURL", "(", "ip", "net", ".", "IP", ",", "token", "string", ")", "string", "{", "return", "fmt", ".", "Sprintf", "(", "\"http://%v:%v/%v\"", ",", "ip", ",", "MetadataServicePort", ",", "token", ")", "\n", "}" ]
// MetadataServicePublicURL returns the public URL used to host the metadata service
[ "MetadataServicePublicURL", "returns", "the", "public", "URL", "used", "to", "host", "the", "metadata", "service" ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/common/common.go#L249-L251
train
rkt/rkt
common/common.go
LookupPath
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) }
go
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) }
[ "func", "LookupPath", "(", "bin", "string", ",", "paths", "string", ")", "(", "string", ",", "error", ")", "{", "pathsArr", ":=", "filepath", ".", "SplitList", "(", "paths", ")", "\n", "for", "_", ",", "path", ":=", "range", "pathsArr", "{", "binPath", ":=", "filepath", ".", "Join", "(", "path", ",", "bin", ")", "\n", "binAbsPath", ",", "err", ":=", "filepath", ".", "Abs", "(", "binPath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"\"", ",", "fmt", ".", "Errorf", "(", "\"unable to find absolute path for %s\"", ",", "binPath", ")", "\n", "}", "\n", "if", "fileutil", ".", "IsExecutable", "(", "binAbsPath", ")", "{", "return", "binAbsPath", ",", "nil", "\n", "}", "\n", "}", "\n", "return", "\"\"", ",", "fmt", ".", "Errorf", "(", "\"unable to find %q in %q\"", ",", "bin", ",", "paths", ")", "\n", "}" ]
// LookupPath search for bin in paths. If found, it returns its absolute path, // if not, an error
[ "LookupPath", "search", "for", "bin", "in", "paths", ".", "If", "found", "it", "returns", "its", "absolute", "path", "if", "not", "an", "error" ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/common/common.go#L375-L388
train
rkt/rkt
common/common.go
SystemdVersion
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 }
go
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 }
[ "func", "SystemdVersion", "(", "systemdBinaryPath", "string", ")", "(", "int", ",", "error", ")", "{", "versionBytes", ",", "err", ":=", "exec", ".", "Command", "(", "systemdBinaryPath", ",", "\"--version\"", ")", ".", "CombinedOutput", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "-", "1", ",", "errwrap", ".", "Wrap", "(", "fmt", ".", "Errorf", "(", "\"unable to probe %s version\"", ",", "systemdBinaryPath", ")", ",", "err", ")", "\n", "}", "\n", "versionStr", ":=", "strings", ".", "SplitN", "(", "string", "(", "versionBytes", ")", ",", "\"\\n\"", ",", "\\n", ")", "[", "2", "]", "\n", "0", "\n", "var", "version", "int", "\n", "n", ",", "err", ":=", "fmt", ".", "Sscanf", "(", "versionStr", ",", "\"systemd %d\"", ",", "&", "version", ")", "\n", "if", "err", "!=", "nil", "||", "n", "!=", "1", "{", "return", "-", "1", ",", "fmt", ".", "Errorf", "(", "\"cannot parse version: %q\"", ",", "versionStr", ")", "\n", "}", "\n", "}" ]
// SystemdVersion parses and returns the version of a given systemd binary
[ "SystemdVersion", "parses", "and", "returns", "the", "version", "of", "a", "given", "systemd", "binary" ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/common/common.go#L391-L404
train
rkt/rkt
common/common.go
SupportsOverlay
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") }
go
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") }
[ "func", "SupportsOverlay", "(", ")", "error", "{", "_", "=", "exec", ".", "Command", "(", "\"modprobe\"", ",", "\"overlay\"", ")", ".", "Run", "(", ")", "\n", "f", ",", "err", ":=", "os", ".", "Open", "(", "\"/proc/filesystems\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "ErrOverlayUnsupported", "(", "fmt", ".", "Sprintf", "(", "\"cannot open /proc/filesystems: %v\"", ",", "err", ")", ")", "\n", "}", "\n", "defer", "f", ".", "Close", "(", ")", "\n", "s", ":=", "bufio", ".", "NewScanner", "(", "f", ")", "\n", "for", "s", ".", "Scan", "(", ")", "{", "if", "s", ".", "Text", "(", ")", "==", "\"nodev\\toverlay\"", "\\t", "\n", "}", "\n", "{", "return", "nil", "\n", "}", "\n", "}" ]
// 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.
[ "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", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/common/common.go#L409-L430
train
rkt/rkt
common/common.go
RemoveEmptyLines
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 }
go
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 }
[ "func", "RemoveEmptyLines", "(", "str", "string", ")", "[", "]", "string", "{", "lines", ":=", "make", "(", "[", "]", "string", ",", "0", ")", "\n", "for", "_", ",", "v", ":=", "range", "strings", ".", "Split", "(", "str", ",", "\"\\n\"", ")", "\\n", "\n", "{", "if", "len", "(", "v", ")", ">", "0", "{", "lines", "=", "append", "(", "lines", ",", "v", ")", "\n", "}", "\n", "}", "\n", "}" ]
// RemoveEmptyLines removes empty lines from the given string // and breaks it up into a list of strings at newline characters
[ "RemoveEmptyLines", "removes", "empty", "lines", "from", "the", "given", "string", "and", "breaks", "it", "up", "into", "a", "list", "of", "strings", "at", "newline", "characters" ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/common/common.go#L490-L500
train
rkt/rkt
common/common.go
GetExitStatus
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 }
go
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 }
[ "func", "GetExitStatus", "(", "err", "error", ")", "(", "int", ",", "error", ")", "{", "if", "err", "==", "nil", "{", "return", "0", ",", "nil", "\n", "}", "\n", "if", "exiterr", ",", "ok", ":=", "err", ".", "(", "*", "exec", ".", "ExitError", ")", ";", "ok", "{", "if", "status", ",", "ok", ":=", "exiterr", ".", "Sys", "(", ")", ".", "(", "syscall", ".", "WaitStatus", ")", ";", "ok", "{", "return", "status", ".", "ExitStatus", "(", ")", ",", "nil", "\n", "}", "\n", "}", "\n", "return", "-", "1", ",", "err", "\n", "}" ]
// 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
[ "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" ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/common/common.go#L504-L515
train
rkt/rkt
common/common.go
ImageNameToAppName
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 }
go
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 }
[ "func", "ImageNameToAppName", "(", "name", "types", ".", "ACIdentifier", ")", "(", "*", "types", ".", "ACName", ",", "error", ")", "{", "parts", ":=", "strings", ".", "Split", "(", "name", ".", "String", "(", ")", ",", "\"/\"", ")", "\n", "last", ":=", "parts", "[", "len", "(", "parts", ")", "-", "1", "]", "\n", "sn", ",", "err", ":=", "types", ".", "SanitizeACName", "(", "last", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "types", ".", "MustACName", "(", "sn", ")", ",", "nil", "\n", "}" ]
// 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
[ "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" ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/common/common.go#L545-L555
train
rkt/rkt
stage1/init/kvm/network.go
GetNetworkDescriptions
func GetNetworkDescriptions(n *networking.Networking) []NetDescriber { var nds []NetDescriber for _, an := range n.GetActiveNetworks() { nds = append(nds, an) } return nds }
go
func GetNetworkDescriptions(n *networking.Networking) []NetDescriber { var nds []NetDescriber for _, an := range n.GetActiveNetworks() { nds = append(nds, an) } return nds }
[ "func", "GetNetworkDescriptions", "(", "n", "*", "networking", ".", "Networking", ")", "[", "]", "NetDescriber", "{", "var", "nds", "[", "]", "NetDescriber", "\n", "for", "_", ",", "an", ":=", "range", "n", ".", "GetActiveNetworks", "(", ")", "{", "nds", "=", "append", "(", "nds", ",", "an", ")", "\n", "}", "\n", "return", "nds", "\n", "}" ]
// GetNetworkDescriptions converts activeNets to netDescribers
[ "GetNetworkDescriptions", "converts", "activeNets", "to", "netDescribers" ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage1/init/kvm/network.go#L32-L38
train
rkt/rkt
stage1/init/kvm/network.go
GetKVMNetArgs
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 }
go
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 }
[ "func", "GetKVMNetArgs", "(", "nds", "[", "]", "NetDescriber", ")", "(", "[", "]", "string", ",", "error", ")", "{", "var", "lkvmArgs", "[", "]", "string", "\n", "for", "_", ",", "nd", ":=", "range", "nds", "{", "lkvmArgs", "=", "append", "(", "lkvmArgs", ",", "\"--network\"", ")", "\n", "lkvmArg", ":=", "fmt", ".", "Sprintf", "(", "\"mode=tap,tapif=%s,host_ip=%s,guest_ip=%s\"", ",", "nd", ".", "IfName", "(", ")", ",", "nd", ".", "Gateway", "(", ")", ",", "nd", ".", "GuestIP", "(", ")", ")", "\n", "lkvmArgs", "=", "append", "(", "lkvmArgs", ",", "lkvmArg", ")", "\n", "}", "\n", "return", "lkvmArgs", ",", "nil", "\n", "}" ]
// 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
[ "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" ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage1/init/kvm/network.go#L55-L66
train
rkt/rkt
stage1/init/kvm/network.go
generateMacAddress
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 }
go
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 }
[ "func", "generateMacAddress", "(", ")", "(", "net", ".", "HardwareAddr", ",", "error", ")", "{", "mac", ":=", "[", "]", "byte", "{", "2", ",", "0x65", ",", "0x02", ",", "0", ",", "0", ",", "0", ",", "}", "\n", "_", ",", "err", ":=", "rand", ".", "Read", "(", "mac", "[", "3", ":", "6", "]", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"cannot generate random mac address\"", ")", ",", "err", ")", "\n", "}", "\n", "return", "mac", ",", "nil", "\n", "}" ]
// generateMacAddress returns net.HardwareAddr filled with fixed 3 byte prefix // complemented by 3 random bytes.
[ "generateMacAddress", "returns", "net", ".", "HardwareAddr", "filled", "with", "fixed", "3", "byte", "prefix", "complemented", "by", "3", "random", "bytes", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage1/init/kvm/network.go#L70-L83
train
rkt/rkt
tools/depsgen/util.go
replacePlaceholders
func replacePlaceholders(str string, kv ...string) string { for ph, value := range toMap(kv...) { str = strings.Replace(str, "!!!"+ph+"!!!", value, -1) } return str }
go
func replacePlaceholders(str string, kv ...string) string { for ph, value := range toMap(kv...) { str = strings.Replace(str, "!!!"+ph+"!!!", value, -1) } return str }
[ "func", "replacePlaceholders", "(", "str", "string", ",", "kv", "...", "string", ")", "string", "{", "for", "ph", ",", "value", ":=", "range", "toMap", "(", "kv", "...", ")", "{", "str", "=", "strings", ".", "Replace", "(", "str", ",", "\"!!!\"", "+", "ph", "+", "\"!!!\"", ",", "value", ",", "-", "1", ")", "\n", "}", "\n", "return", "str", "\n", "}" ]
// 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.
[ "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", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/tools/depsgen/util.go#L54-L59
train
rkt/rkt
tools/depsgen/util.go
standardFlags
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 }
go
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 }
[ "func", "standardFlags", "(", "cmd", "string", ")", "(", "*", "flag", ".", "FlagSet", ",", "*", "string", ")", "{", "f", ":=", "flag", ".", "NewFlagSet", "(", "appName", "(", ")", "+", "\" \"", "+", "cmd", ",", "flag", ".", "ExitOnError", ")", "\n", "target", ":=", "f", ".", "String", "(", "\"target\"", ",", "\"\"", ",", "\"Make target (example: $(FOO_BINARY))\"", ")", "\n", "return", "f", ",", "target", "\n", "}" ]
// standardFlags returns a new flag set with target flag already set up
[ "standardFlags", "returns", "a", "new", "flag", "set", "with", "target", "flag", "already", "set", "up" ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/tools/depsgen/util.go#L62-L66
train
rkt/rkt
networking/net_plugin.go
netPluginAdd
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 }
go
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 }
[ "func", "(", "e", "*", "podEnv", ")", "netPluginAdd", "(", "n", "*", "activeNet", ",", "netns", "string", ")", "error", "{", "output", ",", "err", ":=", "e", ".", "execNetPlugin", "(", "\"ADD\"", ",", "n", ",", "netns", ")", "\n", "if", "err", "!=", "nil", "{", "return", "pluginErr", "(", "err", ",", "output", ")", "\n", "}", "\n", "pr", ":=", "cnitypes", ".", "Result", "{", "}", "\n", "if", "err", "=", "json", ".", "Unmarshal", "(", "output", ",", "&", "pr", ")", ";", "err", "!=", "nil", "{", "err", "=", "errwrap", ".", "Wrap", "(", "fmt", ".", "Errorf", "(", "\"parsing %q\"", ",", "string", "(", "output", ")", ")", ",", "err", ")", "\n", "return", "errwrap", ".", "Wrap", "(", "fmt", ".", "Errorf", "(", "\"error parsing %q result\"", ",", "n", ".", "conf", ".", "Name", ")", ",", "err", ")", "\n", "}", "\n", "if", "pr", ".", "IP4", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "n", ".", "runtime", ".", "MergeCNIResult", "(", "pr", ")", "\n", "return", "nil", "\n", "}" ]
// Executes a given network plugin. If successful, mutates n.runtime with // the runtime information
[ "Executes", "a", "given", "network", "plugin", ".", "If", "successful", "mutates", "n", ".", "runtime", "with", "the", "runtime", "information" ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/networking/net_plugin.go#L54-L73
train
rkt/rkt
rkt/api_service.go
copyPod
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 }
go
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 }
[ "func", "copyPod", "(", "pod", "*", "v1alpha", ".", "Pod", ")", "*", "v1alpha", ".", "Pod", "{", "p", ":=", "&", "v1alpha", ".", "Pod", "{", "Id", ":", "pod", ".", "Id", ",", "Manifest", ":", "pod", ".", "Manifest", ",", "Annotations", ":", "pod", ".", "Annotations", ",", "}", "\n", "for", "_", ",", "app", ":=", "range", "pod", ".", "Apps", "{", "p", ".", "Apps", "=", "append", "(", "p", ".", "Apps", ",", "&", "v1alpha", ".", "App", "{", "Name", ":", "app", ".", "Name", ",", "Image", ":", "app", ".", "Image", ",", "Annotations", ":", "app", ".", "Annotations", ",", "}", ")", "\n", "}", "\n", "return", "p", "\n", "}" ]
// copyPod copies the immutable information of the pod into the new pod.
[ "copyPod", "copies", "the", "immutable", "information", "of", "the", "pod", "into", "the", "new", "pod", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/api_service.go#L89-L104
train
rkt/rkt
rkt/api_service.go
copyImage
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, } }
go
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, } }
[ "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", ",", "}", "\n", "}" ]
// copyImage copies the image object to avoid modification on the original one.
[ "copyImage", "copies", "the", "image", "object", "to", "avoid", "modification", "on", "the", "original", "one", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/api_service.go#L107-L119
train
rkt/rkt
rkt/api_service.go
GetInfo
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 }
go
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 }
[ "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", "\n", "}" ]
// GetInfo returns the information about the rkt, appc, api server version.
[ "GetInfo", "returns", "the", "information", "about", "the", "rkt", "appc", "api", "server", "version", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/api_service.go#L154-L170
train
rkt/rkt
rkt/api_service.go
containsAllKeyValues
func containsAllKeyValues(actualKVs []*v1alpha.KeyValue, requiredKVs []*v1alpha.KeyValue) bool { for _, requiredKV := range requiredKVs { actualValue, ok := findInKeyValues(actualKVs, requiredKV.Key) if !ok || actualValue != requiredKV.Value { return false } } return true }
go
func containsAllKeyValues(actualKVs []*v1alpha.KeyValue, requiredKVs []*v1alpha.KeyValue) bool { for _, requiredKV := range requiredKVs { actualValue, ok := findInKeyValues(actualKVs, requiredKV.Key) if !ok || actualValue != requiredKV.Value { return false } } return true }
[ "func", "containsAllKeyValues", "(", "actualKVs", "[", "]", "*", "v1alpha", ".", "KeyValue", ",", "requiredKVs", "[", "]", "*", "v1alpha", ".", "KeyValue", ")", "bool", "{", "for", "_", ",", "requiredKV", ":=", "range", "requiredKVs", "{", "actualValue", ",", "ok", ":=", "findInKeyValues", "(", "actualKVs", ",", "requiredKV", ".", "Key", ")", "\n", "if", "!", "ok", "||", "actualValue", "!=", "requiredKV", ".", "Value", "{", "return", "false", "\n", "}", "\n", "}", "\n", "return", "true", "\n", "}" ]
// containsAllKeyValues returns true if the actualKVs contains all of the key-value // pairs listed in requiredKVs, otherwise it returns false.
[ "containsAllKeyValues", "returns", "true", "if", "the", "actualKVs", "contains", "all", "of", "the", "key", "-", "value", "pairs", "listed", "in", "requiredKVs", "otherwise", "it", "returns", "false", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/api_service.go#L183-L191
train
rkt/rkt
rkt/api_service.go
satisfiesPodFilter
func satisfiesPodFilter(pod v1alpha.Pod, filter v1alpha.PodFilter) bool { // Filter according to the ID. if len(filter.Ids) > 0 { s := set.NewString(filter.Ids...) if !s.Has(pod.Id) { return false } } // Filter according to the state. if len(filter.States) > 0 { foundState := false for _, state := range filter.States { if pod.State == state { foundState = true break } } if !foundState { return false } } // Filter according to the app names. if len(filter.AppNames) > 0 { s := set.NewString() for _, app := range pod.Apps { s.Insert(app.Name) } if !s.HasAll(filter.AppNames...) { return false } } // Filter according to the image IDs. if len(filter.ImageIds) > 0 { s := set.NewString() for _, app := range pod.Apps { s.Insert(app.Image.Id) } if !s.HasAll(filter.ImageIds...) { return false } } // Filter according to the network names. if len(filter.NetworkNames) > 0 { s := set.NewString() for _, network := range pod.Networks { s.Insert(network.Name) } if !s.HasAll(filter.NetworkNames...) { return false } } // Filter according to the annotations. if len(filter.Annotations) > 0 { if !containsAllKeyValues(pod.Annotations, filter.Annotations) { return false } } // Filter according to the cgroup. if len(filter.Cgroups) > 0 { s := set.NewString(filter.Cgroups...) if !s.Has(pod.Cgroup) { return false } } // Filter if pod's cgroup is a prefix of the passed in cgroup if len(filter.PodSubCgroups) > 0 { matched := false if pod.Cgroup != "" { for _, cgroup := range filter.PodSubCgroups { if strings.HasPrefix(cgroup, pod.Cgroup) { matched = true break } } } if !matched { return false } } return true }
go
func satisfiesPodFilter(pod v1alpha.Pod, filter v1alpha.PodFilter) bool { // Filter according to the ID. if len(filter.Ids) > 0 { s := set.NewString(filter.Ids...) if !s.Has(pod.Id) { return false } } // Filter according to the state. if len(filter.States) > 0 { foundState := false for _, state := range filter.States { if pod.State == state { foundState = true break } } if !foundState { return false } } // Filter according to the app names. if len(filter.AppNames) > 0 { s := set.NewString() for _, app := range pod.Apps { s.Insert(app.Name) } if !s.HasAll(filter.AppNames...) { return false } } // Filter according to the image IDs. if len(filter.ImageIds) > 0 { s := set.NewString() for _, app := range pod.Apps { s.Insert(app.Image.Id) } if !s.HasAll(filter.ImageIds...) { return false } } // Filter according to the network names. if len(filter.NetworkNames) > 0 { s := set.NewString() for _, network := range pod.Networks { s.Insert(network.Name) } if !s.HasAll(filter.NetworkNames...) { return false } } // Filter according to the annotations. if len(filter.Annotations) > 0 { if !containsAllKeyValues(pod.Annotations, filter.Annotations) { return false } } // Filter according to the cgroup. if len(filter.Cgroups) > 0 { s := set.NewString(filter.Cgroups...) if !s.Has(pod.Cgroup) { return false } } // Filter if pod's cgroup is a prefix of the passed in cgroup if len(filter.PodSubCgroups) > 0 { matched := false if pod.Cgroup != "" { for _, cgroup := range filter.PodSubCgroups { if strings.HasPrefix(cgroup, pod.Cgroup) { matched = true break } } } if !matched { return false } } return true }
[ "func", "satisfiesPodFilter", "(", "pod", "v1alpha", ".", "Pod", ",", "filter", "v1alpha", ".", "PodFilter", ")", "bool", "{", "if", "len", "(", "filter", ".", "Ids", ")", ">", "0", "{", "s", ":=", "set", ".", "NewString", "(", "filter", ".", "Ids", "...", ")", "\n", "if", "!", "s", ".", "Has", "(", "pod", ".", "Id", ")", "{", "return", "false", "\n", "}", "\n", "}", "\n", "if", "len", "(", "filter", ".", "States", ")", ">", "0", "{", "foundState", ":=", "false", "\n", "for", "_", ",", "state", ":=", "range", "filter", ".", "States", "{", "if", "pod", ".", "State", "==", "state", "{", "foundState", "=", "true", "\n", "break", "\n", "}", "\n", "}", "\n", "if", "!", "foundState", "{", "return", "false", "\n", "}", "\n", "}", "\n", "if", "len", "(", "filter", ".", "AppNames", ")", ">", "0", "{", "s", ":=", "set", ".", "NewString", "(", ")", "\n", "for", "_", ",", "app", ":=", "range", "pod", ".", "Apps", "{", "s", ".", "Insert", "(", "app", ".", "Name", ")", "\n", "}", "\n", "if", "!", "s", ".", "HasAll", "(", "filter", ".", "AppNames", "...", ")", "{", "return", "false", "\n", "}", "\n", "}", "\n", "if", "len", "(", "filter", ".", "ImageIds", ")", ">", "0", "{", "s", ":=", "set", ".", "NewString", "(", ")", "\n", "for", "_", ",", "app", ":=", "range", "pod", ".", "Apps", "{", "s", ".", "Insert", "(", "app", ".", "Image", ".", "Id", ")", "\n", "}", "\n", "if", "!", "s", ".", "HasAll", "(", "filter", ".", "ImageIds", "...", ")", "{", "return", "false", "\n", "}", "\n", "}", "\n", "if", "len", "(", "filter", ".", "NetworkNames", ")", ">", "0", "{", "s", ":=", "set", ".", "NewString", "(", ")", "\n", "for", "_", ",", "network", ":=", "range", "pod", ".", "Networks", "{", "s", ".", "Insert", "(", "network", ".", "Name", ")", "\n", "}", "\n", "if", "!", "s", ".", "HasAll", "(", "filter", ".", "NetworkNames", "...", ")", "{", "return", "false", "\n", "}", "\n", "}", "\n", "if", "len", "(", "filter", ".", "Annotations", ")", ">", "0", "{", "if", "!", "containsAllKeyValues", "(", "pod", ".", "Annotations", ",", "filter", ".", "Annotations", ")", "{", "return", "false", "\n", "}", "\n", "}", "\n", "if", "len", "(", "filter", ".", "Cgroups", ")", ">", "0", "{", "s", ":=", "set", ".", "NewString", "(", "filter", ".", "Cgroups", "...", ")", "\n", "if", "!", "s", ".", "Has", "(", "pod", ".", "Cgroup", ")", "{", "return", "false", "\n", "}", "\n", "}", "\n", "if", "len", "(", "filter", ".", "PodSubCgroups", ")", ">", "0", "{", "matched", ":=", "false", "\n", "if", "pod", ".", "Cgroup", "!=", "\"\"", "{", "for", "_", ",", "cgroup", ":=", "range", "filter", ".", "PodSubCgroups", "{", "if", "strings", ".", "HasPrefix", "(", "cgroup", ",", "pod", ".", "Cgroup", ")", "{", "matched", "=", "true", "\n", "break", "\n", "}", "\n", "}", "\n", "}", "\n", "if", "!", "matched", "{", "return", "false", "\n", "}", "\n", "}", "\n", "return", "true", "\n", "}" ]
// satisfiesPodFilter returns true if the pod satisfies the filter. // The pod, filter must not be nil.
[ "satisfiesPodFilter", "returns", "true", "if", "the", "pod", "satisfies", "the", "filter", ".", "The", "pod", "filter", "must", "not", "be", "nil", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/api_service.go#L210-L299
train
rkt/rkt
rkt/api_service.go
satisfiesAnyPodFilters
func satisfiesAnyPodFilters(pod *v1alpha.Pod, filters []*v1alpha.PodFilter) bool { // No filters, return true directly. if len(filters) == 0 { return true } for _, filter := range filters { if satisfiesPodFilter(*pod, *filter) { return true } } return false }
go
func satisfiesAnyPodFilters(pod *v1alpha.Pod, filters []*v1alpha.PodFilter) bool { // No filters, return true directly. if len(filters) == 0 { return true } for _, filter := range filters { if satisfiesPodFilter(*pod, *filter) { return true } } return false }
[ "func", "satisfiesAnyPodFilters", "(", "pod", "*", "v1alpha", ".", "Pod", ",", "filters", "[", "]", "*", "v1alpha", ".", "PodFilter", ")", "bool", "{", "if", "len", "(", "filters", ")", "==", "0", "{", "return", "true", "\n", "}", "\n", "for", "_", ",", "filter", ":=", "range", "filters", "{", "if", "satisfiesPodFilter", "(", "*", "pod", ",", "*", "filter", ")", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// satisfiesAnyPodFilters returns true if any of the filter conditions is satisfied // by the pod, or there's no filters.
[ "satisfiesAnyPodFilters", "returns", "true", "if", "any", "of", "the", "filter", "conditions", "is", "satisfied", "by", "the", "pod", "or", "there", "s", "no", "filters", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/api_service.go#L303-L315
train
rkt/rkt
rkt/api_service.go
getApplist
func getApplist(manifest *schema.PodManifest) []*v1alpha.App { var apps []*v1alpha.App for _, app := range manifest.Apps { img := &v1alpha.Image{ BaseFormat: &v1alpha.ImageFormat{ // Only support appc image now. If it's a docker image, then it // will be transformed to appc before storing in the disk store. Type: v1alpha.ImageType_IMAGE_TYPE_APPC, Version: schema.AppContainerVersion.String(), }, Id: app.Image.ID.String(), // Only image format and image ID are returned in 'ListPods()'. } apps = append(apps, &v1alpha.App{ Name: app.Name.String(), Image: img, Annotations: convertAnnotationsToKeyValue(app.Annotations), State: v1alpha.AppState_APP_STATE_UNDEFINED, ExitCode: -1, }) } return apps }
go
func getApplist(manifest *schema.PodManifest) []*v1alpha.App { var apps []*v1alpha.App for _, app := range manifest.Apps { img := &v1alpha.Image{ BaseFormat: &v1alpha.ImageFormat{ // Only support appc image now. If it's a docker image, then it // will be transformed to appc before storing in the disk store. Type: v1alpha.ImageType_IMAGE_TYPE_APPC, Version: schema.AppContainerVersion.String(), }, Id: app.Image.ID.String(), // Only image format and image ID are returned in 'ListPods()'. } apps = append(apps, &v1alpha.App{ Name: app.Name.String(), Image: img, Annotations: convertAnnotationsToKeyValue(app.Annotations), State: v1alpha.AppState_APP_STATE_UNDEFINED, ExitCode: -1, }) } return apps }
[ "func", "getApplist", "(", "manifest", "*", "schema", ".", "PodManifest", ")", "[", "]", "*", "v1alpha", ".", "App", "{", "var", "apps", "[", "]", "*", "v1alpha", ".", "App", "\n", "for", "_", ",", "app", ":=", "range", "manifest", ".", "Apps", "{", "img", ":=", "&", "v1alpha", ".", "Image", "{", "BaseFormat", ":", "&", "v1alpha", ".", "ImageFormat", "{", "Type", ":", "v1alpha", ".", "ImageType_IMAGE_TYPE_APPC", ",", "Version", ":", "schema", ".", "AppContainerVersion", ".", "String", "(", ")", ",", "}", ",", "Id", ":", "app", ".", "Image", ".", "ID", ".", "String", "(", ")", ",", "}", "\n", "apps", "=", "append", "(", "apps", ",", "&", "v1alpha", ".", "App", "{", "Name", ":", "app", ".", "Name", ".", "String", "(", ")", ",", "Image", ":", "img", ",", "Annotations", ":", "convertAnnotationsToKeyValue", "(", "app", ".", "Annotations", ")", ",", "State", ":", "v1alpha", ".", "AppState_APP_STATE_UNDEFINED", ",", "ExitCode", ":", "-", "1", ",", "}", ")", "\n", "}", "\n", "return", "apps", "\n", "}" ]
// getApplist returns a list of apps in the pod.
[ "getApplist", "returns", "a", "list", "of", "apps", "in", "the", "pod", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/api_service.go#L370-L393
train
rkt/rkt
rkt/api_service.go
getNetworks
func getNetworks(p *pkgPod.Pod) []*v1alpha.Network { var networks []*v1alpha.Network for _, n := range p.Nets { networks = append(networks, &v1alpha.Network{ Name: n.NetName, // There will be IPv6 support soon so distinguish between v4 and v6 Ipv4: n.IP.String(), }) } return networks }
go
func getNetworks(p *pkgPod.Pod) []*v1alpha.Network { var networks []*v1alpha.Network for _, n := range p.Nets { networks = append(networks, &v1alpha.Network{ Name: n.NetName, // There will be IPv6 support soon so distinguish between v4 and v6 Ipv4: n.IP.String(), }) } return networks }
[ "func", "getNetworks", "(", "p", "*", "pkgPod", ".", "Pod", ")", "[", "]", "*", "v1alpha", ".", "Network", "{", "var", "networks", "[", "]", "*", "v1alpha", ".", "Network", "\n", "for", "_", ",", "n", ":=", "range", "p", ".", "Nets", "{", "networks", "=", "append", "(", "networks", ",", "&", "v1alpha", ".", "Network", "{", "Name", ":", "n", ".", "NetName", ",", "Ipv4", ":", "n", ".", "IP", ".", "String", "(", ")", ",", "}", ")", "\n", "}", "\n", "return", "networks", "\n", "}" ]
// getNetworks returns the list of the info of the network that the pod belongs to.
[ "getNetworks", "returns", "the", "list", "of", "the", "info", "of", "the", "network", "that", "the", "pod", "belongs", "to", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/api_service.go#L396-L406
train
rkt/rkt
rkt/api_service.go
fillStaticAppInfo
func fillStaticAppInfo(store *imagestore.Store, pod *pkgPod.Pod, v1pod *v1alpha.Pod) error { var errlist []error // Fill static app image info. for _, app := range v1pod.Apps { // Fill app's image info. app.Image = &v1alpha.Image{ BaseFormat: &v1alpha.ImageFormat{ // Only support appc image now. If it's a docker image, then it // will be transformed to appc before storing in the disk store. Type: v1alpha.ImageType_IMAGE_TYPE_APPC, Version: schema.AppContainerVersion.String(), }, Id: app.Image.Id, // Other information are not available because they require the image // info from store. Some of it is filled in below if possible. } im, err := pod.AppImageManifest(app.Name) if err != nil { stderr.PrintE(fmt.Sprintf("failed to get image manifests for app %q", app.Name), err) errlist = append(errlist, err) } else { app.Image.Name = im.Name.String() version, ok := im.Labels.Get("version") if !ok { version = "latest" } app.Image.Version = version } } if len(errlist) != 0 { return errs{errlist} } return nil }
go
func fillStaticAppInfo(store *imagestore.Store, pod *pkgPod.Pod, v1pod *v1alpha.Pod) error { var errlist []error // Fill static app image info. for _, app := range v1pod.Apps { // Fill app's image info. app.Image = &v1alpha.Image{ BaseFormat: &v1alpha.ImageFormat{ // Only support appc image now. If it's a docker image, then it // will be transformed to appc before storing in the disk store. Type: v1alpha.ImageType_IMAGE_TYPE_APPC, Version: schema.AppContainerVersion.String(), }, Id: app.Image.Id, // Other information are not available because they require the image // info from store. Some of it is filled in below if possible. } im, err := pod.AppImageManifest(app.Name) if err != nil { stderr.PrintE(fmt.Sprintf("failed to get image manifests for app %q", app.Name), err) errlist = append(errlist, err) } else { app.Image.Name = im.Name.String() version, ok := im.Labels.Get("version") if !ok { version = "latest" } app.Image.Version = version } } if len(errlist) != 0 { return errs{errlist} } return nil }
[ "func", "fillStaticAppInfo", "(", "store", "*", "imagestore", ".", "Store", ",", "pod", "*", "pkgPod", ".", "Pod", ",", "v1pod", "*", "v1alpha", ".", "Pod", ")", "error", "{", "var", "errlist", "[", "]", "error", "\n", "for", "_", ",", "app", ":=", "range", "v1pod", ".", "Apps", "{", "app", ".", "Image", "=", "&", "v1alpha", ".", "Image", "{", "BaseFormat", ":", "&", "v1alpha", ".", "ImageFormat", "{", "Type", ":", "v1alpha", ".", "ImageType_IMAGE_TYPE_APPC", ",", "Version", ":", "schema", ".", "AppContainerVersion", ".", "String", "(", ")", ",", "}", ",", "Id", ":", "app", ".", "Image", ".", "Id", ",", "}", "\n", "im", ",", "err", ":=", "pod", ".", "AppImageManifest", "(", "app", ".", "Name", ")", "\n", "if", "err", "!=", "nil", "{", "stderr", ".", "PrintE", "(", "fmt", ".", "Sprintf", "(", "\"failed to get image manifests for app %q\"", ",", "app", ".", "Name", ")", ",", "err", ")", "\n", "errlist", "=", "append", "(", "errlist", ",", "err", ")", "\n", "}", "else", "{", "app", ".", "Image", ".", "Name", "=", "im", ".", "Name", ".", "String", "(", ")", "\n", "version", ",", "ok", ":=", "im", ".", "Labels", ".", "Get", "(", "\"version\"", ")", "\n", "if", "!", "ok", "{", "version", "=", "\"latest\"", "\n", "}", "\n", "app", ".", "Image", ".", "Version", "=", "version", "\n", "}", "\n", "}", "\n", "if", "len", "(", "errlist", ")", "!=", "0", "{", "return", "errs", "{", "errlist", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// fillStaticAppInfo will modify the 'v1pod' in place with the information retrieved with 'pod'. // Today, these information are static and will not change during the pod's lifecycle.
[ "fillStaticAppInfo", "will", "modify", "the", "v1pod", "in", "place", "with", "the", "information", "retrieved", "with", "pod", ".", "Today", "these", "information", "are", "static", "and", "will", "not", "change", "during", "the", "pod", "s", "lifecycle", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/api_service.go#L419-L456
train
rkt/rkt
rkt/api_service.go
getBasicPod
func (s *v1AlphaAPIServer) getBasicPod(p *pkgPod.Pod) *v1alpha.Pod { mtime, mtimeErr := getPodManifestModTime(p) if mtimeErr != nil { stderr.PrintE(fmt.Sprintf("failed to read the pod manifest's mtime for pod %q", p.UUID), mtimeErr) } // Couldn't use pod.uuid directly as it's a pointer. itemValue, found := s.podCache.Get(p.UUID.String()) if found && mtimeErr == nil { cacheItem := itemValue.(*podCacheItem) // Check the mtime to make sure we are not returning stale manifests. if !mtime.After(cacheItem.mtime) { return copyPod(cacheItem.pod) } } pod, err := s.getBasicPodFromDisk(p) if mtimeErr != nil || err != nil { // If any error happens or the mtime is unknown, // returns the raw pod directly without adding it to the cache. return pod } cacheItem := &podCacheItem{pod, mtime} s.podCache.Add(p.UUID.String(), cacheItem) // Return a copy of the pod, so the cached pod is not mutated later. return copyPod(cacheItem.pod) }
go
func (s *v1AlphaAPIServer) getBasicPod(p *pkgPod.Pod) *v1alpha.Pod { mtime, mtimeErr := getPodManifestModTime(p) if mtimeErr != nil { stderr.PrintE(fmt.Sprintf("failed to read the pod manifest's mtime for pod %q", p.UUID), mtimeErr) } // Couldn't use pod.uuid directly as it's a pointer. itemValue, found := s.podCache.Get(p.UUID.String()) if found && mtimeErr == nil { cacheItem := itemValue.(*podCacheItem) // Check the mtime to make sure we are not returning stale manifests. if !mtime.After(cacheItem.mtime) { return copyPod(cacheItem.pod) } } pod, err := s.getBasicPodFromDisk(p) if mtimeErr != nil || err != nil { // If any error happens or the mtime is unknown, // returns the raw pod directly without adding it to the cache. return pod } cacheItem := &podCacheItem{pod, mtime} s.podCache.Add(p.UUID.String(), cacheItem) // Return a copy of the pod, so the cached pod is not mutated later. return copyPod(cacheItem.pod) }
[ "func", "(", "s", "*", "v1AlphaAPIServer", ")", "getBasicPod", "(", "p", "*", "pkgPod", ".", "Pod", ")", "*", "v1alpha", ".", "Pod", "{", "mtime", ",", "mtimeErr", ":=", "getPodManifestModTime", "(", "p", ")", "\n", "if", "mtimeErr", "!=", "nil", "{", "stderr", ".", "PrintE", "(", "fmt", ".", "Sprintf", "(", "\"failed to read the pod manifest's mtime for pod %q\"", ",", "p", ".", "UUID", ")", ",", "mtimeErr", ")", "\n", "}", "\n", "itemValue", ",", "found", ":=", "s", ".", "podCache", ".", "Get", "(", "p", ".", "UUID", ".", "String", "(", ")", ")", "\n", "if", "found", "&&", "mtimeErr", "==", "nil", "{", "cacheItem", ":=", "itemValue", ".", "(", "*", "podCacheItem", ")", "\n", "if", "!", "mtime", ".", "After", "(", "cacheItem", ".", "mtime", ")", "{", "return", "copyPod", "(", "cacheItem", ".", "pod", ")", "\n", "}", "\n", "}", "\n", "pod", ",", "err", ":=", "s", ".", "getBasicPodFromDisk", "(", "p", ")", "\n", "if", "mtimeErr", "!=", "nil", "||", "err", "!=", "nil", "{", "return", "pod", "\n", "}", "\n", "cacheItem", ":=", "&", "podCacheItem", "{", "pod", ",", "mtime", "}", "\n", "s", ".", "podCache", ".", "Add", "(", "p", ".", "UUID", ".", "String", "(", ")", ",", "cacheItem", ")", "\n", "return", "copyPod", "(", "cacheItem", ".", "pod", ")", "\n", "}" ]
// getBasicPod returns v1alpha.Pod with basic pod information.
[ "getBasicPod", "returns", "v1alpha", ".", "Pod", "with", "basic", "pod", "information", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/api_service.go#L484-L513
train

No dataset card yet

New: Create and edit this dataset card directly on the website!

Contribute a Dataset Card
Downloads last month
0
Add dataset card