repo
stringlengths
5
67
sha
stringlengths
40
40
path
stringlengths
4
234
url
stringlengths
85
339
language
stringclasses
6 values
split
stringclasses
3 values
doc
stringlengths
3
51.2k
sign
stringlengths
5
8.01k
problem
stringlengths
13
51.2k
output
stringlengths
0
3.87M
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
rkt/api_service.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/api_service.go#L183-L191
go
train
// containsAllKeyValues returns true if the actualKVs contains all of the key-value // pairs listed in requiredKVs, otherwise it returns false.
func containsAllKeyValues(actualKVs []*v1alpha.KeyValue, requiredKVs []*v1alpha.KeyValue) bool
// containsAllKeyValues returns true if the actualKVs contains all of the key-value // pairs listed in requiredKVs, otherwise it returns false. func containsAllKeyValues(actualKVs []*v1alpha.KeyValue, requiredKVs []*v1alpha.KeyValue) bool
{ for _, requiredKV := range requiredKVs { actualValue, ok := findInKeyValues(actualKVs, requiredKV.Key) if !ok || actualValue != requiredKV.Value { return false } } return true }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
rkt/api_service.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/api_service.go#L210-L299
go
train
// satisfiesPodFilter returns true if the pod satisfies the filter. // The pod, filter must not be nil.
func satisfiesPodFilter(pod v1alpha.Pod, filter v1alpha.PodFilter) bool
// satisfiesPodFilter returns true if the pod satisfies the filter. // The pod, filter must not be nil. func satisfiesPodFilter(pod v1alpha.Pod, filter v1alpha.PodFilter) bool
{ // Filter according to the ID. if len(filter.Ids) > 0 { s := set.NewString(filter.Ids...) if !s.Has(pod.Id) { return false } } // Filter according to the state. if len(filter.States) > 0 { foundState := false for _, state := range filter.States { if pod.State == state { foundState = true break } } if !foundState { return false } } // Filter according to the app names. if len(filter.AppNames) > 0 { s := set.NewString() for _, app := range pod.Apps { s.Insert(app.Name) } if !s.HasAll(filter.AppNames...) { return false } } // Filter according to the image IDs. if len(filter.ImageIds) > 0 { s := set.NewString() for _, app := range pod.Apps { s.Insert(app.Image.Id) } if !s.HasAll(filter.ImageIds...) { return false } } // Filter according to the network names. if len(filter.NetworkNames) > 0 { s := set.NewString() for _, network := range pod.Networks { s.Insert(network.Name) } if !s.HasAll(filter.NetworkNames...) { return false } } // Filter according to the annotations. if len(filter.Annotations) > 0 { if !containsAllKeyValues(pod.Annotations, filter.Annotations) { return false } } // Filter according to the cgroup. if len(filter.Cgroups) > 0 { s := set.NewString(filter.Cgroups...) if !s.Has(pod.Cgroup) { return false } } // Filter if pod's cgroup is a prefix of the passed in cgroup if len(filter.PodSubCgroups) > 0 { matched := false if pod.Cgroup != "" { for _, cgroup := range filter.PodSubCgroups { if strings.HasPrefix(cgroup, pod.Cgroup) { matched = true break } } } if !matched { return false } } return true }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
rkt/api_service.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/api_service.go#L303-L315
go
train
// satisfiesAnyPodFilters returns true if any of the filter conditions is satisfied // by the pod, or there's no filters.
func satisfiesAnyPodFilters(pod *v1alpha.Pod, filters []*v1alpha.PodFilter) bool
// satisfiesAnyPodFilters returns true if any of the filter conditions is satisfied // by the pod, or there's no filters. func satisfiesAnyPodFilters(pod *v1alpha.Pod, filters []*v1alpha.PodFilter) bool
{ // No filters, return true directly. if len(filters) == 0 { return true } for _, filter := range filters { if satisfiesPodFilter(*pod, *filter) { return true } } return false }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
rkt/api_service.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/api_service.go#L328-L367
go
train
// getPodCgroup gets the cgroup path for a pod. This can be done in one of a couple ways: // // 1) stage1-coreos // // This one can be tricky because after machined registration, the cgroup might change. // For these flavors, the cgroup it will end up in after machined moves it is // written to a file named `subcgroup`, so we use that instead. // // 2) All others // // Assume that we can simply get the cgroup of the pod's init PID, and use that.
func getPodCgroup(p *pkgPod.Pod, pid int) (string, error)
// getPodCgroup gets the cgroup path for a pod. This can be done in one of a couple ways: // // 1) stage1-coreos // // This one can be tricky because after machined registration, the cgroup might change. // For these flavors, the cgroup it will end up in after machined moves it is // written to a file named `subcgroup`, so we use that instead. // // 2) All others // // Assume that we can simply get the cgroup of the pod's init PID, and use that. func getPodCgroup(p *pkgPod.Pod, pid int) (string, error)
{ // Note, this file should always exist if the pid is known since it is // written before the pid file // The contents are of the form: // machined-registration (whether it has happened or not, but if stage1 plans to do so): // 'machine.slice/machine-rkt\x2dbfb67ff1\x2dc745\x2d4aec\x2db1e1\x2d7ce85a1fd42b.scope' // no registration, ran as systemd-unit 'foo.service': // 'system.slice/foo.service' // stage1-fly: file does not exist subCgroupFile := filepath.Join(p.Path(), "subcgroup") data, err := ioutil.ReadFile(subCgroupFile) // normalize cgroup to include a leading '/' if err == nil { strCgroup := string(data) if strings.HasPrefix(strCgroup, "/") { return strCgroup, nil } return "/" + strCgroup, nil } if !os.IsNotExist(err) { return "", err } // if it is an "isNotExist", assume this is a stage1 flavor that won't change // cgroups. Just give the systemd cgroup of its pid // Get cgroup for the "name=systemd" controller; we assume the api-server is // running on a system using systemd for returning cgroups, and will just not // set it otherwise. cgroup, err := v1.GetCgroupPathByPid(pid, "name=systemd") if err != nil { return "", err } // If the stage1 systemd > v226, it will put the PID1 into "init.scope" // implicit scope unit in the root slice. // See https://github.com/rkt/rkt/pull/2331#issuecomment-203540543 // // TODO(yifan): Revisit this when using unified cgroup hierarchy. cgroup = strings.TrimSuffix(cgroup, "/init.scope") return cgroup, nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
rkt/api_service.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/api_service.go#L370-L393
go
train
// getApplist returns a list of apps in the pod.
func getApplist(manifest *schema.PodManifest) []*v1alpha.App
// getApplist returns a list of apps in the pod. func getApplist(manifest *schema.PodManifest) []*v1alpha.App
{ var apps []*v1alpha.App for _, app := range manifest.Apps { img := &v1alpha.Image{ BaseFormat: &v1alpha.ImageFormat{ // Only support appc image now. If it's a docker image, then it // will be transformed to appc before storing in the disk store. Type: v1alpha.ImageType_IMAGE_TYPE_APPC, Version: schema.AppContainerVersion.String(), }, Id: app.Image.ID.String(), // Only image format and image ID are returned in 'ListPods()'. } apps = append(apps, &v1alpha.App{ Name: app.Name.String(), Image: img, Annotations: convertAnnotationsToKeyValue(app.Annotations), State: v1alpha.AppState_APP_STATE_UNDEFINED, ExitCode: -1, }) } return apps }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
rkt/api_service.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/api_service.go#L396-L406
go
train
// getNetworks returns the list of the info of the network that the pod belongs to.
func getNetworks(p *pkgPod.Pod) []*v1alpha.Network
// getNetworks returns the list of the info of the network that the pod belongs to. func getNetworks(p *pkgPod.Pod) []*v1alpha.Network
{ var networks []*v1alpha.Network for _, n := range p.Nets { networks = append(networks, &v1alpha.Network{ Name: n.NetName, // There will be IPv6 support soon so distinguish between v4 and v6 Ipv4: n.IP.String(), }) } return networks }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
rkt/api_service.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/api_service.go#L419-L456
go
train
// fillStaticAppInfo will modify the 'v1pod' in place with the information retrieved with 'pod'. // Today, these information are static and will not change during the pod's lifecycle.
func fillStaticAppInfo(store *imagestore.Store, pod *pkgPod.Pod, v1pod *v1alpha.Pod) error
// fillStaticAppInfo will modify the 'v1pod' in place with the information retrieved with 'pod'. // Today, these information are static and will not change during the pod's lifecycle. func fillStaticAppInfo(store *imagestore.Store, pod *pkgPod.Pod, v1pod *v1alpha.Pod) error
{ var errlist []error // Fill static app image info. for _, app := range v1pod.Apps { // Fill app's image info. app.Image = &v1alpha.Image{ BaseFormat: &v1alpha.ImageFormat{ // Only support appc image now. If it's a docker image, then it // will be transformed to appc before storing in the disk store. Type: v1alpha.ImageType_IMAGE_TYPE_APPC, Version: schema.AppContainerVersion.String(), }, Id: app.Image.Id, // Other information are not available because they require the image // info from store. Some of it is filled in below if possible. } im, err := pod.AppImageManifest(app.Name) if err != nil { stderr.PrintE(fmt.Sprintf("failed to get image manifests for app %q", app.Name), err) errlist = append(errlist, err) } else { app.Image.Name = im.Name.String() version, ok := im.Labels.Get("version") if !ok { version = "latest" } app.Image.Version = version } } if len(errlist) != 0 { return errs{errlist} } return nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
rkt/api_service.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/api_service.go#L484-L513
go
train
// getBasicPod returns v1alpha.Pod with basic pod information.
func (s *v1AlphaAPIServer) getBasicPod(p *pkgPod.Pod) *v1alpha.Pod
// getBasicPod returns v1alpha.Pod with basic pod information. 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) }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
rkt/api_service.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/api_service.go#L518-L612
go
train
// fillPodDetails fills the v1pod's dynamic info in place, e.g. the pod's state, // the pod's network info, the apps' state, etc. Such information can change // during the lifecycle of the pod, so we need to read it in every request.
func fillPodDetails(store *imagestore.Store, p *pkgPod.Pod, v1pod *v1alpha.Pod)
// fillPodDetails fills the v1pod's dynamic info in place, e.g. the pod's state, // the pod's network info, the apps' state, etc. Such information can change // during the lifecycle of the pod, so we need to read it in every request. func fillPodDetails(store *imagestore.Store, p *pkgPod.Pod, v1pod *v1alpha.Pod)
{ v1pod.Pid = -1 switch p.State() { case pkgPod.Embryo: v1pod.State = v1alpha.PodState_POD_STATE_EMBRYO // When a pod is in embryo state, there is not much // information to return. return case pkgPod.Preparing: v1pod.State = v1alpha.PodState_POD_STATE_PREPARING case pkgPod.AbortedPrepare: v1pod.State = v1alpha.PodState_POD_STATE_ABORTED_PREPARE case pkgPod.Prepared: v1pod.State = v1alpha.PodState_POD_STATE_PREPARED case pkgPod.Running: v1pod.State = v1alpha.PodState_POD_STATE_RUNNING v1pod.Networks = getNetworks(p) case pkgPod.Deleting: v1pod.State = v1alpha.PodState_POD_STATE_DELETING case pkgPod.Exited: v1pod.State = v1alpha.PodState_POD_STATE_EXITED v1pod.Networks = getNetworks(p) case pkgPod.Garbage, pkgPod.ExitedGarbage: v1pod.State = v1alpha.PodState_POD_STATE_GARBAGE default: v1pod.State = v1alpha.PodState_POD_STATE_UNDEFINED return } createdAt, err := p.CreationTime() if err != nil { stderr.PrintE(fmt.Sprintf("failed to get the creation time for pod %q", p.UUID), err) } else if !createdAt.IsZero() { v1pod.CreatedAt = createdAt.UnixNano() } startedAt, err := p.StartTime() if err != nil { stderr.PrintE(fmt.Sprintf("failed to get the start time for pod %q", p.UUID), err) } else if !startedAt.IsZero() { v1pod.StartedAt = startedAt.UnixNano() } gcMarkedAt, err := p.GCMarkedTime() if err != nil { stderr.PrintE(fmt.Sprintf("failed to get the gc marked time for pod %q", p.UUID), err) } else if !gcMarkedAt.IsZero() { v1pod.GcMarkedAt = gcMarkedAt.UnixNano() } pid, err := p.Pid() if err != nil { stderr.PrintE(fmt.Sprintf("failed to get the PID for pod %q", p.UUID), err) } else { v1pod.Pid = int32(pid) } if v1pod.State == v1alpha.PodState_POD_STATE_RUNNING { pid, err := p.ContainerPid1() if err != nil { stderr.PrintE(fmt.Sprintf("failed to get the container PID1 for pod %q", p.UUID), err) } else { cgroup, err := getPodCgroup(p, pid) if err != nil { stderr.PrintE(fmt.Sprintf("failed to get the cgroup path for pod %q", p.UUID), err) } else { v1pod.Cgroup = cgroup } } } for _, app := range v1pod.Apps { readStatus := false if p.State() == pkgPod.Running { readStatus = true app.State = v1alpha.AppState_APP_STATE_RUNNING } else if p.IsAfterRun() { readStatus = true app.State = v1alpha.AppState_APP_STATE_EXITED } else { app.State = v1alpha.AppState_APP_STATE_UNDEFINED } if readStatus { exitCode, err := p.AppExitCode(app.Name) if err != nil && !os.IsNotExist(err) { stderr.PrintE(fmt.Sprintf("failed to read status for app %q", app.Name), err) } app.ExitCode = int32(exitCode) } } }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
rkt/api_service.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/api_service.go#L654-L688
go
train
// aciInfoToV1AlphaAPIImage takes an aciInfo object and construct the v1alpha.Image object.
func aciInfoToV1AlphaAPIImage(store *imagestore.Store, aciInfo *imagestore.ACIInfo) (*v1alpha.Image, error)
// aciInfoToV1AlphaAPIImage takes an aciInfo object and construct the v1alpha.Image object. 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 }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
rkt/api_service.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/api_service.go#L716-L784
go
train
// satisfiesImageFilter returns true if the image satisfies the filter. // The image, filter must not be nil.
func satisfiesImageFilter(image v1alpha.Image, filter v1alpha.ImageFilter) bool
// satisfiesImageFilter returns true if the image satisfies the filter. // The image, filter must not be nil. 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 }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
rkt/api_service.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/api_service.go#L788-L799
go
train
// satisfiesAnyImageFilters returns true if any of the filter conditions is satisfied // by the image, or there's no filters.
func satisfiesAnyImageFilters(image *v1alpha.Image, filters []*v1alpha.ImageFilter) bool
// satisfiesAnyImageFilters returns true if any of the filter conditions is satisfied // by the image, or there's no filters. 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 }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
rkt/api_service.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/api_service.go#L831-L852
go
train
// getImageInfo returns the image info of a given image ID. // It will first try to read the image info from cache. // - If the image exists in cache: // - If the image exists on disk, then return it directly. // - Otherwise, return nil. // - Else, try to return the image from disk.
func (s *v1AlphaAPIServer) getImageInfo(imageID string) (*v1alpha.Image, error)
// getImageInfo returns the image info of a given image ID. // It will first try to read the image info from cache. // - If the image exists in cache: // - If the image exists on disk, then return it directly. // - Otherwise, return nil. // - Else, try to return the image from disk. func (s *v1AlphaAPIServer) getImageInfo(imageID string) (*v1alpha.Image, error)
{ item, found := s.imgCache.Get(imageID) if found { image := item.(*imageCacheItem).image // Check if the image has been removed. if found := s.store.HasFullKey(image.Id); !found { s.imgCache.Remove(imageID) return nil, fmt.Errorf("no such image with ID %q", imageID) } return copyImage(image), nil } image, err := s.getImageInfoFromDisk(s.store, imageID) if err != nil { return nil, err } s.imgCache.Add(imageID, &imageCacheItem{image}) return copyImage(image), err }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
rkt/api_service.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/api_service.go#L855-L868
go
train
// getImageInfoFromDisk for a given image ID, returns the *v1alpha.Image object.
func (s *v1AlphaAPIServer) getImageInfoFromDisk(store *imagestore.Store, imageID string) (*v1alpha.Image, error)
// getImageInfoFromDisk for a given image ID, returns the *v1alpha.Image object. func (s *v1AlphaAPIServer) getImageInfoFromDisk(store *imagestore.Store, imageID string) (*v1alpha.Image, error)
{ aciInfo, err := store.GetACIInfoWithBlobKey(imageID) if err != nil { stderr.PrintE(fmt.Sprintf("failed to get ACI info for image %q", imageID), err) return nil, err } image, err := aciInfoToV1AlphaAPIImage(store, aciInfo) if err != nil { stderr.PrintE(fmt.Sprintf("failed to convert ACI to v1alphaAPIImage for image %q", imageID), err) return nil, err } return image, nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
rkt/api_service.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/api_service.go#L902-L941
go
train
// Open one or more listening sockets, then start the gRPC server
func runAPIService(cmd *cobra.Command, args []string) (exit int)
// Open one or more listening sockets, then start the gRPC server 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 }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
rkt/api_service.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/api_service.go#L947-L978
go
train
// Open API sockets based on command line parameters and // the magic environment variable from systemd // // see sd_listen_fds(3)
func openAPISockets() ([]net.Listener, error)
// Open API sockets based on command line parameters and // the magic environment variable from systemd // // see sd_listen_fds(3) func openAPISockets() ([]net.Listener, error)
{ listeners := []net.Listener{} fds := systemdFDs(true) // Try to get the socket fds from systemd if len(fds) > 0 { if flagAPIServiceListenAddr != "" { return nil, fmt.Errorf("started under systemd.socket(5), but --listen passed! Quitting.") } stderr.Printf("Listening on %d systemd-provided socket(s)\n", len(fds)) for _, fd := range fds { l, err := net.FileListener(fd) if err != nil { return nil, errwrap.Wrap(fmt.Errorf("could not open listener"), err) } listeners = append(listeners, l) } } else { if flagAPIServiceListenAddr == "" { flagAPIServiceListenAddr = common.APIServiceListenAddr } stderr.Printf("Listening on %s\n", flagAPIServiceListenAddr) l, err := net.Listen("tcp", flagAPIServiceListenAddr) if err != nil { return nil, errwrap.Wrap(fmt.Errorf("could not open tcp socket"), err) } listeners = append(listeners, l) } return listeners, nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
stage1/init/common/units.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage1/init/common/units.go#L206-L349
go
train
// SetupAppIO prepares all properties related to streams (stdin/stdout/stderr) and TTY // for an application service unit. // // It works according to the following steps: // 1. short-circuit interactive pods and legacy systemd, for backward compatibility // 2. parse app-level annotations to determine stdin/stdout/stderr mode // 2a. if an annotation is missing/invalid, it fallbacks to legacy mode (in: null, out/err: journald) // 2b. if a valid annotation is found, it prepares: // - TTY and stream properties for the systemd service unit // - env variables for iottymux binary // 3. if any of stdin/stdout/stderr is in TTY or streaming mode: // 3a. the env file for iottymux is written to `/rkt/iottymux/<appname>/env` with the above content // 3b. for TTY mode, a `TTYPath` property and an `After=ttymux@<appname>.service` dependency are added // 3c. for streaming mode, a `Before=iomux@<appname>.service` dependency is added // // For complete details, see dev-docs at Documentation/devel/log-attach-design.md
func (uw *UnitWriter) SetupAppIO(p *stage1commontypes.Pod, ra *schema.RuntimeApp, binPath string, opts ...*unit.UnitOption) []*unit.UnitOption
// SetupAppIO prepares all properties related to streams (stdin/stdout/stderr) and TTY // for an application service unit. // // It works according to the following steps: // 1. short-circuit interactive pods and legacy systemd, for backward compatibility // 2. parse app-level annotations to determine stdin/stdout/stderr mode // 2a. if an annotation is missing/invalid, it fallbacks to legacy mode (in: null, out/err: journald) // 2b. if a valid annotation is found, it prepares: // - TTY and stream properties for the systemd service unit // - env variables for iottymux binary // 3. if any of stdin/stdout/stderr is in TTY or streaming mode: // 3a. the env file for iottymux is written to `/rkt/iottymux/<appname>/env` with the above content // 3b. for TTY mode, a `TTYPath` property and an `After=ttymux@<appname>.service` dependency are added // 3c. for streaming mode, a `Before=iomux@<appname>.service` dependency is added // // For complete details, see dev-docs at Documentation/devel/log-attach-design.md func (uw *UnitWriter) SetupAppIO(p *stage1commontypes.Pod, ra *schema.RuntimeApp, binPath string, opts ...*unit.UnitOption) []*unit.UnitOption
{ if uw.err != nil { return opts } if p.Interactive { opts = append(opts, unit.NewUnitOption("Service", "StandardInput", "tty")) opts = append(opts, unit.NewUnitOption("Service", "StandardOutput", "tty")) opts = append(opts, unit.NewUnitOption("Service", "StandardError", "tty")) return opts } flavor, systemdVersion, err := GetFlavor(uw.p) if err != nil { uw.err = err return opts } stdin, _ := ra.Annotations.Get(stage1commontypes.AppStdinMode) stdout, _ := ra.Annotations.Get(stage1commontypes.AppStdoutMode) stderr, _ := ra.Annotations.Get(stage1commontypes.AppStderrMode) // Attach needs https://github.com/systemd/systemd/pull/4179, ie. systemd v232 or a backport if ((flavor == "src" || flavor == "host") && systemdVersion < 232) || ((flavor == "coreos" || flavor == "kvm") && systemdVersion < 231) { // Explicit error if systemd is too old for attaching if stdin != "" || stdout != "" || stderr != "" { uw.err = fmt.Errorf("stage1 systemd %d does not support attachable I/O", systemdVersion) return opts } opts = append(opts, unit.NewUnitOption("Service", "StandardInput", "null")) opts = append(opts, unit.NewUnitOption("Service", "StandardOutput", "journal+console")) opts = append(opts, unit.NewUnitOption("Service", "StandardError", "journal+console")) return opts } var iottymuxEnvFlags []string needsIOMux := false needsTTYMux := false switch stdin { case "stream": needsIOMux = true uw.AppSocketUnit(ra.Name, binPath, "stdin") iottymuxEnvFlags = append(iottymuxEnvFlags, "STAGE2_STDIN=true") opts = append(opts, unit.NewUnitOption("Service", "StandardInput", "fd")) opts = append(opts, unit.NewUnitOption("Service", "Sockets", fmt.Sprintf("%s-%s.socket", ra.Name, "stdin"))) case "tty": needsTTYMux = true iottymuxEnvFlags = append(iottymuxEnvFlags, "STAGE2_STDIN=true") opts = append(opts, unit.NewUnitOption("Service", "StandardInput", "tty-force")) case "interactive": opts = append(opts, unit.NewUnitOption("Service", "StandardInput", "tty")) default: // null mode opts = append(opts, unit.NewUnitOption("Service", "StandardInput", "null")) } switch stdout { case "stream": needsIOMux = true uw.AppSocketUnit(ra.Name, binPath, "stdout") iottymuxEnvFlags = append(iottymuxEnvFlags, "STAGE2_STDOUT=true") opts = append(opts, unit.NewUnitOption("Service", "StandardOutput", "fd")) opts = append(opts, unit.NewUnitOption("Service", "Sockets", fmt.Sprintf("%s-%s.socket", ra.Name, "stdout"))) case "tty": needsTTYMux = true iottymuxEnvFlags = append(iottymuxEnvFlags, "STAGE2_STDOUT=true") opts = append(opts, unit.NewUnitOption("Service", "StandardOutput", "tty")) case "interactive": opts = append(opts, unit.NewUnitOption("Service", "StandardOutput", "tty")) case "null": opts = append(opts, unit.NewUnitOption("Service", "StandardOutput", "null")) default: // log mode opts = append(opts, unit.NewUnitOption("Service", "StandardOutput", "journal+console")) } switch stderr { case "stream": needsIOMux = true uw.AppSocketUnit(ra.Name, binPath, "stderr") iottymuxEnvFlags = append(iottymuxEnvFlags, "STAGE2_STDERR=true") opts = append(opts, unit.NewUnitOption("Service", "StandardError", "fd")) opts = append(opts, unit.NewUnitOption("Service", "Sockets", fmt.Sprintf("%s-%s.socket", ra.Name, "stderr"))) case "tty": needsTTYMux = true iottymuxEnvFlags = append(iottymuxEnvFlags, "STAGE2_STDERR=true") opts = append(opts, unit.NewUnitOption("Service", "StandardError", "tty")) case "interactive": opts = append(opts, unit.NewUnitOption("Service", "StandardError", "tty")) case "null": opts = append(opts, unit.NewUnitOption("Service", "StandardError", "null")) default: // log mode opts = append(opts, unit.NewUnitOption("Service", "StandardError", "journal+console")) } // if at least one stream requires I/O muxing, an appropriate iottymux dependency needs to be setup if needsIOMux || needsTTYMux { // an env file is written here for iottymux, containing service configuration. appIODir := IOMuxDir(p.Root, ra.Name) os.MkdirAll(appIODir, 0644) file, err := os.OpenFile(filepath.Join(appIODir, "env"), os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644) if err != nil { uw.err = err return nil } defer file.Close() // env file specifies: debug verbosity, which streams to mux and whether a dedicated TTY is needed. file.WriteString(fmt.Sprintf("STAGE2_TTY=%t\n", needsTTYMux)) file.WriteString(fmt.Sprintf("STAGE1_DEBUG=%t\n", p.Debug)) for _, l := range iottymuxEnvFlags { file.WriteString(l + "\n") } if needsIOMux { // streaming mode brings in a `iomux@.service` before-dependency opts = append(opts, unit.NewUnitOption("Unit", "Requires", fmt.Sprintf("iomux@%s.service", ra.Name))) opts = append(opts, unit.NewUnitOption("Unit", "Before", fmt.Sprintf("iomux@%s.service", ra.Name))) logMode, ok := p.Manifest.Annotations.Get("coreos.com/rkt/experiment/logmode") if ok { file.WriteString(fmt.Sprintf("STAGE1_LOGMODE=%s\n", logMode)) } switch logMode { case "k8s-plain": kubernetesLogPath, ok := ra.Annotations.Get("coreos.com/rkt/experiment/kubernetes-log-path") if !ok { uw.err = fmt.Errorf("kubernetes-log-path annotation needs to be specified when k8s-plain logging mode is used") return nil } file.WriteString(fmt.Sprintf("KUBERNETES_LOG_PATH=%s\n", kubernetesLogPath)) } } else if needsTTYMux { // tty mode brings in a `ttymux@.service` after-dependency (it needs to create the TTY first) opts = append(opts, unit.NewUnitOption("Service", "TTYPath", filepath.Join("/rkt/iottymux", ra.Name.String(), "stage2-pts"))) opts = append(opts, unit.NewUnitOption("Unit", "Requires", fmt.Sprintf("ttymux@%s.service", ra.Name))) opts = append(opts, unit.NewUnitOption("Unit", "After", fmt.Sprintf("ttymux@%s.service", ra.Name))) } } return opts }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
stage1/init/common/units.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage1/init/common/units.go#L367-L387
go
train
// WriteUnit writes a systemd unit in the given path with the given unit options // if no previous error occurred.
func (uw *UnitWriter) WriteUnit(path string, errmsg string, opts ...*unit.UnitOption)
// WriteUnit writes a systemd unit in the given path with the given unit options // if no previous error occurred. 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 } }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
stage1/init/common/units.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage1/init/common/units.go#L392-L439
go
train
// 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.
func (uw *UnitWriter) writeShutdownService(exec string, opts ...*unit.UnitOption)
// 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. 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..., ) }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
stage1/init/common/units.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage1/init/common/units.go#L442-L450
go
train
// Activate actives the given unit in the given wantPath.
func (uw *UnitWriter) Activate(unit, wantPath string)
// Activate actives the given unit in the given wantPath. 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) } }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
stage1/init/common/units.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage1/init/common/units.go#L458-L509
go
train
// AppUnit sets up the main systemd service unit for the application.
func (uw *UnitWriter) AppUnit(ra *schema.RuntimeApp, binPath string, opts ...*unit.UnitOption)
// AppUnit sets up the main systemd service unit for the application. 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)) }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
stage1/init/common/units.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage1/init/common/units.go#L512-L734
go
train
// appSystemdUnit sets up an application for isolation via systemd
func (uw *UnitWriter) appSystemdUnit(pa *preparedApp, binPath string, opts []*unit.UnitOption) []*unit.UnitOption
// appSystemdUnit sets up an application for isolation via systemd func (uw *UnitWriter) appSystemdUnit(pa *preparedApp, binPath string, opts []*unit.UnitOption) []*unit.UnitOption
{ if uw.err != nil { return nil } flavor, systemdVersion, err := GetFlavor(uw.p) if err != nil { uw.err = errwrap.Wrap(errors.New("unable to determine stage1 flavor"), err) return nil } ra := pa.app app := ra.App appName := ra.Name imgName := uw.p.AppNameToImageName(ra.Name) podAbsRoot, err := filepath.Abs(uw.p.Root) if err != nil { uw.err = err return nil } var supplementaryGroups []string for _, g := range app.SupplementaryGIDs { supplementaryGroups = append(supplementaryGroups, strconv.Itoa(g)) } // Write env file if err := common.WriteEnvFile(common.ComposeEnviron(pa.env), &uw.p.UidRange, EnvFilePath(uw.p.Root, pa.app.Name)); err != nil { uw.err = errwrap.Wrapf("unable to write environment file", err) return nil } execStart := append([]string{binPath}, app.Exec[1:]...) execStartString := quoteExec(execStart) opts = append(opts, unit.NewUnitOption("Service", "ExecStart", execStartString), unit.NewUnitOption("Service", "RootDirectory", common.RelAppRootfsPath(appName)), unit.NewUnitOption("Service", "WorkingDirectory", app.WorkingDirectory), unit.NewUnitOption("Service", "EnvironmentFile", RelEnvFilePath(appName)), unit.NewUnitOption("Service", "User", strconv.Itoa(int(pa.uid))), unit.NewUnitOption("Service", "Group", strconv.Itoa(int(pa.gid))), unit.NewUnitOption("Service", "PermissionsStartOnly", "true"), unit.NewUnitOption("Unit", "Requires", InstantiatedPrepareAppUnitName(ra.Name)), unit.NewUnitOption("Unit", "After", InstantiatedPrepareAppUnitName(ra.Name)), ) if len(supplementaryGroups) > 0 { opts = appendOptionsList(opts, "Service", "SupplementaryGroups", "", supplementaryGroups...) } if !uw.p.InsecureOptions.DisableCapabilities { opts = append(opts, unit.NewUnitOption("Service", "CapabilityBoundingSet", strings.Join(pa.capabilities, " "))) } // Apply seccomp isolator, if any and not opt-ing out; // see https://www.freedesktop.org/software/systemd/man/systemd.exec.html#SystemCallFilter= if pa.seccomp != nil { opts, err = seccompUnitOptions(opts, pa.seccomp) if err != nil { uw.err = errwrap.Wrapf("unable to apply seccomp options", err) return nil } } opts = append(opts, unit.NewUnitOption("Service", "NoNewPrivileges", strconv.FormatBool(pa.noNewPrivileges))) if ra.ReadOnlyRootFS { for _, m := range pa.mounts { mntPath, err := EvaluateSymlinksInsideApp(podAbsRoot, m.Mount.Path) if err != nil { uw.err = err return nil } if !m.ReadOnly { rwDir := filepath.Join(common.RelAppRootfsPath(ra.Name), mntPath) opts = appendOptionsList(opts, "Service", "ReadWriteDirectories", "", rwDir) } } opts = appendOptionsList(opts, "Service", "ReadOnlyDirectories", "", common.RelAppRootfsPath(ra.Name)) } // Unless we have --insecure-options=paths, then do some path protections: // // * prevent access to sensitive kernel tunables // * Run the app in a separate mount namespace // if !uw.p.InsecureOptions.DisablePaths { // Systemd 231+ has InaccessiblePaths // older versions only have InaccessibleDirectories // Paths prepended with "-" are ignored if they don't exist. if systemdVersion >= 231 { opts = appendOptionsList(opts, "Service", "InaccessiblePaths", "-", pa.relAppPaths(pa.hiddenPaths)...) opts = appendOptionsList(opts, "Service", "InaccessiblePaths", "-", pa.relAppPaths(pa.hiddenDirs)...) opts = appendOptionsList(opts, "Service", "ReadOnlyPaths", "-", pa.relAppPaths(pa.roPaths)...) } else { opts = appendOptionsList(opts, "Service", "InaccessibleDirectories", "-", pa.relAppPaths(pa.hiddenDirs)...) opts = appendOptionsList(opts, "Service", "ReadOnlyDirectories", "-", pa.relAppPaths(pa.roPaths)...) } if systemdVersion >= 233 { // ProtectKernelTunables is introduced in systemd-v232 but didn't work // until v233 due to a systemd bug, see // https://github.com/systemd/systemd/pull/4594 // However, from v233, setting ProtectKernelTunables + RootDirectory causes // MountAPIVFS to be enabled unconditionally, which we don't want. // // opts = append(opts, unit.NewUnitOption("Service", "ProtectKernelTunables", "true")) // MountAPIVFS is introduced in systemd-233. Don't let systemd mount /sys: // it is mounted by prepare-app (tested by TestVolumeSysfs) opts = append(opts, unit.NewUnitOption("Service", "MountAPIVFS", "false")) } // MountFlags=shared creates a new mount namespace and (as unintuitive // as it might seem) makes sure the mount is slave+shared. opts = append(opts, unit.NewUnitOption("Service", "MountFlags", "shared")) } // Generate default device policy for the app, as well as the list of allowed devices. // For kvm flavor, devices are VM-specific and restricting them is not strictly needed. if !uw.p.InsecureOptions.DisablePaths && flavor != "kvm" { opts = append(opts, unit.NewUnitOption("Service", "DevicePolicy", "closed")) deviceAllows, err := generateDeviceAllows(common.Stage1RootfsPath(podAbsRoot), appName, app.MountPoints, pa.mounts, &uw.p.UidRange) if err != nil { uw.err = err return nil } for _, dev := range deviceAllows { opts = append(opts, unit.NewUnitOption("Service", "DeviceAllow", dev)) } } for _, eh := range app.EventHandlers { var typ string switch eh.Name { case "pre-start": typ = "ExecStartPre" case "post-stop": typ = "ExecStopPost" default: uw.err = fmt.Errorf("unrecognized eventHandler: %v", eh.Name) return nil } exec := quoteExec(eh.Exec) opts = append(opts, unit.NewUnitOption("Service", typ, exec)) } // Resource isolators if pa.resources.MemoryLimit != nil { opts = append(opts, unit.NewUnitOption("Service", "MemoryLimit", strconv.FormatUint(*pa.resources.MemoryLimit, 10))) } if pa.resources.CPUQuota != nil { quota := strconv.FormatUint(*pa.resources.CPUQuota, 10) + "%" opts = append(opts, unit.NewUnitOption("Service", "CPUQuota", quota)) } if pa.resources.LinuxCPUShares != nil { opts = append(opts, unit.NewUnitOption("Service", "CPUShares", strconv.FormatUint(*pa.resources.LinuxCPUShares, 10))) } if pa.resources.LinuxOOMScoreAdjust != nil { opts = append(opts, unit.NewUnitOption("Service", "OOMScoreAdjust", strconv.Itoa(*pa.resources.LinuxOOMScoreAdjust))) } var saPorts []types.Port for _, p := range ra.App.Ports { if p.SocketActivated { saPorts = append(saPorts, p) } } if len(saPorts) > 0 { sockopts := []*unit.UnitOption{ unit.NewUnitOption("Unit", "Description", fmt.Sprintf("Application=%v Image=%v %s", appName, imgName, "socket-activated ports")), unit.NewUnitOption("Unit", "DefaultDependencies", "false"), unit.NewUnitOption("Socket", "BindIPv6Only", "both"), unit.NewUnitOption("Socket", "Service", ServiceUnitName(appName)), } for _, sap := range saPorts { var proto string switch sap.Protocol { case "tcp": proto = "ListenStream" case "udp": proto = "ListenDatagram" default: uw.err = fmt.Errorf("unrecognized protocol: %v", sap.Protocol) return nil } // We find the host port for the pod's port and use that in the // socket unit file. // This is so because systemd inside the pod will match based on // the socket port number, and since the socket was created on the // host, it will have the host port number. port := findHostPort(*uw.p.Manifest, sap.Name) if port == 0 { log.Printf("warning: no --port option for socket-activated port %q, assuming port %d as specified in the manifest", sap.Name, sap.Port) port = sap.Port } sockopts = append(sockopts, unit.NewUnitOption("Socket", proto, fmt.Sprintf("%v", port))) } file, err := os.OpenFile(SocketUnitPath(uw.p.Root, appName), os.O_WRONLY|os.O_CREATE, 0644) if err != nil { uw.err = errwrap.Wrap(errors.New("failed to create socket file"), err) return nil } defer file.Close() if _, err = io.Copy(file, unit.Serialize(sockopts)); err != nil { uw.err = errwrap.Wrap(errors.New("failed to write socket unit file"), err) return nil } if err = os.Symlink(path.Join("..", SocketUnitName(appName)), SocketWantPath(uw.p.Root, appName)); err != nil { uw.err = errwrap.Wrap(errors.New("failed to link socket want"), err) return nil } opts = append(opts, unit.NewUnitOption("Unit", "Requires", SocketUnitName(appName))) } return opts }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
stage1/init/common/units.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage1/init/common/units.go#L737-L764
go
train
// AppReaperUnit writes an app reaper service unit for the given app in the given path using the given unit options.
func (uw *UnitWriter) AppReaperUnit(appName types.ACName, binPath string, opts ...*unit.UnitOption)
// AppReaperUnit writes an app reaper service unit for the given app in the given path using the given unit options. 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..., ) }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
stage1/init/common/units.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage1/init/common/units.go#L767-L786
go
train
// AppSocketUnits writes a stream socket-unit for the given app in the given path.
func (uw *UnitWriter) AppSocketUnit(appName types.ACName, binPath string, streamName string, opts ...*unit.UnitOption)
// AppSocketUnits writes a stream socket-unit for the given app in the given path. 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..., ) }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
stage1/init/common/units.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage1/init/common/units.go#L792-L797
go
train
// 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.
func appendOptionsList(opts []*unit.UnitOption, section, property, prefix string, vals ...string) []*unit.UnitOption
// 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. 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 }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
lib/app.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/lib/app.go#L38-L46
go
train
// 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.
func AppsForPod(uuid, dataDir string, appName string) ([]*v1.App, error)
// 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. 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) }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
lib/app.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/lib/app.go#L73-L116
go
train
// newApp constructs the App object with the runtime app and pod manifest.
func newApp(ra *schema.RuntimeApp, podManifest *schema.PodManifest, pod *pkgPod.Pod, appState appStateFunc) (*v1.App, error)
// newApp constructs the App object with the runtime app and pod manifest. 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 }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
lib/app.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/lib/app.go#L200-L237
go
train
// appStateInImmutablePod infers most App state from the Pod itself, since all apps are created and destroyed with the Pod
func appStateInImmutablePod(app *v1.App, pod *pkgPod.Pod) error
// appStateInImmutablePod infers most App state from the Pod itself, since all apps are created and destroyed with the Pod 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 }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
stage1/common/types/pod.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage1/common/types/pod.go#L80-L87
go
train
// AppNameToImageName takes the name of an app in the Pod and returns the name // of the app's image. The mapping between these two is populated when a Pod is // loaded (using LoadPod).
func (p *Pod) AppNameToImageName(appName types.ACName) types.ACIdentifier
// AppNameToImageName takes the name of an app in the Pod and returns the name // of the app's image. The mapping between these two is populated when a Pod is // loaded (using LoadPod). func (p *Pod) AppNameToImageName(appName types.ACName) types.ACIdentifier
{ image, ok := p.Images[appName.String()] if !ok { // This should be impossible as we have updated the map in LoadPod(). panic(fmt.Sprintf("No images for app %q", appName.String())) } return image.Name }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
stage1/common/types/pod.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage1/common/types/pod.go#L91-L99
go
train
// SaveRuntime persists just the runtime state. This should be called when the // pod is started.
func (p *Pod) SaveRuntime() error
// SaveRuntime persists just the runtime state. This should be called when the // pod is started. 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) }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
stage1/common/types/pod.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage1/common/types/pod.go#L102-L113
go
train
// LoadPodManifest loads a Pod Manifest.
func LoadPodManifest(root string) (*schema.PodManifest, error)
// LoadPodManifest loads a Pod Manifest. 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 }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
stage1/common/types/pod.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage1/common/types/pod.go#L117-L179
go
train
// LoadPod loads a Pod Manifest (as prepared by stage0), the runtime data, and // its associated Application Manifests, under $root/stage1/opt/stage1/$apphash
func LoadPod(root string, uuid *types.UUID, rp *RuntimePod) (*Pod, error)
// LoadPod loads a Pod Manifest (as prepared by stage0), the runtime data, and // its associated Application Manifests, under $root/stage1/opt/stage1/$apphash func LoadPod(root string, uuid *types.UUID, rp *RuntimePod) (*Pod, error)
{ p := &Pod{ Root: root, UUID: *uuid, Images: make(map[string]*schema.ImageManifest), UidRange: *user.NewBlankUidRange(), } // Unserialize runtime parameters if rp != nil { p.RuntimePod = *rp } else { buf, err := ioutil.ReadFile(filepath.Join(p.Root, RuntimeConfigPath)) if err != nil { return nil, errwrap.Wrap(errors.New("failed reading runtime params"), err) } if err := json.Unmarshal(buf, &p.RuntimePod); err != nil { return nil, errwrap.Wrap(errors.New("failed unmarshalling runtime params"), err) } } pm, err := LoadPodManifest(p.Root) if err != nil { return nil, err } p.Manifest = pm // ensure volumes names are unique volNames := make(map[types.ACName]bool, len(pm.Volumes)) for _, vol := range pm.Volumes { if volNames[vol.Name] { return nil, fmt.Errorf("duplicate volume name %q", vol.Name) } volNames[vol.Name] = true } for i, app := range p.Manifest.Apps { impath := common.ImageManifestPath(p.Root, app.Name) buf, err := ioutil.ReadFile(impath) if err != nil { return nil, errwrap.Wrap(fmt.Errorf("failed reading image manifest %q", impath), err) } im := &schema.ImageManifest{} if err = json.Unmarshal(buf, im); err != nil { return nil, errwrap.Wrap(fmt.Errorf("failed unmarshalling image manifest %q", impath), err) } if _, ok := p.Images[app.Name.String()]; ok { return nil, fmt.Errorf("got multiple definitions for app: %v", app.Name) } if app.App == nil { p.Manifest.Apps[i].App = im.App } p.Images[app.Name.String()] = im } if err := p.UidRange.Deserialize([]byte(p.PrivateUsers)); err != nil { return nil, err } return p, nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
rkt/image/fetcher.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/image/fetcher.go#L46-L59
go
train
// FetchImages uses FetchImage to attain a list of image hashes
func (f *Fetcher) FetchImages(al *apps.Apps) error
// FetchImages uses FetchImage to attain a list of image hashes 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 }) }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
rkt/image/fetcher.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/image/fetcher.go#L66-L99
go
train
// 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.
func (f *Fetcher) FetchImage(d dist.Distribution, image, ascPath string) (*types.Hash, error)
// 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. 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 }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
rkt/image/fetcher.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/image/fetcher.go#L112-L131
go
train
// fetchImageDeps will recursively fetch all the image dependencies
func (f *Fetcher) fetchImageDeps(hash string) error
// fetchImageDeps will recursively fetch all the image dependencies 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 }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
rkt/image/fetcher.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/image/fetcher.go#L286-L299
go
train
// TODO(sgotti) I'm not sure setting default os and arch also for image // dependencies is correct since it may break noarch dependencies. Reference: // https://github.com/rkt/rkt/pull/2317
func (db *distBundle) setAppDefaults() error
// TODO(sgotti) I'm not sure setting default os and arch also for image // dependencies is correct since it may break noarch dependencies. Reference: // https://github.com/rkt/rkt/pull/2317 func (db *distBundle) setAppDefaults() error
{ app := db.dist.(*dist.Appc).App() if _, ok := app.Labels["arch"]; !ok { app.Labels["arch"] = common.GetArch() } if _, ok := app.Labels["os"]; !ok { app.Labels["os"] = common.GetOS() } if err := types.IsValidOSArch(app.Labels, stage0.ValidOSArch); err != nil { return errwrap.Wrap(fmt.Errorf("invalid Appc distribution %q", db.image), err) } db.dist = dist.NewAppcFromApp(app) return nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
pkg/log/log.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/log/log.go#L35-L42
go
train
// New creates a new Logger with no Log flags set.
func New(out io.Writer, prefix string, debug bool) *Logger
// New creates a new Logger with no Log flags set. 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 }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
pkg/log/log.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/log/log.go#L49-L56
go
train
// NewLogSet returns a set of Loggers for commonly used output streams: errors, // diagnostics, stdout. The error and stdout streams should generally never be // suppressed. diagnostic can be suppressed by setting the output to // ioutil.Discard. If an output destination is not needed, one can simply // discard it by assigning it to '_'.
func NewLogSet(prefix string, debug bool) (stderr, diagnostic, stdout *Logger)
// NewLogSet returns a set of Loggers for commonly used output streams: errors, // diagnostics, stdout. The error and stdout streams should generally never be // suppressed. diagnostic can be suppressed by setting the output to // ioutil.Discard. If an output destination is not needed, one can simply // discard it by assigning it to '_'. func NewLogSet(prefix string, debug bool) (stderr, diagnostic, stdout *Logger)
{ stderr = New(os.Stderr, prefix, debug) diagnostic = New(os.Stderr, prefix, debug) // Debug not used for stdout. stdout = New(os.Stdout, prefix, false) return stderr, diagnostic, stdout }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
pkg/log/log.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/log/log.go#L64-L78
go
train
// SetFlags is a wrapper around log.SetFlags that adds and removes, ": " to and // from a prefix. This is needed because ": " is only added by golang's log // package if either of the Lshortfile or Llongfile flags are set.
func (l *Logger) SetFlags(flag int)
// SetFlags is a wrapper around log.SetFlags that adds and removes, ": " to and // from a prefix. This is needed because ": " is only added by golang's log // package if either of the Lshortfile or Llongfile flags are set. func (l *Logger) SetFlags(flag int)
{ l.Logger.SetFlags(flag) // Only proceed if we've actually got a prefix if l.Prefix() == "" { return } const clnSpc = ": " if flag&(log.Lshortfile|log.Llongfile) != 0 { l.SetPrefix(strings.TrimSuffix(l.Prefix(), clnSpc)) } else { l.SetPrefix(l.Prefix() + clnSpc) } }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
pkg/log/log.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/log/log.go#L105-L107
go
train
// PrintE prints the msg and its error message(s).
func (l *Logger) PrintE(msg string, e error)
// PrintE prints the msg and its error message(s). func (l *Logger) PrintE(msg string, e error)
{ l.Print(l.formatErr(e, msg)) }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
pkg/log/log.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/log/log.go#L110-L112
go
train
// Error is a convenience function for printing errors without a message.
func (l *Logger) Error(e error)
// Error is a convenience function for printing errors without a message. func (l *Logger) Error(e error)
{ l.Print(l.formatErr(e, "")) }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
pkg/log/log.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/log/log.go#L115-L117
go
train
// Errorf is a convenience function for formatting and printing errors.
func (l *Logger) Errorf(format string, a ...interface{})
// Errorf is a convenience function for formatting and printing errors. func (l *Logger) Errorf(format string, a ...interface{})
{ l.Print(l.formatErr(fmt.Errorf(format, a...), "")) }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
pkg/log/log.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/log/log.go#L120-L123
go
train
// FatalE prints a string and error then calls os.Exit(254).
func (l *Logger) FatalE(msg string, e error)
// FatalE prints a string and error then calls os.Exit(254). func (l *Logger) FatalE(msg string, e error)
{ l.Print(l.formatErr(e, msg)) os.Exit(254) }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
pkg/log/log.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/log/log.go#L126-L129
go
train
// Fatalf prints an error then calls os.Exit(254).
func (l *Logger) Fatalf(format string, a ...interface{})
// Fatalf prints an error then calls os.Exit(254). func (l *Logger) Fatalf(format string, a ...interface{})
{ l.Print(l.formatErr(fmt.Errorf(format, a...), "")) os.Exit(254) }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
pkg/log/log.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/log/log.go#L132-L134
go
train
// PanicE prints a string and error then calls panic.
func (l *Logger) PanicE(msg string, e error)
// PanicE prints a string and error then calls panic. func (l *Logger) PanicE(msg string, e error)
{ l.Panic(l.formatErr(e, msg)) }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
tools/common/util.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/tools/common/util.go#L45-L47
go
train
// Warn is just a shorter version of a formatted printing to // stderr. It appends a newline for you.
func Warn(format string, values ...interface{})
// Warn is just a shorter version of a formatted printing to // stderr. It appends a newline for you. func Warn(format string, values ...interface{})
{ fmt.Fprintf(os.Stderr, fmt.Sprintf("%s%c", format, '\n'), values...) }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
tools/common/util.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/tools/common/util.go#L63-L71
go
train
// MapFilesToDirectories creates one entry for each file and directory // passed. Result is a kind of cross-product. For files f1 and f2 and // directories d1 and d2, the returned list will contain d1/f1 d2/f1 // d1/f2 d2/f2. // // The "files" part might be a bit misleading - you can pass a list of // symlinks or directories there as well.
func MapFilesToDirectories(files, dirs []string) []string
// MapFilesToDirectories creates one entry for each file and directory // passed. Result is a kind of cross-product. For files f1 and f2 and // directories d1 and d2, the returned list will contain d1/f1 d2/f1 // d1/f2 d2/f2. // // The "files" part might be a bit misleading - you can pass a list of // symlinks or directories there as well. func MapFilesToDirectories(files, dirs []string) []string
{ mapped := make([]string, 0, len(files)*len(dirs)) for _, f := range files { for _, d := range dirs { mapped = append(mapped, filepath.Join(d, f)) } } return mapped }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
tools/common/util.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/tools/common/util.go#L75-L81
go
train
// MustAbs returns an absolute path. It works like filepath.Abs, but // panics if it fails.
func MustAbs(dir string) string
// MustAbs returns an absolute path. It works like filepath.Abs, but // panics if it fails. 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) }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
rkt/attach.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/attach.go#L119-L183
go
train
// createStage1AttachFlags parses an attach stage0 CLI "--mode" flag and // returns options suited for stage1/attach entrypoint invocation
func createStage1AttachFlags(attachMode string) ([]string, error)
// createStage1AttachFlags parses an attach stage0 CLI "--mode" flag and // returns options suited for stage1/attach entrypoint invocation func createStage1AttachFlags(attachMode string) ([]string, error)
{ attachArgs := []string{} // list mode: just print endpoints if attachMode == "list" { attachArgs = append(attachArgs, "--action=list") return attachArgs, nil } // auto-attach mode: stage1-attach will figure out endpoints if attachMode == "auto" || attachMode == "" { attachArgs = append(attachArgs, "--action=auto-attach") return attachArgs, nil } // custom-attach mode: user specified endpoints var customEndpoints struct { TTYIn bool TTYOut bool Stdin bool Stdout bool Stderr bool } attachArgs = append(attachArgs, "--action=custom-attach") // parse comma-separated endpoints for custom attach eps := strings.Split(attachMode, ",") for _, e := range eps { switch e { case "stdin": customEndpoints.Stdin = true case "stdout": customEndpoints.Stdout = true case "stderr": customEndpoints.Stderr = true case "tty": customEndpoints.TTYIn = true customEndpoints.TTYOut = true case "tty-in": customEndpoints.TTYIn = true case "tty-out": customEndpoints.TTYOut = true default: return nil, fmt.Errorf("unknown endpoint %q", e) } } // check that the resulting attach mode is sane if !(customEndpoints.TTYIn || customEndpoints.TTYOut || customEndpoints.Stdin || customEndpoints.Stdout || customEndpoints.Stderr) { return nil, fmt.Errorf("mode must specify at least one endpoint to attach") } if (customEndpoints.TTYIn || customEndpoints.TTYOut) && (customEndpoints.Stdin || customEndpoints.Stdout || customEndpoints.Stderr) { return nil, fmt.Errorf("incompatible endpoints %q, cannot simultaneously attach TTY and streams", attachMode) } attachArgs = append(attachArgs, fmt.Sprintf("--tty-in=%t", customEndpoints.TTYIn), fmt.Sprintf("--tty-out=%t", customEndpoints.TTYOut), fmt.Sprintf("--stdin=%t", customEndpoints.Stdin), fmt.Sprintf("--stdout=%t", customEndpoints.Stdout), fmt.Sprintf("--stderr=%t", customEndpoints.Stderr), ) return attachArgs, nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
rkt/status.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/status.go#L126-L141
go
train
// 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.
func parseDuration(s string) (time.Duration, error)
// 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. 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 }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
rkt/status.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/status.go#L144-L150
go
train
// newContext returns a new context with timeout t if t > 0.
func newContext(t time.Duration) context.Context
// newContext returns a new context with timeout t if t > 0. func newContext(t time.Duration) context.Context
{ ctx := context.Background() if t > 0 { ctx, _ = context.WithTimeout(ctx, t) } return ctx }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
rkt/status.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/status.go#L153-L168
go
train
// getExitStatuses returns a map of the statuses of the pod.
func getExitStatuses(p *pkgPod.Pod) (map[string]int, error)
// getExitStatuses returns a map of the statuses of the pod. 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 }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
rkt/status.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/status.go#L171-L240
go
train
// printStatus prints the pod's pid and per-app status codes
func printStatus(p *pkgPod.Pod) error
// printStatus prints the pod's pid and per-app status codes 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 }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
stage0/common.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage0/common.go#L48-L109
go
train
// Run wraps the execution of a stage1 entrypoint which // requires crossing the stage0/stage1/stage2 boundary during its execution, // by setting up proper environment variables for enter.
func (ce CrossingEntrypoint) Run() error
// Run wraps the execution of a stage1 entrypoint which // requires crossing the stage0/stage1/stage2 boundary during its execution, // by setting up proper environment variables for enter. func (ce CrossingEntrypoint) Run() error
{ enterCmd, err := getStage1Entrypoint(ce.PodPath, enterEntrypoint) if err != nil { return errwrap.Wrap(errors.New("error determining 'enter' entrypoint"), err) } previousDir, err := os.Getwd() if err != nil { return err } if err := os.Chdir(ce.PodPath); err != nil { return errwrap.Wrap(errors.New("failed changing to dir"), err) } ep, err := getStage1Entrypoint(ce.PodPath, ce.EntrypointName) if err != nil { return fmt.Errorf("%q not implemented for pod's stage1: %v", ce.EntrypointName, err) } execArgs := []string{filepath.Join(common.Stage1RootfsPath(ce.PodPath), ep)} execArgs = append(execArgs, ce.EntrypointArgs...) pathEnv := os.Getenv("PATH") if pathEnv == "" { pathEnv = common.DefaultPath } execEnv := []string{ fmt.Sprintf("%s=%s", common.CrossingEnterCmd, filepath.Join(common.Stage1RootfsPath(ce.PodPath), enterCmd)), fmt.Sprintf("%s=%d", common.CrossingEnterPID, ce.PodPID), fmt.Sprintf("PATH=%s", pathEnv), } c := exec.Cmd{ Path: execArgs[0], Args: execArgs, Env: execEnv, } if ce.Interactive { c.Stdin = os.Stdin c.Stdout = os.Stdout c.Stderr = os.Stderr if err := c.Run(); err != nil { return fmt.Errorf("error executing stage1 entrypoint: %v", err) } } else { out, err := c.CombinedOutput() if len(out) > 0 { debug("%s\n", out) } if err != nil { return errwrap.Wrapf("error executing stage1 entrypoint", err) } } if err := os.Chdir(previousDir); err != nil { return errwrap.Wrap(errors.New("failed changing to dir"), err) } return nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
stage0/common.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage0/common.go#L113-L207
go
train
// generateRuntimeApp merges runtime information from the image manifest and from // runtime configuration overrides, returning a full configuration for a runtime app
func generateRuntimeApp(appRunConfig *apps.App, am *schema.ImageManifest, podMounts []schema.Mount) (schema.RuntimeApp, error)
// generateRuntimeApp merges runtime information from the image manifest and from // runtime configuration overrides, returning a full configuration for a runtime app func generateRuntimeApp(appRunConfig *apps.App, am *schema.ImageManifest, podMounts []schema.Mount) (schema.RuntimeApp, error)
{ ra := schema.RuntimeApp{ App: am.App, Image: schema.RuntimeImage{ Name: &am.Name, ID: appRunConfig.ImageID, Labels: am.Labels, }, Mounts: MergeMounts(podMounts, appRunConfig.Mounts), ReadOnlyRootFS: appRunConfig.ReadOnlyRootFS, } appName, err := types.NewACName(appRunConfig.Name) if err != nil { return ra, errwrap.Wrap(errors.New("invalid app name format"), err) } ra.Name = *appName if appRunConfig.Exec != "" { // Create a minimal App section if not present if am.App == nil { ra.App = &types.App{ User: strconv.Itoa(os.Getuid()), Group: strconv.Itoa(os.Getgid()), } } ra.App.Exec = []string{appRunConfig.Exec} } if appRunConfig.Args != nil { ra.App.Exec = append(ra.App.Exec, appRunConfig.Args...) } if appRunConfig.WorkingDir != "" { ra.App.WorkingDirectory = appRunConfig.WorkingDir } if err := prepareIsolators(appRunConfig, ra.App); err != nil { return ra, err } if appRunConfig.User != "" { ra.App.User = appRunConfig.User } if appRunConfig.Group != "" { ra.App.Group = appRunConfig.Group } if appRunConfig.SupplementaryGIDs != nil { ra.App.SupplementaryGIDs = appRunConfig.SupplementaryGIDs } for k, v := range appRunConfig.Annotations { if _, ok := ra.Annotations.Get(k); ok { continue } kAci, err := types.NewACIdentifier(k) if err != nil { return ra, errwrap.Wrap(fmt.Errorf("error parsing annotation key %q", k), err) } ra.Annotations.Set(*kAci, v) } if appRunConfig.UserAnnotations != nil { ra.App.UserAnnotations = appRunConfig.UserAnnotations } if appRunConfig.UserLabels != nil { ra.App.UserLabels = appRunConfig.UserLabels } if appRunConfig.Stdin != "" { ra.Annotations.Set(stage1types.AppStdinMode, appRunConfig.Stdin.String()) } if appRunConfig.Stdout != "" { ra.Annotations.Set(stage1types.AppStdoutMode, appRunConfig.Stdout.String()) } if appRunConfig.Stderr != "" { ra.Annotations.Set(stage1types.AppStderrMode, appRunConfig.Stderr.String()) } if appRunConfig.Environments != nil { envs := make([]string, 0, len(appRunConfig.Environments)) for name, value := range appRunConfig.Environments { envs = append(envs, fmt.Sprintf("%s=%s", name, value)) } // Let the app level environment override the environment variables. mergeEnvs(&ra.App.Environment, envs, true) } return ra, nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
rkt/image/common.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/image/common.go#L103-L109
go
train
// useCached checks if downloadTime plus maxAge is before/after the current time. // return true if the cached image should be used, false otherwise.
func useCached(downloadTime time.Time, maxAge int) bool
// useCached checks if downloadTime plus maxAge is before/after the current time. // return true if the cached image should be used, false otherwise. func useCached(downloadTime time.Time, maxAge int) bool
{ freshnessLifetime := int(time.Now().Sub(downloadTime).Seconds()) if maxAge > 0 && freshnessLifetime < maxAge { return true } return false }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
rkt/image/common.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/image/common.go#L113-L117
go
train
// ascURLFromImgURL creates a URL to a signature file from passed URL // to an image.
func ascURLFromImgURL(u *url.URL) *url.URL
// ascURLFromImgURL creates a URL to a signature file from passed URL // to an image. func ascURLFromImgURL(u *url.URL) *url.URL
{ copy := *u copy.Path = ascPathFromImgPath(copy.Path) return &copy }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
rkt/image/common.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/image/common.go#L126-L132
go
train
// printIdentities prints a message that signature was verified.
func printIdentities(entity *openpgp.Entity)
// printIdentities prints a message that signature was verified. 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")) }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
rkt/image/common.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/image/common.go#L135-L203
go
train
// DistFromImageString return the distribution for the given input image string
func DistFromImageString(is string) (dist.Distribution, error)
// DistFromImageString return the distribution for the given input image string 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) }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
pkg/distribution/cimd.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/distribution/cimd.go#L34-L51
go
train
// parseCIMD parses the given url and returns a cimd.
func parseCIMD(u *url.URL) (*cimd, error)
// parseCIMD parses the given url and returns a cimd. 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 }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
pkg/distribution/cimd.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/distribution/cimd.go#L54-L56
go
train
// NewCIMDString creates a new cimd URL string.
func NewCIMDString(typ Type, version uint32, data string) string
// NewCIMDString creates a new cimd URL string. func NewCIMDString(typ Type, version uint32, data string) string
{ return fmt.Sprintf("%s:%s:v=%d:%s", Scheme, typ, version, data) }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
rkt/export.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/export.go#L164-L199
go
train
// 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
func getApp(p *pkgPod.Pod) (*schema.RuntimeApp, error)
// 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 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= ...\"") }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
rkt/export.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/export.go#L202-L240
go
train
// mountOverlay mounts the app from the overlay-rendered pod to the destination directory.
func mountOverlay(pod *pkgPod.Pod, app *schema.RuntimeApp, dest string) error
// mountOverlay mounts the app from the overlay-rendered pod to the destination directory. 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 }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
rkt/export.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/export.go#L244-L306
go
train
// buildAci builds a target aci from the root directory using any uid shift // information from uidRange.
func buildAci(root, manifestPath, target string, uidRange *user.UidRange) (e error)
// buildAci builds a target aci from the root directory using any uid shift // information from uidRange. 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 }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
rkt/rkt.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/rkt.go#L176-L188
go
train
// runWrapper returns a func(cmd *cobra.Command, args []string) that internally // will add command function return code and the reinsertion of the "--" flag // terminator.
func runWrapper(cf func(cmd *cobra.Command, args []string) (exit int)) func(cmd *cobra.Command, args []string)
// runWrapper returns a func(cmd *cobra.Command, args []string) that internally // will add command function return code and the reinsertion of the "--" flag // terminator. func runWrapper(cf func(cmd *cobra.Command, args []string) (exit int)) func(cmd *cobra.Command, args []string)
{ return func(cmd *cobra.Command, args []string) { cpufile, memfile, err := startProfile() if err != nil { stderr.PrintE("cannot setup profiling", err) cmdExitCode = 254 return } defer stopProfile(cpufile, memfile) cmdExitCode = cf(cmd, args) } }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
rkt/rkt.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/rkt.go#L192-L202
go
train
// ensureSuperuser will error out if the effective UID of the current process // is not zero. Otherwise, it will invoke the supplied cobra command.
func ensureSuperuser(cf func(cmd *cobra.Command, args []string)) func(cmd *cobra.Command, args []string)
// ensureSuperuser will error out if the effective UID of the current process // is not zero. Otherwise, it will invoke the supplied cobra command. 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) } }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
stage1/init/common/seccomp.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage1/init/common/seccomp.go#L58-L107
go
train
// generateSeccompFilter computes the concrete seccomp filter from the isolators
func generateSeccompFilter(p *stage1commontypes.Pod, pa *preparedApp) (*seccompFilter, error)
// generateSeccompFilter computes the concrete seccomp filter from the isolators 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 }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
stage1/init/common/seccomp.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage1/init/common/seccomp.go#L110-L132
go
train
// seccompUnitOptions converts a concrete seccomp filter to systemd unit options
func seccompUnitOptions(opts []*unit.UnitOption, sf *seccompFilter) ([]*unit.UnitOption, error)
// seccompUnitOptions converts a concrete seccomp filter to systemd unit options 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 }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
stage1/init/common/seccomp.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage1/init/common/seccomp.go#L136-L202
go
train
// parseLinuxSeccompSet gets an appc LinuxSeccompSet and returns an array // of values suitable for systemd SystemCallFilter.
func parseLinuxSeccompSet(p *stage1commontypes.Pod, s types.LinuxSeccompSet) (syscallFilter []string, flag string, err error)
// parseLinuxSeccompSet gets an appc LinuxSeccompSet and returns an array // of values suitable for systemd SystemCallFilter. 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 }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
stage1/app_rm/app_rm.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage1/app_rm/app_rm.go#L56-L88
go
train
// 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.
func main()
// 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. 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) }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
stage1/app_rm/app_rm.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage1/app_rm/app_rm.go#L96-L151
go
train
// cleanupStage0 is the default initial step for rm entrypoint, which takes // care of cleaning up resources in stage0 and calling into stage1 by: // 1. ensuring that the service has been stopped // 2. removing unit files // 3. calling itself in stage1 for further cleanups // 4. calling `systemctl daemon-reload` in stage1
func cleanupStage0(appName *types.ACName, enterCmd []string) error
// cleanupStage0 is the default initial step for rm entrypoint, which takes // care of cleaning up resources in stage0 and calling into stage1 by: // 1. ensuring that the service has been stopped // 2. removing unit files // 3. calling itself in stage1 for further cleanups // 4. calling `systemctl daemon-reload` in stage1 func cleanupStage0(appName *types.ACName, enterCmd []string) error
{ args := enterCmd args = append(args, "/usr/bin/systemctl") args = append(args, "is-active") args = append(args, appName.String()) cmd := exec.Cmd{ Path: args[0], Args: args, } // rely only on the output, since is-active returns non-zero for inactive units out, _ := cmd.Output() switch string(out) { case "failed\n": case "inactive\n": default: return fmt.Errorf("app %q is still running", appName.String()) } s1rootfs := common.Stage1RootfsPath(".") serviceDir := filepath.Join(s1rootfs, "usr", "lib", "systemd", "system") appServicePaths := []string{ filepath.Join(serviceDir, appName.String()+".service"), filepath.Join(serviceDir, "reaper-"+appName.String()+".service"), } for _, p := range appServicePaths { if err := os.Remove(p); err != nil && !os.IsNotExist(err) { return fmt.Errorf("error removing app service file: %s", err) } } // TODO(sur): find all RW cgroups exposed for this app and clean them up in stage0 context // last cleaning steps are performed after entering pod context tasks := [][]string{ // inception: call itself to clean stage1 before proceeding {"/app_rm", "--stage=1", fmt.Sprintf("--app=%s", appName), fmt.Sprintf("--debug=%t", debug)}, // all cleaned-up, let systemd reload and forget about this app {"/usr/bin/systemctl", "daemon-reload"}, } for _, cmdLine := range tasks { args := append(enterCmd, cmdLine...) cmd = exec.Cmd{ Path: args[0], Args: args, } if out, err := cmd.CombinedOutput(); err != nil { return fmt.Errorf("%q removal failed:\n%s", appName, out) } } return nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
stage1/app_rm/app_rm.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage1/app_rm/app_rm.go#L155-L176
go
train
// 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.
func cleanupStage1(appName *types.ACName, enterCmd []string) error
// 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. 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 }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
rkt/gc.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/gc.go#L102-L115
go
train
// renameExited renames exited pods to the exitedGarbage directory
func renameExited() error
// renameExited renames exited pods to the exitedGarbage directory 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 }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
rkt/gc.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/gc.go#L118-L144
go
train
// emptyExitedGarbage discards sufficiently aged pods from exitedGarbageDir()
func emptyExitedGarbage(gracePeriod time.Duration) error
// emptyExitedGarbage discards sufficiently aged pods from exitedGarbageDir() func emptyExitedGarbage(gracePeriod time.Duration) error
{ if err := pkgPod.WalkPods(getDataDir(), pkgPod.IncludeExitedGarbageDir, func(p *pkgPod.Pod) { gp := p.Path() st := &syscall.Stat_t{} if err := syscall.Lstat(gp, st); err != nil { if err != syscall.ENOENT { stderr.PrintE(fmt.Sprintf("unable to stat %q, ignoring", gp), err) } return } if expiration := time.Unix(st.Ctim.Unix()).Add(gracePeriod); time.Now().After(expiration) { if err := p.ExclusiveLock(); err != nil { return } stdout.Printf("Garbage collecting pod %q", p.UUID) deletePod(p) } else { stderr.Printf("pod %q not removed: still within grace period (%s)", p.UUID, gracePeriod) } }); err != nil { return err } return nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
rkt/gc.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/gc.go#L147-L159
go
train
// renameAborted renames failed prepares to the garbage directory
func renameAborted() error
// renameAborted renames failed prepares to the garbage directory 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 }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
rkt/gc.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/gc.go#L162-L183
go
train
// renameExpired renames expired prepared pods to the garbage directory
func renameExpired(preparedExpiration time.Duration) error
// renameExpired renames expired prepared pods to the garbage directory 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 }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
rkt/gc.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/gc.go#L186-L199
go
train
// emptyGarbage discards everything from garbageDir()
func emptyGarbage() error
// emptyGarbage discards everything from garbageDir() func emptyGarbage() error
{ if err := pkgPod.WalkPods(getDataDir(), pkgPod.IncludeGarbageDir, func(p *pkgPod.Pod) { if err := p.ExclusiveLock(); err != nil { return } stdout.Printf("Garbage collecting pod %q", p.UUID) deletePod(p) }); err != nil { return err } return nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
rkt/gc.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/gc.go#L207-L246
go
train
// mountPodStage1 tries to remount stage1 image overlay in case // it is not anymore available in place (e.g. a reboot happened // in-between). If an overlay mount is already there, we assume // stage1 image is properly in place and we don't perform any // further actions. A boolean is returned to signal whether a // a new mount was performed.
func mountPodStage1(ts *treestore.Store, p *pkgPod.Pod) (bool, error)
// mountPodStage1 tries to remount stage1 image overlay in case // it is not anymore available in place (e.g. a reboot happened // in-between). If an overlay mount is already there, we assume // stage1 image is properly in place and we don't perform any // further actions. A boolean is returned to signal whether a // a new mount was performed. func mountPodStage1(ts *treestore.Store, p *pkgPod.Pod) (bool, error)
{ if !p.UsesOverlay() { return false, nil } s1Id, err := p.GetStage1TreeStoreID() if err != nil { return false, errwrap.Wrap(errors.New("error getting stage1 treeStoreID"), err) } s1rootfs := ts.GetRootFS(s1Id) stage1Dir := common.Stage1RootfsPath(p.Path()) if mounts, err := mountinfo.ParseMounts(0); err == nil { for _, m := range mounts { if m.MountPoint == stage1Dir { // stage1 image overlay already in place return false, nil } } } overlayDir := filepath.Join(p.Path(), "overlay") imgDir := filepath.Join(overlayDir, s1Id) upperDir := filepath.Join(imgDir, "upper") workDir := filepath.Join(imgDir, "work") opts := fmt.Sprintf("lowerdir=%s,upperdir=%s,workdir=%s", s1rootfs, upperDir, workDir) err = syscall.Mount("overlay", stage1Dir, "overlay", 0, opts) if err != nil { // -EBUSY means the overlay mount is already present. // This behavior was introduced in Linux 4.13, double-mounts were allowed // in older kernels. if err == syscall.EBUSY { stderr.Println("mount detected on stage1 target, skipping overlay mount") return false, nil } return false, errwrap.Wrap(errors.New("error mounting stage1"), err) } return true, nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
rkt/gc.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/gc.go#L251-L316
go
train
// deletePod cleans up files and resource associated with the pod // pod must be under exclusive lock and be in either ExitedGarbage // or Garbage state
func deletePod(p *pkgPod.Pod) bool
// deletePod cleans up files and resource associated with the pod // pod must be under exclusive lock and be in either ExitedGarbage // or Garbage state 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 }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
store/imagestore/store.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/store/imagestore/store.go#L283-L289
go
train
// backupDB backs up current database.
func (s *Store) backupDB() error
// backupDB backs up current database. 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) }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
store/imagestore/store.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/store/imagestore/store.go#L298-L304
go
train
// TODO(sgotti), unexport this and provide other functions for external users // TmpFile returns an *os.File local to the same filesystem as the Store, or // any error encountered
func (s *Store) TmpFile() (*os.File, error)
// TODO(sgotti), unexport this and provide other functions for external users // TmpFile returns an *os.File local to the same filesystem as the Store, or // any error encountered func (s *Store) TmpFile() (*os.File, error)
{ dir, err := s.TmpDir() if err != nil { return nil, err } return ioutil.TempFile(dir, "") }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
store/imagestore/store.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/store/imagestore/store.go#L311-L325
go
train
// TODO(sgotti), unexport this and provide other functions for external users // TmpNamedFile returns an *os.File with the specified name local to the same // filesystem as the Store, or any error encountered. If the file already // exists it will return the existing file in read/write mode with the cursor // at the end of the file.
func (s Store) TmpNamedFile(name string) (*os.File, error)
// TODO(sgotti), unexport this and provide other functions for external users // TmpNamedFile returns an *os.File with the specified name local to the same // filesystem as the Store, or any error encountered. If the file already // exists it will return the existing file in read/write mode with the cursor // at the end of the file. func (s Store) TmpNamedFile(name string) (*os.File, error)
{ dir, err := s.TmpDir() if err != nil { return nil, err } fname := filepath.Join(dir, name) _, err = os.Stat(fname) if os.IsNotExist(err) { return os.Create(fname) } if err != nil { return nil, err } return os.OpenFile(fname, os.O_RDWR|os.O_APPEND, 0644) }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
store/imagestore/store.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/store/imagestore/store.go#L330-L336
go
train
// TODO(sgotti), unexport this and provide other functions for external users // TmpDir creates and returns dir local to the same filesystem as the Store, // or any error encountered
func (s *Store) TmpDir() (string, error)
// TODO(sgotti), unexport this and provide other functions for external users // TmpDir creates and returns dir local to the same filesystem as the Store, // or any error encountered func (s *Store) TmpDir() (string, error)
{ dir := filepath.Join(s.dir, "tmp") if err := os.MkdirAll(dir, defaultPathPerm); err != nil { return "", err } return dir, nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
store/imagestore/store.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/store/imagestore/store.go#L341-L370
go
train
// ResolveKey resolves a partial key (of format `sha512-0c45e8c0ab2`) to a full // key by considering the key a prefix and using the store for resolution. // If the key is longer than the full key length, it is first truncated.
func (s *Store) ResolveKey(key string) (string, error)
// ResolveKey resolves a partial key (of format `sha512-0c45e8c0ab2`) to a full // key by considering the key a prefix and using the store for resolution. // If the key is longer than the full key length, it is first truncated. func (s *Store) ResolveKey(key string) (string, error)
{ if !strings.HasPrefix(key, hashPrefix) { return "", fmt.Errorf("wrong key prefix") } if len(key) < minlenKey { return "", fmt.Errorf("image ID too short") } if len(key) > lenKey { key = key[:lenKey] } var aciInfos []*ACIInfo err := s.db.Do(func(tx *sql.Tx) error { var err error aciInfos, err = GetACIInfosWithKeyPrefix(tx, key) return err }) if err != nil { return "", errwrap.Wrap(errors.New("error retrieving ACI Infos"), err) } keyCount := len(aciInfos) if keyCount == 0 { return "", ErrKeyNotFound } if keyCount != 1 { return "", fmt.Errorf("ambiguous image ID: %q", key) } return aciInfos[0].BlobKey, nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
store/imagestore/store.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/store/imagestore/store.go#L374-L394
go
train
// ResolveName resolves an image name to a list of full keys and using the // store for resolution.
func (s *Store) ResolveName(name string) ([]string, bool, error)
// ResolveName resolves an image name to a list of full keys and using the // store for resolution. 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 }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
store/imagestore/store.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/store/imagestore/store.go#L431-L500
go
train
// WriteACI takes an ACI encapsulated in an io.Reader, decompresses it if // necessary, and then stores it in the store under a key based on the image ID // (i.e. the hash of the uncompressed ACI) // latest defines if the aci has to be marked as the latest. For example an ACI // discovered without asking for a specific version (latest pattern).
func (s *Store) WriteACI(r io.ReadSeeker, fetchInfo ACIFetchInfo) (string, error)
// WriteACI takes an ACI encapsulated in an io.Reader, decompresses it if // necessary, and then stores it in the store under a key based on the image ID // (i.e. the hash of the uncompressed ACI) // latest defines if the aci has to be marked as the latest. For example an ACI // discovered without asking for a specific version (latest pattern). func (s *Store) WriteACI(r io.ReadSeeker, fetchInfo ACIFetchInfo) (string, error)
{ // We need to allow the store's setgid bits (if any) to propagate, so // disable umask um := syscall.Umask(0) defer syscall.Umask(um) dr, err := aci.NewCompressedReader(r) if err != nil { return "", errwrap.Wrap(errors.New("error decompressing image"), err) } defer dr.Close() // Write the decompressed image (tar) to a temporary file on disk, and // tee so we can generate the hash h := sha512.New() tr := io.TeeReader(dr, h) fh, err := s.TmpFile() if err != nil { return "", errwrap.Wrap(errors.New("error creating image"), err) } sz, err := io.Copy(fh, tr) if err != nil { return "", errwrap.Wrap(errors.New("error copying image"), err) } im, err := aci.ManifestFromImage(fh) if err != nil { return "", errwrap.Wrap(errors.New("error extracting image manifest"), err) } if err := fh.Close(); err != nil { return "", errwrap.Wrap(errors.New("error closing image"), err) } // Import the uncompressed image into the store at the real key key := s.HashToKey(h) keyLock, err := lock.ExclusiveKeyLock(s.imageLockDir, key) if err != nil { return "", errwrap.Wrap(errors.New("error locking image"), err) } defer keyLock.Close() if err = s.stores[blobType].Import(fh.Name(), key, true); err != nil { return "", errwrap.Wrap(errors.New("error importing image"), err) } // Save the imagemanifest using the same key used for the image imj, err := json.Marshal(im) if err != nil { return "", errwrap.Wrap(errors.New("error marshalling image manifest"), err) } if err := s.stores[imageManifestType].Write(key, imj); err != nil { return "", errwrap.Wrap(errors.New("error importing image manifest"), err) } // Save aciinfo if err = s.db.Do(func(tx *sql.Tx) error { aciinfo := &ACIInfo{ BlobKey: key, Name: im.Name.String(), ImportTime: time.Now(), LastUsed: time.Now(), Latest: fetchInfo.Latest, Size: sz, } return WriteACIInfo(tx, aciinfo) }); err != nil { return "", errwrap.Wrap(errors.New("error writing ACI Info"), err) } return key, nil }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
store/imagestore/store.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/store/imagestore/store.go#L506-L551
go
train
// 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.
func (s *Store) RemoveACI(key string) error
// 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. 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 }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
store/imagestore/store.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/store/imagestore/store.go#L555-L570
go
train
// GetRemote tries to retrieve a remote with the given ACIURL. // If remote doesn't exist, it returns ErrRemoteNotFound error.
func (s *Store) GetRemote(aciURL string) (*Remote, error)
// GetRemote tries to retrieve a remote with the given ACIURL. // If remote doesn't exist, it returns ErrRemoteNotFound error. 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 }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
store/imagestore/store.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/store/imagestore/store.go#L573-L578
go
train
// WriteRemote adds or updates the provided Remote.
func (s *Store) WriteRemote(remote *Remote) error
// WriteRemote adds or updates the provided Remote. func (s *Store) WriteRemote(remote *Remote) error
{ err := s.db.Do(func(tx *sql.Tx) error { return WriteRemote(tx, remote) }) return err }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
store/imagestore/store.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/store/imagestore/store.go#L582-L598
go
train
// GetImageManifestJSON gets the ImageManifest JSON bytes with the // specified key.
func (s *Store) GetImageManifestJSON(key string) ([]byte, error)
// GetImageManifestJSON gets the ImageManifest JSON bytes with the // specified key. 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 }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
store/imagestore/store.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/store/imagestore/store.go#L601-L611
go
train
// GetImageManifest gets the ImageManifest with the specified key.
func (s *Store) GetImageManifest(key string) (*schema.ImageManifest, error)
// GetImageManifest gets the ImageManifest with the specified key. 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 }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
store/imagestore/store.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/store/imagestore/store.go#L619-L681
go
train
// GetACI retrieves the ACI that best matches the provided app name and labels. // The returned value is the blob store key of the retrieved ACI. // If there are multiple matching ACIs choose the latest one (defined as the // last one imported in the store). // If no version label is requested, ACIs marked as latest in the ACIInfo are // preferred.
func (s *Store) GetACI(name types.ACIdentifier, labels types.Labels) (string, error)
// GetACI retrieves the ACI that best matches the provided app name and labels. // The returned value is the blob store key of the retrieved ACI. // If there are multiple matching ACIs choose the latest one (defined as the // last one imported in the store). // If no version label is requested, ACIs marked as latest in the ACIInfo are // preferred. func (s *Store) GetACI(name types.ACIdentifier, labels types.Labels) (string, error)
{ var curaciinfo *ACIInfo versionRequested := false if _, ok := labels.Get("version"); ok { versionRequested = true } var aciinfos []*ACIInfo err := s.db.Do(func(tx *sql.Tx) error { var err error aciinfos, _, err = GetACIInfosWithName(tx, name.String()) return err }) if err != nil { return "", err } nextKey: for _, aciinfo := range aciinfos { im, err := s.GetImageManifest(aciinfo.BlobKey) if err != nil { return "", errwrap.Wrap(errors.New("error getting image manifest"), err) } // The image manifest must have all the requested labels for _, l := range labels { ok := false for _, rl := range im.Labels { if l.Name == rl.Name && l.Value == rl.Value { ok = true break } } if !ok { continue nextKey } } if curaciinfo != nil { // If no version is requested prefer the acis marked as latest if !versionRequested { if !curaciinfo.Latest && aciinfo.Latest { curaciinfo = aciinfo continue nextKey } if curaciinfo.Latest && !aciinfo.Latest { continue nextKey } } // If multiple matching image manifests are found, choose the latest imported in the cas. if aciinfo.ImportTime.After(curaciinfo.ImportTime) { curaciinfo = aciinfo } } else { curaciinfo = aciinfo } } if curaciinfo != nil { return curaciinfo.BlobKey, nil } return "", ACINotFoundError{name: name, labels: labels} }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
store/imagestore/store.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/store/imagestore/store.go#L756-L758
go
train
// HasFullKey returns whether the image with the given key exists on the disk by // checking if the image manifest kv store contains the key.
func (s *Store) HasFullKey(key string) bool
// HasFullKey returns whether the image with the given key exists on the disk by // checking if the image manifest kv store contains the key. func (s *Store) HasFullKey(key string) bool
{ return s.stores[imageManifestType].Has(key) }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
store/imagestore/store.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/store/imagestore/store.go#L766-L771
go
train
// keyToString takes a key and returns a shortened and prefixed hexadecimal string version
func keyToString(k []byte) string
// keyToString takes a key and returns a shortened and prefixed hexadecimal string version 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] }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
rkt/image/downloader.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/image/downloader.go#L54-L86
go
train
// Download tries to fetch the passed URL and write the contents into // a given writeSyncer instance.
func (d *downloader) Download(u *url.URL, out writeSyncer) error
// Download tries to fetch the passed URL and write the contents into // a given writeSyncer instance. 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 }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
rkt/enter.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/enter.go#L128-L153
go
train
// 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
func getAppName(p *pkgPod.Pod) (*types.ACName, error)
// 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 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= ...\"") }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
rkt/enter.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/enter.go#L156-L166
go
train
// getEnterArgv returns the argv to use for entering the pod
func getEnterArgv(p *pkgPod.Pod, cmdArgs []string) ([]string, error)
// getEnterArgv returns the argv to use for entering the pod 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 }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
common/cgroup/v1/cgroup.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/common/cgroup/v1/cgroup.go#L36-L47
go
train
// mountFsRO remounts the given mountPoint using the given flags read-only.
func mountFsRO(m fs.Mounter, mountPoint string, flags uintptr) error
// mountFsRO remounts the given mountPoint using the given flags read-only. 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 }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
common/cgroup/v1/cgroup.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/common/cgroup/v1/cgroup.go#L81-L94
go
train
// GetEnabledCgroups returns a map with the enabled cgroup controllers grouped by // hierarchy
func GetEnabledCgroups() (map[int][]string, error)
// GetEnabledCgroups returns a map with the enabled cgroup controllers grouped by // hierarchy 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 }
rkt/rkt
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
common/cgroup/v1/cgroup.go
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/common/cgroup/v1/cgroup.go#L99-L106
go
train
// GetControllerDirs takes a map with the enabled cgroup controllers grouped by // hierarchy and returns the directory names as they should be in // /sys/fs/cgroup
func GetControllerDirs(cgroups map[int][]string) []string
// GetControllerDirs takes a map with the enabled cgroup controllers grouped by // hierarchy and returns the directory names as they should be in // /sys/fs/cgroup func GetControllerDirs(cgroups map[int][]string) []string
{ var controllers []string for _, cs := range cgroups { controllers = append(controllers, strings.Join(cs, ",")) } return controllers }