id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
12,400
juju/charm-helpers
charmhelpers/contrib/amulet/utils.py
AmuletUtils.service_restarted
def service_restarted(self, sentry_unit, service, filename, pgrep_full=None, sleep_time=20): """Check if service was restarted. Compare a service's start time vs a file's last modification time (such as a config file for that service) to determine if the service has been restarted. """ # /!\ DEPRECATION WARNING (beisner): # This method is prone to races in that no before-time is known. # Use validate_service_config_changed instead. # NOTE(beisner) pgrep_full is no longer implemented, as pidof is now # used instead of pgrep. pgrep_full is still passed through to ensure # deprecation WARNS. lp1474030 self.log.warn('DEPRECATION WARNING: use ' 'validate_service_config_changed instead of ' 'service_restarted due to known races.') time.sleep(sleep_time) if (self._get_proc_start_time(sentry_unit, service, pgrep_full) >= self._get_file_mtime(sentry_unit, filename)): return True else: return False
python
def service_restarted(self, sentry_unit, service, filename, pgrep_full=None, sleep_time=20): """Check if service was restarted. Compare a service's start time vs a file's last modification time (such as a config file for that service) to determine if the service has been restarted. """ # /!\ DEPRECATION WARNING (beisner): # This method is prone to races in that no before-time is known. # Use validate_service_config_changed instead. # NOTE(beisner) pgrep_full is no longer implemented, as pidof is now # used instead of pgrep. pgrep_full is still passed through to ensure # deprecation WARNS. lp1474030 self.log.warn('DEPRECATION WARNING: use ' 'validate_service_config_changed instead of ' 'service_restarted due to known races.') time.sleep(sleep_time) if (self._get_proc_start_time(sentry_unit, service, pgrep_full) >= self._get_file_mtime(sentry_unit, filename)): return True else: return False
[ "def", "service_restarted", "(", "self", ",", "sentry_unit", ",", "service", ",", "filename", ",", "pgrep_full", "=", "None", ",", "sleep_time", "=", "20", ")", ":", "# /!\\ DEPRECATION WARNING (beisner):", "# This method is prone to races in that no before-time is known.", "# Use validate_service_config_changed instead.", "# NOTE(beisner) pgrep_full is no longer implemented, as pidof is now", "# used instead of pgrep. pgrep_full is still passed through to ensure", "# deprecation WARNS. lp1474030", "self", ".", "log", ".", "warn", "(", "'DEPRECATION WARNING: use '", "'validate_service_config_changed instead of '", "'service_restarted due to known races.'", ")", "time", ".", "sleep", "(", "sleep_time", ")", "if", "(", "self", ".", "_get_proc_start_time", "(", "sentry_unit", ",", "service", ",", "pgrep_full", ")", ">=", "self", ".", "_get_file_mtime", "(", "sentry_unit", ",", "filename", ")", ")", ":", "return", "True", "else", ":", "return", "False" ]
Check if service was restarted. Compare a service's start time vs a file's last modification time (such as a config file for that service) to determine if the service has been restarted.
[ "Check", "if", "service", "was", "restarted", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/amulet/utils.py#L294-L318
12,401
juju/charm-helpers
charmhelpers/contrib/amulet/utils.py
AmuletUtils.service_restarted_since
def service_restarted_since(self, sentry_unit, mtime, service, pgrep_full=None, sleep_time=20, retry_count=30, retry_sleep_time=10): """Check if service was been started after a given time. Args: sentry_unit (sentry): The sentry unit to check for the service on mtime (float): The epoch time to check against service (string): service name to look for in process table pgrep_full: [Deprecated] Use full command line search mode with pgrep sleep_time (int): Initial sleep time (s) before looking for file retry_sleep_time (int): Time (s) to sleep between retries retry_count (int): If file is not found, how many times to retry Returns: bool: True if service found and its start time it newer than mtime, False if service is older than mtime or if service was not found. """ # NOTE(beisner) pgrep_full is no longer implemented, as pidof is now # used instead of pgrep. pgrep_full is still passed through to ensure # deprecation WARNS. lp1474030 unit_name = sentry_unit.info['unit_name'] self.log.debug('Checking that %s service restarted since %s on ' '%s' % (service, mtime, unit_name)) time.sleep(sleep_time) proc_start_time = None tries = 0 while tries <= retry_count and not proc_start_time: try: proc_start_time = self._get_proc_start_time(sentry_unit, service, pgrep_full) self.log.debug('Attempt {} to get {} proc start time on {} ' 'OK'.format(tries, service, unit_name)) except IOError as e: # NOTE(beisner) - race avoidance, proc may not exist yet. # https://bugs.launchpad.net/charm-helpers/+bug/1474030 self.log.debug('Attempt {} to get {} proc start time on {} ' 'failed\n{}'.format(tries, service, unit_name, e)) time.sleep(retry_sleep_time) tries += 1 if not proc_start_time: self.log.warn('No proc start time found, assuming service did ' 'not start') return False if proc_start_time >= mtime: self.log.debug('Proc start time is newer than provided mtime' '(%s >= %s) on %s (OK)' % (proc_start_time, mtime, unit_name)) return True else: self.log.warn('Proc start time (%s) is older than provided mtime ' '(%s) on %s, service did not ' 'restart' % (proc_start_time, mtime, unit_name)) return False
python
def service_restarted_since(self, sentry_unit, mtime, service, pgrep_full=None, sleep_time=20, retry_count=30, retry_sleep_time=10): """Check if service was been started after a given time. Args: sentry_unit (sentry): The sentry unit to check for the service on mtime (float): The epoch time to check against service (string): service name to look for in process table pgrep_full: [Deprecated] Use full command line search mode with pgrep sleep_time (int): Initial sleep time (s) before looking for file retry_sleep_time (int): Time (s) to sleep between retries retry_count (int): If file is not found, how many times to retry Returns: bool: True if service found and its start time it newer than mtime, False if service is older than mtime or if service was not found. """ # NOTE(beisner) pgrep_full is no longer implemented, as pidof is now # used instead of pgrep. pgrep_full is still passed through to ensure # deprecation WARNS. lp1474030 unit_name = sentry_unit.info['unit_name'] self.log.debug('Checking that %s service restarted since %s on ' '%s' % (service, mtime, unit_name)) time.sleep(sleep_time) proc_start_time = None tries = 0 while tries <= retry_count and not proc_start_time: try: proc_start_time = self._get_proc_start_time(sentry_unit, service, pgrep_full) self.log.debug('Attempt {} to get {} proc start time on {} ' 'OK'.format(tries, service, unit_name)) except IOError as e: # NOTE(beisner) - race avoidance, proc may not exist yet. # https://bugs.launchpad.net/charm-helpers/+bug/1474030 self.log.debug('Attempt {} to get {} proc start time on {} ' 'failed\n{}'.format(tries, service, unit_name, e)) time.sleep(retry_sleep_time) tries += 1 if not proc_start_time: self.log.warn('No proc start time found, assuming service did ' 'not start') return False if proc_start_time >= mtime: self.log.debug('Proc start time is newer than provided mtime' '(%s >= %s) on %s (OK)' % (proc_start_time, mtime, unit_name)) return True else: self.log.warn('Proc start time (%s) is older than provided mtime ' '(%s) on %s, service did not ' 'restart' % (proc_start_time, mtime, unit_name)) return False
[ "def", "service_restarted_since", "(", "self", ",", "sentry_unit", ",", "mtime", ",", "service", ",", "pgrep_full", "=", "None", ",", "sleep_time", "=", "20", ",", "retry_count", "=", "30", ",", "retry_sleep_time", "=", "10", ")", ":", "# NOTE(beisner) pgrep_full is no longer implemented, as pidof is now", "# used instead of pgrep. pgrep_full is still passed through to ensure", "# deprecation WARNS. lp1474030", "unit_name", "=", "sentry_unit", ".", "info", "[", "'unit_name'", "]", "self", ".", "log", ".", "debug", "(", "'Checking that %s service restarted since %s on '", "'%s'", "%", "(", "service", ",", "mtime", ",", "unit_name", ")", ")", "time", ".", "sleep", "(", "sleep_time", ")", "proc_start_time", "=", "None", "tries", "=", "0", "while", "tries", "<=", "retry_count", "and", "not", "proc_start_time", ":", "try", ":", "proc_start_time", "=", "self", ".", "_get_proc_start_time", "(", "sentry_unit", ",", "service", ",", "pgrep_full", ")", "self", ".", "log", ".", "debug", "(", "'Attempt {} to get {} proc start time on {} '", "'OK'", ".", "format", "(", "tries", ",", "service", ",", "unit_name", ")", ")", "except", "IOError", "as", "e", ":", "# NOTE(beisner) - race avoidance, proc may not exist yet.", "# https://bugs.launchpad.net/charm-helpers/+bug/1474030", "self", ".", "log", ".", "debug", "(", "'Attempt {} to get {} proc start time on {} '", "'failed\\n{}'", ".", "format", "(", "tries", ",", "service", ",", "unit_name", ",", "e", ")", ")", "time", ".", "sleep", "(", "retry_sleep_time", ")", "tries", "+=", "1", "if", "not", "proc_start_time", ":", "self", ".", "log", ".", "warn", "(", "'No proc start time found, assuming service did '", "'not start'", ")", "return", "False", "if", "proc_start_time", ">=", "mtime", ":", "self", ".", "log", ".", "debug", "(", "'Proc start time is newer than provided mtime'", "'(%s >= %s) on %s (OK)'", "%", "(", "proc_start_time", ",", "mtime", ",", "unit_name", ")", ")", "return", "True", "else", ":", "self", ".", "log", ".", "warn", "(", "'Proc start time (%s) is older than provided mtime '", "'(%s) on %s, service did not '", "'restart'", "%", "(", "proc_start_time", ",", "mtime", ",", "unit_name", ")", ")", "return", "False" ]
Check if service was been started after a given time. Args: sentry_unit (sentry): The sentry unit to check for the service on mtime (float): The epoch time to check against service (string): service name to look for in process table pgrep_full: [Deprecated] Use full command line search mode with pgrep sleep_time (int): Initial sleep time (s) before looking for file retry_sleep_time (int): Time (s) to sleep between retries retry_count (int): If file is not found, how many times to retry Returns: bool: True if service found and its start time it newer than mtime, False if service is older than mtime or if service was not found.
[ "Check", "if", "service", "was", "been", "started", "after", "a", "given", "time", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/amulet/utils.py#L320-L378
12,402
juju/charm-helpers
charmhelpers/contrib/amulet/utils.py
AmuletUtils.config_updated_since
def config_updated_since(self, sentry_unit, filename, mtime, sleep_time=20, retry_count=30, retry_sleep_time=10): """Check if file was modified after a given time. Args: sentry_unit (sentry): The sentry unit to check the file mtime on filename (string): The file to check mtime of mtime (float): The epoch time to check against sleep_time (int): Initial sleep time (s) before looking for file retry_sleep_time (int): Time (s) to sleep between retries retry_count (int): If file is not found, how many times to retry Returns: bool: True if file was modified more recently than mtime, False if file was modified before mtime, or if file not found. """ unit_name = sentry_unit.info['unit_name'] self.log.debug('Checking that %s updated since %s on ' '%s' % (filename, mtime, unit_name)) time.sleep(sleep_time) file_mtime = None tries = 0 while tries <= retry_count and not file_mtime: try: file_mtime = self._get_file_mtime(sentry_unit, filename) self.log.debug('Attempt {} to get {} file mtime on {} ' 'OK'.format(tries, filename, unit_name)) except IOError as e: # NOTE(beisner) - race avoidance, file may not exist yet. # https://bugs.launchpad.net/charm-helpers/+bug/1474030 self.log.debug('Attempt {} to get {} file mtime on {} ' 'failed\n{}'.format(tries, filename, unit_name, e)) time.sleep(retry_sleep_time) tries += 1 if not file_mtime: self.log.warn('Could not determine file mtime, assuming ' 'file does not exist') return False if file_mtime >= mtime: self.log.debug('File mtime is newer than provided mtime ' '(%s >= %s) on %s (OK)' % (file_mtime, mtime, unit_name)) return True else: self.log.warn('File mtime is older than provided mtime' '(%s < on %s) on %s' % (file_mtime, mtime, unit_name)) return False
python
def config_updated_since(self, sentry_unit, filename, mtime, sleep_time=20, retry_count=30, retry_sleep_time=10): """Check if file was modified after a given time. Args: sentry_unit (sentry): The sentry unit to check the file mtime on filename (string): The file to check mtime of mtime (float): The epoch time to check against sleep_time (int): Initial sleep time (s) before looking for file retry_sleep_time (int): Time (s) to sleep between retries retry_count (int): If file is not found, how many times to retry Returns: bool: True if file was modified more recently than mtime, False if file was modified before mtime, or if file not found. """ unit_name = sentry_unit.info['unit_name'] self.log.debug('Checking that %s updated since %s on ' '%s' % (filename, mtime, unit_name)) time.sleep(sleep_time) file_mtime = None tries = 0 while tries <= retry_count and not file_mtime: try: file_mtime = self._get_file_mtime(sentry_unit, filename) self.log.debug('Attempt {} to get {} file mtime on {} ' 'OK'.format(tries, filename, unit_name)) except IOError as e: # NOTE(beisner) - race avoidance, file may not exist yet. # https://bugs.launchpad.net/charm-helpers/+bug/1474030 self.log.debug('Attempt {} to get {} file mtime on {} ' 'failed\n{}'.format(tries, filename, unit_name, e)) time.sleep(retry_sleep_time) tries += 1 if not file_mtime: self.log.warn('Could not determine file mtime, assuming ' 'file does not exist') return False if file_mtime >= mtime: self.log.debug('File mtime is newer than provided mtime ' '(%s >= %s) on %s (OK)' % (file_mtime, mtime, unit_name)) return True else: self.log.warn('File mtime is older than provided mtime' '(%s < on %s) on %s' % (file_mtime, mtime, unit_name)) return False
[ "def", "config_updated_since", "(", "self", ",", "sentry_unit", ",", "filename", ",", "mtime", ",", "sleep_time", "=", "20", ",", "retry_count", "=", "30", ",", "retry_sleep_time", "=", "10", ")", ":", "unit_name", "=", "sentry_unit", ".", "info", "[", "'unit_name'", "]", "self", ".", "log", ".", "debug", "(", "'Checking that %s updated since %s on '", "'%s'", "%", "(", "filename", ",", "mtime", ",", "unit_name", ")", ")", "time", ".", "sleep", "(", "sleep_time", ")", "file_mtime", "=", "None", "tries", "=", "0", "while", "tries", "<=", "retry_count", "and", "not", "file_mtime", ":", "try", ":", "file_mtime", "=", "self", ".", "_get_file_mtime", "(", "sentry_unit", ",", "filename", ")", "self", ".", "log", ".", "debug", "(", "'Attempt {} to get {} file mtime on {} '", "'OK'", ".", "format", "(", "tries", ",", "filename", ",", "unit_name", ")", ")", "except", "IOError", "as", "e", ":", "# NOTE(beisner) - race avoidance, file may not exist yet.", "# https://bugs.launchpad.net/charm-helpers/+bug/1474030", "self", ".", "log", ".", "debug", "(", "'Attempt {} to get {} file mtime on {} '", "'failed\\n{}'", ".", "format", "(", "tries", ",", "filename", ",", "unit_name", ",", "e", ")", ")", "time", ".", "sleep", "(", "retry_sleep_time", ")", "tries", "+=", "1", "if", "not", "file_mtime", ":", "self", ".", "log", ".", "warn", "(", "'Could not determine file mtime, assuming '", "'file does not exist'", ")", "return", "False", "if", "file_mtime", ">=", "mtime", ":", "self", ".", "log", ".", "debug", "(", "'File mtime is newer than provided mtime '", "'(%s >= %s) on %s (OK)'", "%", "(", "file_mtime", ",", "mtime", ",", "unit_name", ")", ")", "return", "True", "else", ":", "self", ".", "log", ".", "warn", "(", "'File mtime is older than provided mtime'", "'(%s < on %s) on %s'", "%", "(", "file_mtime", ",", "mtime", ",", "unit_name", ")", ")", "return", "False" ]
Check if file was modified after a given time. Args: sentry_unit (sentry): The sentry unit to check the file mtime on filename (string): The file to check mtime of mtime (float): The epoch time to check against sleep_time (int): Initial sleep time (s) before looking for file retry_sleep_time (int): Time (s) to sleep between retries retry_count (int): If file is not found, how many times to retry Returns: bool: True if file was modified more recently than mtime, False if file was modified before mtime, or if file not found.
[ "Check", "if", "file", "was", "modified", "after", "a", "given", "time", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/amulet/utils.py#L380-L431
12,403
juju/charm-helpers
charmhelpers/contrib/amulet/utils.py
AmuletUtils.validate_service_config_changed
def validate_service_config_changed(self, sentry_unit, mtime, service, filename, pgrep_full=None, sleep_time=20, retry_count=30, retry_sleep_time=10): """Check service and file were updated after mtime Args: sentry_unit (sentry): The sentry unit to check for the service on mtime (float): The epoch time to check against service (string): service name to look for in process table filename (string): The file to check mtime of pgrep_full: [Deprecated] Use full command line search mode with pgrep sleep_time (int): Initial sleep in seconds to pass to test helpers retry_count (int): If service is not found, how many times to retry retry_sleep_time (int): Time in seconds to wait between retries Typical Usage: u = OpenStackAmuletUtils(ERROR) ... mtime = u.get_sentry_time(self.cinder_sentry) self.d.configure('cinder', {'verbose': 'True', 'debug': 'True'}) if not u.validate_service_config_changed(self.cinder_sentry, mtime, 'cinder-api', '/etc/cinder/cinder.conf') amulet.raise_status(amulet.FAIL, msg='update failed') Returns: bool: True if both service and file where updated/restarted after mtime, False if service is older than mtime or if service was not found or if filename was modified before mtime. """ # NOTE(beisner) pgrep_full is no longer implemented, as pidof is now # used instead of pgrep. pgrep_full is still passed through to ensure # deprecation WARNS. lp1474030 service_restart = self.service_restarted_since( sentry_unit, mtime, service, pgrep_full=pgrep_full, sleep_time=sleep_time, retry_count=retry_count, retry_sleep_time=retry_sleep_time) config_update = self.config_updated_since( sentry_unit, filename, mtime, sleep_time=sleep_time, retry_count=retry_count, retry_sleep_time=retry_sleep_time) return service_restart and config_update
python
def validate_service_config_changed(self, sentry_unit, mtime, service, filename, pgrep_full=None, sleep_time=20, retry_count=30, retry_sleep_time=10): """Check service and file were updated after mtime Args: sentry_unit (sentry): The sentry unit to check for the service on mtime (float): The epoch time to check against service (string): service name to look for in process table filename (string): The file to check mtime of pgrep_full: [Deprecated] Use full command line search mode with pgrep sleep_time (int): Initial sleep in seconds to pass to test helpers retry_count (int): If service is not found, how many times to retry retry_sleep_time (int): Time in seconds to wait between retries Typical Usage: u = OpenStackAmuletUtils(ERROR) ... mtime = u.get_sentry_time(self.cinder_sentry) self.d.configure('cinder', {'verbose': 'True', 'debug': 'True'}) if not u.validate_service_config_changed(self.cinder_sentry, mtime, 'cinder-api', '/etc/cinder/cinder.conf') amulet.raise_status(amulet.FAIL, msg='update failed') Returns: bool: True if both service and file where updated/restarted after mtime, False if service is older than mtime or if service was not found or if filename was modified before mtime. """ # NOTE(beisner) pgrep_full is no longer implemented, as pidof is now # used instead of pgrep. pgrep_full is still passed through to ensure # deprecation WARNS. lp1474030 service_restart = self.service_restarted_since( sentry_unit, mtime, service, pgrep_full=pgrep_full, sleep_time=sleep_time, retry_count=retry_count, retry_sleep_time=retry_sleep_time) config_update = self.config_updated_since( sentry_unit, filename, mtime, sleep_time=sleep_time, retry_count=retry_count, retry_sleep_time=retry_sleep_time) return service_restart and config_update
[ "def", "validate_service_config_changed", "(", "self", ",", "sentry_unit", ",", "mtime", ",", "service", ",", "filename", ",", "pgrep_full", "=", "None", ",", "sleep_time", "=", "20", ",", "retry_count", "=", "30", ",", "retry_sleep_time", "=", "10", ")", ":", "# NOTE(beisner) pgrep_full is no longer implemented, as pidof is now", "# used instead of pgrep. pgrep_full is still passed through to ensure", "# deprecation WARNS. lp1474030", "service_restart", "=", "self", ".", "service_restarted_since", "(", "sentry_unit", ",", "mtime", ",", "service", ",", "pgrep_full", "=", "pgrep_full", ",", "sleep_time", "=", "sleep_time", ",", "retry_count", "=", "retry_count", ",", "retry_sleep_time", "=", "retry_sleep_time", ")", "config_update", "=", "self", ".", "config_updated_since", "(", "sentry_unit", ",", "filename", ",", "mtime", ",", "sleep_time", "=", "sleep_time", ",", "retry_count", "=", "retry_count", ",", "retry_sleep_time", "=", "retry_sleep_time", ")", "return", "service_restart", "and", "config_update" ]
Check service and file were updated after mtime Args: sentry_unit (sentry): The sentry unit to check for the service on mtime (float): The epoch time to check against service (string): service name to look for in process table filename (string): The file to check mtime of pgrep_full: [Deprecated] Use full command line search mode with pgrep sleep_time (int): Initial sleep in seconds to pass to test helpers retry_count (int): If service is not found, how many times to retry retry_sleep_time (int): Time in seconds to wait between retries Typical Usage: u = OpenStackAmuletUtils(ERROR) ... mtime = u.get_sentry_time(self.cinder_sentry) self.d.configure('cinder', {'verbose': 'True', 'debug': 'True'}) if not u.validate_service_config_changed(self.cinder_sentry, mtime, 'cinder-api', '/etc/cinder/cinder.conf') amulet.raise_status(amulet.FAIL, msg='update failed') Returns: bool: True if both service and file where updated/restarted after mtime, False if service is older than mtime or if service was not found or if filename was modified before mtime.
[ "Check", "service", "and", "file", "were", "updated", "after", "mtime" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/amulet/utils.py#L433-L485
12,404
juju/charm-helpers
charmhelpers/contrib/amulet/utils.py
AmuletUtils.file_to_url
def file_to_url(self, file_rel_path): """Convert a relative file path to a file URL.""" _abs_path = os.path.abspath(file_rel_path) return urlparse.urlparse(_abs_path, scheme='file').geturl()
python
def file_to_url(self, file_rel_path): """Convert a relative file path to a file URL.""" _abs_path = os.path.abspath(file_rel_path) return urlparse.urlparse(_abs_path, scheme='file').geturl()
[ "def", "file_to_url", "(", "self", ",", "file_rel_path", ")", ":", "_abs_path", "=", "os", ".", "path", ".", "abspath", "(", "file_rel_path", ")", "return", "urlparse", ".", "urlparse", "(", "_abs_path", ",", "scheme", "=", "'file'", ")", ".", "geturl", "(", ")" ]
Convert a relative file path to a file URL.
[ "Convert", "a", "relative", "file", "path", "to", "a", "file", "URL", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/amulet/utils.py#L504-L507
12,405
juju/charm-helpers
charmhelpers/contrib/amulet/utils.py
AmuletUtils.check_commands_on_units
def check_commands_on_units(self, commands, sentry_units): """Check that all commands in a list exit zero on all sentry units in a list. :param commands: list of bash commands :param sentry_units: list of sentry unit pointers :returns: None if successful; Failure message otherwise """ self.log.debug('Checking exit codes for {} commands on {} ' 'sentry units...'.format(len(commands), len(sentry_units))) for sentry_unit in sentry_units: for cmd in commands: output, code = sentry_unit.run(cmd) if code == 0: self.log.debug('{} `{}` returned {} ' '(OK)'.format(sentry_unit.info['unit_name'], cmd, code)) else: return ('{} `{}` returned {} ' '{}'.format(sentry_unit.info['unit_name'], cmd, code, output)) return None
python
def check_commands_on_units(self, commands, sentry_units): """Check that all commands in a list exit zero on all sentry units in a list. :param commands: list of bash commands :param sentry_units: list of sentry unit pointers :returns: None if successful; Failure message otherwise """ self.log.debug('Checking exit codes for {} commands on {} ' 'sentry units...'.format(len(commands), len(sentry_units))) for sentry_unit in sentry_units: for cmd in commands: output, code = sentry_unit.run(cmd) if code == 0: self.log.debug('{} `{}` returned {} ' '(OK)'.format(sentry_unit.info['unit_name'], cmd, code)) else: return ('{} `{}` returned {} ' '{}'.format(sentry_unit.info['unit_name'], cmd, code, output)) return None
[ "def", "check_commands_on_units", "(", "self", ",", "commands", ",", "sentry_units", ")", ":", "self", ".", "log", ".", "debug", "(", "'Checking exit codes for {} commands on {} '", "'sentry units...'", ".", "format", "(", "len", "(", "commands", ")", ",", "len", "(", "sentry_units", ")", ")", ")", "for", "sentry_unit", "in", "sentry_units", ":", "for", "cmd", "in", "commands", ":", "output", ",", "code", "=", "sentry_unit", ".", "run", "(", "cmd", ")", "if", "code", "==", "0", ":", "self", ".", "log", ".", "debug", "(", "'{} `{}` returned {} '", "'(OK)'", ".", "format", "(", "sentry_unit", ".", "info", "[", "'unit_name'", "]", ",", "cmd", ",", "code", ")", ")", "else", ":", "return", "(", "'{} `{}` returned {} '", "'{}'", ".", "format", "(", "sentry_unit", ".", "info", "[", "'unit_name'", "]", ",", "cmd", ",", "code", ",", "output", ")", ")", "return", "None" ]
Check that all commands in a list exit zero on all sentry units in a list. :param commands: list of bash commands :param sentry_units: list of sentry unit pointers :returns: None if successful; Failure message otherwise
[ "Check", "that", "all", "commands", "in", "a", "list", "exit", "zero", "on", "all", "sentry", "units", "in", "a", "list", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/amulet/utils.py#L509-L531
12,406
juju/charm-helpers
charmhelpers/contrib/amulet/utils.py
AmuletUtils.get_unit_process_ids
def get_unit_process_ids( self, unit_processes, expect_success=True, pgrep_full=False): """Construct a dict containing unit sentries, process names, and process IDs. :param unit_processes: A dictionary of Amulet sentry instance to list of process names. :param expect_success: if False expect the processes to not be running, raise if they are. :returns: Dictionary of Amulet sentry instance to dictionary of process names to PIDs. """ pid_dict = {} for sentry_unit, process_list in six.iteritems(unit_processes): pid_dict[sentry_unit] = {} for process in process_list: pids = self.get_process_id_list( sentry_unit, process, expect_success=expect_success, pgrep_full=pgrep_full) pid_dict[sentry_unit].update({process: pids}) return pid_dict
python
def get_unit_process_ids( self, unit_processes, expect_success=True, pgrep_full=False): """Construct a dict containing unit sentries, process names, and process IDs. :param unit_processes: A dictionary of Amulet sentry instance to list of process names. :param expect_success: if False expect the processes to not be running, raise if they are. :returns: Dictionary of Amulet sentry instance to dictionary of process names to PIDs. """ pid_dict = {} for sentry_unit, process_list in six.iteritems(unit_processes): pid_dict[sentry_unit] = {} for process in process_list: pids = self.get_process_id_list( sentry_unit, process, expect_success=expect_success, pgrep_full=pgrep_full) pid_dict[sentry_unit].update({process: pids}) return pid_dict
[ "def", "get_unit_process_ids", "(", "self", ",", "unit_processes", ",", "expect_success", "=", "True", ",", "pgrep_full", "=", "False", ")", ":", "pid_dict", "=", "{", "}", "for", "sentry_unit", ",", "process_list", "in", "six", ".", "iteritems", "(", "unit_processes", ")", ":", "pid_dict", "[", "sentry_unit", "]", "=", "{", "}", "for", "process", "in", "process_list", ":", "pids", "=", "self", ".", "get_process_id_list", "(", "sentry_unit", ",", "process", ",", "expect_success", "=", "expect_success", ",", "pgrep_full", "=", "pgrep_full", ")", "pid_dict", "[", "sentry_unit", "]", ".", "update", "(", "{", "process", ":", "pids", "}", ")", "return", "pid_dict" ]
Construct a dict containing unit sentries, process names, and process IDs. :param unit_processes: A dictionary of Amulet sentry instance to list of process names. :param expect_success: if False expect the processes to not be running, raise if they are. :returns: Dictionary of Amulet sentry instance to dictionary of process names to PIDs.
[ "Construct", "a", "dict", "containing", "unit", "sentries", "process", "names", "and", "process", "IDs", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/amulet/utils.py#L558-L578
12,407
juju/charm-helpers
charmhelpers/contrib/amulet/utils.py
AmuletUtils.validate_unit_process_ids
def validate_unit_process_ids(self, expected, actual): """Validate process id quantities for services on units.""" self.log.debug('Checking units for running processes...') self.log.debug('Expected PIDs: {}'.format(expected)) self.log.debug('Actual PIDs: {}'.format(actual)) if len(actual) != len(expected): return ('Unit count mismatch. expected, actual: {}, ' '{} '.format(len(expected), len(actual))) for (e_sentry, e_proc_names) in six.iteritems(expected): e_sentry_name = e_sentry.info['unit_name'] if e_sentry in actual.keys(): a_proc_names = actual[e_sentry] else: return ('Expected sentry ({}) not found in actual dict data.' '{}'.format(e_sentry_name, e_sentry)) if len(e_proc_names.keys()) != len(a_proc_names.keys()): return ('Process name count mismatch. expected, actual: {}, ' '{}'.format(len(expected), len(actual))) for (e_proc_name, e_pids), (a_proc_name, a_pids) in \ zip(e_proc_names.items(), a_proc_names.items()): if e_proc_name != a_proc_name: return ('Process name mismatch. expected, actual: {}, ' '{}'.format(e_proc_name, a_proc_name)) a_pids_length = len(a_pids) fail_msg = ('PID count mismatch. {} ({}) expected, actual: ' '{}, {} ({})'.format(e_sentry_name, e_proc_name, e_pids, a_pids_length, a_pids)) # If expected is a list, ensure at least one PID quantity match if isinstance(e_pids, list) and \ a_pids_length not in e_pids: return fail_msg # If expected is not bool and not list, # ensure PID quantities match elif not isinstance(e_pids, bool) and \ not isinstance(e_pids, list) and \ a_pids_length != e_pids: return fail_msg # If expected is bool True, ensure 1 or more PIDs exist elif isinstance(e_pids, bool) and \ e_pids is True and a_pids_length < 1: return fail_msg # If expected is bool False, ensure 0 PIDs exist elif isinstance(e_pids, bool) and \ e_pids is False and a_pids_length != 0: return fail_msg else: self.log.debug('PID check OK: {} {} {}: ' '{}'.format(e_sentry_name, e_proc_name, e_pids, a_pids)) return None
python
def validate_unit_process_ids(self, expected, actual): """Validate process id quantities for services on units.""" self.log.debug('Checking units for running processes...') self.log.debug('Expected PIDs: {}'.format(expected)) self.log.debug('Actual PIDs: {}'.format(actual)) if len(actual) != len(expected): return ('Unit count mismatch. expected, actual: {}, ' '{} '.format(len(expected), len(actual))) for (e_sentry, e_proc_names) in six.iteritems(expected): e_sentry_name = e_sentry.info['unit_name'] if e_sentry in actual.keys(): a_proc_names = actual[e_sentry] else: return ('Expected sentry ({}) not found in actual dict data.' '{}'.format(e_sentry_name, e_sentry)) if len(e_proc_names.keys()) != len(a_proc_names.keys()): return ('Process name count mismatch. expected, actual: {}, ' '{}'.format(len(expected), len(actual))) for (e_proc_name, e_pids), (a_proc_name, a_pids) in \ zip(e_proc_names.items(), a_proc_names.items()): if e_proc_name != a_proc_name: return ('Process name mismatch. expected, actual: {}, ' '{}'.format(e_proc_name, a_proc_name)) a_pids_length = len(a_pids) fail_msg = ('PID count mismatch. {} ({}) expected, actual: ' '{}, {} ({})'.format(e_sentry_name, e_proc_name, e_pids, a_pids_length, a_pids)) # If expected is a list, ensure at least one PID quantity match if isinstance(e_pids, list) and \ a_pids_length not in e_pids: return fail_msg # If expected is not bool and not list, # ensure PID quantities match elif not isinstance(e_pids, bool) and \ not isinstance(e_pids, list) and \ a_pids_length != e_pids: return fail_msg # If expected is bool True, ensure 1 or more PIDs exist elif isinstance(e_pids, bool) and \ e_pids is True and a_pids_length < 1: return fail_msg # If expected is bool False, ensure 0 PIDs exist elif isinstance(e_pids, bool) and \ e_pids is False and a_pids_length != 0: return fail_msg else: self.log.debug('PID check OK: {} {} {}: ' '{}'.format(e_sentry_name, e_proc_name, e_pids, a_pids)) return None
[ "def", "validate_unit_process_ids", "(", "self", ",", "expected", ",", "actual", ")", ":", "self", ".", "log", ".", "debug", "(", "'Checking units for running processes...'", ")", "self", ".", "log", ".", "debug", "(", "'Expected PIDs: {}'", ".", "format", "(", "expected", ")", ")", "self", ".", "log", ".", "debug", "(", "'Actual PIDs: {}'", ".", "format", "(", "actual", ")", ")", "if", "len", "(", "actual", ")", "!=", "len", "(", "expected", ")", ":", "return", "(", "'Unit count mismatch. expected, actual: {}, '", "'{} '", ".", "format", "(", "len", "(", "expected", ")", ",", "len", "(", "actual", ")", ")", ")", "for", "(", "e_sentry", ",", "e_proc_names", ")", "in", "six", ".", "iteritems", "(", "expected", ")", ":", "e_sentry_name", "=", "e_sentry", ".", "info", "[", "'unit_name'", "]", "if", "e_sentry", "in", "actual", ".", "keys", "(", ")", ":", "a_proc_names", "=", "actual", "[", "e_sentry", "]", "else", ":", "return", "(", "'Expected sentry ({}) not found in actual dict data.'", "'{}'", ".", "format", "(", "e_sentry_name", ",", "e_sentry", ")", ")", "if", "len", "(", "e_proc_names", ".", "keys", "(", ")", ")", "!=", "len", "(", "a_proc_names", ".", "keys", "(", ")", ")", ":", "return", "(", "'Process name count mismatch. expected, actual: {}, '", "'{}'", ".", "format", "(", "len", "(", "expected", ")", ",", "len", "(", "actual", ")", ")", ")", "for", "(", "e_proc_name", ",", "e_pids", ")", ",", "(", "a_proc_name", ",", "a_pids", ")", "in", "zip", "(", "e_proc_names", ".", "items", "(", ")", ",", "a_proc_names", ".", "items", "(", ")", ")", ":", "if", "e_proc_name", "!=", "a_proc_name", ":", "return", "(", "'Process name mismatch. expected, actual: {}, '", "'{}'", ".", "format", "(", "e_proc_name", ",", "a_proc_name", ")", ")", "a_pids_length", "=", "len", "(", "a_pids", ")", "fail_msg", "=", "(", "'PID count mismatch. {} ({}) expected, actual: '", "'{}, {} ({})'", ".", "format", "(", "e_sentry_name", ",", "e_proc_name", ",", "e_pids", ",", "a_pids_length", ",", "a_pids", ")", ")", "# If expected is a list, ensure at least one PID quantity match", "if", "isinstance", "(", "e_pids", ",", "list", ")", "and", "a_pids_length", "not", "in", "e_pids", ":", "return", "fail_msg", "# If expected is not bool and not list,", "# ensure PID quantities match", "elif", "not", "isinstance", "(", "e_pids", ",", "bool", ")", "and", "not", "isinstance", "(", "e_pids", ",", "list", ")", "and", "a_pids_length", "!=", "e_pids", ":", "return", "fail_msg", "# If expected is bool True, ensure 1 or more PIDs exist", "elif", "isinstance", "(", "e_pids", ",", "bool", ")", "and", "e_pids", "is", "True", "and", "a_pids_length", "<", "1", ":", "return", "fail_msg", "# If expected is bool False, ensure 0 PIDs exist", "elif", "isinstance", "(", "e_pids", ",", "bool", ")", "and", "e_pids", "is", "False", "and", "a_pids_length", "!=", "0", ":", "return", "fail_msg", "else", ":", "self", ".", "log", ".", "debug", "(", "'PID check OK: {} {} {}: '", "'{}'", ".", "format", "(", "e_sentry_name", ",", "e_proc_name", ",", "e_pids", ",", "a_pids", ")", ")", "return", "None" ]
Validate process id quantities for services on units.
[ "Validate", "process", "id", "quantities", "for", "services", "on", "units", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/amulet/utils.py#L580-L636
12,408
juju/charm-helpers
charmhelpers/contrib/amulet/utils.py
AmuletUtils.validate_list_of_identical_dicts
def validate_list_of_identical_dicts(self, list_of_dicts): """Check that all dicts within a list are identical.""" hashes = [] for _dict in list_of_dicts: hashes.append(hash(frozenset(_dict.items()))) self.log.debug('Hashes: {}'.format(hashes)) if len(set(hashes)) == 1: self.log.debug('Dicts within list are identical') else: return 'Dicts within list are not identical' return None
python
def validate_list_of_identical_dicts(self, list_of_dicts): """Check that all dicts within a list are identical.""" hashes = [] for _dict in list_of_dicts: hashes.append(hash(frozenset(_dict.items()))) self.log.debug('Hashes: {}'.format(hashes)) if len(set(hashes)) == 1: self.log.debug('Dicts within list are identical') else: return 'Dicts within list are not identical' return None
[ "def", "validate_list_of_identical_dicts", "(", "self", ",", "list_of_dicts", ")", ":", "hashes", "=", "[", "]", "for", "_dict", "in", "list_of_dicts", ":", "hashes", ".", "append", "(", "hash", "(", "frozenset", "(", "_dict", ".", "items", "(", ")", ")", ")", ")", "self", ".", "log", ".", "debug", "(", "'Hashes: {}'", ".", "format", "(", "hashes", ")", ")", "if", "len", "(", "set", "(", "hashes", ")", ")", "==", "1", ":", "self", ".", "log", ".", "debug", "(", "'Dicts within list are identical'", ")", "else", ":", "return", "'Dicts within list are not identical'", "return", "None" ]
Check that all dicts within a list are identical.
[ "Check", "that", "all", "dicts", "within", "a", "list", "are", "identical", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/amulet/utils.py#L638-L650
12,409
juju/charm-helpers
charmhelpers/contrib/amulet/utils.py
AmuletUtils.get_unit_hostnames
def get_unit_hostnames(self, units): """Return a dict of juju unit names to hostnames.""" host_names = {} for unit in units: host_names[unit.info['unit_name']] = \ str(unit.file_contents('/etc/hostname').strip()) self.log.debug('Unit host names: {}'.format(host_names)) return host_names
python
def get_unit_hostnames(self, units): """Return a dict of juju unit names to hostnames.""" host_names = {} for unit in units: host_names[unit.info['unit_name']] = \ str(unit.file_contents('/etc/hostname').strip()) self.log.debug('Unit host names: {}'.format(host_names)) return host_names
[ "def", "get_unit_hostnames", "(", "self", ",", "units", ")", ":", "host_names", "=", "{", "}", "for", "unit", "in", "units", ":", "host_names", "[", "unit", ".", "info", "[", "'unit_name'", "]", "]", "=", "str", "(", "unit", ".", "file_contents", "(", "'/etc/hostname'", ")", ".", "strip", "(", ")", ")", "self", ".", "log", ".", "debug", "(", "'Unit host names: {}'", ".", "format", "(", "host_names", ")", ")", "return", "host_names" ]
Return a dict of juju unit names to hostnames.
[ "Return", "a", "dict", "of", "juju", "unit", "names", "to", "hostnames", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/amulet/utils.py#L669-L676
12,410
juju/charm-helpers
charmhelpers/contrib/amulet/utils.py
AmuletUtils.run_cmd_unit
def run_cmd_unit(self, sentry_unit, cmd): """Run a command on a unit, return the output and exit code.""" output, code = sentry_unit.run(cmd) if code == 0: self.log.debug('{} `{}` command returned {} ' '(OK)'.format(sentry_unit.info['unit_name'], cmd, code)) else: msg = ('{} `{}` command returned {} ' '{}'.format(sentry_unit.info['unit_name'], cmd, code, output)) amulet.raise_status(amulet.FAIL, msg=msg) return str(output), code
python
def run_cmd_unit(self, sentry_unit, cmd): """Run a command on a unit, return the output and exit code.""" output, code = sentry_unit.run(cmd) if code == 0: self.log.debug('{} `{}` command returned {} ' '(OK)'.format(sentry_unit.info['unit_name'], cmd, code)) else: msg = ('{} `{}` command returned {} ' '{}'.format(sentry_unit.info['unit_name'], cmd, code, output)) amulet.raise_status(amulet.FAIL, msg=msg) return str(output), code
[ "def", "run_cmd_unit", "(", "self", ",", "sentry_unit", ",", "cmd", ")", ":", "output", ",", "code", "=", "sentry_unit", ".", "run", "(", "cmd", ")", "if", "code", "==", "0", ":", "self", ".", "log", ".", "debug", "(", "'{} `{}` command returned {} '", "'(OK)'", ".", "format", "(", "sentry_unit", ".", "info", "[", "'unit_name'", "]", ",", "cmd", ",", "code", ")", ")", "else", ":", "msg", "=", "(", "'{} `{}` command returned {} '", "'{}'", ".", "format", "(", "sentry_unit", ".", "info", "[", "'unit_name'", "]", ",", "cmd", ",", "code", ",", "output", ")", ")", "amulet", ".", "raise_status", "(", "amulet", ".", "FAIL", ",", "msg", "=", "msg", ")", "return", "str", "(", "output", ")", ",", "code" ]
Run a command on a unit, return the output and exit code.
[ "Run", "a", "command", "on", "a", "unit", "return", "the", "output", "and", "exit", "code", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/amulet/utils.py#L678-L690
12,411
juju/charm-helpers
charmhelpers/contrib/amulet/utils.py
AmuletUtils.file_exists_on_unit
def file_exists_on_unit(self, sentry_unit, file_name): """Check if a file exists on a unit.""" try: sentry_unit.file_stat(file_name) return True except IOError: return False except Exception as e: msg = 'Error checking file {}: {}'.format(file_name, e) amulet.raise_status(amulet.FAIL, msg=msg)
python
def file_exists_on_unit(self, sentry_unit, file_name): """Check if a file exists on a unit.""" try: sentry_unit.file_stat(file_name) return True except IOError: return False except Exception as e: msg = 'Error checking file {}: {}'.format(file_name, e) amulet.raise_status(amulet.FAIL, msg=msg)
[ "def", "file_exists_on_unit", "(", "self", ",", "sentry_unit", ",", "file_name", ")", ":", "try", ":", "sentry_unit", ".", "file_stat", "(", "file_name", ")", "return", "True", "except", "IOError", ":", "return", "False", "except", "Exception", "as", "e", ":", "msg", "=", "'Error checking file {}: {}'", ".", "format", "(", "file_name", ",", "e", ")", "amulet", ".", "raise_status", "(", "amulet", ".", "FAIL", ",", "msg", "=", "msg", ")" ]
Check if a file exists on a unit.
[ "Check", "if", "a", "file", "exists", "on", "a", "unit", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/amulet/utils.py#L692-L701
12,412
juju/charm-helpers
charmhelpers/contrib/amulet/utils.py
AmuletUtils.file_contents_safe
def file_contents_safe(self, sentry_unit, file_name, max_wait=60, fatal=False): """Get file contents from a sentry unit. Wrap amulet file_contents with retry logic to address races where a file checks as existing, but no longer exists by the time file_contents is called. Return None if file not found. Optionally raise if fatal is True.""" unit_name = sentry_unit.info['unit_name'] file_contents = False tries = 0 while not file_contents and tries < (max_wait / 4): try: file_contents = sentry_unit.file_contents(file_name) except IOError: self.log.debug('Attempt {} to open file {} from {} ' 'failed'.format(tries, file_name, unit_name)) time.sleep(4) tries += 1 if file_contents: return file_contents elif not fatal: return None elif fatal: msg = 'Failed to get file contents from unit.' amulet.raise_status(amulet.FAIL, msg)
python
def file_contents_safe(self, sentry_unit, file_name, max_wait=60, fatal=False): """Get file contents from a sentry unit. Wrap amulet file_contents with retry logic to address races where a file checks as existing, but no longer exists by the time file_contents is called. Return None if file not found. Optionally raise if fatal is True.""" unit_name = sentry_unit.info['unit_name'] file_contents = False tries = 0 while not file_contents and tries < (max_wait / 4): try: file_contents = sentry_unit.file_contents(file_name) except IOError: self.log.debug('Attempt {} to open file {} from {} ' 'failed'.format(tries, file_name, unit_name)) time.sleep(4) tries += 1 if file_contents: return file_contents elif not fatal: return None elif fatal: msg = 'Failed to get file contents from unit.' amulet.raise_status(amulet.FAIL, msg)
[ "def", "file_contents_safe", "(", "self", ",", "sentry_unit", ",", "file_name", ",", "max_wait", "=", "60", ",", "fatal", "=", "False", ")", ":", "unit_name", "=", "sentry_unit", ".", "info", "[", "'unit_name'", "]", "file_contents", "=", "False", "tries", "=", "0", "while", "not", "file_contents", "and", "tries", "<", "(", "max_wait", "/", "4", ")", ":", "try", ":", "file_contents", "=", "sentry_unit", ".", "file_contents", "(", "file_name", ")", "except", "IOError", ":", "self", ".", "log", ".", "debug", "(", "'Attempt {} to open file {} from {} '", "'failed'", ".", "format", "(", "tries", ",", "file_name", ",", "unit_name", ")", ")", "time", ".", "sleep", "(", "4", ")", "tries", "+=", "1", "if", "file_contents", ":", "return", "file_contents", "elif", "not", "fatal", ":", "return", "None", "elif", "fatal", ":", "msg", "=", "'Failed to get file contents from unit.'", "amulet", ".", "raise_status", "(", "amulet", ".", "FAIL", ",", "msg", ")" ]
Get file contents from a sentry unit. Wrap amulet file_contents with retry logic to address races where a file checks as existing, but no longer exists by the time file_contents is called. Return None if file not found. Optionally raise if fatal is True.
[ "Get", "file", "contents", "from", "a", "sentry", "unit", ".", "Wrap", "amulet", "file_contents", "with", "retry", "logic", "to", "address", "races", "where", "a", "file", "checks", "as", "existing", "but", "no", "longer", "exists", "by", "the", "time", "file_contents", "is", "called", ".", "Return", "None", "if", "file", "not", "found", ".", "Optionally", "raise", "if", "fatal", "is", "True", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/amulet/utils.py#L703-L728
12,413
juju/charm-helpers
charmhelpers/contrib/amulet/utils.py
AmuletUtils.port_knock_tcp
def port_knock_tcp(self, host="localhost", port=22, timeout=15): """Open a TCP socket to check for a listening sevice on a host. :param host: host name or IP address, default to localhost :param port: TCP port number, default to 22 :param timeout: Connect timeout, default to 15 seconds :returns: True if successful, False if connect failed """ # Resolve host name if possible try: connect_host = socket.gethostbyname(host) host_human = "{} ({})".format(connect_host, host) except socket.error as e: self.log.warn('Unable to resolve address: ' '{} ({}) Trying anyway!'.format(host, e)) connect_host = host host_human = connect_host # Attempt socket connection try: knock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) knock.settimeout(timeout) knock.connect((connect_host, port)) knock.close() self.log.debug('Socket connect OK for host ' '{} on port {}.'.format(host_human, port)) return True except socket.error as e: self.log.debug('Socket connect FAIL for' ' {} port {} ({})'.format(host_human, port, e)) return False
python
def port_knock_tcp(self, host="localhost", port=22, timeout=15): """Open a TCP socket to check for a listening sevice on a host. :param host: host name or IP address, default to localhost :param port: TCP port number, default to 22 :param timeout: Connect timeout, default to 15 seconds :returns: True if successful, False if connect failed """ # Resolve host name if possible try: connect_host = socket.gethostbyname(host) host_human = "{} ({})".format(connect_host, host) except socket.error as e: self.log.warn('Unable to resolve address: ' '{} ({}) Trying anyway!'.format(host, e)) connect_host = host host_human = connect_host # Attempt socket connection try: knock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) knock.settimeout(timeout) knock.connect((connect_host, port)) knock.close() self.log.debug('Socket connect OK for host ' '{} on port {}.'.format(host_human, port)) return True except socket.error as e: self.log.debug('Socket connect FAIL for' ' {} port {} ({})'.format(host_human, port, e)) return False
[ "def", "port_knock_tcp", "(", "self", ",", "host", "=", "\"localhost\"", ",", "port", "=", "22", ",", "timeout", "=", "15", ")", ":", "# Resolve host name if possible", "try", ":", "connect_host", "=", "socket", ".", "gethostbyname", "(", "host", ")", "host_human", "=", "\"{} ({})\"", ".", "format", "(", "connect_host", ",", "host", ")", "except", "socket", ".", "error", "as", "e", ":", "self", ".", "log", ".", "warn", "(", "'Unable to resolve address: '", "'{} ({}) Trying anyway!'", ".", "format", "(", "host", ",", "e", ")", ")", "connect_host", "=", "host", "host_human", "=", "connect_host", "# Attempt socket connection", "try", ":", "knock", "=", "socket", ".", "socket", "(", "socket", ".", "AF_INET", ",", "socket", ".", "SOCK_STREAM", ")", "knock", ".", "settimeout", "(", "timeout", ")", "knock", ".", "connect", "(", "(", "connect_host", ",", "port", ")", ")", "knock", ".", "close", "(", ")", "self", ".", "log", ".", "debug", "(", "'Socket connect OK for host '", "'{} on port {}.'", ".", "format", "(", "host_human", ",", "port", ")", ")", "return", "True", "except", "socket", ".", "error", "as", "e", ":", "self", ".", "log", ".", "debug", "(", "'Socket connect FAIL for'", "' {} port {} ({})'", ".", "format", "(", "host_human", ",", "port", ",", "e", ")", ")", "return", "False" ]
Open a TCP socket to check for a listening sevice on a host. :param host: host name or IP address, default to localhost :param port: TCP port number, default to 22 :param timeout: Connect timeout, default to 15 seconds :returns: True if successful, False if connect failed
[ "Open", "a", "TCP", "socket", "to", "check", "for", "a", "listening", "sevice", "on", "a", "host", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/amulet/utils.py#L730-L761
12,414
juju/charm-helpers
charmhelpers/contrib/amulet/utils.py
AmuletUtils.port_knock_units
def port_knock_units(self, sentry_units, port=22, timeout=15, expect_success=True): """Open a TCP socket to check for a listening sevice on each listed juju unit. :param sentry_units: list of sentry unit pointers :param port: TCP port number, default to 22 :param timeout: Connect timeout, default to 15 seconds :expect_success: True by default, set False to invert logic :returns: None if successful, Failure message otherwise """ for unit in sentry_units: host = unit.info['public-address'] connected = self.port_knock_tcp(host, port, timeout) if not connected and expect_success: return 'Socket connect failed.' elif connected and not expect_success: return 'Socket connected unexpectedly.'
python
def port_knock_units(self, sentry_units, port=22, timeout=15, expect_success=True): """Open a TCP socket to check for a listening sevice on each listed juju unit. :param sentry_units: list of sentry unit pointers :param port: TCP port number, default to 22 :param timeout: Connect timeout, default to 15 seconds :expect_success: True by default, set False to invert logic :returns: None if successful, Failure message otherwise """ for unit in sentry_units: host = unit.info['public-address'] connected = self.port_knock_tcp(host, port, timeout) if not connected and expect_success: return 'Socket connect failed.' elif connected and not expect_success: return 'Socket connected unexpectedly.'
[ "def", "port_knock_units", "(", "self", ",", "sentry_units", ",", "port", "=", "22", ",", "timeout", "=", "15", ",", "expect_success", "=", "True", ")", ":", "for", "unit", "in", "sentry_units", ":", "host", "=", "unit", ".", "info", "[", "'public-address'", "]", "connected", "=", "self", ".", "port_knock_tcp", "(", "host", ",", "port", ",", "timeout", ")", "if", "not", "connected", "and", "expect_success", ":", "return", "'Socket connect failed.'", "elif", "connected", "and", "not", "expect_success", ":", "return", "'Socket connected unexpectedly.'" ]
Open a TCP socket to check for a listening sevice on each listed juju unit. :param sentry_units: list of sentry unit pointers :param port: TCP port number, default to 22 :param timeout: Connect timeout, default to 15 seconds :expect_success: True by default, set False to invert logic :returns: None if successful, Failure message otherwise
[ "Open", "a", "TCP", "socket", "to", "check", "for", "a", "listening", "sevice", "on", "each", "listed", "juju", "unit", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/amulet/utils.py#L763-L780
12,415
juju/charm-helpers
charmhelpers/contrib/amulet/utils.py
AmuletUtils.wait_on_action
def wait_on_action(self, action_id, _check_output=subprocess.check_output): """Wait for a given action, returning if it completed or not. action_id a string action uuid _check_output parameter is no longer used """ data = amulet.actions.get_action_output(action_id, full_output=True) return data.get(u"status") == "completed"
python
def wait_on_action(self, action_id, _check_output=subprocess.check_output): """Wait for a given action, returning if it completed or not. action_id a string action uuid _check_output parameter is no longer used """ data = amulet.actions.get_action_output(action_id, full_output=True) return data.get(u"status") == "completed"
[ "def", "wait_on_action", "(", "self", ",", "action_id", ",", "_check_output", "=", "subprocess", ".", "check_output", ")", ":", "data", "=", "amulet", ".", "actions", ".", "get_action_output", "(", "action_id", ",", "full_output", "=", "True", ")", "return", "data", ".", "get", "(", "u\"status\"", ")", "==", "\"completed\"" ]
Wait for a given action, returning if it completed or not. action_id a string action uuid _check_output parameter is no longer used
[ "Wait", "for", "a", "given", "action", "returning", "if", "it", "completed", "or", "not", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/amulet/utils.py#L804-L811
12,416
juju/charm-helpers
charmhelpers/contrib/amulet/utils.py
AmuletUtils.status_get
def status_get(self, unit): """Return the current service status of this unit.""" raw_status, return_code = unit.run( "status-get --format=json --include-data") if return_code != 0: return ("unknown", "") status = json.loads(raw_status) return (status["status"], status["message"])
python
def status_get(self, unit): """Return the current service status of this unit.""" raw_status, return_code = unit.run( "status-get --format=json --include-data") if return_code != 0: return ("unknown", "") status = json.loads(raw_status) return (status["status"], status["message"])
[ "def", "status_get", "(", "self", ",", "unit", ")", ":", "raw_status", ",", "return_code", "=", "unit", ".", "run", "(", "\"status-get --format=json --include-data\"", ")", "if", "return_code", "!=", "0", ":", "return", "(", "\"unknown\"", ",", "\"\"", ")", "status", "=", "json", ".", "loads", "(", "raw_status", ")", "return", "(", "status", "[", "\"status\"", "]", ",", "status", "[", "\"message\"", "]", ")" ]
Return the current service status of this unit.
[ "Return", "the", "current", "service", "status", "of", "this", "unit", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/amulet/utils.py#L813-L820
12,417
juju/charm-helpers
charmhelpers/contrib/database/mysql.py
MySQLHelper.execute
def execute(self, sql): """Execute arbitary SQL against the database.""" cursor = self.connection.cursor() try: cursor.execute(sql) finally: cursor.close()
python
def execute(self, sql): """Execute arbitary SQL against the database.""" cursor = self.connection.cursor() try: cursor.execute(sql) finally: cursor.close()
[ "def", "execute", "(", "self", ",", "sql", ")", ":", "cursor", "=", "self", ".", "connection", ".", "cursor", "(", ")", "try", ":", "cursor", ".", "execute", "(", "sql", ")", "finally", ":", "cursor", ".", "close", "(", ")" ]
Execute arbitary SQL against the database.
[ "Execute", "arbitary", "SQL", "against", "the", "database", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/database/mysql.py#L160-L166
12,418
juju/charm-helpers
charmhelpers/contrib/database/mysql.py
MySQLHelper.select
def select(self, sql): """ Execute arbitrary SQL select query against the database and return the results. :param sql: SQL select query to execute :type sql: string :returns: SQL select query result :rtype: list of lists :raises: MySQLdb.Error """ cursor = self.connection.cursor() try: cursor.execute(sql) results = [list(i) for i in cursor.fetchall()] finally: cursor.close() return results
python
def select(self, sql): """ Execute arbitrary SQL select query against the database and return the results. :param sql: SQL select query to execute :type sql: string :returns: SQL select query result :rtype: list of lists :raises: MySQLdb.Error """ cursor = self.connection.cursor() try: cursor.execute(sql) results = [list(i) for i in cursor.fetchall()] finally: cursor.close() return results
[ "def", "select", "(", "self", ",", "sql", ")", ":", "cursor", "=", "self", ".", "connection", ".", "cursor", "(", ")", "try", ":", "cursor", ".", "execute", "(", "sql", ")", "results", "=", "[", "list", "(", "i", ")", "for", "i", "in", "cursor", ".", "fetchall", "(", ")", "]", "finally", ":", "cursor", ".", "close", "(", ")", "return", "results" ]
Execute arbitrary SQL select query against the database and return the results. :param sql: SQL select query to execute :type sql: string :returns: SQL select query result :rtype: list of lists :raises: MySQLdb.Error
[ "Execute", "arbitrary", "SQL", "select", "query", "against", "the", "database", "and", "return", "the", "results", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/database/mysql.py#L168-L185
12,419
juju/charm-helpers
charmhelpers/contrib/database/mysql.py
MySQLHelper.migrate_passwords_to_leader_storage
def migrate_passwords_to_leader_storage(self, excludes=None): """Migrate any passwords storage on disk to leader storage.""" if not is_leader(): log("Skipping password migration as not the lead unit", level=DEBUG) return dirname = os.path.dirname(self.root_passwd_file_template) path = os.path.join(dirname, '*.passwd') for f in glob.glob(path): if excludes and f in excludes: log("Excluding %s from leader storage migration" % (f), level=DEBUG) continue key = os.path.basename(f) with open(f, 'r') as passwd: _value = passwd.read().strip() try: leader_set(settings={key: _value}) if self.delete_ondisk_passwd_file: os.unlink(f) except ValueError: # NOTE cluster relation not yet ready - skip for now pass
python
def migrate_passwords_to_leader_storage(self, excludes=None): """Migrate any passwords storage on disk to leader storage.""" if not is_leader(): log("Skipping password migration as not the lead unit", level=DEBUG) return dirname = os.path.dirname(self.root_passwd_file_template) path = os.path.join(dirname, '*.passwd') for f in glob.glob(path): if excludes and f in excludes: log("Excluding %s from leader storage migration" % (f), level=DEBUG) continue key = os.path.basename(f) with open(f, 'r') as passwd: _value = passwd.read().strip() try: leader_set(settings={key: _value}) if self.delete_ondisk_passwd_file: os.unlink(f) except ValueError: # NOTE cluster relation not yet ready - skip for now pass
[ "def", "migrate_passwords_to_leader_storage", "(", "self", ",", "excludes", "=", "None", ")", ":", "if", "not", "is_leader", "(", ")", ":", "log", "(", "\"Skipping password migration as not the lead unit\"", ",", "level", "=", "DEBUG", ")", "return", "dirname", "=", "os", ".", "path", ".", "dirname", "(", "self", ".", "root_passwd_file_template", ")", "path", "=", "os", ".", "path", ".", "join", "(", "dirname", ",", "'*.passwd'", ")", "for", "f", "in", "glob", ".", "glob", "(", "path", ")", ":", "if", "excludes", "and", "f", "in", "excludes", ":", "log", "(", "\"Excluding %s from leader storage migration\"", "%", "(", "f", ")", ",", "level", "=", "DEBUG", ")", "continue", "key", "=", "os", ".", "path", ".", "basename", "(", "f", ")", "with", "open", "(", "f", ",", "'r'", ")", "as", "passwd", ":", "_value", "=", "passwd", ".", "read", "(", ")", ".", "strip", "(", ")", "try", ":", "leader_set", "(", "settings", "=", "{", "key", ":", "_value", "}", ")", "if", "self", ".", "delete_ondisk_passwd_file", ":", "os", ".", "unlink", "(", "f", ")", "except", "ValueError", ":", "# NOTE cluster relation not yet ready - skip for now", "pass" ]
Migrate any passwords storage on disk to leader storage.
[ "Migrate", "any", "passwords", "storage", "on", "disk", "to", "leader", "storage", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/database/mysql.py#L187-L212
12,420
juju/charm-helpers
charmhelpers/contrib/database/mysql.py
MySQLHelper.get_mysql_password_on_disk
def get_mysql_password_on_disk(self, username=None, password=None): """Retrieve, generate or store a mysql password for the provided username on disk.""" if username: template = self.user_passwd_file_template passwd_file = template.format(username) else: passwd_file = self.root_passwd_file_template _password = None if os.path.exists(passwd_file): log("Using existing password file '%s'" % passwd_file, level=DEBUG) with open(passwd_file, 'r') as passwd: _password = passwd.read().strip() else: log("Generating new password file '%s'" % passwd_file, level=DEBUG) if not os.path.isdir(os.path.dirname(passwd_file)): # NOTE: need to ensure this is not mysql root dir (which needs # to be mysql readable) mkdir(os.path.dirname(passwd_file), owner='root', group='root', perms=0o770) # Force permissions - for some reason the chmod in makedirs # fails os.chmod(os.path.dirname(passwd_file), 0o770) _password = password or pwgen(length=32) write_file(passwd_file, _password, owner='root', group='root', perms=0o660) return _password
python
def get_mysql_password_on_disk(self, username=None, password=None): """Retrieve, generate or store a mysql password for the provided username on disk.""" if username: template = self.user_passwd_file_template passwd_file = template.format(username) else: passwd_file = self.root_passwd_file_template _password = None if os.path.exists(passwd_file): log("Using existing password file '%s'" % passwd_file, level=DEBUG) with open(passwd_file, 'r') as passwd: _password = passwd.read().strip() else: log("Generating new password file '%s'" % passwd_file, level=DEBUG) if not os.path.isdir(os.path.dirname(passwd_file)): # NOTE: need to ensure this is not mysql root dir (which needs # to be mysql readable) mkdir(os.path.dirname(passwd_file), owner='root', group='root', perms=0o770) # Force permissions - for some reason the chmod in makedirs # fails os.chmod(os.path.dirname(passwd_file), 0o770) _password = password or pwgen(length=32) write_file(passwd_file, _password, owner='root', group='root', perms=0o660) return _password
[ "def", "get_mysql_password_on_disk", "(", "self", ",", "username", "=", "None", ",", "password", "=", "None", ")", ":", "if", "username", ":", "template", "=", "self", ".", "user_passwd_file_template", "passwd_file", "=", "template", ".", "format", "(", "username", ")", "else", ":", "passwd_file", "=", "self", ".", "root_passwd_file_template", "_password", "=", "None", "if", "os", ".", "path", ".", "exists", "(", "passwd_file", ")", ":", "log", "(", "\"Using existing password file '%s'\"", "%", "passwd_file", ",", "level", "=", "DEBUG", ")", "with", "open", "(", "passwd_file", ",", "'r'", ")", "as", "passwd", ":", "_password", "=", "passwd", ".", "read", "(", ")", ".", "strip", "(", ")", "else", ":", "log", "(", "\"Generating new password file '%s'\"", "%", "passwd_file", ",", "level", "=", "DEBUG", ")", "if", "not", "os", ".", "path", ".", "isdir", "(", "os", ".", "path", ".", "dirname", "(", "passwd_file", ")", ")", ":", "# NOTE: need to ensure this is not mysql root dir (which needs", "# to be mysql readable)", "mkdir", "(", "os", ".", "path", ".", "dirname", "(", "passwd_file", ")", ",", "owner", "=", "'root'", ",", "group", "=", "'root'", ",", "perms", "=", "0o770", ")", "# Force permissions - for some reason the chmod in makedirs", "# fails", "os", ".", "chmod", "(", "os", ".", "path", ".", "dirname", "(", "passwd_file", ")", ",", "0o770", ")", "_password", "=", "password", "or", "pwgen", "(", "length", "=", "32", ")", "write_file", "(", "passwd_file", ",", "_password", ",", "owner", "=", "'root'", ",", "group", "=", "'root'", ",", "perms", "=", "0o660", ")", "return", "_password" ]
Retrieve, generate or store a mysql password for the provided username on disk.
[ "Retrieve", "generate", "or", "store", "a", "mysql", "password", "for", "the", "provided", "username", "on", "disk", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/database/mysql.py#L214-L243
12,421
juju/charm-helpers
charmhelpers/contrib/database/mysql.py
MySQLHelper.passwd_keys
def passwd_keys(self, username): """Generator to return keys used to store passwords in peer store. NOTE: we support both legacy and new format to support mysql charm prior to refactor. This is necessary to avoid LP 1451890. """ keys = [] if username == 'mysql': log("Bad username '%s'" % (username), level=WARNING) if username: # IMPORTANT: *newer* format must be returned first keys.append('mysql-%s.passwd' % (username)) keys.append('%s.passwd' % (username)) else: keys.append('mysql.passwd') for key in keys: yield key
python
def passwd_keys(self, username): """Generator to return keys used to store passwords in peer store. NOTE: we support both legacy and new format to support mysql charm prior to refactor. This is necessary to avoid LP 1451890. """ keys = [] if username == 'mysql': log("Bad username '%s'" % (username), level=WARNING) if username: # IMPORTANT: *newer* format must be returned first keys.append('mysql-%s.passwd' % (username)) keys.append('%s.passwd' % (username)) else: keys.append('mysql.passwd') for key in keys: yield key
[ "def", "passwd_keys", "(", "self", ",", "username", ")", ":", "keys", "=", "[", "]", "if", "username", "==", "'mysql'", ":", "log", "(", "\"Bad username '%s'\"", "%", "(", "username", ")", ",", "level", "=", "WARNING", ")", "if", "username", ":", "# IMPORTANT: *newer* format must be returned first", "keys", ".", "append", "(", "'mysql-%s.passwd'", "%", "(", "username", ")", ")", "keys", ".", "append", "(", "'%s.passwd'", "%", "(", "username", ")", ")", "else", ":", "keys", ".", "append", "(", "'mysql.passwd'", ")", "for", "key", "in", "keys", ":", "yield", "key" ]
Generator to return keys used to store passwords in peer store. NOTE: we support both legacy and new format to support mysql charm prior to refactor. This is necessary to avoid LP 1451890.
[ "Generator", "to", "return", "keys", "used", "to", "store", "passwords", "in", "peer", "store", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/database/mysql.py#L245-L263
12,422
juju/charm-helpers
charmhelpers/contrib/database/mysql.py
MySQLHelper.get_mysql_password
def get_mysql_password(self, username=None, password=None): """Retrieve, generate or store a mysql password for the provided username using peer relation cluster.""" excludes = [] # First check peer relation. try: for key in self.passwd_keys(username): _password = leader_get(key) if _password: break # If root password available don't update peer relation from local if _password and not username: excludes.append(self.root_passwd_file_template) except ValueError: # cluster relation is not yet started; use on-disk _password = None # If none available, generate new one if not _password: _password = self.get_mysql_password_on_disk(username, password) # Put on wire if required if self.migrate_passwd_to_leader_storage: self.migrate_passwords_to_leader_storage(excludes=excludes) return _password
python
def get_mysql_password(self, username=None, password=None): """Retrieve, generate or store a mysql password for the provided username using peer relation cluster.""" excludes = [] # First check peer relation. try: for key in self.passwd_keys(username): _password = leader_get(key) if _password: break # If root password available don't update peer relation from local if _password and not username: excludes.append(self.root_passwd_file_template) except ValueError: # cluster relation is not yet started; use on-disk _password = None # If none available, generate new one if not _password: _password = self.get_mysql_password_on_disk(username, password) # Put on wire if required if self.migrate_passwd_to_leader_storage: self.migrate_passwords_to_leader_storage(excludes=excludes) return _password
[ "def", "get_mysql_password", "(", "self", ",", "username", "=", "None", ",", "password", "=", "None", ")", ":", "excludes", "=", "[", "]", "# First check peer relation.", "try", ":", "for", "key", "in", "self", ".", "passwd_keys", "(", "username", ")", ":", "_password", "=", "leader_get", "(", "key", ")", "if", "_password", ":", "break", "# If root password available don't update peer relation from local", "if", "_password", "and", "not", "username", ":", "excludes", ".", "append", "(", "self", ".", "root_passwd_file_template", ")", "except", "ValueError", ":", "# cluster relation is not yet started; use on-disk", "_password", "=", "None", "# If none available, generate new one", "if", "not", "_password", ":", "_password", "=", "self", ".", "get_mysql_password_on_disk", "(", "username", ",", "password", ")", "# Put on wire if required", "if", "self", ".", "migrate_passwd_to_leader_storage", ":", "self", ".", "migrate_passwords_to_leader_storage", "(", "excludes", "=", "excludes", ")", "return", "_password" ]
Retrieve, generate or store a mysql password for the provided username using peer relation cluster.
[ "Retrieve", "generate", "or", "store", "a", "mysql", "password", "for", "the", "provided", "username", "using", "peer", "relation", "cluster", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/database/mysql.py#L265-L293
12,423
juju/charm-helpers
charmhelpers/contrib/database/mysql.py
MySQLHelper.set_mysql_password
def set_mysql_password(self, username, password): """Update a mysql password for the provided username changing the leader settings To update root's password pass `None` in the username """ if username is None: username = 'root' # get root password via leader-get, it may be that in the past (when # changes to root-password were not supported) the user changed the # password, so leader-get is more reliable source than # config.previous('root-password'). rel_username = None if username == 'root' else username cur_passwd = self.get_mysql_password(rel_username) # password that needs to be set new_passwd = password # update password for all users (e.g. root@localhost, root@::1, etc) try: self.connect(user=username, password=cur_passwd) cursor = self.connection.cursor() except MySQLdb.OperationalError as ex: raise MySQLSetPasswordError(('Cannot connect using password in ' 'leader settings (%s)') % ex, ex) try: # NOTE(freyes): Due to skip-name-resolve root@$HOSTNAME account # fails when using SET PASSWORD so using UPDATE against the # mysql.user table is needed, but changes to this table are not # replicated across the cluster, so this update needs to run in # all the nodes. More info at # http://galeracluster.com/documentation-webpages/userchanges.html release = CompareHostReleases(lsb_release()['DISTRIB_CODENAME']) if release < 'bionic': SQL_UPDATE_PASSWD = ("UPDATE mysql.user SET password = " "PASSWORD( %s ) WHERE user = %s;") else: # PXC 5.7 (introduced in Bionic) uses authentication_string SQL_UPDATE_PASSWD = ("UPDATE mysql.user SET " "authentication_string = " "PASSWORD( %s ) WHERE user = %s;") cursor.execute(SQL_UPDATE_PASSWD, (new_passwd, username)) cursor.execute('FLUSH PRIVILEGES;') self.connection.commit() except MySQLdb.OperationalError as ex: raise MySQLSetPasswordError('Cannot update password: %s' % str(ex), ex) finally: cursor.close() # check the password was changed try: self.connect(user=username, password=new_passwd) self.execute('select 1;') except MySQLdb.OperationalError as ex: raise MySQLSetPasswordError(('Cannot connect using new password: ' '%s') % str(ex), ex) if not is_leader(): log('Only the leader can set a new password in the relation', level=DEBUG) return for key in self.passwd_keys(rel_username): _password = leader_get(key) if _password: log('Updating password for %s (%s)' % (key, rel_username), level=DEBUG) leader_set(settings={key: new_passwd})
python
def set_mysql_password(self, username, password): """Update a mysql password for the provided username changing the leader settings To update root's password pass `None` in the username """ if username is None: username = 'root' # get root password via leader-get, it may be that in the past (when # changes to root-password were not supported) the user changed the # password, so leader-get is more reliable source than # config.previous('root-password'). rel_username = None if username == 'root' else username cur_passwd = self.get_mysql_password(rel_username) # password that needs to be set new_passwd = password # update password for all users (e.g. root@localhost, root@::1, etc) try: self.connect(user=username, password=cur_passwd) cursor = self.connection.cursor() except MySQLdb.OperationalError as ex: raise MySQLSetPasswordError(('Cannot connect using password in ' 'leader settings (%s)') % ex, ex) try: # NOTE(freyes): Due to skip-name-resolve root@$HOSTNAME account # fails when using SET PASSWORD so using UPDATE against the # mysql.user table is needed, but changes to this table are not # replicated across the cluster, so this update needs to run in # all the nodes. More info at # http://galeracluster.com/documentation-webpages/userchanges.html release = CompareHostReleases(lsb_release()['DISTRIB_CODENAME']) if release < 'bionic': SQL_UPDATE_PASSWD = ("UPDATE mysql.user SET password = " "PASSWORD( %s ) WHERE user = %s;") else: # PXC 5.7 (introduced in Bionic) uses authentication_string SQL_UPDATE_PASSWD = ("UPDATE mysql.user SET " "authentication_string = " "PASSWORD( %s ) WHERE user = %s;") cursor.execute(SQL_UPDATE_PASSWD, (new_passwd, username)) cursor.execute('FLUSH PRIVILEGES;') self.connection.commit() except MySQLdb.OperationalError as ex: raise MySQLSetPasswordError('Cannot update password: %s' % str(ex), ex) finally: cursor.close() # check the password was changed try: self.connect(user=username, password=new_passwd) self.execute('select 1;') except MySQLdb.OperationalError as ex: raise MySQLSetPasswordError(('Cannot connect using new password: ' '%s') % str(ex), ex) if not is_leader(): log('Only the leader can set a new password in the relation', level=DEBUG) return for key in self.passwd_keys(rel_username): _password = leader_get(key) if _password: log('Updating password for %s (%s)' % (key, rel_username), level=DEBUG) leader_set(settings={key: new_passwd})
[ "def", "set_mysql_password", "(", "self", ",", "username", ",", "password", ")", ":", "if", "username", "is", "None", ":", "username", "=", "'root'", "# get root password via leader-get, it may be that in the past (when", "# changes to root-password were not supported) the user changed the", "# password, so leader-get is more reliable source than", "# config.previous('root-password').", "rel_username", "=", "None", "if", "username", "==", "'root'", "else", "username", "cur_passwd", "=", "self", ".", "get_mysql_password", "(", "rel_username", ")", "# password that needs to be set", "new_passwd", "=", "password", "# update password for all users (e.g. root@localhost, root@::1, etc)", "try", ":", "self", ".", "connect", "(", "user", "=", "username", ",", "password", "=", "cur_passwd", ")", "cursor", "=", "self", ".", "connection", ".", "cursor", "(", ")", "except", "MySQLdb", ".", "OperationalError", "as", "ex", ":", "raise", "MySQLSetPasswordError", "(", "(", "'Cannot connect using password in '", "'leader settings (%s)'", ")", "%", "ex", ",", "ex", ")", "try", ":", "# NOTE(freyes): Due to skip-name-resolve root@$HOSTNAME account", "# fails when using SET PASSWORD so using UPDATE against the", "# mysql.user table is needed, but changes to this table are not", "# replicated across the cluster, so this update needs to run in", "# all the nodes. More info at", "# http://galeracluster.com/documentation-webpages/userchanges.html", "release", "=", "CompareHostReleases", "(", "lsb_release", "(", ")", "[", "'DISTRIB_CODENAME'", "]", ")", "if", "release", "<", "'bionic'", ":", "SQL_UPDATE_PASSWD", "=", "(", "\"UPDATE mysql.user SET password = \"", "\"PASSWORD( %s ) WHERE user = %s;\"", ")", "else", ":", "# PXC 5.7 (introduced in Bionic) uses authentication_string", "SQL_UPDATE_PASSWD", "=", "(", "\"UPDATE mysql.user SET \"", "\"authentication_string = \"", "\"PASSWORD( %s ) WHERE user = %s;\"", ")", "cursor", ".", "execute", "(", "SQL_UPDATE_PASSWD", ",", "(", "new_passwd", ",", "username", ")", ")", "cursor", ".", "execute", "(", "'FLUSH PRIVILEGES;'", ")", "self", ".", "connection", ".", "commit", "(", ")", "except", "MySQLdb", ".", "OperationalError", "as", "ex", ":", "raise", "MySQLSetPasswordError", "(", "'Cannot update password: %s'", "%", "str", "(", "ex", ")", ",", "ex", ")", "finally", ":", "cursor", ".", "close", "(", ")", "# check the password was changed", "try", ":", "self", ".", "connect", "(", "user", "=", "username", ",", "password", "=", "new_passwd", ")", "self", ".", "execute", "(", "'select 1;'", ")", "except", "MySQLdb", ".", "OperationalError", "as", "ex", ":", "raise", "MySQLSetPasswordError", "(", "(", "'Cannot connect using new password: '", "'%s'", ")", "%", "str", "(", "ex", ")", ",", "ex", ")", "if", "not", "is_leader", "(", ")", ":", "log", "(", "'Only the leader can set a new password in the relation'", ",", "level", "=", "DEBUG", ")", "return", "for", "key", "in", "self", ".", "passwd_keys", "(", "rel_username", ")", ":", "_password", "=", "leader_get", "(", "key", ")", "if", "_password", ":", "log", "(", "'Updating password for %s (%s)'", "%", "(", "key", ",", "rel_username", ")", ",", "level", "=", "DEBUG", ")", "leader_set", "(", "settings", "=", "{", "key", ":", "new_passwd", "}", ")" ]
Update a mysql password for the provided username changing the leader settings To update root's password pass `None` in the username
[ "Update", "a", "mysql", "password", "for", "the", "provided", "username", "changing", "the", "leader", "settings" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/database/mysql.py#L299-L370
12,424
juju/charm-helpers
charmhelpers/contrib/database/mysql.py
MySQLHelper.get_allowed_units
def get_allowed_units(self, database, username, relation_id=None): """Get list of units with access grants for database with username. This is typically used to provide shared-db relations with a list of which units have been granted access to the given database. """ self.connect(password=self.get_mysql_root_password()) allowed_units = set() for unit in related_units(relation_id): settings = relation_get(rid=relation_id, unit=unit) # First check for setting with prefix, then without for attr in ["%s_hostname" % (database), 'hostname']: hosts = settings.get(attr, None) if hosts: break if hosts: # hostname can be json-encoded list of hostnames try: hosts = json.loads(hosts) except ValueError: hosts = [hosts] else: hosts = [settings['private-address']] if hosts: for host in hosts: host = self.normalize_address(host) if self.grant_exists(database, username, host): log("Grant exists for host '%s' on db '%s'" % (host, database), level=DEBUG) if unit not in allowed_units: allowed_units.add(unit) else: log("Grant does NOT exist for host '%s' on db '%s'" % (host, database), level=DEBUG) else: log("No hosts found for grant check", level=INFO) return allowed_units
python
def get_allowed_units(self, database, username, relation_id=None): """Get list of units with access grants for database with username. This is typically used to provide shared-db relations with a list of which units have been granted access to the given database. """ self.connect(password=self.get_mysql_root_password()) allowed_units = set() for unit in related_units(relation_id): settings = relation_get(rid=relation_id, unit=unit) # First check for setting with prefix, then without for attr in ["%s_hostname" % (database), 'hostname']: hosts = settings.get(attr, None) if hosts: break if hosts: # hostname can be json-encoded list of hostnames try: hosts = json.loads(hosts) except ValueError: hosts = [hosts] else: hosts = [settings['private-address']] if hosts: for host in hosts: host = self.normalize_address(host) if self.grant_exists(database, username, host): log("Grant exists for host '%s' on db '%s'" % (host, database), level=DEBUG) if unit not in allowed_units: allowed_units.add(unit) else: log("Grant does NOT exist for host '%s' on db '%s'" % (host, database), level=DEBUG) else: log("No hosts found for grant check", level=INFO) return allowed_units
[ "def", "get_allowed_units", "(", "self", ",", "database", ",", "username", ",", "relation_id", "=", "None", ")", ":", "self", ".", "connect", "(", "password", "=", "self", ".", "get_mysql_root_password", "(", ")", ")", "allowed_units", "=", "set", "(", ")", "for", "unit", "in", "related_units", "(", "relation_id", ")", ":", "settings", "=", "relation_get", "(", "rid", "=", "relation_id", ",", "unit", "=", "unit", ")", "# First check for setting with prefix, then without", "for", "attr", "in", "[", "\"%s_hostname\"", "%", "(", "database", ")", ",", "'hostname'", "]", ":", "hosts", "=", "settings", ".", "get", "(", "attr", ",", "None", ")", "if", "hosts", ":", "break", "if", "hosts", ":", "# hostname can be json-encoded list of hostnames", "try", ":", "hosts", "=", "json", ".", "loads", "(", "hosts", ")", "except", "ValueError", ":", "hosts", "=", "[", "hosts", "]", "else", ":", "hosts", "=", "[", "settings", "[", "'private-address'", "]", "]", "if", "hosts", ":", "for", "host", "in", "hosts", ":", "host", "=", "self", ".", "normalize_address", "(", "host", ")", "if", "self", ".", "grant_exists", "(", "database", ",", "username", ",", "host", ")", ":", "log", "(", "\"Grant exists for host '%s' on db '%s'\"", "%", "(", "host", ",", "database", ")", ",", "level", "=", "DEBUG", ")", "if", "unit", "not", "in", "allowed_units", ":", "allowed_units", ".", "add", "(", "unit", ")", "else", ":", "log", "(", "\"Grant does NOT exist for host '%s' on db '%s'\"", "%", "(", "host", ",", "database", ")", ",", "level", "=", "DEBUG", ")", "else", ":", "log", "(", "\"No hosts found for grant check\"", ",", "level", "=", "INFO", ")", "return", "allowed_units" ]
Get list of units with access grants for database with username. This is typically used to provide shared-db relations with a list of which units have been granted access to the given database.
[ "Get", "list", "of", "units", "with", "access", "grants", "for", "database", "with", "username", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/database/mysql.py#L387-L426
12,425
juju/charm-helpers
charmhelpers/contrib/database/mysql.py
MySQLHelper.configure_db
def configure_db(self, hostname, database, username, admin=False): """Configure access to database for username from hostname.""" self.connect(password=self.get_mysql_root_password()) if not self.database_exists(database): self.create_database(database) remote_ip = self.normalize_address(hostname) password = self.get_mysql_password(username) if not self.grant_exists(database, username, remote_ip): if not admin: self.create_grant(database, username, remote_ip, password) else: self.create_admin_grant(username, remote_ip, password) self.flush_priviledges() return password
python
def configure_db(self, hostname, database, username, admin=False): """Configure access to database for username from hostname.""" self.connect(password=self.get_mysql_root_password()) if not self.database_exists(database): self.create_database(database) remote_ip = self.normalize_address(hostname) password = self.get_mysql_password(username) if not self.grant_exists(database, username, remote_ip): if not admin: self.create_grant(database, username, remote_ip, password) else: self.create_admin_grant(username, remote_ip, password) self.flush_priviledges() return password
[ "def", "configure_db", "(", "self", ",", "hostname", ",", "database", ",", "username", ",", "admin", "=", "False", ")", ":", "self", ".", "connect", "(", "password", "=", "self", ".", "get_mysql_root_password", "(", ")", ")", "if", "not", "self", ".", "database_exists", "(", "database", ")", ":", "self", ".", "create_database", "(", "database", ")", "remote_ip", "=", "self", ".", "normalize_address", "(", "hostname", ")", "password", "=", "self", ".", "get_mysql_password", "(", "username", ")", "if", "not", "self", ".", "grant_exists", "(", "database", ",", "username", ",", "remote_ip", ")", ":", "if", "not", "admin", ":", "self", ".", "create_grant", "(", "database", ",", "username", ",", "remote_ip", ",", "password", ")", "else", ":", "self", ".", "create_admin_grant", "(", "username", ",", "remote_ip", ",", "password", ")", "self", ".", "flush_priviledges", "(", ")", "return", "password" ]
Configure access to database for username from hostname.
[ "Configure", "access", "to", "database", "for", "username", "from", "hostname", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/database/mysql.py#L428-L443
12,426
juju/charm-helpers
charmhelpers/contrib/database/mysql.py
PerconaClusterHelper.human_to_bytes
def human_to_bytes(self, human): """Convert human readable configuration options to bytes.""" num_re = re.compile('^[0-9]+$') if num_re.match(human): return human factors = { 'K': 1024, 'M': 1048576, 'G': 1073741824, 'T': 1099511627776 } modifier = human[-1] if modifier in factors: return int(human[:-1]) * factors[modifier] if modifier == '%': total_ram = self.human_to_bytes(self.get_mem_total()) if self.is_32bit_system() and total_ram > self.sys_mem_limit(): total_ram = self.sys_mem_limit() factor = int(human[:-1]) * 0.01 pctram = total_ram * factor return int(pctram - (pctram % self.DEFAULT_PAGE_SIZE)) raise ValueError("Can only convert K,M,G, or T")
python
def human_to_bytes(self, human): """Convert human readable configuration options to bytes.""" num_re = re.compile('^[0-9]+$') if num_re.match(human): return human factors = { 'K': 1024, 'M': 1048576, 'G': 1073741824, 'T': 1099511627776 } modifier = human[-1] if modifier in factors: return int(human[:-1]) * factors[modifier] if modifier == '%': total_ram = self.human_to_bytes(self.get_mem_total()) if self.is_32bit_system() and total_ram > self.sys_mem_limit(): total_ram = self.sys_mem_limit() factor = int(human[:-1]) * 0.01 pctram = total_ram * factor return int(pctram - (pctram % self.DEFAULT_PAGE_SIZE)) raise ValueError("Can only convert K,M,G, or T")
[ "def", "human_to_bytes", "(", "self", ",", "human", ")", ":", "num_re", "=", "re", ".", "compile", "(", "'^[0-9]+$'", ")", "if", "num_re", ".", "match", "(", "human", ")", ":", "return", "human", "factors", "=", "{", "'K'", ":", "1024", ",", "'M'", ":", "1048576", ",", "'G'", ":", "1073741824", ",", "'T'", ":", "1099511627776", "}", "modifier", "=", "human", "[", "-", "1", "]", "if", "modifier", "in", "factors", ":", "return", "int", "(", "human", "[", ":", "-", "1", "]", ")", "*", "factors", "[", "modifier", "]", "if", "modifier", "==", "'%'", ":", "total_ram", "=", "self", ".", "human_to_bytes", "(", "self", ".", "get_mem_total", "(", ")", ")", "if", "self", ".", "is_32bit_system", "(", ")", "and", "total_ram", ">", "self", ".", "sys_mem_limit", "(", ")", ":", "total_ram", "=", "self", ".", "sys_mem_limit", "(", ")", "factor", "=", "int", "(", "human", "[", ":", "-", "1", "]", ")", "*", "0.01", "pctram", "=", "total_ram", "*", "factor", "return", "int", "(", "pctram", "-", "(", "pctram", "%", "self", ".", "DEFAULT_PAGE_SIZE", ")", ")", "raise", "ValueError", "(", "\"Can only convert K,M,G, or T\"", ")" ]
Convert human readable configuration options to bytes.
[ "Convert", "human", "readable", "configuration", "options", "to", "bytes", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/database/mysql.py#L470-L494
12,427
juju/charm-helpers
charmhelpers/contrib/database/mysql.py
PerconaClusterHelper.sys_mem_limit
def sys_mem_limit(self): """Determine the default memory limit for the current service unit.""" if platform.machine() in ['armv7l']: _mem_limit = self.human_to_bytes('2700M') # experimentally determined else: # Limit for x86 based 32bit systems _mem_limit = self.human_to_bytes('4G') return _mem_limit
python
def sys_mem_limit(self): """Determine the default memory limit for the current service unit.""" if platform.machine() in ['armv7l']: _mem_limit = self.human_to_bytes('2700M') # experimentally determined else: # Limit for x86 based 32bit systems _mem_limit = self.human_to_bytes('4G') return _mem_limit
[ "def", "sys_mem_limit", "(", "self", ")", ":", "if", "platform", ".", "machine", "(", ")", "in", "[", "'armv7l'", "]", ":", "_mem_limit", "=", "self", ".", "human_to_bytes", "(", "'2700M'", ")", "# experimentally determined", "else", ":", "# Limit for x86 based 32bit systems", "_mem_limit", "=", "self", ".", "human_to_bytes", "(", "'4G'", ")", "return", "_mem_limit" ]
Determine the default memory limit for the current service unit.
[ "Determine", "the", "default", "memory", "limit", "for", "the", "current", "service", "unit", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/database/mysql.py#L503-L511
12,428
juju/charm-helpers
charmhelpers/contrib/database/mysql.py
PerconaClusterHelper.get_mem_total
def get_mem_total(self): """Calculate the total memory in the current service unit.""" with open('/proc/meminfo') as meminfo_file: for line in meminfo_file: key, mem = line.split(':', 2) if key == 'MemTotal': mtot, modifier = mem.strip().split(' ') return '%s%s' % (mtot, modifier[0].upper())
python
def get_mem_total(self): """Calculate the total memory in the current service unit.""" with open('/proc/meminfo') as meminfo_file: for line in meminfo_file: key, mem = line.split(':', 2) if key == 'MemTotal': mtot, modifier = mem.strip().split(' ') return '%s%s' % (mtot, modifier[0].upper())
[ "def", "get_mem_total", "(", "self", ")", ":", "with", "open", "(", "'/proc/meminfo'", ")", "as", "meminfo_file", ":", "for", "line", "in", "meminfo_file", ":", "key", ",", "mem", "=", "line", ".", "split", "(", "':'", ",", "2", ")", "if", "key", "==", "'MemTotal'", ":", "mtot", ",", "modifier", "=", "mem", ".", "strip", "(", ")", ".", "split", "(", "' '", ")", "return", "'%s%s'", "%", "(", "mtot", ",", "modifier", "[", "0", "]", ".", "upper", "(", ")", ")" ]
Calculate the total memory in the current service unit.
[ "Calculate", "the", "total", "memory", "in", "the", "current", "service", "unit", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/database/mysql.py#L513-L520
12,429
juju/charm-helpers
charmhelpers/contrib/database/mysql.py
PerconaClusterHelper.parse_config
def parse_config(self): """Parse charm configuration and calculate values for config files.""" config = config_get() mysql_config = {} if 'max-connections' in config: mysql_config['max_connections'] = config['max-connections'] if 'wait-timeout' in config: mysql_config['wait_timeout'] = config['wait-timeout'] if 'innodb-flush-log-at-trx-commit' in config: mysql_config['innodb_flush_log_at_trx_commit'] = \ config['innodb-flush-log-at-trx-commit'] elif 'tuning-level' in config: mysql_config['innodb_flush_log_at_trx_commit'] = \ self.INNODB_FLUSH_CONFIG_VALUES.get(config['tuning-level'], 1) if ('innodb-change-buffering' in config and config['innodb-change-buffering'] in self.INNODB_VALID_BUFFERING_VALUES): mysql_config['innodb_change_buffering'] = config['innodb-change-buffering'] if 'innodb-io-capacity' in config: mysql_config['innodb_io_capacity'] = config['innodb-io-capacity'] # Set a sane default key_buffer size mysql_config['key_buffer'] = self.human_to_bytes('32M') total_memory = self.human_to_bytes(self.get_mem_total()) dataset_bytes = config.get('dataset-size', None) innodb_buffer_pool_size = config.get('innodb-buffer-pool-size', None) if innodb_buffer_pool_size: innodb_buffer_pool_size = self.human_to_bytes( innodb_buffer_pool_size) elif dataset_bytes: log("Option 'dataset-size' has been deprecated, please use" "innodb_buffer_pool_size option instead", level="WARN") innodb_buffer_pool_size = self.human_to_bytes( dataset_bytes) else: # NOTE(jamespage): pick the smallest of 50% of RAM or 512MB # to ensure that deployments in containers # without constraints don't try to consume # silly amounts of memory. innodb_buffer_pool_size = min( int(total_memory * self.DEFAULT_INNODB_BUFFER_FACTOR), self.DEFAULT_INNODB_BUFFER_SIZE_MAX ) if innodb_buffer_pool_size > total_memory: log("innodb_buffer_pool_size; {} is greater than system available memory:{}".format( innodb_buffer_pool_size, total_memory), level='WARN') mysql_config['innodb_buffer_pool_size'] = innodb_buffer_pool_size return mysql_config
python
def parse_config(self): """Parse charm configuration and calculate values for config files.""" config = config_get() mysql_config = {} if 'max-connections' in config: mysql_config['max_connections'] = config['max-connections'] if 'wait-timeout' in config: mysql_config['wait_timeout'] = config['wait-timeout'] if 'innodb-flush-log-at-trx-commit' in config: mysql_config['innodb_flush_log_at_trx_commit'] = \ config['innodb-flush-log-at-trx-commit'] elif 'tuning-level' in config: mysql_config['innodb_flush_log_at_trx_commit'] = \ self.INNODB_FLUSH_CONFIG_VALUES.get(config['tuning-level'], 1) if ('innodb-change-buffering' in config and config['innodb-change-buffering'] in self.INNODB_VALID_BUFFERING_VALUES): mysql_config['innodb_change_buffering'] = config['innodb-change-buffering'] if 'innodb-io-capacity' in config: mysql_config['innodb_io_capacity'] = config['innodb-io-capacity'] # Set a sane default key_buffer size mysql_config['key_buffer'] = self.human_to_bytes('32M') total_memory = self.human_to_bytes(self.get_mem_total()) dataset_bytes = config.get('dataset-size', None) innodb_buffer_pool_size = config.get('innodb-buffer-pool-size', None) if innodb_buffer_pool_size: innodb_buffer_pool_size = self.human_to_bytes( innodb_buffer_pool_size) elif dataset_bytes: log("Option 'dataset-size' has been deprecated, please use" "innodb_buffer_pool_size option instead", level="WARN") innodb_buffer_pool_size = self.human_to_bytes( dataset_bytes) else: # NOTE(jamespage): pick the smallest of 50% of RAM or 512MB # to ensure that deployments in containers # without constraints don't try to consume # silly amounts of memory. innodb_buffer_pool_size = min( int(total_memory * self.DEFAULT_INNODB_BUFFER_FACTOR), self.DEFAULT_INNODB_BUFFER_SIZE_MAX ) if innodb_buffer_pool_size > total_memory: log("innodb_buffer_pool_size; {} is greater than system available memory:{}".format( innodb_buffer_pool_size, total_memory), level='WARN') mysql_config['innodb_buffer_pool_size'] = innodb_buffer_pool_size return mysql_config
[ "def", "parse_config", "(", "self", ")", ":", "config", "=", "config_get", "(", ")", "mysql_config", "=", "{", "}", "if", "'max-connections'", "in", "config", ":", "mysql_config", "[", "'max_connections'", "]", "=", "config", "[", "'max-connections'", "]", "if", "'wait-timeout'", "in", "config", ":", "mysql_config", "[", "'wait_timeout'", "]", "=", "config", "[", "'wait-timeout'", "]", "if", "'innodb-flush-log-at-trx-commit'", "in", "config", ":", "mysql_config", "[", "'innodb_flush_log_at_trx_commit'", "]", "=", "config", "[", "'innodb-flush-log-at-trx-commit'", "]", "elif", "'tuning-level'", "in", "config", ":", "mysql_config", "[", "'innodb_flush_log_at_trx_commit'", "]", "=", "self", ".", "INNODB_FLUSH_CONFIG_VALUES", ".", "get", "(", "config", "[", "'tuning-level'", "]", ",", "1", ")", "if", "(", "'innodb-change-buffering'", "in", "config", "and", "config", "[", "'innodb-change-buffering'", "]", "in", "self", ".", "INNODB_VALID_BUFFERING_VALUES", ")", ":", "mysql_config", "[", "'innodb_change_buffering'", "]", "=", "config", "[", "'innodb-change-buffering'", "]", "if", "'innodb-io-capacity'", "in", "config", ":", "mysql_config", "[", "'innodb_io_capacity'", "]", "=", "config", "[", "'innodb-io-capacity'", "]", "# Set a sane default key_buffer size", "mysql_config", "[", "'key_buffer'", "]", "=", "self", ".", "human_to_bytes", "(", "'32M'", ")", "total_memory", "=", "self", ".", "human_to_bytes", "(", "self", ".", "get_mem_total", "(", ")", ")", "dataset_bytes", "=", "config", ".", "get", "(", "'dataset-size'", ",", "None", ")", "innodb_buffer_pool_size", "=", "config", ".", "get", "(", "'innodb-buffer-pool-size'", ",", "None", ")", "if", "innodb_buffer_pool_size", ":", "innodb_buffer_pool_size", "=", "self", ".", "human_to_bytes", "(", "innodb_buffer_pool_size", ")", "elif", "dataset_bytes", ":", "log", "(", "\"Option 'dataset-size' has been deprecated, please use\"", "\"innodb_buffer_pool_size option instead\"", ",", "level", "=", "\"WARN\"", ")", "innodb_buffer_pool_size", "=", "self", ".", "human_to_bytes", "(", "dataset_bytes", ")", "else", ":", "# NOTE(jamespage): pick the smallest of 50% of RAM or 512MB", "# to ensure that deployments in containers", "# without constraints don't try to consume", "# silly amounts of memory.", "innodb_buffer_pool_size", "=", "min", "(", "int", "(", "total_memory", "*", "self", ".", "DEFAULT_INNODB_BUFFER_FACTOR", ")", ",", "self", ".", "DEFAULT_INNODB_BUFFER_SIZE_MAX", ")", "if", "innodb_buffer_pool_size", ">", "total_memory", ":", "log", "(", "\"innodb_buffer_pool_size; {} is greater than system available memory:{}\"", ".", "format", "(", "innodb_buffer_pool_size", ",", "total_memory", ")", ",", "level", "=", "'WARN'", ")", "mysql_config", "[", "'innodb_buffer_pool_size'", "]", "=", "innodb_buffer_pool_size", "return", "mysql_config" ]
Parse charm configuration and calculate values for config files.
[ "Parse", "charm", "configuration", "and", "calculate", "values", "for", "config", "files", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/database/mysql.py#L522-L577
12,430
juju/charm-helpers
charmhelpers/contrib/storage/linux/loopback.py
create_loopback
def create_loopback(file_path): ''' Create a loopback device for a given backing file. :returns: str: Full path to new loopback device (eg, /dev/loop0) ''' file_path = os.path.abspath(file_path) check_call(['losetup', '--find', file_path]) for d, f in six.iteritems(loopback_devices()): if f == file_path: return d
python
def create_loopback(file_path): ''' Create a loopback device for a given backing file. :returns: str: Full path to new loopback device (eg, /dev/loop0) ''' file_path = os.path.abspath(file_path) check_call(['losetup', '--find', file_path]) for d, f in six.iteritems(loopback_devices()): if f == file_path: return d
[ "def", "create_loopback", "(", "file_path", ")", ":", "file_path", "=", "os", ".", "path", ".", "abspath", "(", "file_path", ")", "check_call", "(", "[", "'losetup'", ",", "'--find'", ",", "file_path", "]", ")", "for", "d", ",", "f", "in", "six", ".", "iteritems", "(", "loopback_devices", "(", ")", ")", ":", "if", "f", "==", "file_path", ":", "return", "d" ]
Create a loopback device for a given backing file. :returns: str: Full path to new loopback device (eg, /dev/loop0)
[ "Create", "a", "loopback", "device", "for", "a", "given", "backing", "file", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/storage/linux/loopback.py#L48-L58
12,431
juju/charm-helpers
charmhelpers/contrib/storage/linux/loopback.py
ensure_loopback_device
def ensure_loopback_device(path, size): ''' Ensure a loopback device exists for a given backing file path and size. If it a loopback device is not mapped to file, a new one will be created. TODO: Confirm size of found loopback device. :returns: str: Full path to the ensured loopback device (eg, /dev/loop0) ''' for d, f in six.iteritems(loopback_devices()): if f == path: return d if not os.path.exists(path): cmd = ['truncate', '--size', size, path] check_call(cmd) return create_loopback(path)
python
def ensure_loopback_device(path, size): ''' Ensure a loopback device exists for a given backing file path and size. If it a loopback device is not mapped to file, a new one will be created. TODO: Confirm size of found loopback device. :returns: str: Full path to the ensured loopback device (eg, /dev/loop0) ''' for d, f in six.iteritems(loopback_devices()): if f == path: return d if not os.path.exists(path): cmd = ['truncate', '--size', size, path] check_call(cmd) return create_loopback(path)
[ "def", "ensure_loopback_device", "(", "path", ",", "size", ")", ":", "for", "d", ",", "f", "in", "six", ".", "iteritems", "(", "loopback_devices", "(", ")", ")", ":", "if", "f", "==", "path", ":", "return", "d", "if", "not", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "cmd", "=", "[", "'truncate'", ",", "'--size'", ",", "size", ",", "path", "]", "check_call", "(", "cmd", ")", "return", "create_loopback", "(", "path", ")" ]
Ensure a loopback device exists for a given backing file path and size. If it a loopback device is not mapped to file, a new one will be created. TODO: Confirm size of found loopback device. :returns: str: Full path to the ensured loopback device (eg, /dev/loop0)
[ "Ensure", "a", "loopback", "device", "exists", "for", "a", "given", "backing", "file", "path", "and", "size", ".", "If", "it", "a", "loopback", "device", "is", "not", "mapped", "to", "file", "a", "new", "one", "will", "be", "created", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/storage/linux/loopback.py#L61-L78
12,432
juju/charm-helpers
charmhelpers/contrib/peerstorage/__init__.py
leader_get
def leader_get(attribute=None, rid=None): """Wrapper to ensure that settings are migrated from the peer relation. This is to support upgrading an environment that does not support Juju leadership election to one that does. If a setting is not extant in the leader-get but is on the relation-get peer rel, it is migrated and marked as such so that it is not re-migrated. """ migration_key = '__leader_get_migrated_settings__' if not is_leader(): return _leader_get(attribute=attribute) settings_migrated = False leader_settings = _leader_get(attribute=attribute) previously_migrated = _leader_get(attribute=migration_key) if previously_migrated: migrated = set(json.loads(previously_migrated)) else: migrated = set([]) try: if migration_key in leader_settings: del leader_settings[migration_key] except TypeError: pass if attribute: if attribute in migrated: return leader_settings # If attribute not present in leader db, check if this unit has set # the attribute in the peer relation if not leader_settings: peer_setting = _relation_get(attribute=attribute, unit=local_unit(), rid=rid) if peer_setting: leader_set(settings={attribute: peer_setting}) leader_settings = peer_setting if leader_settings: settings_migrated = True migrated.add(attribute) else: r_settings = _relation_get(unit=local_unit(), rid=rid) if r_settings: for key in set(r_settings.keys()).difference(migrated): # Leader setting wins if not leader_settings.get(key): leader_settings[key] = r_settings[key] settings_migrated = True migrated.add(key) if settings_migrated: leader_set(**leader_settings) if migrated and settings_migrated: migrated = json.dumps(list(migrated)) leader_set(settings={migration_key: migrated}) return leader_settings
python
def leader_get(attribute=None, rid=None): """Wrapper to ensure that settings are migrated from the peer relation. This is to support upgrading an environment that does not support Juju leadership election to one that does. If a setting is not extant in the leader-get but is on the relation-get peer rel, it is migrated and marked as such so that it is not re-migrated. """ migration_key = '__leader_get_migrated_settings__' if not is_leader(): return _leader_get(attribute=attribute) settings_migrated = False leader_settings = _leader_get(attribute=attribute) previously_migrated = _leader_get(attribute=migration_key) if previously_migrated: migrated = set(json.loads(previously_migrated)) else: migrated = set([]) try: if migration_key in leader_settings: del leader_settings[migration_key] except TypeError: pass if attribute: if attribute in migrated: return leader_settings # If attribute not present in leader db, check if this unit has set # the attribute in the peer relation if not leader_settings: peer_setting = _relation_get(attribute=attribute, unit=local_unit(), rid=rid) if peer_setting: leader_set(settings={attribute: peer_setting}) leader_settings = peer_setting if leader_settings: settings_migrated = True migrated.add(attribute) else: r_settings = _relation_get(unit=local_unit(), rid=rid) if r_settings: for key in set(r_settings.keys()).difference(migrated): # Leader setting wins if not leader_settings.get(key): leader_settings[key] = r_settings[key] settings_migrated = True migrated.add(key) if settings_migrated: leader_set(**leader_settings) if migrated and settings_migrated: migrated = json.dumps(list(migrated)) leader_set(settings={migration_key: migrated}) return leader_settings
[ "def", "leader_get", "(", "attribute", "=", "None", ",", "rid", "=", "None", ")", ":", "migration_key", "=", "'__leader_get_migrated_settings__'", "if", "not", "is_leader", "(", ")", ":", "return", "_leader_get", "(", "attribute", "=", "attribute", ")", "settings_migrated", "=", "False", "leader_settings", "=", "_leader_get", "(", "attribute", "=", "attribute", ")", "previously_migrated", "=", "_leader_get", "(", "attribute", "=", "migration_key", ")", "if", "previously_migrated", ":", "migrated", "=", "set", "(", "json", ".", "loads", "(", "previously_migrated", ")", ")", "else", ":", "migrated", "=", "set", "(", "[", "]", ")", "try", ":", "if", "migration_key", "in", "leader_settings", ":", "del", "leader_settings", "[", "migration_key", "]", "except", "TypeError", ":", "pass", "if", "attribute", ":", "if", "attribute", "in", "migrated", ":", "return", "leader_settings", "# If attribute not present in leader db, check if this unit has set", "# the attribute in the peer relation", "if", "not", "leader_settings", ":", "peer_setting", "=", "_relation_get", "(", "attribute", "=", "attribute", ",", "unit", "=", "local_unit", "(", ")", ",", "rid", "=", "rid", ")", "if", "peer_setting", ":", "leader_set", "(", "settings", "=", "{", "attribute", ":", "peer_setting", "}", ")", "leader_settings", "=", "peer_setting", "if", "leader_settings", ":", "settings_migrated", "=", "True", "migrated", ".", "add", "(", "attribute", ")", "else", ":", "r_settings", "=", "_relation_get", "(", "unit", "=", "local_unit", "(", ")", ",", "rid", "=", "rid", ")", "if", "r_settings", ":", "for", "key", "in", "set", "(", "r_settings", ".", "keys", "(", ")", ")", ".", "difference", "(", "migrated", ")", ":", "# Leader setting wins", "if", "not", "leader_settings", ".", "get", "(", "key", ")", ":", "leader_settings", "[", "key", "]", "=", "r_settings", "[", "key", "]", "settings_migrated", "=", "True", "migrated", ".", "add", "(", "key", ")", "if", "settings_migrated", ":", "leader_set", "(", "*", "*", "leader_settings", ")", "if", "migrated", "and", "settings_migrated", ":", "migrated", "=", "json", ".", "dumps", "(", "list", "(", "migrated", ")", ")", "leader_set", "(", "settings", "=", "{", "migration_key", ":", "migrated", "}", ")", "return", "leader_settings" ]
Wrapper to ensure that settings are migrated from the peer relation. This is to support upgrading an environment that does not support Juju leadership election to one that does. If a setting is not extant in the leader-get but is on the relation-get peer rel, it is migrated and marked as such so that it is not re-migrated.
[ "Wrapper", "to", "ensure", "that", "settings", "are", "migrated", "from", "the", "peer", "relation", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/peerstorage/__init__.py#L60-L122
12,433
juju/charm-helpers
charmhelpers/contrib/peerstorage/__init__.py
relation_set
def relation_set(relation_id=None, relation_settings=None, **kwargs): """Attempt to use leader-set if supported in the current version of Juju, otherwise falls back on relation-set. Note that we only attempt to use leader-set if the provided relation_id is a peer relation id or no relation id is provided (in which case we assume we are within the peer relation context). """ try: if relation_id in relation_ids('cluster'): return leader_set(settings=relation_settings, **kwargs) else: raise NotImplementedError except NotImplementedError: return _relation_set(relation_id=relation_id, relation_settings=relation_settings, **kwargs)
python
def relation_set(relation_id=None, relation_settings=None, **kwargs): """Attempt to use leader-set if supported in the current version of Juju, otherwise falls back on relation-set. Note that we only attempt to use leader-set if the provided relation_id is a peer relation id or no relation id is provided (in which case we assume we are within the peer relation context). """ try: if relation_id in relation_ids('cluster'): return leader_set(settings=relation_settings, **kwargs) else: raise NotImplementedError except NotImplementedError: return _relation_set(relation_id=relation_id, relation_settings=relation_settings, **kwargs)
[ "def", "relation_set", "(", "relation_id", "=", "None", ",", "relation_settings", "=", "None", ",", "*", "*", "kwargs", ")", ":", "try", ":", "if", "relation_id", "in", "relation_ids", "(", "'cluster'", ")", ":", "return", "leader_set", "(", "settings", "=", "relation_settings", ",", "*", "*", "kwargs", ")", "else", ":", "raise", "NotImplementedError", "except", "NotImplementedError", ":", "return", "_relation_set", "(", "relation_id", "=", "relation_id", ",", "relation_settings", "=", "relation_settings", ",", "*", "*", "kwargs", ")" ]
Attempt to use leader-set if supported in the current version of Juju, otherwise falls back on relation-set. Note that we only attempt to use leader-set if the provided relation_id is a peer relation id or no relation id is provided (in which case we assume we are within the peer relation context).
[ "Attempt", "to", "use", "leader", "-", "set", "if", "supported", "in", "the", "current", "version", "of", "Juju", "otherwise", "falls", "back", "on", "relation", "-", "set", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/peerstorage/__init__.py#L125-L140
12,434
juju/charm-helpers
charmhelpers/contrib/peerstorage/__init__.py
relation_get
def relation_get(attribute=None, unit=None, rid=None): """Attempt to use leader-get if supported in the current version of Juju, otherwise falls back on relation-get. Note that we only attempt to use leader-get if the provided rid is a peer relation id or no relation id is provided (in which case we assume we are within the peer relation context). """ try: if rid in relation_ids('cluster'): return leader_get(attribute, rid) else: raise NotImplementedError except NotImplementedError: return _relation_get(attribute=attribute, rid=rid, unit=unit)
python
def relation_get(attribute=None, unit=None, rid=None): """Attempt to use leader-get if supported in the current version of Juju, otherwise falls back on relation-get. Note that we only attempt to use leader-get if the provided rid is a peer relation id or no relation id is provided (in which case we assume we are within the peer relation context). """ try: if rid in relation_ids('cluster'): return leader_get(attribute, rid) else: raise NotImplementedError except NotImplementedError: return _relation_get(attribute=attribute, rid=rid, unit=unit)
[ "def", "relation_get", "(", "attribute", "=", "None", ",", "unit", "=", "None", ",", "rid", "=", "None", ")", ":", "try", ":", "if", "rid", "in", "relation_ids", "(", "'cluster'", ")", ":", "return", "leader_get", "(", "attribute", ",", "rid", ")", "else", ":", "raise", "NotImplementedError", "except", "NotImplementedError", ":", "return", "_relation_get", "(", "attribute", "=", "attribute", ",", "rid", "=", "rid", ",", "unit", "=", "unit", ")" ]
Attempt to use leader-get if supported in the current version of Juju, otherwise falls back on relation-get. Note that we only attempt to use leader-get if the provided rid is a peer relation id or no relation id is provided (in which case we assume we are within the peer relation context).
[ "Attempt", "to", "use", "leader", "-", "get", "if", "supported", "in", "the", "current", "version", "of", "Juju", "otherwise", "falls", "back", "on", "relation", "-", "get", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/peerstorage/__init__.py#L143-L157
12,435
juju/charm-helpers
charmhelpers/contrib/peerstorage/__init__.py
peer_retrieve
def peer_retrieve(key, relation_name='cluster'): """Retrieve a named key from peer relation `relation_name`.""" cluster_rels = relation_ids(relation_name) if len(cluster_rels) > 0: cluster_rid = cluster_rels[0] return relation_get(attribute=key, rid=cluster_rid, unit=local_unit()) else: raise ValueError('Unable to detect' 'peer relation {}'.format(relation_name))
python
def peer_retrieve(key, relation_name='cluster'): """Retrieve a named key from peer relation `relation_name`.""" cluster_rels = relation_ids(relation_name) if len(cluster_rels) > 0: cluster_rid = cluster_rels[0] return relation_get(attribute=key, rid=cluster_rid, unit=local_unit()) else: raise ValueError('Unable to detect' 'peer relation {}'.format(relation_name))
[ "def", "peer_retrieve", "(", "key", ",", "relation_name", "=", "'cluster'", ")", ":", "cluster_rels", "=", "relation_ids", "(", "relation_name", ")", "if", "len", "(", "cluster_rels", ")", ">", "0", ":", "cluster_rid", "=", "cluster_rels", "[", "0", "]", "return", "relation_get", "(", "attribute", "=", "key", ",", "rid", "=", "cluster_rid", ",", "unit", "=", "local_unit", "(", ")", ")", "else", ":", "raise", "ValueError", "(", "'Unable to detect'", "'peer relation {}'", ".", "format", "(", "relation_name", ")", ")" ]
Retrieve a named key from peer relation `relation_name`.
[ "Retrieve", "a", "named", "key", "from", "peer", "relation", "relation_name", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/peerstorage/__init__.py#L160-L169
12,436
juju/charm-helpers
charmhelpers/contrib/peerstorage/__init__.py
peer_echo
def peer_echo(includes=None, force=False): """Echo filtered attributes back onto the same relation for storage. This is a requirement to use the peerstorage module - it needs to be called from the peer relation's changed hook. If Juju leader support exists this will be a noop unless force is True. """ try: is_leader() except NotImplementedError: pass else: if not force: return # NOOP if leader-election is supported # Use original non-leader calls relation_get = _relation_get relation_set = _relation_set rdata = relation_get() echo_data = {} if includes is None: echo_data = rdata.copy() for ex in ['private-address', 'public-address']: if ex in echo_data: echo_data.pop(ex) else: for attribute, value in six.iteritems(rdata): for include in includes: if include in attribute: echo_data[attribute] = value if len(echo_data) > 0: relation_set(relation_settings=echo_data)
python
def peer_echo(includes=None, force=False): """Echo filtered attributes back onto the same relation for storage. This is a requirement to use the peerstorage module - it needs to be called from the peer relation's changed hook. If Juju leader support exists this will be a noop unless force is True. """ try: is_leader() except NotImplementedError: pass else: if not force: return # NOOP if leader-election is supported # Use original non-leader calls relation_get = _relation_get relation_set = _relation_set rdata = relation_get() echo_data = {} if includes is None: echo_data = rdata.copy() for ex in ['private-address', 'public-address']: if ex in echo_data: echo_data.pop(ex) else: for attribute, value in six.iteritems(rdata): for include in includes: if include in attribute: echo_data[attribute] = value if len(echo_data) > 0: relation_set(relation_settings=echo_data)
[ "def", "peer_echo", "(", "includes", "=", "None", ",", "force", "=", "False", ")", ":", "try", ":", "is_leader", "(", ")", "except", "NotImplementedError", ":", "pass", "else", ":", "if", "not", "force", ":", "return", "# NOOP if leader-election is supported", "# Use original non-leader calls", "relation_get", "=", "_relation_get", "relation_set", "=", "_relation_set", "rdata", "=", "relation_get", "(", ")", "echo_data", "=", "{", "}", "if", "includes", "is", "None", ":", "echo_data", "=", "rdata", ".", "copy", "(", ")", "for", "ex", "in", "[", "'private-address'", ",", "'public-address'", "]", ":", "if", "ex", "in", "echo_data", ":", "echo_data", ".", "pop", "(", "ex", ")", "else", ":", "for", "attribute", ",", "value", "in", "six", ".", "iteritems", "(", "rdata", ")", ":", "for", "include", "in", "includes", ":", "if", "include", "in", "attribute", ":", "echo_data", "[", "attribute", "]", "=", "value", "if", "len", "(", "echo_data", ")", ">", "0", ":", "relation_set", "(", "relation_settings", "=", "echo_data", ")" ]
Echo filtered attributes back onto the same relation for storage. This is a requirement to use the peerstorage module - it needs to be called from the peer relation's changed hook. If Juju leader support exists this will be a noop unless force is True.
[ "Echo", "filtered", "attributes", "back", "onto", "the", "same", "relation", "for", "storage", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/peerstorage/__init__.py#L204-L237
12,437
juju/charm-helpers
charmhelpers/contrib/peerstorage/__init__.py
peer_store_and_set
def peer_store_and_set(relation_id=None, peer_relation_name='cluster', peer_store_fatal=False, relation_settings=None, delimiter='_', **kwargs): """Store passed-in arguments both in argument relation and in peer storage. It functions like doing relation_set() and peer_store() at the same time, with the same data. @param relation_id: the id of the relation to store the data on. Defaults to the current relation. @param peer_store_fatal: Set to True, the function will raise an exception should the peer sotrage not be avialable.""" relation_settings = relation_settings if relation_settings else {} relation_set(relation_id=relation_id, relation_settings=relation_settings, **kwargs) if is_relation_made(peer_relation_name): for key, value in six.iteritems(dict(list(kwargs.items()) + list(relation_settings.items()))): key_prefix = relation_id or current_relation_id() peer_store(key_prefix + delimiter + key, value, relation_name=peer_relation_name) else: if peer_store_fatal: raise ValueError('Unable to detect ' 'peer relation {}'.format(peer_relation_name))
python
def peer_store_and_set(relation_id=None, peer_relation_name='cluster', peer_store_fatal=False, relation_settings=None, delimiter='_', **kwargs): """Store passed-in arguments both in argument relation and in peer storage. It functions like doing relation_set() and peer_store() at the same time, with the same data. @param relation_id: the id of the relation to store the data on. Defaults to the current relation. @param peer_store_fatal: Set to True, the function will raise an exception should the peer sotrage not be avialable.""" relation_settings = relation_settings if relation_settings else {} relation_set(relation_id=relation_id, relation_settings=relation_settings, **kwargs) if is_relation_made(peer_relation_name): for key, value in six.iteritems(dict(list(kwargs.items()) + list(relation_settings.items()))): key_prefix = relation_id or current_relation_id() peer_store(key_prefix + delimiter + key, value, relation_name=peer_relation_name) else: if peer_store_fatal: raise ValueError('Unable to detect ' 'peer relation {}'.format(peer_relation_name))
[ "def", "peer_store_and_set", "(", "relation_id", "=", "None", ",", "peer_relation_name", "=", "'cluster'", ",", "peer_store_fatal", "=", "False", ",", "relation_settings", "=", "None", ",", "delimiter", "=", "'_'", ",", "*", "*", "kwargs", ")", ":", "relation_settings", "=", "relation_settings", "if", "relation_settings", "else", "{", "}", "relation_set", "(", "relation_id", "=", "relation_id", ",", "relation_settings", "=", "relation_settings", ",", "*", "*", "kwargs", ")", "if", "is_relation_made", "(", "peer_relation_name", ")", ":", "for", "key", ",", "value", "in", "six", ".", "iteritems", "(", "dict", "(", "list", "(", "kwargs", ".", "items", "(", ")", ")", "+", "list", "(", "relation_settings", ".", "items", "(", ")", ")", ")", ")", ":", "key_prefix", "=", "relation_id", "or", "current_relation_id", "(", ")", "peer_store", "(", "key_prefix", "+", "delimiter", "+", "key", ",", "value", ",", "relation_name", "=", "peer_relation_name", ")", "else", ":", "if", "peer_store_fatal", ":", "raise", "ValueError", "(", "'Unable to detect '", "'peer relation {}'", ".", "format", "(", "peer_relation_name", ")", ")" ]
Store passed-in arguments both in argument relation and in peer storage. It functions like doing relation_set() and peer_store() at the same time, with the same data. @param relation_id: the id of the relation to store the data on. Defaults to the current relation. @param peer_store_fatal: Set to True, the function will raise an exception should the peer sotrage not be avialable.
[ "Store", "passed", "-", "in", "arguments", "both", "in", "argument", "relation", "and", "in", "peer", "storage", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/peerstorage/__init__.py#L240-L267
12,438
juju/charm-helpers
charmhelpers/core/files.py
sed
def sed(filename, before, after, flags='g'): """ Search and replaces the given pattern on filename. :param filename: relative or absolute file path. :param before: expression to be replaced (see 'man sed') :param after: expression to replace with (see 'man sed') :param flags: sed-compatible regex flags in example, to make the search and replace case insensitive, specify ``flags="i"``. The ``g`` flag is always specified regardless, so you do not need to remember to include it when overriding this parameter. :returns: If the sed command exit code was zero then return, otherwise raise CalledProcessError. """ expression = r's/{0}/{1}/{2}'.format(before, after, flags) return subprocess.check_call(["sed", "-i", "-r", "-e", expression, os.path.expanduser(filename)])
python
def sed(filename, before, after, flags='g'): """ Search and replaces the given pattern on filename. :param filename: relative or absolute file path. :param before: expression to be replaced (see 'man sed') :param after: expression to replace with (see 'man sed') :param flags: sed-compatible regex flags in example, to make the search and replace case insensitive, specify ``flags="i"``. The ``g`` flag is always specified regardless, so you do not need to remember to include it when overriding this parameter. :returns: If the sed command exit code was zero then return, otherwise raise CalledProcessError. """ expression = r's/{0}/{1}/{2}'.format(before, after, flags) return subprocess.check_call(["sed", "-i", "-r", "-e", expression, os.path.expanduser(filename)])
[ "def", "sed", "(", "filename", ",", "before", ",", "after", ",", "flags", "=", "'g'", ")", ":", "expression", "=", "r's/{0}/{1}/{2}'", ".", "format", "(", "before", ",", "after", ",", "flags", ")", "return", "subprocess", ".", "check_call", "(", "[", "\"sed\"", ",", "\"-i\"", ",", "\"-r\"", ",", "\"-e\"", ",", "expression", ",", "os", ".", "path", ".", "expanduser", "(", "filename", ")", "]", ")" ]
Search and replaces the given pattern on filename. :param filename: relative or absolute file path. :param before: expression to be replaced (see 'man sed') :param after: expression to replace with (see 'man sed') :param flags: sed-compatible regex flags in example, to make the search and replace case insensitive, specify ``flags="i"``. The ``g`` flag is always specified regardless, so you do not need to remember to include it when overriding this parameter. :returns: If the sed command exit code was zero then return, otherwise raise CalledProcessError.
[ "Search", "and", "replaces", "the", "given", "pattern", "on", "filename", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/files.py#L24-L43
12,439
juju/charm-helpers
charmhelpers/contrib/hardening/ssh/checks/config.py
SSHConfigContext.get_listening
def get_listening(self, listen=['0.0.0.0']): """Returns a list of addresses SSH can list on Turns input into a sensible list of IPs SSH can listen on. Input must be a python list of interface names, IPs and/or CIDRs. :param listen: list of IPs, CIDRs, interface names :returns: list of IPs available on the host """ if listen == ['0.0.0.0']: return listen value = [] for network in listen: try: ip = get_address_in_network(network=network, fatal=True) except ValueError: if is_ip(network): ip = network else: try: ip = get_iface_addr(iface=network, fatal=False)[0] except IndexError: continue value.append(ip) if value == []: return ['0.0.0.0'] return value
python
def get_listening(self, listen=['0.0.0.0']): """Returns a list of addresses SSH can list on Turns input into a sensible list of IPs SSH can listen on. Input must be a python list of interface names, IPs and/or CIDRs. :param listen: list of IPs, CIDRs, interface names :returns: list of IPs available on the host """ if listen == ['0.0.0.0']: return listen value = [] for network in listen: try: ip = get_address_in_network(network=network, fatal=True) except ValueError: if is_ip(network): ip = network else: try: ip = get_iface_addr(iface=network, fatal=False)[0] except IndexError: continue value.append(ip) if value == []: return ['0.0.0.0'] return value
[ "def", "get_listening", "(", "self", ",", "listen", "=", "[", "'0.0.0.0'", "]", ")", ":", "if", "listen", "==", "[", "'0.0.0.0'", "]", ":", "return", "listen", "value", "=", "[", "]", "for", "network", "in", "listen", ":", "try", ":", "ip", "=", "get_address_in_network", "(", "network", "=", "network", ",", "fatal", "=", "True", ")", "except", "ValueError", ":", "if", "is_ip", "(", "network", ")", ":", "ip", "=", "network", "else", ":", "try", ":", "ip", "=", "get_iface_addr", "(", "iface", "=", "network", ",", "fatal", "=", "False", ")", "[", "0", "]", "except", "IndexError", ":", "continue", "value", ".", "append", "(", "ip", ")", "if", "value", "==", "[", "]", ":", "return", "[", "'0.0.0.0'", "]", "return", "value" ]
Returns a list of addresses SSH can list on Turns input into a sensible list of IPs SSH can listen on. Input must be a python list of interface names, IPs and/or CIDRs. :param listen: list of IPs, CIDRs, interface names :returns: list of IPs available on the host
[ "Returns", "a", "list", "of", "addresses", "SSH", "can", "list", "on" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/hardening/ssh/checks/config.py#L135-L163
12,440
juju/charm-helpers
charmhelpers/contrib/openstack/templating.py
get_loader
def get_loader(templates_dir, os_release): """ Create a jinja2.ChoiceLoader containing template dirs up to and including os_release. If directory template directory is missing at templates_dir, it will be omitted from the loader. templates_dir is added to the bottom of the search list as a base loading dir. A charm may also ship a templates dir with this module and it will be appended to the bottom of the search list, eg:: hooks/charmhelpers/contrib/openstack/templates :param templates_dir (str): Base template directory containing release sub-directories. :param os_release (str): OpenStack release codename to construct template loader. :returns: jinja2.ChoiceLoader constructed with a list of jinja2.FilesystemLoaders, ordered in descending order by OpenStack release. """ tmpl_dirs = [(rel, os.path.join(templates_dir, rel)) for rel in six.itervalues(OPENSTACK_CODENAMES)] if not os.path.isdir(templates_dir): log('Templates directory not found @ %s.' % templates_dir, level=ERROR) raise OSConfigException # the bottom contains tempaltes_dir and possibly a common templates dir # shipped with the helper. loaders = [FileSystemLoader(templates_dir)] helper_templates = os.path.join(os.path.dirname(__file__), 'templates') if os.path.isdir(helper_templates): loaders.append(FileSystemLoader(helper_templates)) for rel, tmpl_dir in tmpl_dirs: if os.path.isdir(tmpl_dir): loaders.insert(0, FileSystemLoader(tmpl_dir)) if rel == os_release: break # demote this log to the lowest level; we don't really need to see these # lots in production even when debugging. log('Creating choice loader with dirs: %s' % [l.searchpath for l in loaders], level=TRACE) return ChoiceLoader(loaders)
python
def get_loader(templates_dir, os_release): """ Create a jinja2.ChoiceLoader containing template dirs up to and including os_release. If directory template directory is missing at templates_dir, it will be omitted from the loader. templates_dir is added to the bottom of the search list as a base loading dir. A charm may also ship a templates dir with this module and it will be appended to the bottom of the search list, eg:: hooks/charmhelpers/contrib/openstack/templates :param templates_dir (str): Base template directory containing release sub-directories. :param os_release (str): OpenStack release codename to construct template loader. :returns: jinja2.ChoiceLoader constructed with a list of jinja2.FilesystemLoaders, ordered in descending order by OpenStack release. """ tmpl_dirs = [(rel, os.path.join(templates_dir, rel)) for rel in six.itervalues(OPENSTACK_CODENAMES)] if not os.path.isdir(templates_dir): log('Templates directory not found @ %s.' % templates_dir, level=ERROR) raise OSConfigException # the bottom contains tempaltes_dir and possibly a common templates dir # shipped with the helper. loaders = [FileSystemLoader(templates_dir)] helper_templates = os.path.join(os.path.dirname(__file__), 'templates') if os.path.isdir(helper_templates): loaders.append(FileSystemLoader(helper_templates)) for rel, tmpl_dir in tmpl_dirs: if os.path.isdir(tmpl_dir): loaders.insert(0, FileSystemLoader(tmpl_dir)) if rel == os_release: break # demote this log to the lowest level; we don't really need to see these # lots in production even when debugging. log('Creating choice loader with dirs: %s' % [l.searchpath for l in loaders], level=TRACE) return ChoiceLoader(loaders)
[ "def", "get_loader", "(", "templates_dir", ",", "os_release", ")", ":", "tmpl_dirs", "=", "[", "(", "rel", ",", "os", ".", "path", ".", "join", "(", "templates_dir", ",", "rel", ")", ")", "for", "rel", "in", "six", ".", "itervalues", "(", "OPENSTACK_CODENAMES", ")", "]", "if", "not", "os", ".", "path", ".", "isdir", "(", "templates_dir", ")", ":", "log", "(", "'Templates directory not found @ %s.'", "%", "templates_dir", ",", "level", "=", "ERROR", ")", "raise", "OSConfigException", "# the bottom contains tempaltes_dir and possibly a common templates dir", "# shipped with the helper.", "loaders", "=", "[", "FileSystemLoader", "(", "templates_dir", ")", "]", "helper_templates", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "'templates'", ")", "if", "os", ".", "path", ".", "isdir", "(", "helper_templates", ")", ":", "loaders", ".", "append", "(", "FileSystemLoader", "(", "helper_templates", ")", ")", "for", "rel", ",", "tmpl_dir", "in", "tmpl_dirs", ":", "if", "os", ".", "path", ".", "isdir", "(", "tmpl_dir", ")", ":", "loaders", ".", "insert", "(", "0", ",", "FileSystemLoader", "(", "tmpl_dir", ")", ")", "if", "rel", "==", "os_release", ":", "break", "# demote this log to the lowest level; we don't really need to see these", "# lots in production even when debugging.", "log", "(", "'Creating choice loader with dirs: %s'", "%", "[", "l", ".", "searchpath", "for", "l", "in", "loaders", "]", ",", "level", "=", "TRACE", ")", "return", "ChoiceLoader", "(", "loaders", ")" ]
Create a jinja2.ChoiceLoader containing template dirs up to and including os_release. If directory template directory is missing at templates_dir, it will be omitted from the loader. templates_dir is added to the bottom of the search list as a base loading dir. A charm may also ship a templates dir with this module and it will be appended to the bottom of the search list, eg:: hooks/charmhelpers/contrib/openstack/templates :param templates_dir (str): Base template directory containing release sub-directories. :param os_release (str): OpenStack release codename to construct template loader. :returns: jinja2.ChoiceLoader constructed with a list of jinja2.FilesystemLoaders, ordered in descending order by OpenStack release.
[ "Create", "a", "jinja2", ".", "ChoiceLoader", "containing", "template", "dirs", "up", "to", "and", "including", "os_release", ".", "If", "directory", "template", "directory", "is", "missing", "at", "templates_dir", "it", "will", "be", "omitted", "from", "the", "loader", ".", "templates_dir", "is", "added", "to", "the", "bottom", "of", "the", "search", "list", "as", "a", "base", "loading", "dir", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/templating.py#L43-L88
12,441
juju/charm-helpers
charmhelpers/contrib/openstack/templating.py
OSConfigTemplate.complete_contexts
def complete_contexts(self): ''' Return a list of interfaces that have satisfied contexts. ''' if self._complete_contexts: return self._complete_contexts self.context() return self._complete_contexts
python
def complete_contexts(self): ''' Return a list of interfaces that have satisfied contexts. ''' if self._complete_contexts: return self._complete_contexts self.context() return self._complete_contexts
[ "def", "complete_contexts", "(", "self", ")", ":", "if", "self", ".", "_complete_contexts", ":", "return", "self", ".", "_complete_contexts", "self", ".", "context", "(", ")", "return", "self", ".", "_complete_contexts" ]
Return a list of interfaces that have satisfied contexts.
[ "Return", "a", "list", "of", "interfaces", "that", "have", "satisfied", "contexts", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/templating.py#L121-L128
12,442
juju/charm-helpers
charmhelpers/contrib/openstack/templating.py
OSConfigRenderer.write
def write(self, config_file): """ Write a single config file, raises if config file is not registered. """ if config_file not in self.templates: log('Config not registered: %s' % config_file, level=ERROR) raise OSConfigException _out = self.render(config_file) if six.PY3: _out = _out.encode('UTF-8') with open(config_file, 'wb') as out: out.write(_out) log('Wrote template %s.' % config_file, level=INFO)
python
def write(self, config_file): """ Write a single config file, raises if config file is not registered. """ if config_file not in self.templates: log('Config not registered: %s' % config_file, level=ERROR) raise OSConfigException _out = self.render(config_file) if six.PY3: _out = _out.encode('UTF-8') with open(config_file, 'wb') as out: out.write(_out) log('Wrote template %s.' % config_file, level=INFO)
[ "def", "write", "(", "self", ",", "config_file", ")", ":", "if", "config_file", "not", "in", "self", ".", "templates", ":", "log", "(", "'Config not registered: %s'", "%", "config_file", ",", "level", "=", "ERROR", ")", "raise", "OSConfigException", "_out", "=", "self", ".", "render", "(", "config_file", ")", "if", "six", ".", "PY3", ":", "_out", "=", "_out", ".", "encode", "(", "'UTF-8'", ")", "with", "open", "(", "config_file", ",", "'wb'", ")", "as", "out", ":", "out", ".", "write", "(", "_out", ")", "log", "(", "'Wrote template %s.'", "%", "config_file", ",", "level", "=", "INFO", ")" ]
Write a single config file, raises if config file is not registered.
[ "Write", "a", "single", "config", "file", "raises", "if", "config", "file", "is", "not", "registered", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/templating.py#L313-L328
12,443
juju/charm-helpers
charmhelpers/contrib/openstack/templating.py
OSConfigRenderer.write_all
def write_all(self): """ Write out all registered config files. """ [self.write(k) for k in six.iterkeys(self.templates)]
python
def write_all(self): """ Write out all registered config files. """ [self.write(k) for k in six.iterkeys(self.templates)]
[ "def", "write_all", "(", "self", ")", ":", "[", "self", ".", "write", "(", "k", ")", "for", "k", "in", "six", ".", "iterkeys", "(", "self", ".", "templates", ")", "]" ]
Write out all registered config files.
[ "Write", "out", "all", "registered", "config", "files", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/templating.py#L330-L334
12,444
juju/charm-helpers
charmhelpers/contrib/openstack/templating.py
OSConfigRenderer.set_release
def set_release(self, openstack_release): """ Resets the template environment and generates a new template loader based on a the new openstack release. """ self._tmpl_env = None self.openstack_release = openstack_release self._get_tmpl_env()
python
def set_release(self, openstack_release): """ Resets the template environment and generates a new template loader based on a the new openstack release. """ self._tmpl_env = None self.openstack_release = openstack_release self._get_tmpl_env()
[ "def", "set_release", "(", "self", ",", "openstack_release", ")", ":", "self", ".", "_tmpl_env", "=", "None", "self", ".", "openstack_release", "=", "openstack_release", "self", ".", "_get_tmpl_env", "(", ")" ]
Resets the template environment and generates a new template loader based on a the new openstack release.
[ "Resets", "the", "template", "environment", "and", "generates", "a", "new", "template", "loader", "based", "on", "a", "the", "new", "openstack", "release", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/templating.py#L336-L343
12,445
juju/charm-helpers
charmhelpers/contrib/openstack/templating.py
OSConfigRenderer.complete_contexts
def complete_contexts(self): ''' Returns a list of context interfaces that yield a complete context. ''' interfaces = [] [interfaces.extend(i.complete_contexts()) for i in six.itervalues(self.templates)] return interfaces
python
def complete_contexts(self): ''' Returns a list of context interfaces that yield a complete context. ''' interfaces = [] [interfaces.extend(i.complete_contexts()) for i in six.itervalues(self.templates)] return interfaces
[ "def", "complete_contexts", "(", "self", ")", ":", "interfaces", "=", "[", "]", "[", "interfaces", ".", "extend", "(", "i", ".", "complete_contexts", "(", ")", ")", "for", "i", "in", "six", ".", "itervalues", "(", "self", ".", "templates", ")", "]", "return", "interfaces" ]
Returns a list of context interfaces that yield a complete context.
[ "Returns", "a", "list", "of", "context", "interfaces", "that", "yield", "a", "complete", "context", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/templating.py#L345-L352
12,446
juju/charm-helpers
charmhelpers/contrib/hahelpers/cluster.py
is_elected_leader
def is_elected_leader(resource): """ Returns True if the charm executing this is the elected cluster leader. It relies on two mechanisms to determine leadership: 1. If juju is sufficiently new and leadership election is supported, the is_leader command will be used. 2. If the charm is part of a corosync cluster, call corosync to determine leadership. 3. If the charm is not part of a corosync cluster, the leader is determined as being "the alive unit with the lowest unit numer". In other words, the oldest surviving unit. """ try: return juju_is_leader() except NotImplementedError: log('Juju leadership election feature not enabled' ', using fallback support', level=WARNING) if is_clustered(): if not is_crm_leader(resource): log('Deferring action to CRM leader.', level=INFO) return False else: peers = peer_units() if peers and not oldest_peer(peers): log('Deferring action to oldest service unit.', level=INFO) return False return True
python
def is_elected_leader(resource): """ Returns True if the charm executing this is the elected cluster leader. It relies on two mechanisms to determine leadership: 1. If juju is sufficiently new and leadership election is supported, the is_leader command will be used. 2. If the charm is part of a corosync cluster, call corosync to determine leadership. 3. If the charm is not part of a corosync cluster, the leader is determined as being "the alive unit with the lowest unit numer". In other words, the oldest surviving unit. """ try: return juju_is_leader() except NotImplementedError: log('Juju leadership election feature not enabled' ', using fallback support', level=WARNING) if is_clustered(): if not is_crm_leader(resource): log('Deferring action to CRM leader.', level=INFO) return False else: peers = peer_units() if peers and not oldest_peer(peers): log('Deferring action to oldest service unit.', level=INFO) return False return True
[ "def", "is_elected_leader", "(", "resource", ")", ":", "try", ":", "return", "juju_is_leader", "(", ")", "except", "NotImplementedError", ":", "log", "(", "'Juju leadership election feature not enabled'", "', using fallback support'", ",", "level", "=", "WARNING", ")", "if", "is_clustered", "(", ")", ":", "if", "not", "is_crm_leader", "(", "resource", ")", ":", "log", "(", "'Deferring action to CRM leader.'", ",", "level", "=", "INFO", ")", "return", "False", "else", ":", "peers", "=", "peer_units", "(", ")", "if", "peers", "and", "not", "oldest_peer", "(", "peers", ")", ":", "log", "(", "'Deferring action to oldest service unit.'", ",", "level", "=", "INFO", ")", "return", "False", "return", "True" ]
Returns True if the charm executing this is the elected cluster leader. It relies on two mechanisms to determine leadership: 1. If juju is sufficiently new and leadership election is supported, the is_leader command will be used. 2. If the charm is part of a corosync cluster, call corosync to determine leadership. 3. If the charm is not part of a corosync cluster, the leader is determined as being "the alive unit with the lowest unit numer". In other words, the oldest surviving unit.
[ "Returns", "True", "if", "the", "charm", "executing", "this", "is", "the", "elected", "cluster", "leader", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/hahelpers/cluster.py#L78-L107
12,447
juju/charm-helpers
charmhelpers/contrib/hahelpers/cluster.py
is_crm_dc
def is_crm_dc(): """ Determine leadership by querying the pacemaker Designated Controller """ cmd = ['crm', 'status'] try: status = subprocess.check_output(cmd, stderr=subprocess.STDOUT) if not isinstance(status, six.text_type): status = six.text_type(status, "utf-8") except subprocess.CalledProcessError as ex: raise CRMDCNotFound(str(ex)) current_dc = '' for line in status.split('\n'): if line.startswith('Current DC'): # Current DC: juju-lytrusty-machine-2 (168108163) - partition with quorum current_dc = line.split(':')[1].split()[0] if current_dc == get_unit_hostname(): return True elif current_dc == 'NONE': raise CRMDCNotFound('Current DC: NONE') return False
python
def is_crm_dc(): """ Determine leadership by querying the pacemaker Designated Controller """ cmd = ['crm', 'status'] try: status = subprocess.check_output(cmd, stderr=subprocess.STDOUT) if not isinstance(status, six.text_type): status = six.text_type(status, "utf-8") except subprocess.CalledProcessError as ex: raise CRMDCNotFound(str(ex)) current_dc = '' for line in status.split('\n'): if line.startswith('Current DC'): # Current DC: juju-lytrusty-machine-2 (168108163) - partition with quorum current_dc = line.split(':')[1].split()[0] if current_dc == get_unit_hostname(): return True elif current_dc == 'NONE': raise CRMDCNotFound('Current DC: NONE') return False
[ "def", "is_crm_dc", "(", ")", ":", "cmd", "=", "[", "'crm'", ",", "'status'", "]", "try", ":", "status", "=", "subprocess", ".", "check_output", "(", "cmd", ",", "stderr", "=", "subprocess", ".", "STDOUT", ")", "if", "not", "isinstance", "(", "status", ",", "six", ".", "text_type", ")", ":", "status", "=", "six", ".", "text_type", "(", "status", ",", "\"utf-8\"", ")", "except", "subprocess", ".", "CalledProcessError", "as", "ex", ":", "raise", "CRMDCNotFound", "(", "str", "(", "ex", ")", ")", "current_dc", "=", "''", "for", "line", "in", "status", ".", "split", "(", "'\\n'", ")", ":", "if", "line", ".", "startswith", "(", "'Current DC'", ")", ":", "# Current DC: juju-lytrusty-machine-2 (168108163) - partition with quorum", "current_dc", "=", "line", ".", "split", "(", "':'", ")", "[", "1", "]", ".", "split", "(", ")", "[", "0", "]", "if", "current_dc", "==", "get_unit_hostname", "(", ")", ":", "return", "True", "elif", "current_dc", "==", "'NONE'", ":", "raise", "CRMDCNotFound", "(", "'Current DC: NONE'", ")", "return", "False" ]
Determine leadership by querying the pacemaker Designated Controller
[ "Determine", "leadership", "by", "querying", "the", "pacemaker", "Designated", "Controller" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/hahelpers/cluster.py#L121-L143
12,448
juju/charm-helpers
charmhelpers/contrib/hahelpers/cluster.py
is_crm_leader
def is_crm_leader(resource, retry=False): """ Returns True if the charm calling this is the elected corosync leader, as returned by calling the external "crm" command. We allow this operation to be retried to avoid the possibility of getting a false negative. See LP #1396246 for more info. """ if resource == DC_RESOURCE_NAME: return is_crm_dc() cmd = ['crm', 'resource', 'show', resource] try: status = subprocess.check_output(cmd, stderr=subprocess.STDOUT) if not isinstance(status, six.text_type): status = six.text_type(status, "utf-8") except subprocess.CalledProcessError: status = None if status and get_unit_hostname() in status: return True if status and "resource %s is NOT running" % (resource) in status: raise CRMResourceNotFound("CRM resource %s not found" % (resource)) return False
python
def is_crm_leader(resource, retry=False): """ Returns True if the charm calling this is the elected corosync leader, as returned by calling the external "crm" command. We allow this operation to be retried to avoid the possibility of getting a false negative. See LP #1396246 for more info. """ if resource == DC_RESOURCE_NAME: return is_crm_dc() cmd = ['crm', 'resource', 'show', resource] try: status = subprocess.check_output(cmd, stderr=subprocess.STDOUT) if not isinstance(status, six.text_type): status = six.text_type(status, "utf-8") except subprocess.CalledProcessError: status = None if status and get_unit_hostname() in status: return True if status and "resource %s is NOT running" % (resource) in status: raise CRMResourceNotFound("CRM resource %s not found" % (resource)) return False
[ "def", "is_crm_leader", "(", "resource", ",", "retry", "=", "False", ")", ":", "if", "resource", "==", "DC_RESOURCE_NAME", ":", "return", "is_crm_dc", "(", ")", "cmd", "=", "[", "'crm'", ",", "'resource'", ",", "'show'", ",", "resource", "]", "try", ":", "status", "=", "subprocess", ".", "check_output", "(", "cmd", ",", "stderr", "=", "subprocess", ".", "STDOUT", ")", "if", "not", "isinstance", "(", "status", ",", "six", ".", "text_type", ")", ":", "status", "=", "six", ".", "text_type", "(", "status", ",", "\"utf-8\"", ")", "except", "subprocess", ".", "CalledProcessError", ":", "status", "=", "None", "if", "status", "and", "get_unit_hostname", "(", ")", "in", "status", ":", "return", "True", "if", "status", "and", "\"resource %s is NOT running\"", "%", "(", "resource", ")", "in", "status", ":", "raise", "CRMResourceNotFound", "(", "\"CRM resource %s not found\"", "%", "(", "resource", ")", ")", "return", "False" ]
Returns True if the charm calling this is the elected corosync leader, as returned by calling the external "crm" command. We allow this operation to be retried to avoid the possibility of getting a false negative. See LP #1396246 for more info.
[ "Returns", "True", "if", "the", "charm", "calling", "this", "is", "the", "elected", "corosync", "leader", "as", "returned", "by", "calling", "the", "external", "crm", "command", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/hahelpers/cluster.py#L148-L172
12,449
juju/charm-helpers
charmhelpers/contrib/hahelpers/cluster.py
peer_ips
def peer_ips(peer_relation='cluster', addr_key='private-address'): '''Return a dict of peers and their private-address''' peers = {} for r_id in relation_ids(peer_relation): for unit in relation_list(r_id): peers[unit] = relation_get(addr_key, rid=r_id, unit=unit) return peers
python
def peer_ips(peer_relation='cluster', addr_key='private-address'): '''Return a dict of peers and their private-address''' peers = {} for r_id in relation_ids(peer_relation): for unit in relation_list(r_id): peers[unit] = relation_get(addr_key, rid=r_id, unit=unit) return peers
[ "def", "peer_ips", "(", "peer_relation", "=", "'cluster'", ",", "addr_key", "=", "'private-address'", ")", ":", "peers", "=", "{", "}", "for", "r_id", "in", "relation_ids", "(", "peer_relation", ")", ":", "for", "unit", "in", "relation_list", "(", "r_id", ")", ":", "peers", "[", "unit", "]", "=", "relation_get", "(", "addr_key", ",", "rid", "=", "r_id", ",", "unit", "=", "unit", ")", "return", "peers" ]
Return a dict of peers and their private-address
[ "Return", "a", "dict", "of", "peers", "and", "their", "private", "-", "address" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/hahelpers/cluster.py#L189-L195
12,450
juju/charm-helpers
charmhelpers/contrib/hahelpers/cluster.py
oldest_peer
def oldest_peer(peers): """Determines who the oldest peer is by comparing unit numbers.""" local_unit_no = int(os.getenv('JUJU_UNIT_NAME').split('/')[1]) for peer in peers: remote_unit_no = int(peer.split('/')[1]) if remote_unit_no < local_unit_no: return False return True
python
def oldest_peer(peers): """Determines who the oldest peer is by comparing unit numbers.""" local_unit_no = int(os.getenv('JUJU_UNIT_NAME').split('/')[1]) for peer in peers: remote_unit_no = int(peer.split('/')[1]) if remote_unit_no < local_unit_no: return False return True
[ "def", "oldest_peer", "(", "peers", ")", ":", "local_unit_no", "=", "int", "(", "os", ".", "getenv", "(", "'JUJU_UNIT_NAME'", ")", ".", "split", "(", "'/'", ")", "[", "1", "]", ")", "for", "peer", "in", "peers", ":", "remote_unit_no", "=", "int", "(", "peer", ".", "split", "(", "'/'", ")", "[", "1", "]", ")", "if", "remote_unit_no", "<", "local_unit_no", ":", "return", "False", "return", "True" ]
Determines who the oldest peer is by comparing unit numbers.
[ "Determines", "who", "the", "oldest", "peer", "is", "by", "comparing", "unit", "numbers", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/hahelpers/cluster.py#L198-L205
12,451
juju/charm-helpers
charmhelpers/contrib/hahelpers/cluster.py
canonical_url
def canonical_url(configs, vip_setting='vip'): ''' Returns the correct HTTP URL to this host given the state of HTTPS configuration and hacluster. :configs : OSTemplateRenderer: A config tempating object to inspect for a complete https context. :vip_setting: str: Setting in charm config that specifies VIP address. ''' scheme = 'http' if 'https' in configs.complete_contexts(): scheme = 'https' if is_clustered(): addr = config_get(vip_setting) else: addr = unit_get('private-address') return '%s://%s' % (scheme, addr)
python
def canonical_url(configs, vip_setting='vip'): ''' Returns the correct HTTP URL to this host given the state of HTTPS configuration and hacluster. :configs : OSTemplateRenderer: A config tempating object to inspect for a complete https context. :vip_setting: str: Setting in charm config that specifies VIP address. ''' scheme = 'http' if 'https' in configs.complete_contexts(): scheme = 'https' if is_clustered(): addr = config_get(vip_setting) else: addr = unit_get('private-address') return '%s://%s' % (scheme, addr)
[ "def", "canonical_url", "(", "configs", ",", "vip_setting", "=", "'vip'", ")", ":", "scheme", "=", "'http'", "if", "'https'", "in", "configs", ".", "complete_contexts", "(", ")", ":", "scheme", "=", "'https'", "if", "is_clustered", "(", ")", ":", "addr", "=", "config_get", "(", "vip_setting", ")", "else", ":", "addr", "=", "unit_get", "(", "'private-address'", ")", "return", "'%s://%s'", "%", "(", "scheme", ",", "addr", ")" ]
Returns the correct HTTP URL to this host given the state of HTTPS configuration and hacluster. :configs : OSTemplateRenderer: A config tempating object to inspect for a complete https context. :vip_setting: str: Setting in charm config that specifies VIP address.
[ "Returns", "the", "correct", "HTTP", "URL", "to", "this", "host", "given", "the", "state", "of", "HTTPS", "configuration", "and", "hacluster", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/hahelpers/cluster.py#L354-L372
12,452
juju/charm-helpers
charmhelpers/contrib/hahelpers/cluster.py
distributed_wait
def distributed_wait(modulo=None, wait=None, operation_name='operation'): ''' Distribute operations by waiting based on modulo_distribution If modulo and or wait are not set, check config_get for those values. If config values are not set, default to modulo=3 and wait=30. :param modulo: int The modulo number creates the group distribution :param wait: int The constant time wait value :param operation_name: string Operation name for status message i.e. 'restart' :side effect: Calls config_get() :side effect: Calls log() :side effect: Calls status_set() :side effect: Calls time.sleep() ''' if modulo is None: modulo = config_get('modulo-nodes') or 3 if wait is None: wait = config_get('known-wait') or 30 if juju_is_leader(): # The leader should never wait calculated_wait = 0 else: # non_zero_wait=True guarantees the non-leader who gets modulo 0 # will still wait calculated_wait = modulo_distribution(modulo=modulo, wait=wait, non_zero_wait=True) msg = "Waiting {} seconds for {} ...".format(calculated_wait, operation_name) log(msg, DEBUG) status_set('maintenance', msg) time.sleep(calculated_wait)
python
def distributed_wait(modulo=None, wait=None, operation_name='operation'): ''' Distribute operations by waiting based on modulo_distribution If modulo and or wait are not set, check config_get for those values. If config values are not set, default to modulo=3 and wait=30. :param modulo: int The modulo number creates the group distribution :param wait: int The constant time wait value :param operation_name: string Operation name for status message i.e. 'restart' :side effect: Calls config_get() :side effect: Calls log() :side effect: Calls status_set() :side effect: Calls time.sleep() ''' if modulo is None: modulo = config_get('modulo-nodes') or 3 if wait is None: wait = config_get('known-wait') or 30 if juju_is_leader(): # The leader should never wait calculated_wait = 0 else: # non_zero_wait=True guarantees the non-leader who gets modulo 0 # will still wait calculated_wait = modulo_distribution(modulo=modulo, wait=wait, non_zero_wait=True) msg = "Waiting {} seconds for {} ...".format(calculated_wait, operation_name) log(msg, DEBUG) status_set('maintenance', msg) time.sleep(calculated_wait)
[ "def", "distributed_wait", "(", "modulo", "=", "None", ",", "wait", "=", "None", ",", "operation_name", "=", "'operation'", ")", ":", "if", "modulo", "is", "None", ":", "modulo", "=", "config_get", "(", "'modulo-nodes'", ")", "or", "3", "if", "wait", "is", "None", ":", "wait", "=", "config_get", "(", "'known-wait'", ")", "or", "30", "if", "juju_is_leader", "(", ")", ":", "# The leader should never wait", "calculated_wait", "=", "0", "else", ":", "# non_zero_wait=True guarantees the non-leader who gets modulo 0", "# will still wait", "calculated_wait", "=", "modulo_distribution", "(", "modulo", "=", "modulo", ",", "wait", "=", "wait", ",", "non_zero_wait", "=", "True", ")", "msg", "=", "\"Waiting {} seconds for {} ...\"", ".", "format", "(", "calculated_wait", ",", "operation_name", ")", "log", "(", "msg", ",", "DEBUG", ")", "status_set", "(", "'maintenance'", ",", "msg", ")", "time", ".", "sleep", "(", "calculated_wait", ")" ]
Distribute operations by waiting based on modulo_distribution If modulo and or wait are not set, check config_get for those values. If config values are not set, default to modulo=3 and wait=30. :param modulo: int The modulo number creates the group distribution :param wait: int The constant time wait value :param operation_name: string Operation name for status message i.e. 'restart' :side effect: Calls config_get() :side effect: Calls log() :side effect: Calls status_set() :side effect: Calls time.sleep()
[ "Distribute", "operations", "by", "waiting", "based", "on", "modulo_distribution" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/hahelpers/cluster.py#L375-L406
12,453
juju/charm-helpers
charmhelpers/fetch/centos.py
update
def update(fatal=False): """Update local yum cache.""" cmd = ['yum', '--assumeyes', 'update'] log("Update with fatal: {}".format(fatal)) _run_yum_command(cmd, fatal)
python
def update(fatal=False): """Update local yum cache.""" cmd = ['yum', '--assumeyes', 'update'] log("Update with fatal: {}".format(fatal)) _run_yum_command(cmd, fatal)
[ "def", "update", "(", "fatal", "=", "False", ")", ":", "cmd", "=", "[", "'yum'", ",", "'--assumeyes'", ",", "'update'", "]", "log", "(", "\"Update with fatal: {}\"", ".", "format", "(", "fatal", ")", ")", "_run_yum_command", "(", "cmd", ",", "fatal", ")" ]
Update local yum cache.
[ "Update", "local", "yum", "cache", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/fetch/centos.py#L64-L68
12,454
juju/charm-helpers
charmhelpers/fetch/centos.py
yum_search
def yum_search(packages): """Search for a package.""" output = {} cmd = ['yum', 'search'] if isinstance(packages, six.string_types): cmd.append(packages) else: cmd.extend(packages) log("Searching for {}".format(packages)) result = subprocess.check_output(cmd) for package in list(packages): output[package] = package in result return output
python
def yum_search(packages): """Search for a package.""" output = {} cmd = ['yum', 'search'] if isinstance(packages, six.string_types): cmd.append(packages) else: cmd.extend(packages) log("Searching for {}".format(packages)) result = subprocess.check_output(cmd) for package in list(packages): output[package] = package in result return output
[ "def", "yum_search", "(", "packages", ")", ":", "output", "=", "{", "}", "cmd", "=", "[", "'yum'", ",", "'search'", "]", "if", "isinstance", "(", "packages", ",", "six", ".", "string_types", ")", ":", "cmd", ".", "append", "(", "packages", ")", "else", ":", "cmd", ".", "extend", "(", "packages", ")", "log", "(", "\"Searching for {}\"", ".", "format", "(", "packages", ")", ")", "result", "=", "subprocess", ".", "check_output", "(", "cmd", ")", "for", "package", "in", "list", "(", "packages", ")", ":", "output", "[", "package", "]", "=", "package", "in", "result", "return", "output" ]
Search for a package.
[ "Search", "for", "a", "package", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/fetch/centos.py#L82-L94
12,455
juju/charm-helpers
charmhelpers/fetch/centos.py
_run_yum_command
def _run_yum_command(cmd, fatal=False): """Run an YUM command. Checks the output and retry if the fatal flag is set to True. :param: cmd: str: The yum command to run. :param: fatal: bool: Whether the command's output should be checked and retried. """ env = os.environ.copy() if fatal: retry_count = 0 result = None # If the command is considered "fatal", we need to retry if the yum # lock was not acquired. while result is None or result == YUM_NO_LOCK: try: result = subprocess.check_call(cmd, env=env) except subprocess.CalledProcessError as e: retry_count = retry_count + 1 if retry_count > YUM_NO_LOCK_RETRY_COUNT: raise result = e.returncode log("Couldn't acquire YUM lock. Will retry in {} seconds." "".format(YUM_NO_LOCK_RETRY_DELAY)) time.sleep(YUM_NO_LOCK_RETRY_DELAY) else: subprocess.call(cmd, env=env)
python
def _run_yum_command(cmd, fatal=False): """Run an YUM command. Checks the output and retry if the fatal flag is set to True. :param: cmd: str: The yum command to run. :param: fatal: bool: Whether the command's output should be checked and retried. """ env = os.environ.copy() if fatal: retry_count = 0 result = None # If the command is considered "fatal", we need to retry if the yum # lock was not acquired. while result is None or result == YUM_NO_LOCK: try: result = subprocess.check_call(cmd, env=env) except subprocess.CalledProcessError as e: retry_count = retry_count + 1 if retry_count > YUM_NO_LOCK_RETRY_COUNT: raise result = e.returncode log("Couldn't acquire YUM lock. Will retry in {} seconds." "".format(YUM_NO_LOCK_RETRY_DELAY)) time.sleep(YUM_NO_LOCK_RETRY_DELAY) else: subprocess.call(cmd, env=env)
[ "def", "_run_yum_command", "(", "cmd", ",", "fatal", "=", "False", ")", ":", "env", "=", "os", ".", "environ", ".", "copy", "(", ")", "if", "fatal", ":", "retry_count", "=", "0", "result", "=", "None", "# If the command is considered \"fatal\", we need to retry if the yum", "# lock was not acquired.", "while", "result", "is", "None", "or", "result", "==", "YUM_NO_LOCK", ":", "try", ":", "result", "=", "subprocess", ".", "check_call", "(", "cmd", ",", "env", "=", "env", ")", "except", "subprocess", ".", "CalledProcessError", "as", "e", ":", "retry_count", "=", "retry_count", "+", "1", "if", "retry_count", ">", "YUM_NO_LOCK_RETRY_COUNT", ":", "raise", "result", "=", "e", ".", "returncode", "log", "(", "\"Couldn't acquire YUM lock. Will retry in {} seconds.\"", "\"\"", ".", "format", "(", "YUM_NO_LOCK_RETRY_DELAY", ")", ")", "time", ".", "sleep", "(", "YUM_NO_LOCK_RETRY_DELAY", ")", "else", ":", "subprocess", ".", "call", "(", "cmd", ",", "env", "=", "env", ")" ]
Run an YUM command. Checks the output and retry if the fatal flag is set to True. :param: cmd: str: The yum command to run. :param: fatal: bool: Whether the command's output should be checked and retried.
[ "Run", "an", "YUM", "command", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/fetch/centos.py#L140-L171
12,456
juju/charm-helpers
charmhelpers/cli/__init__.py
OutputFormatter.py
def py(self, output): """Output data as a nicely-formatted python data structure""" import pprint pprint.pprint(output, stream=self.outfile)
python
def py(self, output): """Output data as a nicely-formatted python data structure""" import pprint pprint.pprint(output, stream=self.outfile)
[ "def", "py", "(", "self", ",", "output", ")", ":", "import", "pprint", "pprint", ".", "pprint", "(", "output", ",", "stream", "=", "self", ".", "outfile", ")" ]
Output data as a nicely-formatted python data structure
[ "Output", "data", "as", "a", "nicely", "-", "formatted", "python", "data", "structure" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/cli/__init__.py#L60-L63
12,457
juju/charm-helpers
charmhelpers/cli/__init__.py
OutputFormatter.csv
def csv(self, output): """Output data as excel-compatible CSV""" import csv csvwriter = csv.writer(self.outfile) csvwriter.writerows(output)
python
def csv(self, output): """Output data as excel-compatible CSV""" import csv csvwriter = csv.writer(self.outfile) csvwriter.writerows(output)
[ "def", "csv", "(", "self", ",", "output", ")", ":", "import", "csv", "csvwriter", "=", "csv", ".", "writer", "(", "self", ".", "outfile", ")", "csvwriter", ".", "writerows", "(", "output", ")" ]
Output data as excel-compatible CSV
[ "Output", "data", "as", "excel", "-", "compatible", "CSV" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/cli/__init__.py#L75-L79
12,458
juju/charm-helpers
charmhelpers/cli/__init__.py
OutputFormatter.tab
def tab(self, output): """Output data in excel-compatible tab-delimited format""" import csv csvwriter = csv.writer(self.outfile, dialect=csv.excel_tab) csvwriter.writerows(output)
python
def tab(self, output): """Output data in excel-compatible tab-delimited format""" import csv csvwriter = csv.writer(self.outfile, dialect=csv.excel_tab) csvwriter.writerows(output)
[ "def", "tab", "(", "self", ",", "output", ")", ":", "import", "csv", "csvwriter", "=", "csv", ".", "writer", "(", "self", ".", "outfile", ",", "dialect", "=", "csv", ".", "excel_tab", ")", "csvwriter", ".", "writerows", "(", "output", ")" ]
Output data in excel-compatible tab-delimited format
[ "Output", "data", "in", "excel", "-", "compatible", "tab", "-", "delimited", "format" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/cli/__init__.py#L81-L85
12,459
juju/charm-helpers
charmhelpers/cli/__init__.py
CommandLine.subcommand
def subcommand(self, command_name=None): """ Decorate a function as a subcommand. Use its arguments as the command-line arguments""" def wrapper(decorated): cmd_name = command_name or decorated.__name__ subparser = self.subparsers.add_parser(cmd_name, description=decorated.__doc__) for args, kwargs in describe_arguments(decorated): subparser.add_argument(*args, **kwargs) subparser.set_defaults(func=decorated) return decorated return wrapper
python
def subcommand(self, command_name=None): """ Decorate a function as a subcommand. Use its arguments as the command-line arguments""" def wrapper(decorated): cmd_name = command_name or decorated.__name__ subparser = self.subparsers.add_parser(cmd_name, description=decorated.__doc__) for args, kwargs in describe_arguments(decorated): subparser.add_argument(*args, **kwargs) subparser.set_defaults(func=decorated) return decorated return wrapper
[ "def", "subcommand", "(", "self", ",", "command_name", "=", "None", ")", ":", "def", "wrapper", "(", "decorated", ")", ":", "cmd_name", "=", "command_name", "or", "decorated", ".", "__name__", "subparser", "=", "self", ".", "subparsers", ".", "add_parser", "(", "cmd_name", ",", "description", "=", "decorated", ".", "__doc__", ")", "for", "args", ",", "kwargs", "in", "describe_arguments", "(", "decorated", ")", ":", "subparser", ".", "add_argument", "(", "*", "args", ",", "*", "*", "kwargs", ")", "subparser", ".", "set_defaults", "(", "func", "=", "decorated", ")", "return", "decorated", "return", "wrapper" ]
Decorate a function as a subcommand. Use its arguments as the command-line arguments
[ "Decorate", "a", "function", "as", "a", "subcommand", ".", "Use", "its", "arguments", "as", "the", "command", "-", "line", "arguments" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/cli/__init__.py#L107-L119
12,460
juju/charm-helpers
charmhelpers/cli/__init__.py
CommandLine.run
def run(self): "Run cli, processing arguments and executing subcommands." arguments = self.argument_parser.parse_args() argspec = inspect.getargspec(arguments.func) vargs = [] for arg in argspec.args: vargs.append(getattr(arguments, arg)) if argspec.varargs: vargs.extend(getattr(arguments, argspec.varargs)) output = arguments.func(*vargs) if getattr(arguments.func, '_cli_test_command', False): self.exit_code = 0 if output else 1 output = '' if getattr(arguments.func, '_cli_no_output', False): output = '' self.formatter.format_output(output, arguments.format) if charmhelpers.core.unitdata._KV: charmhelpers.core.unitdata._KV.flush()
python
def run(self): "Run cli, processing arguments and executing subcommands." arguments = self.argument_parser.parse_args() argspec = inspect.getargspec(arguments.func) vargs = [] for arg in argspec.args: vargs.append(getattr(arguments, arg)) if argspec.varargs: vargs.extend(getattr(arguments, argspec.varargs)) output = arguments.func(*vargs) if getattr(arguments.func, '_cli_test_command', False): self.exit_code = 0 if output else 1 output = '' if getattr(arguments.func, '_cli_no_output', False): output = '' self.formatter.format_output(output, arguments.format) if charmhelpers.core.unitdata._KV: charmhelpers.core.unitdata._KV.flush()
[ "def", "run", "(", "self", ")", ":", "arguments", "=", "self", ".", "argument_parser", ".", "parse_args", "(", ")", "argspec", "=", "inspect", ".", "getargspec", "(", "arguments", ".", "func", ")", "vargs", "=", "[", "]", "for", "arg", "in", "argspec", ".", "args", ":", "vargs", ".", "append", "(", "getattr", "(", "arguments", ",", "arg", ")", ")", "if", "argspec", ".", "varargs", ":", "vargs", ".", "extend", "(", "getattr", "(", "arguments", ",", "argspec", ".", "varargs", ")", ")", "output", "=", "arguments", ".", "func", "(", "*", "vargs", ")", "if", "getattr", "(", "arguments", ".", "func", ",", "'_cli_test_command'", ",", "False", ")", ":", "self", ".", "exit_code", "=", "0", "if", "output", "else", "1", "output", "=", "''", "if", "getattr", "(", "arguments", ".", "func", ",", "'_cli_no_output'", ",", "False", ")", ":", "output", "=", "''", "self", ".", "formatter", ".", "format_output", "(", "output", ",", "arguments", ".", "format", ")", "if", "charmhelpers", ".", "core", ".", "unitdata", ".", "_KV", ":", "charmhelpers", ".", "core", ".", "unitdata", ".", "_KV", ".", "flush", "(", ")" ]
Run cli, processing arguments and executing subcommands.
[ "Run", "cli", "processing", "arguments", "and", "executing", "subcommands", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/cli/__init__.py#L148-L165
12,461
juju/charm-helpers
charmhelpers/contrib/unison/__init__.py
ssh_authorized_peers
def ssh_authorized_peers(peer_interface, user, group=None, ensure_local_user=False): """ Main setup function, should be called from both peer -changed and -joined hooks with the same parameters. """ if ensure_local_user: ensure_user(user, group) priv_key, pub_key = get_keypair(user) hook = hook_name() if hook == '%s-relation-joined' % peer_interface: relation_set(ssh_pub_key=pub_key) elif hook == '%s-relation-changed' % peer_interface or \ hook == '%s-relation-departed' % peer_interface: hosts = [] keys = [] for r_id in relation_ids(peer_interface): for unit in related_units(r_id): ssh_pub_key = relation_get('ssh_pub_key', rid=r_id, unit=unit) priv_addr = relation_get('private-address', rid=r_id, unit=unit) if ssh_pub_key: keys.append(ssh_pub_key) hosts.append(priv_addr) else: log('ssh_authorized_peers(): ssh_pub_key ' 'missing for unit %s, skipping.' % unit) write_authorized_keys(user, keys) write_known_hosts(user, hosts) authed_hosts = ':'.join(hosts) relation_set(ssh_authorized_hosts=authed_hosts)
python
def ssh_authorized_peers(peer_interface, user, group=None, ensure_local_user=False): """ Main setup function, should be called from both peer -changed and -joined hooks with the same parameters. """ if ensure_local_user: ensure_user(user, group) priv_key, pub_key = get_keypair(user) hook = hook_name() if hook == '%s-relation-joined' % peer_interface: relation_set(ssh_pub_key=pub_key) elif hook == '%s-relation-changed' % peer_interface or \ hook == '%s-relation-departed' % peer_interface: hosts = [] keys = [] for r_id in relation_ids(peer_interface): for unit in related_units(r_id): ssh_pub_key = relation_get('ssh_pub_key', rid=r_id, unit=unit) priv_addr = relation_get('private-address', rid=r_id, unit=unit) if ssh_pub_key: keys.append(ssh_pub_key) hosts.append(priv_addr) else: log('ssh_authorized_peers(): ssh_pub_key ' 'missing for unit %s, skipping.' % unit) write_authorized_keys(user, keys) write_known_hosts(user, hosts) authed_hosts = ':'.join(hosts) relation_set(ssh_authorized_hosts=authed_hosts)
[ "def", "ssh_authorized_peers", "(", "peer_interface", ",", "user", ",", "group", "=", "None", ",", "ensure_local_user", "=", "False", ")", ":", "if", "ensure_local_user", ":", "ensure_user", "(", "user", ",", "group", ")", "priv_key", ",", "pub_key", "=", "get_keypair", "(", "user", ")", "hook", "=", "hook_name", "(", ")", "if", "hook", "==", "'%s-relation-joined'", "%", "peer_interface", ":", "relation_set", "(", "ssh_pub_key", "=", "pub_key", ")", "elif", "hook", "==", "'%s-relation-changed'", "%", "peer_interface", "or", "hook", "==", "'%s-relation-departed'", "%", "peer_interface", ":", "hosts", "=", "[", "]", "keys", "=", "[", "]", "for", "r_id", "in", "relation_ids", "(", "peer_interface", ")", ":", "for", "unit", "in", "related_units", "(", "r_id", ")", ":", "ssh_pub_key", "=", "relation_get", "(", "'ssh_pub_key'", ",", "rid", "=", "r_id", ",", "unit", "=", "unit", ")", "priv_addr", "=", "relation_get", "(", "'private-address'", ",", "rid", "=", "r_id", ",", "unit", "=", "unit", ")", "if", "ssh_pub_key", ":", "keys", ".", "append", "(", "ssh_pub_key", ")", "hosts", ".", "append", "(", "priv_addr", ")", "else", ":", "log", "(", "'ssh_authorized_peers(): ssh_pub_key '", "'missing for unit %s, skipping.'", "%", "unit", ")", "write_authorized_keys", "(", "user", ",", "keys", ")", "write_known_hosts", "(", "user", ",", "hosts", ")", "authed_hosts", "=", "':'", ".", "join", "(", "hosts", ")", "relation_set", "(", "ssh_authorized_hosts", "=", "authed_hosts", ")" ]
Main setup function, should be called from both peer -changed and -joined hooks with the same parameters.
[ "Main", "setup", "function", "should", "be", "called", "from", "both", "peer", "-", "changed", "and", "-", "joined", "hooks", "with", "the", "same", "parameters", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/unison/__init__.py#L185-L219
12,462
juju/charm-helpers
charmhelpers/contrib/unison/__init__.py
collect_authed_hosts
def collect_authed_hosts(peer_interface): '''Iterate through the units on peer interface to find all that have the calling host in its authorized hosts list''' hosts = [] for r_id in (relation_ids(peer_interface) or []): for unit in related_units(r_id): private_addr = relation_get('private-address', rid=r_id, unit=unit) authed_hosts = relation_get('ssh_authorized_hosts', rid=r_id, unit=unit) if not authed_hosts: log('Peer %s has not authorized *any* hosts yet, skipping.' % (unit), level=INFO) continue if unit_private_ip() in authed_hosts.split(':'): hosts.append(private_addr) else: log('Peer %s has not authorized *this* host yet, skipping.' % (unit), level=INFO) return hosts
python
def collect_authed_hosts(peer_interface): '''Iterate through the units on peer interface to find all that have the calling host in its authorized hosts list''' hosts = [] for r_id in (relation_ids(peer_interface) or []): for unit in related_units(r_id): private_addr = relation_get('private-address', rid=r_id, unit=unit) authed_hosts = relation_get('ssh_authorized_hosts', rid=r_id, unit=unit) if not authed_hosts: log('Peer %s has not authorized *any* hosts yet, skipping.' % (unit), level=INFO) continue if unit_private_ip() in authed_hosts.split(':'): hosts.append(private_addr) else: log('Peer %s has not authorized *this* host yet, skipping.' % (unit), level=INFO) return hosts
[ "def", "collect_authed_hosts", "(", "peer_interface", ")", ":", "hosts", "=", "[", "]", "for", "r_id", "in", "(", "relation_ids", "(", "peer_interface", ")", "or", "[", "]", ")", ":", "for", "unit", "in", "related_units", "(", "r_id", ")", ":", "private_addr", "=", "relation_get", "(", "'private-address'", ",", "rid", "=", "r_id", ",", "unit", "=", "unit", ")", "authed_hosts", "=", "relation_get", "(", "'ssh_authorized_hosts'", ",", "rid", "=", "r_id", ",", "unit", "=", "unit", ")", "if", "not", "authed_hosts", ":", "log", "(", "'Peer %s has not authorized *any* hosts yet, skipping.'", "%", "(", "unit", ")", ",", "level", "=", "INFO", ")", "continue", "if", "unit_private_ip", "(", ")", "in", "authed_hosts", ".", "split", "(", "':'", ")", ":", "hosts", ".", "append", "(", "private_addr", ")", "else", ":", "log", "(", "'Peer %s has not authorized *this* host yet, skipping.'", "%", "(", "unit", ")", ",", "level", "=", "INFO", ")", "return", "hosts" ]
Iterate through the units on peer interface to find all that have the calling host in its authorized hosts list
[ "Iterate", "through", "the", "units", "on", "peer", "interface", "to", "find", "all", "that", "have", "the", "calling", "host", "in", "its", "authorized", "hosts", "list" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/unison/__init__.py#L242-L263
12,463
juju/charm-helpers
charmhelpers/contrib/unison/__init__.py
sync_path_to_host
def sync_path_to_host(path, host, user, verbose=False, cmd=None, gid=None, fatal=False): """Sync path to an specific peer host Propagates exception if operation fails and fatal=True. """ cmd = cmd or copy(BASE_CMD) if not verbose: cmd.append('-silent') # removing trailing slash from directory paths, unison # doesn't like these. if path.endswith('/'): path = path[:(len(path) - 1)] cmd = cmd + [path, 'ssh://%s@%s/%s' % (user, host, path)] try: log('Syncing local path %s to %s@%s:%s' % (path, user, host, path)) run_as_user(user, cmd, gid) except Exception: log('Error syncing remote files') if fatal: raise
python
def sync_path_to_host(path, host, user, verbose=False, cmd=None, gid=None, fatal=False): """Sync path to an specific peer host Propagates exception if operation fails and fatal=True. """ cmd = cmd or copy(BASE_CMD) if not verbose: cmd.append('-silent') # removing trailing slash from directory paths, unison # doesn't like these. if path.endswith('/'): path = path[:(len(path) - 1)] cmd = cmd + [path, 'ssh://%s@%s/%s' % (user, host, path)] try: log('Syncing local path %s to %s@%s:%s' % (path, user, host, path)) run_as_user(user, cmd, gid) except Exception: log('Error syncing remote files') if fatal: raise
[ "def", "sync_path_to_host", "(", "path", ",", "host", ",", "user", ",", "verbose", "=", "False", ",", "cmd", "=", "None", ",", "gid", "=", "None", ",", "fatal", "=", "False", ")", ":", "cmd", "=", "cmd", "or", "copy", "(", "BASE_CMD", ")", "if", "not", "verbose", ":", "cmd", ".", "append", "(", "'-silent'", ")", "# removing trailing slash from directory paths, unison", "# doesn't like these.", "if", "path", ".", "endswith", "(", "'/'", ")", ":", "path", "=", "path", "[", ":", "(", "len", "(", "path", ")", "-", "1", ")", "]", "cmd", "=", "cmd", "+", "[", "path", ",", "'ssh://%s@%s/%s'", "%", "(", "user", ",", "host", ",", "path", ")", "]", "try", ":", "log", "(", "'Syncing local path %s to %s@%s:%s'", "%", "(", "path", ",", "user", ",", "host", ",", "path", ")", ")", "run_as_user", "(", "user", ",", "cmd", ",", "gid", ")", "except", "Exception", ":", "log", "(", "'Error syncing remote files'", ")", "if", "fatal", ":", "raise" ]
Sync path to an specific peer host Propagates exception if operation fails and fatal=True.
[ "Sync", "path", "to", "an", "specific", "peer", "host" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/unison/__init__.py#L266-L289
12,464
juju/charm-helpers
charmhelpers/contrib/unison/__init__.py
sync_to_peer
def sync_to_peer(host, user, paths=None, verbose=False, cmd=None, gid=None, fatal=False): """Sync paths to an specific peer host Propagates exception if any operation fails and fatal=True. """ if paths: for p in paths: sync_path_to_host(p, host, user, verbose, cmd, gid, fatal)
python
def sync_to_peer(host, user, paths=None, verbose=False, cmd=None, gid=None, fatal=False): """Sync paths to an specific peer host Propagates exception if any operation fails and fatal=True. """ if paths: for p in paths: sync_path_to_host(p, host, user, verbose, cmd, gid, fatal)
[ "def", "sync_to_peer", "(", "host", ",", "user", ",", "paths", "=", "None", ",", "verbose", "=", "False", ",", "cmd", "=", "None", ",", "gid", "=", "None", ",", "fatal", "=", "False", ")", ":", "if", "paths", ":", "for", "p", "in", "paths", ":", "sync_path_to_host", "(", "p", ",", "host", ",", "user", ",", "verbose", ",", "cmd", ",", "gid", ",", "fatal", ")" ]
Sync paths to an specific peer host Propagates exception if any operation fails and fatal=True.
[ "Sync", "paths", "to", "an", "specific", "peer", "host" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/unison/__init__.py#L292-L300
12,465
juju/charm-helpers
charmhelpers/contrib/unison/__init__.py
sync_to_peers
def sync_to_peers(peer_interface, user, paths=None, verbose=False, cmd=None, gid=None, fatal=False): """Sync all hosts to an specific path The type of group is integer, it allows user has permissions to operate a directory have a different group id with the user id. Propagates exception if any operation fails and fatal=True. """ if paths: for host in collect_authed_hosts(peer_interface): sync_to_peer(host, user, paths, verbose, cmd, gid, fatal)
python
def sync_to_peers(peer_interface, user, paths=None, verbose=False, cmd=None, gid=None, fatal=False): """Sync all hosts to an specific path The type of group is integer, it allows user has permissions to operate a directory have a different group id with the user id. Propagates exception if any operation fails and fatal=True. """ if paths: for host in collect_authed_hosts(peer_interface): sync_to_peer(host, user, paths, verbose, cmd, gid, fatal)
[ "def", "sync_to_peers", "(", "peer_interface", ",", "user", ",", "paths", "=", "None", ",", "verbose", "=", "False", ",", "cmd", "=", "None", ",", "gid", "=", "None", ",", "fatal", "=", "False", ")", ":", "if", "paths", ":", "for", "host", "in", "collect_authed_hosts", "(", "peer_interface", ")", ":", "sync_to_peer", "(", "host", ",", "user", ",", "paths", ",", "verbose", ",", "cmd", ",", "gid", ",", "fatal", ")" ]
Sync all hosts to an specific path The type of group is integer, it allows user has permissions to operate a directory have a different group id with the user id. Propagates exception if any operation fails and fatal=True.
[ "Sync", "all", "hosts", "to", "an", "specific", "path" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/unison/__init__.py#L303-L314
12,466
juju/charm-helpers
charmhelpers/fetch/python/packages.py
parse_options
def parse_options(given, available): """Given a set of options, check if available""" for key, value in sorted(given.items()): if not value: continue if key in available: yield "--{0}={1}".format(key, value)
python
def parse_options(given, available): """Given a set of options, check if available""" for key, value in sorted(given.items()): if not value: continue if key in available: yield "--{0}={1}".format(key, value)
[ "def", "parse_options", "(", "given", ",", "available", ")", ":", "for", "key", ",", "value", "in", "sorted", "(", "given", ".", "items", "(", ")", ")", ":", "if", "not", "value", ":", "continue", "if", "key", "in", "available", ":", "yield", "\"--{0}={1}\"", ".", "format", "(", "key", ",", "value", ")" ]
Given a set of options, check if available
[ "Given", "a", "set", "of", "options", "check", "if", "available" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/fetch/python/packages.py#L53-L59
12,467
juju/charm-helpers
charmhelpers/fetch/python/packages.py
pip_install_requirements
def pip_install_requirements(requirements, constraints=None, **options): """Install a requirements file. :param constraints: Path to pip constraints file. http://pip.readthedocs.org/en/stable/user_guide/#constraints-files """ command = ["install"] available_options = ('proxy', 'src', 'log', ) for option in parse_options(options, available_options): command.append(option) command.append("-r {0}".format(requirements)) if constraints: command.append("-c {0}".format(constraints)) log("Installing from file: {} with constraints {} " "and options: {}".format(requirements, constraints, command)) else: log("Installing from file: {} with options: {}".format(requirements, command)) pip_execute(command)
python
def pip_install_requirements(requirements, constraints=None, **options): """Install a requirements file. :param constraints: Path to pip constraints file. http://pip.readthedocs.org/en/stable/user_guide/#constraints-files """ command = ["install"] available_options = ('proxy', 'src', 'log', ) for option in parse_options(options, available_options): command.append(option) command.append("-r {0}".format(requirements)) if constraints: command.append("-c {0}".format(constraints)) log("Installing from file: {} with constraints {} " "and options: {}".format(requirements, constraints, command)) else: log("Installing from file: {} with options: {}".format(requirements, command)) pip_execute(command)
[ "def", "pip_install_requirements", "(", "requirements", ",", "constraints", "=", "None", ",", "*", "*", "options", ")", ":", "command", "=", "[", "\"install\"", "]", "available_options", "=", "(", "'proxy'", ",", "'src'", ",", "'log'", ",", ")", "for", "option", "in", "parse_options", "(", "options", ",", "available_options", ")", ":", "command", ".", "append", "(", "option", ")", "command", ".", "append", "(", "\"-r {0}\"", ".", "format", "(", "requirements", ")", ")", "if", "constraints", ":", "command", ".", "append", "(", "\"-c {0}\"", ".", "format", "(", "constraints", ")", ")", "log", "(", "\"Installing from file: {} with constraints {} \"", "\"and options: {}\"", ".", "format", "(", "requirements", ",", "constraints", ",", "command", ")", ")", "else", ":", "log", "(", "\"Installing from file: {} with options: {}\"", ".", "format", "(", "requirements", ",", "command", ")", ")", "pip_execute", "(", "command", ")" ]
Install a requirements file. :param constraints: Path to pip constraints file. http://pip.readthedocs.org/en/stable/user_guide/#constraints-files
[ "Install", "a", "requirements", "file", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/fetch/python/packages.py#L62-L82
12,468
juju/charm-helpers
charmhelpers/fetch/python/packages.py
pip_install
def pip_install(package, fatal=False, upgrade=False, venv=None, constraints=None, **options): """Install a python package""" if venv: venv_python = os.path.join(venv, 'bin/pip') command = [venv_python, "install"] else: command = ["install"] available_options = ('proxy', 'src', 'log', 'index-url', ) for option in parse_options(options, available_options): command.append(option) if upgrade: command.append('--upgrade') if constraints: command.extend(['-c', constraints]) if isinstance(package, list): command.extend(package) else: command.append(package) log("Installing {} package with options: {}".format(package, command)) if venv: subprocess.check_call(command) else: pip_execute(command)
python
def pip_install(package, fatal=False, upgrade=False, venv=None, constraints=None, **options): """Install a python package""" if venv: venv_python = os.path.join(venv, 'bin/pip') command = [venv_python, "install"] else: command = ["install"] available_options = ('proxy', 'src', 'log', 'index-url', ) for option in parse_options(options, available_options): command.append(option) if upgrade: command.append('--upgrade') if constraints: command.extend(['-c', constraints]) if isinstance(package, list): command.extend(package) else: command.append(package) log("Installing {} package with options: {}".format(package, command)) if venv: subprocess.check_call(command) else: pip_execute(command)
[ "def", "pip_install", "(", "package", ",", "fatal", "=", "False", ",", "upgrade", "=", "False", ",", "venv", "=", "None", ",", "constraints", "=", "None", ",", "*", "*", "options", ")", ":", "if", "venv", ":", "venv_python", "=", "os", ".", "path", ".", "join", "(", "venv", ",", "'bin/pip'", ")", "command", "=", "[", "venv_python", ",", "\"install\"", "]", "else", ":", "command", "=", "[", "\"install\"", "]", "available_options", "=", "(", "'proxy'", ",", "'src'", ",", "'log'", ",", "'index-url'", ",", ")", "for", "option", "in", "parse_options", "(", "options", ",", "available_options", ")", ":", "command", ".", "append", "(", "option", ")", "if", "upgrade", ":", "command", ".", "append", "(", "'--upgrade'", ")", "if", "constraints", ":", "command", ".", "extend", "(", "[", "'-c'", ",", "constraints", "]", ")", "if", "isinstance", "(", "package", ",", "list", ")", ":", "command", ".", "extend", "(", "package", ")", "else", ":", "command", ".", "append", "(", "package", ")", "log", "(", "\"Installing {} package with options: {}\"", ".", "format", "(", "package", ",", "command", ")", ")", "if", "venv", ":", "subprocess", ".", "check_call", "(", "command", ")", "else", ":", "pip_execute", "(", "command", ")" ]
Install a python package
[ "Install", "a", "python", "package" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/fetch/python/packages.py#L85-L114
12,469
juju/charm-helpers
charmhelpers/fetch/python/packages.py
pip_uninstall
def pip_uninstall(package, **options): """Uninstall a python package""" command = ["uninstall", "-q", "-y"] available_options = ('proxy', 'log', ) for option in parse_options(options, available_options): command.append(option) if isinstance(package, list): command.extend(package) else: command.append(package) log("Uninstalling {} package with options: {}".format(package, command)) pip_execute(command)
python
def pip_uninstall(package, **options): """Uninstall a python package""" command = ["uninstall", "-q", "-y"] available_options = ('proxy', 'log', ) for option in parse_options(options, available_options): command.append(option) if isinstance(package, list): command.extend(package) else: command.append(package) log("Uninstalling {} package with options: {}".format(package, command)) pip_execute(command)
[ "def", "pip_uninstall", "(", "package", ",", "*", "*", "options", ")", ":", "command", "=", "[", "\"uninstall\"", ",", "\"-q\"", ",", "\"-y\"", "]", "available_options", "=", "(", "'proxy'", ",", "'log'", ",", ")", "for", "option", "in", "parse_options", "(", "options", ",", "available_options", ")", ":", "command", ".", "append", "(", "option", ")", "if", "isinstance", "(", "package", ",", "list", ")", ":", "command", ".", "extend", "(", "package", ")", "else", ":", "command", ".", "append", "(", "package", ")", "log", "(", "\"Uninstalling {} package with options: {}\"", ".", "format", "(", "package", ",", "command", ")", ")", "pip_execute", "(", "command", ")" ]
Uninstall a python package
[ "Uninstall", "a", "python", "package" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/fetch/python/packages.py#L117-L132
12,470
juju/charm-helpers
charmhelpers/fetch/python/packages.py
pip_create_virtualenv
def pip_create_virtualenv(path=None): """Create an isolated Python environment.""" if six.PY2: apt_install('python-virtualenv') else: apt_install('python3-virtualenv') if path: venv_path = path else: venv_path = os.path.join(charm_dir(), 'venv') if not os.path.exists(venv_path): subprocess.check_call(['virtualenv', venv_path])
python
def pip_create_virtualenv(path=None): """Create an isolated Python environment.""" if six.PY2: apt_install('python-virtualenv') else: apt_install('python3-virtualenv') if path: venv_path = path else: venv_path = os.path.join(charm_dir(), 'venv') if not os.path.exists(venv_path): subprocess.check_call(['virtualenv', venv_path])
[ "def", "pip_create_virtualenv", "(", "path", "=", "None", ")", ":", "if", "six", ".", "PY2", ":", "apt_install", "(", "'python-virtualenv'", ")", "else", ":", "apt_install", "(", "'python3-virtualenv'", ")", "if", "path", ":", "venv_path", "=", "path", "else", ":", "venv_path", "=", "os", ".", "path", ".", "join", "(", "charm_dir", "(", ")", ",", "'venv'", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "venv_path", ")", ":", "subprocess", ".", "check_call", "(", "[", "'virtualenv'", ",", "venv_path", "]", ")" ]
Create an isolated Python environment.
[ "Create", "an", "isolated", "Python", "environment", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/fetch/python/packages.py#L141-L154
12,471
juju/charm-helpers
charmhelpers/fetch/__init__.py
configure_sources
def configure_sources(update=False, sources_var='install_sources', keys_var='install_keys'): """Configure multiple sources from charm configuration. The lists are encoded as yaml fragments in the configuration. The fragment needs to be included as a string. Sources and their corresponding keys are of the types supported by add_source(). Example config: install_sources: | - "ppa:foo" - "http://example.com/repo precise main" install_keys: | - null - "a1b2c3d4" Note that 'null' (a.k.a. None) should not be quoted. """ sources = safe_load((config(sources_var) or '').strip()) or [] keys = safe_load((config(keys_var) or '').strip()) or None if isinstance(sources, six.string_types): sources = [sources] if keys is None: for source in sources: add_source(source, None) else: if isinstance(keys, six.string_types): keys = [keys] if len(sources) != len(keys): raise SourceConfigError( 'Install sources and keys lists are different lengths') for source, key in zip(sources, keys): add_source(source, key) if update: _fetch_update(fatal=True)
python
def configure_sources(update=False, sources_var='install_sources', keys_var='install_keys'): """Configure multiple sources from charm configuration. The lists are encoded as yaml fragments in the configuration. The fragment needs to be included as a string. Sources and their corresponding keys are of the types supported by add_source(). Example config: install_sources: | - "ppa:foo" - "http://example.com/repo precise main" install_keys: | - null - "a1b2c3d4" Note that 'null' (a.k.a. None) should not be quoted. """ sources = safe_load((config(sources_var) or '').strip()) or [] keys = safe_load((config(keys_var) or '').strip()) or None if isinstance(sources, six.string_types): sources = [sources] if keys is None: for source in sources: add_source(source, None) else: if isinstance(keys, six.string_types): keys = [keys] if len(sources) != len(keys): raise SourceConfigError( 'Install sources and keys lists are different lengths') for source, key in zip(sources, keys): add_source(source, key) if update: _fetch_update(fatal=True)
[ "def", "configure_sources", "(", "update", "=", "False", ",", "sources_var", "=", "'install_sources'", ",", "keys_var", "=", "'install_keys'", ")", ":", "sources", "=", "safe_load", "(", "(", "config", "(", "sources_var", ")", "or", "''", ")", ".", "strip", "(", ")", ")", "or", "[", "]", "keys", "=", "safe_load", "(", "(", "config", "(", "keys_var", ")", "or", "''", ")", ".", "strip", "(", ")", ")", "or", "None", "if", "isinstance", "(", "sources", ",", "six", ".", "string_types", ")", ":", "sources", "=", "[", "sources", "]", "if", "keys", "is", "None", ":", "for", "source", "in", "sources", ":", "add_source", "(", "source", ",", "None", ")", "else", ":", "if", "isinstance", "(", "keys", ",", "six", ".", "string_types", ")", ":", "keys", "=", "[", "keys", "]", "if", "len", "(", "sources", ")", "!=", "len", "(", "keys", ")", ":", "raise", "SourceConfigError", "(", "'Install sources and keys lists are different lengths'", ")", "for", "source", ",", "key", "in", "zip", "(", "sources", ",", "keys", ")", ":", "add_source", "(", "source", ",", "key", ")", "if", "update", ":", "_fetch_update", "(", "fatal", "=", "True", ")" ]
Configure multiple sources from charm configuration. The lists are encoded as yaml fragments in the configuration. The fragment needs to be included as a string. Sources and their corresponding keys are of the types supported by add_source(). Example config: install_sources: | - "ppa:foo" - "http://example.com/repo precise main" install_keys: | - null - "a1b2c3d4" Note that 'null' (a.k.a. None) should not be quoted.
[ "Configure", "multiple", "sources", "from", "charm", "configuration", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/fetch/__init__.py#L110-L148
12,472
juju/charm-helpers
charmhelpers/fetch/__init__.py
install_remote
def install_remote(source, *args, **kwargs): """Install a file tree from a remote source. The specified source should be a url of the form: scheme://[host]/path[#[option=value][&...]] Schemes supported are based on this modules submodules. Options supported are submodule-specific. Additional arguments are passed through to the submodule. For example:: dest = install_remote('http://example.com/archive.tgz', checksum='deadbeef', hash_type='sha1') This will download `archive.tgz`, validate it using SHA1 and, if the file is ok, extract it and return the directory in which it was extracted. If the checksum fails, it will raise :class:`charmhelpers.core.host.ChecksumError`. """ # We ONLY check for True here because can_handle may return a string # explaining why it can't handle a given source. handlers = [h for h in plugins() if h.can_handle(source) is True] for handler in handlers: try: return handler.install(source, *args, **kwargs) except UnhandledSource as e: log('Install source attempt unsuccessful: {}'.format(e), level='WARNING') raise UnhandledSource("No handler found for source {}".format(source))
python
def install_remote(source, *args, **kwargs): """Install a file tree from a remote source. The specified source should be a url of the form: scheme://[host]/path[#[option=value][&...]] Schemes supported are based on this modules submodules. Options supported are submodule-specific. Additional arguments are passed through to the submodule. For example:: dest = install_remote('http://example.com/archive.tgz', checksum='deadbeef', hash_type='sha1') This will download `archive.tgz`, validate it using SHA1 and, if the file is ok, extract it and return the directory in which it was extracted. If the checksum fails, it will raise :class:`charmhelpers.core.host.ChecksumError`. """ # We ONLY check for True here because can_handle may return a string # explaining why it can't handle a given source. handlers = [h for h in plugins() if h.can_handle(source) is True] for handler in handlers: try: return handler.install(source, *args, **kwargs) except UnhandledSource as e: log('Install source attempt unsuccessful: {}'.format(e), level='WARNING') raise UnhandledSource("No handler found for source {}".format(source))
[ "def", "install_remote", "(", "source", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# We ONLY check for True here because can_handle may return a string", "# explaining why it can't handle a given source.", "handlers", "=", "[", "h", "for", "h", "in", "plugins", "(", ")", "if", "h", ".", "can_handle", "(", "source", ")", "is", "True", "]", "for", "handler", "in", "handlers", ":", "try", ":", "return", "handler", ".", "install", "(", "source", ",", "*", "args", ",", "*", "*", "kwargs", ")", "except", "UnhandledSource", "as", "e", ":", "log", "(", "'Install source attempt unsuccessful: {}'", ".", "format", "(", "e", ")", ",", "level", "=", "'WARNING'", ")", "raise", "UnhandledSource", "(", "\"No handler found for source {}\"", ".", "format", "(", "source", ")", ")" ]
Install a file tree from a remote source. The specified source should be a url of the form: scheme://[host]/path[#[option=value][&...]] Schemes supported are based on this modules submodules. Options supported are submodule-specific. Additional arguments are passed through to the submodule. For example:: dest = install_remote('http://example.com/archive.tgz', checksum='deadbeef', hash_type='sha1') This will download `archive.tgz`, validate it using SHA1 and, if the file is ok, extract it and return the directory in which it was extracted. If the checksum fails, it will raise :class:`charmhelpers.core.host.ChecksumError`.
[ "Install", "a", "file", "tree", "from", "a", "remote", "source", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/fetch/__init__.py#L151-L181
12,473
juju/charm-helpers
charmhelpers/fetch/__init__.py
BaseFetchHandler.base_url
def base_url(self, url): """Return url without querystring or fragment""" parts = list(self.parse_url(url)) parts[4:] = ['' for i in parts[4:]] return urlunparse(parts)
python
def base_url(self, url): """Return url without querystring or fragment""" parts = list(self.parse_url(url)) parts[4:] = ['' for i in parts[4:]] return urlunparse(parts)
[ "def", "base_url", "(", "self", ",", "url", ")", ":", "parts", "=", "list", "(", "self", ".", "parse_url", "(", "url", ")", ")", "parts", "[", "4", ":", "]", "=", "[", "''", "for", "i", "in", "parts", "[", "4", ":", "]", "]", "return", "urlunparse", "(", "parts", ")" ]
Return url without querystring or fragment
[ "Return", "url", "without", "querystring", "or", "fragment" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/fetch/__init__.py#L75-L79
12,474
juju/charm-helpers
charmhelpers/contrib/storage/linux/utils.py
is_block_device
def is_block_device(path): ''' Confirm device at path is a valid block device node. :returns: boolean: True if path is a block device, False if not. ''' if not os.path.exists(path): return False return S_ISBLK(os.stat(path).st_mode)
python
def is_block_device(path): ''' Confirm device at path is a valid block device node. :returns: boolean: True if path is a block device, False if not. ''' if not os.path.exists(path): return False return S_ISBLK(os.stat(path).st_mode)
[ "def", "is_block_device", "(", "path", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "return", "False", "return", "S_ISBLK", "(", "os", ".", "stat", "(", "path", ")", ".", "st_mode", ")" ]
Confirm device at path is a valid block device node. :returns: boolean: True if path is a block device, False if not.
[ "Confirm", "device", "at", "path", "is", "a", "valid", "block", "device", "node", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/storage/linux/utils.py#L67-L75
12,475
juju/charm-helpers
charmhelpers/contrib/storage/linux/utils.py
zap_disk
def zap_disk(block_device): ''' Clear a block device of partition table. Relies on sgdisk, which is installed as pat of the 'gdisk' package in Ubuntu. :param block_device: str: Full path of block device to clean. ''' # https://github.com/ceph/ceph/commit/fdd7f8d83afa25c4e09aaedd90ab93f3b64a677b # sometimes sgdisk exits non-zero; this is OK, dd will clean up call(['sgdisk', '--zap-all', '--', block_device]) call(['sgdisk', '--clear', '--mbrtogpt', '--', block_device]) dev_end = check_output(['blockdev', '--getsz', block_device]).decode('UTF-8') gpt_end = int(dev_end.split()[0]) - 100 check_call(['dd', 'if=/dev/zero', 'of=%s' % (block_device), 'bs=1M', 'count=1']) check_call(['dd', 'if=/dev/zero', 'of=%s' % (block_device), 'bs=512', 'count=100', 'seek=%s' % (gpt_end)])
python
def zap_disk(block_device): ''' Clear a block device of partition table. Relies on sgdisk, which is installed as pat of the 'gdisk' package in Ubuntu. :param block_device: str: Full path of block device to clean. ''' # https://github.com/ceph/ceph/commit/fdd7f8d83afa25c4e09aaedd90ab93f3b64a677b # sometimes sgdisk exits non-zero; this is OK, dd will clean up call(['sgdisk', '--zap-all', '--', block_device]) call(['sgdisk', '--clear', '--mbrtogpt', '--', block_device]) dev_end = check_output(['blockdev', '--getsz', block_device]).decode('UTF-8') gpt_end = int(dev_end.split()[0]) - 100 check_call(['dd', 'if=/dev/zero', 'of=%s' % (block_device), 'bs=1M', 'count=1']) check_call(['dd', 'if=/dev/zero', 'of=%s' % (block_device), 'bs=512', 'count=100', 'seek=%s' % (gpt_end)])
[ "def", "zap_disk", "(", "block_device", ")", ":", "# https://github.com/ceph/ceph/commit/fdd7f8d83afa25c4e09aaedd90ab93f3b64a677b", "# sometimes sgdisk exits non-zero; this is OK, dd will clean up", "call", "(", "[", "'sgdisk'", ",", "'--zap-all'", ",", "'--'", ",", "block_device", "]", ")", "call", "(", "[", "'sgdisk'", ",", "'--clear'", ",", "'--mbrtogpt'", ",", "'--'", ",", "block_device", "]", ")", "dev_end", "=", "check_output", "(", "[", "'blockdev'", ",", "'--getsz'", ",", "block_device", "]", ")", ".", "decode", "(", "'UTF-8'", ")", "gpt_end", "=", "int", "(", "dev_end", ".", "split", "(", ")", "[", "0", "]", ")", "-", "100", "check_call", "(", "[", "'dd'", ",", "'if=/dev/zero'", ",", "'of=%s'", "%", "(", "block_device", ")", ",", "'bs=1M'", ",", "'count=1'", "]", ")", "check_call", "(", "[", "'dd'", ",", "'if=/dev/zero'", ",", "'of=%s'", "%", "(", "block_device", ")", ",", "'bs=512'", ",", "'count=100'", ",", "'seek=%s'", "%", "(", "gpt_end", ")", "]", ")" ]
Clear a block device of partition table. Relies on sgdisk, which is installed as pat of the 'gdisk' package in Ubuntu. :param block_device: str: Full path of block device to clean.
[ "Clear", "a", "block", "device", "of", "partition", "table", ".", "Relies", "on", "sgdisk", "which", "is", "installed", "as", "pat", "of", "the", "gdisk", "package", "in", "Ubuntu", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/storage/linux/utils.py#L78-L95
12,476
juju/charm-helpers
charmhelpers/contrib/storage/linux/utils.py
is_device_mounted
def is_device_mounted(device): '''Given a device path, return True if that device is mounted, and False if it isn't. :param device: str: Full path of the device to check. :returns: boolean: True if the path represents a mounted device, False if it doesn't. ''' try: out = check_output(['lsblk', '-P', device]).decode('UTF-8') except Exception: return False return bool(re.search(r'MOUNTPOINT=".+"', out))
python
def is_device_mounted(device): '''Given a device path, return True if that device is mounted, and False if it isn't. :param device: str: Full path of the device to check. :returns: boolean: True if the path represents a mounted device, False if it doesn't. ''' try: out = check_output(['lsblk', '-P', device]).decode('UTF-8') except Exception: return False return bool(re.search(r'MOUNTPOINT=".+"', out))
[ "def", "is_device_mounted", "(", "device", ")", ":", "try", ":", "out", "=", "check_output", "(", "[", "'lsblk'", ",", "'-P'", ",", "device", "]", ")", ".", "decode", "(", "'UTF-8'", ")", "except", "Exception", ":", "return", "False", "return", "bool", "(", "re", ".", "search", "(", "r'MOUNTPOINT=\".+\"'", ",", "out", ")", ")" ]
Given a device path, return True if that device is mounted, and False if it isn't. :param device: str: Full path of the device to check. :returns: boolean: True if the path represents a mounted device, False if it doesn't.
[ "Given", "a", "device", "path", "return", "True", "if", "that", "device", "is", "mounted", "and", "False", "if", "it", "isn", "t", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/storage/linux/utils.py#L98-L110
12,477
juju/charm-helpers
charmhelpers/contrib/storage/linux/utils.py
mkfs_xfs
def mkfs_xfs(device, force=False): """Format device with XFS filesystem. By default this should fail if the device already has a filesystem on it. :param device: Full path to device to format :ptype device: tr :param force: Force operation :ptype: force: boolean""" cmd = ['mkfs.xfs'] if force: cmd.append("-f") cmd += ['-i', 'size=1024', device] check_call(cmd)
python
def mkfs_xfs(device, force=False): """Format device with XFS filesystem. By default this should fail if the device already has a filesystem on it. :param device: Full path to device to format :ptype device: tr :param force: Force operation :ptype: force: boolean""" cmd = ['mkfs.xfs'] if force: cmd.append("-f") cmd += ['-i', 'size=1024', device] check_call(cmd)
[ "def", "mkfs_xfs", "(", "device", ",", "force", "=", "False", ")", ":", "cmd", "=", "[", "'mkfs.xfs'", "]", "if", "force", ":", "cmd", ".", "append", "(", "\"-f\"", ")", "cmd", "+=", "[", "'-i'", ",", "'size=1024'", ",", "device", "]", "check_call", "(", "cmd", ")" ]
Format device with XFS filesystem. By default this should fail if the device already has a filesystem on it. :param device: Full path to device to format :ptype device: tr :param force: Force operation :ptype: force: boolean
[ "Format", "device", "with", "XFS", "filesystem", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/storage/linux/utils.py#L113-L126
12,478
juju/charm-helpers
charmhelpers/contrib/charmhelpers/__init__.py
wait_for_machine
def wait_for_machine(num_machines=1, timeout=300): """Wait `timeout` seconds for `num_machines` machines to come up. This wait_for... function can be called by other wait_for functions whose timeouts might be too short in situations where only a bare Juju setup has been bootstrapped. :return: A tuple of (num_machines, time_taken). This is used for testing. """ # You may think this is a hack, and you'd be right. The easiest way # to tell what environment we're working in (LXC vs EC2) is to check # the dns-name of the first machine. If it's localhost we're in LXC # and we can just return here. if get_machine_data()[0]['dns-name'] == 'localhost': return 1, 0 start_time = time.time() while True: # Drop the first machine, since it's the Zookeeper and that's # not a machine that we need to wait for. This will only work # for EC2 environments, which is why we return early above if # we're in LXC. machine_data = get_machine_data() non_zookeeper_machines = [ machine_data[key] for key in list(machine_data.keys())[1:]] if len(non_zookeeper_machines) >= num_machines: all_machines_running = True for machine in non_zookeeper_machines: if machine.get('instance-state') != 'running': all_machines_running = False break if all_machines_running: break if time.time() - start_time >= timeout: raise RuntimeError('timeout waiting for service to start') time.sleep(SLEEP_AMOUNT) return num_machines, time.time() - start_time
python
def wait_for_machine(num_machines=1, timeout=300): """Wait `timeout` seconds for `num_machines` machines to come up. This wait_for... function can be called by other wait_for functions whose timeouts might be too short in situations where only a bare Juju setup has been bootstrapped. :return: A tuple of (num_machines, time_taken). This is used for testing. """ # You may think this is a hack, and you'd be right. The easiest way # to tell what environment we're working in (LXC vs EC2) is to check # the dns-name of the first machine. If it's localhost we're in LXC # and we can just return here. if get_machine_data()[0]['dns-name'] == 'localhost': return 1, 0 start_time = time.time() while True: # Drop the first machine, since it's the Zookeeper and that's # not a machine that we need to wait for. This will only work # for EC2 environments, which is why we return early above if # we're in LXC. machine_data = get_machine_data() non_zookeeper_machines = [ machine_data[key] for key in list(machine_data.keys())[1:]] if len(non_zookeeper_machines) >= num_machines: all_machines_running = True for machine in non_zookeeper_machines: if machine.get('instance-state') != 'running': all_machines_running = False break if all_machines_running: break if time.time() - start_time >= timeout: raise RuntimeError('timeout waiting for service to start') time.sleep(SLEEP_AMOUNT) return num_machines, time.time() - start_time
[ "def", "wait_for_machine", "(", "num_machines", "=", "1", ",", "timeout", "=", "300", ")", ":", "# You may think this is a hack, and you'd be right. The easiest way", "# to tell what environment we're working in (LXC vs EC2) is to check", "# the dns-name of the first machine. If it's localhost we're in LXC", "# and we can just return here.", "if", "get_machine_data", "(", ")", "[", "0", "]", "[", "'dns-name'", "]", "==", "'localhost'", ":", "return", "1", ",", "0", "start_time", "=", "time", ".", "time", "(", ")", "while", "True", ":", "# Drop the first machine, since it's the Zookeeper and that's", "# not a machine that we need to wait for. This will only work", "# for EC2 environments, which is why we return early above if", "# we're in LXC.", "machine_data", "=", "get_machine_data", "(", ")", "non_zookeeper_machines", "=", "[", "machine_data", "[", "key", "]", "for", "key", "in", "list", "(", "machine_data", ".", "keys", "(", ")", ")", "[", "1", ":", "]", "]", "if", "len", "(", "non_zookeeper_machines", ")", ">=", "num_machines", ":", "all_machines_running", "=", "True", "for", "machine", "in", "non_zookeeper_machines", ":", "if", "machine", ".", "get", "(", "'instance-state'", ")", "!=", "'running'", ":", "all_machines_running", "=", "False", "break", "if", "all_machines_running", ":", "break", "if", "time", ".", "time", "(", ")", "-", "start_time", ">=", "timeout", ":", "raise", "RuntimeError", "(", "'timeout waiting for service to start'", ")", "time", ".", "sleep", "(", "SLEEP_AMOUNT", ")", "return", "num_machines", ",", "time", ".", "time", "(", ")", "-", "start_time" ]
Wait `timeout` seconds for `num_machines` machines to come up. This wait_for... function can be called by other wait_for functions whose timeouts might be too short in situations where only a bare Juju setup has been bootstrapped. :return: A tuple of (num_machines, time_taken). This is used for testing.
[ "Wait", "timeout", "seconds", "for", "num_machines", "machines", "to", "come", "up", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/charmhelpers/__init__.py#L119-L155
12,479
juju/charm-helpers
charmhelpers/contrib/charmhelpers/__init__.py
wait_for_unit
def wait_for_unit(service_name, timeout=480): """Wait `timeout` seconds for a given service name to come up.""" wait_for_machine(num_machines=1) start_time = time.time() while True: state = unit_info(service_name, 'agent-state') if 'error' in state or state == 'started': break if time.time() - start_time >= timeout: raise RuntimeError('timeout waiting for service to start') time.sleep(SLEEP_AMOUNT) if state != 'started': raise RuntimeError('unit did not start, agent-state: ' + state)
python
def wait_for_unit(service_name, timeout=480): """Wait `timeout` seconds for a given service name to come up.""" wait_for_machine(num_machines=1) start_time = time.time() while True: state = unit_info(service_name, 'agent-state') if 'error' in state or state == 'started': break if time.time() - start_time >= timeout: raise RuntimeError('timeout waiting for service to start') time.sleep(SLEEP_AMOUNT) if state != 'started': raise RuntimeError('unit did not start, agent-state: ' + state)
[ "def", "wait_for_unit", "(", "service_name", ",", "timeout", "=", "480", ")", ":", "wait_for_machine", "(", "num_machines", "=", "1", ")", "start_time", "=", "time", ".", "time", "(", ")", "while", "True", ":", "state", "=", "unit_info", "(", "service_name", ",", "'agent-state'", ")", "if", "'error'", "in", "state", "or", "state", "==", "'started'", ":", "break", "if", "time", ".", "time", "(", ")", "-", "start_time", ">=", "timeout", ":", "raise", "RuntimeError", "(", "'timeout waiting for service to start'", ")", "time", ".", "sleep", "(", "SLEEP_AMOUNT", ")", "if", "state", "!=", "'started'", ":", "raise", "RuntimeError", "(", "'unit did not start, agent-state: '", "+", "state", ")" ]
Wait `timeout` seconds for a given service name to come up.
[ "Wait", "timeout", "seconds", "for", "a", "given", "service", "name", "to", "come", "up", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/charmhelpers/__init__.py#L159-L171
12,480
juju/charm-helpers
charmhelpers/contrib/charmhelpers/__init__.py
wait_for_relation
def wait_for_relation(service_name, relation_name, timeout=120): """Wait `timeout` seconds for a given relation to come up.""" start_time = time.time() while True: relation = unit_info(service_name, 'relations').get(relation_name) if relation is not None and relation['state'] == 'up': break if time.time() - start_time >= timeout: raise RuntimeError('timeout waiting for relation to be up') time.sleep(SLEEP_AMOUNT)
python
def wait_for_relation(service_name, relation_name, timeout=120): """Wait `timeout` seconds for a given relation to come up.""" start_time = time.time() while True: relation = unit_info(service_name, 'relations').get(relation_name) if relation is not None and relation['state'] == 'up': break if time.time() - start_time >= timeout: raise RuntimeError('timeout waiting for relation to be up') time.sleep(SLEEP_AMOUNT)
[ "def", "wait_for_relation", "(", "service_name", ",", "relation_name", ",", "timeout", "=", "120", ")", ":", "start_time", "=", "time", ".", "time", "(", ")", "while", "True", ":", "relation", "=", "unit_info", "(", "service_name", ",", "'relations'", ")", ".", "get", "(", "relation_name", ")", "if", "relation", "is", "not", "None", "and", "relation", "[", "'state'", "]", "==", "'up'", ":", "break", "if", "time", ".", "time", "(", ")", "-", "start_time", ">=", "timeout", ":", "raise", "RuntimeError", "(", "'timeout waiting for relation to be up'", ")", "time", ".", "sleep", "(", "SLEEP_AMOUNT", ")" ]
Wait `timeout` seconds for a given relation to come up.
[ "Wait", "timeout", "seconds", "for", "a", "given", "relation", "to", "come", "up", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/charmhelpers/__init__.py#L175-L184
12,481
juju/charm-helpers
charmhelpers/core/host_factory/ubuntu.py
service_available
def service_available(service_name): """Determine whether a system service is available""" try: subprocess.check_output( ['service', service_name, 'status'], stderr=subprocess.STDOUT).decode('UTF-8') except subprocess.CalledProcessError as e: return b'unrecognized service' not in e.output else: return True
python
def service_available(service_name): """Determine whether a system service is available""" try: subprocess.check_output( ['service', service_name, 'status'], stderr=subprocess.STDOUT).decode('UTF-8') except subprocess.CalledProcessError as e: return b'unrecognized service' not in e.output else: return True
[ "def", "service_available", "(", "service_name", ")", ":", "try", ":", "subprocess", ".", "check_output", "(", "[", "'service'", ",", "service_name", ",", "'status'", "]", ",", "stderr", "=", "subprocess", ".", "STDOUT", ")", ".", "decode", "(", "'UTF-8'", ")", "except", "subprocess", ".", "CalledProcessError", "as", "e", ":", "return", "b'unrecognized service'", "not", "in", "e", ".", "output", "else", ":", "return", "True" ]
Determine whether a system service is available
[ "Determine", "whether", "a", "system", "service", "is", "available" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/host_factory/ubuntu.py#L41-L50
12,482
juju/charm-helpers
charmhelpers/contrib/saltstack/__init__.py
install_salt_support
def install_salt_support(from_ppa=True): """Installs the salt-minion helper for machine state. By default the salt-minion package is installed from the saltstack PPA. If from_ppa is False you must ensure that the salt-minion package is available in the apt cache. """ if from_ppa: subprocess.check_call([ '/usr/bin/add-apt-repository', '--yes', 'ppa:saltstack/salt', ]) subprocess.check_call(['/usr/bin/apt-get', 'update']) # We install salt-common as salt-minion would run the salt-minion # daemon. charmhelpers.fetch.apt_install('salt-common')
python
def install_salt_support(from_ppa=True): """Installs the salt-minion helper for machine state. By default the salt-minion package is installed from the saltstack PPA. If from_ppa is False you must ensure that the salt-minion package is available in the apt cache. """ if from_ppa: subprocess.check_call([ '/usr/bin/add-apt-repository', '--yes', 'ppa:saltstack/salt', ]) subprocess.check_call(['/usr/bin/apt-get', 'update']) # We install salt-common as salt-minion would run the salt-minion # daemon. charmhelpers.fetch.apt_install('salt-common')
[ "def", "install_salt_support", "(", "from_ppa", "=", "True", ")", ":", "if", "from_ppa", ":", "subprocess", ".", "check_call", "(", "[", "'/usr/bin/add-apt-repository'", ",", "'--yes'", ",", "'ppa:saltstack/salt'", ",", "]", ")", "subprocess", ".", "check_call", "(", "[", "'/usr/bin/apt-get'", ",", "'update'", "]", ")", "# We install salt-common as salt-minion would run the salt-minion", "# daemon.", "charmhelpers", ".", "fetch", ".", "apt_install", "(", "'salt-common'", ")" ]
Installs the salt-minion helper for machine state. By default the salt-minion package is installed from the saltstack PPA. If from_ppa is False you must ensure that the salt-minion package is available in the apt cache.
[ "Installs", "the", "salt", "-", "minion", "helper", "for", "machine", "state", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/saltstack/__init__.py#L88-L104
12,483
juju/charm-helpers
charmhelpers/contrib/saltstack/__init__.py
update_machine_state
def update_machine_state(state_path): """Update the machine state using the provided state declaration.""" charmhelpers.contrib.templating.contexts.juju_state_to_yaml( salt_grains_path) subprocess.check_call([ 'salt-call', '--local', 'state.template', state_path, ])
python
def update_machine_state(state_path): """Update the machine state using the provided state declaration.""" charmhelpers.contrib.templating.contexts.juju_state_to_yaml( salt_grains_path) subprocess.check_call([ 'salt-call', '--local', 'state.template', state_path, ])
[ "def", "update_machine_state", "(", "state_path", ")", ":", "charmhelpers", ".", "contrib", ".", "templating", ".", "contexts", ".", "juju_state_to_yaml", "(", "salt_grains_path", ")", "subprocess", ".", "check_call", "(", "[", "'salt-call'", ",", "'--local'", ",", "'state.template'", ",", "state_path", ",", "]", ")" ]
Update the machine state using the provided state declaration.
[ "Update", "the", "machine", "state", "using", "the", "provided", "state", "declaration", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/saltstack/__init__.py#L107-L116
12,484
juju/charm-helpers
charmhelpers/contrib/storage/linux/ceph.py
pool_exists
def pool_exists(service, name): """Check to see if a RADOS pool already exists.""" try: out = check_output(['rados', '--id', service, 'lspools']) if six.PY3: out = out.decode('UTF-8') except CalledProcessError: return False return name in out.split()
python
def pool_exists(service, name): """Check to see if a RADOS pool already exists.""" try: out = check_output(['rados', '--id', service, 'lspools']) if six.PY3: out = out.decode('UTF-8') except CalledProcessError: return False return name in out.split()
[ "def", "pool_exists", "(", "service", ",", "name", ")", ":", "try", ":", "out", "=", "check_output", "(", "[", "'rados'", ",", "'--id'", ",", "service", ",", "'lspools'", "]", ")", "if", "six", ".", "PY3", ":", "out", "=", "out", ".", "decode", "(", "'UTF-8'", ")", "except", "CalledProcessError", ":", "return", "False", "return", "name", "in", "out", ".", "split", "(", ")" ]
Check to see if a RADOS pool already exists.
[ "Check", "to", "see", "if", "a", "RADOS", "pool", "already", "exists", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/storage/linux/ceph.py#L753-L762
12,485
juju/charm-helpers
charmhelpers/contrib/storage/linux/ceph.py
install
def install(): """Basic Ceph client installation.""" ceph_dir = "/etc/ceph" if not os.path.exists(ceph_dir): os.mkdir(ceph_dir) apt_install('ceph-common', fatal=True)
python
def install(): """Basic Ceph client installation.""" ceph_dir = "/etc/ceph" if not os.path.exists(ceph_dir): os.mkdir(ceph_dir) apt_install('ceph-common', fatal=True)
[ "def", "install", "(", ")", ":", "ceph_dir", "=", "\"/etc/ceph\"", "if", "not", "os", ".", "path", ".", "exists", "(", "ceph_dir", ")", ":", "os", ".", "mkdir", "(", "ceph_dir", ")", "apt_install", "(", "'ceph-common'", ",", "fatal", "=", "True", ")" ]
Basic Ceph client installation.
[ "Basic", "Ceph", "client", "installation", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/storage/linux/ceph.py#L787-L793
12,486
juju/charm-helpers
charmhelpers/contrib/storage/linux/ceph.py
rbd_exists
def rbd_exists(service, pool, rbd_img): """Check to see if a RADOS block device exists.""" try: out = check_output(['rbd', 'list', '--id', service, '--pool', pool]) if six.PY3: out = out.decode('UTF-8') except CalledProcessError: return False return rbd_img in out
python
def rbd_exists(service, pool, rbd_img): """Check to see if a RADOS block device exists.""" try: out = check_output(['rbd', 'list', '--id', service, '--pool', pool]) if six.PY3: out = out.decode('UTF-8') except CalledProcessError: return False return rbd_img in out
[ "def", "rbd_exists", "(", "service", ",", "pool", ",", "rbd_img", ")", ":", "try", ":", "out", "=", "check_output", "(", "[", "'rbd'", ",", "'list'", ",", "'--id'", ",", "service", ",", "'--pool'", ",", "pool", "]", ")", "if", "six", ".", "PY3", ":", "out", "=", "out", ".", "decode", "(", "'UTF-8'", ")", "except", "CalledProcessError", ":", "return", "False", "return", "rbd_img", "in", "out" ]
Check to see if a RADOS block device exists.
[ "Check", "to", "see", "if", "a", "RADOS", "block", "device", "exists", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/storage/linux/ceph.py#L796-L806
12,487
juju/charm-helpers
charmhelpers/contrib/storage/linux/ceph.py
create_rbd_image
def create_rbd_image(service, pool, image, sizemb): """Create a new RADOS block device.""" cmd = ['rbd', 'create', image, '--size', str(sizemb), '--id', service, '--pool', pool] check_call(cmd)
python
def create_rbd_image(service, pool, image, sizemb): """Create a new RADOS block device.""" cmd = ['rbd', 'create', image, '--size', str(sizemb), '--id', service, '--pool', pool] check_call(cmd)
[ "def", "create_rbd_image", "(", "service", ",", "pool", ",", "image", ",", "sizemb", ")", ":", "cmd", "=", "[", "'rbd'", ",", "'create'", ",", "image", ",", "'--size'", ",", "str", "(", "sizemb", ")", ",", "'--id'", ",", "service", ",", "'--pool'", ",", "pool", "]", "check_call", "(", "cmd", ")" ]
Create a new RADOS block device.
[ "Create", "a", "new", "RADOS", "block", "device", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/storage/linux/ceph.py#L809-L813
12,488
juju/charm-helpers
charmhelpers/contrib/storage/linux/ceph.py
set_app_name_for_pool
def set_app_name_for_pool(client, pool, name): """ Calls `osd pool application enable` for the specified pool name :param client: Name of the ceph client to use :type client: str :param pool: Pool to set app name for :type pool: str :param name: app name for the specified pool :type name: str :raises: CalledProcessError if ceph call fails """ if cmp_pkgrevno('ceph-common', '12.0.0') >= 0: cmd = ['ceph', '--id', client, 'osd', 'pool', 'application', 'enable', pool, name] check_call(cmd)
python
def set_app_name_for_pool(client, pool, name): """ Calls `osd pool application enable` for the specified pool name :param client: Name of the ceph client to use :type client: str :param pool: Pool to set app name for :type pool: str :param name: app name for the specified pool :type name: str :raises: CalledProcessError if ceph call fails """ if cmp_pkgrevno('ceph-common', '12.0.0') >= 0: cmd = ['ceph', '--id', client, 'osd', 'pool', 'application', 'enable', pool, name] check_call(cmd)
[ "def", "set_app_name_for_pool", "(", "client", ",", "pool", ",", "name", ")", ":", "if", "cmp_pkgrevno", "(", "'ceph-common'", ",", "'12.0.0'", ")", ">=", "0", ":", "cmd", "=", "[", "'ceph'", ",", "'--id'", ",", "client", ",", "'osd'", ",", "'pool'", ",", "'application'", ",", "'enable'", ",", "pool", ",", "name", "]", "check_call", "(", "cmd", ")" ]
Calls `osd pool application enable` for the specified pool name :param client: Name of the ceph client to use :type client: str :param pool: Pool to set app name for :type pool: str :param name: app name for the specified pool :type name: str :raises: CalledProcessError if ceph call fails
[ "Calls", "osd", "pool", "application", "enable", "for", "the", "specified", "pool", "name" ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/storage/linux/ceph.py#L825-L841
12,489
juju/charm-helpers
charmhelpers/contrib/storage/linux/ceph.py
create_pool
def create_pool(service, name, replicas=3, pg_num=None): """Create a new RADOS pool.""" if pool_exists(service, name): log("Ceph pool {} already exists, skipping creation".format(name), level=WARNING) return if not pg_num: # Calculate the number of placement groups based # on upstream recommended best practices. osds = get_osds(service) if osds: pg_num = (len(osds) * 100 // replicas) else: # NOTE(james-page): Default to 200 for older ceph versions # which don't support OSD query from cli pg_num = 200 cmd = ['ceph', '--id', service, 'osd', 'pool', 'create', name, str(pg_num)] check_call(cmd) update_pool(service, name, settings={'size': str(replicas)})
python
def create_pool(service, name, replicas=3, pg_num=None): """Create a new RADOS pool.""" if pool_exists(service, name): log("Ceph pool {} already exists, skipping creation".format(name), level=WARNING) return if not pg_num: # Calculate the number of placement groups based # on upstream recommended best practices. osds = get_osds(service) if osds: pg_num = (len(osds) * 100 // replicas) else: # NOTE(james-page): Default to 200 for older ceph versions # which don't support OSD query from cli pg_num = 200 cmd = ['ceph', '--id', service, 'osd', 'pool', 'create', name, str(pg_num)] check_call(cmd) update_pool(service, name, settings={'size': str(replicas)})
[ "def", "create_pool", "(", "service", ",", "name", ",", "replicas", "=", "3", ",", "pg_num", "=", "None", ")", ":", "if", "pool_exists", "(", "service", ",", "name", ")", ":", "log", "(", "\"Ceph pool {} already exists, skipping creation\"", ".", "format", "(", "name", ")", ",", "level", "=", "WARNING", ")", "return", "if", "not", "pg_num", ":", "# Calculate the number of placement groups based", "# on upstream recommended best practices.", "osds", "=", "get_osds", "(", "service", ")", "if", "osds", ":", "pg_num", "=", "(", "len", "(", "osds", ")", "*", "100", "//", "replicas", ")", "else", ":", "# NOTE(james-page): Default to 200 for older ceph versions", "# which don't support OSD query from cli", "pg_num", "=", "200", "cmd", "=", "[", "'ceph'", ",", "'--id'", ",", "service", ",", "'osd'", ",", "'pool'", ",", "'create'", ",", "name", ",", "str", "(", "pg_num", ")", "]", "check_call", "(", "cmd", ")", "update_pool", "(", "service", ",", "name", ",", "settings", "=", "{", "'size'", ":", "str", "(", "replicas", ")", "}", ")" ]
Create a new RADOS pool.
[ "Create", "a", "new", "RADOS", "pool", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/storage/linux/ceph.py#L844-L865
12,490
juju/charm-helpers
charmhelpers/contrib/storage/linux/ceph.py
add_key
def add_key(service, key): """ Add a key to a keyring. Creates the keyring if it doesn't already exist. Logs and returns if the key is already in the keyring. """ keyring = _keyring_path(service) if os.path.exists(keyring): with open(keyring, 'r') as ring: if key in ring.read(): log('Ceph keyring exists at %s and has not changed.' % keyring, level=DEBUG) return log('Updating existing keyring %s.' % keyring, level=DEBUG) cmd = ['ceph-authtool', keyring, '--create-keyring', '--name=client.{}'.format(service), '--add-key={}'.format(key)] check_call(cmd) log('Created new ceph keyring at %s.' % keyring, level=DEBUG)
python
def add_key(service, key): """ Add a key to a keyring. Creates the keyring if it doesn't already exist. Logs and returns if the key is already in the keyring. """ keyring = _keyring_path(service) if os.path.exists(keyring): with open(keyring, 'r') as ring: if key in ring.read(): log('Ceph keyring exists at %s and has not changed.' % keyring, level=DEBUG) return log('Updating existing keyring %s.' % keyring, level=DEBUG) cmd = ['ceph-authtool', keyring, '--create-keyring', '--name=client.{}'.format(service), '--add-key={}'.format(key)] check_call(cmd) log('Created new ceph keyring at %s.' % keyring, level=DEBUG)
[ "def", "add_key", "(", "service", ",", "key", ")", ":", "keyring", "=", "_keyring_path", "(", "service", ")", "if", "os", ".", "path", ".", "exists", "(", "keyring", ")", ":", "with", "open", "(", "keyring", ",", "'r'", ")", "as", "ring", ":", "if", "key", "in", "ring", ".", "read", "(", ")", ":", "log", "(", "'Ceph keyring exists at %s and has not changed.'", "%", "keyring", ",", "level", "=", "DEBUG", ")", "return", "log", "(", "'Updating existing keyring %s.'", "%", "keyring", ",", "level", "=", "DEBUG", ")", "cmd", "=", "[", "'ceph-authtool'", ",", "keyring", ",", "'--create-keyring'", ",", "'--name=client.{}'", ".", "format", "(", "service", ")", ",", "'--add-key={}'", ".", "format", "(", "key", ")", "]", "check_call", "(", "cmd", ")", "log", "(", "'Created new ceph keyring at %s.'", "%", "keyring", ",", "level", "=", "DEBUG", ")" ]
Add a key to a keyring. Creates the keyring if it doesn't already exist. Logs and returns if the key is already in the keyring.
[ "Add", "a", "key", "to", "a", "keyring", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/storage/linux/ceph.py#L883-L903
12,491
juju/charm-helpers
charmhelpers/contrib/storage/linux/ceph.py
delete_keyring
def delete_keyring(service): """Delete an existing Ceph keyring.""" keyring = _keyring_path(service) if not os.path.exists(keyring): log('Keyring does not exist at %s' % keyring, level=WARNING) return os.remove(keyring) log('Deleted ring at %s.' % keyring, level=INFO)
python
def delete_keyring(service): """Delete an existing Ceph keyring.""" keyring = _keyring_path(service) if not os.path.exists(keyring): log('Keyring does not exist at %s' % keyring, level=WARNING) return os.remove(keyring) log('Deleted ring at %s.' % keyring, level=INFO)
[ "def", "delete_keyring", "(", "service", ")", ":", "keyring", "=", "_keyring_path", "(", "service", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "keyring", ")", ":", "log", "(", "'Keyring does not exist at %s'", "%", "keyring", ",", "level", "=", "WARNING", ")", "return", "os", ".", "remove", "(", "keyring", ")", "log", "(", "'Deleted ring at %s.'", "%", "keyring", ",", "level", "=", "INFO", ")" ]
Delete an existing Ceph keyring.
[ "Delete", "an", "existing", "Ceph", "keyring", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/storage/linux/ceph.py#L911-L919
12,492
juju/charm-helpers
charmhelpers/contrib/storage/linux/ceph.py
create_key_file
def create_key_file(service, key): """Create a file containing key.""" keyfile = _keyfile_path(service) if os.path.exists(keyfile): log('Keyfile exists at %s.' % keyfile, level=WARNING) return with open(keyfile, 'w') as fd: fd.write(key) log('Created new keyfile at %s.' % keyfile, level=INFO)
python
def create_key_file(service, key): """Create a file containing key.""" keyfile = _keyfile_path(service) if os.path.exists(keyfile): log('Keyfile exists at %s.' % keyfile, level=WARNING) return with open(keyfile, 'w') as fd: fd.write(key) log('Created new keyfile at %s.' % keyfile, level=INFO)
[ "def", "create_key_file", "(", "service", ",", "key", ")", ":", "keyfile", "=", "_keyfile_path", "(", "service", ")", "if", "os", ".", "path", ".", "exists", "(", "keyfile", ")", ":", "log", "(", "'Keyfile exists at %s.'", "%", "keyfile", ",", "level", "=", "WARNING", ")", "return", "with", "open", "(", "keyfile", ",", "'w'", ")", "as", "fd", ":", "fd", ".", "write", "(", "key", ")", "log", "(", "'Created new keyfile at %s.'", "%", "keyfile", ",", "level", "=", "INFO", ")" ]
Create a file containing key.
[ "Create", "a", "file", "containing", "key", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/storage/linux/ceph.py#L922-L932
12,493
juju/charm-helpers
charmhelpers/contrib/storage/linux/ceph.py
get_ceph_nodes
def get_ceph_nodes(relation='ceph'): """Query named relation to determine current nodes.""" hosts = [] for r_id in relation_ids(relation): for unit in related_units(r_id): hosts.append(relation_get('private-address', unit=unit, rid=r_id)) return hosts
python
def get_ceph_nodes(relation='ceph'): """Query named relation to determine current nodes.""" hosts = [] for r_id in relation_ids(relation): for unit in related_units(r_id): hosts.append(relation_get('private-address', unit=unit, rid=r_id)) return hosts
[ "def", "get_ceph_nodes", "(", "relation", "=", "'ceph'", ")", ":", "hosts", "=", "[", "]", "for", "r_id", "in", "relation_ids", "(", "relation", ")", ":", "for", "unit", "in", "related_units", "(", "r_id", ")", ":", "hosts", ".", "append", "(", "relation_get", "(", "'private-address'", ",", "unit", "=", "unit", ",", "rid", "=", "r_id", ")", ")", "return", "hosts" ]
Query named relation to determine current nodes.
[ "Query", "named", "relation", "to", "determine", "current", "nodes", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/storage/linux/ceph.py#L935-L942
12,494
juju/charm-helpers
charmhelpers/contrib/storage/linux/ceph.py
configure
def configure(service, key, auth, use_syslog): """Perform basic configuration of Ceph.""" add_key(service, key) create_key_file(service, key) hosts = get_ceph_nodes() with open('/etc/ceph/ceph.conf', 'w') as ceph_conf: ceph_conf.write(CEPH_CONF.format(auth=auth, keyring=_keyring_path(service), mon_hosts=",".join(map(str, hosts)), use_syslog=use_syslog)) modprobe('rbd')
python
def configure(service, key, auth, use_syslog): """Perform basic configuration of Ceph.""" add_key(service, key) create_key_file(service, key) hosts = get_ceph_nodes() with open('/etc/ceph/ceph.conf', 'w') as ceph_conf: ceph_conf.write(CEPH_CONF.format(auth=auth, keyring=_keyring_path(service), mon_hosts=",".join(map(str, hosts)), use_syslog=use_syslog)) modprobe('rbd')
[ "def", "configure", "(", "service", ",", "key", ",", "auth", ",", "use_syslog", ")", ":", "add_key", "(", "service", ",", "key", ")", "create_key_file", "(", "service", ",", "key", ")", "hosts", "=", "get_ceph_nodes", "(", ")", "with", "open", "(", "'/etc/ceph/ceph.conf'", ",", "'w'", ")", "as", "ceph_conf", ":", "ceph_conf", ".", "write", "(", "CEPH_CONF", ".", "format", "(", "auth", "=", "auth", ",", "keyring", "=", "_keyring_path", "(", "service", ")", ",", "mon_hosts", "=", "\",\"", ".", "join", "(", "map", "(", "str", ",", "hosts", ")", ")", ",", "use_syslog", "=", "use_syslog", ")", ")", "modprobe", "(", "'rbd'", ")" ]
Perform basic configuration of Ceph.
[ "Perform", "basic", "configuration", "of", "Ceph", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/storage/linux/ceph.py#L945-L955
12,495
juju/charm-helpers
charmhelpers/contrib/storage/linux/ceph.py
image_mapped
def image_mapped(name): """Determine whether a RADOS block device is mapped locally.""" try: out = check_output(['rbd', 'showmapped']) if six.PY3: out = out.decode('UTF-8') except CalledProcessError: return False return name in out
python
def image_mapped(name): """Determine whether a RADOS block device is mapped locally.""" try: out = check_output(['rbd', 'showmapped']) if six.PY3: out = out.decode('UTF-8') except CalledProcessError: return False return name in out
[ "def", "image_mapped", "(", "name", ")", ":", "try", ":", "out", "=", "check_output", "(", "[", "'rbd'", ",", "'showmapped'", "]", ")", "if", "six", ".", "PY3", ":", "out", "=", "out", ".", "decode", "(", "'UTF-8'", ")", "except", "CalledProcessError", ":", "return", "False", "return", "name", "in", "out" ]
Determine whether a RADOS block device is mapped locally.
[ "Determine", "whether", "a", "RADOS", "block", "device", "is", "mapped", "locally", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/storage/linux/ceph.py#L958-L967
12,496
juju/charm-helpers
charmhelpers/contrib/storage/linux/ceph.py
map_block_storage
def map_block_storage(service, pool, image): """Map a RADOS block device for local use.""" cmd = [ 'rbd', 'map', '{}/{}'.format(pool, image), '--user', service, '--secret', _keyfile_path(service), ] check_call(cmd)
python
def map_block_storage(service, pool, image): """Map a RADOS block device for local use.""" cmd = [ 'rbd', 'map', '{}/{}'.format(pool, image), '--user', service, '--secret', _keyfile_path(service), ] check_call(cmd)
[ "def", "map_block_storage", "(", "service", ",", "pool", ",", "image", ")", ":", "cmd", "=", "[", "'rbd'", ",", "'map'", ",", "'{}/{}'", ".", "format", "(", "pool", ",", "image", ")", ",", "'--user'", ",", "service", ",", "'--secret'", ",", "_keyfile_path", "(", "service", ")", ",", "]", "check_call", "(", "cmd", ")" ]
Map a RADOS block device for local use.
[ "Map", "a", "RADOS", "block", "device", "for", "local", "use", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/storage/linux/ceph.py#L970-L981
12,497
juju/charm-helpers
charmhelpers/contrib/storage/linux/ceph.py
make_filesystem
def make_filesystem(blk_device, fstype='ext4', timeout=10): """Make a new filesystem on the specified block device.""" count = 0 e_noent = os.errno.ENOENT while not os.path.exists(blk_device): if count >= timeout: log('Gave up waiting on block device %s' % blk_device, level=ERROR) raise IOError(e_noent, os.strerror(e_noent), blk_device) log('Waiting for block device %s to appear' % blk_device, level=DEBUG) count += 1 time.sleep(1) else: log('Formatting block device %s as filesystem %s.' % (blk_device, fstype), level=INFO) check_call(['mkfs', '-t', fstype, blk_device])
python
def make_filesystem(blk_device, fstype='ext4', timeout=10): """Make a new filesystem on the specified block device.""" count = 0 e_noent = os.errno.ENOENT while not os.path.exists(blk_device): if count >= timeout: log('Gave up waiting on block device %s' % blk_device, level=ERROR) raise IOError(e_noent, os.strerror(e_noent), blk_device) log('Waiting for block device %s to appear' % blk_device, level=DEBUG) count += 1 time.sleep(1) else: log('Formatting block device %s as filesystem %s.' % (blk_device, fstype), level=INFO) check_call(['mkfs', '-t', fstype, blk_device])
[ "def", "make_filesystem", "(", "blk_device", ",", "fstype", "=", "'ext4'", ",", "timeout", "=", "10", ")", ":", "count", "=", "0", "e_noent", "=", "os", ".", "errno", ".", "ENOENT", "while", "not", "os", ".", "path", ".", "exists", "(", "blk_device", ")", ":", "if", "count", ">=", "timeout", ":", "log", "(", "'Gave up waiting on block device %s'", "%", "blk_device", ",", "level", "=", "ERROR", ")", "raise", "IOError", "(", "e_noent", ",", "os", ".", "strerror", "(", "e_noent", ")", ",", "blk_device", ")", "log", "(", "'Waiting for block device %s to appear'", "%", "blk_device", ",", "level", "=", "DEBUG", ")", "count", "+=", "1", "time", ".", "sleep", "(", "1", ")", "else", ":", "log", "(", "'Formatting block device %s as filesystem %s.'", "%", "(", "blk_device", ",", "fstype", ")", ",", "level", "=", "INFO", ")", "check_call", "(", "[", "'mkfs'", ",", "'-t'", ",", "fstype", ",", "blk_device", "]", ")" ]
Make a new filesystem on the specified block device.
[ "Make", "a", "new", "filesystem", "on", "the", "specified", "block", "device", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/storage/linux/ceph.py#L989-L1006
12,498
juju/charm-helpers
charmhelpers/contrib/storage/linux/ceph.py
place_data_on_block_device
def place_data_on_block_device(blk_device, data_src_dst): """Migrate data in data_src_dst to blk_device and then remount.""" # mount block device into /mnt mount(blk_device, '/mnt') # copy data to /mnt copy_files(data_src_dst, '/mnt') # umount block device umount('/mnt') # Grab user/group ID's from original source _dir = os.stat(data_src_dst) uid = _dir.st_uid gid = _dir.st_gid # re-mount where the data should originally be # TODO: persist is currently a NO-OP in core.host mount(blk_device, data_src_dst, persist=True) # ensure original ownership of new mount. os.chown(data_src_dst, uid, gid)
python
def place_data_on_block_device(blk_device, data_src_dst): """Migrate data in data_src_dst to blk_device and then remount.""" # mount block device into /mnt mount(blk_device, '/mnt') # copy data to /mnt copy_files(data_src_dst, '/mnt') # umount block device umount('/mnt') # Grab user/group ID's from original source _dir = os.stat(data_src_dst) uid = _dir.st_uid gid = _dir.st_gid # re-mount where the data should originally be # TODO: persist is currently a NO-OP in core.host mount(blk_device, data_src_dst, persist=True) # ensure original ownership of new mount. os.chown(data_src_dst, uid, gid)
[ "def", "place_data_on_block_device", "(", "blk_device", ",", "data_src_dst", ")", ":", "# mount block device into /mnt", "mount", "(", "blk_device", ",", "'/mnt'", ")", "# copy data to /mnt", "copy_files", "(", "data_src_dst", ",", "'/mnt'", ")", "# umount block device", "umount", "(", "'/mnt'", ")", "# Grab user/group ID's from original source", "_dir", "=", "os", ".", "stat", "(", "data_src_dst", ")", "uid", "=", "_dir", ".", "st_uid", "gid", "=", "_dir", ".", "st_gid", "# re-mount where the data should originally be", "# TODO: persist is currently a NO-OP in core.host", "mount", "(", "blk_device", ",", "data_src_dst", ",", "persist", "=", "True", ")", "# ensure original ownership of new mount.", "os", ".", "chown", "(", "data_src_dst", ",", "uid", ",", "gid", ")" ]
Migrate data in data_src_dst to blk_device and then remount.
[ "Migrate", "data", "in", "data_src_dst", "to", "blk_device", "and", "then", "remount", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/storage/linux/ceph.py#L1009-L1025
12,499
juju/charm-helpers
charmhelpers/contrib/storage/linux/ceph.py
ensure_ceph_keyring
def ensure_ceph_keyring(service, user=None, group=None, relation='ceph', key=None): """Ensures a ceph keyring is created for a named service and optionally ensures user and group ownership. @returns boolean: Flag to indicate whether a key was successfully written to disk based on either relation data or a supplied key """ if not key: for rid in relation_ids(relation): for unit in related_units(rid): key = relation_get('key', rid=rid, unit=unit) if key: break if not key: return False add_key(service=service, key=key) keyring = _keyring_path(service) if user and group: check_call(['chown', '%s.%s' % (user, group), keyring]) return True
python
def ensure_ceph_keyring(service, user=None, group=None, relation='ceph', key=None): """Ensures a ceph keyring is created for a named service and optionally ensures user and group ownership. @returns boolean: Flag to indicate whether a key was successfully written to disk based on either relation data or a supplied key """ if not key: for rid in relation_ids(relation): for unit in related_units(rid): key = relation_get('key', rid=rid, unit=unit) if key: break if not key: return False add_key(service=service, key=key) keyring = _keyring_path(service) if user and group: check_call(['chown', '%s.%s' % (user, group), keyring]) return True
[ "def", "ensure_ceph_keyring", "(", "service", ",", "user", "=", "None", ",", "group", "=", "None", ",", "relation", "=", "'ceph'", ",", "key", "=", "None", ")", ":", "if", "not", "key", ":", "for", "rid", "in", "relation_ids", "(", "relation", ")", ":", "for", "unit", "in", "related_units", "(", "rid", ")", ":", "key", "=", "relation_get", "(", "'key'", ",", "rid", "=", "rid", ",", "unit", "=", "unit", ")", "if", "key", ":", "break", "if", "not", "key", ":", "return", "False", "add_key", "(", "service", "=", "service", ",", "key", "=", "key", ")", "keyring", "=", "_keyring_path", "(", "service", ")", "if", "user", "and", "group", ":", "check_call", "(", "[", "'chown'", ",", "'%s.%s'", "%", "(", "user", ",", "group", ")", ",", "keyring", "]", ")", "return", "True" ]
Ensures a ceph keyring is created for a named service and optionally ensures user and group ownership. @returns boolean: Flag to indicate whether a key was successfully written to disk based on either relation data or a supplied key
[ "Ensures", "a", "ceph", "keyring", "is", "created", "for", "a", "named", "service", "and", "optionally", "ensures", "user", "and", "group", "ownership", "." ]
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/storage/linux/ceph.py#L1092-L1115