idx int64 0 251k | question stringlengths 53 3.53k | target stringlengths 5 1.23k | len_question int64 20 893 | len_target int64 3 238 |
|---|---|---|---|---|
228,400 | 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 the sudoers group. %s.' , str ( e ) ) if not os . path . exists ( self . google_sudoers_file ) : try : with open ( self . google_sudoers_file , 'w' ) as group : message = '%{0} ALL=(ALL:ALL) NOPASSWD:ALL' . format ( self . google_sudoers_group ) group . write ( message ) except IOError as e : self . logger . error ( 'Could not write sudoers file. %s. %s' , self . google_sudoers_file , str ( e ) ) return file_utils . SetPermissions ( self . google_sudoers_file , mode = 0o440 , uid = 0 , gid = 0 ) | Create a Linux group for Google added sudo user accounts . | 254 | 11 |
228,401 | 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.' , user , str ( e ) ) return False else : self . logger . info ( 'Created user account %s.' , user ) return True | Configure a Linux user account . | 118 | 7 |
228,402 | 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 . CalledProcessError as e : self . logger . warning ( 'Could not update user %s. %s.' , user , str ( e ) ) return False else : self . logger . debug ( 'Updated user account %s.' , user ) return True | Update group membership for a Linux user . | 138 | 8 |
228,403 | 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' ) # Not all sshd's support multiple authorized_keys files so we have to # share one with the user. We add each of our entries as follows: # # Added by Google # authorized_key_entry authorized_keys_file = os . path . join ( ssh_dir , 'authorized_keys' ) # Do not write to the authorized keys file if it is a symlink. if os . path . islink ( ssh_dir ) or os . path . islink ( authorized_keys_file ) : self . logger . warning ( 'Not updating authorized keys for user %s. File is a symlink.' , user ) return # Create home directory if it does not exist. This can happen if _GetUser # (getpwnam) returns non-local user info (e.g., from LDAP). if not os . path . exists ( home_dir ) : file_utils . SetPermissions ( home_dir , mode = 0o755 , uid = uid , gid = gid , mkdir = True ) # Create ssh directory if it does not exist. file_utils . SetPermissions ( ssh_dir , mode = 0o700 , uid = uid , gid = gid , mkdir = True ) # Create entry in the authorized keys file. prefix = self . logger . name + '-' with tempfile . NamedTemporaryFile ( mode = 'w' , prefix = prefix , delete = True ) as updated_keys : updated_keys_file = updated_keys . name if os . path . exists ( authorized_keys_file ) : lines = open ( authorized_keys_file ) . readlines ( ) else : lines = [ ] google_lines = set ( ) for i , line in enumerate ( lines ) : if line . startswith ( self . google_comment ) : google_lines . update ( [ i , i + 1 ] ) # Write user's authorized key entries. for i , line in enumerate ( lines ) : if i not in google_lines and line : line += '\n' if not line . endswith ( '\n' ) else '' updated_keys . write ( line ) # Write the Google authorized key entries at the end of the file. # Each entry is preceded by '# Added by Google'. for ssh_key in ssh_keys : ssh_key += '\n' if not ssh_key . endswith ( '\n' ) else '' updated_keys . write ( '%s\n' % self . google_comment ) updated_keys . write ( ssh_key ) # Write buffered data to the updated keys file without closing it and # update the Linux user's authorized keys file. updated_keys . flush ( ) shutil . copy ( updated_keys_file , authorized_keys_file ) file_utils . SetPermissions ( authorized_keys_file , mode = 0o600 , uid = uid , gid = gid ) | Update the authorized keys file for a Linux user with a list of SSH keys . | 726 | 16 |
228,404 | 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.' , user ) command = self . gpasswd_remove_cmd . format ( user = user , group = self . google_sudoers_group ) try : subprocess . check_call ( command . split ( ' ' ) ) except subprocess . CalledProcessError as e : self . logger . warning ( 'Could not update user %s. %s.' , user , str ( e ) ) return False else : self . logger . debug ( 'Removed user %s from the Google sudoers group.' , user ) return True | Update sudoer group membership for a Linux user account . | 203 | 11 |
228,405 | 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 OSError as e : message = 'Could not remove authorized keys for user %s. %s.' self . logger . warning ( message , user , str ( e ) ) | Remove a Linux user account s authorized keys file to prevent login . | 137 | 13 |
228,406 | 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 . | 60 | 10 |
228,407 | 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 . path . exists ( self . google_users_dir ) : os . makedirs ( self . google_users_dir ) shutil . copy ( updated_users_file , self . google_users_file ) file_utils . SetPermissions ( self . google_users_file , mode = 0o600 , uid = 0 , gid = 0 ) | Set the list of configured Google user accounts . | 167 | 9 |
228,408 | 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 ) : # User does not exist. Attempt to create the user and add them to the # appropriate user groups. if not ( self . _AddUser ( user ) and self . _UpdateUserGroups ( user , self . groups ) ) : return False # Add the user to the google sudoers group. if not self . _UpdateSudoer ( user , sudoer = True ) : return False # Don't try to manage account SSH keys with a shell set to disable # logins. This helps avoid problems caused by operator and root sharing # a home directory in CentOS and RHEL. pw_entry = self . _GetUser ( user ) if pw_entry and os . path . basename ( pw_entry . pw_shell ) == 'nologin' : message = 'Not updating user %s. User set `nologin` as login shell.' self . logger . debug ( message , user ) return True try : self . _UpdateAuthorizedKeys ( user , ssh_keys ) except ( IOError , OSError ) as e : message = 'Could not update the authorized keys file for user %s. %s.' self . logger . warning ( message , user , str ( e ) ) return False else : return True | Update a Linux user with authorized SSH keys . | 323 | 9 |
228,409 | 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.' , user , str ( e ) ) else : self . logger . info ( 'Removed user account %s.' , user ) self . _RemoveAuthorizedKeys ( user ) self . _UpdateSudoer ( user , sudoer = False ) | Remove a Linux user account . | 140 | 6 |
228,410 | 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 . | 63 | 7 |
228,411 | 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 # Prevent log spam when OS Login is not installed. self . oslogin_installed = True if not os . path . exists ( constants . OSLOGIN_NSS_CACHE ) : return False return not retcode | Check whether OS Login is installed . | 133 | 7 |
228,412 | 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 . | 64 | 9 |
228,413 | 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 . | 74 | 9 |
228,414 | 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 can only be enabled when OS Login is enabled. two_factor_desired = two_factor_desired and oslogin_desired if oslogin_desired : params = [ 'activate' ] if two_factor_desired : params += [ '--twofactor' ] # OS Login is desired and not enabled. if not oslogin_configured : self . logger . info ( 'Activating OS Login.' ) return self . _RunOsLoginControl ( params ) or self . _RunOsLoginNssCache ( ) # Enable two factor authentication. if two_factor_desired and not two_factor_configured : self . logger . info ( 'Activating OS Login two factor authentication.' ) return self . _RunOsLoginControl ( params ) or self . _RunOsLoginNssCache ( ) # Deactivate two factor authentication. if two_factor_configured and not two_factor_desired : self . logger . info ( 'Reactivating OS Login with two factor disabled.' ) return ( self . _RunOsLoginControl ( [ 'deactivate' ] ) or self . _RunOsLoginControl ( params ) ) # OS Login features are already enabled. Update the cache if appropriate. current_time = time . time ( ) if current_time - self . update_time > NSS_CACHE_DURATION_SEC : self . update_time = current_time return self . _RunOsLoginNssCache ( ) elif oslogin_configured : self . logger . info ( 'Deactivating OS Login.' ) return ( self . _RunOsLoginControl ( [ 'deactivate' ] ) or self . _RemoveOsLoginNssCache ( ) ) # No action was needed. return 0 | Update whether OS Login is enabled and update NSS cache if necessary . | 447 | 14 |
228,415 | 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 ( dhclient_command + [ '-x' ] + interfaces ) subprocess . check_call ( dhclient_command + interfaces ) except subprocess . CalledProcessError : logger . warning ( 'Could not enable interfaces %s.' , interfaces ) | Configure the network interfaces using dhclient . | 139 | 9 |
228,416 | 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 . | 79 | 7 |
228,417 | 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 : subprocess . check_call ( [ 'service' , 'ntpd' , 'start' ] ) except subprocess . CalledProcessError : logger . warning ( 'Failed to sync system time with ntp server.' ) else : logger . info ( 'Synced system time with ntp server.' ) | Sync clock using ntpdate . | 182 | 7 |
228,418 | 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 . | 47 | 9 |
228,419 | def _CreateConfig ( self , project_id ) : project_id = project_id or self . _GetNumericProjectId ( ) # Our project doesn't support service accounts. 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 = self . boto_config_header ) boto_dir = os . path . dirname ( self . boto_config_script ) config . SetOption ( 'GSUtil' , 'default_project_id' , project_id ) config . SetOption ( 'GSUtil' , 'default_api_version' , '2' ) config . SetOption ( 'GoogleCompute' , 'service_account' , 'default' ) config . SetOption ( 'Plugin' , 'plugin_directory' , boto_dir ) config . WriteConfig ( config_file = self . boto_config ) | Create the boto config to support standalone GSUtil . | 234 | 12 |
228,420 | 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 . | 48 | 13 |
228,421 | 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 ) stdout , stderr = process . communicate ( ) except OSError as e : self . logger . warning ( 'Exception running %s. %s.' , command , str ( e ) ) else : if process . returncode : message = 'Non-zero exit status running %s. %s.' self . logger . warning ( message , command , stderr . strip ( ) ) else : return stdout . decode ( 'utf-8' , 'replace' ) return '' | Run a command with ip route and return the response . | 199 | 11 |
228,422 | 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 . | 49 | 9 |
228,423 | 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 . | 85 | 11 |
228,424 | 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 . | 65 | 13 |
228,425 | 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 . | 44 | 8 |
228,426 | 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 . _ModifyInterface ( interface_config , 'NM_CONTROLLED' , 'no' , replace = True ) else : with open ( interface_config , 'w' ) as interface_file : interface_content = [ '# Added by Google.' , 'BOOTPROTO=none' , 'DEFROUTE=no' , 'DEVICE=%s' % interface , 'IPV6INIT=no' , 'NM_CONTROLLED=no' , 'NOZEROCONF=yes' , '' , ] interface_file . write ( '\n' . join ( interface_content ) ) logger . info ( 'Created config file for interface %s.' , interface ) | Disable network manager management on a list of network interfaces . | 235 | 11 |
228,427 | 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 replace : for line in fileinput . input ( interface_config , inplace = True ) : print ( re . sub ( r'%s=.*' % config_key , config_entry , line . rstrip ( ) ) ) | Write a value to a config file if not already present . | 147 | 12 |
228,428 | 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 ( 'Invalid schema %s. Not expiring key.' , schema ) return False try : json_obj = json . loads ( json_str ) except ValueError : self . logger . debug ( 'Invalid JSON %s. Not expiring key.' , json_str ) return False if 'expireOn' not in json_obj : self . logger . debug ( 'No expiration timestamp. Not expiring key.' ) return False expire_str = json_obj [ 'expireOn' ] format_str = '%Y-%m-%dT%H:%M:%S+0000' try : expire_time = datetime . datetime . strptime ( expire_str , format_str ) except ValueError : self . logger . warning ( 'Expiration timestamp "%s" not in format %s. Not expiring key.' , expire_str , format_str ) return False # Expire the key if and only if we have exceeded the expiration timestamp. return datetime . datetime . utcnow ( ) > expire_time | Check whether an SSH key has expired . | 315 | 8 |
228,429 | 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 split_line = line . split ( ':' , 1 ) if len ( split_line ) != 2 : self . logger . info ( 'SSH key is not a complete entry: %s.' , split_line ) continue user , key = split_line if self . _HasExpired ( key ) : self . logger . debug ( 'Expired SSH key for user %s: %s.' , user , key ) continue if user not in user_map : user_map [ user ] = [ ] user_map [ user ] . append ( key ) logging . debug ( 'User accounts: %s.' , user_map ) return user_map | Parse the SSH key data into a user map . | 233 | 11 |
228,430 | 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' ] [ 'attributes' ] except KeyError : project_data = { } self . logger . warning ( 'Project attributes were not found.' ) return instance_data , project_data | Get dictionaries for instance and project attributes . | 121 | 9 |
228,431 | 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_project != 'true' and not instance_data . get ( 'sshKeys' ) : valid_keys . append ( project_data . get ( 'ssh-keys' ) ) valid_keys . append ( project_data . get ( 'sshKeys' ) ) accounts_data = '\n' . join ( [ key for key in valid_keys if key ] ) return self . _ParseAccountsData ( accounts_data ) | Get the user accounts specified in metadata server contents . | 187 | 10 |
228,432 | 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 . invalid_users . add ( user ) else : self . user_ssh_keys [ user ] = ssh_keys [ : ] | Provision and update Linux user accounts based on account metadata . | 120 | 12 |
228,433 | 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 . | 55 | 14 |
228,434 | 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 . lower ( ) == 'true' | Get the value of the enable - oslogin metadata key . | 91 | 12 |
228,435 | 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 = { } self . oslogin . UpdateOsLogin ( True , two_factor_desired = enable_two_factor ) else : desired_users = self . _GetAccountsData ( result ) self . oslogin . UpdateOsLogin ( False ) remove_users = sorted ( set ( configured_users ) - set ( desired_users . keys ( ) ) ) self . _UpdateUsers ( desired_users ) self . _RemoveUsers ( remove_users ) self . utils . SetConfiguredUsers ( desired_users . keys ( ) ) | Called when there are changes to the contents of the metadata server . | 199 | 14 |
228,436 | 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 . | 61 | 17 |
228,437 | 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 . | 97 | 9 |
228,438 | 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 locking %s. %s.' % ( path , str ( e ) ) ) | Lock the provided file descriptor . | 120 | 6 |
228,439 | 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 . | 104 | 7 |
228,440 | 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 . | 59 | 12 |
228,441 | 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 . getcode ( ) == httpclient . SERVICE_UNAVAILABLE ) : continue elif isinstance ( e , socket . timeout ) : continue raise else : if response . getcode ( ) == httpclient . OK : return response else : raise StatusException ( response ) return Wrapper | Function decorator to retry on a service unavailable exception . | 158 | 12 |
228,442 | 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 ( urlrequest . ProxyHandler ( { } ) ) timeout = timeout or self . timeout return request_opener . open ( request , timeout = timeout * 1.1 ) | Performs a GET request with the metadata headers . | 129 | 10 |
228,443 | 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 . | 54 | 9 |
228,444 | 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 , 'recursive' : recursive , 'timeout_sec' : timeout or self . timeout , 'wait_for_change' : wait , } while True : response = self . _GetMetadataRequest ( metadata_url , params = params , timeout = timeout ) etag_updated = self . _UpdateEtag ( response ) if wait and not etag_updated and not timeout : # Retry until the etag is updated. continue else : # One of the following are true: # - Waiting for change is not required. # - The etag is updated. # - The user specified a request timeout. break return json . loads ( response . read ( ) . decode ( 'utf-8' ) ) | Request the contents of metadata server and deserialize the response . | 243 | 13 |
228,445 | 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 , socket . error , urlerror . URLError ) as e : if not isinstance ( e , type ( exception ) ) : exception = e self . logger . error ( 'GET request error retrieving metadata. %s.' , e ) if retry : continue else : break | Wait for a successful metadata response . | 137 | 7 |
228,446 | 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 ( 'Exception calling the response handler. %s.' , e ) | Watch for changes to the contents of the metadata server . | 87 | 11 |
228,447 | 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 . | 62 | 12 |
228,448 | 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 . | 88 | 7 |
228,449 | 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 . | 43 | 11 |
228,450 | 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 . | 43 | 10 |
228,451 | 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 = sorted ( set ( configured ) - set ( desired ) ) self . _LogForwardedIpChanges ( configured , desired , to_add , to_remove , interface ) self . _AddForwardedIps ( to_add , interface ) self . _RemoveForwardedIps ( to_remove , interface ) | Handle changes to the forwarded IPs on a network interface . | 153 | 12 |
228,452 | 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' % interface , '' , ] with open ( interface_config , 'w' ) as interface_file : interface_file . write ( '\n' . join ( interface_content ) ) logger . info ( 'Created ifcfg file for interface %s.' , interface ) | Write ifcfg files for multi - NIC support . | 167 | 10 |
228,453 | 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 . | 77 | 5 |
228,454 | 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_forwarding_enabled : self . ip_forwarding . HandleForwardedIps ( interface . name , interface . forwarded_ips , interface . ip ) | Called when network interface metadata changes . | 109 | 8 |
228,455 | 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 ( 'forwardedIps' , [ ] ) ) if self . ip_aliases : ip_addresses . extend ( network_interface . get ( 'ipAliases' , [ ] ) ) if self . target_instance_ips : ip_addresses . extend ( network_interface . get ( 'targetInstanceIps' , [ ] ) ) interfaces . append ( NetworkDaemon . NetworkInterface ( interface , ip_addresses , network_interface . get ( 'ip' , [ ] ) ) ) else : message = 'Network interface not found for MAC address: %s.' self . logger . warning ( message , mac_address ) return interfaces | Extracts network interface metadata . | 215 | 7 |
228,456 | def _build_url ( self , query_params ) : url = '' count = 0 while count < len ( self . _url_path ) : url += '/{}' . format ( self . _url_path [ count ] ) count += 1 # add slash if self . append_slash : url += '/' if query_params : url_values = urlencode ( sorted ( query_params . items ( ) ) , True ) url = '{}?{}' . format ( url , url_values ) if self . _version : url = self . _build_versioned_url ( url ) else : url = '{}{}' . format ( self . host , url ) return url | Build the final URL to be passed to urllib | 153 | 11 |
228,457 | 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 | 88 | 5 |
228,458 | 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 . | 60 | 26 |
228,459 | 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 | 68 | 4 |
228,460 | def airborne_position ( msg0 , msg1 , t0 , t1 ) : mb0 = common . hex2bin ( msg0 ) [ 32 : ] mb1 = common . hex2bin ( msg1 ) [ 32 : ] # 131072 is 2^17, since CPR lat and lon are 17 bits each. 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 cprlon_odd = common . bin2int ( mb1 [ 39 : 56 ] ) / 131072.0 air_d_lat_even = 360.0 / 60 air_d_lat_odd = 360.0 / 59 # compute latitude index 'j' j = common . floor ( 59 * cprlat_even - 60 * cprlat_odd + 0.5 ) lat_even = float ( air_d_lat_even * ( j % 60 + cprlat_even ) ) lat_odd = float ( air_d_lat_odd * ( j % 59 + cprlat_odd ) ) if lat_even >= 270 : lat_even = lat_even - 360 if lat_odd >= 270 : lat_odd = lat_odd - 360 # check if both are in the same latidude zone, exit if not if common . cprNL ( lat_even ) != common . cprNL ( lat_odd ) : return None # compute ni, longitude index m, and longitude if ( t0 > t1 ) : lat = lat_even nl = common . cprNL ( lat ) ni = max ( common . cprNL ( lat ) - 0 , 1 ) m = common . floor ( cprlon_even * ( nl - 1 ) - cprlon_odd * nl + 0.5 ) lon = ( 360.0 / ni ) * ( m % ni + cprlon_even ) else : lat = lat_odd nl = common . cprNL ( lat ) ni = max ( common . cprNL ( lat ) - 1 , 1 ) m = common . floor ( cprlon_even * ( nl - 1 ) - cprlon_odd * nl + 0.5 ) lon = ( 360.0 / ni ) * ( m % ni + cprlon_odd ) if lon > 180 : lon = lon - 360 return round ( lat , 5 ) , round ( lon , 5 ) | Decode airborn position from a pair of even and odd position message | 589 | 14 |
228,461 | 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 ) + common . floor ( 0.5 + ( ( lat_ref % d_lat ) / d_lat ) - cprlat ) lat = d_lat * ( j + cprlat ) ni = common . cprNL ( lat ) - i if ni > 0 : d_lon = 360.0 / ni else : d_lon = 360.0 m = common . floor ( lon_ref / d_lon ) + common . floor ( 0.5 + ( ( lon_ref % d_lon ) / d_lon ) - cprlon ) lon = d_lon * ( m + cprlon ) return round ( lat , 5 ) , round ( lon , 5 ) | 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 . | 276 | 38 |
228,462 | 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 . | 55 | 15 |
228,463 | 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 | 104 | 23 |
228,464 | def gray2int ( graystr ) : num = bin2int ( graystr ) num ^= ( num >> 8 ) num ^= ( num >> 4 ) num ^= ( num >> 2 ) num ^= ( num >> 1 ) return num | Convert greycode to binary | 52 | 6 |
228,465 | def allzeros ( msg ) : d = hex2bin ( data ( msg ) ) if bin2int ( d ) > 0 : return False else : return True | check if the data bits are all zeros | 35 | 9 |
228,466 | def wrongstatus ( data , sb , msb , lsb ) : # status bit, most significant bit, least significant bit 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 . | 69 | 21 |
228,467 | 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 | 68 | 4 |
228,468 | 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_lookup [ tc ] if isinstance ( NIC , dict ) : NIC = NIC [ NICs ] try : Rc = uncertainty . NICv1 [ NIC ] [ NICs ] [ 'Rc' ] VPL = uncertainty . NICv1 [ NIC ] [ NICs ] [ 'VPL' ] except KeyError : Rc , VPL = uncertainty . NA , uncertainty . NA return Rc , VPL | Calculate NIC navigation integrity category for ADS - B version 1 | 183 | 13 |
228,469 | def nic_v2 ( msg , NICa , NICbc ) : 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_NICv2_lookup [ tc ] if 20 <= tc <= 22 : NICs = 0 else : NICs = NICa * 2 + NICbc try : if isinstance ( NIC , dict ) : NIC = NIC [ NICs ] Rc = uncertainty . NICv2 [ NIC ] [ NICs ] [ 'Rc' ] except KeyError : Rc = uncertainty . NA return Rc | Calculate NIC navigation integrity category for ADS - B version 2 | 178 | 13 |
228,470 | def nic_s ( msg ) : tc = typecode ( msg ) if tc != 31 : raise RuntimeError ( "%s: Not a status operation message, expecting TC = 31" % msg ) msgbin = common . hex2bin ( msg ) nic_s = int ( msgbin [ 75 ] ) return nic_s | Obtain NIC supplement bit TC = 31 message | 68 | 9 |
228,471 | def nic_b ( msg ) : tc = typecode ( msg ) if tc < 9 or tc > 18 : raise RuntimeError ( "%s: Not a airborne position message, expecting 8<TC<19" % msg ) msgbin = common . hex2bin ( msg ) nic_b = int ( msgbin [ 39 ] ) return nic_b | Obtain NICb navigation integrity category supplement - b | 74 | 10 |
228,472 | def nac_p ( msg ) : tc = typecode ( msg ) if tc not in [ 29 , 31 ] : raise RuntimeError ( "%s: Not a target state and status message, \ or operation status message, expecting TC = 29 or 31" % msg ) msgbin = common . hex2bin ( msg ) if tc == 29 : NACp = common . bin2int ( msgbin [ 71 : 75 ] ) elif tc == 31 : NACp = common . bin2int ( msgbin [ 76 : 80 ] ) try : EPU = uncertainty . NACp [ NACp ] [ 'EPU' ] VEPU = uncertainty . NACp [ NACp ] [ 'VEPU' ] except KeyError : EPU , VEPU = uncertainty . NA , uncertainty . NA return EPU , VEPU | Calculate NACp Navigation Accuracy Category - Position | 181 | 11 |
228,473 | def nac_v ( msg ) : tc = typecode ( msg ) if tc != 19 : raise RuntimeError ( "%s: Not an airborne velocity message, expecting TC = 19" % msg ) msgbin = common . hex2bin ( msg ) NACv = common . bin2int ( msgbin [ 42 : 45 ] ) try : HFOMr = uncertainty . NACv [ NACv ] [ 'HFOMr' ] VFOMr = uncertainty . NACv [ NACv ] [ 'VFOMr' ] except KeyError : HFOMr , VFOMr = uncertainty . NA , uncertainty . NA return HFOMr , VFOMr | Calculate NACv Navigation Accuracy Category - Velocity | 146 | 11 |
228,474 | def sil ( msg , version ) : tc = typecode ( msg ) if tc not in [ 29 , 31 ] : raise RuntimeError ( "%s: Not a target state and status messag, \ or operation status message, expecting TC = 29 or 31" % msg ) msgbin = common . hex2bin ( msg ) if tc == 29 : SIL = common . bin2int ( msgbin [ 76 : 78 ] ) elif tc == 31 : SIL = common . bin2int ( msgbin [ 82 : 84 ] ) try : PE_RCu = uncertainty . SIL [ SIL ] [ 'PE_RCu' ] PE_VPL = uncertainty . SIL [ SIL ] [ 'PE_VPL' ] except KeyError : PE_RCu , PE_VPL = uncertainty . NA , uncertainty . NA base = 'unknown' if version == 2 : if tc == 29 : SIL_SUP = common . bin2int ( msgbin [ 39 ] ) elif tc == 31 : SIL_SUP = common . bin2int ( msgbin [ 86 ] ) if SIL_SUP == 0 : base = "hour" elif SIL_SUP == 1 : base = "sample" return PE_RCu , PE_VPL , base | Calculate SIL Surveillance Integrity Level | 262 | 7 |
228,475 | def roll50 ( msg ) : d = hex2bin ( data ( msg ) ) if d [ 0 ] == '0' : return None sign = int ( d [ 1 ] ) # 1 -> left wing down value = bin2int ( d [ 2 : 11 ] ) if sign : value = value - 512 angle = value * 45.0 / 256.0 # degree return round ( angle , 1 ) | Roll angle BDS 5 0 message | 86 | 6 |
228,476 | def trk50 ( msg ) : d = hex2bin ( data ( msg ) ) if d [ 11 ] == '0' : return None sign = int ( d [ 12 ] ) # 1 -> west value = bin2int ( d [ 13 : 23 ] ) if sign : value = value - 1024 trk = value * 90.0 / 512.0 # convert from [-180, 180] to [0, 360] if trk < 0 : trk = 360 + trk return round ( trk , 3 ) | True track angle BDS 5 0 message | 112 | 7 |
228,477 | def gs50 ( msg ) : d = hex2bin ( data ( msg ) ) if d [ 23 ] == '0' : return None spd = bin2int ( d [ 24 : 34 ] ) * 2 # kts return spd | Ground speed BDS 5 0 message | 53 | 6 |
228,478 | def tas50 ( msg ) : d = hex2bin ( data ( msg ) ) if d [ 45 ] == '0' : return None tas = bin2int ( d [ 46 : 56 ] ) * 2 # kts return tas | Aircraft true airspeed BDS 5 0 message | 53 | 9 |
228,479 | def ias53 ( msg ) : d = hex2bin ( data ( msg ) ) if d [ 12 ] == '0' : return None ias = bin2int ( d [ 13 : 23 ] ) # knots return ias | Indicated airspeed DBS 5 3 message | 50 | 9 |
228,480 | def mach53 ( msg ) : d = hex2bin ( data ( msg ) ) if d [ 23 ] == '0' : return None mach = bin2int ( d [ 24 : 33 ] ) * 0.008 return round ( mach , 3 ) | MACH number DBS 5 3 message | 54 | 8 |
228,481 | def tas53 ( msg ) : d = hex2bin ( data ( msg ) ) if d [ 33 ] == '0' : return None tas = bin2int ( d [ 34 : 46 ] ) * 0.5 # kts return round ( tas , 1 ) | Aircraft true airspeed BDS 5 3 message | 60 | 9 |
228,482 | def read_skysense_buffer ( self ) : SS_MSGLENGTH = 24 SS_STARTCHAR = 0x24 if len ( self . buffer ) <= SS_MSGLENGTH : return None messages = [ ] while len ( self . buffer ) > SS_MSGLENGTH : i = 0 if self . buffer [ i ] == SS_STARTCHAR and self . buffer [ i + SS_MSGLENGTH ] == SS_STARTCHAR : i += 1 if ( self . buffer [ i ] >> 7 ) : #Long message payload = self . buffer [ i : i + 14 ] else : #Short message payload = self . buffer [ i : i + 7 ] msg = '' . join ( '%02X' % j for j in payload ) i += 14 #Both message types use 14 bytes tsbin = self . buffer [ i : i + 6 ] sec = ( ( tsbin [ 0 ] & 0x7f ) << 10 ) | ( tsbin [ 1 ] << 2 ) | ( tsbin [ 2 ] >> 6 ) nano = ( ( tsbin [ 2 ] & 0x3f ) << 24 ) | ( tsbin [ 3 ] << 16 ) | ( tsbin [ 4 ] << 8 ) | tsbin [ 5 ] ts = sec + nano * 1.0e-9 i += 6 #Signal and noise level - Don't care for now i += 3 self . buffer = self . buffer [ SS_MSGLENGTH : ] messages . append ( [ msg , ts ] ) else : self . buffer = self . buffer [ 1 : ] return messages | Skysense stream format . | 338 | 6 |
228,483 | def is10 ( msg ) : if allzeros ( msg ) : return False d = hex2bin ( data ( msg ) ) # first 8 bits must be 0x10 if d [ 0 : 8 ] != '00010000' : return False # bit 10 to 14 are reserved if bin2int ( d [ 9 : 14 ] ) != 0 : return False # overlay capabilty conflict if d [ 14 ] == '1' and bin2int ( d [ 16 : 23 ] ) < 5 : return False if d [ 14 ] == '0' and bin2int ( d [ 16 : 23 ] ) > 4 : return False return True | Check if a message is likely to be BDS code 1 0 | 136 | 12 |
228,484 | def is17 ( msg ) : if allzeros ( msg ) : return False d = hex2bin ( data ( msg ) ) if bin2int ( d [ 28 : 56 ] ) != 0 : return False caps = cap17 ( msg ) # basic BDS codes for ADS-B shall be supported # assuming ADS-B out is installed (2017EU/2020US mandate) # if not set(['BDS05', 'BDS06', 'BDS08', 'BDS09', 'BDS20']).issubset(caps): # return False # at least you can respond who you are if 'BDS20' not in caps : return False return True | Check if a message is likely to be BDS code 1 7 | 142 | 12 |
228,485 | def cap17 ( msg ) : allbds = [ '05' , '06' , '07' , '08' , '09' , '0A' , '20' , '21' , '40' , '41' , '42' , '43' , '44' , '45' , '48' , '50' , '51' , '52' , '53' , '54' , '55' , '56' , '5F' , '60' , 'NA' , 'NA' , 'E1' , 'E2' ] d = hex2bin ( data ( msg ) ) idx = [ i for i , v in enumerate ( d [ : 28 ] ) if v == '1' ] capacity = [ 'BDS' + allbds [ i ] for i in idx if allbds [ i ] is not 'NA' ] return capacity | Extract capacities from BDS 1 7 message | 199 | 8 |
228,486 | def get_aircraft ( self ) : acs = self . acs icaos = list ( acs . keys ( ) ) for icao in icaos : if acs [ icao ] [ 'lat' ] is None : acs . pop ( icao ) return acs | all aircraft that are stored in memeory | 66 | 8 |
228,487 | def altitude_diff ( msg ) : tc = common . typecode ( msg ) if tc != 19 : raise RuntimeError ( "%s: Not a airborne velocity message, expecting TC=19" % msg ) msgbin = common . hex2bin ( msg ) sign = - 1 if int ( msgbin [ 80 ] ) else 1 value = common . bin2int ( msgbin [ 81 : 88 ] ) if value == 0 or value == 127 : return None else : return sign * ( value - 1 ) * 25 | Decode the differece between GNSS and barometric altitude | 108 | 12 |
228,488 | def is50or60 ( msg , spd_ref , trk_ref , alt_ref ) : def vxy ( v , angle ) : vx = v * np . sin ( np . radians ( angle ) ) vy = v * np . cos ( np . radians ( angle ) ) return vx , vy if not ( bds50 . is50 ( msg ) and bds60 . is60 ( msg ) ) : return None h50 = bds50 . trk50 ( msg ) v50 = bds50 . gs50 ( msg ) if h50 is None or v50 is None : return 'BDS50,BDS60' h60 = bds60 . hdg60 ( msg ) m60 = bds60 . mach60 ( msg ) i60 = bds60 . ias60 ( msg ) if h60 is None or ( m60 is None and i60 is None ) : return 'BDS50,BDS60' m60 = np . nan if m60 is None else m60 i60 = np . nan if i60 is None else i60 XY5 = vxy ( v50 * aero . kts , h50 ) XY6m = vxy ( aero . mach2tas ( m60 , alt_ref * aero . ft ) , h60 ) XY6i = vxy ( aero . cas2tas ( i60 * aero . kts , alt_ref * aero . ft ) , h60 ) allbds = [ 'BDS50' , 'BDS60' , 'BDS60' ] X = np . array ( [ XY5 , XY6m , XY6i ] ) Mu = np . array ( vxy ( spd_ref * aero . kts , trk_ref ) ) # compute Mahalanobis distance matrix # Cov = [[20**2, 0], [0, 20**2]] # mmatrix = np.sqrt(np.dot(np.dot(X-Mu, np.linalg.inv(Cov)), (X-Mu).T)) # dist = np.diag(mmatrix) # since the covariance matrix is identity matrix, # M-dist is same as eculidian distance try : dist = np . linalg . norm ( X - Mu , axis = 1 ) BDS = allbds [ np . nanargmin ( dist ) ] except ValueError : return 'BDS50,BDS60' return BDS | Use reference ground speed and trk to determine BDS50 and DBS60 . | 543 | 16 |
228,489 | def infer ( msg , mrar = False ) : df = common . df ( msg ) if common . allzeros ( msg ) : return 'EMPTY' # For ADS-B / Mode-S extended squitter if df == 17 : tc = common . typecode ( msg ) if 1 <= tc <= 4 : return 'BDS08' # indentification and category if 5 <= tc <= 8 : return 'BDS06' # surface movement if 9 <= tc <= 18 : return 'BDS05' # airborne position, baro-alt if tc == 19 : return 'BDS09' # airborne velocity if 20 <= tc <= 22 : return 'BDS05' # airborne position, gnss-alt if tc == 28 : return 'BDS61' # aircraft status if tc == 29 : return 'BDS62' # target state and status if tc == 31 : return 'BDS65' # operational status # For Comm-B replies IS10 = bds10 . is10 ( msg ) IS17 = bds17 . is17 ( msg ) IS20 = bds20 . is20 ( msg ) IS30 = bds30 . is30 ( msg ) IS40 = bds40 . is40 ( msg ) IS50 = bds50 . is50 ( msg ) IS60 = bds60 . is60 ( msg ) IS44 = bds44 . is44 ( msg ) IS45 = bds45 . is45 ( msg ) if mrar : allbds = np . array ( [ "BDS10" , "BDS17" , "BDS20" , "BDS30" , "BDS40" , "BDS44" , "BDS45" , "BDS50" , "BDS60" ] ) mask = [ IS10 , IS17 , IS20 , IS30 , IS40 , IS44 , IS45 , IS50 , IS60 ] else : allbds = np . array ( [ "BDS10" , "BDS17" , "BDS20" , "BDS30" , "BDS40" , "BDS50" , "BDS60" ] ) mask = [ IS10 , IS17 , IS20 , IS30 , IS40 , IS50 , IS60 ] bds = ',' . join ( sorted ( allbds [ mask ] ) ) if len ( bds ) == 0 : return None else : return bds | Estimate the most likely BDS code of an message . | 518 | 11 |
228,490 | def is40 ( msg ) : if allzeros ( msg ) : return False d = hex2bin ( data ( msg ) ) # status bit 1, 14, and 27 if wrongstatus ( d , 1 , 2 , 13 ) : return False if wrongstatus ( d , 14 , 15 , 26 ) : return False if wrongstatus ( d , 27 , 28 , 39 ) : return False if wrongstatus ( d , 48 , 49 , 51 ) : return False if wrongstatus ( d , 54 , 55 , 56 ) : return False # bits 40-47 and 52-53 shall all be zero if bin2int ( d [ 39 : 47 ] ) != 0 : return False if bin2int ( d [ 51 : 53 ] ) != 0 : return False return True | Check if a message is likely to be BDS code 4 0 | 161 | 12 |
228,491 | def alt40fms ( msg ) : d = hex2bin ( data ( msg ) ) if d [ 13 ] == '0' : return None alt = bin2int ( d [ 14 : 26 ] ) * 16 # ft return alt | Selected altitude FMS | 51 | 5 |
228,492 | def p40baro ( msg ) : d = hex2bin ( data ( msg ) ) if d [ 26 ] == '0' : return None p = bin2int ( d [ 27 : 39 ] ) * 0.1 + 800 # millibar return p | Barometric pressure setting | 57 | 4 |
228,493 | def is44 ( msg ) : if allzeros ( msg ) : return False d = hex2bin ( data ( msg ) ) # status bit 5, 35, 47, 50 if wrongstatus ( d , 5 , 6 , 23 ) : return False if wrongstatus ( d , 35 , 36 , 46 ) : return False if wrongstatus ( d , 47 , 48 , 49 ) : return False if wrongstatus ( d , 50 , 51 , 56 ) : return False # Bits 1-4 indicate source, values > 4 reserved and should not occur if bin2int ( d [ 0 : 4 ] ) > 4 : return False vw = wind44 ( msg ) if vw is not None and vw [ 0 ] > 250 : return False temp , temp2 = temp44 ( msg ) if min ( temp , temp2 ) > 60 or max ( temp , temp2 ) < - 80 : return False return True | Check if a message is likely to be BDS code 4 4 . | 192 | 13 |
228,494 | def wind44 ( msg ) : d = hex2bin ( data ( msg ) ) status = int ( d [ 4 ] ) if not status : return None speed = bin2int ( d [ 5 : 14 ] ) # knots direction = bin2int ( d [ 14 : 23 ] ) * 180.0 / 256.0 # degree return round ( speed , 0 ) , round ( direction , 1 ) | Wind speed and direction . | 85 | 5 |
228,495 | def p44 ( msg ) : d = hex2bin ( data ( msg ) ) if d [ 34 ] == '0' : return None p = bin2int ( d [ 35 : 46 ] ) # hPa return p | Static pressure . | 48 | 3 |
228,496 | def is60 ( msg ) : if allzeros ( msg ) : return False d = hex2bin ( data ( msg ) ) # status bit 1, 13, 24, 35, 46 if wrongstatus ( d , 1 , 2 , 12 ) : return False if wrongstatus ( d , 13 , 14 , 23 ) : return False if wrongstatus ( d , 24 , 25 , 34 ) : return False if wrongstatus ( d , 35 , 36 , 45 ) : return False if wrongstatus ( d , 46 , 47 , 56 ) : return False ias = ias60 ( msg ) if ias is not None and ias > 500 : return False mach = mach60 ( msg ) if mach is not None and mach > 1 : return False vr_baro = vr60baro ( msg ) if vr_baro is not None and abs ( vr_baro ) > 6000 : return False vr_ins = vr60ins ( msg ) if vr_ins is not None and abs ( vr_ins ) > 6000 : return False return True | Check if a message is likely to be BDS code 6 0 | 229 | 12 |
228,497 | def hdg60 ( msg ) : d = hex2bin ( data ( msg ) ) if d [ 0 ] == '0' : return None sign = int ( d [ 1 ] ) # 1 -> west value = bin2int ( d [ 2 : 12 ] ) if sign : value = value - 1024 hdg = value * 90 / 512.0 # degree # convert from [-180, 180] to [0, 360] if hdg < 0 : hdg = 360 + hdg return round ( hdg , 3 ) | Megnetic heading of aircraft | 118 | 5 |
228,498 | def mach60 ( msg ) : d = hex2bin ( data ( msg ) ) if d [ 23 ] == '0' : return None mach = bin2int ( d [ 24 : 34 ] ) * 2.048 / 512.0 return round ( mach , 3 ) | Aircraft MACH number | 58 | 5 |
228,499 | def vr60baro ( msg ) : d = hex2bin ( data ( msg ) ) if d [ 34 ] == '0' : return None sign = int ( d [ 35 ] ) # 1 -> negative value, two's complement value = bin2int ( d [ 36 : 45 ] ) if value == 0 or value == 511 : # all zeros or all ones return 0 value = value - 512 if sign else value roc = value * 32 # feet/min return roc | Vertical rate from barometric measurement this value may be very noisy . | 105 | 14 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.