id
int32
0
167k
repo
stringlengths
5
54
path
stringlengths
4
155
func_name
stringlengths
1
118
original_string
stringlengths
52
85.5k
language
stringclasses
1 value
code
stringlengths
52
85.5k
code_tokens
listlengths
21
1.41k
docstring
stringlengths
6
2.61k
docstring_tokens
listlengths
3
215
sha
stringlengths
40
40
url
stringlengths
85
252
21,000
rkt/rkt
rkt/gc.go
renameExpired
func renameExpired(preparedExpiration time.Duration) error { if err := pkgPod.WalkPods(getDataDir(), pkgPod.IncludePreparedDir, func(p *pkgPod.Pod) { st := &syscall.Stat_t{} pp := p.Path() if err := syscall.Lstat(pp, st); err != nil { if err != syscall.ENOENT { stderr.PrintE(fmt.Sprintf("unable to stat %q, ignoring", pp), err) } return } if expiration := time.Unix(st.Ctim.Unix()).Add(preparedExpiration); time.Now().After(expiration) { stderr.Printf("moving expired prepared pod %q to garbage", p.UUID) if err := p.ToGarbage(); err != nil && err != os.ErrNotExist { stderr.PrintE("rename error", err) } } }); err != nil { return err } return nil }
go
func renameExpired(preparedExpiration time.Duration) error { if err := pkgPod.WalkPods(getDataDir(), pkgPod.IncludePreparedDir, func(p *pkgPod.Pod) { st := &syscall.Stat_t{} pp := p.Path() if err := syscall.Lstat(pp, st); err != nil { if err != syscall.ENOENT { stderr.PrintE(fmt.Sprintf("unable to stat %q, ignoring", pp), err) } return } if expiration := time.Unix(st.Ctim.Unix()).Add(preparedExpiration); time.Now().After(expiration) { stderr.Printf("moving expired prepared pod %q to garbage", p.UUID) if err := p.ToGarbage(); err != nil && err != os.ErrNotExist { stderr.PrintE("rename error", err) } } }); err != nil { return err } return nil }
[ "func", "renameExpired", "(", "preparedExpiration", "time", ".", "Duration", ")", "error", "{", "if", "err", ":=", "pkgPod", ".", "WalkPods", "(", "getDataDir", "(", ")", ",", "pkgPod", ".", "IncludePreparedDir", ",", "func", "(", "p", "*", "pkgPod", ".", "Pod", ")", "{", "st", ":=", "&", "syscall", ".", "Stat_t", "{", "}", "\n", "pp", ":=", "p", ".", "Path", "(", ")", "\n", "if", "err", ":=", "syscall", ".", "Lstat", "(", "pp", ",", "st", ")", ";", "err", "!=", "nil", "{", "if", "err", "!=", "syscall", ".", "ENOENT", "{", "stderr", ".", "PrintE", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "pp", ")", ",", "err", ")", "\n", "}", "\n", "return", "\n", "}", "\n\n", "if", "expiration", ":=", "time", ".", "Unix", "(", "st", ".", "Ctim", ".", "Unix", "(", ")", ")", ".", "Add", "(", "preparedExpiration", ")", ";", "time", ".", "Now", "(", ")", ".", "After", "(", "expiration", ")", "{", "stderr", ".", "Printf", "(", "\"", "\"", ",", "p", ".", "UUID", ")", "\n", "if", "err", ":=", "p", ".", "ToGarbage", "(", ")", ";", "err", "!=", "nil", "&&", "err", "!=", "os", ".", "ErrNotExist", "{", "stderr", ".", "PrintE", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}", "\n", "}", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// renameExpired renames expired prepared pods to the garbage directory
[ "renameExpired", "renames", "expired", "prepared", "pods", "to", "the", "garbage", "directory" ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/gc.go#L162-L183
21,001
rkt/rkt
rkt/gc.go
deletePod
func deletePod(p *pkgPod.Pod) bool { podState := p.State() if podState != pkgPod.ExitedGarbage && podState != pkgPod.Garbage && podState != pkgPod.ExitedDeleting { stderr.Errorf("non-garbage pod %q (status %q), skipped", p.UUID, p.State()) return false } if podState == pkgPod.ExitedGarbage { s, err := imagestore.NewStore(storeDir()) if err != nil { stderr.PrintE("cannot open store", err) return false } defer s.Close() ts, err := treestore.NewStore(treeStoreDir(), s) if err != nil { stderr.PrintE("cannot open store", err) return false } if globalFlags.Debug { stage0.InitDebug() } if newMount, err := mountPodStage1(ts, p); err == nil { if err = stage0.GC(p.Path(), p.UUID, globalFlags.LocalConfigDir); err != nil { stderr.PrintE(fmt.Sprintf("problem performing stage1 GC on %q", p.UUID), err) } // Linux <4.13 allows an overlay fs to be mounted over itself, so let's // unmount it here to avoid problems when running stage0.MountGC if p.UsesOverlay() && newMount { stage1Mnt := common.Stage1RootfsPath(p.Path()) if err := syscall.Unmount(stage1Mnt, 0); err != nil && err != syscall.EBUSY { stderr.PrintE("error unmounting stage1", err) } } } else { stderr.PrintE("skipping stage1 GC", err) } // unmount all leftover mounts if err := stage0.MountGC(p.Path(), p.UUID.String()); err != nil { stderr.PrintE(fmt.Sprintf("GC of leftover mounts for pod %q failed", p.UUID), err) return false } } // remove the rootfs first; if this fails (eg. due to busy mountpoints), pod manifest // is left in place and clean-up can be re-tried later. rootfsPath, err := p.Stage1RootfsPath() if err == nil { if e := os.RemoveAll(rootfsPath); e != nil { stderr.PrintE(fmt.Sprintf("unable to remove pod rootfs %q", p.UUID), e) return false } } // finally remove all remaining pieces if err := os.RemoveAll(p.Path()); err != nil { stderr.PrintE(fmt.Sprintf("unable to remove pod %q", p.UUID), err) return false } return true }
go
func deletePod(p *pkgPod.Pod) bool { podState := p.State() if podState != pkgPod.ExitedGarbage && podState != pkgPod.Garbage && podState != pkgPod.ExitedDeleting { stderr.Errorf("non-garbage pod %q (status %q), skipped", p.UUID, p.State()) return false } if podState == pkgPod.ExitedGarbage { s, err := imagestore.NewStore(storeDir()) if err != nil { stderr.PrintE("cannot open store", err) return false } defer s.Close() ts, err := treestore.NewStore(treeStoreDir(), s) if err != nil { stderr.PrintE("cannot open store", err) return false } if globalFlags.Debug { stage0.InitDebug() } if newMount, err := mountPodStage1(ts, p); err == nil { if err = stage0.GC(p.Path(), p.UUID, globalFlags.LocalConfigDir); err != nil { stderr.PrintE(fmt.Sprintf("problem performing stage1 GC on %q", p.UUID), err) } // Linux <4.13 allows an overlay fs to be mounted over itself, so let's // unmount it here to avoid problems when running stage0.MountGC if p.UsesOverlay() && newMount { stage1Mnt := common.Stage1RootfsPath(p.Path()) if err := syscall.Unmount(stage1Mnt, 0); err != nil && err != syscall.EBUSY { stderr.PrintE("error unmounting stage1", err) } } } else { stderr.PrintE("skipping stage1 GC", err) } // unmount all leftover mounts if err := stage0.MountGC(p.Path(), p.UUID.String()); err != nil { stderr.PrintE(fmt.Sprintf("GC of leftover mounts for pod %q failed", p.UUID), err) return false } } // remove the rootfs first; if this fails (eg. due to busy mountpoints), pod manifest // is left in place and clean-up can be re-tried later. rootfsPath, err := p.Stage1RootfsPath() if err == nil { if e := os.RemoveAll(rootfsPath); e != nil { stderr.PrintE(fmt.Sprintf("unable to remove pod rootfs %q", p.UUID), e) return false } } // finally remove all remaining pieces if err := os.RemoveAll(p.Path()); err != nil { stderr.PrintE(fmt.Sprintf("unable to remove pod %q", p.UUID), err) return false } return true }
[ "func", "deletePod", "(", "p", "*", "pkgPod", ".", "Pod", ")", "bool", "{", "podState", ":=", "p", ".", "State", "(", ")", "\n", "if", "podState", "!=", "pkgPod", ".", "ExitedGarbage", "&&", "podState", "!=", "pkgPod", ".", "Garbage", "&&", "podState", "!=", "pkgPod", ".", "ExitedDeleting", "{", "stderr", ".", "Errorf", "(", "\"", "\"", ",", "p", ".", "UUID", ",", "p", ".", "State", "(", ")", ")", "\n", "return", "false", "\n", "}", "\n\n", "if", "podState", "==", "pkgPod", ".", "ExitedGarbage", "{", "s", ",", "err", ":=", "imagestore", ".", "NewStore", "(", "storeDir", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "stderr", ".", "PrintE", "(", "\"", "\"", ",", "err", ")", "\n", "return", "false", "\n", "}", "\n", "defer", "s", ".", "Close", "(", ")", "\n\n", "ts", ",", "err", ":=", "treestore", ".", "NewStore", "(", "treeStoreDir", "(", ")", ",", "s", ")", "\n", "if", "err", "!=", "nil", "{", "stderr", ".", "PrintE", "(", "\"", "\"", ",", "err", ")", "\n", "return", "false", "\n", "}", "\n\n", "if", "globalFlags", ".", "Debug", "{", "stage0", ".", "InitDebug", "(", ")", "\n", "}", "\n\n", "if", "newMount", ",", "err", ":=", "mountPodStage1", "(", "ts", ",", "p", ")", ";", "err", "==", "nil", "{", "if", "err", "=", "stage0", ".", "GC", "(", "p", ".", "Path", "(", ")", ",", "p", ".", "UUID", ",", "globalFlags", ".", "LocalConfigDir", ")", ";", "err", "!=", "nil", "{", "stderr", ".", "PrintE", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "p", ".", "UUID", ")", ",", "err", ")", "\n", "}", "\n", "// 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", "(", ")", ")", "\n", "if", "err", ":=", "syscall", ".", "Unmount", "(", "stage1Mnt", ",", "0", ")", ";", "err", "!=", "nil", "&&", "err", "!=", "syscall", ".", "EBUSY", "{", "stderr", ".", "PrintE", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n", "}", "\n", "}", "else", "{", "stderr", ".", "PrintE", "(", "\"", "\"", ",", "err", ")", "\n", "}", "\n\n", "// unmount all leftover mounts", "if", "err", ":=", "stage0", ".", "MountGC", "(", "p", ".", "Path", "(", ")", ",", "p", ".", "UUID", ".", "String", "(", ")", ")", ";", "err", "!=", "nil", "{", "stderr", ".", "PrintE", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "p", ".", "UUID", ")", ",", "err", ")", "\n", "return", "false", "\n", "}", "\n", "}", "\n\n", "// 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", "(", ")", "\n", "if", "err", "==", "nil", "{", "if", "e", ":=", "os", ".", "RemoveAll", "(", "rootfsPath", ")", ";", "e", "!=", "nil", "{", "stderr", ".", "PrintE", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "p", ".", "UUID", ")", ",", "e", ")", "\n", "return", "false", "\n", "}", "\n", "}", "\n\n", "// finally remove all remaining pieces", "if", "err", ":=", "os", ".", "RemoveAll", "(", "p", ".", "Path", "(", ")", ")", ";", "err", "!=", "nil", "{", "stderr", ".", "PrintE", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "p", ".", "UUID", ")", ",", "err", ")", "\n", "return", "false", "\n", "}", "\n\n", "return", "true", "\n", "}" ]
// deletePod cleans up files and resource associated with the pod // pod must be under exclusive lock and be in either ExitedGarbage // or Garbage state
[ "deletePod", "cleans", "up", "files", "and", "resource", "associated", "with", "the", "pod", "pod", "must", "be", "under", "exclusive", "lock", "and", "be", "in", "either", "ExitedGarbage", "or", "Garbage", "state" ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/gc.go#L251-L316
21,002
rkt/rkt
store/imagestore/store.go
backupDB
func (s *Store) backupDB() error { if os.Geteuid() != 0 { return ErrDBUpdateNeedsRoot } backupsDir := filepath.Join(s.dir, "db-backups") return backup.CreateBackup(s.dbDir(), backupsDir, backupsNumber) }
go
func (s *Store) backupDB() error { if os.Geteuid() != 0 { return ErrDBUpdateNeedsRoot } backupsDir := filepath.Join(s.dir, "db-backups") return backup.CreateBackup(s.dbDir(), backupsDir, backupsNumber) }
[ "func", "(", "s", "*", "Store", ")", "backupDB", "(", ")", "error", "{", "if", "os", ".", "Geteuid", "(", ")", "!=", "0", "{", "return", "ErrDBUpdateNeedsRoot", "\n", "}", "\n", "backupsDir", ":=", "filepath", ".", "Join", "(", "s", ".", "dir", ",", "\"", "\"", ")", "\n", "return", "backup", ".", "CreateBackup", "(", "s", ".", "dbDir", "(", ")", ",", "backupsDir", ",", "backupsNumber", ")", "\n", "}" ]
// backupDB backs up current database.
[ "backupDB", "backs", "up", "current", "database", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/store/imagestore/store.go#L283-L289
21,003
rkt/rkt
store/imagestore/store.go
ResolveName
func (s *Store) ResolveName(name string) ([]string, bool, error) { var ( aciInfos []*ACIInfo found bool ) err := s.db.Do(func(tx *sql.Tx) error { var err error aciInfos, found, err = GetACIInfosWithName(tx, name) return err }) if err != nil { return nil, found, errwrap.Wrap(errors.New("error retrieving ACI Infos"), err) } keys := make([]string, len(aciInfos)) for i, aciInfo := range aciInfos { keys[i] = aciInfo.BlobKey } return keys, found, nil }
go
func (s *Store) ResolveName(name string) ([]string, bool, error) { var ( aciInfos []*ACIInfo found bool ) err := s.db.Do(func(tx *sql.Tx) error { var err error aciInfos, found, err = GetACIInfosWithName(tx, name) return err }) if err != nil { return nil, found, errwrap.Wrap(errors.New("error retrieving ACI Infos"), err) } keys := make([]string, len(aciInfos)) for i, aciInfo := range aciInfos { keys[i] = aciInfo.BlobKey } return keys, found, nil }
[ "func", "(", "s", "*", "Store", ")", "ResolveName", "(", "name", "string", ")", "(", "[", "]", "string", ",", "bool", ",", "error", ")", "{", "var", "(", "aciInfos", "[", "]", "*", "ACIInfo", "\n", "found", "bool", "\n", ")", "\n", "err", ":=", "s", ".", "db", ".", "Do", "(", "func", "(", "tx", "*", "sql", ".", "Tx", ")", "error", "{", "var", "err", "error", "\n", "aciInfos", ",", "found", ",", "err", "=", "GetACIInfosWithName", "(", "tx", ",", "name", ")", "\n", "return", "err", "\n", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "found", ",", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"", "\"", ")", ",", "err", ")", "\n", "}", "\n\n", "keys", ":=", "make", "(", "[", "]", "string", ",", "len", "(", "aciInfos", ")", ")", "\n", "for", "i", ",", "aciInfo", ":=", "range", "aciInfos", "{", "keys", "[", "i", "]", "=", "aciInfo", ".", "BlobKey", "\n", "}", "\n\n", "return", "keys", ",", "found", ",", "nil", "\n", "}" ]
// ResolveName resolves an image name to a list of full keys and using the // store for resolution.
[ "ResolveName", "resolves", "an", "image", "name", "to", "a", "list", "of", "full", "keys", "and", "using", "the", "store", "for", "resolution", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/store/imagestore/store.go#L374-L394
21,004
rkt/rkt
store/imagestore/store.go
RemoveACI
func (s *Store) RemoveACI(key string) error { imageKeyLock, err := lock.ExclusiveKeyLock(s.imageLockDir, key) if err != nil { return errwrap.Wrap(errors.New("error locking image"), err) } defer imageKeyLock.Close() // Firstly remove aciinfo and remote from the db in an unique transaction. // remote needs to be removed or a GetRemote will return a blobKey not // referenced by any ACIInfo. err = s.db.Do(func(tx *sql.Tx) error { if _, found, err := GetACIInfoWithBlobKey(tx, key); err != nil { return errwrap.Wrap(errors.New("error getting aciinfo"), err) } else if !found { return fmt.Errorf("cannot find image with key: %s", key) } if err := RemoveACIInfo(tx, key); err != nil { return err } if err := RemoveRemote(tx, key); err != nil { return err } return nil }) if err != nil { return errwrap.Wrap(fmt.Errorf("cannot remove image with ID: %s from db", key), err) } // Then remove non transactional entries from the blob, imageManifest // and tree store. // TODO(sgotti). Now that the ACIInfo is removed the image doesn't // exists anymore, but errors removing non transactional entries can // leave stale data that will require a cas GC to be implemented. var storeErrors []error for _, ds := range s.stores { if err := ds.Erase(key); err != nil { // If there's an error save it and continue with the other stores storeErrors = append(storeErrors, err) } } if len(storeErrors) > 0 { return &StoreRemovalError{errors: storeErrors} } return nil }
go
func (s *Store) RemoveACI(key string) error { imageKeyLock, err := lock.ExclusiveKeyLock(s.imageLockDir, key) if err != nil { return errwrap.Wrap(errors.New("error locking image"), err) } defer imageKeyLock.Close() // Firstly remove aciinfo and remote from the db in an unique transaction. // remote needs to be removed or a GetRemote will return a blobKey not // referenced by any ACIInfo. err = s.db.Do(func(tx *sql.Tx) error { if _, found, err := GetACIInfoWithBlobKey(tx, key); err != nil { return errwrap.Wrap(errors.New("error getting aciinfo"), err) } else if !found { return fmt.Errorf("cannot find image with key: %s", key) } if err := RemoveACIInfo(tx, key); err != nil { return err } if err := RemoveRemote(tx, key); err != nil { return err } return nil }) if err != nil { return errwrap.Wrap(fmt.Errorf("cannot remove image with ID: %s from db", key), err) } // Then remove non transactional entries from the blob, imageManifest // and tree store. // TODO(sgotti). Now that the ACIInfo is removed the image doesn't // exists anymore, but errors removing non transactional entries can // leave stale data that will require a cas GC to be implemented. var storeErrors []error for _, ds := range s.stores { if err := ds.Erase(key); err != nil { // If there's an error save it and continue with the other stores storeErrors = append(storeErrors, err) } } if len(storeErrors) > 0 { return &StoreRemovalError{errors: storeErrors} } return nil }
[ "func", "(", "s", "*", "Store", ")", "RemoveACI", "(", "key", "string", ")", "error", "{", "imageKeyLock", ",", "err", ":=", "lock", ".", "ExclusiveKeyLock", "(", "s", ".", "imageLockDir", ",", "key", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"", "\"", ")", ",", "err", ")", "\n", "}", "\n", "defer", "imageKeyLock", ".", "Close", "(", ")", "\n\n", "// 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", "(", "\"", "\"", ")", ",", "err", ")", "\n", "}", "else", "if", "!", "found", "{", "return", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "key", ")", "\n", "}", "\n\n", "if", "err", ":=", "RemoveACIInfo", "(", "tx", ",", "key", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "RemoveRemote", "(", "tx", ",", "key", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errwrap", ".", "Wrap", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "key", ")", ",", "err", ")", "\n", "}", "\n\n", "// 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", "\n", "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", ")", "\n", "}", "\n", "}", "\n", "if", "len", "(", "storeErrors", ")", ">", "0", "{", "return", "&", "StoreRemovalError", "{", "errors", ":", "storeErrors", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// RemoveACI removes the ACI with the given key. It firstly removes the aci // infos inside the db, then it tries to remove the non transactional data. // If some error occurs removing some non transactional data a // StoreRemovalError is returned.
[ "RemoveACI", "removes", "the", "ACI", "with", "the", "given", "key", ".", "It", "firstly", "removes", "the", "aci", "infos", "inside", "the", "db", "then", "it", "tries", "to", "remove", "the", "non", "transactional", "data", ".", "If", "some", "error", "occurs", "removing", "some", "non", "transactional", "data", "a", "StoreRemovalError", "is", "returned", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/store/imagestore/store.go#L506-L551
21,005
rkt/rkt
store/imagestore/store.go
GetRemote
func (s *Store) GetRemote(aciURL string) (*Remote, error) { var remote *Remote err := s.db.Do(func(tx *sql.Tx) error { var err error remote, err = GetRemote(tx, aciURL) return err }) if err != nil { return nil, err } return remote, nil }
go
func (s *Store) GetRemote(aciURL string) (*Remote, error) { var remote *Remote err := s.db.Do(func(tx *sql.Tx) error { var err error remote, err = GetRemote(tx, aciURL) return err }) if err != nil { return nil, err } return remote, nil }
[ "func", "(", "s", "*", "Store", ")", "GetRemote", "(", "aciURL", "string", ")", "(", "*", "Remote", ",", "error", ")", "{", "var", "remote", "*", "Remote", "\n\n", "err", ":=", "s", ".", "db", ".", "Do", "(", "func", "(", "tx", "*", "sql", ".", "Tx", ")", "error", "{", "var", "err", "error", "\n\n", "remote", ",", "err", "=", "GetRemote", "(", "tx", ",", "aciURL", ")", "\n\n", "return", "err", "\n", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "remote", ",", "nil", "\n", "}" ]
// GetRemote tries to retrieve a remote with the given ACIURL. // If remote doesn't exist, it returns ErrRemoteNotFound error.
[ "GetRemote", "tries", "to", "retrieve", "a", "remote", "with", "the", "given", "ACIURL", ".", "If", "remote", "doesn", "t", "exist", "it", "returns", "ErrRemoteNotFound", "error", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/store/imagestore/store.go#L555-L570
21,006
rkt/rkt
store/imagestore/store.go
GetImageManifestJSON
func (s *Store) GetImageManifestJSON(key string) ([]byte, error) { key, err := s.ResolveKey(key) if err != nil { return nil, errwrap.Wrap(errors.New("error resolving image ID"), err) } keyLock, err := lock.SharedKeyLock(s.imageLockDir, key) if err != nil { return nil, errwrap.Wrap(errors.New("error locking image"), err) } defer keyLock.Close() imj, err := s.stores[imageManifestType].Read(key) if err != nil { return nil, errwrap.Wrap(errors.New("error retrieving image manifest"), err) } return imj, nil }
go
func (s *Store) GetImageManifestJSON(key string) ([]byte, error) { key, err := s.ResolveKey(key) if err != nil { return nil, errwrap.Wrap(errors.New("error resolving image ID"), err) } keyLock, err := lock.SharedKeyLock(s.imageLockDir, key) if err != nil { return nil, errwrap.Wrap(errors.New("error locking image"), err) } defer keyLock.Close() imj, err := s.stores[imageManifestType].Read(key) if err != nil { return nil, errwrap.Wrap(errors.New("error retrieving image manifest"), err) } return imj, nil }
[ "func", "(", "s", "*", "Store", ")", "GetImageManifestJSON", "(", "key", "string", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "key", ",", "err", ":=", "s", ".", "ResolveKey", "(", "key", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"", "\"", ")", ",", "err", ")", "\n", "}", "\n", "keyLock", ",", "err", ":=", "lock", ".", "SharedKeyLock", "(", "s", ".", "imageLockDir", ",", "key", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"", "\"", ")", ",", "err", ")", "\n", "}", "\n", "defer", "keyLock", ".", "Close", "(", ")", "\n\n", "imj", ",", "err", ":=", "s", ".", "stores", "[", "imageManifestType", "]", ".", "Read", "(", "key", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"", "\"", ")", ",", "err", ")", "\n", "}", "\n", "return", "imj", ",", "nil", "\n", "}" ]
// GetImageManifestJSON gets the ImageManifest JSON bytes with the // specified key.
[ "GetImageManifestJSON", "gets", "the", "ImageManifest", "JSON", "bytes", "with", "the", "specified", "key", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/store/imagestore/store.go#L582-L598
21,007
rkt/rkt
store/imagestore/store.go
GetImageManifest
func (s *Store) GetImageManifest(key string) (*schema.ImageManifest, error) { imj, err := s.GetImageManifestJSON(key) if err != nil { return nil, err } var im *schema.ImageManifest if err = json.Unmarshal(imj, &im); err != nil { return nil, errwrap.Wrap(errors.New("error unmarshalling image manifest"), err) } return im, nil }
go
func (s *Store) GetImageManifest(key string) (*schema.ImageManifest, error) { imj, err := s.GetImageManifestJSON(key) if err != nil { return nil, err } var im *schema.ImageManifest if err = json.Unmarshal(imj, &im); err != nil { return nil, errwrap.Wrap(errors.New("error unmarshalling image manifest"), err) } return im, nil }
[ "func", "(", "s", "*", "Store", ")", "GetImageManifest", "(", "key", "string", ")", "(", "*", "schema", ".", "ImageManifest", ",", "error", ")", "{", "imj", ",", "err", ":=", "s", ".", "GetImageManifestJSON", "(", "key", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "var", "im", "*", "schema", ".", "ImageManifest", "\n", "if", "err", "=", "json", ".", "Unmarshal", "(", "imj", ",", "&", "im", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"", "\"", ")", ",", "err", ")", "\n", "}", "\n", "return", "im", ",", "nil", "\n", "}" ]
// GetImageManifest gets the ImageManifest with the specified key.
[ "GetImageManifest", "gets", "the", "ImageManifest", "with", "the", "specified", "key", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/store/imagestore/store.go#L601-L611
21,008
rkt/rkt
store/imagestore/store.go
HasFullKey
func (s *Store) HasFullKey(key string) bool { return s.stores[imageManifestType].Has(key) }
go
func (s *Store) HasFullKey(key string) bool { return s.stores[imageManifestType].Has(key) }
[ "func", "(", "s", "*", "Store", ")", "HasFullKey", "(", "key", "string", ")", "bool", "{", "return", "s", ".", "stores", "[", "imageManifestType", "]", ".", "Has", "(", "key", ")", "\n", "}" ]
// HasFullKey returns whether the image with the given key exists on the disk by // checking if the image manifest kv store contains the key.
[ "HasFullKey", "returns", "whether", "the", "image", "with", "the", "given", "key", "exists", "on", "the", "disk", "by", "checking", "if", "the", "image", "manifest", "kv", "store", "contains", "the", "key", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/store/imagestore/store.go#L756-L758
21,009
rkt/rkt
store/imagestore/store.go
keyToString
func keyToString(k []byte) string { if len(k) != lenHash { panic(fmt.Sprintf("bad hash passed to hashToKey: %x", k)) } return fmt.Sprintf("%s%x", hashPrefix, k)[0:lenKey] }
go
func keyToString(k []byte) string { if len(k) != lenHash { panic(fmt.Sprintf("bad hash passed to hashToKey: %x", k)) } return fmt.Sprintf("%s%x", hashPrefix, k)[0:lenKey] }
[ "func", "keyToString", "(", "k", "[", "]", "byte", ")", "string", "{", "if", "len", "(", "k", ")", "!=", "lenHash", "{", "panic", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "k", ")", ")", "\n", "}", "\n", "return", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "hashPrefix", ",", "k", ")", "[", "0", ":", "lenKey", "]", "\n", "}" ]
// keyToString takes a key and returns a shortened and prefixed hexadecimal string version
[ "keyToString", "takes", "a", "key", "and", "returns", "a", "shortened", "and", "prefixed", "hexadecimal", "string", "version" ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/store/imagestore/store.go#L766-L771
21,010
rkt/rkt
rkt/image/downloader.go
Download
func (d *downloader) Download(u *url.URL, out writeSyncer) error { client, err := d.Session.Client() if err != nil { return err } req, err := d.Session.Request(u) if err != nil { return err } res, err := client.Do(req) if err != nil { return err } defer res.Body.Close() if stopNow, err := d.Session.HandleStatus(res); stopNow || err != nil { return err } reader, err := d.Session.BodyReader(res) if err != nil { return err } if _, err := io.Copy(out, reader); err != nil { return errwrap.Wrap(fmt.Errorf("failed to download %q", u.String()), err) } if err := out.Sync(); err != nil { return errwrap.Wrap(fmt.Errorf("failed to sync data from %q to disk", u.String()), err) } return nil }
go
func (d *downloader) Download(u *url.URL, out writeSyncer) error { client, err := d.Session.Client() if err != nil { return err } req, err := d.Session.Request(u) if err != nil { return err } res, err := client.Do(req) if err != nil { return err } defer res.Body.Close() if stopNow, err := d.Session.HandleStatus(res); stopNow || err != nil { return err } reader, err := d.Session.BodyReader(res) if err != nil { return err } if _, err := io.Copy(out, reader); err != nil { return errwrap.Wrap(fmt.Errorf("failed to download %q", u.String()), err) } if err := out.Sync(); err != nil { return errwrap.Wrap(fmt.Errorf("failed to sync data from %q to disk", u.String()), err) } return nil }
[ "func", "(", "d", "*", "downloader", ")", "Download", "(", "u", "*", "url", ".", "URL", ",", "out", "writeSyncer", ")", "error", "{", "client", ",", "err", ":=", "d", ".", "Session", ".", "Client", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "req", ",", "err", ":=", "d", ".", "Session", ".", "Request", "(", "u", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "res", ",", "err", ":=", "client", ".", "Do", "(", "req", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "res", ".", "Body", ".", "Close", "(", ")", "\n\n", "if", "stopNow", ",", "err", ":=", "d", ".", "Session", ".", "HandleStatus", "(", "res", ")", ";", "stopNow", "||", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "reader", ",", "err", ":=", "d", ".", "Session", ".", "BodyReader", "(", "res", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "_", ",", "err", ":=", "io", ".", "Copy", "(", "out", ",", "reader", ")", ";", "err", "!=", "nil", "{", "return", "errwrap", ".", "Wrap", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "u", ".", "String", "(", ")", ")", ",", "err", ")", "\n", "}", "\n\n", "if", "err", ":=", "out", ".", "Sync", "(", ")", ";", "err", "!=", "nil", "{", "return", "errwrap", ".", "Wrap", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "u", ".", "String", "(", ")", ")", ",", "err", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Download tries to fetch the passed URL and write the contents into // a given writeSyncer instance.
[ "Download", "tries", "to", "fetch", "the", "passed", "URL", "and", "write", "the", "contents", "into", "a", "given", "writeSyncer", "instance", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/image/downloader.go#L54-L86
21,011
rkt/rkt
rkt/enter.go
getAppName
func getAppName(p *pkgPod.Pod) (*types.ACName, error) { if flagAppName != "" { return types.NewACName(flagAppName) } // figure out the app name, or show a list if multiple are present _, m, err := p.PodManifest() if err != nil { return nil, errwrap.Wrap(errors.New("error reading pod manifest"), err) } switch len(m.Apps) { case 0: return nil, fmt.Errorf("pod contains zero apps") case 1: return &m.Apps[0].Name, nil default: } stderr.Print("pod contains multiple apps:") for _, ra := range m.Apps { stderr.Printf("\t%v", ra.Name) } return nil, fmt.Errorf("specify app using \"rkt enter --app= ...\"") }
go
func getAppName(p *pkgPod.Pod) (*types.ACName, error) { if flagAppName != "" { return types.NewACName(flagAppName) } // figure out the app name, or show a list if multiple are present _, m, err := p.PodManifest() if err != nil { return nil, errwrap.Wrap(errors.New("error reading pod manifest"), err) } switch len(m.Apps) { case 0: return nil, fmt.Errorf("pod contains zero apps") case 1: return &m.Apps[0].Name, nil default: } stderr.Print("pod contains multiple apps:") for _, ra := range m.Apps { stderr.Printf("\t%v", ra.Name) } return nil, fmt.Errorf("specify app using \"rkt enter --app= ...\"") }
[ "func", "getAppName", "(", "p", "*", "pkgPod", ".", "Pod", ")", "(", "*", "types", ".", "ACName", ",", "error", ")", "{", "if", "flagAppName", "!=", "\"", "\"", "{", "return", "types", ".", "NewACName", "(", "flagAppName", ")", "\n", "}", "\n\n", "// figure out the app name, or show a list if multiple are present", "_", ",", "m", ",", "err", ":=", "p", ".", "PodManifest", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"", "\"", ")", ",", "err", ")", "\n", "}", "\n\n", "switch", "len", "(", "m", ".", "Apps", ")", "{", "case", "0", ":", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "case", "1", ":", "return", "&", "m", ".", "Apps", "[", "0", "]", ".", "Name", ",", "nil", "\n", "default", ":", "}", "\n\n", "stderr", ".", "Print", "(", "\"", "\"", ")", "\n", "for", "_", ",", "ra", ":=", "range", "m", ".", "Apps", "{", "stderr", ".", "Printf", "(", "\"", "\\t", "\"", ",", "ra", ".", "Name", ")", "\n", "}", "\n\n", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\\\"", "\\\"", "\"", ")", "\n", "}" ]
// getAppName returns the app name to enter // If one was supplied in the flags then it's simply returned // If the PM contains a single app, that app's name is returned // If the PM has multiple apps, the names are printed and an error is returned
[ "getAppName", "returns", "the", "app", "name", "to", "enter", "If", "one", "was", "supplied", "in", "the", "flags", "then", "it", "s", "simply", "returned", "If", "the", "PM", "contains", "a", "single", "app", "that", "app", "s", "name", "is", "returned", "If", "the", "PM", "has", "multiple", "apps", "the", "names", "are", "printed", "and", "an", "error", "is", "returned" ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/enter.go#L128-L153
21,012
rkt/rkt
rkt/enter.go
getEnterArgv
func getEnterArgv(p *pkgPod.Pod, cmdArgs []string) ([]string, error) { var argv []string if len(cmdArgs) < 2 { stderr.Printf("no command specified, assuming %q", defaultCmd) argv = []string{defaultCmd} } else { argv = cmdArgs[1:] } return argv, nil }
go
func getEnterArgv(p *pkgPod.Pod, cmdArgs []string) ([]string, error) { var argv []string if len(cmdArgs) < 2 { stderr.Printf("no command specified, assuming %q", defaultCmd) argv = []string{defaultCmd} } else { argv = cmdArgs[1:] } return argv, nil }
[ "func", "getEnterArgv", "(", "p", "*", "pkgPod", ".", "Pod", ",", "cmdArgs", "[", "]", "string", ")", "(", "[", "]", "string", ",", "error", ")", "{", "var", "argv", "[", "]", "string", "\n", "if", "len", "(", "cmdArgs", ")", "<", "2", "{", "stderr", ".", "Printf", "(", "\"", "\"", ",", "defaultCmd", ")", "\n", "argv", "=", "[", "]", "string", "{", "defaultCmd", "}", "\n", "}", "else", "{", "argv", "=", "cmdArgs", "[", "1", ":", "]", "\n", "}", "\n\n", "return", "argv", ",", "nil", "\n", "}" ]
// getEnterArgv returns the argv to use for entering the pod
[ "getEnterArgv", "returns", "the", "argv", "to", "use", "for", "entering", "the", "pod" ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/enter.go#L156-L166
21,013
rkt/rkt
common/cgroup/v1/cgroup.go
mountFsRO
func mountFsRO(m fs.Mounter, mountPoint string, flags uintptr) error { flags = flags | syscall.MS_BIND | syscall.MS_REMOUNT | syscall.MS_RDONLY if err := m.Mount(mountPoint, mountPoint, "", flags, ""); err != nil { return errwrap.Wrap(fmt.Errorf("error remounting read-only %q", mountPoint), err) } return nil }
go
func mountFsRO(m fs.Mounter, mountPoint string, flags uintptr) error { flags = flags | syscall.MS_BIND | syscall.MS_REMOUNT | syscall.MS_RDONLY if err := m.Mount(mountPoint, mountPoint, "", flags, ""); err != nil { return errwrap.Wrap(fmt.Errorf("error remounting read-only %q", mountPoint), err) } return nil }
[ "func", "mountFsRO", "(", "m", "fs", ".", "Mounter", ",", "mountPoint", "string", ",", "flags", "uintptr", ")", "error", "{", "flags", "=", "flags", "|", "syscall", ".", "MS_BIND", "|", "syscall", ".", "MS_REMOUNT", "|", "syscall", ".", "MS_RDONLY", "\n\n", "if", "err", ":=", "m", ".", "Mount", "(", "mountPoint", ",", "mountPoint", ",", "\"", "\"", ",", "flags", ",", "\"", "\"", ")", ";", "err", "!=", "nil", "{", "return", "errwrap", ".", "Wrap", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "mountPoint", ")", ",", "err", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// mountFsRO remounts the given mountPoint using the given flags read-only.
[ "mountFsRO", "remounts", "the", "given", "mountPoint", "using", "the", "given", "flags", "read", "-", "only", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/common/cgroup/v1/cgroup.go#L36-L47
21,014
rkt/rkt
common/cgroup/v1/cgroup.go
GetEnabledCgroups
func GetEnabledCgroups() (map[int][]string, error) { cgroupsFile, err := os.Open("/proc/cgroups") if err != nil { return nil, err } defer cgroupsFile.Close() cgroups, err := parseCgroups(cgroupsFile) if err != nil { return nil, errwrap.Wrap(errors.New("error parsing /proc/cgroups"), err) } return cgroups, nil }
go
func GetEnabledCgroups() (map[int][]string, error) { cgroupsFile, err := os.Open("/proc/cgroups") if err != nil { return nil, err } defer cgroupsFile.Close() cgroups, err := parseCgroups(cgroupsFile) if err != nil { return nil, errwrap.Wrap(errors.New("error parsing /proc/cgroups"), err) } return cgroups, nil }
[ "func", "GetEnabledCgroups", "(", ")", "(", "map", "[", "int", "]", "[", "]", "string", ",", "error", ")", "{", "cgroupsFile", ",", "err", ":=", "os", ".", "Open", "(", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "defer", "cgroupsFile", ".", "Close", "(", ")", "\n\n", "cgroups", ",", "err", ":=", "parseCgroups", "(", "cgroupsFile", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"", "\"", ")", ",", "err", ")", "\n", "}", "\n\n", "return", "cgroups", ",", "nil", "\n", "}" ]
// GetEnabledCgroups returns a map with the enabled cgroup controllers grouped by // hierarchy
[ "GetEnabledCgroups", "returns", "a", "map", "with", "the", "enabled", "cgroup", "controllers", "grouped", "by", "hierarchy" ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/common/cgroup/v1/cgroup.go#L81-L94
21,015
rkt/rkt
common/cgroup/v1/cgroup.go
GetOwnCgroupPath
func GetOwnCgroupPath(controller string) (string, error) { parts, err := parseCgroupController("/proc/self/cgroup", controller) if err != nil { return "", err } return parts[2], nil }
go
func GetOwnCgroupPath(controller string) (string, error) { parts, err := parseCgroupController("/proc/self/cgroup", controller) if err != nil { return "", err } return parts[2], nil }
[ "func", "GetOwnCgroupPath", "(", "controller", "string", ")", "(", "string", ",", "error", ")", "{", "parts", ",", "err", ":=", "parseCgroupController", "(", "\"", "\"", ",", "controller", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "return", "parts", "[", "2", "]", ",", "nil", "\n", "}" ]
// GetOwnCgroupPath returns the cgroup path of this process in controller // hierarchy
[ "GetOwnCgroupPath", "returns", "the", "cgroup", "path", "of", "this", "process", "in", "controller", "hierarchy" ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/common/cgroup/v1/cgroup.go#L149-L155
21,016
rkt/rkt
common/cgroup/v1/cgroup.go
GetCgroupPathByPid
func GetCgroupPathByPid(pid int, controller string) (string, error) { parts, err := parseCgroupController(fmt.Sprintf("/proc/%d/cgroup", pid), controller) if err != nil { return "", err } return parts[2], nil }
go
func GetCgroupPathByPid(pid int, controller string) (string, error) { parts, err := parseCgroupController(fmt.Sprintf("/proc/%d/cgroup", pid), controller) if err != nil { return "", err } return parts[2], nil }
[ "func", "GetCgroupPathByPid", "(", "pid", "int", ",", "controller", "string", ")", "(", "string", ",", "error", ")", "{", "parts", ",", "err", ":=", "parseCgroupController", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "pid", ")", ",", "controller", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "return", "parts", "[", "2", "]", ",", "nil", "\n", "}" ]
// GetCgroupPathByPid returns the cgroup path of the process with the given pid // and given controller.
[ "GetCgroupPathByPid", "returns", "the", "cgroup", "path", "of", "the", "process", "with", "the", "given", "pid", "and", "given", "controller", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/common/cgroup/v1/cgroup.go#L159-L165
21,017
rkt/rkt
common/cgroup/v1/cgroup.go
JoinSubcgroup
func JoinSubcgroup(controller string, subcgroup string) error { subcgroupPath := filepath.Join("/sys/fs/cgroup", controller, subcgroup) if err := os.MkdirAll(subcgroupPath, 0600); err != nil { return errwrap.Wrap(fmt.Errorf("error creating %q subcgroup", subcgroup), err) } pidBytes := []byte(strconv.Itoa(os.Getpid())) if err := ioutil.WriteFile(filepath.Join(subcgroupPath, "cgroup.procs"), pidBytes, 0600); err != nil { return errwrap.Wrap(fmt.Errorf("error adding ourselves to the %q subcgroup", subcgroup), err) } return nil }
go
func JoinSubcgroup(controller string, subcgroup string) error { subcgroupPath := filepath.Join("/sys/fs/cgroup", controller, subcgroup) if err := os.MkdirAll(subcgroupPath, 0600); err != nil { return errwrap.Wrap(fmt.Errorf("error creating %q subcgroup", subcgroup), err) } pidBytes := []byte(strconv.Itoa(os.Getpid())) if err := ioutil.WriteFile(filepath.Join(subcgroupPath, "cgroup.procs"), pidBytes, 0600); err != nil { return errwrap.Wrap(fmt.Errorf("error adding ourselves to the %q subcgroup", subcgroup), err) } return nil }
[ "func", "JoinSubcgroup", "(", "controller", "string", ",", "subcgroup", "string", ")", "error", "{", "subcgroupPath", ":=", "filepath", ".", "Join", "(", "\"", "\"", ",", "controller", ",", "subcgroup", ")", "\n", "if", "err", ":=", "os", ".", "MkdirAll", "(", "subcgroupPath", ",", "0600", ")", ";", "err", "!=", "nil", "{", "return", "errwrap", ".", "Wrap", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "subcgroup", ")", ",", "err", ")", "\n", "}", "\n", "pidBytes", ":=", "[", "]", "byte", "(", "strconv", ".", "Itoa", "(", "os", ".", "Getpid", "(", ")", ")", ")", "\n", "if", "err", ":=", "ioutil", ".", "WriteFile", "(", "filepath", ".", "Join", "(", "subcgroupPath", ",", "\"", "\"", ")", ",", "pidBytes", ",", "0600", ")", ";", "err", "!=", "nil", "{", "return", "errwrap", ".", "Wrap", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "subcgroup", ")", ",", "err", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// JoinSubcgroup makes the calling process join the subcgroup hierarchy on a // particular controller
[ "JoinSubcgroup", "makes", "the", "calling", "process", "join", "the", "subcgroup", "hierarchy", "on", "a", "particular", "controller" ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/common/cgroup/v1/cgroup.go#L169-L180
21,018
rkt/rkt
common/cgroup/v1/cgroup.go
IsControllerMounted
func IsControllerMounted(c string) (bool, error) { cgroupProcsPath := filepath.Join("/sys/fs/cgroup", c, "cgroup.procs") if _, err := os.Stat(cgroupProcsPath); err != nil { if !os.IsNotExist(err) { return false, err } return false, nil } return true, nil }
go
func IsControllerMounted(c string) (bool, error) { cgroupProcsPath := filepath.Join("/sys/fs/cgroup", c, "cgroup.procs") if _, err := os.Stat(cgroupProcsPath); err != nil { if !os.IsNotExist(err) { return false, err } return false, nil } return true, nil }
[ "func", "IsControllerMounted", "(", "c", "string", ")", "(", "bool", ",", "error", ")", "{", "cgroupProcsPath", ":=", "filepath", ".", "Join", "(", "\"", "\"", ",", "c", ",", "\"", "\"", ")", "\n", "if", "_", ",", "err", ":=", "os", ".", "Stat", "(", "cgroupProcsPath", ")", ";", "err", "!=", "nil", "{", "if", "!", "os", ".", "IsNotExist", "(", "err", ")", "{", "return", "false", ",", "err", "\n", "}", "\n", "return", "false", ",", "nil", "\n", "}", "\n\n", "return", "true", ",", "nil", "\n", "}" ]
// IsControllerMounted returns whether a controller is mounted by checking that // cgroup.procs is accessible
[ "IsControllerMounted", "returns", "whether", "a", "controller", "is", "mounted", "by", "checking", "that", "cgroup", ".", "procs", "is", "accessible" ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/common/cgroup/v1/cgroup.go#L238-L248
21,019
rkt/rkt
pkg/fileutil/fileutil_linux.go
Lgetxattr
func Lgetxattr(path string, attr string) ([]byte, error) { pathBytes, err := syscall.BytePtrFromString(path) if err != nil { return nil, err } attrBytes, err := syscall.BytePtrFromString(attr) if err != nil { return nil, err } dest := make([]byte, 128) destBytes := unsafe.Pointer(&dest[0]) sz, _, errno := syscall.Syscall6(syscall.SYS_LGETXATTR, uintptr(unsafe.Pointer(pathBytes)), uintptr(unsafe.Pointer(attrBytes)), uintptr(destBytes), uintptr(len(dest)), 0, 0) if errno == syscall.ENODATA { return nil, nil } if errno == syscall.ERANGE { dest = make([]byte, sz) destBytes := unsafe.Pointer(&dest[0]) sz, _, errno = syscall.Syscall6(syscall.SYS_LGETXATTR, uintptr(unsafe.Pointer(pathBytes)), uintptr(unsafe.Pointer(attrBytes)), uintptr(destBytes), uintptr(len(dest)), 0, 0) } if errno != 0 { return nil, errno } return dest[:sz], nil }
go
func Lgetxattr(path string, attr string) ([]byte, error) { pathBytes, err := syscall.BytePtrFromString(path) if err != nil { return nil, err } attrBytes, err := syscall.BytePtrFromString(attr) if err != nil { return nil, err } dest := make([]byte, 128) destBytes := unsafe.Pointer(&dest[0]) sz, _, errno := syscall.Syscall6(syscall.SYS_LGETXATTR, uintptr(unsafe.Pointer(pathBytes)), uintptr(unsafe.Pointer(attrBytes)), uintptr(destBytes), uintptr(len(dest)), 0, 0) if errno == syscall.ENODATA { return nil, nil } if errno == syscall.ERANGE { dest = make([]byte, sz) destBytes := unsafe.Pointer(&dest[0]) sz, _, errno = syscall.Syscall6(syscall.SYS_LGETXATTR, uintptr(unsafe.Pointer(pathBytes)), uintptr(unsafe.Pointer(attrBytes)), uintptr(destBytes), uintptr(len(dest)), 0, 0) } if errno != 0 { return nil, errno } return dest[:sz], nil }
[ "func", "Lgetxattr", "(", "path", "string", ",", "attr", "string", ")", "(", "[", "]", "byte", ",", "error", ")", "{", "pathBytes", ",", "err", ":=", "syscall", ".", "BytePtrFromString", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "attrBytes", ",", "err", ":=", "syscall", ".", "BytePtrFromString", "(", "attr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "dest", ":=", "make", "(", "[", "]", "byte", ",", "128", ")", "\n", "destBytes", ":=", "unsafe", ".", "Pointer", "(", "&", "dest", "[", "0", "]", ")", "\n", "sz", ",", "_", ",", "errno", ":=", "syscall", ".", "Syscall6", "(", "syscall", ".", "SYS_LGETXATTR", ",", "uintptr", "(", "unsafe", ".", "Pointer", "(", "pathBytes", ")", ")", ",", "uintptr", "(", "unsafe", ".", "Pointer", "(", "attrBytes", ")", ")", ",", "uintptr", "(", "destBytes", ")", ",", "uintptr", "(", "len", "(", "dest", ")", ")", ",", "0", ",", "0", ")", "\n", "if", "errno", "==", "syscall", ".", "ENODATA", "{", "return", "nil", ",", "nil", "\n", "}", "\n", "if", "errno", "==", "syscall", ".", "ERANGE", "{", "dest", "=", "make", "(", "[", "]", "byte", ",", "sz", ")", "\n", "destBytes", ":=", "unsafe", ".", "Pointer", "(", "&", "dest", "[", "0", "]", ")", "\n", "sz", ",", "_", ",", "errno", "=", "syscall", ".", "Syscall6", "(", "syscall", ".", "SYS_LGETXATTR", ",", "uintptr", "(", "unsafe", ".", "Pointer", "(", "pathBytes", ")", ")", ",", "uintptr", "(", "unsafe", ".", "Pointer", "(", "attrBytes", ")", ")", ",", "uintptr", "(", "destBytes", ")", ",", "uintptr", "(", "len", "(", "dest", ")", ")", ",", "0", ",", "0", ")", "\n", "}", "\n", "if", "errno", "!=", "0", "{", "return", "nil", ",", "errno", "\n", "}", "\n\n", "return", "dest", "[", ":", "sz", "]", ",", "nil", "\n", "}" ]
// Returns a nil slice and nil error if the xattr is not set
[ "Returns", "a", "nil", "slice", "and", "nil", "error", "if", "the", "xattr", "is", "not", "set" ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/fileutil/fileutil_linux.go#L58-L84
21,020
rkt/rkt
pkg/fileutil/fileutil_linux.go
GetDeviceInfo
func GetDeviceInfo(path string) (kind rune, major uint64, minor uint64, err error) { d, err := os.Lstat(path) if err != nil { return } mode := d.Mode() if mode&os.ModeDevice == 0 { err = fmt.Errorf("not a device: %s", path) return } stat_t, ok := d.Sys().(*syscall.Stat_t) if !ok { err = fmt.Errorf("cannot determine device number") return } return getDeviceInfo(mode, stat_t.Rdev) }
go
func GetDeviceInfo(path string) (kind rune, major uint64, minor uint64, err error) { d, err := os.Lstat(path) if err != nil { return } mode := d.Mode() if mode&os.ModeDevice == 0 { err = fmt.Errorf("not a device: %s", path) return } stat_t, ok := d.Sys().(*syscall.Stat_t) if !ok { err = fmt.Errorf("cannot determine device number") return } return getDeviceInfo(mode, stat_t.Rdev) }
[ "func", "GetDeviceInfo", "(", "path", "string", ")", "(", "kind", "rune", ",", "major", "uint64", ",", "minor", "uint64", ",", "err", "error", ")", "{", "d", ",", "err", ":=", "os", ".", "Lstat", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\n", "}", "\n", "mode", ":=", "d", ".", "Mode", "(", ")", "\n\n", "if", "mode", "&", "os", ".", "ModeDevice", "==", "0", "{", "err", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "path", ")", "\n", "return", "\n", "}", "\n", "stat_t", ",", "ok", ":=", "d", ".", "Sys", "(", ")", ".", "(", "*", "syscall", ".", "Stat_t", ")", "\n", "if", "!", "ok", "{", "err", "=", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "return", "\n", "}", "\n", "return", "getDeviceInfo", "(", "mode", ",", "stat_t", ".", "Rdev", ")", "\n", "}" ]
// GetDeviceInfo returns the type, major, and minor numbers of a device. // Kind is 'b' or 'c' for block and character devices, respectively. // This does not follow symlinks.
[ "GetDeviceInfo", "returns", "the", "type", "major", "and", "minor", "numbers", "of", "a", "device", ".", "Kind", "is", "b", "or", "c", "for", "block", "and", "character", "devices", "respectively", ".", "This", "does", "not", "follow", "symlinks", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/fileutil/fileutil_linux.go#L113-L130
21,021
rkt/rkt
pkg/fileutil/fileutil_linux.go
getDeviceInfo
func getDeviceInfo(mode os.FileMode, rdev uint64) (kind rune, major uint64, minor uint64, err error) { kind = 'b' if mode&os.ModeCharDevice != 0 { kind = 'c' } major = (rdev >> 8) & 0xfff minor = (rdev & 0xff) | ((rdev >> 12) & 0xfff00) return }
go
func getDeviceInfo(mode os.FileMode, rdev uint64) (kind rune, major uint64, minor uint64, err error) { kind = 'b' if mode&os.ModeCharDevice != 0 { kind = 'c' } major = (rdev >> 8) & 0xfff minor = (rdev & 0xff) | ((rdev >> 12) & 0xfff00) return }
[ "func", "getDeviceInfo", "(", "mode", "os", ".", "FileMode", ",", "rdev", "uint64", ")", "(", "kind", "rune", ",", "major", "uint64", ",", "minor", "uint64", ",", "err", "error", ")", "{", "kind", "=", "'b'", "\n\n", "if", "mode", "&", "os", ".", "ModeCharDevice", "!=", "0", "{", "kind", "=", "'c'", "\n", "}", "\n\n", "major", "=", "(", "rdev", ">>", "8", ")", "&", "0xfff", "\n", "minor", "=", "(", "rdev", "&", "0xff", ")", "|", "(", "(", "rdev", ">>", "12", ")", "&", "0xfff00", ")", "\n\n", "return", "\n", "}" ]
// Parse the device info out of the mode bits. Separate for testability.
[ "Parse", "the", "device", "info", "out", "of", "the", "mode", "bits", ".", "Separate", "for", "testability", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/fileutil/fileutil_linux.go#L133-L144
21,022
rkt/rkt
common/cgroup/cgroup.go
IsIsolatorSupported
func IsIsolatorSupported(isolator string) (bool, error) { isUnified, err := IsCgroupUnified("/") if err != nil { return false, errwrap.Wrap(errors.New("error determining cgroup version"), err) } if isUnified { controllers, err := v2.GetEnabledControllers() if err != nil { return false, errwrap.Wrap(errors.New("error determining enabled controllers"), err) } for _, c := range controllers { if c == isolator { return true, nil } } return false, nil } return v1.IsControllerMounted(isolator) }
go
func IsIsolatorSupported(isolator string) (bool, error) { isUnified, err := IsCgroupUnified("/") if err != nil { return false, errwrap.Wrap(errors.New("error determining cgroup version"), err) } if isUnified { controllers, err := v2.GetEnabledControllers() if err != nil { return false, errwrap.Wrap(errors.New("error determining enabled controllers"), err) } for _, c := range controllers { if c == isolator { return true, nil } } return false, nil } return v1.IsControllerMounted(isolator) }
[ "func", "IsIsolatorSupported", "(", "isolator", "string", ")", "(", "bool", ",", "error", ")", "{", "isUnified", ",", "err", ":=", "IsCgroupUnified", "(", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"", "\"", ")", ",", "err", ")", "\n", "}", "\n\n", "if", "isUnified", "{", "controllers", ",", "err", ":=", "v2", ".", "GetEnabledControllers", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"", "\"", ")", ",", "err", ")", "\n", "}", "\n", "for", "_", ",", "c", ":=", "range", "controllers", "{", "if", "c", "==", "isolator", "{", "return", "true", ",", "nil", "\n", "}", "\n", "}", "\n", "return", "false", ",", "nil", "\n", "}", "\n", "return", "v1", ".", "IsControllerMounted", "(", "isolator", ")", "\n", "}" ]
// IsIsolatorSupported returns whether an isolator is supported in the kernel
[ "IsIsolatorSupported", "returns", "whether", "an", "isolator", "is", "supported", "in", "the", "kernel" ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/common/cgroup/cgroup.go#L37-L56
21,023
rkt/rkt
pkg/backup/backup.go
CreateBackup
func CreateBackup(dir, backupsDir string, limit int) error { tmpBackupDir := filepath.Join(backupsDir, "tmp") if err := os.MkdirAll(backupsDir, 0750); err != nil { return err } if err := fileutil.CopyTree(dir, tmpBackupDir, user.NewBlankUidRange()); err != nil { return err } defer os.RemoveAll(tmpBackupDir) // prune backups if err := pruneOldBackups(backupsDir, limit-1); err != nil { return err } if err := shiftBackups(backupsDir, limit-2); err != nil { return err } if err := os.Rename(tmpBackupDir, filepath.Join(backupsDir, "0")); err != nil { return err } return nil }
go
func CreateBackup(dir, backupsDir string, limit int) error { tmpBackupDir := filepath.Join(backupsDir, "tmp") if err := os.MkdirAll(backupsDir, 0750); err != nil { return err } if err := fileutil.CopyTree(dir, tmpBackupDir, user.NewBlankUidRange()); err != nil { return err } defer os.RemoveAll(tmpBackupDir) // prune backups if err := pruneOldBackups(backupsDir, limit-1); err != nil { return err } if err := shiftBackups(backupsDir, limit-2); err != nil { return err } if err := os.Rename(tmpBackupDir, filepath.Join(backupsDir, "0")); err != nil { return err } return nil }
[ "func", "CreateBackup", "(", "dir", ",", "backupsDir", "string", ",", "limit", "int", ")", "error", "{", "tmpBackupDir", ":=", "filepath", ".", "Join", "(", "backupsDir", ",", "\"", "\"", ")", "\n", "if", "err", ":=", "os", ".", "MkdirAll", "(", "backupsDir", ",", "0750", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "fileutil", ".", "CopyTree", "(", "dir", ",", "tmpBackupDir", ",", "user", ".", "NewBlankUidRange", "(", ")", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "defer", "os", ".", "RemoveAll", "(", "tmpBackupDir", ")", "\n", "// prune backups", "if", "err", ":=", "pruneOldBackups", "(", "backupsDir", ",", "limit", "-", "1", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "shiftBackups", "(", "backupsDir", ",", "limit", "-", "2", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "os", ".", "Rename", "(", "tmpBackupDir", ",", "filepath", ".", "Join", "(", "backupsDir", ",", "\"", "\"", ")", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// CreateBackup backs a directory up in a given directory. It basically // copies this directory into a given backups directory. The backups // directory has a simple structure - a directory inside named "0" is // the most recent backup. A directory name for oldest backup is // deduced from a given limit. For instance, for limit being 5 the // name for the oldest backup would be "4". If a backups number // exceeds the given limit then only newest ones are kept and the rest // is removed.
[ "CreateBackup", "backs", "a", "directory", "up", "in", "a", "given", "directory", ".", "It", "basically", "copies", "this", "directory", "into", "a", "given", "backups", "directory", ".", "The", "backups", "directory", "has", "a", "simple", "structure", "-", "a", "directory", "inside", "named", "0", "is", "the", "most", "recent", "backup", ".", "A", "directory", "name", "for", "oldest", "backup", "is", "deduced", "from", "a", "given", "limit", ".", "For", "instance", "for", "limit", "being", "5", "the", "name", "for", "the", "oldest", "backup", "would", "be", "4", ".", "If", "a", "backups", "number", "exceeds", "the", "given", "limit", "then", "only", "newest", "ones", "are", "kept", "and", "the", "rest", "is", "removed", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/backup/backup.go#L35-L55
21,024
rkt/rkt
pkg/backup/backup.go
pruneOldBackups
func pruneOldBackups(dir string, limit int) error { if list, err := ioutil.ReadDir(dir); err != nil { return err } else { for _, fi := range list { if num, err := strconv.Atoi(fi.Name()); err != nil { // directory name is not a number, // leave it alone continue } else if num < limit { // directory name is a number lower // than a limit, leave it alone continue } path := filepath.Join(dir, fi.Name()) if err := os.RemoveAll(path); err != nil { return err } } } return nil }
go
func pruneOldBackups(dir string, limit int) error { if list, err := ioutil.ReadDir(dir); err != nil { return err } else { for _, fi := range list { if num, err := strconv.Atoi(fi.Name()); err != nil { // directory name is not a number, // leave it alone continue } else if num < limit { // directory name is a number lower // than a limit, leave it alone continue } path := filepath.Join(dir, fi.Name()) if err := os.RemoveAll(path); err != nil { return err } } } return nil }
[ "func", "pruneOldBackups", "(", "dir", "string", ",", "limit", "int", ")", "error", "{", "if", "list", ",", "err", ":=", "ioutil", ".", "ReadDir", "(", "dir", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "else", "{", "for", "_", ",", "fi", ":=", "range", "list", "{", "if", "num", ",", "err", ":=", "strconv", ".", "Atoi", "(", "fi", ".", "Name", "(", ")", ")", ";", "err", "!=", "nil", "{", "// directory name is not a number,", "// leave it alone", "continue", "\n", "}", "else", "if", "num", "<", "limit", "{", "// directory name is a number lower", "// than a limit, leave it alone", "continue", "\n", "}", "\n", "path", ":=", "filepath", ".", "Join", "(", "dir", ",", "fi", ".", "Name", "(", ")", ")", "\n", "if", "err", ":=", "os", ".", "RemoveAll", "(", "path", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// pruneOldBackups removes old backups, that is - directories with // names greater or equal than given limit.
[ "pruneOldBackups", "removes", "old", "backups", "that", "is", "-", "directories", "with", "names", "greater", "or", "equal", "than", "given", "limit", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/backup/backup.go#L59-L80
21,025
rkt/rkt
pkg/backup/backup.go
shiftBackups
func shiftBackups(dir string, oldest int) error { if oldest < 0 { return nil } for i := oldest; i >= 0; i-- { current := filepath.Join(dir, strconv.Itoa(i)) inc := filepath.Join(dir, strconv.Itoa(i+1)) if err := os.Rename(current, inc); err != nil && !os.IsNotExist(err) { return err } } return nil }
go
func shiftBackups(dir string, oldest int) error { if oldest < 0 { return nil } for i := oldest; i >= 0; i-- { current := filepath.Join(dir, strconv.Itoa(i)) inc := filepath.Join(dir, strconv.Itoa(i+1)) if err := os.Rename(current, inc); err != nil && !os.IsNotExist(err) { return err } } return nil }
[ "func", "shiftBackups", "(", "dir", "string", ",", "oldest", "int", ")", "error", "{", "if", "oldest", "<", "0", "{", "return", "nil", "\n", "}", "\n", "for", "i", ":=", "oldest", ";", "i", ">=", "0", ";", "i", "--", "{", "current", ":=", "filepath", ".", "Join", "(", "dir", ",", "strconv", ".", "Itoa", "(", "i", ")", ")", "\n", "inc", ":=", "filepath", ".", "Join", "(", "dir", ",", "strconv", ".", "Itoa", "(", "i", "+", "1", ")", ")", "\n", "if", "err", ":=", "os", ".", "Rename", "(", "current", ",", "inc", ")", ";", "err", "!=", "nil", "&&", "!", "os", ".", "IsNotExist", "(", "err", ")", "{", "return", "err", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// shiftBackups renames all directories with names being numbers up to // oldest to names with numbers greater by one.
[ "shiftBackups", "renames", "all", "directories", "with", "names", "being", "numbers", "up", "to", "oldest", "to", "names", "with", "numbers", "greater", "by", "one", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/backup/backup.go#L84-L96
21,026
rkt/rkt
pkg/aci/aci.go
NewBasicACI
func NewBasicACI(dir string, name string) (*os.File, error) { manifest := schema.ImageManifest{ ACKind: schema.ImageManifestKind, ACVersion: schema.AppContainerVersion, Name: types.ACIdentifier(name), } b, err := manifest.MarshalJSON() if err != nil { return nil, err } return NewACI(dir, string(b), nil) }
go
func NewBasicACI(dir string, name string) (*os.File, error) { manifest := schema.ImageManifest{ ACKind: schema.ImageManifestKind, ACVersion: schema.AppContainerVersion, Name: types.ACIdentifier(name), } b, err := manifest.MarshalJSON() if err != nil { return nil, err } return NewACI(dir, string(b), nil) }
[ "func", "NewBasicACI", "(", "dir", "string", ",", "name", "string", ")", "(", "*", "os", ".", "File", ",", "error", ")", "{", "manifest", ":=", "schema", ".", "ImageManifest", "{", "ACKind", ":", "schema", ".", "ImageManifestKind", ",", "ACVersion", ":", "schema", ".", "AppContainerVersion", ",", "Name", ":", "types", ".", "ACIdentifier", "(", "name", ")", ",", "}", "\n\n", "b", ",", "err", ":=", "manifest", ".", "MarshalJSON", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "NewACI", "(", "dir", ",", "string", "(", "b", ")", ",", "nil", ")", "\n", "}" ]
// NewBasicACI creates a new ACI in the given directory with the given name. // Used for testing.
[ "NewBasicACI", "creates", "a", "new", "ACI", "in", "the", "given", "directory", "with", "the", "given", "name", ".", "Used", "for", "testing", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/aci/aci.go#L109-L122
21,027
rkt/rkt
pkg/aci/aci.go
NewACI
func NewACI(dir string, manifest string, entries []*ACIEntry) (*os.File, error) { var im schema.ImageManifest if err := im.UnmarshalJSON([]byte(manifest)); err != nil { return nil, errwrap.Wrap(errors.New("invalid image manifest"), err) } tf, err := ioutil.TempFile(dir, "") if err != nil { return nil, err } defer os.Remove(tf.Name()) tw := tar.NewWriter(tf) aw := NewImageWriter(im, tw) for _, entry := range entries { // Add default mode if entry.Header.Mode == 0 { if entry.Header.Typeflag == tar.TypeDir { entry.Header.Mode = 0755 } else { entry.Header.Mode = 0644 } } // Add calling user uid and gid or tests will fail entry.Header.Uid = os.Getuid() entry.Header.Gid = os.Getgid() sr := strings.NewReader(entry.Contents) if err := aw.AddFile(entry.Header, sr); err != nil { return nil, err } } if err := aw.Close(); err != nil { return nil, err } return tf, nil }
go
func NewACI(dir string, manifest string, entries []*ACIEntry) (*os.File, error) { var im schema.ImageManifest if err := im.UnmarshalJSON([]byte(manifest)); err != nil { return nil, errwrap.Wrap(errors.New("invalid image manifest"), err) } tf, err := ioutil.TempFile(dir, "") if err != nil { return nil, err } defer os.Remove(tf.Name()) tw := tar.NewWriter(tf) aw := NewImageWriter(im, tw) for _, entry := range entries { // Add default mode if entry.Header.Mode == 0 { if entry.Header.Typeflag == tar.TypeDir { entry.Header.Mode = 0755 } else { entry.Header.Mode = 0644 } } // Add calling user uid and gid or tests will fail entry.Header.Uid = os.Getuid() entry.Header.Gid = os.Getgid() sr := strings.NewReader(entry.Contents) if err := aw.AddFile(entry.Header, sr); err != nil { return nil, err } } if err := aw.Close(); err != nil { return nil, err } return tf, nil }
[ "func", "NewACI", "(", "dir", "string", ",", "manifest", "string", ",", "entries", "[", "]", "*", "ACIEntry", ")", "(", "*", "os", ".", "File", ",", "error", ")", "{", "var", "im", "schema", ".", "ImageManifest", "\n", "if", "err", ":=", "im", ".", "UnmarshalJSON", "(", "[", "]", "byte", "(", "manifest", ")", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"", "\"", ")", ",", "err", ")", "\n", "}", "\n\n", "tf", ",", "err", ":=", "ioutil", ".", "TempFile", "(", "dir", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "defer", "os", ".", "Remove", "(", "tf", ".", "Name", "(", ")", ")", "\n\n", "tw", ":=", "tar", ".", "NewWriter", "(", "tf", ")", "\n", "aw", ":=", "NewImageWriter", "(", "im", ",", "tw", ")", "\n\n", "for", "_", ",", "entry", ":=", "range", "entries", "{", "// Add default mode", "if", "entry", ".", "Header", ".", "Mode", "==", "0", "{", "if", "entry", ".", "Header", ".", "Typeflag", "==", "tar", ".", "TypeDir", "{", "entry", ".", "Header", ".", "Mode", "=", "0755", "\n", "}", "else", "{", "entry", ".", "Header", ".", "Mode", "=", "0644", "\n", "}", "\n", "}", "\n", "// Add calling user uid and gid or tests will fail", "entry", ".", "Header", ".", "Uid", "=", "os", ".", "Getuid", "(", ")", "\n", "entry", ".", "Header", ".", "Gid", "=", "os", ".", "Getgid", "(", ")", "\n", "sr", ":=", "strings", ".", "NewReader", "(", "entry", ".", "Contents", ")", "\n", "if", "err", ":=", "aw", ".", "AddFile", "(", "entry", ".", "Header", ",", "sr", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "}", "\n\n", "if", "err", ":=", "aw", ".", "Close", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "tf", ",", "nil", "\n", "}" ]
// NewACI creates a new ACI in the given directory with the given image // manifest and entries. // Used for testing.
[ "NewACI", "creates", "a", "new", "ACI", "in", "the", "given", "directory", "with", "the", "given", "image", "manifest", "and", "entries", ".", "Used", "for", "testing", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/aci/aci.go#L127-L164
21,028
rkt/rkt
pkg/aci/aci.go
NewDetachedSignature
func NewDetachedSignature(armoredPrivateKey string, aci io.Reader) (io.Reader, error) { entityList, err := openpgp.ReadArmoredKeyRing(bytes.NewBufferString(armoredPrivateKey)) if err != nil { return nil, err } if len(entityList) < 1 { return nil, errors.New("empty entity list") } signature := &bytes.Buffer{} if err := openpgp.ArmoredDetachSign(signature, entityList[0], aci, nil); err != nil { return nil, err } return signature, nil }
go
func NewDetachedSignature(armoredPrivateKey string, aci io.Reader) (io.Reader, error) { entityList, err := openpgp.ReadArmoredKeyRing(bytes.NewBufferString(armoredPrivateKey)) if err != nil { return nil, err } if len(entityList) < 1 { return nil, errors.New("empty entity list") } signature := &bytes.Buffer{} if err := openpgp.ArmoredDetachSign(signature, entityList[0], aci, nil); err != nil { return nil, err } return signature, nil }
[ "func", "NewDetachedSignature", "(", "armoredPrivateKey", "string", ",", "aci", "io", ".", "Reader", ")", "(", "io", ".", "Reader", ",", "error", ")", "{", "entityList", ",", "err", ":=", "openpgp", ".", "ReadArmoredKeyRing", "(", "bytes", ".", "NewBufferString", "(", "armoredPrivateKey", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "len", "(", "entityList", ")", "<", "1", "{", "return", "nil", ",", "errors", ".", "New", "(", "\"", "\"", ")", "\n", "}", "\n", "signature", ":=", "&", "bytes", ".", "Buffer", "{", "}", "\n", "if", "err", ":=", "openpgp", ".", "ArmoredDetachSign", "(", "signature", ",", "entityList", "[", "0", "]", ",", "aci", ",", "nil", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "signature", ",", "nil", "\n", "}" ]
// NewDetachedSignature creates a new openpgp armored detached signature for the given ACI // signed with armoredPrivateKey.
[ "NewDetachedSignature", "creates", "a", "new", "openpgp", "armored", "detached", "signature", "for", "the", "given", "ACI", "signed", "with", "armoredPrivateKey", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/aci/aci.go#L168-L181
21,029
rkt/rkt
pkg/pod/sandbox.go
SandboxManifest
func (p *Pod) SandboxManifest() (*schema.PodManifest, error) { _, pm, err := p.PodManifest() // this takes the lock fd to load the manifest, hence path is not needed here if err != nil { return nil, errwrap.Wrap(errors.New("error loading pod manifest"), err) } ms, ok := pm.Annotations.Get("coreos.com/rkt/stage1/mutable") if ok { p.mutable, err = strconv.ParseBool(ms) if err != nil { return nil, errwrap.Wrap(errors.New("error parsing mutable annotation"), err) } } if !p.mutable { return nil, ErrImmutable } return pm, nil }
go
func (p *Pod) SandboxManifest() (*schema.PodManifest, error) { _, pm, err := p.PodManifest() // this takes the lock fd to load the manifest, hence path is not needed here if err != nil { return nil, errwrap.Wrap(errors.New("error loading pod manifest"), err) } ms, ok := pm.Annotations.Get("coreos.com/rkt/stage1/mutable") if ok { p.mutable, err = strconv.ParseBool(ms) if err != nil { return nil, errwrap.Wrap(errors.New("error parsing mutable annotation"), err) } } if !p.mutable { return nil, ErrImmutable } return pm, nil }
[ "func", "(", "p", "*", "Pod", ")", "SandboxManifest", "(", ")", "(", "*", "schema", ".", "PodManifest", ",", "error", ")", "{", "_", ",", "pm", ",", "err", ":=", "p", ".", "PodManifest", "(", ")", "// this takes the lock fd to load the manifest, hence path is not needed here", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"", "\"", ")", ",", "err", ")", "\n", "}", "\n\n", "ms", ",", "ok", ":=", "pm", ".", "Annotations", ".", "Get", "(", "\"", "\"", ")", "\n", "if", "ok", "{", "p", ".", "mutable", ",", "err", "=", "strconv", ".", "ParseBool", "(", "ms", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"", "\"", ")", ",", "err", ")", "\n", "}", "\n", "}", "\n\n", "if", "!", "p", ".", "mutable", "{", "return", "nil", ",", "ErrImmutable", "\n", "}", "\n\n", "return", "pm", ",", "nil", "\n", "}" ]
// SandboxManifest loads the underlying pod manifest and checks whether mutable operations are allowed. // It returns ErrImmutable if the pod does not allow mutable operations or any other error if the operation failed. // Upon success a reference to the pod manifest is returned and mutable operations are possible.
[ "SandboxManifest", "loads", "the", "underlying", "pod", "manifest", "and", "checks", "whether", "mutable", "operations", "are", "allowed", ".", "It", "returns", "ErrImmutable", "if", "the", "pod", "does", "not", "allow", "mutable", "operations", "or", "any", "other", "error", "if", "the", "operation", "failed", ".", "Upon", "success", "a", "reference", "to", "the", "pod", "manifest", "is", "returned", "and", "mutable", "operations", "are", "possible", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/pod/sandbox.go#L37-L56
21,030
rkt/rkt
pkg/pod/sandbox.go
UpdateManifest
func (p *Pod) UpdateManifest(m *schema.PodManifest, path string) error { if !p.mutable { return ErrImmutable } mpath := common.PodManifestPath(path) mstat, err := os.Stat(mpath) if err != nil { return err } tmpf, err := ioutil.TempFile(path, "") if err != nil { return err } defer func() { tmpf.Close() os.Remove(tmpf.Name()) }() if err := tmpf.Chmod(mstat.Mode().Perm()); err != nil { return err } if err := json.NewEncoder(tmpf).Encode(m); err != nil { return err } if err := os.Rename(tmpf.Name(), mpath); err != nil { return err } return nil }
go
func (p *Pod) UpdateManifest(m *schema.PodManifest, path string) error { if !p.mutable { return ErrImmutable } mpath := common.PodManifestPath(path) mstat, err := os.Stat(mpath) if err != nil { return err } tmpf, err := ioutil.TempFile(path, "") if err != nil { return err } defer func() { tmpf.Close() os.Remove(tmpf.Name()) }() if err := tmpf.Chmod(mstat.Mode().Perm()); err != nil { return err } if err := json.NewEncoder(tmpf).Encode(m); err != nil { return err } if err := os.Rename(tmpf.Name(), mpath); err != nil { return err } return nil }
[ "func", "(", "p", "*", "Pod", ")", "UpdateManifest", "(", "m", "*", "schema", ".", "PodManifest", ",", "path", "string", ")", "error", "{", "if", "!", "p", ".", "mutable", "{", "return", "ErrImmutable", "\n", "}", "\n\n", "mpath", ":=", "common", ".", "PodManifestPath", "(", "path", ")", "\n", "mstat", ",", "err", ":=", "os", ".", "Stat", "(", "mpath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "tmpf", ",", "err", ":=", "ioutil", ".", "TempFile", "(", "path", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "defer", "func", "(", ")", "{", "tmpf", ".", "Close", "(", ")", "\n", "os", ".", "Remove", "(", "tmpf", ".", "Name", "(", ")", ")", "\n", "}", "(", ")", "\n\n", "if", "err", ":=", "tmpf", ".", "Chmod", "(", "mstat", ".", "Mode", "(", ")", ".", "Perm", "(", ")", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "err", ":=", "json", ".", "NewEncoder", "(", "tmpf", ")", ".", "Encode", "(", "m", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "err", ":=", "os", ".", "Rename", "(", "tmpf", ".", "Name", "(", ")", ",", "mpath", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// UpdateManifest updates the given pod manifest in the given path atomically on the file system. // The pod manifest has to be locked using LockManifest first to avoid races in case of concurrent writes.
[ "UpdateManifest", "updates", "the", "given", "pod", "manifest", "in", "the", "given", "path", "atomically", "on", "the", "file", "system", ".", "The", "pod", "manifest", "has", "to", "be", "locked", "using", "LockManifest", "first", "to", "avoid", "races", "in", "case", "of", "concurrent", "writes", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/pod/sandbox.go#L60-L94
21,031
rkt/rkt
pkg/pod/sandbox.go
ExclusiveLockManifest
func (p *Pod) ExclusiveLockManifest() error { if p.manifestLock != nil { return p.manifestLock.ExclusiveLock() // This is idempotent } l, err := lock.ExclusiveLock(common.PodManifestLockPath(p.Path()), lock.RegFile) if err != nil { return err } p.manifestLock = l return nil }
go
func (p *Pod) ExclusiveLockManifest() error { if p.manifestLock != nil { return p.manifestLock.ExclusiveLock() // This is idempotent } l, err := lock.ExclusiveLock(common.PodManifestLockPath(p.Path()), lock.RegFile) if err != nil { return err } p.manifestLock = l return nil }
[ "func", "(", "p", "*", "Pod", ")", "ExclusiveLockManifest", "(", ")", "error", "{", "if", "p", ".", "manifestLock", "!=", "nil", "{", "return", "p", ".", "manifestLock", ".", "ExclusiveLock", "(", ")", "// This is idempotent", "\n", "}", "\n\n", "l", ",", "err", ":=", "lock", ".", "ExclusiveLock", "(", "common", ".", "PodManifestLockPath", "(", "p", ".", "Path", "(", ")", ")", ",", "lock", ".", "RegFile", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "p", ".", "manifestLock", "=", "l", "\n", "return", "nil", "\n", "}" ]
// ExclusiveLockManifest gets an exclusive lock on only the pod manifest in the app sandbox. // Since the pod might already be running, we can't just get an exclusive lock on the pod itself.
[ "ExclusiveLockManifest", "gets", "an", "exclusive", "lock", "on", "only", "the", "pod", "manifest", "in", "the", "app", "sandbox", ".", "Since", "the", "pod", "might", "already", "be", "running", "we", "can", "t", "just", "get", "an", "exclusive", "lock", "on", "the", "pod", "itself", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/pod/sandbox.go#L98-L110
21,032
rkt/rkt
pkg/pod/sandbox.go
UnlockManifest
func (p *Pod) UnlockManifest() error { if p.manifestLock == nil { return nil } if err := p.manifestLock.Close(); err != nil { return err } p.manifestLock = nil return nil }
go
func (p *Pod) UnlockManifest() error { if p.manifestLock == nil { return nil } if err := p.manifestLock.Close(); err != nil { return err } p.manifestLock = nil return nil }
[ "func", "(", "p", "*", "Pod", ")", "UnlockManifest", "(", ")", "error", "{", "if", "p", ".", "manifestLock", "==", "nil", "{", "return", "nil", "\n", "}", "\n\n", "if", "err", ":=", "p", ".", "manifestLock", ".", "Close", "(", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "p", ".", "manifestLock", "=", "nil", "\n", "return", "nil", "\n", "}" ]
// UnlockManifest unlocks the pod manifest lock.
[ "UnlockManifest", "unlocks", "the", "pod", "manifest", "lock", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/pod/sandbox.go#L113-L123
21,033
rkt/rkt
store/imagestore/schema.go
getDBVersion
func getDBVersion(tx *sql.Tx) (int, error) { var version int rows, err := tx.Query("SELECT version FROM version") if err != nil { return -1, err } defer rows.Close() found := false for rows.Next() { if err := rows.Scan(&version); err != nil { return -1, err } found = true break } if err := rows.Err(); err != nil { return -1, err } if !found { return -1, fmt.Errorf("db version table empty") } return version, nil }
go
func getDBVersion(tx *sql.Tx) (int, error) { var version int rows, err := tx.Query("SELECT version FROM version") if err != nil { return -1, err } defer rows.Close() found := false for rows.Next() { if err := rows.Scan(&version); err != nil { return -1, err } found = true break } if err := rows.Err(); err != nil { return -1, err } if !found { return -1, fmt.Errorf("db version table empty") } return version, nil }
[ "func", "getDBVersion", "(", "tx", "*", "sql", ".", "Tx", ")", "(", "int", ",", "error", ")", "{", "var", "version", "int", "\n", "rows", ",", "err", ":=", "tx", ".", "Query", "(", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "-", "1", ",", "err", "\n", "}", "\n", "defer", "rows", ".", "Close", "(", ")", "\n", "found", ":=", "false", "\n", "for", "rows", ".", "Next", "(", ")", "{", "if", "err", ":=", "rows", ".", "Scan", "(", "&", "version", ")", ";", "err", "!=", "nil", "{", "return", "-", "1", ",", "err", "\n", "}", "\n", "found", "=", "true", "\n", "break", "\n", "}", "\n", "if", "err", ":=", "rows", ".", "Err", "(", ")", ";", "err", "!=", "nil", "{", "return", "-", "1", ",", "err", "\n", "}", "\n", "if", "!", "found", "{", "return", "-", "1", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "version", ",", "nil", "\n", "}" ]
// getDBVersion retrieves the current db version
[ "getDBVersion", "retrieves", "the", "current", "db", "version" ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/store/imagestore/schema.go#L66-L88
21,034
rkt/rkt
store/imagestore/schema.go
updateDBVersion
func updateDBVersion(tx *sql.Tx, version int) error { // ql doesn't have an INSERT OR UPDATE function so // it's faster to remove and reinsert the row _, err := tx.Exec("DELETE FROM version") if err != nil { return err } _, err = tx.Exec("INSERT INTO version VALUES ($1)", version) if err != nil { return err } return nil }
go
func updateDBVersion(tx *sql.Tx, version int) error { // ql doesn't have an INSERT OR UPDATE function so // it's faster to remove and reinsert the row _, err := tx.Exec("DELETE FROM version") if err != nil { return err } _, err = tx.Exec("INSERT INTO version VALUES ($1)", version) if err != nil { return err } return nil }
[ "func", "updateDBVersion", "(", "tx", "*", "sql", ".", "Tx", ",", "version", "int", ")", "error", "{", "// ql doesn't have an INSERT OR UPDATE function so", "// it's faster to remove and reinsert the row", "_", ",", "err", ":=", "tx", ".", "Exec", "(", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "_", ",", "err", "=", "tx", ".", "Exec", "(", "\"", "\"", ",", "version", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// updateDBVersion updates the db version
[ "updateDBVersion", "updates", "the", "db", "version" ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/store/imagestore/schema.go#L91-L103
21,035
rkt/rkt
pkg/acl/acl.go
InitACL
func InitACL() (*ACL, error) { h, err := getHandle() if err != nil { return nil, err } return &ACL{lib: h}, nil }
go
func InitACL() (*ACL, error) { h, err := getHandle() if err != nil { return nil, err } return &ACL{lib: h}, nil }
[ "func", "InitACL", "(", ")", "(", "*", "ACL", ",", "error", ")", "{", "h", ",", "err", ":=", "getHandle", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "&", "ACL", "{", "lib", ":", "h", "}", ",", "nil", "\n", "}" ]
// InitACL dlopens libacl and returns an ACL object if successful.
[ "InitACL", "dlopens", "libacl", "and", "returns", "an", "ACL", "object", "if", "successful", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/acl/acl.go#L220-L227
21,036
rkt/rkt
pkg/acl/acl.go
ParseACL
func (a *ACL) ParseACL(acl string) error { acl_from_text, err := getSymbolPointer(a.lib.handle, "acl_from_text") if err != nil { return err } cacl := C.CString(acl) defer C.free(unsafe.Pointer(cacl)) retACL, err := C.my_acl_from_text(acl_from_text, cacl) if retACL == nil { return errwrap.Wrap(errors.New("error calling acl_from_text"), err) } a.a = retACL return nil }
go
func (a *ACL) ParseACL(acl string) error { acl_from_text, err := getSymbolPointer(a.lib.handle, "acl_from_text") if err != nil { return err } cacl := C.CString(acl) defer C.free(unsafe.Pointer(cacl)) retACL, err := C.my_acl_from_text(acl_from_text, cacl) if retACL == nil { return errwrap.Wrap(errors.New("error calling acl_from_text"), err) } a.a = retACL return nil }
[ "func", "(", "a", "*", "ACL", ")", "ParseACL", "(", "acl", "string", ")", "error", "{", "acl_from_text", ",", "err", ":=", "getSymbolPointer", "(", "a", ".", "lib", ".", "handle", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "cacl", ":=", "C", ".", "CString", "(", "acl", ")", "\n", "defer", "C", ".", "free", "(", "unsafe", ".", "Pointer", "(", "cacl", ")", ")", "\n\n", "retACL", ",", "err", ":=", "C", ".", "my_acl_from_text", "(", "acl_from_text", ",", "cacl", ")", "\n", "if", "retACL", "==", "nil", "{", "return", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"", "\"", ")", ",", "err", ")", "\n", "}", "\n\n", "a", ".", "a", "=", "retACL", "\n\n", "return", "nil", "\n", "}" ]
// ParseACL parses a string representation of an ACL.
[ "ParseACL", "parses", "a", "string", "representation", "of", "an", "ACL", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/acl/acl.go#L230-L246
21,037
rkt/rkt
pkg/acl/acl.go
Free
func (a *ACL) Free() error { acl_free, err := getSymbolPointer(a.lib.handle, "acl_free") if err != nil { return err } ret, err := C.my_acl_free(acl_free, a.a) if ret < 0 { return errwrap.Wrap(errors.New("error calling acl_free"), err) } return a.lib.close() }
go
func (a *ACL) Free() error { acl_free, err := getSymbolPointer(a.lib.handle, "acl_free") if err != nil { return err } ret, err := C.my_acl_free(acl_free, a.a) if ret < 0 { return errwrap.Wrap(errors.New("error calling acl_free"), err) } return a.lib.close() }
[ "func", "(", "a", "*", "ACL", ")", "Free", "(", ")", "error", "{", "acl_free", ",", "err", ":=", "getSymbolPointer", "(", "a", ".", "lib", ".", "handle", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "ret", ",", "err", ":=", "C", ".", "my_acl_free", "(", "acl_free", ",", "a", ".", "a", ")", "\n", "if", "ret", "<", "0", "{", "return", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"", "\"", ")", ",", "err", ")", "\n", "}", "\n\n", "return", "a", ".", "lib", ".", "close", "(", ")", "\n", "}" ]
// Free frees libacl's internal structures and closes libacl.
[ "Free", "frees", "libacl", "s", "internal", "structures", "and", "closes", "libacl", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/acl/acl.go#L249-L261
21,038
rkt/rkt
pkg/acl/acl.go
SetFileACLDefault
func (a *ACL) SetFileACLDefault(path string) error { acl_set_file, err := getSymbolPointer(a.lib.handle, "acl_set_file") if err != nil { return err } cpath := C.CString(path) defer C.free(unsafe.Pointer(cpath)) ret, err := C.my_acl_set_file(acl_set_file, cpath, C.ACL_TYPE_DEFAULT, a.a) if ret < 0 { return errwrap.Wrap(errors.New("error calling acl_set_file"), err) } return nil }
go
func (a *ACL) SetFileACLDefault(path string) error { acl_set_file, err := getSymbolPointer(a.lib.handle, "acl_set_file") if err != nil { return err } cpath := C.CString(path) defer C.free(unsafe.Pointer(cpath)) ret, err := C.my_acl_set_file(acl_set_file, cpath, C.ACL_TYPE_DEFAULT, a.a) if ret < 0 { return errwrap.Wrap(errors.New("error calling acl_set_file"), err) } return nil }
[ "func", "(", "a", "*", "ACL", ")", "SetFileACLDefault", "(", "path", "string", ")", "error", "{", "acl_set_file", ",", "err", ":=", "getSymbolPointer", "(", "a", ".", "lib", ".", "handle", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "cpath", ":=", "C", ".", "CString", "(", "path", ")", "\n", "defer", "C", ".", "free", "(", "unsafe", ".", "Pointer", "(", "cpath", ")", ")", "\n\n", "ret", ",", "err", ":=", "C", ".", "my_acl_set_file", "(", "acl_set_file", ",", "cpath", ",", "C", ".", "ACL_TYPE_DEFAULT", ",", "a", ".", "a", ")", "\n", "if", "ret", "<", "0", "{", "return", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"", "\"", ")", ",", "err", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// SetFileACLDefault sets the "default" ACL for path.
[ "SetFileACLDefault", "sets", "the", "default", "ACL", "for", "path", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/acl/acl.go#L264-L279
21,039
rkt/rkt
pkg/acl/acl.go
Valid
func (a *ACL) Valid() error { acl_valid, err := getSymbolPointer(a.lib.handle, "acl_valid") if err != nil { return err } ret, err := C.my_acl_valid(acl_valid, a.a) if ret < 0 { return errwrap.Wrap(errors.New("invalid acl"), err) } return nil }
go
func (a *ACL) Valid() error { acl_valid, err := getSymbolPointer(a.lib.handle, "acl_valid") if err != nil { return err } ret, err := C.my_acl_valid(acl_valid, a.a) if ret < 0 { return errwrap.Wrap(errors.New("invalid acl"), err) } return nil }
[ "func", "(", "a", "*", "ACL", ")", "Valid", "(", ")", "error", "{", "acl_valid", ",", "err", ":=", "getSymbolPointer", "(", "a", ".", "lib", ".", "handle", ",", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "ret", ",", "err", ":=", "C", ".", "my_acl_valid", "(", "acl_valid", ",", "a", ".", "a", ")", "\n", "if", "ret", "<", "0", "{", "return", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"", "\"", ")", ",", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// Valid checks whether the ACL is valid.
[ "Valid", "checks", "whether", "the", "ACL", "is", "valid", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/acl/acl.go#L282-L293
21,040
rkt/rkt
pkg/acl/acl.go
AddBaseEntries
func (a *ACL) AddBaseEntries(path string) error { fi, err := os.Lstat(path) if err != nil { return err } mode := fi.Mode().Perm() var r, w, x bool // set USER_OBJ entry r = mode&userRead == userRead w = mode&userWrite == userWrite x = mode&userExec == userExec if err := a.addBaseEntryFromMode(TagUserObj, r, w, x); err != nil { return err } // set GROUP_OBJ entry r = mode&groupRead == groupRead w = mode&groupWrite == groupWrite x = mode&groupExec == groupExec if err := a.addBaseEntryFromMode(TagGroupObj, r, w, x); err != nil { return err } // set OTHER entry r = mode&otherRead == otherRead w = mode&otherWrite == otherWrite x = mode&otherExec == otherExec if err := a.addBaseEntryFromMode(TagOther, r, w, x); err != nil { return err } return nil }
go
func (a *ACL) AddBaseEntries(path string) error { fi, err := os.Lstat(path) if err != nil { return err } mode := fi.Mode().Perm() var r, w, x bool // set USER_OBJ entry r = mode&userRead == userRead w = mode&userWrite == userWrite x = mode&userExec == userExec if err := a.addBaseEntryFromMode(TagUserObj, r, w, x); err != nil { return err } // set GROUP_OBJ entry r = mode&groupRead == groupRead w = mode&groupWrite == groupWrite x = mode&groupExec == groupExec if err := a.addBaseEntryFromMode(TagGroupObj, r, w, x); err != nil { return err } // set OTHER entry r = mode&otherRead == otherRead w = mode&otherWrite == otherWrite x = mode&otherExec == otherExec if err := a.addBaseEntryFromMode(TagOther, r, w, x); err != nil { return err } return nil }
[ "func", "(", "a", "*", "ACL", ")", "AddBaseEntries", "(", "path", "string", ")", "error", "{", "fi", ",", "err", ":=", "os", ".", "Lstat", "(", "path", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "mode", ":=", "fi", ".", "Mode", "(", ")", ".", "Perm", "(", ")", "\n", "var", "r", ",", "w", ",", "x", "bool", "\n\n", "// set USER_OBJ entry", "r", "=", "mode", "&", "userRead", "==", "userRead", "\n", "w", "=", "mode", "&", "userWrite", "==", "userWrite", "\n", "x", "=", "mode", "&", "userExec", "==", "userExec", "\n", "if", "err", ":=", "a", ".", "addBaseEntryFromMode", "(", "TagUserObj", ",", "r", ",", "w", ",", "x", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// set GROUP_OBJ entry", "r", "=", "mode", "&", "groupRead", "==", "groupRead", "\n", "w", "=", "mode", "&", "groupWrite", "==", "groupWrite", "\n", "x", "=", "mode", "&", "groupExec", "==", "groupExec", "\n", "if", "err", ":=", "a", ".", "addBaseEntryFromMode", "(", "TagGroupObj", ",", "r", ",", "w", ",", "x", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// set OTHER entry", "r", "=", "mode", "&", "otherRead", "==", "otherRead", "\n", "w", "=", "mode", "&", "otherWrite", "==", "otherWrite", "\n", "x", "=", "mode", "&", "otherExec", "==", "otherExec", "\n", "if", "err", ":=", "a", ".", "addBaseEntryFromMode", "(", "TagOther", ",", "r", ",", "w", ",", "x", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// AddBaseEntries adds the base ACL entries from the file permissions.
[ "AddBaseEntries", "adds", "the", "base", "ACL", "entries", "from", "the", "file", "permissions", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/acl/acl.go#L296-L329
21,041
rkt/rkt
pkg/distribution/appc.go
NewAppc
func NewAppc(u *url.URL) (Distribution, error) { c, err := parseCIMD(u) if err != nil { return nil, fmt.Errorf("cannot parse URI: %q: %v", u.String(), err) } if c.Type != TypeAppc { return nil, fmt.Errorf("wrong distribution type: %q", c.Type) } appcStr := c.Data for n, v := range u.Query() { appcStr += fmt.Sprintf(",%s=%s", n, v[0]) } app, err := discovery.NewAppFromString(appcStr) if err != nil { return nil, fmt.Errorf("wrong appc image string %q: %v", u.String(), err) } return NewAppcFromApp(app), nil }
go
func NewAppc(u *url.URL) (Distribution, error) { c, err := parseCIMD(u) if err != nil { return nil, fmt.Errorf("cannot parse URI: %q: %v", u.String(), err) } if c.Type != TypeAppc { return nil, fmt.Errorf("wrong distribution type: %q", c.Type) } appcStr := c.Data for n, v := range u.Query() { appcStr += fmt.Sprintf(",%s=%s", n, v[0]) } app, err := discovery.NewAppFromString(appcStr) if err != nil { return nil, fmt.Errorf("wrong appc image string %q: %v", u.String(), err) } return NewAppcFromApp(app), nil }
[ "func", "NewAppc", "(", "u", "*", "url", ".", "URL", ")", "(", "Distribution", ",", "error", ")", "{", "c", ",", "err", ":=", "parseCIMD", "(", "u", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "u", ".", "String", "(", ")", ",", "err", ")", "\n", "}", "\n", "if", "c", ".", "Type", "!=", "TypeAppc", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "c", ".", "Type", ")", "\n", "}", "\n\n", "appcStr", ":=", "c", ".", "Data", "\n", "for", "n", ",", "v", ":=", "range", "u", ".", "Query", "(", ")", "{", "appcStr", "+=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "n", ",", "v", "[", "0", "]", ")", "\n", "}", "\n", "app", ",", "err", ":=", "discovery", ".", "NewAppFromString", "(", "appcStr", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "u", ".", "String", "(", ")", ",", "err", ")", "\n", "}", "\n\n", "return", "NewAppcFromApp", "(", "app", ")", ",", "nil", "\n", "}" ]
// NewAppc returns an Appc distribution from an Appc distribution URI
[ "NewAppc", "returns", "an", "Appc", "distribution", "from", "an", "Appc", "distribution", "URI" ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/distribution/appc.go#L52-L71
21,042
rkt/rkt
pkg/distribution/appc.go
NewAppcFromApp
func NewAppcFromApp(app *discovery.App) Distribution { rawuri := NewCIMDString(TypeAppc, distAppcVersion, url.QueryEscape(app.Name.String())) var version string labels := types.Labels{} for n, v := range app.Labels { if n == "version" { version = v } labels = append(labels, types.Label{Name: n, Value: v}) } if len(labels) > 0 { queries := make([]string, len(labels)) rawuri += "?" for i, l := range labels { queries[i] = fmt.Sprintf("%s=%s", l.Name, url.QueryEscape(l.Value)) } rawuri += strings.Join(queries, "&") } u, err := url.Parse(rawuri) if err != nil { panic(fmt.Errorf("cannot parse URI %q: %v", rawuri, err)) } // save the URI as sorted to make it ready for comparison purell.NormalizeURL(u, purell.FlagSortQuery) str := app.Name.String() if version != "" { str += fmt.Sprintf(":%s", version) } labelsort.By(labelsort.RankedName).Sort(labels) for _, l := range labels { if l.Name != "version" { str += fmt.Sprintf(",%s=%s", l.Name, l.Value) } } return &Appc{ cimd: u, app: app.Copy(), str: str, } }
go
func NewAppcFromApp(app *discovery.App) Distribution { rawuri := NewCIMDString(TypeAppc, distAppcVersion, url.QueryEscape(app.Name.String())) var version string labels := types.Labels{} for n, v := range app.Labels { if n == "version" { version = v } labels = append(labels, types.Label{Name: n, Value: v}) } if len(labels) > 0 { queries := make([]string, len(labels)) rawuri += "?" for i, l := range labels { queries[i] = fmt.Sprintf("%s=%s", l.Name, url.QueryEscape(l.Value)) } rawuri += strings.Join(queries, "&") } u, err := url.Parse(rawuri) if err != nil { panic(fmt.Errorf("cannot parse URI %q: %v", rawuri, err)) } // save the URI as sorted to make it ready for comparison purell.NormalizeURL(u, purell.FlagSortQuery) str := app.Name.String() if version != "" { str += fmt.Sprintf(":%s", version) } labelsort.By(labelsort.RankedName).Sort(labels) for _, l := range labels { if l.Name != "version" { str += fmt.Sprintf(",%s=%s", l.Name, l.Value) } } return &Appc{ cimd: u, app: app.Copy(), str: str, } }
[ "func", "NewAppcFromApp", "(", "app", "*", "discovery", ".", "App", ")", "Distribution", "{", "rawuri", ":=", "NewCIMDString", "(", "TypeAppc", ",", "distAppcVersion", ",", "url", ".", "QueryEscape", "(", "app", ".", "Name", ".", "String", "(", ")", ")", ")", "\n\n", "var", "version", "string", "\n", "labels", ":=", "types", ".", "Labels", "{", "}", "\n", "for", "n", ",", "v", ":=", "range", "app", ".", "Labels", "{", "if", "n", "==", "\"", "\"", "{", "version", "=", "v", "\n", "}", "\n\n", "labels", "=", "append", "(", "labels", ",", "types", ".", "Label", "{", "Name", ":", "n", ",", "Value", ":", "v", "}", ")", "\n", "}", "\n\n", "if", "len", "(", "labels", ")", ">", "0", "{", "queries", ":=", "make", "(", "[", "]", "string", ",", "len", "(", "labels", ")", ")", "\n", "rawuri", "+=", "\"", "\"", "\n", "for", "i", ",", "l", ":=", "range", "labels", "{", "queries", "[", "i", "]", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "l", ".", "Name", ",", "url", ".", "QueryEscape", "(", "l", ".", "Value", ")", ")", "\n", "}", "\n", "rawuri", "+=", "strings", ".", "Join", "(", "queries", ",", "\"", "\"", ")", "\n", "}", "\n\n", "u", ",", "err", ":=", "url", ".", "Parse", "(", "rawuri", ")", "\n", "if", "err", "!=", "nil", "{", "panic", "(", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "rawuri", ",", "err", ")", ")", "\n", "}", "\n\n", "// save the URI as sorted to make it ready for comparison", "purell", ".", "NormalizeURL", "(", "u", ",", "purell", ".", "FlagSortQuery", ")", "\n\n", "str", ":=", "app", ".", "Name", ".", "String", "(", ")", "\n", "if", "version", "!=", "\"", "\"", "{", "str", "+=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "version", ")", "\n", "}", "\n\n", "labelsort", ".", "By", "(", "labelsort", ".", "RankedName", ")", ".", "Sort", "(", "labels", ")", "\n", "for", "_", ",", "l", ":=", "range", "labels", "{", "if", "l", ".", "Name", "!=", "\"", "\"", "{", "str", "+=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "l", ".", "Name", ",", "l", ".", "Value", ")", "\n", "}", "\n", "}", "\n\n", "return", "&", "Appc", "{", "cimd", ":", "u", ",", "app", ":", "app", ".", "Copy", "(", ")", ",", "str", ":", "str", ",", "}", "\n", "}" ]
// NewAppcFromApp returns an Appc distribution from an appc App discovery string
[ "NewAppcFromApp", "returns", "an", "Appc", "distribution", "from", "an", "appc", "App", "discovery", "string" ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/distribution/appc.go#L74-L121
21,043
rkt/rkt
pkg/sys/sys.go
CloseOnExec
func CloseOnExec(fd int, set bool) error { flag := uintptr(0) if set { flag = syscall.FD_CLOEXEC } _, _, err := syscall.RawSyscall(syscall.SYS_FCNTL, uintptr(fd), syscall.F_SETFD, flag) if err != 0 { return syscall.Errno(err) } return nil }
go
func CloseOnExec(fd int, set bool) error { flag := uintptr(0) if set { flag = syscall.FD_CLOEXEC } _, _, err := syscall.RawSyscall(syscall.SYS_FCNTL, uintptr(fd), syscall.F_SETFD, flag) if err != 0 { return syscall.Errno(err) } return nil }
[ "func", "CloseOnExec", "(", "fd", "int", ",", "set", "bool", ")", "error", "{", "flag", ":=", "uintptr", "(", "0", ")", "\n", "if", "set", "{", "flag", "=", "syscall", ".", "FD_CLOEXEC", "\n", "}", "\n", "_", ",", "_", ",", "err", ":=", "syscall", ".", "RawSyscall", "(", "syscall", ".", "SYS_FCNTL", ",", "uintptr", "(", "fd", ")", ",", "syscall", ".", "F_SETFD", ",", "flag", ")", "\n", "if", "err", "!=", "0", "{", "return", "syscall", ".", "Errno", "(", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// CloseOnExec sets or clears FD_CLOEXEC flag on a file descriptor
[ "CloseOnExec", "sets", "or", "clears", "FD_CLOEXEC", "flag", "on", "a", "file", "descriptor" ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/sys/sys.go#L22-L32
21,044
rkt/rkt
common/cgroup/v2/cgroup.go
GetEnabledControllers
func GetEnabledControllers() ([]string, error) { controllersFile, err := os.Open("/sys/fs/cgroup/cgroup.controllers") if err != nil { return nil, err } defer controllersFile.Close() sc := bufio.NewScanner(controllersFile) sc.Scan() if err := sc.Err(); err != nil { return nil, err } return strings.Split(sc.Text(), " "), nil }
go
func GetEnabledControllers() ([]string, error) { controllersFile, err := os.Open("/sys/fs/cgroup/cgroup.controllers") if err != nil { return nil, err } defer controllersFile.Close() sc := bufio.NewScanner(controllersFile) sc.Scan() if err := sc.Err(); err != nil { return nil, err } return strings.Split(sc.Text(), " "), nil }
[ "func", "GetEnabledControllers", "(", ")", "(", "[", "]", "string", ",", "error", ")", "{", "controllersFile", ",", "err", ":=", "os", ".", "Open", "(", "\"", "\"", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "defer", "controllersFile", ".", "Close", "(", ")", "\n\n", "sc", ":=", "bufio", ".", "NewScanner", "(", "controllersFile", ")", "\n\n", "sc", ".", "Scan", "(", ")", "\n", "if", "err", ":=", "sc", ".", "Err", "(", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "strings", ".", "Split", "(", "sc", ".", "Text", "(", ")", ",", "\"", "\"", ")", ",", "nil", "\n", "}" ]
// GetEnabledControllers returns a list of enabled cgroup controllers
[ "GetEnabledControllers", "returns", "a", "list", "of", "enabled", "cgroup", "controllers" ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/common/cgroup/v2/cgroup.go#L30-L45
21,045
rkt/rkt
tools/depsgen/globcmd.go
globGetArgs
func globGetArgs(args []string) globArgs { f, target := standardFlags(globCmd) suffix := f.String("suffix", "", "File suffix (example: .go)") globbingMode := f.String("glob-mode", "all", "Which files to glob (normal, dot-files, all [default])") filelist := f.String("filelist", "", "Read all the files from this file") var mapTo []string mapToWrapper := common.StringSliceWrapper{Slice: &mapTo} f.Var(&mapToWrapper, "map-to", "Map contents of filelist to this directory, can be used multiple times") f.Parse(args) if *target == "" { common.Die("--target parameter must be specified and cannot be empty") } mode := globModeFromString(*globbingMode) if *filelist == "" { common.Die("--filelist parameter must be specified and cannot be empty") } if len(mapTo) < 1 { common.Die("--map-to parameter must be specified at least once") } return globArgs{ target: *target, suffix: *suffix, mode: mode, filelist: *filelist, mapTo: mapTo, } }
go
func globGetArgs(args []string) globArgs { f, target := standardFlags(globCmd) suffix := f.String("suffix", "", "File suffix (example: .go)") globbingMode := f.String("glob-mode", "all", "Which files to glob (normal, dot-files, all [default])") filelist := f.String("filelist", "", "Read all the files from this file") var mapTo []string mapToWrapper := common.StringSliceWrapper{Slice: &mapTo} f.Var(&mapToWrapper, "map-to", "Map contents of filelist to this directory, can be used multiple times") f.Parse(args) if *target == "" { common.Die("--target parameter must be specified and cannot be empty") } mode := globModeFromString(*globbingMode) if *filelist == "" { common.Die("--filelist parameter must be specified and cannot be empty") } if len(mapTo) < 1 { common.Die("--map-to parameter must be specified at least once") } return globArgs{ target: *target, suffix: *suffix, mode: mode, filelist: *filelist, mapTo: mapTo, } }
[ "func", "globGetArgs", "(", "args", "[", "]", "string", ")", "globArgs", "{", "f", ",", "target", ":=", "standardFlags", "(", "globCmd", ")", "\n", "suffix", ":=", "f", ".", "String", "(", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "globbingMode", ":=", "f", ".", "String", "(", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "filelist", ":=", "f", ".", "String", "(", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "var", "mapTo", "[", "]", "string", "\n", "mapToWrapper", ":=", "common", ".", "StringSliceWrapper", "{", "Slice", ":", "&", "mapTo", "}", "\n", "f", ".", "Var", "(", "&", "mapToWrapper", ",", "\"", "\"", ",", "\"", "\"", ")", "\n\n", "f", ".", "Parse", "(", "args", ")", "\n", "if", "*", "target", "==", "\"", "\"", "{", "common", ".", "Die", "(", "\"", "\"", ")", "\n", "}", "\n", "mode", ":=", "globModeFromString", "(", "*", "globbingMode", ")", "\n", "if", "*", "filelist", "==", "\"", "\"", "{", "common", ".", "Die", "(", "\"", "\"", ")", "\n", "}", "\n", "if", "len", "(", "mapTo", ")", "<", "1", "{", "common", ".", "Die", "(", "\"", "\"", ")", "\n", "}", "\n", "return", "globArgs", "{", "target", ":", "*", "target", ",", "suffix", ":", "*", "suffix", ",", "mode", ":", "mode", ",", "filelist", ":", "*", "filelist", ",", "mapTo", ":", "mapTo", ",", "}", "\n", "}" ]
// globGetArgs parses given parameters and returns a target, a suffix // and a list of files.
[ "globGetArgs", "parses", "given", "parameters", "and", "returns", "a", "target", "a", "suffix", "and", "a", "list", "of", "files", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/tools/depsgen/globcmd.go#L76-L103
21,046
rkt/rkt
tools/depsgen/globcmd.go
globGetMakeFunction
func globGetMakeFunction(files []string, suffix string, mode globMode) string { dirs := map[string]struct{}{} for _, file := range files { dirs[filepath.Dir(file)] = struct{}{} } makeWildcards := make([]string, 0, len(dirs)) wildcard := globGetMakeSnippet(mode) for dir := range dirs { str := replacePlaceholders(wildcard, "SUFFIX", suffix, "DIR", dir) makeWildcards = append(makeWildcards, str) } return replacePlaceholders(globMakeFunction, "WILDCARDS", strings.Join(makeWildcards, " ")) }
go
func globGetMakeFunction(files []string, suffix string, mode globMode) string { dirs := map[string]struct{}{} for _, file := range files { dirs[filepath.Dir(file)] = struct{}{} } makeWildcards := make([]string, 0, len(dirs)) wildcard := globGetMakeSnippet(mode) for dir := range dirs { str := replacePlaceholders(wildcard, "SUFFIX", suffix, "DIR", dir) makeWildcards = append(makeWildcards, str) } return replacePlaceholders(globMakeFunction, "WILDCARDS", strings.Join(makeWildcards, " ")) }
[ "func", "globGetMakeFunction", "(", "files", "[", "]", "string", ",", "suffix", "string", ",", "mode", "globMode", ")", "string", "{", "dirs", ":=", "map", "[", "string", "]", "struct", "{", "}", "{", "}", "\n", "for", "_", ",", "file", ":=", "range", "files", "{", "dirs", "[", "filepath", ".", "Dir", "(", "file", ")", "]", "=", "struct", "{", "}", "{", "}", "\n", "}", "\n", "makeWildcards", ":=", "make", "(", "[", "]", "string", ",", "0", ",", "len", "(", "dirs", ")", ")", "\n", "wildcard", ":=", "globGetMakeSnippet", "(", "mode", ")", "\n", "for", "dir", ":=", "range", "dirs", "{", "str", ":=", "replacePlaceholders", "(", "wildcard", ",", "\"", "\"", ",", "suffix", ",", "\"", "\"", ",", "dir", ")", "\n", "makeWildcards", "=", "append", "(", "makeWildcards", ",", "str", ")", "\n", "}", "\n", "return", "replacePlaceholders", "(", "globMakeFunction", ",", "\"", "\"", ",", "strings", ".", "Join", "(", "makeWildcards", ",", "\"", "\"", ")", ")", "\n", "}" ]
// globGetMakeFunction returns a make snippet which calls wildcard // function in all directories where given files are and with a given // suffix.
[ "globGetMakeFunction", "returns", "a", "make", "snippet", "which", "calls", "wildcard", "function", "in", "all", "directories", "where", "given", "files", "are", "and", "with", "a", "given", "suffix", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/tools/depsgen/globcmd.go#L143-L155
21,047
rkt/rkt
pkg/pod/wait.go
WaitFinished
func (p *Pod) WaitFinished(ctx context.Context) error { f := func() bool { switch err := p.TrySharedLock(); err { case nil: // the pod is now locked successfully, hence one of the running phases passed. // continue with unlocking the pod immediately below. case lock.ErrLocked: // pod is still locked, hence we are still in a running phase. // i.e. in pepare, run, exitedGarbage, garbage state. return false default: // some error occurred, bail out. return true } // unlock immediately if err := p.Unlock(); err != nil { return true } if err := p.refreshState(); err != nil { return true } // if we're in the gap between preparing and running in a split prepare/run-prepared usage, take a nap if p.isPrepared { time.Sleep(time.Second) } return p.IsFinished() } return retry(ctx, f, 100*time.Millisecond) }
go
func (p *Pod) WaitFinished(ctx context.Context) error { f := func() bool { switch err := p.TrySharedLock(); err { case nil: // the pod is now locked successfully, hence one of the running phases passed. // continue with unlocking the pod immediately below. case lock.ErrLocked: // pod is still locked, hence we are still in a running phase. // i.e. in pepare, run, exitedGarbage, garbage state. return false default: // some error occurred, bail out. return true } // unlock immediately if err := p.Unlock(); err != nil { return true } if err := p.refreshState(); err != nil { return true } // if we're in the gap between preparing and running in a split prepare/run-prepared usage, take a nap if p.isPrepared { time.Sleep(time.Second) } return p.IsFinished() } return retry(ctx, f, 100*time.Millisecond) }
[ "func", "(", "p", "*", "Pod", ")", "WaitFinished", "(", "ctx", "context", ".", "Context", ")", "error", "{", "f", ":=", "func", "(", ")", "bool", "{", "switch", "err", ":=", "p", ".", "TrySharedLock", "(", ")", ";", "err", "{", "case", "nil", ":", "// the pod is now locked successfully, hence one of the running phases passed.", "// continue with unlocking the pod immediately below.", "case", "lock", ".", "ErrLocked", ":", "// pod is still locked, hence we are still in a running phase.", "// i.e. in pepare, run, exitedGarbage, garbage state.", "return", "false", "\n", "default", ":", "// some error occurred, bail out.", "return", "true", "\n", "}", "\n\n", "// unlock immediately", "if", "err", ":=", "p", ".", "Unlock", "(", ")", ";", "err", "!=", "nil", "{", "return", "true", "\n", "}", "\n\n", "if", "err", ":=", "p", ".", "refreshState", "(", ")", ";", "err", "!=", "nil", "{", "return", "true", "\n", "}", "\n\n", "// if we're in the gap between preparing and running in a split prepare/run-prepared usage, take a nap", "if", "p", ".", "isPrepared", "{", "time", ".", "Sleep", "(", "time", ".", "Second", ")", "\n", "}", "\n\n", "return", "p", ".", "IsFinished", "(", ")", "\n", "}", "\n\n", "return", "retry", "(", "ctx", ",", "f", ",", "100", "*", "time", ".", "Millisecond", ")", "\n", "}" ]
// WaitFinished waits for a pod to finish by polling every 100 milliseconds // or until the given context is cancelled. This method refreshes the pod state. // It is the caller's responsibility to determine the actual terminal state.
[ "WaitFinished", "waits", "for", "a", "pod", "to", "finish", "by", "polling", "every", "100", "milliseconds", "or", "until", "the", "given", "context", "is", "cancelled", ".", "This", "method", "refreshes", "the", "pod", "state", ".", "It", "is", "the", "caller", "s", "responsibility", "to", "determine", "the", "actual", "terminal", "state", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/pod/wait.go#L28-L61
21,048
rkt/rkt
pkg/pod/wait.go
WaitReady
func (p *Pod) WaitReady(ctx context.Context) error { f := func() bool { if err := p.refreshState(); err != nil { return false } return p.IsSupervisorReady() } return retry(ctx, f, 100*time.Millisecond) }
go
func (p *Pod) WaitReady(ctx context.Context) error { f := func() bool { if err := p.refreshState(); err != nil { return false } return p.IsSupervisorReady() } return retry(ctx, f, 100*time.Millisecond) }
[ "func", "(", "p", "*", "Pod", ")", "WaitReady", "(", "ctx", "context", ".", "Context", ")", "error", "{", "f", ":=", "func", "(", ")", "bool", "{", "if", "err", ":=", "p", ".", "refreshState", "(", ")", ";", "err", "!=", "nil", "{", "return", "false", "\n", "}", "\n\n", "return", "p", ".", "IsSupervisorReady", "(", ")", "\n", "}", "\n\n", "return", "retry", "(", "ctx", ",", "f", ",", "100", "*", "time", ".", "Millisecond", ")", "\n", "}" ]
// WaitReady blocks until the pod is ready by polling the readiness state every 100 milliseconds // or until the given context is cancelled. This method refreshes the pod state.
[ "WaitReady", "blocks", "until", "the", "pod", "is", "ready", "by", "polling", "the", "readiness", "state", "every", "100", "milliseconds", "or", "until", "the", "given", "context", "is", "cancelled", ".", "This", "method", "refreshes", "the", "pod", "state", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/pod/wait.go#L65-L75
21,049
rkt/rkt
pkg/pod/wait.go
retry
func retry(ctx context.Context, f func() bool, delay time.Duration) error { if f() { return nil } ticker := time.NewTicker(delay) errChan := make(chan error) go func() { defer close(errChan) for { select { case <-ctx.Done(): errChan <- ctx.Err() return case <-ticker.C: if f() { return } } } }() return <-errChan }
go
func retry(ctx context.Context, f func() bool, delay time.Duration) error { if f() { return nil } ticker := time.NewTicker(delay) errChan := make(chan error) go func() { defer close(errChan) for { select { case <-ctx.Done(): errChan <- ctx.Err() return case <-ticker.C: if f() { return } } } }() return <-errChan }
[ "func", "retry", "(", "ctx", "context", ".", "Context", ",", "f", "func", "(", ")", "bool", ",", "delay", "time", ".", "Duration", ")", "error", "{", "if", "f", "(", ")", "{", "return", "nil", "\n", "}", "\n\n", "ticker", ":=", "time", ".", "NewTicker", "(", "delay", ")", "\n", "errChan", ":=", "make", "(", "chan", "error", ")", "\n\n", "go", "func", "(", ")", "{", "defer", "close", "(", "errChan", ")", "\n\n", "for", "{", "select", "{", "case", "<-", "ctx", ".", "Done", "(", ")", ":", "errChan", "<-", "ctx", ".", "Err", "(", ")", "\n", "return", "\n", "case", "<-", "ticker", ".", "C", ":", "if", "f", "(", ")", "{", "return", "\n", "}", "\n", "}", "\n", "}", "\n", "}", "(", ")", "\n\n", "return", "<-", "errChan", "\n", "}" ]
// retry calls function f indefinitely with the given delay between invocations // until f returns true or the given context is cancelled. // It returns immediately without delay in case function f immediately returns true.
[ "retry", "calls", "function", "f", "indefinitely", "with", "the", "given", "delay", "between", "invocations", "until", "f", "returns", "true", "or", "the", "given", "context", "is", "cancelled", ".", "It", "returns", "immediately", "without", "delay", "in", "case", "function", "f", "immediately", "returns", "true", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/pod/wait.go#L80-L105
21,050
rkt/rkt
pkg/fileutil/fileutil.go
DirSize
func DirSize(path string) (int64, error) { seenInode := make(map[uint64]struct{}) if _, err := os.Stat(path); err == nil { var sz int64 err := filepath.Walk(path, func(path string, info os.FileInfo, err error) error { if hasHardLinks(info) { ino := getInode(info) if _, ok := seenInode[ino]; !ok { seenInode[ino] = struct{}{} sz += info.Size() } } else { sz += info.Size() } return err }) return sz, err } return 0, nil }
go
func DirSize(path string) (int64, error) { seenInode := make(map[uint64]struct{}) if _, err := os.Stat(path); err == nil { var sz int64 err := filepath.Walk(path, func(path string, info os.FileInfo, err error) error { if hasHardLinks(info) { ino := getInode(info) if _, ok := seenInode[ino]; !ok { seenInode[ino] = struct{}{} sz += info.Size() } } else { sz += info.Size() } return err }) return sz, err } return 0, nil }
[ "func", "DirSize", "(", "path", "string", ")", "(", "int64", ",", "error", ")", "{", "seenInode", ":=", "make", "(", "map", "[", "uint64", "]", "struct", "{", "}", ")", "\n\n", "if", "_", ",", "err", ":=", "os", ".", "Stat", "(", "path", ")", ";", "err", "==", "nil", "{", "var", "sz", "int64", "\n", "err", ":=", "filepath", ".", "Walk", "(", "path", ",", "func", "(", "path", "string", ",", "info", "os", ".", "FileInfo", ",", "err", "error", ")", "error", "{", "if", "hasHardLinks", "(", "info", ")", "{", "ino", ":=", "getInode", "(", "info", ")", "\n", "if", "_", ",", "ok", ":=", "seenInode", "[", "ino", "]", ";", "!", "ok", "{", "seenInode", "[", "ino", "]", "=", "struct", "{", "}", "{", "}", "\n", "sz", "+=", "info", ".", "Size", "(", ")", "\n", "}", "\n", "}", "else", "{", "sz", "+=", "info", ".", "Size", "(", ")", "\n", "}", "\n", "return", "err", "\n", "}", ")", "\n", "return", "sz", ",", "err", "\n", "}", "\n\n", "return", "0", ",", "nil", "\n", "}" ]
// DirSize takes a path and returns its size in bytes
[ "DirSize", "takes", "a", "path", "and", "returns", "its", "size", "in", "bytes" ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/fileutil/fileutil.go#L208-L229
21,051
rkt/rkt
pkg/fileutil/fileutil.go
IsDeviceNode
func IsDeviceNode(path string) bool { d, err := os.Lstat(path) if err == nil { m := d.Mode() return m&os.ModeDevice == os.ModeDevice } return false }
go
func IsDeviceNode(path string) bool { d, err := os.Lstat(path) if err == nil { m := d.Mode() return m&os.ModeDevice == os.ModeDevice } return false }
[ "func", "IsDeviceNode", "(", "path", "string", ")", "bool", "{", "d", ",", "err", ":=", "os", ".", "Lstat", "(", "path", ")", "\n", "if", "err", "==", "nil", "{", "m", ":=", "d", ".", "Mode", "(", ")", "\n", "return", "m", "&", "os", ".", "ModeDevice", "==", "os", ".", "ModeDevice", "\n", "}", "\n", "return", "false", "\n", "}" ]
// IsDeviceNode checks if the given path points to a block or char device. // It doesn't follow symlinks.
[ "IsDeviceNode", "checks", "if", "the", "given", "path", "points", "to", "a", "block", "or", "char", "device", ".", "It", "doesn", "t", "follow", "symlinks", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/fileutil/fileutil.go#L244-L251
21,052
rkt/rkt
stage1/init/kvm/hypervisor/hvlkvm/lkvm_driver.go
StartCmd
func StartCmd(wdPath, uuid, kernelPath string, nds []kvm.NetDescriber, cpu, mem int64, debug bool) []string { machineID := strings.Replace(uuid, "-", "", -1) driverConfiguration := hypervisor.KvmHypervisor{ Bin: "./lkvm", KernelParams: []string{ "systemd.default_standard_error=journal+console", "systemd.default_standard_output=journal+console", "systemd.machine_id=" + machineID, }, } driverConfiguration.InitKernelParams(debug) startCmd := []string{ filepath.Join(wdPath, driverConfiguration.Bin), "run", "--name", "rkt-" + uuid, "--no-dhcp", "--cpu", strconv.Itoa(int(cpu)), "--mem", strconv.Itoa(int(mem)), "--console=virtio", "--kernel", kernelPath, "--disk", "stage1/rootfs", // relative to run/pods/uuid dir this is a place where systemd resides "--params", strings.Join(driverConfiguration.KernelParams, " "), } return append(startCmd, kvmNetArgs(nds)...) }
go
func StartCmd(wdPath, uuid, kernelPath string, nds []kvm.NetDescriber, cpu, mem int64, debug bool) []string { machineID := strings.Replace(uuid, "-", "", -1) driverConfiguration := hypervisor.KvmHypervisor{ Bin: "./lkvm", KernelParams: []string{ "systemd.default_standard_error=journal+console", "systemd.default_standard_output=journal+console", "systemd.machine_id=" + machineID, }, } driverConfiguration.InitKernelParams(debug) startCmd := []string{ filepath.Join(wdPath, driverConfiguration.Bin), "run", "--name", "rkt-" + uuid, "--no-dhcp", "--cpu", strconv.Itoa(int(cpu)), "--mem", strconv.Itoa(int(mem)), "--console=virtio", "--kernel", kernelPath, "--disk", "stage1/rootfs", // relative to run/pods/uuid dir this is a place where systemd resides "--params", strings.Join(driverConfiguration.KernelParams, " "), } return append(startCmd, kvmNetArgs(nds)...) }
[ "func", "StartCmd", "(", "wdPath", ",", "uuid", ",", "kernelPath", "string", ",", "nds", "[", "]", "kvm", ".", "NetDescriber", ",", "cpu", ",", "mem", "int64", ",", "debug", "bool", ")", "[", "]", "string", "{", "machineID", ":=", "strings", ".", "Replace", "(", "uuid", ",", "\"", "\"", ",", "\"", "\"", ",", "-", "1", ")", "\n", "driverConfiguration", ":=", "hypervisor", ".", "KvmHypervisor", "{", "Bin", ":", "\"", "\"", ",", "KernelParams", ":", "[", "]", "string", "{", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", "+", "machineID", ",", "}", ",", "}", "\n\n", "driverConfiguration", ".", "InitKernelParams", "(", "debug", ")", "\n\n", "startCmd", ":=", "[", "]", "string", "{", "filepath", ".", "Join", "(", "wdPath", ",", "driverConfiguration", ".", "Bin", ")", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", "+", "uuid", ",", "\"", "\"", ",", "\"", "\"", ",", "strconv", ".", "Itoa", "(", "int", "(", "cpu", ")", ")", ",", "\"", "\"", ",", "strconv", ".", "Itoa", "(", "int", "(", "mem", ")", ")", ",", "\"", "\"", ",", "\"", "\"", ",", "kernelPath", ",", "\"", "\"", ",", "\"", "\"", ",", "// relative to run/pods/uuid dir this is a place where systemd resides", "\"", "\"", ",", "strings", ".", "Join", "(", "driverConfiguration", ".", "KernelParams", ",", "\"", "\"", ")", ",", "}", "\n", "return", "append", "(", "startCmd", ",", "kvmNetArgs", "(", "nds", ")", "...", ")", "\n", "}" ]
// StartCmd takes path to stage1, UUID of the pod, path to kernel, network // describers, memory in megabytes and quantity of cpus and prepares command // line to run LKVM process
[ "StartCmd", "takes", "path", "to", "stage1", "UUID", "of", "the", "pod", "path", "to", "kernel", "network", "describers", "memory", "in", "megabytes", "and", "quantity", "of", "cpus", "and", "prepares", "command", "line", "to", "run", "LKVM", "process" ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage1/init/kvm/hypervisor/hvlkvm/lkvm_driver.go#L30-L56
21,053
rkt/rkt
stage1/init/kvm/hypervisor/hvlkvm/lkvm_driver.go
kvmNetArgs
func kvmNetArgs(nds []kvm.NetDescriber) []string { var lkvmArgs []string for _, nd := range nds { lkvmArgs = append(lkvmArgs, "--network") lkvmArgs = append( lkvmArgs, fmt.Sprintf("mode=tap,tapif=%s,host_ip=%s,guest_ip=%s", nd.IfName(), nd.Gateway(), nd.GuestIP()), ) } return lkvmArgs }
go
func kvmNetArgs(nds []kvm.NetDescriber) []string { var lkvmArgs []string for _, nd := range nds { lkvmArgs = append(lkvmArgs, "--network") lkvmArgs = append( lkvmArgs, fmt.Sprintf("mode=tap,tapif=%s,host_ip=%s,guest_ip=%s", nd.IfName(), nd.Gateway(), nd.GuestIP()), ) } return lkvmArgs }
[ "func", "kvmNetArgs", "(", "nds", "[", "]", "kvm", ".", "NetDescriber", ")", "[", "]", "string", "{", "var", "lkvmArgs", "[", "]", "string", "\n\n", "for", "_", ",", "nd", ":=", "range", "nds", "{", "lkvmArgs", "=", "append", "(", "lkvmArgs", ",", "\"", "\"", ")", "\n", "lkvmArgs", "=", "append", "(", "lkvmArgs", ",", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "nd", ".", "IfName", "(", ")", ",", "nd", ".", "Gateway", "(", ")", ",", "nd", ".", "GuestIP", "(", ")", ")", ",", ")", "\n", "}", "\n\n", "return", "lkvmArgs", "\n", "}" ]
// kvmNetArgs returns additional arguments that need to be passed // to lkvm tool to configure networks properly. Logic is based on // network configuration extracted from Networking struct // and essentially from activeNets that expose NetDescriber behavior
[ "kvmNetArgs", "returns", "additional", "arguments", "that", "need", "to", "be", "passed", "to", "lkvm", "tool", "to", "configure", "networks", "properly", ".", "Logic", "is", "based", "on", "network", "configuration", "extracted", "from", "Networking", "struct", "and", "essentially", "from", "activeNets", "that", "expose", "NetDescriber", "behavior" ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage1/init/kvm/hypervisor/hvlkvm/lkvm_driver.go#L62-L74
21,054
rkt/rkt
pkg/flag/optionlist.go
NewOptionList
func NewOptionList(permissibleOptions []string, defaultOptions string) (*OptionList, error) { permissible := make(map[string]struct{}) ol := &OptionList{ allOptions: permissibleOptions, permissible: permissible, typeName: "OptionList", } for _, o := range permissibleOptions { ol.permissible[o] = struct{}{} } if err := ol.Set(defaultOptions); err != nil { return nil, errwrap.Wrap(errors.New("problem setting defaults"), err) } return ol, nil }
go
func NewOptionList(permissibleOptions []string, defaultOptions string) (*OptionList, error) { permissible := make(map[string]struct{}) ol := &OptionList{ allOptions: permissibleOptions, permissible: permissible, typeName: "OptionList", } for _, o := range permissibleOptions { ol.permissible[o] = struct{}{} } if err := ol.Set(defaultOptions); err != nil { return nil, errwrap.Wrap(errors.New("problem setting defaults"), err) } return ol, nil }
[ "func", "NewOptionList", "(", "permissibleOptions", "[", "]", "string", ",", "defaultOptions", "string", ")", "(", "*", "OptionList", ",", "error", ")", "{", "permissible", ":=", "make", "(", "map", "[", "string", "]", "struct", "{", "}", ")", "\n", "ol", ":=", "&", "OptionList", "{", "allOptions", ":", "permissibleOptions", ",", "permissible", ":", "permissible", ",", "typeName", ":", "\"", "\"", ",", "}", "\n\n", "for", "_", ",", "o", ":=", "range", "permissibleOptions", "{", "ol", ".", "permissible", "[", "o", "]", "=", "struct", "{", "}", "{", "}", "\n", "}", "\n\n", "if", "err", ":=", "ol", ".", "Set", "(", "defaultOptions", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"", "\"", ")", ",", "err", ")", "\n", "}", "\n\n", "return", "ol", ",", "nil", "\n", "}" ]
// NewOptionList initializes an OptionList. PermissibleOptions is the complete // set of allowable options. It will set all options specified in defaultOptions // as provided; they will all be cleared if this flag is passed in the CLI
[ "NewOptionList", "initializes", "an", "OptionList", ".", "PermissibleOptions", "is", "the", "complete", "set", "of", "allowable", "options", ".", "It", "will", "set", "all", "options", "specified", "in", "defaultOptions", "as", "provided", ";", "they", "will", "all", "be", "cleared", "if", "this", "flag", "is", "passed", "in", "the", "CLI" ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/flag/optionlist.go#L38-L55
21,055
rkt/rkt
rkt/image_gc.go
gcTreeStore
func gcTreeStore(ts *treestore.Store) error { // Take an exclusive lock to block other pods being created. // This is needed to avoid races between the below steps (getting the // list of referenced treeStoreIDs, getting the list of treeStoreIDs // from the store, removal of unreferenced treeStoreIDs) and new // pods/treeStores being created/referenced keyLock, err := lock.ExclusiveKeyLock(lockDir(), common.PrepareLock) if err != nil { return errwrap.Wrap(errors.New("cannot get exclusive prepare lock"), err) } defer keyLock.Close() referencedTreeStoreIDs, err := getReferencedTreeStoreIDs() if err != nil { return errwrap.Wrap(errors.New("cannot get referenced treestoreIDs"), err) } treeStoreIDs, err := ts.GetIDs() if err != nil { return errwrap.Wrap(errors.New("cannot get treestoreIDs from the store"), err) } for _, treeStoreID := range treeStoreIDs { if _, ok := referencedTreeStoreIDs[treeStoreID]; !ok { if err := ts.Remove(treeStoreID); err != nil { stderr.PrintE(fmt.Sprintf("error removing treestore %q", treeStoreID), err) } else { stderr.Printf("removed treestore %q", treeStoreID) } } } return nil }
go
func gcTreeStore(ts *treestore.Store) error { // Take an exclusive lock to block other pods being created. // This is needed to avoid races between the below steps (getting the // list of referenced treeStoreIDs, getting the list of treeStoreIDs // from the store, removal of unreferenced treeStoreIDs) and new // pods/treeStores being created/referenced keyLock, err := lock.ExclusiveKeyLock(lockDir(), common.PrepareLock) if err != nil { return errwrap.Wrap(errors.New("cannot get exclusive prepare lock"), err) } defer keyLock.Close() referencedTreeStoreIDs, err := getReferencedTreeStoreIDs() if err != nil { return errwrap.Wrap(errors.New("cannot get referenced treestoreIDs"), err) } treeStoreIDs, err := ts.GetIDs() if err != nil { return errwrap.Wrap(errors.New("cannot get treestoreIDs from the store"), err) } for _, treeStoreID := range treeStoreIDs { if _, ok := referencedTreeStoreIDs[treeStoreID]; !ok { if err := ts.Remove(treeStoreID); err != nil { stderr.PrintE(fmt.Sprintf("error removing treestore %q", treeStoreID), err) } else { stderr.Printf("removed treestore %q", treeStoreID) } } } return nil }
[ "func", "gcTreeStore", "(", "ts", "*", "treestore", ".", "Store", ")", "error", "{", "// Take an exclusive lock to block other pods being created.", "// This is needed to avoid races between the below steps (getting the", "// list of referenced treeStoreIDs, getting the list of treeStoreIDs", "// from the store, removal of unreferenced treeStoreIDs) and new", "// pods/treeStores being created/referenced", "keyLock", ",", "err", ":=", "lock", ".", "ExclusiveKeyLock", "(", "lockDir", "(", ")", ",", "common", ".", "PrepareLock", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"", "\"", ")", ",", "err", ")", "\n", "}", "\n", "defer", "keyLock", ".", "Close", "(", ")", "\n", "referencedTreeStoreIDs", ",", "err", ":=", "getReferencedTreeStoreIDs", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"", "\"", ")", ",", "err", ")", "\n", "}", "\n", "treeStoreIDs", ",", "err", ":=", "ts", ".", "GetIDs", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"", "\"", ")", ",", "err", ")", "\n", "}", "\n", "for", "_", ",", "treeStoreID", ":=", "range", "treeStoreIDs", "{", "if", "_", ",", "ok", ":=", "referencedTreeStoreIDs", "[", "treeStoreID", "]", ";", "!", "ok", "{", "if", "err", ":=", "ts", ".", "Remove", "(", "treeStoreID", ")", ";", "err", "!=", "nil", "{", "stderr", ".", "PrintE", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "treeStoreID", ")", ",", "err", ")", "\n", "}", "else", "{", "stderr", ".", "Printf", "(", "\"", "\"", ",", "treeStoreID", ")", "\n", "}", "\n", "}", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// gcTreeStore removes all treeStoreIDs not referenced by any non garbage // collected pod from the store.
[ "gcTreeStore", "removes", "all", "treeStoreIDs", "not", "referenced", "by", "any", "non", "garbage", "collected", "pod", "from", "the", "store", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/image_gc.go#L82-L111
21,056
rkt/rkt
rkt/image_gc.go
getRunningImages
func getRunningImages() ([]string, error) { var runningImages []string var errors []error err := pkgPod.WalkPods(getDataDir(), pkgPod.IncludeMostDirs, func(p *pkgPod.Pod) { var pm schema.PodManifest if p.State() != pkgPod.Running { return } if !p.PodManifestAvailable() { return } _, manifest, err := p.PodManifest() if err != nil { errors = append(errors, newPodListReadError(p, err)) return } pm = *manifest for _, app := range pm.Apps { runningImages = append(runningImages, app.Image.ID.String()) } }) if err != nil { return nil, err } if len(errors) > 0 { return nil, errors[0] } return runningImages, nil }
go
func getRunningImages() ([]string, error) { var runningImages []string var errors []error err := pkgPod.WalkPods(getDataDir(), pkgPod.IncludeMostDirs, func(p *pkgPod.Pod) { var pm schema.PodManifest if p.State() != pkgPod.Running { return } if !p.PodManifestAvailable() { return } _, manifest, err := p.PodManifest() if err != nil { errors = append(errors, newPodListReadError(p, err)) return } pm = *manifest for _, app := range pm.Apps { runningImages = append(runningImages, app.Image.ID.String()) } }) if err != nil { return nil, err } if len(errors) > 0 { return nil, errors[0] } return runningImages, nil }
[ "func", "getRunningImages", "(", ")", "(", "[", "]", "string", ",", "error", ")", "{", "var", "runningImages", "[", "]", "string", "\n", "var", "errors", "[", "]", "error", "\n", "err", ":=", "pkgPod", ".", "WalkPods", "(", "getDataDir", "(", ")", ",", "pkgPod", ".", "IncludeMostDirs", ",", "func", "(", "p", "*", "pkgPod", ".", "Pod", ")", "{", "var", "pm", "schema", ".", "PodManifest", "\n", "if", "p", ".", "State", "(", ")", "!=", "pkgPod", ".", "Running", "{", "return", "\n", "}", "\n", "if", "!", "p", ".", "PodManifestAvailable", "(", ")", "{", "return", "\n", "}", "\n", "_", ",", "manifest", ",", "err", ":=", "p", ".", "PodManifest", "(", ")", "\n", "if", "err", "!=", "nil", "{", "errors", "=", "append", "(", "errors", ",", "newPodListReadError", "(", "p", ",", "err", ")", ")", "\n", "return", "\n", "}", "\n", "pm", "=", "*", "manifest", "\n", "for", "_", ",", "app", ":=", "range", "pm", ".", "Apps", "{", "runningImages", "=", "append", "(", "runningImages", ",", "app", ".", "Image", ".", "ID", ".", "String", "(", ")", ")", "\n", "}", "\n", "}", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "len", "(", "errors", ")", ">", "0", "{", "return", "nil", ",", "errors", "[", "0", "]", "\n", "}", "\n", "return", "runningImages", ",", "nil", "\n", "}" ]
// getRunningImages will return the image IDs used to create any of the // currently running pods
[ "getRunningImages", "will", "return", "the", "image", "IDs", "used", "to", "create", "any", "of", "the", "currently", "running", "pods" ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/rkt/image_gc.go#L167-L195
21,057
rkt/rkt
stage0/run.go
deduplicateMPs
func deduplicateMPs(mounts []schema.Mount) []schema.Mount { var res []schema.Mount seen := make(map[string]struct{}) for _, m := range mounts { cleanPath := path.Clean(m.Path) if _, ok := seen[cleanPath]; !ok { res = append(res, m) seen[cleanPath] = struct{}{} } } return res }
go
func deduplicateMPs(mounts []schema.Mount) []schema.Mount { var res []schema.Mount seen := make(map[string]struct{}) for _, m := range mounts { cleanPath := path.Clean(m.Path) if _, ok := seen[cleanPath]; !ok { res = append(res, m) seen[cleanPath] = struct{}{} } } return res }
[ "func", "deduplicateMPs", "(", "mounts", "[", "]", "schema", ".", "Mount", ")", "[", "]", "schema", ".", "Mount", "{", "var", "res", "[", "]", "schema", ".", "Mount", "\n", "seen", ":=", "make", "(", "map", "[", "string", "]", "struct", "{", "}", ")", "\n", "for", "_", ",", "m", ":=", "range", "mounts", "{", "cleanPath", ":=", "path", ".", "Clean", "(", "m", ".", "Path", ")", "\n", "if", "_", ",", "ok", ":=", "seen", "[", "cleanPath", "]", ";", "!", "ok", "{", "res", "=", "append", "(", "res", ",", "m", ")", "\n", "seen", "[", "cleanPath", "]", "=", "struct", "{", "}", "{", "}", "\n", "}", "\n", "}", "\n", "return", "res", "\n", "}" ]
// deduplicateMPs removes Mounts with duplicated paths. If there's more than // one Mount with the same path, it keeps the first one encountered.
[ "deduplicateMPs", "removes", "Mounts", "with", "duplicated", "paths", ".", "If", "there", "s", "more", "than", "one", "Mount", "with", "the", "same", "path", "it", "keeps", "the", "first", "one", "encountered", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage0/run.go#L161-L172
21,058
rkt/rkt
stage0/run.go
MergeMounts
func MergeMounts(mounts []schema.Mount, appMounts []schema.Mount) []schema.Mount { ml := append(appMounts, mounts...) return deduplicateMPs(ml) }
go
func MergeMounts(mounts []schema.Mount, appMounts []schema.Mount) []schema.Mount { ml := append(appMounts, mounts...) return deduplicateMPs(ml) }
[ "func", "MergeMounts", "(", "mounts", "[", "]", "schema", ".", "Mount", ",", "appMounts", "[", "]", "schema", ".", "Mount", ")", "[", "]", "schema", ".", "Mount", "{", "ml", ":=", "append", "(", "appMounts", ",", "mounts", "...", ")", "\n", "return", "deduplicateMPs", "(", "ml", ")", "\n", "}" ]
// MergeMounts combines the global and per-app mount slices
[ "MergeMounts", "combines", "the", "global", "and", "per", "-", "app", "mount", "slices" ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage0/run.go#L175-L178
21,059
rkt/rkt
stage0/run.go
Prepare
func Prepare(cfg PrepareConfig, dir string, uuid *types.UUID) error { if err := os.MkdirAll(common.AppsInfoPath(dir), common.DefaultRegularDirPerm); err != nil { return errwrap.Wrap(errors.New("error creating apps info directory"), err) } debug("Preparing stage1") if err := prepareStage1Image(cfg, dir); err != nil { return errwrap.Wrap(errors.New("error preparing stage1"), err) } var pmb []byte var err error if len(cfg.PodManifest) > 0 { pmb, err = validatePodManifest(cfg, dir) } else { pmb, err = generatePodManifest(cfg, dir) } if err != nil { return err } cfg.CommonConfig.ManifestData = string(pmb) // create pod lock file for app add/rm operations. f, err := os.OpenFile(common.PodManifestLockPath(dir), os.O_CREATE|os.O_RDWR, 0600) if err != nil { return err } f.Close() debug("Writing pod manifest") fn := common.PodManifestPath(dir) if err := ioutil.WriteFile(fn, pmb, common.DefaultRegularFilePerm); err != nil { return errwrap.Wrap(errors.New("error writing pod manifest"), err) } f, err = os.OpenFile(common.PodCreatedPath(dir), os.O_CREATE|os.O_RDWR, common.DefaultRegularFilePerm) if err != nil { return err } f.Close() if cfg.UseOverlay { // mark the pod as prepared with overlay f, err := os.Create(filepath.Join(dir, common.OverlayPreparedFilename)) if err != nil { return errwrap.Wrap(errors.New("error writing overlay marker file"), err) } defer f.Close() } if cfg.PrivateUsers.Shift > 0 { // mark the pod as prepared for user namespaces uidrangeBytes := cfg.PrivateUsers.Serialize() if err := ioutil.WriteFile(filepath.Join(dir, common.PrivateUsersPreparedFilename), uidrangeBytes, common.DefaultRegularFilePerm); err != nil { return errwrap.Wrap(errors.New("error writing userns marker file"), err) } } return nil }
go
func Prepare(cfg PrepareConfig, dir string, uuid *types.UUID) error { if err := os.MkdirAll(common.AppsInfoPath(dir), common.DefaultRegularDirPerm); err != nil { return errwrap.Wrap(errors.New("error creating apps info directory"), err) } debug("Preparing stage1") if err := prepareStage1Image(cfg, dir); err != nil { return errwrap.Wrap(errors.New("error preparing stage1"), err) } var pmb []byte var err error if len(cfg.PodManifest) > 0 { pmb, err = validatePodManifest(cfg, dir) } else { pmb, err = generatePodManifest(cfg, dir) } if err != nil { return err } cfg.CommonConfig.ManifestData = string(pmb) // create pod lock file for app add/rm operations. f, err := os.OpenFile(common.PodManifestLockPath(dir), os.O_CREATE|os.O_RDWR, 0600) if err != nil { return err } f.Close() debug("Writing pod manifest") fn := common.PodManifestPath(dir) if err := ioutil.WriteFile(fn, pmb, common.DefaultRegularFilePerm); err != nil { return errwrap.Wrap(errors.New("error writing pod manifest"), err) } f, err = os.OpenFile(common.PodCreatedPath(dir), os.O_CREATE|os.O_RDWR, common.DefaultRegularFilePerm) if err != nil { return err } f.Close() if cfg.UseOverlay { // mark the pod as prepared with overlay f, err := os.Create(filepath.Join(dir, common.OverlayPreparedFilename)) if err != nil { return errwrap.Wrap(errors.New("error writing overlay marker file"), err) } defer f.Close() } if cfg.PrivateUsers.Shift > 0 { // mark the pod as prepared for user namespaces uidrangeBytes := cfg.PrivateUsers.Serialize() if err := ioutil.WriteFile(filepath.Join(dir, common.PrivateUsersPreparedFilename), uidrangeBytes, common.DefaultRegularFilePerm); err != nil { return errwrap.Wrap(errors.New("error writing userns marker file"), err) } } return nil }
[ "func", "Prepare", "(", "cfg", "PrepareConfig", ",", "dir", "string", ",", "uuid", "*", "types", ".", "UUID", ")", "error", "{", "if", "err", ":=", "os", ".", "MkdirAll", "(", "common", ".", "AppsInfoPath", "(", "dir", ")", ",", "common", ".", "DefaultRegularDirPerm", ")", ";", "err", "!=", "nil", "{", "return", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"", "\"", ")", ",", "err", ")", "\n", "}", "\n", "debug", "(", "\"", "\"", ")", "\n", "if", "err", ":=", "prepareStage1Image", "(", "cfg", ",", "dir", ")", ";", "err", "!=", "nil", "{", "return", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"", "\"", ")", ",", "err", ")", "\n", "}", "\n\n", "var", "pmb", "[", "]", "byte", "\n", "var", "err", "error", "\n", "if", "len", "(", "cfg", ".", "PodManifest", ")", ">", "0", "{", "pmb", ",", "err", "=", "validatePodManifest", "(", "cfg", ",", "dir", ")", "\n", "}", "else", "{", "pmb", ",", "err", "=", "generatePodManifest", "(", "cfg", ",", "dir", ")", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "cfg", ".", "CommonConfig", ".", "ManifestData", "=", "string", "(", "pmb", ")", "\n\n", "// create pod lock file for app add/rm operations.", "f", ",", "err", ":=", "os", ".", "OpenFile", "(", "common", ".", "PodManifestLockPath", "(", "dir", ")", ",", "os", ".", "O_CREATE", "|", "os", ".", "O_RDWR", ",", "0600", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "f", ".", "Close", "(", ")", "\n\n", "debug", "(", "\"", "\"", ")", "\n", "fn", ":=", "common", ".", "PodManifestPath", "(", "dir", ")", "\n", "if", "err", ":=", "ioutil", ".", "WriteFile", "(", "fn", ",", "pmb", ",", "common", ".", "DefaultRegularFilePerm", ")", ";", "err", "!=", "nil", "{", "return", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"", "\"", ")", ",", "err", ")", "\n", "}", "\n\n", "f", ",", "err", "=", "os", ".", "OpenFile", "(", "common", ".", "PodCreatedPath", "(", "dir", ")", ",", "os", ".", "O_CREATE", "|", "os", ".", "O_RDWR", ",", "common", ".", "DefaultRegularFilePerm", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "f", ".", "Close", "(", ")", "\n\n", "if", "cfg", ".", "UseOverlay", "{", "// mark the pod as prepared with overlay", "f", ",", "err", ":=", "os", ".", "Create", "(", "filepath", ".", "Join", "(", "dir", ",", "common", ".", "OverlayPreparedFilename", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"", "\"", ")", ",", "err", ")", "\n", "}", "\n", "defer", "f", ".", "Close", "(", ")", "\n", "}", "\n\n", "if", "cfg", ".", "PrivateUsers", ".", "Shift", ">", "0", "{", "// mark the pod as prepared for user namespaces", "uidrangeBytes", ":=", "cfg", ".", "PrivateUsers", ".", "Serialize", "(", ")", "\n\n", "if", "err", ":=", "ioutil", ".", "WriteFile", "(", "filepath", ".", "Join", "(", "dir", ",", "common", ".", "PrivateUsersPreparedFilename", ")", ",", "uidrangeBytes", ",", "common", ".", "DefaultRegularFilePerm", ")", ";", "err", "!=", "nil", "{", "return", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"", "\"", ")", ",", "err", ")", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Prepare sets up a pod based on the given config.
[ "Prepare", "sets", "up", "a", "pod", "based", "on", "the", "given", "config", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage0/run.go#L408-L468
21,060
rkt/rkt
stage0/run.go
setupAppImage
func setupAppImage(cfg RunConfig, appName types.ACName, img types.Hash, cdir string, useOverlay bool) error { ad := common.AppPath(cdir, appName) if useOverlay { err := os.MkdirAll(ad, common.DefaultRegularDirPerm) if err != nil { return errwrap.Wrap(errors.New("error creating image directory"), err) } treeStoreID, err := ioutil.ReadFile(common.AppTreeStoreIDPath(cdir, appName)) if err != nil { return err } if err := copyAppManifest(cdir, appName, ad); err != nil { return err } if err := overlayRender(cfg, string(treeStoreID), cdir, ad, appName.String()); err != nil { return errwrap.Wrap(errors.New("error rendering overlay filesystem"), err) } } return ensureMtabExists(filepath.Join(ad, "rootfs")) }
go
func setupAppImage(cfg RunConfig, appName types.ACName, img types.Hash, cdir string, useOverlay bool) error { ad := common.AppPath(cdir, appName) if useOverlay { err := os.MkdirAll(ad, common.DefaultRegularDirPerm) if err != nil { return errwrap.Wrap(errors.New("error creating image directory"), err) } treeStoreID, err := ioutil.ReadFile(common.AppTreeStoreIDPath(cdir, appName)) if err != nil { return err } if err := copyAppManifest(cdir, appName, ad); err != nil { return err } if err := overlayRender(cfg, string(treeStoreID), cdir, ad, appName.String()); err != nil { return errwrap.Wrap(errors.New("error rendering overlay filesystem"), err) } } return ensureMtabExists(filepath.Join(ad, "rootfs")) }
[ "func", "setupAppImage", "(", "cfg", "RunConfig", ",", "appName", "types", ".", "ACName", ",", "img", "types", ".", "Hash", ",", "cdir", "string", ",", "useOverlay", "bool", ")", "error", "{", "ad", ":=", "common", ".", "AppPath", "(", "cdir", ",", "appName", ")", "\n", "if", "useOverlay", "{", "err", ":=", "os", ".", "MkdirAll", "(", "ad", ",", "common", ".", "DefaultRegularDirPerm", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"", "\"", ")", ",", "err", ")", "\n", "}", "\n", "treeStoreID", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "common", ".", "AppTreeStoreIDPath", "(", "cdir", ",", "appName", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "copyAppManifest", "(", "cdir", ",", "appName", ",", "ad", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n", "if", "err", ":=", "overlayRender", "(", "cfg", ",", "string", "(", "treeStoreID", ")", ",", "cdir", ",", "ad", ",", "appName", ".", "String", "(", ")", ")", ";", "err", "!=", "nil", "{", "return", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"", "\"", ")", ",", "err", ")", "\n", "}", "\n", "}", "\n", "return", "ensureMtabExists", "(", "filepath", ".", "Join", "(", "ad", ",", "\"", "\"", ")", ")", "\n", "}" ]
// setupAppImage mounts the overlay filesystem for the app image that // corresponds to the given hash if useOverlay is true. // It also creates an mtab file in the application's rootfs if one is not // present.
[ "setupAppImage", "mounts", "the", "overlay", "filesystem", "for", "the", "app", "image", "that", "corresponds", "to", "the", "given", "hash", "if", "useOverlay", "is", "true", ".", "It", "also", "creates", "an", "mtab", "file", "in", "the", "application", "s", "rootfs", "if", "one", "is", "not", "present", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage0/run.go#L773-L792
21,061
rkt/rkt
stage0/run.go
prepareStage1Image
func prepareStage1Image(cfg PrepareConfig, cdir string) error { s1 := common.Stage1ImagePath(cdir) if err := os.MkdirAll(s1, common.DefaultRegularDirPerm); err != nil { return errwrap.Wrap(errors.New("error creating stage1 directory"), err) } treeStoreID, _, err := cfg.TreeStore.Render(cfg.Stage1Image.String(), false) if err != nil { return errwrap.Wrap(errors.New("error rendering tree image"), err) } if err := writeManifest(*cfg.CommonConfig, cfg.Stage1Image, s1); err != nil { return errwrap.Wrap(errors.New("error writing manifest"), err) } if !cfg.UseOverlay { destRootfs := filepath.Join(s1, "rootfs") cachedTreePath := cfg.TreeStore.GetRootFS(treeStoreID) if err := fileutil.CopyTree(cachedTreePath, destRootfs, cfg.PrivateUsers); err != nil { return errwrap.Wrap(errors.New("error rendering ACI"), err) } } fn := path.Join(cdir, common.Stage1TreeStoreIDFilename) if err := ioutil.WriteFile(fn, []byte(treeStoreID), common.DefaultRegularFilePerm); err != nil { return errwrap.Wrap(errors.New("error writing stage1 treeStoreID"), err) } return nil }
go
func prepareStage1Image(cfg PrepareConfig, cdir string) error { s1 := common.Stage1ImagePath(cdir) if err := os.MkdirAll(s1, common.DefaultRegularDirPerm); err != nil { return errwrap.Wrap(errors.New("error creating stage1 directory"), err) } treeStoreID, _, err := cfg.TreeStore.Render(cfg.Stage1Image.String(), false) if err != nil { return errwrap.Wrap(errors.New("error rendering tree image"), err) } if err := writeManifest(*cfg.CommonConfig, cfg.Stage1Image, s1); err != nil { return errwrap.Wrap(errors.New("error writing manifest"), err) } if !cfg.UseOverlay { destRootfs := filepath.Join(s1, "rootfs") cachedTreePath := cfg.TreeStore.GetRootFS(treeStoreID) if err := fileutil.CopyTree(cachedTreePath, destRootfs, cfg.PrivateUsers); err != nil { return errwrap.Wrap(errors.New("error rendering ACI"), err) } } fn := path.Join(cdir, common.Stage1TreeStoreIDFilename) if err := ioutil.WriteFile(fn, []byte(treeStoreID), common.DefaultRegularFilePerm); err != nil { return errwrap.Wrap(errors.New("error writing stage1 treeStoreID"), err) } return nil }
[ "func", "prepareStage1Image", "(", "cfg", "PrepareConfig", ",", "cdir", "string", ")", "error", "{", "s1", ":=", "common", ".", "Stage1ImagePath", "(", "cdir", ")", "\n", "if", "err", ":=", "os", ".", "MkdirAll", "(", "s1", ",", "common", ".", "DefaultRegularDirPerm", ")", ";", "err", "!=", "nil", "{", "return", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"", "\"", ")", ",", "err", ")", "\n", "}", "\n\n", "treeStoreID", ",", "_", ",", "err", ":=", "cfg", ".", "TreeStore", ".", "Render", "(", "cfg", ".", "Stage1Image", ".", "String", "(", ")", ",", "false", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"", "\"", ")", ",", "err", ")", "\n", "}", "\n\n", "if", "err", ":=", "writeManifest", "(", "*", "cfg", ".", "CommonConfig", ",", "cfg", ".", "Stage1Image", ",", "s1", ")", ";", "err", "!=", "nil", "{", "return", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"", "\"", ")", ",", "err", ")", "\n", "}", "\n\n", "if", "!", "cfg", ".", "UseOverlay", "{", "destRootfs", ":=", "filepath", ".", "Join", "(", "s1", ",", "\"", "\"", ")", "\n", "cachedTreePath", ":=", "cfg", ".", "TreeStore", ".", "GetRootFS", "(", "treeStoreID", ")", "\n", "if", "err", ":=", "fileutil", ".", "CopyTree", "(", "cachedTreePath", ",", "destRootfs", ",", "cfg", ".", "PrivateUsers", ")", ";", "err", "!=", "nil", "{", "return", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"", "\"", ")", ",", "err", ")", "\n", "}", "\n", "}", "\n\n", "fn", ":=", "path", ".", "Join", "(", "cdir", ",", "common", ".", "Stage1TreeStoreIDFilename", ")", "\n", "if", "err", ":=", "ioutil", ".", "WriteFile", "(", "fn", ",", "[", "]", "byte", "(", "treeStoreID", ")", ",", "common", ".", "DefaultRegularFilePerm", ")", ";", "err", "!=", "nil", "{", "return", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"", "\"", ")", ",", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// prepareStage1Image renders and verifies tree cache of the given hash // when using overlay. // When useOverlay is false, it attempts to render and expand the stage1.
[ "prepareStage1Image", "renders", "and", "verifies", "tree", "cache", "of", "the", "given", "hash", "when", "using", "overlay", ".", "When", "useOverlay", "is", "false", "it", "attempts", "to", "render", "and", "expand", "the", "stage1", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage0/run.go#L830-L858
21,062
rkt/rkt
stage0/run.go
setupStage1Image
func setupStage1Image(cfg RunConfig, cdir string, useOverlay bool) error { s1 := common.Stage1ImagePath(cdir) if useOverlay { treeStoreID, err := ioutil.ReadFile(filepath.Join(cdir, common.Stage1TreeStoreIDFilename)) if err != nil { return err } // pass an empty appName if err := overlayRender(cfg, string(treeStoreID), cdir, s1, ""); err != nil { return errwrap.Wrap(errors.New("error rendering overlay filesystem"), err) } // we will later read the status from the upper layer of the overlay fs // force the status directory to be there by touching it statusPath := filepath.Join(s1, "rootfs", "rkt", "status") if err := os.Chtimes(statusPath, time.Now(), time.Now()); err != nil { return errwrap.Wrap(errors.New("error touching status dir"), err) } } return nil }
go
func setupStage1Image(cfg RunConfig, cdir string, useOverlay bool) error { s1 := common.Stage1ImagePath(cdir) if useOverlay { treeStoreID, err := ioutil.ReadFile(filepath.Join(cdir, common.Stage1TreeStoreIDFilename)) if err != nil { return err } // pass an empty appName if err := overlayRender(cfg, string(treeStoreID), cdir, s1, ""); err != nil { return errwrap.Wrap(errors.New("error rendering overlay filesystem"), err) } // we will later read the status from the upper layer of the overlay fs // force the status directory to be there by touching it statusPath := filepath.Join(s1, "rootfs", "rkt", "status") if err := os.Chtimes(statusPath, time.Now(), time.Now()); err != nil { return errwrap.Wrap(errors.New("error touching status dir"), err) } } return nil }
[ "func", "setupStage1Image", "(", "cfg", "RunConfig", ",", "cdir", "string", ",", "useOverlay", "bool", ")", "error", "{", "s1", ":=", "common", ".", "Stage1ImagePath", "(", "cdir", ")", "\n", "if", "useOverlay", "{", "treeStoreID", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "filepath", ".", "Join", "(", "cdir", ",", "common", ".", "Stage1TreeStoreIDFilename", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "// pass an empty appName", "if", "err", ":=", "overlayRender", "(", "cfg", ",", "string", "(", "treeStoreID", ")", ",", "cdir", ",", "s1", ",", "\"", "\"", ")", ";", "err", "!=", "nil", "{", "return", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"", "\"", ")", ",", "err", ")", "\n", "}", "\n\n", "// we will later read the status from the upper layer of the overlay fs", "// force the status directory to be there by touching it", "statusPath", ":=", "filepath", ".", "Join", "(", "s1", ",", "\"", "\"", ",", "\"", "\"", ",", "\"", "\"", ")", "\n", "if", "err", ":=", "os", ".", "Chtimes", "(", "statusPath", ",", "time", ".", "Now", "(", ")", ",", "time", ".", "Now", "(", ")", ")", ";", "err", "!=", "nil", "{", "return", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"", "\"", ")", ",", "err", ")", "\n", "}", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// setupStage1Image mounts the overlay filesystem for stage1. // When useOverlay is false it is a noop
[ "setupStage1Image", "mounts", "the", "overlay", "filesystem", "for", "stage1", ".", "When", "useOverlay", "is", "false", "it", "is", "a", "noop" ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage0/run.go#L862-L884
21,063
rkt/rkt
stage0/run.go
writeManifest
func writeManifest(cfg CommonConfig, img types.Hash, dest string) error { mb, err := cfg.Store.GetImageManifestJSON(img.String()) if err != nil { return err } debug("Writing image manifest") if err := ioutil.WriteFile(filepath.Join(dest, "manifest"), mb, common.DefaultRegularFilePerm); err != nil { return errwrap.Wrap(errors.New("error writing image manifest"), err) } return nil }
go
func writeManifest(cfg CommonConfig, img types.Hash, dest string) error { mb, err := cfg.Store.GetImageManifestJSON(img.String()) if err != nil { return err } debug("Writing image manifest") if err := ioutil.WriteFile(filepath.Join(dest, "manifest"), mb, common.DefaultRegularFilePerm); err != nil { return errwrap.Wrap(errors.New("error writing image manifest"), err) } return nil }
[ "func", "writeManifest", "(", "cfg", "CommonConfig", ",", "img", "types", ".", "Hash", ",", "dest", "string", ")", "error", "{", "mb", ",", "err", ":=", "cfg", ".", "Store", ".", "GetImageManifestJSON", "(", "img", ".", "String", "(", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "debug", "(", "\"", "\"", ")", "\n", "if", "err", ":=", "ioutil", ".", "WriteFile", "(", "filepath", ".", "Join", "(", "dest", ",", "\"", "\"", ")", ",", "mb", ",", "common", ".", "DefaultRegularFilePerm", ")", ";", "err", "!=", "nil", "{", "return", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"", "\"", ")", ",", "err", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// writeManifest takes an img ID and writes the corresponding manifest in dest
[ "writeManifest", "takes", "an", "img", "ID", "and", "writes", "the", "corresponding", "manifest", "in", "dest" ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage0/run.go#L887-L899
21,064
rkt/rkt
stage0/run.go
copyAppManifest
func copyAppManifest(cdir string, appName types.ACName, dest string) error { appInfoDir := common.AppInfoPath(cdir, appName) sourceFn := filepath.Join(appInfoDir, "manifest") destFn := filepath.Join(dest, "manifest") if err := fileutil.CopyRegularFile(sourceFn, destFn); err != nil { return errwrap.Wrap(errors.New("error copying image manifest"), err) } return nil }
go
func copyAppManifest(cdir string, appName types.ACName, dest string) error { appInfoDir := common.AppInfoPath(cdir, appName) sourceFn := filepath.Join(appInfoDir, "manifest") destFn := filepath.Join(dest, "manifest") if err := fileutil.CopyRegularFile(sourceFn, destFn); err != nil { return errwrap.Wrap(errors.New("error copying image manifest"), err) } return nil }
[ "func", "copyAppManifest", "(", "cdir", "string", ",", "appName", "types", ".", "ACName", ",", "dest", "string", ")", "error", "{", "appInfoDir", ":=", "common", ".", "AppInfoPath", "(", "cdir", ",", "appName", ")", "\n", "sourceFn", ":=", "filepath", ".", "Join", "(", "appInfoDir", ",", "\"", "\"", ")", "\n", "destFn", ":=", "filepath", ".", "Join", "(", "dest", ",", "\"", "\"", ")", "\n", "if", "err", ":=", "fileutil", ".", "CopyRegularFile", "(", "sourceFn", ",", "destFn", ")", ";", "err", "!=", "nil", "{", "return", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"", "\"", ")", ",", "err", ")", "\n", "}", "\n", "return", "nil", "\n", "}" ]
// copyAppManifest copies to saved image manifest for the given appName and // writes it in the dest directory.
[ "copyAppManifest", "copies", "to", "saved", "image", "manifest", "for", "the", "given", "appName", "and", "writes", "it", "in", "the", "dest", "directory", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage0/run.go#L903-L911
21,065
rkt/rkt
stage0/run.go
overlayRender
func overlayRender(cfg RunConfig, treeStoreID string, cdir string, dest string, appName string) error { cachedTreePath := cfg.TreeStore.GetRootFS(treeStoreID) mc, err := prepareOverlay(cachedTreePath, treeStoreID, cdir, dest, appName, cfg.MountLabel, cfg.RktGid, common.DefaultRegularDirPerm) if err != nil { return errwrap.Wrap(errors.New("problem preparing overlay directories"), err) } if err = overlay.Mount(mc); err != nil { return errwrap.Wrap(errors.New("problem mounting overlay filesystem"), err) } return nil }
go
func overlayRender(cfg RunConfig, treeStoreID string, cdir string, dest string, appName string) error { cachedTreePath := cfg.TreeStore.GetRootFS(treeStoreID) mc, err := prepareOverlay(cachedTreePath, treeStoreID, cdir, dest, appName, cfg.MountLabel, cfg.RktGid, common.DefaultRegularDirPerm) if err != nil { return errwrap.Wrap(errors.New("problem preparing overlay directories"), err) } if err = overlay.Mount(mc); err != nil { return errwrap.Wrap(errors.New("problem mounting overlay filesystem"), err) } return nil }
[ "func", "overlayRender", "(", "cfg", "RunConfig", ",", "treeStoreID", "string", ",", "cdir", "string", ",", "dest", "string", ",", "appName", "string", ")", "error", "{", "cachedTreePath", ":=", "cfg", ".", "TreeStore", ".", "GetRootFS", "(", "treeStoreID", ")", "\n", "mc", ",", "err", ":=", "prepareOverlay", "(", "cachedTreePath", ",", "treeStoreID", ",", "cdir", ",", "dest", ",", "appName", ",", "cfg", ".", "MountLabel", ",", "cfg", ".", "RktGid", ",", "common", ".", "DefaultRegularDirPerm", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"", "\"", ")", ",", "err", ")", "\n", "}", "\n", "if", "err", "=", "overlay", ".", "Mount", "(", "mc", ")", ";", "err", "!=", "nil", "{", "return", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"", "\"", ")", ",", "err", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// overlayRender renders the image that corresponds to the given hash using the // overlay filesystem. It mounts an overlay filesystem from the cached tree of // the image as rootfs.
[ "overlayRender", "renders", "the", "image", "that", "corresponds", "to", "the", "given", "hash", "using", "the", "overlay", "filesystem", ".", "It", "mounts", "an", "overlay", "filesystem", "from", "the", "cached", "tree", "of", "the", "image", "as", "rootfs", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage0/run.go#L916-L928
21,066
rkt/rkt
stage0/run.go
prepareOverlay
func prepareOverlay(lower, treeStoreID, cdir, dest, appName, lbl string, gid int, fm os.FileMode) (*overlay.MountCfg, error) { fi, err := os.Stat(lower) if err != nil { return nil, err } imgMode := fi.Mode() dst := path.Join(dest, "rootfs") if err := os.MkdirAll(dst, imgMode); err != nil { return nil, err } overlayDir := path.Join(cdir, "overlay") if err := os.MkdirAll(overlayDir, fm); err != nil { return nil, err } // Since the parent directory (rkt/pods/$STATE/$POD_UUID) has the 'S_ISGID' bit, here // we need to explicitly turn the bit off when creating this overlay // directory so that it won't inherit the bit. Otherwise the files // created by users within the pod will inherit the 'S_ISGID' bit // as well. if err := os.Chmod(overlayDir, fm); err != nil { return nil, err } imgDir := path.Join(overlayDir, treeStoreID) if err := os.MkdirAll(imgDir, fm); err != nil { return nil, err } // Also make 'rkt/pods/$STATE/$POD_UUID/overlay/$IMAGE_ID' to be readable by 'rkt' group // As 'rkt' status will read the 'rkt/pods/$STATE/$POD_UUID/overlay/$IMAGE_ID/upper/rkt/status/$APP' // to get exgid if err := os.Chown(imgDir, -1, gid); err != nil { return nil, err } upper := path.Join(imgDir, "upper", appName) if err := os.MkdirAll(upper, imgMode); err != nil { return nil, err } if err := label.SetFileLabel(upper, lbl); err != nil { return nil, err } work := path.Join(imgDir, "work", appName) if err := os.MkdirAll(work, fm); err != nil { return nil, err } if err := label.SetFileLabel(work, lbl); err != nil { return nil, err } return &overlay.MountCfg{lower, upper, work, dst, lbl}, nil }
go
func prepareOverlay(lower, treeStoreID, cdir, dest, appName, lbl string, gid int, fm os.FileMode) (*overlay.MountCfg, error) { fi, err := os.Stat(lower) if err != nil { return nil, err } imgMode := fi.Mode() dst := path.Join(dest, "rootfs") if err := os.MkdirAll(dst, imgMode); err != nil { return nil, err } overlayDir := path.Join(cdir, "overlay") if err := os.MkdirAll(overlayDir, fm); err != nil { return nil, err } // Since the parent directory (rkt/pods/$STATE/$POD_UUID) has the 'S_ISGID' bit, here // we need to explicitly turn the bit off when creating this overlay // directory so that it won't inherit the bit. Otherwise the files // created by users within the pod will inherit the 'S_ISGID' bit // as well. if err := os.Chmod(overlayDir, fm); err != nil { return nil, err } imgDir := path.Join(overlayDir, treeStoreID) if err := os.MkdirAll(imgDir, fm); err != nil { return nil, err } // Also make 'rkt/pods/$STATE/$POD_UUID/overlay/$IMAGE_ID' to be readable by 'rkt' group // As 'rkt' status will read the 'rkt/pods/$STATE/$POD_UUID/overlay/$IMAGE_ID/upper/rkt/status/$APP' // to get exgid if err := os.Chown(imgDir, -1, gid); err != nil { return nil, err } upper := path.Join(imgDir, "upper", appName) if err := os.MkdirAll(upper, imgMode); err != nil { return nil, err } if err := label.SetFileLabel(upper, lbl); err != nil { return nil, err } work := path.Join(imgDir, "work", appName) if err := os.MkdirAll(work, fm); err != nil { return nil, err } if err := label.SetFileLabel(work, lbl); err != nil { return nil, err } return &overlay.MountCfg{lower, upper, work, dst, lbl}, nil }
[ "func", "prepareOverlay", "(", "lower", ",", "treeStoreID", ",", "cdir", ",", "dest", ",", "appName", ",", "lbl", "string", ",", "gid", "int", ",", "fm", "os", ".", "FileMode", ")", "(", "*", "overlay", ".", "MountCfg", ",", "error", ")", "{", "fi", ",", "err", ":=", "os", ".", "Stat", "(", "lower", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "imgMode", ":=", "fi", ".", "Mode", "(", ")", "\n\n", "dst", ":=", "path", ".", "Join", "(", "dest", ",", "\"", "\"", ")", "\n", "if", "err", ":=", "os", ".", "MkdirAll", "(", "dst", ",", "imgMode", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "overlayDir", ":=", "path", ".", "Join", "(", "cdir", ",", "\"", "\"", ")", "\n", "if", "err", ":=", "os", ".", "MkdirAll", "(", "overlayDir", ",", "fm", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "// Since the parent directory (rkt/pods/$STATE/$POD_UUID) has the 'S_ISGID' bit, here", "// we need to explicitly turn the bit off when creating this overlay", "// directory so that it won't inherit the bit. Otherwise the files", "// created by users within the pod will inherit the 'S_ISGID' bit", "// as well.", "if", "err", ":=", "os", ".", "Chmod", "(", "overlayDir", ",", "fm", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "imgDir", ":=", "path", ".", "Join", "(", "overlayDir", ",", "treeStoreID", ")", "\n", "if", "err", ":=", "os", ".", "MkdirAll", "(", "imgDir", ",", "fm", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "// Also make 'rkt/pods/$STATE/$POD_UUID/overlay/$IMAGE_ID' to be readable by 'rkt' group", "// As 'rkt' status will read the 'rkt/pods/$STATE/$POD_UUID/overlay/$IMAGE_ID/upper/rkt/status/$APP'", "// to get exgid", "if", "err", ":=", "os", ".", "Chown", "(", "imgDir", ",", "-", "1", ",", "gid", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "upper", ":=", "path", ".", "Join", "(", "imgDir", ",", "\"", "\"", ",", "appName", ")", "\n", "if", "err", ":=", "os", ".", "MkdirAll", "(", "upper", ",", "imgMode", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "err", ":=", "label", ".", "SetFileLabel", "(", "upper", ",", "lbl", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "work", ":=", "path", ".", "Join", "(", "imgDir", ",", "\"", "\"", ",", "appName", ")", "\n", "if", "err", ":=", "os", ".", "MkdirAll", "(", "work", ",", "fm", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "if", "err", ":=", "label", ".", "SetFileLabel", "(", "work", ",", "lbl", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n\n", "return", "&", "overlay", ".", "MountCfg", "{", "lower", ",", "upper", ",", "work", ",", "dst", ",", "lbl", "}", ",", "nil", "\n", "}" ]
// prepateOverlay sets up the needed directories, files and permissions for the // overlay-rendered pods
[ "prepateOverlay", "sets", "up", "the", "needed", "directories", "files", "and", "permissions", "for", "the", "overlay", "-", "rendered", "pods" ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage0/run.go#L932-L987
21,067
rkt/rkt
store/treestore/tree.go
NewStore
func NewStore(dir string, store *imagestore.Store) (*Store, error) { // TODO(sgotti) backward compatibility with the current tree store paths. Needs a migration path to better paths. ts := &Store{dir: filepath.Join(dir, "tree"), store: store} ts.lockDir = filepath.Join(dir, "treestorelocks") if err := os.MkdirAll(ts.lockDir, 0755); err != nil { return nil, err } return ts, nil }
go
func NewStore(dir string, store *imagestore.Store) (*Store, error) { // TODO(sgotti) backward compatibility with the current tree store paths. Needs a migration path to better paths. ts := &Store{dir: filepath.Join(dir, "tree"), store: store} ts.lockDir = filepath.Join(dir, "treestorelocks") if err := os.MkdirAll(ts.lockDir, 0755); err != nil { return nil, err } return ts, nil }
[ "func", "NewStore", "(", "dir", "string", ",", "store", "*", "imagestore", ".", "Store", ")", "(", "*", "Store", ",", "error", ")", "{", "// TODO(sgotti) backward compatibility with the current tree store paths. Needs a migration path to better paths.", "ts", ":=", "&", "Store", "{", "dir", ":", "filepath", ".", "Join", "(", "dir", ",", "\"", "\"", ")", ",", "store", ":", "store", "}", "\n\n", "ts", ".", "lockDir", "=", "filepath", ".", "Join", "(", "dir", ",", "\"", "\"", ")", "\n", "if", "err", ":=", "os", ".", "MkdirAll", "(", "ts", ".", "lockDir", ",", "0755", ")", ";", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "return", "ts", ",", "nil", "\n", "}" ]
// NewStore creates a Store for managing filesystem trees, including the dependency graph resolution of the underlying image layers.
[ "NewStore", "creates", "a", "Store", "for", "managing", "filesystem", "trees", "including", "the", "dependency", "graph", "resolution", "of", "the", "underlying", "image", "layers", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/store/treestore/tree.go#L73-L82
21,068
rkt/rkt
store/treestore/tree.go
GetID
func (ts *Store) GetID(key string) (string, error) { hash, err := types.NewHash(key) if err != nil { return "", err } images, err := acirenderer.CreateDepListFromImageID(*hash, ts.store) if err != nil { return "", err } var keys []string for _, image := range images { keys = append(keys, image.Key) } imagesString := strings.Join(keys, ",") h := sha512.New() h.Write([]byte(imagesString)) return "deps-" + hashToKey(h), nil }
go
func (ts *Store) GetID(key string) (string, error) { hash, err := types.NewHash(key) if err != nil { return "", err } images, err := acirenderer.CreateDepListFromImageID(*hash, ts.store) if err != nil { return "", err } var keys []string for _, image := range images { keys = append(keys, image.Key) } imagesString := strings.Join(keys, ",") h := sha512.New() h.Write([]byte(imagesString)) return "deps-" + hashToKey(h), nil }
[ "func", "(", "ts", "*", "Store", ")", "GetID", "(", "key", "string", ")", "(", "string", ",", "error", ")", "{", "hash", ",", "err", ":=", "types", ".", "NewHash", "(", "key", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n", "images", ",", "err", ":=", "acirenderer", ".", "CreateDepListFromImageID", "(", "*", "hash", ",", "ts", ".", "store", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "err", "\n", "}", "\n\n", "var", "keys", "[", "]", "string", "\n", "for", "_", ",", "image", ":=", "range", "images", "{", "keys", "=", "append", "(", "keys", ",", "image", ".", "Key", ")", "\n", "}", "\n", "imagesString", ":=", "strings", ".", "Join", "(", "keys", ",", "\"", "\"", ")", "\n", "h", ":=", "sha512", ".", "New", "(", ")", "\n", "h", ".", "Write", "(", "[", "]", "byte", "(", "imagesString", ")", ")", "\n", "return", "\"", "\"", "+", "hashToKey", "(", "h", ")", ",", "nil", "\n", "}" ]
// GetID calculates the treestore ID for the given image key. // The treeStoreID is computed as an hash of the flattened dependency tree // image keys. In this way the ID may change for the same key if the image's // dependencies change.
[ "GetID", "calculates", "the", "treestore", "ID", "for", "the", "given", "image", "key", ".", "The", "treeStoreID", "is", "computed", "as", "an", "hash", "of", "the", "flattened", "dependency", "tree", "image", "keys", ".", "In", "this", "way", "the", "ID", "may", "change", "for", "the", "same", "key", "if", "the", "image", "s", "dependencies", "change", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/store/treestore/tree.go#L88-L106
21,069
rkt/rkt
store/treestore/tree.go
Render
func (ts *Store) Render(key string, rebuild bool) (id string, hash string, err error) { id, err = ts.GetID(key) if err != nil { return "", "", errwrap.Wrap(errors.New("cannot calculate treestore id"), err) } // this lock references the treestore dir for the specified id. treeStoreKeyLock, err := lock.ExclusiveKeyLock(ts.lockDir, id) if err != nil { return "", "", errwrap.Wrap(errors.New("error locking tree store"), err) } defer treeStoreKeyLock.Close() if !rebuild { rendered, err := ts.IsRendered(id) if err != nil { return "", "", errwrap.Wrap(errors.New("cannot determine if tree is already rendered"), err) } if rendered { return id, "", nil } } // Firstly remove a possible partial treestore if existing. // This is needed as a previous ACI removal operation could have failed // cleaning the tree store leaving some stale files. if err := ts.remove(id); err != nil { return "", "", err } if hash, err = ts.render(id, key); err != nil { return "", "", err } return id, hash, nil }
go
func (ts *Store) Render(key string, rebuild bool) (id string, hash string, err error) { id, err = ts.GetID(key) if err != nil { return "", "", errwrap.Wrap(errors.New("cannot calculate treestore id"), err) } // this lock references the treestore dir for the specified id. treeStoreKeyLock, err := lock.ExclusiveKeyLock(ts.lockDir, id) if err != nil { return "", "", errwrap.Wrap(errors.New("error locking tree store"), err) } defer treeStoreKeyLock.Close() if !rebuild { rendered, err := ts.IsRendered(id) if err != nil { return "", "", errwrap.Wrap(errors.New("cannot determine if tree is already rendered"), err) } if rendered { return id, "", nil } } // Firstly remove a possible partial treestore if existing. // This is needed as a previous ACI removal operation could have failed // cleaning the tree store leaving some stale files. if err := ts.remove(id); err != nil { return "", "", err } if hash, err = ts.render(id, key); err != nil { return "", "", err } return id, hash, nil }
[ "func", "(", "ts", "*", "Store", ")", "Render", "(", "key", "string", ",", "rebuild", "bool", ")", "(", "id", "string", ",", "hash", "string", ",", "err", "error", ")", "{", "id", ",", "err", "=", "ts", ".", "GetID", "(", "key", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "\"", "\"", ",", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"", "\"", ")", ",", "err", ")", "\n", "}", "\n\n", "// this lock references the treestore dir for the specified id.", "treeStoreKeyLock", ",", "err", ":=", "lock", ".", "ExclusiveKeyLock", "(", "ts", ".", "lockDir", ",", "id", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "\"", "\"", ",", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"", "\"", ")", ",", "err", ")", "\n", "}", "\n", "defer", "treeStoreKeyLock", ".", "Close", "(", ")", "\n\n", "if", "!", "rebuild", "{", "rendered", ",", "err", ":=", "ts", ".", "IsRendered", "(", "id", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "\"", "\"", ",", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"", "\"", ")", ",", "err", ")", "\n", "}", "\n", "if", "rendered", "{", "return", "id", ",", "\"", "\"", ",", "nil", "\n", "}", "\n", "}", "\n", "// Firstly remove a possible partial treestore if existing.", "// This is needed as a previous ACI removal operation could have failed", "// cleaning the tree store leaving some stale files.", "if", "err", ":=", "ts", ".", "remove", "(", "id", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "\"", "\"", ",", "err", "\n", "}", "\n", "if", "hash", ",", "err", "=", "ts", ".", "render", "(", "id", ",", "key", ")", ";", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "\"", "\"", ",", "err", "\n", "}", "\n\n", "return", "id", ",", "hash", ",", "nil", "\n", "}" ]
// Render renders a treestore for the given image key if it's not // already fully rendered. // Users of treestore should call s.Render before using it to ensure // that the treestore is completely rendered. // Returns the id and hash of the rendered treestore if it is newly rendered, // and only the id if it is already rendered.
[ "Render", "renders", "a", "treestore", "for", "the", "given", "image", "key", "if", "it", "s", "not", "already", "fully", "rendered", ".", "Users", "of", "treestore", "should", "call", "s", ".", "Render", "before", "using", "it", "to", "ensure", "that", "the", "treestore", "is", "completely", "rendered", ".", "Returns", "the", "id", "and", "hash", "of", "the", "rendered", "treestore", "if", "it", "is", "newly", "rendered", "and", "only", "the", "id", "if", "it", "is", "already", "rendered", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/store/treestore/tree.go#L114-L147
21,070
rkt/rkt
store/treestore/tree.go
Check
func (ts *Store) Check(id string) (string, error) { treeStoreKeyLock, err := lock.SharedKeyLock(ts.lockDir, id) if err != nil { return "", errwrap.Wrap(errors.New("error locking tree store"), err) } defer treeStoreKeyLock.Close() return ts.check(id) }
go
func (ts *Store) Check(id string) (string, error) { treeStoreKeyLock, err := lock.SharedKeyLock(ts.lockDir, id) if err != nil { return "", errwrap.Wrap(errors.New("error locking tree store"), err) } defer treeStoreKeyLock.Close() return ts.check(id) }
[ "func", "(", "ts", "*", "Store", ")", "Check", "(", "id", "string", ")", "(", "string", ",", "error", ")", "{", "treeStoreKeyLock", ",", "err", ":=", "lock", ".", "SharedKeyLock", "(", "ts", ".", "lockDir", ",", "id", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"", "\"", ")", ",", "err", ")", "\n", "}", "\n", "defer", "treeStoreKeyLock", ".", "Close", "(", ")", "\n\n", "return", "ts", ".", "check", "(", "id", ")", "\n", "}" ]
// Check verifies the treestore consistency for the specified id.
[ "Check", "verifies", "the", "treestore", "consistency", "for", "the", "specified", "id", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/store/treestore/tree.go#L150-L158
21,071
rkt/rkt
store/treestore/tree.go
Remove
func (ts *Store) Remove(id string) error { treeStoreKeyLock, err := lock.ExclusiveKeyLock(ts.lockDir, id) if err != nil { return errwrap.Wrap(errors.New("error locking tree store"), err) } defer treeStoreKeyLock.Close() if err := ts.remove(id); err != nil { return errwrap.Wrap(errors.New("error removing the tree store"), err) } return nil }
go
func (ts *Store) Remove(id string) error { treeStoreKeyLock, err := lock.ExclusiveKeyLock(ts.lockDir, id) if err != nil { return errwrap.Wrap(errors.New("error locking tree store"), err) } defer treeStoreKeyLock.Close() if err := ts.remove(id); err != nil { return errwrap.Wrap(errors.New("error removing the tree store"), err) } return nil }
[ "func", "(", "ts", "*", "Store", ")", "Remove", "(", "id", "string", ")", "error", "{", "treeStoreKeyLock", ",", "err", ":=", "lock", ".", "ExclusiveKeyLock", "(", "ts", ".", "lockDir", ",", "id", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"", "\"", ")", ",", "err", ")", "\n", "}", "\n", "defer", "treeStoreKeyLock", ".", "Close", "(", ")", "\n\n", "if", "err", ":=", "ts", ".", "remove", "(", "id", ")", ";", "err", "!=", "nil", "{", "return", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"", "\"", ")", ",", "err", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// Remove removes the rendered image in tree store with the given id.
[ "Remove", "removes", "the", "rendered", "image", "in", "tree", "store", "with", "the", "given", "id", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/store/treestore/tree.go#L161-L173
21,072
rkt/rkt
store/treestore/tree.go
remove
func (ts *Store) remove(id string) error { treepath := ts.GetPath(id) // If tree path doesn't exist we're done _, err := os.Stat(treepath) if err != nil && os.IsNotExist(err) { return nil } if err != nil { return errwrap.Wrap(errors.New("failed to open tree store directory"), err) } renderedFilePath := filepath.Join(treepath, renderedfilename) // The "rendered" flag file should be the firstly removed file. So if // the removal ends with some error leaving some stale files IsRendered() // will return false. _, err = os.Stat(renderedFilePath) if err != nil && !os.IsNotExist(err) { return err } if !os.IsNotExist(err) { err := os.Remove(renderedFilePath) // Ensure that the treepath directory is fsynced after removing the // "rendered" flag file f, err := os.Open(treepath) if err != nil { return errwrap.Wrap(errors.New("failed to open tree store directory"), err) } defer f.Close() err = f.Sync() if err != nil { return errwrap.Wrap(errors.New("failed to sync tree store directory"), err) } } // Ignore error retrieving image hash key, _ := ts.GetImageHash(id) if err := os.RemoveAll(treepath); err != nil { return err } if key != "" { return ts.store.UpdateTreeStoreSize(key, 0) } return nil }
go
func (ts *Store) remove(id string) error { treepath := ts.GetPath(id) // If tree path doesn't exist we're done _, err := os.Stat(treepath) if err != nil && os.IsNotExist(err) { return nil } if err != nil { return errwrap.Wrap(errors.New("failed to open tree store directory"), err) } renderedFilePath := filepath.Join(treepath, renderedfilename) // The "rendered" flag file should be the firstly removed file. So if // the removal ends with some error leaving some stale files IsRendered() // will return false. _, err = os.Stat(renderedFilePath) if err != nil && !os.IsNotExist(err) { return err } if !os.IsNotExist(err) { err := os.Remove(renderedFilePath) // Ensure that the treepath directory is fsynced after removing the // "rendered" flag file f, err := os.Open(treepath) if err != nil { return errwrap.Wrap(errors.New("failed to open tree store directory"), err) } defer f.Close() err = f.Sync() if err != nil { return errwrap.Wrap(errors.New("failed to sync tree store directory"), err) } } // Ignore error retrieving image hash key, _ := ts.GetImageHash(id) if err := os.RemoveAll(treepath); err != nil { return err } if key != "" { return ts.store.UpdateTreeStoreSize(key, 0) } return nil }
[ "func", "(", "ts", "*", "Store", ")", "remove", "(", "id", "string", ")", "error", "{", "treepath", ":=", "ts", ".", "GetPath", "(", "id", ")", "\n", "// If tree path doesn't exist we're done", "_", ",", "err", ":=", "os", ".", "Stat", "(", "treepath", ")", "\n", "if", "err", "!=", "nil", "&&", "os", ".", "IsNotExist", "(", "err", ")", "{", "return", "nil", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"", "\"", ")", ",", "err", ")", "\n", "}", "\n\n", "renderedFilePath", ":=", "filepath", ".", "Join", "(", "treepath", ",", "renderedfilename", ")", "\n", "// The \"rendered\" flag file should be the firstly removed file. So if", "// the removal ends with some error leaving some stale files IsRendered()", "// will return false.", "_", ",", "err", "=", "os", ".", "Stat", "(", "renderedFilePath", ")", "\n", "if", "err", "!=", "nil", "&&", "!", "os", ".", "IsNotExist", "(", "err", ")", "{", "return", "err", "\n", "}", "\n", "if", "!", "os", ".", "IsNotExist", "(", "err", ")", "{", "err", ":=", "os", ".", "Remove", "(", "renderedFilePath", ")", "\n", "// Ensure that the treepath directory is fsynced after removing the", "// \"rendered\" flag file", "f", ",", "err", ":=", "os", ".", "Open", "(", "treepath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"", "\"", ")", ",", "err", ")", "\n", "}", "\n", "defer", "f", ".", "Close", "(", ")", "\n", "err", "=", "f", ".", "Sync", "(", ")", "\n", "if", "err", "!=", "nil", "{", "return", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"", "\"", ")", ",", "err", ")", "\n", "}", "\n", "}", "\n\n", "// Ignore error retrieving image hash", "key", ",", "_", ":=", "ts", ".", "GetImageHash", "(", "id", ")", "\n\n", "if", "err", ":=", "os", ".", "RemoveAll", "(", "treepath", ")", ";", "err", "!=", "nil", "{", "return", "err", "\n", "}", "\n\n", "if", "key", "!=", "\"", "\"", "{", "return", "ts", ".", "store", ".", "UpdateTreeStoreSize", "(", "key", ",", "0", ")", "\n", "}", "\n\n", "return", "nil", "\n", "}" ]
// remove cleans the directory for the provided id
[ "remove", "cleans", "the", "directory", "for", "the", "provided", "id" ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/store/treestore/tree.go#L270-L316
21,073
rkt/rkt
store/treestore/tree.go
IsRendered
func (ts *Store) IsRendered(id string) (bool, error) { // if the "rendered" flag file exists, assume that the store is already // fully rendered. treepath := ts.GetPath(id) _, err := os.Stat(filepath.Join(treepath, renderedfilename)) if os.IsNotExist(err) { return false, nil } if err != nil { return false, err } return true, nil }
go
func (ts *Store) IsRendered(id string) (bool, error) { // if the "rendered" flag file exists, assume that the store is already // fully rendered. treepath := ts.GetPath(id) _, err := os.Stat(filepath.Join(treepath, renderedfilename)) if os.IsNotExist(err) { return false, nil } if err != nil { return false, err } return true, nil }
[ "func", "(", "ts", "*", "Store", ")", "IsRendered", "(", "id", "string", ")", "(", "bool", ",", "error", ")", "{", "// if the \"rendered\" flag file exists, assume that the store is already", "// fully rendered.", "treepath", ":=", "ts", ".", "GetPath", "(", "id", ")", "\n", "_", ",", "err", ":=", "os", ".", "Stat", "(", "filepath", ".", "Join", "(", "treepath", ",", "renderedfilename", ")", ")", "\n", "if", "os", ".", "IsNotExist", "(", "err", ")", "{", "return", "false", ",", "nil", "\n", "}", "\n", "if", "err", "!=", "nil", "{", "return", "false", ",", "err", "\n", "}", "\n", "return", "true", ",", "nil", "\n", "}" ]
// IsRendered checks if the tree store with the provided id is fully rendered
[ "IsRendered", "checks", "if", "the", "tree", "store", "with", "the", "provided", "id", "is", "fully", "rendered" ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/store/treestore/tree.go#L319-L331
21,074
rkt/rkt
store/treestore/tree.go
Hash
func (ts *Store) Hash(id string) (string, error) { treepath := ts.GetPath(id) hash := sha512.New() iw := newHashWriter(hash) err := filepath.Walk(treepath, buildWalker(treepath, iw)) if err != nil { return "", errwrap.Wrap(errors.New("error walking rootfs"), err) } hashstring := hashToKey(hash) return hashstring, nil }
go
func (ts *Store) Hash(id string) (string, error) { treepath := ts.GetPath(id) hash := sha512.New() iw := newHashWriter(hash) err := filepath.Walk(treepath, buildWalker(treepath, iw)) if err != nil { return "", errwrap.Wrap(errors.New("error walking rootfs"), err) } hashstring := hashToKey(hash) return hashstring, nil }
[ "func", "(", "ts", "*", "Store", ")", "Hash", "(", "id", "string", ")", "(", "string", ",", "error", ")", "{", "treepath", ":=", "ts", ".", "GetPath", "(", "id", ")", "\n\n", "hash", ":=", "sha512", ".", "New", "(", ")", "\n", "iw", ":=", "newHashWriter", "(", "hash", ")", "\n", "err", ":=", "filepath", ".", "Walk", "(", "treepath", ",", "buildWalker", "(", "treepath", ",", "iw", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"", "\"", ")", ",", "err", ")", "\n", "}", "\n\n", "hashstring", ":=", "hashToKey", "(", "hash", ")", "\n\n", "return", "hashstring", ",", "nil", "\n", "}" ]
// Hash calculates an hash of the rendered ACI. It uses the same functions // used to create a tar but instead of writing the full archive is just // computes the sha512 sum of the file infos and contents.
[ "Hash", "calculates", "an", "hash", "of", "the", "rendered", "ACI", ".", "It", "uses", "the", "same", "functions", "used", "to", "create", "a", "tar", "but", "instead", "of", "writing", "the", "full", "archive", "is", "just", "computes", "the", "sha512", "sum", "of", "the", "file", "infos", "and", "contents", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/store/treestore/tree.go#L350-L363
21,075
rkt/rkt
store/treestore/tree.go
check
func (ts *Store) check(id string) (string, error) { treepath := ts.GetPath(id) hash, err := ioutil.ReadFile(filepath.Join(treepath, hashfilename)) if err != nil { return "", errwrap.Wrap(ErrReadHashfile, err) } curhash, err := ts.Hash(id) if err != nil { return "", errwrap.Wrap(errors.New("cannot calculate tree hash"), err) } if curhash != string(hash) { return "", fmt.Errorf("wrong tree hash: %s, expected: %s", curhash, hash) } return curhash, nil }
go
func (ts *Store) check(id string) (string, error) { treepath := ts.GetPath(id) hash, err := ioutil.ReadFile(filepath.Join(treepath, hashfilename)) if err != nil { return "", errwrap.Wrap(ErrReadHashfile, err) } curhash, err := ts.Hash(id) if err != nil { return "", errwrap.Wrap(errors.New("cannot calculate tree hash"), err) } if curhash != string(hash) { return "", fmt.Errorf("wrong tree hash: %s, expected: %s", curhash, hash) } return curhash, nil }
[ "func", "(", "ts", "*", "Store", ")", "check", "(", "id", "string", ")", "(", "string", ",", "error", ")", "{", "treepath", ":=", "ts", ".", "GetPath", "(", "id", ")", "\n", "hash", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "filepath", ".", "Join", "(", "treepath", ",", "hashfilename", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "errwrap", ".", "Wrap", "(", "ErrReadHashfile", ",", "err", ")", "\n", "}", "\n", "curhash", ",", "err", ":=", "ts", ".", "Hash", "(", "id", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"", "\"", ")", ",", "err", ")", "\n", "}", "\n", "if", "curhash", "!=", "string", "(", "hash", ")", "{", "return", "\"", "\"", ",", "fmt", ".", "Errorf", "(", "\"", "\"", ",", "curhash", ",", "hash", ")", "\n", "}", "\n", "return", "curhash", ",", "nil", "\n", "}" ]
// check calculates the actual rendered ACI's hash and verifies that it matches // the saved value. Returns the calculated hash.
[ "check", "calculates", "the", "actual", "rendered", "ACI", "s", "hash", "and", "verifies", "that", "it", "matches", "the", "saved", "value", ".", "Returns", "the", "calculated", "hash", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/store/treestore/tree.go#L367-L381
21,076
rkt/rkt
store/treestore/tree.go
Size
func (ts *Store) Size(id string) (int64, error) { sz, err := fileutil.DirSize(ts.GetPath(id)) if err != nil { return -1, errwrap.Wrap(errors.New("error calculating size"), err) } return sz, nil }
go
func (ts *Store) Size(id string) (int64, error) { sz, err := fileutil.DirSize(ts.GetPath(id)) if err != nil { return -1, errwrap.Wrap(errors.New("error calculating size"), err) } return sz, nil }
[ "func", "(", "ts", "*", "Store", ")", "Size", "(", "id", "string", ")", "(", "int64", ",", "error", ")", "{", "sz", ",", "err", ":=", "fileutil", ".", "DirSize", "(", "ts", ".", "GetPath", "(", "id", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "-", "1", ",", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"", "\"", ")", ",", "err", ")", "\n", "}", "\n", "return", "sz", ",", "nil", "\n", "}" ]
// Size returns the size of the rootfs for the provided id. It is a relatively // expensive operation, it goes through all the files and adds up their size.
[ "Size", "returns", "the", "size", "of", "the", "rootfs", "for", "the", "provided", "id", ".", "It", "is", "a", "relatively", "expensive", "operation", "it", "goes", "through", "all", "the", "files", "and", "adds", "up", "their", "size", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/store/treestore/tree.go#L385-L391
21,077
rkt/rkt
store/treestore/tree.go
GetImageHash
func (ts *Store) GetImageHash(id string) (string, error) { treepath := ts.GetPath(id) imgHash, err := ioutil.ReadFile(filepath.Join(treepath, imagefilename)) if err != nil { return "", errwrap.Wrap(errors.New("cannot read image file"), err) } return string(imgHash), nil }
go
func (ts *Store) GetImageHash(id string) (string, error) { treepath := ts.GetPath(id) imgHash, err := ioutil.ReadFile(filepath.Join(treepath, imagefilename)) if err != nil { return "", errwrap.Wrap(errors.New("cannot read image file"), err) } return string(imgHash), nil }
[ "func", "(", "ts", "*", "Store", ")", "GetImageHash", "(", "id", "string", ")", "(", "string", ",", "error", ")", "{", "treepath", ":=", "ts", ".", "GetPath", "(", "id", ")", "\n\n", "imgHash", ",", "err", ":=", "ioutil", ".", "ReadFile", "(", "filepath", ".", "Join", "(", "treepath", ",", "imagefilename", ")", ")", "\n", "if", "err", "!=", "nil", "{", "return", "\"", "\"", ",", "errwrap", ".", "Wrap", "(", "errors", ".", "New", "(", "\"", "\"", ")", ",", "err", ")", "\n", "}", "\n\n", "return", "string", "(", "imgHash", ")", ",", "nil", "\n", "}" ]
// GetImageHash returns the hash of the image that uses the tree store // identified by id.
[ "GetImageHash", "returns", "the", "hash", "of", "the", "image", "that", "uses", "the", "tree", "store", "identified", "by", "id", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/store/treestore/tree.go#L395-L404
21,078
rkt/rkt
pkg/mountinfo/mountinfo.go
HasPrefix
func HasPrefix(p string) FilterFunc { return FilterFunc(func(m *Mount) bool { return strings.HasPrefix(m.MountPoint, p) }) }
go
func HasPrefix(p string) FilterFunc { return FilterFunc(func(m *Mount) bool { return strings.HasPrefix(m.MountPoint, p) }) }
[ "func", "HasPrefix", "(", "p", "string", ")", "FilterFunc", "{", "return", "FilterFunc", "(", "func", "(", "m", "*", "Mount", ")", "bool", "{", "return", "strings", ".", "HasPrefix", "(", "m", ".", "MountPoint", ",", "p", ")", "\n", "}", ")", "\n", "}" ]
// HasPrefix returns a FilterFunc which returns true if // the mountpoint of a given mount has prefix p, else false.
[ "HasPrefix", "returns", "a", "FilterFunc", "which", "returns", "true", "if", "the", "mountpoint", "of", "a", "given", "mount", "has", "prefix", "p", "else", "false", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/mountinfo/mountinfo.go#L32-L36
21,079
rkt/rkt
pkg/mountinfo/mountinfo.go
ParseMounts
func ParseMounts(pid uint) (Mounts, error) { var procPath string if pid == 0 { procPath = "/proc/self/mountinfo" } else { procPath = fmt.Sprintf("/proc/%d/mountinfo", pid) } mi, err := os.Open(procPath) if err != nil { return nil, err } defer mi.Close() return parseMountinfo(mi) }
go
func ParseMounts(pid uint) (Mounts, error) { var procPath string if pid == 0 { procPath = "/proc/self/mountinfo" } else { procPath = fmt.Sprintf("/proc/%d/mountinfo", pid) } mi, err := os.Open(procPath) if err != nil { return nil, err } defer mi.Close() return parseMountinfo(mi) }
[ "func", "ParseMounts", "(", "pid", "uint", ")", "(", "Mounts", ",", "error", ")", "{", "var", "procPath", "string", "\n", "if", "pid", "==", "0", "{", "procPath", "=", "\"", "\"", "\n", "}", "else", "{", "procPath", "=", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "pid", ")", "\n", "}", "\n\n", "mi", ",", "err", ":=", "os", ".", "Open", "(", "procPath", ")", "\n", "if", "err", "!=", "nil", "{", "return", "nil", ",", "err", "\n", "}", "\n", "defer", "mi", ".", "Close", "(", ")", "\n\n", "return", "parseMountinfo", "(", "mi", ")", "\n", "}" ]
// ParseMounts returns all mountpoints associated with a process mount namespace. // The special value 0 as pid argument is used to specify the current process.
[ "ParseMounts", "returns", "all", "mountpoints", "associated", "with", "a", "process", "mount", "namespace", ".", "The", "special", "value", "0", "as", "pid", "argument", "is", "used", "to", "specify", "the", "current", "process", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/pkg/mountinfo/mountinfo.go#L40-L55
21,080
rkt/rkt
stage1/init/kvm/resources.go
findResources
func findResources(isolators types.Isolators) (mem, cpus int64) { for _, i := range isolators { switch v := i.Value().(type) { case *types.ResourceMemory: mem = v.Limit().Value() // Convert bytes into megabytes mem /= 1024 * 1024 case *types.ResourceCPU: cpus = v.Limit().Value() } } return mem, cpus }
go
func findResources(isolators types.Isolators) (mem, cpus int64) { for _, i := range isolators { switch v := i.Value().(type) { case *types.ResourceMemory: mem = v.Limit().Value() // Convert bytes into megabytes mem /= 1024 * 1024 case *types.ResourceCPU: cpus = v.Limit().Value() } } return mem, cpus }
[ "func", "findResources", "(", "isolators", "types", ".", "Isolators", ")", "(", "mem", ",", "cpus", "int64", ")", "{", "for", "_", ",", "i", ":=", "range", "isolators", "{", "switch", "v", ":=", "i", ".", "Value", "(", ")", ".", "(", "type", ")", "{", "case", "*", "types", ".", "ResourceMemory", ":", "mem", "=", "v", ".", "Limit", "(", ")", ".", "Value", "(", ")", "\n", "// Convert bytes into megabytes", "mem", "/=", "1024", "*", "1024", "\n", "case", "*", "types", ".", "ResourceCPU", ":", "cpus", "=", "v", ".", "Limit", "(", ")", ".", "Value", "(", ")", "\n", "}", "\n", "}", "\n", "return", "mem", ",", "cpus", "\n", "}" ]
// findResources finds value of last isolator for particular type.
[ "findResources", "finds", "value", "of", "last", "isolator", "for", "particular", "type", "." ]
0c8765619cae3391a9ffa12c8dbd12ba7a475eb8
https://github.com/rkt/rkt/blob/0c8765619cae3391a9ffa12c8dbd12ba7a475eb8/stage1/init/kvm/resources.go#L42-L54
21,081
go-playground/validator
struct_level.go
wrapStructLevelFunc
func wrapStructLevelFunc(fn StructLevelFunc) StructLevelFuncCtx { return func(ctx context.Context, sl StructLevel) { fn(sl) } }
go
func wrapStructLevelFunc(fn StructLevelFunc) StructLevelFuncCtx { return func(ctx context.Context, sl StructLevel) { fn(sl) } }
[ "func", "wrapStructLevelFunc", "(", "fn", "StructLevelFunc", ")", "StructLevelFuncCtx", "{", "return", "func", "(", "ctx", "context", ".", "Context", ",", "sl", "StructLevel", ")", "{", "fn", "(", "sl", ")", "\n", "}", "\n", "}" ]
// wrapStructLevelFunc wraps normal StructLevelFunc makes it compatible with StructLevelFuncCtx
[ "wrapStructLevelFunc", "wraps", "normal", "StructLevelFunc", "makes", "it", "compatible", "with", "StructLevelFuncCtx" ]
e25e66164b537d7b3161dfede38466880534e783
https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/struct_level.go#L16-L20
21,082
go-playground/validator
struct_level.go
ExtractType
func (v *validate) ExtractType(field reflect.Value) (reflect.Value, reflect.Kind, bool) { return v.extractTypeInternal(field, false) }
go
func (v *validate) ExtractType(field reflect.Value) (reflect.Value, reflect.Kind, bool) { return v.extractTypeInternal(field, false) }
[ "func", "(", "v", "*", "validate", ")", "ExtractType", "(", "field", "reflect", ".", "Value", ")", "(", "reflect", ".", "Value", ",", "reflect", ".", "Kind", ",", "bool", ")", "{", "return", "v", ".", "extractTypeInternal", "(", "field", ",", "false", ")", "\n", "}" ]
// ExtractType gets the actual underlying type of field value.
[ "ExtractType", "gets", "the", "actual", "underlying", "type", "of", "field", "value", "." ]
e25e66164b537d7b3161dfede38466880534e783
https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/struct_level.go#L104-L106
21,083
go-playground/validator
struct_level.go
ReportError
func (v *validate) ReportError(field interface{}, fieldName, structFieldName, tag, param string) { fv, kind, _ := v.extractTypeInternal(reflect.ValueOf(field), false) if len(structFieldName) == 0 { structFieldName = fieldName } v.str1 = string(append(v.ns, fieldName...)) if v.v.hasTagNameFunc || fieldName != structFieldName { v.str2 = string(append(v.actualNs, structFieldName...)) } else { v.str2 = v.str1 } if kind == reflect.Invalid { v.errs = append(v.errs, &fieldError{ v: v.v, tag: tag, actualTag: tag, ns: v.str1, structNs: v.str2, fieldLen: uint8(len(fieldName)), structfieldLen: uint8(len(structFieldName)), param: param, kind: kind, }, ) return } v.errs = append(v.errs, &fieldError{ v: v.v, tag: tag, actualTag: tag, ns: v.str1, structNs: v.str2, fieldLen: uint8(len(fieldName)), structfieldLen: uint8(len(structFieldName)), value: fv.Interface(), param: param, kind: kind, typ: fv.Type(), }, ) }
go
func (v *validate) ReportError(field interface{}, fieldName, structFieldName, tag, param string) { fv, kind, _ := v.extractTypeInternal(reflect.ValueOf(field), false) if len(structFieldName) == 0 { structFieldName = fieldName } v.str1 = string(append(v.ns, fieldName...)) if v.v.hasTagNameFunc || fieldName != structFieldName { v.str2 = string(append(v.actualNs, structFieldName...)) } else { v.str2 = v.str1 } if kind == reflect.Invalid { v.errs = append(v.errs, &fieldError{ v: v.v, tag: tag, actualTag: tag, ns: v.str1, structNs: v.str2, fieldLen: uint8(len(fieldName)), structfieldLen: uint8(len(structFieldName)), param: param, kind: kind, }, ) return } v.errs = append(v.errs, &fieldError{ v: v.v, tag: tag, actualTag: tag, ns: v.str1, structNs: v.str2, fieldLen: uint8(len(fieldName)), structfieldLen: uint8(len(structFieldName)), value: fv.Interface(), param: param, kind: kind, typ: fv.Type(), }, ) }
[ "func", "(", "v", "*", "validate", ")", "ReportError", "(", "field", "interface", "{", "}", ",", "fieldName", ",", "structFieldName", ",", "tag", ",", "param", "string", ")", "{", "fv", ",", "kind", ",", "_", ":=", "v", ".", "extractTypeInternal", "(", "reflect", ".", "ValueOf", "(", "field", ")", ",", "false", ")", "\n\n", "if", "len", "(", "structFieldName", ")", "==", "0", "{", "structFieldName", "=", "fieldName", "\n", "}", "\n\n", "v", ".", "str1", "=", "string", "(", "append", "(", "v", ".", "ns", ",", "fieldName", "...", ")", ")", "\n\n", "if", "v", ".", "v", ".", "hasTagNameFunc", "||", "fieldName", "!=", "structFieldName", "{", "v", ".", "str2", "=", "string", "(", "append", "(", "v", ".", "actualNs", ",", "structFieldName", "...", ")", ")", "\n", "}", "else", "{", "v", ".", "str2", "=", "v", ".", "str1", "\n", "}", "\n\n", "if", "kind", "==", "reflect", ".", "Invalid", "{", "v", ".", "errs", "=", "append", "(", "v", ".", "errs", ",", "&", "fieldError", "{", "v", ":", "v", ".", "v", ",", "tag", ":", "tag", ",", "actualTag", ":", "tag", ",", "ns", ":", "v", ".", "str1", ",", "structNs", ":", "v", ".", "str2", ",", "fieldLen", ":", "uint8", "(", "len", "(", "fieldName", ")", ")", ",", "structfieldLen", ":", "uint8", "(", "len", "(", "structFieldName", ")", ")", ",", "param", ":", "param", ",", "kind", ":", "kind", ",", "}", ",", ")", "\n", "return", "\n", "}", "\n\n", "v", ".", "errs", "=", "append", "(", "v", ".", "errs", ",", "&", "fieldError", "{", "v", ":", "v", ".", "v", ",", "tag", ":", "tag", ",", "actualTag", ":", "tag", ",", "ns", ":", "v", ".", "str1", ",", "structNs", ":", "v", ".", "str2", ",", "fieldLen", ":", "uint8", "(", "len", "(", "fieldName", ")", ")", ",", "structfieldLen", ":", "uint8", "(", "len", "(", "structFieldName", ")", ")", ",", "value", ":", "fv", ".", "Interface", "(", ")", ",", "param", ":", "param", ",", "kind", ":", "kind", ",", "typ", ":", "fv", ".", "Type", "(", ")", ",", "}", ",", ")", "\n", "}" ]
// ReportError reports an error just by passing the field and tag information
[ "ReportError", "reports", "an", "error", "just", "by", "passing", "the", "field", "and", "tag", "information" ]
e25e66164b537d7b3161dfede38466880534e783
https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/struct_level.go#L109-L158
21,084
go-playground/validator
_examples/custom/main.go
ValidateValuer
func ValidateValuer(field reflect.Value) interface{} { if valuer, ok := field.Interface().(driver.Valuer); ok { val, err := valuer.Value() if err == nil { return val } // handle the error how you want } return nil }
go
func ValidateValuer(field reflect.Value) interface{} { if valuer, ok := field.Interface().(driver.Valuer); ok { val, err := valuer.Value() if err == nil { return val } // handle the error how you want } return nil }
[ "func", "ValidateValuer", "(", "field", "reflect", ".", "Value", ")", "interface", "{", "}", "{", "if", "valuer", ",", "ok", ":=", "field", ".", "Interface", "(", ")", ".", "(", "driver", ".", "Valuer", ")", ";", "ok", "{", "val", ",", "err", ":=", "valuer", ".", "Value", "(", ")", "\n", "if", "err", "==", "nil", "{", "return", "val", "\n", "}", "\n", "// handle the error how you want", "}", "\n\n", "return", "nil", "\n", "}" ]
// ValidateValuer implements validator.CustomTypeFunc
[ "ValidateValuer", "implements", "validator", ".", "CustomTypeFunc" ]
e25e66164b537d7b3161dfede38466880534e783
https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/_examples/custom/main.go#L39-L51
21,085
go-playground/validator
errors.go
Error
func (e *InvalidValidationError) Error() string { if e.Type == nil { return "validator: (nil)" } return "validator: (nil " + e.Type.String() + ")" }
go
func (e *InvalidValidationError) Error() string { if e.Type == nil { return "validator: (nil)" } return "validator: (nil " + e.Type.String() + ")" }
[ "func", "(", "e", "*", "InvalidValidationError", ")", "Error", "(", ")", "string", "{", "if", "e", ".", "Type", "==", "nil", "{", "return", "\"", "\"", "\n", "}", "\n\n", "return", "\"", "\"", "+", "e", ".", "Type", ".", "String", "(", ")", "+", "\"", "\"", "\n", "}" ]
// Error returns InvalidValidationError message
[ "Error", "returns", "InvalidValidationError", "message" ]
e25e66164b537d7b3161dfede38466880534e783
https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/errors.go#L26-L33
21,086
go-playground/validator
errors.go
Error
func (ve ValidationErrors) Error() string { buff := bytes.NewBufferString("") var fe *fieldError for i := 0; i < len(ve); i++ { fe = ve[i].(*fieldError) buff.WriteString(fe.Error()) buff.WriteString("\n") } return strings.TrimSpace(buff.String()) }
go
func (ve ValidationErrors) Error() string { buff := bytes.NewBufferString("") var fe *fieldError for i := 0; i < len(ve); i++ { fe = ve[i].(*fieldError) buff.WriteString(fe.Error()) buff.WriteString("\n") } return strings.TrimSpace(buff.String()) }
[ "func", "(", "ve", "ValidationErrors", ")", "Error", "(", ")", "string", "{", "buff", ":=", "bytes", ".", "NewBufferString", "(", "\"", "\"", ")", "\n\n", "var", "fe", "*", "fieldError", "\n\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "ve", ")", ";", "i", "++", "{", "fe", "=", "ve", "[", "i", "]", ".", "(", "*", "fieldError", ")", "\n", "buff", ".", "WriteString", "(", "fe", ".", "Error", "(", ")", ")", "\n", "buff", ".", "WriteString", "(", "\"", "\\n", "\"", ")", "\n", "}", "\n\n", "return", "strings", ".", "TrimSpace", "(", "buff", ".", "String", "(", ")", ")", "\n", "}" ]
// Error is intended for use in development + debugging and not intended to be a production error message. // It allows ValidationErrors to subscribe to the Error interface. // All information to create an error message specific to your application is contained within // the FieldError found within the ValidationErrors array
[ "Error", "is", "intended", "for", "use", "in", "development", "+", "debugging", "and", "not", "intended", "to", "be", "a", "production", "error", "message", ".", "It", "allows", "ValidationErrors", "to", "subscribe", "to", "the", "Error", "interface", ".", "All", "information", "to", "create", "an", "error", "message", "specific", "to", "your", "application", "is", "contained", "within", "the", "FieldError", "found", "within", "the", "ValidationErrors", "array" ]
e25e66164b537d7b3161dfede38466880534e783
https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/errors.go#L43-L57
21,087
go-playground/validator
errors.go
Translate
func (ve ValidationErrors) Translate(ut ut.Translator) ValidationErrorsTranslations { trans := make(ValidationErrorsTranslations) var fe *fieldError for i := 0; i < len(ve); i++ { fe = ve[i].(*fieldError) // // in case an Anonymous struct was used, ensure that the key // // would be 'Username' instead of ".Username" // if len(fe.ns) > 0 && fe.ns[:1] == "." { // trans[fe.ns[1:]] = fe.Translate(ut) // continue // } trans[fe.ns] = fe.Translate(ut) } return trans }
go
func (ve ValidationErrors) Translate(ut ut.Translator) ValidationErrorsTranslations { trans := make(ValidationErrorsTranslations) var fe *fieldError for i := 0; i < len(ve); i++ { fe = ve[i].(*fieldError) // // in case an Anonymous struct was used, ensure that the key // // would be 'Username' instead of ".Username" // if len(fe.ns) > 0 && fe.ns[:1] == "." { // trans[fe.ns[1:]] = fe.Translate(ut) // continue // } trans[fe.ns] = fe.Translate(ut) } return trans }
[ "func", "(", "ve", "ValidationErrors", ")", "Translate", "(", "ut", "ut", ".", "Translator", ")", "ValidationErrorsTranslations", "{", "trans", ":=", "make", "(", "ValidationErrorsTranslations", ")", "\n\n", "var", "fe", "*", "fieldError", "\n\n", "for", "i", ":=", "0", ";", "i", "<", "len", "(", "ve", ")", ";", "i", "++", "{", "fe", "=", "ve", "[", "i", "]", ".", "(", "*", "fieldError", ")", "\n\n", "// // in case an Anonymous struct was used, ensure that the key", "// // would be 'Username' instead of \".Username\"", "// if len(fe.ns) > 0 && fe.ns[:1] == \".\" {", "// \ttrans[fe.ns[1:]] = fe.Translate(ut)", "// \tcontinue", "// }", "trans", "[", "fe", ".", "ns", "]", "=", "fe", ".", "Translate", "(", "ut", ")", "\n", "}", "\n\n", "return", "trans", "\n", "}" ]
// Translate translates all of the ValidationErrors
[ "Translate", "translates", "all", "of", "the", "ValidationErrors" ]
e25e66164b537d7b3161dfede38466880534e783
https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/errors.go#L60-L80
21,088
go-playground/validator
errors.go
Field
func (fe *fieldError) Field() string { return fe.ns[len(fe.ns)-int(fe.fieldLen):] // // return fe.field // fld := fe.ns[len(fe.ns)-int(fe.fieldLen):] // log.Println("FLD:", fld) // if len(fld) > 0 && fld[:1] == "." { // return fld[1:] // } // return fld }
go
func (fe *fieldError) Field() string { return fe.ns[len(fe.ns)-int(fe.fieldLen):] // // return fe.field // fld := fe.ns[len(fe.ns)-int(fe.fieldLen):] // log.Println("FLD:", fld) // if len(fld) > 0 && fld[:1] == "." { // return fld[1:] // } // return fld }
[ "func", "(", "fe", "*", "fieldError", ")", "Field", "(", ")", "string", "{", "return", "fe", ".", "ns", "[", "len", "(", "fe", ".", "ns", ")", "-", "int", "(", "fe", ".", "fieldLen", ")", ":", "]", "\n", "// // return fe.field", "// fld := fe.ns[len(fe.ns)-int(fe.fieldLen):]", "// log.Println(\"FLD:\", fld)", "// if len(fld) > 0 && fld[:1] == \".\" {", "// \treturn fld[1:]", "// }", "// return fld", "}" ]
// Field returns the fields name with the tag name taking precedence over the // fields actual name.
[ "Field", "returns", "the", "fields", "name", "with", "the", "tag", "name", "taking", "precedence", "over", "the", "fields", "actual", "name", "." ]
e25e66164b537d7b3161dfede38466880534e783
https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/errors.go#L206-L219
21,089
go-playground/validator
errors.go
StructField
func (fe *fieldError) StructField() string { // return fe.structField return fe.structNs[len(fe.structNs)-int(fe.structfieldLen):] }
go
func (fe *fieldError) StructField() string { // return fe.structField return fe.structNs[len(fe.structNs)-int(fe.structfieldLen):] }
[ "func", "(", "fe", "*", "fieldError", ")", "StructField", "(", ")", "string", "{", "// return fe.structField", "return", "fe", ".", "structNs", "[", "len", "(", "fe", ".", "structNs", ")", "-", "int", "(", "fe", ".", "structfieldLen", ")", ":", "]", "\n", "}" ]
// returns the fields actual name from the struct, when able to determine.
[ "returns", "the", "fields", "actual", "name", "from", "the", "struct", "when", "able", "to", "determine", "." ]
e25e66164b537d7b3161dfede38466880534e783
https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/errors.go#L222-L225
21,090
go-playground/validator
errors.go
Error
func (fe *fieldError) Error() string { return fmt.Sprintf(fieldErrMsg, fe.ns, fe.Field(), fe.tag) }
go
func (fe *fieldError) Error() string { return fmt.Sprintf(fieldErrMsg, fe.ns, fe.Field(), fe.tag) }
[ "func", "(", "fe", "*", "fieldError", ")", "Error", "(", ")", "string", "{", "return", "fmt", ".", "Sprintf", "(", "fieldErrMsg", ",", "fe", ".", "ns", ",", "fe", ".", "Field", "(", ")", ",", "fe", ".", "tag", ")", "\n", "}" ]
// Error returns the fieldError's error message
[ "Error", "returns", "the", "fieldError", "s", "error", "message" ]
e25e66164b537d7b3161dfede38466880534e783
https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/errors.go#L250-L252
21,091
go-playground/validator
non-standard/validators/notblank.go
NotBlank
func NotBlank(fl validator.FieldLevel) bool { field := fl.Field() switch field.Kind() { case reflect.String: return len(strings.TrimSpace(field.String())) > 0 case reflect.Chan, reflect.Map, reflect.Slice, reflect.Array: return field.Len() > 0 case reflect.Ptr, reflect.Interface, reflect.Func: return !field.IsNil() default: return field.IsValid() && field.Interface() != reflect.Zero(field.Type()).Interface() } }
go
func NotBlank(fl validator.FieldLevel) bool { field := fl.Field() switch field.Kind() { case reflect.String: return len(strings.TrimSpace(field.String())) > 0 case reflect.Chan, reflect.Map, reflect.Slice, reflect.Array: return field.Len() > 0 case reflect.Ptr, reflect.Interface, reflect.Func: return !field.IsNil() default: return field.IsValid() && field.Interface() != reflect.Zero(field.Type()).Interface() } }
[ "func", "NotBlank", "(", "fl", "validator", ".", "FieldLevel", ")", "bool", "{", "field", ":=", "fl", ".", "Field", "(", ")", "\n\n", "switch", "field", ".", "Kind", "(", ")", "{", "case", "reflect", ".", "String", ":", "return", "len", "(", "strings", ".", "TrimSpace", "(", "field", ".", "String", "(", ")", ")", ")", ">", "0", "\n", "case", "reflect", ".", "Chan", ",", "reflect", ".", "Map", ",", "reflect", ".", "Slice", ",", "reflect", ".", "Array", ":", "return", "field", ".", "Len", "(", ")", ">", "0", "\n", "case", "reflect", ".", "Ptr", ",", "reflect", ".", "Interface", ",", "reflect", ".", "Func", ":", "return", "!", "field", ".", "IsNil", "(", ")", "\n", "default", ":", "return", "field", ".", "IsValid", "(", ")", "&&", "field", ".", "Interface", "(", ")", "!=", "reflect", ".", "Zero", "(", "field", ".", "Type", "(", ")", ")", ".", "Interface", "(", ")", "\n", "}", "\n", "}" ]
// NotBlank is the validation function for validating if the current field // has a value or length greater than zero, or is not a space only string.
[ "NotBlank", "is", "the", "validation", "function", "for", "validating", "if", "the", "current", "field", "has", "a", "value", "or", "length", "greater", "than", "zero", "or", "is", "not", "a", "space", "only", "string", "." ]
e25e66164b537d7b3161dfede38466880534e783
https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/non-standard/validators/notblank.go#L12-L25
21,092
go-playground/validator
baked_in.go
wrapFunc
func wrapFunc(fn Func) FuncCtx { if fn == nil { return nil // be sure not to wrap a bad function. } return func(ctx context.Context, fl FieldLevel) bool { return fn(fl) } }
go
func wrapFunc(fn Func) FuncCtx { if fn == nil { return nil // be sure not to wrap a bad function. } return func(ctx context.Context, fl FieldLevel) bool { return fn(fl) } }
[ "func", "wrapFunc", "(", "fn", "Func", ")", "FuncCtx", "{", "if", "fn", "==", "nil", "{", "return", "nil", "// be sure not to wrap a bad function.", "\n", "}", "\n", "return", "func", "(", "ctx", "context", ".", "Context", ",", "fl", "FieldLevel", ")", "bool", "{", "return", "fn", "(", "fl", ")", "\n", "}", "\n", "}" ]
// wrapFunc wraps noramal Func makes it compatible with FuncCtx
[ "wrapFunc", "wraps", "noramal", "Func", "makes", "it", "compatible", "with", "FuncCtx" ]
e25e66164b537d7b3161dfede38466880534e783
https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/baked_in.go#L30-L37
21,093
go-playground/validator
baked_in.go
isUnique
func isUnique(fl FieldLevel) bool { field := fl.Field() v := reflect.ValueOf(struct{}{}) switch field.Kind() { case reflect.Slice, reflect.Array: m := reflect.MakeMap(reflect.MapOf(field.Type().Elem(), v.Type())) for i := 0; i < field.Len(); i++ { m.SetMapIndex(field.Index(i), v) } return field.Len() == m.Len() case reflect.Map: m := reflect.MakeMap(reflect.MapOf(field.Type().Elem(), v.Type())) for _, k := range field.MapKeys() { m.SetMapIndex(field.MapIndex(k), v) } return field.Len() == m.Len() default: panic(fmt.Sprintf("Bad field type %T", field.Interface())) } }
go
func isUnique(fl FieldLevel) bool { field := fl.Field() v := reflect.ValueOf(struct{}{}) switch field.Kind() { case reflect.Slice, reflect.Array: m := reflect.MakeMap(reflect.MapOf(field.Type().Elem(), v.Type())) for i := 0; i < field.Len(); i++ { m.SetMapIndex(field.Index(i), v) } return field.Len() == m.Len() case reflect.Map: m := reflect.MakeMap(reflect.MapOf(field.Type().Elem(), v.Type())) for _, k := range field.MapKeys() { m.SetMapIndex(field.MapIndex(k), v) } return field.Len() == m.Len() default: panic(fmt.Sprintf("Bad field type %T", field.Interface())) } }
[ "func", "isUnique", "(", "fl", "FieldLevel", ")", "bool", "{", "field", ":=", "fl", ".", "Field", "(", ")", "\n", "v", ":=", "reflect", ".", "ValueOf", "(", "struct", "{", "}", "{", "}", ")", "\n\n", "switch", "field", ".", "Kind", "(", ")", "{", "case", "reflect", ".", "Slice", ",", "reflect", ".", "Array", ":", "m", ":=", "reflect", ".", "MakeMap", "(", "reflect", ".", "MapOf", "(", "field", ".", "Type", "(", ")", ".", "Elem", "(", ")", ",", "v", ".", "Type", "(", ")", ")", ")", "\n\n", "for", "i", ":=", "0", ";", "i", "<", "field", ".", "Len", "(", ")", ";", "i", "++", "{", "m", ".", "SetMapIndex", "(", "field", ".", "Index", "(", "i", ")", ",", "v", ")", "\n", "}", "\n", "return", "field", ".", "Len", "(", ")", "==", "m", ".", "Len", "(", ")", "\n", "case", "reflect", ".", "Map", ":", "m", ":=", "reflect", ".", "MakeMap", "(", "reflect", ".", "MapOf", "(", "field", ".", "Type", "(", ")", ".", "Elem", "(", ")", ",", "v", ".", "Type", "(", ")", ")", ")", "\n\n", "for", "_", ",", "k", ":=", "range", "field", ".", "MapKeys", "(", ")", "{", "m", ".", "SetMapIndex", "(", "field", ".", "MapIndex", "(", "k", ")", ",", "v", ")", "\n", "}", "\n", "return", "field", ".", "Len", "(", ")", "==", "m", ".", "Len", "(", ")", "\n", "default", ":", "panic", "(", "fmt", ".", "Sprintf", "(", "\"", "\"", ",", "field", ".", "Interface", "(", ")", ")", ")", "\n", "}", "\n", "}" ]
// isUnique is the validation function for validating if each array|slice|map value is unique
[ "isUnique", "is", "the", "validation", "function", "for", "validating", "if", "each", "array|slice|map", "value", "is", "unique" ]
e25e66164b537d7b3161dfede38466880534e783
https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/baked_in.go#L220-L243
21,094
go-playground/validator
baked_in.go
isMAC
func isMAC(fl FieldLevel) bool { _, err := net.ParseMAC(fl.Field().String()) return err == nil }
go
func isMAC(fl FieldLevel) bool { _, err := net.ParseMAC(fl.Field().String()) return err == nil }
[ "func", "isMAC", "(", "fl", "FieldLevel", ")", "bool", "{", "_", ",", "err", ":=", "net", ".", "ParseMAC", "(", "fl", ".", "Field", "(", ")", ".", "String", "(", ")", ")", "\n\n", "return", "err", "==", "nil", "\n", "}" ]
// IsMAC is the validation function for validating if the field's value is a valid MAC address.
[ "IsMAC", "is", "the", "validation", "function", "for", "validating", "if", "the", "field", "s", "value", "is", "a", "valid", "MAC", "address", "." ]
e25e66164b537d7b3161dfede38466880534e783
https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/baked_in.go#L246-L251
21,095
go-playground/validator
baked_in.go
isCIDRv4
func isCIDRv4(fl FieldLevel) bool { ip, _, err := net.ParseCIDR(fl.Field().String()) return err == nil && ip.To4() != nil }
go
func isCIDRv4(fl FieldLevel) bool { ip, _, err := net.ParseCIDR(fl.Field().String()) return err == nil && ip.To4() != nil }
[ "func", "isCIDRv4", "(", "fl", "FieldLevel", ")", "bool", "{", "ip", ",", "_", ",", "err", ":=", "net", ".", "ParseCIDR", "(", "fl", ".", "Field", "(", ")", ".", "String", "(", ")", ")", "\n\n", "return", "err", "==", "nil", "&&", "ip", ".", "To4", "(", ")", "!=", "nil", "\n", "}" ]
// IsCIDRv4 is the validation function for validating if the field's value is a valid v4 CIDR address.
[ "IsCIDRv4", "is", "the", "validation", "function", "for", "validating", "if", "the", "field", "s", "value", "is", "a", "valid", "v4", "CIDR", "address", "." ]
e25e66164b537d7b3161dfede38466880534e783
https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/baked_in.go#L254-L259
21,096
go-playground/validator
baked_in.go
isCIDR
func isCIDR(fl FieldLevel) bool { _, _, err := net.ParseCIDR(fl.Field().String()) return err == nil }
go
func isCIDR(fl FieldLevel) bool { _, _, err := net.ParseCIDR(fl.Field().String()) return err == nil }
[ "func", "isCIDR", "(", "fl", "FieldLevel", ")", "bool", "{", "_", ",", "_", ",", "err", ":=", "net", ".", "ParseCIDR", "(", "fl", ".", "Field", "(", ")", ".", "String", "(", ")", ")", "\n\n", "return", "err", "==", "nil", "\n", "}" ]
// IsCIDR is the validation function for validating if the field's value is a valid v4 or v6 CIDR address.
[ "IsCIDR", "is", "the", "validation", "function", "for", "validating", "if", "the", "field", "s", "value", "is", "a", "valid", "v4", "or", "v6", "CIDR", "address", "." ]
e25e66164b537d7b3161dfede38466880534e783
https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/baked_in.go#L270-L275
21,097
go-playground/validator
baked_in.go
isIPv6
func isIPv6(fl FieldLevel) bool { ip := net.ParseIP(fl.Field().String()) return ip != nil && ip.To4() == nil }
go
func isIPv6(fl FieldLevel) bool { ip := net.ParseIP(fl.Field().String()) return ip != nil && ip.To4() == nil }
[ "func", "isIPv6", "(", "fl", "FieldLevel", ")", "bool", "{", "ip", ":=", "net", ".", "ParseIP", "(", "fl", ".", "Field", "(", ")", ".", "String", "(", ")", ")", "\n\n", "return", "ip", "!=", "nil", "&&", "ip", ".", "To4", "(", ")", "==", "nil", "\n", "}" ]
// IsIPv6 is the validation function for validating if the field's value is a valid v6 IP address.
[ "IsIPv6", "is", "the", "validation", "function", "for", "validating", "if", "the", "field", "s", "value", "is", "a", "valid", "v6", "IP", "address", "." ]
e25e66164b537d7b3161dfede38466880534e783
https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/baked_in.go#L286-L291
21,098
go-playground/validator
baked_in.go
isIP
func isIP(fl FieldLevel) bool { ip := net.ParseIP(fl.Field().String()) return ip != nil }
go
func isIP(fl FieldLevel) bool { ip := net.ParseIP(fl.Field().String()) return ip != nil }
[ "func", "isIP", "(", "fl", "FieldLevel", ")", "bool", "{", "ip", ":=", "net", ".", "ParseIP", "(", "fl", ".", "Field", "(", ")", ".", "String", "(", ")", ")", "\n\n", "return", "ip", "!=", "nil", "\n", "}" ]
// IsIP is the validation function for validating if the field's value is a valid v4 or v6 IP address.
[ "IsIP", "is", "the", "validation", "function", "for", "validating", "if", "the", "field", "s", "value", "is", "a", "valid", "v4", "or", "v6", "IP", "address", "." ]
e25e66164b537d7b3161dfede38466880534e783
https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/baked_in.go#L294-L299
21,099
go-playground/validator
baked_in.go
isSSN
func isSSN(fl FieldLevel) bool { field := fl.Field() if field.Len() != 11 { return false } return sSNRegex.MatchString(field.String()) }
go
func isSSN(fl FieldLevel) bool { field := fl.Field() if field.Len() != 11 { return false } return sSNRegex.MatchString(field.String()) }
[ "func", "isSSN", "(", "fl", "FieldLevel", ")", "bool", "{", "field", ":=", "fl", ".", "Field", "(", ")", "\n\n", "if", "field", ".", "Len", "(", ")", "!=", "11", "{", "return", "false", "\n", "}", "\n\n", "return", "sSNRegex", ".", "MatchString", "(", "field", ".", "String", "(", ")", ")", "\n", "}" ]
// IsSSN is the validation function for validating if the field's value is a valid SSN.
[ "IsSSN", "is", "the", "validation", "function", "for", "validating", "if", "the", "field", "s", "value", "is", "a", "valid", "SSN", "." ]
e25e66164b537d7b3161dfede38466880534e783
https://github.com/go-playground/validator/blob/e25e66164b537d7b3161dfede38466880534e783/baked_in.go#L302-L311