idx
int64
0
167k
question
stringlengths
60
3.56k
target
stringlengths
5
1.43k
len_question
int64
21
889
len_target
int64
3
529
100
func ( l * Logger ) Errorf ( format string , a ... interface { } ) { l . Print ( l . formatErr ( fmt . Errorf ( format , a ... ) , " " ) ) }
Errorf is a convenience function for formatting and printing errors .
46
12
101
func ( l * Logger ) PanicE ( msg string , e error ) { l . Panic ( l . formatErr ( e , msg ) ) }
PanicE prints a string and error then calls panic .
33
12
102
func Warn ( format string , values ... interface { } ) { fmt . Fprintf ( os . Stderr , fmt . Sprintf ( " " , format , '\n' ) , values ... ) }
Warn is just a shorter version of a formatted printing to stderr . It appends a newline for you .
44
25
103
func MustAbs ( dir string ) string { absDir , err := filepath . Abs ( dir ) if err != nil { panic ( fmt . Sprintf ( " \n " , dir , err ) ) } return filepath . Clean ( absDir ) }
MustAbs returns an absolute path . It works like filepath . Abs but panics if it fails .
54
21
104
func parseDuration ( s string ) ( time . Duration , error ) { if s == " " { return time . Duration ( - 1 ) , nil } b , err := strconv . ParseBool ( s ) switch { case err != nil : return time . ParseDuration ( s ) case b : return time . Duration ( - 1 ) , nil } return time . Duration ( 0 ) , nil }
parseDuration converts the given string s to a duration value . If it is empty string or a true boolean value according to strconv . ParseBool a negative duration is returned . If the boolean value is false a 0 duration is returned . If the string s is a duration value then it is returned . It returns an error if the duration conversion failed .
86
72
105
func newContext ( t time . Duration ) context . Context { ctx := context . Background ( ) if t > 0 { ctx , _ = context . WithTimeout ( ctx , t ) } return ctx }
newContext returns a new context with timeout t if t > 0 .
46
14
106
func getExitStatuses ( p * pkgPod . Pod ) ( map [ string ] int , error ) { _ , manifest , err := p . PodManifest ( ) if err != nil { return nil , err } stats := make ( map [ string ] int ) for _ , app := range manifest . Apps { exitCode , err := p . AppExitCode ( app . Name . String ( ) ) if err != nil { continue } stats [ app . Name . String ( ) ] = exitCode } return stats , nil }
getExitStatuses returns a map of the statuses of the pod .
112
15
107
func printStatus ( p * pkgPod . Pod ) error { if flagFormat != outputFormatTabbed { pod , err := lib . NewPodFromInternalPod ( p ) if err != nil { return fmt . Errorf ( " " , err ) } switch flagFormat { case outputFormatJSON : result , err := json . Marshal ( pod ) if err != nil { return fmt . Errorf ( " " , err ) } stdout . Print ( string ( result ) ) case outputFormatPrettyJSON : result , err := json . MarshalIndent ( pod , " " , " \t " ) if err != nil { return fmt . Errorf ( " " , err ) } stdout . Print ( string ( result ) ) } return nil } state := p . State ( ) stdout . Printf ( " " , state ) created , err := p . CreationTime ( ) if err != nil { return fmt . Errorf ( " " , p . UUID , err ) } createdStr := created . Format ( defaultTimeLayout ) stdout . Printf ( " " , createdStr ) started , err := p . StartTime ( ) if err != nil { return fmt . Errorf ( " " , p . UUID , err ) } var startedStr string if ! started . IsZero ( ) { startedStr = started . Format ( defaultTimeLayout ) stdout . Printf ( " " , startedStr ) } if state == pkgPod . Running || state == pkgPod . Exited { stdout . Printf ( " " , fmtNets ( p . Nets ) ) } if ! ( state == pkgPod . Running || state == pkgPod . Deleting || state == pkgPod . ExitedDeleting || state == pkgPod . Exited || state == pkgPod . ExitedGarbage ) { return nil } if pid , err := p . Pid ( ) ; err == nil { // the pid file might not be written yet when the state changes to 'Running' // it may also never be written if systemd never executes (e.g.: a bad command) stdout . Printf ( " " , pid ) } stdout . Printf ( " " , ( state == pkgPod . Exited || state == pkgPod . ExitedGarbage ) ) if state != pkgPod . Running { stats , err := getExitStatuses ( p ) if err != nil { return fmt . Errorf ( " " , p . UUID , err ) } for app , stat := range stats { stdout . Printf ( " " , app , stat ) } } return nil }
printStatus prints the pod s pid and per - app status codes
556
13
108
func ascURLFromImgURL ( u * url . URL ) * url . URL { copy := * u copy . Path = ascPathFromImgPath ( copy . Path ) return & copy }
ascURLFromImgURL creates a URL to a signature file from passed URL to an image .
42
20
109
func printIdentities ( entity * openpgp . Entity ) { lines := [ ] string { " " } for _ , v := range entity . Identities { lines = append ( lines , fmt . Sprintf ( " " , v . Name ) ) } log . Print ( strings . Join ( lines , " \n " ) ) }
printIdentities prints a message that signature was verified .
71
11
110
func DistFromImageString ( is string ) ( dist . Distribution , error ) { u , err := url . Parse ( is ) if err != nil { return nil , errwrap . Wrap ( fmt . Errorf ( " " , is ) , err ) } // Convert user friendly image string names to internal distribution URIs // file:///full/path/to/aci/file.aci -> archive:aci:file%3A%2F%2F%2Ffull%2Fpath%2Fto%2Faci%2Ffile.aci switch u . Scheme { case " " : // no scheme given, hence it is an appc image name or path appImageType := guessAppcOrPath ( is , [ ] string { schema . ACIExtension } ) switch appImageType { case imageStringName : app , err := discovery . NewAppFromString ( is ) if err != nil { return nil , fmt . Errorf ( " " , is , err ) } return dist . NewAppcFromApp ( app ) , nil case imageStringPath : absPath , err := filepath . Abs ( is ) if err != nil { return nil , errwrap . Wrap ( fmt . Errorf ( " " , is ) , err ) } is = " " + absPath // given a file:// image string, call this function again to return an ACI distribution return DistFromImageString ( is ) default : return nil , fmt . Errorf ( " " , appImageType ) } case " " , " " , " " : // An ACI archive with any transport type (file, http, s3 etc...) and final aci extension if filepath . Ext ( u . Path ) == schema . ACIExtension { dist , err := dist . NewACIArchiveFromTransportURL ( u ) if err != nil { return nil , fmt . Errorf ( " " , err ) } return dist , nil } case " " : // Accept both docker: and docker:// uri dockerStr := is if strings . HasPrefix ( dockerStr , " " ) { dockerStr = strings . TrimPrefix ( dockerStr , " " ) } else if strings . HasPrefix ( dockerStr , " " ) { dockerStr = strings . TrimPrefix ( dockerStr , " " ) } dist , err := dist . NewDockerFromString ( dockerStr ) if err != nil { return nil , fmt . Errorf ( " " , err ) } return dist , nil case dist . Scheme : // cimd return dist . Parse ( is ) default : // any other scheme is a an appc image name, i.e. "my-app:v1.0" app , err := discovery . NewAppFromString ( is ) if err != nil { return nil , fmt . Errorf ( " " , is , err ) } return dist . NewAppcFromApp ( app ) , nil } return nil , fmt . Errorf ( " " , is ) }
DistFromImageString return the distribution for the given input image string
638
13
111
func parseCIMD ( u * url . URL ) ( * cimd , error ) { if u . Scheme != Scheme { return nil , fmt . Errorf ( " " , u . Scheme ) } parts := strings . SplitN ( u . Opaque , " " , 3 ) if len ( parts ) < 3 { return nil , fmt . Errorf ( " " , u . String ( ) ) } version , err := strconv . ParseUint ( strings . TrimPrefix ( parts [ 1 ] , " " ) , 10 , 32 ) if err != nil { return nil , fmt . Errorf ( " " , parts [ 1 ] ) } return & cimd { Type : Type ( parts [ 0 ] ) , Version : uint32 ( version ) , Data : parts [ 2 ] , } , nil }
parseCIMD parses the given url and returns a cimd .
176
16
112
func NewCIMDString ( typ Type , version uint32 , data string ) string { return fmt . Sprintf ( " " , Scheme , typ , version , data ) }
NewCIMDString creates a new cimd URL string .
37
14
113
func getApp ( p * pkgPod . Pod ) ( * schema . RuntimeApp , error ) { _ , manifest , err := p . PodManifest ( ) if err != nil { return nil , errwrap . Wrap ( errors . New ( " " ) , err ) } apps := manifest . Apps if flagExportAppName != " " { exportAppName , err := types . NewACName ( flagExportAppName ) if err != nil { return nil , err } for _ , ra := range apps { if * exportAppName == ra . Name { return & ra , nil } } return nil , fmt . Errorf ( " " , flagExportAppName ) } switch len ( apps ) { case 0 : return nil , fmt . Errorf ( " " ) case 1 : return & apps [ 0 ] , nil default : } stderr . Print ( " " ) for _ , ra := range apps { stderr . Printf ( " \t " , ra . Name ) } return nil , fmt . Errorf ( " \" \" " ) }
getApp returns the app to export If one was supplied in the flags then it s returned if present If the PM contains a single app that app is returned If the PM has multiple apps the names are printed and an error is returned
224
46
114
func mountOverlay ( pod * pkgPod . Pod , app * schema . RuntimeApp , dest string ) error { if _ , err := os . Stat ( dest ) ; err != nil { return err } s , err := imagestore . NewStore ( getDataDir ( ) ) if err != nil { return errwrap . Wrap ( errors . New ( " " ) , err ) } ts , err := treestore . NewStore ( treeStoreDir ( ) , s ) if err != nil { return errwrap . Wrap ( errors . New ( " " ) , err ) } treeStoreID , err := pod . GetAppTreeStoreID ( app . Name ) if err != nil { return err } lower := ts . GetRootFS ( treeStoreID ) imgDir := filepath . Join ( filepath . Join ( pod . Path ( ) , " " ) , treeStoreID ) if _ , err := os . Stat ( imgDir ) ; err != nil { return err } upper := filepath . Join ( imgDir , " " , app . Name . String ( ) ) if _ , err := os . Stat ( upper ) ; err != nil { return err } work := filepath . Join ( imgDir , " " , app . Name . String ( ) ) if _ , err := os . Stat ( work ) ; err != nil { return err } if err := overlay . Mount ( & overlay . MountCfg { lower , upper , work , dest , " " } ) ; err != nil { return errwrap . Wrap ( errors . New ( " " ) , err ) } return nil }
mountOverlay mounts the app from the overlay - rendered pod to the destination directory .
340
17
115
func buildAci ( root , manifestPath , target string , uidRange * user . UidRange ) ( e error ) { mode := os . O_CREATE | os . O_WRONLY if flagOverwriteACI { mode |= os . O_TRUNC } else { mode |= os . O_EXCL } aciFile , err := os . OpenFile ( target , mode , 0644 ) if err != nil { if os . IsExist ( err ) { return errors . New ( " " ) } else { return errwrap . Wrap ( fmt . Errorf ( " " , target ) , err ) } } gw := gzip . NewWriter ( aciFile ) tr := tar . NewWriter ( gw ) defer func ( ) { tr . Close ( ) gw . Close ( ) aciFile . Close ( ) // e is implicitly assigned by the return statement. As defer runs // after return, but before actually returning, this works. if e != nil { os . Remove ( target ) } } ( ) b , err := ioutil . ReadFile ( manifestPath ) if err != nil { return errwrap . Wrap ( errors . New ( " " ) , err ) } var im schema . ImageManifest if err := im . UnmarshalJSON ( b ) ; err != nil { return errwrap . Wrap ( errors . New ( " " ) , err ) } iw := aci . NewImageWriter ( im , tr ) // Unshift uid and gid when pod was started with --private-user (user namespace) var walkerCb aci . TarHeaderWalkFunc = func ( hdr * tar . Header ) bool { if uidRange != nil { uid , gid , err := uidRange . UnshiftRange ( uint32 ( hdr . Uid ) , uint32 ( hdr . Gid ) ) if err != nil { stderr . PrintE ( " " , err ) return false } hdr . Uid , hdr . Gid = int ( uid ) , int ( gid ) } return true } if err := filepath . Walk ( root , aci . BuildWalker ( root , iw , walkerCb ) ) ; err != nil { return errwrap . Wrap ( errors . New ( " " ) , err ) } if err = iw . Close ( ) ; err != nil { return errwrap . Wrap ( fmt . Errorf ( " " , target ) , err ) } return }
buildAci builds a target aci from the root directory using any uid shift information from uidRange .
538
23
116
func ensureSuperuser ( cf func ( cmd * cobra . Command , args [ ] string ) ) func ( cmd * cobra . Command , args [ ] string ) { return func ( cmd * cobra . Command , args [ ] string ) { if os . Geteuid ( ) != 0 { stderr . Print ( " " ) cmdExitCode = 254 return } cf ( cmd , args ) } }
ensureSuperuser will error out if the effective UID of the current process is not zero . Otherwise it will invoke the supplied cobra command .
87
29
117
func generateSeccompFilter ( p * stage1commontypes . Pod , pa * preparedApp ) ( * seccompFilter , error ) { sf := seccompFilter { } seenIsolators := 0 for _ , i := range pa . app . App . Isolators { var flag string var err error if seccomp , ok := i . Value ( ) . ( types . LinuxSeccompSet ) ; ok { seenIsolators ++ // By appc spec, only one seccomp isolator per app is allowed if seenIsolators > 1 { return nil , ErrTooManySeccompIsolators } switch i . Name { case types . LinuxSeccompRemoveSetName : sf . mode = ModeBlacklist sf . syscalls , flag , err = parseLinuxSeccompSet ( p , seccomp ) if err != nil { return nil , err } if flag == " " { // we interpret "remove @empty" to mean "default whitelist" sf . mode = ModeWhitelist sf . syscalls = RktDefaultSeccompWhitelist } case types . LinuxSeccompRetainSetName : sf . mode = ModeWhitelist sf . syscalls , flag , err = parseLinuxSeccompSet ( p , seccomp ) if err != nil { return nil , err } if flag == " " { // Opt-out seccomp filtering return nil , nil } } sf . errno = string ( seccomp . Errno ( ) ) } } // If unset, use rkt default whitelist if seenIsolators == 0 { sf . mode = ModeWhitelist sf . syscalls = RktDefaultSeccompWhitelist } // Non-priv apps *must* have NoNewPrivileges set if they have seccomp sf . forceNoNewPrivileges = ( pa . uid != 0 ) return & sf , nil }
generateSeccompFilter computes the concrete seccomp filter from the isolators
422
18
118
func seccompUnitOptions ( opts [ ] * unit . UnitOption , sf * seccompFilter ) ( [ ] * unit . UnitOption , error ) { if sf == nil { return opts , nil } if sf . errno != " " { opts = append ( opts , unit . NewUnitOption ( " " , " " , sf . errno ) ) } var filterPrefix string switch sf . mode { case ModeWhitelist : filterPrefix = sdWhitelistPrefix case ModeBlacklist : filterPrefix = sdBlacklistPrefix default : return nil , fmt . Errorf ( " " , sf . mode ) } // SystemCallFilter options are written down one entry per line, because // filtering sets may be quite large and overlong lines break unit serialization. opts = appendOptionsList ( opts , " " , " " , filterPrefix , sf . syscalls ... ) return opts , nil }
seccompUnitOptions converts a concrete seccomp filter to systemd unit options
209
16
119
func parseLinuxSeccompSet ( p * stage1commontypes . Pod , s types . LinuxSeccompSet ) ( syscallFilter [ ] string , flag string , err error ) { for _ , item := range s . Set ( ) { if item [ 0 ] == '@' { // Wildcards wildcard := strings . SplitN ( string ( item ) , " " , 2 ) if len ( wildcard ) != 2 { continue } scope := wildcard [ 0 ] name := wildcard [ 1 ] switch scope { case " " : // appc-reserved wildcards switch name { case " " : return nil , " " , nil case " " : return nil , " " , nil } case " " : // Docker-originated wildcards switch name { case " " : syscallFilter = append ( syscallFilter , DockerDefaultSeccompBlacklist ... ) case " " : syscallFilter = append ( syscallFilter , DockerDefaultSeccompWhitelist ... ) } case " " : // Custom rkt wildcards switch name { case " " : syscallFilter = append ( syscallFilter , RktDefaultSeccompBlacklist ... ) case " " : syscallFilter = append ( syscallFilter , RktDefaultSeccompWhitelist ... ) } case " " : // Custom systemd wildcards (systemd >= 231) _ , systemdVersion , err := GetFlavor ( p ) if err != nil || systemdVersion < 231 { return nil , " " , errors . New ( " " ) } switch name { case " " : syscallFilter = append ( syscallFilter , " " ) case " " : syscallFilter = append ( syscallFilter , " " ) case " " : syscallFilter = append ( syscallFilter , " " ) case " " : syscallFilter = append ( syscallFilter , " " ) case " " : syscallFilter = append ( syscallFilter , " " ) case " " : syscallFilter = append ( syscallFilter , " " ) case " " : syscallFilter = append ( syscallFilter , " " ) case " " : syscallFilter = append ( syscallFilter , " " ) } } } else { // Plain syscall name syscallFilter = append ( syscallFilter , string ( item ) ) } } return syscallFilter , " " , nil }
parseLinuxSeccompSet gets an appc LinuxSeccompSet and returns an array of values suitable for systemd SystemCallFilter .
531
28
120
func main ( ) { flag . Parse ( ) stage1initcommon . InitDebug ( debug ) log , diag , _ = rktlog . NewLogSet ( " " , debug ) if ! debug { diag . SetOutput ( ioutil . Discard ) } appName , err := types . NewACName ( flagApp ) if err != nil { log . FatalE ( " " , err ) } enterCmd := stage1common . PrepareEnterCmd ( false ) switch flagStage { case 0 : // clean resources in stage0 err = cleanupStage0 ( appName , enterCmd ) case 1 : // clean resources in stage1 err = cleanupStage1 ( appName , enterCmd ) default : // unknown step err = fmt . Errorf ( " " , flagStage ) } if err != nil { log . FatalE ( " " , err ) } os . Exit ( 0 ) }
This is a multi - step entrypoint . It starts in stage0 context then invokes itself again in stage1 context to perform further cleanup at pod level .
190
32
121
func cleanupStage1 ( appName * types . ACName , enterCmd [ ] string ) error { // TODO(lucab): re-evaluate once/if we support systemd as non-pid1 (eg. host pid-ns inheriting) mnts , err := mountinfo . ParseMounts ( 1 ) if err != nil { return err } appRootFs := filepath . Join ( " " , appName . String ( ) , " " ) mnts = mnts . Filter ( mountinfo . HasPrefix ( appRootFs ) ) // soft-errors here, stage0 may still be able to continue with the removal anyway for _ , m := range mnts { // unlink first to avoid back-propagation _ = syscall . Mount ( " " , m . MountPoint , " " , syscall . MS_PRIVATE | syscall . MS_REC , " " ) // simple unmount, it may fail if the target is busy (eg. overlapping children) if e := syscall . Unmount ( m . MountPoint , 0 ) ; e != nil { // if busy, just detach here and let the kernel clean it once free _ = syscall . Unmount ( m . MountPoint , syscall . MNT_DETACH ) } } return nil }
cleanupStage1 is meant to be executed in stage1 context . It inspects pod systemd - pid1 mountinfo to find all remaining mountpoints for appName and proceed to clean them up .
286
40
122
func renameExited ( ) error { if err := pkgPod . WalkPods ( getDataDir ( ) , pkgPod . IncludeRunDir , func ( p * pkgPod . Pod ) { if p . State ( ) == pkgPod . Exited { stderr . Printf ( " " , p . UUID ) if err := p . ToExitedGarbage ( ) ; err != nil && err != os . ErrNotExist { stderr . PrintE ( " " , err ) } } } ) ; err != nil { return err } return nil }
renameExited renames exited pods to the exitedGarbage directory
126
14
123
func renameAborted ( ) error { if err := pkgPod . WalkPods ( getDataDir ( ) , pkgPod . IncludePrepareDir , func ( p * pkgPod . Pod ) { if p . State ( ) == pkgPod . AbortedPrepare { stderr . Printf ( " " , p . UUID ) if err := p . ToGarbage ( ) ; err != nil && err != os . ErrNotExist { stderr . PrintE ( " " , err ) } } } ) ; err != nil { return err } return nil }
renameAborted renames failed prepares to the garbage directory
127
12
124
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 ( " " , pp ) , err ) } return } if expiration := time . Unix ( st . Ctim . Unix ( ) ) . Add ( preparedExpiration ) ; time . Now ( ) . After ( expiration ) { stderr . Printf ( " " , p . UUID ) if err := p . ToGarbage ( ) ; err != nil && err != os . ErrNotExist { stderr . PrintE ( " " , err ) } } } ) ; err != nil { return err } return nil }
renameExpired renames expired prepared pods to the garbage directory
224
13
125
func deletePod ( p * pkgPod . Pod ) bool { podState := p . State ( ) if podState != pkgPod . ExitedGarbage && podState != pkgPod . Garbage && podState != pkgPod . ExitedDeleting { stderr . Errorf ( " " , p . UUID , p . State ( ) ) return false } if podState == pkgPod . ExitedGarbage { s , err := imagestore . NewStore ( storeDir ( ) ) if err != nil { stderr . PrintE ( " " , err ) return false } defer s . Close ( ) ts , err := treestore . NewStore ( treeStoreDir ( ) , s ) if err != nil { stderr . PrintE ( " " , 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 ( " " , 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 ( " " , err ) } } } else { stderr . PrintE ( " " , err ) } // unmount all leftover mounts if err := stage0 . MountGC ( p . Path ( ) , p . UUID . String ( ) ) ; err != nil { stderr . PrintE ( fmt . Sprintf ( " " , 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 ( " " , p . UUID ) , e ) return false } } // finally remove all remaining pieces if err := os . RemoveAll ( p . Path ( ) ) ; err != nil { stderr . PrintE ( fmt . Sprintf ( " " , p . UUID ) , err ) return false } return true }
deletePod cleans up files and resource associated with the pod pod must be under exclusive lock and be in either ExitedGarbage or Garbage state
610
29
126
func ( s * Store ) backupDB ( ) error { if os . Geteuid ( ) != 0 { return ErrDBUpdateNeedsRoot } backupsDir := filepath . Join ( s . dir , " " ) return backup . CreateBackup ( s . dbDir ( ) , backupsDir , backupsNumber ) }
backupDB backs up current database .
67
8
127
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 ( " " ) , err ) } keys := make ( [ ] string , len ( aciInfos ) ) for i , aciInfo := range aciInfos { keys [ i ] = aciInfo . BlobKey } return keys , found , nil }
ResolveName resolves an image name to a list of full keys and using the store for resolution .
160
20
128
func ( s * Store ) RemoveACI ( key string ) error { imageKeyLock , err := lock . ExclusiveKeyLock ( s . imageLockDir , key ) if err != nil { return errwrap . Wrap ( errors . New ( " " ) , 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 ( " " ) , err ) } else if ! found { return fmt . Errorf ( " " , 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 ( " " , 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 }
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 .
403
53
129
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 }
GetRemote tries to retrieve a remote with the given ACIURL . If remote doesn t exist it returns ErrRemoteNotFound error .
79
27
130
func ( s * Store ) GetImageManifestJSON ( key string ) ( [ ] byte , error ) { key , err := s . ResolveKey ( key ) if err != nil { return nil , errwrap . Wrap ( errors . New ( " " ) , err ) } keyLock , err := lock . SharedKeyLock ( s . imageLockDir , key ) if err != nil { return nil , errwrap . Wrap ( errors . New ( " " ) , err ) } defer keyLock . Close ( ) imj , err := s . stores [ imageManifestType ] . Read ( key ) if err != nil { return nil , errwrap . Wrap ( errors . New ( " " ) , err ) } return imj , nil }
GetImageManifestJSON gets the ImageManifest JSON bytes with the specified key .
158
17
131
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 ( " " ) , err ) } return im , nil }
GetImageManifest gets the ImageManifest with the specified key .
103
14
132
func ( s * Store ) HasFullKey ( key string ) bool { return s . stores [ imageManifestType ] . Has ( 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 .
31
28
133
func keyToString ( k [ ] byte ) string { if len ( k ) != lenHash { panic ( fmt . Sprintf ( " " , k ) ) } return fmt . Sprintf ( " " , hashPrefix , k ) [ 0 : lenKey ] }
keyToString takes a key and returns a shortened and prefixed hexadecimal string version
57
19
134
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 ( " " , u . String ( ) ) , err ) } if err := out . Sync ( ) ; err != nil { return errwrap . Wrap ( fmt . Errorf ( " " , u . String ( ) ) , err ) } return nil }
Download tries to fetch the passed URL and write the contents into a given writeSyncer instance .
216
19
135
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 ( " " ) , err ) } switch len ( m . Apps ) { case 0 : return nil , fmt . Errorf ( " " ) case 1 : return & m . Apps [ 0 ] . Name , nil default : } stderr . Print ( " " ) for _ , ra := range m . Apps { stderr . Printf ( " \t " , ra . Name ) } return nil , fmt . Errorf ( " \" \" " ) }
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
185
49
136
func getEnterArgv ( p * pkgPod . Pod , cmdArgs [ ] string ) ( [ ] string , error ) { var argv [ ] string if len ( cmdArgs ) < 2 { stderr . Printf ( " " , defaultCmd ) argv = [ ] string { defaultCmd } } else { argv = cmdArgs [ 1 : ] } return argv , nil }
getEnterArgv returns the argv to use for entering the pod
85
14
137
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 ( " " , mountPoint ) , err ) } return nil }
mountFsRO remounts the given mountPoint using the given flags read - only .
102
18
138
func GetEnabledCgroups ( ) ( map [ int ] [ ] string , error ) { cgroupsFile , err := os . Open ( " " ) if err != nil { return nil , err } defer cgroupsFile . Close ( ) cgroups , err := parseCgroups ( cgroupsFile ) if err != nil { return nil , errwrap . Wrap ( errors . New ( " " ) , err ) } return cgroups , nil }
GetEnabledCgroups returns a map with the enabled cgroup controllers grouped by hierarchy
93
16
139
func GetOwnCgroupPath ( controller string ) ( string , error ) { parts , err := parseCgroupController ( " " , controller ) if err != nil { return " " , err } return parts [ 2 ] , nil }
GetOwnCgroupPath returns the cgroup path of this process in controller hierarchy
49
16
140
func GetCgroupPathByPid ( pid int , controller string ) ( string , error ) { parts , err := parseCgroupController ( fmt . Sprintf ( " " , pid ) , controller ) if err != nil { return " " , err } return parts [ 2 ] , nil }
GetCgroupPathByPid returns the cgroup path of the process with the given pid and given controller .
62
23
141
func JoinSubcgroup ( controller string , subcgroup string ) error { subcgroupPath := filepath . Join ( " " , controller , subcgroup ) if err := os . MkdirAll ( subcgroupPath , 0600 ) ; err != nil { return errwrap . Wrap ( fmt . Errorf ( " " , subcgroup ) , err ) } pidBytes := [ ] byte ( strconv . Itoa ( os . Getpid ( ) ) ) if err := ioutil . WriteFile ( filepath . Join ( subcgroupPath , " " ) , pidBytes , 0600 ) ; err != nil { return errwrap . Wrap ( fmt . Errorf ( " " , subcgroup ) , err ) } return nil }
JoinSubcgroup makes the calling process join the subcgroup hierarchy on a particular controller
160
18
142
func IsControllerMounted ( c string ) ( bool , error ) { cgroupProcsPath := filepath . Join ( " " , c , " " ) if _ , err := os . Stat ( cgroupProcsPath ) ; err != nil { if ! os . IsNotExist ( err ) { return false , err } return false , nil } return true , nil }
IsControllerMounted returns whether a controller is mounted by checking that cgroup . procs is accessible
81
20
143
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 }
Returns a nil slice and nil error if the xattr is not set
329
14
144
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 ( " " , path ) return } stat_t , ok := d . Sys ( ) . ( * syscall . Stat_t ) if ! ok { err = fmt . Errorf ( " " ) return } return getDeviceInfo ( mode , stat_t . Rdev ) }
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 .
127
33
145
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 }
Parse the device info out of the mode bits . Separate for testability .
91
17
146
func IsIsolatorSupported ( isolator string ) ( bool , error ) { isUnified , err := IsCgroupUnified ( " " ) if err != nil { return false , errwrap . Wrap ( errors . New ( " " ) , err ) } if isUnified { controllers , err := v2 . GetEnabledControllers ( ) if err != nil { return false , errwrap . Wrap ( errors . New ( " " ) , err ) } for _ , c := range controllers { if c == isolator { return true , nil } } return false , nil } return v1 . IsControllerMounted ( isolator ) }
IsIsolatorSupported returns whether an isolator is supported in the kernel
136
15
147
func CreateBackup ( dir , backupsDir string , limit int ) error { tmpBackupDir := filepath . Join ( backupsDir , " " ) 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 , " " ) ) ; err != nil { return err } return nil }
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 .
187
92
148
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 }
pruneOldBackups removes old backups that is - directories with names greater or equal than given limit .
145
21
149
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 }
shiftBackups renames all directories with names being numbers up to oldest to names with numbers greater by one .
106
22
150
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 ) }
NewBasicACI creates a new ACI in the given directory with the given name . Used for testing .
95
22
151
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 ( " " ) , 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 }
NewACI creates a new ACI in the given directory with the given image manifest and entries . Used for testing .
288
24
152
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 ( " " ) } signature := & bytes . Buffer { } if err := openpgp . ArmoredDetachSign ( signature , entityList [ 0 ] , aci , nil ) ; err != nil { return nil , err } return signature , nil }
NewDetachedSignature creates a new openpgp armored detached signature for the given ACI signed with armoredPrivateKey .
130
25
153
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 ( " " ) , err ) } ms , ok := pm . Annotations . Get ( " " ) if ok { p . mutable , err = strconv . ParseBool ( ms ) if err != nil { return nil , errwrap . Wrap ( errors . New ( " " ) , err ) } } if ! p . mutable { return nil , ErrImmutable } return pm , nil }
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 .
155
58
154
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 }
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 .
201
40
155
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 }
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 .
86
39
156
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 }
UnlockManifest unlocks the pod manifest lock .
52
10
157
func getDBVersion ( tx * sql . Tx ) ( int , error ) { var version int rows , err := tx . Query ( " " ) 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 ( " " ) } return version , nil }
getDBVersion retrieves the current db version
126
9
158
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 ( " " ) if err != nil { return err } _ , err = tx . Exec ( " " , version ) if err != nil { return err } return nil }
updateDBVersion updates the db version
84
7
159
func InitACL ( ) ( * ACL , error ) { h , err := getHandle ( ) if err != nil { return nil , err } return & ACL { lib : h } , nil }
InitACL dlopens libacl and returns an ACL object if successful .
42
16
160
func ( a * ACL ) ParseACL ( acl string ) error { acl_from_text , err := getSymbolPointer ( a . lib . handle , " " ) 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 ( " " ) , err ) } a . a = retACL return nil }
ParseACL parses a string representation of an ACL .
134
13
161
func ( a * ACL ) Free ( ) error { acl_free , err := getSymbolPointer ( a . lib . handle , " " ) if err != nil { return err } ret , err := C . my_acl_free ( acl_free , a . a ) if ret < 0 { return errwrap . Wrap ( errors . New ( " " ) , err ) } return a . lib . close ( ) }
Free frees libacl s internal structures and closes libacl .
93
13
162
func ( a * ACL ) SetFileACLDefault ( path string ) error { acl_set_file , err := getSymbolPointer ( a . lib . handle , " " ) 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 ( " " ) , err ) } return nil }
SetFileACLDefault sets the default ACL for path .
135
12
163
func ( a * ACL ) Valid ( ) error { acl_valid , err := getSymbolPointer ( a . lib . handle , " " ) if err != nil { return err } ret , err := C . my_acl_valid ( acl_valid , a . a ) if ret < 0 { return errwrap . Wrap ( errors . New ( " " ) , err ) } return nil }
Valid checks whether the ACL is valid .
87
8
164
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 }
AddBaseEntries adds the base ACL entries from the file permissions .
243
14
165
func NewAppc ( u * url . URL ) ( Distribution , error ) { c , err := parseCIMD ( u ) if err != nil { return nil , fmt . Errorf ( " " , u . String ( ) , err ) } if c . Type != TypeAppc { return nil , fmt . Errorf ( " " , c . Type ) } appcStr := c . Data for n , v := range u . Query ( ) { appcStr += fmt . Sprintf ( " " , n , v [ 0 ] ) } app , err := discovery . NewAppFromString ( appcStr ) if err != nil { return nil , fmt . Errorf ( " " , u . String ( ) , err ) } return NewAppcFromApp ( app ) , nil }
NewAppc returns an Appc distribution from an Appc distribution URI
169
14
166
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 = 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 ( " " , l . Name , url . QueryEscape ( l . Value ) ) } rawuri += strings . Join ( queries , " " ) } u , err := url . Parse ( rawuri ) if err != nil { panic ( fmt . Errorf ( " " , 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 ( " " , version ) } labelsort . By ( labelsort . RankedName ) . Sort ( labels ) for _ , l := range labels { if l . Name != " " { str += fmt . Sprintf ( " " , l . Name , l . Value ) } } return & Appc { cimd : u , app : app . Copy ( ) , str : str , } }
NewAppcFromApp returns an Appc distribution from an appc App discovery string
343
17
167
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 }
CloseOnExec sets or clears FD_CLOEXEC flag on a file descriptor
100
17
168
func GetEnabledControllers ( ) ( [ ] string , error ) { controllersFile , err := os . Open ( " " ) 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 }
GetEnabledControllers returns a list of enabled cgroup controllers
96
12
169
func globGetArgs ( args [ ] string ) globArgs { f , target := standardFlags ( globCmd ) suffix := f . String ( " " , " " , " " ) globbingMode := f . String ( " " , " " , " " ) filelist := f . String ( " " , " " , " " ) var mapTo [ ] string mapToWrapper := common . StringSliceWrapper { Slice : & mapTo } f . Var ( & mapToWrapper , " " , " " ) f . Parse ( args ) if * target == " " { common . Die ( " " ) } mode := globModeFromString ( * globbingMode ) if * filelist == " " { common . Die ( " " ) } if len ( mapTo ) < 1 { common . Die ( " " ) } return globArgs { target : * target , suffix : * suffix , mode : mode , filelist : * filelist , mapTo : mapTo , } }
globGetArgs parses given parameters and returns a target a suffix and a list of files .
213
20
170
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 , " " , dir ) makeWildcards = append ( makeWildcards , str ) } return replacePlaceholders ( globMakeFunction , " " , strings . Join ( makeWildcards , " " ) ) }
globGetMakeFunction returns a make snippet which calls wildcard function in all directories where given files are and with a given suffix .
152
27
171
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 ) }
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 .
227
43
172
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 ) }
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 .
69
32
173
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 }
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 .
109
37
174
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 }
DirSize takes a path and returns its size in bytes
157
11
175
func IsDeviceNode ( path string ) bool { d , err := os . Lstat ( path ) if err == nil { m := d . Mode ( ) return m & os . ModeDevice == os . ModeDevice } return false }
IsDeviceNode checks if the given path points to a block or char device . It doesn t follow symlinks .
49
23
176
func StartCmd ( wdPath , uuid , kernelPath string , nds [ ] kvm . NetDescriber , cpu , mem int64 , debug bool ) [ ] string { machineID := strings . Replace ( uuid , " " , " " , - 1 ) driverConfiguration := hypervisor . KvmHypervisor { Bin : " " , KernelParams : [ ] string { " " , " " , " " + machineID , } , } driverConfiguration . InitKernelParams ( debug ) 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 , " " ) , } return append ( startCmd , kvmNetArgs ( nds ) ... ) }
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
244
37
177
func kvmNetArgs ( nds [ ] kvm . NetDescriber ) [ ] string { var lkvmArgs [ ] string for _ , nd := range nds { lkvmArgs = append ( lkvmArgs , " " ) lkvmArgs = append ( lkvmArgs , fmt . Sprintf ( " " , nd . IfName ( ) , nd . Gateway ( ) , nd . GuestIP ( ) ) , ) } return lkvmArgs }
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
106
45
178
func NewOptionList ( permissibleOptions [ ] string , defaultOptions string ) ( * OptionList , error ) { permissible := make ( map [ string ] struct { } ) ol := & OptionList { allOptions : permissibleOptions , permissible : permissible , typeName : " " , } for _ , o := range permissibleOptions { ol . permissible [ o ] = struct { } { } } if err := ol . Set ( defaultOptions ) ; err != nil { return nil , errwrap . Wrap ( errors . New ( " " ) , err ) } return ol , nil }
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
119
45
179
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 ( " " ) , err ) } defer keyLock . Close ( ) referencedTreeStoreIDs , err := getReferencedTreeStoreIDs ( ) if err != nil { return errwrap . Wrap ( errors . New ( " " ) , err ) } treeStoreIDs , err := ts . GetIDs ( ) if err != nil { return errwrap . Wrap ( errors . New ( " " ) , err ) } for _ , treeStoreID := range treeStoreIDs { if _ , ok := referencedTreeStoreIDs [ treeStoreID ] ; ! ok { if err := ts . Remove ( treeStoreID ) ; err != nil { stderr . PrintE ( fmt . Sprintf ( " " , treeStoreID ) , err ) } else { stderr . Printf ( " " , treeStoreID ) } } } return nil }
gcTreeStore removes all treeStoreIDs not referenced by any non garbage collected pod from the store .
299
20
180
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 }
getRunningImages will return the image IDs used to create any of the currently running pods
200
17
181
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 }
deduplicateMPs removes Mounts with duplicated paths . If there s more than one Mount with the same path it keeps the first one encountered .
97
32
182
func MergeMounts ( mounts [ ] schema . Mount , appMounts [ ] schema . Mount ) [ ] schema . Mount { ml := append ( appMounts , mounts ... ) return deduplicateMPs ( ml ) }
MergeMounts combines the global and per - app mount slices
49
13
183
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 ) } debug ( " " ) if err := prepareStage1Image ( cfg , dir ) ; err != nil { return errwrap . Wrap ( errors . New ( " " ) , 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 ( " " ) fn := common . PodManifestPath ( dir ) if err := ioutil . WriteFile ( fn , pmb , common . DefaultRegularFilePerm ) ; err != nil { return errwrap . Wrap ( errors . New ( " " ) , 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 ( " " ) , 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 ( " " ) , err ) } } return nil }
Prepare sets up a pod based on the given config .
533
12
184
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 ( " " ) , 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 ( " " ) , err ) } } return ensureMtabExists ( filepath . Join ( ad , " " ) ) }
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 .
221
43
185
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 ( " " ) , err ) } treeStoreID , _ , err := cfg . TreeStore . Render ( cfg . Stage1Image . String ( ) , false ) if err != nil { return errwrap . Wrap ( errors . New ( " " ) , err ) } if err := writeManifest ( * cfg . CommonConfig , cfg . Stage1Image , s1 ) ; err != nil { return errwrap . Wrap ( errors . New ( " " ) , err ) } if ! cfg . UseOverlay { destRootfs := filepath . Join ( s1 , " " ) cachedTreePath := cfg . TreeStore . GetRootFS ( treeStoreID ) if err := fileutil . CopyTree ( cachedTreePath , destRootfs , cfg . PrivateUsers ) ; err != nil { return errwrap . Wrap ( errors . New ( " " ) , err ) } } fn := path . Join ( cdir , common . Stage1TreeStoreIDFilename ) if err := ioutil . WriteFile ( fn , [ ] byte ( treeStoreID ) , common . DefaultRegularFilePerm ) ; err != nil { return errwrap . Wrap ( errors . New ( " " ) , err ) } return nil }
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 .
329
35
186
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 ( " " ) , 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 , " " , " " , " " ) if err := os . Chtimes ( statusPath , time . Now ( ) , time . Now ( ) ) ; err != nil { return errwrap . Wrap ( errors . New ( " " ) , err ) } } return nil }
setupStage1Image mounts the overlay filesystem for stage1 . When useOverlay is false it is a noop
227
23
187
func writeManifest ( cfg CommonConfig , img types . Hash , dest string ) error { mb , err := cfg . Store . GetImageManifestJSON ( img . String ( ) ) if err != nil { return err } debug ( " " ) if err := ioutil . WriteFile ( filepath . Join ( dest , " " ) , mb , common . DefaultRegularFilePerm ) ; err != nil { return errwrap . Wrap ( errors . New ( " " ) , err ) } return nil }
writeManifest takes an img ID and writes the corresponding manifest in dest
112
14
188
func copyAppManifest ( cdir string , appName types . ACName , dest string ) error { appInfoDir := common . AppInfoPath ( cdir , appName ) sourceFn := filepath . Join ( appInfoDir , " " ) destFn := filepath . Join ( dest , " " ) if err := fileutil . CopyRegularFile ( sourceFn , destFn ) ; err != nil { return errwrap . Wrap ( errors . New ( " " ) , err ) } return nil }
copyAppManifest copies to saved image manifest for the given appName and writes it in the dest directory .
111
22
189
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 ( " " ) , err ) } if err = overlay . Mount ( mc ) ; err != nil { return errwrap . Wrap ( errors . New ( " " ) , err ) } return nil }
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 .
147
33
190
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 , " " ) if err := os . MkdirAll ( dst , imgMode ) ; err != nil { return nil , err } overlayDir := path . Join ( cdir , " " ) 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 , " " , 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 , " " , 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 }
prepateOverlay sets up the needed directories files and permissions for the overlay - rendered pods
548
18
191
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 } ts . lockDir = filepath . Join ( dir , " " ) if err := os . MkdirAll ( ts . lockDir , 0755 ) ; err != nil { return nil , err } return ts , nil }
NewStore creates a Store for managing filesystem trees including the dependency graph resolution of the underlying image layers .
115
20
192
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 " " + hashToKey ( h ) , nil }
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 .
144
49
193
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 ( " " ) , 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 ( " " ) , err ) } defer treeStoreKeyLock . Close ( ) if ! rebuild { rendered , err := ts . IsRendered ( id ) if err != nil { return " " , " " , errwrap . Wrap ( errors . New ( " " ) , 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 }
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 .
284
69
194
func ( ts * Store ) Check ( id string ) ( string , error ) { treeStoreKeyLock , err := lock . SharedKeyLock ( ts . lockDir , id ) if err != nil { return " " , errwrap . Wrap ( errors . New ( " " ) , err ) } defer treeStoreKeyLock . Close ( ) return ts . check ( id ) }
Check verifies the treestore consistency for the specified id .
79
13
195
func ( ts * Store ) Remove ( id string ) error { treeStoreKeyLock , err := lock . ExclusiveKeyLock ( ts . lockDir , id ) if err != nil { return errwrap . Wrap ( errors . New ( " " ) , err ) } defer treeStoreKeyLock . Close ( ) if err := ts . remove ( id ) ; err != nil { return errwrap . Wrap ( errors . New ( " " ) , err ) } return nil }
Remove removes the rendered image in tree store with the given id .
98
13
196
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 ( " " ) , 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 ( " " ) , err ) } defer f . Close ( ) err = f . Sync ( ) if err != nil { return errwrap . Wrap ( errors . New ( " " ) , 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 }
remove cleans the directory for the provided id
345
8
197
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 }
IsRendered checks if the tree store with the provided id is fully rendered
102
15
198
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 ( " " ) , err ) } hashstring := hashToKey ( hash ) return hashstring , nil }
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 .
108
44
199
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 ( " " ) , err ) } if curhash != string ( hash ) { return " " , fmt . Errorf ( " " , curhash , hash ) } return curhash , nil }
check calculates the actual rendered ACI s hash and verifies that it matches the saved value . Returns the calculated hash .
143
24