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 ...
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 t...
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 storin...
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. ...
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 = tempfil...
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. """ ...
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 meta...
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...
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_sc...
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...
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....
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 (no...
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, Tru...
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 = (...
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 ob...
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'...
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.Called...
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=u...
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) ...
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 setti...
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 exc...
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: s...
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...
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 [u...
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: u...
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 bo...
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(' ')) ...
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] + par...
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._Run...
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: retu...
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: ...
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 scrip...
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 hard...
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(...
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...
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 ...
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: ...
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 = { ...
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 ...
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: ...
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', 't...
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 = ['a...
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: ...
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 =...
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, 'al...
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 ...
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 ...
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: ...
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 pr...
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 ...
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...
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 o...
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 {} l...
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 = met...
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, pro...
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: continu...
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(use...
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._GetInstan...
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() ...
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...
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 ...
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 t...
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. ...
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 fi...
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) 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 operatio...
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: IO...
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....
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. Rais...
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 metad...
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....
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...
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 metadat...
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 met...
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 change...
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, tim...
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. rec...
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 ...
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. ...
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. ...
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 a...
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_forwar...
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_forwa...
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 inter...
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 ...
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, u...
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 devi...
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...
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.EnableN...
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_ad...
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...
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): ...
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, ...
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 ...
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: url...
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 = comm...
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 = '#ABCDEFGHIJKLMN...
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 Retur...
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 t...
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)...
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: ...
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 = com...
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...
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...
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 < 0x28FF...
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 ...
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 Downlin...
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 ...
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