Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def walk(self, action, doc=None):
# Infer the document thanks to .parent magic
if doc is None:
doc = self.doc
# First iterate over children
for child in self._children:
obj = getattr(self, child)
... | [
"\n Walk through the element and all its children (sub-elements),\n applying the provided function ``action``.\n\n A trivial example would be:\n\n .. code-block:: python\n\n from panflute import *\n\n def no_action(elem, doc):\n pass\n\n do... |
Please provide a description of the function:def stdio(filters=None, search_dirs=None, data_dir=True, sys_path=True, panfl_=False, input_stream=None, output_stream=None):
doc = load(input_stream)
# meta = doc.metadata # Local variable 'meta' value is not used
verbose = doc.get_metadata('panflute-verbo... | [
"\n Reads JSON from stdin and second CLI argument:\n ``sys.argv[1]``. Dumps JSON doc to the stdout.\n\n :param filters: Union[List[str], None]\n if None then read from metadata\n :param search_dirs: Union[List[str], None]\n if None then read from metadata\n :param data_dir: bool\n :p... |
Please provide a description of the function:def panfl(filters, to, search_dirs, data_dir, sys_path):
if to is None:
if (len(filters) > 1) or search_dirs or not sys_path or data_dir:
raise ValueError('When no `--to` option then Pandoc filter mode assumed and ' +
... | [
"\n Allows Panflute to be run as a command line executable:\n\n * to be used in Pandoctools shell scripts as Pandoc filter with\n multiple arguments (should have -t/--to option in this case):\n ``pandoc -t json | panfl -t markdown foo.bar | pandoc -f json``\n\n * to be used as a Pandoc filter (in... |
Please provide a description of the function:def autorun_filters(filters, doc, search_dirs, verbose):
def remove_py(s):
return s[:-3] if s.endswith('.py') else s
filter_paths = []
for filter_ in filters:
filter_exp = p.normpath(p.expanduser(p.expandvars(filter_)))
if filte... | [
"\n :param filters: list of str\n :param doc: panflute.Doc\n :param search_dirs: list of str\n :param verbose: bool\n :return: panflute.Doc\n "
] |
Please provide a description of the function:def search(self, term: str, case_sensitive: bool = False) -> 'PrettyDir':
if case_sensitive:
return PrettyDir(
self.obj, [pattr for pattr in self.pattrs if term in pattr.name]
)
else:
term = term.lo... | [
"Searches for names that match some pattern.\n\n Args:\n term: String used to match names. A name is returned if it matches\n the whole search term.\n case_sensitive: Boolean to match case or not, default is False\n (case insensitive).\n\n Return:\n ... |
Please provide a description of the function:def properties(self) -> 'PrettyDir':
return PrettyDir(
self.obj,
[
pattr
for pattr in self.pattrs
if category_match(pattr.category, AttrCategory.PROPERTY)
],
) | [
"Returns all properties of the inspected object.\n\n Note that \"properties\" can mean \"variables\".\n "
] |
Please provide a description of the function:def methods(self) -> 'PrettyDir':
return PrettyDir(
self.obj,
[
pattr
for pattr in self.pattrs
if category_match(pattr.category, AttrCategory.FUNCTION)
],
) | [
"Returns all methods of the inspected object.\n\n Note that \"methods\" can mean \"functions\" when inspecting a module.\n "
] |
Please provide a description of the function:def public(self) -> 'PrettyDir':
return PrettyDir(
self.obj, [pattr for pattr in self.pattrs if not pattr.name.startswith('_')]
) | [
"Returns public attributes of the inspected object."
] |
Please provide a description of the function:def own(self) -> 'PrettyDir':
return PrettyDir(
self.obj,
[
pattr
for pattr in self.pattrs
if pattr.name in type(self.obj).__dict__
or pattr.name in self.obj.__dict__
... | [
"Returns attributes that are not inhterited from parent classes.\n\n Now we only use a simple judgement, it is expected that many attributes\n not get returned, especially invoked on a module.\n\n For instance, there's no way to distinguish between properties that\n are initialized in in... |
Please provide a description of the function:def get_oneline_doc(self) -> str:
attr = self.attr_obj
if self.display_group == AttrCategory.DESCRIPTOR:
if isinstance(attr, property):
doc_list = ['@property with getter']
if attr.fset:
... | [
"\n Doc doesn't necessarily mean doctring. It could be anything that\n should be put after the attr's name as an explanation.\n "
] |
Please provide a description of the function:def format_pattrs(pattrs: List['api.PrettyAttribute']) -> str:
output = []
pattrs.sort(
key=lambda x: (
_FORMATTER[x.display_group].display_index,
x.display_group,
x.name,
)
)
for display_group, grouped... | [
"Generates repr string given a list of pattrs."
] |
Please provide a description of the function:def get_attr_from_dict(inspected_obj: Any, attr_name: str) -> Any:
if inspect.isclass(inspected_obj):
obj_list = [inspected_obj] + list(inspected_obj.__mro__)
else:
obj_list = [inspected_obj] + list(inspected_obj.__class__.__mro__)
for obj in... | [
"Ensures we get descriptor object instead of its return value.\n "
] |
Please provide a description of the function:def attr_category_postprocess(get_attr_category_func):
@functools.wraps(get_attr_category_func)
def wrapped(
name: str, attr: Any, obj: Any
) -> Tuple[AttrCategory, ...]:
category = get_attr_category_func(name, attr, obj)
category = l... | [
"Unifies attr_category to a tuple, add AttrCategory.SLOT if needed."
] |
Please provide a description of the function:def get_peak_mem():
'''
this returns peak memory use since process starts till the moment its called
'''
import resource
rusage_denom = 1024.
if sys.platform == 'darwin':
# ... it seems that in OSX the output is different units ...
rus... | [] |
Please provide a description of the function:def record(self, ch_node):
'''
Incremental changes
'''
rec = self.serialize_node(ch_node)
self.history.append(rec) | [] |
Please provide a description of the function:def sparse_is_desireable(lhs, rhs):
'''
Examines a pair of matrices and determines if the result of their multiplication should be sparse or not.
'''
return False
if len(lhs.shape) == 1:
return False
else:
lhs_rows, lhs_cols = lhs.shap... | [] |
Please provide a description of the function:def convert_inputs_to_sparse_if_necessary(lhs, rhs):
'''
This function checks to see if a sparse output is desireable given the inputs and if so, casts the inputs to sparse in order to make it so.
'''
if not sp.issparse(lhs) or not sp.issparse(rhs):
i... | [] |
Please provide a description of the function:def setup_objective(obj, free_variables, on_step=None, disp=True, make_dense=False):
'''
obj here can be a list of ch objects or a dict of label: ch objects. Either way, the ch
objects will be merged into one objective using a ChInputsStacked. The labels are just... | [] |
Please provide a description of the function:def minimize_dogleg(obj, free_variables, on_step=None,
maxiter=200, max_fevals=np.inf, sparse_solver='spsolve',
disp=True, e_1=1e-15, e_2=1e-15, e_3=0., delta_0=None,
treat_as_dense=False):
solve = set... | [
"\"Nonlinear optimization using Powell's dogleg method.\n See Lourakis et al, 2005, ICCV '05, \"Is Levenberg-Marquardt the\n Most Efficient Optimization for Implementing Bundle Adjustment?\":\n http://www.ics.forth.gr/cvrl/publications/conferences/0201-P0401-lourakis-levenberg.pdf\n\n e_N are stopping c... |
Please provide a description of the function:def dr_wrt(self, wrt, profiler=None):
'''
Loop over free variables and delete cache for the whole tree after finished each one
'''
if wrt is self.x:
jacs = []
for fvi, freevar in enumerate(self.free_variables):
... | [] |
Please provide a description of the function:def J(self):
'''
Compute Jacobian. Analyze dr graph first to disable unnecessary caching
'''
result = self.dr_wrt(self.x, profiler=self.profiler).copy()
if self.profiler:
self.profiler.harvest()
return np.atleast_2d... | [] |
Please provide a description of the function:def sid(self):
pnames = list(self.terms)+list(self.dterms)
pnames.sort()
return (self.__class__, tuple([(k, id(self.__dict__[k])) for k in pnames if k in self.__dict__])) | [
"Semantic id."
] |
Please provide a description of the function:def compute_dr_wrt(self,wrt):
if wrt is self: # special base case
return sp.eye(self.x.size, self.x.size)
#return np.array([[1]])
return None | [
"Default method for objects that just contain a number or ndarray"
] |
Please provide a description of the function:def show_tree_cache(self, label, current_node=None):
'''
Show tree and cache info with color represent _status
Optionally accpet current_node arg to highlight the current node we are in
'''
import os
import tempfile
imp... | [] |
Please provide a description of the function:def show_tree(self, cachelim=np.inf):
import tempfile
import subprocess
assert DEBUG, "Please use dr tree visualization functions in debug mode"
def string_for(self, my_name):
if hasattr(self, 'label'):
m... | [
"Cachelim is in Mb. For any cached jacobians above cachelim, they are also added to the graph. "
] |
Please provide a description of the function:def tree_iterator(self, visited=None, path=None):
'''
Generator function that traverse the dr tree start from this node (self).
'''
if visited is None:
visited = set()
if self not in visited:
if path and isinst... | [] |
Please provide a description of the function:def get_ubuntu_release_from_sentry(self, sentry_unit):
msg = None
cmd = 'lsb_release -cs'
release, code = sentry_unit.run(cmd)
if code == 0:
self.log.debug('{} lsb_release: {}'.format(
sentry_unit.info['uni... | [
"Get Ubuntu release codename from sentry unit.\n\n :param sentry_unit: amulet sentry/service unit pointer\n :returns: list of strings - release codename, failure message\n "
] |
Please provide a description of the function:def validate_services(self, commands):
self.log.debug('Checking status of system services...')
# /!\ DEPRECATION WARNING (beisner):
# New and existing tests should be rewritten to use
# validate_services_by_name() as it is aware of i... | [
"Validate that lists of commands succeed on service units. Can be\n used to verify system services are running on the corresponding\n service units.\n\n :param commands: dict with sentry keys and arbitrary command list vals\n :returns: None if successful, Failure string message ot... |
Please provide a description of the function:def validate_services_by_name(self, sentry_services):
self.log.debug('Checking status of system services...')
# Point at which systemd became a thing
systemd_switch = self.ubuntu_releases.index('vivid')
for sentry_unit, services_lis... | [
"Validate system service status by service name, automatically\n detecting init system based on Ubuntu release codename.\n\n :param sentry_services: dict with sentry keys and svc list values\n :returns: None if successful, Failure string message otherwise\n "
] |
Please provide a description of the function:def _get_config(self, unit, filename):
file_contents = unit.file_contents(filename)
# NOTE(beisner): by default, ConfigParser does not handle options
# with no value, such as the flags used in the mysql my.cnf file.
# https://bugs.p... | [
"Get a ConfigParser object for parsing a unit's config file."
] |
Please provide a description of the function:def validate_config_data(self, sentry_unit, config_file, section,
expected):
self.log.debug('Validating config file data ({} in {} on {})'
'...'.format(section, config_file,
... | [
"Validate config file data.\n\n Verify that the specified section of the config file contains\n the expected option key:value pairs.\n\n Compare expected dictionary data vs actual dictionary data.\n The values in the 'expected' dictionary can be strings, bools, ints,\n ... |
Please provide a description of the function:def _validate_dict_data(self, expected, actual):
self.log.debug('actual: {}'.format(repr(actual)))
self.log.debug('expected: {}'.format(repr(expected)))
for k, v in six.iteritems(expected):
if k in actual:
if (isi... | [
"Validate dictionary data.\n\n Compare expected dictionary data vs actual dictionary data.\n The values in the 'expected' dictionary can be strings, bools, ints,\n longs, or can be a function that evaluates a variable and returns a\n bool.\n "
] |
Please provide a description of the function:def validate_relation_data(self, sentry_unit, relation, expected):
actual = sentry_unit.relation(relation[0], relation[1])
return self._validate_dict_data(expected, actual) | [
"Validate actual relation data based on expected relation data."
] |
Please provide a description of the function:def _validate_list_data(self, expected, actual):
for e in expected:
if e not in actual:
return "expected item {} not found in actual list".format(e)
return None | [
"Compare expected list vs actual list data."
] |
Please provide a description of the function:def _get_proc_start_time(self, sentry_unit, service, pgrep_full=None):
pid_list = self.get_process_id_list(
sentry_unit, service, pgrep_full=pgrep_full)
pid = pid_list[0]
proc_dir = '/proc/{}'.format(pid)
self.log.debug('P... | [
"Get start time of a process based on the last modification time\n of the /proc/pid directory.\n\n :sentry_unit: The sentry unit to check for the service on\n :service: service name to look for in process table\n :pgrep_full: [Deprecated] Use full command line search mode with pgre... |
Please provide a description of the function: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_servic... | [
"Check if service was restarted.\n\n Compare a service's start time vs a file's last modification time\n (such as a config file for that service) to determine if the service\n has been restarted.\n "
] |
Please provide a description of the function: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... | [
"Check if service was been started after a given time.\n\n Args:\n sentry_unit (sentry): The sentry unit to check for the service on\n mtime (float): The epoch time to check against\n service (string): service name to look for in process table\n pgrep_full: [Deprecated] Us... |
Please provide a description of the function: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 upd... | [
"Check if file was modified after a given time.\n\n Args:\n sentry_unit (sentry): The sentry unit to check the file mtime on\n filename (string): The file to check mtime of\n mtime (float): The epoch time to check against\n sleep_time (int): Initial sleep time (s) before l... |
Please provide a description of the function: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\n\n Args:\n sentry_unit (sentry): The sentry unit to check for the service on\n mtime (float): The epoch time to check against\n service (string): service name to look for in process table\n filename (string): The file to ch... |
Please provide a description of the function: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."
] |
Please provide a description of the function: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)))
... | [
"Check that all commands in a list exit zero on all\n sentry units in a list.\n\n :param commands: list of bash commands\n :param sentry_units: list of sentry unit pointers\n :returns: None if successful; Failure message otherwise\n "
] |
Please provide a description of the function:def get_process_id_list(self, sentry_unit, process_name,
expect_success=True, pgrep_full=False):
if pgrep_full:
cmd = 'pgrep -f "{}"'.format(process_name)
else:
cmd = 'pidof -x "{}"'.format(process_... | [
"Get a list of process ID(s) from a single sentry juju unit\n for a single process name.\n\n :param sentry_unit: Amulet sentry instance (juju unit)\n :param process_name: Process name\n :param expect_success: If False, expect the PID to be missing,\n raise if it is present.\n ... |
Please provide a description of the function: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 proces... | [
"Construct a dict containing unit sentries, process names, and\n process IDs.\n\n :param unit_processes: A dictionary of Amulet sentry instance\n to list of process names.\n :param expect_success: if False expect the processes to not be\n running, raise if they are.\n ... |
Please provide a description of the function: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) != ... | [
"Validate process id quantities for services on units."
] |
Please provide a description of the function: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:
... | [
"Check that all dicts within a list are identical."
] |
Please provide a description of the function:def validate_sectionless_conf(self, file_contents, expected):
for line in file_contents.split('\n'):
if '=' in line:
args = line.split('=')
if len(args) <= 1:
continue
key = args... | [
"A crude conf parser. Useful to inspect configuration files which\n do not have section headers (as would be necessary in order to use\n the configparser). Such as openstack-dashboard or rabbitmq confs."
] |
Please provide a description of the function: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 a dict of juju unit names to hostnames."
] |
Please provide a description of the function: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'],
... | [
"Run a command on a unit, return the output and exit code."
] |
Please provide a description of the function: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 {}: {}'.fo... | [
"Check if a file exists on a unit."
] |
Please provide a description of the function: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):
... | [
"Get file contents from a sentry unit. Wrap amulet file_contents\n with retry logic to address races where a file checks as existing,\n but no longer exists by the time file_contents is called.\n Return None if file not found. Optionally raise if fatal is True."
] |
Please provide a description of the function: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 ... | [
"Open a TCP socket to check for a listening sevice on a host.\n\n :param host: host name or IP address, default to localhost\n :param port: TCP port number, default to 22\n :param timeout: Connect timeout, default to 15 seconds\n :returns: True if successful, False if connect failed\n ... |
Please provide a description of the function: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)
... | [
"Open a TCP socket to check for a listening sevice on each\n listed juju unit.\n\n :param sentry_units: list of sentry unit pointers\n :param port: TCP port number, default to 22\n :param timeout: Connect timeout, default to 15 seconds\n :expect_success: True by default, set False... |
Please provide a description of the function:def run_action(self, unit_sentry, action,
_check_output=subprocess.check_output,
params=None):
self.log.warn('charmhelpers.contrib.amulet.utils.run_action has been '
'deprecated for amulet.run_actio... | [
"Translate to amulet's built in run_action(). Deprecated.\n\n Run the named action on a given unit sentry.\n\n params a dict of parameters to use\n _check_output parameter is no longer used\n\n @return action_id.\n "
] |
Please provide a description of the function: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.\n\n action_id a string action uuid\n _check_output parameter is no longer used\n "
] |
Please provide a description of the function: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"], s... | [
"Return the current service status of this unit."
] |
Please provide a description of the function:def execute(self, sql):
cursor = self.connection.cursor()
try:
cursor.execute(sql)
finally:
cursor.close() | [
"Execute arbitary SQL against the database."
] |
Please provide a description of the function: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 | [
"\n Execute arbitrary SQL select query against the database\n and return the results.\n\n :param sql: SQL select query to execute\n :type sql: string\n :returns: SQL select query result\n :rtype: list of lists\n :raises: MySQLdb.Error\n "
] |
Please provide a description of the function: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_temp... | [
"Migrate any passwords storage on disk to leader storage."
] |
Please provide a description of the function: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
... | [
"Retrieve, generate or store a mysql password for the provided\n username on disk."
] |
Please provide a description of the function: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... | [
"Generator to return keys used to store passwords in peer store.\n\n NOTE: we support both legacy and new format to support mysql\n charm prior to refactor. This is necessary to avoid LP 1451890.\n "
] |
Please provide a description of the function: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:
... | [
"Retrieve, generate or store a mysql password for the provided\n username using peer relation cluster."
] |
Please provide a description of the function:def normalize_address(self, hostname):
if config_get('prefer-ipv6'):
# TODO: add support for ipv6 dns
return hostname
if hostname != unit_get('private-address'):
return get_host_ip(hostname, fallback=hostname)
... | [
"Ensure that address returned is an IP address (i.e. not fqdn)"
] |
Please provide a description of the function: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=u... | [
"Get list of units with access grants for database with username.\n\n This is typically used to provide shared-db relations with a list of\n which units have been granted access to the given database.\n "
] |
Please provide a description of the function: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(hos... | [
"Configure access to database for username from hostname."
] |
Please provide a description of the function: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
... | [
"Convert human readable configuration options to bytes."
] |
Please provide a description of the function: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')
... | [
"Determine the default memory limit for the current service unit."
] |
Please provide a description of the function: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(' ')
... | [
"Calculate the total memory in the current service unit."
] |
Please provide a description of the function: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_timeo... | [
"Parse charm configuration and calculate values for config files."
] |
Please provide a description of the function:def persistent_modprobe(module):
with open('/etc/modules', 'r+') as modules:
if module not in modules.read():
modules.write(module + "\n") | [
"Load a kernel module and configure for auto-load on reboot."
] |
Please provide a description of the function:def loopback_devices():
'''
Parse through 'losetup -a' output to determine currently mapped
loopback devices. Output is expected to look like:
/dev/loop0: [0807]:961814 (/tmp/my.img)
:returns: dict: a dict mapping {loopback_dev: backing_file}
''... | [] |
Please provide a description of the function: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,... | [] |
Please provide a description of the function: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: Ful... | [] |
Please provide a description of the function: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_... | [
"Wrapper to ensure that settings are migrated from the peer relation.\n\n This is to support upgrading an environment that does not support\n Juju leadership election to one that does.\n\n If a setting is not extant in the leader-get but is on the relation-get\n peer rel, it is migrated and marked as su... |
Please provide a description of the function: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 NotImplem... | [
"Attempt to use leader-set if supported in the current version of Juju,\n otherwise falls back on relation-set.\n\n Note that we only attempt to use leader-set if the provided relation_id is\n a peer relation id or no relation id is provided (in which case we assume\n we are within the peer relation con... |
Please provide a description of the function: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(attr... | [
"Attempt to use leader-get if supported in the current version of Juju,\n otherwise falls back on relation-get.\n\n Note that we only attempt to use leader-get if the provided rid is a peer\n relation id or no relation id is provided (in which case we assume we are\n within the peer relation context).\n... |
Please provide a description of the function: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())... | [
"Retrieve a named key from peer relation `relation_name`."
] |
Please provide a description of the function:def peer_retrieve_by_prefix(prefix, relation_name='cluster', delimiter='_',
inc_list=None, exc_list=None):
inc_list = inc_list if inc_list else []
exc_list = exc_list if exc_list else []
peerdb_settings = peer_retrieve('-', relati... | [
" Retrieve k/v pairs given a prefix and filter using {inc,exc}_list "
] |
Please provide a description of the function:def peer_store(key, value, relation_name='cluster'):
cluster_rels = relation_ids(relation_name)
if len(cluster_rels) > 0:
cluster_rid = cluster_rels[0]
relation_set(relation_id=cluster_rid,
relation_settings={key: value})
... | [
"Store the key/value pair on the named peer relation `relation_name`."
] |
Please provide a description of the function: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 = _relat... | [
"Echo filtered attributes back onto the same relation for storage.\n\n This is a requirement to use the peerstorage module - it needs to be called\n from the peer relation's changed hook.\n\n If Juju leader support exists this will be a noop unless force is True.\n "
] |
Please provide a description of the function: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 {}
rel... | [
"Store passed-in arguments both in argument relation and in peer storage.\n\n It functions like doing relation_set() and peer_store() at the same time,\n with the same data.\n\n @param relation_id: the id of the relation to store the data on. Defaults\n to the current relation.\n ... |
Please provide a description of the function: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,
... | [
"\n Search and replaces the given pattern on filename.\n\n :param filename: relative or absolute file path.\n :param before: expression to be replaced (see 'man sed')\n :param after: expression to replace with (see 'man sed')\n :param flags: sed-compatible regex flags in example, to make\n the se... |
Please provide a description of the function:def lsb_release():
d = {}
with open('/etc/os-release', 'r') as lsb:
for l in lsb:
s = l.split('=')
if len(s) != 2:
continue
d[s[0].strip()] = s[1].strip()
return d | [
"Return /etc/os-release in a dict."
] |
Please provide a description of the function:def cmp_pkgrevno(package, revno, pkgcache=None):
if not pkgcache:
y = yum.YumBase()
packages = y.doPackageLists()
pkgcache = {i.Name: i.version for i in packages['installed']}
pkg = pkgcache[package]
if pkg > revno:
return 1
... | [
"Compare supplied revno with the revno of the installed package.\n\n * 1 => Installed revno is greater than supplied arg\n * 0 => Installed revno is the same as supplied arg\n * -1 => Installed revno is less than supplied arg\n\n This function imports YumBase function if the pkgcache argument\n is ... |
Please provide a description of the function: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 V... | [
"Returns a list of addresses SSH can list on\n\n Turns input into a sensible list of IPs SSH can listen on. Input\n must be a python list of interface names, IPs and/or CIDRs.\n\n :param listen: list of IPs, CIDRs, interface names\n\n :returns: list of IPs available on the host\n ... |
Please provide a description of the function: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_d... | [
"\n Create a jinja2.ChoiceLoader containing template dirs up to\n and including os_release. If directory template directory\n is missing at templates_dir, it will be omitted from the loader.\n templates_dir is added to the bottom of the search list as a base\n loading dir.\n\n A charm may also sh... |
Please provide a description of the function: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 | [] |
Please provide a description of the function:def register(self, config_file, contexts, config_template=None):
self.templates[config_file] = OSConfigTemplate(
config_file=config_file,
contexts=contexts,
config_template=config_template
)
log('Registered... | [
"\n Register a config file with a list of context generators to be called\n during rendering.\n config_template can be used to load a template from a string instead of\n using template loaders and template files.\n :param config_file (str): a path where a config file will be rende... |
Please provide a description of the function:def _get_template_from_string(self, ostmpl):
'''
Get a jinja2 template object from a string.
:param ostmpl: OSConfigTemplate to use as a data source.
'''
self._get_tmpl_env()
template = self._tmpl_env.from_string(ostmpl.config_... | [] |
Please provide a description of the function: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 = _o... | [
"\n Write a single config file, raises if config file is not registered.\n "
] |
Please provide a description of the function:def write_all(self):
[self.write(k) for k in six.iterkeys(self.templates)] | [
"\n Write out all registered config files.\n "
] |
Please provide a description of the function:def set_release(self, openstack_release):
self._tmpl_env = None
self.openstack_release = openstack_release
self._get_tmpl_env() | [
"\n Resets the template environment and generates a new template loader\n based on a the new openstack release.\n "
] |
Please provide a description of the function: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 interfa... | [] |
Please provide a description of the function:def get_incomplete_context_data(self, interfaces):
'''
Return dictionary of relation status of interfaces and any missing
required context data. Example:
{'amqp': {'missing_data': ['rabbitmq_password'], 'related': True},
'zero... | [] |
Please provide a description of the function: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... | [
"\n Returns True if the charm executing this is the elected cluster leader.\n\n It relies on two mechanisms to determine leadership:\n 1. If juju is sufficiently new and leadership election is supported,\n the is_leader command will be used.\n 2. If the charm is part of a corosync cluster... |
Please provide a description of the function: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 a... | [
"\n Determine leadership by querying the pacemaker Designated Controller\n "
] |
Please provide a description of the function: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, s... | [
"\n Returns True if the charm calling this is the elected corosync leader,\n as returned by calling the external \"crm\" command.\n\n We allow this operation to be retried to avoid the possibility of getting a\n false negative. See LP #1396246 for more info.\n "
] |
Please provide a description of the function: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,... | [] |
Please provide a description of the function: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."
] |
Please provide a description of the function:def https():
'''
Determines whether enough data has been provided in configuration
or relation data to configure HTTPS
.
returns: boolean
'''
use_https = config_get('use-https')
if use_https and bool_from_string(use_https):
return True... | [] |
Please provide a description of the function:def determine_api_port(public_port, singlenode_mode=False):
'''
Determine correct API server listening port based on
existence of HTTPS reverse proxy and/or haproxy.
public_port: int: standard public port for given service
singlenode_mode: boolean: Shuf... | [] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.