INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Regenerates SSH host keys when the VM is restarted with a new IP address. Booting a VM from an image with a known SSH key allows a number of attacks. This function will regenerating the host key whenever the IP address changes. This applies the first time the instance is booted, and each time the disk is used to boot a new instance. Args: host_key_types: string, a comma separated list of host key types.
def _SetSshHostKeys(self, host_key_types=None): """Regenerates SSH host keys when the VM is restarted with a new IP address. Booting a VM from an image with a known SSH key allows a number of attacks. This function will regenerating the host key whenever the IP address changes. This applies the first time the instance is booted, and each time the disk is used to boot a new instance. Args: host_key_types: string, a comma separated list of host key types. """ 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'ssh_host_(?P<type>[a-z0-9]*)_key\Z') key_dir = '/etc/ssh' key_files = [f for f in os.listdir(key_dir) if file_regex.match(f)] key_types = host_key_types.split(',') if host_key_types else [] key_types_files = ['ssh_host_%s_key' % key_type for key_type in key_types] for key_file in set(key_files) | set(key_types_files): key_type = file_regex.match(key_file).group('type') key_dest = os.path.join(key_dir, key_file) self._GenerateSshKey(key_type, key_dest) self._StartSshd() self.instance_config.SetOption(section, 'instance_id', str(instance_id))
Set the boto config so GSUtil works with provisioned service accounts.
def _SetupBotoConfig(self): """Set the boto config so GSUtil works with provisioned service accounts.""" project_id = self._GetNumericProjectId() try: boto_config.BotoConfig(project_id, debug=self.debug) except (IOError, OSError) as e: self.logger.warning(str(e))
Download a Google Storage URL using an authentication token. If the token cannot be fetched, fallback to unauthenticated download. Args: url: string, the URL to download. dest_dir: string, the path to a directory for storing metadata scripts. Returns: string, the path to the file storing the metadata script.
def _DownloadAuthUrl(self, url, dest_dir): """Download a Google Storage URL using an authentication token. If the token cannot be fetched, fallback to unauthenticated download. Args: url: string, the URL to download. dest_dir: string, the path to a directory for storing metadata scripts. Returns: string, the path to the file storing the metadata script. """ 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.GetMetadata( self.token_metadata_key, recursive=False, retry=False) if not response: self.logger.info( 'Authentication token not found. Attempting unauthenticated ' 'download.') return self._DownloadUrl(url, dest_dir) self.token = '%s %s' % ( response.get('token_type', ''), response.get('access_token', '')) try: request = urlrequest.Request(url) request.add_unredirected_header('Metadata-Flavor', 'Google') request.add_unredirected_header('Authorization', self.token) content = urlrequest.urlopen(request).read().decode('utf-8') except (httpclient.HTTPException, socket.error, urlerror.URLError) as e: self.logger.warning('Could not download %s. %s.', url, str(e)) return None with open(dest, 'wb') as f: f.write(content) return dest
Download a script from a given URL. Args: url: string, the URL to download. dest_dir: string, the path to a directory for storing metadata scripts. Returns: string, the path to the file storing the metadata script.
def _DownloadUrl(self, url, dest_dir): """Download a script from a given URL. Args: url: string, the URL to download. dest_dir: string, the path to a directory for storing metadata scripts. Returns: string, the path to the file storing the metadata script. """ 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.HTTPException, socket.error, urlerror.URLError) as e: self.logger.warning('Could not download %s. %s.', url, str(e)) except Exception as e: self.logger.warning('Exception downloading %s. %s.', url, str(e)) return None
Download the contents of the URL to the destination. Args: url: string, the URL to download. dest_dir: string, the path to a directory for storing metadata scripts. Returns: string, the path to the file storing the metadata script.
def _DownloadScript(self, url, dest_dir): """Download the contents of the URL to the destination. Args: url: string, the URL to download. dest_dir: string, the path to a directory for storing metadata scripts. Returns: string, the path to the file storing the metadata script. """ # Check for the preferred Google Storage URL format: # gs://<bucket>/<object> if url.startswith(r'gs://'): # Convert the string into a standard URL. url = re.sub('^gs://', 'https://storage.googleapis.com/', url) return self._DownloadAuthUrl(url, dest_dir) header = r'http[s]?://' domain = r'storage\.googleapis\.com' # Many of the Google Storage URLs are supported below. # It is prefered that customers specify their object using # its gs://<bucket>/<object> url. bucket = r'(?P<bucket>[a-z0-9][-_.a-z0-9]*[a-z0-9])' # Accept any non-empty string that doesn't contain a wildcard character obj = r'(?P<obj>[^\*\?]+)' # Check for the Google Storage URLs: # http://<bucket>.storage.googleapis.com/<object> # https://<bucket>.storage.googleapis.com/<object> gs_regex = re.compile(r'\A%s%s\.%s/%s\Z' % (header, bucket, domain, obj)) match = gs_regex.match(url) if match: return self._DownloadAuthUrl(url, dest_dir) # Check for the other possible Google Storage URLs: # http://storage.googleapis.com/<bucket>/<object> # https://storage.googleapis.com/<bucket>/<object> # # The following are deprecated but checked: # http://commondatastorage.googleapis.com/<bucket>/<object> # https://commondatastorage.googleapis.com/<bucket>/<object> gs_regex = re.compile( r'\A%s(commondata)?%s/%s/%s\Z' % (header, domain, bucket, obj)) match = gs_regex.match(url) if match: return self._DownloadAuthUrl(url, dest_dir) # Unauthenticated download of the object. return self._DownloadUrl(url, dest_dir)
Retrieve the scripts from attribute metadata. Args: attribute_data: dict, the contents of the attributes metadata. dest_dir: string, the path to a directory for storing metadata scripts. Returns: dict, a dictionary mapping metadata keys to files storing scripts.
def _GetAttributeScripts(self, attribute_data, dest_dir): """Retrieve the scripts from attribute metadata. Args: attribute_data: dict, the contents of the attributes metadata. dest_dir: string, the path to a directory for storing metadata scripts. Returns: dict, a dictionary mapping metadata keys to files storing scripts. """ 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 tempfile.NamedTemporaryFile( mode='w', dir=dest_dir, delete=False) as dest: dest.write(metadata_value.lstrip()) script_dict[metadata_key] = dest.name metadata_key = '%s-script-url' % self.script_type metadata_value = attribute_data.get(metadata_key) if metadata_value: self.logger.info('Found %s in metadata.', metadata_key) script_dict[metadata_key] = self._DownloadScript( metadata_value, dest_dir) return script_dict
Retrieve the scripts to execute. Args: dest_dir: string, the path to a directory for storing metadata scripts. Returns: dict, a dictionary mapping set metadata keys with associated scripts.
def GetScripts(self, dest_dir): """Retrieve the scripts to execute. Args: dest_dir: string, the path to a directory for storing metadata scripts. Returns: dict, a dictionary mapping set metadata keys with associated scripts. """ 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']['attributes'] except KeyError: project_data = None self.logger.warning('Project attributes were not found.') return (self._GetAttributeScripts(instance_data, dest_dir) or self._GetAttributeScripts(project_data, dest_dir))
Add executable permissions to a file. Args: metadata_script: string, the path to the executable file.
def _MakeExecutable(self, metadata_script): """Add executable permissions to a file. Args: metadata_script: string, the path to the executable file. """ mode = os.stat(metadata_script).st_mode os.chmod(metadata_script, mode | stat.S_IEXEC)
Run a script and log the streamed script output. Args: metadata_key: string, the key specifing the metadata script. metadata_script: string, the file location of an executable script.
def _RunScript(self, metadata_key, metadata_script): """Run a script and log the streamed script output. Args: metadata_key: string, the key specifing the metadata script. metadata_script: string, the file location of an executable script. """ process = subprocess.Popen( metadata_script, shell=True, executable=self.default_shell, stderr=subprocess.STDOUT, stdout=subprocess.PIPE) while True: for line in iter(process.stdout.readline, b''): message = line.decode('utf-8', 'replace').rstrip('\n') if message: self.logger.info('%s: %s', metadata_key, message) if process.poll() is not None: break self.logger.info('%s: Return code %s.', metadata_key, process.returncode)
Run the metadata scripts; execute a URL script first if one is provided. Args: script_dict: a dictionary mapping metadata keys to script files.
def RunScripts(self, script_dict): """Run the metadata scripts; execute a URL script first if one is provided. Args: script_dict: a dictionary mapping metadata keys to script files. """ 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.', self.script_type) for metadata_key in metadata_keys: metadata_script = script_dict.get(metadata_key) self._MakeExecutable(metadata_script) self._RunScript(metadata_key, metadata_script)
Create a file header in the config. Args: fp: int, a file pointer for writing the header.
def _AddHeader(self, fp): """Create a file header in the config. Args: fp: int, a file pointer for writing the header. """ 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')
Get the value of an option in the config file. Args: section: string, the section of the config file to check. option: string, the option to retrieve the value of. Returns: string, the value of the option or None if the option doesn't exist.
def GetOptionString(self, section, option): """Get the value of an option in the config file. Args: section: string, the section of the config file to check. option: string, the option to retrieve the value of. Returns: string, the value of the option or None if the option doesn't exist. """ if self.config.has_option(section, option): return self.config.get(section, option) else: return None
Get the value of an option in the config file. Args: section: string, the section of the config file to check. option: string, the option to retrieve the value of. Returns: bool, True if the option is enabled or not set.
def GetOptionBool(self, section, option): """Get the value of an option in the config file. Args: section: string, the section of the config file to check. option: string, the option to retrieve the value of. Returns: bool, True if the option is enabled or not set. """ return (not self.config.has_option(section, option) or self.config.getboolean(section, option))
Set the value of an option in the config file. Args: section: string, the section of the config file to check. option: string, the option to set the value of. value: string, the value to set the option. overwrite: bool, True to overwrite an existing value in the config file.
def SetOption(self, section, option, value, overwrite=True): """Set the value of an option in the config file. Args: section: string, the section of the config file to check. option: string, the option to set the value of. value: string, the value to set the option. overwrite: bool, True to overwrite an existing value in the config file. """ 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))
Write the config values to a given file. Args: config_file: string, the file location of the config file to write.
def WriteConfig(self, config_file=None): """Write the config values to a given file. Args: config_file: string, the file location of the config file to write. """ 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 open(config_file, 'w') as config_fp: if self.config_header: self._AddHeader(config_fp) self.config.write(config_fp)
Get a logging object with handlers for sending logs to SysLog. Args: name: string, the name of the logger which will be added to log entries. debug: bool, True if debug output should write to the console. facility: int, an encoding of the SysLog handler's facility and priority. Returns: logging object, an object for logging entries.
def Logger(name, debug=False, facility=None): """Get a logging object with handlers for sending logs to SysLog. Args: name: string, the name of the logger which will be added to log entries. debug: bool, True if debug output should write to the console. facility: int, an encoding of the SysLog handler's facility and priority. Returns: logging object, an object for logging entries. """ 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: # Create a handler for console logging. console_handler = logging.StreamHandler() console_handler.setLevel(logging.DEBUG) console_handler.setFormatter(formatter) logger.addHandler(console_handler) if facility: # Create a handler for sending logs to SysLog. syslog_handler = logging.handlers.SysLogHandler( address=constants.SYSLOG_SOCKET, facility=facility) syslog_handler.setLevel(logging.INFO) syslog_handler.setFormatter(formatter) logger.addHandler(syslog_handler) return logger
Create a Linux group for Google added sudo user accounts.
def _CreateSudoersGroup(self): """Create a Linux group for Google added sudo user accounts.""" 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)
Configure a Linux user account. Args: user: string, the name of the Linux user account to create. Returns: bool, True if user creation succeeded.
def _AddUser(self, user): """Configure a Linux user account. Args: user: string, the name of the Linux user account to create. Returns: bool, True if user creation succeeded. """ 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
Update group membership for a Linux user. Args: user: string, the name of the Linux user account. groups: list, the group names to add the user as a member. Returns: bool, True if user update succeeded.
def _UpdateUserGroups(self, user, groups): """Update group membership for a Linux user. Args: user: string, the name of the Linux user account. groups: list, the group names to add the user as a member. Returns: bool, True if user update succeeded. """ 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 the authorized keys file for a Linux user with a list of SSH keys. Args: user: string, the name of the Linux user account. ssh_keys: list, the SSH key strings associated with the user. Raises: IOError, raised when there is an exception updating a file. OSError, raised when setting permissions or writing to a read-only file system.
def _UpdateAuthorizedKeys(self, user, ssh_keys): """Update the authorized keys file for a Linux user with a list of SSH keys. Args: user: string, the name of the Linux user account. ssh_keys: list, the SSH key strings associated with the user. Raises: IOError, raised when there is an exception updating a file. OSError, raised when setting permissions or writing to a read-only file system. """ 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 sudoer group membership for a Linux user account. Args: user: string, the name of the Linux user account. sudoer: bool, True if the user should be a sudoer. Returns: bool, True if user update succeeded.
def _UpdateSudoer(self, user, sudoer=False): """Update sudoer group membership for a Linux user account. Args: user: string, the name of the Linux user account. sudoer: bool, True if the user should be a sudoer. Returns: bool, True if user update succeeded. """ 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
Remove a Linux user account's authorized keys file to prevent login. Args: user: string, the Linux user account to remove access.
def _RemoveAuthorizedKeys(self, user): """Remove a Linux user account's authorized keys file to prevent login. Args: user: string, the Linux user account to remove access. """ 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))
Retrieve the list of configured Google user accounts. Returns: list, the username strings of users congfigured by Google.
def GetConfiguredUsers(self): """Retrieve the list of configured Google user accounts. Returns: list, the username strings of users congfigured by Google. """ if os.path.exists(self.google_users_file): users = open(self.google_users_file).readlines() else: users = [] return [user.strip() for user in users]
Set the list of configured Google user accounts. Args: users: list, the username strings of the Linux accounts.
def SetConfiguredUsers(self, users): """Set the list of configured Google user accounts. Args: users: list, the username strings of the Linux accounts. """ 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)
Update a Linux user with authorized SSH keys. Args: user: string, the name of the Linux user account. ssh_keys: list, the SSH key strings associated with the user. Returns: bool, True if the user account updated successfully.
def UpdateUser(self, user, ssh_keys): """Update a Linux user with authorized SSH keys. Args: user: string, the name of the Linux user account. ssh_keys: list, the SSH key strings associated with the user. Returns: bool, True if the user account updated successfully. """ 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
Remove a Linux user account. Args: user: string, the Linux user account to remove.
def RemoveUser(self, user): """Remove a Linux user account. Args: user: string, the Linux user account to remove. """ 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)
Run the OS Login control script. Args: params: list, the params to pass to the script Returns: int, the return code from the call, or None if the script is not found.
def _RunOsLoginControl(self, params): """Run the OS Login control script. Args: params: list, the params to pass to the script Returns: int, the return code from the call, or None if the script is not found. """ try: return subprocess.call([constants.OSLOGIN_CONTROL_SCRIPT] + params) except OSError as e: if e.errno == errno.ENOENT: return None else: raise
Check whether OS Login is installed. Args: two_factor: bool, True if two factor should be enabled. Returns: bool, True if OS Login is installed.
def _GetStatus(self, two_factor=False): """Check whether OS Login is installed. Args: two_factor: bool, True if two factor should be enabled. Returns: bool, True if OS Login is installed. """ 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
Run the OS Login NSS cache binary. Returns: int, the return code from the call, or None if the script is not found.
def _RunOsLoginNssCache(self): """Run the OS Login NSS cache binary. Returns: int, the return code from the call, or None if the script is not found. """ try: return subprocess.call([constants.OSLOGIN_NSS_CACHE_SCRIPT]) except OSError as e: if e.errno == errno.ENOENT: return None else: raise
Remove the OS Login NSS cache file.
def _RemoveOsLoginNssCache(self): """Remove the OS Login NSS cache file.""" 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
Update whether OS Login is enabled and update NSS cache if necessary. Args: oslogin_desired: bool, enable OS Login if True, disable if False. two_factor_desired: bool, enable two factor if True, disable if False. Returns: int, the return code from updating OS Login, or None if not present.
def UpdateOsLogin(self, oslogin_desired, two_factor_desired=False): """Update whether OS Login is enabled and update NSS cache if necessary. Args: oslogin_desired: bool, enable OS Login if True, disable if False. two_factor_desired: bool, enable two factor if True, disable if False. Returns: int, the return code from updating OS Login, or None if not present. """ 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
Configure the network interfaces using dhclient. Args: interfaces: list of string, the output device names to enable. logger: logger object, used to write to SysLog and serial port. dhclient_script: string, the path to a dhclient script used by dhclient.
def CallDhclient( interfaces, logger, dhclient_script=None): """Configure the network interfaces using dhclient. Args: interfaces: list of string, the output device names to enable. logger: logger object, used to write to SysLog and serial port. dhclient_script: string, the path to a dhclient script used by dhclient. """ 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)
Sync clock using hwclock. Args: logger: logger object, used to write to SysLog and serial port.
def CallHwclock(logger): """Sync clock using hwclock. Args: logger: logger object, used to write to SysLog and serial port. """ 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 ntpdate. Args: logger: logger object, used to write to SysLog and serial port.
def CallNtpdate(logger): """Sync clock using ntpdate. Args: logger: logger object, used to write to SysLog and serial port. """ 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.')
Enable the list of network interfaces. Args: interfaces: list of string, the output device names to enable.
def EnableNetworkInterfaces(self, interfaces): """Enable the list of network interfaces. Args: interfaces: list of string, the output device names to enable. """ # The default Ethernet interface is enabled by default. Do not attempt to # enable interfaces if only one interface is specified in metadata. if not interfaces or set(interfaces) == self.interfaces: return self.logger.info('Ethernet interfaces: %s.', interfaces) self.interfaces = set(interfaces) if self.dhcp_command: try: subprocess.check_call([self.dhcp_command]) except subprocess.CalledProcessError: self.logger.warning('Could not enable Ethernet interfaces.') return # Distro-specific setup for network interfaces. self.distro_utils.EnableNetworkInterfaces( interfaces, self.logger, dhclient_script=self.dhclient_script)
Enable the list of network interfaces. Args: interfaces: list of string, the output device names to enable. logger: logger object, used to write to SysLog and serial port. dhclient_script: string, the path to a dhclient script used by dhclient.
def EnableNetworkInterfaces( self, interfaces, logger, dhclient_script=None): """Enable the list of network interfaces. Args: interfaces: list of string, the output device names to enable. logger: logger object, used to write to SysLog and serial port. dhclient_script: string, the path to a dhclient script used by dhclient. """ helpers.CallDhclient(interfaces, logger, dhclient_script=dhclient_script)
Get the numeric project ID for this VM. Returns: string, the numeric project ID if one is found.
def _GetNumericProjectId(self): """Get the numeric project ID for this VM. Returns: string, the numeric project ID if one is found. """ project_id = 'project/numeric-project-id' return self.watcher.GetMetadata(metadata_key=project_id, recursive=False)
Create the boto config to support standalone GSUtil. Args: project_id: string, the project ID to use in the config file.
def _CreateConfig(self, project_id): """Create the boto config to support standalone GSUtil. Args: project_id: string, the project ID to use in the config file. """ 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 a dictionary of parameters to append to the ip route command. Args: **kwargs: dict, the string parameters to update in the ip route command. Returns: dict, the string parameters to append to the ip route command.
def _CreateRouteOptions(self, **kwargs): """Create a dictionary of parameters to append to the ip route command. Args: **kwargs: dict, the string parameters to update in the ip route command. Returns: dict, the string parameters to append to the ip route command. """ options = { 'proto': self.proto_id, 'scope': 'host', } options.update(kwargs) return options
Run a command with ip route and return the response. Args: args: list, the string ip route command args to execute. options: dict, the string parameters to append to the ip route command. Returns: string, the standard output from the ip route command execution.
def _RunIpRoute(self, args=None, options=None): """Run a command with ip route and return the response. Args: args: list, the string ip route command args to execute. options: dict, the string parameters to append to the ip route command. Returns: string, the standard output from the ip route command execution. """ 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 ''
Parse and validate forwarded IP addresses. Args: forwarded_ips: list, the IP address strings to parse. Returns: list, the valid IP address strings.
def ParseForwardedIps(self, forwarded_ips): """Parse and validate forwarded IP addresses. Args: forwarded_ips: list, the IP address strings to parse. Returns: list, the valid IP address strings. """ addresses = [] forwarded_ips = forwarded_ips or [] for ip in forwarded_ips: if ip and (IP_REGEX.match(ip) or IP_ALIAS_REGEX.match(ip)): addresses.append(ip[:-3] if ip.endswith('/32') else ip) else: self.logger.warning('Could not parse IP address: "%s".', ip) return addresses
Retrieve the list of configured forwarded IP addresses. Args: interface: string, the output device to query. interface_ip: string, current interface ip address. Returns: list, the IP address strings.
def GetForwardedIps(self, interface, interface_ip=None): """Retrieve the list of configured forwarded IP addresses. Args: interface: string, the output device to query. interface_ip: string, current interface ip address. Returns: list, the IP address strings. """ args = ['ls', 'table', 'local', 'type', 'local'] options = self._CreateRouteOptions(dev=interface) result = self._RunIpRoute(args=args, options=options) result = re.sub(r'local\s', r'', result) return self.ParseForwardedIps(result.split())
Configure a new IP address on the network interface. Args: address: string, the IP address to configure. interface: string, the output device to use.
def AddForwardedIp(self, address, interface): """Configure a new IP address on the network interface. Args: address: string, the IP address to configure. interface: string, the output device to use. """ address = address if IP_ALIAS_REGEX.match(address) else '%s/32' % address args = ['add', 'to', 'local', address] options = self._CreateRouteOptions(dev=interface) self._RunIpRoute(args=args, options=options)
Parse and validate forwarded IP addresses. Args: forwarded_ips: list, the IP address strings to parse. Returns: list, the valid IP address strings.
def ParseForwardedIps(self, forwarded_ips): """Parse and validate forwarded IP addresses. Args: forwarded_ips: list, the IP address strings to parse. Returns: list, the valid IP address strings. """ addresses = [] forwarded_ips = forwarded_ips or [] for ip in forwarded_ips: if ip and (IP_REGEX.match(ip) or IP_ALIAS_REGEX.match(ip)): addresses.extend([str(addr) for addr in list(netaddr.IPNetwork(ip))]) else: self.logger.warning('Could not parse IP address: "%s".', ip) return addresses
Retrieve the list of configured forwarded IP addresses. Args: interface: string, the output device to query. interface_ip: string, current interface ip address. Returns: list, the IP address strings.
def GetForwardedIps(self, interface, interface_ip=None): """Retrieve the list of configured forwarded IP addresses. Args: interface: string, the output device to query. interface_ip: string, current interface ip address. Returns: list, the IP address strings. """ try: ips = netifaces.ifaddresses(interface) ips = ips[netifaces.AF_INET] except (ValueError, IndexError): return [] forwarded_ips = [] for ip in ips: if ip['addr'] != interface_ip: full_addr = '%s/%d' % (ip['addr'], netaddr.IPAddress(ip['netmask']).netmask_bits()) forwarded_ips.append(full_addr) return self.ParseForwardedIps(forwarded_ips)
Configure a new IP address on the network interface. Args: address: string, the IP address to configure. interface: string, the output device to use.
def AddForwardedIp(self, address, interface): """Configure a new IP address on the network interface. Args: address: string, the IP address to configure. interface: string, the output device to use. """ for ip in list(netaddr.IPNetwork(address)): self._RunIfconfig(args=[interface, 'alias', '%s/32' % str(ip)])
Delete an IP address on the network interface. Args: address: string, the IP address to configure. interface: string, the output device to use.
def RemoveForwardedIp(self, address, interface): """Delete an IP address on the network interface. Args: address: string, the IP address to configure. interface: string, the output device to use. """ ip = netaddr.IPNetwork(address) self._RunIfconfig(args=[interface, '-alias', str(ip.ip)])
Return all Google Storage scopes available on this VM.
def _GetGsScopes(self): """Return all Google Storage scopes available on this VM.""" 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 an OAuth 2.0 access token for Google Storage.
def _GetAccessToken(self): """Return an OAuth 2.0 access token for Google Storage.""" service_accounts = self.watcher.GetMetadata(metadata_key=self.metadata_key) try: return service_accounts[self.service_account]['token']['access_token'] except KeyError: return None
Called when clock drift token changes. Args: response: string, the metadata response with the new drift token value.
def HandleClockSync(self, response): """Called when clock drift token changes. Args: response: string, the metadata response with the new drift token value. """ self.logger.info('Clock drift token has changed: %s.', response) self.distro_utils.HandleClockSync(self.logger)
Enable the list of network interfaces. Args: interfaces: list of string, the output device names to enable. logger: logger object, used to write to SysLog and serial port. dhclient_script: string, the path to a dhclient script used by dhclient.
def EnableNetworkInterfaces( self, interfaces, logger, dhclient_script=None): """Enable the list of network interfaces. Args: interfaces: list of string, the output device names to enable. logger: logger object, used to write to SysLog and serial port. dhclient_script: string, the path to a dhclient script used by dhclient. """ # Should always exist in EL 7. if os.path.exists(self.network_path): self._DisableNetworkManager(interfaces, logger) helpers.CallDhclient(interfaces, logger)
Disable network manager management on a list of network interfaces. Args: interfaces: list of string, the output device names enable. logger: logger object, used to write to SysLog and serial port.
def _DisableNetworkManager(self, interfaces, logger): """Disable network manager management on a list of network interfaces. Args: interfaces: list of string, the output device names enable. logger: logger object, used to write to SysLog and serial port. """ 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)
Write a value to a config file if not already present. Args: interface_config: string, the path to a config file. config_key: string, the configuration key to set. config_value: string, the value to set for the configuration key. replace: bool, replace the configuration option if already present.
def _ModifyInterface( self, interface_config, config_key, config_value, replace=False): """Write a value to a config file if not already present. Args: interface_config: string, the path to a config file. config_key: string, the configuration key to set. config_value: string, the value to set for the configuration key. replace: bool, replace the configuration option if already present. """ 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()))
Check whether an SSH key has expired. Uses Google-specific semantics of the OpenSSH public key format's comment field to determine if an SSH key is past its expiration timestamp, and therefore no longer to be trusted. This format is still subject to change. Reliance on it in any way is at your own risk. Args: key: string, a single public key entry in OpenSSH public key file format. This will be checked for Google-specific comment semantics, and if present, those will be analysed. Returns: bool, True if the key has Google-specific comment semantics and has an expiration timestamp in the past, or False otherwise.
def _HasExpired(self, key): """Check whether an SSH key has expired. Uses Google-specific semantics of the OpenSSH public key format's comment field to determine if an SSH key is past its expiration timestamp, and therefore no longer to be trusted. This format is still subject to change. Reliance on it in any way is at your own risk. Args: key: string, a single public key entry in OpenSSH public key file format. This will be checked for Google-specific comment semantics, and if present, those will be analysed. Returns: bool, True if the key has Google-specific comment semantics and has an expiration timestamp in the past, or False otherwise. """ 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
Parse the SSH key data into a user map. Args: account_data: string, the metadata server SSH key attributes data. Returns: dict, a mapping of the form: {'username': ['sshkey1, 'sshkey2', ...]}.
def _ParseAccountsData(self, account_data): """Parse the SSH key data into a user map. Args: account_data: string, the metadata server SSH key attributes data. Returns: dict, a mapping of the form: {'username': ['sshkey1, 'sshkey2', ...]}. """ 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
Get dictionaries for instance and project attributes. Args: metadata_dict: json, the deserialized contents of the metadata server. Returns: tuple, two dictionaries for instance and project attributes.
def _GetInstanceAndProjectAttributes(self, metadata_dict): """Get dictionaries for instance and project attributes. Args: metadata_dict: json, the deserialized contents of the metadata server. Returns: tuple, two dictionaries for instance and project attributes. """ 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 the user accounts specified in metadata server contents. Args: metadata_dict: json, the deserialized contents of the metadata server. Returns: dict, a mapping of the form: {'username': ['sshkey1, 'sshkey2', ...]}.
def _GetAccountsData(self, metadata_dict): """Get the user accounts specified in metadata server contents. Args: metadata_dict: json, the deserialized contents of the metadata server. Returns: dict, a mapping of the form: {'username': ['sshkey1, 'sshkey2', ...]}. """ 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)
Provision and update Linux user accounts based on account metadata. Args: update_users: dict, authorized users mapped to their public SSH keys.
def _UpdateUsers(self, update_users): """Provision and update Linux user accounts based on account metadata. Args: update_users: dict, authorized users mapped to their public SSH keys. """ 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[:]
Deprovision Linux user accounts that do not appear in account metadata. Args: remove_users: list, the username strings of the Linux accounts to remove.
def _RemoveUsers(self, remove_users): """Deprovision Linux user accounts that do not appear in account metadata. Args: remove_users: list, the username strings of the Linux accounts to remove. """ for username in remove_users: self.utils.RemoveUser(username) self.user_ssh_keys.pop(username, None) self.invalid_users -= set(remove_users)
Get the value of the enable-oslogin metadata key. Args: metadata_dict: json, the deserialized contents of the metadata server. Returns: bool, True if OS Login is enabled for VM access.
def _GetEnableOsLoginValue(self, metadata_dict): """Get the value of the enable-oslogin metadata key. Args: metadata_dict: json, the deserialized contents of the metadata server. Returns: bool, True if OS Login is enabled for VM access. """ 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'
Called when there are changes to the contents of the metadata server. Args: result: json, the deserialized contents of the metadata server.
def HandleAccounts(self, result): """Called when there are changes to the contents of the metadata server. Args: result: json, the deserialized contents of the metadata server. """ 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())
Set the appropriate SELinux context, if SELinux tools are installed. Calls /sbin/restorecon on the provided path to set the SELinux context as specified by policy. This call does not operate recursively. Only some OS configurations use SELinux. It is therefore acceptable for restorecon to be missing, in which case we do nothing. Args: path: string, the path on which to fix the SELinux context.
def _SetSELinuxContext(path): """Set the appropriate SELinux context, if SELinux tools are installed. Calls /sbin/restorecon on the provided path to set the SELinux context as specified by policy. This call does not operate recursively. Only some OS configurations use SELinux. It is therefore acceptable for restorecon to be missing, in which case we do nothing. Args: path: string, the path on which to fix the SELinux context. """ restorecon = '/sbin/restorecon' if os.path.isfile(restorecon) and os.access(restorecon, os.X_OK): subprocess.call([restorecon, path])
Set the permissions and ownership of a path. Args: path: string, the path for which owner ID and group ID needs to be setup. mode: octal string, the permissions to set on the path. uid: int, the owner ID to be set for the path. gid: int, the group ID to be set for the path. mkdir: bool, True if the directory needs to be created.
def SetPermissions(path, mode=None, uid=None, gid=None, mkdir=False): """Set the permissions and ownership of a path. Args: path: string, the path for which owner ID and group ID needs to be setup. mode: octal string, the permissions to set on the path. uid: int, the owner ID to be set for the path. gid: int, the group ID to be set for the path. mkdir: bool, True if the directory needs to be created. """ 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)
Lock the provided file descriptor. Args: fd: int, the file descriptor of the file to lock. path: string, the name of the file to lock. blocking: bool, whether the function should return immediately. Raises: IOError, raised from flock while attempting to lock a file.
def Lock(fd, path, blocking): """Lock the provided file descriptor. Args: fd: int, the file descriptor of the file to lock. path: string, the name of the file to lock. blocking: bool, whether the function should return immediately. Raises: IOError, raised from flock while attempting to lock a file. """ 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)))
Release the lock on the file. Args: fd: int, the file descriptor of the file to unlock. path: string, the name of the file to lock. Raises: IOError, raised from flock while attempting to release a file lock.
def Unlock(fd, path): """Release the lock on the file. Args: fd: int, the file descriptor of the file to unlock. path: string, the name of the file to lock. Raises: IOError, raised from flock while attempting to release a file lock. """ 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)))
Interface to flock-based file locking to prevent concurrent executions. Args: path: string, the name of the file to lock. blocking: bool, whether the function should return immediately. Yields: None, yields when a lock on the file is obtained. Raises: IOError, raised from flock locking operations on a file. OSError, raised from file operations.
def LockFile(path, blocking=False): """Interface to flock-based file locking to prevent concurrent executions. Args: path: string, the name of the file to lock. blocking: bool, whether the function should return immediately. Yields: None, yields when a lock on the file is obtained. Raises: IOError, raised from flock locking operations on a file. OSError, raised from file operations. """ fd = os.open(path, os.O_CREAT) try: Lock(fd, path, blocking) yield finally: try: Unlock(fd, path) finally: os.close(fd)
Function decorator to retry on a service unavailable exception.
def RetryOnUnavailable(func): """Function decorator to retry on a service unavailable exception.""" @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
Performs a GET request with the metadata headers. Args: metadata_url: string, the URL to perform a GET request on. params: dictionary, the query parameters in the GET request. timeout: int, timeout in seconds for metadata requests. Returns: HTTP response from the GET request. Raises: urlerror.HTTPError: raises when the GET request fails.
def _GetMetadataRequest(self, metadata_url, params=None, timeout=None): """Performs a GET request with the metadata headers. Args: metadata_url: string, the URL to perform a GET request on. params: dictionary, the query parameters in the GET request. timeout: int, timeout in seconds for metadata requests. Returns: HTTP response from the GET request. Raises: urlerror.HTTPError: raises when the GET request fails. """ 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)
Update the etag from an API response. Args: response: HTTP response with a header field. Returns: bool, True if the etag in the response header updated.
def _UpdateEtag(self, response): """Update the etag from an API response. Args: response: HTTP response with a header field. Returns: bool, True if the etag in the response header updated. """ etag = response.headers.get('etag', self.etag) etag_updated = self.etag != etag self.etag = etag return etag_updated
Request the contents of metadata server and deserialize the response. Args: metadata_key: string, the metadata key to watch for changes. recursive: bool, True if we should recursively watch for metadata changes. wait: bool, True if we should wait for a metadata change. timeout: int, timeout in seconds for returning metadata output. Returns: json, the deserialized contents of the metadata server.
def _GetMetadataUpdate( self, metadata_key='', recursive=True, wait=True, timeout=None): """Request the contents of metadata server and deserialize the response. Args: metadata_key: string, the metadata key to watch for changes. recursive: bool, True if we should recursively watch for metadata changes. wait: bool, True if we should wait for a metadata change. timeout: int, timeout in seconds for returning metadata output. Returns: json, the deserialized contents of the metadata server. """ 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'))
Wait for a successful metadata response. Args: metadata_key: string, the metadata key to watch for changes. recursive: bool, True if we should recursively watch for metadata changes. wait: bool, True if we should wait for a metadata change. timeout: int, timeout in seconds for returning metadata output. retry: bool, True if we should retry on failure. Returns: json, the deserialized contents of the metadata server.
def _HandleMetadataUpdate( self, metadata_key='', recursive=True, wait=True, timeout=None, retry=True): """Wait for a successful metadata response. Args: metadata_key: string, the metadata key to watch for changes. recursive: bool, True if we should recursively watch for metadata changes. wait: bool, True if we should wait for a metadata change. timeout: int, timeout in seconds for returning metadata output. retry: bool, True if we should retry on failure. Returns: json, the deserialized contents of the metadata server. """ 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
Watch for changes to the contents of the metadata server. Args: handler: callable, a function to call with the updated metadata contents. metadata_key: string, the metadata key to watch for changes. recursive: bool, True if we should recursively watch for metadata changes. timeout: int, timeout in seconds for returning metadata output.
def WatchMetadata( self, handler, metadata_key='', recursive=True, timeout=None): """Watch for changes to the contents of the metadata server. Args: handler: callable, a function to call with the updated metadata contents. metadata_key: string, the metadata key to watch for changes. recursive: bool, True if we should recursively watch for metadata changes. timeout: int, timeout in seconds for returning metadata output. """ 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)
Retrieve the contents of metadata server for a metadata key. Args: metadata_key: string, the metadata key to watch for changes. recursive: bool, True if we should recursively watch for metadata changes. timeout: int, timeout in seconds for returning metadata output. retry: bool, True if we should retry on failure. Returns: json, the deserialized contents of the metadata server or None if error.
def GetMetadata( self, metadata_key='', recursive=True, timeout=None, retry=True): """Retrieve the contents of metadata server for a metadata key. Args: metadata_key: string, the metadata key to watch for changes. recursive: bool, True if we should recursively watch for metadata changes. timeout: int, timeout in seconds for returning metadata output. retry: bool, True if we should retry on failure. Returns: json, the deserialized contents of the metadata server or None if error. """ return self._HandleMetadataUpdate( metadata_key=metadata_key, recursive=recursive, wait=False, timeout=timeout, retry=retry)
Log the planned IP address changes. Args: configured: list, the IP address strings already configured. desired: list, the IP address strings that will be configured. to_add: list, the forwarded IP address strings to configure. to_remove: list, the forwarded IP address strings to delete. interface: string, the output device to modify.
def _LogForwardedIpChanges( self, configured, desired, to_add, to_remove, interface): """Log the planned IP address changes. Args: configured: list, the IP address strings already configured. desired: list, the IP address strings that will be configured. to_add: list, the forwarded IP address strings to configure. to_remove: list, the forwarded IP address strings to delete. interface: string, the output device to modify. """ 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)
Configure the forwarded IP address on the network interface. Args: forwarded_ips: list, the forwarded IP address strings to configure. interface: string, the output device to use.
def _AddForwardedIps(self, forwarded_ips, interface): """Configure the forwarded IP address on the network interface. Args: forwarded_ips: list, the forwarded IP address strings to configure. interface: string, the output device to use. """ for address in forwarded_ips: self.ip_forwarding_utils.AddForwardedIp(address, interface)
Remove the forwarded IP addresses from the network interface. Args: forwarded_ips: list, the forwarded IP address strings to delete. interface: string, the output device to use.
def _RemoveForwardedIps(self, forwarded_ips, interface): """Remove the forwarded IP addresses from the network interface. Args: forwarded_ips: list, the forwarded IP address strings to delete. interface: string, the output device to use. """ for address in forwarded_ips: self.ip_forwarding_utils.RemoveForwardedIp(address, interface)
Handle changes to the forwarded IPs on a network interface. Args: interface: string, the output device to configure. forwarded_ips: list, the forwarded IP address strings desired. interface_ip: string, current interface ip address.
def HandleForwardedIps(self, interface, forwarded_ips, interface_ip=None): """Handle changes to the forwarded IPs on a network interface. Args: interface: string, the output device to configure. forwarded_ips: list, the forwarded IP address strings desired. interface_ip: string, current interface ip address. """ 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)
Enable the list of network interfaces. Args: interfaces: list of string, the output device names to enable. logger: logger object, used to write to SysLog and serial port. dhclient_script: string, the path to a dhclient script used by dhclient.
def EnableNetworkInterfaces( self, interfaces, logger, dhclient_script=None): """Enable the list of network interfaces. Args: interfaces: list of string, the output device names to enable. logger: logger object, used to write to SysLog and serial port. dhclient_script: string, the path to a dhclient script used by dhclient. """ interfaces_to_up = [i for i in interfaces if i != 'eth0'] if interfaces_to_up: logger.info('Enabling the Ethernet interfaces %s.', interfaces_to_up) self._WriteIfcfg(interfaces_to_up, logger) self._Ifup(interfaces_to_up, logger)
Write ifcfg files for multi-NIC support. Overwrites the files. This allows us to update ifcfg-* in the future. Disable the network setup to override this behavior and customize the configurations. Args: interfaces: list of string, the output device names to enable. logger: logger object, used to write to SysLog and serial port.
def _WriteIfcfg(self, interfaces, logger): """Write ifcfg files for multi-NIC support. Overwrites the files. This allows us to update ifcfg-* in the future. Disable the network setup to override this behavior and customize the configurations. Args: interfaces: list of string, the output device names to enable. logger: logger object, used to write to SysLog and serial port. """ 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)
Activate network interfaces. Args: interfaces: list of string, the output device names to enable. logger: logger object, used to write to SysLog and serial port.
def _Ifup(self, interfaces, logger): """Activate network interfaces. Args: interfaces: list of string, the output device names to enable. logger: logger object, used to write to SysLog and serial port. """ ifup = ['/usr/sbin/wicked', 'ifup', '--timeout', '1'] try: subprocess.check_call(ifup + interfaces) except subprocess.CalledProcessError: logger.warning('Could not activate interfaces %s.', interfaces)
Called when network interface metadata changes. Args: result: dict, the metadata response with the network interfaces.
def HandleNetworkInterfaces(self, result): """Called when network interface metadata changes. Args: result: dict, the metadata response with the network interfaces. """ 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)
Extracts network interface metadata. Args: metadata: dict, the metadata response with the new network interfaces. Returns: list, a list of NetworkInterface objects.
def _ExtractInterfaceMetadata(self, metadata): """Extracts network interface metadata. Args: metadata: dict, the metadata response with the new network interfaces. Returns: list, a list of NetworkInterface objects. """ 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
Subclass this function for your own needs. Or just pass the version as part of the URL (e.g. client._('/v3')) :param url: URI portion of the full URL being requested :type url: string :return: string
def _build_versioned_url(self, url): """Subclass this function for your own needs. Or just pass the version as part of the URL (e.g. client._('/v3')) :param url: URI portion of the full URL being requested :type url: string :return: string """ return '{}/v{}{}'.format(self.host, str(self._version), url)
Build the final URL to be passed to urllib :param query_params: A dictionary of all the query parameters :type query_params: dictionary :return: string
def _build_url(self, query_params): """Build the final URL to be passed to urllib :param query_params: A dictionary of all the query parameters :type query_params: dictionary :return: string """ 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
Make a new Client object :param name: Name of the url segment :type name: string :return: A Client object
def _build_client(self, name=None): """Make a new Client object :param name: Name of the url segment :type name: string :return: A Client object """ 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 the API call and return the response. This is separated into it's own function, so we can mock it easily for testing. :param opener: :type opener: :param request: url payload to request :type request: urllib.Request object :param timeout: timeout value or None :type timeout: float :return: urllib response
def _make_request(self, opener, request, timeout=None): """Make the API call and return the response. This is separated into it's own function, so we can mock it easily for testing. :param opener: :type opener: :param request: url payload to request :type request: urllib.Request object :param timeout: timeout value or None :type timeout: float :return: urllib response """ 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
Aircraft category number Args: msg (string): 28 bytes hexadecimal message string Returns: int: category number
def category(msg): """Aircraft category number Args: msg (string): 28 bytes hexadecimal message string Returns: int: category number """ 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 callsign Args: msg (string): 28 bytes hexadecimal message string Returns: string: callsign
def callsign(msg): """Aircraft callsign Args: msg (string): 28 bytes hexadecimal message string Returns: string: callsign """ if common.typecode(msg) < 1 or common.typecode(msg) > 4: raise RuntimeError("%s: Not a identification message" % msg) chars = '#ABCDEFGHIJKLMNOPQRSTUVWXYZ#####_###############0123456789######' msgbin = common.hex2bin(msg) csbin = msgbin[40:96] cs = '' cs += chars[common.bin2int(csbin[0:6])] cs += chars[common.bin2int(csbin[6:12])] cs += chars[common.bin2int(csbin[12:18])] cs += chars[common.bin2int(csbin[18:24])] cs += chars[common.bin2int(csbin[24:30])] cs += chars[common.bin2int(csbin[30:36])] cs += chars[common.bin2int(csbin[36:42])] cs += chars[common.bin2int(csbin[42:48])] # clean string, remove spaces and marks, if any. # cs = cs.replace('_', '') cs = cs.replace('#', '') return cs
Decode airborn position from a pair of even and odd position message Args: msg0 (string): even message (28 bytes hexadecimal string) msg1 (string): odd message (28 bytes hexadecimal string) t0 (int): timestamps for the even message t1 (int): timestamps for the odd message Returns: (float, float): (latitude, longitude) of the aircraft
def airborne_position(msg0, msg1, t0, t1): """Decode airborn position from a pair of even and odd position message Args: msg0 (string): even message (28 bytes hexadecimal string) msg1 (string): odd message (28 bytes hexadecimal string) t0 (int): timestamps for the even message t1 (int): timestamps for the odd message Returns: (float, float): (latitude, longitude) of the aircraft """ 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 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. Args: msg (string): even message (28 bytes hexadecimal string) lat_ref: previous known latitude lon_ref: previous known longitude Returns: (float, float): (latitude, longitude) of the aircraft
def airborne_position_with_ref(msg, lat_ref, lon_ref): """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. Args: msg (string): even message (28 bytes hexadecimal string) lat_ref: previous known latitude lon_ref: previous known longitude Returns: (float, float): (latitude, longitude) of the aircraft """ 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 aircraft altitude Args: msg (string): 28 bytes hexadecimal message string Returns: int: altitude in feet
def altitude(msg): """Decode aircraft altitude Args: msg (string): 28 bytes hexadecimal message string Returns: int: altitude in feet """ tc = common.typecode(msg) if tc<9 or tc==19 or tc>22: raise RuntimeError("%s: Not a airborn position message" % msg) mb = common.hex2bin(msg)[32:] if tc < 19: # barometric altitude q = mb[15] if q: n = common.bin2int(mb[8:15]+mb[16:20]) alt = n * 25 - 1000 else: alt = None else: # GNSS altitude, meters -> feet alt = common.bin2int(mb[8:20]) * 3.28084 return alt
Convert a hexdecimal string to binary string, with zero fillings.
def hex2bin(hexstr): """Convert a hexdecimal string to binary string, with zero fillings. """ num_of_bits = len(hexstr) * 4 binstr = bin(int(hexstr, 16))[2:].zfill(int(num_of_bits)) return binstr
Mode-S Cyclic Redundancy Check Detect if bit error occurs in the Mode-S message Args: msg (string): 28 bytes hexadecimal message string encode (bool): True to encode the date only and return the checksum Returns: string: message checksum, or partity bits (encoder)
def crc(msg, encode=False): """Mode-S Cyclic Redundancy Check Detect if bit error occurs in the Mode-S message Args: msg (string): 28 bytes hexadecimal message string encode (bool): True to encode the date only and return the checksum Returns: string: message checksum, or partity bits (encoder) """ # the polynominal generattor code for CRC [1111111111111010000001001] generator = np.array([1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,0,0,0,0,0,1,0,0,1]) ng = len(generator) msgnpbin = bin2np(hex2bin(msg)) if encode: msgnpbin[-24:] = [0] * 24 # loop all bits, except last 24 piraty bits for i in range(len(msgnpbin)-24): if msgnpbin[i] == 0: continue # perform XOR, when 1 msgnpbin[i:i+ng] = np.bitwise_xor(msgnpbin[i:i+ng], generator) # last 24 bits reminder = np2bin(msgnpbin[-24:]) return reminder
Calculate the ICAO address from an Mode-S message with DF4, DF5, DF20, DF21 Args: msg (String): 28 bytes hexadecimal message string Returns: String: ICAO address in 6 bytes hexadecimal string
def icao(msg): """Calculate the ICAO address from an Mode-S message with DF4, DF5, DF20, DF21 Args: msg (String): 28 bytes hexadecimal message string Returns: String: ICAO address in 6 bytes hexadecimal string """ 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
Check whether the ICAO address is assigned (Annex 10, Vol 3)
def is_icao_assigned(icao): """ Check whether the ICAO address is assigned (Annex 10, Vol 3)""" if (icao is None) or (not isinstance(icao, str)) or (len(icao)!=6): return False icaoint = hex2int(icao) if 0x200000 < icaoint < 0x27FFFF: return False # AFI if 0x280000 < icaoint < 0x28FFFF: return False # SAM if 0x500000 < icaoint < 0x5FFFFF: return False # EUR, NAT if 0x600000 < icaoint < 0x67FFFF: return False # MID if 0x680000 < icaoint < 0x6F0000: return False # ASIA if 0x900000 < icaoint < 0x9FFFFF: return False # NAM, PAC if 0xB00000 < icaoint < 0xBFFFFF: return False # CAR if 0xD00000 < icaoint < 0xDFFFFF: return False # future if 0xF00000 < icaoint < 0xFFFFFF: return False # future return True
NL() function in CPR decoding
def cprNL(lat): """NL() function in CPR decoding""" if lat == 0: return 59 if lat == 87 or lat == -87: return 2 if lat > 87 or lat < -87: return 1 nz = 15 a = 1 - np.cos(np.pi / (2 * nz)) b = np.cos(np.pi / 180.0 * abs(lat)) ** 2 nl = 2 * np.pi / (np.arccos(1 - a/b)) NL = floor(nl) return NL
Computes identity (squawk code) from DF5 or DF21 message, bit 20-32. credit: @fbyrkjeland Args: msg (String): 28 bytes hexadecimal message string Returns: string: squawk code
def idcode(msg): """Computes identity (squawk code) from DF5 or DF21 message, bit 20-32. credit: @fbyrkjeland Args: msg (String): 28 bytes hexadecimal message string Returns: string: squawk code """ if df(msg) not in [5, 21]: raise RuntimeError("Message must be Downlink Format 5 or 21.") mbin = hex2bin(msg) C1 = mbin[19] A1 = mbin[20] C2 = mbin[21] A2 = mbin[22] C4 = mbin[23] A4 = mbin[24] # _ = mbin[25] B1 = mbin[26] D1 = mbin[27] B2 = mbin[28] D2 = mbin[29] B4 = mbin[30] D4 = mbin[31] byte1 = int(A4+A2+A1, 2) byte2 = int(B4+B2+B1, 2) byte3 = int(C4+C2+C1, 2) byte4 = int(D4+D2+D1, 2) return str(byte1) + str(byte2) + str(byte3) + str(byte4)
Computes the altitude from DF4 or DF20 message, bit 20-32. credit: @fbyrkjeland Args: msg (String): 28 bytes hexadecimal message string Returns: int: altitude in ft
def altcode(msg): """Computes the altitude from DF4 or DF20 message, bit 20-32. credit: @fbyrkjeland Args: msg (String): 28 bytes hexadecimal message string Returns: int: altitude in ft """ if df(msg) not in [0, 4, 16, 20]: raise RuntimeError("Message must be Downlink Format 0, 4, 16, or 20.") # Altitude code, bit 20-32 mbin = hex2bin(msg) mbit = mbin[25] # M bit: 26 qbit = mbin[27] # Q bit: 28 if mbit == '0': # unit in ft if qbit == '1': # 25ft interval vbin = mbin[19:25] + mbin[26] + mbin[28:32] alt = bin2int(vbin) * 25 - 1000 if qbit == '0': # 100ft interval, above 50175ft C1 = mbin[19] A1 = mbin[20] C2 = mbin[21] A2 = mbin[22] C4 = mbin[23] A4 = mbin[24] # _ = mbin[25] B1 = mbin[26] # D1 = mbin[27] # always zero B2 = mbin[28] D2 = mbin[29] B4 = mbin[30] D4 = mbin[31] graystr = D2 + D4 + A1 + A2 + A4 + B1 + B2 + B4 + C1 + C2 + C4 alt = gray2alt(graystr) if mbit == '1': # unit in meter vbin = mbin[19:25] + mbin[26:31] alt = int(bin2int(vbin) * 3.28084) # convert to ft return alt
Convert greycode to binary
def gray2int(graystr): """Convert greycode to binary""" num = bin2int(graystr) num ^= (num >> 8) num ^= (num >> 4) num ^= (num >> 2) num ^= (num >> 1) return num
check if the data bits are all zeros Args: msg (String): 28 bytes hexadecimal message string Returns: bool: True or False
def allzeros(msg): """check if the data bits are all zeros Args: msg (String): 28 bytes hexadecimal message string Returns: bool: True or False """ d = hex2bin(data(msg)) if bin2int(d) > 0: return False else: return True