Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def atstart(callback, *args, **kwargs):
'''Schedule a callback to run before the main hook.
Callbacks are run in the order they were added.
This is useful for modules and classes to perform initialization
and inject behavior. In particular:
- Run c... | [] |
Please provide a description of the function:def _run_atstart():
'''Hook frameworks must invoke this before running the main hook body.'''
global _atstart
for callback, args, kwargs in _atstart:
callback(*args, **kwargs)
del _atstart[:] | [] |
Please provide a description of the function:def _run_atexit():
'''Hook frameworks must invoke this after the main hook body has
successfully completed. Do not invoke it if the hook fails.'''
global _atexit
for callback, args, kwargs in reversed(_atexit):
callback(*args, **kwargs)
del _atexi... | [] |
Please provide a description of the function:def network_get_primary_address(binding):
'''
Deprecated since Juju 2.3; use network_get()
Retrieve the primary network address for a named binding
:param binding: string. The name of a relation of extra-binding
:return: string. The primary IP address f... | [] |
Please provide a description of the function:def network_get(endpoint, relation_id=None):
if not has_juju_version('2.2'):
raise NotImplementedError(juju_version()) # earlier versions require --primary-address
if relation_id and not has_juju_version('2.3'):
raise NotImplementedError # 2.3 ... | [
"\n Retrieve the network details for a relation endpoint\n\n :param endpoint: string. The name of a relation endpoint\n :param relation_id: int. The ID of the relation for the current context.\n :return: dict. The loaded YAML output of the network-get query.\n :raise: NotImplementedError if request n... |
Please provide a description of the function:def add_metric(*args, **kwargs):
_args = ['add-metric']
_kvpairs = []
_kvpairs.extend(args)
_kvpairs.extend(['{}={}'.format(k, v) for k, v in kwargs.items()])
_args.extend(sorted(_kvpairs))
try:
subprocess.check_call(_args)
return... | [
"Add metric values. Values may be expressed with keyword arguments. For\n metric names containing dashes, these may be expressed as one or more\n 'key=value' positional arguments. May only be called from the collect-metrics\n hook."
] |
Please provide a description of the function:def iter_units_for_relation_name(relation_name):
RelatedUnit = namedtuple('RelatedUnit', 'rid, unit')
for rid in relation_ids(relation_name):
for unit in related_units(rid):
yield RelatedUnit(rid, unit) | [
"Iterate through all units in a relation\n\n Generator that iterates through all the units in a relation and yields\n a named tuple with rid and unit field names.\n\n Usage:\n data = [(u.rid, u.unit)\n for u in iter_units_for_relation_name(relation_name)]\n\n :param relation_name: string r... |
Please provide a description of the function:def ingress_address(rid=None, unit=None):
settings = relation_get(rid=rid, unit=unit)
return (settings.get('ingress-address') or
settings.get('private-address')) | [
"\n Retrieve the ingress-address from a relation when available.\n Otherwise, return the private-address.\n\n When used on the consuming side of the relation (unit is a remote\n unit), the ingress-address is the IP address that this unit needs\n to use to reach the provided service on the remote unit... |
Please provide a description of the function:def egress_subnets(rid=None, unit=None):
def _to_range(addr):
if re.search(r'^(?:\d{1,3}\.){3}\d{1,3}$', addr) is not None:
addr += '/32'
elif ':' in addr and '/' not in addr: # IPv6
addr += '/128'
return addr
se... | [
"\n Retrieve the egress-subnets from a relation.\n\n This function is to be used on the providing side of the\n relation, and provides the ranges of addresses that client\n connections may come from. The result is uninteresting on\n the consuming side of a relation (unit == local_unit()).\n\n Retu... |
Please provide a description of the function:def unit_doomed(unit=None):
if not has_juju_version("2.4.1"):
# We cannot risk blindly returning False for 'we don't know',
# because that could cause data loss; if call sites don't
# need an accurate answer, they likely don't need this helpe... | [
"Determines if the unit is being removed from the model\n\n Requires Juju 2.4.1.\n\n :param unit: string unit name, defaults to local_unit\n :side effect: calls goal_state\n :side effect: calls local_unit\n :side effect: calls has_juju_version\n :return: True if the unit is being removed, already ... |
Please provide a description of the function:def env_proxy_settings(selected_settings=None):
SUPPORTED_SETTINGS = {
'http': 'HTTP_PROXY',
'https': 'HTTPS_PROXY',
'no_proxy': 'NO_PROXY',
'ftp': 'FTP_PROXY'
}
if selected_settings is None:
selected_settings = SUPPOR... | [
"Get proxy settings from process environment variables.\n\n Get charm proxy settings from environment variables that correspond to\n juju-http-proxy, juju-https-proxy and juju-no-proxy (available as of 2.4.2,\n see lp:1782236) in a format suitable for passing to an application that\n reacts to proxy set... |
Please provide a description of the function:def load_previous(self, path=None):
self.path = path or self.path
with open(self.path) as f:
try:
self._prev_dict = json.load(f)
except ValueError as e:
log('Unable to parse previous config data... | [
"Load previous copy of config from disk.\n\n In normal usage you don't need to call this method directly - it\n is called automatically at object initialization.\n\n :param path:\n\n File path from which to load the previous config. If `None`,\n config is loaded from the d... |
Please provide a description of the function:def changed(self, key):
if self._prev_dict is None:
return True
return self.previous(key) != self.get(key) | [
"Return True if the current value for this key is different from\n the previous value.\n\n "
] |
Please provide a description of the function:def save(self):
with open(self.path, 'w') as f:
os.fchmod(f.fileno(), 0o600)
json.dump(self, f) | [
"Save this config to disk.\n\n If the charm is using the :mod:`Services Framework <services.base>`\n or :meth:'@hook <Hooks.hook>' decorator, this\n is called automatically at the end of successful hook execution.\n Otherwise, it should be called directly by user code.\n\n To disa... |
Please provide a description of the function:def execute(self, args):
_run_atstart()
hook_name = os.path.basename(args[0])
if hook_name in self._hooks:
try:
self._hooks[hook_name]()
except SystemExit as x:
if x.code is None or x.co... | [
"Execute a registered hook based on args[0]"
] |
Please provide a description of the function:def hook(self, *hook_names):
def wrapper(decorated):
for hook_name in hook_names:
self.register(hook_name, decorated)
else:
self.register(decorated.__name__, decorated)
if '_' in decorat... | [
"Decorator, registering them as hooks"
] |
Please provide a description of the function:def shutdown(self):
sys.stdout = self.old_stdout
sys.stdin = self.old_stdin
self.skt.close()
self.set_continue() | [
"Revert stdin and stdout, close the socket."
] |
Please provide a description of the function:def start():
action_set('meta.start', time.strftime('%Y-%m-%dT%H:%M:%SZ'))
COLLECT_PROFILE_DATA = '/usr/local/bin/collect-profile-data'
if os.path.exists(COLLECT_PROFILE_DATA):
subprocess.check_output([COLLECT_PROFILE_DATA]) | [
"\n If the collectd charm is also installed, tell it to send a snapshot\n of the current profile data.\n "
] |
Please provide a description of the function:def get_os_codename_install_source(src):
'''Derive OpenStack release codename from a given installation source.'''
ubuntu_rel = lsb_release()['DISTRIB_CODENAME']
rel = ''
if src is None:
return rel
if src in ['distro', 'distro-proposed', 'proposed... | [] |
Please provide a description of the function:def get_os_version_codename(codename, version_map=OPENSTACK_CODENAMES):
'''Determine OpenStack version number from codename.'''
for k, v in six.iteritems(version_map):
if v == codename:
return k
e = 'Could not derive OpenStack version for '\
... | [] |
Please provide a description of the function:def get_os_version_codename_swift(codename):
'''Determine OpenStack version number of swift from codename.'''
for k, v in six.iteritems(SWIFT_CODENAMES):
if k == codename:
return v[-1]
e = 'Could not derive swift version for '\
'codena... | [] |
Please provide a description of the function:def get_swift_codename(version):
'''Determine OpenStack codename that corresponds to swift version.'''
codenames = [k for k, v in six.iteritems(SWIFT_CODENAMES) if version in v]
if len(codenames) > 1:
# If more than one release codename contains this ver... | [] |
Please provide a description of the function:def get_os_codename_package(package, fatal=True):
'''Derive OpenStack release codename from an installed package.'''
if snap_install_requested():
cmd = ['snap', 'list', package]
try:
out = subprocess.check_output(cmd)
if six.P... | [] |
Please provide a description of the function:def get_os_version_package(pkg, fatal=True):
'''Derive OpenStack version number from an installed package.'''
codename = get_os_codename_package(pkg, fatal=fatal)
if not codename:
return None
if 'swift' in pkg:
vers_map = SWIFT_CODENAMES
... | [] |
Please provide a description of the function:def os_release(package, base='essex', reset_cache=False):
'''
Returns OpenStack release codename from a cached global.
If reset_cache then unset the cached os_release version and return the
freshly determined version.
If the codename can not be determin... | [] |
Please provide a description of the function:def import_key(keyid):
try:
return fetch_import_key(keyid)
except GPGKeyError as e:
error_out("Could not import key: {}".format(str(e))) | [
"Import a key, either ASCII armored, or a GPG key id.\n\n @param keyid: the key in ASCII armor format, or a GPG key id.\n @raises SystemExit() via sys.exit() on failure.\n "
] |
Please provide a description of the function:def get_source_and_pgp_key(source_and_key):
try:
source, key = source_and_key.split('|', 2)
return source, key or None
except ValueError:
return source_and_key, None | [
"Look for a pgp key ID or ascii-armor key in the given input.\n\n :param source_and_key: Sting, \"source_spec|keyid\" where '|keyid' is\n optional.\n :returns (source_spec, key_id OR None) as a tuple. Returns None for key_id\n if there was no '|' in the source_and_key string.\n "
] |
Please provide a description of the function:def configure_installation_source(source_plus_key):
if source_plus_key.startswith('snap'):
# Do nothing for snap installs
return
# extract the key if there is one, denoted by a '|' in the rel
source, key = get_source_and_pgp_key(source_plus_k... | [
"Configure an installation source.\n\n The functionality is provided by charmhelpers.fetch.add_source()\n The difference between the two functions is that add_source() signature\n requires the key to be passed directly, whereas this function passes an\n optional key by appending '|<key>' to the end of t... |
Please provide a description of the function:def config_value_changed(option):
hook_data = unitdata.HookData()
with hook_data():
db = unitdata.kv()
current = config(option)
saved = db.get(option)
db.set(option, current)
if saved is None:
return False
... | [
"\n Determine if config value changed since last call to this function.\n "
] |
Please provide a description of the function:def save_script_rc(script_path="scripts/scriptrc", **env_vars):
juju_rc_path = "%s/%s" % (charm_dir(), script_path)
if not os.path.exists(os.path.dirname(juju_rc_path)):
os.mkdir(os.path.dirname(juju_rc_path))
with open(juju_rc_path, 'wt') as rc_scri... | [
"\n Write an rc file in the charm-delivered directory containing\n exported environment variables provided by env_vars. Any charm scripts run\n outside the juju hook environment can source this scriptrc to obtain\n updated config information necessary to perform health checks or\n service changes.\n ... |
Please provide a description of the function:def openstack_upgrade_available(package):
import apt_pkg as apt
src = config('openstack-origin')
cur_vers = get_os_version_package(package)
if not cur_vers:
# The package has not been installed yet do not attempt upgrade
return False
... | [
"\n Determines if an OpenStack upgrade is available from installation\n source, based on version of installed package.\n\n :param package: str: Name of installed package.\n\n :returns: bool: : Returns True if configured installation source offers\n a newer version of package.\... |
Please provide a description of the function:def ensure_block_device(block_device):
'''
Confirm block_device, create as loopback if necessary.
:param block_device: str: Full path of block device to ensure.
:returns: str: Full path of ensured block device.
'''
_none = ['None', 'none', None]
... | [] |
Please provide a description of the function:def clean_storage(block_device):
'''
Ensures a block device is clean. That is:
- unmounted
- any lvm volume groups are deactivated
- any lvm physical device signatures removed
- partition table wiped
:param block_device: str: Ful... | [] |
Please provide a description of the function:def os_requires_version(ostack_release, pkg):
def wrap(f):
@wraps(f)
def wrapped_f(*args):
if os_release(pkg) < ostack_release:
raise Exception("This hook is not supported on releases"
" bef... | [
"\n Decorator for hook to specify minimum supported release\n "
] |
Please provide a description of the function:def os_workload_status(configs, required_interfaces, charm_func=None):
def wrap(f):
@wraps(f)
def wrapped_f(*args, **kwargs):
# Run the original function first
f(*args, **kwargs)
# Set workload status now that cont... | [
"\n Decorator to set workload status based on complete contexts\n "
] |
Please provide a description of the function:def set_os_workload_status(configs, required_interfaces, charm_func=None,
services=None, ports=None):
state, message = _determine_os_workload_status(
configs, required_interfaces, charm_func, services, ports)
status_set(state, ... | [
"Set the state of the workload status for the charm.\n\n This calls _determine_os_workload_status() to get the new state, message\n and sets the status using status_set()\n\n @param configs: a templating.OSConfigRenderer() object\n @param required_interfaces: {generic: [specific, specific2, ...]}\n @... |
Please provide a description of the function:def _determine_os_workload_status(
configs, required_interfaces, charm_func=None,
services=None, ports=None):
state, message = _ows_check_if_paused(services, ports)
if state is None:
state, message = _ows_check_generic_interfaces(
... | [
"Determine the state of the workload status for the charm.\n\n This function returns the new workload status for the charm based\n on the state of the interfaces, the paused state and whether the\n services are actually running and any specified ports are open.\n\n This checks:\n\n 1. if the unit sh... |
Please provide a description of the function:def _ows_check_if_paused(services=None, ports=None):
if is_unit_upgrading_set():
state, message = check_actually_paused(services=services,
ports=ports)
if state is None:
# we're paused okay, ... | [
"Check if the unit is supposed to be paused, and if so check that the\n services/ports (if passed) are actually stopped/not being listened to.\n\n If the unit isn't supposed to be paused, just return None, None\n\n If the unit is performing a series upgrade, return a message indicating\n this.\n\n @p... |
Please provide a description of the function:def _ows_check_generic_interfaces(configs, required_interfaces):
incomplete_rel_data = incomplete_relation_data(configs,
required_interfaces)
state = None
message = None
missing_relations = set()
inc... | [
"Check the complete contexts to determine the workload status.\n\n - Checks for missing or incomplete contexts\n - juju log details of missing required data.\n - determines the correct workload status\n - creates an appropriate message for status_set(...)\n\n if there are no problems then the fun... |
Please provide a description of the function:def _ows_check_charm_func(state, message, charm_func_with_configs):
if charm_func_with_configs:
charm_state, charm_message = charm_func_with_configs()
if (charm_state != 'active' and
charm_state != 'unknown' and
charm_... | [
"Run a custom check function for the charm to see if it wants to\n change the state. This is only run if not in 'maintenance' and\n tests to see if the new state is more important that the previous\n one determined by the interfaces/relations check.\n\n @param state: the previously determined state so ... |
Please provide a description of the function:def _ows_check_services_running(services, ports):
messages = []
state = None
if services is not None:
services = _extract_services_list_helper(services)
services_running, running = _check_running_services(services)
if not all(running)... | [
"Check that the services that should be running are actually running\n and that any ports specified are being listened to.\n\n @param services: list of strings OR dictionary specifying services/ports\n @param ports: list of ports\n @returns state, message: strings or None, None\n "
] |
Please provide a description of the function:def _extract_services_list_helper(services):
if services is None:
return {}
if isinstance(services, dict):
services = services.values()
# either extract the list of services from the dictionary, or if
# it is a simple string, use that. i.... | [
"Extract a OrderedDict of {service: [ports]} of the supplied services\n for use by the other functions.\n\n The services object can either be:\n - None : no services were passed (an empty dict is returned)\n - a list of strings\n - A dictionary (optionally OrderedDict) {service_name: {'service'... |
Please provide a description of the function:def _check_running_services(services):
services_running = [service_running(s) for s in services]
return list(zip(services, services_running)), services_running | [
"Check that the services dict provided is actually running and provide\n a list of (service, boolean) tuples for each service.\n\n Returns both a zipped list of (service, boolean) and a list of booleans\n in the same order as the services.\n\n @param services: OrderedDict of strings: [ports], one for ea... |
Please provide a description of the function:def _check_listening_on_services_ports(services, test=False):
test = not(not(test)) # ensure test is True or False
all_ports = list(itertools.chain(*services.values()))
ports_states = [port_has_listener('0.0.0.0', p) for p in all_ports]
map_ports = Orde... | [
"Check that the unit is actually listening (has the port open) on the\n ports that the service specifies are open. If test is True then the\n function returns the services with ports that are open rather than\n closed.\n\n Returns an OrderedDict of service: ports and a list of booleans\n\n @param ser... |
Please provide a description of the function:def _check_listening_on_ports_list(ports):
ports_open = [port_has_listener('0.0.0.0', p) for p in ports]
return zip(ports, ports_open), ports_open | [
"Check that the ports list given are being listened to\n\n Returns a list of ports being listened to and a list of the\n booleans.\n\n @param ports: LIST or port numbers.\n @returns [(port_num, boolean), ...], [boolean]\n "
] |
Please provide a description of the function:def workload_state_compare(current_workload_state, workload_state):
hierarchy = {'unknown': -1,
'active': 0,
'maintenance': 1,
'waiting': 2,
'blocked': 3,
}
if hierarchy.get(wo... | [
" Return highest priority of two states"
] |
Please provide a description of the function:def incomplete_relation_data(configs, required_interfaces):
complete_ctxts = configs.complete_contexts()
incomplete_relations = [
svc_type
for svc_type, interfaces in required_interfaces.items()
if not set(interfaces).intersection(complet... | [
"Check complete contexts against required_interfaces\n Return dictionary of incomplete relation data.\n\n configs is an OSConfigRenderer object with configs registered\n\n required_interfaces is a dictionary of required general interfaces\n with dictionary values of possible specific interfaces.\n Ex... |
Please provide a description of the function:def do_action_openstack_upgrade(package, upgrade_callback, configs):
ret = False
if openstack_upgrade_available(package):
if config('action-managed-upgrade'):
juju_log('Upgrading OpenStack release')
try:
upgrade_... | [
"Perform action-managed OpenStack upgrade.\n\n Upgrades packages to the configured openstack-origin version and sets\n the corresponding action status as a result.\n\n If the charm was installed from source we cannot upgrade it.\n For backwards compatibility a config flag (action-managed-upgrade) must\n... |
Please provide a description of the function:def check_actually_paused(services=None, ports=None):
state = None
message = None
messages = []
if services is not None:
services = _extract_services_list_helper(services)
services_running, services_states = _check_running_services(servic... | [
"Check that services listed in the services object and ports\n are actually closed (not listened to), to verify that the unit is\n properly paused.\n\n @param services: See _extract_services_list_helper\n @returns status, : string for status (None if okay)\n message : string for problem for ... |
Please provide a description of the function:def is_unit_paused_set():
try:
with unitdata.HookData()() as t:
kv = t[0]
# transform something truth-y into a Boolean.
return not(not(kv.get('unit-paused')))
except Exception:
return False | [
"Return the state of the kv().get('unit-paused').\n This does NOT verify that the unit really is paused.\n\n To help with units that don't have HookData() (testing)\n if it excepts, return False\n "
] |
Please provide a description of the function:def manage_payload_services(action, services=None, charm_func=None):
actions = {
'pause': service_pause,
'resume': service_resume,
'start': service_start,
'stop': service_stop}
action = action.lower()
if action not in actions.... | [
"Run an action against all services.\n\n An optional charm_func() can be called. It should raise an Exception to\n indicate that the function failed. If it was succesfull it should return\n None or an optional message.\n\n The signature for charm_func is:\n charm_func() -> message: str\n\n charm_f... |
Please provide a description of the function:def pause_unit(assess_status_func, services=None, ports=None,
charm_func=None):
_, messages = manage_payload_services(
'pause',
services=services,
charm_func=charm_func)
set_unit_paused()
if assess_status_func:
... | [
"Pause a unit by stopping the services and setting 'unit-paused'\n in the local kv() store.\n\n Also checks that the services have stopped and ports are no longer\n being listened to.\n\n An optional charm_func() can be called that can either raise an\n Exception or return non None, None to indicate ... |
Please provide a description of the function:def resume_unit(assess_status_func, services=None, ports=None,
charm_func=None):
_, messages = manage_payload_services(
'resume',
services=services,
charm_func=charm_func)
clear_unit_paused()
if assess_status_func:
... | [
"Resume a unit by starting the services and clearning 'unit-paused'\n in the local kv() store.\n\n Also checks that the services have started and ports are being listened to.\n\n An optional charm_func() can be called that can either raise an\n Exception or return non None to indicate that the unit\n ... |
Please provide a description of the function:def make_assess_status_func(*args, **kwargs):
def _assess_status_func():
state, message = _determine_os_workload_status(*args, **kwargs)
status_set(state, message)
if state not in ['maintenance', 'active']:
return message
... | [
"Creates an assess_status_func() suitable for handing to pause_unit()\n and resume_unit().\n\n This uses the _determine_os_workload_status(...) function to determine\n what the workload_status should be for the unit. If the unit is\n not in maintenance or active states, then the message is returned to\... |
Please provide a description of the function:def pausable_restart_on_change(restart_map, stopstart=False,
restart_functions=None):
def wrap(f):
# py27 compatible nonlocal variable. When py3 only, replace with
# nonlocal keyword
__restart_map_cache = {'cac... | [
"A restart_on_change decorator that checks to see if the unit is\n paused. If it is paused then the decorated function doesn't fire.\n\n This is provided as a helper, as the @restart_on_change(...) decorator\n is in core.host, yet the openstack specific helpers are in this file\n (contrib.openstack.util... |
Please provide a description of the function:def ordered(orderme):
if not isinstance(orderme, dict):
raise ValueError('argument must be a dict type')
result = OrderedDict()
for k, v in sorted(six.iteritems(orderme), key=lambda x: x[0]):
if isinstance(v, dict):
result[k] = o... | [
"Converts the provided dictionary into a collections.OrderedDict.\n\n The items in the returned OrderedDict will be inserted based on the\n natural sort order of the keys. Nested dictionaries will also be sorted\n in order to ensure fully predictable ordering.\n\n :param orderme: the dict to order\n ... |
Please provide a description of the function:def config_flags_parser(config_flags):
# If we find a colon before an equals sign then treat it as yaml.
# Note: limit it to finding the colon first since this indicates assignment
# for inline yaml.
colon = config_flags.find(':')
equals = config_fla... | [
"Parses config flags string into dict.\n\n This parsing method supports a few different formats for the config\n flag values to be parsed:\n\n 1. A string in the simple format of key=value pairs, with the possibility\n of specifying multiple key value pairs within the same string. For\n e... |
Please provide a description of the function:def os_application_version_set(package):
'''Set version of application for Juju 2.0 and later'''
application_version = get_upstream_version(package)
# NOTE(jamespage) if not able to figure out package version, fallback to
# openstack codename ... | [] |
Please provide a description of the function:def enable_memcache(source=None, release=None, package=None):
_release = None
if release:
_release = release
else:
_release = os_release(package, base='icehouse')
if not _release:
_release = get_os_codename_install_source(source)
... | [
"Determine if memcache should be enabled on the local unit\n\n @param release: release of OpenStack currently deployed\n @param package: package to derive OpenStack version deployed\n @returns boolean Whether memcache should be enabled\n "
] |
Please provide a description of the function:def token_cache_pkgs(source=None, release=None):
packages = []
if enable_memcache(source=source, release=release):
packages.extend(['memcached', 'python-memcache'])
return packages | [
"Determine additional packages needed for token caching\n\n @param source: source string for charm\n @param release: release of OpenStack currently deployed\n @returns List of package to enable token caching\n "
] |
Please provide a description of the function:def update_json_file(filename, items):
if not items:
return
with open(filename) as fd:
policy = json.load(fd)
# Compare before and after and if nothing has changed don't write the file
# since that could cause unnecessary service restar... | [
"Updates the json `filename` with a given dict.\n :param filename: path to json file (e.g. /etc/glance/policy.json)\n :param items: dict of items to update\n "
] |
Please provide a description of the function:def snap_install_requested():
origin = config('openstack-origin') or ""
if not origin.startswith('snap:'):
return False
_src = origin[5:]
if '/' in _src:
channel = _src.split('/')[1]
else:
# Handle snap:track with no channel
... | [
" Determine if installing from snaps\n\n If openstack-origin is of the form snap:track/channel[/branch]\n and channel is in SNAPS_CHANNELS return True.\n "
] |
Please provide a description of the function:def get_snaps_install_info_from_origin(snaps, src, mode='classic'):
if not src.startswith('snap:'):
juju_log("Snap source is not a snap origin", 'WARN')
return {}
_src = src[5:]
channel = '--channel={}'.format(_src)
return {snap: {'cha... | [
"Generate a dictionary of snap install information from origin\n\n @param snaps: List of snaps\n @param src: String of openstack-origin or source of the form\n snap:track/channel\n @param mode: String classic, devmode or jailmode\n @returns: Dictionary of snaps with channels and modes\n "
] |
Please provide a description of the function:def install_os_snaps(snaps, refresh=False):
def _ensure_flag(flag):
if flag.startswith('--'):
return flag
return '--{}'.format(flag)
if refresh:
for snap in snaps.keys():
snap_refresh(snap,
... | [
"Install OpenStack snaps from channel and with mode\n\n @param snaps: Dictionary of snaps with channels and modes of the form:\n {'snap_name': {'channel': 'snap_channel',\n 'mode': 'snap_mode'}}\n Where channel is a snapstore channel and mode is --classic, --devmode\n o... |
Please provide a description of the function:def is_unit_upgrading_set():
try:
with unitdata.HookData()() as t:
kv = t[0]
# transform something truth-y into a Boolean.
return not(not(kv.get('unit-upgrading')))
except Exception:
return False | [
"Return the state of the kv().get('unit-upgrading').\n\n To help with units that don't have HookData() (testing)\n if it excepts, return False\n "
] |
Please provide a description of the function:def series_upgrade_complete(resume_unit_helper=None, configs=None):
clear_unit_paused()
clear_unit_upgrading()
if configs:
configs.write_all()
if resume_unit_helper:
resume_unit_helper(configs) | [
" Run common series upgrade complete tasks.\n\n :param resume_unit_helper: function: Function to resume unit\n :param configs: OSConfigRenderer object: Configurations\n :returns None:\n "
] |
Please provide a description of the function:def get_certificate_request(json_encode=True):
req = CertRequest(json_encode=json_encode)
req.add_hostname_cn()
# Add os-hostname entries
for net_type in [INTERNAL, ADMIN, PUBLIC]:
net_config = config(ADDRESS_MAP[net_type]['override'])
tr... | [
"Generate a certificatee requests based on the network confioguration\n\n "
] |
Please provide a description of the function:def create_ip_cert_links(ssl_dir, custom_hostname_link=None):
hostname = get_hostname(unit_get('private-address'))
hostname_cert = os.path.join(
ssl_dir,
'cert_{}'.format(hostname))
hostname_key = os.path.join(
ssl_dir,
'key_{... | [
"Create symlinks for SAN records\n\n :param ssl_dir: str Directory to create symlinks in\n :param custom_hostname_link: str Additional link to be created\n "
] |
Please provide a description of the function:def install_certs(ssl_dir, certs, chain=None, user='root', group='root'):
for cn, bundle in certs.items():
cert_filename = 'cert_{}'.format(cn)
key_filename = 'key_{}'.format(cn)
cert_data = bundle['cert']
if chain:
# Appe... | [
"Install the certs passed into the ssl dir and append the chain if\n provided.\n\n :param ssl_dir: str Directory to create symlinks in\n :param certs: {} {'cn': {'cert': 'CERT', 'key': 'KEY'}}\n :param chain: str Chain to be appended to certs\n :param user: (Optional) Owner of certificate files. D... |
Please provide a description of the function:def process_certificates(service_name, relation_id, unit,
custom_hostname_link=None, user='root', group='root'):
data = relation_get(rid=relation_id, unit=unit)
ssl_dir = os.path.join('/etc/apache2/ssl/', service_name)
mkdir(path=ssl... | [
"Process the certificates supplied down the relation\n\n :param service_name: str Name of service the certifcates are for.\n :param relation_id: str Relation id providing the certs\n :param unit: str Unit providing the certs\n :param custom_hostname_link: str Name of custom link to create\n :param us... |
Please provide a description of the function:def get_requests_for_local_unit(relation_name=None):
local_name = local_unit().replace('/', '_')
raw_certs_key = '{}.processed_requests'.format(local_name)
relation_name = relation_name or 'certificates'
bundles = []
for rid in relation_ids(relation_... | [
"Extract any certificates data targeted at this unit down relation_name.\n\n :param relation_name: str Name of relation to check for data.\n :returns: List of bundles of certificates.\n :rtype: List of dicts\n "
] |
Please provide a description of the function:def get_bundle_for_cn(cn, relation_name=None):
entries = get_requests_for_local_unit(relation_name)
cert_bundle = {}
for entry in entries:
for _cn, bundle in entry['certs'].items():
if _cn == cn:
cert_bundle = {
... | [
"Extract certificates for the given cn.\n\n :param cn: str Canonical Name on certificate.\n :param relation_name: str Relation to check for certificates down.\n :returns: Dictionary of certificate data,\n :rtype: dict.\n "
] |
Please provide a description of the function:def add_entry(self, net_type, cn, addresses):
self.entries.append({
'cn': cn,
'addresses': addresses}) | [
"Add a request to the batch\n\n :param net_type: str netwrok space name request is for\n :param cn: str Canonical Name for certificate\n :param addresses: [] List of addresses to be used as SANs\n "
] |
Please provide a description of the function:def add_hostname_cn(self):
ip = unit_get('private-address')
addresses = [ip]
# If a vip is being used without os-hostname config or
# network spaces then we need to ensure the local units
# cert has the approriate vip in the S... | [
"Add a request for the hostname of the machine"
] |
Please provide a description of the function:def add_hostname_cn_ip(self, addresses):
for addr in addresses:
if addr not in self.hostname_entry['addresses']:
self.hostname_entry['addresses'].append(addr) | [
"Add an address to the SAN list for the hostname request\n\n :param addr: [] List of address to be added\n "
] |
Please provide a description of the function:def get_request(self):
if self.hostname_entry:
self.entries.append(self.hostname_entry)
request = {}
for entry in self.entries:
sans = sorted(list(set(entry['addresses'])))
request[entry['cn']] = {'sans': s... | [
"Generate request from the batched up entries\n\n "
] |
Please provide a description of the function:def render(template, extra={}, **kwargs):
context = hookenv.execution_environment()
context.update(extra)
context.update(kwargs)
return template.format(**context) | [
"Return the template rendered using Python's str.format()."
] |
Please provide a description of the function:def get_audits():
audits = []
settings = utils.get_settings('os')
# Apply the sysctl settings which are configured to be applied.
audits.append(SysctlConf())
# Make sure that only root has access to the sysctl.conf file, and
# that it is read-on... | [
"Get OS hardening sysctl audits.\n\n :returns: dictionary of audits\n "
] |
Please provide a description of the function:def _stat(file):
out = subprocess.check_output(
['stat', '-c', '%U %G %a', file]).decode('utf-8')
return Ownership(*out.strip().split(' ')) | [
"\n Get the Ownership information from a file.\n\n :param file: The path to a file to stat\n :type file: str\n :returns: owner, group, and mode of the specified file\n :rtype: Ownership\n :raises subprocess.CalledProcessError: If the underlying stat fails\n "
] |
Please provide a description of the function:def _config_ini(path):
conf = configparser.ConfigParser()
conf.read(path)
return dict(conf) | [
"\n Parse an ini file\n\n :param path: The path to a file to parse\n :type file: str\n :returns: Configuration contained in path\n :rtype: Dict\n "
] |
Please provide a description of the function:def _validate_file_ownership(owner, group, file_name, optional=False):
try:
ownership = _stat(file_name)
except subprocess.CalledProcessError as e:
print("Error reading file: {}".format(e))
if not optional:
assert False, "Spec... | [
"\n Validate that a specified file is owned by `owner:group`.\n\n :param owner: Name of the owner\n :type owner: str\n :param group: Name of the group\n :type group: str\n :param file_name: Path to the file to verify\n :type file_name: str\n :param optional: Is this file optional,\n ... |
Please provide a description of the function:def _validate_file_mode(mode, file_name, optional=False):
try:
ownership = _stat(file_name)
except subprocess.CalledProcessError as e:
print("Error reading file: {}".format(e))
if not optional:
assert False, "Specified file do... | [
"\n Validate that a specified file has the specified permissions.\n\n :param mode: file mode that is desires\n :type owner: str\n :param file_name: Path to the file to verify\n :type file_name: str\n :param optional: Is this file optional,\n ie: Should this test fail when it's ... |
Please provide a description of the function:def _config_section(config, section):
path = os.path.join(config.get('config_path'), config.get('config_file'))
conf = _config_ini(path)
return conf.get(section) | [
"Read the configuration file and return a section."
] |
Please provide a description of the function:def validate_file_ownership(config):
files = config.get('files', {})
for file_name, options in files.items():
for key in options.keys():
if key not in ["owner", "group", "mode"]:
raise RuntimeError(
"Invali... | [
"Verify that configuration files are owned by the correct user/group."
] |
Please provide a description of the function:def validate_file_permissions(config):
files = config.get('files', {})
for file_name, options in files.items():
for key in options.keys():
if key not in ["owner", "group", "mode"]:
raise RuntimeError(
"Inva... | [
"Verify that permissions on configuration files are secure enough."
] |
Please provide a description of the function:def validate_uses_tls_for_keystone(audit_options):
section = _config_section(audit_options, 'keystone_authtoken')
assert section is not None, "Missing section 'keystone_authtoken'"
assert not section.get('insecure') and \
"https://" in section.get("a... | [
"Verify that TLS is used to communicate with Keystone."
] |
Please provide a description of the function:def validate_uses_tls_for_glance(audit_options):
section = _config_section(audit_options, 'glance')
assert section is not None, "Missing section 'glance'"
assert not section.get('insecure') and \
"https://" in section.get("api_servers"), \
"T... | [
"Verify that TLS is used to communicate with Glance."
] |
Please provide a description of the function:def is_ready(self):
ready = len(self.get(self.name, [])) > 0
if not ready:
hookenv.log('Incomplete relation: {}'.format(self.__class__.__name__), hookenv.DEBUG)
return ready | [
"\n Returns True if all of the `required_keys` are available from any units.\n "
] |
Please provide a description of the function:def _is_ready(self, unit_data):
return set(unit_data.keys()).issuperset(set(self.required_keys)) | [
"\n Helper method that tests a set of relation data and returns True if\n all of the `required_keys` are present.\n "
] |
Please provide a description of the function:def get_data(self):
if not hookenv.relation_ids(self.name):
return
ns = self.setdefault(self.name, [])
for rid in sorted(hookenv.relation_ids(self.name)):
for unit in sorted(hookenv.related_units(rid)):
... | [
"\n Retrieve the relation data for each unit involved in a relation and,\n if complete, store it in a list under `self[self.name]`. This\n is automatically called when the RelationContext is instantiated.\n\n The units are sorted lexographically first by the service ID, then by\n ... |
Please provide a description of the function:def service_restart(service_name):
if host.service_available(service_name):
if host.service_running(service_name):
host.service_restart(service_name)
else:
host.service_start(service_name) | [
"\n Wrapper around host.service_restart to prevent spurious \"unknown service\"\n messages in the logs.\n "
] |
Please provide a description of the function:def manage(self):
hookenv._run_atstart()
try:
hook_name = hookenv.hook_name()
if hook_name == 'stop':
self.stop_services()
else:
self.reconfigure_services()
self.prov... | [
"\n Handle the current hook by doing The Right Thing with the registered services.\n "
] |
Please provide a description of the function:def provide_data(self):
for service_name, service in self.services.items():
service_ready = self.is_ready(service_name)
for provider in service.get('provided_data', []):
for relid in hookenv.relation_ids(provider.name)... | [
"\n Set the relation data for each provider in the ``provided_data`` list.\n\n A provider must have a `name` attribute, which indicates which relation\n to set data on, and a `provide_data()` method, which returns a dict of\n data to set.\n\n The `provide_data()` method can option... |
Please provide a description of the function:def reconfigure_services(self, *service_names):
for service_name in service_names or self.services.keys():
if self.is_ready(service_name):
self.fire_event('data_ready', service_name)
self.fire_event('start', servic... | [
"\n Update all files for one or more registered services, and,\n if ready, optionally restart them.\n\n If no service names are given, reconfigures all registered services.\n "
] |
Please provide a description of the function:def stop_services(self, *service_names):
for service_name in service_names or self.services.keys():
self.fire_event('stop', service_name, default=[
manage_ports,
service_stop]) | [
"\n Stop one or more registered services, by name.\n\n If no service names are given, stops all registered services.\n "
] |
Please provide a description of the function:def get_service(self, service_name):
service = self.services.get(service_name)
if not service:
raise KeyError('Service not registered: %s' % service_name)
return service | [
"\n Given the name of a registered service, return its service definition.\n "
] |
Please provide a description of the function:def fire_event(self, event_name, service_name, default=None):
service = self.get_service(service_name)
callbacks = service.get(event_name, default)
if not callbacks:
return
if not isinstance(callbacks, Iterable):
... | [
"\n Fire a data_ready, data_lost, start, or stop event on a given service.\n "
] |
Please provide a description of the function:def is_ready(self, service_name):
service = self.get_service(service_name)
reqs = service.get('required_data', [])
return all(bool(req) for req in reqs) | [
"\n Determine if a registered service is ready, by checking its 'required_data'.\n\n A 'required_data' item can be any mapping type, and is considered ready\n if `bool(item)` evaluates as True.\n "
] |
Please provide a description of the function:def save_ready(self, service_name):
self._load_ready_file()
self._ready.add(service_name)
self._save_ready_file() | [
"\n Save an indicator that the given service is now data_ready.\n "
] |
Please provide a description of the function:def save_lost(self, service_name):
self._load_ready_file()
self._ready.discard(service_name)
self._save_ready_file() | [
"\n Save an indicator that the given service is no longer data_ready.\n "
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.