idx
int64
0
252k
question
stringlengths
48
5.28k
target
stringlengths
5
1.23k
229,300
def to_xdr_amount ( value ) : if not isinstance ( value , str ) : raise NotValidParamError ( "Value of type '{}' must be of type String, but got {}" . format ( value , type ( value ) ) ) try : amount = int ( ( Decimal ( value ) * ONE ) . to_integral_exact ( context = Context ( traps = [ Inexact ] ) ) ) except decimal ....
Converts an amount to the appropriate value to send over the network as a part of an XDR object .
229,301
def to_xdr_object ( self ) : return Xdr . types . Memo ( type = Xdr . const . MEMO_TEXT , text = self . text )
Creates an XDR Memo object for a transaction with MEMO_TEXT .
229,302
def to_xdr_object ( self ) : return Xdr . types . Memo ( type = Xdr . const . MEMO_ID , id = self . memo_id )
Creates an XDR Memo object for a transaction with MEMO_ID .
229,303
def to_xdr_object ( self ) : return Xdr . types . Memo ( type = Xdr . const . MEMO_HASH , hash = self . memo_hash )
Creates an XDR Memo object for a transaction with MEMO_HASH .
229,304
def to_xdr_object ( self ) : return Xdr . types . Memo ( type = Xdr . const . MEMO_RETURN , retHash = self . memo_return )
Creates an XDR Memo object for a transaction with MEMO_RETURN .
229,305
def append_hashx_signer ( self , hashx , signer_weight , source = None ) : return self . append_set_options_op ( signer_address = hashx , signer_type = 'hashX' , signer_weight = signer_weight , source = source )
Add a HashX signer to an account .
229,306
def append_pre_auth_tx_signer ( self , pre_auth_tx , signer_weight , source = None ) : return self . append_set_options_op ( signer_address = pre_auth_tx , signer_type = 'preAuthTx' , signer_weight = signer_weight , source = source )
Add a PreAuthTx signer to an account .
229,307
def next_builder ( self ) : sequence = self . sequence + 1 next_builder = Builder ( horizon_uri = self . horizon . horizon_uri , address = self . address , network = self . network , sequence = sequence , fee = self . fee ) next_builder . keypair = self . keypair return next_builder
Create a new builder based off of this one with its sequence number incremented .
229,308
def get_sequence ( self ) : if not self . address : raise StellarAddressInvalidError ( 'No address provided.' ) address = self . horizon . account ( self . address ) return int ( address . get ( 'sequence' ) )
Get the sequence number for a given account via Horizon .
229,309
def to_dict ( self ) : rv = { 'code' : self . code } if not self . is_native ( ) : rv [ 'issuer' ] = self . issuer rv [ 'type' ] = self . type else : rv [ 'type' ] = 'native' return rv
Generate a dict for this object s attributes .
229,310
def id_unique ( dict_id , name , lineno ) : if dict_id in name_dict : global error_occurred error_occurred = True print ( "ERROR - {0:s} definition {1:s} at line {2:d} conflicts with {3:s}" . format ( name , dict_id , lineno , name_dict [ dict_id ] ) ) return False else : return True
Returns True if dict_id not already used . Otherwise invokes error
229,311
def main ( ) : import sys import argparse stdout = buffer ( sys . stdout ) parser = argparse . ArgumentParser ( description = main . __doc__ ) parser . add_argument ( 'file' , metavar = 'FILE' , nargs = '?' , type = argparse . FileType ( 'r' ) , default = '-' ) parser . add_argument ( '-d' , '--decode' , action = 'stor...
Base58 encode or decode FILE or standard input to standard output .
229,312
def _Dhcpcd ( self , interfaces , logger ) : for interface in interfaces : dhcpcd = [ '/sbin/dhcpcd' ] try : subprocess . check_call ( dhcpcd + [ '-x' , interface ] ) except subprocess . CalledProcessError : logger . info ( 'Dhcpcd not yet running for interface %s.' , interface ) try : subprocess . check_call ( dhcpcd ...
Use dhcpcd to activate the interfaces .
229,313
def _CreateTempDir ( prefix , run_dir = None ) : temp_dir = tempfile . mkdtemp ( prefix = prefix + '-' , dir = run_dir ) try : yield temp_dir finally : shutil . rmtree ( temp_dir )
Context manager for creating a temporary directory .
229,314
def _RunScripts ( self , run_dir = None ) : with _CreateTempDir ( self . script_type , run_dir = run_dir ) as dest_dir : try : self . logger . info ( 'Starting %s scripts.' , self . script_type ) script_dict = self . retriever . GetScripts ( dest_dir ) self . executor . RunScripts ( script_dict ) finally : self . logge...
Retrieve metadata scripts and execute them .
229,315
def _GetInstanceConfig ( self ) : try : instance_data = self . metadata_dict [ 'instance' ] [ 'attributes' ] except KeyError : instance_data = { } self . logger . warning ( 'Instance attributes were not found.' ) try : project_data = self . metadata_dict [ 'project' ] [ 'attributes' ] except KeyError : project_data = {...
Get the instance configuration specified in metadata .
229,316
def _GenerateSshKey ( self , key_type , key_dest ) : with tempfile . NamedTemporaryFile ( prefix = key_type , delete = True ) as temp : temp_key = temp . name command = [ 'ssh-keygen' , '-t' , key_type , '-f' , temp_key , '-N' , '' , '-q' ] try : self . logger . info ( 'Generating SSH key %s.' , key_dest ) subprocess ....
Generate a new SSH key .
229,317
def _StartSshd ( self ) : if os . path . exists ( constants . LOCALBASE + '/bin/systemctl' ) : return elif ( os . path . exists ( '/etc/init.d/ssh' ) or os . path . exists ( '/etc/init/ssh.conf' ) ) : subprocess . call ( [ 'service' , 'ssh' , 'start' ] ) subprocess . call ( [ 'service' , 'ssh' , 'reload' ] ) elif ( os ...
Initialize the SSH daemon .
229,318
def _SetSshHostKeys ( self , host_key_types = None ) : section = 'Instance' instance_id = self . _GetInstanceId ( ) if instance_id != self . instance_config . GetOptionString ( section , 'instance_id' ) : self . logger . info ( 'Generating SSH host keys for instance %s.' , instance_id ) file_regex = re . compile ( r'ss...
Regenerates SSH host keys when the VM is restarted with a new IP address .
229,319
def _SetupBotoConfig ( self ) : project_id = self . _GetNumericProjectId ( ) try : boto_config . BotoConfig ( project_id , debug = self . debug ) except ( IOError , OSError ) as e : self . logger . warning ( str ( e ) )
Set the boto config so GSUtil works with provisioned service accounts .
229,320
def _DownloadAuthUrl ( self , url , dest_dir ) : dest_file = tempfile . NamedTemporaryFile ( dir = dest_dir , delete = False ) dest_file . close ( ) dest = dest_file . name self . logger . info ( 'Downloading url from %s to %s using authentication token.' , url , dest ) if not self . token : response = self . watcher ....
Download a Google Storage URL using an authentication token .
229,321
def _DownloadUrl ( self , url , dest_dir ) : dest_file = tempfile . NamedTemporaryFile ( dir = dest_dir , delete = False ) dest_file . close ( ) dest = dest_file . name self . logger . info ( 'Downloading url from %s to %s.' , url , dest ) try : urlretrieve . urlretrieve ( url , dest ) return dest except ( httpclient ....
Download a script from a given URL .
229,322
def _DownloadScript ( self , url , dest_dir ) : if url . startswith ( r'gs://' ) : url = re . sub ( '^gs://' , 'https://storage.googleapis.com/' , url ) return self . _DownloadAuthUrl ( url , dest_dir ) header = r'http[s]?://' domain = r'storage\.googleapis\.com' bucket = r'(?P<bucket>[a-z0-9][-_.a-z0-9]*[a-z0-9])' obj...
Download the contents of the URL to the destination .
229,323
def _GetAttributeScripts ( self , attribute_data , dest_dir ) : script_dict = { } attribute_data = attribute_data or { } metadata_key = '%s-script' % self . script_type metadata_value = attribute_data . get ( metadata_key ) if metadata_value : self . logger . info ( 'Found %s in metadata.' , metadata_key ) with tempfil...
Retrieve the scripts from attribute metadata .
229,324
def GetScripts ( self , dest_dir ) : metadata_dict = self . watcher . GetMetadata ( ) or { } try : instance_data = metadata_dict [ 'instance' ] [ 'attributes' ] except KeyError : instance_data = None self . logger . warning ( 'Instance attributes were not found.' ) try : project_data = metadata_dict [ 'project' ] [ 'at...
Retrieve the scripts to execute .
229,325
def _MakeExecutable ( self , metadata_script ) : mode = os . stat ( metadata_script ) . st_mode os . chmod ( metadata_script , mode | stat . S_IEXEC )
Add executable permissions to a file .
229,326
def RunScripts ( self , script_dict ) : metadata_types = [ '%s-script-url' , '%s-script' ] metadata_keys = [ key % self . script_type for key in metadata_types ] metadata_keys = [ key for key in metadata_keys if script_dict . get ( key ) ] if not metadata_keys : self . logger . info ( 'No %s scripts found in metadata.'...
Run the metadata scripts ; execute a URL script first if one is provided .
229,327
def _AddHeader ( self , fp ) : text = textwrap . wrap ( textwrap . dedent ( self . config_header ) , break_on_hyphens = False ) fp . write ( '\n' . join ( [ '# ' + line for line in text ] ) ) fp . write ( '\n\n' )
Create a file header in the config .
229,328
def SetOption ( self , section , option , value , overwrite = True ) : if not overwrite and self . config . has_option ( section , option ) : return if not self . config . has_section ( section ) : self . config . add_section ( section ) self . config . set ( section , option , str ( value ) )
Set the value of an option in the config file .
229,329
def WriteConfig ( self , config_file = None ) : config_file = config_file or self . config_file config_name = os . path . splitext ( os . path . basename ( config_file ) ) [ 0 ] config_lock = ( '%s/lock/google_%s.lock' % ( constants . LOCALSTATEDIR , config_name ) ) with file_utils . LockFile ( config_lock ) : with ope...
Write the config values to a given file .
229,330
def Logger ( name , debug = False , facility = None ) : logger = logging . getLogger ( name ) logger . handlers = [ ] logger . addHandler ( logging . NullHandler ( ) ) logger . propagate = False logger . setLevel ( logging . DEBUG ) formatter = logging . Formatter ( name + ': %(levelname)s %(message)s' ) if debug : con...
Get a logging object with handlers for sending logs to SysLog .
229,331
def _CreateSudoersGroup ( self ) : if not self . _GetGroup ( self . google_sudoers_group ) : try : command = self . groupadd_cmd . format ( group = self . google_sudoers_group ) subprocess . check_call ( command . split ( ' ' ) ) except subprocess . CalledProcessError as e : self . logger . warning ( 'Could not create ...
Create a Linux group for Google added sudo user accounts .
229,332
def _AddUser ( self , user ) : self . logger . info ( 'Creating a new user account for %s.' , user ) command = self . useradd_cmd . format ( user = user ) try : subprocess . check_call ( command . split ( ' ' ) ) except subprocess . CalledProcessError as e : self . logger . warning ( 'Could not create user %s. %s.' , u...
Configure a Linux user account .
229,333
def _UpdateUserGroups ( self , user , groups ) : groups = ',' . join ( groups ) self . logger . debug ( 'Updating user %s with groups %s.' , user , groups ) command = self . usermod_cmd . format ( user = user , groups = groups ) try : subprocess . check_call ( command . split ( ' ' ) ) except subprocess . CalledProcess...
Update group membership for a Linux user .
229,334
def _UpdateAuthorizedKeys ( self , user , ssh_keys ) : pw_entry = self . _GetUser ( user ) if not pw_entry : return uid = pw_entry . pw_uid gid = pw_entry . pw_gid home_dir = pw_entry . pw_dir ssh_dir = os . path . join ( home_dir , '.ssh' ) authorized_keys_file = os . path . join ( ssh_dir , 'authorized_keys' ) if os ...
Update the authorized keys file for a Linux user with a list of SSH keys .
229,335
def _UpdateSudoer ( self , user , sudoer = False ) : if sudoer : self . logger . info ( 'Adding user %s to the Google sudoers group.' , user ) command = self . gpasswd_add_cmd . format ( user = user , group = self . google_sudoers_group ) else : self . logger . info ( 'Removing user %s from the Google sudoers group.' ,...
Update sudoer group membership for a Linux user account .
229,336
def _RemoveAuthorizedKeys ( self , user ) : pw_entry = self . _GetUser ( user ) if not pw_entry : return home_dir = pw_entry . pw_dir authorized_keys_file = os . path . join ( home_dir , '.ssh' , 'authorized_keys' ) if os . path . exists ( authorized_keys_file ) : try : os . remove ( authorized_keys_file ) except OSErr...
Remove a Linux user account s authorized keys file to prevent login .
229,337
def GetConfiguredUsers ( self ) : if os . path . exists ( self . google_users_file ) : users = open ( self . google_users_file ) . readlines ( ) else : users = [ ] return [ user . strip ( ) for user in users ]
Retrieve the list of configured Google user accounts .
229,338
def SetConfiguredUsers ( self , users ) : prefix = self . logger . name + '-' with tempfile . NamedTemporaryFile ( mode = 'w' , prefix = prefix , delete = True ) as updated_users : updated_users_file = updated_users . name for user in users : updated_users . write ( user + '\n' ) updated_users . flush ( ) if not os . p...
Set the list of configured Google user accounts .
229,339
def UpdateUser ( self , user , ssh_keys ) : if not bool ( USER_REGEX . match ( user ) ) : self . logger . warning ( 'Invalid user account name %s.' , user ) return False if not self . _GetUser ( user ) : if not ( self . _AddUser ( user ) and self . _UpdateUserGroups ( user , self . groups ) ) : return False if not self...
Update a Linux user with authorized SSH keys .
229,340
def RemoveUser ( self , user ) : self . logger . info ( 'Removing user %s.' , user ) if self . remove : command = self . userdel_cmd . format ( user = user ) try : subprocess . check_call ( command . split ( ' ' ) ) except subprocess . CalledProcessError as e : self . logger . warning ( 'Could not remove user %s. %s.' ...
Remove a Linux user account .
229,341
def _RunOsLoginControl ( self , params ) : try : return subprocess . call ( [ constants . OSLOGIN_CONTROL_SCRIPT ] + params ) except OSError as e : if e . errno == errno . ENOENT : return None else : raise
Run the OS Login control script .
229,342
def _GetStatus ( self , two_factor = False ) : params = [ 'status' ] if two_factor : params += [ '--twofactor' ] retcode = self . _RunOsLoginControl ( params ) if retcode is None : if self . oslogin_installed : self . logger . warning ( 'OS Login not installed.' ) self . oslogin_installed = False return None self . osl...
Check whether OS Login is installed .
229,343
def _RunOsLoginNssCache ( self ) : try : return subprocess . call ( [ constants . OSLOGIN_NSS_CACHE_SCRIPT ] ) except OSError as e : if e . errno == errno . ENOENT : return None else : raise
Run the OS Login NSS cache binary .
229,344
def _RemoveOsLoginNssCache ( self ) : if os . path . exists ( constants . OSLOGIN_NSS_CACHE ) : try : os . remove ( constants . OSLOGIN_NSS_CACHE ) except OSError as e : if e . errno != errno . ENOENT : raise
Remove the OS Login NSS cache file .
229,345
def UpdateOsLogin ( self , oslogin_desired , two_factor_desired = False ) : oslogin_configured = self . _GetStatus ( two_factor = False ) if oslogin_configured is None : return None two_factor_configured = self . _GetStatus ( two_factor = True ) two_factor_desired = two_factor_desired and oslogin_desired if oslogin_des...
Update whether OS Login is enabled and update NSS cache if necessary .
229,346
def CallDhclient ( interfaces , logger , dhclient_script = None ) : logger . info ( 'Enabling the Ethernet interfaces %s.' , interfaces ) dhclient_command = [ 'dhclient' ] if dhclient_script and os . path . exists ( dhclient_script ) : dhclient_command += [ '-sf' , dhclient_script ] try : subprocess . check_call ( dhcl...
Configure the network interfaces using dhclient .
229,347
def CallHwclock ( logger ) : command = [ '/sbin/hwclock' , '--hctosys' ] try : subprocess . check_call ( command ) except subprocess . CalledProcessError : logger . warning ( 'Failed to sync system time with hardware clock.' ) else : logger . info ( 'Synced system time with hardware clock.' )
Sync clock using hwclock .
229,348
def CallNtpdate ( logger ) : ntpd_inactive = subprocess . call ( [ 'service' , 'ntpd' , 'status' ] ) try : if not ntpd_inactive : subprocess . check_call ( [ 'service' , 'ntpd' , 'stop' ] ) subprocess . check_call ( 'ntpdate `awk \'$1=="server" {print $2}\' /etc/ntp.conf`' , shell = True ) if not ntpd_inactive : subpro...
Sync clock using ntpdate .
229,349
def _GetNumericProjectId ( self ) : project_id = 'project/numeric-project-id' return self . watcher . GetMetadata ( metadata_key = project_id , recursive = False )
Get the numeric project ID for this VM .
229,350
def _CreateConfig ( self , project_id ) : project_id = project_id or self . _GetNumericProjectId ( ) if not project_id : return self . boto_config_header %= ( self . boto_config_script , self . boto_config_template ) config = config_manager . ConfigManager ( config_file = self . boto_config_template , config_header = s...
Create the boto config to support standalone GSUtil .
229,351
def _CreateRouteOptions ( self , ** kwargs ) : options = { 'proto' : self . proto_id , 'scope' : 'host' , } options . update ( kwargs ) return options
Create a dictionary of parameters to append to the ip route command .
229,352
def _RunIpRoute ( self , args = None , options = None ) : args = args or [ ] options = options or { } command = [ 'ip' , 'route' ] command . extend ( args ) for item in options . items ( ) : command . extend ( item ) try : process = subprocess . Popen ( command , stdout = subprocess . PIPE , stderr = subprocess . PIPE ...
Run a command with ip route and return the response .
229,353
def RemoveForwardedIp ( self , address , interface ) : ip = netaddr . IPNetwork ( address ) self . _RunIfconfig ( args = [ interface , '-alias' , str ( ip . ip ) ] )
Delete an IP address on the network interface .
229,354
def _GetGsScopes ( self ) : service_accounts = self . watcher . GetMetadata ( metadata_key = self . metadata_key ) try : scopes = service_accounts [ self . service_account ] [ 'scopes' ] return list ( GS_SCOPES . intersection ( set ( scopes ) ) ) if scopes else None except KeyError : return None
Return all Google Storage scopes available on this VM .
229,355
def _GetAccessToken ( self ) : service_accounts = self . watcher . GetMetadata ( metadata_key = self . metadata_key ) try : return service_accounts [ self . service_account ] [ 'token' ] [ 'access_token' ] except KeyError : return None
Return an OAuth 2 . 0 access token for Google Storage .
229,356
def HandleClockSync ( self , response ) : self . logger . info ( 'Clock drift token has changed: %s.' , response ) self . distro_utils . HandleClockSync ( self . logger )
Called when clock drift token changes .
229,357
def _DisableNetworkManager ( self , interfaces , logger ) : for interface in interfaces : interface_config = os . path . join ( self . network_path , 'ifcfg-%s' % interface ) if os . path . exists ( interface_config ) : self . _ModifyInterface ( interface_config , 'DEVICE' , interface , replace = False ) self . _Modify...
Disable network manager management on a list of network interfaces .
229,358
def _ModifyInterface ( self , interface_config , config_key , config_value , replace = False ) : config_entry = '%s=%s' % ( config_key , config_value ) if not open ( interface_config ) . read ( ) . count ( config_key ) : with open ( interface_config , 'a' ) as config : config . write ( '%s\n' % config_entry ) elif repl...
Write a value to a config file if not already present .
229,359
def _HasExpired ( self , key ) : self . logger . debug ( 'Processing key: %s.' , key ) try : schema , json_str = key . split ( None , 3 ) [ 2 : ] except ( ValueError , AttributeError ) : self . logger . debug ( 'No schema identifier. Not expiring key.' ) return False if schema != 'google-ssh' : self . logger . debug ( ...
Check whether an SSH key has expired .
229,360
def _ParseAccountsData ( self , account_data ) : if not account_data : return { } lines = [ line for line in account_data . splitlines ( ) if line ] user_map = { } for line in lines : if not all ( ord ( c ) < 128 for c in line ) : self . logger . info ( 'SSH key contains non-ascii character: %s.' , line ) continue spli...
Parse the SSH key data into a user map .
229,361
def _GetInstanceAndProjectAttributes ( self , metadata_dict ) : metadata_dict = metadata_dict or { } try : instance_data = metadata_dict [ 'instance' ] [ 'attributes' ] except KeyError : instance_data = { } self . logger . warning ( 'Instance attributes were not found.' ) try : project_data = metadata_dict [ 'project' ...
Get dictionaries for instance and project attributes .
229,362
def _GetAccountsData ( self , metadata_dict ) : instance_data , project_data = self . _GetInstanceAndProjectAttributes ( metadata_dict ) valid_keys = [ instance_data . get ( 'sshKeys' ) , instance_data . get ( 'ssh-keys' ) ] block_project = instance_data . get ( 'block-project-ssh-keys' , '' ) . lower ( ) if block_proj...
Get the user accounts specified in metadata server contents .
229,363
def _UpdateUsers ( self , update_users ) : for user , ssh_keys in update_users . items ( ) : if not user or user in self . invalid_users : continue configured_keys = self . user_ssh_keys . get ( user , [ ] ) if set ( ssh_keys ) != set ( configured_keys ) : if not self . utils . UpdateUser ( user , ssh_keys ) : self . i...
Provision and update Linux user accounts based on account metadata .
229,364
def _RemoveUsers ( self , remove_users ) : for username in remove_users : self . utils . RemoveUser ( username ) self . user_ssh_keys . pop ( username , None ) self . invalid_users -= set ( remove_users )
Deprovision Linux user accounts that do not appear in account metadata .
229,365
def _GetEnableOsLoginValue ( self , metadata_dict ) : instance_data , project_data = self . _GetInstanceAndProjectAttributes ( metadata_dict ) instance_value = instance_data . get ( 'enable-oslogin' ) project_value = project_data . get ( 'enable-oslogin' ) value = instance_value or project_value or '' return value . lo...
Get the value of the enable - oslogin metadata key .
229,366
def HandleAccounts ( self , result ) : self . logger . debug ( 'Checking for changes to user accounts.' ) configured_users = self . utils . GetConfiguredUsers ( ) enable_oslogin = self . _GetEnableOsLoginValue ( result ) enable_two_factor = self . _GetEnableTwoFactorValue ( result ) if enable_oslogin : desired_users = ...
Called when there are changes to the contents of the metadata server .
229,367
def _SetSELinuxContext ( path ) : restorecon = '/sbin/restorecon' if os . path . isfile ( restorecon ) and os . access ( restorecon , os . X_OK ) : subprocess . call ( [ restorecon , path ] )
Set the appropriate SELinux context if SELinux tools are installed .
229,368
def SetPermissions ( path , mode = None , uid = None , gid = None , mkdir = False ) : if mkdir and not os . path . exists ( path ) : os . mkdir ( path , mode or 0o777 ) elif mode : os . chmod ( path , mode ) if uid and gid : os . chown ( path , uid , gid ) _SetSELinuxContext ( path )
Set the permissions and ownership of a path .
229,369
def Lock ( fd , path , blocking ) : operation = fcntl . LOCK_EX if blocking else fcntl . LOCK_EX | fcntl . LOCK_NB try : fcntl . flock ( fd , operation ) except IOError as e : if e . errno == errno . EWOULDBLOCK : raise IOError ( 'Exception locking %s. File already locked.' % path ) else : raise IOError ( 'Exception lo...
Lock the provided file descriptor .
229,370
def Unlock ( fd , path ) : try : fcntl . flock ( fd , fcntl . LOCK_UN | fcntl . LOCK_NB ) except IOError as e : if e . errno == errno . EWOULDBLOCK : raise IOError ( 'Exception unlocking %s. Locked by another process.' % path ) else : raise IOError ( 'Exception unlocking %s. %s.' % ( path , str ( e ) ) )
Release the lock on the file .
229,371
def LockFile ( path , blocking = False ) : fd = os . open ( path , os . O_CREAT ) try : Lock ( fd , path , blocking ) yield finally : try : Unlock ( fd , path ) finally : os . close ( fd )
Interface to flock - based file locking to prevent concurrent executions .
229,372
def RetryOnUnavailable ( func ) : @ functools . wraps ( func ) def Wrapper ( * args , ** kwargs ) : while True : try : response = func ( * args , ** kwargs ) except ( httpclient . HTTPException , socket . error , urlerror . URLError ) as e : time . sleep ( 5 ) if ( isinstance ( e , urlerror . HTTPError ) and e . getcod...
Function decorator to retry on a service unavailable exception .
229,373
def _GetMetadataRequest ( self , metadata_url , params = None , timeout = None ) : headers = { 'Metadata-Flavor' : 'Google' } params = urlparse . urlencode ( params or { } ) url = '%s?%s' % ( metadata_url , params ) request = urlrequest . Request ( url , headers = headers ) request_opener = urlrequest . build_opener ( ...
Performs a GET request with the metadata headers .
229,374
def _UpdateEtag ( self , response ) : etag = response . headers . get ( 'etag' , self . etag ) etag_updated = self . etag != etag self . etag = etag return etag_updated
Update the etag from an API response .
229,375
def _GetMetadataUpdate ( self , metadata_key = '' , recursive = True , wait = True , timeout = None ) : metadata_key = os . path . join ( metadata_key , '' ) if recursive else metadata_key metadata_url = os . path . join ( METADATA_SERVER , metadata_key ) params = { 'alt' : 'json' , 'last_etag' : self . etag , 'recursi...
Request the contents of metadata server and deserialize the response .
229,376
def _HandleMetadataUpdate ( self , metadata_key = '' , recursive = True , wait = True , timeout = None , retry = True ) : exception = None while True : try : return self . _GetMetadataUpdate ( metadata_key = metadata_key , recursive = recursive , wait = wait , timeout = timeout ) except ( httpclient . HTTPException , s...
Wait for a successful metadata response .
229,377
def WatchMetadata ( self , handler , metadata_key = '' , recursive = True , timeout = None ) : while True : response = self . _HandleMetadataUpdate ( metadata_key = metadata_key , recursive = recursive , wait = True , timeout = timeout ) try : handler ( response ) except Exception as e : self . logger . exception ( 'Ex...
Watch for changes to the contents of the metadata server .
229,378
def GetMetadata ( self , metadata_key = '' , recursive = True , timeout = None , retry = True ) : return self . _HandleMetadataUpdate ( metadata_key = metadata_key , recursive = recursive , wait = False , timeout = timeout , retry = retry )
Retrieve the contents of metadata server for a metadata key .
229,379
def _LogForwardedIpChanges ( self , configured , desired , to_add , to_remove , interface ) : if not to_add and not to_remove : return self . logger . info ( 'Changing %s IPs from %s to %s by adding %s and removing %s.' , interface , configured or None , desired or None , to_add or None , to_remove or None )
Log the planned IP address changes .
229,380
def _AddForwardedIps ( self , forwarded_ips , interface ) : for address in forwarded_ips : self . ip_forwarding_utils . AddForwardedIp ( address , interface )
Configure the forwarded IP address on the network interface .
229,381
def _RemoveForwardedIps ( self , forwarded_ips , interface ) : for address in forwarded_ips : self . ip_forwarding_utils . RemoveForwardedIp ( address , interface )
Remove the forwarded IP addresses from the network interface .
229,382
def HandleForwardedIps ( self , interface , forwarded_ips , interface_ip = None ) : desired = self . ip_forwarding_utils . ParseForwardedIps ( forwarded_ips ) configured = self . ip_forwarding_utils . GetForwardedIps ( interface , interface_ip ) to_add = sorted ( set ( desired ) - set ( configured ) ) to_remove = sorte...
Handle changes to the forwarded IPs on a network interface .
229,383
def _WriteIfcfg ( self , interfaces , logger ) : for interface in interfaces : interface_config = os . path . join ( self . network_path , 'ifcfg-%s' % interface ) interface_content = [ '# Added by Google.' , 'STARTMODE=hotplug' , 'BOOTPROTO=dhcp' , 'DHCLIENT_SET_DEFAULT_ROUTE=yes' , 'DHCLIENT_ROUTE_PRIORITY=10%s00' % ...
Write ifcfg files for multi - NIC support .
229,384
def _Ifup ( self , interfaces , logger ) : ifup = [ '/usr/sbin/wicked' , 'ifup' , '--timeout' , '1' ] try : subprocess . check_call ( ifup + interfaces ) except subprocess . CalledProcessError : logger . warning ( 'Could not activate interfaces %s.' , interfaces )
Activate network interfaces .
229,385
def HandleNetworkInterfaces ( self , result ) : network_interfaces = self . _ExtractInterfaceMetadata ( result ) if self . network_setup_enabled : self . network_setup . EnableNetworkInterfaces ( [ interface . name for interface in network_interfaces [ 1 : ] ] ) for interface in network_interfaces : if self . ip_forwar...
Called when network interface metadata changes .
229,386
def _ExtractInterfaceMetadata ( self , metadata ) : interfaces = [ ] for network_interface in metadata : mac_address = network_interface . get ( 'mac' ) interface = self . network_utils . GetNetworkInterface ( mac_address ) ip_addresses = [ ] if interface : ip_addresses . extend ( network_interface . get ( 'forwardedIp...
Extracts network interface metadata .
229,387
def _build_url ( self , query_params ) : url = '' count = 0 while count < len ( self . _url_path ) : url += '/{}' . format ( self . _url_path [ count ] ) count += 1 if self . append_slash : url += '/' if query_params : url_values = urlencode ( sorted ( query_params . items ( ) ) , True ) url = '{}?{}' . format ( url , ...
Build the final URL to be passed to urllib
229,388
def _build_client ( self , name = None ) : url_path = self . _url_path + [ name ] if name else self . _url_path return Client ( host = self . host , version = self . _version , request_headers = self . request_headers , url_path = url_path , append_slash = self . append_slash , timeout = self . timeout )
Make a new Client object
229,389
def _make_request ( self , opener , request , timeout = None ) : timeout = timeout or self . timeout try : return opener . open ( request , timeout = timeout ) except HTTPError as err : exc = handle_error ( err ) exc . __cause__ = None raise exc
Make the API call and return the response . This is separated into it s own function so we can mock it easily for testing .
229,390
def category ( msg ) : if common . typecode ( msg ) < 1 or common . typecode ( msg ) > 4 : raise RuntimeError ( "%s: Not a identification message" % msg ) msgbin = common . hex2bin ( msg ) return common . bin2int ( msgbin [ 5 : 8 ] )
Aircraft category number
229,391
def airborne_position ( msg0 , msg1 , t0 , t1 ) : mb0 = common . hex2bin ( msg0 ) [ 32 : ] mb1 = common . hex2bin ( msg1 ) [ 32 : ] cprlat_even = common . bin2int ( mb0 [ 22 : 39 ] ) / 131072.0 cprlon_even = common . bin2int ( mb0 [ 39 : 56 ] ) / 131072.0 cprlat_odd = common . bin2int ( mb1 [ 22 : 39 ] ) / 131072.0 cpr...
Decode airborn position from a pair of even and odd position message
229,392
def airborne_position_with_ref ( msg , lat_ref , lon_ref ) : mb = common . hex2bin ( msg ) [ 32 : ] cprlat = common . bin2int ( mb [ 22 : 39 ] ) / 131072.0 cprlon = common . bin2int ( mb [ 39 : 56 ] ) / 131072.0 i = int ( mb [ 21 ] ) d_lat = 360.0 / 59 if i else 360.0 / 60 j = common . floor ( lat_ref / d_lat ) + commo...
Decode airborne position with only one message knowing reference nearby location such as previously calculated location ground station or airport location etc . The reference position shall be with in 180NM of the true position .
229,393
def hex2bin ( hexstr ) : num_of_bits = len ( hexstr ) * 4 binstr = bin ( int ( hexstr , 16 ) ) [ 2 : ] . zfill ( int ( num_of_bits ) ) return binstr
Convert a hexdecimal string to binary string with zero fillings .
229,394
def icao ( msg ) : DF = df ( msg ) if DF in ( 11 , 17 , 18 ) : addr = msg [ 2 : 8 ] elif DF in ( 0 , 4 , 5 , 16 , 20 , 21 ) : c0 = bin2int ( crc ( msg , encode = True ) ) c1 = hex2int ( msg [ - 6 : ] ) addr = '%06X' % ( c0 ^ c1 ) else : addr = None return addr
Calculate the ICAO address from an Mode - S message with DF4 DF5 DF20 DF21
229,395
def gray2int ( graystr ) : num = bin2int ( graystr ) num ^= ( num >> 8 ) num ^= ( num >> 4 ) num ^= ( num >> 2 ) num ^= ( num >> 1 ) return num
Convert greycode to binary
229,396
def allzeros ( msg ) : d = hex2bin ( data ( msg ) ) if bin2int ( d ) > 0 : return False else : return True
check if the data bits are all zeros
229,397
def wrongstatus ( data , sb , msb , lsb ) : status = int ( data [ sb - 1 ] ) value = bin2int ( data [ msb - 1 : lsb ] ) if not status : if value != 0 : return True return False
Check if the status bit and field bits are consistency . This Function is used for checking BDS code versions .
229,398
def version ( msg ) : tc = typecode ( msg ) if tc != 31 : raise RuntimeError ( "%s: Not a status operation message, expecting TC = 31" % msg ) msgbin = common . hex2bin ( msg ) version = common . bin2int ( msgbin [ 72 : 75 ] ) return version
ADS - B Version
229,399
def nic_v1 ( msg , NICs ) : if typecode ( msg ) < 5 or typecode ( msg ) > 22 : raise RuntimeError ( "%s: Not a surface position message (5<TC<8), \ airborne position message (8<TC<19), \ or airborne position with GNSS height (20<TC<22)" % msg ) tc = typecode ( msg ) NIC = uncertainty . TC_NICv1_lo...
Calculate NIC navigation integrity category for ADS - B version 1