idx int64 0 167k | question stringlengths 64 85.5k | 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 t... | 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" ) ... | 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 . Unmarsha... | 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 ) ... | 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 ( [ ] activeNe... | 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 ni... | 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 " + nam... | 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... | 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 = t... | 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 ( ) { foun... | 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"
} els... | 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, ... | 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" , "... | 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... | 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... | 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]/]IMAG... | 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 . ... | 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 : ret... | 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... | 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" ... | 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 discove... | 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 ... | 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 { ins... | 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 ( )
}
} ( )
... | 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
... | 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 { cas... | 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" ) , er... | 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 ne... | 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 ... | 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 )
}
... | 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 ( share... | 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" ,... | 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 ... | 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 ... | 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 ( lk... | 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 ( "pars... | 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 , }... | 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 .... | 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 , ... | 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 ==... | 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 : ap... | 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 . AppContainerVers... | 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 . UUI... | 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 . Imag... | 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 ( im... | 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
}
i... | 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
}
de... | 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 (... | 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... | 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"... | 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 ( ... | 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 . UserLabe... | 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 . ... | 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 ... | 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 n... | 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 . Wit... | 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 ( )
... | 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
- 2