idx
int64
0
167k
question
stringlengths
60
3.56k
target
stringlengths
5
1.43k
len_question
int64
21
889
len_target
int64
3
529
0
func getAllDepTypes ( ) [ ] string { depTypes := make ( [ ] string , 0 , len ( cmds ) ) for depType := range cmds { depTypes = append ( depTypes , depType ) } sort . Strings ( depTypes ) return depTypes }
getAllDepTypes returns a sorted list of names of all dep type commands .
60
16
1
func getIoProgressReader ( label string , res * http . Response ) io . Reader { prefix := " " + label fmtBytesSize := 18 barSize := int64 ( 80 - len ( prefix ) - fmtBytesSize ) bar := ioprogress . DrawTextFormatBarForW ( barSize , os . Stderr ) fmtfunc := func ( progress , total int64 ) string { // Content-Length is set to -1 when unknown. if total == - 1 { return fmt . Sprintf ( " " , prefix , ioprogress . ByteUnitStr ( progress ) , ) } return fmt . Sprintf ( " " , prefix , bar ( progress , total ) , ioprogress . DrawTextFormatBytes ( progress , total ) , ) } return & ioprogress . Reader { Reader : res . Body , Size : res . ContentLength , DrawFunc : ioprogress . DrawTerminalf ( os . Stderr , fmtfunc ) , DrawInterval : time . Second , } }
getIoProgressReader returns a reader that wraps the HTTP response body so it prints a pretty progress bar when reading data from it .
217
27
2
func ( f * removeOnClose ) Close ( ) error { if f == nil || f . File == nil { return nil } name := f . File . Name ( ) if err := f . File . Close ( ) ; err != nil { return err } if err := os . Remove ( name ) ; err != nil && ! os . IsNotExist ( err ) { return err } return nil }
Close closes the file and then removes it from disk . No error is returned if the file did not exist at the point of removal .
85
27
3
func getTmpROC ( s * imagestore . Store , path string ) ( * removeOnClose , error ) { h := sha512 . New ( ) h . Write ( [ ] byte ( path ) ) pathHash := s . HashToKey ( h ) tmp , err := s . TmpNamedFile ( pathHash ) if err != nil { return nil , errwrap . Wrap ( errors . New ( " " ) , err ) } // let's lock the file to avoid concurrent writes to the temporary file, it // will go away when removing the temp file _ , err = lock . TryExclusiveLock ( tmp . Name ( ) , lock . RegFile ) if err != nil { if err != lock . ErrLocked { return nil , errwrap . Wrap ( errors . New ( " " ) , err ) } log . Printf ( " " ) _ , err = lock . ExclusiveLock ( tmp . Name ( ) , lock . RegFile ) if err != nil { return nil , errwrap . Wrap ( errors . New ( " " ) , err ) } } return & removeOnClose { File : tmp } , nil }
getTmpROC returns a removeOnClose instance wrapping a temporary file provided by the passed store . The actual file name is based on a hash of the passed path .
243
35
4
func getStage1Entrypoint ( cdir string , entrypoint string ) ( string , error ) { b , err := ioutil . ReadFile ( common . Stage1ManifestPath ( cdir ) ) if err != nil { return " " , errwrap . Wrap ( errors . New ( " " ) , err ) } s1m := schema . ImageManifest { } if err := json . Unmarshal ( b , & s1m ) ; err != nil { return " " , errwrap . Wrap ( errors . New ( " " ) , err ) } if ep , ok := s1m . Annotations . Get ( entrypoint ) ; ok { return ep , nil } return " " , fmt . Errorf ( " " , entrypoint ) }
getStage1Entrypoint retrieves the named entrypoint from the stage1 manifest for a given pod
162
20
5
func getStage1InterfaceVersion ( cdir string ) ( int , error ) { b , err := ioutil . ReadFile ( common . Stage1ManifestPath ( cdir ) ) if err != nil { return - 1 , errwrap . Wrap ( errors . New ( " " ) , err ) } s1m := schema . ImageManifest { } if err := json . Unmarshal ( b , & s1m ) ; err != nil { return - 1 , errwrap . Wrap ( errors . New ( " " ) , err ) } if iv , ok := s1m . Annotations . Get ( interfaceVersion ) ; ok { v , err := strconv . Atoi ( iv ) if err != nil { return - 1 , errwrap . Wrap ( errors . New ( " " ) , err ) } return v , nil } // "interface-version" annotation not found, assume version 1 return 1 , nil }
getStage1InterfaceVersion retrieves the interface version from the stage1 manifest for a given pod
198
19
6
func ( e * podEnv ) loadNets ( ) ( [ ] activeNet , error ) { if e . netsLoadList . None ( ) { stderr . Printf ( " " ) return nil , nil } nets , err := e . newNetLoader ( ) . loadNets ( e . netsLoadList ) if err != nil { return nil , err } netSlice := make ( [ ] activeNet , 0 , len ( nets ) ) for _ , net := range nets { netSlice = append ( netSlice , net ) } sort . Sort ( byFilename ( netSlice ) ) missing := missingNets ( e . netsLoadList , netSlice ) if len ( missing ) > 0 { return nil , fmt . Errorf ( " " , strings . Join ( missing , " " ) ) } // Add the runtime args to the network instances. // We don't do this earlier because we also load networks in other contexts for _ , n := range nets { n . runtime . Args = e . netsLoadList . SpecificArgs ( n . conf . Name ) } return netSlice , nil }
Loads nets specified by user both from a configurable user location and builtin from stage1 . User supplied network configs override what is built into stage1 . The order in which networks are applied to pods will be defined by their filenames .
240
51
7
func prepareApp ( p * stage1commontypes . Pod , ra * schema . RuntimeApp ) ( * preparedApp , error ) { pa := preparedApp { app : ra , env : ra . App . Environment , noNewPrivileges : getAppNoNewPrivileges ( ra . App . Isolators ) , } var err error // Determine numeric uid and gid u , g , err := ParseUserGroup ( p , ra ) if err != nil { return nil , errwrap . Wrap ( errors . New ( " " ) , err ) } if u < 0 || g < 0 { return nil , errors . New ( " " ) } pa . uid = uint32 ( u ) pa . gid = uint32 ( g ) // Set some rkt-provided environment variables pa . env . Set ( " " , ra . Name . String ( ) ) if p . MetadataServiceURL != " " { pa . env . Set ( " " , p . MetadataServiceURL ) } // Determine capability set pa . capabilities , err = getAppCapabilities ( ra . App . Isolators ) if err != nil { return nil , errwrap . Wrap ( errors . New ( " " ) , err ) } // Determine mounts cfd := ConvertedFromDocker ( p . Images [ ra . Name . String ( ) ] ) pa . mounts , err = GenerateMounts ( ra , p . Manifest . Volumes , cfd ) if err != nil { return nil , errwrap . Wrap ( errors . New ( " " ) , err ) } // Compute resources pa . resources , err = computeAppResources ( ra . App . Isolators ) if err != nil { return nil , errwrap . Wrap ( errors . New ( " " ) , err ) } // Protect kernel tunables by default if ! p . InsecureOptions . DisablePaths { pa . roPaths = append ( pa . roPaths , protectKernelROPaths ... ) pa . hiddenPaths = append ( pa . hiddenDirs , protectKernelHiddenPaths ... ) pa . hiddenDirs = append ( pa . hiddenDirs , protectKernelHiddenDirs ... ) } // Seccomp if ! p . InsecureOptions . DisableSeccomp { pa . seccomp , err = generateSeccompFilter ( p , & pa ) if err != nil { return nil , err } if pa . seccomp != nil && pa . seccomp . forceNoNewPrivileges { pa . noNewPrivileges = true } } // Write the systemd-sysusers config file if err := generateSysusers ( p , pa . app , int ( pa . uid ) , int ( pa . gid ) , & p . UidRange ) ; err != nil { return nil , errwrap . Wrapf ( " " , err ) } return & pa , nil }
prepareApp sets up the internal runtime context for a specific app .
617
14
8
func computeAppResources ( isolators types . Isolators ) ( appResources , error ) { res := appResources { } var err error withIsolator := func ( name string , f func ( ) error ) error { ok , err := cgroup . IsIsolatorSupported ( name ) if err != nil { return errwrap . Wrapf ( " " + name , err ) } if ! ok { fmt . Fprintf ( os . Stderr , " \n " , name ) return nil } return f ( ) } for _ , isolator := range isolators { if err != nil { return res , err } switch v := isolator . Value ( ) . ( type ) { case * types . ResourceMemory : err = withIsolator ( " " , func ( ) error { if v . Limit ( ) == nil { return nil } val := uint64 ( v . Limit ( ) . Value ( ) ) res . MemoryLimit = & val return nil } ) case * types . ResourceCPU : err = withIsolator ( " " , func ( ) error { if v . Limit ( ) == nil { return nil } if v . Limit ( ) . Value ( ) > MaxMilliValue { return fmt . Errorf ( " " , v . Limit ( ) . String ( ) ) } val := uint64 ( v . Limit ( ) . MilliValue ( ) / 10 ) res . CPUQuota = & val return nil } ) case * types . LinuxCPUShares : err = withIsolator ( " " , func ( ) error { val := uint64 ( * v ) res . LinuxCPUShares = & val return nil } ) case * types . LinuxOOMScoreAdj : val := int ( * v ) res . LinuxOOMScoreAdjust = & val } } return res , err }
computeAppResources processes any isolators that manipulate cgroups .
385
13
9
func GetACIInfosWithKeyPrefix ( tx * sql . Tx , prefix string ) ( [ ] * ACIInfo , error ) { var aciinfos [ ] * ACIInfo rows , err := tx . Query ( " " , prefix ) if err != nil { return nil , err } defer rows . Close ( ) for rows . Next ( ) { aciinfo := & ACIInfo { } if err := aciinfoRowScan ( rows , aciinfo ) ; err != nil { return nil , err } aciinfos = append ( aciinfos , aciinfo ) } if err := rows . Err ( ) ; err != nil { return nil , err } return aciinfos , err }
GetAciInfosWithKeyPrefix returns all the ACIInfos with a blobkey starting with the given prefix .
157
26
10
func GetACIInfosWithName ( tx * sql . Tx , name string ) ( [ ] * ACIInfo , bool , error ) { var aciinfos [ ] * ACIInfo found := false rows , err := tx . Query ( " " , name ) if err != nil { return nil , false , err } defer rows . Close ( ) for rows . Next ( ) { found = true aciinfo := & ACIInfo { } if err := aciinfoRowScan ( rows , aciinfo ) ; err != nil { return nil , false , err } aciinfos = append ( aciinfos , aciinfo ) } if err := rows . Err ( ) ; err != nil { return nil , false , err } return aciinfos , found , err }
GetAciInfosWithName returns all the ACIInfos for a given name . found will be false if no aciinfo exists .
171
30
11
func GetACIInfoWithBlobKey ( tx * sql . Tx , blobKey string ) ( * ACIInfo , bool , error ) { aciinfo := & ACIInfo { } found := false rows , err := tx . Query ( " " , blobKey ) if err != nil { return nil , false , err } defer rows . Close ( ) for rows . Next ( ) { found = true if err := aciinfoRowScan ( rows , aciinfo ) ; err != nil { return nil , false , err } // No more than one row for blobkey must exist. break } if err := rows . Err ( ) ; err != nil { return nil , false , err } return aciinfo , found , err }
GetAciInfosWithBlobKey returns the ACIInfo with the given blobKey . found will be false if no aciinfo exists .
157
31
12
func GetAllACIInfos ( tx * sql . Tx , sortfields [ ] string , ascending bool ) ( [ ] * ACIInfo , error ) { var aciinfos [ ] * ACIInfo query := " " if len ( sortfields ) > 0 { query += fmt . Sprintf ( " " , strings . Join ( sortfields , " " ) ) if ascending { query += " " } else { query += " " } } rows , err := tx . Query ( query ) if err != nil { return nil , err } defer rows . Close ( ) for rows . Next ( ) { aciinfo := & ACIInfo { } if err := aciinfoRowScan ( rows , aciinfo ) ; err != nil { return nil , err } aciinfos = append ( aciinfos , aciinfo ) } if err := rows . Err ( ) ; err != nil { return nil , err } return aciinfos , err }
GetAllACIInfos returns all the ACIInfos sorted by optional sortfields and with ascending or descending order .
207
25
13
func WriteACIInfo ( tx * sql . Tx , aciinfo * ACIInfo ) error { // ql doesn't have an INSERT OR UPDATE function so // it's faster to remove and reinsert the row _ , err := tx . Exec ( " " , aciinfo . BlobKey ) if err != nil { return err } _ , err = tx . Exec ( " " , aciinfo . BlobKey , aciinfo . Name , aciinfo . ImportTime , aciinfo . LastUsed , aciinfo . Latest , aciinfo . Size , aciinfo . TreeStoreSize ) if err != nil { return err } return nil }
WriteACIInfo adds or updates the provided aciinfo .
144
13
14
func StartCmd ( wdPath , name , kernelPath string , nds [ ] kvm . NetDescriber , cpu , mem int64 , debug bool ) [ ] string { var ( driverConfiguration = hypervisor . KvmHypervisor { Bin : " " , KernelParams : [ ] string { " " , " " , " " , " " , " " , " " , } , } ) driverConfiguration . InitKernelParams ( debug ) cmd := [ ] string { filepath . Join ( wdPath , driverConfiguration . Bin ) , " " , wdPath , " " , " " , " " , " " , " " , strconv . FormatInt ( cpu , 10 ) , " " , strconv . FormatInt ( mem , 10 ) , " " , kernelPath , " " , " " , " " , " " , " " , fmt . Sprintf ( " " , strings . Join ( driverConfiguration . KernelParams , " " ) ) , " " , " " , " " , " " , " " , " " , } return append ( cmd , kvmNetArgs ( nds ) ... ) }
StartCmd takes path to stage1 name of the machine path to kernel network describers memory in megabytes and quantity of cpus and prepares command line to run QEMU process
245
36
15
func kvmNetArgs ( nds [ ] kvm . NetDescriber ) [ ] string { var qemuArgs [ ] string for _ , nd := range nds { qemuArgs = append ( qemuArgs , [ ] string { " " , " " } ... ) qemuNic := fmt . Sprintf ( " " , nd . IfName ( ) ) qemuArgs = append ( qemuArgs , [ ] string { " " , qemuNic } ... ) } return qemuArgs }
kvmNetArgs returns additional arguments that need to be passed to qemu to configure networks properly . Logic is based on network configuration extracted from Networking struct and essentially from activeNets that expose NetDescriber behavior
117
44
16
func ( hv * KvmHypervisor ) InitKernelParams ( isDebug bool ) { hv . KernelParams = append ( hv . KernelParams , [ ] string { " " , " " , " " , " " , " " } ... ) if isDebug { hv . KernelParams = append ( hv . KernelParams , [ ] string { " " , " " , " " , } ... ) } else { hv . KernelParams = append ( hv . KernelParams , [ ] string { " " , " " , " " , " " , " " , } ... ) } customKernelParams := os . Getenv ( " " ) if customKernelParams != " " { hv . KernelParams = append ( hv . KernelParams , customKernelParams ) } }
InitKernelParams sets debug and common parameters passed to the kernel
184
14
17
func ( f * dockerFetcher ) Hash ( u * url . URL ) ( string , error ) { ensureLogger ( f . Debug ) dockerURL , err := d2acommon . ParseDockerURL ( path . Join ( u . Host , u . Path ) ) if err != nil { return " " , fmt . Errorf ( `invalid docker URL %q; expected syntax is "docker://[REGISTRY_HOST[:REGISTRY_PORT]/]IMAGE_NAME[:TAG]"` , u ) } latest := dockerURL . Tag == " " return f . fetchImageFrom ( u , latest ) }
Hash uses docker2aci to download the image and convert it to ACI then stores it in the store and returns the hash .
140
26
18
func registerPod ( root string , uuid * types . UUID , apps schema . AppList ) ( token string , rerr error ) { u := uuid . String ( ) var err error token , err = generateMDSToken ( ) if err != nil { rerr = errwrap . Wrap ( errors . New ( " " ) , err ) return } pmfPath := common . PodManifestPath ( root ) pmf , err := os . Open ( pmfPath ) if err != nil { rerr = errwrap . Wrap ( fmt . Errorf ( " " , pmfPath ) , err ) return } pth := fmt . Sprintf ( " " , u , token ) err = httpRequest ( " " , pth , pmf ) pmf . Close ( ) if err != nil { rerr = errwrap . Wrap ( errors . New ( " " ) , err ) return } defer func ( ) { if rerr != nil { unregisterPod ( root , uuid ) } } ( ) rf , err := os . Create ( filepath . Join ( root , mdsRegisteredFile ) ) if err != nil { rerr = errwrap . Wrap ( errors . New ( " " ) , err ) return } rf . Close ( ) for _ , app := range apps { ampath := common . ImageManifestPath ( root , app . Name ) amf , err := os . Open ( ampath ) if err != nil { rerr = errwrap . Wrap ( fmt . Errorf ( " " , ampath ) , err ) return } err = registerApp ( u , app . Name . String ( ) , amf ) amf . Close ( ) if err != nil { rerr = errwrap . Wrap ( errors . New ( " " ) , err ) return } } return }
registerPod registers pod with metadata service . Returns authentication token to be passed in the URL
386
17
19
func unregisterPod ( root string , uuid * types . UUID ) error { _ , err := os . Stat ( filepath . Join ( root , mdsRegisteredFile ) ) switch { case err == nil : pth := path . Join ( " " , uuid . String ( ) ) return httpRequest ( " " , pth , nil ) case os . IsNotExist ( err ) : return nil default : return err } }
unregisterPod unregisters pod with the metadata service .
94
12
20
func CheckMdsAvailability ( ) error { if conn , err := net . Dial ( " " , common . MetadataServiceRegSock ) ; err != nil { return errUnreachable } else { conn . Close ( ) return nil } }
CheckMdsAvailability checks whether a local metadata service can be reached .
52
14
21
func ( ni * NetInfo ) MergeCNIResult ( result types . Result ) { ni . IP = result . IP4 . IP . IP ni . Mask = net . IP ( result . IP4 . IP . Mask ) ni . HostIP = result . IP4 . Gateway ni . IP4 = result . IP4 ni . DNS = result . DNS }
MergeCNIResult will incorporate the result of a CNI plugin s execution
76
17
22
func Add ( name string , fn commandFn ) Entrypoint { if _ , ok := commands [ name ] ; ok { panic ( fmt . Errorf ( " " , name ) ) } commands [ name ] = fn return Entrypoint ( name ) }
Add adds a new multicall command . name is the command name and fn is the function that will be executed for the specified command . It returns the related Entrypoint . Packages adding new multicall commands should call Add in their init function .
53
49
23
func addStage1ImageFlags ( flags * pflag . FlagSet ) { for _ , data := range stage1FlagsData { wrapper := & stage1ImageLocationFlag { loc : & overriddenStage1Location , kind : data . kind , } flags . Var ( wrapper , data . flag , data . help ) } }
addStage1ImageFlags adds flags for specifying custom stage1 image
68
13
24
func HasChrootCapability ( ) bool { // Checking the capabilities should be enough, but in case there're // problem retrieving them, fallback checking for the effective uid // (hoping it hasn't dropped its CAP_SYS_CHROOT). caps , err := capability . NewPid ( 0 ) if err == nil { return caps . Get ( capability . EFFECTIVE , capability . CAP_SYS_CHROOT ) } else { return os . Geteuid ( ) == 0 } }
HasChrootCapability checks if the current process has the CAP_SYS_CHROOT capability
108
21
25
func LookupGidFromFile ( groupName , groupFile string ) ( gid int , err error ) { groups , err := parseGroupFile ( groupFile ) if err != nil { return - 1 , errwrap . Wrap ( fmt . Errorf ( " " , groupFile ) , err ) } group , ok := groups [ groupName ] if ! ok { return - 1 , fmt . Errorf ( " " , groupName ) } return group . Gid , nil }
LookupGid reads the group file specified by groupFile and returns the gid of the group specified by groupName .
101
25
26
func TryExclusiveKeyLock ( lockDir string , key string ) ( * KeyLock , error ) { return createAndLock ( lockDir , key , keyLockExclusive | keyLockNonBlocking ) }
TryExclusiveLock takes an exclusive lock on the key without blocking . lockDir is the directory where the lock file will be created . It will return ErrLocked if any lock is already held .
44
40
27
func ExclusiveKeyLock ( lockDir string , key string ) ( * KeyLock , error ) { return createAndLock ( lockDir , key , keyLockExclusive ) }
ExclusiveLock takes an exclusive lock on a key . lockDir is the directory where the lock file will be created . It will block if an exclusive lock is already held on the key .
36
38
28
func ( l * KeyLock ) Unlock ( ) error { err := l . keyLock . Unlock ( ) if err != nil { return err } return nil }
Unlock unlocks the key lock .
33
7
29
func CleanKeyLocks ( lockDir string ) error { f , err := os . Open ( lockDir ) if err != nil { return errwrap . Wrap ( errors . New ( " " ) , err ) } defer f . Close ( ) files , err := f . Readdir ( 0 ) if err != nil { return errwrap . Wrap ( errors . New ( " " ) , err ) } for _ , f := range files { filename := filepath . Join ( lockDir , f . Name ( ) ) keyLock , err := TryExclusiveKeyLock ( lockDir , f . Name ( ) ) if err == ErrLocked { continue } if err != nil { return err } err = os . Remove ( filename ) if err != nil { keyLock . Close ( ) return errwrap . Wrap ( errors . New ( " " ) , err ) } keyLock . Close ( ) } return nil }
CleanKeyLocks remove lock files from the lockDir . For every key it tries to take an Exclusive lock on it and skip it if it fails with ErrLocked
192
34
30
func ( m * Manager ) GetPubKeyLocations ( prefix string ) ( [ ] string , error ) { ensureLogger ( m . Debug ) if prefix == " " { return nil , fmt . Errorf ( " " ) } kls , err := m . metaDiscoverPubKeyLocations ( prefix ) if err != nil { return nil , errwrap . Wrap ( errors . New ( " " ) , err ) } if len ( kls ) == 0 { return nil , fmt . Errorf ( " " , prefix ) } return kls , nil }
GetPubKeyLocations discovers locations at prefix
118
9
31
func ( m * Manager ) AddKeys ( pkls [ ] string , prefix string , accept AcceptOption ) error { ensureLogger ( m . Debug ) if m . Ks == nil { return fmt . Errorf ( " " ) } for _ , pkl := range pkls { u , err := url . Parse ( pkl ) if err != nil { return err } pk , err := m . getPubKey ( u ) if err != nil { return errwrap . Wrap ( fmt . Errorf ( " " , pkl ) , err ) } defer pk . Close ( ) err = displayKey ( prefix , pkl , pk ) if err != nil { return errwrap . Wrap ( fmt . Errorf ( " " , pkl ) , err ) } if m . TrustKeysFromHTTPS && u . Scheme == " " { accept = AcceptForce } if accept == AcceptAsk { if ! terminal . IsTerminal ( int ( os . Stdin . Fd ( ) ) ) || ! terminal . IsTerminal ( int ( os . Stderr . Fd ( ) ) ) { log . Printf ( " " , prefix ) log . Printf ( " " ) log . Printf ( " " , prefix ) return fmt . Errorf ( " " ) } accepted , err := reviewKey ( ) if err != nil { return errwrap . Wrap ( errors . New ( " " ) , err ) } if ! accepted { log . Printf ( " " , pkl ) continue } } if accept == AcceptForce { stdout . Printf ( " " , pkl , prefix ) } else { stdout . Printf ( " " , pkl , prefix ) } if prefix == " " { path , err := m . Ks . StoreTrustedKeyRoot ( pk ) if err != nil { return errwrap . Wrap ( errors . New ( " " ) , err ) } stdout . Printf ( " " , path ) } else { path , err := m . Ks . StoreTrustedKeyPrefix ( prefix , pk ) if err != nil { return errwrap . Wrap ( fmt . Errorf ( " " , prefix ) , err ) } stdout . Printf ( " " , prefix , path ) } } return nil }
AddKeys adds the keys listed in pkls at prefix
486
12
32
func ( m * Manager ) metaDiscoverPubKeyLocations ( prefix string ) ( [ ] string , error ) { app , err := discovery . NewAppFromString ( prefix ) if err != nil { return nil , err } hostHeaders := config . ResolveAuthPerHost ( m . AuthPerHost ) insecure := discovery . InsecureNone if m . InsecureAllowHTTP { insecure = insecure | discovery . InsecureHTTP } if m . InsecureSkipTLSCheck { insecure = insecure | discovery . InsecureTLS } keys , attempts , err := discovery . DiscoverPublicKeys ( * app , hostHeaders , insecure , 0 ) if err != nil && m . Debug { for _ , a := range attempts { log . PrintE ( fmt . Sprintf ( " " , a . Prefix ) , a . Error ) } } return keys , err }
metaDiscoverPubKeyLocations discovers the locations of public keys through ACDiscovery by applying prefix as an ACApp
182
23
33
func downloadKey ( u * url . URL , skipTLSCheck bool ) ( * os . File , error ) { tf , err := ioutil . TempFile ( " " , " " ) if err != nil { return nil , errwrap . Wrap ( errors . New ( " " ) , err ) } os . Remove ( tf . Name ( ) ) // no need to keep the tempfile around defer func ( ) { if tf != nil { tf . Close ( ) } } ( ) // TODO(krnowak): we should probably apply credential headers // from config here var client * http . Client if skipTLSCheck { client = insecureClient } else { client = secureClient } res , err := client . Get ( u . String ( ) ) if err != nil { return nil , errwrap . Wrap ( errors . New ( " " ) , err ) } defer res . Body . Close ( ) if res . StatusCode != http . StatusOK { return nil , fmt . Errorf ( " " , res . StatusCode ) } if _ , err := io . Copy ( tf , res . Body ) ; err != nil { return nil , errwrap . Wrap ( errors . New ( " " ) , err ) } if _ , err = tf . Seek ( 0 , os . SEEK_SET ) ; err != nil { return nil , errwrap . Wrap ( errors . New ( " " ) , err ) } retTf := tf tf = nil return retTf , nil }
downloadKey retrieves the file storing it in a deleted tempfile
318
13
34
func displayKey ( prefix , location string , key * os . File ) error { defer key . Seek ( 0 , os . SEEK_SET ) kr , err := openpgp . ReadArmoredKeyRing ( key ) if err != nil { return errwrap . Wrap ( errors . New ( " " ) , err ) } log . Printf ( " \n " , prefix , location ) for _ , k := range kr { stdout . Printf ( " " , fingerToString ( k . PrimaryKey . Fingerprint ) ) for _ , sk := range k . Subkeys { stdout . Printf ( " " , fingerToString ( sk . PublicKey . Fingerprint ) ) } for n := range k . Identities { stdout . Printf ( " \t " , n ) } } return nil }
displayKey shows the key summary
176
6
35
func reviewKey ( ) ( bool , error ) { in := bufio . NewReader ( os . Stdin ) for { stdout . Printf ( " " ) input , err := in . ReadString ( '\n' ) if err != nil { return false , errwrap . Wrap ( errors . New ( " " ) , err ) } switch input { case " \n " : return true , nil case " \n " : return false , nil default : stdout . Printf ( " " ) } } }
reviewKey asks the user to accept the key
110
9
36
func setupTapDevice ( podID types . UUID ) ( netlink . Link , error ) { // network device names are limited to 16 characters // the suffix %d will be replaced by the kernel with a suitable number nameTemplate := fmt . Sprintf ( " " , podID . String ( ) [ 0 : 4 ] ) ifName , err := tuntap . CreatePersistentIface ( nameTemplate , tuntap . Tap ) if err != nil { return nil , errwrap . Wrap ( errors . New ( " " ) , err ) } link , err := netlink . LinkByName ( ifName ) if err != nil { return nil , errwrap . Wrap ( fmt . Errorf ( " " , ifName ) , err ) } if err := netlink . LinkSetUp ( link ) ; err != nil { return nil , errwrap . Wrap ( fmt . Errorf ( " " , ifName ) , err ) } return link , nil }
setupTapDevice creates persistent tap device and returns a newly created netlink . Link structure
203
17
37
func setupMacVTapDevice ( podID types . UUID , config MacVTapNetConf , interfaceNumber int ) ( netlink . Link , error ) { master , err := netlink . LinkByName ( config . Master ) if err != nil { return nil , errwrap . Wrap ( fmt . Errorf ( " " , config . Master ) , err ) } var mode netlink . MacvlanMode switch config . Mode { // if not set - defaults to bridge mode as in: // https://github.com/rkt/rkt/blob/master/Documentation/networking.md#macvlan case " " , " " : mode = netlink . MACVLAN_MODE_BRIDGE case " " : mode = netlink . MACVLAN_MODE_PRIVATE case " " : mode = netlink . MACVLAN_MODE_VEPA case " " : mode = netlink . MACVLAN_MODE_PASSTHRU default : return nil , fmt . Errorf ( " " , config . Mode ) } mtu := master . Attrs ( ) . MTU if config . MTU != 0 { mtu = config . MTU } interfaceName := fmt . Sprintf ( " " , podID . String ( ) [ 0 : 4 ] , interfaceNumber ) link := & netlink . Macvtap { Macvlan : netlink . Macvlan { LinkAttrs : netlink . LinkAttrs { Name : interfaceName , MTU : mtu , ParentIndex : master . Attrs ( ) . Index , } , Mode : mode , } , } if err := netlink . LinkAdd ( link ) ; err != nil { return nil , errwrap . Wrap ( errors . New ( " " ) , err ) } // TODO: duplicate following lines for ipv6 support, when it will be added in other places ipv4SysctlValueName := fmt . Sprintf ( IPv4InterfaceArpProxySysctlTemplate , interfaceName ) if _ , err := cnisysctl . Sysctl ( ipv4SysctlValueName , " " ) ; err != nil { // remove the newly added link and ignore errors, because we already are in a failed state _ = netlink . LinkDel ( link ) return nil , errwrap . Wrap ( fmt . Errorf ( " " , interfaceName ) , err ) } if err := netlink . LinkSetUp ( link ) ; err != nil { // remove the newly added link and ignore errors, because we already are in a failed state _ = netlink . LinkDel ( link ) return nil , errwrap . Wrap ( errors . New ( " " ) , err ) } return link , nil }
setupTapDevice creates persistent macvtap device and returns a newly created netlink . Link structure using part of pod hash and interface number in interface name
577
30
38
func ( n * Networking ) kvmTeardown ( ) { if err := n . teardownForwarding ( ) ; err != nil { stderr . PrintE ( " " , err ) } n . teardownKvmNets ( ) }
kvmTeardown network teardown for kvm flavor based pods similar to Networking . Teardown but without host namespaces
57
28
39
func ( f * fileFetcher ) Hash ( aciPath string , a * asc ) ( string , error ) { ensureLogger ( f . Debug ) absPath , err := filepath . Abs ( aciPath ) if err != nil { return " " , errwrap . Wrap ( fmt . Errorf ( " " , aciPath ) , err ) } aciPath = absPath aciFile , err := f . getFile ( aciPath , a ) if err != nil { return " " , err } defer aciFile . Close ( ) key , err := f . S . WriteACI ( aciFile , imagestore . ACIFetchInfo { Latest : false , } ) if err != nil { return " " , err } return key , nil }
Hash opens a file optionally verifies it against passed asc stores it in the store and returns the hash .
167
21
40
func ( f * fileFetcher ) getVerifiedFile ( aciPath string , a * asc ) ( * os . File , error ) { var aciFile * os . File // closed on error var errClose error // error signaling to close aciFile f . maybeOverrideAsc ( aciPath , a ) ascFile , err := a . Get ( ) if err != nil { return nil , errwrap . Wrap ( errors . New ( " " ) , err ) } defer ascFile . Close ( ) aciFile , err = os . Open ( aciPath ) if err != nil { return nil , errwrap . Wrap ( errors . New ( " " ) , err ) } defer func ( ) { if errClose != nil { aciFile . Close ( ) } } ( ) validator , errClose := newValidator ( aciFile ) if errClose != nil { return nil , errClose } entity , errClose := validator . ValidateWithSignature ( f . Ks , ascFile ) if errClose != nil { return nil , errwrap . Wrap ( fmt . Errorf ( " " , validator . ImageName ( ) ) , errClose ) } printIdentities ( entity ) return aciFile , nil }
fetch opens and verifies the ACI .
266
10
41
func NewLoggingMounter ( m Mounter , um Unmounter , logf func ( string , ... interface { } ) ) MountUnmounter { return & loggingMounter { m , um , logf } }
NewLoggingMounter returns a MountUnmounter that logs mount events using the given logger func .
47
21
42
func Extend ( description string ) error { connection := tpmclient . New ( " " , timeout ) err := connection . Extend ( 15 , 0x1000 , nil , description ) return err }
Extend extends the TPM log with the provided string . Returns any error .
40
16
43
func Stage1RootfsPath ( root string ) string { return filepath . Join ( Stage1ImagePath ( root ) , aci . RootfsDir ) }
Stage1RootfsPath returns the path to the stage1 rootfs
34
14
44
func Stage1ManifestPath ( root string ) string { return filepath . Join ( Stage1ImagePath ( root ) , aci . ManifestFile ) }
Stage1ManifestPath returns the path to the stage1 s manifest file inside the expanded ACI .
33
21
45
func AppStatusPath ( root , appName string ) string { return filepath . Join ( AppsStatusesPath ( root ) , appName ) }
AppStatusPath returns the path of the status file of an app .
31
14
46
func AppStatusPathFromStage1Rootfs ( rootfs , appName string ) string { return filepath . Join ( AppsStatusesPathFromStage1Rootfs ( rootfs ) , appName ) }
AppStatusPathFromStage1Rootfs returns the path of the status file of an app . It receives the stage1 rootfs as parameter instead of the pod root .
43
34
47
func AppPath ( root string , appName types . ACName ) string { return filepath . Join ( AppsPath ( root ) , appName . String ( ) ) }
AppPath returns the path to an app s rootfs .
36
12
48
func AppRootfsPath ( root string , appName types . ACName ) string { return filepath . Join ( AppPath ( root , appName ) , aci . RootfsDir ) }
AppRootfsPath returns the path to an app s rootfs .
41
14
49
func RelAppPath ( appName types . ACName ) string { return filepath . Join ( stage2Dir , appName . String ( ) ) }
RelAppPath returns the path of an app relative to the stage1 chroot .
32
17
50
func RelAppRootfsPath ( appName types . ACName ) string { return filepath . Join ( RelAppPath ( appName ) , aci . RootfsDir ) }
RelAppRootfsPath returns the path of an app s rootfs relative to the stage1 chroot .
38
22
51
func ImageManifestPath ( root string , appName types . ACName ) string { return filepath . Join ( AppPath ( root , appName ) , aci . ManifestFile ) }
ImageManifestPath returns the path to the app s manifest file of a pod .
40
17
52
func AppInfoPath ( root string , appName types . ACName ) string { return filepath . Join ( AppsInfoPath ( root ) , appName . String ( ) ) }
AppInfoPath returns the path to the app s appsinfo directory of a pod .
38
17
53
func AppTreeStoreIDPath ( root string , appName types . ACName ) string { return filepath . Join ( AppInfoPath ( root , appName ) , AppTreeStoreIDFilename ) }
AppTreeStoreIDPath returns the path to the app s treeStoreID file of a pod .
42
20
54
func AppImageManifestPath ( root string , appName types . ACName ) string { return filepath . Join ( AppInfoPath ( root , appName ) , aci . ManifestFile ) }
AppImageManifestPath returns the path to the app s ImageManifest file
42
16
55
func CreateSharedVolumesPath ( root string ) ( string , error ) { sharedVolPath := SharedVolumesPath ( root ) if err := os . MkdirAll ( sharedVolPath , SharedVolumePerm ) ; err != nil { return " " , errwrap . Wrap ( errors . New ( " " ) , err ) } // In case it already existed and we didn't make it, ensure permissions are // what the caller expects them to be. if err := os . Chmod ( sharedVolPath , SharedVolumePerm ) ; err != nil { return " " , errwrap . Wrap ( fmt . Errorf ( " " , sharedVolPath ) , err ) } return sharedVolPath , nil }
CreateSharedVolumesPath ensures the sharedVolumePath for the pod root passed in exists . It returns the shared volume path or an error .
150
29
56
func MetadataServicePublicURL ( ip net . IP , token string ) string { return fmt . Sprintf ( " " , ip , MetadataServicePort , token ) }
MetadataServicePublicURL returns the public URL used to host the metadata service
36
15
57
func LookupPath ( bin string , paths string ) ( string , error ) { pathsArr := filepath . SplitList ( paths ) for _ , path := range pathsArr { binPath := filepath . Join ( path , bin ) binAbsPath , err := filepath . Abs ( binPath ) if err != nil { return " " , fmt . Errorf ( " " , binPath ) } if fileutil . IsExecutable ( binAbsPath ) { return binAbsPath , nil } } return " " , fmt . Errorf ( " " , bin , paths ) }
LookupPath search for bin in paths . If found it returns its absolute path if not an error
124
20
58
func SystemdVersion ( systemdBinaryPath string ) ( int , error ) { versionBytes , err := exec . Command ( systemdBinaryPath , " " ) . CombinedOutput ( ) if err != nil { return - 1 , errwrap . Wrap ( fmt . Errorf ( " " , systemdBinaryPath ) , err ) } versionStr := strings . SplitN ( string ( versionBytes ) , " \n " , 2 ) [ 0 ] var version int n , err := fmt . Sscanf ( versionStr , " " , & version ) if err != nil || n != 1 { return - 1 , fmt . Errorf ( " " , versionStr ) } return version , nil }
SystemdVersion parses and returns the version of a given systemd binary
146
14
59
func SupportsOverlay ( ) error { // ignore exec.Command error, modprobe may not be present on the system, // or the kernel module will fail to load. // we'll find out by reading the side effect in /proc/filesystems _ = exec . Command ( " " , " " ) . Run ( ) f , err := os . Open ( " " ) if err != nil { // don't use errwrap so consumers can type-check on ErrOverlayUnsupported return ErrOverlayUnsupported ( fmt . Sprintf ( " " , err ) ) } defer f . Close ( ) s := bufio . NewScanner ( f ) for s . Scan ( ) { if s . Text ( ) == " \t " { return nil } } return ErrOverlayUnsupported ( " " ) }
SupportsOverlay returns whether the operating system generally supports OverlayFS returning an instance of ErrOverlayUnsupported which encodes the reason . It is sufficient to check for nil if the reason is not of interest .
173
44
60
func RemoveEmptyLines ( str string ) [ ] string { lines := make ( [ ] string , 0 ) for _ , v := range strings . Split ( str , " \n " ) { if len ( v ) > 0 { lines = append ( lines , v ) } } return lines }
RemoveEmptyLines removes empty lines from the given string and breaks it up into a list of strings at newline characters
62
24
61
func GetExitStatus ( err error ) ( int , error ) { if err == nil { return 0 , nil } if exiterr , ok := err . ( * exec . ExitError ) ; ok { // the program has exited with an exit code != 0 if status , ok := exiterr . Sys ( ) . ( syscall . WaitStatus ) ; ok { return status . ExitStatus ( ) , nil } } return - 1 , err }
GetExitStatus converts an error to an exit status . If it wasn t an exit status ! = 0 it returns the same error that it was called with
96
31
62
func ImageNameToAppName ( name types . ACIdentifier ) ( * types . ACName , error ) { parts := strings . Split ( name . String ( ) , " " ) last := parts [ len ( parts ) - 1 ] sn , err := types . SanitizeACName ( last ) if err != nil { return nil , err } return types . MustACName ( sn ) , nil }
ImageNameToAppName converts the full name of image to an app name without special characters - we use it as a default app name when specyfing it is optional
86
34
63
func GetNetworkDescriptions ( n * networking . Networking ) [ ] NetDescriber { var nds [ ] NetDescriber for _ , an := range n . GetActiveNetworks ( ) { nds = append ( nds , an ) } return nds }
GetNetworkDescriptions converts activeNets to netDescribers
58
14
64
func GetKVMNetArgs ( nds [ ] NetDescriber ) ( [ ] string , error ) { var lkvmArgs [ ] string for _ , nd := range nds { lkvmArgs = append ( lkvmArgs , " " ) lkvmArg := fmt . Sprintf ( " " , nd . IfName ( ) , nd . Gateway ( ) , nd . GuestIP ( ) ) lkvmArgs = append ( lkvmArgs , lkvmArg ) } return lkvmArgs , nil }
GetKVMNetArgs returns additional arguments that need to be passed to lkvm tool to configure networks properly . Logic is based on Network configuration extracted from Networking struct and essentially from activeNets that expose netDescriber behavior
118
46
65
func generateMacAddress ( ) ( net . HardwareAddr , error ) { mac := [ ] byte { 2 , // locally administered unicast 0x65 , 0x02 , // OUI (randomly chosen by jell) 0 , 0 , 0 , // bytes to randomly overwrite } _ , err := rand . Read ( mac [ 3 : 6 ] ) if err != nil { return nil , errwrap . Wrap ( errors . New ( " " ) , err ) } return mac , nil }
generateMacAddress returns net . HardwareAddr filled with fixed 3 byte prefix complemented by 3 random bytes .
104
23
66
func replacePlaceholders ( str string , kv ... string ) string { for ph , value := range toMap ( kv ... ) { str = strings . Replace ( str , " " + ph + " " , value , - 1 ) } return str }
replacePlaceholders replaces placeholders with values in kv in initial str . Placeholders are in form of !!!FOO!!! but those passed here should be without exclamation marks .
54
37
67
func standardFlags ( cmd string ) ( * flag . FlagSet , * string ) { f := flag . NewFlagSet ( appName ( ) + " " + cmd , flag . ExitOnError ) target := f . String ( " " , " " , " " ) return f , target }
standardFlags returns a new flag set with target flag already set up
62
13
68
func ( e * podEnv ) netPluginAdd ( n * activeNet , netns string ) error { output , err := e . execNetPlugin ( " " , n , netns ) if err != nil { return pluginErr ( err , output ) } pr := cnitypes . Result { } if err = json . Unmarshal ( output , & pr ) ; err != nil { err = errwrap . Wrap ( fmt . Errorf ( " " , string ( output ) ) , err ) return errwrap . Wrap ( fmt . Errorf ( " " , n . conf . Name ) , err ) } if pr . IP4 == nil { return nil // TODO(casey) should this be an error? } // All is well - mutate the runtime n . runtime . MergeCNIResult ( pr ) return nil }
Executes a given network plugin . If successful mutates n . runtime with the runtime information
181
18
69
func copyPod ( pod * v1alpha . Pod ) * v1alpha . Pod { p := & v1alpha . Pod { Id : pod . Id , Manifest : pod . Manifest , Annotations : pod . Annotations , } for _ , app := range pod . Apps { p . Apps = append ( p . Apps , & v1alpha . App { Name : app . Name , Image : app . Image , Annotations : app . Annotations , } ) } return p }
copyPod copies the immutable information of the pod into the new pod .
98
14
70
func copyImage ( img * v1alpha . Image ) * v1alpha . Image { return & v1alpha . Image { BaseFormat : img . BaseFormat , Id : img . Id , Name : img . Name , Version : img . Version , ImportTimestamp : img . ImportTimestamp , Manifest : img . Manifest , Size : img . Size , Annotations : img . Annotations , Labels : img . Labels , } }
copyImage copies the image object to avoid modification on the original one .
91
14
71
func ( s * v1AlphaAPIServer ) GetInfo ( context . Context , * v1alpha . GetInfoRequest ) ( * v1alpha . GetInfoResponse , error ) { return & v1alpha . GetInfoResponse { Info : & v1alpha . Info { RktVersion : version . Version , AppcVersion : schema . AppContainerVersion . String ( ) , ApiVersion : supportedAPIVersion , GlobalFlags : & v1alpha . GlobalFlags { Dir : getDataDir ( ) , SystemConfigDir : globalFlags . SystemConfigDir , LocalConfigDir : globalFlags . LocalConfigDir , UserConfigDir : globalFlags . UserConfigDir , InsecureFlags : globalFlags . InsecureFlags . String ( ) , TrustKeysFromHttps : globalFlags . TrustKeysFromHTTPS , } , } , } , nil }
GetInfo returns the information about the rkt appc api server version .
181
15
72
func containsAllKeyValues ( actualKVs [ ] * v1alpha . KeyValue , requiredKVs [ ] * v1alpha . KeyValue ) bool { for _ , requiredKV := range requiredKVs { actualValue , ok := findInKeyValues ( actualKVs , requiredKV . Key ) if ! ok || actualValue != requiredKV . Value { return false } } return true }
containsAllKeyValues returns true if the actualKVs contains all of the key - value pairs listed in requiredKVs otherwise it returns false .
86
30
73
func satisfiesPodFilter ( pod v1alpha . Pod , filter v1alpha . PodFilter ) bool { // Filter according to the ID. if len ( filter . Ids ) > 0 { s := set . NewString ( filter . Ids ... ) if ! s . Has ( pod . Id ) { return false } } // Filter according to the state. if len ( filter . States ) > 0 { foundState := false for _ , state := range filter . States { if pod . State == state { foundState = true break } } if ! foundState { return false } } // Filter according to the app names. if len ( filter . AppNames ) > 0 { s := set . NewString ( ) for _ , app := range pod . Apps { s . Insert ( app . Name ) } if ! s . HasAll ( filter . AppNames ... ) { return false } } // Filter according to the image IDs. if len ( filter . ImageIds ) > 0 { s := set . NewString ( ) for _ , app := range pod . Apps { s . Insert ( app . Image . Id ) } if ! s . HasAll ( filter . ImageIds ... ) { return false } } // Filter according to the network names. if len ( filter . NetworkNames ) > 0 { s := set . NewString ( ) for _ , network := range pod . Networks { s . Insert ( network . Name ) } if ! s . HasAll ( filter . NetworkNames ... ) { return false } } // Filter according to the annotations. if len ( filter . Annotations ) > 0 { if ! containsAllKeyValues ( pod . Annotations , filter . Annotations ) { return false } } // Filter according to the cgroup. if len ( filter . Cgroups ) > 0 { s := set . NewString ( filter . Cgroups ... ) if ! s . Has ( pod . Cgroup ) { return false } } // Filter if pod's cgroup is a prefix of the passed in cgroup if len ( filter . PodSubCgroups ) > 0 { matched := false if pod . Cgroup != " " { for _ , cgroup := range filter . PodSubCgroups { if strings . HasPrefix ( cgroup , pod . Cgroup ) { matched = true break } } } if ! matched { return false } } return true }
satisfiesPodFilter returns true if the pod satisfies the filter . The pod filter must not be nil .
492
22
74
func satisfiesAnyPodFilters ( pod * v1alpha . Pod , filters [ ] * v1alpha . PodFilter ) bool { // No filters, return true directly. if len ( filters ) == 0 { return true } for _ , filter := range filters { if satisfiesPodFilter ( * pod , * filter ) { return true } } return false }
satisfiesAnyPodFilters returns true if any of the filter conditions is satisfied by the pod or there s no filters .
74
26
75
func getApplist ( manifest * schema . PodManifest ) [ ] * v1alpha . App { var apps [ ] * v1alpha . App for _ , app := range manifest . Apps { img := & v1alpha . Image { BaseFormat : & v1alpha . ImageFormat { // Only support appc image now. If it's a docker image, then it // will be transformed to appc before storing in the disk store. Type : v1alpha . ImageType_IMAGE_TYPE_APPC , Version : schema . AppContainerVersion . String ( ) , } , Id : app . Image . ID . String ( ) , // Only image format and image ID are returned in 'ListPods()'. } apps = append ( apps , & v1alpha . App { Name : app . Name . String ( ) , Image : img , Annotations : convertAnnotationsToKeyValue ( app . Annotations ) , State : v1alpha . AppState_APP_STATE_UNDEFINED , ExitCode : - 1 , } ) } return apps }
getApplist returns a list of apps in the pod .
224
12
76
func getNetworks ( p * pkgPod . Pod ) [ ] * v1alpha . Network { var networks [ ] * v1alpha . Network for _ , n := range p . Nets { networks = append ( networks , & v1alpha . Network { Name : n . NetName , // There will be IPv6 support soon so distinguish between v4 and v6 Ipv4 : n . IP . String ( ) , } ) } return networks }
getNetworks returns the list of the info of the network that the pod belongs to .
97
18
77
func fillStaticAppInfo ( store * imagestore . Store , pod * pkgPod . Pod , v1pod * v1alpha . Pod ) error { var errlist [ ] error // Fill static app image info. for _ , app := range v1pod . Apps { // Fill app's image info. app . Image = & v1alpha . Image { BaseFormat : & v1alpha . ImageFormat { // Only support appc image now. If it's a docker image, then it // will be transformed to appc before storing in the disk store. Type : v1alpha . ImageType_IMAGE_TYPE_APPC , Version : schema . AppContainerVersion . String ( ) , } , Id : app . Image . Id , // Other information are not available because they require the image // info from store. Some of it is filled in below if possible. } im , err := pod . AppImageManifest ( app . Name ) if err != nil { stderr . PrintE ( fmt . Sprintf ( " " , app . Name ) , err ) errlist = append ( errlist , err ) } else { app . Image . Name = im . Name . String ( ) version , ok := im . Labels . Get ( " " ) if ! ok { version = " " } app . Image . Version = version } } if len ( errlist ) != 0 { return errs { errlist } } return nil }
fillStaticAppInfo will modify the v1pod in place with the information retrieved with pod . Today these information are static and will not change during the pod s lifecycle .
305
35
78
func ( s * v1AlphaAPIServer ) getBasicPod ( p * pkgPod . Pod ) * v1alpha . Pod { mtime , mtimeErr := getPodManifestModTime ( p ) if mtimeErr != nil { stderr . PrintE ( fmt . Sprintf ( " " , p . UUID ) , mtimeErr ) } // Couldn't use pod.uuid directly as it's a pointer. itemValue , found := s . podCache . Get ( p . UUID . String ( ) ) if found && mtimeErr == nil { cacheItem := itemValue . ( * podCacheItem ) // Check the mtime to make sure we are not returning stale manifests. if ! mtime . After ( cacheItem . mtime ) { return copyPod ( cacheItem . pod ) } } pod , err := s . getBasicPodFromDisk ( p ) if mtimeErr != nil || err != nil { // If any error happens or the mtime is unknown, // returns the raw pod directly without adding it to the cache. return pod } cacheItem := & podCacheItem { pod , mtime } s . podCache . Add ( p . UUID . String ( ) , cacheItem ) // Return a copy of the pod, so the cached pod is not mutated later. return copyPod ( cacheItem . pod ) }
getBasicPod returns v1alpha . Pod with basic pod information .
294
14
79
func aciInfoToV1AlphaAPIImage ( store * imagestore . Store , aciInfo * imagestore . ACIInfo ) ( * v1alpha . Image , error ) { manifest , err := store . GetImageManifestJSON ( aciInfo . BlobKey ) if err != nil { stderr . PrintE ( " " , err ) return nil , err } var im schema . ImageManifest if err = json . Unmarshal ( manifest , & im ) ; err != nil { stderr . PrintE ( " " , err ) return nil , err } version , ok := im . Labels . Get ( " " ) if ! ok { version = " " } return & v1alpha . Image { BaseFormat : & v1alpha . ImageFormat { // Only support appc image now. If it's a docker image, then it // will be transformed to appc before storing in the disk store. Type : v1alpha . ImageType_IMAGE_TYPE_APPC , Version : schema . AppContainerVersion . String ( ) , } , Id : aciInfo . BlobKey , Name : im . Name . String ( ) , Version : version , ImportTimestamp : aciInfo . ImportTime . Unix ( ) , Manifest : manifest , Size : aciInfo . Size + aciInfo . TreeStoreSize , Annotations : convertAnnotationsToKeyValue ( im . Annotations ) , Labels : convertLabelsToKeyValue ( im . Labels ) , } , nil }
aciInfoToV1AlphaAPIImage takes an aciInfo object and construct the v1alpha . Image object .
325
24
80
func satisfiesImageFilter ( image v1alpha . Image , filter v1alpha . ImageFilter ) bool { // Filter according to the IDs. if len ( filter . Ids ) > 0 { s := set . NewString ( filter . Ids ... ) if ! s . Has ( image . Id ) { return false } } // Filter according to the image full names. if len ( filter . FullNames ) > 0 { s := set . NewString ( filter . FullNames ... ) if ! s . Has ( image . Name ) { return false } } // Filter according to the image name prefixes. if len ( filter . Prefixes ) > 0 { s := set . NewString ( filter . Prefixes ... ) if ! s . ConditionalHas ( isPrefixOf , image . Name ) { return false } } // Filter according to the image base name. if len ( filter . BaseNames ) > 0 { s := set . NewString ( filter . BaseNames ... ) if ! s . ConditionalHas ( isBaseNameOf , image . Name ) { return false } } // Filter according to the image keywords. if len ( filter . Keywords ) > 0 { s := set . NewString ( filter . Keywords ... ) if ! s . ConditionalHas ( isPartOf , image . Name ) { return false } } // Filter according to the imported time. if filter . ImportedAfter > 0 { if image . ImportTimestamp <= filter . ImportedAfter { return false } } if filter . ImportedBefore > 0 { if image . ImportTimestamp >= filter . ImportedBefore { return false } } // Filter according to the image labels. if len ( filter . Labels ) > 0 { if ! containsAllKeyValues ( image . Labels , filter . Labels ) { return false } } // Filter according to the annotations. if len ( filter . Annotations ) > 0 { if ! containsAllKeyValues ( image . Annotations , filter . Annotations ) { return false } } return true }
satisfiesImageFilter returns true if the image satisfies the filter . The image filter must not be nil .
421
22
81
func satisfiesAnyImageFilters ( image * v1alpha . Image , filters [ ] * v1alpha . ImageFilter ) bool { // No filters, return true directly. if len ( filters ) == 0 { return true } for _ , filter := range filters { if satisfiesImageFilter ( * image , * filter ) { return true } } return false }
satisfiesAnyImageFilters returns true if any of the filter conditions is satisfied by the image or there s no filters .
74
26
82
func runAPIService ( cmd * cobra . Command , args [ ] string ) ( exit int ) { // Set up the signal handler here so we can make sure the // signals are caught after print the starting message. signal . Notify ( exitCh , syscall . SIGINT , syscall . SIGTERM ) stderr . Print ( " " ) listeners , err := openAPISockets ( ) if err != nil { stderr . PrintE ( " " , err ) return 254 } if len ( listeners ) == 0 { // This is unlikely... stderr . Println ( " " ) return 254 } publicServer := grpc . NewServer ( ) // TODO(yifan): Add TLS credential option. v1AlphaAPIServer , err := newV1AlphaAPIServer ( ) if err != nil { stderr . PrintE ( " " , err ) return 254 } v1alpha . RegisterPublicAPIServer ( publicServer , v1AlphaAPIServer ) for _ , l := range listeners { defer l . Close ( ) go publicServer . Serve ( l ) } stderr . Printf ( " " ) <- exitCh stderr . Print ( " " ) return }
Open one or more listening sockets then start the gRPC server
263
13
83
func ( uw * UnitWriter ) WriteUnit ( path string , errmsg string , opts ... * unit . UnitOption ) { if uw . err != nil { return } file , err := os . OpenFile ( path , os . O_WRONLY | os . O_CREATE | os . O_TRUNC , 0644 ) if err != nil { uw . err = errwrap . Wrap ( errors . New ( errmsg ) , err ) return } defer file . Close ( ) if _ , err = io . Copy ( file , unit . Serialize ( opts ) ) ; err != nil { uw . err = errwrap . Wrap ( errors . New ( errmsg ) , err ) return } if err := user . ShiftFiles ( [ ] string { path } , & uw . p . UidRange ) ; err != nil { uw . err = errwrap . Wrap ( errors . New ( errmsg ) , err ) return } }
WriteUnit writes a systemd unit in the given path with the given unit options if no previous error occurred .
208
21
84
func ( uw * UnitWriter ) writeShutdownService ( exec string , opts ... * unit . UnitOption ) { if uw . err != nil { return } flavor , systemdVersion , err := GetFlavor ( uw . p ) if err != nil { uw . err = errwrap . Wrap ( errors . New ( " " ) , err ) return } opts = append ( opts , [ ] * unit . UnitOption { // The default stdout is /dev/console (the tty created by nspawn). // But the tty might be destroyed if rkt is executed via ssh and // the user terminates the ssh session. We still want // shutdown.service to succeed in that case, so don't use // /dev/console. unit . NewUnitOption ( " " , " " , " " ) , unit . NewUnitOption ( " " , " " , " " ) , unit . NewUnitOption ( " " , " " , " " ) , } ... ) shutdownVerb := " " // systemd <v227 doesn't allow the "exit" verb when running as PID 1, so // use "halt". // If systemdVersion is 0 it means it couldn't be guessed, assume it's new // enough for "systemctl exit". // This can happen, for example, when building rkt with: // // ./configure --with-stage1-flavors=src --with-stage1-systemd-version=master // // The patches for the "exit" verb are backported to the "coreos" flavor, so // don't rely on the systemd version on the "coreos" flavor. if flavor != " " && systemdVersion != 0 && systemdVersion < 227 { shutdownVerb = " " } opts = append ( opts , unit . NewUnitOption ( " " , exec , fmt . Sprintf ( " " , shutdownVerb ) ) , ) uw . WriteUnit ( ServiceUnitPath ( uw . p . Root , " " ) , " " , opts ... , ) }
writeShutdownService writes a shutdown . service unit with the given unit options if no previous error occurred . exec specifies how systemctl should be invoked i . e . ExecStart or ExecStop .
438
39
85
func ( uw * UnitWriter ) Activate ( unit , wantPath string ) { if uw . err != nil { return } if err := os . Symlink ( path . Join ( " " , unit ) , wantPath ) ; err != nil && ! os . IsExist ( err ) { uw . err = errwrap . Wrap ( errors . New ( " " ) , err ) } }
Activate actives the given unit in the given wantPath .
86
13
86
func ( uw * UnitWriter ) AppUnit ( ra * schema . RuntimeApp , binPath string , opts ... * unit . UnitOption ) { if uw . err != nil { return } if len ( ra . App . Exec ) == 0 { uw . err = fmt . Errorf ( `image %q has an empty "exec" (try --exec=BINARY)` , uw . p . AppNameToImageName ( ra . Name ) ) return } pa , err := prepareApp ( uw . p , ra ) if err != nil { uw . err = err return } appName := ra . Name . String ( ) imgName := uw . p . AppNameToImageName ( ra . Name ) /* Write the generic unit options */ opts = append ( opts , [ ] * unit . UnitOption { unit . NewUnitOption ( " " , " " , fmt . Sprintf ( " " , appName , imgName ) ) , unit . NewUnitOption ( " " , " " , " " ) , unit . NewUnitOption ( " " , " " , fmt . Sprintf ( " " , appName ) ) , unit . NewUnitOption ( " " , " " , " " ) , // This helps working around a race // (https://github.com/systemd/systemd/issues/2913) that causes the // systemd unit name not getting written to the journal if the unit is // short-lived and runs as non-root. unit . NewUnitOption ( " " , " " , appName ) , } ... ) // Setup I/O for iottymux (stdin/stdout/stderr) opts = append ( opts , uw . SetupAppIO ( uw . p , ra , binPath ) ... ) if supportsNotify ( uw . p , ra . Name . String ( ) ) { opts = append ( opts , unit . NewUnitOption ( " " , " " , " " ) ) } // Some pre-start jobs take a long time, set the timeout to 0 opts = append ( opts , unit . NewUnitOption ( " " , " " , " " ) ) opts = append ( opts , unit . NewUnitOption ( " " , " " , " " ) ) opts = append ( opts , unit . NewUnitOption ( " " , " " , " " ) ) opts = uw . appSystemdUnit ( pa , binPath , opts ) uw . WriteUnit ( ServiceUnitPath ( uw . p . Root , ra . Name ) , " " , opts ... ) uw . Activate ( ServiceUnitName ( ra . Name ) , ServiceWantPath ( uw . p . Root , ra . Name ) ) }
AppUnit sets up the main systemd service unit for the application .
599
13
87
func ( uw * UnitWriter ) AppReaperUnit ( appName types . ACName , binPath string , opts ... * unit . UnitOption ) { if uw . err != nil { return } opts = append ( opts , [ ] * unit . UnitOption { unit . NewUnitOption ( " " , " " , fmt . Sprintf ( " " , appName ) ) , unit . NewUnitOption ( " " , " " , " " ) , unit . NewUnitOption ( " " , " " , " " ) , unit . NewUnitOption ( " " , " " , " " ) , unit . NewUnitOption ( " " , " " , " " ) , unit . NewUnitOption ( " " , " " , " " ) , unit . NewUnitOption ( " " , " " , " " ) , unit . NewUnitOption ( " " , " " , " " ) , unit . NewUnitOption ( " " , " " , fmt . Sprintf ( " \" \" \" \" \" \" " , appName , common . RelAppRootfsPath ( appName ) , binPath , ) ) , } ... ) uw . WriteUnit ( ServiceUnitPath ( uw . p . Root , types . ACName ( fmt . Sprintf ( " " , appName ) ) ) , fmt . Sprintf ( " " , appName ) , opts ... , ) }
AppReaperUnit writes an app reaper service unit for the given app in the given path using the given unit options .
301
25
88
func ( uw * UnitWriter ) AppSocketUnit ( appName types . ACName , binPath string , streamName string , opts ... * unit . UnitOption ) { opts = append ( opts , [ ] * unit . UnitOption { unit . NewUnitOption ( " " , " " , fmt . Sprintf ( " " , streamName , appName ) ) , unit . NewUnitOption ( " " , " " , " " ) , unit . NewUnitOption ( " " , " " , " " ) , unit . NewUnitOption ( " " , " " , " " ) , unit . NewUnitOption ( " " , " " , " " ) , unit . NewUnitOption ( " " , " " , fmt . Sprintf ( " " , appName ) ) , unit . NewUnitOption ( " " , " " , " " ) , unit . NewUnitOption ( " " , " " , fmt . Sprintf ( " " , appName ) ) , unit . NewUnitOption ( " " , " " , streamName ) , unit . NewUnitOption ( " " , " " , filepath . Join ( " " , appName . String ( ) , " " + streamName ) ) , } ... ) uw . WriteUnit ( TypedUnitPath ( uw . p . Root , appName . String ( ) + " " + streamName , " " ) , fmt . Sprintf ( " " , streamName , appName ) , opts ... , ) }
AppSocketUnits writes a stream socket - unit for the given app in the given path .
321
19
89
func appendOptionsList ( opts [ ] * unit . UnitOption , section , property , prefix string , vals ... string ) [ ] * unit . UnitOption { for _ , v := range vals { opts = append ( opts , unit . NewUnitOption ( section , property , fmt . Sprintf ( " " , prefix , v ) ) ) } return opts }
appendOptionsList updates an existing unit options list appending an array of new properties one entry at a time . This is the preferred method to avoid hitting line length limits in unit files . Target property must support multi - line entries .
81
46
90
func AppsForPod ( uuid , dataDir string , appName string ) ( [ ] * v1 . App , error ) { p , err := pkgPod . PodFromUUIDString ( dataDir , uuid ) if err != nil { return nil , err } defer p . Close ( ) return appsForPod ( p , appName , appStateInMutablePod ) }
AppsForPod returns the apps of the pod with the given uuid in the given data directory . If appName is non - empty then only the app with the given name will be returned .
82
39
91
func newApp ( ra * schema . RuntimeApp , podManifest * schema . PodManifest , pod * pkgPod . Pod , appState appStateFunc ) ( * v1 . App , error ) { app := & v1 . App { Name : ra . Name . String ( ) , ImageID : ra . Image . ID . String ( ) , UserAnnotations : ra . App . UserAnnotations , UserLabels : ra . App . UserLabels , } podVols := podManifest . Volumes podVolsByName := make ( map [ types . ACName ] types . Volume , len ( podVols ) ) for i := range podManifest . Volumes { podVolsByName [ podVols [ i ] . Name ] = podVols [ i ] } for _ , mnt := range ra . Mounts { readOnly := false var hostPath string // AppVolume is optional if av := mnt . AppVolume ; av != nil { hostPath = av . Source if ro := av . ReadOnly ; ro != nil { readOnly = * ro } } else { hostPath = podVolsByName [ mnt . Volume ] . Source if ro := podVolsByName [ mnt . Volume ] . ReadOnly ; ro != nil { readOnly = * ro } } app . Mounts = append ( app . Mounts , & v1 . Mount { Name : mnt . Volume . String ( ) , ContainerPath : mnt . Path , HostPath : hostPath , ReadOnly : readOnly , } ) } // Generate state. if err := appState ( app , pod ) ; err != nil { return nil , fmt . Errorf ( " " , err ) } return app , nil }
newApp constructs the App object with the runtime app and pod manifest .
373
14
92
func appStateInImmutablePod ( app * v1 . App , pod * pkgPod . Pod ) error { app . State = appStateFromPod ( pod ) t , err := pod . CreationTime ( ) if err != nil { return err } createdAt := t . UnixNano ( ) app . CreatedAt = & createdAt code , err := pod . AppExitCode ( app . Name ) if err == nil { // there is an exit code, it is definitely Exited app . State = v1 . AppStateExited exitCode := int32 ( code ) app . ExitCode = & exitCode } start , err := pod . StartTime ( ) if err != nil { return err } if ! start . IsZero ( ) { startedAt := start . UnixNano ( ) app . StartedAt = & startedAt } // the best we can guess for immutable pods finish , err := pod . GCMarkedTime ( ) if err != nil { return err } if ! finish . IsZero ( ) { finishedAt := finish . UnixNano ( ) app . FinishedAt = & finishedAt } return nil }
appStateInImmutablePod infers most App state from the Pod itself since all apps are created and destroyed with the Pod
237
25
93
func ( p * Pod ) SaveRuntime ( ) error { path := filepath . Join ( p . Root , RuntimeConfigPath ) buf , err := json . Marshal ( p . RuntimePod ) if err != nil { return err } return ioutil . WriteFile ( path , buf , 0644 ) }
SaveRuntime persists just the runtime state . This should be called when the pod is started .
64
18
94
func LoadPodManifest ( root string ) ( * schema . PodManifest , error ) { buf , err := ioutil . ReadFile ( common . PodManifestPath ( root ) ) if err != nil { return nil , errwrap . Wrap ( errors . New ( " " ) , err ) } pm := & schema . PodManifest { } if err := json . Unmarshal ( buf , pm ) ; err != nil { return nil , errwrap . Wrap ( errors . New ( " " ) , err ) } return pm , nil }
LoadPodManifest loads a Pod Manifest .
118
9
95
func ( f * Fetcher ) FetchImages ( al * apps . Apps ) error { return al . Walk ( func ( app * apps . App ) error { d , err := DistFromImageString ( app . Image ) if err != nil { return err } h , err := f . FetchImage ( d , app . Image , app . Asc ) if err != nil { return err } app . ImageID = * h return nil } ) }
FetchImages uses FetchImage to attain a list of image hashes
95
14
96
func ( f * Fetcher ) FetchImage ( d dist . Distribution , image , ascPath string ) ( * types . Hash , error ) { ensureLogger ( f . Debug ) db := & distBundle { dist : d , image : image , } a := f . getAsc ( ascPath ) hash , err := f . fetchSingleImage ( db , a ) if err != nil { return nil , err } if f . WithDeps { err = f . fetchImageDeps ( hash ) if err != nil { return nil , err } } // we need to be able to do a chroot and access to the tree store // directories, we need to // 1) check if the system supports OverlayFS // 2) check if we're root if common . SupportsOverlay ( ) == nil && os . Geteuid ( ) == 0 { if _ , _ , err := f . Ts . Render ( hash , false ) ; err != nil { return nil , errwrap . Wrap ( errors . New ( " " ) , err ) } } h , err := types . NewHash ( hash ) if err != nil { // should never happen log . PanicE ( " " , err ) } return h , nil }
FetchImage will take an image as either a path a URL or a name string and import it into the store if found . If ascPath is not it must exist as a local file and will be used as the signature file for verification unless verification is disabled . If f . WithDeps is true also image dependencies are fetched .
260
68
97
func ( f * Fetcher ) fetchImageDeps ( hash string ) error { imgsl := list . New ( ) seen := map [ string ] dist . Distribution { } f . addImageDeps ( hash , imgsl , seen ) for el := imgsl . Front ( ) ; el != nil ; el = el . Next ( ) { a := & asc { } d := el . Value . ( * dist . Appc ) str := d . String ( ) db := & distBundle { dist : d , image : str , } hash , err := f . fetchSingleImage ( db , a ) if err != nil { return err } f . addImageDeps ( hash , imgsl , seen ) } return nil }
fetchImageDeps will recursively fetch all the image dependencies
154
14
98
func New ( out io . Writer , prefix string , debug bool ) * Logger { l := & Logger { debug : debug , Logger : log . New ( out , prefix , 0 ) , } l . SetFlags ( 0 ) return l }
New creates a new Logger with no Log flags set .
53
12
99
func ( l * Logger ) Error ( e error ) { l . Print ( l . formatErr ( e , " " ) ) }
Error is a convenience function for printing errors without a message .
30
12

Dataset Card for "UDR_Go_new"

More Information needed

Downloads last month
2
Edit dataset card