Dataset Viewer
Auto-converted to Parquet Duplicate
idx
int64
0
41.8k
question
stringlengths
66
3.48k
target
stringlengths
5
1.43k
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 .
1
func getIoProgressReader ( label string , res * http . Response ) io . Reader { prefix := "Downloading " + label fmtBytesSize := 18 barSize := int64 ( 80 - len ( prefix ) - fmtBytesSize ) bar := ioprogress . DrawTextFormatBarForW ( barSize , os . Stderr ) fmtfunc := func ( progress , total int64 ) string { if total == - 1 { return fmt . Sprintf ( "%s: %v of an unknown total size" , prefix , ioprogress . ByteUnitStr ( progress ) , ) } return fmt . Sprintf ( "%s: %s %s" , 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 .
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 .
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 ( "error setting up temporary file" ) , err ) } _ , err = lock . TryExclusiveLock ( tmp . Name ( ) , lock . RegFile ) if err != nil { if err != lock . ErrLocked { return nil , errwrap . Wrap ( errors . New ( "failed to lock temporary file" ) , err ) } log . Printf ( "another rkt instance is downloading this file, waiting..." ) _ , err = lock . ExclusiveLock ( tmp . Name ( ) , lock . RegFile ) if err != nil { return nil , errwrap . Wrap ( errors . New ( "failed to lock temporary file" ) , 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 .
4
func getStage1Entrypoint ( cdir string , entrypoint string ) ( string , error ) { b , err := ioutil . ReadFile ( common . Stage1ManifestPath ( cdir ) ) if err != nil { return "" , errwrap . Wrap ( errors . New ( "error reading pod manifest" ) , err ) } s1m := schema . ImageManifest { } if err := json . Unmarshal ( b , & s1m ) ; err != nil { return "" , errwrap . Wrap ( errors . New ( "error unmarshaling stage1 manifest" ) , err ) } if ep , ok := s1m . Annotations . Get ( entrypoint ) ; ok { return ep , nil } return "" , fmt . Errorf ( "entrypoint %q not found" , entrypoint ) }
getStage1Entrypoint retrieves the named entrypoint from the stage1 manifest for a given pod
5
func getStage1InterfaceVersion ( cdir string ) ( int , error ) { b , err := ioutil . ReadFile ( common . Stage1ManifestPath ( cdir ) ) if err != nil { return - 1 , errwrap . Wrap ( errors . New ( "error reading pod manifest" ) , err ) } s1m := schema . ImageManifest { } if err := json . Unmarshal ( b , & s1m ) ; err != nil { return - 1 , errwrap . Wrap ( errors . New ( "error unmarshaling stage1 manifest" ) , err ) } if iv , ok := s1m . Annotations . Get ( interfaceVersion ) ; ok { v , err := strconv . Atoi ( iv ) if err != nil { return - 1 , errwrap . Wrap ( errors . New ( "error parsing interface version" ) , err ) } return v , nil } return 1 , nil }
getStage1InterfaceVersion retrieves the interface version from the stage1 manifest for a given pod
6
func ( e * podEnv ) loadNets ( ) ( [ ] activeNet , error ) { if e . netsLoadList . None ( ) { stderr . Printf ( "networking namespace with loopback only" ) 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 ( "networks not found: %v" , strings . Join ( missing , ", " ) ) } 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 .
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 u , g , err := ParseUserGroup ( p , ra ) if err != nil { return nil , errwrap . Wrap ( errors . New ( "unable to determine app's uid and gid" ) , err ) } if u < 0 || g < 0 { return nil , errors . New ( "Invalid uid or gid" ) } pa . uid = uint32 ( u ) pa . gid = uint32 ( g ) pa . env . Set ( "AC_APP_NAME" , ra . Name . String ( ) ) if p . MetadataServiceURL != "" { pa . env . Set ( "AC_METADATA_URL" , p . MetadataServiceURL ) } pa . capabilities , err = getAppCapabilities ( ra . App . Isolators ) if err != nil { return nil , errwrap . Wrap ( errors . New ( "unable to construct capabilities" ) , err ) } 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 ( "unable to compute mounts" ) , err ) } pa . resources , err = computeAppResources ( ra . App . Isolators ) if err != nil { return nil , errwrap . Wrap ( errors . New ( "unable to compute resources" ) , err ) } if ! p . InsecureOptions . DisablePaths { pa . roPaths = append ( pa . roPaths , protectKernelROPaths ... ) pa . hiddenPaths = append ( pa . hiddenDirs , protectKernelHiddenPaths ... ) pa . hiddenDirs = append ( pa . hiddenDirs , protectKernelHiddenDirs ... ) } 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 } } if err := generateSysusers ( p , pa . app , int ( pa . uid ) , int ( pa . gid ) , & p . UidRange ) ; err != nil { return nil , errwrap . Wrapf ( "unable to generate sysusers file" , err ) } return & pa , nil }
prepareApp sets up the internal runtime context for a specific app .
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 ( "could not check for isolator " + name , err ) } if ! ok { fmt . Fprintf ( os . Stderr , "warning: resource/%s isolator set but support disabled in the kernel, skipping\n" , \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 ( "memory" , func ( ) error { if v . Limit ( ) == nil { return nil } val := uint64 ( v . Limit ( ) . Value ( ) ) res . MemoryLimit = & val return nil } ) case * types . ResourceCPU : err = withIsolator ( "cpu" , func ( ) error { if v . Limit ( ) == nil { return nil } if v . Limit ( ) . Value ( ) > MaxMilliValue { return fmt . Errorf ( "cpu limit exceeds the maximum millivalue: %v" , v . Limit ( ) . String ( ) ) } val := uint64 ( v . Limit ( ) . MilliValue ( ) / 10 ) res . CPUQuota = & val return nil } ) case * types . LinuxCPUShares : err = withIsolator ( "cpu" , func ( ) error { val := uint64 ( * v ) res . LinuxCPUShares = & val return nil } ) case * types . LinuxOOMScoreAdj : val := int ( * v ) res . LinuxOOMScoreAdjust = & val } } }
computeAppResources processes any isolators that manipulate cgroups .
9
func GetACIInfosWithKeyPrefix ( tx * sql . Tx , prefix string ) ( [ ] * ACIInfo , error ) { var aciinfos [ ] * ACIInfo rows , err := tx . Query ( "SELECT * from aciinfo WHERE hasPrefix(blobkey, $1)" , 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 .
10
func GetACIInfosWithName ( tx * sql . Tx , name string ) ( [ ] * ACIInfo , bool , error ) { var aciinfos [ ] * ACIInfo found := false rows , err := tx . Query ( "SELECT * from aciinfo WHERE name == $1" , 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 .
11
func GetACIInfoWithBlobKey ( tx * sql . Tx , blobKey string ) ( * ACIInfo , bool , error ) { aciinfo := & ACIInfo { } found := false rows , err := tx . Query ( "SELECT * from aciinfo WHERE blobkey == $1" , 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 } 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 .
12
func GetAllACIInfos ( tx * sql . Tx , sortfields [ ] string , ascending bool ) ( [ ] * ACIInfo , error ) { var aciinfos [ ] * ACIInfo query := "SELECT * from aciinfo" if len ( sortfields ) > 0 { query += fmt . Sprintf ( " ORDER BY %s " , strings . Join ( sortfields , ", " ) ) if ascending { query += "ASC" } else { query += "DESC" } } 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 .
13
func WriteACIInfo ( tx * sql . Tx , aciinfo * ACIInfo ) error { _ , err := tx . Exec ( "DELETE from aciinfo where blobkey == $1" , aciinfo . BlobKey ) if err != nil { return err } _ , err = tx . Exec ( "INSERT into aciinfo (blobkey, name, importtime, lastused, latest, size, treestoresize) VALUES ($1, $2, $3, $4, $5, $6, $7)" , 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 .
14
func StartCmd ( wdPath , name , kernelPath string , nds [ ] kvm . NetDescriber , cpu , mem int64 , debug bool ) [ ] string { var ( driverConfiguration = hypervisor . KvmHypervisor { Bin : "./qemu" , KernelParams : [ ] string { "root=/dev/root" , "rootfstype=9p" , "rootflags=trans=virtio,version=9p2000.L,cache=mmap" , "rw" , "systemd.default_standard_error=journal+console" , "systemd.default_standard_output=journal+console" , } , } ) driverConfiguration . InitKernelParams ( debug ) cmd := [ ] string { filepath . Join ( wdPath , driverConfiguration . Bin ) , "-L" , wdPath , "-no-reboot" , "-display" , "none" , "-enable-kvm" , "-smp" , strconv . FormatInt ( cpu , 10 ) , "-m" , strconv . FormatInt ( mem , 10 ) , "-kernel" , kernelPath , "-fsdev" , "local,id=root,path=stage1/rootfs,security_model=none" , "-device" , "virtio-9p-pci,fsdev=root,mount_tag=/dev/root" , "-append" , fmt . Sprintf ( "%s" , strings . Join ( driverConfiguration . KernelParams , " " ) ) , "-chardev" , "stdio,id=virtiocon0,signal=off" , "-device" , "virtio-serial" , "-device" , "virtconsole,chardev=virtiocon0" , } 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
15
func kvmNetArgs ( nds [ ] kvm . NetDescriber ) [ ] string { var qemuArgs [ ] string for _ , nd := range nds { qemuArgs = append ( qemuArgs , [ ] string { "-net" , "nic,model=virtio" } ... ) qemuNic := fmt . Sprintf ( "tap,ifname=%s,script=no,downscript=no,vhost=on" , nd . IfName ( ) ) qemuArgs = append ( qemuArgs , [ ] string { "-net" , 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
16
func ( hv * KvmHypervisor ) InitKernelParams ( isDebug bool ) { hv . KernelParams = append ( hv . KernelParams , [ ] string { "console=hvc0" , "init=/usr/lib/systemd/systemd" , "no_timer_check" , "noreplace-smp" , "tsc=reliable" } ... ) if isDebug { hv . KernelParams = append ( hv . KernelParams , [ ] string { "debug" , "systemd.log_level=debug" , "systemd.show_status=true" , } ... ) } else { hv . KernelParams = append ( hv . KernelParams , [ ] string { "systemd.show_status=false" , "systemd.log_target=null" , "rd.udev.log-priority=3" , "quiet=vga" , "quiet systemd.log_level=emerg" , } ... ) } customKernelParams := os . Getenv ( "RKT_HYPERVISOR_EXTRA_KERNEL_PARAMS" ) if customKernelParams != "" { hv . KernelParams = append ( hv . KernelParams , customKernelParams ) } }
InitKernelParams sets debug and common parameters passed to the kernel
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 == "latest" 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 .
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 ( "failed to generate MDS token" ) , err ) return } pmfPath := common . PodManifestPath ( root ) pmf , err := os . Open ( pmfPath ) if err != nil { rerr = errwrap . Wrap ( fmt . Errorf ( "failed to open runtime manifest (%v)" , pmfPath ) , err ) return } pth := fmt . Sprintf ( "/pods/%v?token=%v" , u , token ) err = httpRequest ( "PUT" , pth , pmf ) pmf . Close ( ) if err != nil { rerr = errwrap . Wrap ( errors . New ( "failed to register pod with metadata svc" ) , 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 ( "failed to create mds-register file" ) , 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 ( "failed reading app manifest %q" , ampath ) , err ) return } err = registerApp ( u , app . Name . String ( ) , amf ) amf . Close ( ) if err != nil { rerr = errwrap . Wrap ( errors . New ( "failed to register app with metadata svc" ) , err ) return } } return }
registerPod registers pod with metadata service . Returns authentication token to be passed in the URL
19
func unregisterPod ( root string , uuid * types . UUID ) error { _ , err := os . Stat ( filepath . Join ( root , mdsRegisteredFile ) ) switch { case err == nil : pth := path . Join ( "/pods" , uuid . String ( ) ) return httpRequest ( "DELETE" , pth , nil ) case os . IsNotExist ( err ) : return nil default : return err } }
unregisterPod unregisters pod with the metadata service .
20
func CheckMdsAvailability ( ) error { if conn , err := net . Dial ( "unix" , common . MetadataServiceRegSock ) ; err != nil { return errUnreachable } else { conn . Close ( ) return nil } }
CheckMdsAvailability checks whether a local metadata service can be reached .
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
22
func Add ( name string , fn commandFn ) Entrypoint { if _ , ok := commands [ name ] ; ok { panic ( fmt . Errorf ( "command with name %q already exists" , 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 .
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
24
func HasChrootCapability ( ) bool { 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
25
func LookupGidFromFile ( groupName , groupFile string ) ( gid int , err error ) { groups , err := parseGroupFile ( groupFile ) if err != nil { return - 1 , errwrap . Wrap ( fmt . Errorf ( "error parsing %q file" , groupFile ) , err ) } group , ok := groups [ groupName ] if ! ok { return - 1 , fmt . Errorf ( "%q group not found" , groupName ) } return group . Gid , nil }
LookupGid reads the group file specified by groupFile and returns the gid of the group specified by groupName .
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 .
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 .
28
func ( l * KeyLock ) Unlock ( ) error { err := l . keyLock . Unlock ( ) if err != nil { return err } return nil }
Unlock unlocks the key lock .
29
func CleanKeyLocks ( lockDir string ) error { f , err := os . Open ( lockDir ) if err != nil { return errwrap . Wrap ( errors . New ( "error opening lockDir" ) , err ) } defer f . Close ( ) files , err := f . Readdir ( 0 ) if err != nil { return errwrap . Wrap ( errors . New ( "error getting lock files list" ) , 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 ( "error removing lock file" ) , 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
30
func ( m * Manager ) GetPubKeyLocations ( prefix string ) ( [ ] string , error ) { ensureLogger ( m . Debug ) if prefix == "" { return nil , fmt . Errorf ( "empty prefix" ) } kls , err := m . metaDiscoverPubKeyLocations ( prefix ) if err != nil { return nil , errwrap . Wrap ( errors . New ( "prefix meta discovery error" ) , err ) } if len ( kls ) == 0 { return nil , fmt . Errorf ( "meta discovery on %s resulted in no keys" , prefix ) } return kls , nil }
GetPubKeyLocations discovers locations at prefix
31
func ( m * Manager ) AddKeys ( pkls [ ] string , prefix string , accept AcceptOption ) error { ensureLogger ( m . Debug ) if m . Ks == nil { return fmt . Errorf ( "no keystore available to add keys to" ) } 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 ( "error accessing the key %s" , pkl ) , err ) } defer pk . Close ( ) err = displayKey ( prefix , pkl , pk ) if err != nil { return errwrap . Wrap ( fmt . Errorf ( "error displaying the key %s" , pkl ) , err ) } if m . TrustKeysFromHTTPS && u . Scheme == "https" { accept = AcceptForce } if accept == AcceptAsk { if ! terminal . IsTerminal ( int ( os . Stdin . Fd ( ) ) ) || ! terminal . IsTerminal ( int ( os . Stderr . Fd ( ) ) ) { log . Printf ( "To trust the key for %q, do one of the following:" , prefix ) log . Printf ( " - call rkt with --trust-keys-from-https" ) log . Printf ( " - run: rkt trust --prefix %q" , prefix ) return fmt . Errorf ( "error reviewing key: unable to ask user to review fingerprint due to lack of tty" ) } accepted , err := reviewKey ( ) if err != nil { return errwrap . Wrap ( errors . New ( "error reviewing key" ) , err ) } if ! accepted { log . Printf ( "not trusting %q" , pkl ) continue } } if accept == AcceptForce { stdout . Printf ( "Trusting %q for prefix %q without fingerprint review." , pkl , prefix ) } else { stdout . Printf ( "Trusting %q for prefix %q after fingerprint review." , pkl , prefix ) } if prefix == "" { path , err := m . Ks . StoreTrustedKeyRoot ( pk ) if err != nil { return errwrap . Wrap ( errors . New ( "error adding root key" ) , err ) } stdout . Printf ( "Added root key at %q" , path ) } else { path , err := m . Ks . StoreTrustedKeyPrefix ( prefix , pk ) if err != nil { return errwrap . Wrap ( fmt . Errorf ( "error adding key for prefix %q" , prefix ) , err ) } stdout . Printf ( "Added key for prefix %q at %q" , prefix , path ) } } return nil }
AddKeys adds the keys listed in pkls at prefix
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 ( "meta tag 'ac-discovery-pubkeys' not found on %s" , a . Prefix ) , a . Error ) } } return keys , err }
metaDiscoverPubKeyLocations discovers the locations of public keys through ACDiscovery by applying prefix as an ACApp
33
func downloadKey ( u * url . URL , skipTLSCheck bool ) ( * os . File , error ) { tf , err := ioutil . TempFile ( "" , "" ) if err != nil { return nil , errwrap . Wrap ( errors . New ( "error creating tempfile" ) , err ) } os . Remove ( tf . Name ( ) ) defer func ( ) { if tf != nil { tf . Close ( ) } } ( ) 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 ( "error getting key" ) , err ) } defer res . Body . Close ( ) if res . StatusCode != http . StatusOK { return nil , fmt . Errorf ( "bad HTTP status code: %d" , res . StatusCode ) } if _ , err := io . Copy ( tf , res . Body ) ; err != nil { return nil , errwrap . Wrap ( errors . New ( "error copying key" ) , err ) } if _ , err = tf . Seek ( 0 , os . SEEK_SET ) ; err != nil { return nil , errwrap . Wrap ( errors . New ( "error seeking" ) , err ) } retTf := tf tf = nil return retTf , nil }
downloadKey retrieves the file storing it in a deleted tempfile
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 ( "error reading key" ) , err ) } log . Printf ( "prefix: %q\nkey: %q" , \n , prefix ) location for _ , k := range kr { stdout . Printf ( "gpg key fingerprint is: %s" , fingerToString ( k . PrimaryKey . Fingerprint ) ) for _ , sk := range k . Subkeys { stdout . Printf ( " Subkey fingerprint: %s" , fingerToString ( sk . PublicKey . Fingerprint ) ) } for n := range k . Identities { stdout . Printf ( "\t%s" , \t ) } } }
displayKey shows the key summary
35
func reviewKey ( ) ( bool , error ) { in := bufio . NewReader ( os . Stdin ) for { stdout . Printf ( "Are you sure you want to trust this key (yes/no)?" ) input , err := in . ReadString ( '\n' ) if err != nil { return false , errwrap . Wrap ( errors . New ( "error reading input" ) , err ) } switch input { case "yes\n" : \n return true , nil case "no\n" : \n } } }
reviewKey asks the user to accept the key
36
func setupTapDevice ( podID types . UUID ) ( netlink . Link , error ) { nameTemplate := fmt . Sprintf ( "rkt-%s-tap%%d" , podID . String ( ) [ 0 : 4 ] ) ifName , err := tuntap . CreatePersistentIface ( nameTemplate , tuntap . Tap ) if err != nil { return nil , errwrap . Wrap ( errors . New ( "tuntap persist" ) , err ) } link , err := netlink . LinkByName ( ifName ) if err != nil { return nil , errwrap . Wrap ( fmt . Errorf ( "cannot find link %q" , ifName ) , err ) } if err := netlink . LinkSetUp ( link ) ; err != nil { return nil , errwrap . Wrap ( fmt . Errorf ( "cannot set link up %q" , ifName ) , err ) } return link , nil }
setupTapDevice creates persistent tap device and returns a newly created netlink . Link structure
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 ( "cannot find master device '%v'" , config . Master ) , err ) } var mode netlink . MacvlanMode switch config . Mode { case "" , "bridge" : mode = netlink . MACVLAN_MODE_BRIDGE case "private" : mode = netlink . MACVLAN_MODE_PRIVATE case "vepa" : mode = netlink . MACVLAN_MODE_VEPA case "passthru" : mode = netlink . MACVLAN_MODE_PASSTHRU default : return nil , fmt . Errorf ( "unsupported macvtap mode: %v" , config . Mode ) } mtu := master . Attrs ( ) . MTU if config . MTU != 0 { mtu = config . MTU } interfaceName := fmt . Sprintf ( "rkt-%s-vtap%d" , 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 ( "cannot create macvtap interface" ) , err ) } ipv4SysctlValueName := fmt . Sprintf ( IPv4InterfaceArpProxySysctlTemplate , interfaceName ) if _ , err := cnisysctl . Sysctl ( ipv4SysctlValueName , "1" ) ; err != nil { _ = netlink . LinkDel ( link ) return nil , errwrap . Wrap ( fmt . Errorf ( "failed to set proxy_arp on newly added interface %q" , interfaceName ) , err ) } if err := netlink . LinkSetUp ( link ) ; err != nil { _ = netlink . LinkDel ( link ) return nil , errwrap . Wrap ( errors . New ( "cannot set up macvtap interface" ) , 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
38
func ( n * Networking ) kvmTeardown ( ) { if err := n . teardownForwarding ( ) ; err != nil { stderr . PrintE ( "error removing forwarded ports (kvm)" , err ) } n . teardownKvmNets ( ) }
kvmTeardown network teardown for kvm flavor based pods similar to Networking . Teardown but without host namespaces
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 ( "failed to get an absolute path for %q" , 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 .
40
func ( f * fileFetcher ) getVerifiedFile ( aciPath string , a * asc ) ( * os . File , error ) { var aciFile * os . File var errClose error f . maybeOverrideAsc ( aciPath , a ) ascFile , err := a . Get ( ) if err != nil { return nil , errwrap . Wrap ( errors . New ( "error opening signature file" ) , err ) } defer ascFile . Close ( ) aciFile , err = os . Open ( aciPath ) if err != nil { return nil , errwrap . Wrap ( errors . New ( "error opening ACI file" ) , 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 ( "image %q verification failed" , validator . ImageName ( ) ) , errClose ) } printIdentities ( entity ) return aciFile , nil }
fetch opens and verifies the ACI .
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 .
42
func Extend ( description string ) error { connection := tpmclient . New ( "localhost:12041" , timeout ) err := connection . Extend ( 15 , 0x1000 , nil , description ) return err }
Extend extends the TPM log with the provided string . Returns any error .
43
func Stage1RootfsPath ( root string ) string { return filepath . Join ( Stage1ImagePath ( root ) , aci . RootfsDir ) }
Stage1RootfsPath returns the path to the stage1 rootfs
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 .
45
func AppStatusPath ( root , appName string ) string { return filepath . Join ( AppsStatusesPath ( root ) , appName ) }
AppStatusPath returns the path of the status file of an app .
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 .
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 .
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 .
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 .
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 .
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 .
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 .
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 .
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
55
func CreateSharedVolumesPath ( root string ) ( string , error ) { sharedVolPath := SharedVolumesPath ( root ) if err := os . MkdirAll ( sharedVolPath , SharedVolumePerm ) ; err != nil { return "" , errwrap . Wrap ( errors . New ( "could not create shared volumes directory" ) , err ) } if err := os . Chmod ( sharedVolPath , SharedVolumePerm ) ; err != nil { return "" , errwrap . Wrap ( fmt . Errorf ( "could not change permissions of %q" , 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 .
56
func MetadataServicePublicURL ( ip net . IP , token string ) string { return fmt . Sprintf ( "http://%v:%v/%v" , ip , MetadataServicePort , token ) }
MetadataServicePublicURL returns the public URL used to host the metadata service
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 ( "unable to find absolute path for %s" , binPath ) } if fileutil . IsExecutable ( binAbsPath ) { return binAbsPath , nil } } return "" , fmt . Errorf ( "unable to find %q in %q" , bin , paths ) }
LookupPath search for bin in paths . If found it returns its absolute path if not an error
58
func SystemdVersion ( systemdBinaryPath string ) ( int , error ) { versionBytes , err := exec . Command ( systemdBinaryPath , "--version" ) . CombinedOutput ( ) if err != nil { return - 1 , errwrap . Wrap ( fmt . Errorf ( "unable to probe %s version" , systemdBinaryPath ) , err ) } versionStr := strings . SplitN ( string ( versionBytes ) , "\n" , \n ) [ 2 ] 0 var version int n , err := fmt . Sscanf ( versionStr , "systemd %d" , & version ) if err != nil || n != 1 { return - 1 , fmt . Errorf ( "cannot parse version: %q" , versionStr ) } }
SystemdVersion parses and returns the version of a given systemd binary
59
func SupportsOverlay ( ) error { _ = exec . Command ( "modprobe" , "overlay" ) . Run ( ) f , err := os . Open ( "/proc/filesystems" ) if err != nil { return ErrOverlayUnsupported ( fmt . Sprintf ( "cannot open /proc/filesystems: %v" , err ) ) } defer f . Close ( ) s := bufio . NewScanner ( f ) for s . Scan ( ) { if s . Text ( ) == "nodev\toverlay" \t } { return nil } }
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 .
60
func RemoveEmptyLines ( str string ) [ ] string { lines := make ( [ ] string , 0 ) for _ , v := range strings . Split ( str , "\n" ) \n { if len ( v ) > 0 { lines = append ( lines , v ) } } }
RemoveEmptyLines removes empty lines from the given string and breaks it up into a list of strings at newline characters
61
func GetExitStatus ( err error ) ( int , error ) { if err == nil { return 0 , nil } if exiterr , ok := err . ( * exec . ExitError ) ; ok { 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
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
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
64
func GetKVMNetArgs ( nds [ ] NetDescriber ) ( [ ] string , error ) { var lkvmArgs [ ] string for _ , nd := range nds { lkvmArgs = append ( lkvmArgs , "--network" ) lkvmArg := fmt . Sprintf ( "mode=tap,tapif=%s,host_ip=%s,guest_ip=%s" , 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
65
func generateMacAddress ( ) ( net . HardwareAddr , error ) { mac := [ ] byte { 2 , 0x65 , 0x02 , 0 , 0 , 0 , } _ , err := rand . Read ( mac [ 3 : 6 ] ) if err != nil { return nil , errwrap . Wrap ( errors . New ( "cannot generate random mac address" ) , err ) } return mac , nil }
generateMacAddress returns net . HardwareAddr filled with fixed 3 byte prefix complemented by 3 random bytes .
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 .
67
func standardFlags ( cmd string ) ( * flag . FlagSet , * string ) { f := flag . NewFlagSet ( appName ( ) + " " + cmd , flag . ExitOnError ) target := f . String ( "target" , "" , "Make target (example: $(FOO_BINARY))" ) return f , target }
standardFlags returns a new flag set with target flag already set up
68
func ( e * podEnv ) netPluginAdd ( n * activeNet , netns string ) error { output , err := e . execNetPlugin ( "ADD" , 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 ( "parsing %q" , string ( output ) ) , err ) return errwrap . Wrap ( fmt . Errorf ( "error parsing %q result" , n . conf . Name ) , err ) } if pr . IP4 == nil { return nil } n . runtime . MergeCNIResult ( pr ) return nil }
Executes a given network plugin . If successful mutates n . runtime with the runtime information
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 .
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 .
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 .
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 .
73
func satisfiesPodFilter ( pod v1alpha . Pod , filter v1alpha . PodFilter ) bool { if len ( filter . Ids ) > 0 { s := set . NewString ( filter . Ids ... ) if ! s . Has ( pod . Id ) { return false } } if len ( filter . States ) > 0 { foundState := false for _ , state := range filter . States { if pod . State == state { foundState = true break } } if ! foundState { return false } } if len ( filter . AppNames ) > 0 { s := set . NewString ( ) for _ , app := range pod . Apps { s . Insert ( app . Name ) } if ! s . HasAll ( filter . AppNames ... ) { return false } } 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 } } if len ( filter . NetworkNames ) > 0 { s := set . NewString ( ) for _ , network := range pod . Networks { s . Insert ( network . Name ) } if ! s . HasAll ( filter . NetworkNames ... ) { return false } } if len ( filter . Annotations ) > 0 { if ! containsAllKeyValues ( pod . Annotations , filter . Annotations ) { return false } } if len ( filter . Cgroups ) > 0 { s := set . NewString ( filter . Cgroups ... ) if ! s . Has ( pod . Cgroup ) { return false } } 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 .
74
func satisfiesAnyPodFilters ( pod * v1alpha . Pod , filters [ ] * v1alpha . PodFilter ) bool { 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 .
75
func getApplist ( manifest * schema . PodManifest ) [ ] * v1alpha . App { var apps [ ] * v1alpha . App for _ , app := range manifest . Apps { img := & v1alpha . Image { BaseFormat : & v1alpha . ImageFormat { Type : v1alpha . ImageType_IMAGE_TYPE_APPC , Version : schema . AppContainerVersion . String ( ) , } , Id : app . Image . ID . String ( ) , } 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 .
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 , Ipv4 : n . IP . String ( ) , } ) } return networks }
getNetworks returns the list of the info of the network that the pod belongs to .
77
func fillStaticAppInfo ( store * imagestore . Store , pod * pkgPod . Pod , v1pod * v1alpha . Pod ) error { var errlist [ ] error for _ , app := range v1pod . Apps { app . Image = & v1alpha . Image { BaseFormat : & v1alpha . ImageFormat { Type : v1alpha . ImageType_IMAGE_TYPE_APPC , Version : schema . AppContainerVersion . String ( ) , } , Id : app . Image . Id , } im , err := pod . AppImageManifest ( app . Name ) if err != nil { stderr . PrintE ( fmt . Sprintf ( "failed to get image manifests for app %q" , app . Name ) , err ) errlist = append ( errlist , err ) } else { app . Image . Name = im . Name . String ( ) version , ok := im . Labels . Get ( "version" ) if ! ok { version = "latest" } app . Image . Version = version } } if len ( errlist ) != 0 { return errs { errlist } } return nil }
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 .
78
func ( s * v1AlphaAPIServer ) getBasicPod ( p * pkgPod . Pod ) * v1alpha . Pod { mtime , mtimeErr := getPodManifestModTime ( p ) if mtimeErr != nil { stderr . PrintE ( fmt . Sprintf ( "failed to read the pod manifest's mtime for pod %q" , p . UUID ) , mtimeErr ) } itemValue , found := s . podCache . Get ( p . UUID . String ( ) ) if found && mtimeErr == nil { cacheItem := itemValue . ( * podCacheItem ) if ! mtime . After ( cacheItem . mtime ) { return copyPod ( cacheItem . pod ) } } pod , err := s . getBasicPodFromDisk ( p ) if mtimeErr != nil || err != nil { return pod } cacheItem := & podCacheItem { pod , mtime } s . podCache . Add ( p . UUID . String ( ) , cacheItem ) return copyPod ( cacheItem . pod ) }
getBasicPod returns v1alpha . Pod with basic pod information .
79
func aciInfoToV1AlphaAPIImage ( store * imagestore . Store , aciInfo * imagestore . ACIInfo ) ( * v1alpha . Image , error ) { manifest , err := store . GetImageManifestJSON ( aciInfo . BlobKey ) if err != nil { stderr . PrintE ( "failed to read the image manifest" , err ) return nil , err } var im schema . ImageManifest if err = json . Unmarshal ( manifest , & im ) ; err != nil { stderr . PrintE ( "failed to unmarshal image manifest" , err ) return nil , err } version , ok := im . Labels . Get ( "version" ) if ! ok { version = "latest" } return & v1alpha . Image { BaseFormat : & v1alpha . ImageFormat { 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 .
80
func satisfiesImageFilter ( image v1alpha . Image , filter v1alpha . ImageFilter ) bool { if len ( filter . Ids ) > 0 { s := set . NewString ( filter . Ids ... ) if ! s . Has ( image . Id ) { return false } } if len ( filter . FullNames ) > 0 { s := set . NewString ( filter . FullNames ... ) if ! s . Has ( image . Name ) { return false } } if len ( filter . Prefixes ) > 0 { s := set . NewString ( filter . Prefixes ... ) if ! s . ConditionalHas ( isPrefixOf , image . Name ) { return false } } if len ( filter . BaseNames ) > 0 { s := set . NewString ( filter . BaseNames ... ) if ! s . ConditionalHas ( isBaseNameOf , image . Name ) { return false } } if len ( filter . Keywords ) > 0 { s := set . NewString ( filter . Keywords ... ) if ! s . ConditionalHas ( isPartOf , image . Name ) { return false } } if filter . ImportedAfter > 0 { if image . ImportTimestamp <= filter . ImportedAfter { return false } } if filter . ImportedBefore > 0 { if image . ImportTimestamp >= filter . ImportedBefore { return false } } if len ( filter . Labels ) > 0 { if ! containsAllKeyValues ( image . Labels , filter . Labels ) { return false } } 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 .
81
func satisfiesAnyImageFilters ( image * v1alpha . Image , filters [ ] * v1alpha . ImageFilter ) bool { 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 .
82
func runAPIService ( cmd * cobra . Command , args [ ] string ) ( exit int ) { signal . Notify ( exitCh , syscall . SIGINT , syscall . SIGTERM ) stderr . Print ( "API service starting..." ) listeners , err := openAPISockets ( ) if err != nil { stderr . PrintE ( "Failed to open sockets" , err ) return 254 } if len ( listeners ) == 0 { stderr . Println ( "No sockets to listen to. Quitting." ) return 254 } publicServer := grpc . NewServer ( ) v1AlphaAPIServer , err := newV1AlphaAPIServer ( ) if err != nil { stderr . PrintE ( "failed to create API service" , err ) return 254 } v1alpha . RegisterPublicAPIServer ( publicServer , v1AlphaAPIServer ) for _ , l := range listeners { defer l . Close ( ) go publicServer . Serve ( l ) } stderr . Printf ( "API service running" ) <- exitCh stderr . Print ( "API service exiting..." ) return }
Open one or more listening sockets then start the gRPC server
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 .
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 ( "failed to create shutdown service" ) , err ) return } opts = append ( opts , [ ] * unit . UnitOption { unit . NewUnitOption ( "Service" , "StandardInput" , "null" ) , unit . NewUnitOption ( "Service" , "StandardOutput" , "null" ) , unit . NewUnitOption ( "Service" , "StandardError" , "null" ) , } ... ) shutdownVerb := "exit" if flavor != "coreos" && systemdVersion != 0 && systemdVersion < 227 { shutdownVerb = "halt" } opts = append ( opts , unit . NewUnitOption ( "Service" , exec , fmt . Sprintf ( "/usr/bin/systemctl --force %s" , shutdownVerb ) ) , ) uw . WriteUnit ( ServiceUnitPath ( uw . p . Root , "shutdown" ) , "failed to create shutdown service" , opts ... , ) }
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 .
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 ( "failed to link service want" ) , err ) } }
Activate actives the given unit in the given wantPath .
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 ) opts = append ( opts , [ ] * unit . UnitOption { unit . NewUnitOption ( "Unit" , "Description" , fmt . Sprintf ( "Application=%v Image=%v" , appName , imgName ) ) , unit . NewUnitOption ( "Unit" , "DefaultDependencies" , "false" ) , unit . NewUnitOption ( "Unit" , "Wants" , fmt . Sprintf ( "reaper-%s.service" , appName ) ) , unit . NewUnitOption ( "Service" , "Restart" , "no" ) , unit . NewUnitOption ( "Service" , "SyslogIdentifier" , appName ) , } ... ) opts = append ( opts , uw . SetupAppIO ( uw . p , ra , binPath ) ... ) if supportsNotify ( uw . p , ra . Name . String ( ) ) { opts = append ( opts , unit . NewUnitOption ( "Service" , "Type" , "notify" ) ) } opts = append ( opts , unit . NewUnitOption ( "Service" , "TimeoutStartSec" , "0" ) ) opts = append ( opts , unit . NewUnitOption ( "Unit" , "Requires" , "sysusers.service" ) ) opts = append ( opts , unit . NewUnitOption ( "Unit" , "After" , "sysusers.service" ) ) opts = uw . appSystemdUnit ( pa , binPath , opts ) uw . WriteUnit ( ServiceUnitPath ( uw . p . Root , ra . Name ) , "failed to create service unit file" , opts ... ) uw . Activate ( ServiceUnitName ( ra . Name ) , ServiceWantPath ( uw . p . Root , ra . Name ) ) }
AppUnit sets up the main systemd service unit for the application .
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 ( "Unit" , "Description" , fmt . Sprintf ( "%s Reaper" , appName ) ) , unit . NewUnitOption ( "Unit" , "DefaultDependencies" , "false" ) , unit . NewUnitOption ( "Unit" , "StopWhenUnneeded" , "yes" ) , unit . NewUnitOption ( "Unit" , "Before" , "halt.target" ) , unit . NewUnitOption ( "Unit" , "Conflicts" , "exit.target" ) , unit . NewUnitOption ( "Unit" , "Conflicts" , "halt.target" ) , unit . NewUnitOption ( "Unit" , "Conflicts" , "poweroff.target" ) , unit . NewUnitOption ( "Service" , "RemainAfterExit" , "yes" ) , unit . NewUnitOption ( "Service" , "ExecStop" , fmt . Sprintf ( "/reaper.sh \"%s\" \"%s\" \"%s\"" , \" , \" , \" , ) ) , } ... ) \" }
AppReaperUnit writes an app reaper service unit for the given app in the given path using the given unit options .
88
func ( uw * UnitWriter ) AppSocketUnit ( appName types . ACName , binPath string , streamName string , opts ... * unit . UnitOption ) { opts = append ( opts , [ ] * unit . UnitOption { unit . NewUnitOption ( "Unit" , "Description" , fmt . Sprintf ( "%s socket for %s" , streamName , appName ) ) , unit . NewUnitOption ( "Unit" , "DefaultDependencies" , "no" ) , unit . NewUnitOption ( "Unit" , "StopWhenUnneeded" , "yes" ) , unit . NewUnitOption ( "Unit" , "RefuseManualStart" , "yes" ) , unit . NewUnitOption ( "Unit" , "RefuseManualStop" , "yes" ) , unit . NewUnitOption ( "Unit" , "BindsTo" , fmt . Sprintf ( "%s.service" , appName ) ) , unit . NewUnitOption ( "Socket" , "RemoveOnStop" , "yes" ) , unit . NewUnitOption ( "Socket" , "Service" , fmt . Sprintf ( "%s.service" , appName ) ) , unit . NewUnitOption ( "Socket" , "FileDescriptorName" , streamName ) , unit . NewUnitOption ( "Socket" , "ListenFIFO" , filepath . Join ( "/rkt/iottymux" , appName . String ( ) , "stage2-" + streamName ) ) , } ... ) uw . WriteUnit ( TypedUnitPath ( uw . p . Root , appName . String ( ) + "-" + streamName , "socket" ) , fmt . Sprintf ( "failed to write %s socket for %q service" , streamName , appName ) , opts ... , ) }
AppSocketUnits writes a stream socket - unit for the given app in the given path .
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 ( "%s%s" , 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 .
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 .
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 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 , } ) } if err := appState ( app , pod ) ; err != nil { return nil , fmt . Errorf ( "error getting app's state: %v" , err ) } return app , nil }
newApp constructs the App object with the runtime app and pod manifest .
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 { 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 } 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
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 .
94
func LoadPodManifest ( root string ) ( * schema . PodManifest , error ) { buf , err := ioutil . ReadFile ( common . PodManifestPath ( root ) ) if err != nil { return nil , errwrap . Wrap ( errors . New ( "failed reading pod manifest" ) , err ) } pm := & schema . PodManifest { } if err := json . Unmarshal ( buf , pm ) ; err != nil { return nil , errwrap . Wrap ( errors . New ( "failed unmarshalling pod manifest" ) , err ) } return pm , nil }
LoadPodManifest loads a Pod Manifest .
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
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 } } if common . SupportsOverlay ( ) == nil && os . Geteuid ( ) == 0 { if _ , _ , err := f . Ts . Render ( hash , false ) ; err != nil { return nil , errwrap . Wrap ( errors . New ( "error rendering tree store" ) , err ) } } h , err := types . NewHash ( hash ) if err != nil { log . PanicE ( "invalid hash" , 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 .
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
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 .
99
func ( l * Logger ) Error ( e error ) { l . Print ( l . formatErr ( e , "" ) ) }
Error is a convenience function for printing errors without a message .
End of preview. Expand in Data Studio

No dataset card yet

Downloads last month
10