idx
int64
0
167k
question
stringlengths
60
3.56k
target
stringlengths
5
1.43k
len_question
int64
21
889
len_target
int64
3
529
167,000
func ( f * httpFetcher ) Hash ( u * url . URL , a * asc ) ( string , error ) { ensureLogger ( f . Debug ) urlStr := u . String ( ) if ! f . NoCache && f . Rem != nil { if useCached ( f . Rem . DownloadTime , f . Rem . CacheMaxAge ) { diag . Printf ( " " , urlStr ) return f . Rem . BlobKey , nil } } diag . Printf ( " " , urlStr ) aciFile , cd , err := f . fetchURL ( u , a , eTag ( f . Rem ) ) if err != nil { return " " , err } defer aciFile . Close ( ) if key := maybeUseCached ( f . Rem , cd ) ; key != " " { // TODO(krnowak): that does not update the store with // the new CacheMaxAge and Download Time, so it will // query the server every time after initial // CacheMaxAge is exceeded return key , nil } key , err := f . S . WriteACI ( aciFile , imagestore . ACIFetchInfo { Latest : false , } ) if err != nil { return " " , err } // TODO(krnowak): What's the point of the second parameter? // The SigURL field in imagestore.Remote seems to be completely // unused. newRem := imagestore . NewRemote ( urlStr , a . Location ) newRem . BlobKey = key newRem . DownloadTime = time . Now ( ) if cd != nil { newRem . ETag = cd . ETag newRem . CacheMaxAge = cd . MaxAge } err = f . S . WriteRemote ( newRem ) if err != nil { return " " , err } return key , nil }
Hash fetches the URL optionally verifies it against passed asc stores it in the store and returns the hash .
392
22
167,001
func addMountsStage0 ( p * stage1types . Pod , ra * schema . RuntimeApp , enterCmd [ ] string ) error { sharedVolPath , err := common . CreateSharedVolumesPath ( p . Root ) if err != nil { return err } vols := make ( map [ types . ACName ] types . Volume ) for _ , v := range p . Manifest . Volumes { vols [ v . Name ] = v } imageManifest := p . Images [ ra . Name . String ( ) ] mounts , err := stage1init . GenerateMounts ( ra , p . Manifest . Volumes , stage1init . ConvertedFromDocker ( imageManifest ) ) if err != nil { return errwrap . Wrapf ( " " , err ) } absRoot , err := filepath . Abs ( p . Root ) if err != nil { return errwrap . Wrapf ( " " , err ) } appRootfs := common . AppRootfsPath ( absRoot , ra . Name ) // This logic is mostly copied from appToNspawnArgs // TODO(cdc): deduplicate for _ , m := range mounts { shPath := filepath . Join ( sharedVolPath , m . Volume . Name . String ( ) ) // Evaluate symlinks within the app's rootfs - otherwise absolute // symlinks will be wrong. mntPath , err := stage1init . EvaluateSymlinksInsideApp ( appRootfs , m . Mount . Path ) if err != nil { return errwrap . Wrap ( fmt . Errorf ( " " , m . Mount . Path ) , err ) } // Create the stage1 destination if err := stage1init . PrepareMountpoints ( shPath , filepath . Join ( appRootfs , mntPath ) , & m . Volume , m . DockerImplicit ) ; err != nil { return errwrap . Wrapf ( " " , err ) } err = addMountStage0 ( p , ra , & m , mntPath , enterCmd ) if err != nil { return errwrap . Wrap ( fmt . Errorf ( " " , m . Mount . Volume , m . Mount . Path ) , err ) } } return nil }
addMountStage0 iterates over all requested mounts and bind mounts them to the stage2 rootfs .
469
21
167,002
func ( p * playground ) Cleanup ( ) error { if err := os . Remove ( p . playground ) ; err != nil { return err } if err := p . mnt . Unmount ( p . tmpDir , 0 ) ; err != nil { return err } return os . Remove ( p . tmpDir ) }
Cleanup cleans up the playground . It removes it unmounts the parent directory and removes the unmounted directory .
68
23
167,003
func ShiftFiles ( filesToShift [ ] string , uidRange * UidRange ) error { if uidRange . Shift != 0 && uidRange . Count != 0 { for _ , f := range filesToShift { if err := os . Chown ( f , int ( uidRange . Shift ) , int ( uidRange . Shift ) ) ; err != nil { return err } } } return nil }
ShiftFiles shifts filesToshift by the amounts specified in uidRange
89
15
167,004
func ( f * nameFetcher ) Hash ( app * discovery . App , a * asc ) ( string , error ) { ensureLogger ( f . Debug ) name := app . Name . String ( ) diag . Printf ( " " , name ) ep , err := f . discoverApp ( app ) if err != nil { return " " , errwrap . Wrap ( fmt . Errorf ( " " , name ) , err ) } latest := false // No specified version label, mark it as latest if _ , ok := app . Labels [ " " ] ; ! ok { latest = true } return f . fetchImageFromEndpoints ( app , ep , a , latest ) }
Hash runs the discovery fetches the image optionally verifies it against passed asc stores it in the store and returns the hash .
146
25
167,005
func ( cfg * MountCfg ) Opts ( ) string { opts := fmt . Sprintf ( " " , sanitize ( cfg . Lower ) , sanitize ( cfg . Upper ) , sanitize ( cfg . Work ) , ) return label . FormatMountLabel ( opts , cfg . Lbl ) }
Opts returns options for mount system call .
74
9
167,006
func Mount ( cfg * MountCfg ) error { err := syscall . Mount ( " " , cfg . Dest , " " , 0 , cfg . Opts ( ) ) if err != nil { const text = " " return errwrap . Wrap ( fmt . Errorf ( text , cfg . Opts ( ) , cfg . Dest ) , err ) } return nil }
Mount mounts the upper and lower directories to the destination directory . The MountCfg struct supplies information required to build the mount system call .
84
27
167,007
func ( l * FileLock ) TryExclusiveLock ( ) error { err := syscall . Flock ( l . fd , syscall . LOCK_EX | syscall . LOCK_NB ) if err == syscall . EWOULDBLOCK { err = ErrLocked } return err }
TryExclusiveLock takes an exclusive lock without blocking . This is idempotent when the Lock already represents an exclusive lock and tries promote a shared lock to exclusive atomically . It will return ErrLocked if any lock is already held .
68
49
167,008
func ( l * FileLock ) ExclusiveLock ( ) error { return syscall . Flock ( l . fd , syscall . LOCK_EX ) }
ExclusiveLock takes an exclusive lock . This is idempotent when the Lock already represents an exclusive lock and promotes a shared lock to exclusive atomically . It will block if an exclusive lock is already held .
36
43
167,009
func ( l * FileLock ) Unlock ( ) error { return syscall . Flock ( l . fd , syscall . LOCK_UN ) }
Unlock unlocks the lock
35
5
167,010
func ( l * FileLock ) Fd ( ) ( int , error ) { var err error if l . fd == - 1 { err = errors . New ( " " ) } return l . fd , err }
Fd returns the lock s file descriptor or an error if the lock is closed
47
16
167,011
func ( l * FileLock ) Close ( ) error { fd := l . fd l . fd = - 1 return syscall . Close ( fd ) }
Close closes the lock which implicitly unlocks it as well
37
10
167,012
func NewLock ( path string , lockType LockType ) ( * FileLock , error ) { l := & FileLock { path : path , fd : - 1 } mode := syscall . O_RDONLY | syscall . O_CLOEXEC if lockType == Dir { mode |= syscall . O_DIRECTORY } lfd , err := syscall . Open ( l . path , mode , 0 ) if err != nil { if err == syscall . ENOENT { err = ErrNotExist } else if err == syscall . EACCES { err = ErrPermission } return nil , err } l . fd = lfd var stat syscall . Stat_t err = syscall . Fstat ( lfd , & stat ) if err != nil { return nil , err } // Check if the file is a regular file if lockType == RegFile && ! ( stat . Mode & syscall . S_IFMT == syscall . S_IFREG ) { return nil , ErrNotRegular } return l , nil }
NewLock opens a new lock on a file without acquisition
236
11
167,013
func goGetArgs ( args [ ] string ) ( string , string , string , goDepsMode ) { f , target := standardFlags ( goCmd ) repo := f . String ( " " , " " , " " ) module := f . String ( " " , " " , " " ) mode := f . String ( " " , " " , " " ) f . Parse ( args ) if * repo == " " { common . Die ( " " ) } if * module == " " { common . Die ( " " ) } var dMode goDepsMode switch * mode { case " " : dMode = goMakeMode if * target == " " { common . Die ( " " ) } case " " : dMode = goFilesMode default : common . Die ( " " , * mode ) } return * target , * repo , * module , dMode }
getArgs parses given parameters and returns target repo module and mode . If mode is files then target is optional .
187
23
167,014
func goGetPackageDeps ( repo , module string ) [ ] string { dir , deps := goGetDeps ( repo , module ) return goGetFiles ( dir , deps ) }
goGetPackageDeps returns a list of files that are used to build a module in a given repo .
41
22
167,015
func goGetDeps ( repo , module string ) ( string , [ ] string ) { pkg := path . Join ( repo , module ) rawTuples := goRun ( goList ( [ ] string { " " , " " } , [ ] string { pkg } ) ) if len ( rawTuples ) != 1 { common . Die ( " " ) } tuple := goSliceRawTuple ( rawTuples [ 0 ] ) dir := tuple [ 0 ] if module != " " { dirsToStrip := 1 + strings . Count ( module , " " ) for i := 0 ; i < dirsToStrip ; i ++ { dir = filepath . Dir ( dir ) } } dir = filepath . Clean ( dir ) deps := goSliceRawSlice ( tuple [ 1 ] ) return dir , append ( [ ] string { pkg } , deps ... ) }
goGetDeps gets the directory of a given repo and the all dependencies direct or indirect of a given module in the repo .
192
26
167,016
func goGetFiles ( dir string , pkgs [ ] string ) [ ] string { params := [ ] string { " " , " " , " " , } var allFiles [ ] string rawTuples := goRun ( goList ( params , pkgs ) ) for _ , raw := range rawTuples { tuple := goSliceRawTuple ( raw ) moduleDir := filepath . Clean ( tuple [ 0 ] ) dirSep := fmt . Sprintf ( " " , dir , filepath . Separator ) moduleDirSep := fmt . Sprintf ( " " , moduleDir , filepath . Separator ) if ! strings . HasPrefix ( moduleDirSep , dirSep ) { continue } relModuleDir , err := filepath . Rel ( dir , moduleDir ) if err != nil { common . Die ( " " , moduleDir , dir ) } files := append ( goSliceRawSlice ( tuple [ 1 ] ) , goSliceRawSlice ( tuple [ 2 ] ) ... ) for i := 0 ; i < len ( files ) ; i ++ { files [ i ] = filepath . Join ( relModuleDir , files [ i ] ) } allFiles = append ( allFiles , files ... ) } return allFiles }
goGetFiles returns a list of files that are in given packages . File paths are relative to a given directory .
268
23
167,017
func goRun ( argv [ ] string ) [ ] string { cmd := exec . Command ( argv [ 0 ] , argv [ 1 : ] ... ) stdout := new ( bytes . Buffer ) stderr := new ( bytes . Buffer ) cmd . Stdout = stdout cmd . Stderr = stderr if err := cmd . Run ( ) ; err != nil { common . Die ( " " , strings . Join ( argv , " " ) , err , stderr . String ( ) ) } rawLines := strings . Split ( stdout . String ( ) , " \n " ) lines := make ( [ ] string , 0 , len ( rawLines ) ) for _ , line := range rawLines { if trimmed := strings . TrimSpace ( line ) ; trimmed != " " { lines = append ( lines , trimmed ) } } return lines }
goRun executes given argument list and captures its output . The output is sliced into lines with empty lines being discarded .
189
23
167,018
func goSliceRawSlice ( s string ) [ ] string { s = strings . TrimPrefix ( s , " " ) s = strings . TrimSuffix ( s , " " ) s = strings . TrimSpace ( s ) if s == " " { return nil } a := strings . Split ( s , " " ) return a }
goSliceRawSlice slices given string representation of a slice into slice of strings .
77
18
167,019
func ConvertedFromDocker ( im * schema . ImageManifest ) bool { if im == nil { // nil sometimes sneaks in here due to unit tests return false } ann := im . Annotations _ , ok := ann . Get ( " " ) return ok }
ConvertedFromDocker determines if an app s image has been converted from docker . This is needed because implicit docker empty volumes have different behavior from AppC
54
31
167,020
func ( m * Mount ) Source ( podRoot string ) string { switch m . Volume . Kind { case " " : return m . Volume . Source case " " : return filepath . Join ( common . SharedVolumesPath ( podRoot ) , m . Volume . Name . String ( ) ) } return " " // We validate in GenerateMounts that it's valid }
Source computes the real volume source for a volume . Volumes of type empty use a workdir relative to podRoot
79
24
167,021
func GenerateMounts ( ra * schema . RuntimeApp , podVolumes [ ] types . Volume , convertedFromDocker bool ) ( [ ] Mount , error ) { app := ra . App var genMnts [ ] Mount vols := make ( map [ types . ACName ] types . Volume ) for _ , v := range podVolumes { vols [ v . Name ] = v } // RuntimeApps have mounts, whereas Apps have mountPoints. mountPoints are partially for // Docker compat; since apps can declare mountpoints. However, if we just run with rkt run, // then we'll only have a Mount and no corresponding MountPoint. // Furthermore, Mounts can have embedded volumes in the case of the CRI. // So, we generate a pile of Mounts and their corresponding Volume // Map of hostpath -> Mount mnts := make ( map [ string ] schema . Mount ) // Check runtimeApp's Mounts for _ , m := range ra . Mounts { mnts [ m . Path ] = m vol := m . AppVolume // Mounts can supply a volume if vol == nil { vv , ok := vols [ m . Volume ] if ! ok { return nil , fmt . Errorf ( " " , m . Volume ) } vol = & vv } // Find a corresponding MountPoint, which is optional ro := false for _ , mp := range ra . App . MountPoints { if mp . Name == m . Volume { ro = mp . ReadOnly break } } if vol . ReadOnly != nil { ro = * vol . ReadOnly } switch vol . Kind { case " " : case " " : default : return nil , fmt . Errorf ( " " , vol . Name , vol . Kind ) } genMnts = append ( genMnts , Mount { Mount : m , DockerImplicit : false , ReadOnly : ro , Volume : * vol , } ) } // Now, match up MountPoints with Mounts or Volumes // If there's no Mount and no Volume, generate an empty volume for _ , mp := range app . MountPoints { // there's already a Mount for this MountPoint, stop if _ , ok := mnts [ mp . Path ] ; ok { continue } // No Mount, try to match based on volume name vol , ok := vols [ mp . Name ] // there is no volume for this mount point, creating an "empty" volume // implicitly if ! ok { defaultMode := " " defaultUID := 0 defaultGID := 0 uniqName := ra . Name + " " + mp . Name emptyVol := types . Volume { Name : uniqName , Kind : " " , Mode : & defaultMode , UID : & defaultUID , GID : & defaultGID , } log . Printf ( " \" \" " , mp . Name ) if convertedFromDocker { log . Printf ( " " , mp . Name ) } vols [ uniqName ] = emptyVol genMnts = append ( genMnts , Mount { Mount : schema . Mount { Volume : uniqName , Path : mp . Path , } , Volume : emptyVol , ReadOnly : mp . ReadOnly , DockerImplicit : convertedFromDocker , } ) } else { ro := mp . ReadOnly if vol . ReadOnly != nil { ro = * vol . ReadOnly } genMnts = append ( genMnts , Mount { Mount : schema . Mount { Volume : vol . Name , Path : mp . Path , } , Volume : vol , ReadOnly : ro , DockerImplicit : false , } ) } } return genMnts , nil }
GenerateMounts maps MountPoint paths to volumes returning a list of mounts each with a parameter indicating if it s an implicit empty volume from a Docker image .
772
32
167,022
func EnsureTargetExists ( source , destination string ) error { fileInfo , err := os . Stat ( source ) if err != nil { return errwrap . Wrap ( fmt . Errorf ( " " , source ) , err ) } targetPathParent , _ := filepath . Split ( destination ) if err := os . MkdirAll ( targetPathParent , common . SharedVolumePerm ) ; err != nil { return errwrap . Wrap ( fmt . Errorf ( " " , targetPathParent ) , err ) } if fileInfo . IsDir ( ) { if err := os . Mkdir ( destination , common . SharedVolumePerm ) ; err != nil && ! os . IsExist ( err ) { return errwrap . Wrap ( errors . New ( " " + destination ) , err ) } } else { if file , err := os . OpenFile ( destination , os . O_CREATE , common . SharedVolumePerm ) ; err != nil { return errwrap . Wrap ( errors . New ( " " ) , err ) } else { file . Close ( ) } } return nil }
EnsureTargetExists will recursively create a given mountpoint . If directories are created their permissions are initialized to common . SharedVolumePerm
232
30
167,023
func ( o * httpOps ) DownloadSignature ( a * asc ) ( readSeekCloser , bool , error ) { ensureLogger ( o . Debug ) diag . Printf ( " " , a . Location ) ascFile , err := a . Get ( ) if err == nil { return ascFile , false , nil } if _ , ok := err . ( * statusAcceptedError ) ; ok { log . Printf ( " " ) return NopReadSeekCloser ( nil ) , true , nil } return nil , false , errwrap . Wrap ( errors . New ( " " ) , err ) }
DownloadSignature takes an asc instance and tries to get the signature . If the remote server asked to to defer the download this function will return true and no error and no file .
133
36
167,024
func ( o * httpOps ) DownloadSignatureAgain ( a * asc ) ( readSeekCloser , error ) { ensureLogger ( o . Debug ) ascFile , retry , err := o . DownloadSignature ( a ) if err != nil { return nil , err } if retry { return nil , fmt . Errorf ( " " ) } return ascFile , nil }
DownloadSignatureAgain does a similar thing to DownloadSignature but it expects the signature to be actually provided that is - no deferring this time .
82
30
167,025
func ( o * httpOps ) DownloadImage ( u * url . URL ) ( readSeekCloser , * cacheData , error ) { ensureLogger ( o . Debug ) image , cd , err := o . DownloadImageWithETag ( u , " " ) if err != nil { return nil , nil , err } if cd . UseCached { return nil , nil , fmt . Errorf ( " " ) } return image , cd , nil }
DownloadImage download the image duh . It expects to actually receive the file instead of being asked to use the cached version .
97
25
167,026
func ( o * httpOps ) DownloadImageWithETag ( u * url . URL , etag string ) ( readSeekCloser , * cacheData , error ) { var aciFile * removeOnClose // closed on error var errClose error // error signaling to close aciFile ensureLogger ( o . Debug ) aciFile , err := getTmpROC ( o . S , u . String ( ) ) if err != nil { return nil , nil , err } defer func ( ) { if errClose != nil { aciFile . Close ( ) } } ( ) session := o . getSession ( u , aciFile . File , " " , etag ) dl := o . getDownloader ( session ) errClose = dl . Download ( u , aciFile . File ) if errClose != nil { return nil , nil , errwrap . Wrap ( errors . New ( " " ) , errClose ) } if session . Cd . UseCached { aciFile . Close ( ) return NopReadSeekCloser ( nil ) , session . Cd , nil } return aciFile , session . Cd , nil }
DownloadImageWithETag might download an image or tell you to use the cached image . In the latter case the returned file will be nil .
249
29
167,027
func ( o * httpOps ) AscRemoteFetcher ( ) * remoteAscFetcher { ensureLogger ( o . Debug ) f := func ( u * url . URL , file * os . File ) error { switch u . Scheme { case " " , " " : default : return fmt . Errorf ( " " , " " , u . Scheme ) } session := o . getSession ( u , file , " " , " " ) dl := o . getDownloader ( session ) err := dl . Download ( u , file ) if err != nil { return err } if session . Cd . UseCached { return fmt . Errorf ( " " , u . String ( ) ) } return nil } return & remoteAscFetcher { F : f , S : o . S , } }
AscRemoteFetcher provides a remoteAscFetcher for asc .
176
17
167,028
func actionAttach ( statusPath string , autoMode bool ) error { var endpoints Targets dialTimeout := 15 * time . Second // retrieve available endpoints statusFile , err := os . OpenFile ( statusPath , os . O_RDONLY , os . ModePerm ) if err != nil { return err } err = json . NewDecoder ( statusFile ) . Decode ( & endpoints ) _ = statusFile . Close ( ) if err != nil { return err } // retrieve custom attaching modes customTargets := struct { ttyIn bool ttyOut bool stdin bool stdout bool stderr bool } { } if ! autoMode { customTargets . ttyIn , _ = strconv . ParseBool ( os . Getenv ( " " ) ) customTargets . ttyOut , _ = strconv . ParseBool ( os . Getenv ( " " ) ) customTargets . stdin , _ = strconv . ParseBool ( os . Getenv ( " " ) ) customTargets . stdout , _ = strconv . ParseBool ( os . Getenv ( " " ) ) customTargets . stderr , _ = strconv . ParseBool ( os . Getenv ( " " ) ) } // Proxy I/O between this process and the iottymux service: // - input (stdin, tty-in) copying routines can only be canceled by process killing (ie. user detaching) // - output (stdout, stderr, tty-out) copying routines are canceled by errors when reading from remote service c := make ( chan error ) copyOut := func ( w io . Writer , conn net . Conn ) { _ , err := io . Copy ( w , conn ) c <- err } for _ , ep := range endpoints . Targets { d := net . Dialer { Timeout : dialTimeout } conn , err := d . Dial ( ep . Domain , ep . Address ) if err != nil { return err } defer conn . Close ( ) switch ep . Name { case " " : if autoMode || customTargets . stdin { go io . Copy ( conn , os . Stdin ) } case " " : if autoMode || customTargets . stdout { go copyOut ( os . Stdout , conn ) } case " " : if autoMode || customTargets . stderr { go copyOut ( os . Stderr , conn ) } case " " : if autoMode || customTargets . ttyIn { go io . Copy ( conn , os . Stdin ) } if autoMode || customTargets . ttyOut { go copyOut ( os . Stdout , conn ) } else { go copyOut ( ioutil . Discard , conn ) } } } // as soon as one output copying routine fails, this unblocks and the whole process exits return <- c }
actionAttach handles the attach action either in automatic or custom endpoints mode .
635
15
167,029
func dispatchSig ( stop chan <- error ) { sigChan := make ( chan os . Signal ) signal . Notify ( sigChan , syscall . SIGTERM , syscall . SIGHUP , syscall . SIGINT , ) go func ( ) { diag . Println ( " " ) sig := <- sigChan diag . Printf ( " \n " , sig ) close ( stop ) } ( ) }
dispatchSig launches a goroutine and closes the given stop channel when SIGTERM SIGHUP or SIGINT is received .
95
27
167,030
func bufferLine ( src io . Reader , c chan <- [ ] byte , ec chan <- error ) { rd := bufio . NewReader ( src ) for { lineOut , err := rd . ReadBytes ( '\n' ) if len ( lineOut ) > 0 { c <- lineOut } if err != nil { ec <- err } } }
bufferLine buffers and queues a single line from a Reader to a multiplexer If reading from src fails it hard - fails and propagates the error back .
78
32
167,031
func acceptConn ( socket net . Listener , c chan <- net . Conn , stream string ) { for { conn , err := socket . Accept ( ) if err == nil { diag . Printf ( " \n " , stream ) c <- conn } } }
acceptConn accepts a single client and queues it for further proxying It is never canceled explicitly as it is bound to the lifetime of the main process .
57
30
167,032
func muxInput ( clients <- chan net . Conn , stdin * os . File ) { for { select { case c := <- clients : go bufferInput ( c , stdin ) } } }
muxInput accepts remote clients and multiplex input line from them
43
13
167,033
func bufferInput ( conn net . Conn , stdin * os . File ) { rd := bufio . NewReader ( conn ) defer conn . Close ( ) for { lineIn , err := rd . ReadBytes ( '\n' ) if len ( lineIn ) == 0 && err != nil { return } _ , err = stdin . Write ( lineIn ) if err != nil { return } } }
bufferInput buffers and write a single line from a remote client to the local app
88
16
167,034
func muxOutput ( streamLabel string , lines chan [ ] byte , clients <- chan net . Conn , targets <- chan io . WriteCloser ) { var logs [ ] io . WriteCloser var conns [ ] io . WriteCloser writeAndFilter := func ( wc io . WriteCloser , line [ ] byte ) bool { _ , err := wc . Write ( line ) if err != nil { wc . Close ( ) } return err != nil } logsWriteAndFilter := func ( wc io . WriteCloser , line [ ] byte ) bool { out := [ ] byte ( fmt . Sprintf ( " " , time . Now ( ) . Format ( time . RFC3339Nano ) , streamLabel , line ) ) return writeAndFilter ( wc , out ) } for { select { // an incoming output line to multiplex // TODO(lucab): ordered non-blocking writes case l := <- lines : conns = filterTargets ( conns , l , writeAndFilter ) logs = filterTargets ( logs , l , logsWriteAndFilter ) // a new remote client case c := <- clients : conns = append ( conns , c ) // a new local log target case t := <- targets : logs = append ( logs , t ) } } }
muxOutput receives remote clients and local log targets multiplexing output lines to them
281
17
167,035
func filterTargets ( wcs [ ] io . WriteCloser , line [ ] byte , filter func ( io . WriteCloser , [ ] byte ) bool , ) [ ] io . WriteCloser { var filteredTargets [ ] io . WriteCloser for _ , c := range wcs { if ! filter ( c , line ) { filteredTargets = append ( filteredTargets , c ) } } return filteredTargets }
filterTargets passes line to each writer in wcs filtering out single writers if filter returns true .
97
21
167,036
func New ( config * Config ) * Keystore { if config == nil { config = defaultConfig } return & Keystore { config } }
New returns a new Keystore based on config .
29
10
167,037
func CheckSignature ( prefix string , signed , signature io . ReadSeeker ) ( * openpgp . Entity , error ) { ks := New ( defaultConfig ) return checkSignature ( ks , prefix , signed , signature ) }
CheckSignature is a convenience method for creating a Keystore with a default configuration and invoking CheckSignature .
51
22
167,038
func ( ks * Keystore ) DeleteTrustedKeyPrefix ( prefix , fingerprint string ) error { acidentifier , err := types . NewACIdentifier ( prefix ) if err != nil { return err } return os . Remove ( path . Join ( ks . LocalPrefixPath , acidentifier . String ( ) , fingerprint ) ) }
DeleteTrustedKeyPrefix deletes the prefix trusted key identified by fingerprint .
74
16
167,039
func ( ks * Keystore ) MaskTrustedKeySystemPrefix ( prefix , fingerprint string ) ( string , error ) { acidentifier , err := types . NewACIdentifier ( prefix ) if err != nil { return " " , err } dst := path . Join ( ks . LocalPrefixPath , acidentifier . String ( ) , fingerprint ) if err := ioutil . WriteFile ( dst , [ ] byte ( " " ) , 0644 ) ; err != nil { return " " , err } if err := os . Chmod ( dst , 0644 ) ; err != nil { return " " , err } return dst , nil }
MaskTrustedKeySystemPrefix masks the system prefix trusted key identified by fingerprint .
140
17
167,040
func ( ks * Keystore ) DeleteTrustedKeyRoot ( fingerprint string ) error { return os . Remove ( path . Join ( ks . LocalRootPath , fingerprint ) ) }
DeleteTrustedKeyRoot deletes the root trusted key identified by fingerprint .
39
15
167,041
func ( ks * Keystore ) MaskTrustedKeySystemRoot ( fingerprint string ) ( string , error ) { dst := path . Join ( ks . LocalRootPath , fingerprint ) if err := ioutil . WriteFile ( dst , [ ] byte ( " " ) , 0644 ) ; err != nil { return " " , err } if err := os . Chmod ( dst , 0644 ) ; err != nil { return " " , err } return dst , nil }
MaskTrustedKeySystemRoot masks the system root trusted key identified by fingerprint .
102
16
167,042
func ( ks * Keystore ) TrustedKeyPrefixExists ( prefix string ) ( bool , error ) { acidentifier , err := types . NewACIdentifier ( prefix ) if err != nil { return false , err } pathNamesPrefix := [ ] string { // example: /etc/rkt/trustedkeys/prefix.d/coreos.com/etcd path . Join ( ks . LocalPrefixPath , acidentifier . String ( ) ) , // example: /usr/lib/rkt/trustedkeys/prefix.d/coreos.com/etcd path . Join ( ks . SystemPrefixPath , acidentifier . String ( ) ) , } for _ , p := range pathNamesPrefix { _ , err := os . Stat ( p ) if os . IsNotExist ( err ) { continue } if err != nil { return false , errwrap . Wrap ( fmt . Errorf ( " " , p ) , err ) } files , err := ioutil . ReadDir ( p ) if err != nil { return false , errwrap . Wrap ( fmt . Errorf ( " " , p ) , err ) } for _ , f := range files { if ! f . IsDir ( ) && f . Size ( ) > 0 { return true , nil } } } parentPrefix , _ := path . Split ( prefix ) parentPrefix = strings . Trim ( parentPrefix , " " ) if parentPrefix != " " { return ks . TrustedKeyPrefixExists ( parentPrefix ) } return false , nil }
TrustKeyPrefixExists returns whether or not there exists 1 or more trusted keys for a given prefix or for any parent prefix .
343
27
167,043
func ( ks * Keystore ) TrustedKeyPrefixWithFingerprintExists ( prefix string , r io . ReadSeeker ) ( bool , error ) { defer r . Seek ( 0 , os . SEEK_SET ) entityList , err := openpgp . ReadArmoredKeyRing ( r ) if err != nil { return false , err } if len ( entityList ) < 1 { return false , errors . New ( " " ) } pubKey := entityList [ 0 ] . PrimaryKey fileName := fingerprintToFilename ( pubKey . Fingerprint ) pathNamesRoot := [ ] string { // example: /etc/rkt/trustedkeys/root.d/8b86de38890ddb7291867b025210bd8888182190 path . Join ( ks . LocalRootPath , fileName ) , // example: /usr/lib/rkt/trustedkeys/root.d/8b86de38890ddb7291867b025210bd8888182190 path . Join ( ks . SystemRootPath , fileName ) , } var pathNamesPrefix [ ] string if prefix != " " { acidentifier , err := types . NewACIdentifier ( prefix ) if err != nil { return false , err } pathNamesPrefix = [ ] string { // example: /etc/rkt/trustedkeys/prefix.d/coreos.com/etcd/8b86de38890ddb7291867b025210bd8888182190 path . Join ( ks . LocalPrefixPath , acidentifier . String ( ) , fileName ) , // example: /usr/lib/rkt/trustedkeys/prefix.d/coreos.com/etcd/8b86de38890ddb7291867b025210bd8888182190 path . Join ( ks . SystemPrefixPath , acidentifier . String ( ) , fileName ) , } } pathNames := append ( pathNamesRoot , pathNamesPrefix ... ) for _ , p := range pathNames { _ , err := os . Stat ( p ) if err == nil { return true , nil } else if ! os . IsNotExist ( err ) { return false , errwrap . Wrap ( fmt . Errorf ( " " , p ) , err ) } } return false , nil }
TrustedKeyPrefixWithFingerprintExists returns whether or not a trusted key with the fingerprint of the key accessible through r exists for the given prefix .
507
33
167,044
func ( ks * Keystore ) StoreTrustedKeyPrefix ( prefix string , r io . Reader ) ( string , error ) { acidentifier , err := types . NewACIdentifier ( prefix ) if err != nil { return " " , err } return storeTrustedKey ( path . Join ( ks . LocalPrefixPath , acidentifier . String ( ) ) , r ) }
StoreTrustedKeyPrefix stores the contents of public key r as a prefix trusted key .
85
19
167,045
func ( ks * Keystore ) StoreTrustedKeyRoot ( r io . Reader ) ( string , error ) { return storeTrustedKey ( ks . LocalRootPath , r ) }
StoreTrustedKeyRoot stores the contents of public key r as a root trusted key .
41
18
167,046
func ( s String ) ConditionalHas ( conditionFunc func ( source , item string ) bool , item string ) bool { for source := range s { if conditionFunc ( source , item ) { return true } } return false }
ConditionalHas returns true if and only if there is any item source in the set that satisfies the conditionFunc wrt item .
49
27
167,047
func RelEnvFilePath ( appName types . ACName ) string { return filepath . Join ( envDir , appName . String ( ) ) }
RelEnvFilePath returns the path to the environment file for the given app name relative to the pod s root .
33
24
167,048
func EnvFilePath ( root string , appName types . ACName ) string { return filepath . Join ( common . Stage1RootfsPath ( root ) , RelEnvFilePath ( appName ) ) }
EnvFilePath returns the path to the environment file for the given app name .
46
17
167,049
func IOMuxDir ( root string , appName types . ACName ) string { return filepath . Join ( common . Stage1RootfsPath ( root ) , ioMuxDir , appName . String ( ) ) }
IOMUxFilePath returns the path to the environment file for the given app name .
48
19
167,050
func ServiceWantPath ( root string , appName types . ACName ) string { return filepath . Join ( common . Stage1RootfsPath ( root ) , defaultWantsDir , ServiceUnitName ( appName ) ) }
ServiceWantPath returns the systemd default . target want symlink path for the given app name .
48
20
167,051
func InstantiatedPrepareAppUnitName ( appName types . ACName ) string { // Naming respecting escaping rules, see systemd.unit(5) and systemd-escape(1) escapedRoot := unit . UnitNamePathEscape ( common . RelAppRootfsPath ( appName ) ) return " " + escapedRoot + " " }
InstantiatedPrepareAppUnitName returns the systemd service unit name for prepare - app instantiated for the given root .
72
24
167,052
func SocketUnitPath ( root string , appName types . ACName ) string { return filepath . Join ( common . Stage1RootfsPath ( root ) , UnitsDir , SocketUnitName ( appName ) ) }
SocketUnitPath returns the path to the systemd socket file for the given app name .
46
17
167,053
func SocketWantPath ( root string , appName types . ACName ) string { return filepath . Join ( common . Stage1RootfsPath ( root ) , socketsWantsDir , SocketUnitName ( appName ) ) }
SocketWantPath returns the systemd sockets . target . wants symlink path for the given app name .
48
21
167,054
func TypedUnitPath ( root string , unitName string , unitType string ) string { return filepath . Join ( common . Stage1RootfsPath ( root ) , UnitsDir , unitName + " " + unitType ) }
TypedUnitPath returns the path to a custom - typed unit file
49
14
167,055
func NewACIArchive ( u * url . URL ) ( Distribution , error ) { c , err := parseCIMD ( u ) if err != nil { return nil , fmt . Errorf ( " " , u . String ( ) , err ) } if c . Type != TypeACIArchive { return nil , fmt . Errorf ( " " , c . Type ) } // This should be a valid URL data , err := url . QueryUnescape ( c . Data ) if err != nil { return nil , errwrap . Wrap ( fmt . Errorf ( " " , c . Data ) , err ) } aciu , err := url . Parse ( data ) if err != nil { return nil , errwrap . Wrap ( fmt . Errorf ( " " , c . Data ) , err ) } // save the URI as sorted to make it ready for comparison purell . NormalizeURL ( u , purell . FlagSortQuery ) str := u . String ( ) if path := aciu . String ( ) ; filepath . Ext ( path ) == schema . ACIExtension { str = path } return & ACIArchive { cimdURL : u , transportURL : aciu , str : str , } , nil }
NewACIArchive creates a new aci - archive distribution from the provided distribution uri .
266
20
167,056
func ( a * ACIArchive ) TransportURL ( ) * url . URL { // Create a copy of the transport URL tu , err := url . Parse ( a . transportURL . String ( ) ) if err != nil { panic ( fmt . Errorf ( " " , err ) ) } return tu }
TransportURL returns a copy of the transport URL .
66
11
167,057
func MountGC ( path , uuid string ) error { err := common . ChrootPrivateUnmount ( path , log , debug ) if err != nil { return errwrap . Wrap ( fmt . Errorf ( " " , uuid ) , err ) } return nil }
MountGC removes mounts from pods that couldn t be GCed cleanly .
57
15
167,058
func matchUUID ( dataDir , uuid string ) ( [ ] string , error ) { if uuid == " " { return nil , types . ErrNoEmptyUUID } ls , err := listPods ( dataDir , IncludeMostDirs ) if err != nil { return nil , err } var matches [ ] string for _ , p := range ls { if strings . HasPrefix ( p , uuid ) { matches = append ( matches , p ) } } return matches , nil }
matchUUID attempts to match the uuid specified as uuid against all pods present . An array of matches is returned which may be empty when nothing matches .
105
32
167,059
func resolveUUID ( dataDir , uuid string ) ( * types . UUID , error ) { uuid = strings . ToLower ( uuid ) m , err := matchUUID ( dataDir , uuid ) if err != nil { return nil , err } if len ( m ) == 0 { return nil , fmt . Errorf ( " " , uuid ) } if len ( m ) > 1 { return nil , fmt . Errorf ( " " , len ( m ) ) } u , err := types . NewUUID ( m [ 0 ] ) if err != nil { return nil , errwrap . Wrap ( errors . New ( " " ) , err ) } return u , nil }
resolveUUID attempts to resolve the uuid specified as uuid against all pods present . An unambiguously matched uuid or nil is returned .
149
31
167,060
func ReadUUIDFromFile ( path string ) ( string , error ) { uuid , err := ioutil . ReadFile ( path ) if err != nil { return " " , err } return string ( bytes . TrimSpace ( uuid ) ) , nil }
ReadUUIDFromFile reads the uuid string from the given path .
57
15
167,061
func WriteUUIDToFile ( uuid * types . UUID , path string ) error { return ioutil . WriteFile ( path , [ ] byte ( uuid . String ( ) ) , 0644 ) }
WriteUUIDToFile writes the uuid string to the given path .
46
15
167,062
func Setup ( podRoot string , podID types . UUID , fps [ ] commonnet . ForwardedPort , netList common . NetList , localConfig , flavor string , noDNS , debug bool ) ( * Networking , error ) { stderr = log . New ( os . Stderr , " " , debug ) debuglog = debug if flavor == " " { return kvmSetup ( podRoot , podID , fps , netList , localConfig , noDNS ) } // TODO(jonboulle): currently podRoot is _always_ ".", and behaviour in other // circumstances is untested. This should be cleaned up. n := Networking { podEnv : podEnv { podRoot : podRoot , podID : podID , netsLoadList : netList , localConfig : localConfig , } , } err := n . mountNetnsDirectory ( ) if err != nil { return nil , err } // Create the network namespace (and save its name in a file) err = n . podNSCreate ( ) if err != nil { return nil , err } n . nets , err = n . loadNets ( ) if err != nil { return nil , errwrap . Wrap ( errors . New ( " " ) , err ) } if err := n . setupNets ( n . nets , noDNS ) ; err != nil { return nil , err } if len ( fps ) > 0 { if err = n . enableDefaultLocalnetRouting ( ) ; err != nil { return nil , err } podIP , err := n . GetForwardableNetPodIP ( ) if err != nil { return nil , err } if err := n . setupForwarding ( ) ; err != nil { n . teardownForwarding ( ) return nil , err } if err := n . forwardPorts ( fps , podIP ) ; err != nil { n . teardownForwarding ( ) return nil , err } } // Switch to the podNS if err := n . podNS . Set ( ) ; err != nil { return nil , err } if err = loUp ( ) ; err != nil { return nil , err } return & n , nil }
Setup creates a new networking namespace and executes network plugins to set up networking . It returns in the new pod namespace
468
22
167,063
func ( n * Networking ) enableDefaultLocalnetRouting ( ) error { routeLocalnetFormat := " " defaultHostIP , err := n . GetForwardableNetHostIP ( ) if err != nil { return err } defaultHostIPstring := defaultHostIP . String ( ) switch { case strings . Contains ( defaultHostIPstring , " " ) : routeLocalnetFormat = " " case strings . Contains ( defaultHostIPstring , " " ) : return fmt . Errorf ( " " , defaultHostIPstring ) default : return fmt . Errorf ( " " , defaultHostIPstring ) } hostIfaces , err := n . GetIfacesByIP ( defaultHostIP ) if err != nil { return err } for _ , hostIface := range hostIfaces { routeLocalnetPath := fmt . Sprintf ( routeLocalnetFormat , hostIface . Name ) routeLocalnetValue , err := ioutil . ReadFile ( routeLocalnetPath ) if err != nil { return err } if strings . TrimSpace ( string ( routeLocalnetValue ) ) != " " { routeLocalnetFile , err := os . OpenFile ( routeLocalnetPath , os . O_WRONLY , 0 ) if err != nil { return err } defer routeLocalnetFile . Close ( ) if _ , err = io . WriteString ( routeLocalnetFile , " " ) ; err != nil { return err } } } return nil }
enableDefaultLocalnetRouting enables the route_localnet attribute on the supposedly default network interface . This allows setting up loopback NAT so the host can access the pod s forwarded ports on the localhost address .
308
43
167,064
func Load ( podRoot string , podID * types . UUID , localConfig string ) ( * Networking , error ) { // the current directory is pod root pdirfd , err := syscall . Open ( podRoot , syscall . O_RDONLY | syscall . O_DIRECTORY , 0 ) if err != nil { return nil , errwrap . Wrap ( fmt . Errorf ( " " , podRoot ) , err ) } defer syscall . Close ( pdirfd ) nis , err := netinfo . LoadAt ( pdirfd ) if err != nil { return nil , err } var nets [ ] activeNet for _ , ni := range nis { n , err := loadNet ( ni . ConfPath ) if err != nil { if ! os . IsNotExist ( err ) { stderr . PrintE ( fmt . Sprintf ( " " , ni . ConfPath ) , err ) } continue } // make a copy of ni to make it a unique object as it's saved via ptr rti := ni n . runtime = & rti nets = append ( nets , * n ) } p := podEnv { podRoot : podRoot , podID : * podID , localConfig : localConfig , } err = p . podNSLoad ( ) if err != nil { return nil , err } return & Networking { podEnv : p , nets : nets , } , nil }
Load creates the Networking object from saved state . Assumes the current netns is that of the host .
308
22
167,065
func ( n * Networking ) GetIfacesByIP ( ifaceIP net . IP ) ( [ ] net . Interface , error ) { ifaces , err := net . Interfaces ( ) if err != nil { return nil , err } searchAddr := strings . Split ( ifaceIP . String ( ) , " " ) [ 0 ] resultInterfaces := make ( [ ] net . Interface , 0 ) for _ , iface := range ifaces { if iface . Flags & net . FlagLoopback != 0 { continue } addrs , err := iface . Addrs ( ) if err != nil { return nil , errwrap . Wrap ( fmt . Errorf ( " " , iface . Name ) , err ) } for _ , addr := range addrs { currentAddr := strings . Split ( addr . String ( ) , " " ) [ 0 ] if searchAddr == currentAddr { resultInterfaces = append ( resultInterfaces , iface ) break } } } if len ( resultInterfaces ) == 0 { return nil , fmt . Errorf ( " " , ifaceIP ) } return resultInterfaces , nil }
GetIfacesByIP searches for and returns the interfaces with the given IP Disregards the subnet mask since not every net . IP object contains On success it will return the list of found interfaces
243
40
167,066
func ( n * Networking ) Teardown ( flavor string , debug bool ) { stderr = log . New ( os . Stderr , " " , debug ) debuglog = debug // Teardown everything in reverse order of setup. // This should be idempotent -- be tolerant of missing stuff if flavor == " " { n . kvmTeardown ( ) return } if err := n . teardownForwarding ( ) ; err != nil { stderr . PrintE ( " " , err ) } err := n . podNSLoad ( ) if err != nil { stderr . PrintE ( " " , err ) } n . teardownNets ( n . nets ) n . podNSDestroy ( ) }
Teardown cleans up a produced Networking object .
160
11
167,067
func ( e * Networking ) Save ( ) error { if e . podNS != nil { if err := e . podNSPathSave ( ) ; err != nil { return err } } var nis [ ] netinfo . NetInfo for _ , n := range e . nets { nis = append ( nis , * n . runtime ) } return netinfo . Save ( e . podRoot , nis ) }
Save writes out the info about active nets for rkt list and friends to display
90
16
167,068
func CleanUpGarbage ( podRoot string , podID * types . UUID ) error { p := podEnv { podRoot : podRoot , podID : * podID , } err := p . podNSLoad ( ) if err != nil { return err } return p . podNSDestroy ( ) }
CleanUpGarbage can be called when Load fails but there may still be some garbage lying around . Right now this deletes the namespace .
66
28
167,069
func ( a * asc ) Get ( ) ( readSeekCloser , error ) { if a . Fetcher != nil { return a . Fetcher . Get ( a . Location ) } return NopReadSeekCloser ( nil ) , nil }
Get fetches a signature file . It returns nil and no error if there was no fetcher set .
54
21
167,070
func ( f * Finder ) FindImages ( al * apps . Apps ) error { return al . Walk ( func ( app * apps . App ) error { h , err := f . FindImage ( app . Image , app . Asc ) if err != nil { return err } app . ImageID = * h return nil } ) }
FindImages uses FindImage to attain a list of image hashes
69
12
167,071
func ( f * Finder ) FindImage ( img string , asc string ) ( * types . Hash , error ) { ensureLogger ( f . Debug ) // Check if it's an hash if _ , err := types . NewHash ( img ) ; err == nil { h , err := f . getHashFromStore ( img ) if err != nil { return nil , err } return h , nil } d , err := DistFromImageString ( img ) if err != nil { return nil , err } // urls, names, paths have to be fetched, potentially remotely ft := ( * Fetcher ) ( f ) h , err := ft . FetchImage ( d , img , asc ) if err != nil { return nil , err } return h , nil }
FindImage tries to get a hash of a passed image ideally from store . Otherwise this might involve fetching it from remote with the Fetcher .
161
29
167,072
func fileAccessible ( path string ) bool { if info , err := os . Stat ( path ) ; err == nil { return info . Mode ( ) . IsRegular ( ) } return false }
fileAccessible checks if the given path exists and is a regular file
41
14
167,073
func generateKeyPair ( private string ) error { out , err := exec . Command ( " " , " " , // silence " " , " " , // type " " , " " , // length in bits " " , private , // output file " " , " " , // no passphrase ) . Output ( ) if err != nil { // out is in form of bytes buffer and we have to turn it into slice ending on first \0 occurrence return fmt . Errorf ( " " , err , string ( out [ : ] ) ) } return nil }
generateKeyPair calls ssh - keygen with private key location for key generation purpose
118
18
167,074
func ( m * Mount ) NeedsRemountPrivate ( ) bool { for _ , key := range [ ] string { " " , " " , } { if _ , needsRemount := m . Opts [ key ] ; needsRemount { return true } } return false }
NeedsRemountPrivate checks if this mountPoint needs to be remounted as private in order for children to be properly unmounted without leaking to parents .
58
32
167,075
func ( ms Mounts ) Filter ( f FilterFunc ) Mounts { filtered := make ( [ ] * Mount , 0 , len ( ms ) ) for _ , m := range ms { if f ( m ) { filtered = append ( filtered , m ) } } return Mounts ( filtered ) }
Filter returns a filtered copy of Mounts
63
8
167,076
func ( ms Mounts ) mountDepth ( i int ) int { ancestorCount := 0 current := ms [ i ] for found := true ; found ; { found = false for _ , mnt := range ms { if mnt . ID == current . Parent { ancestorCount ++ current = mnt found = true break } } } return ancestorCount }
mountDepth determines and returns the number of ancestors of the mount at index i
72
15
167,077
func NewBitFlags ( permissibleOptions [ ] string , defaultOptions string , flagMap map [ string ] int ) ( * BitFlags , error ) { ol , err := NewOptionList ( permissibleOptions , defaultOptions ) if err != nil { return nil , err } bf := & BitFlags { OptionList : ol , FlagMap : flagMap , } bf . typeName = " " if err := bf . Set ( defaultOptions ) ; err != nil { return nil , errwrap . Wrap ( errors . New ( " " ) , err ) } return bf , nil }
NewBitFlags initializes a simple bitflag version of the OptionList Type . flagMap is the mapping from option names to the integer value
123
28
167,078
func parseList ( scanner * bufio . Scanner , count int ) ( [ ] string , error ) { got := 0 items := make ( [ ] string , 0 , count ) for { if ! scanner . Scan ( ) { if err := scanner . Err ( ) ; err != nil { return nil , err } return nil , fmt . Errorf ( " " ) } line := scanner . Text ( ) if line == " " { if got < count { return nil , fmt . Errorf ( " " , count , got ) } break } got ++ if got > count { return nil , fmt . Errorf ( " " , count ) } items = append ( items , line ) } return items , nil }
parseList parses the list part of a block . It makes sure that there is an exactly expected count of items .
149
24
167,079
func ( list * Lists ) GenerateFilelist ( out io . Writer ) error { w := bufio . NewWriter ( out ) for _ , pair := range list . getPairs ( ) { dLen := len ( * pair . data ) toWrite := [ ] string { pair . kind , " \n " , strconv . Itoa ( dLen ) , " \n " , } if dLen > 0 { toWrite = append ( toWrite , strings . Join ( * pair . data , " \n " ) , " \n " ) } toWrite = append ( toWrite , " \n " ) for _ , str := range toWrite { if _ , err := w . WriteString ( str ) ; err != nil { return err } } } w . Flush ( ) return nil }
GenerateFilelist generates a filelist duh . And writes it to a given writer . The format of generated file is described in filelist . ParseFilelist .
172
35
167,080
func GenerateFileDeps ( target , filesGenerator string , files [ ] string ) string { return replacePlaceholders ( fileDepMkTemplate , " " , appName ( ) , " " , filesGenerator , " " , strings . Join ( files , " " ) , " " , target , ) }
GenerateFileDeps returns contents of make file describing dependencies of given target on given files and checking if files weren t added or removed in directories where given files are .
67
34
167,081
func MakeResolvConf ( dns cnitypes . DNS , comment string ) string { content := " " if len ( comment ) > 0 { content += fmt . Sprintf ( " \n \n " , comment ) } if len ( dns . Search ) > 0 { content += fmt . Sprintf ( " \n " , strings . Join ( dns . Search , " " ) ) } for _ , ns := range dns . Nameservers { content += fmt . Sprintf ( " \n " , ns ) } if len ( dns . Options ) > 0 { content += fmt . Sprintf ( " \n " , strings . Join ( dns . Options , " " ) ) } if len ( dns . Domain ) > 0 { content += fmt . Sprintf ( " \n " , dns . Domain ) } return content }
MakeResolvConf generates resolv . conf contents given a cni DNS configuration
184
18
167,082
func extractFileFromTar ( tr * tar . Reader , file string ) ( [ ] byte , error ) { for { hdr , err := tr . Next ( ) switch err { case io . EOF : return nil , fmt . Errorf ( " " ) case nil : if filepath . Clean ( hdr . Name ) != filepath . Clean ( file ) { continue } switch hdr . Typeflag { case tar . TypeReg : case tar . TypeRegA : default : return nil , fmt . Errorf ( " " ) } buf , err := ioutil . ReadAll ( tr ) if err != nil { return nil , err } return buf , nil default : return nil , err } } }
extractFileFromTar extracts a regular file from the given tar returning its contents as a byte slice
150
20
167,083
func ( n * Networking ) GetForwardableNet ( ) ( * activeNet , error ) { numberNets := len ( n . nets ) if numberNets == 0 { return nil , fmt . Errorf ( " " ) } for _ , net := range n . nets { if net . IPMasq ( ) { return & net , nil } } return & n . nets [ numberNets - 1 ] , nil }
GetForwardableNet iterates through all loaded networks and returns either the first network that has masquerading enabled or the last network in case there is no masqueraded one or an error if no network was loaded .
91
44
167,084
func ( e * podEnv ) setupForwarding ( ) error { ipt , err := iptables . New ( ) if err != nil { return err } // Create a separate chain for this pod. This helps with debugging // and makes it easier to cleanup chainDNAT := e . portFwdChain ( " " ) chainSNAT := e . portFwdChain ( " " ) if err = ipt . NewChain ( " " , chainDNAT ) ; err != nil { return err } if err = ipt . NewChain ( " " , chainSNAT ) ; err != nil { return err } chainRuleDNAT := e . portFwdChainRuleSpec ( chainDNAT , " " ) chainRuleSNAT := e . portFwdChainRuleSpec ( chainSNAT , " " ) for _ , entry := range [ ] struct { chain string customChainRule [ ] string } { { " " , chainRuleSNAT } , // traffic originating from this host from loopback { " " , chainRuleDNAT } , // outside traffic hitting this host { " " , chainRuleDNAT } , // traffic originating from this host on non-loopback } { exists , err := ipt . Exists ( " " , entry . chain , entry . customChainRule ... ) if err != nil { return err } if ! exists { err = ipt . Insert ( " " , entry . chain , 1 , entry . customChainRule ... ) if err != nil { return err } } } return nil }
setupForwarding creates the iptables chains
323
9
167,085
func KvmNetworkingToSystemd ( p * stage1commontypes . Pod , n * networking . Networking ) error { podRoot := common . Stage1RootfsPath ( p . Root ) // networking netDescriptions := kvm . GetNetworkDescriptions ( n ) if err := kvm . GenerateNetworkInterfaceUnits ( filepath . Join ( podRoot , stage1initcommon . UnitsDir ) , netDescriptions ) ; err != nil { return errwrap . Wrap ( errors . New ( " " ) , err ) } return nil }
KvmNetworkingToSystemd generates systemd unit files for a pod according to network configuration
121
18
167,086
func initPods ( dataDir string ) error { if ! podsInitialized { dirs := [ ] string { embryoDir ( dataDir ) , prepareDir ( dataDir ) , preparedDir ( dataDir ) , runDir ( dataDir ) , exitedGarbageDir ( dataDir ) , garbageDir ( dataDir ) } for _ , d := range dirs { if err := os . MkdirAll ( d , 0750 ) ; err != nil { return errwrap . Wrap ( errors . New ( " " ) , err ) } } podsInitialized = true } return nil }
initPods creates the required global directories
121
8
167,087
func ( p * Pod ) embryoPath ( ) string { return filepath . Join ( embryoDir ( p . dataDir ) , p . UUID . String ( ) ) }
embryoPath returns the path to the pod where it would be in the embryoDir in its embryonic state .
37
23
167,088
func ( p * Pod ) preparePath ( ) string { return filepath . Join ( prepareDir ( p . dataDir ) , p . UUID . String ( ) ) }
preparePath returns the path to the pod where it would be in the prepareDir in its preparing state .
37
22
167,089
func ( p * Pod ) preparedPath ( ) string { return filepath . Join ( preparedDir ( p . dataDir ) , p . UUID . String ( ) ) }
preparedPath returns the path to the pod where it would be in the preparedDir .
37
18
167,090
func ( p * Pod ) runPath ( ) string { return filepath . Join ( runDir ( p . dataDir ) , p . UUID . String ( ) ) }
runPath returns the path to the pod where it would be in the runDir .
37
17
167,091
func ( p * Pod ) exitedGarbagePath ( ) string { return filepath . Join ( exitedGarbageDir ( p . dataDir ) , p . UUID . String ( ) ) }
exitedGarbagePath returns the path to the pod where it would be in the exitedGarbageDir .
41
22
167,092
func ( p * Pod ) garbagePath ( ) string { return filepath . Join ( garbageDir ( p . dataDir ) , p . UUID . String ( ) ) }
garbagePath returns the path to the pod where it would be in the garbageDir .
37
18
167,093
func ( p * Pod ) ToExitedGarbage ( ) error { if ! p . isExited || p . isExitedGarbage { return fmt . Errorf ( " " ) } if err := os . Rename ( p . runPath ( ) , p . exitedGarbagePath ( ) ) ; err != nil { // TODO(vc): another case where we could race with a concurrent ToExitedGarbage(), let caller deal with the error. return err } df , err := os . Open ( exitedGarbageDir ( p . dataDir ) ) if err != nil { return err } defer df . Close ( ) if err := df . Sync ( ) ; err != nil { return err } p . isExitedGarbage = true return nil }
ToExitedGarbage transitions a pod from run - > exitedGarbage This method refreshes the pod state .
162
23
167,094
func ( p * Pod ) ToGarbage ( ) error { if ! p . isAbortedPrepare && ! p . isPrepared { return fmt . Errorf ( " " ) } if err := os . Rename ( p . Path ( ) , p . garbagePath ( ) ) ; err != nil { return err } df , err := os . Open ( garbageDir ( p . dataDir ) ) if err != nil { return err } defer df . Close ( ) if err := df . Sync ( ) ; err != nil { return err } p . isAbortedPrepare = false p . isPrepared = false p . isGarbage = true return nil }
ToGarbage transitions a pod from abortedPrepared - > garbage or prepared - > garbage This method refreshes the pod state .
142
26
167,095
func listPods ( dataDir string , include IncludeMask ) ( [ ] string , error ) { // uniqued due to the possibility of a pod being renamed from across directories during the list operation ups := make ( map [ string ] struct { } ) dirs := [ ] struct { kind IncludeMask path string } { { // the order here is significant: embryo -> preparing -> prepared -> running -> exitedGarbage kind : IncludeEmbryoDir , path : embryoDir ( dataDir ) , } , { kind : IncludePrepareDir , path : prepareDir ( dataDir ) , } , { kind : IncludePreparedDir , path : preparedDir ( dataDir ) , } , { kind : IncludeRunDir , path : runDir ( dataDir ) , } , { kind : IncludeExitedGarbageDir , path : exitedGarbageDir ( dataDir ) , } , { kind : IncludeGarbageDir , path : garbageDir ( dataDir ) , } , } for _ , d := range dirs { if include & d . kind != 0 { ps , err := listPodsFromDir ( d . path ) if err != nil { return nil , err } for _ , p := range ps { ups [ p ] = struct { } { } } } } ps := make ( [ ] string , 0 , len ( ups ) ) for p := range ups { ps = append ( ps , p ) } return ps , nil }
listPods returns a list of pod uuids in string form .
302
15
167,096
func listPodsFromDir ( cdir string ) ( [ ] string , error ) { var ps [ ] string ls , err := ioutil . ReadDir ( cdir ) if err != nil { if os . IsNotExist ( err ) { return ps , nil } return nil , errwrap . Wrap ( errors . New ( " " ) , err ) } for _ , p := range ls { if ! p . IsDir ( ) { fmt . Fprintf ( os . Stderr , " " , p . Name ( ) ) continue } ps = append ( ps , p . Name ( ) ) } return ps , nil }
listPodsFromDir returns a list of pod uuids in string form from a specific directory .
135
21
167,097
func ( p * Pod ) readFile ( path string ) ( [ ] byte , error ) { f , err := p . openFile ( path , syscall . O_RDONLY ) if err != nil { return nil , err } defer f . Close ( ) return ioutil . ReadAll ( f ) }
readFile reads an entire file from a pod s directory .
68
12
167,098
func ( p * Pod ) readIntFromFile ( path string ) ( i int , err error ) { b , err := p . readFile ( path ) if err != nil { return } _ , err = fmt . Sscanf ( string ( b ) , " " , & i ) return }
readIntFromFile reads an int from a file in a pod s directory .
63
16
167,099
func ( p * Pod ) openFile ( path string , flags int ) ( * os . File , error ) { cdirfd , err := p . Fd ( ) if err != nil { return nil , err } fd , err := syscall . Openat ( cdirfd , path , flags , 0 ) if err != nil { return nil , err } return os . NewFile ( uintptr ( fd ) , path ) , nil }
openFile opens a file from a pod s directory returning a file descriptor .
96
15