repo
stringlengths
5
67
path
stringlengths
4
218
func_name
stringlengths
0
151
original_string
stringlengths
52
373k
language
stringclasses
6 values
code
stringlengths
52
373k
code_tokens
listlengths
10
512
docstring
stringlengths
3
47.2k
docstring_tokens
listlengths
3
234
sha
stringlengths
40
40
url
stringlengths
85
339
partition
stringclasses
3 values
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
rkt/rkt
rkt/api_service.go
aciInfoToV1AlphaAPIImage
func aciInfoToV1AlphaAPIImage(store *imagestore.Store, aciInfo *imagestore.ACIInfo) (*v1alpha.Image, error) { manifest, err := store.GetImageManifestJSON(aciInfo.BlobKey) if err != nil { stderr.PrintE("failed to read the image manifest", err) return nil, err } var im schema.ImageManifest if err = json.Unmarshal(manifest, &im); err != nil { stderr.PrintE("failed to unmarshal image manifest", err) return nil, err } version, ok := im.Labels.Get("version") if !ok { version = "latest" } return &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: aciInfo.BlobKey, Name: im.Name.String(), Version: version, ImportTimestamp: aciInfo.ImportTime.Unix(), Manifest: manifest, Size: aciInfo.Size + aciInfo.TreeStoreSize, Annotations: convertAnnotationsToKeyValue(im.Annotations), Labels: convertLabelsToKeyValue(im.Labels), }, nil }
go
func aciInfoToV1AlphaAPIImage(store *imagestore.Store, aciInfo *imagestore.ACIInfo) (*v1alpha.Image, error) { manifest, err := store.GetImageManifestJSON(aciInfo.BlobKey) if err != nil { stderr.PrintE("failed to read the image manifest", err) return nil, err } var im schema.ImageManifest if err = json.Unmarshal(manifest, &im); err != nil { stderr.PrintE("failed to unmarshal image manifest", err) return nil, err } version, ok := im.Labels.Get("version") if !ok { version = "latest" } return &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: aciInfo.BlobKey, Name: im.Name.String(), Version: version, ImportTimestamp: aciInfo.ImportTime.Unix(), Manifest: manifest, Size: aciInfo.Size + aciInfo.TreeStoreSize, Annotations: convertAnnotationsToKeyValue(im.Annotations), Labels: convertLabelsToKeyValue(im.Labels), }, nil }
[ "func", "aciInfoToV1AlphaAPIImage", "(", "store", "*", "imagestore", ".", "Store", ",", "aciInfo", "*", "imagestore", ".", "ACIInfo", ")", "(", "*", "v1alpha", ".", "Image", ",", "error", ")", "{", "manifest", ",", "err", ":=", "store", ".", "GetImageManifestJSON", "(", "aciInfo", ".", "BlobKey", ")", "\n", "if", "err", "!=", "nil", "{", "stderr", ".", "PrintE", "(", "\"failed to read the image manifest\"", ",", "err", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n", "var", "im", "schema", ".", "ImageManifest", "\n", "if", "err", "=", "json", ".", "Unmarshal", "(", "manifest", ",", "&", "im", ")", ";", "err", "!=", "nil", "{", "stderr", ".", "PrintE", "(", "\"failed to unmarshal image manifest\"", ",", "err", ")", "\n", "return", "nil", ",", "err", "\n", "}", "\n", "version", ",", "ok", ":=", "im", ".", "Labels", ".", "Get", "(", "\"version\"", ")", "\n", "if", "!", "ok", "{", "version", "=", "\"latest\"", "\n", "}", "\n", "return", "&", "v1alpha", ".", "Image", "{", "BaseFormat", ":", "&", "v1alpha", ".", "ImageFormat", "{", "Type", ":", "v1alpha", ".", "ImageType_IMAGE_TYPE_APPC", ",", "Version", ":", "schema", ".", "AppContainerVersion", ".", "String", "(", ")", ",", "}", ",", "Id", ":", "aciInfo", ".", "BlobKey", ",", "Name", ":", "im", ".", "Name", ".", "String", "(", ")", ",", "Version", ":", "version", ",", "ImportTimestamp", ":", "aciInfo", ".", "ImportTime", ".", "Unix", "(", ")", ",", "Manifest", ":", "manifest", ",", "Size", ":", "aciInfo", ".", "Size", "+", "aciInfo", ".", "TreeStoreSize", ",", "Annotations", ":", "convertAnnotationsToKeyValue", "(", "im", ".", "Annotations", ")", ",", "Labels", ":", "convertLabelsToKeyValue", "(", "im", ".", "Labels", ")", ",", "}", ",", "nil", "\n", "}" ]
// aciInfoToV1AlphaAPIImage takes an aciInfo object and construct the v1alpha.Image object.
[ "aciInfoToV1AlphaAPIImage", "takes", "an", "aciInfo", "object", "and", "construct", "the", "v1alpha", ".", "Image", "object", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/api_service.go#L654-L688
train
rkt/rkt
rkt/api_service.go
satisfiesImageFilter
func satisfiesImageFilter(image v1alpha.Image, filter v1alpha.ImageFilter) bool { // Filter according to the IDs. if len(filter.Ids) > 0 { s := set.NewString(filter.Ids...) if !s.Has(image.Id) { return false } } // Filter according to the image full names. if len(filter.FullNames) > 0 { s := set.NewString(filter.FullNames...) if !s.Has(image.Name) { return false } } // Filter according to the image name prefixes. if len(filter.Prefixes) > 0 { s := set.NewString(filter.Prefixes...) if !s.ConditionalHas(isPrefixOf, image.Name) { return false } } // Filter according to the image base name. if len(filter.BaseNames) > 0 { s := set.NewString(filter.BaseNames...) if !s.ConditionalHas(isBaseNameOf, image.Name) { return false } } // Filter according to the image keywords. if len(filter.Keywords) > 0 { s := set.NewString(filter.Keywords...) if !s.ConditionalHas(isPartOf, image.Name) { return false } } // Filter according to the imported time. if filter.ImportedAfter > 0 { if image.ImportTimestamp <= filter.ImportedAfter { return false } } if filter.ImportedBefore > 0 { if image.ImportTimestamp >= filter.ImportedBefore { return false } } // Filter according to the image labels. if len(filter.Labels) > 0 { if !containsAllKeyValues(image.Labels, filter.Labels) { return false } } // Filter according to the annotations. if len(filter.Annotations) > 0 { if !containsAllKeyValues(image.Annotations, filter.Annotations) { return false } } return true }
go
func satisfiesImageFilter(image v1alpha.Image, filter v1alpha.ImageFilter) bool { // Filter according to the IDs. if len(filter.Ids) > 0 { s := set.NewString(filter.Ids...) if !s.Has(image.Id) { return false } } // Filter according to the image full names. if len(filter.FullNames) > 0 { s := set.NewString(filter.FullNames...) if !s.Has(image.Name) { return false } } // Filter according to the image name prefixes. if len(filter.Prefixes) > 0 { s := set.NewString(filter.Prefixes...) if !s.ConditionalHas(isPrefixOf, image.Name) { return false } } // Filter according to the image base name. if len(filter.BaseNames) > 0 { s := set.NewString(filter.BaseNames...) if !s.ConditionalHas(isBaseNameOf, image.Name) { return false } } // Filter according to the image keywords. if len(filter.Keywords) > 0 { s := set.NewString(filter.Keywords...) if !s.ConditionalHas(isPartOf, image.Name) { return false } } // Filter according to the imported time. if filter.ImportedAfter > 0 { if image.ImportTimestamp <= filter.ImportedAfter { return false } } if filter.ImportedBefore > 0 { if image.ImportTimestamp >= filter.ImportedBefore { return false } } // Filter according to the image labels. if len(filter.Labels) > 0 { if !containsAllKeyValues(image.Labels, filter.Labels) { return false } } // Filter according to the annotations. if len(filter.Annotations) > 0 { if !containsAllKeyValues(image.Annotations, filter.Annotations) { return false } } return true }
[ "func", "satisfiesImageFilter", "(", "image", "v1alpha", ".", "Image", ",", "filter", "v1alpha", ".", "ImageFilter", ")", "bool", "{", "if", "len", "(", "filter", ".", "Ids", ")", ">", "0", "{", "s", ":=", "set", ".", "NewString", "(", "filter", ".", "Ids", "...", ")", "\n", "if", "!", "s", ".", "Has", "(", "image", ".", "Id", ")", "{", "return", "false", "\n", "}", "\n", "}", "\n", "if", "len", "(", "filter", ".", "FullNames", ")", ">", "0", "{", "s", ":=", "set", ".", "NewString", "(", "filter", ".", "FullNames", "...", ")", "\n", "if", "!", "s", ".", "Has", "(", "image", ".", "Name", ")", "{", "return", "false", "\n", "}", "\n", "}", "\n", "if", "len", "(", "filter", ".", "Prefixes", ")", ">", "0", "{", "s", ":=", "set", ".", "NewString", "(", "filter", ".", "Prefixes", "...", ")", "\n", "if", "!", "s", ".", "ConditionalHas", "(", "isPrefixOf", ",", "image", ".", "Name", ")", "{", "return", "false", "\n", "}", "\n", "}", "\n", "if", "len", "(", "filter", ".", "BaseNames", ")", ">", "0", "{", "s", ":=", "set", ".", "NewString", "(", "filter", ".", "BaseNames", "...", ")", "\n", "if", "!", "s", ".", "ConditionalHas", "(", "isBaseNameOf", ",", "image", ".", "Name", ")", "{", "return", "false", "\n", "}", "\n", "}", "\n", "if", "len", "(", "filter", ".", "Keywords", ")", ">", "0", "{", "s", ":=", "set", ".", "NewString", "(", "filter", ".", "Keywords", "...", ")", "\n", "if", "!", "s", ".", "ConditionalHas", "(", "isPartOf", ",", "image", ".", "Name", ")", "{", "return", "false", "\n", "}", "\n", "}", "\n", "if", "filter", ".", "ImportedAfter", ">", "0", "{", "if", "image", ".", "ImportTimestamp", "<=", "filter", ".", "ImportedAfter", "{", "return", "false", "\n", "}", "\n", "}", "\n", "if", "filter", ".", "ImportedBefore", ">", "0", "{", "if", "image", ".", "ImportTimestamp", ">=", "filter", ".", "ImportedBefore", "{", "return", "false", "\n", "}", "\n", "}", "\n", "if", "len", "(", "filter", ".", "Labels", ")", ">", "0", "{", "if", "!", "containsAllKeyValues", "(", "image", ".", "Labels", ",", "filter", ".", "Labels", ")", "{", "return", "false", "\n", "}", "\n", "}", "\n", "if", "len", "(", "filter", ".", "Annotations", ")", ">", "0", "{", "if", "!", "containsAllKeyValues", "(", "image", ".", "Annotations", ",", "filter", ".", "Annotations", ")", "{", "return", "false", "\n", "}", "\n", "}", "\n", "return", "true", "\n", "}" ]
// satisfiesImageFilter returns true if the image satisfies the filter. // The image, filter must not be nil.
[ "satisfiesImageFilter", "returns", "true", "if", "the", "image", "satisfies", "the", "filter", ".", "The", "image", "filter", "must", "not", "be", "nil", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/api_service.go#L716-L784
train
rkt/rkt
rkt/api_service.go
satisfiesAnyImageFilters
func satisfiesAnyImageFilters(image *v1alpha.Image, filters []*v1alpha.ImageFilter) bool { // No filters, return true directly. if len(filters) == 0 { return true } for _, filter := range filters { if satisfiesImageFilter(*image, *filter) { return true } } return false }
go
func satisfiesAnyImageFilters(image *v1alpha.Image, filters []*v1alpha.ImageFilter) bool { // No filters, return true directly. if len(filters) == 0 { return true } for _, filter := range filters { if satisfiesImageFilter(*image, *filter) { return true } } return false }
[ "func", "satisfiesAnyImageFilters", "(", "image", "*", "v1alpha", ".", "Image", ",", "filters", "[", "]", "*", "v1alpha", ".", "ImageFilter", ")", "bool", "{", "if", "len", "(", "filters", ")", "==", "0", "{", "return", "true", "\n", "}", "\n", "for", "_", ",", "filter", ":=", "range", "filters", "{", "if", "satisfiesImageFilter", "(", "*", "image", ",", "*", "filter", ")", "{", "return", "true", "\n", "}", "\n", "}", "\n", "return", "false", "\n", "}" ]
// satisfiesAnyImageFilters returns true if any of the filter conditions is satisfied // by the image, or there's no filters.
[ "satisfiesAnyImageFilters", "returns", "true", "if", "any", "of", "the", "filter", "conditions", "is", "satisfied", "by", "the", "image", "or", "there", "s", "no", "filters", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/api_service.go#L788-L799
train
rkt/rkt
rkt/api_service.go
runAPIService
func runAPIService(cmd *cobra.Command, args []string) (exit int) { // Set up the signal handler here so we can make sure the // signals are caught after print the starting message. signal.Notify(exitCh, syscall.SIGINT, syscall.SIGTERM) stderr.Print("API service starting...") listeners, err := openAPISockets() if err != nil { stderr.PrintE("Failed to open sockets", err) return 254 } if len(listeners) == 0 { // This is unlikely... stderr.Println("No sockets to listen to. Quitting.") return 254 } publicServer := grpc.NewServer() // TODO(yifan): Add TLS credential option. v1AlphaAPIServer, err := newV1AlphaAPIServer() if err != nil { stderr.PrintE("failed to create API service", err) return 254 } v1alpha.RegisterPublicAPIServer(publicServer, v1AlphaAPIServer) for _, l := range listeners { defer l.Close() go publicServer.Serve(l) } stderr.Printf("API service running") <-exitCh stderr.Print("API service exiting...") return }
go
func runAPIService(cmd *cobra.Command, args []string) (exit int) { // Set up the signal handler here so we can make sure the // signals are caught after print the starting message. signal.Notify(exitCh, syscall.SIGINT, syscall.SIGTERM) stderr.Print("API service starting...") listeners, err := openAPISockets() if err != nil { stderr.PrintE("Failed to open sockets", err) return 254 } if len(listeners) == 0 { // This is unlikely... stderr.Println("No sockets to listen to. Quitting.") return 254 } publicServer := grpc.NewServer() // TODO(yifan): Add TLS credential option. v1AlphaAPIServer, err := newV1AlphaAPIServer() if err != nil { stderr.PrintE("failed to create API service", err) return 254 } v1alpha.RegisterPublicAPIServer(publicServer, v1AlphaAPIServer) for _, l := range listeners { defer l.Close() go publicServer.Serve(l) } stderr.Printf("API service running") <-exitCh stderr.Print("API service exiting...") return }
[ "func", "runAPIService", "(", "cmd", "*", "cobra", ".", "Command", ",", "args", "[", "]", "string", ")", "(", "exit", "int", ")", "{", "signal", ".", "Notify", "(", "exitCh", ",", "syscall", ".", "SIGINT", ",", "syscall", ".", "SIGTERM", ")", "\n", "stderr", ".", "Print", "(", "\"API service starting...\"", ")", "\n", "listeners", ",", "err", ":=", "openAPISockets", "(", ")", "\n", "if", "err", "!=", "nil", "{", "stderr", ".", "PrintE", "(", "\"Failed to open sockets\"", ",", "err", ")", "\n", "return", "254", "\n", "}", "\n", "if", "len", "(", "listeners", ")", "==", "0", "{", "stderr", ".", "Println", "(", "\"No sockets to listen to. Quitting.\"", ")", "\n", "return", "254", "\n", "}", "\n", "publicServer", ":=", "grpc", ".", "NewServer", "(", ")", "\n", "v1AlphaAPIServer", ",", "err", ":=", "newV1AlphaAPIServer", "(", ")", "\n", "if", "err", "!=", "nil", "{", "stderr", ".", "PrintE", "(", "\"failed to create API service\"", ",", "err", ")", "\n", "return", "254", "\n", "}", "\n", "v1alpha", ".", "RegisterPublicAPIServer", "(", "publicServer", ",", "v1AlphaAPIServer", ")", "\n", "for", "_", ",", "l", ":=", "range", "listeners", "{", "defer", "l", ".", "Close", "(", ")", "\n", "go", "publicServer", ".", "Serve", "(", "l", ")", "\n", "}", "\n", "stderr", ".", "Printf", "(", "\"API service running\"", ")", "\n", "<-", "exitCh", "\n", "stderr", ".", "Print", "(", "\"API service exiting...\"", ")", "\n", "return", "\n", "}" ]
// Open one or more listening sockets, then start the gRPC server
[ "Open", "one", "or", "more", "listening", "sockets", "then", "start", "the", "gRPC", "server" ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/api_service.go#L902-L941
train
rkt/rkt
stage1/init/common/units.go
WriteUnit
func (uw *UnitWriter) WriteUnit(path string, errmsg string, opts ...*unit.UnitOption) { if uw.err != nil { return } file, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644) if err != nil { uw.err = errwrap.Wrap(errors.New(errmsg), err) return } defer file.Close() if _, err = io.Copy(file, unit.Serialize(opts)); err != nil { uw.err = errwrap.Wrap(errors.New(errmsg), err) return } if err := user.ShiftFiles([]string{path}, &uw.p.UidRange); err != nil { uw.err = errwrap.Wrap(errors.New(errmsg), err) return } }
go
func (uw *UnitWriter) WriteUnit(path string, errmsg string, opts ...*unit.UnitOption) { if uw.err != nil { return } file, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644) if err != nil { uw.err = errwrap.Wrap(errors.New(errmsg), err) return } defer file.Close() if _, err = io.Copy(file, unit.Serialize(opts)); err != nil { uw.err = errwrap.Wrap(errors.New(errmsg), err) return } if err := user.ShiftFiles([]string{path}, &uw.p.UidRange); err != nil { uw.err = errwrap.Wrap(errors.New(errmsg), err) return } }
[ "func", "(", "uw", "*", "UnitWriter", ")", "WriteUnit", "(", "path", "string", ",", "errmsg", "string", ",", "opts", "...", "*", "unit", ".", "UnitOption", ")", "{", "if", "uw", ".", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "file", ",", "err", ":=", "os", ".", "OpenFile", "(", "path", ",", "os", ".", "O_WRONLY", "|", "os", ".", "O_CREATE", "|", "os", ".", "O_TRUNC", ",", "0644", ")", "\n", "if", "err", "!=", "nil", "{", "uw", ".", "err", "=", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "errmsg", ")", ",", "err", ")", "\n", "return", "\n", "}", "\n", "defer", "file", ".", "Close", "(", ")", "\n", "if", "_", ",", "err", "=", "io", ".", "Copy", "(", "file", ",", "unit", ".", "Serialize", "(", "opts", ")", ")", ";", "err", "!=", "nil", "{", "uw", ".", "err", "=", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "errmsg", ")", ",", "err", ")", "\n", "return", "\n", "}", "\n", "if", "err", ":=", "user", ".", "ShiftFiles", "(", "[", "]", "string", "{", "path", "}", ",", "&", "uw", ".", "p", ".", "UidRange", ")", ";", "err", "!=", "nil", "{", "uw", ".", "err", "=", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "errmsg", ")", ",", "err", ")", "\n", "return", "\n", "}", "\n", "}" ]
// WriteUnit writes a systemd unit in the given path with the given unit options // if no previous error occurred.
[ "WriteUnit", "writes", "a", "systemd", "unit", "in", "the", "given", "path", "with", "the", "given", "unit", "options", "if", "no", "previous", "error", "occurred", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage1/init/common/units.go#L367-L387
train
rkt/rkt
stage1/init/common/units.go
writeShutdownService
func (uw *UnitWriter) writeShutdownService(exec string, opts ...*unit.UnitOption) { if uw.err != nil { return } flavor, systemdVersion, err := GetFlavor(uw.p) if err != nil { uw.err = errwrap.Wrap(errors.New("failed to create shutdown service"), err) return } opts = append(opts, []*unit.UnitOption{ // The default stdout is /dev/console (the tty created by nspawn). // But the tty might be destroyed if rkt is executed via ssh and // the user terminates the ssh session. We still want // shutdown.service to succeed in that case, so don't use // /dev/console. unit.NewUnitOption("Service", "StandardInput", "null"), unit.NewUnitOption("Service", "StandardOutput", "null"), unit.NewUnitOption("Service", "StandardError", "null"), }...) shutdownVerb := "exit" // systemd <v227 doesn't allow the "exit" verb when running as PID 1, so // use "halt". // If systemdVersion is 0 it means it couldn't be guessed, assume it's new // enough for "systemctl exit". // This can happen, for example, when building rkt with: // // ./configure --with-stage1-flavors=src --with-stage1-systemd-version=master // // The patches for the "exit" verb are backported to the "coreos" flavor, so // don't rely on the systemd version on the "coreos" flavor. if flavor != "coreos" && systemdVersion != 0 && systemdVersion < 227 { shutdownVerb = "halt" } opts = append( opts, unit.NewUnitOption("Service", exec, fmt.Sprintf("/usr/bin/systemctl --force %s", shutdownVerb)), ) uw.WriteUnit( ServiceUnitPath(uw.p.Root, "shutdown"), "failed to create shutdown service", opts..., ) }
go
func (uw *UnitWriter) writeShutdownService(exec string, opts ...*unit.UnitOption) { if uw.err != nil { return } flavor, systemdVersion, err := GetFlavor(uw.p) if err != nil { uw.err = errwrap.Wrap(errors.New("failed to create shutdown service"), err) return } opts = append(opts, []*unit.UnitOption{ // The default stdout is /dev/console (the tty created by nspawn). // But the tty might be destroyed if rkt is executed via ssh and // the user terminates the ssh session. We still want // shutdown.service to succeed in that case, so don't use // /dev/console. unit.NewUnitOption("Service", "StandardInput", "null"), unit.NewUnitOption("Service", "StandardOutput", "null"), unit.NewUnitOption("Service", "StandardError", "null"), }...) shutdownVerb := "exit" // systemd <v227 doesn't allow the "exit" verb when running as PID 1, so // use "halt". // If systemdVersion is 0 it means it couldn't be guessed, assume it's new // enough for "systemctl exit". // This can happen, for example, when building rkt with: // // ./configure --with-stage1-flavors=src --with-stage1-systemd-version=master // // The patches for the "exit" verb are backported to the "coreos" flavor, so // don't rely on the systemd version on the "coreos" flavor. if flavor != "coreos" && systemdVersion != 0 && systemdVersion < 227 { shutdownVerb = "halt" } opts = append( opts, unit.NewUnitOption("Service", exec, fmt.Sprintf("/usr/bin/systemctl --force %s", shutdownVerb)), ) uw.WriteUnit( ServiceUnitPath(uw.p.Root, "shutdown"), "failed to create shutdown service", opts..., ) }
[ "func", "(", "uw", "*", "UnitWriter", ")", "writeShutdownService", "(", "exec", "string", ",", "opts", "...", "*", "unit", ".", "UnitOption", ")", "{", "if", "uw", ".", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "flavor", ",", "systemdVersion", ",", "err", ":=", "GetFlavor", "(", "uw", ".", "p", ")", "\n", "if", "err", "!=", "nil", "{", "uw", ".", "err", "=", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"failed to create shutdown service\"", ")", ",", "err", ")", "\n", "return", "\n", "}", "\n", "opts", "=", "append", "(", "opts", ",", "[", "]", "*", "unit", ".", "UnitOption", "{", "unit", ".", "NewUnitOption", "(", "\"Service\"", ",", "\"StandardInput\"", ",", "\"null\"", ")", ",", "unit", ".", "NewUnitOption", "(", "\"Service\"", ",", "\"StandardOutput\"", ",", "\"null\"", ")", ",", "unit", ".", "NewUnitOption", "(", "\"Service\"", ",", "\"StandardError\"", ",", "\"null\"", ")", ",", "}", "...", ")", "\n", "shutdownVerb", ":=", "\"exit\"", "\n", "if", "flavor", "!=", "\"coreos\"", "&&", "systemdVersion", "!=", "0", "&&", "systemdVersion", "<", "227", "{", "shutdownVerb", "=", "\"halt\"", "\n", "}", "\n", "opts", "=", "append", "(", "opts", ",", "unit", ".", "NewUnitOption", "(", "\"Service\"", ",", "exec", ",", "fmt", ".", "Sprintf", "(", "\"/usr/bin/systemctl --force %s\"", ",", "shutdownVerb", ")", ")", ",", ")", "\n", "uw", ".", "WriteUnit", "(", "ServiceUnitPath", "(", "uw", ".", "p", ".", "Root", ",", "\"shutdown\"", ")", ",", "\"failed to create shutdown service\"", ",", "opts", "...", ",", ")", "\n", "}" ]
// writeShutdownService writes a shutdown.service unit with the given unit options // if no previous error occurred. // exec specifies how systemctl should be invoked, i.e. ExecStart, or ExecStop.
[ "writeShutdownService", "writes", "a", "shutdown", ".", "service", "unit", "with", "the", "given", "unit", "options", "if", "no", "previous", "error", "occurred", ".", "exec", "specifies", "how", "systemctl", "should", "be", "invoked", "i", ".", "e", ".", "ExecStart", "or", "ExecStop", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage1/init/common/units.go#L392-L439
train
rkt/rkt
stage1/init/common/units.go
Activate
func (uw *UnitWriter) Activate(unit, wantPath string) { if uw.err != nil { return } if err := os.Symlink(path.Join("..", unit), wantPath); err != nil && !os.IsExist(err) { uw.err = errwrap.Wrap(errors.New("failed to link service want"), err) } }
go
func (uw *UnitWriter) Activate(unit, wantPath string) { if uw.err != nil { return } if err := os.Symlink(path.Join("..", unit), wantPath); err != nil && !os.IsExist(err) { uw.err = errwrap.Wrap(errors.New("failed to link service want"), err) } }
[ "func", "(", "uw", "*", "UnitWriter", ")", "Activate", "(", "unit", ",", "wantPath", "string", ")", "{", "if", "uw", ".", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "if", "err", ":=", "os", ".", "Symlink", "(", "path", ".", "Join", "(", "\"..\"", ",", "unit", ")", ",", "wantPath", ")", ";", "err", "!=", "nil", "&&", "!", "os", ".", "IsExist", "(", "err", ")", "{", "uw", ".", "err", "=", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"failed to link service want\"", ")", ",", "err", ")", "\n", "}", "\n", "}" ]
// Activate actives the given unit in the given wantPath.
[ "Activate", "actives", "the", "given", "unit", "in", "the", "given", "wantPath", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage1/init/common/units.go#L442-L450
train
rkt/rkt
stage1/init/common/units.go
AppUnit
func (uw *UnitWriter) AppUnit(ra *schema.RuntimeApp, binPath string, opts ...*unit.UnitOption) { if uw.err != nil { return } if len(ra.App.Exec) == 0 { uw.err = fmt.Errorf(`image %q has an empty "exec" (try --exec=BINARY)`, uw.p.AppNameToImageName(ra.Name)) return } pa, err := prepareApp(uw.p, ra) if err != nil { uw.err = err return } appName := ra.Name.String() imgName := uw.p.AppNameToImageName(ra.Name) /* Write the generic unit options */ opts = append(opts, []*unit.UnitOption{ unit.NewUnitOption("Unit", "Description", fmt.Sprintf("Application=%v Image=%v", appName, imgName)), unit.NewUnitOption("Unit", "DefaultDependencies", "false"), unit.NewUnitOption("Unit", "Wants", fmt.Sprintf("reaper-%s.service", appName)), unit.NewUnitOption("Service", "Restart", "no"), // This helps working around a race // (https://github.com/systemd/systemd/issues/2913) that causes the // systemd unit name not getting written to the journal if the unit is // short-lived and runs as non-root. unit.NewUnitOption("Service", "SyslogIdentifier", appName), }...) // Setup I/O for iottymux (stdin/stdout/stderr) opts = append(opts, uw.SetupAppIO(uw.p, ra, binPath)...) if supportsNotify(uw.p, ra.Name.String()) { opts = append(opts, unit.NewUnitOption("Service", "Type", "notify")) } // Some pre-start jobs take a long time, set the timeout to 0 opts = append(opts, unit.NewUnitOption("Service", "TimeoutStartSec", "0")) opts = append(opts, unit.NewUnitOption("Unit", "Requires", "sysusers.service")) opts = append(opts, unit.NewUnitOption("Unit", "After", "sysusers.service")) opts = uw.appSystemdUnit(pa, binPath, opts) uw.WriteUnit(ServiceUnitPath(uw.p.Root, ra.Name), "failed to create service unit file", opts...) uw.Activate(ServiceUnitName(ra.Name), ServiceWantPath(uw.p.Root, ra.Name)) }
go
func (uw *UnitWriter) AppUnit(ra *schema.RuntimeApp, binPath string, opts ...*unit.UnitOption) { if uw.err != nil { return } if len(ra.App.Exec) == 0 { uw.err = fmt.Errorf(`image %q has an empty "exec" (try --exec=BINARY)`, uw.p.AppNameToImageName(ra.Name)) return } pa, err := prepareApp(uw.p, ra) if err != nil { uw.err = err return } appName := ra.Name.String() imgName := uw.p.AppNameToImageName(ra.Name) /* Write the generic unit options */ opts = append(opts, []*unit.UnitOption{ unit.NewUnitOption("Unit", "Description", fmt.Sprintf("Application=%v Image=%v", appName, imgName)), unit.NewUnitOption("Unit", "DefaultDependencies", "false"), unit.NewUnitOption("Unit", "Wants", fmt.Sprintf("reaper-%s.service", appName)), unit.NewUnitOption("Service", "Restart", "no"), // This helps working around a race // (https://github.com/systemd/systemd/issues/2913) that causes the // systemd unit name not getting written to the journal if the unit is // short-lived and runs as non-root. unit.NewUnitOption("Service", "SyslogIdentifier", appName), }...) // Setup I/O for iottymux (stdin/stdout/stderr) opts = append(opts, uw.SetupAppIO(uw.p, ra, binPath)...) if supportsNotify(uw.p, ra.Name.String()) { opts = append(opts, unit.NewUnitOption("Service", "Type", "notify")) } // Some pre-start jobs take a long time, set the timeout to 0 opts = append(opts, unit.NewUnitOption("Service", "TimeoutStartSec", "0")) opts = append(opts, unit.NewUnitOption("Unit", "Requires", "sysusers.service")) opts = append(opts, unit.NewUnitOption("Unit", "After", "sysusers.service")) opts = uw.appSystemdUnit(pa, binPath, opts) uw.WriteUnit(ServiceUnitPath(uw.p.Root, ra.Name), "failed to create service unit file", opts...) uw.Activate(ServiceUnitName(ra.Name), ServiceWantPath(uw.p.Root, ra.Name)) }
[ "func", "(", "uw", "*", "UnitWriter", ")", "AppUnit", "(", "ra", "*", "schema", ".", "RuntimeApp", ",", "binPath", "string", ",", "opts", "...", "*", "unit", ".", "UnitOption", ")", "{", "if", "uw", ".", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "if", "len", "(", "ra", ".", "App", ".", "Exec", ")", "==", "0", "{", "uw", ".", "err", "=", "fmt", ".", "Errorf", "(", "`image %q has an empty \"exec\" (try --exec=BINARY)`", ",", "uw", ".", "p", ".", "AppNameToImageName", "(", "ra", ".", "Name", ")", ")", "\n", "return", "\n", "}", "\n", "pa", ",", "err", ":=", "prepareApp", "(", "uw", ".", "p", ",", "ra", ")", "\n", "if", "err", "!=", "nil", "{", "uw", ".", "err", "=", "err", "\n", "return", "\n", "}", "\n", "appName", ":=", "ra", ".", "Name", ".", "String", "(", ")", "\n", "imgName", ":=", "uw", ".", "p", ".", "AppNameToImageName", "(", "ra", ".", "Name", ")", "\n", "opts", "=", "append", "(", "opts", ",", "[", "]", "*", "unit", ".", "UnitOption", "{", "unit", ".", "NewUnitOption", "(", "\"Unit\"", ",", "\"Description\"", ",", "fmt", ".", "Sprintf", "(", "\"Application=%v Image=%v\"", ",", "appName", ",", "imgName", ")", ")", ",", "unit", ".", "NewUnitOption", "(", "\"Unit\"", ",", "\"DefaultDependencies\"", ",", "\"false\"", ")", ",", "unit", ".", "NewUnitOption", "(", "\"Unit\"", ",", "\"Wants\"", ",", "fmt", ".", "Sprintf", "(", "\"reaper-%s.service\"", ",", "appName", ")", ")", ",", "unit", ".", "NewUnitOption", "(", "\"Service\"", ",", "\"Restart\"", ",", "\"no\"", ")", ",", "unit", ".", "NewUnitOption", "(", "\"Service\"", ",", "\"SyslogIdentifier\"", ",", "appName", ")", ",", "}", "...", ")", "\n", "opts", "=", "append", "(", "opts", ",", "uw", ".", "SetupAppIO", "(", "uw", ".", "p", ",", "ra", ",", "binPath", ")", "...", ")", "\n", "if", "supportsNotify", "(", "uw", ".", "p", ",", "ra", ".", "Name", ".", "String", "(", ")", ")", "{", "opts", "=", "append", "(", "opts", ",", "unit", ".", "NewUnitOption", "(", "\"Service\"", ",", "\"Type\"", ",", "\"notify\"", ")", ")", "\n", "}", "\n", "opts", "=", "append", "(", "opts", ",", "unit", ".", "NewUnitOption", "(", "\"Service\"", ",", "\"TimeoutStartSec\"", ",", "\"0\"", ")", ")", "\n", "opts", "=", "append", "(", "opts", ",", "unit", ".", "NewUnitOption", "(", "\"Unit\"", ",", "\"Requires\"", ",", "\"sysusers.service\"", ")", ")", "\n", "opts", "=", "append", "(", "opts", ",", "unit", ".", "NewUnitOption", "(", "\"Unit\"", ",", "\"After\"", ",", "\"sysusers.service\"", ")", ")", "\n", "opts", "=", "uw", ".", "appSystemdUnit", "(", "pa", ",", "binPath", ",", "opts", ")", "\n", "uw", ".", "WriteUnit", "(", "ServiceUnitPath", "(", "uw", ".", "p", ".", "Root", ",", "ra", ".", "Name", ")", ",", "\"failed to create service unit file\"", ",", "opts", "...", ")", "\n", "uw", ".", "Activate", "(", "ServiceUnitName", "(", "ra", ".", "Name", ")", ",", "ServiceWantPath", "(", "uw", ".", "p", ".", "Root", ",", "ra", ".", "Name", ")", ")", "\n", "}" ]
// AppUnit sets up the main systemd service unit for the application.
[ "AppUnit", "sets", "up", "the", "main", "systemd", "service", "unit", "for", "the", "application", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage1/init/common/units.go#L458-L509
train
rkt/rkt
stage1/init/common/units.go
AppReaperUnit
func (uw *UnitWriter) AppReaperUnit(appName types.ACName, binPath string, opts ...*unit.UnitOption) { if uw.err != nil { return } opts = append(opts, []*unit.UnitOption{ unit.NewUnitOption("Unit", "Description", fmt.Sprintf("%s Reaper", appName)), unit.NewUnitOption("Unit", "DefaultDependencies", "false"), unit.NewUnitOption("Unit", "StopWhenUnneeded", "yes"), unit.NewUnitOption("Unit", "Before", "halt.target"), unit.NewUnitOption("Unit", "Conflicts", "exit.target"), unit.NewUnitOption("Unit", "Conflicts", "halt.target"), unit.NewUnitOption("Unit", "Conflicts", "poweroff.target"), unit.NewUnitOption("Service", "RemainAfterExit", "yes"), unit.NewUnitOption("Service", "ExecStop", fmt.Sprintf( "/reaper.sh \"%s\" \"%s\" \"%s\"", appName, common.RelAppRootfsPath(appName), binPath, )), }...) uw.WriteUnit( ServiceUnitPath(uw.p.Root, types.ACName(fmt.Sprintf("reaper-%s", appName))), fmt.Sprintf("failed to write app %q reaper service", appName), opts..., ) }
go
func (uw *UnitWriter) AppReaperUnit(appName types.ACName, binPath string, opts ...*unit.UnitOption) { if uw.err != nil { return } opts = append(opts, []*unit.UnitOption{ unit.NewUnitOption("Unit", "Description", fmt.Sprintf("%s Reaper", appName)), unit.NewUnitOption("Unit", "DefaultDependencies", "false"), unit.NewUnitOption("Unit", "StopWhenUnneeded", "yes"), unit.NewUnitOption("Unit", "Before", "halt.target"), unit.NewUnitOption("Unit", "Conflicts", "exit.target"), unit.NewUnitOption("Unit", "Conflicts", "halt.target"), unit.NewUnitOption("Unit", "Conflicts", "poweroff.target"), unit.NewUnitOption("Service", "RemainAfterExit", "yes"), unit.NewUnitOption("Service", "ExecStop", fmt.Sprintf( "/reaper.sh \"%s\" \"%s\" \"%s\"", appName, common.RelAppRootfsPath(appName), binPath, )), }...) uw.WriteUnit( ServiceUnitPath(uw.p.Root, types.ACName(fmt.Sprintf("reaper-%s", appName))), fmt.Sprintf("failed to write app %q reaper service", appName), opts..., ) }
[ "func", "(", "uw", "*", "UnitWriter", ")", "AppReaperUnit", "(", "appName", "types", ".", "ACName", ",", "binPath", "string", ",", "opts", "...", "*", "unit", ".", "UnitOption", ")", "{", "if", "uw", ".", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "opts", "=", "append", "(", "opts", ",", "[", "]", "*", "unit", ".", "UnitOption", "{", "unit", ".", "NewUnitOption", "(", "\"Unit\"", ",", "\"Description\"", ",", "fmt", ".", "Sprintf", "(", "\"%s Reaper\"", ",", "appName", ")", ")", ",", "unit", ".", "NewUnitOption", "(", "\"Unit\"", ",", "\"DefaultDependencies\"", ",", "\"false\"", ")", ",", "unit", ".", "NewUnitOption", "(", "\"Unit\"", ",", "\"StopWhenUnneeded\"", ",", "\"yes\"", ")", ",", "unit", ".", "NewUnitOption", "(", "\"Unit\"", ",", "\"Before\"", ",", "\"halt.target\"", ")", ",", "unit", ".", "NewUnitOption", "(", "\"Unit\"", ",", "\"Conflicts\"", ",", "\"exit.target\"", ")", ",", "unit", ".", "NewUnitOption", "(", "\"Unit\"", ",", "\"Conflicts\"", ",", "\"halt.target\"", ")", ",", "unit", ".", "NewUnitOption", "(", "\"Unit\"", ",", "\"Conflicts\"", ",", "\"poweroff.target\"", ")", ",", "unit", ".", "NewUnitOption", "(", "\"Service\"", ",", "\"RemainAfterExit\"", ",", "\"yes\"", ")", ",", "unit", ".", "NewUnitOption", "(", "\"Service\"", ",", "\"ExecStop\"", ",", "fmt", ".", "Sprintf", "(", "\"/reaper.sh \\\"%s\\\" \\\"%s\\\" \\\"%s\\\"\"", ",", "\\\"", ",", "\\\"", ",", "\\\"", ",", ")", ")", ",", "}", "...", ")", "\n", "\\\"", "\n", "}" ]
// AppReaperUnit writes an app reaper service unit for the given app in the given path using the given unit options.
[ "AppReaperUnit", "writes", "an", "app", "reaper", "service", "unit", "for", "the", "given", "app", "in", "the", "given", "path", "using", "the", "given", "unit", "options", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage1/init/common/units.go#L737-L764
train
rkt/rkt
stage1/init/common/units.go
AppSocketUnit
func (uw *UnitWriter) AppSocketUnit(appName types.ACName, binPath string, streamName string, opts ...*unit.UnitOption) { opts = append(opts, []*unit.UnitOption{ unit.NewUnitOption("Unit", "Description", fmt.Sprintf("%s socket for %s", streamName, appName)), unit.NewUnitOption("Unit", "DefaultDependencies", "no"), unit.NewUnitOption("Unit", "StopWhenUnneeded", "yes"), unit.NewUnitOption("Unit", "RefuseManualStart", "yes"), unit.NewUnitOption("Unit", "RefuseManualStop", "yes"), unit.NewUnitOption("Unit", "BindsTo", fmt.Sprintf("%s.service", appName)), unit.NewUnitOption("Socket", "RemoveOnStop", "yes"), unit.NewUnitOption("Socket", "Service", fmt.Sprintf("%s.service", appName)), unit.NewUnitOption("Socket", "FileDescriptorName", streamName), unit.NewUnitOption("Socket", "ListenFIFO", filepath.Join("/rkt/iottymux", appName.String(), "stage2-"+streamName)), }...) uw.WriteUnit( TypedUnitPath(uw.p.Root, appName.String()+"-"+streamName, "socket"), fmt.Sprintf("failed to write %s socket for %q service", streamName, appName), opts..., ) }
go
func (uw *UnitWriter) AppSocketUnit(appName types.ACName, binPath string, streamName string, opts ...*unit.UnitOption) { opts = append(opts, []*unit.UnitOption{ unit.NewUnitOption("Unit", "Description", fmt.Sprintf("%s socket for %s", streamName, appName)), unit.NewUnitOption("Unit", "DefaultDependencies", "no"), unit.NewUnitOption("Unit", "StopWhenUnneeded", "yes"), unit.NewUnitOption("Unit", "RefuseManualStart", "yes"), unit.NewUnitOption("Unit", "RefuseManualStop", "yes"), unit.NewUnitOption("Unit", "BindsTo", fmt.Sprintf("%s.service", appName)), unit.NewUnitOption("Socket", "RemoveOnStop", "yes"), unit.NewUnitOption("Socket", "Service", fmt.Sprintf("%s.service", appName)), unit.NewUnitOption("Socket", "FileDescriptorName", streamName), unit.NewUnitOption("Socket", "ListenFIFO", filepath.Join("/rkt/iottymux", appName.String(), "stage2-"+streamName)), }...) uw.WriteUnit( TypedUnitPath(uw.p.Root, appName.String()+"-"+streamName, "socket"), fmt.Sprintf("failed to write %s socket for %q service", streamName, appName), opts..., ) }
[ "func", "(", "uw", "*", "UnitWriter", ")", "AppSocketUnit", "(", "appName", "types", ".", "ACName", ",", "binPath", "string", ",", "streamName", "string", ",", "opts", "...", "*", "unit", ".", "UnitOption", ")", "{", "opts", "=", "append", "(", "opts", ",", "[", "]", "*", "unit", ".", "UnitOption", "{", "unit", ".", "NewUnitOption", "(", "\"Unit\"", ",", "\"Description\"", ",", "fmt", ".", "Sprintf", "(", "\"%s socket for %s\"", ",", "streamName", ",", "appName", ")", ")", ",", "unit", ".", "NewUnitOption", "(", "\"Unit\"", ",", "\"DefaultDependencies\"", ",", "\"no\"", ")", ",", "unit", ".", "NewUnitOption", "(", "\"Unit\"", ",", "\"StopWhenUnneeded\"", ",", "\"yes\"", ")", ",", "unit", ".", "NewUnitOption", "(", "\"Unit\"", ",", "\"RefuseManualStart\"", ",", "\"yes\"", ")", ",", "unit", ".", "NewUnitOption", "(", "\"Unit\"", ",", "\"RefuseManualStop\"", ",", "\"yes\"", ")", ",", "unit", ".", "NewUnitOption", "(", "\"Unit\"", ",", "\"BindsTo\"", ",", "fmt", ".", "Sprintf", "(", "\"%s.service\"", ",", "appName", ")", ")", ",", "unit", ".", "NewUnitOption", "(", "\"Socket\"", ",", "\"RemoveOnStop\"", ",", "\"yes\"", ")", ",", "unit", ".", "NewUnitOption", "(", "\"Socket\"", ",", "\"Service\"", ",", "fmt", ".", "Sprintf", "(", "\"%s.service\"", ",", "appName", ")", ")", ",", "unit", ".", "NewUnitOption", "(", "\"Socket\"", ",", "\"FileDescriptorName\"", ",", "streamName", ")", ",", "unit", ".", "NewUnitOption", "(", "\"Socket\"", ",", "\"ListenFIFO\"", ",", "filepath", ".", "Join", "(", "\"/rkt/iottymux\"", ",", "appName", ".", "String", "(", ")", ",", "\"stage2-\"", "+", "streamName", ")", ")", ",", "}", "...", ")", "\n", "uw", ".", "WriteUnit", "(", "TypedUnitPath", "(", "uw", ".", "p", ".", "Root", ",", "appName", ".", "String", "(", ")", "+", "\"-\"", "+", "streamName", ",", "\"socket\"", ")", ",", "fmt", ".", "Sprintf", "(", "\"failed to write %s socket for %q service\"", ",", "streamName", ",", "appName", ")", ",", "opts", "...", ",", ")", "\n", "}" ]
// AppSocketUnits writes a stream socket-unit for the given app in the given path.
[ "AppSocketUnits", "writes", "a", "stream", "socket", "-", "unit", "for", "the", "given", "app", "in", "the", "given", "path", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage1/init/common/units.go#L767-L786
train
rkt/rkt
stage1/init/common/units.go
appendOptionsList
func appendOptionsList(opts []*unit.UnitOption, section, property, prefix string, vals ...string) []*unit.UnitOption { for _, v := range vals { opts = append(opts, unit.NewUnitOption(section, property, fmt.Sprintf("%s%s", prefix, v))) } return opts }
go
func appendOptionsList(opts []*unit.UnitOption, section, property, prefix string, vals ...string) []*unit.UnitOption { for _, v := range vals { opts = append(opts, unit.NewUnitOption(section, property, fmt.Sprintf("%s%s", prefix, v))) } return opts }
[ "func", "appendOptionsList", "(", "opts", "[", "]", "*", "unit", ".", "UnitOption", ",", "section", ",", "property", ",", "prefix", "string", ",", "vals", "...", "string", ")", "[", "]", "*", "unit", ".", "UnitOption", "{", "for", "_", ",", "v", ":=", "range", "vals", "{", "opts", "=", "append", "(", "opts", ",", "unit", ".", "NewUnitOption", "(", "section", ",", "property", ",", "fmt", ".", "Sprintf", "(", "\"%s%s\"", ",", "prefix", ",", "v", ")", ")", ")", "\n", "}", "\n", "return", "opts", "\n", "}" ]
// appendOptionsList updates an existing unit options list appending // an array of new properties, one entry at a time. // This is the preferred method to avoid hitting line length limits // in unit files. Target property must support multi-line entries.
[ "appendOptionsList", "updates", "an", "existing", "unit", "options", "list", "appending", "an", "array", "of", "new", "properties", "one", "entry", "at", "a", "time", ".", "This", "is", "the", "preferred", "method", "to", "avoid", "hitting", "line", "length", "limits", "in", "unit", "files", ".", "Target", "property", "must", "support", "multi", "-", "line", "entries", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage1/init/common/units.go#L792-L797
train
rkt/rkt
lib/app.go
AppsForPod
func AppsForPod(uuid, dataDir string, appName string) ([]*v1.App, error) { p, err := pkgPod.PodFromUUIDString(dataDir, uuid) if err != nil { return nil, err } defer p.Close() return appsForPod(p, appName, appStateInMutablePod) }
go
func AppsForPod(uuid, dataDir string, appName string) ([]*v1.App, error) { p, err := pkgPod.PodFromUUIDString(dataDir, uuid) if err != nil { return nil, err } defer p.Close() return appsForPod(p, appName, appStateInMutablePod) }
[ "func", "AppsForPod", "(", "uuid", ",", "dataDir", "string", ",", "appName", "string", ")", "(", "[", "]", "*", "v1", ".", "App", ",", "error", ")", "{", "p", ",", "err", ":=", "pkgPod", ".", "PodFromUUIDString", "(", "dataDir", ",", "uuid", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "defer", "p", ".", "Close", "(", ")", "\n", "return", "appsForPod", "(", "p", ",", "appName", ",", "appStateInMutablePod", ")", "\n", "}" ]
// AppsForPod returns the apps of the pod with the given uuid in the given data directory. // If appName is non-empty, then only the app with the given name will be returned.
[ "AppsForPod", "returns", "the", "apps", "of", "the", "pod", "with", "the", "given", "uuid", "in", "the", "given", "data", "directory", ".", "If", "appName", "is", "non", "-", "empty", "then", "only", "the", "app", "with", "the", "given", "name", "will", "be", "returned", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/lib/app.go#L38-L46
train
rkt/rkt
lib/app.go
newApp
func newApp(ra *schema.RuntimeApp, podManifest *schema.PodManifest, pod *pkgPod.Pod, appState appStateFunc) (*v1.App, error) { app := &v1.App{ Name: ra.Name.String(), ImageID: ra.Image.ID.String(), UserAnnotations: ra.App.UserAnnotations, UserLabels: ra.App.UserLabels, } podVols := podManifest.Volumes podVolsByName := make(map[types.ACName]types.Volume, len(podVols)) for i := range podManifest.Volumes { podVolsByName[podVols[i].Name] = podVols[i] } for _, mnt := range ra.Mounts { readOnly := false var hostPath string // AppVolume is optional if av := mnt.AppVolume; av != nil { hostPath = av.Source if ro := av.ReadOnly; ro != nil { readOnly = *ro } } else { hostPath = podVolsByName[mnt.Volume].Source if ro := podVolsByName[mnt.Volume].ReadOnly; ro != nil { readOnly = *ro } } app.Mounts = append(app.Mounts, &v1.Mount{ Name: mnt.Volume.String(), ContainerPath: mnt.Path, HostPath: hostPath, ReadOnly: readOnly, }) } // Generate state. if err := appState(app, pod); err != nil { return nil, fmt.Errorf("error getting app's state: %v", err) } return app, nil }
go
func newApp(ra *schema.RuntimeApp, podManifest *schema.PodManifest, pod *pkgPod.Pod, appState appStateFunc) (*v1.App, error) { app := &v1.App{ Name: ra.Name.String(), ImageID: ra.Image.ID.String(), UserAnnotations: ra.App.UserAnnotations, UserLabels: ra.App.UserLabels, } podVols := podManifest.Volumes podVolsByName := make(map[types.ACName]types.Volume, len(podVols)) for i := range podManifest.Volumes { podVolsByName[podVols[i].Name] = podVols[i] } for _, mnt := range ra.Mounts { readOnly := false var hostPath string // AppVolume is optional if av := mnt.AppVolume; av != nil { hostPath = av.Source if ro := av.ReadOnly; ro != nil { readOnly = *ro } } else { hostPath = podVolsByName[mnt.Volume].Source if ro := podVolsByName[mnt.Volume].ReadOnly; ro != nil { readOnly = *ro } } app.Mounts = append(app.Mounts, &v1.Mount{ Name: mnt.Volume.String(), ContainerPath: mnt.Path, HostPath: hostPath, ReadOnly: readOnly, }) } // Generate state. if err := appState(app, pod); err != nil { return nil, fmt.Errorf("error getting app's state: %v", err) } return app, nil }
[ "func", "newApp", "(", "ra", "*", "schema", ".", "RuntimeApp", ",", "podManifest", "*", "schema", ".", "PodManifest", ",", "pod", "*", "pkgPod", ".", "Pod", ",", "appState", "appStateFunc", ")", "(", "*", "v1", ".", "App", ",", "error", ")", "{", "app", ":=", "&", "v1", ".", "App", "{", "Name", ":", "ra", ".", "Name", ".", "String", "(", ")", ",", "ImageID", ":", "ra", ".", "Image", ".", "ID", ".", "String", "(", ")", ",", "UserAnnotations", ":", "ra", ".", "App", ".", "UserAnnotations", ",", "UserLabels", ":", "ra", ".", "App", ".", "UserLabels", ",", "}", "\n", "podVols", ":=", "podManifest", ".", "Volumes", "\n", "podVolsByName", ":=", "make", "(", "map", "[", "types", ".", "ACName", "]", "types", ".", "Volume", ",", "len", "(", "podVols", ")", ")", "\n", "for", "i", ":=", "range", "podManifest", ".", "Volumes", "{", "podVolsByName", "[", "podVols", "[", "i", "]", ".", "Name", "]", "=", "podVols", "[", "i", "]", "\n", "}", "\n", "for", "_", ",", "mnt", ":=", "range", "ra", ".", "Mounts", "{", "readOnly", ":=", "false", "\n", "var", "hostPath", "string", "\n", "if", "av", ":=", "mnt", ".", "AppVolume", ";", "av", "!=", "nil", "{", "hostPath", "=", "av", ".", "Source", "\n", "if", "ro", ":=", "av", ".", "ReadOnly", ";", "ro", "!=", "nil", "{", "readOnly", "=", "*", "ro", "\n", "}", "\n", "}", "else", "{", "hostPath", "=", "podVolsByName", "[", "mnt", ".", "Volume", "]", ".", "Source", "\n", "if", "ro", ":=", "podVolsByName", "[", "mnt", ".", "Volume", "]", ".", "ReadOnly", ";", "ro", "!=", "nil", "{", "readOnly", "=", "*", "ro", "\n", "}", "\n", "}", "\n", "app", ".", "Mounts", "=", "append", "(", "app", ".", "Mounts", ",", "&", "v1", ".", "Mount", "{", "Name", ":", "mnt", ".", "Volume", ".", "String", "(", ")", ",", "ContainerPath", ":", "mnt", ".", "Path", ",", "HostPath", ":", "hostPath", ",", "ReadOnly", ":", "readOnly", ",", "}", ")", "\n", "}", "\n", "if", "err", ":=", "appState", "(", "app", ",", "pod", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"error getting app's state: %v\"", ",", "err", ")", "\n", "}", "\n", "return", "app", ",", "nil", "\n", "}" ]
// newApp constructs the App object with the runtime app and pod manifest.
[ "newApp", "constructs", "the", "App", "object", "with", "the", "runtime", "app", "and", "pod", "manifest", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/lib/app.go#L73-L116
train
rkt/rkt
lib/app.go
appStateInImmutablePod
func appStateInImmutablePod(app *v1.App, pod *pkgPod.Pod) error { app.State = appStateFromPod(pod) t, err := pod.CreationTime() if err != nil { return err } createdAt := t.UnixNano() app.CreatedAt = &createdAt code, err := pod.AppExitCode(app.Name) if err == nil { // there is an exit code, it is definitely Exited app.State = v1.AppStateExited exitCode := int32(code) app.ExitCode = &exitCode } start, err := pod.StartTime() if err != nil { return err } if !start.IsZero() { startedAt := start.UnixNano() app.StartedAt = &startedAt } // the best we can guess for immutable pods finish, err := pod.GCMarkedTime() if err != nil { return err } if !finish.IsZero() { finishedAt := finish.UnixNano() app.FinishedAt = &finishedAt } return nil }
go
func appStateInImmutablePod(app *v1.App, pod *pkgPod.Pod) error { app.State = appStateFromPod(pod) t, err := pod.CreationTime() if err != nil { return err } createdAt := t.UnixNano() app.CreatedAt = &createdAt code, err := pod.AppExitCode(app.Name) if err == nil { // there is an exit code, it is definitely Exited app.State = v1.AppStateExited exitCode := int32(code) app.ExitCode = &exitCode } start, err := pod.StartTime() if err != nil { return err } if !start.IsZero() { startedAt := start.UnixNano() app.StartedAt = &startedAt } // the best we can guess for immutable pods finish, err := pod.GCMarkedTime() if err != nil { return err } if !finish.IsZero() { finishedAt := finish.UnixNano() app.FinishedAt = &finishedAt } return nil }
[ "func", "appStateInImmutablePod", "(", "app", "*", "v1", ".", "App", ",", "pod", "*", "pkgPod", ".", "Pod", ")", "error", "{", "app", ".", "State", "=", "appStateFromPod", "(", "pod", ")", "\n", "t", ",", "err", ":=", "pod", ".", "CreationTime", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "createdAt", ":=", "t", ".", "UnixNano", "(", ")", "\n", "app", ".", "CreatedAt", "=", "&", "createdAt", "\n", "code", ",", "err", ":=", "pod", ".", "AppExitCode", "(", "app", ".", "Name", ")", "\n", "if", "err", "==", "nil", "{", "app", ".", "State", "=", "v1", ".", "AppStateExited", "\n", "exitCode", ":=", "int32", "(", "code", ")", "\n", "app", ".", "ExitCode", "=", "&", "exitCode", "\n", "}", "\n", "start", ",", "err", ":=", "pod", ".", "StartTime", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "!", "start", ".", "IsZero", "(", ")", "{", "startedAt", ":=", "start", ".", "UnixNano", "(", ")", "\n", "app", ".", "StartedAt", "=", "&", "startedAt", "\n", "}", "\n", "finish", ",", "err", ":=", "pod", ".", "GCMarkedTime", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "!", "finish", ".", "IsZero", "(", ")", "{", "finishedAt", ":=", "finish", ".", "UnixNano", "(", ")", "\n", "app", ".", "FinishedAt", "=", "&", "finishedAt", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// appStateInImmutablePod infers most App state from the Pod itself, since all apps are created and destroyed with the Pod
[ "appStateInImmutablePod", "infers", "most", "App", "state", "from", "the", "Pod", "itself", "since", "all", "apps", "are", "created", "and", "destroyed", "with", "the", "Pod" ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/lib/app.go#L200-L237
train
rkt/rkt
stage1/common/types/pod.go
SaveRuntime
func (p *Pod) SaveRuntime() error { path := filepath.Join(p.Root, RuntimeConfigPath) buf, err := json.Marshal(p.RuntimePod) if err != nil { return err } return ioutil.WriteFile(path, buf, 0644) }
go
func (p *Pod) SaveRuntime() error { path := filepath.Join(p.Root, RuntimeConfigPath) buf, err := json.Marshal(p.RuntimePod) if err != nil { return err } return ioutil.WriteFile(path, buf, 0644) }
[ "func", "(", "p", "*", "Pod", ")", "SaveRuntime", "(", ")", "error", "{", "path", ":=", "filepath", ".", "Join", "(", "p", ".", "Root", ",", "RuntimeConfigPath", ")", "\n", "buf", ",", "err", ":=", "json", ".", "Marshal", "(", "p", ".", "RuntimePod", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "ioutil", ".", "WriteFile", "(", "path", ",", "buf", ",", "0644", ")", "\n", "}" ]
// SaveRuntime persists just the runtime state. This should be called when the // pod is started.
[ "SaveRuntime", "persists", "just", "the", "runtime", "state", ".", "This", "should", "be", "called", "when", "the", "pod", "is", "started", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage1/common/types/pod.go#L91-L99
train
rkt/rkt
stage1/common/types/pod.go
LoadPodManifest
func LoadPodManifest(root string) (*schema.PodManifest, error) { buf, err := ioutil.ReadFile(common.PodManifestPath(root)) if err != nil { return nil, errwrap.Wrap(errors.New("failed reading pod manifest"), err) } pm := &schema.PodManifest{} if err := json.Unmarshal(buf, pm); err != nil { return nil, errwrap.Wrap(errors.New("failed unmarshalling pod manifest"), err) } return pm, nil }
go
func LoadPodManifest(root string) (*schema.PodManifest, error) { buf, err := ioutil.ReadFile(common.PodManifestPath(root)) if err != nil { return nil, errwrap.Wrap(errors.New("failed reading pod manifest"), err) } pm := &schema.PodManifest{} if err := json.Unmarshal(buf, pm); err != nil { return nil, errwrap.Wrap(errors.New("failed unmarshalling pod manifest"), err) } return pm, nil }
[ "func", "LoadPodManifest", "(", "root", "string", ")", "(", "*", "schema", ".", "PodManifest", ",", "error", ")", "{", "buf", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "common", ".", "PodManifestPath", "(", "root", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"failed reading pod manifest\"", ")", ",", "err", ")", "\n", "}", "\n", "pm", ":=", "&", "schema", ".", "PodManifest", "{", "}", "\n", "if", "err", ":=", "json", ".", "Unmarshal", "(", "buf", ",", "pm", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"failed unmarshalling pod manifest\"", ")", ",", "err", ")", "\n", "}", "\n", "return", "pm", ",", "nil", "\n", "}" ]
// LoadPodManifest loads a Pod Manifest.
[ "LoadPodManifest", "loads", "a", "Pod", "Manifest", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage1/common/types/pod.go#L102-L113
train
rkt/rkt
rkt/image/fetcher.go
FetchImages
func (f *Fetcher) FetchImages(al *apps.Apps) error { return al.Walk(func(app *apps.App) error { d, err := DistFromImageString(app.Image) if err != nil { return err } h, err := f.FetchImage(d, app.Image, app.Asc) if err != nil { return err } app.ImageID = *h return nil }) }
go
func (f *Fetcher) FetchImages(al *apps.Apps) error { return al.Walk(func(app *apps.App) error { d, err := DistFromImageString(app.Image) if err != nil { return err } h, err := f.FetchImage(d, app.Image, app.Asc) if err != nil { return err } app.ImageID = *h return nil }) }
[ "func", "(", "f", "*", "Fetcher", ")", "FetchImages", "(", "al", "*", "apps", ".", "Apps", ")", "error", "{", "return", "al", ".", "Walk", "(", "func", "(", "app", "*", "apps", ".", "App", ")", "error", "{", "d", ",", "err", ":=", "DistFromImageString", "(", "app", ".", "Image", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "h", ",", "err", ":=", "f", ".", "FetchImage", "(", "d", ",", "app", ".", "Image", ",", "app", ".", "Asc", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "app", ".", "ImageID", "=", "*", "h", "\n", "return", "nil", "\n", "}", ")", "\n", "}" ]
// FetchImages uses FetchImage to attain a list of image hashes
[ "FetchImages", "uses", "FetchImage", "to", "attain", "a", "list", "of", "image", "hashes" ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/image/fetcher.go#L46-L59
train
rkt/rkt
rkt/image/fetcher.go
FetchImage
func (f *Fetcher) FetchImage(d dist.Distribution, image, ascPath string) (*types.Hash, error) { ensureLogger(f.Debug) db := &distBundle{ dist: d, image: image, } a := f.getAsc(ascPath) hash, err := f.fetchSingleImage(db, a) if err != nil { return nil, err } if f.WithDeps { err = f.fetchImageDeps(hash) if err != nil { return nil, err } } // we need to be able to do a chroot and access to the tree store // directories, we need to // 1) check if the system supports OverlayFS // 2) check if we're root if common.SupportsOverlay() == nil && os.Geteuid() == 0 { if _, _, err := f.Ts.Render(hash, false); err != nil { return nil, errwrap.Wrap(errors.New("error rendering tree store"), err) } } h, err := types.NewHash(hash) if err != nil { // should never happen log.PanicE("invalid hash", err) } return h, nil }
go
func (f *Fetcher) FetchImage(d dist.Distribution, image, ascPath string) (*types.Hash, error) { ensureLogger(f.Debug) db := &distBundle{ dist: d, image: image, } a := f.getAsc(ascPath) hash, err := f.fetchSingleImage(db, a) if err != nil { return nil, err } if f.WithDeps { err = f.fetchImageDeps(hash) if err != nil { return nil, err } } // we need to be able to do a chroot and access to the tree store // directories, we need to // 1) check if the system supports OverlayFS // 2) check if we're root if common.SupportsOverlay() == nil && os.Geteuid() == 0 { if _, _, err := f.Ts.Render(hash, false); err != nil { return nil, errwrap.Wrap(errors.New("error rendering tree store"), err) } } h, err := types.NewHash(hash) if err != nil { // should never happen log.PanicE("invalid hash", err) } return h, nil }
[ "func", "(", "f", "*", "Fetcher", ")", "FetchImage", "(", "d", "dist", ".", "Distribution", ",", "image", ",", "ascPath", "string", ")", "(", "*", "types", ".", "Hash", ",", "error", ")", "{", "ensureLogger", "(", "f", ".", "Debug", ")", "\n", "db", ":=", "&", "distBundle", "{", "dist", ":", "d", ",", "image", ":", "image", ",", "}", "\n", "a", ":=", "f", ".", "getAsc", "(", "ascPath", ")", "\n", "hash", ",", "err", ":=", "f", ".", "fetchSingleImage", "(", "db", ",", "a", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "f", ".", "WithDeps", "{", "err", "=", "f", ".", "fetchImageDeps", "(", "hash", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n", "if", "common", ".", "SupportsOverlay", "(", ")", "==", "nil", "&&", "os", ".", "Geteuid", "(", ")", "==", "0", "{", "if", "_", ",", "_", ",", "err", ":=", "f", ".", "Ts", ".", "Render", "(", "hash", ",", "false", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"error rendering tree store\"", ")", ",", "err", ")", "\n", "}", "\n", "}", "\n", "h", ",", "err", ":=", "types", ".", "NewHash", "(", "hash", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "PanicE", "(", "\"invalid hash\"", ",", "err", ")", "\n", "}", "\n", "return", "h", ",", "nil", "\n", "}" ]
// FetchImage will take an image as either a path, a URL or a name // string and import it into the store if found. If ascPath is not "", // it must exist as a local file and will be used as the signature // file for verification, unless verification is disabled. If // f.WithDeps is true also image dependencies are fetched.
[ "FetchImage", "will", "take", "an", "image", "as", "either", "a", "path", "a", "URL", "or", "a", "name", "string", "and", "import", "it", "into", "the", "store", "if", "found", ".", "If", "ascPath", "is", "not", "it", "must", "exist", "as", "a", "local", "file", "and", "will", "be", "used", "as", "the", "signature", "file", "for", "verification", "unless", "verification", "is", "disabled", ".", "If", "f", ".", "WithDeps", "is", "true", "also", "image", "dependencies", "are", "fetched", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/image/fetcher.go#L66-L99
train
rkt/rkt
rkt/image/fetcher.go
fetchImageDeps
func (f *Fetcher) fetchImageDeps(hash string) error { imgsl := list.New() seen := map[string]dist.Distribution{} f.addImageDeps(hash, imgsl, seen) for el := imgsl.Front(); el != nil; el = el.Next() { a := &asc{} d := el.Value.(*dist.Appc) str := d.String() db := &distBundle{ dist: d, image: str, } hash, err := f.fetchSingleImage(db, a) if err != nil { return err } f.addImageDeps(hash, imgsl, seen) } return nil }
go
func (f *Fetcher) fetchImageDeps(hash string) error { imgsl := list.New() seen := map[string]dist.Distribution{} f.addImageDeps(hash, imgsl, seen) for el := imgsl.Front(); el != nil; el = el.Next() { a := &asc{} d := el.Value.(*dist.Appc) str := d.String() db := &distBundle{ dist: d, image: str, } hash, err := f.fetchSingleImage(db, a) if err != nil { return err } f.addImageDeps(hash, imgsl, seen) } return nil }
[ "func", "(", "f", "*", "Fetcher", ")", "fetchImageDeps", "(", "hash", "string", ")", "error", "{", "imgsl", ":=", "list", ".", "New", "(", ")", "\n", "seen", ":=", "map", "[", "string", "]", "dist", ".", "Distribution", "{", "}", "\n", "f", ".", "addImageDeps", "(", "hash", ",", "imgsl", ",", "seen", ")", "\n", "for", "el", ":=", "imgsl", ".", "Front", "(", ")", ";", "el", "!=", "nil", ";", "el", "=", "el", ".", "Next", "(", ")", "{", "a", ":=", "&", "asc", "{", "}", "\n", "d", ":=", "el", ".", "Value", ".", "(", "*", "dist", ".", "Appc", ")", "\n", "str", ":=", "d", ".", "String", "(", ")", "\n", "db", ":=", "&", "distBundle", "{", "dist", ":", "d", ",", "image", ":", "str", ",", "}", "\n", "hash", ",", "err", ":=", "f", ".", "fetchSingleImage", "(", "db", ",", "a", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "f", ".", "addImageDeps", "(", "hash", ",", "imgsl", ",", "seen", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// fetchImageDeps will recursively fetch all the image dependencies
[ "fetchImageDeps", "will", "recursively", "fetch", "all", "the", "image", "dependencies" ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/image/fetcher.go#L112-L131
train
rkt/rkt
pkg/log/log.go
New
func New(out io.Writer, prefix string, debug bool) *Logger { l := &Logger{ debug: debug, Logger: log.New(out, prefix, 0), } l.SetFlags(0) return l }
go
func New(out io.Writer, prefix string, debug bool) *Logger { l := &Logger{ debug: debug, Logger: log.New(out, prefix, 0), } l.SetFlags(0) return l }
[ "func", "New", "(", "out", "io", ".", "Writer", ",", "prefix", "string", ",", "debug", "bool", ")", "*", "Logger", "{", "l", ":=", "&", "Logger", "{", "debug", ":", "debug", ",", "Logger", ":", "log", ".", "New", "(", "out", ",", "prefix", ",", "0", ")", ",", "}", "\n", "l", ".", "SetFlags", "(", "0", ")", "\n", "return", "l", "\n", "}" ]
// New creates a new Logger with no Log flags set.
[ "New", "creates", "a", "new", "Logger", "with", "no", "Log", "flags", "set", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/log/log.go#L35-L42
train
rkt/rkt
pkg/log/log.go
Error
func (l *Logger) Error(e error) { l.Print(l.formatErr(e, "")) }
go
func (l *Logger) Error(e error) { l.Print(l.formatErr(e, "")) }
[ "func", "(", "l", "*", "Logger", ")", "Error", "(", "e", "error", ")", "{", "l", ".", "Print", "(", "l", ".", "formatErr", "(", "e", ",", "\"\"", ")", ")", "\n", "}" ]
// Error is a convenience function for printing errors without a message.
[ "Error", "is", "a", "convenience", "function", "for", "printing", "errors", "without", "a", "message", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/log/log.go#L110-L112
train
rkt/rkt
pkg/log/log.go
Errorf
func (l *Logger) Errorf(format string, a ...interface{}) { l.Print(l.formatErr(fmt.Errorf(format, a...), "")) }
go
func (l *Logger) Errorf(format string, a ...interface{}) { l.Print(l.formatErr(fmt.Errorf(format, a...), "")) }
[ "func", "(", "l", "*", "Logger", ")", "Errorf", "(", "format", "string", ",", "a", "...", "interface", "{", "}", ")", "{", "l", ".", "Print", "(", "l", ".", "formatErr", "(", "fmt", ".", "Errorf", "(", "format", ",", "a", "...", ")", ",", "\"\"", ")", ")", "\n", "}" ]
// Errorf is a convenience function for formatting and printing errors.
[ "Errorf", "is", "a", "convenience", "function", "for", "formatting", "and", "printing", "errors", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/log/log.go#L115-L117
train
rkt/rkt
pkg/log/log.go
PanicE
func (l *Logger) PanicE(msg string, e error) { l.Panic(l.formatErr(e, msg)) }
go
func (l *Logger) PanicE(msg string, e error) { l.Panic(l.formatErr(e, msg)) }
[ "func", "(", "l", "*", "Logger", ")", "PanicE", "(", "msg", "string", ",", "e", "error", ")", "{", "l", ".", "Panic", "(", "l", ".", "formatErr", "(", "e", ",", "msg", ")", ")", "\n", "}" ]
// PanicE prints a string and error then calls panic.
[ "PanicE", "prints", "a", "string", "and", "error", "then", "calls", "panic", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/log/log.go#L132-L134
train
rkt/rkt
tools/common/util.go
Warn
func Warn(format string, values ...interface{}) { fmt.Fprintf(os.Stderr, fmt.Sprintf("%s%c", format, '\n'), values...) }
go
func Warn(format string, values ...interface{}) { fmt.Fprintf(os.Stderr, fmt.Sprintf("%s%c", format, '\n'), values...) }
[ "func", "Warn", "(", "format", "string", ",", "values", "...", "interface", "{", "}", ")", "{", "fmt", ".", "Fprintf", "(", "os", ".", "Stderr", ",", "fmt", ".", "Sprintf", "(", "\"%s%c\"", ",", "format", ",", "'\\n'", ")", ",", "values", "...", ")", "\n", "}" ]
// Warn is just a shorter version of a formatted printing to // stderr. It appends a newline for you.
[ "Warn", "is", "just", "a", "shorter", "version", "of", "a", "formatted", "printing", "to", "stderr", ".", "It", "appends", "a", "newline", "for", "you", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/tools/common/util.go#L45-L47
train
rkt/rkt
tools/common/util.go
MustAbs
func MustAbs(dir string) string { absDir, err := filepath.Abs(dir) if err != nil { panic(fmt.Sprintf("Failed to get absolute path of a directory %q: %v\n", dir, err)) } return filepath.Clean(absDir) }
go
func MustAbs(dir string) string { absDir, err := filepath.Abs(dir) if err != nil { panic(fmt.Sprintf("Failed to get absolute path of a directory %q: %v\n", dir, err)) } return filepath.Clean(absDir) }
[ "func", "MustAbs", "(", "dir", "string", ")", "string", "{", "absDir", ",", "err", ":=", "filepath", ".", "Abs", "(", "dir", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "fmt", ".", "Sprintf", "(", "\"Failed to get absolute path of a directory %q: %v\\n\"", ",", "\\n", ",", "dir", ")", ")", "\n", "}", "\n", "err", "\n", "}" ]
// MustAbs returns an absolute path. It works like filepath.Abs, but // panics if it fails.
[ "MustAbs", "returns", "an", "absolute", "path", ".", "It", "works", "like", "filepath", ".", "Abs", "but", "panics", "if", "it", "fails", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/tools/common/util.go#L75-L81
train
rkt/rkt
rkt/status.go
parseDuration
func parseDuration(s string) (time.Duration, error) { if s == "" { return time.Duration(-1), nil } b, err := strconv.ParseBool(s) switch { case err != nil: return time.ParseDuration(s) case b: return time.Duration(-1), nil } return time.Duration(0), nil }
go
func parseDuration(s string) (time.Duration, error) { if s == "" { return time.Duration(-1), nil } b, err := strconv.ParseBool(s) switch { case err != nil: return time.ParseDuration(s) case b: return time.Duration(-1), nil } return time.Duration(0), nil }
[ "func", "parseDuration", "(", "s", "string", ")", "(", "time", ".", "Duration", ",", "error", ")", "{", "if", "s", "==", "\"\"", "{", "return", "time", ".", "Duration", "(", "-", "1", ")", ",", "nil", "\n", "}", "\n", "b", ",", "err", ":=", "strconv", ".", "ParseBool", "(", "s", ")", "\n", "switch", "{", "case", "err", "!=", "nil", ":", "return", "time", ".", "ParseDuration", "(", "s", ")", "\n", "case", "b", ":", "return", "time", ".", "Duration", "(", "-", "1", ")", ",", "nil", "\n", "}", "\n", "return", "time", ".", "Duration", "(", "0", ")", ",", "nil", "\n", "}" ]
// parseDuration converts the given string s to a duration value. // If it is empty string or a true boolean value according to strconv.ParseBool, a negative duration is returned. // If the boolean value is false, a 0 duration is returned. // If the string s is a duration value, then it is returned. // It returns an error if the duration conversion failed.
[ "parseDuration", "converts", "the", "given", "string", "s", "to", "a", "duration", "value", ".", "If", "it", "is", "empty", "string", "or", "a", "true", "boolean", "value", "according", "to", "strconv", ".", "ParseBool", "a", "negative", "duration", "is", "returned", ".", "If", "the", "boolean", "value", "is", "false", "a", "0", "duration", "is", "returned", ".", "If", "the", "string", "s", "is", "a", "duration", "value", "then", "it", "is", "returned", ".", "It", "returns", "an", "error", "if", "the", "duration", "conversion", "failed", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/status.go#L126-L141
train
rkt/rkt
rkt/status.go
newContext
func newContext(t time.Duration) context.Context { ctx := context.Background() if t > 0 { ctx, _ = context.WithTimeout(ctx, t) } return ctx }
go
func newContext(t time.Duration) context.Context { ctx := context.Background() if t > 0 { ctx, _ = context.WithTimeout(ctx, t) } return ctx }
[ "func", "newContext", "(", "t", "time", ".", "Duration", ")", "context", ".", "Context", "{", "ctx", ":=", "context", ".", "Background", "(", ")", "\n", "if", "t", ">", "0", "{", "ctx", ",", "_", "=", "context", ".", "WithTimeout", "(", "ctx", ",", "t", ")", "\n", "}", "\n", "return", "ctx", "\n", "}" ]
// newContext returns a new context with timeout t if t > 0.
[ "newContext", "returns", "a", "new", "context", "with", "timeout", "t", "if", "t", ">", "0", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/status.go#L144-L150
train
rkt/rkt
rkt/status.go
getExitStatuses
func getExitStatuses(p *pkgPod.Pod) (map[string]int, error) { _, manifest, err := p.PodManifest() if err != nil { return nil, err } stats := make(map[string]int) for _, app := range manifest.Apps { exitCode, err := p.AppExitCode(app.Name.String()) if err != nil { continue } stats[app.Name.String()] = exitCode } return stats, nil }
go
func getExitStatuses(p *pkgPod.Pod) (map[string]int, error) { _, manifest, err := p.PodManifest() if err != nil { return nil, err } stats := make(map[string]int) for _, app := range manifest.Apps { exitCode, err := p.AppExitCode(app.Name.String()) if err != nil { continue } stats[app.Name.String()] = exitCode } return stats, nil }
[ "func", "getExitStatuses", "(", "p", "*", "pkgPod", ".", "Pod", ")", "(", "map", "[", "string", "]", "int", ",", "error", ")", "{", "_", ",", "manifest", ",", "err", ":=", "p", ".", "PodManifest", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "stats", ":=", "make", "(", "map", "[", "string", "]", "int", ")", "\n", "for", "_", ",", "app", ":=", "range", "manifest", ".", "Apps", "{", "exitCode", ",", "err", ":=", "p", ".", "AppExitCode", "(", "app", ".", "Name", ".", "String", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "continue", "\n", "}", "\n", "stats", "[", "app", ".", "Name", ".", "String", "(", ")", "]", "=", "exitCode", "\n", "}", "\n", "return", "stats", ",", "nil", "\n", "}" ]
// getExitStatuses returns a map of the statuses of the pod.
[ "getExitStatuses", "returns", "a", "map", "of", "the", "statuses", "of", "the", "pod", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/status.go#L153-L168
train
rkt/rkt
rkt/status.go
printStatus
func printStatus(p *pkgPod.Pod) error { if flagFormat != outputFormatTabbed { pod, err := lib.NewPodFromInternalPod(p) if err != nil { return fmt.Errorf("error converting pod: %v", err) } switch flagFormat { case outputFormatJSON: result, err := json.Marshal(pod) if err != nil { return fmt.Errorf("error marshaling the pod: %v", err) } stdout.Print(string(result)) case outputFormatPrettyJSON: result, err := json.MarshalIndent(pod, "", "\t") if err != nil { return fmt.Errorf("error marshaling the pod: %v", err) } stdout.Print(string(result)) } return nil } state := p.State() stdout.Printf("state=%s", state) created, err := p.CreationTime() if err != nil { return fmt.Errorf("unable to get creation time for pod %q: %v", p.UUID, err) } createdStr := created.Format(defaultTimeLayout) stdout.Printf("created=%s", createdStr) started, err := p.StartTime() if err != nil { return fmt.Errorf("unable to get start time for pod %q: %v", p.UUID, err) } var startedStr string if !started.IsZero() { startedStr = started.Format(defaultTimeLayout) stdout.Printf("started=%s", startedStr) } if state == pkgPod.Running || state == pkgPod.Exited { stdout.Printf("networks=%s", fmtNets(p.Nets)) } if !(state == pkgPod.Running || state == pkgPod.Deleting || state == pkgPod.ExitedDeleting || state == pkgPod.Exited || state == pkgPod.ExitedGarbage) { return nil } if pid, err := p.Pid(); err == nil { // the pid file might not be written yet when the state changes to 'Running' // it may also never be written if systemd never executes (e.g.: a bad command) stdout.Printf("pid=%d", pid) } stdout.Printf("exited=%t", (state == pkgPod.Exited || state == pkgPod.ExitedGarbage)) if state != pkgPod.Running { stats, err := getExitStatuses(p) if err != nil { return fmt.Errorf("unable to get exit statuses for pod %q: %v", p.UUID, err) } for app, stat := range stats { stdout.Printf("app-%s=%d", app, stat) } } return nil }
go
func printStatus(p *pkgPod.Pod) error { if flagFormat != outputFormatTabbed { pod, err := lib.NewPodFromInternalPod(p) if err != nil { return fmt.Errorf("error converting pod: %v", err) } switch flagFormat { case outputFormatJSON: result, err := json.Marshal(pod) if err != nil { return fmt.Errorf("error marshaling the pod: %v", err) } stdout.Print(string(result)) case outputFormatPrettyJSON: result, err := json.MarshalIndent(pod, "", "\t") if err != nil { return fmt.Errorf("error marshaling the pod: %v", err) } stdout.Print(string(result)) } return nil } state := p.State() stdout.Printf("state=%s", state) created, err := p.CreationTime() if err != nil { return fmt.Errorf("unable to get creation time for pod %q: %v", p.UUID, err) } createdStr := created.Format(defaultTimeLayout) stdout.Printf("created=%s", createdStr) started, err := p.StartTime() if err != nil { return fmt.Errorf("unable to get start time for pod %q: %v", p.UUID, err) } var startedStr string if !started.IsZero() { startedStr = started.Format(defaultTimeLayout) stdout.Printf("started=%s", startedStr) } if state == pkgPod.Running || state == pkgPod.Exited { stdout.Printf("networks=%s", fmtNets(p.Nets)) } if !(state == pkgPod.Running || state == pkgPod.Deleting || state == pkgPod.ExitedDeleting || state == pkgPod.Exited || state == pkgPod.ExitedGarbage) { return nil } if pid, err := p.Pid(); err == nil { // the pid file might not be written yet when the state changes to 'Running' // it may also never be written if systemd never executes (e.g.: a bad command) stdout.Printf("pid=%d", pid) } stdout.Printf("exited=%t", (state == pkgPod.Exited || state == pkgPod.ExitedGarbage)) if state != pkgPod.Running { stats, err := getExitStatuses(p) if err != nil { return fmt.Errorf("unable to get exit statuses for pod %q: %v", p.UUID, err) } for app, stat := range stats { stdout.Printf("app-%s=%d", app, stat) } } return nil }
[ "func", "printStatus", "(", "p", "*", "pkgPod", ".", "Pod", ")", "error", "{", "if", "flagFormat", "!=", "outputFormatTabbed", "{", "pod", ",", "err", ":=", "lib", ".", "NewPodFromInternalPod", "(", "p", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"error converting pod: %v\"", ",", "err", ")", "\n", "}", "\n", "switch", "flagFormat", "{", "case", "outputFormatJSON", ":", "result", ",", "err", ":=", "json", ".", "Marshal", "(", "pod", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"error marshaling the pod: %v\"", ",", "err", ")", "\n", "}", "\n", "stdout", ".", "Print", "(", "string", "(", "result", ")", ")", "\n", "case", "outputFormatPrettyJSON", ":", "result", ",", "err", ":=", "json", ".", "MarshalIndent", "(", "pod", ",", "\"\"", ",", "\"\\t\"", ")", "\n", "\\t", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"error marshaling the pod: %v\"", ",", "err", ")", "\n", "}", "\n", "}", "\n", "stdout", ".", "Print", "(", "string", "(", "result", ")", ")", "\n", "}", "\n", "return", "nil", "\n", "state", ":=", "p", ".", "State", "(", ")", "\n", "stdout", ".", "Printf", "(", "\"state=%s\"", ",", "state", ")", "\n", "created", ",", "err", ":=", "p", ".", "CreationTime", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"unable to get creation time for pod %q: %v\"", ",", "p", ".", "UUID", ",", "err", ")", "\n", "}", "\n", "createdStr", ":=", "created", ".", "Format", "(", "defaultTimeLayout", ")", "\n", "stdout", ".", "Printf", "(", "\"created=%s\"", ",", "createdStr", ")", "\n", "started", ",", "err", ":=", "p", ".", "StartTime", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"unable to get start time for pod %q: %v\"", ",", "p", ".", "UUID", ",", "err", ")", "\n", "}", "\n", "var", "startedStr", "string", "\n", "if", "!", "started", ".", "IsZero", "(", ")", "{", "startedStr", "=", "started", ".", "Format", "(", "defaultTimeLayout", ")", "\n", "stdout", ".", "Printf", "(", "\"started=%s\"", ",", "startedStr", ")", "\n", "}", "\n", "if", "state", "==", "pkgPod", ".", "Running", "||", "state", "==", "pkgPod", ".", "Exited", "{", "stdout", ".", "Printf", "(", "\"networks=%s\"", ",", "fmtNets", "(", "p", ".", "Nets", ")", ")", "\n", "}", "\n", "if", "!", "(", "state", "==", "pkgPod", ".", "Running", "||", "state", "==", "pkgPod", ".", "Deleting", "||", "state", "==", "pkgPod", ".", "ExitedDeleting", "||", "state", "==", "pkgPod", ".", "Exited", "||", "state", "==", "pkgPod", ".", "ExitedGarbage", ")", "{", "return", "nil", "\n", "}", "\n", "if", "pid", ",", "err", ":=", "p", ".", "Pid", "(", ")", ";", "err", "==", "nil", "{", "stdout", ".", "Printf", "(", "\"pid=%d\"", ",", "pid", ")", "\n", "}", "\n", "stdout", ".", "Printf", "(", "\"exited=%t\"", ",", "(", "state", "==", "pkgPod", ".", "Exited", "||", "state", "==", "pkgPod", ".", "ExitedGarbage", ")", ")", "\n", "if", "state", "!=", "pkgPod", ".", "Running", "{", "stats", ",", "err", ":=", "getExitStatuses", "(", "p", ")", "\n", "if", "err", "!=", "nil", "{", "return", "fmt", ".", "Errorf", "(", "\"unable to get exit statuses for pod %q: %v\"", ",", "p", ".", "UUID", ",", "err", ")", "\n", "}", "\n", "for", "app", ",", "stat", ":=", "range", "stats", "{", "stdout", ".", "Printf", "(", "\"app-%s=%d\"", ",", "app", ",", "stat", ")", "\n", "}", "\n", "}", "\n", "}" ]
// printStatus prints the pod's pid and per-app status codes
[ "printStatus", "prints", "the", "pod", "s", "pid", "and", "per", "-", "app", "status", "codes" ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/status.go#L171-L240
train
rkt/rkt
rkt/image/common.go
ascURLFromImgURL
func ascURLFromImgURL(u *url.URL) *url.URL { copy := *u copy.Path = ascPathFromImgPath(copy.Path) return &copy }
go
func ascURLFromImgURL(u *url.URL) *url.URL { copy := *u copy.Path = ascPathFromImgPath(copy.Path) return &copy }
[ "func", "ascURLFromImgURL", "(", "u", "*", "url", ".", "URL", ")", "*", "url", ".", "URL", "{", "copy", ":=", "*", "u", "\n", "copy", ".", "Path", "=", "ascPathFromImgPath", "(", "copy", ".", "Path", ")", "\n", "return", "&", "copy", "\n", "}" ]
// ascURLFromImgURL creates a URL to a signature file from passed URL // to an image.
[ "ascURLFromImgURL", "creates", "a", "URL", "to", "a", "signature", "file", "from", "passed", "URL", "to", "an", "image", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/image/common.go#L113-L117
train
rkt/rkt
rkt/image/common.go
printIdentities
func printIdentities(entity *openpgp.Entity) { lines := []string{"signature verified:"} for _, v := range entity.Identities { lines = append(lines, fmt.Sprintf(" %s", v.Name)) } log.Print(strings.Join(lines, "\n")) }
go
func printIdentities(entity *openpgp.Entity) { lines := []string{"signature verified:"} for _, v := range entity.Identities { lines = append(lines, fmt.Sprintf(" %s", v.Name)) } log.Print(strings.Join(lines, "\n")) }
[ "func", "printIdentities", "(", "entity", "*", "openpgp", ".", "Entity", ")", "{", "lines", ":=", "[", "]", "string", "{", "\"signature verified:\"", "}", "\n", "for", "_", ",", "v", ":=", "range", "entity", ".", "Identities", "{", "lines", "=", "append", "(", "lines", ",", "fmt", ".", "Sprintf", "(", "\" %s\"", ",", "v", ".", "Name", ")", ")", "\n", "}", "\n", "log", ".", "Print", "(", "strings", ".", "Join", "(", "lines", ",", "\"\\n\"", ")", ")", "\n", "}" ]
// printIdentities prints a message that signature was verified.
[ "printIdentities", "prints", "a", "message", "that", "signature", "was", "verified", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/image/common.go#L126-L132
train
rkt/rkt
rkt/image/common.go
DistFromImageString
func DistFromImageString(is string) (dist.Distribution, error) { u, err := url.Parse(is) if err != nil { return nil, errwrap.Wrap(fmt.Errorf("failed to parse image url %q", is), err) } // Convert user friendly image string names to internal distribution URIs // file:///full/path/to/aci/file.aci -> archive:aci:file%3A%2F%2F%2Ffull%2Fpath%2Fto%2Faci%2Ffile.aci switch u.Scheme { case "": // no scheme given, hence it is an appc image name or path appImageType := guessAppcOrPath(is, []string{schema.ACIExtension}) switch appImageType { case imageStringName: app, err := discovery.NewAppFromString(is) if err != nil { return nil, fmt.Errorf("invalid appc image string %q: %v", is, err) } return dist.NewAppcFromApp(app), nil case imageStringPath: absPath, err := filepath.Abs(is) if err != nil { return nil, errwrap.Wrap(fmt.Errorf("failed to get an absolute path for %q", is), err) } is = "file://" + absPath // given a file:// image string, call this function again to return an ACI distribution return DistFromImageString(is) default: return nil, fmt.Errorf("invalid image string type %q", appImageType) } case "file", "http", "https": // An ACI archive with any transport type (file, http, s3 etc...) and final aci extension if filepath.Ext(u.Path) == schema.ACIExtension { dist, err := dist.NewACIArchiveFromTransportURL(u) if err != nil { return nil, fmt.Errorf("archive distribution creation error: %v", err) } return dist, nil } case "docker": // Accept both docker: and docker:// uri dockerStr := is if strings.HasPrefix(dockerStr, "docker://") { dockerStr = strings.TrimPrefix(dockerStr, "docker://") } else if strings.HasPrefix(dockerStr, "docker:") { dockerStr = strings.TrimPrefix(dockerStr, "docker:") } dist, err := dist.NewDockerFromString(dockerStr) if err != nil { return nil, fmt.Errorf("docker distribution creation error: %v", err) } return dist, nil case dist.Scheme: // cimd return dist.Parse(is) default: // any other scheme is a an appc image name, i.e. "my-app:v1.0" app, err := discovery.NewAppFromString(is) if err != nil { return nil, fmt.Errorf("invalid appc image string %q: %v", is, err) } return dist.NewAppcFromApp(app), nil } return nil, fmt.Errorf("invalid image string %q", is) }
go
func DistFromImageString(is string) (dist.Distribution, error) { u, err := url.Parse(is) if err != nil { return nil, errwrap.Wrap(fmt.Errorf("failed to parse image url %q", is), err) } // Convert user friendly image string names to internal distribution URIs // file:///full/path/to/aci/file.aci -> archive:aci:file%3A%2F%2F%2Ffull%2Fpath%2Fto%2Faci%2Ffile.aci switch u.Scheme { case "": // no scheme given, hence it is an appc image name or path appImageType := guessAppcOrPath(is, []string{schema.ACIExtension}) switch appImageType { case imageStringName: app, err := discovery.NewAppFromString(is) if err != nil { return nil, fmt.Errorf("invalid appc image string %q: %v", is, err) } return dist.NewAppcFromApp(app), nil case imageStringPath: absPath, err := filepath.Abs(is) if err != nil { return nil, errwrap.Wrap(fmt.Errorf("failed to get an absolute path for %q", is), err) } is = "file://" + absPath // given a file:// image string, call this function again to return an ACI distribution return DistFromImageString(is) default: return nil, fmt.Errorf("invalid image string type %q", appImageType) } case "file", "http", "https": // An ACI archive with any transport type (file, http, s3 etc...) and final aci extension if filepath.Ext(u.Path) == schema.ACIExtension { dist, err := dist.NewACIArchiveFromTransportURL(u) if err != nil { return nil, fmt.Errorf("archive distribution creation error: %v", err) } return dist, nil } case "docker": // Accept both docker: and docker:// uri dockerStr := is if strings.HasPrefix(dockerStr, "docker://") { dockerStr = strings.TrimPrefix(dockerStr, "docker://") } else if strings.HasPrefix(dockerStr, "docker:") { dockerStr = strings.TrimPrefix(dockerStr, "docker:") } dist, err := dist.NewDockerFromString(dockerStr) if err != nil { return nil, fmt.Errorf("docker distribution creation error: %v", err) } return dist, nil case dist.Scheme: // cimd return dist.Parse(is) default: // any other scheme is a an appc image name, i.e. "my-app:v1.0" app, err := discovery.NewAppFromString(is) if err != nil { return nil, fmt.Errorf("invalid appc image string %q: %v", is, err) } return dist.NewAppcFromApp(app), nil } return nil, fmt.Errorf("invalid image string %q", is) }
[ "func", "DistFromImageString", "(", "is", "string", ")", "(", "dist", ".", "Distribution", ",", "error", ")", "{", "u", ",", "err", ":=", "url", ".", "Parse", "(", "is", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errwrap", ".", "Wrap", "(", "fmt", ".", "Errorf", "(", "\"failed to parse image url %q\"", ",", "is", ")", ",", "err", ")", "\n", "}", "\n", "switch", "u", ".", "Scheme", "{", "case", "\"\"", ":", "appImageType", ":=", "guessAppcOrPath", "(", "is", ",", "[", "]", "string", "{", "schema", ".", "ACIExtension", "}", ")", "\n", "switch", "appImageType", "{", "case", "imageStringName", ":", "app", ",", "err", ":=", "discovery", ".", "NewAppFromString", "(", "is", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"invalid appc image string %q: %v\"", ",", "is", ",", "err", ")", "\n", "}", "\n", "return", "dist", ".", "NewAppcFromApp", "(", "app", ")", ",", "nil", "\n", "case", "imageStringPath", ":", "absPath", ",", "err", ":=", "filepath", ".", "Abs", "(", "is", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errwrap", ".", "Wrap", "(", "fmt", ".", "Errorf", "(", "\"failed to get an absolute path for %q\"", ",", "is", ")", ",", "err", ")", "\n", "}", "\n", "is", "=", "\"file://\"", "+", "absPath", "\n", "return", "DistFromImageString", "(", "is", ")", "\n", "default", ":", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"invalid image string type %q\"", ",", "appImageType", ")", "\n", "}", "\n", "case", "\"file\"", ",", "\"http\"", ",", "\"https\"", ":", "if", "filepath", ".", "Ext", "(", "u", ".", "Path", ")", "==", "schema", ".", "ACIExtension", "{", "dist", ",", "err", ":=", "dist", ".", "NewACIArchiveFromTransportURL", "(", "u", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"archive distribution creation error: %v\"", ",", "err", ")", "\n", "}", "\n", "return", "dist", ",", "nil", "\n", "}", "\n", "case", "\"docker\"", ":", "dockerStr", ":=", "is", "\n", "if", "strings", ".", "HasPrefix", "(", "dockerStr", ",", "\"docker://\"", ")", "{", "dockerStr", "=", "strings", ".", "TrimPrefix", "(", "dockerStr", ",", "\"docker://\"", ")", "\n", "}", "else", "if", "strings", ".", "HasPrefix", "(", "dockerStr", ",", "\"docker:\"", ")", "{", "dockerStr", "=", "strings", ".", "TrimPrefix", "(", "dockerStr", ",", "\"docker:\"", ")", "\n", "}", "\n", "dist", ",", "err", ":=", "dist", ".", "NewDockerFromString", "(", "dockerStr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"docker distribution creation error: %v\"", ",", "err", ")", "\n", "}", "\n", "return", "dist", ",", "nil", "\n", "case", "dist", ".", "Scheme", ":", "return", "dist", ".", "Parse", "(", "is", ")", "\n", "default", ":", "app", ",", "err", ":=", "discovery", ".", "NewAppFromString", "(", "is", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"invalid appc image string %q: %v\"", ",", "is", ",", "err", ")", "\n", "}", "\n", "return", "dist", ".", "NewAppcFromApp", "(", "app", ")", ",", "nil", "\n", "}", "\n", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"invalid image string %q\"", ",", "is", ")", "\n", "}" ]
// DistFromImageString return the distribution for the given input image string
[ "DistFromImageString", "return", "the", "distribution", "for", "the", "given", "input", "image", "string" ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/image/common.go#L135-L203
train
rkt/rkt
pkg/distribution/cimd.go
parseCIMD
func parseCIMD(u *url.URL) (*cimd, error) { if u.Scheme != Scheme { return nil, fmt.Errorf("unsupported scheme: %q", u.Scheme) } parts := strings.SplitN(u.Opaque, ":", 3) if len(parts) < 3 { return nil, fmt.Errorf("malformed distribution uri: %q", u.String()) } version, err := strconv.ParseUint(strings.TrimPrefix(parts[1], "v="), 10, 32) if err != nil { return nil, fmt.Errorf("malformed distribution version: %s", parts[1]) } return &cimd{ Type: Type(parts[0]), Version: uint32(version), Data: parts[2], }, nil }
go
func parseCIMD(u *url.URL) (*cimd, error) { if u.Scheme != Scheme { return nil, fmt.Errorf("unsupported scheme: %q", u.Scheme) } parts := strings.SplitN(u.Opaque, ":", 3) if len(parts) < 3 { return nil, fmt.Errorf("malformed distribution uri: %q", u.String()) } version, err := strconv.ParseUint(strings.TrimPrefix(parts[1], "v="), 10, 32) if err != nil { return nil, fmt.Errorf("malformed distribution version: %s", parts[1]) } return &cimd{ Type: Type(parts[0]), Version: uint32(version), Data: parts[2], }, nil }
[ "func", "parseCIMD", "(", "u", "*", "url", ".", "URL", ")", "(", "*", "cimd", ",", "error", ")", "{", "if", "u", ".", "Scheme", "!=", "Scheme", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"unsupported scheme: %q\"", ",", "u", ".", "Scheme", ")", "\n", "}", "\n", "parts", ":=", "strings", ".", "SplitN", "(", "u", ".", "Opaque", ",", "\":\"", ",", "3", ")", "\n", "if", "len", "(", "parts", ")", "<", "3", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"malformed distribution uri: %q\"", ",", "u", ".", "String", "(", ")", ")", "\n", "}", "\n", "version", ",", "err", ":=", "strconv", ".", "ParseUint", "(", "strings", ".", "TrimPrefix", "(", "parts", "[", "1", "]", ",", "\"v=\"", ")", ",", "10", ",", "32", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"malformed distribution version: %s\"", ",", "parts", "[", "1", "]", ")", "\n", "}", "\n", "return", "&", "cimd", "{", "Type", ":", "Type", "(", "parts", "[", "0", "]", ")", ",", "Version", ":", "uint32", "(", "version", ")", ",", "Data", ":", "parts", "[", "2", "]", ",", "}", ",", "nil", "\n", "}" ]
// parseCIMD parses the given url and returns a cimd.
[ "parseCIMD", "parses", "the", "given", "url", "and", "returns", "a", "cimd", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/distribution/cimd.go#L34-L51
train
rkt/rkt
pkg/distribution/cimd.go
NewCIMDString
func NewCIMDString(typ Type, version uint32, data string) string { return fmt.Sprintf("%s:%s:v=%d:%s", Scheme, typ, version, data) }
go
func NewCIMDString(typ Type, version uint32, data string) string { return fmt.Sprintf("%s:%s:v=%d:%s", Scheme, typ, version, data) }
[ "func", "NewCIMDString", "(", "typ", "Type", ",", "version", "uint32", ",", "data", "string", ")", "string", "{", "return", "fmt", ".", "Sprintf", "(", "\"%s:%s:v=%d:%s\"", ",", "Scheme", ",", "typ", ",", "version", ",", "data", ")", "\n", "}" ]
// NewCIMDString creates a new cimd URL string.
[ "NewCIMDString", "creates", "a", "new", "cimd", "URL", "string", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/distribution/cimd.go#L54-L56
train
rkt/rkt
rkt/export.go
getApp
func getApp(p *pkgPod.Pod) (*schema.RuntimeApp, error) { _, manifest, err := p.PodManifest() if err != nil { return nil, errwrap.Wrap(errors.New("problem getting the pod's manifest"), err) } apps := manifest.Apps if flagExportAppName != "" { exportAppName, err := types.NewACName(flagExportAppName) if err != nil { return nil, err } for _, ra := range apps { if *exportAppName == ra.Name { return &ra, nil } } return nil, fmt.Errorf("app %s is not present in pod", flagExportAppName) } switch len(apps) { case 0: return nil, fmt.Errorf("pod contains zero apps") case 1: return &apps[0], nil default: } stderr.Print("pod contains multiple apps:") for _, ra := range apps { stderr.Printf("\t%v", ra.Name) } return nil, fmt.Errorf("specify app using \"rkt export --app= ...\"") }
go
func getApp(p *pkgPod.Pod) (*schema.RuntimeApp, error) { _, manifest, err := p.PodManifest() if err != nil { return nil, errwrap.Wrap(errors.New("problem getting the pod's manifest"), err) } apps := manifest.Apps if flagExportAppName != "" { exportAppName, err := types.NewACName(flagExportAppName) if err != nil { return nil, err } for _, ra := range apps { if *exportAppName == ra.Name { return &ra, nil } } return nil, fmt.Errorf("app %s is not present in pod", flagExportAppName) } switch len(apps) { case 0: return nil, fmt.Errorf("pod contains zero apps") case 1: return &apps[0], nil default: } stderr.Print("pod contains multiple apps:") for _, ra := range apps { stderr.Printf("\t%v", ra.Name) } return nil, fmt.Errorf("specify app using \"rkt export --app= ...\"") }
[ "func", "getApp", "(", "p", "*", "pkgPod", ".", "Pod", ")", "(", "*", "schema", ".", "RuntimeApp", ",", "error", ")", "{", "_", ",", "manifest", ",", "err", ":=", "p", ".", "PodManifest", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"problem getting the pod's manifest\"", ")", ",", "err", ")", "\n", "}", "\n", "apps", ":=", "manifest", ".", "Apps", "\n", "if", "flagExportAppName", "!=", "\"\"", "{", "exportAppName", ",", "err", ":=", "types", ".", "NewACName", "(", "flagExportAppName", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "for", "_", ",", "ra", ":=", "range", "apps", "{", "if", "*", "exportAppName", "==", "ra", ".", "Name", "{", "return", "&", "ra", ",", "nil", "\n", "}", "\n", "}", "\n", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"app %s is not present in pod\"", ",", "flagExportAppName", ")", "\n", "}", "\n", "switch", "len", "(", "apps", ")", "{", "case", "0", ":", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"pod contains zero apps\"", ")", "\n", "case", "1", ":", "return", "&", "apps", "[", "0", "]", ",", "nil", "\n", "default", ":", "}", "\n", "stderr", ".", "Print", "(", "\"pod contains multiple apps:\"", ")", "\n", "for", "_", ",", "ra", ":=", "range", "apps", "{", "stderr", ".", "Printf", "(", "\"\\t%v\"", ",", "\\t", ")", "\n", "}", "\n", "ra", ".", "Name", "\n", "}" ]
// getApp returns the app to export // If one was supplied in the flags then it's returned if present // If the PM contains a single app, that app is returned // If the PM has multiple apps, the names are printed and an error is returned
[ "getApp", "returns", "the", "app", "to", "export", "If", "one", "was", "supplied", "in", "the", "flags", "then", "it", "s", "returned", "if", "present", "If", "the", "PM", "contains", "a", "single", "app", "that", "app", "is", "returned", "If", "the", "PM", "has", "multiple", "apps", "the", "names", "are", "printed", "and", "an", "error", "is", "returned" ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/export.go#L164-L199
train
rkt/rkt
rkt/export.go
mountOverlay
func mountOverlay(pod *pkgPod.Pod, app *schema.RuntimeApp, dest string) error { if _, err := os.Stat(dest); err != nil { return err } s, err := imagestore.NewStore(getDataDir()) if err != nil { return errwrap.Wrap(errors.New("cannot open store"), err) } ts, err := treestore.NewStore(treeStoreDir(), s) if err != nil { return errwrap.Wrap(errors.New("cannot open treestore"), err) } treeStoreID, err := pod.GetAppTreeStoreID(app.Name) if err != nil { return err } lower := ts.GetRootFS(treeStoreID) imgDir := filepath.Join(filepath.Join(pod.Path(), "overlay"), treeStoreID) if _, err := os.Stat(imgDir); err != nil { return err } upper := filepath.Join(imgDir, "upper", app.Name.String()) if _, err := os.Stat(upper); err != nil { return err } work := filepath.Join(imgDir, "work", app.Name.String()) if _, err := os.Stat(work); err != nil { return err } if err := overlay.Mount(&overlay.MountCfg{lower, upper, work, dest, ""}); err != nil { return errwrap.Wrap(errors.New("problem mounting overlayfs directory"), err) } return nil }
go
func mountOverlay(pod *pkgPod.Pod, app *schema.RuntimeApp, dest string) error { if _, err := os.Stat(dest); err != nil { return err } s, err := imagestore.NewStore(getDataDir()) if err != nil { return errwrap.Wrap(errors.New("cannot open store"), err) } ts, err := treestore.NewStore(treeStoreDir(), s) if err != nil { return errwrap.Wrap(errors.New("cannot open treestore"), err) } treeStoreID, err := pod.GetAppTreeStoreID(app.Name) if err != nil { return err } lower := ts.GetRootFS(treeStoreID) imgDir := filepath.Join(filepath.Join(pod.Path(), "overlay"), treeStoreID) if _, err := os.Stat(imgDir); err != nil { return err } upper := filepath.Join(imgDir, "upper", app.Name.String()) if _, err := os.Stat(upper); err != nil { return err } work := filepath.Join(imgDir, "work", app.Name.String()) if _, err := os.Stat(work); err != nil { return err } if err := overlay.Mount(&overlay.MountCfg{lower, upper, work, dest, ""}); err != nil { return errwrap.Wrap(errors.New("problem mounting overlayfs directory"), err) } return nil }
[ "func", "mountOverlay", "(", "pod", "*", "pkgPod", ".", "Pod", ",", "app", "*", "schema", ".", "RuntimeApp", ",", "dest", "string", ")", "error", "{", "if", "_", ",", "err", ":=", "os", ".", "Stat", "(", "dest", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "s", ",", "err", ":=", "imagestore", ".", "NewStore", "(", "getDataDir", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"cannot open store\"", ")", ",", "err", ")", "\n", "}", "\n", "ts", ",", "err", ":=", "treestore", ".", "NewStore", "(", "treeStoreDir", "(", ")", ",", "s", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"cannot open treestore\"", ")", ",", "err", ")", "\n", "}", "\n", "treeStoreID", ",", "err", ":=", "pod", ".", "GetAppTreeStoreID", "(", "app", ".", "Name", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "lower", ":=", "ts", ".", "GetRootFS", "(", "treeStoreID", ")", "\n", "imgDir", ":=", "filepath", ".", "Join", "(", "filepath", ".", "Join", "(", "pod", ".", "Path", "(", ")", ",", "\"overlay\"", ")", ",", "treeStoreID", ")", "\n", "if", "_", ",", "err", ":=", "os", ".", "Stat", "(", "imgDir", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "upper", ":=", "filepath", ".", "Join", "(", "imgDir", ",", "\"upper\"", ",", "app", ".", "Name", ".", "String", "(", ")", ")", "\n", "if", "_", ",", "err", ":=", "os", ".", "Stat", "(", "upper", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "work", ":=", "filepath", ".", "Join", "(", "imgDir", ",", "\"work\"", ",", "app", ".", "Name", ".", "String", "(", ")", ")", "\n", "if", "_", ",", "err", ":=", "os", ".", "Stat", "(", "work", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "overlay", ".", "Mount", "(", "&", "overlay", ".", "MountCfg", "{", "lower", ",", "upper", ",", "work", ",", "dest", ",", "\"\"", "}", ")", ";", "err", "!=", "nil", "{", "return", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"problem mounting overlayfs directory\"", ")", ",", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// mountOverlay mounts the app from the overlay-rendered pod to the destination directory.
[ "mountOverlay", "mounts", "the", "app", "from", "the", "overlay", "-", "rendered", "pod", "to", "the", "destination", "directory", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/export.go#L202-L240
train
rkt/rkt
rkt/export.go
buildAci
func buildAci(root, manifestPath, target string, uidRange *user.UidRange) (e error) { mode := os.O_CREATE | os.O_WRONLY if flagOverwriteACI { mode |= os.O_TRUNC } else { mode |= os.O_EXCL } aciFile, err := os.OpenFile(target, mode, 0644) if err != nil { if os.IsExist(err) { return errors.New("target file exists (try --overwrite)") } else { return errwrap.Wrap(fmt.Errorf("unable to open target %s", target), err) } } gw := gzip.NewWriter(aciFile) tr := tar.NewWriter(gw) defer func() { tr.Close() gw.Close() aciFile.Close() // e is implicitly assigned by the return statement. As defer runs // after return, but before actually returning, this works. if e != nil { os.Remove(target) } }() b, err := ioutil.ReadFile(manifestPath) if err != nil { return errwrap.Wrap(errors.New("unable to read Image Manifest"), err) } var im schema.ImageManifest if err := im.UnmarshalJSON(b); err != nil { return errwrap.Wrap(errors.New("unable to load Image Manifest"), err) } iw := aci.NewImageWriter(im, tr) // Unshift uid and gid when pod was started with --private-user (user namespace) var walkerCb aci.TarHeaderWalkFunc = func(hdr *tar.Header) bool { if uidRange != nil { uid, gid, err := uidRange.UnshiftRange(uint32(hdr.Uid), uint32(hdr.Gid)) if err != nil { stderr.PrintE("error unshifting gid and uid", err) return false } hdr.Uid, hdr.Gid = int(uid), int(gid) } return true } if err := filepath.Walk(root, aci.BuildWalker(root, iw, walkerCb)); err != nil { return errwrap.Wrap(errors.New("error walking rootfs"), err) } if err = iw.Close(); err != nil { return errwrap.Wrap(fmt.Errorf("unable to close image %s", target), err) } return }
go
func buildAci(root, manifestPath, target string, uidRange *user.UidRange) (e error) { mode := os.O_CREATE | os.O_WRONLY if flagOverwriteACI { mode |= os.O_TRUNC } else { mode |= os.O_EXCL } aciFile, err := os.OpenFile(target, mode, 0644) if err != nil { if os.IsExist(err) { return errors.New("target file exists (try --overwrite)") } else { return errwrap.Wrap(fmt.Errorf("unable to open target %s", target), err) } } gw := gzip.NewWriter(aciFile) tr := tar.NewWriter(gw) defer func() { tr.Close() gw.Close() aciFile.Close() // e is implicitly assigned by the return statement. As defer runs // after return, but before actually returning, this works. if e != nil { os.Remove(target) } }() b, err := ioutil.ReadFile(manifestPath) if err != nil { return errwrap.Wrap(errors.New("unable to read Image Manifest"), err) } var im schema.ImageManifest if err := im.UnmarshalJSON(b); err != nil { return errwrap.Wrap(errors.New("unable to load Image Manifest"), err) } iw := aci.NewImageWriter(im, tr) // Unshift uid and gid when pod was started with --private-user (user namespace) var walkerCb aci.TarHeaderWalkFunc = func(hdr *tar.Header) bool { if uidRange != nil { uid, gid, err := uidRange.UnshiftRange(uint32(hdr.Uid), uint32(hdr.Gid)) if err != nil { stderr.PrintE("error unshifting gid and uid", err) return false } hdr.Uid, hdr.Gid = int(uid), int(gid) } return true } if err := filepath.Walk(root, aci.BuildWalker(root, iw, walkerCb)); err != nil { return errwrap.Wrap(errors.New("error walking rootfs"), err) } if err = iw.Close(); err != nil { return errwrap.Wrap(fmt.Errorf("unable to close image %s", target), err) } return }
[ "func", "buildAci", "(", "root", ",", "manifestPath", ",", "target", "string", ",", "uidRange", "*", "user", ".", "UidRange", ")", "(", "e", "error", ")", "{", "mode", ":=", "os", ".", "O_CREATE", "|", "os", ".", "O_WRONLY", "\n", "if", "flagOverwriteACI", "{", "mode", "|=", "os", ".", "O_TRUNC", "\n", "}", "else", "{", "mode", "|=", "os", ".", "O_EXCL", "\n", "}", "\n", "aciFile", ",", "err", ":=", "os", ".", "OpenFile", "(", "target", ",", "mode", ",", "0644", ")", "\n", "if", "err", "!=", "nil", "{", "if", "os", ".", "IsExist", "(", "err", ")", "{", "return", "errors", ".", "New", "(", "\"target file exists (try --overwrite)\"", ")", "\n", "}", "else", "{", "return", "errwrap", ".", "Wrap", "(", "fmt", ".", "Errorf", "(", "\"unable to open target %s\"", ",", "target", ")", ",", "err", ")", "\n", "}", "\n", "}", "\n", "gw", ":=", "gzip", ".", "NewWriter", "(", "aciFile", ")", "\n", "tr", ":=", "tar", ".", "NewWriter", "(", "gw", ")", "\n", "defer", "func", "(", ")", "{", "tr", ".", "Close", "(", ")", "\n", "gw", ".", "Close", "(", ")", "\n", "aciFile", ".", "Close", "(", ")", "\n", "if", "e", "!=", "nil", "{", "os", ".", "Remove", "(", "target", ")", "\n", "}", "\n", "}", "(", ")", "\n", "b", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "manifestPath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"unable to read Image Manifest\"", ")", ",", "err", ")", "\n", "}", "\n", "var", "im", "schema", ".", "ImageManifest", "\n", "if", "err", ":=", "im", ".", "UnmarshalJSON", "(", "b", ")", ";", "err", "!=", "nil", "{", "return", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"unable to load Image Manifest\"", ")", ",", "err", ")", "\n", "}", "\n", "iw", ":=", "aci", ".", "NewImageWriter", "(", "im", ",", "tr", ")", "\n", "var", "walkerCb", "aci", ".", "TarHeaderWalkFunc", "=", "func", "(", "hdr", "*", "tar", ".", "Header", ")", "bool", "{", "if", "uidRange", "!=", "nil", "{", "uid", ",", "gid", ",", "err", ":=", "uidRange", ".", "UnshiftRange", "(", "uint32", "(", "hdr", ".", "Uid", ")", ",", "uint32", "(", "hdr", ".", "Gid", ")", ")", "\n", "if", "err", "!=", "nil", "{", "stderr", ".", "PrintE", "(", "\"error unshifting gid and uid\"", ",", "err", ")", "\n", "return", "false", "\n", "}", "\n", "hdr", ".", "Uid", ",", "hdr", ".", "Gid", "=", "int", "(", "uid", ")", ",", "int", "(", "gid", ")", "\n", "}", "\n", "return", "true", "\n", "}", "\n", "if", "err", ":=", "filepath", ".", "Walk", "(", "root", ",", "aci", ".", "BuildWalker", "(", "root", ",", "iw", ",", "walkerCb", ")", ")", ";", "err", "!=", "nil", "{", "return", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"error walking rootfs\"", ")", ",", "err", ")", "\n", "}", "\n", "if", "err", "=", "iw", ".", "Close", "(", ")", ";", "err", "!=", "nil", "{", "return", "errwrap", ".", "Wrap", "(", "fmt", ".", "Errorf", "(", "\"unable to close image %s\"", ",", "target", ")", ",", "err", ")", "\n", "}", "\n", "return", "\n", "}" ]
// buildAci builds a target aci from the root directory using any uid shift // information from uidRange.
[ "buildAci", "builds", "a", "target", "aci", "from", "the", "root", "directory", "using", "any", "uid", "shift", "information", "from", "uidRange", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/export.go#L244-L306
train
rkt/rkt
rkt/rkt.go
ensureSuperuser
func ensureSuperuser(cf func(cmd *cobra.Command, args []string)) func(cmd *cobra.Command, args []string) { return func(cmd *cobra.Command, args []string) { if os.Geteuid() != 0 { stderr.Print("cannot run as unprivileged user") cmdExitCode = 254 return } cf(cmd, args) } }
go
func ensureSuperuser(cf func(cmd *cobra.Command, args []string)) func(cmd *cobra.Command, args []string) { return func(cmd *cobra.Command, args []string) { if os.Geteuid() != 0 { stderr.Print("cannot run as unprivileged user") cmdExitCode = 254 return } cf(cmd, args) } }
[ "func", "ensureSuperuser", "(", "cf", "func", "(", "cmd", "*", "cobra", ".", "Command", ",", "args", "[", "]", "string", ")", ")", "func", "(", "cmd", "*", "cobra", ".", "Command", ",", "args", "[", "]", "string", ")", "{", "return", "func", "(", "cmd", "*", "cobra", ".", "Command", ",", "args", "[", "]", "string", ")", "{", "if", "os", ".", "Geteuid", "(", ")", "!=", "0", "{", "stderr", ".", "Print", "(", "\"cannot run as unprivileged user\"", ")", "\n", "cmdExitCode", "=", "254", "\n", "return", "\n", "}", "\n", "cf", "(", "cmd", ",", "args", ")", "\n", "}", "\n", "}" ]
// ensureSuperuser will error out if the effective UID of the current process // is not zero. Otherwise, it will invoke the supplied cobra command.
[ "ensureSuperuser", "will", "error", "out", "if", "the", "effective", "UID", "of", "the", "current", "process", "is", "not", "zero", ".", "Otherwise", "it", "will", "invoke", "the", "supplied", "cobra", "command", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/rkt.go#L192-L202
train
rkt/rkt
stage1/init/common/seccomp.go
generateSeccompFilter
func generateSeccompFilter(p *stage1commontypes.Pod, pa *preparedApp) (*seccompFilter, error) { sf := seccompFilter{} seenIsolators := 0 for _, i := range pa.app.App.Isolators { var flag string var err error if seccomp, ok := i.Value().(types.LinuxSeccompSet); ok { seenIsolators++ // By appc spec, only one seccomp isolator per app is allowed if seenIsolators > 1 { return nil, ErrTooManySeccompIsolators } switch i.Name { case types.LinuxSeccompRemoveSetName: sf.mode = ModeBlacklist sf.syscalls, flag, err = parseLinuxSeccompSet(p, seccomp) if err != nil { return nil, err } if flag == "empty" { // we interpret "remove @empty" to mean "default whitelist" sf.mode = ModeWhitelist sf.syscalls = RktDefaultSeccompWhitelist } case types.LinuxSeccompRetainSetName: sf.mode = ModeWhitelist sf.syscalls, flag, err = parseLinuxSeccompSet(p, seccomp) if err != nil { return nil, err } if flag == "all" { // Opt-out seccomp filtering return nil, nil } } sf.errno = string(seccomp.Errno()) } } // If unset, use rkt default whitelist if seenIsolators == 0 { sf.mode = ModeWhitelist sf.syscalls = RktDefaultSeccompWhitelist } // Non-priv apps *must* have NoNewPrivileges set if they have seccomp sf.forceNoNewPrivileges = (pa.uid != 0) return &sf, nil }
go
func generateSeccompFilter(p *stage1commontypes.Pod, pa *preparedApp) (*seccompFilter, error) { sf := seccompFilter{} seenIsolators := 0 for _, i := range pa.app.App.Isolators { var flag string var err error if seccomp, ok := i.Value().(types.LinuxSeccompSet); ok { seenIsolators++ // By appc spec, only one seccomp isolator per app is allowed if seenIsolators > 1 { return nil, ErrTooManySeccompIsolators } switch i.Name { case types.LinuxSeccompRemoveSetName: sf.mode = ModeBlacklist sf.syscalls, flag, err = parseLinuxSeccompSet(p, seccomp) if err != nil { return nil, err } if flag == "empty" { // we interpret "remove @empty" to mean "default whitelist" sf.mode = ModeWhitelist sf.syscalls = RktDefaultSeccompWhitelist } case types.LinuxSeccompRetainSetName: sf.mode = ModeWhitelist sf.syscalls, flag, err = parseLinuxSeccompSet(p, seccomp) if err != nil { return nil, err } if flag == "all" { // Opt-out seccomp filtering return nil, nil } } sf.errno = string(seccomp.Errno()) } } // If unset, use rkt default whitelist if seenIsolators == 0 { sf.mode = ModeWhitelist sf.syscalls = RktDefaultSeccompWhitelist } // Non-priv apps *must* have NoNewPrivileges set if they have seccomp sf.forceNoNewPrivileges = (pa.uid != 0) return &sf, nil }
[ "func", "generateSeccompFilter", "(", "p", "*", "stage1commontypes", ".", "Pod", ",", "pa", "*", "preparedApp", ")", "(", "*", "seccompFilter", ",", "error", ")", "{", "sf", ":=", "seccompFilter", "{", "}", "\n", "seenIsolators", ":=", "0", "\n", "for", "_", ",", "i", ":=", "range", "pa", ".", "app", ".", "App", ".", "Isolators", "{", "var", "flag", "string", "\n", "var", "err", "error", "\n", "if", "seccomp", ",", "ok", ":=", "i", ".", "Value", "(", ")", ".", "(", "types", ".", "LinuxSeccompSet", ")", ";", "ok", "{", "seenIsolators", "++", "\n", "if", "seenIsolators", ">", "1", "{", "return", "nil", ",", "ErrTooManySeccompIsolators", "\n", "}", "\n", "switch", "i", ".", "Name", "{", "case", "types", ".", "LinuxSeccompRemoveSetName", ":", "sf", ".", "mode", "=", "ModeBlacklist", "\n", "sf", ".", "syscalls", ",", "flag", ",", "err", "=", "parseLinuxSeccompSet", "(", "p", ",", "seccomp", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "flag", "==", "\"empty\"", "{", "sf", ".", "mode", "=", "ModeWhitelist", "\n", "sf", ".", "syscalls", "=", "RktDefaultSeccompWhitelist", "\n", "}", "\n", "case", "types", ".", "LinuxSeccompRetainSetName", ":", "sf", ".", "mode", "=", "ModeWhitelist", "\n", "sf", ".", "syscalls", ",", "flag", ",", "err", "=", "parseLinuxSeccompSet", "(", "p", ",", "seccomp", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "flag", "==", "\"all\"", "{", "return", "nil", ",", "nil", "\n", "}", "\n", "}", "\n", "sf", ".", "errno", "=", "string", "(", "seccomp", ".", "Errno", "(", ")", ")", "\n", "}", "\n", "}", "\n", "if", "seenIsolators", "==", "0", "{", "sf", ".", "mode", "=", "ModeWhitelist", "\n", "sf", ".", "syscalls", "=", "RktDefaultSeccompWhitelist", "\n", "}", "\n", "sf", ".", "forceNoNewPrivileges", "=", "(", "pa", ".", "uid", "!=", "0", ")", "\n", "return", "&", "sf", ",", "nil", "\n", "}" ]
// generateSeccompFilter computes the concrete seccomp filter from the isolators
[ "generateSeccompFilter", "computes", "the", "concrete", "seccomp", "filter", "from", "the", "isolators" ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage1/init/common/seccomp.go#L58-L107
train
rkt/rkt
stage1/init/common/seccomp.go
seccompUnitOptions
func seccompUnitOptions(opts []*unit.UnitOption, sf *seccompFilter) ([]*unit.UnitOption, error) { if sf == nil { return opts, nil } if sf.errno != "" { opts = append(opts, unit.NewUnitOption("Service", "SystemCallErrorNumber", sf.errno)) } var filterPrefix string switch sf.mode { case ModeWhitelist: filterPrefix = sdWhitelistPrefix case ModeBlacklist: filterPrefix = sdBlacklistPrefix default: return nil, fmt.Errorf("unknown filter mode %v", sf.mode) } // SystemCallFilter options are written down one entry per line, because // filtering sets may be quite large and overlong lines break unit serialization. opts = appendOptionsList(opts, "Service", "SystemCallFilter", filterPrefix, sf.syscalls...) return opts, nil }
go
func seccompUnitOptions(opts []*unit.UnitOption, sf *seccompFilter) ([]*unit.UnitOption, error) { if sf == nil { return opts, nil } if sf.errno != "" { opts = append(opts, unit.NewUnitOption("Service", "SystemCallErrorNumber", sf.errno)) } var filterPrefix string switch sf.mode { case ModeWhitelist: filterPrefix = sdWhitelistPrefix case ModeBlacklist: filterPrefix = sdBlacklistPrefix default: return nil, fmt.Errorf("unknown filter mode %v", sf.mode) } // SystemCallFilter options are written down one entry per line, because // filtering sets may be quite large and overlong lines break unit serialization. opts = appendOptionsList(opts, "Service", "SystemCallFilter", filterPrefix, sf.syscalls...) return opts, nil }
[ "func", "seccompUnitOptions", "(", "opts", "[", "]", "*", "unit", ".", "UnitOption", ",", "sf", "*", "seccompFilter", ")", "(", "[", "]", "*", "unit", ".", "UnitOption", ",", "error", ")", "{", "if", "sf", "==", "nil", "{", "return", "opts", ",", "nil", "\n", "}", "\n", "if", "sf", ".", "errno", "!=", "\"\"", "{", "opts", "=", "append", "(", "opts", ",", "unit", ".", "NewUnitOption", "(", "\"Service\"", ",", "\"SystemCallErrorNumber\"", ",", "sf", ".", "errno", ")", ")", "\n", "}", "\n", "var", "filterPrefix", "string", "\n", "switch", "sf", ".", "mode", "{", "case", "ModeWhitelist", ":", "filterPrefix", "=", "sdWhitelistPrefix", "\n", "case", "ModeBlacklist", ":", "filterPrefix", "=", "sdBlacklistPrefix", "\n", "default", ":", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"unknown filter mode %v\"", ",", "sf", ".", "mode", ")", "\n", "}", "\n", "opts", "=", "appendOptionsList", "(", "opts", ",", "\"Service\"", ",", "\"SystemCallFilter\"", ",", "filterPrefix", ",", "sf", ".", "syscalls", "...", ")", "\n", "return", "opts", ",", "nil", "\n", "}" ]
// seccompUnitOptions converts a concrete seccomp filter to systemd unit options
[ "seccompUnitOptions", "converts", "a", "concrete", "seccomp", "filter", "to", "systemd", "unit", "options" ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage1/init/common/seccomp.go#L110-L132
train
rkt/rkt
stage1/init/common/seccomp.go
parseLinuxSeccompSet
func parseLinuxSeccompSet(p *stage1commontypes.Pod, s types.LinuxSeccompSet) (syscallFilter []string, flag string, err error) { for _, item := range s.Set() { if item[0] == '@' { // Wildcards wildcard := strings.SplitN(string(item), "/", 2) if len(wildcard) != 2 { continue } scope := wildcard[0] name := wildcard[1] switch scope { case "@appc.io": // appc-reserved wildcards switch name { case "all": return nil, "all", nil case "empty": return nil, "empty", nil } case "@docker": // Docker-originated wildcards switch name { case "default-blacklist": syscallFilter = append(syscallFilter, DockerDefaultSeccompBlacklist...) case "default-whitelist": syscallFilter = append(syscallFilter, DockerDefaultSeccompWhitelist...) } case "@rkt": // Custom rkt wildcards switch name { case "default-blacklist": syscallFilter = append(syscallFilter, RktDefaultSeccompBlacklist...) case "default-whitelist": syscallFilter = append(syscallFilter, RktDefaultSeccompWhitelist...) } case "@systemd": // Custom systemd wildcards (systemd >= 231) _, systemdVersion, err := GetFlavor(p) if err != nil || systemdVersion < 231 { return nil, "", errors.New("Unsupported or unknown systemd version, seccomp groups need systemd >= v231") } switch name { case "clock": syscallFilter = append(syscallFilter, "@clock") case "default-whitelist": syscallFilter = append(syscallFilter, "@default") case "mount": syscallFilter = append(syscallFilter, "@mount") case "network-io": syscallFilter = append(syscallFilter, "@network-io") case "obsolete": syscallFilter = append(syscallFilter, "@obsolete") case "privileged": syscallFilter = append(syscallFilter, "@privileged") case "process": syscallFilter = append(syscallFilter, "@process") case "raw-io": syscallFilter = append(syscallFilter, "@raw-io") } } } else { // Plain syscall name syscallFilter = append(syscallFilter, string(item)) } } return syscallFilter, "", nil }
go
func parseLinuxSeccompSet(p *stage1commontypes.Pod, s types.LinuxSeccompSet) (syscallFilter []string, flag string, err error) { for _, item := range s.Set() { if item[0] == '@' { // Wildcards wildcard := strings.SplitN(string(item), "/", 2) if len(wildcard) != 2 { continue } scope := wildcard[0] name := wildcard[1] switch scope { case "@appc.io": // appc-reserved wildcards switch name { case "all": return nil, "all", nil case "empty": return nil, "empty", nil } case "@docker": // Docker-originated wildcards switch name { case "default-blacklist": syscallFilter = append(syscallFilter, DockerDefaultSeccompBlacklist...) case "default-whitelist": syscallFilter = append(syscallFilter, DockerDefaultSeccompWhitelist...) } case "@rkt": // Custom rkt wildcards switch name { case "default-blacklist": syscallFilter = append(syscallFilter, RktDefaultSeccompBlacklist...) case "default-whitelist": syscallFilter = append(syscallFilter, RktDefaultSeccompWhitelist...) } case "@systemd": // Custom systemd wildcards (systemd >= 231) _, systemdVersion, err := GetFlavor(p) if err != nil || systemdVersion < 231 { return nil, "", errors.New("Unsupported or unknown systemd version, seccomp groups need systemd >= v231") } switch name { case "clock": syscallFilter = append(syscallFilter, "@clock") case "default-whitelist": syscallFilter = append(syscallFilter, "@default") case "mount": syscallFilter = append(syscallFilter, "@mount") case "network-io": syscallFilter = append(syscallFilter, "@network-io") case "obsolete": syscallFilter = append(syscallFilter, "@obsolete") case "privileged": syscallFilter = append(syscallFilter, "@privileged") case "process": syscallFilter = append(syscallFilter, "@process") case "raw-io": syscallFilter = append(syscallFilter, "@raw-io") } } } else { // Plain syscall name syscallFilter = append(syscallFilter, string(item)) } } return syscallFilter, "", nil }
[ "func", "parseLinuxSeccompSet", "(", "p", "*", "stage1commontypes", ".", "Pod", ",", "s", "types", ".", "LinuxSeccompSet", ")", "(", "syscallFilter", "[", "]", "string", ",", "flag", "string", ",", "err", "error", ")", "{", "for", "_", ",", "item", ":=", "range", "s", ".", "Set", "(", ")", "{", "if", "item", "[", "0", "]", "==", "'@'", "{", "wildcard", ":=", "strings", ".", "SplitN", "(", "string", "(", "item", ")", ",", "\"/\"", ",", "2", ")", "\n", "if", "len", "(", "wildcard", ")", "!=", "2", "{", "continue", "\n", "}", "\n", "scope", ":=", "wildcard", "[", "0", "]", "\n", "name", ":=", "wildcard", "[", "1", "]", "\n", "switch", "scope", "{", "case", "\"@appc.io\"", ":", "switch", "name", "{", "case", "\"all\"", ":", "return", "nil", ",", "\"all\"", ",", "nil", "\n", "case", "\"empty\"", ":", "return", "nil", ",", "\"empty\"", ",", "nil", "\n", "}", "\n", "case", "\"@docker\"", ":", "switch", "name", "{", "case", "\"default-blacklist\"", ":", "syscallFilter", "=", "append", "(", "syscallFilter", ",", "DockerDefaultSeccompBlacklist", "...", ")", "\n", "case", "\"default-whitelist\"", ":", "syscallFilter", "=", "append", "(", "syscallFilter", ",", "DockerDefaultSeccompWhitelist", "...", ")", "\n", "}", "\n", "case", "\"@rkt\"", ":", "switch", "name", "{", "case", "\"default-blacklist\"", ":", "syscallFilter", "=", "append", "(", "syscallFilter", ",", "RktDefaultSeccompBlacklist", "...", ")", "\n", "case", "\"default-whitelist\"", ":", "syscallFilter", "=", "append", "(", "syscallFilter", ",", "RktDefaultSeccompWhitelist", "...", ")", "\n", "}", "\n", "case", "\"@systemd\"", ":", "_", ",", "systemdVersion", ",", "err", ":=", "GetFlavor", "(", "p", ")", "\n", "if", "err", "!=", "nil", "||", "systemdVersion", "<", "231", "{", "return", "nil", ",", "\"\"", ",", "errors", ".", "New", "(", "\"Unsupported or unknown systemd version, seccomp groups need systemd >= v231\"", ")", "\n", "}", "\n", "switch", "name", "{", "case", "\"clock\"", ":", "syscallFilter", "=", "append", "(", "syscallFilter", ",", "\"@clock\"", ")", "\n", "case", "\"default-whitelist\"", ":", "syscallFilter", "=", "append", "(", "syscallFilter", ",", "\"@default\"", ")", "\n", "case", "\"mount\"", ":", "syscallFilter", "=", "append", "(", "syscallFilter", ",", "\"@mount\"", ")", "\n", "case", "\"network-io\"", ":", "syscallFilter", "=", "append", "(", "syscallFilter", ",", "\"@network-io\"", ")", "\n", "case", "\"obsolete\"", ":", "syscallFilter", "=", "append", "(", "syscallFilter", ",", "\"@obsolete\"", ")", "\n", "case", "\"privileged\"", ":", "syscallFilter", "=", "append", "(", "syscallFilter", ",", "\"@privileged\"", ")", "\n", "case", "\"process\"", ":", "syscallFilter", "=", "append", "(", "syscallFilter", ",", "\"@process\"", ")", "\n", "case", "\"raw-io\"", ":", "syscallFilter", "=", "append", "(", "syscallFilter", ",", "\"@raw-io\"", ")", "\n", "}", "\n", "}", "\n", "}", "else", "{", "syscallFilter", "=", "append", "(", "syscallFilter", ",", "string", "(", "item", ")", ")", "\n", "}", "\n", "}", "\n", "return", "syscallFilter", ",", "\"\"", ",", "nil", "\n", "}" ]
// parseLinuxSeccompSet gets an appc LinuxSeccompSet and returns an array // of values suitable for systemd SystemCallFilter.
[ "parseLinuxSeccompSet", "gets", "an", "appc", "LinuxSeccompSet", "and", "returns", "an", "array", "of", "values", "suitable", "for", "systemd", "SystemCallFilter", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage1/init/common/seccomp.go#L136-L202
train
rkt/rkt
stage1/app_rm/app_rm.go
main
func main() { flag.Parse() stage1initcommon.InitDebug(debug) log, diag, _ = rktlog.NewLogSet("app-rm", debug) if !debug { diag.SetOutput(ioutil.Discard) } appName, err := types.NewACName(flagApp) if err != nil { log.FatalE("invalid app name", err) } enterCmd := stage1common.PrepareEnterCmd(false) switch flagStage { case 0: // clean resources in stage0 err = cleanupStage0(appName, enterCmd) case 1: // clean resources in stage1 err = cleanupStage1(appName, enterCmd) default: // unknown step err = fmt.Errorf("unsupported cleaning step %d", flagStage) } if err != nil { log.FatalE("cleanup error", err) } os.Exit(0) }
go
func main() { flag.Parse() stage1initcommon.InitDebug(debug) log, diag, _ = rktlog.NewLogSet("app-rm", debug) if !debug { diag.SetOutput(ioutil.Discard) } appName, err := types.NewACName(flagApp) if err != nil { log.FatalE("invalid app name", err) } enterCmd := stage1common.PrepareEnterCmd(false) switch flagStage { case 0: // clean resources in stage0 err = cleanupStage0(appName, enterCmd) case 1: // clean resources in stage1 err = cleanupStage1(appName, enterCmd) default: // unknown step err = fmt.Errorf("unsupported cleaning step %d", flagStage) } if err != nil { log.FatalE("cleanup error", err) } os.Exit(0) }
[ "func", "main", "(", ")", "{", "flag", ".", "Parse", "(", ")", "\n", "stage1initcommon", ".", "InitDebug", "(", "debug", ")", "\n", "log", ",", "diag", ",", "_", "=", "rktlog", ".", "NewLogSet", "(", "\"app-rm\"", ",", "debug", ")", "\n", "if", "!", "debug", "{", "diag", ".", "SetOutput", "(", "ioutil", ".", "Discard", ")", "\n", "}", "\n", "appName", ",", "err", ":=", "types", ".", "NewACName", "(", "flagApp", ")", "\n", "if", "err", "!=", "nil", "{", "log", ".", "FatalE", "(", "\"invalid app name\"", ",", "err", ")", "\n", "}", "\n", "enterCmd", ":=", "stage1common", ".", "PrepareEnterCmd", "(", "false", ")", "\n", "switch", "flagStage", "{", "case", "0", ":", "err", "=", "cleanupStage0", "(", "appName", ",", "enterCmd", ")", "\n", "case", "1", ":", "err", "=", "cleanupStage1", "(", "appName", ",", "enterCmd", ")", "\n", "default", ":", "err", "=", "fmt", ".", "Errorf", "(", "\"unsupported cleaning step %d\"", ",", "flagStage", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "log", ".", "FatalE", "(", "\"cleanup error\"", ",", "err", ")", "\n", "}", "\n", "os", ".", "Exit", "(", "0", ")", "\n", "}" ]
// This is a multi-step entrypoint. It starts in stage0 context then invokes // itself again in stage1 context to perform further cleanup at pod level.
[ "This", "is", "a", "multi", "-", "step", "entrypoint", ".", "It", "starts", "in", "stage0", "context", "then", "invokes", "itself", "again", "in", "stage1", "context", "to", "perform", "further", "cleanup", "at", "pod", "level", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage1/app_rm/app_rm.go#L56-L88
train
rkt/rkt
stage1/app_rm/app_rm.go
cleanupStage1
func cleanupStage1(appName *types.ACName, enterCmd []string) error { // TODO(lucab): re-evaluate once/if we support systemd as non-pid1 (eg. host pid-ns inheriting) mnts, err := mountinfo.ParseMounts(1) if err != nil { return err } appRootFs := filepath.Join("/opt/stage2", appName.String(), "rootfs") mnts = mnts.Filter(mountinfo.HasPrefix(appRootFs)) // soft-errors here, stage0 may still be able to continue with the removal anyway for _, m := range mnts { // unlink first to avoid back-propagation _ = syscall.Mount("", m.MountPoint, "", syscall.MS_PRIVATE|syscall.MS_REC, "") // simple unmount, it may fail if the target is busy (eg. overlapping children) if e := syscall.Unmount(m.MountPoint, 0); e != nil { // if busy, just detach here and let the kernel clean it once free _ = syscall.Unmount(m.MountPoint, syscall.MNT_DETACH) } } return nil }
go
func cleanupStage1(appName *types.ACName, enterCmd []string) error { // TODO(lucab): re-evaluate once/if we support systemd as non-pid1 (eg. host pid-ns inheriting) mnts, err := mountinfo.ParseMounts(1) if err != nil { return err } appRootFs := filepath.Join("/opt/stage2", appName.String(), "rootfs") mnts = mnts.Filter(mountinfo.HasPrefix(appRootFs)) // soft-errors here, stage0 may still be able to continue with the removal anyway for _, m := range mnts { // unlink first to avoid back-propagation _ = syscall.Mount("", m.MountPoint, "", syscall.MS_PRIVATE|syscall.MS_REC, "") // simple unmount, it may fail if the target is busy (eg. overlapping children) if e := syscall.Unmount(m.MountPoint, 0); e != nil { // if busy, just detach here and let the kernel clean it once free _ = syscall.Unmount(m.MountPoint, syscall.MNT_DETACH) } } return nil }
[ "func", "cleanupStage1", "(", "appName", "*", "types", ".", "ACName", ",", "enterCmd", "[", "]", "string", ")", "error", "{", "mnts", ",", "err", ":=", "mountinfo", ".", "ParseMounts", "(", "1", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "appRootFs", ":=", "filepath", ".", "Join", "(", "\"/opt/stage2\"", ",", "appName", ".", "String", "(", ")", ",", "\"rootfs\"", ")", "\n", "mnts", "=", "mnts", ".", "Filter", "(", "mountinfo", ".", "HasPrefix", "(", "appRootFs", ")", ")", "\n", "for", "_", ",", "m", ":=", "range", "mnts", "{", "_", "=", "syscall", ".", "Mount", "(", "\"\"", ",", "m", ".", "MountPoint", ",", "\"\"", ",", "syscall", ".", "MS_PRIVATE", "|", "syscall", ".", "MS_REC", ",", "\"\"", ")", "\n", "if", "e", ":=", "syscall", ".", "Unmount", "(", "m", ".", "MountPoint", ",", "0", ")", ";", "e", "!=", "nil", "{", "_", "=", "syscall", ".", "Unmount", "(", "m", ".", "MountPoint", ",", "syscall", ".", "MNT_DETACH", ")", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// cleanupStage1 is meant to be executed in stage1 context. It inspects pod systemd-pid1 mountinfo to // find all remaining mountpoints for appName and proceed to clean them up.
[ "cleanupStage1", "is", "meant", "to", "be", "executed", "in", "stage1", "context", ".", "It", "inspects", "pod", "systemd", "-", "pid1", "mountinfo", "to", "find", "all", "remaining", "mountpoints", "for", "appName", "and", "proceed", "to", "clean", "them", "up", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage1/app_rm/app_rm.go#L155-L176
train
rkt/rkt
rkt/gc.go
renameExited
func renameExited() error { if err := pkgPod.WalkPods(getDataDir(), pkgPod.IncludeRunDir, func(p *pkgPod.Pod) { if p.State() == pkgPod.Exited { stderr.Printf("moving pod %q to garbage", p.UUID) if err := p.ToExitedGarbage(); err != nil && err != os.ErrNotExist { stderr.PrintE("rename error", err) } } }); err != nil { return err } return nil }
go
func renameExited() error { if err := pkgPod.WalkPods(getDataDir(), pkgPod.IncludeRunDir, func(p *pkgPod.Pod) { if p.State() == pkgPod.Exited { stderr.Printf("moving pod %q to garbage", p.UUID) if err := p.ToExitedGarbage(); err != nil && err != os.ErrNotExist { stderr.PrintE("rename error", err) } } }); err != nil { return err } return nil }
[ "func", "renameExited", "(", ")", "error", "{", "if", "err", ":=", "pkgPod", ".", "WalkPods", "(", "getDataDir", "(", ")", ",", "pkgPod", ".", "IncludeRunDir", ",", "func", "(", "p", "*", "pkgPod", ".", "Pod", ")", "{", "if", "p", ".", "State", "(", ")", "==", "pkgPod", ".", "Exited", "{", "stderr", ".", "Printf", "(", "\"moving pod %q to garbage\"", ",", "p", ".", "UUID", ")", "\n", "if", "err", ":=", "p", ".", "ToExitedGarbage", "(", ")", ";", "err", "!=", "nil", "&&", "err", "!=", "os", ".", "ErrNotExist", "{", "stderr", ".", "PrintE", "(", "\"rename error\"", ",", "err", ")", "\n", "}", "\n", "}", "\n", "}", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// renameExited renames exited pods to the exitedGarbage directory
[ "renameExited", "renames", "exited", "pods", "to", "the", "exitedGarbage", "directory" ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/gc.go#L102-L115
train
rkt/rkt
rkt/gc.go
renameAborted
func renameAborted() error { if err := pkgPod.WalkPods(getDataDir(), pkgPod.IncludePrepareDir, func(p *pkgPod.Pod) { if p.State() == pkgPod.AbortedPrepare { stderr.Printf("moving failed prepare %q to garbage", p.UUID) if err := p.ToGarbage(); err != nil && err != os.ErrNotExist { stderr.PrintE("rename error", err) } } }); err != nil { return err } return nil }
go
func renameAborted() error { if err := pkgPod.WalkPods(getDataDir(), pkgPod.IncludePrepareDir, func(p *pkgPod.Pod) { if p.State() == pkgPod.AbortedPrepare { stderr.Printf("moving failed prepare %q to garbage", p.UUID) if err := p.ToGarbage(); err != nil && err != os.ErrNotExist { stderr.PrintE("rename error", err) } } }); err != nil { return err } return nil }
[ "func", "renameAborted", "(", ")", "error", "{", "if", "err", ":=", "pkgPod", ".", "WalkPods", "(", "getDataDir", "(", ")", ",", "pkgPod", ".", "IncludePrepareDir", ",", "func", "(", "p", "*", "pkgPod", ".", "Pod", ")", "{", "if", "p", ".", "State", "(", ")", "==", "pkgPod", ".", "AbortedPrepare", "{", "stderr", ".", "Printf", "(", "\"moving failed prepare %q to garbage\"", ",", "p", ".", "UUID", ")", "\n", "if", "err", ":=", "p", ".", "ToGarbage", "(", ")", ";", "err", "!=", "nil", "&&", "err", "!=", "os", ".", "ErrNotExist", "{", "stderr", ".", "PrintE", "(", "\"rename error\"", ",", "err", ")", "\n", "}", "\n", "}", "\n", "}", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// renameAborted renames failed prepares to the garbage directory
[ "renameAborted", "renames", "failed", "prepares", "to", "the", "garbage", "directory" ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/gc.go#L147-L159
train
rkt/rkt
rkt/gc.go
renameExpired
func renameExpired(preparedExpiration time.Duration) error { if err := pkgPod.WalkPods(getDataDir(), pkgPod.IncludePreparedDir, func(p *pkgPod.Pod) { st := &syscall.Stat_t{} pp := p.Path() if err := syscall.Lstat(pp, st); err != nil { if err != syscall.ENOENT { stderr.PrintE(fmt.Sprintf("unable to stat %q, ignoring", pp), err) } return } if expiration := time.Unix(st.Ctim.Unix()).Add(preparedExpiration); time.Now().After(expiration) { stderr.Printf("moving expired prepared pod %q to garbage", p.UUID) if err := p.ToGarbage(); err != nil && err != os.ErrNotExist { stderr.PrintE("rename error", err) } } }); err != nil { return err } return nil }
go
func renameExpired(preparedExpiration time.Duration) error { if err := pkgPod.WalkPods(getDataDir(), pkgPod.IncludePreparedDir, func(p *pkgPod.Pod) { st := &syscall.Stat_t{} pp := p.Path() if err := syscall.Lstat(pp, st); err != nil { if err != syscall.ENOENT { stderr.PrintE(fmt.Sprintf("unable to stat %q, ignoring", pp), err) } return } if expiration := time.Unix(st.Ctim.Unix()).Add(preparedExpiration); time.Now().After(expiration) { stderr.Printf("moving expired prepared pod %q to garbage", p.UUID) if err := p.ToGarbage(); err != nil && err != os.ErrNotExist { stderr.PrintE("rename error", err) } } }); err != nil { return err } return nil }
[ "func", "renameExpired", "(", "preparedExpiration", "time", ".", "Duration", ")", "error", "{", "if", "err", ":=", "pkgPod", ".", "WalkPods", "(", "getDataDir", "(", ")", ",", "pkgPod", ".", "IncludePreparedDir", ",", "func", "(", "p", "*", "pkgPod", ".", "Pod", ")", "{", "st", ":=", "&", "syscall", ".", "Stat_t", "{", "}", "\n", "pp", ":=", "p", ".", "Path", "(", ")", "\n", "if", "err", ":=", "syscall", ".", "Lstat", "(", "pp", ",", "st", ")", ";", "err", "!=", "nil", "{", "if", "err", "!=", "syscall", ".", "ENOENT", "{", "stderr", ".", "PrintE", "(", "fmt", ".", "Sprintf", "(", "\"unable to stat %q, ignoring\"", ",", "pp", ")", ",", "err", ")", "\n", "}", "\n", "return", "\n", "}", "\n", "if", "expiration", ":=", "time", ".", "Unix", "(", "st", ".", "Ctim", ".", "Unix", "(", ")", ")", ".", "Add", "(", "preparedExpiration", ")", ";", "time", ".", "Now", "(", ")", ".", "After", "(", "expiration", ")", "{", "stderr", ".", "Printf", "(", "\"moving expired prepared pod %q to garbage\"", ",", "p", ".", "UUID", ")", "\n", "if", "err", ":=", "p", ".", "ToGarbage", "(", ")", ";", "err", "!=", "nil", "&&", "err", "!=", "os", ".", "ErrNotExist", "{", "stderr", ".", "PrintE", "(", "\"rename error\"", ",", "err", ")", "\n", "}", "\n", "}", "\n", "}", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// renameExpired renames expired prepared pods to the garbage directory
[ "renameExpired", "renames", "expired", "prepared", "pods", "to", "the", "garbage", "directory" ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/gc.go#L162-L183
train
rkt/rkt
rkt/gc.go
deletePod
func deletePod(p *pkgPod.Pod) bool { podState := p.State() if podState != pkgPod.ExitedGarbage && podState != pkgPod.Garbage && podState != pkgPod.ExitedDeleting { stderr.Errorf("non-garbage pod %q (status %q), skipped", p.UUID, p.State()) return false } if podState == pkgPod.ExitedGarbage { s, err := imagestore.NewStore(storeDir()) if err != nil { stderr.PrintE("cannot open store", err) return false } defer s.Close() ts, err := treestore.NewStore(treeStoreDir(), s) if err != nil { stderr.PrintE("cannot open store", err) return false } if globalFlags.Debug { stage0.InitDebug() } if newMount, err := mountPodStage1(ts, p); err == nil { if err = stage0.GC(p.Path(), p.UUID, globalFlags.LocalConfigDir); err != nil { stderr.PrintE(fmt.Sprintf("problem performing stage1 GC on %q", p.UUID), err) } // Linux <4.13 allows an overlay fs to be mounted over itself, so let's // unmount it here to avoid problems when running stage0.MountGC if p.UsesOverlay() && newMount { stage1Mnt := common.Stage1RootfsPath(p.Path()) if err := syscall.Unmount(stage1Mnt, 0); err != nil && err != syscall.EBUSY { stderr.PrintE("error unmounting stage1", err) } } } else { stderr.PrintE("skipping stage1 GC", err) } // unmount all leftover mounts if err := stage0.MountGC(p.Path(), p.UUID.String()); err != nil { stderr.PrintE(fmt.Sprintf("GC of leftover mounts for pod %q failed", p.UUID), err) return false } } // remove the rootfs first; if this fails (eg. due to busy mountpoints), pod manifest // is left in place and clean-up can be re-tried later. rootfsPath, err := p.Stage1RootfsPath() if err == nil { if e := os.RemoveAll(rootfsPath); e != nil { stderr.PrintE(fmt.Sprintf("unable to remove pod rootfs %q", p.UUID), e) return false } } // finally remove all remaining pieces if err := os.RemoveAll(p.Path()); err != nil { stderr.PrintE(fmt.Sprintf("unable to remove pod %q", p.UUID), err) return false } return true }
go
func deletePod(p *pkgPod.Pod) bool { podState := p.State() if podState != pkgPod.ExitedGarbage && podState != pkgPod.Garbage && podState != pkgPod.ExitedDeleting { stderr.Errorf("non-garbage pod %q (status %q), skipped", p.UUID, p.State()) return false } if podState == pkgPod.ExitedGarbage { s, err := imagestore.NewStore(storeDir()) if err != nil { stderr.PrintE("cannot open store", err) return false } defer s.Close() ts, err := treestore.NewStore(treeStoreDir(), s) if err != nil { stderr.PrintE("cannot open store", err) return false } if globalFlags.Debug { stage0.InitDebug() } if newMount, err := mountPodStage1(ts, p); err == nil { if err = stage0.GC(p.Path(), p.UUID, globalFlags.LocalConfigDir); err != nil { stderr.PrintE(fmt.Sprintf("problem performing stage1 GC on %q", p.UUID), err) } // Linux <4.13 allows an overlay fs to be mounted over itself, so let's // unmount it here to avoid problems when running stage0.MountGC if p.UsesOverlay() && newMount { stage1Mnt := common.Stage1RootfsPath(p.Path()) if err := syscall.Unmount(stage1Mnt, 0); err != nil && err != syscall.EBUSY { stderr.PrintE("error unmounting stage1", err) } } } else { stderr.PrintE("skipping stage1 GC", err) } // unmount all leftover mounts if err := stage0.MountGC(p.Path(), p.UUID.String()); err != nil { stderr.PrintE(fmt.Sprintf("GC of leftover mounts for pod %q failed", p.UUID), err) return false } } // remove the rootfs first; if this fails (eg. due to busy mountpoints), pod manifest // is left in place and clean-up can be re-tried later. rootfsPath, err := p.Stage1RootfsPath() if err == nil { if e := os.RemoveAll(rootfsPath); e != nil { stderr.PrintE(fmt.Sprintf("unable to remove pod rootfs %q", p.UUID), e) return false } } // finally remove all remaining pieces if err := os.RemoveAll(p.Path()); err != nil { stderr.PrintE(fmt.Sprintf("unable to remove pod %q", p.UUID), err) return false } return true }
[ "func", "deletePod", "(", "p", "*", "pkgPod", ".", "Pod", ")", "bool", "{", "podState", ":=", "p", ".", "State", "(", ")", "\n", "if", "podState", "!=", "pkgPod", ".", "ExitedGarbage", "&&", "podState", "!=", "pkgPod", ".", "Garbage", "&&", "podState", "!=", "pkgPod", ".", "ExitedDeleting", "{", "stderr", ".", "Errorf", "(", "\"non-garbage pod %q (status %q), skipped\"", ",", "p", ".", "UUID", ",", "p", ".", "State", "(", ")", ")", "\n", "return", "false", "\n", "}", "\n", "if", "podState", "==", "pkgPod", ".", "ExitedGarbage", "{", "s", ",", "err", ":=", "imagestore", ".", "NewStore", "(", "storeDir", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "stderr", ".", "PrintE", "(", "\"cannot open store\"", ",", "err", ")", "\n", "return", "false", "\n", "}", "\n", "defer", "s", ".", "Close", "(", ")", "\n", "ts", ",", "err", ":=", "treestore", ".", "NewStore", "(", "treeStoreDir", "(", ")", ",", "s", ")", "\n", "if", "err", "!=", "nil", "{", "stderr", ".", "PrintE", "(", "\"cannot open store\"", ",", "err", ")", "\n", "return", "false", "\n", "}", "\n", "if", "globalFlags", ".", "Debug", "{", "stage0", ".", "InitDebug", "(", ")", "\n", "}", "\n", "if", "newMount", ",", "err", ":=", "mountPodStage1", "(", "ts", ",", "p", ")", ";", "err", "==", "nil", "{", "if", "err", "=", "stage0", ".", "GC", "(", "p", ".", "Path", "(", ")", ",", "p", ".", "UUID", ",", "globalFlags", ".", "LocalConfigDir", ")", ";", "err", "!=", "nil", "{", "stderr", ".", "PrintE", "(", "fmt", ".", "Sprintf", "(", "\"problem performing stage1 GC on %q\"", ",", "p", ".", "UUID", ")", ",", "err", ")", "\n", "}", "\n", "if", "p", ".", "UsesOverlay", "(", ")", "&&", "newMount", "{", "stage1Mnt", ":=", "common", ".", "Stage1RootfsPath", "(", "p", ".", "Path", "(", ")", ")", "\n", "if", "err", ":=", "syscall", ".", "Unmount", "(", "stage1Mnt", ",", "0", ")", ";", "err", "!=", "nil", "&&", "err", "!=", "syscall", ".", "EBUSY", "{", "stderr", ".", "PrintE", "(", "\"error unmounting stage1\"", ",", "err", ")", "\n", "}", "\n", "}", "\n", "}", "else", "{", "stderr", ".", "PrintE", "(", "\"skipping stage1 GC\"", ",", "err", ")", "\n", "}", "\n", "if", "err", ":=", "stage0", ".", "MountGC", "(", "p", ".", "Path", "(", ")", ",", "p", ".", "UUID", ".", "String", "(", ")", ")", ";", "err", "!=", "nil", "{", "stderr", ".", "PrintE", "(", "fmt", ".", "Sprintf", "(", "\"GC of leftover mounts for pod %q failed\"", ",", "p", ".", "UUID", ")", ",", "err", ")", "\n", "return", "false", "\n", "}", "\n", "}", "\n", "rootfsPath", ",", "err", ":=", "p", ".", "Stage1RootfsPath", "(", ")", "\n", "if", "err", "==", "nil", "{", "if", "e", ":=", "os", ".", "RemoveAll", "(", "rootfsPath", ")", ";", "e", "!=", "nil", "{", "stderr", ".", "PrintE", "(", "fmt", ".", "Sprintf", "(", "\"unable to remove pod rootfs %q\"", ",", "p", ".", "UUID", ")", ",", "e", ")", "\n", "return", "false", "\n", "}", "\n", "}", "\n", "if", "err", ":=", "os", ".", "RemoveAll", "(", "p", ".", "Path", "(", ")", ")", ";", "err", "!=", "nil", "{", "stderr", ".", "PrintE", "(", "fmt", ".", "Sprintf", "(", "\"unable to remove pod %q\"", ",", "p", ".", "UUID", ")", ",", "err", ")", "\n", "return", "false", "\n", "}", "\n", "return", "true", "\n", "}" ]
// deletePod cleans up files and resource associated with the pod // pod must be under exclusive lock and be in either ExitedGarbage // or Garbage state
[ "deletePod", "cleans", "up", "files", "and", "resource", "associated", "with", "the", "pod", "pod", "must", "be", "under", "exclusive", "lock", "and", "be", "in", "either", "ExitedGarbage", "or", "Garbage", "state" ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/gc.go#L251-L316
train
rkt/rkt
store/imagestore/store.go
backupDB
func (s *Store) backupDB() error { if os.Geteuid() != 0 { return ErrDBUpdateNeedsRoot } backupsDir := filepath.Join(s.dir, "db-backups") return backup.CreateBackup(s.dbDir(), backupsDir, backupsNumber) }
go
func (s *Store) backupDB() error { if os.Geteuid() != 0 { return ErrDBUpdateNeedsRoot } backupsDir := filepath.Join(s.dir, "db-backups") return backup.CreateBackup(s.dbDir(), backupsDir, backupsNumber) }
[ "func", "(", "s", "*", "Store", ")", "backupDB", "(", ")", "error", "{", "if", "os", ".", "Geteuid", "(", ")", "!=", "0", "{", "return", "ErrDBUpdateNeedsRoot", "\n", "}", "\n", "backupsDir", ":=", "filepath", ".", "Join", "(", "s", ".", "dir", ",", "\"db-backups\"", ")", "\n", "return", "backup", ".", "CreateBackup", "(", "s", ".", "dbDir", "(", ")", ",", "backupsDir", ",", "backupsNumber", ")", "\n", "}" ]
// backupDB backs up current database.
[ "backupDB", "backs", "up", "current", "database", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/store/imagestore/store.go#L283-L289
train
rkt/rkt
store/imagestore/store.go
ResolveName
func (s *Store) ResolveName(name string) ([]string, bool, error) { var ( aciInfos []*ACIInfo found bool ) err := s.db.Do(func(tx *sql.Tx) error { var err error aciInfos, found, err = GetACIInfosWithName(tx, name) return err }) if err != nil { return nil, found, errwrap.Wrap(errors.New("error retrieving ACI Infos"), err) } keys := make([]string, len(aciInfos)) for i, aciInfo := range aciInfos { keys[i] = aciInfo.BlobKey } return keys, found, nil }
go
func (s *Store) ResolveName(name string) ([]string, bool, error) { var ( aciInfos []*ACIInfo found bool ) err := s.db.Do(func(tx *sql.Tx) error { var err error aciInfos, found, err = GetACIInfosWithName(tx, name) return err }) if err != nil { return nil, found, errwrap.Wrap(errors.New("error retrieving ACI Infos"), err) } keys := make([]string, len(aciInfos)) for i, aciInfo := range aciInfos { keys[i] = aciInfo.BlobKey } return keys, found, nil }
[ "func", "(", "s", "*", "Store", ")", "ResolveName", "(", "name", "string", ")", "(", "[", "]", "string", ",", "bool", ",", "error", ")", "{", "var", "(", "aciInfos", "[", "]", "*", "ACIInfo", "\n", "found", "bool", "\n", ")", "\n", "err", ":=", "s", ".", "db", ".", "Do", "(", "func", "(", "tx", "*", "sql", ".", "Tx", ")", "error", "{", "var", "err", "error", "\n", "aciInfos", ",", "found", ",", "err", "=", "GetACIInfosWithName", "(", "tx", ",", "name", ")", "\n", "return", "err", "\n", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "found", ",", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"error retrieving ACI Infos\"", ")", ",", "err", ")", "\n", "}", "\n", "keys", ":=", "make", "(", "[", "]", "string", ",", "len", "(", "aciInfos", ")", ")", "\n", "for", "i", ",", "aciInfo", ":=", "range", "aciInfos", "{", "keys", "[", "i", "]", "=", "aciInfo", ".", "BlobKey", "\n", "}", "\n", "return", "keys", ",", "found", ",", "nil", "\n", "}" ]
// ResolveName resolves an image name to a list of full keys and using the // store for resolution.
[ "ResolveName", "resolves", "an", "image", "name", "to", "a", "list", "of", "full", "keys", "and", "using", "the", "store", "for", "resolution", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/store/imagestore/store.go#L374-L394
train
rkt/rkt
store/imagestore/store.go
RemoveACI
func (s *Store) RemoveACI(key string) error { imageKeyLock, err := lock.ExclusiveKeyLock(s.imageLockDir, key) if err != nil { return errwrap.Wrap(errors.New("error locking image"), err) } defer imageKeyLock.Close() // Firstly remove aciinfo and remote from the db in an unique transaction. // remote needs to be removed or a GetRemote will return a blobKey not // referenced by any ACIInfo. err = s.db.Do(func(tx *sql.Tx) error { if _, found, err := GetACIInfoWithBlobKey(tx, key); err != nil { return errwrap.Wrap(errors.New("error getting aciinfo"), err) } else if !found { return fmt.Errorf("cannot find image with key: %s", key) } if err := RemoveACIInfo(tx, key); err != nil { return err } if err := RemoveRemote(tx, key); err != nil { return err } return nil }) if err != nil { return errwrap.Wrap(fmt.Errorf("cannot remove image with ID: %s from db", key), err) } // Then remove non transactional entries from the blob, imageManifest // and tree store. // TODO(sgotti). Now that the ACIInfo is removed the image doesn't // exists anymore, but errors removing non transactional entries can // leave stale data that will require a cas GC to be implemented. var storeErrors []error for _, ds := range s.stores { if err := ds.Erase(key); err != nil { // If there's an error save it and continue with the other stores storeErrors = append(storeErrors, err) } } if len(storeErrors) > 0 { return &StoreRemovalError{errors: storeErrors} } return nil }
go
func (s *Store) RemoveACI(key string) error { imageKeyLock, err := lock.ExclusiveKeyLock(s.imageLockDir, key) if err != nil { return errwrap.Wrap(errors.New("error locking image"), err) } defer imageKeyLock.Close() // Firstly remove aciinfo and remote from the db in an unique transaction. // remote needs to be removed or a GetRemote will return a blobKey not // referenced by any ACIInfo. err = s.db.Do(func(tx *sql.Tx) error { if _, found, err := GetACIInfoWithBlobKey(tx, key); err != nil { return errwrap.Wrap(errors.New("error getting aciinfo"), err) } else if !found { return fmt.Errorf("cannot find image with key: %s", key) } if err := RemoveACIInfo(tx, key); err != nil { return err } if err := RemoveRemote(tx, key); err != nil { return err } return nil }) if err != nil { return errwrap.Wrap(fmt.Errorf("cannot remove image with ID: %s from db", key), err) } // Then remove non transactional entries from the blob, imageManifest // and tree store. // TODO(sgotti). Now that the ACIInfo is removed the image doesn't // exists anymore, but errors removing non transactional entries can // leave stale data that will require a cas GC to be implemented. var storeErrors []error for _, ds := range s.stores { if err := ds.Erase(key); err != nil { // If there's an error save it and continue with the other stores storeErrors = append(storeErrors, err) } } if len(storeErrors) > 0 { return &StoreRemovalError{errors: storeErrors} } return nil }
[ "func", "(", "s", "*", "Store", ")", "RemoveACI", "(", "key", "string", ")", "error", "{", "imageKeyLock", ",", "err", ":=", "lock", ".", "ExclusiveKeyLock", "(", "s", ".", "imageLockDir", ",", "key", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"error locking image\"", ")", ",", "err", ")", "\n", "}", "\n", "defer", "imageKeyLock", ".", "Close", "(", ")", "\n", "err", "=", "s", ".", "db", ".", "Do", "(", "func", "(", "tx", "*", "sql", ".", "Tx", ")", "error", "{", "if", "_", ",", "found", ",", "err", ":=", "GetACIInfoWithBlobKey", "(", "tx", ",", "key", ")", ";", "err", "!=", "nil", "{", "return", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"error getting aciinfo\"", ")", ",", "err", ")", "\n", "}", "else", "if", "!", "found", "{", "return", "fmt", ".", "Errorf", "(", "\"cannot find image with key: %s\"", ",", "key", ")", "\n", "}", "\n", "if", "err", ":=", "RemoveACIInfo", "(", "tx", ",", "key", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "RemoveRemote", "(", "tx", ",", "key", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errwrap", ".", "Wrap", "(", "fmt", ".", "Errorf", "(", "\"cannot remove image with ID: %s from db\"", ",", "key", ")", ",", "err", ")", "\n", "}", "\n", "var", "storeErrors", "[", "]", "error", "\n", "for", "_", ",", "ds", ":=", "range", "s", ".", "stores", "{", "if", "err", ":=", "ds", ".", "Erase", "(", "key", ")", ";", "err", "!=", "nil", "{", "storeErrors", "=", "append", "(", "storeErrors", ",", "err", ")", "\n", "}", "\n", "}", "\n", "if", "len", "(", "storeErrors", ")", ">", "0", "{", "return", "&", "StoreRemovalError", "{", "errors", ":", "storeErrors", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// RemoveACI removes the ACI with the given key. It firstly removes the aci // infos inside the db, then it tries to remove the non transactional data. // If some error occurs removing some non transactional data a // StoreRemovalError is returned.
[ "RemoveACI", "removes", "the", "ACI", "with", "the", "given", "key", ".", "It", "firstly", "removes", "the", "aci", "infos", "inside", "the", "db", "then", "it", "tries", "to", "remove", "the", "non", "transactional", "data", ".", "If", "some", "error", "occurs", "removing", "some", "non", "transactional", "data", "a", "StoreRemovalError", "is", "returned", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/store/imagestore/store.go#L506-L551
train
rkt/rkt
store/imagestore/store.go
GetRemote
func (s *Store) GetRemote(aciURL string) (*Remote, error) { var remote *Remote err := s.db.Do(func(tx *sql.Tx) error { var err error remote, err = GetRemote(tx, aciURL) return err }) if err != nil { return nil, err } return remote, nil }
go
func (s *Store) GetRemote(aciURL string) (*Remote, error) { var remote *Remote err := s.db.Do(func(tx *sql.Tx) error { var err error remote, err = GetRemote(tx, aciURL) return err }) if err != nil { return nil, err } return remote, nil }
[ "func", "(", "s", "*", "Store", ")", "GetRemote", "(", "aciURL", "string", ")", "(", "*", "Remote", ",", "error", ")", "{", "var", "remote", "*", "Remote", "\n", "err", ":=", "s", ".", "db", ".", "Do", "(", "func", "(", "tx", "*", "sql", ".", "Tx", ")", "error", "{", "var", "err", "error", "\n", "remote", ",", "err", "=", "GetRemote", "(", "tx", ",", "aciURL", ")", "\n", "return", "err", "\n", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "remote", ",", "nil", "\n", "}" ]
// GetRemote tries to retrieve a remote with the given ACIURL. // If remote doesn't exist, it returns ErrRemoteNotFound error.
[ "GetRemote", "tries", "to", "retrieve", "a", "remote", "with", "the", "given", "ACIURL", ".", "If", "remote", "doesn", "t", "exist", "it", "returns", "ErrRemoteNotFound", "error", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/store/imagestore/store.go#L555-L570
train
rkt/rkt
store/imagestore/store.go
GetImageManifestJSON
func (s *Store) GetImageManifestJSON(key string) ([]byte, error) { key, err := s.ResolveKey(key) if err != nil { return nil, errwrap.Wrap(errors.New("error resolving image ID"), err) } keyLock, err := lock.SharedKeyLock(s.imageLockDir, key) if err != nil { return nil, errwrap.Wrap(errors.New("error locking image"), err) } defer keyLock.Close() imj, err := s.stores[imageManifestType].Read(key) if err != nil { return nil, errwrap.Wrap(errors.New("error retrieving image manifest"), err) } return imj, nil }
go
func (s *Store) GetImageManifestJSON(key string) ([]byte, error) { key, err := s.ResolveKey(key) if err != nil { return nil, errwrap.Wrap(errors.New("error resolving image ID"), err) } keyLock, err := lock.SharedKeyLock(s.imageLockDir, key) if err != nil { return nil, errwrap.Wrap(errors.New("error locking image"), err) } defer keyLock.Close() imj, err := s.stores[imageManifestType].Read(key) if err != nil { return nil, errwrap.Wrap(errors.New("error retrieving image manifest"), err) } return imj, nil }
[ "func", "(", "s", "*", "Store", ")", "GetImageManifestJSON", "(", "key", "string", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "key", ",", "err", ":=", "s", ".", "ResolveKey", "(", "key", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"error resolving image ID\"", ")", ",", "err", ")", "\n", "}", "\n", "keyLock", ",", "err", ":=", "lock", ".", "SharedKeyLock", "(", "s", ".", "imageLockDir", ",", "key", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"error locking image\"", ")", ",", "err", ")", "\n", "}", "\n", "defer", "keyLock", ".", "Close", "(", ")", "\n", "imj", ",", "err", ":=", "s", ".", "stores", "[", "imageManifestType", "]", ".", "Read", "(", "key", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"error retrieving image manifest\"", ")", ",", "err", ")", "\n", "}", "\n", "return", "imj", ",", "nil", "\n", "}" ]
// GetImageManifestJSON gets the ImageManifest JSON bytes with the // specified key.
[ "GetImageManifestJSON", "gets", "the", "ImageManifest", "JSON", "bytes", "with", "the", "specified", "key", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/store/imagestore/store.go#L582-L598
train
rkt/rkt
store/imagestore/store.go
GetImageManifest
func (s *Store) GetImageManifest(key string) (*schema.ImageManifest, error) { imj, err := s.GetImageManifestJSON(key) if err != nil { return nil, err } var im *schema.ImageManifest if err = json.Unmarshal(imj, &im); err != nil { return nil, errwrap.Wrap(errors.New("error unmarshalling image manifest"), err) } return im, nil }
go
func (s *Store) GetImageManifest(key string) (*schema.ImageManifest, error) { imj, err := s.GetImageManifestJSON(key) if err != nil { return nil, err } var im *schema.ImageManifest if err = json.Unmarshal(imj, &im); err != nil { return nil, errwrap.Wrap(errors.New("error unmarshalling image manifest"), err) } return im, nil }
[ "func", "(", "s", "*", "Store", ")", "GetImageManifest", "(", "key", "string", ")", "(", "*", "schema", ".", "ImageManifest", ",", "error", ")", "{", "imj", ",", "err", ":=", "s", ".", "GetImageManifestJSON", "(", "key", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "var", "im", "*", "schema", ".", "ImageManifest", "\n", "if", "err", "=", "json", ".", "Unmarshal", "(", "imj", ",", "&", "im", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"error unmarshalling image manifest\"", ")", ",", "err", ")", "\n", "}", "\n", "return", "im", ",", "nil", "\n", "}" ]
// GetImageManifest gets the ImageManifest with the specified key.
[ "GetImageManifest", "gets", "the", "ImageManifest", "with", "the", "specified", "key", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/store/imagestore/store.go#L601-L611
train
rkt/rkt
store/imagestore/store.go
HasFullKey
func (s *Store) HasFullKey(key string) bool { return s.stores[imageManifestType].Has(key) }
go
func (s *Store) HasFullKey(key string) bool { return s.stores[imageManifestType].Has(key) }
[ "func", "(", "s", "*", "Store", ")", "HasFullKey", "(", "key", "string", ")", "bool", "{", "return", "s", ".", "stores", "[", "imageManifestType", "]", ".", "Has", "(", "key", ")", "\n", "}" ]
// HasFullKey returns whether the image with the given key exists on the disk by // checking if the image manifest kv store contains the key.
[ "HasFullKey", "returns", "whether", "the", "image", "with", "the", "given", "key", "exists", "on", "the", "disk", "by", "checking", "if", "the", "image", "manifest", "kv", "store", "contains", "the", "key", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/store/imagestore/store.go#L756-L758
train
rkt/rkt
store/imagestore/store.go
keyToString
func keyToString(k []byte) string { if len(k) != lenHash { panic(fmt.Sprintf("bad hash passed to hashToKey: %x", k)) } return fmt.Sprintf("%s%x", hashPrefix, k)[0:lenKey] }
go
func keyToString(k []byte) string { if len(k) != lenHash { panic(fmt.Sprintf("bad hash passed to hashToKey: %x", k)) } return fmt.Sprintf("%s%x", hashPrefix, k)[0:lenKey] }
[ "func", "keyToString", "(", "k", "[", "]", "byte", ")", "string", "{", "if", "len", "(", "k", ")", "!=", "lenHash", "{", "panic", "(", "fmt", ".", "Sprintf", "(", "\"bad hash passed to hashToKey: %x\"", ",", "k", ")", ")", "\n", "}", "\n", "return", "fmt", ".", "Sprintf", "(", "\"%s%x\"", ",", "hashPrefix", ",", "k", ")", "[", "0", ":", "lenKey", "]", "\n", "}" ]
// keyToString takes a key and returns a shortened and prefixed hexadecimal string version
[ "keyToString", "takes", "a", "key", "and", "returns", "a", "shortened", "and", "prefixed", "hexadecimal", "string", "version" ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/store/imagestore/store.go#L766-L771
train
rkt/rkt
rkt/image/downloader.go
Download
func (d *downloader) Download(u *url.URL, out writeSyncer) error { client, err := d.Session.Client() if err != nil { return err } req, err := d.Session.Request(u) if err != nil { return err } res, err := client.Do(req) if err != nil { return err } defer res.Body.Close() if stopNow, err := d.Session.HandleStatus(res); stopNow || err != nil { return err } reader, err := d.Session.BodyReader(res) if err != nil { return err } if _, err := io.Copy(out, reader); err != nil { return errwrap.Wrap(fmt.Errorf("failed to download %q", u.String()), err) } if err := out.Sync(); err != nil { return errwrap.Wrap(fmt.Errorf("failed to sync data from %q to disk", u.String()), err) } return nil }
go
func (d *downloader) Download(u *url.URL, out writeSyncer) error { client, err := d.Session.Client() if err != nil { return err } req, err := d.Session.Request(u) if err != nil { return err } res, err := client.Do(req) if err != nil { return err } defer res.Body.Close() if stopNow, err := d.Session.HandleStatus(res); stopNow || err != nil { return err } reader, err := d.Session.BodyReader(res) if err != nil { return err } if _, err := io.Copy(out, reader); err != nil { return errwrap.Wrap(fmt.Errorf("failed to download %q", u.String()), err) } if err := out.Sync(); err != nil { return errwrap.Wrap(fmt.Errorf("failed to sync data from %q to disk", u.String()), err) } return nil }
[ "func", "(", "d", "*", "downloader", ")", "Download", "(", "u", "*", "url", ".", "URL", ",", "out", "writeSyncer", ")", "error", "{", "client", ",", "err", ":=", "d", ".", "Session", ".", "Client", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "req", ",", "err", ":=", "d", ".", "Session", ".", "Request", "(", "u", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "res", ",", "err", ":=", "client", ".", "Do", "(", "req", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "res", ".", "Body", ".", "Close", "(", ")", "\n", "if", "stopNow", ",", "err", ":=", "d", ".", "Session", ".", "HandleStatus", "(", "res", ")", ";", "stopNow", "||", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "reader", ",", "err", ":=", "d", ".", "Session", ".", "BodyReader", "(", "res", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "_", ",", "err", ":=", "io", ".", "Copy", "(", "out", ",", "reader", ")", ";", "err", "!=", "nil", "{", "return", "errwrap", ".", "Wrap", "(", "fmt", ".", "Errorf", "(", "\"failed to download %q\"", ",", "u", ".", "String", "(", ")", ")", ",", "err", ")", "\n", "}", "\n", "if", "err", ":=", "out", ".", "Sync", "(", ")", ";", "err", "!=", "nil", "{", "return", "errwrap", ".", "Wrap", "(", "fmt", ".", "Errorf", "(", "\"failed to sync data from %q to disk\"", ",", "u", ".", "String", "(", ")", ")", ",", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Download tries to fetch the passed URL and write the contents into // a given writeSyncer instance.
[ "Download", "tries", "to", "fetch", "the", "passed", "URL", "and", "write", "the", "contents", "into", "a", "given", "writeSyncer", "instance", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/image/downloader.go#L54-L86
train
rkt/rkt
rkt/enter.go
getAppName
func getAppName(p *pkgPod.Pod) (*types.ACName, error) { if flagAppName != "" { return types.NewACName(flagAppName) } // figure out the app name, or show a list if multiple are present _, m, err := p.PodManifest() if err != nil { return nil, errwrap.Wrap(errors.New("error reading pod manifest"), err) } switch len(m.Apps) { case 0: return nil, fmt.Errorf("pod contains zero apps") case 1: return &m.Apps[0].Name, nil default: } stderr.Print("pod contains multiple apps:") for _, ra := range m.Apps { stderr.Printf("\t%v", ra.Name) } return nil, fmt.Errorf("specify app using \"rkt enter --app= ...\"") }
go
func getAppName(p *pkgPod.Pod) (*types.ACName, error) { if flagAppName != "" { return types.NewACName(flagAppName) } // figure out the app name, or show a list if multiple are present _, m, err := p.PodManifest() if err != nil { return nil, errwrap.Wrap(errors.New("error reading pod manifest"), err) } switch len(m.Apps) { case 0: return nil, fmt.Errorf("pod contains zero apps") case 1: return &m.Apps[0].Name, nil default: } stderr.Print("pod contains multiple apps:") for _, ra := range m.Apps { stderr.Printf("\t%v", ra.Name) } return nil, fmt.Errorf("specify app using \"rkt enter --app= ...\"") }
[ "func", "getAppName", "(", "p", "*", "pkgPod", ".", "Pod", ")", "(", "*", "types", ".", "ACName", ",", "error", ")", "{", "if", "flagAppName", "!=", "\"\"", "{", "return", "types", ".", "NewACName", "(", "flagAppName", ")", "\n", "}", "\n", "_", ",", "m", ",", "err", ":=", "p", ".", "PodManifest", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"error reading pod manifest\"", ")", ",", "err", ")", "\n", "}", "\n", "switch", "len", "(", "m", ".", "Apps", ")", "{", "case", "0", ":", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"pod contains zero apps\"", ")", "\n", "case", "1", ":", "return", "&", "m", ".", "Apps", "[", "0", "]", ".", "Name", ",", "nil", "\n", "default", ":", "}", "\n", "stderr", ".", "Print", "(", "\"pod contains multiple apps:\"", ")", "\n", "for", "_", ",", "ra", ":=", "range", "m", ".", "Apps", "{", "stderr", ".", "Printf", "(", "\"\\t%v\"", ",", "\\t", ")", "\n", "}", "\n", "ra", ".", "Name", "\n", "}" ]
// getAppName returns the app name to enter // If one was supplied in the flags then it's simply returned // If the PM contains a single app, that app's name is returned // If the PM has multiple apps, the names are printed and an error is returned
[ "getAppName", "returns", "the", "app", "name", "to", "enter", "If", "one", "was", "supplied", "in", "the", "flags", "then", "it", "s", "simply", "returned", "If", "the", "PM", "contains", "a", "single", "app", "that", "app", "s", "name", "is", "returned", "If", "the", "PM", "has", "multiple", "apps", "the", "names", "are", "printed", "and", "an", "error", "is", "returned" ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/enter.go#L128-L153
train
rkt/rkt
rkt/enter.go
getEnterArgv
func getEnterArgv(p *pkgPod.Pod, cmdArgs []string) ([]string, error) { var argv []string if len(cmdArgs) < 2 { stderr.Printf("no command specified, assuming %q", defaultCmd) argv = []string{defaultCmd} } else { argv = cmdArgs[1:] } return argv, nil }
go
func getEnterArgv(p *pkgPod.Pod, cmdArgs []string) ([]string, error) { var argv []string if len(cmdArgs) < 2 { stderr.Printf("no command specified, assuming %q", defaultCmd) argv = []string{defaultCmd} } else { argv = cmdArgs[1:] } return argv, nil }
[ "func", "getEnterArgv", "(", "p", "*", "pkgPod", ".", "Pod", ",", "cmdArgs", "[", "]", "string", ")", "(", "[", "]", "string", ",", "error", ")", "{", "var", "argv", "[", "]", "string", "\n", "if", "len", "(", "cmdArgs", ")", "<", "2", "{", "stderr", ".", "Printf", "(", "\"no command specified, assuming %q\"", ",", "defaultCmd", ")", "\n", "argv", "=", "[", "]", "string", "{", "defaultCmd", "}", "\n", "}", "else", "{", "argv", "=", "cmdArgs", "[", "1", ":", "]", "\n", "}", "\n", "return", "argv", ",", "nil", "\n", "}" ]
// getEnterArgv returns the argv to use for entering the pod
[ "getEnterArgv", "returns", "the", "argv", "to", "use", "for", "entering", "the", "pod" ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/enter.go#L156-L166
train
rkt/rkt
common/cgroup/v1/cgroup.go
mountFsRO
func mountFsRO(m fs.Mounter, mountPoint string, flags uintptr) error { flags = flags | syscall.MS_BIND | syscall.MS_REMOUNT | syscall.MS_RDONLY if err := m.Mount(mountPoint, mountPoint, "", flags, ""); err != nil { return errwrap.Wrap(fmt.Errorf("error remounting read-only %q", mountPoint), err) } return nil }
go
func mountFsRO(m fs.Mounter, mountPoint string, flags uintptr) error { flags = flags | syscall.MS_BIND | syscall.MS_REMOUNT | syscall.MS_RDONLY if err := m.Mount(mountPoint, mountPoint, "", flags, ""); err != nil { return errwrap.Wrap(fmt.Errorf("error remounting read-only %q", mountPoint), err) } return nil }
[ "func", "mountFsRO", "(", "m", "fs", ".", "Mounter", ",", "mountPoint", "string", ",", "flags", "uintptr", ")", "error", "{", "flags", "=", "flags", "|", "syscall", ".", "MS_BIND", "|", "syscall", ".", "MS_REMOUNT", "|", "syscall", ".", "MS_RDONLY", "\n", "if", "err", ":=", "m", ".", "Mount", "(", "mountPoint", ",", "mountPoint", ",", "\"\"", ",", "flags", ",", "\"\"", ")", ";", "err", "!=", "nil", "{", "return", "errwrap", ".", "Wrap", "(", "fmt", ".", "Errorf", "(", "\"error remounting read-only %q\"", ",", "mountPoint", ")", ",", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// mountFsRO remounts the given mountPoint using the given flags read-only.
[ "mountFsRO", "remounts", "the", "given", "mountPoint", "using", "the", "given", "flags", "read", "-", "only", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/common/cgroup/v1/cgroup.go#L36-L47
train
rkt/rkt
common/cgroup/v1/cgroup.go
GetEnabledCgroups
func GetEnabledCgroups() (map[int][]string, error) { cgroupsFile, err := os.Open("/proc/cgroups") if err != nil { return nil, err } defer cgroupsFile.Close() cgroups, err := parseCgroups(cgroupsFile) if err != nil { return nil, errwrap.Wrap(errors.New("error parsing /proc/cgroups"), err) } return cgroups, nil }
go
func GetEnabledCgroups() (map[int][]string, error) { cgroupsFile, err := os.Open("/proc/cgroups") if err != nil { return nil, err } defer cgroupsFile.Close() cgroups, err := parseCgroups(cgroupsFile) if err != nil { return nil, errwrap.Wrap(errors.New("error parsing /proc/cgroups"), err) } return cgroups, nil }
[ "func", "GetEnabledCgroups", "(", ")", "(", "map", "[", "int", "]", "[", "]", "string", ",", "error", ")", "{", "cgroupsFile", ",", "err", ":=", "os", ".", "Open", "(", "\"/proc/cgroups\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "defer", "cgroupsFile", ".", "Close", "(", ")", "\n", "cgroups", ",", "err", ":=", "parseCgroups", "(", "cgroupsFile", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"error parsing /proc/cgroups\"", ")", ",", "err", ")", "\n", "}", "\n", "return", "cgroups", ",", "nil", "\n", "}" ]
// GetEnabledCgroups returns a map with the enabled cgroup controllers grouped by // hierarchy
[ "GetEnabledCgroups", "returns", "a", "map", "with", "the", "enabled", "cgroup", "controllers", "grouped", "by", "hierarchy" ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/common/cgroup/v1/cgroup.go#L81-L94
train
rkt/rkt
common/cgroup/v1/cgroup.go
GetOwnCgroupPath
func GetOwnCgroupPath(controller string) (string, error) { parts, err := parseCgroupController("/proc/self/cgroup", controller) if err != nil { return "", err } return parts[2], nil }
go
func GetOwnCgroupPath(controller string) (string, error) { parts, err := parseCgroupController("/proc/self/cgroup", controller) if err != nil { return "", err } return parts[2], nil }
[ "func", "GetOwnCgroupPath", "(", "controller", "string", ")", "(", "string", ",", "error", ")", "{", "parts", ",", "err", ":=", "parseCgroupController", "(", "\"/proc/self/cgroup\"", ",", "controller", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"\"", ",", "err", "\n", "}", "\n", "return", "parts", "[", "2", "]", ",", "nil", "\n", "}" ]
// GetOwnCgroupPath returns the cgroup path of this process in controller // hierarchy
[ "GetOwnCgroupPath", "returns", "the", "cgroup", "path", "of", "this", "process", "in", "controller", "hierarchy" ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/common/cgroup/v1/cgroup.go#L149-L155
train
rkt/rkt
common/cgroup/v1/cgroup.go
GetCgroupPathByPid
func GetCgroupPathByPid(pid int, controller string) (string, error) { parts, err := parseCgroupController(fmt.Sprintf("/proc/%d/cgroup", pid), controller) if err != nil { return "", err } return parts[2], nil }
go
func GetCgroupPathByPid(pid int, controller string) (string, error) { parts, err := parseCgroupController(fmt.Sprintf("/proc/%d/cgroup", pid), controller) if err != nil { return "", err } return parts[2], nil }
[ "func", "GetCgroupPathByPid", "(", "pid", "int", ",", "controller", "string", ")", "(", "string", ",", "error", ")", "{", "parts", ",", "err", ":=", "parseCgroupController", "(", "fmt", ".", "Sprintf", "(", "\"/proc/%d/cgroup\"", ",", "pid", ")", ",", "controller", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"\"", ",", "err", "\n", "}", "\n", "return", "parts", "[", "2", "]", ",", "nil", "\n", "}" ]
// GetCgroupPathByPid returns the cgroup path of the process with the given pid // and given controller.
[ "GetCgroupPathByPid", "returns", "the", "cgroup", "path", "of", "the", "process", "with", "the", "given", "pid", "and", "given", "controller", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/common/cgroup/v1/cgroup.go#L159-L165
train
rkt/rkt
common/cgroup/v1/cgroup.go
JoinSubcgroup
func JoinSubcgroup(controller string, subcgroup string) error { subcgroupPath := filepath.Join("/sys/fs/cgroup", controller, subcgroup) if err := os.MkdirAll(subcgroupPath, 0600); err != nil { return errwrap.Wrap(fmt.Errorf("error creating %q subcgroup", subcgroup), err) } pidBytes := []byte(strconv.Itoa(os.Getpid())) if err := ioutil.WriteFile(filepath.Join(subcgroupPath, "cgroup.procs"), pidBytes, 0600); err != nil { return errwrap.Wrap(fmt.Errorf("error adding ourselves to the %q subcgroup", subcgroup), err) } return nil }
go
func JoinSubcgroup(controller string, subcgroup string) error { subcgroupPath := filepath.Join("/sys/fs/cgroup", controller, subcgroup) if err := os.MkdirAll(subcgroupPath, 0600); err != nil { return errwrap.Wrap(fmt.Errorf("error creating %q subcgroup", subcgroup), err) } pidBytes := []byte(strconv.Itoa(os.Getpid())) if err := ioutil.WriteFile(filepath.Join(subcgroupPath, "cgroup.procs"), pidBytes, 0600); err != nil { return errwrap.Wrap(fmt.Errorf("error adding ourselves to the %q subcgroup", subcgroup), err) } return nil }
[ "func", "JoinSubcgroup", "(", "controller", "string", ",", "subcgroup", "string", ")", "error", "{", "subcgroupPath", ":=", "filepath", ".", "Join", "(", "\"/sys/fs/cgroup\"", ",", "controller", ",", "subcgroup", ")", "\n", "if", "err", ":=", "os", ".", "MkdirAll", "(", "subcgroupPath", ",", "0600", ")", ";", "err", "!=", "nil", "{", "return", "errwrap", ".", "Wrap", "(", "fmt", ".", "Errorf", "(", "\"error creating %q subcgroup\"", ",", "subcgroup", ")", ",", "err", ")", "\n", "}", "\n", "pidBytes", ":=", "[", "]", "byte", "(", "strconv", ".", "Itoa", "(", "os", ".", "Getpid", "(", ")", ")", ")", "\n", "if", "err", ":=", "ioutil", ".", "WriteFile", "(", "filepath", ".", "Join", "(", "subcgroupPath", ",", "\"cgroup.procs\"", ")", ",", "pidBytes", ",", "0600", ")", ";", "err", "!=", "nil", "{", "return", "errwrap", ".", "Wrap", "(", "fmt", ".", "Errorf", "(", "\"error adding ourselves to the %q subcgroup\"", ",", "subcgroup", ")", ",", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// JoinSubcgroup makes the calling process join the subcgroup hierarchy on a // particular controller
[ "JoinSubcgroup", "makes", "the", "calling", "process", "join", "the", "subcgroup", "hierarchy", "on", "a", "particular", "controller" ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/common/cgroup/v1/cgroup.go#L169-L180
train
rkt/rkt
common/cgroup/v1/cgroup.go
IsControllerMounted
func IsControllerMounted(c string) (bool, error) { cgroupProcsPath := filepath.Join("/sys/fs/cgroup", c, "cgroup.procs") if _, err := os.Stat(cgroupProcsPath); err != nil { if !os.IsNotExist(err) { return false, err } return false, nil } return true, nil }
go
func IsControllerMounted(c string) (bool, error) { cgroupProcsPath := filepath.Join("/sys/fs/cgroup", c, "cgroup.procs") if _, err := os.Stat(cgroupProcsPath); err != nil { if !os.IsNotExist(err) { return false, err } return false, nil } return true, nil }
[ "func", "IsControllerMounted", "(", "c", "string", ")", "(", "bool", ",", "error", ")", "{", "cgroupProcsPath", ":=", "filepath", ".", "Join", "(", "\"/sys/fs/cgroup\"", ",", "c", ",", "\"cgroup.procs\"", ")", "\n", "if", "_", ",", "err", ":=", "os", ".", "Stat", "(", "cgroupProcsPath", ")", ";", "err", "!=", "nil", "{", "if", "!", "os", ".", "IsNotExist", "(", "err", ")", "{", "return", "false", ",", "err", "\n", "}", "\n", "return", "false", ",", "nil", "\n", "}", "\n", "return", "true", ",", "nil", "\n", "}" ]
// IsControllerMounted returns whether a controller is mounted by checking that // cgroup.procs is accessible
[ "IsControllerMounted", "returns", "whether", "a", "controller", "is", "mounted", "by", "checking", "that", "cgroup", ".", "procs", "is", "accessible" ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/common/cgroup/v1/cgroup.go#L238-L248
train
rkt/rkt
pkg/fileutil/fileutil_linux.go
Lgetxattr
func Lgetxattr(path string, attr string) ([]byte, error) { pathBytes, err := syscall.BytePtrFromString(path) if err != nil { return nil, err } attrBytes, err := syscall.BytePtrFromString(attr) if err != nil { return nil, err } dest := make([]byte, 128) destBytes := unsafe.Pointer(&dest[0]) sz, _, errno := syscall.Syscall6(syscall.SYS_LGETXATTR, uintptr(unsafe.Pointer(pathBytes)), uintptr(unsafe.Pointer(attrBytes)), uintptr(destBytes), uintptr(len(dest)), 0, 0) if errno == syscall.ENODATA { return nil, nil } if errno == syscall.ERANGE { dest = make([]byte, sz) destBytes := unsafe.Pointer(&dest[0]) sz, _, errno = syscall.Syscall6(syscall.SYS_LGETXATTR, uintptr(unsafe.Pointer(pathBytes)), uintptr(unsafe.Pointer(attrBytes)), uintptr(destBytes), uintptr(len(dest)), 0, 0) } if errno != 0 { return nil, errno } return dest[:sz], nil }
go
func Lgetxattr(path string, attr string) ([]byte, error) { pathBytes, err := syscall.BytePtrFromString(path) if err != nil { return nil, err } attrBytes, err := syscall.BytePtrFromString(attr) if err != nil { return nil, err } dest := make([]byte, 128) destBytes := unsafe.Pointer(&dest[0]) sz, _, errno := syscall.Syscall6(syscall.SYS_LGETXATTR, uintptr(unsafe.Pointer(pathBytes)), uintptr(unsafe.Pointer(attrBytes)), uintptr(destBytes), uintptr(len(dest)), 0, 0) if errno == syscall.ENODATA { return nil, nil } if errno == syscall.ERANGE { dest = make([]byte, sz) destBytes := unsafe.Pointer(&dest[0]) sz, _, errno = syscall.Syscall6(syscall.SYS_LGETXATTR, uintptr(unsafe.Pointer(pathBytes)), uintptr(unsafe.Pointer(attrBytes)), uintptr(destBytes), uintptr(len(dest)), 0, 0) } if errno != 0 { return nil, errno } return dest[:sz], nil }
[ "func", "Lgetxattr", "(", "path", "string", ",", "attr", "string", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "pathBytes", ",", "err", ":=", "syscall", ".", "BytePtrFromString", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "attrBytes", ",", "err", ":=", "syscall", ".", "BytePtrFromString", "(", "attr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "dest", ":=", "make", "(", "[", "]", "byte", ",", "128", ")", "\n", "destBytes", ":=", "unsafe", ".", "Pointer", "(", "&", "dest", "[", "0", "]", ")", "\n", "sz", ",", "_", ",", "errno", ":=", "syscall", ".", "Syscall6", "(", "syscall", ".", "SYS_LGETXATTR", ",", "uintptr", "(", "unsafe", ".", "Pointer", "(", "pathBytes", ")", ")", ",", "uintptr", "(", "unsafe", ".", "Pointer", "(", "attrBytes", ")", ")", ",", "uintptr", "(", "destBytes", ")", ",", "uintptr", "(", "len", "(", "dest", ")", ")", ",", "0", ",", "0", ")", "\n", "if", "errno", "==", "syscall", ".", "ENODATA", "{", "return", "nil", ",", "nil", "\n", "}", "\n", "if", "errno", "==", "syscall", ".", "ERANGE", "{", "dest", "=", "make", "(", "[", "]", "byte", ",", "sz", ")", "\n", "destBytes", ":=", "unsafe", ".", "Pointer", "(", "&", "dest", "[", "0", "]", ")", "\n", "sz", ",", "_", ",", "errno", "=", "syscall", ".", "Syscall6", "(", "syscall", ".", "SYS_LGETXATTR", ",", "uintptr", "(", "unsafe", ".", "Pointer", "(", "pathBytes", ")", ")", ",", "uintptr", "(", "unsafe", ".", "Pointer", "(", "attrBytes", ")", ")", ",", "uintptr", "(", "destBytes", ")", ",", "uintptr", "(", "len", "(", "dest", ")", ")", ",", "0", ",", "0", ")", "\n", "}", "\n", "if", "errno", "!=", "0", "{", "return", "nil", ",", "errno", "\n", "}", "\n", "return", "dest", "[", ":", "sz", "]", ",", "nil", "\n", "}" ]
// Returns a nil slice and nil error if the xattr is not set
[ "Returns", "a", "nil", "slice", "and", "nil", "error", "if", "the", "xattr", "is", "not", "set" ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/fileutil/fileutil_linux.go#L58-L84
train
rkt/rkt
pkg/fileutil/fileutil_linux.go
GetDeviceInfo
func GetDeviceInfo(path string) (kind rune, major uint64, minor uint64, err error) { d, err := os.Lstat(path) if err != nil { return } mode := d.Mode() if mode&os.ModeDevice == 0 { err = fmt.Errorf("not a device: %s", path) return } stat_t, ok := d.Sys().(*syscall.Stat_t) if !ok { err = fmt.Errorf("cannot determine device number") return } return getDeviceInfo(mode, stat_t.Rdev) }
go
func GetDeviceInfo(path string) (kind rune, major uint64, minor uint64, err error) { d, err := os.Lstat(path) if err != nil { return } mode := d.Mode() if mode&os.ModeDevice == 0 { err = fmt.Errorf("not a device: %s", path) return } stat_t, ok := d.Sys().(*syscall.Stat_t) if !ok { err = fmt.Errorf("cannot determine device number") return } return getDeviceInfo(mode, stat_t.Rdev) }
[ "func", "GetDeviceInfo", "(", "path", "string", ")", "(", "kind", "rune", ",", "major", "uint64", ",", "minor", "uint64", ",", "err", "error", ")", "{", "d", ",", "err", ":=", "os", ".", "Lstat", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "mode", ":=", "d", ".", "Mode", "(", ")", "\n", "if", "mode", "&", "os", ".", "ModeDevice", "==", "0", "{", "err", "=", "fmt", ".", "Errorf", "(", "\"not a device: %s\"", ",", "path", ")", "\n", "return", "\n", "}", "\n", "stat_t", ",", "ok", ":=", "d", ".", "Sys", "(", ")", ".", "(", "*", "syscall", ".", "Stat_t", ")", "\n", "if", "!", "ok", "{", "err", "=", "fmt", ".", "Errorf", "(", "\"cannot determine device number\"", ")", "\n", "return", "\n", "}", "\n", "return", "getDeviceInfo", "(", "mode", ",", "stat_t", ".", "Rdev", ")", "\n", "}" ]
// GetDeviceInfo returns the type, major, and minor numbers of a device. // Kind is 'b' or 'c' for block and character devices, respectively. // This does not follow symlinks.
[ "GetDeviceInfo", "returns", "the", "type", "major", "and", "minor", "numbers", "of", "a", "device", ".", "Kind", "is", "b", "or", "c", "for", "block", "and", "character", "devices", "respectively", ".", "This", "does", "not", "follow", "symlinks", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/fileutil/fileutil_linux.go#L113-L130
train
rkt/rkt
pkg/fileutil/fileutil_linux.go
getDeviceInfo
func getDeviceInfo(mode os.FileMode, rdev uint64) (kind rune, major uint64, minor uint64, err error) { kind = 'b' if mode&os.ModeCharDevice != 0 { kind = 'c' } major = (rdev >> 8) & 0xfff minor = (rdev & 0xff) | ((rdev >> 12) & 0xfff00) return }
go
func getDeviceInfo(mode os.FileMode, rdev uint64) (kind rune, major uint64, minor uint64, err error) { kind = 'b' if mode&os.ModeCharDevice != 0 { kind = 'c' } major = (rdev >> 8) & 0xfff minor = (rdev & 0xff) | ((rdev >> 12) & 0xfff00) return }
[ "func", "getDeviceInfo", "(", "mode", "os", ".", "FileMode", ",", "rdev", "uint64", ")", "(", "kind", "rune", ",", "major", "uint64", ",", "minor", "uint64", ",", "err", "error", ")", "{", "kind", "=", "'b'", "\n", "if", "mode", "&", "os", ".", "ModeCharDevice", "!=", "0", "{", "kind", "=", "'c'", "\n", "}", "\n", "major", "=", "(", "rdev", ">>", "8", ")", "&", "0xfff", "\n", "minor", "=", "(", "rdev", "&", "0xff", ")", "|", "(", "(", "rdev", ">>", "12", ")", "&", "0xfff00", ")", "\n", "return", "\n", "}" ]
// Parse the device info out of the mode bits. Separate for testability.
[ "Parse", "the", "device", "info", "out", "of", "the", "mode", "bits", ".", "Separate", "for", "testability", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/fileutil/fileutil_linux.go#L133-L144
train
rkt/rkt
common/cgroup/cgroup.go
IsIsolatorSupported
func IsIsolatorSupported(isolator string) (bool, error) { isUnified, err := IsCgroupUnified("/") if err != nil { return false, errwrap.Wrap(errors.New("error determining cgroup version"), err) } if isUnified { controllers, err := v2.GetEnabledControllers() if err != nil { return false, errwrap.Wrap(errors.New("error determining enabled controllers"), err) } for _, c := range controllers { if c == isolator { return true, nil } } return false, nil } return v1.IsControllerMounted(isolator) }
go
func IsIsolatorSupported(isolator string) (bool, error) { isUnified, err := IsCgroupUnified("/") if err != nil { return false, errwrap.Wrap(errors.New("error determining cgroup version"), err) } if isUnified { controllers, err := v2.GetEnabledControllers() if err != nil { return false, errwrap.Wrap(errors.New("error determining enabled controllers"), err) } for _, c := range controllers { if c == isolator { return true, nil } } return false, nil } return v1.IsControllerMounted(isolator) }
[ "func", "IsIsolatorSupported", "(", "isolator", "string", ")", "(", "bool", ",", "error", ")", "{", "isUnified", ",", "err", ":=", "IsCgroupUnified", "(", "\"/\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"error determining cgroup version\"", ")", ",", "err", ")", "\n", "}", "\n", "if", "isUnified", "{", "controllers", ",", "err", ":=", "v2", ".", "GetEnabledControllers", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"error determining enabled controllers\"", ")", ",", "err", ")", "\n", "}", "\n", "for", "_", ",", "c", ":=", "range", "controllers", "{", "if", "c", "==", "isolator", "{", "return", "true", ",", "nil", "\n", "}", "\n", "}", "\n", "return", "false", ",", "nil", "\n", "}", "\n", "return", "v1", ".", "IsControllerMounted", "(", "isolator", ")", "\n", "}" ]
// IsIsolatorSupported returns whether an isolator is supported in the kernel
[ "IsIsolatorSupported", "returns", "whether", "an", "isolator", "is", "supported", "in", "the", "kernel" ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/common/cgroup/cgroup.go#L37-L56
train
rkt/rkt
pkg/backup/backup.go
CreateBackup
func CreateBackup(dir, backupsDir string, limit int) error { tmpBackupDir := filepath.Join(backupsDir, "tmp") if err := os.MkdirAll(backupsDir, 0750); err != nil { return err } if err := fileutil.CopyTree(dir, tmpBackupDir, user.NewBlankUidRange()); err != nil { return err } defer os.RemoveAll(tmpBackupDir) // prune backups if err := pruneOldBackups(backupsDir, limit-1); err != nil { return err } if err := shiftBackups(backupsDir, limit-2); err != nil { return err } if err := os.Rename(tmpBackupDir, filepath.Join(backupsDir, "0")); err != nil { return err } return nil }
go
func CreateBackup(dir, backupsDir string, limit int) error { tmpBackupDir := filepath.Join(backupsDir, "tmp") if err := os.MkdirAll(backupsDir, 0750); err != nil { return err } if err := fileutil.CopyTree(dir, tmpBackupDir, user.NewBlankUidRange()); err != nil { return err } defer os.RemoveAll(tmpBackupDir) // prune backups if err := pruneOldBackups(backupsDir, limit-1); err != nil { return err } if err := shiftBackups(backupsDir, limit-2); err != nil { return err } if err := os.Rename(tmpBackupDir, filepath.Join(backupsDir, "0")); err != nil { return err } return nil }
[ "func", "CreateBackup", "(", "dir", ",", "backupsDir", "string", ",", "limit", "int", ")", "error", "{", "tmpBackupDir", ":=", "filepath", ".", "Join", "(", "backupsDir", ",", "\"tmp\"", ")", "\n", "if", "err", ":=", "os", ".", "MkdirAll", "(", "backupsDir", ",", "0750", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "fileutil", ".", "CopyTree", "(", "dir", ",", "tmpBackupDir", ",", "user", ".", "NewBlankUidRange", "(", ")", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "os", ".", "RemoveAll", "(", "tmpBackupDir", ")", "\n", "if", "err", ":=", "pruneOldBackups", "(", "backupsDir", ",", "limit", "-", "1", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "shiftBackups", "(", "backupsDir", ",", "limit", "-", "2", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "os", ".", "Rename", "(", "tmpBackupDir", ",", "filepath", ".", "Join", "(", "backupsDir", ",", "\"0\"", ")", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// CreateBackup backs a directory up in a given directory. It basically // copies this directory into a given backups directory. The backups // directory has a simple structure - a directory inside named "0" is // the most recent backup. A directory name for oldest backup is // deduced from a given limit. For instance, for limit being 5 the // name for the oldest backup would be "4". If a backups number // exceeds the given limit then only newest ones are kept and the rest // is removed.
[ "CreateBackup", "backs", "a", "directory", "up", "in", "a", "given", "directory", ".", "It", "basically", "copies", "this", "directory", "into", "a", "given", "backups", "directory", ".", "The", "backups", "directory", "has", "a", "simple", "structure", "-", "a", "directory", "inside", "named", "0", "is", "the", "most", "recent", "backup", ".", "A", "directory", "name", "for", "oldest", "backup", "is", "deduced", "from", "a", "given", "limit", ".", "For", "instance", "for", "limit", "being", "5", "the", "name", "for", "the", "oldest", "backup", "would", "be", "4", ".", "If", "a", "backups", "number", "exceeds", "the", "given", "limit", "then", "only", "newest", "ones", "are", "kept", "and", "the", "rest", "is", "removed", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/backup/backup.go#L35-L55
train
rkt/rkt
pkg/backup/backup.go
pruneOldBackups
func pruneOldBackups(dir string, limit int) error { if list, err := ioutil.ReadDir(dir); err != nil { return err } else { for _, fi := range list { if num, err := strconv.Atoi(fi.Name()); err != nil { // directory name is not a number, // leave it alone continue } else if num < limit { // directory name is a number lower // than a limit, leave it alone continue } path := filepath.Join(dir, fi.Name()) if err := os.RemoveAll(path); err != nil { return err } } } return nil }
go
func pruneOldBackups(dir string, limit int) error { if list, err := ioutil.ReadDir(dir); err != nil { return err } else { for _, fi := range list { if num, err := strconv.Atoi(fi.Name()); err != nil { // directory name is not a number, // leave it alone continue } else if num < limit { // directory name is a number lower // than a limit, leave it alone continue } path := filepath.Join(dir, fi.Name()) if err := os.RemoveAll(path); err != nil { return err } } } return nil }
[ "func", "pruneOldBackups", "(", "dir", "string", ",", "limit", "int", ")", "error", "{", "if", "list", ",", "err", ":=", "ioutil", ".", "ReadDir", "(", "dir", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "else", "{", "for", "_", ",", "fi", ":=", "range", "list", "{", "if", "num", ",", "err", ":=", "strconv", ".", "Atoi", "(", "fi", ".", "Name", "(", ")", ")", ";", "err", "!=", "nil", "{", "continue", "\n", "}", "else", "if", "num", "<", "limit", "{", "continue", "\n", "}", "\n", "path", ":=", "filepath", ".", "Join", "(", "dir", ",", "fi", ".", "Name", "(", ")", ")", "\n", "if", "err", ":=", "os", ".", "RemoveAll", "(", "path", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// pruneOldBackups removes old backups, that is - directories with // names greater or equal than given limit.
[ "pruneOldBackups", "removes", "old", "backups", "that", "is", "-", "directories", "with", "names", "greater", "or", "equal", "than", "given", "limit", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/backup/backup.go#L59-L80
train
rkt/rkt
pkg/backup/backup.go
shiftBackups
func shiftBackups(dir string, oldest int) error { if oldest < 0 { return nil } for i := oldest; i >= 0; i-- { current := filepath.Join(dir, strconv.Itoa(i)) inc := filepath.Join(dir, strconv.Itoa(i+1)) if err := os.Rename(current, inc); err != nil && !os.IsNotExist(err) { return err } } return nil }
go
func shiftBackups(dir string, oldest int) error { if oldest < 0 { return nil } for i := oldest; i >= 0; i-- { current := filepath.Join(dir, strconv.Itoa(i)) inc := filepath.Join(dir, strconv.Itoa(i+1)) if err := os.Rename(current, inc); err != nil && !os.IsNotExist(err) { return err } } return nil }
[ "func", "shiftBackups", "(", "dir", "string", ",", "oldest", "int", ")", "error", "{", "if", "oldest", "<", "0", "{", "return", "nil", "\n", "}", "\n", "for", "i", ":=", "oldest", ";", "i", ">=", "0", ";", "i", "--", "{", "current", ":=", "filepath", ".", "Join", "(", "dir", ",", "strconv", ".", "Itoa", "(", "i", ")", ")", "\n", "inc", ":=", "filepath", ".", "Join", "(", "dir", ",", "strconv", ".", "Itoa", "(", "i", "+", "1", ")", ")", "\n", "if", "err", ":=", "os", ".", "Rename", "(", "current", ",", "inc", ")", ";", "err", "!=", "nil", "&&", "!", "os", ".", "IsNotExist", "(", "err", ")", "{", "return", "err", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// shiftBackups renames all directories with names being numbers up to // oldest to names with numbers greater by one.
[ "shiftBackups", "renames", "all", "directories", "with", "names", "being", "numbers", "up", "to", "oldest", "to", "names", "with", "numbers", "greater", "by", "one", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/backup/backup.go#L84-L96
train
rkt/rkt
pkg/aci/aci.go
NewBasicACI
func NewBasicACI(dir string, name string) (*os.File, error) { manifest := schema.ImageManifest{ ACKind: schema.ImageManifestKind, ACVersion: schema.AppContainerVersion, Name: types.ACIdentifier(name), } b, err := manifest.MarshalJSON() if err != nil { return nil, err } return NewACI(dir, string(b), nil) }
go
func NewBasicACI(dir string, name string) (*os.File, error) { manifest := schema.ImageManifest{ ACKind: schema.ImageManifestKind, ACVersion: schema.AppContainerVersion, Name: types.ACIdentifier(name), } b, err := manifest.MarshalJSON() if err != nil { return nil, err } return NewACI(dir, string(b), nil) }
[ "func", "NewBasicACI", "(", "dir", "string", ",", "name", "string", ")", "(", "*", "os", ".", "File", ",", "error", ")", "{", "manifest", ":=", "schema", ".", "ImageManifest", "{", "ACKind", ":", "schema", ".", "ImageManifestKind", ",", "ACVersion", ":", "schema", ".", "AppContainerVersion", ",", "Name", ":", "types", ".", "ACIdentifier", "(", "name", ")", ",", "}", "\n", "b", ",", "err", ":=", "manifest", ".", "MarshalJSON", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "NewACI", "(", "dir", ",", "string", "(", "b", ")", ",", "nil", ")", "\n", "}" ]
// NewBasicACI creates a new ACI in the given directory with the given name. // Used for testing.
[ "NewBasicACI", "creates", "a", "new", "ACI", "in", "the", "given", "directory", "with", "the", "given", "name", ".", "Used", "for", "testing", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/aci/aci.go#L109-L122
train
rkt/rkt
pkg/aci/aci.go
NewACI
func NewACI(dir string, manifest string, entries []*ACIEntry) (*os.File, error) { var im schema.ImageManifest if err := im.UnmarshalJSON([]byte(manifest)); err != nil { return nil, errwrap.Wrap(errors.New("invalid image manifest"), err) } tf, err := ioutil.TempFile(dir, "") if err != nil { return nil, err } defer os.Remove(tf.Name()) tw := tar.NewWriter(tf) aw := NewImageWriter(im, tw) for _, entry := range entries { // Add default mode if entry.Header.Mode == 0 { if entry.Header.Typeflag == tar.TypeDir { entry.Header.Mode = 0755 } else { entry.Header.Mode = 0644 } } // Add calling user uid and gid or tests will fail entry.Header.Uid = os.Getuid() entry.Header.Gid = os.Getgid() sr := strings.NewReader(entry.Contents) if err := aw.AddFile(entry.Header, sr); err != nil { return nil, err } } if err := aw.Close(); err != nil { return nil, err } return tf, nil }
go
func NewACI(dir string, manifest string, entries []*ACIEntry) (*os.File, error) { var im schema.ImageManifest if err := im.UnmarshalJSON([]byte(manifest)); err != nil { return nil, errwrap.Wrap(errors.New("invalid image manifest"), err) } tf, err := ioutil.TempFile(dir, "") if err != nil { return nil, err } defer os.Remove(tf.Name()) tw := tar.NewWriter(tf) aw := NewImageWriter(im, tw) for _, entry := range entries { // Add default mode if entry.Header.Mode == 0 { if entry.Header.Typeflag == tar.TypeDir { entry.Header.Mode = 0755 } else { entry.Header.Mode = 0644 } } // Add calling user uid and gid or tests will fail entry.Header.Uid = os.Getuid() entry.Header.Gid = os.Getgid() sr := strings.NewReader(entry.Contents) if err := aw.AddFile(entry.Header, sr); err != nil { return nil, err } } if err := aw.Close(); err != nil { return nil, err } return tf, nil }
[ "func", "NewACI", "(", "dir", "string", ",", "manifest", "string", ",", "entries", "[", "]", "*", "ACIEntry", ")", "(", "*", "os", ".", "File", ",", "error", ")", "{", "var", "im", "schema", ".", "ImageManifest", "\n", "if", "err", ":=", "im", ".", "UnmarshalJSON", "(", "[", "]", "byte", "(", "manifest", ")", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"invalid image manifest\"", ")", ",", "err", ")", "\n", "}", "\n", "tf", ",", "err", ":=", "ioutil", ".", "TempFile", "(", "dir", ",", "\"\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "defer", "os", ".", "Remove", "(", "tf", ".", "Name", "(", ")", ")", "\n", "tw", ":=", "tar", ".", "NewWriter", "(", "tf", ")", "\n", "aw", ":=", "NewImageWriter", "(", "im", ",", "tw", ")", "\n", "for", "_", ",", "entry", ":=", "range", "entries", "{", "if", "entry", ".", "Header", ".", "Mode", "==", "0", "{", "if", "entry", ".", "Header", ".", "Typeflag", "==", "tar", ".", "TypeDir", "{", "entry", ".", "Header", ".", "Mode", "=", "0755", "\n", "}", "else", "{", "entry", ".", "Header", ".", "Mode", "=", "0644", "\n", "}", "\n", "}", "\n", "entry", ".", "Header", ".", "Uid", "=", "os", ".", "Getuid", "(", ")", "\n", "entry", ".", "Header", ".", "Gid", "=", "os", ".", "Getgid", "(", ")", "\n", "sr", ":=", "strings", ".", "NewReader", "(", "entry", ".", "Contents", ")", "\n", "if", "err", ":=", "aw", ".", "AddFile", "(", "entry", ".", "Header", ",", "sr", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n", "if", "err", ":=", "aw", ".", "Close", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "tf", ",", "nil", "\n", "}" ]
// NewACI creates a new ACI in the given directory with the given image // manifest and entries. // Used for testing.
[ "NewACI", "creates", "a", "new", "ACI", "in", "the", "given", "directory", "with", "the", "given", "image", "manifest", "and", "entries", ".", "Used", "for", "testing", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/aci/aci.go#L127-L164
train
rkt/rkt
pkg/aci/aci.go
NewDetachedSignature
func NewDetachedSignature(armoredPrivateKey string, aci io.Reader) (io.Reader, error) { entityList, err := openpgp.ReadArmoredKeyRing(bytes.NewBufferString(armoredPrivateKey)) if err != nil { return nil, err } if len(entityList) < 1 { return nil, errors.New("empty entity list") } signature := &bytes.Buffer{} if err := openpgp.ArmoredDetachSign(signature, entityList[0], aci, nil); err != nil { return nil, err } return signature, nil }
go
func NewDetachedSignature(armoredPrivateKey string, aci io.Reader) (io.Reader, error) { entityList, err := openpgp.ReadArmoredKeyRing(bytes.NewBufferString(armoredPrivateKey)) if err != nil { return nil, err } if len(entityList) < 1 { return nil, errors.New("empty entity list") } signature := &bytes.Buffer{} if err := openpgp.ArmoredDetachSign(signature, entityList[0], aci, nil); err != nil { return nil, err } return signature, nil }
[ "func", "NewDetachedSignature", "(", "armoredPrivateKey", "string", ",", "aci", "io", ".", "Reader", ")", "(", "io", ".", "Reader", ",", "error", ")", "{", "entityList", ",", "err", ":=", "openpgp", ".", "ReadArmoredKeyRing", "(", "bytes", ".", "NewBufferString", "(", "armoredPrivateKey", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "len", "(", "entityList", ")", "<", "1", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"empty entity list\"", ")", "\n", "}", "\n", "signature", ":=", "&", "bytes", ".", "Buffer", "{", "}", "\n", "if", "err", ":=", "openpgp", ".", "ArmoredDetachSign", "(", "signature", ",", "entityList", "[", "0", "]", ",", "aci", ",", "nil", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "signature", ",", "nil", "\n", "}" ]
// NewDetachedSignature creates a new openpgp armored detached signature for the given ACI // signed with armoredPrivateKey.
[ "NewDetachedSignature", "creates", "a", "new", "openpgp", "armored", "detached", "signature", "for", "the", "given", "ACI", "signed", "with", "armoredPrivateKey", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/aci/aci.go#L168-L181
train
rkt/rkt
pkg/pod/sandbox.go
SandboxManifest
func (p *Pod) SandboxManifest() (*schema.PodManifest, error) { _, pm, err := p.PodManifest() // this takes the lock fd to load the manifest, hence path is not needed here if err != nil { return nil, errwrap.Wrap(errors.New("error loading pod manifest"), err) } ms, ok := pm.Annotations.Get("coreos.com/rkt/stage1/mutable") if ok { p.mutable, err = strconv.ParseBool(ms) if err != nil { return nil, errwrap.Wrap(errors.New("error parsing mutable annotation"), err) } } if !p.mutable { return nil, ErrImmutable } return pm, nil }
go
func (p *Pod) SandboxManifest() (*schema.PodManifest, error) { _, pm, err := p.PodManifest() // this takes the lock fd to load the manifest, hence path is not needed here if err != nil { return nil, errwrap.Wrap(errors.New("error loading pod manifest"), err) } ms, ok := pm.Annotations.Get("coreos.com/rkt/stage1/mutable") if ok { p.mutable, err = strconv.ParseBool(ms) if err != nil { return nil, errwrap.Wrap(errors.New("error parsing mutable annotation"), err) } } if !p.mutable { return nil, ErrImmutable } return pm, nil }
[ "func", "(", "p", "*", "Pod", ")", "SandboxManifest", "(", ")", "(", "*", "schema", ".", "PodManifest", ",", "error", ")", "{", "_", ",", "pm", ",", "err", ":=", "p", ".", "PodManifest", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"error loading pod manifest\"", ")", ",", "err", ")", "\n", "}", "\n", "ms", ",", "ok", ":=", "pm", ".", "Annotations", ".", "Get", "(", "\"coreos.com/rkt/stage1/mutable\"", ")", "\n", "if", "ok", "{", "p", ".", "mutable", ",", "err", "=", "strconv", ".", "ParseBool", "(", "ms", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"error parsing mutable annotation\"", ")", ",", "err", ")", "\n", "}", "\n", "}", "\n", "if", "!", "p", ".", "mutable", "{", "return", "nil", ",", "ErrImmutable", "\n", "}", "\n", "return", "pm", ",", "nil", "\n", "}" ]
// SandboxManifest loads the underlying pod manifest and checks whether mutable operations are allowed. // It returns ErrImmutable if the pod does not allow mutable operations or any other error if the operation failed. // Upon success a reference to the pod manifest is returned and mutable operations are possible.
[ "SandboxManifest", "loads", "the", "underlying", "pod", "manifest", "and", "checks", "whether", "mutable", "operations", "are", "allowed", ".", "It", "returns", "ErrImmutable", "if", "the", "pod", "does", "not", "allow", "mutable", "operations", "or", "any", "other", "error", "if", "the", "operation", "failed", ".", "Upon", "success", "a", "reference", "to", "the", "pod", "manifest", "is", "returned", "and", "mutable", "operations", "are", "possible", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/pod/sandbox.go#L37-L56
train
rkt/rkt
pkg/pod/sandbox.go
UpdateManifest
func (p *Pod) UpdateManifest(m *schema.PodManifest, path string) error { if !p.mutable { return ErrImmutable } mpath := common.PodManifestPath(path) mstat, err := os.Stat(mpath) if err != nil { return err } tmpf, err := ioutil.TempFile(path, "") if err != nil { return err } defer func() { tmpf.Close() os.Remove(tmpf.Name()) }() if err := tmpf.Chmod(mstat.Mode().Perm()); err != nil { return err } if err := json.NewEncoder(tmpf).Encode(m); err != nil { return err } if err := os.Rename(tmpf.Name(), mpath); err != nil { return err } return nil }
go
func (p *Pod) UpdateManifest(m *schema.PodManifest, path string) error { if !p.mutable { return ErrImmutable } mpath := common.PodManifestPath(path) mstat, err := os.Stat(mpath) if err != nil { return err } tmpf, err := ioutil.TempFile(path, "") if err != nil { return err } defer func() { tmpf.Close() os.Remove(tmpf.Name()) }() if err := tmpf.Chmod(mstat.Mode().Perm()); err != nil { return err } if err := json.NewEncoder(tmpf).Encode(m); err != nil { return err } if err := os.Rename(tmpf.Name(), mpath); err != nil { return err } return nil }
[ "func", "(", "p", "*", "Pod", ")", "UpdateManifest", "(", "m", "*", "schema", ".", "PodManifest", ",", "path", "string", ")", "error", "{", "if", "!", "p", ".", "mutable", "{", "return", "ErrImmutable", "\n", "}", "\n", "mpath", ":=", "common", ".", "PodManifestPath", "(", "path", ")", "\n", "mstat", ",", "err", ":=", "os", ".", "Stat", "(", "mpath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "tmpf", ",", "err", ":=", "ioutil", ".", "TempFile", "(", "path", ",", "\"\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "func", "(", ")", "{", "tmpf", ".", "Close", "(", ")", "\n", "os", ".", "Remove", "(", "tmpf", ".", "Name", "(", ")", ")", "\n", "}", "(", ")", "\n", "if", "err", ":=", "tmpf", ".", "Chmod", "(", "mstat", ".", "Mode", "(", ")", ".", "Perm", "(", ")", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "json", ".", "NewEncoder", "(", "tmpf", ")", ".", "Encode", "(", "m", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "os", ".", "Rename", "(", "tmpf", ".", "Name", "(", ")", ",", "mpath", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// UpdateManifest updates the given pod manifest in the given path atomically on the file system. // The pod manifest has to be locked using LockManifest first to avoid races in case of concurrent writes.
[ "UpdateManifest", "updates", "the", "given", "pod", "manifest", "in", "the", "given", "path", "atomically", "on", "the", "file", "system", ".", "The", "pod", "manifest", "has", "to", "be", "locked", "using", "LockManifest", "first", "to", "avoid", "races", "in", "case", "of", "concurrent", "writes", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/pod/sandbox.go#L60-L94
train
rkt/rkt
pkg/pod/sandbox.go
ExclusiveLockManifest
func (p *Pod) ExclusiveLockManifest() error { if p.manifestLock != nil { return p.manifestLock.ExclusiveLock() // This is idempotent } l, err := lock.ExclusiveLock(common.PodManifestLockPath(p.Path()), lock.RegFile) if err != nil { return err } p.manifestLock = l return nil }
go
func (p *Pod) ExclusiveLockManifest() error { if p.manifestLock != nil { return p.manifestLock.ExclusiveLock() // This is idempotent } l, err := lock.ExclusiveLock(common.PodManifestLockPath(p.Path()), lock.RegFile) if err != nil { return err } p.manifestLock = l return nil }
[ "func", "(", "p", "*", "Pod", ")", "ExclusiveLockManifest", "(", ")", "error", "{", "if", "p", ".", "manifestLock", "!=", "nil", "{", "return", "p", ".", "manifestLock", ".", "ExclusiveLock", "(", ")", "\n", "}", "\n", "l", ",", "err", ":=", "lock", ".", "ExclusiveLock", "(", "common", ".", "PodManifestLockPath", "(", "p", ".", "Path", "(", ")", ")", ",", "lock", ".", "RegFile", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "p", ".", "manifestLock", "=", "l", "\n", "return", "nil", "\n", "}" ]
// ExclusiveLockManifest gets an exclusive lock on only the pod manifest in the app sandbox. // Since the pod might already be running, we can't just get an exclusive lock on the pod itself.
[ "ExclusiveLockManifest", "gets", "an", "exclusive", "lock", "on", "only", "the", "pod", "manifest", "in", "the", "app", "sandbox", ".", "Since", "the", "pod", "might", "already", "be", "running", "we", "can", "t", "just", "get", "an", "exclusive", "lock", "on", "the", "pod", "itself", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/pod/sandbox.go#L98-L110
train
rkt/rkt
pkg/pod/sandbox.go
UnlockManifest
func (p *Pod) UnlockManifest() error { if p.manifestLock == nil { return nil } if err := p.manifestLock.Close(); err != nil { return err } p.manifestLock = nil return nil }
go
func (p *Pod) UnlockManifest() error { if p.manifestLock == nil { return nil } if err := p.manifestLock.Close(); err != nil { return err } p.manifestLock = nil return nil }
[ "func", "(", "p", "*", "Pod", ")", "UnlockManifest", "(", ")", "error", "{", "if", "p", ".", "manifestLock", "==", "nil", "{", "return", "nil", "\n", "}", "\n", "if", "err", ":=", "p", ".", "manifestLock", ".", "Close", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "p", ".", "manifestLock", "=", "nil", "\n", "return", "nil", "\n", "}" ]
// UnlockManifest unlocks the pod manifest lock.
[ "UnlockManifest", "unlocks", "the", "pod", "manifest", "lock", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/pod/sandbox.go#L113-L123
train
rkt/rkt
store/imagestore/schema.go
getDBVersion
func getDBVersion(tx *sql.Tx) (int, error) { var version int rows, err := tx.Query("SELECT version FROM version") if err != nil { return -1, err } defer rows.Close() found := false for rows.Next() { if err := rows.Scan(&version); err != nil { return -1, err } found = true break } if err := rows.Err(); err != nil { return -1, err } if !found { return -1, fmt.Errorf("db version table empty") } return version, nil }
go
func getDBVersion(tx *sql.Tx) (int, error) { var version int rows, err := tx.Query("SELECT version FROM version") if err != nil { return -1, err } defer rows.Close() found := false for rows.Next() { if err := rows.Scan(&version); err != nil { return -1, err } found = true break } if err := rows.Err(); err != nil { return -1, err } if !found { return -1, fmt.Errorf("db version table empty") } return version, nil }
[ "func", "getDBVersion", "(", "tx", "*", "sql", ".", "Tx", ")", "(", "int", ",", "error", ")", "{", "var", "version", "int", "\n", "rows", ",", "err", ":=", "tx", ".", "Query", "(", "\"SELECT version FROM version\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "-", "1", ",", "err", "\n", "}", "\n", "defer", "rows", ".", "Close", "(", ")", "\n", "found", ":=", "false", "\n", "for", "rows", ".", "Next", "(", ")", "{", "if", "err", ":=", "rows", ".", "Scan", "(", "&", "version", ")", ";", "err", "!=", "nil", "{", "return", "-", "1", ",", "err", "\n", "}", "\n", "found", "=", "true", "\n", "break", "\n", "}", "\n", "if", "err", ":=", "rows", ".", "Err", "(", ")", ";", "err", "!=", "nil", "{", "return", "-", "1", ",", "err", "\n", "}", "\n", "if", "!", "found", "{", "return", "-", "1", ",", "fmt", ".", "Errorf", "(", "\"db version table empty\"", ")", "\n", "}", "\n", "return", "version", ",", "nil", "\n", "}" ]
// getDBVersion retrieves the current db version
[ "getDBVersion", "retrieves", "the", "current", "db", "version" ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/store/imagestore/schema.go#L66-L88
train
rkt/rkt
store/imagestore/schema.go
updateDBVersion
func updateDBVersion(tx *sql.Tx, version int) error { // ql doesn't have an INSERT OR UPDATE function so // it's faster to remove and reinsert the row _, err := tx.Exec("DELETE FROM version") if err != nil { return err } _, err = tx.Exec("INSERT INTO version VALUES ($1)", version) if err != nil { return err } return nil }
go
func updateDBVersion(tx *sql.Tx, version int) error { // ql doesn't have an INSERT OR UPDATE function so // it's faster to remove and reinsert the row _, err := tx.Exec("DELETE FROM version") if err != nil { return err } _, err = tx.Exec("INSERT INTO version VALUES ($1)", version) if err != nil { return err } return nil }
[ "func", "updateDBVersion", "(", "tx", "*", "sql", ".", "Tx", ",", "version", "int", ")", "error", "{", "_", ",", "err", ":=", "tx", ".", "Exec", "(", "\"DELETE FROM version\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "_", ",", "err", "=", "tx", ".", "Exec", "(", "\"INSERT INTO version VALUES ($1)\"", ",", "version", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// updateDBVersion updates the db version
[ "updateDBVersion", "updates", "the", "db", "version" ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/store/imagestore/schema.go#L91-L103
train
rkt/rkt
pkg/acl/acl.go
InitACL
func InitACL() (*ACL, error) { h, err := getHandle() if err != nil { return nil, err } return &ACL{lib: h}, nil }
go
func InitACL() (*ACL, error) { h, err := getHandle() if err != nil { return nil, err } return &ACL{lib: h}, nil }
[ "func", "InitACL", "(", ")", "(", "*", "ACL", ",", "error", ")", "{", "h", ",", "err", ":=", "getHandle", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "&", "ACL", "{", "lib", ":", "h", "}", ",", "nil", "\n", "}" ]
// InitACL dlopens libacl and returns an ACL object if successful.
[ "InitACL", "dlopens", "libacl", "and", "returns", "an", "ACL", "object", "if", "successful", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/acl/acl.go#L220-L227
train
rkt/rkt
pkg/acl/acl.go
ParseACL
func (a *ACL) ParseACL(acl string) error { acl_from_text, err := getSymbolPointer(a.lib.handle, "acl_from_text") if err != nil { return err } cacl := C.CString(acl) defer C.free(unsafe.Pointer(cacl)) retACL, err := C.my_acl_from_text(acl_from_text, cacl) if retACL == nil { return errwrap.Wrap(errors.New("error calling acl_from_text"), err) } a.a = retACL return nil }
go
func (a *ACL) ParseACL(acl string) error { acl_from_text, err := getSymbolPointer(a.lib.handle, "acl_from_text") if err != nil { return err } cacl := C.CString(acl) defer C.free(unsafe.Pointer(cacl)) retACL, err := C.my_acl_from_text(acl_from_text, cacl) if retACL == nil { return errwrap.Wrap(errors.New("error calling acl_from_text"), err) } a.a = retACL return nil }
[ "func", "(", "a", "*", "ACL", ")", "ParseACL", "(", "acl", "string", ")", "error", "{", "acl_from_text", ",", "err", ":=", "getSymbolPointer", "(", "a", ".", "lib", ".", "handle", ",", "\"acl_from_text\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "cacl", ":=", "C", ".", "CString", "(", "acl", ")", "\n", "defer", "C", ".", "free", "(", "unsafe", ".", "Pointer", "(", "cacl", ")", ")", "\n", "retACL", ",", "err", ":=", "C", ".", "my_acl_from_text", "(", "acl_from_text", ",", "cacl", ")", "\n", "if", "retACL", "==", "nil", "{", "return", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"error calling acl_from_text\"", ")", ",", "err", ")", "\n", "}", "\n", "a", ".", "a", "=", "retACL", "\n", "return", "nil", "\n", "}" ]
// ParseACL parses a string representation of an ACL.
[ "ParseACL", "parses", "a", "string", "representation", "of", "an", "ACL", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/acl/acl.go#L230-L246
train
rkt/rkt
pkg/acl/acl.go
Free
func (a *ACL) Free() error { acl_free, err := getSymbolPointer(a.lib.handle, "acl_free") if err != nil { return err } ret, err := C.my_acl_free(acl_free, a.a) if ret < 0 { return errwrap.Wrap(errors.New("error calling acl_free"), err) } return a.lib.close() }
go
func (a *ACL) Free() error { acl_free, err := getSymbolPointer(a.lib.handle, "acl_free") if err != nil { return err } ret, err := C.my_acl_free(acl_free, a.a) if ret < 0 { return errwrap.Wrap(errors.New("error calling acl_free"), err) } return a.lib.close() }
[ "func", "(", "a", "*", "ACL", ")", "Free", "(", ")", "error", "{", "acl_free", ",", "err", ":=", "getSymbolPointer", "(", "a", ".", "lib", ".", "handle", ",", "\"acl_free\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "ret", ",", "err", ":=", "C", ".", "my_acl_free", "(", "acl_free", ",", "a", ".", "a", ")", "\n", "if", "ret", "<", "0", "{", "return", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"error calling acl_free\"", ")", ",", "err", ")", "\n", "}", "\n", "return", "a", ".", "lib", ".", "close", "(", ")", "\n", "}" ]
// Free frees libacl's internal structures and closes libacl.
[ "Free", "frees", "libacl", "s", "internal", "structures", "and", "closes", "libacl", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/acl/acl.go#L249-L261
train
rkt/rkt
pkg/acl/acl.go
SetFileACLDefault
func (a *ACL) SetFileACLDefault(path string) error { acl_set_file, err := getSymbolPointer(a.lib.handle, "acl_set_file") if err != nil { return err } cpath := C.CString(path) defer C.free(unsafe.Pointer(cpath)) ret, err := C.my_acl_set_file(acl_set_file, cpath, C.ACL_TYPE_DEFAULT, a.a) if ret < 0 { return errwrap.Wrap(errors.New("error calling acl_set_file"), err) } return nil }
go
func (a *ACL) SetFileACLDefault(path string) error { acl_set_file, err := getSymbolPointer(a.lib.handle, "acl_set_file") if err != nil { return err } cpath := C.CString(path) defer C.free(unsafe.Pointer(cpath)) ret, err := C.my_acl_set_file(acl_set_file, cpath, C.ACL_TYPE_DEFAULT, a.a) if ret < 0 { return errwrap.Wrap(errors.New("error calling acl_set_file"), err) } return nil }
[ "func", "(", "a", "*", "ACL", ")", "SetFileACLDefault", "(", "path", "string", ")", "error", "{", "acl_set_file", ",", "err", ":=", "getSymbolPointer", "(", "a", ".", "lib", ".", "handle", ",", "\"acl_set_file\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "cpath", ":=", "C", ".", "CString", "(", "path", ")", "\n", "defer", "C", ".", "free", "(", "unsafe", ".", "Pointer", "(", "cpath", ")", ")", "\n", "ret", ",", "err", ":=", "C", ".", "my_acl_set_file", "(", "acl_set_file", ",", "cpath", ",", "C", ".", "ACL_TYPE_DEFAULT", ",", "a", ".", "a", ")", "\n", "if", "ret", "<", "0", "{", "return", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"error calling acl_set_file\"", ")", ",", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// SetFileACLDefault sets the "default" ACL for path.
[ "SetFileACLDefault", "sets", "the", "default", "ACL", "for", "path", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/acl/acl.go#L264-L279
train
rkt/rkt
pkg/acl/acl.go
Valid
func (a *ACL) Valid() error { acl_valid, err := getSymbolPointer(a.lib.handle, "acl_valid") if err != nil { return err } ret, err := C.my_acl_valid(acl_valid, a.a) if ret < 0 { return errwrap.Wrap(errors.New("invalid acl"), err) } return nil }
go
func (a *ACL) Valid() error { acl_valid, err := getSymbolPointer(a.lib.handle, "acl_valid") if err != nil { return err } ret, err := C.my_acl_valid(acl_valid, a.a) if ret < 0 { return errwrap.Wrap(errors.New("invalid acl"), err) } return nil }
[ "func", "(", "a", "*", "ACL", ")", "Valid", "(", ")", "error", "{", "acl_valid", ",", "err", ":=", "getSymbolPointer", "(", "a", ".", "lib", ".", "handle", ",", "\"acl_valid\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "ret", ",", "err", ":=", "C", ".", "my_acl_valid", "(", "acl_valid", ",", "a", ".", "a", ")", "\n", "if", "ret", "<", "0", "{", "return", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"invalid acl\"", ")", ",", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Valid checks whether the ACL is valid.
[ "Valid", "checks", "whether", "the", "ACL", "is", "valid", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/acl/acl.go#L282-L293
train
rkt/rkt
pkg/acl/acl.go
AddBaseEntries
func (a *ACL) AddBaseEntries(path string) error { fi, err := os.Lstat(path) if err != nil { return err } mode := fi.Mode().Perm() var r, w, x bool // set USER_OBJ entry r = mode&userRead == userRead w = mode&userWrite == userWrite x = mode&userExec == userExec if err := a.addBaseEntryFromMode(TagUserObj, r, w, x); err != nil { return err } // set GROUP_OBJ entry r = mode&groupRead == groupRead w = mode&groupWrite == groupWrite x = mode&groupExec == groupExec if err := a.addBaseEntryFromMode(TagGroupObj, r, w, x); err != nil { return err } // set OTHER entry r = mode&otherRead == otherRead w = mode&otherWrite == otherWrite x = mode&otherExec == otherExec if err := a.addBaseEntryFromMode(TagOther, r, w, x); err != nil { return err } return nil }
go
func (a *ACL) AddBaseEntries(path string) error { fi, err := os.Lstat(path) if err != nil { return err } mode := fi.Mode().Perm() var r, w, x bool // set USER_OBJ entry r = mode&userRead == userRead w = mode&userWrite == userWrite x = mode&userExec == userExec if err := a.addBaseEntryFromMode(TagUserObj, r, w, x); err != nil { return err } // set GROUP_OBJ entry r = mode&groupRead == groupRead w = mode&groupWrite == groupWrite x = mode&groupExec == groupExec if err := a.addBaseEntryFromMode(TagGroupObj, r, w, x); err != nil { return err } // set OTHER entry r = mode&otherRead == otherRead w = mode&otherWrite == otherWrite x = mode&otherExec == otherExec if err := a.addBaseEntryFromMode(TagOther, r, w, x); err != nil { return err } return nil }
[ "func", "(", "a", "*", "ACL", ")", "AddBaseEntries", "(", "path", "string", ")", "error", "{", "fi", ",", "err", ":=", "os", ".", "Lstat", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "mode", ":=", "fi", ".", "Mode", "(", ")", ".", "Perm", "(", ")", "\n", "var", "r", ",", "w", ",", "x", "bool", "\n", "r", "=", "mode", "&", "userRead", "==", "userRead", "\n", "w", "=", "mode", "&", "userWrite", "==", "userWrite", "\n", "x", "=", "mode", "&", "userExec", "==", "userExec", "\n", "if", "err", ":=", "a", ".", "addBaseEntryFromMode", "(", "TagUserObj", ",", "r", ",", "w", ",", "x", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "r", "=", "mode", "&", "groupRead", "==", "groupRead", "\n", "w", "=", "mode", "&", "groupWrite", "==", "groupWrite", "\n", "x", "=", "mode", "&", "groupExec", "==", "groupExec", "\n", "if", "err", ":=", "a", ".", "addBaseEntryFromMode", "(", "TagGroupObj", ",", "r", ",", "w", ",", "x", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "r", "=", "mode", "&", "otherRead", "==", "otherRead", "\n", "w", "=", "mode", "&", "otherWrite", "==", "otherWrite", "\n", "x", "=", "mode", "&", "otherExec", "==", "otherExec", "\n", "if", "err", ":=", "a", ".", "addBaseEntryFromMode", "(", "TagOther", ",", "r", ",", "w", ",", "x", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// AddBaseEntries adds the base ACL entries from the file permissions.
[ "AddBaseEntries", "adds", "the", "base", "ACL", "entries", "from", "the", "file", "permissions", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/acl/acl.go#L296-L329
train
rkt/rkt
pkg/distribution/appc.go
NewAppc
func NewAppc(u *url.URL) (Distribution, error) { c, err := parseCIMD(u) if err != nil { return nil, fmt.Errorf("cannot parse URI: %q: %v", u.String(), err) } if c.Type != TypeAppc { return nil, fmt.Errorf("wrong distribution type: %q", c.Type) } appcStr := c.Data for n, v := range u.Query() { appcStr += fmt.Sprintf(",%s=%s", n, v[0]) } app, err := discovery.NewAppFromString(appcStr) if err != nil { return nil, fmt.Errorf("wrong appc image string %q: %v", u.String(), err) } return NewAppcFromApp(app), nil }
go
func NewAppc(u *url.URL) (Distribution, error) { c, err := parseCIMD(u) if err != nil { return nil, fmt.Errorf("cannot parse URI: %q: %v", u.String(), err) } if c.Type != TypeAppc { return nil, fmt.Errorf("wrong distribution type: %q", c.Type) } appcStr := c.Data for n, v := range u.Query() { appcStr += fmt.Sprintf(",%s=%s", n, v[0]) } app, err := discovery.NewAppFromString(appcStr) if err != nil { return nil, fmt.Errorf("wrong appc image string %q: %v", u.String(), err) } return NewAppcFromApp(app), nil }
[ "func", "NewAppc", "(", "u", "*", "url", ".", "URL", ")", "(", "Distribution", ",", "error", ")", "{", "c", ",", "err", ":=", "parseCIMD", "(", "u", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"cannot parse URI: %q: %v\"", ",", "u", ".", "String", "(", ")", ",", "err", ")", "\n", "}", "\n", "if", "c", ".", "Type", "!=", "TypeAppc", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"wrong distribution type: %q\"", ",", "c", ".", "Type", ")", "\n", "}", "\n", "appcStr", ":=", "c", ".", "Data", "\n", "for", "n", ",", "v", ":=", "range", "u", ".", "Query", "(", ")", "{", "appcStr", "+=", "fmt", ".", "Sprintf", "(", "\",%s=%s\"", ",", "n", ",", "v", "[", "0", "]", ")", "\n", "}", "\n", "app", ",", "err", ":=", "discovery", ".", "NewAppFromString", "(", "appcStr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"wrong appc image string %q: %v\"", ",", "u", ".", "String", "(", ")", ",", "err", ")", "\n", "}", "\n", "return", "NewAppcFromApp", "(", "app", ")", ",", "nil", "\n", "}" ]
// NewAppc returns an Appc distribution from an Appc distribution URI
[ "NewAppc", "returns", "an", "Appc", "distribution", "from", "an", "Appc", "distribution", "URI" ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/distribution/appc.go#L52-L71
train
rkt/rkt
pkg/distribution/appc.go
NewAppcFromApp
func NewAppcFromApp(app *discovery.App) Distribution { rawuri := NewCIMDString(TypeAppc, distAppcVersion, url.QueryEscape(app.Name.String())) var version string labels := types.Labels{} for n, v := range app.Labels { if n == "version" { version = v } labels = append(labels, types.Label{Name: n, Value: v}) } if len(labels) > 0 { queries := make([]string, len(labels)) rawuri += "?" for i, l := range labels { queries[i] = fmt.Sprintf("%s=%s", l.Name, url.QueryEscape(l.Value)) } rawuri += strings.Join(queries, "&") } u, err := url.Parse(rawuri) if err != nil { panic(fmt.Errorf("cannot parse URI %q: %v", rawuri, err)) } // save the URI as sorted to make it ready for comparison purell.NormalizeURL(u, purell.FlagSortQuery) str := app.Name.String() if version != "" { str += fmt.Sprintf(":%s", version) } labelsort.By(labelsort.RankedName).Sort(labels) for _, l := range labels { if l.Name != "version" { str += fmt.Sprintf(",%s=%s", l.Name, l.Value) } } return &Appc{ cimd: u, app: app.Copy(), str: str, } }
go
func NewAppcFromApp(app *discovery.App) Distribution { rawuri := NewCIMDString(TypeAppc, distAppcVersion, url.QueryEscape(app.Name.String())) var version string labels := types.Labels{} for n, v := range app.Labels { if n == "version" { version = v } labels = append(labels, types.Label{Name: n, Value: v}) } if len(labels) > 0 { queries := make([]string, len(labels)) rawuri += "?" for i, l := range labels { queries[i] = fmt.Sprintf("%s=%s", l.Name, url.QueryEscape(l.Value)) } rawuri += strings.Join(queries, "&") } u, err := url.Parse(rawuri) if err != nil { panic(fmt.Errorf("cannot parse URI %q: %v", rawuri, err)) } // save the URI as sorted to make it ready for comparison purell.NormalizeURL(u, purell.FlagSortQuery) str := app.Name.String() if version != "" { str += fmt.Sprintf(":%s", version) } labelsort.By(labelsort.RankedName).Sort(labels) for _, l := range labels { if l.Name != "version" { str += fmt.Sprintf(",%s=%s", l.Name, l.Value) } } return &Appc{ cimd: u, app: app.Copy(), str: str, } }
[ "func", "NewAppcFromApp", "(", "app", "*", "discovery", ".", "App", ")", "Distribution", "{", "rawuri", ":=", "NewCIMDString", "(", "TypeAppc", ",", "distAppcVersion", ",", "url", ".", "QueryEscape", "(", "app", ".", "Name", ".", "String", "(", ")", ")", ")", "\n", "var", "version", "string", "\n", "labels", ":=", "types", ".", "Labels", "{", "}", "\n", "for", "n", ",", "v", ":=", "range", "app", ".", "Labels", "{", "if", "n", "==", "\"version\"", "{", "version", "=", "v", "\n", "}", "\n", "labels", "=", "append", "(", "labels", ",", "types", ".", "Label", "{", "Name", ":", "n", ",", "Value", ":", "v", "}", ")", "\n", "}", "\n", "if", "len", "(", "labels", ")", ">", "0", "{", "queries", ":=", "make", "(", "[", "]", "string", ",", "len", "(", "labels", ")", ")", "\n", "rawuri", "+=", "\"?\"", "\n", "for", "i", ",", "l", ":=", "range", "labels", "{", "queries", "[", "i", "]", "=", "fmt", ".", "Sprintf", "(", "\"%s=%s\"", ",", "l", ".", "Name", ",", "url", ".", "QueryEscape", "(", "l", ".", "Value", ")", ")", "\n", "}", "\n", "rawuri", "+=", "strings", ".", "Join", "(", "queries", ",", "\"&\"", ")", "\n", "}", "\n", "u", ",", "err", ":=", "url", ".", "Parse", "(", "rawuri", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "fmt", ".", "Errorf", "(", "\"cannot parse URI %q: %v\"", ",", "rawuri", ",", "err", ")", ")", "\n", "}", "\n", "purell", ".", "NormalizeURL", "(", "u", ",", "purell", ".", "FlagSortQuery", ")", "\n", "str", ":=", "app", ".", "Name", ".", "String", "(", ")", "\n", "if", "version", "!=", "\"\"", "{", "str", "+=", "fmt", ".", "Sprintf", "(", "\":%s\"", ",", "version", ")", "\n", "}", "\n", "labelsort", ".", "By", "(", "labelsort", ".", "RankedName", ")", ".", "Sort", "(", "labels", ")", "\n", "for", "_", ",", "l", ":=", "range", "labels", "{", "if", "l", ".", "Name", "!=", "\"version\"", "{", "str", "+=", "fmt", ".", "Sprintf", "(", "\",%s=%s\"", ",", "l", ".", "Name", ",", "l", ".", "Value", ")", "\n", "}", "\n", "}", "\n", "return", "&", "Appc", "{", "cimd", ":", "u", ",", "app", ":", "app", ".", "Copy", "(", ")", ",", "str", ":", "str", ",", "}", "\n", "}" ]
// NewAppcFromApp returns an Appc distribution from an appc App discovery string
[ "NewAppcFromApp", "returns", "an", "Appc", "distribution", "from", "an", "appc", "App", "discovery", "string" ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/distribution/appc.go#L74-L121
train
rkt/rkt
pkg/sys/sys.go
CloseOnExec
func CloseOnExec(fd int, set bool) error { flag := uintptr(0) if set { flag = syscall.FD_CLOEXEC } _, _, err := syscall.RawSyscall(syscall.SYS_FCNTL, uintptr(fd), syscall.F_SETFD, flag) if err != 0 { return syscall.Errno(err) } return nil }
go
func CloseOnExec(fd int, set bool) error { flag := uintptr(0) if set { flag = syscall.FD_CLOEXEC } _, _, err := syscall.RawSyscall(syscall.SYS_FCNTL, uintptr(fd), syscall.F_SETFD, flag) if err != 0 { return syscall.Errno(err) } return nil }
[ "func", "CloseOnExec", "(", "fd", "int", ",", "set", "bool", ")", "error", "{", "flag", ":=", "uintptr", "(", "0", ")", "\n", "if", "set", "{", "flag", "=", "syscall", ".", "FD_CLOEXEC", "\n", "}", "\n", "_", ",", "_", ",", "err", ":=", "syscall", ".", "RawSyscall", "(", "syscall", ".", "SYS_FCNTL", ",", "uintptr", "(", "fd", ")", ",", "syscall", ".", "F_SETFD", ",", "flag", ")", "\n", "if", "err", "!=", "0", "{", "return", "syscall", ".", "Errno", "(", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// CloseOnExec sets or clears FD_CLOEXEC flag on a file descriptor
[ "CloseOnExec", "sets", "or", "clears", "FD_CLOEXEC", "flag", "on", "a", "file", "descriptor" ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/sys/sys.go#L22-L32
train
rkt/rkt
common/cgroup/v2/cgroup.go
GetEnabledControllers
func GetEnabledControllers() ([]string, error) { controllersFile, err := os.Open("/sys/fs/cgroup/cgroup.controllers") if err != nil { return nil, err } defer controllersFile.Close() sc := bufio.NewScanner(controllersFile) sc.Scan() if err := sc.Err(); err != nil { return nil, err } return strings.Split(sc.Text(), " "), nil }
go
func GetEnabledControllers() ([]string, error) { controllersFile, err := os.Open("/sys/fs/cgroup/cgroup.controllers") if err != nil { return nil, err } defer controllersFile.Close() sc := bufio.NewScanner(controllersFile) sc.Scan() if err := sc.Err(); err != nil { return nil, err } return strings.Split(sc.Text(), " "), nil }
[ "func", "GetEnabledControllers", "(", ")", "(", "[", "]", "string", ",", "error", ")", "{", "controllersFile", ",", "err", ":=", "os", ".", "Open", "(", "\"/sys/fs/cgroup/cgroup.controllers\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "defer", "controllersFile", ".", "Close", "(", ")", "\n", "sc", ":=", "bufio", ".", "NewScanner", "(", "controllersFile", ")", "\n", "sc", ".", "Scan", "(", ")", "\n", "if", "err", ":=", "sc", ".", "Err", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "strings", ".", "Split", "(", "sc", ".", "Text", "(", ")", ",", "\" \"", ")", ",", "nil", "\n", "}" ]
// GetEnabledControllers returns a list of enabled cgroup controllers
[ "GetEnabledControllers", "returns", "a", "list", "of", "enabled", "cgroup", "controllers" ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/common/cgroup/v2/cgroup.go#L30-L45
train
rkt/rkt
tools/depsgen/globcmd.go
globGetArgs
func globGetArgs(args []string) globArgs { f, target := standardFlags(globCmd) suffix := f.String("suffix", "", "File suffix (example: .go)") globbingMode := f.String("glob-mode", "all", "Which files to glob (normal, dot-files, all [default])") filelist := f.String("filelist", "", "Read all the files from this file") var mapTo []string mapToWrapper := common.StringSliceWrapper{Slice: &mapTo} f.Var(&mapToWrapper, "map-to", "Map contents of filelist to this directory, can be used multiple times") f.Parse(args) if *target == "" { common.Die("--target parameter must be specified and cannot be empty") } mode := globModeFromString(*globbingMode) if *filelist == "" { common.Die("--filelist parameter must be specified and cannot be empty") } if len(mapTo) < 1 { common.Die("--map-to parameter must be specified at least once") } return globArgs{ target: *target, suffix: *suffix, mode: mode, filelist: *filelist, mapTo: mapTo, } }
go
func globGetArgs(args []string) globArgs { f, target := standardFlags(globCmd) suffix := f.String("suffix", "", "File suffix (example: .go)") globbingMode := f.String("glob-mode", "all", "Which files to glob (normal, dot-files, all [default])") filelist := f.String("filelist", "", "Read all the files from this file") var mapTo []string mapToWrapper := common.StringSliceWrapper{Slice: &mapTo} f.Var(&mapToWrapper, "map-to", "Map contents of filelist to this directory, can be used multiple times") f.Parse(args) if *target == "" { common.Die("--target parameter must be specified and cannot be empty") } mode := globModeFromString(*globbingMode) if *filelist == "" { common.Die("--filelist parameter must be specified and cannot be empty") } if len(mapTo) < 1 { common.Die("--map-to parameter must be specified at least once") } return globArgs{ target: *target, suffix: *suffix, mode: mode, filelist: *filelist, mapTo: mapTo, } }
[ "func", "globGetArgs", "(", "args", "[", "]", "string", ")", "globArgs", "{", "f", ",", "target", ":=", "standardFlags", "(", "globCmd", ")", "\n", "suffix", ":=", "f", ".", "String", "(", "\"suffix\"", ",", "\"\"", ",", "\"File suffix (example: .go)\"", ")", "\n", "globbingMode", ":=", "f", ".", "String", "(", "\"glob-mode\"", ",", "\"all\"", ",", "\"Which files to glob (normal, dot-files, all [default])\"", ")", "\n", "filelist", ":=", "f", ".", "String", "(", "\"filelist\"", ",", "\"\"", ",", "\"Read all the files from this file\"", ")", "\n", "var", "mapTo", "[", "]", "string", "\n", "mapToWrapper", ":=", "common", ".", "StringSliceWrapper", "{", "Slice", ":", "&", "mapTo", "}", "\n", "f", ".", "Var", "(", "&", "mapToWrapper", ",", "\"map-to\"", ",", "\"Map contents of filelist to this directory, can be used multiple times\"", ")", "\n", "f", ".", "Parse", "(", "args", ")", "\n", "if", "*", "target", "==", "\"\"", "{", "common", ".", "Die", "(", "\"--target parameter must be specified and cannot be empty\"", ")", "\n", "}", "\n", "mode", ":=", "globModeFromString", "(", "*", "globbingMode", ")", "\n", "if", "*", "filelist", "==", "\"\"", "{", "common", ".", "Die", "(", "\"--filelist parameter must be specified and cannot be empty\"", ")", "\n", "}", "\n", "if", "len", "(", "mapTo", ")", "<", "1", "{", "common", ".", "Die", "(", "\"--map-to parameter must be specified at least once\"", ")", "\n", "}", "\n", "return", "globArgs", "{", "target", ":", "*", "target", ",", "suffix", ":", "*", "suffix", ",", "mode", ":", "mode", ",", "filelist", ":", "*", "filelist", ",", "mapTo", ":", "mapTo", ",", "}", "\n", "}" ]
// globGetArgs parses given parameters and returns a target, a suffix // and a list of files.
[ "globGetArgs", "parses", "given", "parameters", "and", "returns", "a", "target", "a", "suffix", "and", "a", "list", "of", "files", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/tools/depsgen/globcmd.go#L76-L103
train
rkt/rkt
tools/depsgen/globcmd.go
globGetMakeFunction
func globGetMakeFunction(files []string, suffix string, mode globMode) string { dirs := map[string]struct{}{} for _, file := range files { dirs[filepath.Dir(file)] = struct{}{} } makeWildcards := make([]string, 0, len(dirs)) wildcard := globGetMakeSnippet(mode) for dir := range dirs { str := replacePlaceholders(wildcard, "SUFFIX", suffix, "DIR", dir) makeWildcards = append(makeWildcards, str) } return replacePlaceholders(globMakeFunction, "WILDCARDS", strings.Join(makeWildcards, " ")) }
go
func globGetMakeFunction(files []string, suffix string, mode globMode) string { dirs := map[string]struct{}{} for _, file := range files { dirs[filepath.Dir(file)] = struct{}{} } makeWildcards := make([]string, 0, len(dirs)) wildcard := globGetMakeSnippet(mode) for dir := range dirs { str := replacePlaceholders(wildcard, "SUFFIX", suffix, "DIR", dir) makeWildcards = append(makeWildcards, str) } return replacePlaceholders(globMakeFunction, "WILDCARDS", strings.Join(makeWildcards, " ")) }
[ "func", "globGetMakeFunction", "(", "files", "[", "]", "string", ",", "suffix", "string", ",", "mode", "globMode", ")", "string", "{", "dirs", ":=", "map", "[", "string", "]", "struct", "{", "}", "{", "}", "\n", "for", "_", ",", "file", ":=", "range", "files", "{", "dirs", "[", "filepath", ".", "Dir", "(", "file", ")", "]", "=", "struct", "{", "}", "{", "}", "\n", "}", "\n", "makeWildcards", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "len", "(", "dirs", ")", ")", "\n", "wildcard", ":=", "globGetMakeSnippet", "(", "mode", ")", "\n", "for", "dir", ":=", "range", "dirs", "{", "str", ":=", "replacePlaceholders", "(", "wildcard", ",", "\"SUFFIX\"", ",", "suffix", ",", "\"DIR\"", ",", "dir", ")", "\n", "makeWildcards", "=", "append", "(", "makeWildcards", ",", "str", ")", "\n", "}", "\n", "return", "replacePlaceholders", "(", "globMakeFunction", ",", "\"WILDCARDS\"", ",", "strings", ".", "Join", "(", "makeWildcards", ",", "\" \"", ")", ")", "\n", "}" ]
// globGetMakeFunction returns a make snippet which calls wildcard // function in all directories where given files are and with a given // suffix.
[ "globGetMakeFunction", "returns", "a", "make", "snippet", "which", "calls", "wildcard", "function", "in", "all", "directories", "where", "given", "files", "are", "and", "with", "a", "given", "suffix", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/tools/depsgen/globcmd.go#L143-L155
train
rkt/rkt
pkg/pod/wait.go
WaitFinished
func (p *Pod) WaitFinished(ctx context.Context) error { f := func() bool { switch err := p.TrySharedLock(); err { case nil: // the pod is now locked successfully, hence one of the running phases passed. // continue with unlocking the pod immediately below. case lock.ErrLocked: // pod is still locked, hence we are still in a running phase. // i.e. in pepare, run, exitedGarbage, garbage state. return false default: // some error occurred, bail out. return true } // unlock immediately if err := p.Unlock(); err != nil { return true } if err := p.refreshState(); err != nil { return true } // if we're in the gap between preparing and running in a split prepare/run-prepared usage, take a nap if p.isPrepared { time.Sleep(time.Second) } return p.IsFinished() } return retry(ctx, f, 100*time.Millisecond) }
go
func (p *Pod) WaitFinished(ctx context.Context) error { f := func() bool { switch err := p.TrySharedLock(); err { case nil: // the pod is now locked successfully, hence one of the running phases passed. // continue with unlocking the pod immediately below. case lock.ErrLocked: // pod is still locked, hence we are still in a running phase. // i.e. in pepare, run, exitedGarbage, garbage state. return false default: // some error occurred, bail out. return true } // unlock immediately if err := p.Unlock(); err != nil { return true } if err := p.refreshState(); err != nil { return true } // if we're in the gap between preparing and running in a split prepare/run-prepared usage, take a nap if p.isPrepared { time.Sleep(time.Second) } return p.IsFinished() } return retry(ctx, f, 100*time.Millisecond) }
[ "func", "(", "p", "*", "Pod", ")", "WaitFinished", "(", "ctx", "context", ".", "Context", ")", "error", "{", "f", ":=", "func", "(", ")", "bool", "{", "switch", "err", ":=", "p", ".", "TrySharedLock", "(", ")", ";", "err", "{", "case", "nil", ":", "case", "lock", ".", "ErrLocked", ":", "return", "false", "\n", "default", ":", "return", "true", "\n", "}", "\n", "if", "err", ":=", "p", ".", "Unlock", "(", ")", ";", "err", "!=", "nil", "{", "return", "true", "\n", "}", "\n", "if", "err", ":=", "p", ".", "refreshState", "(", ")", ";", "err", "!=", "nil", "{", "return", "true", "\n", "}", "\n", "if", "p", ".", "isPrepared", "{", "time", ".", "Sleep", "(", "time", ".", "Second", ")", "\n", "}", "\n", "return", "p", ".", "IsFinished", "(", ")", "\n", "}", "\n", "return", "retry", "(", "ctx", ",", "f", ",", "100", "*", "time", ".", "Millisecond", ")", "\n", "}" ]
// WaitFinished waits for a pod to finish by polling every 100 milliseconds // or until the given context is cancelled. This method refreshes the pod state. // It is the caller's responsibility to determine the actual terminal state.
[ "WaitFinished", "waits", "for", "a", "pod", "to", "finish", "by", "polling", "every", "100", "milliseconds", "or", "until", "the", "given", "context", "is", "cancelled", ".", "This", "method", "refreshes", "the", "pod", "state", ".", "It", "is", "the", "caller", "s", "responsibility", "to", "determine", "the", "actual", "terminal", "state", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/pod/wait.go#L28-L61
train
rkt/rkt
pkg/pod/wait.go
WaitReady
func (p *Pod) WaitReady(ctx context.Context) error { f := func() bool { if err := p.refreshState(); err != nil { return false } return p.IsSupervisorReady() } return retry(ctx, f, 100*time.Millisecond) }
go
func (p *Pod) WaitReady(ctx context.Context) error { f := func() bool { if err := p.refreshState(); err != nil { return false } return p.IsSupervisorReady() } return retry(ctx, f, 100*time.Millisecond) }
[ "func", "(", "p", "*", "Pod", ")", "WaitReady", "(", "ctx", "context", ".", "Context", ")", "error", "{", "f", ":=", "func", "(", ")", "bool", "{", "if", "err", ":=", "p", ".", "refreshState", "(", ")", ";", "err", "!=", "nil", "{", "return", "false", "\n", "}", "\n", "return", "p", ".", "IsSupervisorReady", "(", ")", "\n", "}", "\n", "return", "retry", "(", "ctx", ",", "f", ",", "100", "*", "time", ".", "Millisecond", ")", "\n", "}" ]
// WaitReady blocks until the pod is ready by polling the readiness state every 100 milliseconds // or until the given context is cancelled. This method refreshes the pod state.
[ "WaitReady", "blocks", "until", "the", "pod", "is", "ready", "by", "polling", "the", "readiness", "state", "every", "100", "milliseconds", "or", "until", "the", "given", "context", "is", "cancelled", ".", "This", "method", "refreshes", "the", "pod", "state", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/pod/wait.go#L65-L75
train
rkt/rkt
pkg/pod/wait.go
retry
func retry(ctx context.Context, f func() bool, delay time.Duration) error { if f() { return nil } ticker := time.NewTicker(delay) errChan := make(chan error) go func() { defer close(errChan) for { select { case <-ctx.Done(): errChan <- ctx.Err() return case <-ticker.C: if f() { return } } } }() return <-errChan }
go
func retry(ctx context.Context, f func() bool, delay time.Duration) error { if f() { return nil } ticker := time.NewTicker(delay) errChan := make(chan error) go func() { defer close(errChan) for { select { case <-ctx.Done(): errChan <- ctx.Err() return case <-ticker.C: if f() { return } } } }() return <-errChan }
[ "func", "retry", "(", "ctx", "context", ".", "Context", ",", "f", "func", "(", ")", "bool", ",", "delay", "time", ".", "Duration", ")", "error", "{", "if", "f", "(", ")", "{", "return", "nil", "\n", "}", "\n", "ticker", ":=", "time", ".", "NewTicker", "(", "delay", ")", "\n", "errChan", ":=", "make", "(", "chan", "error", ")", "\n", "go", "func", "(", ")", "{", "defer", "close", "(", "errChan", ")", "\n", "for", "{", "select", "{", "case", "<-", "ctx", ".", "Done", "(", ")", ":", "errChan", "<-", "ctx", ".", "Err", "(", ")", "\n", "return", "\n", "case", "<-", "ticker", ".", "C", ":", "if", "f", "(", ")", "{", "return", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "(", ")", "\n", "return", "<-", "errChan", "\n", "}" ]
// retry calls function f indefinitely with the given delay between invocations // until f returns true or the given context is cancelled. // It returns immediately without delay in case function f immediately returns true.
[ "retry", "calls", "function", "f", "indefinitely", "with", "the", "given", "delay", "between", "invocations", "until", "f", "returns", "true", "or", "the", "given", "context", "is", "cancelled", ".", "It", "returns", "immediately", "without", "delay", "in", "case", "function", "f", "immediately", "returns", "true", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/pod/wait.go#L80-L105
train
rkt/rkt
pkg/fileutil/fileutil.go
DirSize
func DirSize(path string) (int64, error) { seenInode := make(map[uint64]struct{}) if _, err := os.Stat(path); err == nil { var sz int64 err := filepath.Walk(path, func(path string, info os.FileInfo, err error) error { if hasHardLinks(info) { ino := getInode(info) if _, ok := seenInode[ino]; !ok { seenInode[ino] = struct{}{} sz += info.Size() } } else { sz += info.Size() } return err }) return sz, err } return 0, nil }
go
func DirSize(path string) (int64, error) { seenInode := make(map[uint64]struct{}) if _, err := os.Stat(path); err == nil { var sz int64 err := filepath.Walk(path, func(path string, info os.FileInfo, err error) error { if hasHardLinks(info) { ino := getInode(info) if _, ok := seenInode[ino]; !ok { seenInode[ino] = struct{}{} sz += info.Size() } } else { sz += info.Size() } return err }) return sz, err } return 0, nil }
[ "func", "DirSize", "(", "path", "string", ")", "(", "int64", ",", "error", ")", "{", "seenInode", ":=", "make", "(", "map", "[", "uint64", "]", "struct", "{", "}", ")", "\n", "if", "_", ",", "err", ":=", "os", ".", "Stat", "(", "path", ")", ";", "err", "==", "nil", "{", "var", "sz", "int64", "\n", "err", ":=", "filepath", ".", "Walk", "(", "path", ",", "func", "(", "path", "string", ",", "info", "os", ".", "FileInfo", ",", "err", "error", ")", "error", "{", "if", "hasHardLinks", "(", "info", ")", "{", "ino", ":=", "getInode", "(", "info", ")", "\n", "if", "_", ",", "ok", ":=", "seenInode", "[", "ino", "]", ";", "!", "ok", "{", "seenInode", "[", "ino", "]", "=", "struct", "{", "}", "{", "}", "\n", "sz", "+=", "info", ".", "Size", "(", ")", "\n", "}", "\n", "}", "else", "{", "sz", "+=", "info", ".", "Size", "(", ")", "\n", "}", "\n", "return", "err", "\n", "}", ")", "\n", "return", "sz", ",", "err", "\n", "}", "\n", "return", "0", ",", "nil", "\n", "}" ]
// DirSize takes a path and returns its size in bytes
[ "DirSize", "takes", "a", "path", "and", "returns", "its", "size", "in", "bytes" ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/fileutil/fileutil.go#L208-L229
train
rkt/rkt
pkg/fileutil/fileutil.go
IsDeviceNode
func IsDeviceNode(path string) bool { d, err := os.Lstat(path) if err == nil { m := d.Mode() return m&os.ModeDevice == os.ModeDevice } return false }
go
func IsDeviceNode(path string) bool { d, err := os.Lstat(path) if err == nil { m := d.Mode() return m&os.ModeDevice == os.ModeDevice } return false }
[ "func", "IsDeviceNode", "(", "path", "string", ")", "bool", "{", "d", ",", "err", ":=", "os", ".", "Lstat", "(", "path", ")", "\n", "if", "err", "==", "nil", "{", "m", ":=", "d", ".", "Mode", "(", ")", "\n", "return", "m", "&", "os", ".", "ModeDevice", "==", "os", ".", "ModeDevice", "\n", "}", "\n", "return", "false", "\n", "}" ]
// IsDeviceNode checks if the given path points to a block or char device. // It doesn't follow symlinks.
[ "IsDeviceNode", "checks", "if", "the", "given", "path", "points", "to", "a", "block", "or", "char", "device", ".", "It", "doesn", "t", "follow", "symlinks", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/fileutil/fileutil.go#L244-L251
train
rkt/rkt
stage1/init/kvm/hypervisor/hvlkvm/lkvm_driver.go
StartCmd
func StartCmd(wdPath, uuid, kernelPath string, nds []kvm.NetDescriber, cpu, mem int64, debug bool) []string { machineID := strings.Replace(uuid, "-", "", -1) driverConfiguration := hypervisor.KvmHypervisor{ Bin: "./lkvm", KernelParams: []string{ "systemd.default_standard_error=journal+console", "systemd.default_standard_output=journal+console", "systemd.machine_id=" + machineID, }, } driverConfiguration.InitKernelParams(debug) startCmd := []string{ filepath.Join(wdPath, driverConfiguration.Bin), "run", "--name", "rkt-" + uuid, "--no-dhcp", "--cpu", strconv.Itoa(int(cpu)), "--mem", strconv.Itoa(int(mem)), "--console=virtio", "--kernel", kernelPath, "--disk", "stage1/rootfs", // relative to run/pods/uuid dir this is a place where systemd resides "--params", strings.Join(driverConfiguration.KernelParams, " "), } return append(startCmd, kvmNetArgs(nds)...) }
go
func StartCmd(wdPath, uuid, kernelPath string, nds []kvm.NetDescriber, cpu, mem int64, debug bool) []string { machineID := strings.Replace(uuid, "-", "", -1) driverConfiguration := hypervisor.KvmHypervisor{ Bin: "./lkvm", KernelParams: []string{ "systemd.default_standard_error=journal+console", "systemd.default_standard_output=journal+console", "systemd.machine_id=" + machineID, }, } driverConfiguration.InitKernelParams(debug) startCmd := []string{ filepath.Join(wdPath, driverConfiguration.Bin), "run", "--name", "rkt-" + uuid, "--no-dhcp", "--cpu", strconv.Itoa(int(cpu)), "--mem", strconv.Itoa(int(mem)), "--console=virtio", "--kernel", kernelPath, "--disk", "stage1/rootfs", // relative to run/pods/uuid dir this is a place where systemd resides "--params", strings.Join(driverConfiguration.KernelParams, " "), } return append(startCmd, kvmNetArgs(nds)...) }
[ "func", "StartCmd", "(", "wdPath", ",", "uuid", ",", "kernelPath", "string", ",", "nds", "[", "]", "kvm", ".", "NetDescriber", ",", "cpu", ",", "mem", "int64", ",", "debug", "bool", ")", "[", "]", "string", "{", "machineID", ":=", "strings", ".", "Replace", "(", "uuid", ",", "\"-\"", ",", "\"\"", ",", "-", "1", ")", "\n", "driverConfiguration", ":=", "hypervisor", ".", "KvmHypervisor", "{", "Bin", ":", "\"./lkvm\"", ",", "KernelParams", ":", "[", "]", "string", "{", "\"systemd.default_standard_error=journal+console\"", ",", "\"systemd.default_standard_output=journal+console\"", ",", "\"systemd.machine_id=\"", "+", "machineID", ",", "}", ",", "}", "\n", "driverConfiguration", ".", "InitKernelParams", "(", "debug", ")", "\n", "startCmd", ":=", "[", "]", "string", "{", "filepath", ".", "Join", "(", "wdPath", ",", "driverConfiguration", ".", "Bin", ")", ",", "\"run\"", ",", "\"--name\"", ",", "\"rkt-\"", "+", "uuid", ",", "\"--no-dhcp\"", ",", "\"--cpu\"", ",", "strconv", ".", "Itoa", "(", "int", "(", "cpu", ")", ")", ",", "\"--mem\"", ",", "strconv", ".", "Itoa", "(", "int", "(", "mem", ")", ")", ",", "\"--console=virtio\"", ",", "\"--kernel\"", ",", "kernelPath", ",", "\"--disk\"", ",", "\"stage1/rootfs\"", ",", "\"--params\"", ",", "strings", ".", "Join", "(", "driverConfiguration", ".", "KernelParams", ",", "\" \"", ")", ",", "}", "\n", "return", "append", "(", "startCmd", ",", "kvmNetArgs", "(", "nds", ")", "...", ")", "\n", "}" ]
// StartCmd takes path to stage1, UUID of the pod, path to kernel, network // describers, memory in megabytes and quantity of cpus and prepares command // line to run LKVM process
[ "StartCmd", "takes", "path", "to", "stage1", "UUID", "of", "the", "pod", "path", "to", "kernel", "network", "describers", "memory", "in", "megabytes", "and", "quantity", "of", "cpus", "and", "prepares", "command", "line", "to", "run", "LKVM", "process" ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage1/init/kvm/hypervisor/hvlkvm/lkvm_driver.go#L30-L56
train
rkt/rkt
stage1/init/kvm/hypervisor/hvlkvm/lkvm_driver.go
kvmNetArgs
func kvmNetArgs(nds []kvm.NetDescriber) []string { var lkvmArgs []string for _, nd := range nds { lkvmArgs = append(lkvmArgs, "--network") lkvmArgs = append( lkvmArgs, fmt.Sprintf("mode=tap,tapif=%s,host_ip=%s,guest_ip=%s", nd.IfName(), nd.Gateway(), nd.GuestIP()), ) } return lkvmArgs }
go
func kvmNetArgs(nds []kvm.NetDescriber) []string { var lkvmArgs []string for _, nd := range nds { lkvmArgs = append(lkvmArgs, "--network") lkvmArgs = append( lkvmArgs, fmt.Sprintf("mode=tap,tapif=%s,host_ip=%s,guest_ip=%s", nd.IfName(), nd.Gateway(), nd.GuestIP()), ) } return lkvmArgs }
[ "func", "kvmNetArgs", "(", "nds", "[", "]", "kvm", ".", "NetDescriber", ")", "[", "]", "string", "{", "var", "lkvmArgs", "[", "]", "string", "\n", "for", "_", ",", "nd", ":=", "range", "nds", "{", "lkvmArgs", "=", "append", "(", "lkvmArgs", ",", "\"--network\"", ")", "\n", "lkvmArgs", "=", "append", "(", "lkvmArgs", ",", "fmt", ".", "Sprintf", "(", "\"mode=tap,tapif=%s,host_ip=%s,guest_ip=%s\"", ",", "nd", ".", "IfName", "(", ")", ",", "nd", ".", "Gateway", "(", ")", ",", "nd", ".", "GuestIP", "(", ")", ")", ",", ")", "\n", "}", "\n", "return", "lkvmArgs", "\n", "}" ]
// kvmNetArgs returns additional arguments that need to be passed // to lkvm tool to configure networks properly. Logic is based on // network configuration extracted from Networking struct // and essentially from activeNets that expose NetDescriber behavior
[ "kvmNetArgs", "returns", "additional", "arguments", "that", "need", "to", "be", "passed", "to", "lkvm", "tool", "to", "configure", "networks", "properly", ".", "Logic", "is", "based", "on", "network", "configuration", "extracted", "from", "Networking", "struct", "and", "essentially", "from", "activeNets", "that", "expose", "NetDescriber", "behavior" ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage1/init/kvm/hypervisor/hvlkvm/lkvm_driver.go#L62-L74
train