Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def ssh_authorized_key_exists(public_key, application_name, user=None):
with open(authorized_keys(application_name, user)) as keys:
return ('%s' % public_key) in keys.read() | [
"Check if given key is in the authorized_key file.\n\n :param public_key: Public key.\n :type public_key: str\n :param application_name: Name of application eg nova-compute-something\n :type application_name: str\n :param user: The user that the ssh asserts are for.\n :type user: str\n :returns... |
Please provide a description of the function:def add_authorized_key(public_key, application_name, user=None):
with open(authorized_keys(application_name, user), 'a') as keys:
keys.write("{}\n".format(public_key)) | [
"Add given key to the authorized_key file.\n\n :param public_key: Public key.\n :type public_key: str\n :param application_name: Name of application eg nova-compute-something\n :type application_name: str\n :param user: The user that the ssh asserts are for.\n :type user: str\n "
] |
Please provide a description of the function:def ssh_compute_add_host_and_key(public_key, hostname, private_address,
application_name, user=None):
# If remote compute node hands us a hostname, ensure we have a
# known hosts entry for its IP, hostname and FQDN.
hosts = [... | [
"Add a compute nodes ssh details to local cache.\n\n Collect various hostname variations and add the corresponding host keys to\n the local known hosts file. Finally, add the supplied public key to the\n authorized_key file.\n\n :param public_key: Public key.\n :type public_key: str\n :param hostn... |
Please provide a description of the function:def ssh_compute_add(public_key, application_name, rid=None, unit=None,
user=None):
relation_data = relation_get(rid=rid, unit=unit)
ssh_compute_add_host_and_key(
public_key,
relation_data.get('hostname'),
relation_data... | [
"Add a compute nodes ssh details to local cache.\n\n Collect various hostname variations and add the corresponding host keys to\n the local known hosts file. Finally, add the supplied public key to the\n authorized_key file.\n\n :param public_key: Public key.\n :type public_key: str\n :param appli... |
Please provide a description of the function:def ssh_known_hosts_lines(application_name, user=None):
known_hosts_list = []
with open(known_hosts(application_name, user)) as hosts:
for hosts_line in hosts:
if hosts_line.rstrip():
known_hosts_list.append(hosts_line.rstrip(... | [
"Return contents of known_hosts file for given application.\n\n :param application_name: Name of application eg nova-compute-something\n :type application_name: str\n :param user: The user that the ssh asserts are for.\n :type user: str\n "
] |
Please provide a description of the function:def ssh_authorized_keys_lines(application_name, user=None):
authorized_keys_list = []
with open(authorized_keys(application_name, user)) as keys:
for authkey_line in keys:
if authkey_line.rstrip():
authorized_keys_list.append... | [
"Return contents of authorized_keys file for given application.\n\n :param application_name: Name of application eg nova-compute-something\n :type application_name: str\n :param user: The user that the ssh asserts are for.\n :type user: str\n "
] |
Please provide a description of the function:def ssh_compute_remove(public_key, application_name, user=None):
if not (os.path.isfile(authorized_keys(application_name, user)) or
os.path.isfile(known_hosts(application_name, user))):
return
keys = ssh_authorized_keys_lines(application_nam... | [
"Remove given public key from authorized_keys file.\n\n :param public_key: Public key.\n :type public_key: str\n :param application_name: Name of application eg nova-compute-something\n :type application_name: str\n :param user: The user that the ssh asserts are for.\n :type user: str\n "
] |
Please provide a description of the function:def get_ssh_settings(application_name, user=None):
settings = {}
keys = {}
prefix = ''
if user:
prefix = '{}_'.format(user)
for i, line in enumerate(ssh_known_hosts_lines(
application_name=application_name, user=user)):
s... | [
"Retrieve the known host entries and public keys for application\n\n Retrieve the known host entries and public keys for application for all\n units of the given application related to this application for the\n app + user combination.\n\n :param application_name: Name of application eg nova-compute-som... |
Please provide a description of the function:def get_all_user_ssh_settings(application_name):
settings = get_ssh_settings(application_name)
settings.update(get_ssh_settings(application_name, user='nova'))
return settings | [
"Retrieve the known host entries and public keys for application\n\n Retrieve the known host entries and public keys for application for all\n units of the given application related to this application for root user\n and nova user.\n\n :param application_name: Name of application eg nova-compute-someth... |
Please provide a description of the function:def filter_installed_packages(packages):
cache = apt_cache()
_pkgs = []
for package in packages:
try:
p = cache[package]
p.current_ver or _pkgs.append(package)
except KeyError:
log('Package {} has no instal... | [
"Return a list of packages that require installation."
] |
Please provide a description of the function:def apt_cache(in_memory=True, progress=None):
from apt import apt_pkg
apt_pkg.init()
if in_memory:
apt_pkg.config.set("Dir::Cache::pkgcache", "")
apt_pkg.config.set("Dir::Cache::srcpkgcache", "")
return apt_pkg.Cache(progress) | [
"Build and return an apt cache."
] |
Please provide a description of the function:def apt_install(packages, options=None, fatal=False):
if options is None:
options = ['--option=Dpkg::Options::=--force-confold']
cmd = ['apt-get', '--assume-yes']
cmd.extend(options)
cmd.append('install')
if isinstance(packages, six.string_t... | [
"Install one or more packages."
] |
Please provide a description of the function:def apt_upgrade(options=None, fatal=False, dist=False):
if options is None:
options = ['--option=Dpkg::Options::=--force-confold']
cmd = ['apt-get', '--assume-yes']
cmd.extend(options)
if dist:
cmd.append('dist-upgrade')
else:
... | [
"Upgrade all packages."
] |
Please provide a description of the function:def apt_purge(packages, fatal=False):
cmd = ['apt-get', '--assume-yes', 'purge']
if isinstance(packages, six.string_types):
cmd.append(packages)
else:
cmd.extend(packages)
log("Purging {}".format(packages))
_run_apt_command(cmd, fatal... | [
"Purge one or more packages."
] |
Please provide a description of the function:def apt_autoremove(purge=True, fatal=False):
cmd = ['apt-get', '--assume-yes', 'autoremove']
if purge:
cmd.append('--purge')
_run_apt_command(cmd, fatal) | [
"Purge one or more packages."
] |
Please provide a description of the function:def apt_mark(packages, mark, fatal=False):
log("Marking {} as {}".format(packages, mark))
cmd = ['apt-mark', mark]
if isinstance(packages, six.string_types):
cmd.append(packages)
else:
cmd.extend(packages)
if fatal:
subproces... | [
"Flag one or more packages using apt-mark."
] |
Please provide a description of the function:def import_key(key):
key = key.strip()
if '-' in key or '\n' in key:
# Send everything not obviously a keyid to GPG to import, as
# we trust its validation better than our own. eg. handling
# comments before the key.
log("PGP key ... | [
"Import an ASCII Armor key.\n\n A Radix64 format keyid is also supported for backwards\n compatibility. In this case Ubuntu keyserver will be\n queried for a key via HTTPS by its keyid. This method\n is less preferrable because https proxy servers may\n require traffic decryption which is equivalent ... |
Please provide a description of the function:def _get_keyid_by_gpg_key(key_material):
# Use the same gpg command for both Xenial and Bionic
cmd = 'gpg --with-colons --with-fingerprint'
ps = subprocess.Popen(cmd.split(),
stdout=subprocess.PIPE,
stderr=... | [
"Get a GPG key fingerprint by GPG key material.\n Gets a GPG key fingerprint (40-digit, 160-bit) by the ASCII armor-encoded\n or binary GPG key material. Can be used, for example, to generate file\n names for keys passed via charm options.\n\n :param key_material: ASCII armor-encoded or binary GPG key m... |
Please provide a description of the function:def _get_key_by_keyid(keyid):
# options=mr - machine-readable output (disables html wrappers)
keyserver_url = ('https://keyserver.ubuntu.com'
'/pks/lookup?op=get&options=mr&exact=on&search=0x{}')
curl_cmd = ['curl', keyserver_url.format(... | [
"Get a key via HTTPS from the Ubuntu keyserver.\n Different key ID formats are supported by SKS keyservers (the longer ones\n are more secure, see \"dead beef attack\" and https://evil32.com/). Since\n HTTPS is used, if SSLBump-like HTTPS proxies are in place, they will\n impersonate keyserver.ubuntu.co... |
Please provide a description of the function:def _dearmor_gpg_key(key_asc):
ps = subprocess.Popen(['gpg', '--dearmor'],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
stdin=subprocess.PIPE)
out, err = ps.communicate(input=key_as... | [
"Converts a GPG key in the ASCII armor format to the binary format.\n\n :param key_asc: A GPG key in ASCII armor format.\n :type key_asc: (str, bytes)\n :returns: A GPG key in binary format\n :rtype: (str, bytes)\n :raises: GPGKeyError\n "
] |
Please provide a description of the function:def _write_apt_gpg_keyfile(key_name, key_material):
with open('/etc/apt/trusted.gpg.d/{}.gpg'.format(key_name),
'wb') as keyf:
keyf.write(key_material) | [
"Writes GPG key material into a file at a provided path.\n\n :param key_name: A key name to use for a key file (could be a fingerprint)\n :type key_name: str\n :param key_material: A GPG key material (binary)\n :type key_material: (str, bytes)\n "
] |
Please provide a description of the function:def add_source(source, key=None, fail_invalid=False):
_mapping = OrderedDict([
(r"^distro$", lambda: None), # This is a NOP
(r"^(?:proposed|distro-proposed)$", _add_proposed),
(r"^cloud-archive:(.*)$", _add_apt_repository),
(r"^((?:d... | [
"Add a package source to this system.\n\n @param source: a URL or sources.list entry, as supported by\n add-apt-repository(1). Examples::\n\n ppa:charmers/example\n deb https://stub:key@private.example.com/ubuntu trusty main\n\n In addition:\n 'proposed:' may be used to enable the stan... |
Please provide a description of the function:def _add_proposed():
release = get_distrib_codename()
arch = platform.machine()
if arch not in six.iterkeys(ARCH_TO_PROPOSED_POCKET):
raise SourceConfigError("Arch {} not supported for (distro-)proposed"
.format(arch))... | [
"Add the PROPOSED_POCKET as /etc/apt/source.list.d/proposed.list\n\n Uses get_distrib_codename to determine the correct stanza for\n the deb line.\n\n For intel architecutres PROPOSED_POCKET is used for the release, but for\n other architectures PROPOSED_PORTS_POCKET is used for the release.\n "
] |
Please provide a description of the function:def _add_apt_repository(spec):
if '{series}' in spec:
series = get_distrib_codename()
spec = spec.replace('{series}', series)
# software-properties package for bionic properly reacts to proxy settings
# passed as environment variables (See lp... | [
"Add the spec using add_apt_repository\n\n :param spec: the parameter to pass to add_apt_repository\n :type spec: str\n "
] |
Please provide a description of the function:def _add_cloud_pocket(pocket):
apt_install(filter_installed_packages(['ubuntu-cloud-keyring']),
fatal=True)
if pocket not in CLOUD_ARCHIVE_POCKETS:
raise SourceConfigError(
'Unsupported cloud: source option %s' %
p... | [
"Add a cloud pocket as /etc/apt/sources.d/cloud-archive.list\n\n Note that this overwrites the existing file if there is one.\n\n This function also converts the simple pocket in to the actual pocket using\n the CLOUD_ARCHIVE_POCKETS mapping.\n\n :param pocket: string representing the pocket to add a de... |
Please provide a description of the function:def _add_cloud_staging(cloud_archive_release, openstack_release):
_verify_is_ubuntu_rel(cloud_archive_release, openstack_release)
ppa = 'ppa:ubuntu-cloud-archive/{}-staging'.format(openstack_release)
cmd = 'add-apt-repository -y {}'.format(ppa)
_run_with... | [
"Add the cloud staging repository which is in\n ppa:ubuntu-cloud-archive/<openstack_release>-staging\n\n This function checks that the cloud_archive_release matches the current\n codename for the distro that charm is being installed on.\n\n :param cloud_archive_release: string, codename for the release.... |
Please provide a description of the function:def _add_cloud_distro_check(cloud_archive_release, openstack_release):
_verify_is_ubuntu_rel(cloud_archive_release, openstack_release)
_add_cloud_pocket("{}-{}".format(cloud_archive_release, openstack_release)) | [
"Add the cloud pocket, but also check the cloud_archive_release against\n the current distro, and use the openstack_release as the full lookup.\n\n This just calls _add_cloud_pocket() with the openstack_release as pocket\n to get the correct cloud-archive.list for dpkg to work with.\n\n :param cloud_arc... |
Please provide a description of the function:def _verify_is_ubuntu_rel(release, os_release):
ubuntu_rel = get_distrib_codename()
if release != ubuntu_rel:
raise SourceConfigError(
'Invalid Cloud Archive release specified: {}-{} on this Ubuntu'
'version ({})'.format(release, ... | [
"Verify that the release is in the same as the current ubuntu release.\n\n :param release: String, lowercase for the release.\n :param os_release: String, the os_release being asked for\n :raises: SourceConfigError if the release is not the same as the ubuntu\n release.\n "
] |
Please provide a description of the function:def _run_with_retries(cmd, max_retries=CMD_RETRY_COUNT, retry_exitcodes=(1,),
retry_message="", cmd_env=None):
env = None
kwargs = {}
if cmd_env:
env = os.environ.copy()
env.update(cmd_env)
kwargs['env'] = env
... | [
"Run a command and retry until success or max_retries is reached.\n\n :param: cmd: str: The apt command to run.\n :param: max_retries: int: The number of retries to attempt on a fatal\n command. Defaults to CMD_RETRY_COUNT.\n :param: retry_exitcodes: tuple: Optional additional exit codes to retry.\n... |
Please provide a description of the function:def _run_apt_command(cmd, fatal=False):
# Provide DEBIAN_FRONTEND=noninteractive if not present in the environment.
cmd_env = {
'DEBIAN_FRONTEND': os.environ.get('DEBIAN_FRONTEND', 'noninteractive')}
if fatal:
_run_with_retries(
... | [
"Run an apt command with optional retries.\n\n :param: cmd: str: The apt command to run.\n :param: fatal: bool: Whether the command's output should be checked and\n retried.\n "
] |
Please provide a description of the function:def get_upstream_version(package):
import apt_pkg
cache = apt_cache()
try:
pkg = cache[package]
except Exception:
# the package is unknown to the current apt cache.
return None
if not pkg.current_ver:
# package is kno... | [
"Determine upstream version based on installed package\n\n @returns None (if not installed) or the upstream version\n "
] |
Please provide a description of the function:def get_bcache_fs():
cachesetroot = "{}/fs/bcache".format(SYSFS)
try:
dirs = os.listdir(cachesetroot)
except OSError:
log("No bcache fs found")
return []
cacheset = set([Bcache('{}/{}'.format(cachesetroot, d)) for d in dirs if not... | [
"Return all cache sets\n "
] |
Please provide a description of the function:def get_stats_action(cachespec, interval):
if cachespec == 'global':
caches = get_bcache_fs()
else:
caches = [Bcache.fromdevice(cachespec)]
res = dict((c.cachepath, c.get_stats(interval)) for c in caches)
return json.dumps(res, indent=4, ... | [
"Action for getting bcache statistics for a given cachespec.\n Cachespec can either be a device name, eg. 'sdb', which will retrieve\n cache stats for the given device, or 'global', which will retrieve stats\n for all cachesets\n "
] |
Please provide a description of the function:def get_stats(self, interval):
intervaldir = 'stats_{}'.format(interval)
path = "{}/{}".format(self.cachepath, intervaldir)
out = dict()
for elem in os.listdir(path):
out[elem] = open('{}/{}'.format(path, elem)).read().str... | [
"Get cache stats\n "
] |
Please provide a description of the function:def update_dns_ha_resource_params(resources, resource_params,
relation_id=None,
crm_ocf='ocf:maas:dns'):
_relation_data = {'resources': {}, 'resource_params': {}}
update_hacluster_dns_ha(charm_n... | [
" Configure DNS-HA resources based on provided configuration and\n update resource dictionaries for the HA relation.\n\n @param resources: Pointer to dictionary of resources.\n Usually instantiated in ha_joined().\n @param resource_params: Pointer to dictionary of resource parameters.\... |
Please provide a description of the function:def expect_ha():
ha_related_units = []
try:
ha_related_units = list(expected_related_units(reltype='ha'))
except (NotImplementedError, KeyError):
pass
return len(ha_related_units) > 0 or config('vip') or config('dns-ha') | [
" Determine if the unit expects to be in HA\n\n Check juju goal-state if ha relation is expected, check for VIP or dns-ha\n settings which indicate the unit should expect to be related to hacluster.\n\n @returns boolean\n "
] |
Please provide a description of the function:def generate_ha_relation_data(service, extra_settings=None):
_haproxy_res = 'res_{}_haproxy'.format(service)
_relation_data = {
'resources': {
_haproxy_res: 'lsb:haproxy',
},
'resource_params': {
_haproxy_res: 'op ... | [
" Generate relation data for ha relation\n\n Based on configuration options and unit interfaces, generate a json\n encoded dict of relation data items for the hacluster relation,\n providing configuration for DNS HA or VIP's + haproxy clone sets.\n\n Example of supplying additional settings::\n\n ... |
Please provide a description of the function:def update_hacluster_dns_ha(service, relation_data,
crm_ocf='ocf:maas:dns'):
# Validate the charm environment for DNS HA
assert_charm_supports_dns_ha()
settings = ['os-admin-hostname', 'os-internal-hostname',
'os-... | [
" Configure DNS-HA resources based on provided configuration\n\n @param service: Name of the service being configured\n @param relation_data: Pointer to dictionary of relation data.\n @param crm_ocf: Corosync Open Cluster Framework resource agent to use for\n DNS HA\n "
] |
Please provide a description of the function:def get_vip_settings(vip):
iface = get_iface_for_address(vip)
netmask = get_netmask_for_address(vip)
fallback = False
if iface is None:
iface = config('vip_iface')
fallback = True
if netmask is None:
netmask = config('vip_cidr... | [
"Calculate which nic is on the correct network for the given vip.\n\n If nic or netmask discovery fail then fallback to using charm supplied\n config. If fallback is used this is indicated via the fallback variable.\n\n @param vip: VIP to lookup nic and cidr for.\n @returns (str, str, bool): eg (iface, ... |
Please provide a description of the function:def update_hacluster_vip(service, relation_data):
cluster_config = get_hacluster_config()
vip_group = []
vips_to_delete = []
for vip in cluster_config['vip'].split():
if is_ipv6(vip):
res_vip = 'ocf:heartbeat:IPv6addr'
vip... | [
" Configure VIP resources based on provided configuration\n\n @param service: Name of the service being configured\n @param relation_data: Pointer to dictionary of relation data.\n "
] |
Please provide a description of the function:def _add_services(self, this_service, other_services):
if this_service['name'] != os.path.basename(os.getcwd()):
s = this_service['name']
msg = "The charm's root directory name needs to be {}".format(s)
amulet.raise_status... | [
"Add services.\n\n Add services to the deployment where this_service is the local charm\n that we're testing and other_services are the other services that\n are being used in the local amulet tests.\n "
] |
Please provide a description of the function:def _add_relations(self, relations):
for k, v in six.iteritems(relations):
self.d.relate(k, v) | [
"Add all of the relations for the services."
] |
Please provide a description of the function:def _configure_services(self, configs):
for service, config in six.iteritems(configs):
self.d.configure(service, config) | [
"Configure all of the services."
] |
Please provide a description of the function:def _deploy(self):
timeout = int(os.environ.get('AMULET_SETUP_TIMEOUT', 900))
try:
self.d.setup(timeout=timeout)
self.d.sentry.wait(timeout=timeout)
except amulet.helpers.TimeoutError:
amulet.raise_status(
... | [
"Deploy environment and wait for all hooks to finish executing."
] |
Please provide a description of the function:def _init_ca(self):
if not exists(path_join(self.ca_dir, 'ca.cnf')):
with open(path_join(self.ca_dir, 'ca.cnf'), 'w') as fh:
fh.write(
CA_CONF_TEMPLATE % (self.get_conf_variables()))
if not exists(path... | [
"Generate the root ca's cert and key.\n "
] |
Please provide a description of the function:def format_endpoint(schema, addr, port, api_version):
return '{}://{}:{}/{}/'.format(schema, addr, port,
get_api_suffix(api_version)) | [
"Return a formatted keystone endpoint\n @param schema: http or https\n @param addr: ipv4/ipv6 host of the keystone service\n @param port: port of the keystone service\n @param api_version: 2 or 3\n @returns a fully formatted keystone endpoint\n "
] |
Please provide a description of the function:def get_keystone_manager(endpoint, api_version, **kwargs):
if api_version == 2:
return KeystoneManager2(endpoint, **kwargs)
if api_version == 3:
return KeystoneManager3(endpoint, **kwargs)
raise ValueError('No manager found for api version {}... | [
"Return a keystonemanager for the correct API version\n\n @param endpoint: the keystone endpoint to point client at\n @param api_version: version of the keystone api the client should use\n @param kwargs: token or username/tenant/password information\n @returns keystonemanager class used for interrogati... |
Please provide a description of the function:def get_keystone_manager_from_identity_service_context():
context = IdentityServiceContext()()
if not context:
msg = "Identity service context cannot be generated"
log(msg, level=ERROR)
raise ValueError(msg)
endpoint = format_endpoin... | [
"Return a keystonmanager generated from a\n instance of charmhelpers.contrib.openstack.context.IdentityServiceContext\n @returns keystonamenager instance\n "
] |
Please provide a description of the function:def resolve_service_id(self, service_name=None, service_type=None):
services = [s._info for s in self.api.services.list()]
service_name = service_name.lower()
for s in services:
name = s['name'].lower()
if service_typ... | [
"Find the service_id of a given service"
] |
Please provide a description of the function:def deactivate_lvm_volume_group(block_device):
'''
Deactivate any volume gruop associated with an LVM physical volume.
:param block_device: str: Full path to LVM physical volume
'''
vg = list_lvm_volume_group(block_device)
if vg:
cmd = ['vgch... | [] |
Please provide a description of the function:def remove_lvm_physical_volume(block_device):
'''
Remove LVM PV signatures from a given block device.
:param block_device: str: Full path of block device to scrub.
'''
p = Popen(['pvremove', '-ff', block_device],
stdin=PIPE)
p.communica... | [] |
Please provide a description of the function:def list_lvm_volume_group(block_device):
'''
List LVM volume group associated with a given block device.
Assumes block device is a valid LVM PV.
:param block_device: str: Full path of block device to inspect.
:returns: str: Name of volume group associa... | [] |
Please provide a description of the function:def list_logical_volumes(select_criteria=None, path_mode=False):
'''
List logical volumes
:param select_criteria: str: Limit list to those volumes matching this
criteria (see 'lvs -S help' for more details)
:param path_mode: ... | [] |
Please provide a description of the function:def create_logical_volume(lv_name, volume_group, size=None):
'''
Create a new logical volume in an existing volume group
:param lv_name: str: name of logical volume to be created.
:param volume_group: str: Name of volume group to use for the new volume.
... | [] |
Please provide a description of the function:def render(source, target, context, owner='root', group='root',
perms=0o444, templates_dir=None, encoding='UTF-8',
template_loader=None, config_template=None):
try:
from jinja2 import FileSystemLoader, Environment, exceptions
except... | [
"\n Render a template.\n\n The `source` path, if not absolute, is relative to the `templates_dir`.\n\n The `target` path should be absolute. It can also be `None`, in which\n case no file will be written.\n\n The context should be a dict containing the values to be replaced in the\n template.\n\n... |
Please provide a description of the function:def cached(func):
@wraps(func)
def wrapper(*args, **kwargs):
global cache
key = json.dumps((func, args, kwargs), sort_keys=True, default=str)
try:
return cache[key]
except KeyError:
pass # Drop out of the ... | [
"Cache return values for multiple executions of func + args\n\n For example::\n\n @cached\n def unit_get(attribute):\n pass\n\n unit_get('test')\n\n will cache the result of unit_get + 'test' for future calls.\n "
] |
Please provide a description of the function:def flush(key):
flush_list = []
for item in cache:
if key in item:
flush_list.append(item)
for item in flush_list:
del cache[item] | [
"Flushes any entries from function cache where the\n key is found in the function+args "
] |
Please provide a description of the function:def log(message, level=None):
command = ['juju-log']
if level:
command += ['-l', level]
if not isinstance(message, six.string_types):
message = repr(message)
command += [message[:SH_MAX_ARG]]
# Missing juju-log should not cause failur... | [
"Write a message to the juju log"
] |
Please provide a description of the function:def execution_environment():
context = {}
context['conf'] = config()
if relation_id():
context['reltype'] = relation_type()
context['relid'] = relation_id()
context['rel'] = relation_get()
context['unit'] = local_unit()
contex... | [
"A convenient bundling of the current execution context"
] |
Please provide a description of the function:def relation_id(relation_name=None, service_or_unit=None):
if not relation_name and not service_or_unit:
return os.environ.get('JUJU_RELATION_ID', None)
elif relation_name and service_or_unit:
service_name = service_or_unit.split('/')[0]
... | [
"The relation ID for the current or a specified relation"
] |
Please provide a description of the function:def principal_unit():
# Juju 2.2 and above provides JUJU_PRINCIPAL_UNIT
principal_unit = os.environ.get('JUJU_PRINCIPAL_UNIT', None)
# If it's empty, then this unit is the principal
if principal_unit == '':
return os.environ['JUJU_UNIT_NAME']
... | [
"Returns the principal unit of this unit, otherwise None"
] |
Please provide a description of the function:def remote_service_name(relid=None):
if relid is None:
unit = remote_unit()
else:
units = related_units(relid)
unit = units[0] if units else None
return unit.split('/')[0] if unit else None | [
"The remote service name for a given relation-id (or the current relation)"
] |
Please provide a description of the function:def config(scope=None):
global _cache_config
config_cmd_line = ['config-get', '--all', '--format=json']
try:
# JSON Decode Exception for Python3.5+
exc_json = json.decoder.JSONDecodeError
except AttributeError:
# JSON Decode Excep... | [
"\n Get the juju charm configuration (scope==None) or individual key,\n (scope=str). The returned value is a Python data structure loaded as\n JSON from the Juju config command.\n\n :param scope: If set, return the value for the specified key.\n :type scope: Optional[str]\n :returns: Either the w... |
Please provide a description of the function:def relation_get(attribute=None, unit=None, rid=None):
_args = ['relation-get', '--format=json']
if rid:
_args.append('-r')
_args.append(rid)
_args.append(attribute or '-')
if unit:
_args.append(unit)
try:
return json.... | [
"Get relation information"
] |
Please provide a description of the function:def relation_set(relation_id=None, relation_settings=None, **kwargs):
relation_settings = relation_settings if relation_settings else {}
relation_cmd_line = ['relation-set']
accepts_file = "--file" in subprocess.check_output(
relation_cmd_line + ["--... | [
"Set relation information for the current unit"
] |
Please provide a description of the function:def relation_clear(r_id=None):
''' Clears any relation data already set on relation r_id '''
settings = relation_get(rid=r_id,
unit=local_unit())
for setting in settings:
if setting not in ['public-address', 'private-address']:... | [] |
Please provide a description of the function:def relation_ids(reltype=None):
reltype = reltype or relation_type()
relid_cmd_line = ['relation-ids', '--format=json']
if reltype is not None:
relid_cmd_line.append(reltype)
return json.loads(
subprocess.check_output(relid_cmd_li... | [
"A list of relation_ids"
] |
Please provide a description of the function:def related_units(relid=None):
relid = relid or relation_id()
units_cmd_line = ['relation-list', '--format=json']
if relid is not None:
units_cmd_line.extend(('-r', relid))
return json.loads(
subprocess.check_output(units_cmd_line).decode... | [
"A list of related units"
] |
Please provide a description of the function:def expected_peer_units():
if not has_juju_version("2.4.0"):
# goal-state first appeared in 2.4.0.
raise NotImplementedError("goal-state")
_goal_state = goal_state()
return (key for key in _goal_state['units']
if '/' in key and ke... | [
"Get a generator for units we expect to join peer relation based on\n goal-state.\n\n The local unit is excluded from the result to make it easy to gauge\n completion of all peers joining the relation with existing hook tools.\n\n Example usage:\n log('peer {} of {} joined peer relation'\n .fo... |
Please provide a description of the function:def expected_related_units(reltype=None):
if not has_juju_version("2.4.4"):
# goal-state existed in 2.4.0, but did not list individual units to
# join a relation in 2.4.1 through 2.4.3. (LP: #1794739)
raise NotImplementedError("goal-state rel... | [
"Get a generator for units we expect to join relation based on\n goal-state.\n\n Note that you can not use this function for the peer relation, take a look\n at expected_peer_units() for that.\n\n This function will raise KeyError if you request information for a\n relation type for which juju goal-s... |
Please provide a description of the function:def relation_for_unit(unit=None, rid=None):
unit = unit or remote_unit()
relation = relation_get(unit=unit, rid=rid)
for key in relation:
if key.endswith('-list'):
relation[key] = relation[key].split()
relation['__unit__'] = unit
... | [
"Get the json represenation of a unit's relation"
] |
Please provide a description of the function:def relations_for_id(relid=None):
relation_data = []
relid = relid or relation_ids()
for unit in related_units(relid):
unit_data = relation_for_unit(unit, relid)
unit_data['__relid__'] = relid
relation_data.append(unit_data)
retur... | [
"Get relations of a specific relation ID"
] |
Please provide a description of the function:def relations_of_type(reltype=None):
relation_data = []
reltype = reltype or relation_type()
for relid in relation_ids(reltype):
for relation in relations_for_id(relid):
relation['__relid__'] = relid
relation_data.append(relat... | [
"Get relations of a specific type"
] |
Please provide a description of the function:def metadata():
with open(os.path.join(charm_dir(), 'metadata.yaml')) as md:
return yaml.safe_load(md) | [
"Get the current charm metadata.yaml contents as a python object"
] |
Please provide a description of the function:def _metadata_unit(unit):
basedir = os.sep.join(charm_dir().split(os.sep)[:-2])
unitdir = 'unit-{}'.format(unit.replace(os.sep, '-'))
joineddir = os.path.join(basedir, unitdir, 'charm', 'metadata.yaml')
if not os.path.exists(joineddir):
return No... | [
"Given the name of a unit (e.g. apache2/0), get the unit charm's\n metadata.yaml. Very similar to metadata() but allows us to inspect\n other units. Unit needs to be co-located, such as a subordinate or\n principal/primary.\n\n :returns: metadata.yaml as a python object.\n\n "
] |
Please provide a description of the function:def relation_types():
rel_types = []
md = metadata()
for key in ('provides', 'requires', 'peers'):
section = md.get(key)
if section:
rel_types.extend(section.keys())
return rel_types | [
"Get a list of relation types supported by this charm"
] |
Please provide a description of the function:def peer_relation_id():
'''Get the peers relation id if a peers relation has been joined, else None.'''
md = metadata()
section = md.get('peers')
if section:
for key in section:
relids = relation_ids(key)
if relids:
... | [] |
Please provide a description of the function:def relation_to_role_and_interface(relation_name):
_metadata = metadata()
for role in ('provides', 'requires', 'peers'):
interface = _metadata.get(role, {}).get(relation_name, {}).get('interface')
if interface:
return role, interface
... | [
"\n Given the name of a relation, return the role and the name of the interface\n that relation uses (where role is one of ``provides``, ``requires``, or ``peers``).\n\n :returns: A tuple containing ``(role, interface)``, or ``(None, None)``.\n "
] |
Please provide a description of the function:def role_and_interface_to_relations(role, interface_name):
_metadata = metadata()
results = []
for relation_name, relation in _metadata.get(role, {}).items():
if relation['interface'] == interface_name:
results.append(relation_name)
r... | [
"\n Given a role and interface name, return a list of relation names for the\n current charm that use that interface under that role (where role is one\n of ``provides``, ``requires``, or ``peers``).\n\n :returns: A list of relation names.\n "
] |
Please provide a description of the function:def interface_to_relations(interface_name):
results = []
for role in ('provides', 'requires', 'peers'):
results.extend(role_and_interface_to_relations(role, interface_name))
return results | [
"\n Given an interface, return a list of relation names for the current\n charm that use that interface.\n\n :returns: A list of relation names.\n "
] |
Please provide a description of the function:def relations():
rels = {}
for reltype in relation_types():
relids = {}
for relid in relation_ids(reltype):
units = {local_unit(): relation_get(unit=local_unit(), rid=relid)}
for unit in related_units(relid):
... | [
"Get a nested dictionary of relation data for all related units"
] |
Please provide a description of the function:def is_relation_made(relation, keys='private-address'):
'''
Determine whether a relation is established by checking for
presence of key(s). If a list of keys is provided, they
must all be present for the relation to be identified as made
'''
if isins... | [] |
Please provide a description of the function:def _port_op(op_name, port, protocol="TCP"):
_args = [op_name]
icmp = protocol.upper() == "ICMP"
if icmp:
_args.append(protocol)
else:
_args.append('{}/{}'.format(port, protocol))
try:
subprocess.check_call(_args)
except s... | [
"Open or close a service network port"
] |
Please provide a description of the function:def open_ports(start, end, protocol="TCP"):
_args = ['open-port']
_args.append('{}-{}/{}'.format(start, end, protocol))
subprocess.check_call(_args) | [
"Opens a range of service network ports"
] |
Please provide a description of the function:def unit_get(attribute):
_args = ['unit-get', '--format=json', attribute]
try:
return json.loads(subprocess.check_output(_args).decode('UTF-8'))
except ValueError:
return None | [
"Get the unit ID for the remote unit"
] |
Please provide a description of the function:def storage_get(attribute=None, storage_id=None):
_args = ['storage-get', '--format=json']
if storage_id:
_args.extend(('-s', storage_id))
if attribute:
_args.append(attribute)
try:
return json.loads(subprocess.check_output(_args)... | [
"Get storage attributes"
] |
Please provide a description of the function:def storage_list(storage_name=None):
_args = ['storage-list', '--format=json']
if storage_name:
_args.append(storage_name)
try:
return json.loads(subprocess.check_output(_args).decode('UTF-8'))
except ValueError:
return None
e... | [
"List the storage IDs for the unit"
] |
Please provide a description of the function:def charm_dir():
d = os.environ.get('JUJU_CHARM_DIR')
if d is not None:
return d
return os.environ.get('CHARM_DIR') | [
"Return the root directory of the current charm"
] |
Please provide a description of the function:def action_get(key=None):
cmd = ['action-get']
if key is not None:
cmd.append(key)
cmd.append('--format=json')
action_data = json.loads(subprocess.check_output(cmd).decode('UTF-8'))
return action_data | [
"Gets the value of an action parameter, or all key/value param pairs"
] |
Please provide a description of the function:def action_set(values):
cmd = ['action-set']
for k, v in list(values.items()):
cmd.append('{}={}'.format(k, v))
subprocess.check_call(cmd) | [
"Sets the values to be returned after the action finishes"
] |
Please provide a description of the function:def status_set(workload_state, message):
valid_states = ['maintenance', 'blocked', 'waiting', 'active']
if workload_state not in valid_states:
raise ValueError(
'{!r} is not a valid workload state'.format(workload_state)
)
cmd = [... | [
"Set the workload state with a message\n\n Use status-set to set the workload state with a message which is visible\n to the user via juju status. If the status-set command is not found then\n assume this is juju < 1.23 and juju-log the message unstead.\n\n workload_state -- valid juju workload state.\n... |
Please provide a description of the function:def status_get():
cmd = ['status-get', "--format=json", "--include-data"]
try:
raw_status = subprocess.check_output(cmd)
except OSError as e:
if e.errno == errno.ENOENT:
return ('unknown', "")
else:
raise
e... | [
"Retrieve the previously set juju workload state and message\n\n If the status-get command is not found then assume this is juju < 1.23 and\n return 'unknown', \"\"\n\n "
] |
Please provide a description of the function:def application_version_set(version):
cmd = ['application-version-set']
cmd.append(version)
try:
subprocess.check_call(cmd)
except OSError:
log("Application Version: {}".format(version)) | [
"Charm authors may trigger this command from any hook to output what\n version of the application is running. This could be a package version,\n for instance postgres version 9.5. It could also be a build number or\n version control revision identifier, for instance git sha 6fb7ba68. "
] |
Please provide a description of the function:def leader_get(attribute=None):
cmd = ['leader-get', '--format=json'] + [attribute or '-']
return json.loads(subprocess.check_output(cmd).decode('UTF-8')) | [
"Juju leader get value(s)"
] |
Please provide a description of the function:def leader_set(settings=None, **kwargs):
# Don't log secrets.
# log("Juju leader-set '%s'" % (settings), level=DEBUG)
cmd = ['leader-set']
settings = settings or {}
settings.update(kwargs)
for k, v in settings.items():
if v is None:
... | [
"Juju leader set value(s)"
] |
Please provide a description of the function:def payload_register(ptype, klass, pid):
cmd = ['payload-register']
for x in [ptype, klass, pid]:
cmd.append(x)
subprocess.check_call(cmd) | [
" is used while a hook is running to let Juju know that a\n payload has been started."
] |
Please provide a description of the function:def payload_unregister(klass, pid):
cmd = ['payload-unregister']
for x in [klass, pid]:
cmd.append(x)
subprocess.check_call(cmd) | [
" is used while a hook is running to let Juju know\n that a payload has been manually stopped. The <class> and <id> provided\n must match a payload that has been previously registered with juju using\n payload-register."
] |
Please provide a description of the function:def payload_status_set(klass, pid, status):
cmd = ['payload-status-set']
for x in [klass, pid, status]:
cmd.append(x)
subprocess.check_call(cmd) | [
"is used to update the current status of a registered payload.\n The <class> and <id> provided must match a payload that has been previously\n registered with juju using payload-register. The <status> must be one of the\n follow: starting, started, stopping, stopped"
] |
Please provide a description of the function:def resource_get(name):
if not name:
return False
cmd = ['resource-get', name]
try:
return subprocess.check_output(cmd).decode('UTF-8')
except subprocess.CalledProcessError:
return False | [
"used to fetch the resource path of the given name.\n\n <name> must match a name of defined resource in metadata.yaml\n\n returns either a path or False if resource not available\n "
] |
Please provide a description of the function:def juju_version():
# Per https://bugs.launchpad.net/juju-core/+bug/1455368/comments/1
jujud = glob.glob('/var/lib/juju/tools/machine-*/jujud')[0]
return subprocess.check_output([jujud, 'version'],
universal_newlines=True).... | [
"Full version string (eg. '1.23.3.1-trusty-amd64')"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.