id
int32 0
252k
| repo
stringlengths 7
55
| path
stringlengths 4
127
| func_name
stringlengths 1
88
| original_string
stringlengths 75
19.8k
| language
stringclasses 1
value | code
stringlengths 75
19.8k
| code_tokens
list | docstring
stringlengths 3
17.3k
| docstring_tokens
list | sha
stringlengths 40
40
| url
stringlengths 87
242
|
|---|---|---|---|---|---|---|---|---|---|---|---|
12,700
|
juju/charm-helpers
|
charmhelpers/fetch/ubuntu.py
|
_write_apt_gpg_keyfile
|
def _write_apt_gpg_keyfile(key_name, key_material):
"""Writes GPG key material into a file at a provided path.
:param key_name: A key name to use for a key file (could be a fingerprint)
:type key_name: str
:param key_material: A GPG key material (binary)
:type key_material: (str, bytes)
"""
with open('/etc/apt/trusted.gpg.d/{}.gpg'.format(key_name),
'wb') as keyf:
keyf.write(key_material)
|
python
|
def _write_apt_gpg_keyfile(key_name, key_material):
"""Writes GPG key material into a file at a provided path.
:param key_name: A key name to use for a key file (could be a fingerprint)
:type key_name: str
:param key_material: A GPG key material (binary)
:type key_material: (str, bytes)
"""
with open('/etc/apt/trusted.gpg.d/{}.gpg'.format(key_name),
'wb') as keyf:
keyf.write(key_material)
|
[
"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.
:param key_name: A key name to use for a key file (could be a fingerprint)
:type key_name: str
:param key_material: A GPG key material (binary)
:type key_material: (str, bytes)
|
[
"Writes",
"GPG",
"key",
"material",
"into",
"a",
"file",
"at",
"a",
"provided",
"path",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/fetch/ubuntu.py#L440-L450
|
12,701
|
juju/charm-helpers
|
charmhelpers/fetch/ubuntu.py
|
_add_apt_repository
|
def _add_apt_repository(spec):
"""Add the spec using add_apt_repository
:param spec: the parameter to pass to add_apt_repository
:type spec: str
"""
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:1433761). This is not the case
# LTS and non-LTS releases below bionic.
_run_with_retries(['add-apt-repository', '--yes', spec],
cmd_env=env_proxy_settings(['https']))
|
python
|
def _add_apt_repository(spec):
"""Add the spec using add_apt_repository
:param spec: the parameter to pass to add_apt_repository
:type spec: str
"""
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:1433761). This is not the case
# LTS and non-LTS releases below bionic.
_run_with_retries(['add-apt-repository', '--yes', spec],
cmd_env=env_proxy_settings(['https']))
|
[
"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:1433761). This is not the case",
"# LTS and non-LTS releases below bionic.",
"_run_with_retries",
"(",
"[",
"'add-apt-repository'",
",",
"'--yes'",
",",
"spec",
"]",
",",
"cmd_env",
"=",
"env_proxy_settings",
"(",
"[",
"'https'",
"]",
")",
")"
] |
Add the spec using add_apt_repository
:param spec: the parameter to pass to add_apt_repository
:type spec: str
|
[
"Add",
"the",
"spec",
"using",
"add_apt_repository"
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/fetch/ubuntu.py#L560-L573
|
12,702
|
juju/charm-helpers
|
charmhelpers/fetch/ubuntu.py
|
_add_cloud_distro_check
|
def _add_cloud_distro_check(cloud_archive_release, openstack_release):
"""Add the cloud pocket, but also check the cloud_archive_release against
the current distro, and use the openstack_release as the full lookup.
This just calls _add_cloud_pocket() with the openstack_release as pocket
to get the correct cloud-archive.list for dpkg to work with.
:param cloud_archive_release:String, codename for the distro release.
:param openstack_release: String, spec for the release to look up in the
CLOUD_ARCHIVE_POCKETS
:raises: SourceConfigError if this is the wrong distro, or the pocket spec
doesn't exist.
"""
_verify_is_ubuntu_rel(cloud_archive_release, openstack_release)
_add_cloud_pocket("{}-{}".format(cloud_archive_release, openstack_release))
|
python
|
def _add_cloud_distro_check(cloud_archive_release, openstack_release):
"""Add the cloud pocket, but also check the cloud_archive_release against
the current distro, and use the openstack_release as the full lookup.
This just calls _add_cloud_pocket() with the openstack_release as pocket
to get the correct cloud-archive.list for dpkg to work with.
:param cloud_archive_release:String, codename for the distro release.
:param openstack_release: String, spec for the release to look up in the
CLOUD_ARCHIVE_POCKETS
:raises: SourceConfigError if this is the wrong distro, or the pocket spec
doesn't exist.
"""
_verify_is_ubuntu_rel(cloud_archive_release, openstack_release)
_add_cloud_pocket("{}-{}".format(cloud_archive_release, openstack_release))
|
[
"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
the current distro, and use the openstack_release as the full lookup.
This just calls _add_cloud_pocket() with the openstack_release as pocket
to get the correct cloud-archive.list for dpkg to work with.
:param cloud_archive_release:String, codename for the distro release.
:param openstack_release: String, spec for the release to look up in the
CLOUD_ARCHIVE_POCKETS
:raises: SourceConfigError if this is the wrong distro, or the pocket spec
doesn't exist.
|
[
"Add",
"the",
"cloud",
"pocket",
"but",
"also",
"check",
"the",
"cloud_archive_release",
"against",
"the",
"current",
"distro",
"and",
"use",
"the",
"openstack_release",
"as",
"the",
"full",
"lookup",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/fetch/ubuntu.py#L617-L631
|
12,703
|
juju/charm-helpers
|
charmhelpers/fetch/ubuntu.py
|
_verify_is_ubuntu_rel
|
def _verify_is_ubuntu_rel(release, os_release):
"""Verify that the release is in the same as the current ubuntu release.
:param release: String, lowercase for the release.
:param os_release: String, the os_release being asked for
:raises: SourceConfigError if the release is not the same as the ubuntu
release.
"""
ubuntu_rel = get_distrib_codename()
if release != ubuntu_rel:
raise SourceConfigError(
'Invalid Cloud Archive release specified: {}-{} on this Ubuntu'
'version ({})'.format(release, os_release, ubuntu_rel))
|
python
|
def _verify_is_ubuntu_rel(release, os_release):
"""Verify that the release is in the same as the current ubuntu release.
:param release: String, lowercase for the release.
:param os_release: String, the os_release being asked for
:raises: SourceConfigError if the release is not the same as the ubuntu
release.
"""
ubuntu_rel = get_distrib_codename()
if release != ubuntu_rel:
raise SourceConfigError(
'Invalid Cloud Archive release specified: {}-{} on this Ubuntu'
'version ({})'.format(release, os_release, ubuntu_rel))
|
[
"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",
",",
"os_release",
",",
"ubuntu_rel",
")",
")"
] |
Verify that the release is in the same as the current ubuntu release.
:param release: String, lowercase for the release.
:param os_release: String, the os_release being asked for
:raises: SourceConfigError if the release is not the same as the ubuntu
release.
|
[
"Verify",
"that",
"the",
"release",
"is",
"in",
"the",
"same",
"as",
"the",
"current",
"ubuntu",
"release",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/fetch/ubuntu.py#L634-L646
|
12,704
|
juju/charm-helpers
|
charmhelpers/fetch/ubuntu.py
|
_run_with_retries
|
def _run_with_retries(cmd, max_retries=CMD_RETRY_COUNT, retry_exitcodes=(1,),
retry_message="", cmd_env=None):
"""Run a command and retry until success or max_retries is reached.
:param: cmd: str: The apt command to run.
:param: max_retries: int: The number of retries to attempt on a fatal
command. Defaults to CMD_RETRY_COUNT.
:param: retry_exitcodes: tuple: Optional additional exit codes to retry.
Defaults to retry on exit code 1.
:param: retry_message: str: Optional log prefix emitted during retries.
:param: cmd_env: dict: Environment variables to add to the command run.
"""
env = None
kwargs = {}
if cmd_env:
env = os.environ.copy()
env.update(cmd_env)
kwargs['env'] = env
if not retry_message:
retry_message = "Failed executing '{}'".format(" ".join(cmd))
retry_message += ". Will retry in {} seconds".format(CMD_RETRY_DELAY)
retry_count = 0
result = None
retry_results = (None,) + retry_exitcodes
while result in retry_results:
try:
# result = subprocess.check_call(cmd, env=env)
result = subprocess.check_call(cmd, **kwargs)
except subprocess.CalledProcessError as e:
retry_count = retry_count + 1
if retry_count > max_retries:
raise
result = e.returncode
log(retry_message)
time.sleep(CMD_RETRY_DELAY)
|
python
|
def _run_with_retries(cmd, max_retries=CMD_RETRY_COUNT, retry_exitcodes=(1,),
retry_message="", cmd_env=None):
"""Run a command and retry until success or max_retries is reached.
:param: cmd: str: The apt command to run.
:param: max_retries: int: The number of retries to attempt on a fatal
command. Defaults to CMD_RETRY_COUNT.
:param: retry_exitcodes: tuple: Optional additional exit codes to retry.
Defaults to retry on exit code 1.
:param: retry_message: str: Optional log prefix emitted during retries.
:param: cmd_env: dict: Environment variables to add to the command run.
"""
env = None
kwargs = {}
if cmd_env:
env = os.environ.copy()
env.update(cmd_env)
kwargs['env'] = env
if not retry_message:
retry_message = "Failed executing '{}'".format(" ".join(cmd))
retry_message += ". Will retry in {} seconds".format(CMD_RETRY_DELAY)
retry_count = 0
result = None
retry_results = (None,) + retry_exitcodes
while result in retry_results:
try:
# result = subprocess.check_call(cmd, env=env)
result = subprocess.check_call(cmd, **kwargs)
except subprocess.CalledProcessError as e:
retry_count = retry_count + 1
if retry_count > max_retries:
raise
result = e.returncode
log(retry_message)
time.sleep(CMD_RETRY_DELAY)
|
[
"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",
"if",
"not",
"retry_message",
":",
"retry_message",
"=",
"\"Failed executing '{}'\"",
".",
"format",
"(",
"\" \"",
".",
"join",
"(",
"cmd",
")",
")",
"retry_message",
"+=",
"\". Will retry in {} seconds\"",
".",
"format",
"(",
"CMD_RETRY_DELAY",
")",
"retry_count",
"=",
"0",
"result",
"=",
"None",
"retry_results",
"=",
"(",
"None",
",",
")",
"+",
"retry_exitcodes",
"while",
"result",
"in",
"retry_results",
":",
"try",
":",
"# result = subprocess.check_call(cmd, env=env)",
"result",
"=",
"subprocess",
".",
"check_call",
"(",
"cmd",
",",
"*",
"*",
"kwargs",
")",
"except",
"subprocess",
".",
"CalledProcessError",
"as",
"e",
":",
"retry_count",
"=",
"retry_count",
"+",
"1",
"if",
"retry_count",
">",
"max_retries",
":",
"raise",
"result",
"=",
"e",
".",
"returncode",
"log",
"(",
"retry_message",
")",
"time",
".",
"sleep",
"(",
"CMD_RETRY_DELAY",
")"
] |
Run a command and retry until success or max_retries is reached.
:param: cmd: str: The apt command to run.
:param: max_retries: int: The number of retries to attempt on a fatal
command. Defaults to CMD_RETRY_COUNT.
:param: retry_exitcodes: tuple: Optional additional exit codes to retry.
Defaults to retry on exit code 1.
:param: retry_message: str: Optional log prefix emitted during retries.
:param: cmd_env: dict: Environment variables to add to the command run.
|
[
"Run",
"a",
"command",
"and",
"retry",
"until",
"success",
"or",
"max_retries",
"is",
"reached",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/fetch/ubuntu.py#L649-L687
|
12,705
|
juju/charm-helpers
|
charmhelpers/fetch/ubuntu.py
|
_run_apt_command
|
def _run_apt_command(cmd, fatal=False):
"""Run an apt command with optional retries.
:param: cmd: str: The apt command to run.
:param: fatal: bool: Whether the command's output should be checked and
retried.
"""
# 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(
cmd, cmd_env=cmd_env, retry_exitcodes=(1, APT_NO_LOCK,),
retry_message="Couldn't acquire DPKG lock")
else:
env = os.environ.copy()
env.update(cmd_env)
subprocess.call(cmd, env=env)
|
python
|
def _run_apt_command(cmd, fatal=False):
"""Run an apt command with optional retries.
:param: cmd: str: The apt command to run.
:param: fatal: bool: Whether the command's output should be checked and
retried.
"""
# 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(
cmd, cmd_env=cmd_env, retry_exitcodes=(1, APT_NO_LOCK,),
retry_message="Couldn't acquire DPKG lock")
else:
env = os.environ.copy()
env.update(cmd_env)
subprocess.call(cmd, env=env)
|
[
"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",
"(",
"cmd",
",",
"cmd_env",
"=",
"cmd_env",
",",
"retry_exitcodes",
"=",
"(",
"1",
",",
"APT_NO_LOCK",
",",
")",
",",
"retry_message",
"=",
"\"Couldn't acquire DPKG lock\"",
")",
"else",
":",
"env",
"=",
"os",
".",
"environ",
".",
"copy",
"(",
")",
"env",
".",
"update",
"(",
"cmd_env",
")",
"subprocess",
".",
"call",
"(",
"cmd",
",",
"env",
"=",
"env",
")"
] |
Run an apt command with optional retries.
:param: cmd: str: The apt command to run.
:param: fatal: bool: Whether the command's output should be checked and
retried.
|
[
"Run",
"an",
"apt",
"command",
"with",
"optional",
"retries",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/fetch/ubuntu.py#L690-L708
|
12,706
|
juju/charm-helpers
|
charmhelpers/fetch/ubuntu.py
|
get_upstream_version
|
def get_upstream_version(package):
"""Determine upstream version based on installed package
@returns None (if not installed) or the upstream version
"""
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 known, but no version is currently installed.
return None
return apt_pkg.upstream_version(pkg.current_ver.ver_str)
|
python
|
def get_upstream_version(package):
"""Determine upstream version based on installed package
@returns None (if not installed) or the upstream version
"""
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 known, but no version is currently installed.
return None
return apt_pkg.upstream_version(pkg.current_ver.ver_str)
|
[
"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 known, but no version is currently installed.",
"return",
"None",
"return",
"apt_pkg",
".",
"upstream_version",
"(",
"pkg",
".",
"current_ver",
".",
"ver_str",
")"
] |
Determine upstream version based on installed package
@returns None (if not installed) or the upstream version
|
[
"Determine",
"upstream",
"version",
"based",
"on",
"installed",
"package"
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/fetch/ubuntu.py#L711-L728
|
12,707
|
juju/charm-helpers
|
charmhelpers/contrib/storage/linux/bcache.py
|
get_bcache_fs
|
def get_bcache_fs():
"""Return all cache sets
"""
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 d.startswith('register')])
return cacheset
|
python
|
def get_bcache_fs():
"""Return all cache sets
"""
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 d.startswith('register')])
return cacheset
|
[
"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",
"d",
".",
"startswith",
"(",
"'register'",
")",
"]",
")",
"return",
"cacheset"
] |
Return all cache sets
|
[
"Return",
"all",
"cache",
"sets"
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/storage/linux/bcache.py#L50-L60
|
12,708
|
juju/charm-helpers
|
charmhelpers/contrib/storage/linux/bcache.py
|
get_stats_action
|
def get_stats_action(cachespec, interval):
"""Action for getting bcache statistics for a given cachespec.
Cachespec can either be a device name, eg. 'sdb', which will retrieve
cache stats for the given device, or 'global', which will retrieve stats
for all cachesets
"""
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, separators=(',', ': '))
|
python
|
def get_stats_action(cachespec, interval):
"""Action for getting bcache statistics for a given cachespec.
Cachespec can either be a device name, eg. 'sdb', which will retrieve
cache stats for the given device, or 'global', which will retrieve stats
for all cachesets
"""
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, separators=(',', ': '))
|
[
"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",
",",
"separators",
"=",
"(",
"','",
",",
"': '",
")",
")"
] |
Action for getting bcache statistics for a given cachespec.
Cachespec can either be a device name, eg. 'sdb', which will retrieve
cache stats for the given device, or 'global', which will retrieve stats
for all cachesets
|
[
"Action",
"for",
"getting",
"bcache",
"statistics",
"for",
"a",
"given",
"cachespec",
".",
"Cachespec",
"can",
"either",
"be",
"a",
"device",
"name",
"eg",
".",
"sdb",
"which",
"will",
"retrieve",
"cache",
"stats",
"for",
"the",
"given",
"device",
"or",
"global",
"which",
"will",
"retrieve",
"stats",
"for",
"all",
"cachesets"
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/storage/linux/bcache.py#L63-L74
|
12,709
|
juju/charm-helpers
|
charmhelpers/contrib/storage/linux/bcache.py
|
Bcache.get_stats
|
def get_stats(self, interval):
"""Get cache stats
"""
intervaldir = 'stats_{}'.format(interval)
path = "{}/{}".format(self.cachepath, intervaldir)
out = dict()
for elem in os.listdir(path):
out[elem] = open('{}/{}'.format(path, elem)).read().strip()
return out
|
python
|
def get_stats(self, interval):
"""Get cache stats
"""
intervaldir = 'stats_{}'.format(interval)
path = "{}/{}".format(self.cachepath, intervaldir)
out = dict()
for elem in os.listdir(path):
out[elem] = open('{}/{}'.format(path, elem)).read().strip()
return out
|
[
"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",
"(",
")",
".",
"strip",
"(",
")",
"return",
"out"
] |
Get cache stats
|
[
"Get",
"cache",
"stats"
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/storage/linux/bcache.py#L39-L47
|
12,710
|
juju/charm-helpers
|
charmhelpers/contrib/openstack/ha/utils.py
|
update_dns_ha_resource_params
|
def update_dns_ha_resource_params(resources, resource_params,
relation_id=None,
crm_ocf='ocf:maas:dns'):
""" Configure DNS-HA resources based on provided configuration and
update resource dictionaries for the HA relation.
@param resources: Pointer to dictionary of resources.
Usually instantiated in ha_joined().
@param resource_params: Pointer to dictionary of resource parameters.
Usually instantiated in ha_joined()
@param relation_id: Relation ID of the ha relation
@param crm_ocf: Corosync Open Cluster Framework resource agent to use for
DNS HA
"""
_relation_data = {'resources': {}, 'resource_params': {}}
update_hacluster_dns_ha(charm_name(),
_relation_data,
crm_ocf)
resources.update(_relation_data['resources'])
resource_params.update(_relation_data['resource_params'])
relation_set(relation_id=relation_id, groups=_relation_data['groups'])
|
python
|
def update_dns_ha_resource_params(resources, resource_params,
relation_id=None,
crm_ocf='ocf:maas:dns'):
""" Configure DNS-HA resources based on provided configuration and
update resource dictionaries for the HA relation.
@param resources: Pointer to dictionary of resources.
Usually instantiated in ha_joined().
@param resource_params: Pointer to dictionary of resource parameters.
Usually instantiated in ha_joined()
@param relation_id: Relation ID of the ha relation
@param crm_ocf: Corosync Open Cluster Framework resource agent to use for
DNS HA
"""
_relation_data = {'resources': {}, 'resource_params': {}}
update_hacluster_dns_ha(charm_name(),
_relation_data,
crm_ocf)
resources.update(_relation_data['resources'])
resource_params.update(_relation_data['resource_params'])
relation_set(relation_id=relation_id, groups=_relation_data['groups'])
|
[
"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_name",
"(",
")",
",",
"_relation_data",
",",
"crm_ocf",
")",
"resources",
".",
"update",
"(",
"_relation_data",
"[",
"'resources'",
"]",
")",
"resource_params",
".",
"update",
"(",
"_relation_data",
"[",
"'resource_params'",
"]",
")",
"relation_set",
"(",
"relation_id",
"=",
"relation_id",
",",
"groups",
"=",
"_relation_data",
"[",
"'groups'",
"]",
")"
] |
Configure DNS-HA resources based on provided configuration and
update resource dictionaries for the HA relation.
@param resources: Pointer to dictionary of resources.
Usually instantiated in ha_joined().
@param resource_params: Pointer to dictionary of resource parameters.
Usually instantiated in ha_joined()
@param relation_id: Relation ID of the ha relation
@param crm_ocf: Corosync Open Cluster Framework resource agent to use for
DNS HA
|
[
"Configure",
"DNS",
"-",
"HA",
"resources",
"based",
"on",
"provided",
"configuration",
"and",
"update",
"resource",
"dictionaries",
"for",
"the",
"HA",
"relation",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/ha/utils.py#L77-L97
|
12,711
|
juju/charm-helpers
|
charmhelpers/contrib/openstack/ha/utils.py
|
expect_ha
|
def expect_ha():
""" Determine if the unit expects to be in HA
Check juju goal-state if ha relation is expected, check for VIP or dns-ha
settings which indicate the unit should expect to be related to hacluster.
@returns boolean
"""
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')
|
python
|
def expect_ha():
""" Determine if the unit expects to be in HA
Check juju goal-state if ha relation is expected, check for VIP or dns-ha
settings which indicate the unit should expect to be related to hacluster.
@returns boolean
"""
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')
|
[
"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
Check juju goal-state if ha relation is expected, check for VIP or dns-ha
settings which indicate the unit should expect to be related to hacluster.
@returns boolean
|
[
"Determine",
"if",
"the",
"unit",
"expects",
"to",
"be",
"in",
"HA"
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/ha/utils.py#L114-L127
|
12,712
|
juju/charm-helpers
|
charmhelpers/contrib/openstack/ha/utils.py
|
generate_ha_relation_data
|
def generate_ha_relation_data(service, extra_settings=None):
""" Generate relation data for ha relation
Based on configuration options and unit interfaces, generate a json
encoded dict of relation data items for the hacluster relation,
providing configuration for DNS HA or VIP's + haproxy clone sets.
Example of supplying additional settings::
COLO_CONSOLEAUTH = 'inf: res_nova_consoleauth grp_nova_vips'
AGENT_CONSOLEAUTH = 'ocf:openstack:nova-consoleauth'
AGENT_CA_PARAMS = 'op monitor interval="5s"'
ha_console_settings = {
'colocations': {'vip_consoleauth': COLO_CONSOLEAUTH},
'init_services': {'res_nova_consoleauth': 'nova-consoleauth'},
'resources': {'res_nova_consoleauth': AGENT_CONSOLEAUTH},
'resource_params': {'res_nova_consoleauth': AGENT_CA_PARAMS})
generate_ha_relation_data('nova', extra_settings=ha_console_settings)
@param service: Name of the service being configured
@param extra_settings: Dict of additional resource data
@returns dict: json encoded data for use with relation_set
"""
_haproxy_res = 'res_{}_haproxy'.format(service)
_relation_data = {
'resources': {
_haproxy_res: 'lsb:haproxy',
},
'resource_params': {
_haproxy_res: 'op monitor interval="5s"'
},
'init_services': {
_haproxy_res: 'haproxy'
},
'clones': {
'cl_{}_haproxy'.format(service): _haproxy_res
},
}
if extra_settings:
for k, v in extra_settings.items():
if _relation_data.get(k):
_relation_data[k].update(v)
else:
_relation_data[k] = v
if config('dns-ha'):
update_hacluster_dns_ha(service, _relation_data)
else:
update_hacluster_vip(service, _relation_data)
return {
'json_{}'.format(k): json.dumps(v, **JSON_ENCODE_OPTIONS)
for k, v in _relation_data.items() if v
}
|
python
|
def generate_ha_relation_data(service, extra_settings=None):
""" Generate relation data for ha relation
Based on configuration options and unit interfaces, generate a json
encoded dict of relation data items for the hacluster relation,
providing configuration for DNS HA or VIP's + haproxy clone sets.
Example of supplying additional settings::
COLO_CONSOLEAUTH = 'inf: res_nova_consoleauth grp_nova_vips'
AGENT_CONSOLEAUTH = 'ocf:openstack:nova-consoleauth'
AGENT_CA_PARAMS = 'op monitor interval="5s"'
ha_console_settings = {
'colocations': {'vip_consoleauth': COLO_CONSOLEAUTH},
'init_services': {'res_nova_consoleauth': 'nova-consoleauth'},
'resources': {'res_nova_consoleauth': AGENT_CONSOLEAUTH},
'resource_params': {'res_nova_consoleauth': AGENT_CA_PARAMS})
generate_ha_relation_data('nova', extra_settings=ha_console_settings)
@param service: Name of the service being configured
@param extra_settings: Dict of additional resource data
@returns dict: json encoded data for use with relation_set
"""
_haproxy_res = 'res_{}_haproxy'.format(service)
_relation_data = {
'resources': {
_haproxy_res: 'lsb:haproxy',
},
'resource_params': {
_haproxy_res: 'op monitor interval="5s"'
},
'init_services': {
_haproxy_res: 'haproxy'
},
'clones': {
'cl_{}_haproxy'.format(service): _haproxy_res
},
}
if extra_settings:
for k, v in extra_settings.items():
if _relation_data.get(k):
_relation_data[k].update(v)
else:
_relation_data[k] = v
if config('dns-ha'):
update_hacluster_dns_ha(service, _relation_data)
else:
update_hacluster_vip(service, _relation_data)
return {
'json_{}'.format(k): json.dumps(v, **JSON_ENCODE_OPTIONS)
for k, v in _relation_data.items() if v
}
|
[
"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 monitor interval=\"5s\"'",
"}",
",",
"'init_services'",
":",
"{",
"_haproxy_res",
":",
"'haproxy'",
"}",
",",
"'clones'",
":",
"{",
"'cl_{}_haproxy'",
".",
"format",
"(",
"service",
")",
":",
"_haproxy_res",
"}",
",",
"}",
"if",
"extra_settings",
":",
"for",
"k",
",",
"v",
"in",
"extra_settings",
".",
"items",
"(",
")",
":",
"if",
"_relation_data",
".",
"get",
"(",
"k",
")",
":",
"_relation_data",
"[",
"k",
"]",
".",
"update",
"(",
"v",
")",
"else",
":",
"_relation_data",
"[",
"k",
"]",
"=",
"v",
"if",
"config",
"(",
"'dns-ha'",
")",
":",
"update_hacluster_dns_ha",
"(",
"service",
",",
"_relation_data",
")",
"else",
":",
"update_hacluster_vip",
"(",
"service",
",",
"_relation_data",
")",
"return",
"{",
"'json_{}'",
".",
"format",
"(",
"k",
")",
":",
"json",
".",
"dumps",
"(",
"v",
",",
"*",
"*",
"JSON_ENCODE_OPTIONS",
")",
"for",
"k",
",",
"v",
"in",
"_relation_data",
".",
"items",
"(",
")",
"if",
"v",
"}"
] |
Generate relation data for ha relation
Based on configuration options and unit interfaces, generate a json
encoded dict of relation data items for the hacluster relation,
providing configuration for DNS HA or VIP's + haproxy clone sets.
Example of supplying additional settings::
COLO_CONSOLEAUTH = 'inf: res_nova_consoleauth grp_nova_vips'
AGENT_CONSOLEAUTH = 'ocf:openstack:nova-consoleauth'
AGENT_CA_PARAMS = 'op monitor interval="5s"'
ha_console_settings = {
'colocations': {'vip_consoleauth': COLO_CONSOLEAUTH},
'init_services': {'res_nova_consoleauth': 'nova-consoleauth'},
'resources': {'res_nova_consoleauth': AGENT_CONSOLEAUTH},
'resource_params': {'res_nova_consoleauth': AGENT_CA_PARAMS})
generate_ha_relation_data('nova', extra_settings=ha_console_settings)
@param service: Name of the service being configured
@param extra_settings: Dict of additional resource data
@returns dict: json encoded data for use with relation_set
|
[
"Generate",
"relation",
"data",
"for",
"ha",
"relation"
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/ha/utils.py#L130-L186
|
12,713
|
juju/charm-helpers
|
charmhelpers/contrib/openstack/ha/utils.py
|
update_hacluster_dns_ha
|
def update_hacluster_dns_ha(service, relation_data,
crm_ocf='ocf:maas:dns'):
""" Configure DNS-HA resources based on provided configuration
@param service: Name of the service being configured
@param relation_data: Pointer to dictionary of relation data.
@param crm_ocf: Corosync Open Cluster Framework resource agent to use for
DNS HA
"""
# Validate the charm environment for DNS HA
assert_charm_supports_dns_ha()
settings = ['os-admin-hostname', 'os-internal-hostname',
'os-public-hostname', 'os-access-hostname']
# Check which DNS settings are set and update dictionaries
hostname_group = []
for setting in settings:
hostname = config(setting)
if hostname is None:
log('DNS HA: Hostname setting {} is None. Ignoring.'
''.format(setting),
DEBUG)
continue
m = re.search('os-(.+?)-hostname', setting)
if m:
endpoint_type = m.group(1)
# resolve_address's ADDRESS_MAP uses 'int' not 'internal'
if endpoint_type == 'internal':
endpoint_type = 'int'
else:
msg = ('Unexpected DNS hostname setting: {}. '
'Cannot determine endpoint_type name'
''.format(setting))
status_set('blocked', msg)
raise DNSHAException(msg)
hostname_key = 'res_{}_{}_hostname'.format(service, endpoint_type)
if hostname_key in hostname_group:
log('DNS HA: Resource {}: {} already exists in '
'hostname group - skipping'.format(hostname_key, hostname),
DEBUG)
continue
hostname_group.append(hostname_key)
relation_data['resources'][hostname_key] = crm_ocf
relation_data['resource_params'][hostname_key] = (
'params fqdn="{}" ip_address="{}"'
.format(hostname, resolve_address(endpoint_type=endpoint_type,
override=False)))
if len(hostname_group) >= 1:
log('DNS HA: Hostname group is set with {} as members. '
'Informing the ha relation'.format(' '.join(hostname_group)),
DEBUG)
relation_data['groups'] = {
DNSHA_GROUP_NAME.format(service=service): ' '.join(hostname_group)
}
else:
msg = 'DNS HA: Hostname group has no members.'
status_set('blocked', msg)
raise DNSHAException(msg)
|
python
|
def update_hacluster_dns_ha(service, relation_data,
crm_ocf='ocf:maas:dns'):
""" Configure DNS-HA resources based on provided configuration
@param service: Name of the service being configured
@param relation_data: Pointer to dictionary of relation data.
@param crm_ocf: Corosync Open Cluster Framework resource agent to use for
DNS HA
"""
# Validate the charm environment for DNS HA
assert_charm_supports_dns_ha()
settings = ['os-admin-hostname', 'os-internal-hostname',
'os-public-hostname', 'os-access-hostname']
# Check which DNS settings are set and update dictionaries
hostname_group = []
for setting in settings:
hostname = config(setting)
if hostname is None:
log('DNS HA: Hostname setting {} is None. Ignoring.'
''.format(setting),
DEBUG)
continue
m = re.search('os-(.+?)-hostname', setting)
if m:
endpoint_type = m.group(1)
# resolve_address's ADDRESS_MAP uses 'int' not 'internal'
if endpoint_type == 'internal':
endpoint_type = 'int'
else:
msg = ('Unexpected DNS hostname setting: {}. '
'Cannot determine endpoint_type name'
''.format(setting))
status_set('blocked', msg)
raise DNSHAException(msg)
hostname_key = 'res_{}_{}_hostname'.format(service, endpoint_type)
if hostname_key in hostname_group:
log('DNS HA: Resource {}: {} already exists in '
'hostname group - skipping'.format(hostname_key, hostname),
DEBUG)
continue
hostname_group.append(hostname_key)
relation_data['resources'][hostname_key] = crm_ocf
relation_data['resource_params'][hostname_key] = (
'params fqdn="{}" ip_address="{}"'
.format(hostname, resolve_address(endpoint_type=endpoint_type,
override=False)))
if len(hostname_group) >= 1:
log('DNS HA: Hostname group is set with {} as members. '
'Informing the ha relation'.format(' '.join(hostname_group)),
DEBUG)
relation_data['groups'] = {
DNSHA_GROUP_NAME.format(service=service): ' '.join(hostname_group)
}
else:
msg = 'DNS HA: Hostname group has no members.'
status_set('blocked', msg)
raise DNSHAException(msg)
|
[
"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-public-hostname'",
",",
"'os-access-hostname'",
"]",
"# Check which DNS settings are set and update dictionaries",
"hostname_group",
"=",
"[",
"]",
"for",
"setting",
"in",
"settings",
":",
"hostname",
"=",
"config",
"(",
"setting",
")",
"if",
"hostname",
"is",
"None",
":",
"log",
"(",
"'DNS HA: Hostname setting {} is None. Ignoring.'",
"''",
".",
"format",
"(",
"setting",
")",
",",
"DEBUG",
")",
"continue",
"m",
"=",
"re",
".",
"search",
"(",
"'os-(.+?)-hostname'",
",",
"setting",
")",
"if",
"m",
":",
"endpoint_type",
"=",
"m",
".",
"group",
"(",
"1",
")",
"# resolve_address's ADDRESS_MAP uses 'int' not 'internal'",
"if",
"endpoint_type",
"==",
"'internal'",
":",
"endpoint_type",
"=",
"'int'",
"else",
":",
"msg",
"=",
"(",
"'Unexpected DNS hostname setting: {}. '",
"'Cannot determine endpoint_type name'",
"''",
".",
"format",
"(",
"setting",
")",
")",
"status_set",
"(",
"'blocked'",
",",
"msg",
")",
"raise",
"DNSHAException",
"(",
"msg",
")",
"hostname_key",
"=",
"'res_{}_{}_hostname'",
".",
"format",
"(",
"service",
",",
"endpoint_type",
")",
"if",
"hostname_key",
"in",
"hostname_group",
":",
"log",
"(",
"'DNS HA: Resource {}: {} already exists in '",
"'hostname group - skipping'",
".",
"format",
"(",
"hostname_key",
",",
"hostname",
")",
",",
"DEBUG",
")",
"continue",
"hostname_group",
".",
"append",
"(",
"hostname_key",
")",
"relation_data",
"[",
"'resources'",
"]",
"[",
"hostname_key",
"]",
"=",
"crm_ocf",
"relation_data",
"[",
"'resource_params'",
"]",
"[",
"hostname_key",
"]",
"=",
"(",
"'params fqdn=\"{}\" ip_address=\"{}\"'",
".",
"format",
"(",
"hostname",
",",
"resolve_address",
"(",
"endpoint_type",
"=",
"endpoint_type",
",",
"override",
"=",
"False",
")",
")",
")",
"if",
"len",
"(",
"hostname_group",
")",
">=",
"1",
":",
"log",
"(",
"'DNS HA: Hostname group is set with {} as members. '",
"'Informing the ha relation'",
".",
"format",
"(",
"' '",
".",
"join",
"(",
"hostname_group",
")",
")",
",",
"DEBUG",
")",
"relation_data",
"[",
"'groups'",
"]",
"=",
"{",
"DNSHA_GROUP_NAME",
".",
"format",
"(",
"service",
"=",
"service",
")",
":",
"' '",
".",
"join",
"(",
"hostname_group",
")",
"}",
"else",
":",
"msg",
"=",
"'DNS HA: Hostname group has no members.'",
"status_set",
"(",
"'blocked'",
",",
"msg",
")",
"raise",
"DNSHAException",
"(",
"msg",
")"
] |
Configure DNS-HA resources based on provided configuration
@param service: Name of the service being configured
@param relation_data: Pointer to dictionary of relation data.
@param crm_ocf: Corosync Open Cluster Framework resource agent to use for
DNS HA
|
[
"Configure",
"DNS",
"-",
"HA",
"resources",
"based",
"on",
"provided",
"configuration"
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/ha/utils.py#L189-L250
|
12,714
|
juju/charm-helpers
|
charmhelpers/contrib/openstack/ha/utils.py
|
get_vip_settings
|
def get_vip_settings(vip):
"""Calculate which nic is on the correct network for the given vip.
If nic or netmask discovery fail then fallback to using charm supplied
config. If fallback is used this is indicated via the fallback variable.
@param vip: VIP to lookup nic and cidr for.
@returns (str, str, bool): eg (iface, netmask, fallback)
"""
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')
fallback = True
return iface, netmask, fallback
|
python
|
def get_vip_settings(vip):
"""Calculate which nic is on the correct network for the given vip.
If nic or netmask discovery fail then fallback to using charm supplied
config. If fallback is used this is indicated via the fallback variable.
@param vip: VIP to lookup nic and cidr for.
@returns (str, str, bool): eg (iface, netmask, fallback)
"""
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')
fallback = True
return iface, netmask, fallback
|
[
"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'",
")",
"fallback",
"=",
"True",
"return",
"iface",
",",
"netmask",
",",
"fallback"
] |
Calculate which nic is on the correct network for the given vip.
If nic or netmask discovery fail then fallback to using charm supplied
config. If fallback is used this is indicated via the fallback variable.
@param vip: VIP to lookup nic and cidr for.
@returns (str, str, bool): eg (iface, netmask, fallback)
|
[
"Calculate",
"which",
"nic",
"is",
"on",
"the",
"correct",
"network",
"for",
"the",
"given",
"vip",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/ha/utils.py#L253-L271
|
12,715
|
juju/charm-helpers
|
charmhelpers/contrib/openstack/ha/utils.py
|
update_hacluster_vip
|
def update_hacluster_vip(service, relation_data):
""" Configure VIP resources based on provided configuration
@param service: Name of the service being configured
@param relation_data: Pointer to dictionary of 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_params = 'ipv6addr'
else:
res_vip = 'ocf:heartbeat:IPaddr2'
vip_params = 'ip'
iface, netmask, fallback = get_vip_settings(vip)
vip_monitoring = 'op monitor depth="0" timeout="20s" interval="10s"'
if iface is not None:
# NOTE(jamespage): Delete old VIP resources
# Old style naming encoding iface in name
# does not work well in environments where
# interface/subnet wiring is not consistent
vip_key = 'res_{}_{}_vip'.format(service, iface)
if vip_key in vips_to_delete:
vip_key = '{}_{}'.format(vip_key, vip_params)
vips_to_delete.append(vip_key)
vip_key = 'res_{}_{}_vip'.format(
service,
hashlib.sha1(vip.encode('UTF-8')).hexdigest()[:7])
relation_data['resources'][vip_key] = res_vip
# NOTE(jamespage):
# Use option provided vip params if these where used
# instead of auto-detected values
if fallback:
relation_data['resource_params'][vip_key] = (
'params {ip}="{vip}" cidr_netmask="{netmask}" '
'nic="{iface}" {vip_monitoring}'.format(
ip=vip_params,
vip=vip,
iface=iface,
netmask=netmask,
vip_monitoring=vip_monitoring))
else:
# NOTE(jamespage):
# let heartbeat figure out which interface and
# netmask to configure, which works nicely
# when network interface naming is not
# consistent across units.
relation_data['resource_params'][vip_key] = (
'params {ip}="{vip}" {vip_monitoring}'.format(
ip=vip_params,
vip=vip,
vip_monitoring=vip_monitoring))
vip_group.append(vip_key)
if vips_to_delete:
try:
relation_data['delete_resources'].extend(vips_to_delete)
except KeyError:
relation_data['delete_resources'] = vips_to_delete
if len(vip_group) >= 1:
key = VIP_GROUP_NAME.format(service=service)
try:
relation_data['groups'][key] = ' '.join(vip_group)
except KeyError:
relation_data['groups'] = {
key: ' '.join(vip_group)
}
|
python
|
def update_hacluster_vip(service, relation_data):
""" Configure VIP resources based on provided configuration
@param service: Name of the service being configured
@param relation_data: Pointer to dictionary of 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_params = 'ipv6addr'
else:
res_vip = 'ocf:heartbeat:IPaddr2'
vip_params = 'ip'
iface, netmask, fallback = get_vip_settings(vip)
vip_monitoring = 'op monitor depth="0" timeout="20s" interval="10s"'
if iface is not None:
# NOTE(jamespage): Delete old VIP resources
# Old style naming encoding iface in name
# does not work well in environments where
# interface/subnet wiring is not consistent
vip_key = 'res_{}_{}_vip'.format(service, iface)
if vip_key in vips_to_delete:
vip_key = '{}_{}'.format(vip_key, vip_params)
vips_to_delete.append(vip_key)
vip_key = 'res_{}_{}_vip'.format(
service,
hashlib.sha1(vip.encode('UTF-8')).hexdigest()[:7])
relation_data['resources'][vip_key] = res_vip
# NOTE(jamespage):
# Use option provided vip params if these where used
# instead of auto-detected values
if fallback:
relation_data['resource_params'][vip_key] = (
'params {ip}="{vip}" cidr_netmask="{netmask}" '
'nic="{iface}" {vip_monitoring}'.format(
ip=vip_params,
vip=vip,
iface=iface,
netmask=netmask,
vip_monitoring=vip_monitoring))
else:
# NOTE(jamespage):
# let heartbeat figure out which interface and
# netmask to configure, which works nicely
# when network interface naming is not
# consistent across units.
relation_data['resource_params'][vip_key] = (
'params {ip}="{vip}" {vip_monitoring}'.format(
ip=vip_params,
vip=vip,
vip_monitoring=vip_monitoring))
vip_group.append(vip_key)
if vips_to_delete:
try:
relation_data['delete_resources'].extend(vips_to_delete)
except KeyError:
relation_data['delete_resources'] = vips_to_delete
if len(vip_group) >= 1:
key = VIP_GROUP_NAME.format(service=service)
try:
relation_data['groups'][key] = ' '.join(vip_group)
except KeyError:
relation_data['groups'] = {
key: ' '.join(vip_group)
}
|
[
"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_params",
"=",
"'ipv6addr'",
"else",
":",
"res_vip",
"=",
"'ocf:heartbeat:IPaddr2'",
"vip_params",
"=",
"'ip'",
"iface",
",",
"netmask",
",",
"fallback",
"=",
"get_vip_settings",
"(",
"vip",
")",
"vip_monitoring",
"=",
"'op monitor depth=\"0\" timeout=\"20s\" interval=\"10s\"'",
"if",
"iface",
"is",
"not",
"None",
":",
"# NOTE(jamespage): Delete old VIP resources",
"# Old style naming encoding iface in name",
"# does not work well in environments where",
"# interface/subnet wiring is not consistent",
"vip_key",
"=",
"'res_{}_{}_vip'",
".",
"format",
"(",
"service",
",",
"iface",
")",
"if",
"vip_key",
"in",
"vips_to_delete",
":",
"vip_key",
"=",
"'{}_{}'",
".",
"format",
"(",
"vip_key",
",",
"vip_params",
")",
"vips_to_delete",
".",
"append",
"(",
"vip_key",
")",
"vip_key",
"=",
"'res_{}_{}_vip'",
".",
"format",
"(",
"service",
",",
"hashlib",
".",
"sha1",
"(",
"vip",
".",
"encode",
"(",
"'UTF-8'",
")",
")",
".",
"hexdigest",
"(",
")",
"[",
":",
"7",
"]",
")",
"relation_data",
"[",
"'resources'",
"]",
"[",
"vip_key",
"]",
"=",
"res_vip",
"# NOTE(jamespage):",
"# Use option provided vip params if these where used",
"# instead of auto-detected values",
"if",
"fallback",
":",
"relation_data",
"[",
"'resource_params'",
"]",
"[",
"vip_key",
"]",
"=",
"(",
"'params {ip}=\"{vip}\" cidr_netmask=\"{netmask}\" '",
"'nic=\"{iface}\" {vip_monitoring}'",
".",
"format",
"(",
"ip",
"=",
"vip_params",
",",
"vip",
"=",
"vip",
",",
"iface",
"=",
"iface",
",",
"netmask",
"=",
"netmask",
",",
"vip_monitoring",
"=",
"vip_monitoring",
")",
")",
"else",
":",
"# NOTE(jamespage):",
"# let heartbeat figure out which interface and",
"# netmask to configure, which works nicely",
"# when network interface naming is not",
"# consistent across units.",
"relation_data",
"[",
"'resource_params'",
"]",
"[",
"vip_key",
"]",
"=",
"(",
"'params {ip}=\"{vip}\" {vip_monitoring}'",
".",
"format",
"(",
"ip",
"=",
"vip_params",
",",
"vip",
"=",
"vip",
",",
"vip_monitoring",
"=",
"vip_monitoring",
")",
")",
"vip_group",
".",
"append",
"(",
"vip_key",
")",
"if",
"vips_to_delete",
":",
"try",
":",
"relation_data",
"[",
"'delete_resources'",
"]",
".",
"extend",
"(",
"vips_to_delete",
")",
"except",
"KeyError",
":",
"relation_data",
"[",
"'delete_resources'",
"]",
"=",
"vips_to_delete",
"if",
"len",
"(",
"vip_group",
")",
">=",
"1",
":",
"key",
"=",
"VIP_GROUP_NAME",
".",
"format",
"(",
"service",
"=",
"service",
")",
"try",
":",
"relation_data",
"[",
"'groups'",
"]",
"[",
"key",
"]",
"=",
"' '",
".",
"join",
"(",
"vip_group",
")",
"except",
"KeyError",
":",
"relation_data",
"[",
"'groups'",
"]",
"=",
"{",
"key",
":",
"' '",
".",
"join",
"(",
"vip_group",
")",
"}"
] |
Configure VIP resources based on provided configuration
@param service: Name of the service being configured
@param relation_data: Pointer to dictionary of relation data.
|
[
"Configure",
"VIP",
"resources",
"based",
"on",
"provided",
"configuration"
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/ha/utils.py#L274-L348
|
12,716
|
juju/charm-helpers
|
charmhelpers/contrib/amulet/deployment.py
|
AmuletDeployment._add_services
|
def _add_services(self, this_service, other_services):
"""Add services.
Add services to the deployment where this_service is the local charm
that we're testing and other_services are the other services that
are being used in the local amulet tests.
"""
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(amulet.FAIL, msg=msg)
if 'units' not in this_service:
this_service['units'] = 1
self.d.add(this_service['name'], units=this_service['units'],
constraints=this_service.get('constraints'),
storage=this_service.get('storage'))
for svc in other_services:
if 'location' in svc:
branch_location = svc['location']
elif self.series:
branch_location = 'cs:{}/{}'.format(self.series, svc['name']),
else:
branch_location = None
if 'units' not in svc:
svc['units'] = 1
self.d.add(svc['name'], charm=branch_location, units=svc['units'],
constraints=svc.get('constraints'),
storage=svc.get('storage'))
|
python
|
def _add_services(self, this_service, other_services):
"""Add services.
Add services to the deployment where this_service is the local charm
that we're testing and other_services are the other services that
are being used in the local amulet tests.
"""
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(amulet.FAIL, msg=msg)
if 'units' not in this_service:
this_service['units'] = 1
self.d.add(this_service['name'], units=this_service['units'],
constraints=this_service.get('constraints'),
storage=this_service.get('storage'))
for svc in other_services:
if 'location' in svc:
branch_location = svc['location']
elif self.series:
branch_location = 'cs:{}/{}'.format(self.series, svc['name']),
else:
branch_location = None
if 'units' not in svc:
svc['units'] = 1
self.d.add(svc['name'], charm=branch_location, units=svc['units'],
constraints=svc.get('constraints'),
storage=svc.get('storage'))
|
[
"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",
"(",
"amulet",
".",
"FAIL",
",",
"msg",
"=",
"msg",
")",
"if",
"'units'",
"not",
"in",
"this_service",
":",
"this_service",
"[",
"'units'",
"]",
"=",
"1",
"self",
".",
"d",
".",
"add",
"(",
"this_service",
"[",
"'name'",
"]",
",",
"units",
"=",
"this_service",
"[",
"'units'",
"]",
",",
"constraints",
"=",
"this_service",
".",
"get",
"(",
"'constraints'",
")",
",",
"storage",
"=",
"this_service",
".",
"get",
"(",
"'storage'",
")",
")",
"for",
"svc",
"in",
"other_services",
":",
"if",
"'location'",
"in",
"svc",
":",
"branch_location",
"=",
"svc",
"[",
"'location'",
"]",
"elif",
"self",
".",
"series",
":",
"branch_location",
"=",
"'cs:{}/{}'",
".",
"format",
"(",
"self",
".",
"series",
",",
"svc",
"[",
"'name'",
"]",
")",
",",
"else",
":",
"branch_location",
"=",
"None",
"if",
"'units'",
"not",
"in",
"svc",
":",
"svc",
"[",
"'units'",
"]",
"=",
"1",
"self",
".",
"d",
".",
"add",
"(",
"svc",
"[",
"'name'",
"]",
",",
"charm",
"=",
"branch_location",
",",
"units",
"=",
"svc",
"[",
"'units'",
"]",
",",
"constraints",
"=",
"svc",
".",
"get",
"(",
"'constraints'",
")",
",",
"storage",
"=",
"svc",
".",
"get",
"(",
"'storage'",
")",
")"
] |
Add services.
Add services to the deployment where this_service is the local charm
that we're testing and other_services are the other services that
are being used in the local amulet tests.
|
[
"Add",
"services",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/amulet/deployment.py#L37-L69
|
12,717
|
juju/charm-helpers
|
charmhelpers/contrib/amulet/deployment.py
|
AmuletDeployment._add_relations
|
def _add_relations(self, relations):
"""Add all of the relations for the services."""
for k, v in six.iteritems(relations):
self.d.relate(k, v)
|
python
|
def _add_relations(self, relations):
"""Add all of the relations for the services."""
for k, v in six.iteritems(relations):
self.d.relate(k, v)
|
[
"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.
|
[
"Add",
"all",
"of",
"the",
"relations",
"for",
"the",
"services",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/amulet/deployment.py#L71-L74
|
12,718
|
juju/charm-helpers
|
charmhelpers/contrib/amulet/deployment.py
|
AmuletDeployment._configure_services
|
def _configure_services(self, configs):
"""Configure all of the services."""
for service, config in six.iteritems(configs):
self.d.configure(service, config)
|
python
|
def _configure_services(self, configs):
"""Configure all of the services."""
for service, config in six.iteritems(configs):
self.d.configure(service, config)
|
[
"def",
"_configure_services",
"(",
"self",
",",
"configs",
")",
":",
"for",
"service",
",",
"config",
"in",
"six",
".",
"iteritems",
"(",
"configs",
")",
":",
"self",
".",
"d",
".",
"configure",
"(",
"service",
",",
"config",
")"
] |
Configure all of the services.
|
[
"Configure",
"all",
"of",
"the",
"services",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/amulet/deployment.py#L76-L79
|
12,719
|
juju/charm-helpers
|
charmhelpers/contrib/amulet/deployment.py
|
AmuletDeployment._deploy
|
def _deploy(self):
"""Deploy environment and wait for all hooks to finish executing."""
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(
amulet.FAIL,
msg="Deployment timed out ({}s)".format(timeout)
)
except Exception:
raise
|
python
|
def _deploy(self):
"""Deploy environment and wait for all hooks to finish executing."""
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(
amulet.FAIL,
msg="Deployment timed out ({}s)".format(timeout)
)
except Exception:
raise
|
[
"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",
"(",
"amulet",
".",
"FAIL",
",",
"msg",
"=",
"\"Deployment timed out ({}s)\"",
".",
"format",
"(",
"timeout",
")",
")",
"except",
"Exception",
":",
"raise"
] |
Deploy environment and wait for all hooks to finish executing.
|
[
"Deploy",
"environment",
"and",
"wait",
"for",
"all",
"hooks",
"to",
"finish",
"executing",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/amulet/deployment.py#L81-L93
|
12,720
|
juju/charm-helpers
|
charmhelpers/contrib/ssl/service.py
|
ServiceCA._init_ca
|
def _init_ca(self):
"""Generate the root ca's cert and key.
"""
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_join(self.ca_dir, 'signing.cnf')):
with open(path_join(self.ca_dir, 'signing.cnf'), 'w') as fh:
fh.write(
SIGNING_CONF_TEMPLATE % (self.get_conf_variables()))
if exists(self.ca_cert) or exists(self.ca_key):
raise RuntimeError("Initialized called when CA already exists")
cmd = ['openssl', 'req', '-config', self.ca_conf,
'-x509', '-nodes', '-newkey', 'rsa',
'-days', self.default_ca_expiry,
'-keyout', self.ca_key, '-out', self.ca_cert,
'-outform', 'PEM']
output = subprocess.check_output(cmd, stderr=subprocess.STDOUT)
log("CA Init:\n %s" % output, level=DEBUG)
|
python
|
def _init_ca(self):
"""Generate the root ca's cert and key.
"""
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_join(self.ca_dir, 'signing.cnf')):
with open(path_join(self.ca_dir, 'signing.cnf'), 'w') as fh:
fh.write(
SIGNING_CONF_TEMPLATE % (self.get_conf_variables()))
if exists(self.ca_cert) or exists(self.ca_key):
raise RuntimeError("Initialized called when CA already exists")
cmd = ['openssl', 'req', '-config', self.ca_conf,
'-x509', '-nodes', '-newkey', 'rsa',
'-days', self.default_ca_expiry,
'-keyout', self.ca_key, '-out', self.ca_cert,
'-outform', 'PEM']
output = subprocess.check_output(cmd, stderr=subprocess.STDOUT)
log("CA Init:\n %s" % output, level=DEBUG)
|
[
"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_join",
"(",
"self",
".",
"ca_dir",
",",
"'signing.cnf'",
")",
")",
":",
"with",
"open",
"(",
"path_join",
"(",
"self",
".",
"ca_dir",
",",
"'signing.cnf'",
")",
",",
"'w'",
")",
"as",
"fh",
":",
"fh",
".",
"write",
"(",
"SIGNING_CONF_TEMPLATE",
"%",
"(",
"self",
".",
"get_conf_variables",
"(",
")",
")",
")",
"if",
"exists",
"(",
"self",
".",
"ca_cert",
")",
"or",
"exists",
"(",
"self",
".",
"ca_key",
")",
":",
"raise",
"RuntimeError",
"(",
"\"Initialized called when CA already exists\"",
")",
"cmd",
"=",
"[",
"'openssl'",
",",
"'req'",
",",
"'-config'",
",",
"self",
".",
"ca_conf",
",",
"'-x509'",
",",
"'-nodes'",
",",
"'-newkey'",
",",
"'rsa'",
",",
"'-days'",
",",
"self",
".",
"default_ca_expiry",
",",
"'-keyout'",
",",
"self",
".",
"ca_key",
",",
"'-out'",
",",
"self",
".",
"ca_cert",
",",
"'-outform'",
",",
"'PEM'",
"]",
"output",
"=",
"subprocess",
".",
"check_output",
"(",
"cmd",
",",
"stderr",
"=",
"subprocess",
".",
"STDOUT",
")",
"log",
"(",
"\"CA Init:\\n %s\"",
"%",
"output",
",",
"level",
"=",
"DEBUG",
")"
] |
Generate the root ca's cert and key.
|
[
"Generate",
"the",
"root",
"ca",
"s",
"cert",
"and",
"key",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/ssl/service.py#L95-L116
|
12,721
|
juju/charm-helpers
|
charmhelpers/contrib/openstack/keystone.py
|
format_endpoint
|
def format_endpoint(schema, addr, port, api_version):
"""Return a formatted keystone endpoint
@param schema: http or https
@param addr: ipv4/ipv6 host of the keystone service
@param port: port of the keystone service
@param api_version: 2 or 3
@returns a fully formatted keystone endpoint
"""
return '{}://{}:{}/{}/'.format(schema, addr, port,
get_api_suffix(api_version))
|
python
|
def format_endpoint(schema, addr, port, api_version):
"""Return a formatted keystone endpoint
@param schema: http or https
@param addr: ipv4/ipv6 host of the keystone service
@param port: port of the keystone service
@param api_version: 2 or 3
@returns a fully formatted keystone endpoint
"""
return '{}://{}:{}/{}/'.format(schema, addr, port,
get_api_suffix(api_version))
|
[
"def",
"format_endpoint",
"(",
"schema",
",",
"addr",
",",
"port",
",",
"api_version",
")",
":",
"return",
"'{}://{}:{}/{}/'",
".",
"format",
"(",
"schema",
",",
"addr",
",",
"port",
",",
"get_api_suffix",
"(",
"api_version",
")",
")"
] |
Return a formatted keystone endpoint
@param schema: http or https
@param addr: ipv4/ipv6 host of the keystone service
@param port: port of the keystone service
@param api_version: 2 or 3
@returns a fully formatted keystone endpoint
|
[
"Return",
"a",
"formatted",
"keystone",
"endpoint"
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/keystone.py#L35-L44
|
12,722
|
juju/charm-helpers
|
charmhelpers/contrib/openstack/keystone.py
|
get_keystone_manager
|
def get_keystone_manager(endpoint, api_version, **kwargs):
"""Return a keystonemanager for the correct API version
@param endpoint: the keystone endpoint to point client at
@param api_version: version of the keystone api the client should use
@param kwargs: token or username/tenant/password information
@returns keystonemanager class used for interrogating keystone
"""
if api_version == 2:
return KeystoneManager2(endpoint, **kwargs)
if api_version == 3:
return KeystoneManager3(endpoint, **kwargs)
raise ValueError('No manager found for api version {}'.format(api_version))
|
python
|
def get_keystone_manager(endpoint, api_version, **kwargs):
"""Return a keystonemanager for the correct API version
@param endpoint: the keystone endpoint to point client at
@param api_version: version of the keystone api the client should use
@param kwargs: token or username/tenant/password information
@returns keystonemanager class used for interrogating keystone
"""
if api_version == 2:
return KeystoneManager2(endpoint, **kwargs)
if api_version == 3:
return KeystoneManager3(endpoint, **kwargs)
raise ValueError('No manager found for api version {}'.format(api_version))
|
[
"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 {}'",
".",
"format",
"(",
"api_version",
")",
")"
] |
Return a keystonemanager for the correct API version
@param endpoint: the keystone endpoint to point client at
@param api_version: version of the keystone api the client should use
@param kwargs: token or username/tenant/password information
@returns keystonemanager class used for interrogating keystone
|
[
"Return",
"a",
"keystonemanager",
"for",
"the",
"correct",
"API",
"version"
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/keystone.py#L47-L59
|
12,723
|
juju/charm-helpers
|
charmhelpers/contrib/openstack/keystone.py
|
get_keystone_manager_from_identity_service_context
|
def get_keystone_manager_from_identity_service_context():
"""Return a keystonmanager generated from a
instance of charmhelpers.contrib.openstack.context.IdentityServiceContext
@returns keystonamenager instance
"""
context = IdentityServiceContext()()
if not context:
msg = "Identity service context cannot be generated"
log(msg, level=ERROR)
raise ValueError(msg)
endpoint = format_endpoint(context['service_protocol'],
context['service_host'],
context['service_port'],
context['api_version'])
if context['api_version'] in (2, "2.0"):
api_version = 2
else:
api_version = 3
return get_keystone_manager(endpoint, api_version,
username=context['admin_user'],
password=context['admin_password'],
tenant_name=context['admin_tenant_name'])
|
python
|
def get_keystone_manager_from_identity_service_context():
"""Return a keystonmanager generated from a
instance of charmhelpers.contrib.openstack.context.IdentityServiceContext
@returns keystonamenager instance
"""
context = IdentityServiceContext()()
if not context:
msg = "Identity service context cannot be generated"
log(msg, level=ERROR)
raise ValueError(msg)
endpoint = format_endpoint(context['service_protocol'],
context['service_host'],
context['service_port'],
context['api_version'])
if context['api_version'] in (2, "2.0"):
api_version = 2
else:
api_version = 3
return get_keystone_manager(endpoint, api_version,
username=context['admin_user'],
password=context['admin_password'],
tenant_name=context['admin_tenant_name'])
|
[
"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_endpoint",
"(",
"context",
"[",
"'service_protocol'",
"]",
",",
"context",
"[",
"'service_host'",
"]",
",",
"context",
"[",
"'service_port'",
"]",
",",
"context",
"[",
"'api_version'",
"]",
")",
"if",
"context",
"[",
"'api_version'",
"]",
"in",
"(",
"2",
",",
"\"2.0\"",
")",
":",
"api_version",
"=",
"2",
"else",
":",
"api_version",
"=",
"3",
"return",
"get_keystone_manager",
"(",
"endpoint",
",",
"api_version",
",",
"username",
"=",
"context",
"[",
"'admin_user'",
"]",
",",
"password",
"=",
"context",
"[",
"'admin_password'",
"]",
",",
"tenant_name",
"=",
"context",
"[",
"'admin_tenant_name'",
"]",
")"
] |
Return a keystonmanager generated from a
instance of charmhelpers.contrib.openstack.context.IdentityServiceContext
@returns keystonamenager instance
|
[
"Return",
"a",
"keystonmanager",
"generated",
"from",
"a",
"instance",
"of",
"charmhelpers",
".",
"contrib",
".",
"openstack",
".",
"context",
".",
"IdentityServiceContext"
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/keystone.py#L62-L86
|
12,724
|
juju/charm-helpers
|
charmhelpers/contrib/openstack/keystone.py
|
KeystoneManager.resolve_service_id
|
def resolve_service_id(self, service_name=None, service_type=None):
"""Find the service_id of a given service"""
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_type and service_name:
if (service_name == name and service_type == s['type']):
return s['id']
elif service_name and service_name == name:
return s['id']
elif service_type and service_type == s['type']:
return s['id']
return None
|
python
|
def resolve_service_id(self, service_name=None, service_type=None):
"""Find the service_id of a given service"""
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_type and service_name:
if (service_name == name and service_type == s['type']):
return s['id']
elif service_name and service_name == name:
return s['id']
elif service_type and service_type == s['type']:
return s['id']
return None
|
[
"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_type",
"and",
"service_name",
":",
"if",
"(",
"service_name",
"==",
"name",
"and",
"service_type",
"==",
"s",
"[",
"'type'",
"]",
")",
":",
"return",
"s",
"[",
"'id'",
"]",
"elif",
"service_name",
"and",
"service_name",
"==",
"name",
":",
"return",
"s",
"[",
"'id'",
"]",
"elif",
"service_type",
"and",
"service_type",
"==",
"s",
"[",
"'type'",
"]",
":",
"return",
"s",
"[",
"'id'",
"]",
"return",
"None"
] |
Find the service_id of a given service
|
[
"Find",
"the",
"service_id",
"of",
"a",
"given",
"service"
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/keystone.py#L91-L105
|
12,725
|
juju/charm-helpers
|
charmhelpers/contrib/storage/linux/lvm.py
|
deactivate_lvm_volume_group
|
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 = ['vgchange', '-an', vg]
check_call(cmd)
|
python
|
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 = ['vgchange', '-an', vg]
check_call(cmd)
|
[
"def",
"deactivate_lvm_volume_group",
"(",
"block_device",
")",
":",
"vg",
"=",
"list_lvm_volume_group",
"(",
"block_device",
")",
"if",
"vg",
":",
"cmd",
"=",
"[",
"'vgchange'",
",",
"'-an'",
",",
"vg",
"]",
"check_call",
"(",
"cmd",
")"
] |
Deactivate any volume gruop associated with an LVM physical volume.
:param block_device: str: Full path to LVM physical volume
|
[
"Deactivate",
"any",
"volume",
"gruop",
"associated",
"with",
"an",
"LVM",
"physical",
"volume",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/storage/linux/lvm.py#L28-L37
|
12,726
|
juju/charm-helpers
|
charmhelpers/contrib/storage/linux/lvm.py
|
remove_lvm_physical_volume
|
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.communicate(input='y\n')
|
python
|
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.communicate(input='y\n')
|
[
"def",
"remove_lvm_physical_volume",
"(",
"block_device",
")",
":",
"p",
"=",
"Popen",
"(",
"[",
"'pvremove'",
",",
"'-ff'",
",",
"block_device",
"]",
",",
"stdin",
"=",
"PIPE",
")",
"p",
".",
"communicate",
"(",
"input",
"=",
"'y\\n'",
")"
] |
Remove LVM PV signatures from a given block device.
:param block_device: str: Full path of block device to scrub.
|
[
"Remove",
"LVM",
"PV",
"signatures",
"from",
"a",
"given",
"block",
"device",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/storage/linux/lvm.py#L55-L63
|
12,727
|
juju/charm-helpers
|
charmhelpers/contrib/storage/linux/lvm.py
|
list_lvm_volume_group
|
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 associated with block device or None
'''
vg = None
pvd = check_output(['pvdisplay', block_device]).splitlines()
for lvm in pvd:
lvm = lvm.decode('UTF-8')
if lvm.strip().startswith('VG Name'):
vg = ' '.join(lvm.strip().split()[2:])
return vg
|
python
|
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 associated with block device or None
'''
vg = None
pvd = check_output(['pvdisplay', block_device]).splitlines()
for lvm in pvd:
lvm = lvm.decode('UTF-8')
if lvm.strip().startswith('VG Name'):
vg = ' '.join(lvm.strip().split()[2:])
return vg
|
[
"def",
"list_lvm_volume_group",
"(",
"block_device",
")",
":",
"vg",
"=",
"None",
"pvd",
"=",
"check_output",
"(",
"[",
"'pvdisplay'",
",",
"block_device",
"]",
")",
".",
"splitlines",
"(",
")",
"for",
"lvm",
"in",
"pvd",
":",
"lvm",
"=",
"lvm",
".",
"decode",
"(",
"'UTF-8'",
")",
"if",
"lvm",
".",
"strip",
"(",
")",
".",
"startswith",
"(",
"'VG Name'",
")",
":",
"vg",
"=",
"' '",
".",
"join",
"(",
"lvm",
".",
"strip",
"(",
")",
".",
"split",
"(",
")",
"[",
"2",
":",
"]",
")",
"return",
"vg"
] |
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 associated with block device or None
|
[
"List",
"LVM",
"volume",
"group",
"associated",
"with",
"a",
"given",
"block",
"device",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/storage/linux/lvm.py#L66-L82
|
12,728
|
juju/charm-helpers
|
charmhelpers/contrib/storage/linux/lvm.py
|
list_logical_volumes
|
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: bool: return logical volume name in 'vg/lv' format, this
format is required for some commands like lvextend
:returns: [str]: List of logical volumes
'''
lv_diplay_attr = 'lv_name'
if path_mode:
# Parsing output logic relies on the column order
lv_diplay_attr = 'vg_name,' + lv_diplay_attr
cmd = ['lvs', '--options', lv_diplay_attr, '--noheadings']
if select_criteria:
cmd.extend(['--select', select_criteria])
lvs = []
for lv in check_output(cmd).decode('UTF-8').splitlines():
if not lv:
continue
if path_mode:
lvs.append('/'.join(lv.strip().split()))
else:
lvs.append(lv.strip())
return lvs
|
python
|
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: bool: return logical volume name in 'vg/lv' format, this
format is required for some commands like lvextend
:returns: [str]: List of logical volumes
'''
lv_diplay_attr = 'lv_name'
if path_mode:
# Parsing output logic relies on the column order
lv_diplay_attr = 'vg_name,' + lv_diplay_attr
cmd = ['lvs', '--options', lv_diplay_attr, '--noheadings']
if select_criteria:
cmd.extend(['--select', select_criteria])
lvs = []
for lv in check_output(cmd).decode('UTF-8').splitlines():
if not lv:
continue
if path_mode:
lvs.append('/'.join(lv.strip().split()))
else:
lvs.append(lv.strip())
return lvs
|
[
"def",
"list_logical_volumes",
"(",
"select_criteria",
"=",
"None",
",",
"path_mode",
"=",
"False",
")",
":",
"lv_diplay_attr",
"=",
"'lv_name'",
"if",
"path_mode",
":",
"# Parsing output logic relies on the column order",
"lv_diplay_attr",
"=",
"'vg_name,'",
"+",
"lv_diplay_attr",
"cmd",
"=",
"[",
"'lvs'",
",",
"'--options'",
",",
"lv_diplay_attr",
",",
"'--noheadings'",
"]",
"if",
"select_criteria",
":",
"cmd",
".",
"extend",
"(",
"[",
"'--select'",
",",
"select_criteria",
"]",
")",
"lvs",
"=",
"[",
"]",
"for",
"lv",
"in",
"check_output",
"(",
"cmd",
")",
".",
"decode",
"(",
"'UTF-8'",
")",
".",
"splitlines",
"(",
")",
":",
"if",
"not",
"lv",
":",
"continue",
"if",
"path_mode",
":",
"lvs",
".",
"append",
"(",
"'/'",
".",
"join",
"(",
"lv",
".",
"strip",
"(",
")",
".",
"split",
"(",
")",
")",
")",
"else",
":",
"lvs",
".",
"append",
"(",
"lv",
".",
"strip",
"(",
")",
")",
"return",
"lvs"
] |
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: bool: return logical volume name in 'vg/lv' format, this
format is required for some commands like lvextend
:returns: [str]: List of logical volumes
|
[
"List",
"logical",
"volumes"
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/storage/linux/lvm.py#L107-L132
|
12,729
|
juju/charm-helpers
|
charmhelpers/contrib/storage/linux/lvm.py
|
create_logical_volume
|
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.
:param size: str: Size of logical volume to create (100% if not supplied)
:raises subprocess.CalledProcessError: in the event that the lvcreate fails.
'''
if size:
check_call([
'lvcreate',
'--yes',
'-L',
'{}'.format(size),
'-n', lv_name, volume_group
])
# create the lv with all the space available, this is needed because the
# system call is different for LVM
else:
check_call([
'lvcreate',
'--yes',
'-l',
'100%FREE',
'-n', lv_name, volume_group
])
|
python
|
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.
:param size: str: Size of logical volume to create (100% if not supplied)
:raises subprocess.CalledProcessError: in the event that the lvcreate fails.
'''
if size:
check_call([
'lvcreate',
'--yes',
'-L',
'{}'.format(size),
'-n', lv_name, volume_group
])
# create the lv with all the space available, this is needed because the
# system call is different for LVM
else:
check_call([
'lvcreate',
'--yes',
'-l',
'100%FREE',
'-n', lv_name, volume_group
])
|
[
"def",
"create_logical_volume",
"(",
"lv_name",
",",
"volume_group",
",",
"size",
"=",
"None",
")",
":",
"if",
"size",
":",
"check_call",
"(",
"[",
"'lvcreate'",
",",
"'--yes'",
",",
"'-L'",
",",
"'{}'",
".",
"format",
"(",
"size",
")",
",",
"'-n'",
",",
"lv_name",
",",
"volume_group",
"]",
")",
"# create the lv with all the space available, this is needed because the",
"# system call is different for LVM",
"else",
":",
"check_call",
"(",
"[",
"'lvcreate'",
",",
"'--yes'",
",",
"'-l'",
",",
"'100%FREE'",
",",
"'-n'",
",",
"lv_name",
",",
"volume_group",
"]",
")"
] |
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.
:param size: str: Size of logical volume to create (100% if not supplied)
:raises subprocess.CalledProcessError: in the event that the lvcreate fails.
|
[
"Create",
"a",
"new",
"logical",
"volume",
"in",
"an",
"existing",
"volume",
"group"
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/storage/linux/lvm.py#L156-L182
|
12,730
|
juju/charm-helpers
|
charmhelpers/core/templating.py
|
render
|
def render(source, target, context, owner='root', group='root',
perms=0o444, templates_dir=None, encoding='UTF-8',
template_loader=None, config_template=None):
"""
Render a template.
The `source` path, if not absolute, is relative to the `templates_dir`.
The `target` path should be absolute. It can also be `None`, in which
case no file will be written.
The context should be a dict containing the values to be replaced in the
template.
config_template may be provided to render from a provided template instead
of loading from a file.
The `owner`, `group`, and `perms` options will be passed to `write_file`.
If omitted, `templates_dir` defaults to the `templates` folder in the charm.
The rendered template will be written to the file as well as being returned
as a string.
Note: Using this requires python-jinja2 or python3-jinja2; if it is not
installed, calling this will attempt to use charmhelpers.fetch.apt_install
to install it.
"""
try:
from jinja2 import FileSystemLoader, Environment, exceptions
except ImportError:
try:
from charmhelpers.fetch import apt_install
except ImportError:
hookenv.log('Could not import jinja2, and could not import '
'charmhelpers.fetch to install it',
level=hookenv.ERROR)
raise
if sys.version_info.major == 2:
apt_install('python-jinja2', fatal=True)
else:
apt_install('python3-jinja2', fatal=True)
from jinja2 import FileSystemLoader, Environment, exceptions
if template_loader:
template_env = Environment(loader=template_loader)
else:
if templates_dir is None:
templates_dir = os.path.join(hookenv.charm_dir(), 'templates')
template_env = Environment(loader=FileSystemLoader(templates_dir))
# load from a string if provided explicitly
if config_template is not None:
template = template_env.from_string(config_template)
else:
try:
source = source
template = template_env.get_template(source)
except exceptions.TemplateNotFound as e:
hookenv.log('Could not load template %s from %s.' %
(source, templates_dir),
level=hookenv.ERROR)
raise e
content = template.render(context)
if target is not None:
target_dir = os.path.dirname(target)
if not os.path.exists(target_dir):
# This is a terrible default directory permission, as the file
# or its siblings will often contain secrets.
host.mkdir(os.path.dirname(target), owner, group, perms=0o755)
host.write_file(target, content.encode(encoding), owner, group, perms)
return content
|
python
|
def render(source, target, context, owner='root', group='root',
perms=0o444, templates_dir=None, encoding='UTF-8',
template_loader=None, config_template=None):
"""
Render a template.
The `source` path, if not absolute, is relative to the `templates_dir`.
The `target` path should be absolute. It can also be `None`, in which
case no file will be written.
The context should be a dict containing the values to be replaced in the
template.
config_template may be provided to render from a provided template instead
of loading from a file.
The `owner`, `group`, and `perms` options will be passed to `write_file`.
If omitted, `templates_dir` defaults to the `templates` folder in the charm.
The rendered template will be written to the file as well as being returned
as a string.
Note: Using this requires python-jinja2 or python3-jinja2; if it is not
installed, calling this will attempt to use charmhelpers.fetch.apt_install
to install it.
"""
try:
from jinja2 import FileSystemLoader, Environment, exceptions
except ImportError:
try:
from charmhelpers.fetch import apt_install
except ImportError:
hookenv.log('Could not import jinja2, and could not import '
'charmhelpers.fetch to install it',
level=hookenv.ERROR)
raise
if sys.version_info.major == 2:
apt_install('python-jinja2', fatal=True)
else:
apt_install('python3-jinja2', fatal=True)
from jinja2 import FileSystemLoader, Environment, exceptions
if template_loader:
template_env = Environment(loader=template_loader)
else:
if templates_dir is None:
templates_dir = os.path.join(hookenv.charm_dir(), 'templates')
template_env = Environment(loader=FileSystemLoader(templates_dir))
# load from a string if provided explicitly
if config_template is not None:
template = template_env.from_string(config_template)
else:
try:
source = source
template = template_env.get_template(source)
except exceptions.TemplateNotFound as e:
hookenv.log('Could not load template %s from %s.' %
(source, templates_dir),
level=hookenv.ERROR)
raise e
content = template.render(context)
if target is not None:
target_dir = os.path.dirname(target)
if not os.path.exists(target_dir):
# This is a terrible default directory permission, as the file
# or its siblings will often contain secrets.
host.mkdir(os.path.dirname(target), owner, group, perms=0o755)
host.write_file(target, content.encode(encoding), owner, group, perms)
return content
|
[
"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",
"ImportError",
":",
"try",
":",
"from",
"charmhelpers",
".",
"fetch",
"import",
"apt_install",
"except",
"ImportError",
":",
"hookenv",
".",
"log",
"(",
"'Could not import jinja2, and could not import '",
"'charmhelpers.fetch to install it'",
",",
"level",
"=",
"hookenv",
".",
"ERROR",
")",
"raise",
"if",
"sys",
".",
"version_info",
".",
"major",
"==",
"2",
":",
"apt_install",
"(",
"'python-jinja2'",
",",
"fatal",
"=",
"True",
")",
"else",
":",
"apt_install",
"(",
"'python3-jinja2'",
",",
"fatal",
"=",
"True",
")",
"from",
"jinja2",
"import",
"FileSystemLoader",
",",
"Environment",
",",
"exceptions",
"if",
"template_loader",
":",
"template_env",
"=",
"Environment",
"(",
"loader",
"=",
"template_loader",
")",
"else",
":",
"if",
"templates_dir",
"is",
"None",
":",
"templates_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"hookenv",
".",
"charm_dir",
"(",
")",
",",
"'templates'",
")",
"template_env",
"=",
"Environment",
"(",
"loader",
"=",
"FileSystemLoader",
"(",
"templates_dir",
")",
")",
"# load from a string if provided explicitly",
"if",
"config_template",
"is",
"not",
"None",
":",
"template",
"=",
"template_env",
".",
"from_string",
"(",
"config_template",
")",
"else",
":",
"try",
":",
"source",
"=",
"source",
"template",
"=",
"template_env",
".",
"get_template",
"(",
"source",
")",
"except",
"exceptions",
".",
"TemplateNotFound",
"as",
"e",
":",
"hookenv",
".",
"log",
"(",
"'Could not load template %s from %s.'",
"%",
"(",
"source",
",",
"templates_dir",
")",
",",
"level",
"=",
"hookenv",
".",
"ERROR",
")",
"raise",
"e",
"content",
"=",
"template",
".",
"render",
"(",
"context",
")",
"if",
"target",
"is",
"not",
"None",
":",
"target_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"target",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"target_dir",
")",
":",
"# This is a terrible default directory permission, as the file",
"# or its siblings will often contain secrets.",
"host",
".",
"mkdir",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"target",
")",
",",
"owner",
",",
"group",
",",
"perms",
"=",
"0o755",
")",
"host",
".",
"write_file",
"(",
"target",
",",
"content",
".",
"encode",
"(",
"encoding",
")",
",",
"owner",
",",
"group",
",",
"perms",
")",
"return",
"content"
] |
Render a template.
The `source` path, if not absolute, is relative to the `templates_dir`.
The `target` path should be absolute. It can also be `None`, in which
case no file will be written.
The context should be a dict containing the values to be replaced in the
template.
config_template may be provided to render from a provided template instead
of loading from a file.
The `owner`, `group`, and `perms` options will be passed to `write_file`.
If omitted, `templates_dir` defaults to the `templates` folder in the charm.
The rendered template will be written to the file as well as being returned
as a string.
Note: Using this requires python-jinja2 or python3-jinja2; if it is not
installed, calling this will attempt to use charmhelpers.fetch.apt_install
to install it.
|
[
"Render",
"a",
"template",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/templating.py#L22-L93
|
12,731
|
juju/charm-helpers
|
charmhelpers/core/hookenv.py
|
cached
|
def cached(func):
"""Cache return values for multiple executions of func + args
For example::
@cached
def unit_get(attribute):
pass
unit_get('test')
will cache the result of unit_get + 'test' for future calls.
"""
@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 exception handler scope.
res = func(*args, **kwargs)
cache[key] = res
return res
wrapper._wrapped = func
return wrapper
|
python
|
def cached(func):
"""Cache return values for multiple executions of func + args
For example::
@cached
def unit_get(attribute):
pass
unit_get('test')
will cache the result of unit_get + 'test' for future calls.
"""
@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 exception handler scope.
res = func(*args, **kwargs)
cache[key] = res
return res
wrapper._wrapped = func
return wrapper
|
[
"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 exception handler scope.",
"res",
"=",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"cache",
"[",
"key",
"]",
"=",
"res",
"return",
"res",
"wrapper",
".",
"_wrapped",
"=",
"func",
"return",
"wrapper"
] |
Cache return values for multiple executions of func + args
For example::
@cached
def unit_get(attribute):
pass
unit_get('test')
will cache the result of unit_get + 'test' for future calls.
|
[
"Cache",
"return",
"values",
"for",
"multiple",
"executions",
"of",
"func",
"+",
"args"
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/hookenv.py#L61-L86
|
12,732
|
juju/charm-helpers
|
charmhelpers/core/hookenv.py
|
flush
|
def flush(key):
"""Flushes any entries from function cache where the
key is found in the function+args """
flush_list = []
for item in cache:
if key in item:
flush_list.append(item)
for item in flush_list:
del cache[item]
|
python
|
def flush(key):
"""Flushes any entries from function cache where the
key is found in the function+args """
flush_list = []
for item in cache:
if key in item:
flush_list.append(item)
for item in flush_list:
del cache[item]
|
[
"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
key is found in the function+args
|
[
"Flushes",
"any",
"entries",
"from",
"function",
"cache",
"where",
"the",
"key",
"is",
"found",
"in",
"the",
"function",
"+",
"args"
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/hookenv.py#L89-L97
|
12,733
|
juju/charm-helpers
|
charmhelpers/core/hookenv.py
|
log
|
def log(message, level=None):
"""Write a message to the juju log"""
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 failures in unit tests
# Send log output to stderr
try:
subprocess.call(command)
except OSError as e:
if e.errno == errno.ENOENT:
if level:
message = "{}: {}".format(level, message)
message = "juju-log: {}".format(message)
print(message, file=sys.stderr)
else:
raise
|
python
|
def log(message, level=None):
"""Write a message to the juju log"""
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 failures in unit tests
# Send log output to stderr
try:
subprocess.call(command)
except OSError as e:
if e.errno == errno.ENOENT:
if level:
message = "{}: {}".format(level, message)
message = "juju-log: {}".format(message)
print(message, file=sys.stderr)
else:
raise
|
[
"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 failures in unit tests",
"# Send log output to stderr",
"try",
":",
"subprocess",
".",
"call",
"(",
"command",
")",
"except",
"OSError",
"as",
"e",
":",
"if",
"e",
".",
"errno",
"==",
"errno",
".",
"ENOENT",
":",
"if",
"level",
":",
"message",
"=",
"\"{}: {}\"",
".",
"format",
"(",
"level",
",",
"message",
")",
"message",
"=",
"\"juju-log: {}\"",
".",
"format",
"(",
"message",
")",
"print",
"(",
"message",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"else",
":",
"raise"
] |
Write a message to the juju log
|
[
"Write",
"a",
"message",
"to",
"the",
"juju",
"log"
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/hookenv.py#L100-L119
|
12,734
|
juju/charm-helpers
|
charmhelpers/core/hookenv.py
|
execution_environment
|
def execution_environment():
"""A convenient bundling of the current execution context"""
context = {}
context['conf'] = config()
if relation_id():
context['reltype'] = relation_type()
context['relid'] = relation_id()
context['rel'] = relation_get()
context['unit'] = local_unit()
context['rels'] = relations()
context['env'] = os.environ
return context
|
python
|
def execution_environment():
"""A convenient bundling of the current execution context"""
context = {}
context['conf'] = config()
if relation_id():
context['reltype'] = relation_type()
context['relid'] = relation_id()
context['rel'] = relation_get()
context['unit'] = local_unit()
context['rels'] = relations()
context['env'] = os.environ
return context
|
[
"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",
"(",
")",
"context",
"[",
"'rels'",
"]",
"=",
"relations",
"(",
")",
"context",
"[",
"'env'",
"]",
"=",
"os",
".",
"environ",
"return",
"context"
] |
A convenient bundling of the current execution context
|
[
"A",
"convenient",
"bundling",
"of",
"the",
"current",
"execution",
"context"
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/hookenv.py#L161-L172
|
12,735
|
juju/charm-helpers
|
charmhelpers/core/hookenv.py
|
relation_id
|
def relation_id(relation_name=None, service_or_unit=None):
"""The relation ID for the current or a specified relation"""
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]
for relid in relation_ids(relation_name):
remote_service = remote_service_name(relid)
if remote_service == service_name:
return relid
else:
raise ValueError('Must specify neither or both of relation_name and service_or_unit')
|
python
|
def relation_id(relation_name=None, service_or_unit=None):
"""The relation ID for the current or a specified relation"""
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]
for relid in relation_ids(relation_name):
remote_service = remote_service_name(relid)
if remote_service == service_name:
return relid
else:
raise ValueError('Must specify neither or both of relation_name and service_or_unit')
|
[
"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",
"]",
"for",
"relid",
"in",
"relation_ids",
"(",
"relation_name",
")",
":",
"remote_service",
"=",
"remote_service_name",
"(",
"relid",
")",
"if",
"remote_service",
"==",
"service_name",
":",
"return",
"relid",
"else",
":",
"raise",
"ValueError",
"(",
"'Must specify neither or both of relation_name and service_or_unit'",
")"
] |
The relation ID for the current or a specified relation
|
[
"The",
"relation",
"ID",
"for",
"the",
"current",
"or",
"a",
"specified",
"relation"
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/hookenv.py#L186-L197
|
12,736
|
juju/charm-helpers
|
charmhelpers/core/hookenv.py
|
principal_unit
|
def principal_unit():
"""Returns the principal unit of this unit, otherwise None"""
# 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']
elif principal_unit is not None:
return principal_unit
# For Juju 2.1 and below, let's try work out the principle unit by
# the various charms' metadata.yaml.
for reltype in relation_types():
for rid in relation_ids(reltype):
for unit in related_units(rid):
md = _metadata_unit(unit)
if not md:
continue
subordinate = md.pop('subordinate', None)
if not subordinate:
return unit
return None
|
python
|
def principal_unit():
"""Returns the principal unit of this unit, otherwise None"""
# 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']
elif principal_unit is not None:
return principal_unit
# For Juju 2.1 and below, let's try work out the principle unit by
# the various charms' metadata.yaml.
for reltype in relation_types():
for rid in relation_ids(reltype):
for unit in related_units(rid):
md = _metadata_unit(unit)
if not md:
continue
subordinate = md.pop('subordinate', None)
if not subordinate:
return unit
return None
|
[
"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'",
"]",
"elif",
"principal_unit",
"is",
"not",
"None",
":",
"return",
"principal_unit",
"# For Juju 2.1 and below, let's try work out the principle unit by",
"# the various charms' metadata.yaml.",
"for",
"reltype",
"in",
"relation_types",
"(",
")",
":",
"for",
"rid",
"in",
"relation_ids",
"(",
"reltype",
")",
":",
"for",
"unit",
"in",
"related_units",
"(",
"rid",
")",
":",
"md",
"=",
"_metadata_unit",
"(",
"unit",
")",
"if",
"not",
"md",
":",
"continue",
"subordinate",
"=",
"md",
".",
"pop",
"(",
"'subordinate'",
",",
"None",
")",
"if",
"not",
"subordinate",
":",
"return",
"unit",
"return",
"None"
] |
Returns the principal unit of this unit, otherwise None
|
[
"Returns",
"the",
"principal",
"unit",
"of",
"this",
"unit",
"otherwise",
"None"
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/hookenv.py#L239-L259
|
12,737
|
juju/charm-helpers
|
charmhelpers/core/hookenv.py
|
relation_get
|
def relation_get(attribute=None, unit=None, rid=None):
"""Get relation information"""
_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.loads(subprocess.check_output(_args).decode('UTF-8'))
except ValueError:
return None
except CalledProcessError as e:
if e.returncode == 2:
return None
raise
|
python
|
def relation_get(attribute=None, unit=None, rid=None):
"""Get relation information"""
_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.loads(subprocess.check_output(_args).decode('UTF-8'))
except ValueError:
return None
except CalledProcessError as e:
if e.returncode == 2:
return None
raise
|
[
"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",
".",
"loads",
"(",
"subprocess",
".",
"check_output",
"(",
"_args",
")",
".",
"decode",
"(",
"'UTF-8'",
")",
")",
"except",
"ValueError",
":",
"return",
"None",
"except",
"CalledProcessError",
"as",
"e",
":",
"if",
"e",
".",
"returncode",
"==",
"2",
":",
"return",
"None",
"raise"
] |
Get relation information
|
[
"Get",
"relation",
"information"
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/hookenv.py#L429-L445
|
12,738
|
juju/charm-helpers
|
charmhelpers/core/hookenv.py
|
relation_set
|
def relation_set(relation_id=None, relation_settings=None, **kwargs):
"""Set relation information for the current unit"""
relation_settings = relation_settings if relation_settings else {}
relation_cmd_line = ['relation-set']
accepts_file = "--file" in subprocess.check_output(
relation_cmd_line + ["--help"], universal_newlines=True)
if relation_id is not None:
relation_cmd_line.extend(('-r', relation_id))
settings = relation_settings.copy()
settings.update(kwargs)
for key, value in settings.items():
# Force value to be a string: it always should, but some call
# sites pass in things like dicts or numbers.
if value is not None:
settings[key] = "{}".format(value)
if accepts_file:
# --file was introduced in Juju 1.23.2. Use it by default if
# available, since otherwise we'll break if the relation data is
# too big. Ideally we should tell relation-set to read the data from
# stdin, but that feature is broken in 1.23.2: Bug #1454678.
with tempfile.NamedTemporaryFile(delete=False) as settings_file:
settings_file.write(yaml.safe_dump(settings).encode("utf-8"))
subprocess.check_call(
relation_cmd_line + ["--file", settings_file.name])
os.remove(settings_file.name)
else:
for key, value in settings.items():
if value is None:
relation_cmd_line.append('{}='.format(key))
else:
relation_cmd_line.append('{}={}'.format(key, value))
subprocess.check_call(relation_cmd_line)
# Flush cache of any relation-gets for local unit
flush(local_unit())
|
python
|
def relation_set(relation_id=None, relation_settings=None, **kwargs):
"""Set relation information for the current unit"""
relation_settings = relation_settings if relation_settings else {}
relation_cmd_line = ['relation-set']
accepts_file = "--file" in subprocess.check_output(
relation_cmd_line + ["--help"], universal_newlines=True)
if relation_id is not None:
relation_cmd_line.extend(('-r', relation_id))
settings = relation_settings.copy()
settings.update(kwargs)
for key, value in settings.items():
# Force value to be a string: it always should, but some call
# sites pass in things like dicts or numbers.
if value is not None:
settings[key] = "{}".format(value)
if accepts_file:
# --file was introduced in Juju 1.23.2. Use it by default if
# available, since otherwise we'll break if the relation data is
# too big. Ideally we should tell relation-set to read the data from
# stdin, but that feature is broken in 1.23.2: Bug #1454678.
with tempfile.NamedTemporaryFile(delete=False) as settings_file:
settings_file.write(yaml.safe_dump(settings).encode("utf-8"))
subprocess.check_call(
relation_cmd_line + ["--file", settings_file.name])
os.remove(settings_file.name)
else:
for key, value in settings.items():
if value is None:
relation_cmd_line.append('{}='.format(key))
else:
relation_cmd_line.append('{}={}'.format(key, value))
subprocess.check_call(relation_cmd_line)
# Flush cache of any relation-gets for local unit
flush(local_unit())
|
[
"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",
"+",
"[",
"\"--help\"",
"]",
",",
"universal_newlines",
"=",
"True",
")",
"if",
"relation_id",
"is",
"not",
"None",
":",
"relation_cmd_line",
".",
"extend",
"(",
"(",
"'-r'",
",",
"relation_id",
")",
")",
"settings",
"=",
"relation_settings",
".",
"copy",
"(",
")",
"settings",
".",
"update",
"(",
"kwargs",
")",
"for",
"key",
",",
"value",
"in",
"settings",
".",
"items",
"(",
")",
":",
"# Force value to be a string: it always should, but some call",
"# sites pass in things like dicts or numbers.",
"if",
"value",
"is",
"not",
"None",
":",
"settings",
"[",
"key",
"]",
"=",
"\"{}\"",
".",
"format",
"(",
"value",
")",
"if",
"accepts_file",
":",
"# --file was introduced in Juju 1.23.2. Use it by default if",
"# available, since otherwise we'll break if the relation data is",
"# too big. Ideally we should tell relation-set to read the data from",
"# stdin, but that feature is broken in 1.23.2: Bug #1454678.",
"with",
"tempfile",
".",
"NamedTemporaryFile",
"(",
"delete",
"=",
"False",
")",
"as",
"settings_file",
":",
"settings_file",
".",
"write",
"(",
"yaml",
".",
"safe_dump",
"(",
"settings",
")",
".",
"encode",
"(",
"\"utf-8\"",
")",
")",
"subprocess",
".",
"check_call",
"(",
"relation_cmd_line",
"+",
"[",
"\"--file\"",
",",
"settings_file",
".",
"name",
"]",
")",
"os",
".",
"remove",
"(",
"settings_file",
".",
"name",
")",
"else",
":",
"for",
"key",
",",
"value",
"in",
"settings",
".",
"items",
"(",
")",
":",
"if",
"value",
"is",
"None",
":",
"relation_cmd_line",
".",
"append",
"(",
"'{}='",
".",
"format",
"(",
"key",
")",
")",
"else",
":",
"relation_cmd_line",
".",
"append",
"(",
"'{}={}'",
".",
"format",
"(",
"key",
",",
"value",
")",
")",
"subprocess",
".",
"check_call",
"(",
"relation_cmd_line",
")",
"# Flush cache of any relation-gets for local unit",
"flush",
"(",
"local_unit",
"(",
")",
")"
] |
Set relation information for the current unit
|
[
"Set",
"relation",
"information",
"for",
"the",
"current",
"unit"
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/hookenv.py#L448-L481
|
12,739
|
juju/charm-helpers
|
charmhelpers/core/hookenv.py
|
relation_clear
|
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']:
settings[setting] = None
relation_set(relation_id=r_id,
**settings)
|
python
|
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']:
settings[setting] = None
relation_set(relation_id=r_id,
**settings)
|
[
"def",
"relation_clear",
"(",
"r_id",
"=",
"None",
")",
":",
"settings",
"=",
"relation_get",
"(",
"rid",
"=",
"r_id",
",",
"unit",
"=",
"local_unit",
"(",
")",
")",
"for",
"setting",
"in",
"settings",
":",
"if",
"setting",
"not",
"in",
"[",
"'public-address'",
",",
"'private-address'",
"]",
":",
"settings",
"[",
"setting",
"]",
"=",
"None",
"relation_set",
"(",
"relation_id",
"=",
"r_id",
",",
"*",
"*",
"settings",
")"
] |
Clears any relation data already set on relation r_id
|
[
"Clears",
"any",
"relation",
"data",
"already",
"set",
"on",
"relation",
"r_id"
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/hookenv.py#L484-L492
|
12,740
|
juju/charm-helpers
|
charmhelpers/core/hookenv.py
|
relation_ids
|
def relation_ids(reltype=None):
"""A list of relation_ids"""
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_line).decode('UTF-8')) or []
return []
|
python
|
def relation_ids(reltype=None):
"""A list of relation_ids"""
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_line).decode('UTF-8')) or []
return []
|
[
"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_line",
")",
".",
"decode",
"(",
"'UTF-8'",
")",
")",
"or",
"[",
"]",
"return",
"[",
"]"
] |
A list of relation_ids
|
[
"A",
"list",
"of",
"relation_ids"
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/hookenv.py#L496-L504
|
12,741
|
juju/charm-helpers
|
charmhelpers/core/hookenv.py
|
related_units
|
def related_units(relid=None):
"""A list of related units"""
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('UTF-8')) or []
|
python
|
def related_units(relid=None):
"""A list of related units"""
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('UTF-8')) or []
|
[
"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",
"(",
"'UTF-8'",
")",
")",
"or",
"[",
"]"
] |
A list of related units
|
[
"A",
"list",
"of",
"related",
"units"
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/hookenv.py#L508-L515
|
12,742
|
juju/charm-helpers
|
charmhelpers/core/hookenv.py
|
expected_peer_units
|
def expected_peer_units():
"""Get a generator for units we expect to join peer relation based on
goal-state.
The local unit is excluded from the result to make it easy to gauge
completion of all peers joining the relation with existing hook tools.
Example usage:
log('peer {} of {} joined peer relation'
.format(len(related_units()),
len(list(expected_peer_units()))))
This function will raise NotImplementedError if used with juju versions
without goal-state support.
:returns: iterator
:rtype: types.GeneratorType
:raises: NotImplementedError
"""
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 key != local_unit())
|
python
|
def expected_peer_units():
"""Get a generator for units we expect to join peer relation based on
goal-state.
The local unit is excluded from the result to make it easy to gauge
completion of all peers joining the relation with existing hook tools.
Example usage:
log('peer {} of {} joined peer relation'
.format(len(related_units()),
len(list(expected_peer_units()))))
This function will raise NotImplementedError if used with juju versions
without goal-state support.
:returns: iterator
:rtype: types.GeneratorType
:raises: NotImplementedError
"""
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 key != local_unit())
|
[
"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",
"key",
"!=",
"local_unit",
"(",
")",
")"
] |
Get a generator for units we expect to join peer relation based on
goal-state.
The local unit is excluded from the result to make it easy to gauge
completion of all peers joining the relation with existing hook tools.
Example usage:
log('peer {} of {} joined peer relation'
.format(len(related_units()),
len(list(expected_peer_units()))))
This function will raise NotImplementedError if used with juju versions
without goal-state support.
:returns: iterator
:rtype: types.GeneratorType
:raises: NotImplementedError
|
[
"Get",
"a",
"generator",
"for",
"units",
"we",
"expect",
"to",
"join",
"peer",
"relation",
"based",
"on",
"goal",
"-",
"state",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/hookenv.py#L518-L542
|
12,743
|
juju/charm-helpers
|
charmhelpers/core/hookenv.py
|
expected_related_units
|
def expected_related_units(reltype=None):
"""Get a generator for units we expect to join relation based on
goal-state.
Note that you can not use this function for the peer relation, take a look
at expected_peer_units() for that.
This function will raise KeyError if you request information for a
relation type for which juju goal-state does not have information. It will
raise NotImplementedError if used with juju versions without goal-state
support.
Example usage:
log('participant {} of {} joined relation {}'
.format(len(related_units()),
len(list(expected_related_units())),
relation_type()))
:param reltype: Relation type to list data for, default is to list data for
the realtion type we are currently executing a hook for.
:type reltype: str
:returns: iterator
:rtype: types.GeneratorType
:raises: KeyError, NotImplementedError
"""
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 relation unit count")
reltype = reltype or relation_type()
_goal_state = goal_state()
return (key for key in _goal_state['relations'][reltype] if '/' in key)
|
python
|
def expected_related_units(reltype=None):
"""Get a generator for units we expect to join relation based on
goal-state.
Note that you can not use this function for the peer relation, take a look
at expected_peer_units() for that.
This function will raise KeyError if you request information for a
relation type for which juju goal-state does not have information. It will
raise NotImplementedError if used with juju versions without goal-state
support.
Example usage:
log('participant {} of {} joined relation {}'
.format(len(related_units()),
len(list(expected_related_units())),
relation_type()))
:param reltype: Relation type to list data for, default is to list data for
the realtion type we are currently executing a hook for.
:type reltype: str
:returns: iterator
:rtype: types.GeneratorType
:raises: KeyError, NotImplementedError
"""
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 relation unit count")
reltype = reltype or relation_type()
_goal_state = goal_state()
return (key for key in _goal_state['relations'][reltype] if '/' in key)
|
[
"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 relation unit count\"",
")",
"reltype",
"=",
"reltype",
"or",
"relation_type",
"(",
")",
"_goal_state",
"=",
"goal_state",
"(",
")",
"return",
"(",
"key",
"for",
"key",
"in",
"_goal_state",
"[",
"'relations'",
"]",
"[",
"reltype",
"]",
"if",
"'/'",
"in",
"key",
")"
] |
Get a generator for units we expect to join relation based on
goal-state.
Note that you can not use this function for the peer relation, take a look
at expected_peer_units() for that.
This function will raise KeyError if you request information for a
relation type for which juju goal-state does not have information. It will
raise NotImplementedError if used with juju versions without goal-state
support.
Example usage:
log('participant {} of {} joined relation {}'
.format(len(related_units()),
len(list(expected_related_units())),
relation_type()))
:param reltype: Relation type to list data for, default is to list data for
the realtion type we are currently executing a hook for.
:type reltype: str
:returns: iterator
:rtype: types.GeneratorType
:raises: KeyError, NotImplementedError
|
[
"Get",
"a",
"generator",
"for",
"units",
"we",
"expect",
"to",
"join",
"relation",
"based",
"on",
"goal",
"-",
"state",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/hookenv.py#L545-L576
|
12,744
|
juju/charm-helpers
|
charmhelpers/core/hookenv.py
|
relation_for_unit
|
def relation_for_unit(unit=None, rid=None):
"""Get the json represenation of a unit's relation"""
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
return relation
|
python
|
def relation_for_unit(unit=None, rid=None):
"""Get the json represenation of a unit's relation"""
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
return relation
|
[
"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",
"return",
"relation"
] |
Get the json represenation of a unit's relation
|
[
"Get",
"the",
"json",
"represenation",
"of",
"a",
"unit",
"s",
"relation"
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/hookenv.py#L580-L588
|
12,745
|
juju/charm-helpers
|
charmhelpers/core/hookenv.py
|
relations_for_id
|
def relations_for_id(relid=None):
"""Get relations of a specific relation ID"""
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)
return relation_data
|
python
|
def relations_for_id(relid=None):
"""Get relations of a specific relation ID"""
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)
return relation_data
|
[
"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",
")",
"return",
"relation_data"
] |
Get relations of a specific relation ID
|
[
"Get",
"relations",
"of",
"a",
"specific",
"relation",
"ID"
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/hookenv.py#L592-L600
|
12,746
|
juju/charm-helpers
|
charmhelpers/core/hookenv.py
|
relations_of_type
|
def relations_of_type(reltype=None):
"""Get relations of a specific type"""
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(relation)
return relation_data
|
python
|
def relations_of_type(reltype=None):
"""Get relations of a specific type"""
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(relation)
return relation_data
|
[
"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",
"(",
"relation",
")",
"return",
"relation_data"
] |
Get relations of a specific type
|
[
"Get",
"relations",
"of",
"a",
"specific",
"type"
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/hookenv.py#L604-L612
|
12,747
|
juju/charm-helpers
|
charmhelpers/core/hookenv.py
|
metadata
|
def metadata():
"""Get the current charm metadata.yaml contents as a python object"""
with open(os.path.join(charm_dir(), 'metadata.yaml')) as md:
return yaml.safe_load(md)
|
python
|
def metadata():
"""Get the current charm metadata.yaml contents as a python object"""
with open(os.path.join(charm_dir(), 'metadata.yaml')) as md:
return yaml.safe_load(md)
|
[
"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
|
[
"Get",
"the",
"current",
"charm",
"metadata",
".",
"yaml",
"contents",
"as",
"a",
"python",
"object"
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/hookenv.py#L616-L619
|
12,748
|
juju/charm-helpers
|
charmhelpers/core/hookenv.py
|
relation_types
|
def relation_types():
"""Get a list of relation types supported by this charm"""
rel_types = []
md = metadata()
for key in ('provides', 'requires', 'peers'):
section = md.get(key)
if section:
rel_types.extend(section.keys())
return rel_types
|
python
|
def relation_types():
"""Get a list of relation types supported by this charm"""
rel_types = []
md = metadata()
for key in ('provides', 'requires', 'peers'):
section = md.get(key)
if section:
rel_types.extend(section.keys())
return rel_types
|
[
"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
|
[
"Get",
"a",
"list",
"of",
"relation",
"types",
"supported",
"by",
"this",
"charm"
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/hookenv.py#L641-L649
|
12,749
|
juju/charm-helpers
|
charmhelpers/core/hookenv.py
|
peer_relation_id
|
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:
return relids[0]
return None
|
python
|
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:
return relids[0]
return None
|
[
"def",
"peer_relation_id",
"(",
")",
":",
"md",
"=",
"metadata",
"(",
")",
"section",
"=",
"md",
".",
"get",
"(",
"'peers'",
")",
"if",
"section",
":",
"for",
"key",
"in",
"section",
":",
"relids",
"=",
"relation_ids",
"(",
"key",
")",
"if",
"relids",
":",
"return",
"relids",
"[",
"0",
"]",
"return",
"None"
] |
Get the peers relation id if a peers relation has been joined, else None.
|
[
"Get",
"the",
"peers",
"relation",
"id",
"if",
"a",
"peers",
"relation",
"has",
"been",
"joined",
"else",
"None",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/hookenv.py#L653-L662
|
12,750
|
juju/charm-helpers
|
charmhelpers/core/hookenv.py
|
interface_to_relations
|
def interface_to_relations(interface_name):
"""
Given an interface, return a list of relation names for the current
charm that use that interface.
:returns: A list of relation names.
"""
results = []
for role in ('provides', 'requires', 'peers'):
results.extend(role_and_interface_to_relations(role, interface_name))
return results
|
python
|
def interface_to_relations(interface_name):
"""
Given an interface, return a list of relation names for the current
charm that use that interface.
:returns: A list of relation names.
"""
results = []
for role in ('provides', 'requires', 'peers'):
results.extend(role_and_interface_to_relations(role, interface_name))
return results
|
[
"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"
] |
Given an interface, return a list of relation names for the current
charm that use that interface.
:returns: A list of relation names.
|
[
"Given",
"an",
"interface",
"return",
"a",
"list",
"of",
"relation",
"names",
"for",
"the",
"current",
"charm",
"that",
"use",
"that",
"interface",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/hookenv.py#L709-L719
|
12,751
|
juju/charm-helpers
|
charmhelpers/core/hookenv.py
|
relations
|
def relations():
"""Get a nested dictionary of relation data for all related units"""
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):
reldata = relation_get(unit=unit, rid=relid)
units[unit] = reldata
relids[relid] = units
rels[reltype] = relids
return rels
|
python
|
def relations():
"""Get a nested dictionary of relation data for all related units"""
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):
reldata = relation_get(unit=unit, rid=relid)
units[unit] = reldata
relids[relid] = units
rels[reltype] = relids
return rels
|
[
"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",
")",
":",
"reldata",
"=",
"relation_get",
"(",
"unit",
"=",
"unit",
",",
"rid",
"=",
"relid",
")",
"units",
"[",
"unit",
"]",
"=",
"reldata",
"relids",
"[",
"relid",
"]",
"=",
"units",
"rels",
"[",
"reltype",
"]",
"=",
"relids",
"return",
"rels"
] |
Get a nested dictionary of relation data for all related units
|
[
"Get",
"a",
"nested",
"dictionary",
"of",
"relation",
"data",
"for",
"all",
"related",
"units"
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/hookenv.py#L729-L741
|
12,752
|
juju/charm-helpers
|
charmhelpers/core/hookenv.py
|
_port_op
|
def _port_op(op_name, port, protocol="TCP"):
"""Open or close a service network port"""
_args = [op_name]
icmp = protocol.upper() == "ICMP"
if icmp:
_args.append(protocol)
else:
_args.append('{}/{}'.format(port, protocol))
try:
subprocess.check_call(_args)
except subprocess.CalledProcessError:
# Older Juju pre 2.3 doesn't support ICMP
# so treat it as a no-op if it fails.
if not icmp:
raise
|
python
|
def _port_op(op_name, port, protocol="TCP"):
"""Open or close a service network port"""
_args = [op_name]
icmp = protocol.upper() == "ICMP"
if icmp:
_args.append(protocol)
else:
_args.append('{}/{}'.format(port, protocol))
try:
subprocess.check_call(_args)
except subprocess.CalledProcessError:
# Older Juju pre 2.3 doesn't support ICMP
# so treat it as a no-op if it fails.
if not icmp:
raise
|
[
"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",
"subprocess",
".",
"CalledProcessError",
":",
"# Older Juju pre 2.3 doesn't support ICMP",
"# so treat it as a no-op if it fails.",
"if",
"not",
"icmp",
":",
"raise"
] |
Open or close a service network port
|
[
"Open",
"or",
"close",
"a",
"service",
"network",
"port"
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/hookenv.py#L764-L778
|
12,753
|
juju/charm-helpers
|
charmhelpers/core/hookenv.py
|
open_ports
|
def open_ports(start, end, protocol="TCP"):
"""Opens a range of service network ports"""
_args = ['open-port']
_args.append('{}-{}/{}'.format(start, end, protocol))
subprocess.check_call(_args)
|
python
|
def open_ports(start, end, protocol="TCP"):
"""Opens a range of service network ports"""
_args = ['open-port']
_args.append('{}-{}/{}'.format(start, end, protocol))
subprocess.check_call(_args)
|
[
"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
|
[
"Opens",
"a",
"range",
"of",
"service",
"network",
"ports"
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/hookenv.py#L791-L795
|
12,754
|
juju/charm-helpers
|
charmhelpers/core/hookenv.py
|
unit_get
|
def unit_get(attribute):
"""Get the unit ID for the remote unit"""
_args = ['unit-get', '--format=json', attribute]
try:
return json.loads(subprocess.check_output(_args).decode('UTF-8'))
except ValueError:
return None
|
python
|
def unit_get(attribute):
"""Get the unit ID for the remote unit"""
_args = ['unit-get', '--format=json', attribute]
try:
return json.loads(subprocess.check_output(_args).decode('UTF-8'))
except ValueError:
return None
|
[
"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
|
[
"Get",
"the",
"unit",
"ID",
"for",
"the",
"remote",
"unit"
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/hookenv.py#L817-L823
|
12,755
|
juju/charm-helpers
|
charmhelpers/core/hookenv.py
|
storage_get
|
def storage_get(attribute=None, storage_id=None):
"""Get storage attributes"""
_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).decode('UTF-8'))
except ValueError:
return None
|
python
|
def storage_get(attribute=None, storage_id=None):
"""Get storage attributes"""
_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).decode('UTF-8'))
except ValueError:
return None
|
[
"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",
")",
".",
"decode",
"(",
"'UTF-8'",
")",
")",
"except",
"ValueError",
":",
"return",
"None"
] |
Get storage attributes
|
[
"Get",
"storage",
"attributes"
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/hookenv.py#L837-L847
|
12,756
|
juju/charm-helpers
|
charmhelpers/core/hookenv.py
|
storage_list
|
def storage_list(storage_name=None):
"""List the storage IDs for the unit"""
_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
except OSError as e:
import errno
if e.errno == errno.ENOENT:
# storage-list does not exist
return []
raise
|
python
|
def storage_list(storage_name=None):
"""List the storage IDs for the unit"""
_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
except OSError as e:
import errno
if e.errno == errno.ENOENT:
# storage-list does not exist
return []
raise
|
[
"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",
"except",
"OSError",
"as",
"e",
":",
"import",
"errno",
"if",
"e",
".",
"errno",
"==",
"errno",
".",
"ENOENT",
":",
"# storage-list does not exist",
"return",
"[",
"]",
"raise"
] |
List the storage IDs for the unit
|
[
"List",
"the",
"storage",
"IDs",
"for",
"the",
"unit"
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/hookenv.py#L851-L865
|
12,757
|
juju/charm-helpers
|
charmhelpers/core/hookenv.py
|
charm_dir
|
def charm_dir():
"""Return the root directory of the current charm"""
d = os.environ.get('JUJU_CHARM_DIR')
if d is not None:
return d
return os.environ.get('CHARM_DIR')
|
python
|
def charm_dir():
"""Return the root directory of the current charm"""
d = os.environ.get('JUJU_CHARM_DIR')
if d is not None:
return d
return os.environ.get('CHARM_DIR')
|
[
"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
|
[
"Return",
"the",
"root",
"directory",
"of",
"the",
"current",
"charm"
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/hookenv.py#L941-L946
|
12,758
|
juju/charm-helpers
|
charmhelpers/core/hookenv.py
|
action_set
|
def action_set(values):
"""Sets the values to be returned after the action finishes"""
cmd = ['action-set']
for k, v in list(values.items()):
cmd.append('{}={}'.format(k, v))
subprocess.check_call(cmd)
|
python
|
def action_set(values):
"""Sets the values to be returned after the action finishes"""
cmd = ['action-set']
for k, v in list(values.items()):
cmd.append('{}={}'.format(k, v))
subprocess.check_call(cmd)
|
[
"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
|
[
"Sets",
"the",
"values",
"to",
"be",
"returned",
"after",
"the",
"action",
"finishes"
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/hookenv.py#L960-L965
|
12,759
|
juju/charm-helpers
|
charmhelpers/core/hookenv.py
|
status_set
|
def status_set(workload_state, message):
"""Set the workload state with a message
Use status-set to set the workload state with a message which is visible
to the user via juju status. If the status-set command is not found then
assume this is juju < 1.23 and juju-log the message unstead.
workload_state -- valid juju workload state.
message -- status update 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 = ['status-set', workload_state, message]
try:
ret = subprocess.call(cmd)
if ret == 0:
return
except OSError as e:
if e.errno != errno.ENOENT:
raise
log_message = 'status-set failed: {} {}'.format(workload_state,
message)
log(log_message, level='INFO')
|
python
|
def status_set(workload_state, message):
"""Set the workload state with a message
Use status-set to set the workload state with a message which is visible
to the user via juju status. If the status-set command is not found then
assume this is juju < 1.23 and juju-log the message unstead.
workload_state -- valid juju workload state.
message -- status update 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 = ['status-set', workload_state, message]
try:
ret = subprocess.call(cmd)
if ret == 0:
return
except OSError as e:
if e.errno != errno.ENOENT:
raise
log_message = 'status-set failed: {} {}'.format(workload_state,
message)
log(log_message, level='INFO')
|
[
"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",
"=",
"[",
"'status-set'",
",",
"workload_state",
",",
"message",
"]",
"try",
":",
"ret",
"=",
"subprocess",
".",
"call",
"(",
"cmd",
")",
"if",
"ret",
"==",
"0",
":",
"return",
"except",
"OSError",
"as",
"e",
":",
"if",
"e",
".",
"errno",
"!=",
"errno",
".",
"ENOENT",
":",
"raise",
"log_message",
"=",
"'status-set failed: {} {}'",
".",
"format",
"(",
"workload_state",
",",
"message",
")",
"log",
"(",
"log_message",
",",
"level",
"=",
"'INFO'",
")"
] |
Set the workload state with a message
Use status-set to set the workload state with a message which is visible
to the user via juju status. If the status-set command is not found then
assume this is juju < 1.23 and juju-log the message unstead.
workload_state -- valid juju workload state.
message -- status update message
|
[
"Set",
"the",
"workload",
"state",
"with",
"a",
"message"
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/hookenv.py#L990-L1015
|
12,760
|
juju/charm-helpers
|
charmhelpers/core/hookenv.py
|
status_get
|
def status_get():
"""Retrieve the previously set juju workload state and message
If the status-get command is not found then assume this is juju < 1.23 and
return 'unknown', ""
"""
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
else:
status = json.loads(raw_status.decode("UTF-8"))
return (status["status"], status["message"])
|
python
|
def status_get():
"""Retrieve the previously set juju workload state and message
If the status-get command is not found then assume this is juju < 1.23 and
return 'unknown', ""
"""
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
else:
status = json.loads(raw_status.decode("UTF-8"))
return (status["status"], status["message"])
|
[
"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",
"else",
":",
"status",
"=",
"json",
".",
"loads",
"(",
"raw_status",
".",
"decode",
"(",
"\"UTF-8\"",
")",
")",
"return",
"(",
"status",
"[",
"\"status\"",
"]",
",",
"status",
"[",
"\"message\"",
"]",
")"
] |
Retrieve the previously set juju workload state and message
If the status-get command is not found then assume this is juju < 1.23 and
return 'unknown', ""
|
[
"Retrieve",
"the",
"previously",
"set",
"juju",
"workload",
"state",
"and",
"message"
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/hookenv.py#L1018-L1035
|
12,761
|
juju/charm-helpers
|
charmhelpers/core/hookenv.py
|
application_version_set
|
def application_version_set(version):
"""Charm authors may trigger this command from any hook to output what
version of the application is running. This could be a package version,
for instance postgres version 9.5. It could also be a build number or
version control revision identifier, for instance git sha 6fb7ba68. """
cmd = ['application-version-set']
cmd.append(version)
try:
subprocess.check_call(cmd)
except OSError:
log("Application Version: {}".format(version))
|
python
|
def application_version_set(version):
"""Charm authors may trigger this command from any hook to output what
version of the application is running. This could be a package version,
for instance postgres version 9.5. It could also be a build number or
version control revision identifier, for instance git sha 6fb7ba68. """
cmd = ['application-version-set']
cmd.append(version)
try:
subprocess.check_call(cmd)
except OSError:
log("Application Version: {}".format(version))
|
[
"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
version of the application is running. This could be a package version,
for instance postgres version 9.5. It could also be a build number or
version control revision identifier, for instance git sha 6fb7ba68.
|
[
"Charm",
"authors",
"may",
"trigger",
"this",
"command",
"from",
"any",
"hook",
"to",
"output",
"what",
"version",
"of",
"the",
"application",
"is",
"running",
".",
"This",
"could",
"be",
"a",
"package",
"version",
"for",
"instance",
"postgres",
"version",
"9",
".",
"5",
".",
"It",
"could",
"also",
"be",
"a",
"build",
"number",
"or",
"version",
"control",
"revision",
"identifier",
"for",
"instance",
"git",
"sha",
"6fb7ba68",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/hookenv.py#L1052-L1063
|
12,762
|
juju/charm-helpers
|
charmhelpers/core/hookenv.py
|
payload_register
|
def payload_register(ptype, klass, pid):
""" is used while a hook is running to let Juju know that a
payload has been started."""
cmd = ['payload-register']
for x in [ptype, klass, pid]:
cmd.append(x)
subprocess.check_call(cmd)
|
python
|
def payload_register(ptype, klass, pid):
""" is used while a hook is running to let Juju know that a
payload has been started."""
cmd = ['payload-register']
for x in [ptype, klass, pid]:
cmd.append(x)
subprocess.check_call(cmd)
|
[
"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
payload has been started.
|
[
"is",
"used",
"while",
"a",
"hook",
"is",
"running",
"to",
"let",
"Juju",
"know",
"that",
"a",
"payload",
"has",
"been",
"started",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/hookenv.py#L1108-L1114
|
12,763
|
juju/charm-helpers
|
charmhelpers/core/hookenv.py
|
resource_get
|
def resource_get(name):
"""used to fetch the resource path of the given name.
<name> must match a name of defined resource in metadata.yaml
returns either a path or False if resource not available
"""
if not name:
return False
cmd = ['resource-get', name]
try:
return subprocess.check_output(cmd).decode('UTF-8')
except subprocess.CalledProcessError:
return False
|
python
|
def resource_get(name):
"""used to fetch the resource path of the given name.
<name> must match a name of defined resource in metadata.yaml
returns either a path or False if resource not available
"""
if not name:
return False
cmd = ['resource-get', name]
try:
return subprocess.check_output(cmd).decode('UTF-8')
except subprocess.CalledProcessError:
return False
|
[
"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.
<name> must match a name of defined resource in metadata.yaml
returns either a path or False if resource not available
|
[
"used",
"to",
"fetch",
"the",
"resource",
"path",
"of",
"the",
"given",
"name",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/hookenv.py#L1142-L1156
|
12,764
|
juju/charm-helpers
|
charmhelpers/core/hookenv.py
|
atstart
|
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 common code before all of your hooks, such as logging
the hook name or interesting relation data.
- Defer object or module initialization that requires a hook
context until we know there actually is a hook context,
making testing easier.
- Rather than requiring charm authors to include boilerplate to
invoke your helper's behavior, have it run automatically if
your object is instantiated or module imported.
This is not at all useful after your hook framework as been launched.
'''
global _atstart
_atstart.append((callback, args, kwargs))
|
python
|
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 common code before all of your hooks, such as logging
the hook name or interesting relation data.
- Defer object or module initialization that requires a hook
context until we know there actually is a hook context,
making testing easier.
- Rather than requiring charm authors to include boilerplate to
invoke your helper's behavior, have it run automatically if
your object is instantiated or module imported.
This is not at all useful after your hook framework as been launched.
'''
global _atstart
_atstart.append((callback, args, kwargs))
|
[
"def",
"atstart",
"(",
"callback",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"global",
"_atstart",
"_atstart",
".",
"append",
"(",
"(",
"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 common code before all of your hooks, such as logging
the hook name or interesting relation data.
- Defer object or module initialization that requires a hook
context until we know there actually is a hook context,
making testing easier.
- Rather than requiring charm authors to include boilerplate to
invoke your helper's behavior, have it run automatically if
your object is instantiated or module imported.
This is not at all useful after your hook framework as been launched.
|
[
"Schedule",
"a",
"callback",
"to",
"run",
"before",
"the",
"main",
"hook",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/hookenv.py#L1177-L1197
|
12,765
|
juju/charm-helpers
|
charmhelpers/core/hookenv.py
|
_run_atstart
|
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[:]
|
python
|
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[:]
|
[
"def",
"_run_atstart",
"(",
")",
":",
"global",
"_atstart",
"for",
"callback",
",",
"args",
",",
"kwargs",
"in",
"_atstart",
":",
"callback",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"del",
"_atstart",
"[",
":",
"]"
] |
Hook frameworks must invoke this before running the main hook body.
|
[
"Hook",
"frameworks",
"must",
"invoke",
"this",
"before",
"running",
"the",
"main",
"hook",
"body",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/hookenv.py#L1207-L1212
|
12,766
|
juju/charm-helpers
|
charmhelpers/core/hookenv.py
|
_run_atexit
|
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 _atexit[:]
|
python
|
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 _atexit[:]
|
[
"def",
"_run_atexit",
"(",
")",
":",
"global",
"_atexit",
"for",
"callback",
",",
"args",
",",
"kwargs",
"in",
"reversed",
"(",
"_atexit",
")",
":",
"callback",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"del",
"_atexit",
"[",
":",
"]"
] |
Hook frameworks must invoke this after the main hook body has
successfully completed. Do not invoke it if the hook fails.
|
[
"Hook",
"frameworks",
"must",
"invoke",
"this",
"after",
"the",
"main",
"hook",
"body",
"has",
"successfully",
"completed",
".",
"Do",
"not",
"invoke",
"it",
"if",
"the",
"hook",
"fails",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/hookenv.py#L1215-L1221
|
12,767
|
juju/charm-helpers
|
charmhelpers/core/hookenv.py
|
network_get
|
def network_get(endpoint, relation_id=None):
"""
Retrieve the network details for a relation endpoint
:param endpoint: string. The name of a relation endpoint
:param relation_id: int. The ID of the relation for the current context.
:return: dict. The loaded YAML output of the network-get query.
:raise: NotImplementedError if request not supported by the Juju version.
"""
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 added the -r option
cmd = ['network-get', endpoint, '--format', 'yaml']
if relation_id:
cmd.append('-r')
cmd.append(relation_id)
response = subprocess.check_output(
cmd,
stderr=subprocess.STDOUT).decode('UTF-8').strip()
return yaml.safe_load(response)
|
python
|
def network_get(endpoint, relation_id=None):
"""
Retrieve the network details for a relation endpoint
:param endpoint: string. The name of a relation endpoint
:param relation_id: int. The ID of the relation for the current context.
:return: dict. The loaded YAML output of the network-get query.
:raise: NotImplementedError if request not supported by the Juju version.
"""
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 added the -r option
cmd = ['network-get', endpoint, '--format', 'yaml']
if relation_id:
cmd.append('-r')
cmd.append(relation_id)
response = subprocess.check_output(
cmd,
stderr=subprocess.STDOUT).decode('UTF-8').strip()
return yaml.safe_load(response)
|
[
"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 added the -r option",
"cmd",
"=",
"[",
"'network-get'",
",",
"endpoint",
",",
"'--format'",
",",
"'yaml'",
"]",
"if",
"relation_id",
":",
"cmd",
".",
"append",
"(",
"'-r'",
")",
"cmd",
".",
"append",
"(",
"relation_id",
")",
"response",
"=",
"subprocess",
".",
"check_output",
"(",
"cmd",
",",
"stderr",
"=",
"subprocess",
".",
"STDOUT",
")",
".",
"decode",
"(",
"'UTF-8'",
")",
".",
"strip",
"(",
")",
"return",
"yaml",
".",
"safe_load",
"(",
"response",
")"
] |
Retrieve the network details for a relation endpoint
:param endpoint: string. The name of a relation endpoint
:param relation_id: int. The ID of the relation for the current context.
:return: dict. The loaded YAML output of the network-get query.
:raise: NotImplementedError if request not supported by the Juju version.
|
[
"Retrieve",
"the",
"network",
"details",
"for",
"a",
"relation",
"endpoint"
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/hookenv.py#L1249-L1270
|
12,768
|
juju/charm-helpers
|
charmhelpers/core/hookenv.py
|
add_metric
|
def add_metric(*args, **kwargs):
"""Add metric values. Values may be expressed with keyword arguments. For
metric names containing dashes, these may be expressed as one or more
'key=value' positional arguments. May only be called from the collect-metrics
hook."""
_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
except EnvironmentError as e:
if e.errno != errno.ENOENT:
raise
log_message = 'add-metric failed: {}'.format(' '.join(_kvpairs))
log(log_message, level='INFO')
|
python
|
def add_metric(*args, **kwargs):
"""Add metric values. Values may be expressed with keyword arguments. For
metric names containing dashes, these may be expressed as one or more
'key=value' positional arguments. May only be called from the collect-metrics
hook."""
_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
except EnvironmentError as e:
if e.errno != errno.ENOENT:
raise
log_message = 'add-metric failed: {}'.format(' '.join(_kvpairs))
log(log_message, level='INFO')
|
[
"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",
"except",
"EnvironmentError",
"as",
"e",
":",
"if",
"e",
".",
"errno",
"!=",
"errno",
".",
"ENOENT",
":",
"raise",
"log_message",
"=",
"'add-metric failed: {}'",
".",
"format",
"(",
"' '",
".",
"join",
"(",
"_kvpairs",
")",
")",
"log",
"(",
"log_message",
",",
"level",
"=",
"'INFO'",
")"
] |
Add metric values. Values may be expressed with keyword arguments. For
metric names containing dashes, these may be expressed as one or more
'key=value' positional arguments. May only be called from the collect-metrics
hook.
|
[
"Add",
"metric",
"values",
".",
"Values",
"may",
"be",
"expressed",
"with",
"keyword",
"arguments",
".",
"For",
"metric",
"names",
"containing",
"dashes",
"these",
"may",
"be",
"expressed",
"as",
"one",
"or",
"more",
"key",
"=",
"value",
"positional",
"arguments",
".",
"May",
"only",
"be",
"called",
"from",
"the",
"collect",
"-",
"metrics",
"hook",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/hookenv.py#L1273-L1290
|
12,769
|
juju/charm-helpers
|
charmhelpers/core/hookenv.py
|
iter_units_for_relation_name
|
def iter_units_for_relation_name(relation_name):
"""Iterate through all units in a relation
Generator that iterates through all the units in a relation and yields
a named tuple with rid and unit field names.
Usage:
data = [(u.rid, u.unit)
for u in iter_units_for_relation_name(relation_name)]
:param relation_name: string relation name
:yield: Named Tuple with rid and unit field names
"""
RelatedUnit = namedtuple('RelatedUnit', 'rid, unit')
for rid in relation_ids(relation_name):
for unit in related_units(rid):
yield RelatedUnit(rid, unit)
|
python
|
def iter_units_for_relation_name(relation_name):
"""Iterate through all units in a relation
Generator that iterates through all the units in a relation and yields
a named tuple with rid and unit field names.
Usage:
data = [(u.rid, u.unit)
for u in iter_units_for_relation_name(relation_name)]
:param relation_name: string relation name
:yield: Named Tuple with rid and unit field names
"""
RelatedUnit = namedtuple('RelatedUnit', 'rid, unit')
for rid in relation_ids(relation_name):
for unit in related_units(rid):
yield RelatedUnit(rid, unit)
|
[
"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
Generator that iterates through all the units in a relation and yields
a named tuple with rid and unit field names.
Usage:
data = [(u.rid, u.unit)
for u in iter_units_for_relation_name(relation_name)]
:param relation_name: string relation name
:yield: Named Tuple with rid and unit field names
|
[
"Iterate",
"through",
"all",
"units",
"in",
"a",
"relation"
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/hookenv.py#L1304-L1320
|
12,770
|
juju/charm-helpers
|
charmhelpers/core/hookenv.py
|
ingress_address
|
def ingress_address(rid=None, unit=None):
"""
Retrieve the ingress-address from a relation when available.
Otherwise, return the private-address.
When used on the consuming side of the relation (unit is a remote
unit), the ingress-address is the IP address that this unit needs
to use to reach the provided service on the remote unit.
When used on the providing side of the relation (unit == local_unit()),
the ingress-address is the IP address that is advertised to remote
units on this relation. Remote units need to use this address to
reach the local provided service on this unit.
Note that charms may document some other method to use in
preference to the ingress_address(), such as an address provided
on a different relation attribute or a service discovery mechanism.
This allows charms to redirect inbound connections to their peers
or different applications such as load balancers.
Usage:
addresses = [ingress_address(rid=u.rid, unit=u.unit)
for u in iter_units_for_relation_name(relation_name)]
:param rid: string relation id
:param unit: string unit name
:side effect: calls relation_get
:return: string IP address
"""
settings = relation_get(rid=rid, unit=unit)
return (settings.get('ingress-address') or
settings.get('private-address'))
|
python
|
def ingress_address(rid=None, unit=None):
"""
Retrieve the ingress-address from a relation when available.
Otherwise, return the private-address.
When used on the consuming side of the relation (unit is a remote
unit), the ingress-address is the IP address that this unit needs
to use to reach the provided service on the remote unit.
When used on the providing side of the relation (unit == local_unit()),
the ingress-address is the IP address that is advertised to remote
units on this relation. Remote units need to use this address to
reach the local provided service on this unit.
Note that charms may document some other method to use in
preference to the ingress_address(), such as an address provided
on a different relation attribute or a service discovery mechanism.
This allows charms to redirect inbound connections to their peers
or different applications such as load balancers.
Usage:
addresses = [ingress_address(rid=u.rid, unit=u.unit)
for u in iter_units_for_relation_name(relation_name)]
:param rid: string relation id
:param unit: string unit name
:side effect: calls relation_get
:return: string IP address
"""
settings = relation_get(rid=rid, unit=unit)
return (settings.get('ingress-address') or
settings.get('private-address'))
|
[
"def",
"ingress_address",
"(",
"rid",
"=",
"None",
",",
"unit",
"=",
"None",
")",
":",
"settings",
"=",
"relation_get",
"(",
"rid",
"=",
"rid",
",",
"unit",
"=",
"unit",
")",
"return",
"(",
"settings",
".",
"get",
"(",
"'ingress-address'",
")",
"or",
"settings",
".",
"get",
"(",
"'private-address'",
")",
")"
] |
Retrieve the ingress-address from a relation when available.
Otherwise, return the private-address.
When used on the consuming side of the relation (unit is a remote
unit), the ingress-address is the IP address that this unit needs
to use to reach the provided service on the remote unit.
When used on the providing side of the relation (unit == local_unit()),
the ingress-address is the IP address that is advertised to remote
units on this relation. Remote units need to use this address to
reach the local provided service on this unit.
Note that charms may document some other method to use in
preference to the ingress_address(), such as an address provided
on a different relation attribute or a service discovery mechanism.
This allows charms to redirect inbound connections to their peers
or different applications such as load balancers.
Usage:
addresses = [ingress_address(rid=u.rid, unit=u.unit)
for u in iter_units_for_relation_name(relation_name)]
:param rid: string relation id
:param unit: string unit name
:side effect: calls relation_get
:return: string IP address
|
[
"Retrieve",
"the",
"ingress",
"-",
"address",
"from",
"a",
"relation",
"when",
"available",
".",
"Otherwise",
"return",
"the",
"private",
"-",
"address",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/hookenv.py#L1323-L1354
|
12,771
|
juju/charm-helpers
|
charmhelpers/core/hookenv.py
|
egress_subnets
|
def egress_subnets(rid=None, unit=None):
"""
Retrieve the egress-subnets from a relation.
This function is to be used on the providing side of the
relation, and provides the ranges of addresses that client
connections may come from. The result is uninteresting on
the consuming side of a relation (unit == local_unit()).
Returns a stable list of subnets in CIDR format.
eg. ['192.168.1.0/24', '2001::F00F/128']
If egress-subnets is not available, falls back to using the published
ingress-address, or finally private-address.
:param rid: string relation id
:param unit: string unit name
:side effect: calls relation_get
:return: list of subnets in CIDR format. eg. ['192.168.1.0/24', '2001::F00F/128']
"""
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
settings = relation_get(rid=rid, unit=unit)
if 'egress-subnets' in settings:
return [n.strip() for n in settings['egress-subnets'].split(',') if n.strip()]
if 'ingress-address' in settings:
return [_to_range(settings['ingress-address'])]
if 'private-address' in settings:
return [_to_range(settings['private-address'])]
return []
|
python
|
def egress_subnets(rid=None, unit=None):
"""
Retrieve the egress-subnets from a relation.
This function is to be used on the providing side of the
relation, and provides the ranges of addresses that client
connections may come from. The result is uninteresting on
the consuming side of a relation (unit == local_unit()).
Returns a stable list of subnets in CIDR format.
eg. ['192.168.1.0/24', '2001::F00F/128']
If egress-subnets is not available, falls back to using the published
ingress-address, or finally private-address.
:param rid: string relation id
:param unit: string unit name
:side effect: calls relation_get
:return: list of subnets in CIDR format. eg. ['192.168.1.0/24', '2001::F00F/128']
"""
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
settings = relation_get(rid=rid, unit=unit)
if 'egress-subnets' in settings:
return [n.strip() for n in settings['egress-subnets'].split(',') if n.strip()]
if 'ingress-address' in settings:
return [_to_range(settings['ingress-address'])]
if 'private-address' in settings:
return [_to_range(settings['private-address'])]
return []
|
[
"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",
"settings",
"=",
"relation_get",
"(",
"rid",
"=",
"rid",
",",
"unit",
"=",
"unit",
")",
"if",
"'egress-subnets'",
"in",
"settings",
":",
"return",
"[",
"n",
".",
"strip",
"(",
")",
"for",
"n",
"in",
"settings",
"[",
"'egress-subnets'",
"]",
".",
"split",
"(",
"','",
")",
"if",
"n",
".",
"strip",
"(",
")",
"]",
"if",
"'ingress-address'",
"in",
"settings",
":",
"return",
"[",
"_to_range",
"(",
"settings",
"[",
"'ingress-address'",
"]",
")",
"]",
"if",
"'private-address'",
"in",
"settings",
":",
"return",
"[",
"_to_range",
"(",
"settings",
"[",
"'private-address'",
"]",
")",
"]",
"return",
"[",
"]"
] |
Retrieve the egress-subnets from a relation.
This function is to be used on the providing side of the
relation, and provides the ranges of addresses that client
connections may come from. The result is uninteresting on
the consuming side of a relation (unit == local_unit()).
Returns a stable list of subnets in CIDR format.
eg. ['192.168.1.0/24', '2001::F00F/128']
If egress-subnets is not available, falls back to using the published
ingress-address, or finally private-address.
:param rid: string relation id
:param unit: string unit name
:side effect: calls relation_get
:return: list of subnets in CIDR format. eg. ['192.168.1.0/24', '2001::F00F/128']
|
[
"Retrieve",
"the",
"egress",
"-",
"subnets",
"from",
"a",
"relation",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/hookenv.py#L1357-L1391
|
12,772
|
juju/charm-helpers
|
charmhelpers/core/hookenv.py
|
unit_doomed
|
def unit_doomed(unit=None):
"""Determines if the unit is being removed from the model
Requires Juju 2.4.1.
:param unit: string unit name, defaults to local_unit
:side effect: calls goal_state
:side effect: calls local_unit
:side effect: calls has_juju_version
:return: True if the unit is being removed, already gone, or never existed
"""
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 helper
# at all.
# goal-state existed in 2.4.0, but did not handle removals
# correctly until 2.4.1.
raise NotImplementedError("is_doomed")
if unit is None:
unit = local_unit()
gs = goal_state()
units = gs.get('units', {})
if unit not in units:
return True
# I don't think 'dead' units ever show up in the goal-state, but
# check anyway in addition to 'dying'.
return units[unit]['status'] in ('dying', 'dead')
|
python
|
def unit_doomed(unit=None):
"""Determines if the unit is being removed from the model
Requires Juju 2.4.1.
:param unit: string unit name, defaults to local_unit
:side effect: calls goal_state
:side effect: calls local_unit
:side effect: calls has_juju_version
:return: True if the unit is being removed, already gone, or never existed
"""
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 helper
# at all.
# goal-state existed in 2.4.0, but did not handle removals
# correctly until 2.4.1.
raise NotImplementedError("is_doomed")
if unit is None:
unit = local_unit()
gs = goal_state()
units = gs.get('units', {})
if unit not in units:
return True
# I don't think 'dead' units ever show up in the goal-state, but
# check anyway in addition to 'dying'.
return units[unit]['status'] in ('dying', 'dead')
|
[
"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 helper",
"# at all.",
"# goal-state existed in 2.4.0, but did not handle removals",
"# correctly until 2.4.1.",
"raise",
"NotImplementedError",
"(",
"\"is_doomed\"",
")",
"if",
"unit",
"is",
"None",
":",
"unit",
"=",
"local_unit",
"(",
")",
"gs",
"=",
"goal_state",
"(",
")",
"units",
"=",
"gs",
".",
"get",
"(",
"'units'",
",",
"{",
"}",
")",
"if",
"unit",
"not",
"in",
"units",
":",
"return",
"True",
"# I don't think 'dead' units ever show up in the goal-state, but",
"# check anyway in addition to 'dying'.",
"return",
"units",
"[",
"unit",
"]",
"[",
"'status'",
"]",
"in",
"(",
"'dying'",
",",
"'dead'",
")"
] |
Determines if the unit is being removed from the model
Requires Juju 2.4.1.
:param unit: string unit name, defaults to local_unit
:side effect: calls goal_state
:side effect: calls local_unit
:side effect: calls has_juju_version
:return: True if the unit is being removed, already gone, or never existed
|
[
"Determines",
"if",
"the",
"unit",
"is",
"being",
"removed",
"from",
"the",
"model"
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/hookenv.py#L1394-L1421
|
12,773
|
juju/charm-helpers
|
charmhelpers/core/hookenv.py
|
env_proxy_settings
|
def env_proxy_settings(selected_settings=None):
"""Get proxy settings from process environment variables.
Get charm proxy settings from environment variables that correspond to
juju-http-proxy, juju-https-proxy and juju-no-proxy (available as of 2.4.2,
see lp:1782236) in a format suitable for passing to an application that
reacts to proxy settings passed as environment variables. Some applications
support lowercase or uppercase notation (e.g. curl), some support only
lowercase (e.g. wget), there are also subjectively rare cases of only
uppercase notation support. no_proxy CIDR and wildcard support also varies
between runtimes and applications as there is no enforced standard.
Some applications may connect to multiple destinations and expose config
options that would affect only proxy settings for a specific destination
these should be handled in charms in an application-specific manner.
:param selected_settings: format only a subset of possible settings
:type selected_settings: list
:rtype: Option(None, dict[str, str])
"""
SUPPORTED_SETTINGS = {
'http': 'HTTP_PROXY',
'https': 'HTTPS_PROXY',
'no_proxy': 'NO_PROXY',
'ftp': 'FTP_PROXY'
}
if selected_settings is None:
selected_settings = SUPPORTED_SETTINGS
selected_vars = [v for k, v in SUPPORTED_SETTINGS.items()
if k in selected_settings]
proxy_settings = {}
for var in selected_vars:
var_val = os.getenv(var)
if var_val:
proxy_settings[var] = var_val
proxy_settings[var.lower()] = var_val
# Now handle juju-prefixed environment variables. The legacy vs new
# environment variable usage is mutually exclusive
charm_var_val = os.getenv('JUJU_CHARM_{}'.format(var))
if charm_var_val:
proxy_settings[var] = charm_var_val
proxy_settings[var.lower()] = charm_var_val
if 'no_proxy' in proxy_settings:
if _contains_range(proxy_settings['no_proxy']):
log(RANGE_WARNING, level=WARNING)
return proxy_settings if proxy_settings else None
|
python
|
def env_proxy_settings(selected_settings=None):
"""Get proxy settings from process environment variables.
Get charm proxy settings from environment variables that correspond to
juju-http-proxy, juju-https-proxy and juju-no-proxy (available as of 2.4.2,
see lp:1782236) in a format suitable for passing to an application that
reacts to proxy settings passed as environment variables. Some applications
support lowercase or uppercase notation (e.g. curl), some support only
lowercase (e.g. wget), there are also subjectively rare cases of only
uppercase notation support. no_proxy CIDR and wildcard support also varies
between runtimes and applications as there is no enforced standard.
Some applications may connect to multiple destinations and expose config
options that would affect only proxy settings for a specific destination
these should be handled in charms in an application-specific manner.
:param selected_settings: format only a subset of possible settings
:type selected_settings: list
:rtype: Option(None, dict[str, str])
"""
SUPPORTED_SETTINGS = {
'http': 'HTTP_PROXY',
'https': 'HTTPS_PROXY',
'no_proxy': 'NO_PROXY',
'ftp': 'FTP_PROXY'
}
if selected_settings is None:
selected_settings = SUPPORTED_SETTINGS
selected_vars = [v for k, v in SUPPORTED_SETTINGS.items()
if k in selected_settings]
proxy_settings = {}
for var in selected_vars:
var_val = os.getenv(var)
if var_val:
proxy_settings[var] = var_val
proxy_settings[var.lower()] = var_val
# Now handle juju-prefixed environment variables. The legacy vs new
# environment variable usage is mutually exclusive
charm_var_val = os.getenv('JUJU_CHARM_{}'.format(var))
if charm_var_val:
proxy_settings[var] = charm_var_val
proxy_settings[var.lower()] = charm_var_val
if 'no_proxy' in proxy_settings:
if _contains_range(proxy_settings['no_proxy']):
log(RANGE_WARNING, level=WARNING)
return proxy_settings if proxy_settings else None
|
[
"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",
"=",
"SUPPORTED_SETTINGS",
"selected_vars",
"=",
"[",
"v",
"for",
"k",
",",
"v",
"in",
"SUPPORTED_SETTINGS",
".",
"items",
"(",
")",
"if",
"k",
"in",
"selected_settings",
"]",
"proxy_settings",
"=",
"{",
"}",
"for",
"var",
"in",
"selected_vars",
":",
"var_val",
"=",
"os",
".",
"getenv",
"(",
"var",
")",
"if",
"var_val",
":",
"proxy_settings",
"[",
"var",
"]",
"=",
"var_val",
"proxy_settings",
"[",
"var",
".",
"lower",
"(",
")",
"]",
"=",
"var_val",
"# Now handle juju-prefixed environment variables. The legacy vs new",
"# environment variable usage is mutually exclusive",
"charm_var_val",
"=",
"os",
".",
"getenv",
"(",
"'JUJU_CHARM_{}'",
".",
"format",
"(",
"var",
")",
")",
"if",
"charm_var_val",
":",
"proxy_settings",
"[",
"var",
"]",
"=",
"charm_var_val",
"proxy_settings",
"[",
"var",
".",
"lower",
"(",
")",
"]",
"=",
"charm_var_val",
"if",
"'no_proxy'",
"in",
"proxy_settings",
":",
"if",
"_contains_range",
"(",
"proxy_settings",
"[",
"'no_proxy'",
"]",
")",
":",
"log",
"(",
"RANGE_WARNING",
",",
"level",
"=",
"WARNING",
")",
"return",
"proxy_settings",
"if",
"proxy_settings",
"else",
"None"
] |
Get proxy settings from process environment variables.
Get charm proxy settings from environment variables that correspond to
juju-http-proxy, juju-https-proxy and juju-no-proxy (available as of 2.4.2,
see lp:1782236) in a format suitable for passing to an application that
reacts to proxy settings passed as environment variables. Some applications
support lowercase or uppercase notation (e.g. curl), some support only
lowercase (e.g. wget), there are also subjectively rare cases of only
uppercase notation support. no_proxy CIDR and wildcard support also varies
between runtimes and applications as there is no enforced standard.
Some applications may connect to multiple destinations and expose config
options that would affect only proxy settings for a specific destination
these should be handled in charms in an application-specific manner.
:param selected_settings: format only a subset of possible settings
:type selected_settings: list
:rtype: Option(None, dict[str, str])
|
[
"Get",
"proxy",
"settings",
"from",
"process",
"environment",
"variables",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/hookenv.py#L1424-L1470
|
12,774
|
juju/charm-helpers
|
charmhelpers/core/hookenv.py
|
Config.load_previous
|
def load_previous(self, path=None):
"""Load previous copy of config from disk.
In normal usage you don't need to call this method directly - it
is called automatically at object initialization.
:param path:
File path from which to load the previous config. If `None`,
config is loaded from the default location. If `path` is
specified, subsequent `save()` calls will write to the same
path.
"""
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 - {}'.format(str(e)),
level=ERROR)
for k, v in copy.deepcopy(self._prev_dict).items():
if k not in self:
self[k] = v
|
python
|
def load_previous(self, path=None):
"""Load previous copy of config from disk.
In normal usage you don't need to call this method directly - it
is called automatically at object initialization.
:param path:
File path from which to load the previous config. If `None`,
config is loaded from the default location. If `path` is
specified, subsequent `save()` calls will write to the same
path.
"""
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 - {}'.format(str(e)),
level=ERROR)
for k, v in copy.deepcopy(self._prev_dict).items():
if k not in self:
self[k] = v
|
[
"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 - {}'",
".",
"format",
"(",
"str",
"(",
"e",
")",
")",
",",
"level",
"=",
"ERROR",
")",
"for",
"k",
",",
"v",
"in",
"copy",
".",
"deepcopy",
"(",
"self",
".",
"_prev_dict",
")",
".",
"items",
"(",
")",
":",
"if",
"k",
"not",
"in",
"self",
":",
"self",
"[",
"k",
"]",
"=",
"v"
] |
Load previous copy of config from disk.
In normal usage you don't need to call this method directly - it
is called automatically at object initialization.
:param path:
File path from which to load the previous config. If `None`,
config is loaded from the default location. If `path` is
specified, subsequent `save()` calls will write to the same
path.
|
[
"Load",
"previous",
"copy",
"of",
"config",
"from",
"disk",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/hookenv.py#L327-L350
|
12,775
|
juju/charm-helpers
|
charmhelpers/core/hookenv.py
|
Config.changed
|
def changed(self, key):
"""Return True if the current value for this key is different from
the previous value.
"""
if self._prev_dict is None:
return True
return self.previous(key) != self.get(key)
|
python
|
def changed(self, key):
"""Return True if the current value for this key is different from
the previous value.
"""
if self._prev_dict is None:
return True
return self.previous(key) != self.get(key)
|
[
"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
the previous value.
|
[
"Return",
"True",
"if",
"the",
"current",
"value",
"for",
"this",
"key",
"is",
"different",
"from",
"the",
"previous",
"value",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/hookenv.py#L352-L359
|
12,776
|
juju/charm-helpers
|
charmhelpers/core/hookenv.py
|
Config.save
|
def save(self):
"""Save this config to disk.
If the charm is using the :mod:`Services Framework <services.base>`
or :meth:'@hook <Hooks.hook>' decorator, this
is called automatically at the end of successful hook execution.
Otherwise, it should be called directly by user code.
To disable automatic saves, set ``implicit_save=False`` on this
instance.
"""
with open(self.path, 'w') as f:
os.fchmod(f.fileno(), 0o600)
json.dump(self, f)
|
python
|
def save(self):
"""Save this config to disk.
If the charm is using the :mod:`Services Framework <services.base>`
or :meth:'@hook <Hooks.hook>' decorator, this
is called automatically at the end of successful hook execution.
Otherwise, it should be called directly by user code.
To disable automatic saves, set ``implicit_save=False`` on this
instance.
"""
with open(self.path, 'w') as f:
os.fchmod(f.fileno(), 0o600)
json.dump(self, f)
|
[
"def",
"save",
"(",
"self",
")",
":",
"with",
"open",
"(",
"self",
".",
"path",
",",
"'w'",
")",
"as",
"f",
":",
"os",
".",
"fchmod",
"(",
"f",
".",
"fileno",
"(",
")",
",",
"0o600",
")",
"json",
".",
"dump",
"(",
"self",
",",
"f",
")"
] |
Save this config to disk.
If the charm is using the :mod:`Services Framework <services.base>`
or :meth:'@hook <Hooks.hook>' decorator, this
is called automatically at the end of successful hook execution.
Otherwise, it should be called directly by user code.
To disable automatic saves, set ``implicit_save=False`` on this
instance.
|
[
"Save",
"this",
"config",
"to",
"disk",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/hookenv.py#L370-L384
|
12,777
|
juju/charm-helpers
|
charmhelpers/core/hookenv.py
|
Hooks.hook
|
def hook(self, *hook_names):
"""Decorator, registering them as hooks"""
def wrapper(decorated):
for hook_name in hook_names:
self.register(hook_name, decorated)
else:
self.register(decorated.__name__, decorated)
if '_' in decorated.__name__:
self.register(
decorated.__name__.replace('_', '-'), decorated)
return decorated
return wrapper
|
python
|
def hook(self, *hook_names):
"""Decorator, registering them as hooks"""
def wrapper(decorated):
for hook_name in hook_names:
self.register(hook_name, decorated)
else:
self.register(decorated.__name__, decorated)
if '_' in decorated.__name__:
self.register(
decorated.__name__.replace('_', '-'), decorated)
return decorated
return wrapper
|
[
"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",
"decorated",
".",
"__name__",
":",
"self",
".",
"register",
"(",
"decorated",
".",
"__name__",
".",
"replace",
"(",
"'_'",
",",
"'-'",
")",
",",
"decorated",
")",
"return",
"decorated",
"return",
"wrapper"
] |
Decorator, registering them as hooks
|
[
"Decorator",
"registering",
"them",
"as",
"hooks"
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/core/hookenv.py#L923-L934
|
12,778
|
juju/charm-helpers
|
charmhelpers/fetch/python/rpdb.py
|
Rpdb.shutdown
|
def shutdown(self):
"""Revert stdin and stdout, close the socket."""
sys.stdout = self.old_stdout
sys.stdin = self.old_stdin
self.skt.close()
self.set_continue()
|
python
|
def shutdown(self):
"""Revert stdin and stdout, close the socket."""
sys.stdout = self.old_stdout
sys.stdin = self.old_stdin
self.skt.close()
self.set_continue()
|
[
"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.
|
[
"Revert",
"stdin",
"and",
"stdout",
"close",
"the",
"socket",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/fetch/python/rpdb.py#L44-L49
|
12,779
|
juju/charm-helpers
|
charmhelpers/contrib/benchmark/__init__.py
|
Benchmark.start
|
def start():
action_set('meta.start', time.strftime('%Y-%m-%dT%H:%M:%SZ'))
"""
If the collectd charm is also installed, tell it to send a snapshot
of the current profile data.
"""
COLLECT_PROFILE_DATA = '/usr/local/bin/collect-profile-data'
if os.path.exists(COLLECT_PROFILE_DATA):
subprocess.check_output([COLLECT_PROFILE_DATA])
|
python
|
def start():
action_set('meta.start', time.strftime('%Y-%m-%dT%H:%M:%SZ'))
"""
If the collectd charm is also installed, tell it to send a snapshot
of the current profile data.
"""
COLLECT_PROFILE_DATA = '/usr/local/bin/collect-profile-data'
if os.path.exists(COLLECT_PROFILE_DATA):
subprocess.check_output([COLLECT_PROFILE_DATA])
|
[
"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",
"]",
")"
] |
If the collectd charm is also installed, tell it to send a snapshot
of the current profile data.
|
[
"If",
"the",
"collectd",
"charm",
"is",
"also",
"installed",
"tell",
"it",
"to",
"send",
"a",
"snapshot",
"of",
"the",
"current",
"profile",
"data",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/benchmark/__init__.py#L99-L108
|
12,780
|
juju/charm-helpers
|
charmhelpers/contrib/openstack/utils.py
|
get_os_codename_install_source
|
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']:
try:
rel = UBUNTU_OPENSTACK_RELEASE[ubuntu_rel]
except KeyError:
e = 'Could not derive openstack release for '\
'this Ubuntu release: %s' % ubuntu_rel
error_out(e)
return rel
if src.startswith('cloud:'):
ca_rel = src.split(':')[1]
ca_rel = ca_rel.split('-')[1].split('/')[0]
return ca_rel
# Best guess match based on deb string provided
if (src.startswith('deb') or
src.startswith('ppa') or
src.startswith('snap')):
for v in OPENSTACK_CODENAMES.values():
if v in src:
return v
|
python
|
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']:
try:
rel = UBUNTU_OPENSTACK_RELEASE[ubuntu_rel]
except KeyError:
e = 'Could not derive openstack release for '\
'this Ubuntu release: %s' % ubuntu_rel
error_out(e)
return rel
if src.startswith('cloud:'):
ca_rel = src.split(':')[1]
ca_rel = ca_rel.split('-')[1].split('/')[0]
return ca_rel
# Best guess match based on deb string provided
if (src.startswith('deb') or
src.startswith('ppa') or
src.startswith('snap')):
for v in OPENSTACK_CODENAMES.values():
if v in src:
return v
|
[
"def",
"get_os_codename_install_source",
"(",
"src",
")",
":",
"ubuntu_rel",
"=",
"lsb_release",
"(",
")",
"[",
"'DISTRIB_CODENAME'",
"]",
"rel",
"=",
"''",
"if",
"src",
"is",
"None",
":",
"return",
"rel",
"if",
"src",
"in",
"[",
"'distro'",
",",
"'distro-proposed'",
",",
"'proposed'",
"]",
":",
"try",
":",
"rel",
"=",
"UBUNTU_OPENSTACK_RELEASE",
"[",
"ubuntu_rel",
"]",
"except",
"KeyError",
":",
"e",
"=",
"'Could not derive openstack release for '",
"'this Ubuntu release: %s'",
"%",
"ubuntu_rel",
"error_out",
"(",
"e",
")",
"return",
"rel",
"if",
"src",
".",
"startswith",
"(",
"'cloud:'",
")",
":",
"ca_rel",
"=",
"src",
".",
"split",
"(",
"':'",
")",
"[",
"1",
"]",
"ca_rel",
"=",
"ca_rel",
".",
"split",
"(",
"'-'",
")",
"[",
"1",
"]",
".",
"split",
"(",
"'/'",
")",
"[",
"0",
"]",
"return",
"ca_rel",
"# Best guess match based on deb string provided",
"if",
"(",
"src",
".",
"startswith",
"(",
"'deb'",
")",
"or",
"src",
".",
"startswith",
"(",
"'ppa'",
")",
"or",
"src",
".",
"startswith",
"(",
"'snap'",
")",
")",
":",
"for",
"v",
"in",
"OPENSTACK_CODENAMES",
".",
"values",
"(",
")",
":",
"if",
"v",
"in",
"src",
":",
"return",
"v"
] |
Derive OpenStack release codename from a given installation source.
|
[
"Derive",
"OpenStack",
"release",
"codename",
"from",
"a",
"given",
"installation",
"source",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/utils.py#L322-L348
|
12,781
|
juju/charm-helpers
|
charmhelpers/contrib/openstack/utils.py
|
get_os_version_codename
|
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 '\
'codename: %s' % codename
error_out(e)
|
python
|
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 '\
'codename: %s' % codename
error_out(e)
|
[
"def",
"get_os_version_codename",
"(",
"codename",
",",
"version_map",
"=",
"OPENSTACK_CODENAMES",
")",
":",
"for",
"k",
",",
"v",
"in",
"six",
".",
"iteritems",
"(",
"version_map",
")",
":",
"if",
"v",
"==",
"codename",
":",
"return",
"k",
"e",
"=",
"'Could not derive OpenStack version for '",
"'codename: %s'",
"%",
"codename",
"error_out",
"(",
"e",
")"
] |
Determine OpenStack version number from codename.
|
[
"Determine",
"OpenStack",
"version",
"number",
"from",
"codename",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/utils.py#L365-L372
|
12,782
|
juju/charm-helpers
|
charmhelpers/contrib/openstack/utils.py
|
get_os_version_codename_swift
|
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 '\
'codename: %s' % codename
error_out(e)
|
python
|
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 '\
'codename: %s' % codename
error_out(e)
|
[
"def",
"get_os_version_codename_swift",
"(",
"codename",
")",
":",
"for",
"k",
",",
"v",
"in",
"six",
".",
"iteritems",
"(",
"SWIFT_CODENAMES",
")",
":",
"if",
"k",
"==",
"codename",
":",
"return",
"v",
"[",
"-",
"1",
"]",
"e",
"=",
"'Could not derive swift version for '",
"'codename: %s'",
"%",
"codename",
"error_out",
"(",
"e",
")"
] |
Determine OpenStack version number of swift from codename.
|
[
"Determine",
"OpenStack",
"version",
"number",
"of",
"swift",
"from",
"codename",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/utils.py#L375-L382
|
12,783
|
juju/charm-helpers
|
charmhelpers/contrib/openstack/utils.py
|
get_swift_codename
|
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 version we determine
# the actual codename based on the highest available install source.
for codename in reversed(codenames):
releases = UBUNTU_OPENSTACK_RELEASE
release = [k for k, v in six.iteritems(releases) if codename in v]
ret = subprocess.check_output(['apt-cache', 'policy', 'swift'])
if six.PY3:
ret = ret.decode('UTF-8')
if codename in ret or release[0] in ret:
return codename
elif len(codenames) == 1:
return codenames[0]
# NOTE: fallback - attempt to match with just major.minor version
match = re.match(r'^(\d+)\.(\d+)', version)
if match:
major_minor_version = match.group(0)
for codename, versions in six.iteritems(SWIFT_CODENAMES):
for release_version in versions:
if release_version.startswith(major_minor_version):
return codename
return None
|
python
|
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 version we determine
# the actual codename based on the highest available install source.
for codename in reversed(codenames):
releases = UBUNTU_OPENSTACK_RELEASE
release = [k for k, v in six.iteritems(releases) if codename in v]
ret = subprocess.check_output(['apt-cache', 'policy', 'swift'])
if six.PY3:
ret = ret.decode('UTF-8')
if codename in ret or release[0] in ret:
return codename
elif len(codenames) == 1:
return codenames[0]
# NOTE: fallback - attempt to match with just major.minor version
match = re.match(r'^(\d+)\.(\d+)', version)
if match:
major_minor_version = match.group(0)
for codename, versions in six.iteritems(SWIFT_CODENAMES):
for release_version in versions:
if release_version.startswith(major_minor_version):
return codename
return None
|
[
"def",
"get_swift_codename",
"(",
"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 version we determine",
"# the actual codename based on the highest available install source.",
"for",
"codename",
"in",
"reversed",
"(",
"codenames",
")",
":",
"releases",
"=",
"UBUNTU_OPENSTACK_RELEASE",
"release",
"=",
"[",
"k",
"for",
"k",
",",
"v",
"in",
"six",
".",
"iteritems",
"(",
"releases",
")",
"if",
"codename",
"in",
"v",
"]",
"ret",
"=",
"subprocess",
".",
"check_output",
"(",
"[",
"'apt-cache'",
",",
"'policy'",
",",
"'swift'",
"]",
")",
"if",
"six",
".",
"PY3",
":",
"ret",
"=",
"ret",
".",
"decode",
"(",
"'UTF-8'",
")",
"if",
"codename",
"in",
"ret",
"or",
"release",
"[",
"0",
"]",
"in",
"ret",
":",
"return",
"codename",
"elif",
"len",
"(",
"codenames",
")",
"==",
"1",
":",
"return",
"codenames",
"[",
"0",
"]",
"# NOTE: fallback - attempt to match with just major.minor version",
"match",
"=",
"re",
".",
"match",
"(",
"r'^(\\d+)\\.(\\d+)'",
",",
"version",
")",
"if",
"match",
":",
"major_minor_version",
"=",
"match",
".",
"group",
"(",
"0",
")",
"for",
"codename",
",",
"versions",
"in",
"six",
".",
"iteritems",
"(",
"SWIFT_CODENAMES",
")",
":",
"for",
"release_version",
"in",
"versions",
":",
"if",
"release_version",
".",
"startswith",
"(",
"major_minor_version",
")",
":",
"return",
"codename",
"return",
"None"
] |
Determine OpenStack codename that corresponds to swift version.
|
[
"Determine",
"OpenStack",
"codename",
"that",
"corresponds",
"to",
"swift",
"version",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/utils.py#L385-L412
|
12,784
|
juju/charm-helpers
|
charmhelpers/contrib/openstack/utils.py
|
get_os_codename_package
|
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.PY3:
out = out.decode('UTF-8')
except subprocess.CalledProcessError:
return None
lines = out.split('\n')
for line in lines:
if package in line:
# Second item in list is Version
return line.split()[1]
import apt_pkg as apt
cache = apt_cache()
try:
pkg = cache[package]
except Exception:
if not fatal:
return None
# the package is unknown to the current apt cache.
e = 'Could not determine version of package with no installation '\
'candidate: %s' % package
error_out(e)
if not pkg.current_ver:
if not fatal:
return None
# package is known, but no version is currently installed.
e = 'Could not determine version of uninstalled package: %s' % package
error_out(e)
vers = apt.upstream_version(pkg.current_ver.ver_str)
if 'swift' in pkg.name:
# Fully x.y.z match for swift versions
match = re.match(r'^(\d+)\.(\d+)\.(\d+)', vers)
else:
# x.y match only for 20XX.X
# and ignore patch level for other packages
match = re.match(r'^(\d+)\.(\d+)', vers)
if match:
vers = match.group(0)
# Generate a major version number for newer semantic
# versions of openstack projects
major_vers = vers.split('.')[0]
# >= Liberty independent project versions
if (package in PACKAGE_CODENAMES and
major_vers in PACKAGE_CODENAMES[package]):
return PACKAGE_CODENAMES[package][major_vers]
else:
# < Liberty co-ordinated project versions
try:
if 'swift' in pkg.name:
return get_swift_codename(vers)
else:
return OPENSTACK_CODENAMES[vers]
except KeyError:
if not fatal:
return None
e = 'Could not determine OpenStack codename for version %s' % vers
error_out(e)
|
python
|
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.PY3:
out = out.decode('UTF-8')
except subprocess.CalledProcessError:
return None
lines = out.split('\n')
for line in lines:
if package in line:
# Second item in list is Version
return line.split()[1]
import apt_pkg as apt
cache = apt_cache()
try:
pkg = cache[package]
except Exception:
if not fatal:
return None
# the package is unknown to the current apt cache.
e = 'Could not determine version of package with no installation '\
'candidate: %s' % package
error_out(e)
if not pkg.current_ver:
if not fatal:
return None
# package is known, but no version is currently installed.
e = 'Could not determine version of uninstalled package: %s' % package
error_out(e)
vers = apt.upstream_version(pkg.current_ver.ver_str)
if 'swift' in pkg.name:
# Fully x.y.z match for swift versions
match = re.match(r'^(\d+)\.(\d+)\.(\d+)', vers)
else:
# x.y match only for 20XX.X
# and ignore patch level for other packages
match = re.match(r'^(\d+)\.(\d+)', vers)
if match:
vers = match.group(0)
# Generate a major version number for newer semantic
# versions of openstack projects
major_vers = vers.split('.')[0]
# >= Liberty independent project versions
if (package in PACKAGE_CODENAMES and
major_vers in PACKAGE_CODENAMES[package]):
return PACKAGE_CODENAMES[package][major_vers]
else:
# < Liberty co-ordinated project versions
try:
if 'swift' in pkg.name:
return get_swift_codename(vers)
else:
return OPENSTACK_CODENAMES[vers]
except KeyError:
if not fatal:
return None
e = 'Could not determine OpenStack codename for version %s' % vers
error_out(e)
|
[
"def",
"get_os_codename_package",
"(",
"package",
",",
"fatal",
"=",
"True",
")",
":",
"if",
"snap_install_requested",
"(",
")",
":",
"cmd",
"=",
"[",
"'snap'",
",",
"'list'",
",",
"package",
"]",
"try",
":",
"out",
"=",
"subprocess",
".",
"check_output",
"(",
"cmd",
")",
"if",
"six",
".",
"PY3",
":",
"out",
"=",
"out",
".",
"decode",
"(",
"'UTF-8'",
")",
"except",
"subprocess",
".",
"CalledProcessError",
":",
"return",
"None",
"lines",
"=",
"out",
".",
"split",
"(",
"'\\n'",
")",
"for",
"line",
"in",
"lines",
":",
"if",
"package",
"in",
"line",
":",
"# Second item in list is Version",
"return",
"line",
".",
"split",
"(",
")",
"[",
"1",
"]",
"import",
"apt_pkg",
"as",
"apt",
"cache",
"=",
"apt_cache",
"(",
")",
"try",
":",
"pkg",
"=",
"cache",
"[",
"package",
"]",
"except",
"Exception",
":",
"if",
"not",
"fatal",
":",
"return",
"None",
"# the package is unknown to the current apt cache.",
"e",
"=",
"'Could not determine version of package with no installation '",
"'candidate: %s'",
"%",
"package",
"error_out",
"(",
"e",
")",
"if",
"not",
"pkg",
".",
"current_ver",
":",
"if",
"not",
"fatal",
":",
"return",
"None",
"# package is known, but no version is currently installed.",
"e",
"=",
"'Could not determine version of uninstalled package: %s'",
"%",
"package",
"error_out",
"(",
"e",
")",
"vers",
"=",
"apt",
".",
"upstream_version",
"(",
"pkg",
".",
"current_ver",
".",
"ver_str",
")",
"if",
"'swift'",
"in",
"pkg",
".",
"name",
":",
"# Fully x.y.z match for swift versions",
"match",
"=",
"re",
".",
"match",
"(",
"r'^(\\d+)\\.(\\d+)\\.(\\d+)'",
",",
"vers",
")",
"else",
":",
"# x.y match only for 20XX.X",
"# and ignore patch level for other packages",
"match",
"=",
"re",
".",
"match",
"(",
"r'^(\\d+)\\.(\\d+)'",
",",
"vers",
")",
"if",
"match",
":",
"vers",
"=",
"match",
".",
"group",
"(",
"0",
")",
"# Generate a major version number for newer semantic",
"# versions of openstack projects",
"major_vers",
"=",
"vers",
".",
"split",
"(",
"'.'",
")",
"[",
"0",
"]",
"# >= Liberty independent project versions",
"if",
"(",
"package",
"in",
"PACKAGE_CODENAMES",
"and",
"major_vers",
"in",
"PACKAGE_CODENAMES",
"[",
"package",
"]",
")",
":",
"return",
"PACKAGE_CODENAMES",
"[",
"package",
"]",
"[",
"major_vers",
"]",
"else",
":",
"# < Liberty co-ordinated project versions",
"try",
":",
"if",
"'swift'",
"in",
"pkg",
".",
"name",
":",
"return",
"get_swift_codename",
"(",
"vers",
")",
"else",
":",
"return",
"OPENSTACK_CODENAMES",
"[",
"vers",
"]",
"except",
"KeyError",
":",
"if",
"not",
"fatal",
":",
"return",
"None",
"e",
"=",
"'Could not determine OpenStack codename for version %s'",
"%",
"vers",
"error_out",
"(",
"e",
")"
] |
Derive OpenStack release codename from an installed package.
|
[
"Derive",
"OpenStack",
"release",
"codename",
"from",
"an",
"installed",
"package",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/utils.py#L415-L483
|
12,785
|
juju/charm-helpers
|
charmhelpers/contrib/openstack/utils.py
|
get_os_version_package
|
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
for cname, version in six.iteritems(vers_map):
if cname == codename:
return version[-1]
else:
vers_map = OPENSTACK_CODENAMES
for version, cname in six.iteritems(vers_map):
if cname == codename:
return version
|
python
|
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
for cname, version in six.iteritems(vers_map):
if cname == codename:
return version[-1]
else:
vers_map = OPENSTACK_CODENAMES
for version, cname in six.iteritems(vers_map):
if cname == codename:
return version
|
[
"def",
"get_os_version_package",
"(",
"pkg",
",",
"fatal",
"=",
"True",
")",
":",
"codename",
"=",
"get_os_codename_package",
"(",
"pkg",
",",
"fatal",
"=",
"fatal",
")",
"if",
"not",
"codename",
":",
"return",
"None",
"if",
"'swift'",
"in",
"pkg",
":",
"vers_map",
"=",
"SWIFT_CODENAMES",
"for",
"cname",
",",
"version",
"in",
"six",
".",
"iteritems",
"(",
"vers_map",
")",
":",
"if",
"cname",
"==",
"codename",
":",
"return",
"version",
"[",
"-",
"1",
"]",
"else",
":",
"vers_map",
"=",
"OPENSTACK_CODENAMES",
"for",
"version",
",",
"cname",
"in",
"six",
".",
"iteritems",
"(",
"vers_map",
")",
":",
"if",
"cname",
"==",
"codename",
":",
"return",
"version"
] |
Derive OpenStack version number from an installed package.
|
[
"Derive",
"OpenStack",
"version",
"number",
"from",
"an",
"installed",
"package",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/utils.py#L486-L502
|
12,786
|
juju/charm-helpers
|
charmhelpers/contrib/openstack/utils.py
|
os_release
|
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 determined from either an installed package or
the installation source, the earliest release supported by the charm should
be returned.
'''
global _os_rel
if reset_cache:
reset_os_release()
if _os_rel:
return _os_rel
_os_rel = (
get_os_codename_package(package, fatal=False) or
get_os_codename_install_source(config('openstack-origin')) or
base)
return _os_rel
|
python
|
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 determined from either an installed package or
the installation source, the earliest release supported by the charm should
be returned.
'''
global _os_rel
if reset_cache:
reset_os_release()
if _os_rel:
return _os_rel
_os_rel = (
get_os_codename_package(package, fatal=False) or
get_os_codename_install_source(config('openstack-origin')) or
base)
return _os_rel
|
[
"def",
"os_release",
"(",
"package",
",",
"base",
"=",
"'essex'",
",",
"reset_cache",
"=",
"False",
")",
":",
"global",
"_os_rel",
"if",
"reset_cache",
":",
"reset_os_release",
"(",
")",
"if",
"_os_rel",
":",
"return",
"_os_rel",
"_os_rel",
"=",
"(",
"get_os_codename_package",
"(",
"package",
",",
"fatal",
"=",
"False",
")",
"or",
"get_os_codename_install_source",
"(",
"config",
"(",
"'openstack-origin'",
")",
")",
"or",
"base",
")",
"return",
"_os_rel"
] |
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 determined from either an installed package or
the installation source, the earliest release supported by the charm should
be returned.
|
[
"Returns",
"OpenStack",
"release",
"codename",
"from",
"a",
"cached",
"global",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/utils.py#L517-L537
|
12,787
|
juju/charm-helpers
|
charmhelpers/contrib/openstack/utils.py
|
import_key
|
def import_key(keyid):
"""Import a key, either ASCII armored, or a GPG key id.
@param keyid: the key in ASCII armor format, or a GPG key id.
@raises SystemExit() via sys.exit() on failure.
"""
try:
return fetch_import_key(keyid)
except GPGKeyError as e:
error_out("Could not import key: {}".format(str(e)))
|
python
|
def import_key(keyid):
"""Import a key, either ASCII armored, or a GPG key id.
@param keyid: the key in ASCII armor format, or a GPG key id.
@raises SystemExit() via sys.exit() on failure.
"""
try:
return fetch_import_key(keyid)
except GPGKeyError as e:
error_out("Could not import key: {}".format(str(e)))
|
[
"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.
@param keyid: the key in ASCII armor format, or a GPG key id.
@raises SystemExit() via sys.exit() on failure.
|
[
"Import",
"a",
"key",
"either",
"ASCII",
"armored",
"or",
"a",
"GPG",
"key",
"id",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/utils.py#L541-L550
|
12,788
|
juju/charm-helpers
|
charmhelpers/contrib/openstack/utils.py
|
get_source_and_pgp_key
|
def get_source_and_pgp_key(source_and_key):
"""Look for a pgp key ID or ascii-armor key in the given input.
:param source_and_key: Sting, "source_spec|keyid" where '|keyid' is
optional.
:returns (source_spec, key_id OR None) as a tuple. Returns None for key_id
if there was no '|' in the source_and_key string.
"""
try:
source, key = source_and_key.split('|', 2)
return source, key or None
except ValueError:
return source_and_key, None
|
python
|
def get_source_and_pgp_key(source_and_key):
"""Look for a pgp key ID or ascii-armor key in the given input.
:param source_and_key: Sting, "source_spec|keyid" where '|keyid' is
optional.
:returns (source_spec, key_id OR None) as a tuple. Returns None for key_id
if there was no '|' in the source_and_key string.
"""
try:
source, key = source_and_key.split('|', 2)
return source, key or None
except ValueError:
return source_and_key, None
|
[
"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.
:param source_and_key: Sting, "source_spec|keyid" where '|keyid' is
optional.
:returns (source_spec, key_id OR None) as a tuple. Returns None for key_id
if there was no '|' in the source_and_key string.
|
[
"Look",
"for",
"a",
"pgp",
"key",
"ID",
"or",
"ascii",
"-",
"armor",
"key",
"in",
"the",
"given",
"input",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/utils.py#L553-L565
|
12,789
|
juju/charm-helpers
|
charmhelpers/contrib/openstack/utils.py
|
configure_installation_source
|
def configure_installation_source(source_plus_key):
"""Configure an installation source.
The functionality is provided by charmhelpers.fetch.add_source()
The difference between the two functions is that add_source() signature
requires the key to be passed directly, whereas this function passes an
optional key by appending '|<key>' to the end of the source specificiation
'source'.
Another difference from add_source() is that the function calls sys.exit(1)
if the configuration fails, whereas add_source() raises
SourceConfigurationError(). Another difference, is that add_source()
silently fails (with a juju_log command) if there is no matching source to
configure, whereas this function fails with a sys.exit(1)
:param source: String_plus_key -- see above for details.
Note that the behaviour on error is to log the error to the juju log and
then call sys.exit(1).
"""
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_key)
# handle the ordinary sources via add_source
try:
fetch_add_source(source, key, fail_invalid=True)
except SourceConfigError as se:
error_out(str(se))
|
python
|
def configure_installation_source(source_plus_key):
"""Configure an installation source.
The functionality is provided by charmhelpers.fetch.add_source()
The difference between the two functions is that add_source() signature
requires the key to be passed directly, whereas this function passes an
optional key by appending '|<key>' to the end of the source specificiation
'source'.
Another difference from add_source() is that the function calls sys.exit(1)
if the configuration fails, whereas add_source() raises
SourceConfigurationError(). Another difference, is that add_source()
silently fails (with a juju_log command) if there is no matching source to
configure, whereas this function fails with a sys.exit(1)
:param source: String_plus_key -- see above for details.
Note that the behaviour on error is to log the error to the juju log and
then call sys.exit(1).
"""
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_key)
# handle the ordinary sources via add_source
try:
fetch_add_source(source, key, fail_invalid=True)
except SourceConfigError as se:
error_out(str(se))
|
[
"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_key",
")",
"# handle the ordinary sources via add_source",
"try",
":",
"fetch_add_source",
"(",
"source",
",",
"key",
",",
"fail_invalid",
"=",
"True",
")",
"except",
"SourceConfigError",
"as",
"se",
":",
"error_out",
"(",
"str",
"(",
"se",
")",
")"
] |
Configure an installation source.
The functionality is provided by charmhelpers.fetch.add_source()
The difference between the two functions is that add_source() signature
requires the key to be passed directly, whereas this function passes an
optional key by appending '|<key>' to the end of the source specificiation
'source'.
Another difference from add_source() is that the function calls sys.exit(1)
if the configuration fails, whereas add_source() raises
SourceConfigurationError(). Another difference, is that add_source()
silently fails (with a juju_log command) if there is no matching source to
configure, whereas this function fails with a sys.exit(1)
:param source: String_plus_key -- see above for details.
Note that the behaviour on error is to log the error to the juju log and
then call sys.exit(1).
|
[
"Configure",
"an",
"installation",
"source",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/utils.py#L570-L600
|
12,790
|
juju/charm-helpers
|
charmhelpers/contrib/openstack/utils.py
|
config_value_changed
|
def config_value_changed(option):
"""
Determine if config value changed since last call to this function.
"""
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
return current != saved
|
python
|
def config_value_changed(option):
"""
Determine if config value changed since last call to this function.
"""
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
return current != saved
|
[
"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",
"return",
"current",
"!=",
"saved"
] |
Determine if config value changed since last call to this function.
|
[
"Determine",
"if",
"config",
"value",
"changed",
"since",
"last",
"call",
"to",
"this",
"function",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/utils.py#L603-L615
|
12,791
|
juju/charm-helpers
|
charmhelpers/contrib/openstack/utils.py
|
save_script_rc
|
def save_script_rc(script_path="scripts/scriptrc", **env_vars):
"""
Write an rc file in the charm-delivered directory containing
exported environment variables provided by env_vars. Any charm scripts run
outside the juju hook environment can source this scriptrc to obtain
updated config information necessary to perform health checks or
service changes.
"""
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_script:
rc_script.write(
"#!/bin/bash\n")
[rc_script.write('export %s=%s\n' % (u, p))
for u, p in six.iteritems(env_vars) if u != "script_path"]
|
python
|
def save_script_rc(script_path="scripts/scriptrc", **env_vars):
"""
Write an rc file in the charm-delivered directory containing
exported environment variables provided by env_vars. Any charm scripts run
outside the juju hook environment can source this scriptrc to obtain
updated config information necessary to perform health checks or
service changes.
"""
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_script:
rc_script.write(
"#!/bin/bash\n")
[rc_script.write('export %s=%s\n' % (u, p))
for u, p in six.iteritems(env_vars) if u != "script_path"]
|
[
"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_script",
":",
"rc_script",
".",
"write",
"(",
"\"#!/bin/bash\\n\"",
")",
"[",
"rc_script",
".",
"write",
"(",
"'export %s=%s\\n'",
"%",
"(",
"u",
",",
"p",
")",
")",
"for",
"u",
",",
"p",
"in",
"six",
".",
"iteritems",
"(",
"env_vars",
")",
"if",
"u",
"!=",
"\"script_path\"",
"]"
] |
Write an rc file in the charm-delivered directory containing
exported environment variables provided by env_vars. Any charm scripts run
outside the juju hook environment can source this scriptrc to obtain
updated config information necessary to perform health checks or
service changes.
|
[
"Write",
"an",
"rc",
"file",
"in",
"the",
"charm",
"-",
"delivered",
"directory",
"containing",
"exported",
"environment",
"variables",
"provided",
"by",
"env_vars",
".",
"Any",
"charm",
"scripts",
"run",
"outside",
"the",
"juju",
"hook",
"environment",
"can",
"source",
"this",
"scriptrc",
"to",
"obtain",
"updated",
"config",
"information",
"necessary",
"to",
"perform",
"health",
"checks",
"or",
"service",
"changes",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/utils.py#L618-L633
|
12,792
|
juju/charm-helpers
|
charmhelpers/contrib/openstack/utils.py
|
openstack_upgrade_available
|
def openstack_upgrade_available(package):
"""
Determines if an OpenStack upgrade is available from installation
source, based on version of installed package.
:param package: str: Name of installed package.
:returns: bool: : Returns True if configured installation source offers
a newer version of 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
if "swift" in package:
codename = get_os_codename_install_source(src)
avail_vers = get_os_version_codename_swift(codename)
else:
avail_vers = get_os_version_install_source(src)
apt.init()
return apt.version_compare(avail_vers, cur_vers) >= 1
|
python
|
def openstack_upgrade_available(package):
"""
Determines if an OpenStack upgrade is available from installation
source, based on version of installed package.
:param package: str: Name of installed package.
:returns: bool: : Returns True if configured installation source offers
a newer version of 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
if "swift" in package:
codename = get_os_codename_install_source(src)
avail_vers = get_os_version_codename_swift(codename)
else:
avail_vers = get_os_version_install_source(src)
apt.init()
return apt.version_compare(avail_vers, cur_vers) >= 1
|
[
"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",
"if",
"\"swift\"",
"in",
"package",
":",
"codename",
"=",
"get_os_codename_install_source",
"(",
"src",
")",
"avail_vers",
"=",
"get_os_version_codename_swift",
"(",
"codename",
")",
"else",
":",
"avail_vers",
"=",
"get_os_version_install_source",
"(",
"src",
")",
"apt",
".",
"init",
"(",
")",
"return",
"apt",
".",
"version_compare",
"(",
"avail_vers",
",",
"cur_vers",
")",
">=",
"1"
] |
Determines if an OpenStack upgrade is available from installation
source, based on version of installed package.
:param package: str: Name of installed package.
:returns: bool: : Returns True if configured installation source offers
a newer version of package.
|
[
"Determines",
"if",
"an",
"OpenStack",
"upgrade",
"is",
"available",
"from",
"installation",
"source",
"based",
"on",
"version",
"of",
"installed",
"package",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/utils.py#L636-L659
|
12,793
|
juju/charm-helpers
|
charmhelpers/contrib/openstack/utils.py
|
ensure_block_device
|
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]
if (block_device in _none):
error_out('prepare_storage(): Missing required input: block_device=%s.'
% block_device)
if block_device.startswith('/dev/'):
bdev = block_device
elif block_device.startswith('/'):
_bd = block_device.split('|')
if len(_bd) == 2:
bdev, size = _bd
else:
bdev = block_device
size = DEFAULT_LOOPBACK_SIZE
bdev = ensure_loopback_device(bdev, size)
else:
bdev = '/dev/%s' % block_device
if not is_block_device(bdev):
error_out('Failed to locate valid block device at %s' % bdev)
return bdev
|
python
|
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]
if (block_device in _none):
error_out('prepare_storage(): Missing required input: block_device=%s.'
% block_device)
if block_device.startswith('/dev/'):
bdev = block_device
elif block_device.startswith('/'):
_bd = block_device.split('|')
if len(_bd) == 2:
bdev, size = _bd
else:
bdev = block_device
size = DEFAULT_LOOPBACK_SIZE
bdev = ensure_loopback_device(bdev, size)
else:
bdev = '/dev/%s' % block_device
if not is_block_device(bdev):
error_out('Failed to locate valid block device at %s' % bdev)
return bdev
|
[
"def",
"ensure_block_device",
"(",
"block_device",
")",
":",
"_none",
"=",
"[",
"'None'",
",",
"'none'",
",",
"None",
"]",
"if",
"(",
"block_device",
"in",
"_none",
")",
":",
"error_out",
"(",
"'prepare_storage(): Missing required input: block_device=%s.'",
"%",
"block_device",
")",
"if",
"block_device",
".",
"startswith",
"(",
"'/dev/'",
")",
":",
"bdev",
"=",
"block_device",
"elif",
"block_device",
".",
"startswith",
"(",
"'/'",
")",
":",
"_bd",
"=",
"block_device",
".",
"split",
"(",
"'|'",
")",
"if",
"len",
"(",
"_bd",
")",
"==",
"2",
":",
"bdev",
",",
"size",
"=",
"_bd",
"else",
":",
"bdev",
"=",
"block_device",
"size",
"=",
"DEFAULT_LOOPBACK_SIZE",
"bdev",
"=",
"ensure_loopback_device",
"(",
"bdev",
",",
"size",
")",
"else",
":",
"bdev",
"=",
"'/dev/%s'",
"%",
"block_device",
"if",
"not",
"is_block_device",
"(",
"bdev",
")",
":",
"error_out",
"(",
"'Failed to locate valid block device at %s'",
"%",
"bdev",
")",
"return",
"bdev"
] |
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.
|
[
"Confirm",
"block_device",
"create",
"as",
"loopback",
"if",
"necessary",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/utils.py#L662-L691
|
12,794
|
juju/charm-helpers
|
charmhelpers/contrib/openstack/utils.py
|
os_requires_version
|
def os_requires_version(ostack_release, pkg):
"""
Decorator for hook to specify minimum supported release
"""
def wrap(f):
@wraps(f)
def wrapped_f(*args):
if os_release(pkg) < ostack_release:
raise Exception("This hook is not supported on releases"
" before %s" % ostack_release)
f(*args)
return wrapped_f
return wrap
|
python
|
def os_requires_version(ostack_release, pkg):
"""
Decorator for hook to specify minimum supported release
"""
def wrap(f):
@wraps(f)
def wrapped_f(*args):
if os_release(pkg) < ostack_release:
raise Exception("This hook is not supported on releases"
" before %s" % ostack_release)
f(*args)
return wrapped_f
return wrap
|
[
"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\"",
"\" before %s\"",
"%",
"ostack_release",
")",
"f",
"(",
"*",
"args",
")",
"return",
"wrapped_f",
"return",
"wrap"
] |
Decorator for hook to specify minimum supported release
|
[
"Decorator",
"for",
"hook",
"to",
"specify",
"minimum",
"supported",
"release"
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/utils.py#L754-L766
|
12,795
|
juju/charm-helpers
|
charmhelpers/contrib/openstack/utils.py
|
os_workload_status
|
def os_workload_status(configs, required_interfaces, charm_func=None):
"""
Decorator to set workload status based on complete contexts
"""
def wrap(f):
@wraps(f)
def wrapped_f(*args, **kwargs):
# Run the original function first
f(*args, **kwargs)
# Set workload status now that contexts have been
# acted on
set_os_workload_status(configs, required_interfaces, charm_func)
return wrapped_f
return wrap
|
python
|
def os_workload_status(configs, required_interfaces, charm_func=None):
"""
Decorator to set workload status based on complete contexts
"""
def wrap(f):
@wraps(f)
def wrapped_f(*args, **kwargs):
# Run the original function first
f(*args, **kwargs)
# Set workload status now that contexts have been
# acted on
set_os_workload_status(configs, required_interfaces, charm_func)
return wrapped_f
return wrap
|
[
"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 contexts have been",
"# acted on",
"set_os_workload_status",
"(",
"configs",
",",
"required_interfaces",
",",
"charm_func",
")",
"return",
"wrapped_f",
"return",
"wrap"
] |
Decorator to set workload status based on complete contexts
|
[
"Decorator",
"to",
"set",
"workload",
"status",
"based",
"on",
"complete",
"contexts"
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/utils.py#L769-L782
|
12,796
|
juju/charm-helpers
|
charmhelpers/contrib/openstack/utils.py
|
set_os_workload_status
|
def set_os_workload_status(configs, required_interfaces, charm_func=None,
services=None, ports=None):
"""Set the state of the workload status for the charm.
This calls _determine_os_workload_status() to get the new state, message
and sets the status using status_set()
@param configs: a templating.OSConfigRenderer() object
@param required_interfaces: {generic: [specific, specific2, ...]}
@param charm_func: a callable function that returns state, message. The
signature is charm_func(configs) -> (state, message)
@param services: list of strings OR dictionary specifying services/ports
@param ports: OPTIONAL list of port numbers.
@returns state, message: the new workload status, user message
"""
state, message = _determine_os_workload_status(
configs, required_interfaces, charm_func, services, ports)
status_set(state, message)
|
python
|
def set_os_workload_status(configs, required_interfaces, charm_func=None,
services=None, ports=None):
"""Set the state of the workload status for the charm.
This calls _determine_os_workload_status() to get the new state, message
and sets the status using status_set()
@param configs: a templating.OSConfigRenderer() object
@param required_interfaces: {generic: [specific, specific2, ...]}
@param charm_func: a callable function that returns state, message. The
signature is charm_func(configs) -> (state, message)
@param services: list of strings OR dictionary specifying services/ports
@param ports: OPTIONAL list of port numbers.
@returns state, message: the new workload status, user message
"""
state, message = _determine_os_workload_status(
configs, required_interfaces, charm_func, services, ports)
status_set(state, message)
|
[
"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",
",",
"message",
")"
] |
Set the state of the workload status for the charm.
This calls _determine_os_workload_status() to get the new state, message
and sets the status using status_set()
@param configs: a templating.OSConfigRenderer() object
@param required_interfaces: {generic: [specific, specific2, ...]}
@param charm_func: a callable function that returns state, message. The
signature is charm_func(configs) -> (state, message)
@param services: list of strings OR dictionary specifying services/ports
@param ports: OPTIONAL list of port numbers.
@returns state, message: the new workload status, user message
|
[
"Set",
"the",
"state",
"of",
"the",
"workload",
"status",
"for",
"the",
"charm",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/utils.py#L785-L802
|
12,797
|
juju/charm-helpers
|
charmhelpers/contrib/openstack/utils.py
|
_determine_os_workload_status
|
def _determine_os_workload_status(
configs, required_interfaces, charm_func=None,
services=None, ports=None):
"""Determine the state of the workload status for the charm.
This function returns the new workload status for the charm based
on the state of the interfaces, the paused state and whether the
services are actually running and any specified ports are open.
This checks:
1. if the unit should be paused, that it is actually paused. If so the
state is 'maintenance' + message, else 'broken'.
2. that the interfaces/relations are complete. If they are not then
it sets the state to either 'broken' or 'waiting' and an appropriate
message.
3. If all the relation data is set, then it checks that the actual
services really are running. If not it sets the state to 'broken'.
If everything is okay then the state returns 'active'.
@param configs: a templating.OSConfigRenderer() object
@param required_interfaces: {generic: [specific, specific2, ...]}
@param charm_func: a callable function that returns state, message. The
signature is charm_func(configs) -> (state, message)
@param services: list of strings OR dictionary specifying services/ports
@param ports: OPTIONAL list of port numbers.
@returns state, message: the new workload status, user message
"""
state, message = _ows_check_if_paused(services, ports)
if state is None:
state, message = _ows_check_generic_interfaces(
configs, required_interfaces)
if state != 'maintenance' and charm_func:
# _ows_check_charm_func() may modify the state, message
state, message = _ows_check_charm_func(
state, message, lambda: charm_func(configs))
if state is None:
state, message = _ows_check_services_running(services, ports)
if state is None:
state = 'active'
message = "Unit is ready"
juju_log(message, 'INFO')
return state, message
|
python
|
def _determine_os_workload_status(
configs, required_interfaces, charm_func=None,
services=None, ports=None):
"""Determine the state of the workload status for the charm.
This function returns the new workload status for the charm based
on the state of the interfaces, the paused state and whether the
services are actually running and any specified ports are open.
This checks:
1. if the unit should be paused, that it is actually paused. If so the
state is 'maintenance' + message, else 'broken'.
2. that the interfaces/relations are complete. If they are not then
it sets the state to either 'broken' or 'waiting' and an appropriate
message.
3. If all the relation data is set, then it checks that the actual
services really are running. If not it sets the state to 'broken'.
If everything is okay then the state returns 'active'.
@param configs: a templating.OSConfigRenderer() object
@param required_interfaces: {generic: [specific, specific2, ...]}
@param charm_func: a callable function that returns state, message. The
signature is charm_func(configs) -> (state, message)
@param services: list of strings OR dictionary specifying services/ports
@param ports: OPTIONAL list of port numbers.
@returns state, message: the new workload status, user message
"""
state, message = _ows_check_if_paused(services, ports)
if state is None:
state, message = _ows_check_generic_interfaces(
configs, required_interfaces)
if state != 'maintenance' and charm_func:
# _ows_check_charm_func() may modify the state, message
state, message = _ows_check_charm_func(
state, message, lambda: charm_func(configs))
if state is None:
state, message = _ows_check_services_running(services, ports)
if state is None:
state = 'active'
message = "Unit is ready"
juju_log(message, 'INFO')
return state, message
|
[
"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",
"(",
"configs",
",",
"required_interfaces",
")",
"if",
"state",
"!=",
"'maintenance'",
"and",
"charm_func",
":",
"# _ows_check_charm_func() may modify the state, message",
"state",
",",
"message",
"=",
"_ows_check_charm_func",
"(",
"state",
",",
"message",
",",
"lambda",
":",
"charm_func",
"(",
"configs",
")",
")",
"if",
"state",
"is",
"None",
":",
"state",
",",
"message",
"=",
"_ows_check_services_running",
"(",
"services",
",",
"ports",
")",
"if",
"state",
"is",
"None",
":",
"state",
"=",
"'active'",
"message",
"=",
"\"Unit is ready\"",
"juju_log",
"(",
"message",
",",
"'INFO'",
")",
"return",
"state",
",",
"message"
] |
Determine the state of the workload status for the charm.
This function returns the new workload status for the charm based
on the state of the interfaces, the paused state and whether the
services are actually running and any specified ports are open.
This checks:
1. if the unit should be paused, that it is actually paused. If so the
state is 'maintenance' + message, else 'broken'.
2. that the interfaces/relations are complete. If they are not then
it sets the state to either 'broken' or 'waiting' and an appropriate
message.
3. If all the relation data is set, then it checks that the actual
services really are running. If not it sets the state to 'broken'.
If everything is okay then the state returns 'active'.
@param configs: a templating.OSConfigRenderer() object
@param required_interfaces: {generic: [specific, specific2, ...]}
@param charm_func: a callable function that returns state, message. The
signature is charm_func(configs) -> (state, message)
@param services: list of strings OR dictionary specifying services/ports
@param ports: OPTIONAL list of port numbers.
@returns state, message: the new workload status, user message
|
[
"Determine",
"the",
"state",
"of",
"the",
"workload",
"status",
"for",
"the",
"charm",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/utils.py#L805-L853
|
12,798
|
juju/charm-helpers
|
charmhelpers/contrib/openstack/utils.py
|
_ows_check_generic_interfaces
|
def _ows_check_generic_interfaces(configs, required_interfaces):
"""Check the complete contexts to determine the workload status.
- Checks for missing or incomplete contexts
- juju log details of missing required data.
- determines the correct workload status
- creates an appropriate message for status_set(...)
if there are no problems then the function returns None, None
@param configs: a templating.OSConfigRenderer() object
@params required_interfaces: {generic_interface: [specific_interface], }
@returns state, message or None, None
"""
incomplete_rel_data = incomplete_relation_data(configs,
required_interfaces)
state = None
message = None
missing_relations = set()
incomplete_relations = set()
for generic_interface, relations_states in incomplete_rel_data.items():
related_interface = None
missing_data = {}
# Related or not?
for interface, relation_state in relations_states.items():
if relation_state.get('related'):
related_interface = interface
missing_data = relation_state.get('missing_data')
break
# No relation ID for the generic_interface?
if not related_interface:
juju_log("{} relation is missing and must be related for "
"functionality. ".format(generic_interface), 'WARN')
state = 'blocked'
missing_relations.add(generic_interface)
else:
# Relation ID eists but no related unit
if not missing_data:
# Edge case - relation ID exists but departings
_hook_name = hook_name()
if (('departed' in _hook_name or 'broken' in _hook_name) and
related_interface in _hook_name):
state = 'blocked'
missing_relations.add(generic_interface)
juju_log("{} relation's interface, {}, "
"relationship is departed or broken "
"and is required for functionality."
"".format(generic_interface, related_interface),
"WARN")
# Normal case relation ID exists but no related unit
# (joining)
else:
juju_log("{} relations's interface, {}, is related but has"
" no units in the relation."
"".format(generic_interface, related_interface),
"INFO")
# Related unit exists and data missing on the relation
else:
juju_log("{} relation's interface, {}, is related awaiting "
"the following data from the relationship: {}. "
"".format(generic_interface, related_interface,
", ".join(missing_data)), "INFO")
if state != 'blocked':
state = 'waiting'
if generic_interface not in missing_relations:
incomplete_relations.add(generic_interface)
if missing_relations:
message = "Missing relations: {}".format(", ".join(missing_relations))
if incomplete_relations:
message += "; incomplete relations: {}" \
"".format(", ".join(incomplete_relations))
state = 'blocked'
elif incomplete_relations:
message = "Incomplete relations: {}" \
"".format(", ".join(incomplete_relations))
state = 'waiting'
return state, message
|
python
|
def _ows_check_generic_interfaces(configs, required_interfaces):
"""Check the complete contexts to determine the workload status.
- Checks for missing or incomplete contexts
- juju log details of missing required data.
- determines the correct workload status
- creates an appropriate message for status_set(...)
if there are no problems then the function returns None, None
@param configs: a templating.OSConfigRenderer() object
@params required_interfaces: {generic_interface: [specific_interface], }
@returns state, message or None, None
"""
incomplete_rel_data = incomplete_relation_data(configs,
required_interfaces)
state = None
message = None
missing_relations = set()
incomplete_relations = set()
for generic_interface, relations_states in incomplete_rel_data.items():
related_interface = None
missing_data = {}
# Related or not?
for interface, relation_state in relations_states.items():
if relation_state.get('related'):
related_interface = interface
missing_data = relation_state.get('missing_data')
break
# No relation ID for the generic_interface?
if not related_interface:
juju_log("{} relation is missing and must be related for "
"functionality. ".format(generic_interface), 'WARN')
state = 'blocked'
missing_relations.add(generic_interface)
else:
# Relation ID eists but no related unit
if not missing_data:
# Edge case - relation ID exists but departings
_hook_name = hook_name()
if (('departed' in _hook_name or 'broken' in _hook_name) and
related_interface in _hook_name):
state = 'blocked'
missing_relations.add(generic_interface)
juju_log("{} relation's interface, {}, "
"relationship is departed or broken "
"and is required for functionality."
"".format(generic_interface, related_interface),
"WARN")
# Normal case relation ID exists but no related unit
# (joining)
else:
juju_log("{} relations's interface, {}, is related but has"
" no units in the relation."
"".format(generic_interface, related_interface),
"INFO")
# Related unit exists and data missing on the relation
else:
juju_log("{} relation's interface, {}, is related awaiting "
"the following data from the relationship: {}. "
"".format(generic_interface, related_interface,
", ".join(missing_data)), "INFO")
if state != 'blocked':
state = 'waiting'
if generic_interface not in missing_relations:
incomplete_relations.add(generic_interface)
if missing_relations:
message = "Missing relations: {}".format(", ".join(missing_relations))
if incomplete_relations:
message += "; incomplete relations: {}" \
"".format(", ".join(incomplete_relations))
state = 'blocked'
elif incomplete_relations:
message = "Incomplete relations: {}" \
"".format(", ".join(incomplete_relations))
state = 'waiting'
return state, message
|
[
"def",
"_ows_check_generic_interfaces",
"(",
"configs",
",",
"required_interfaces",
")",
":",
"incomplete_rel_data",
"=",
"incomplete_relation_data",
"(",
"configs",
",",
"required_interfaces",
")",
"state",
"=",
"None",
"message",
"=",
"None",
"missing_relations",
"=",
"set",
"(",
")",
"incomplete_relations",
"=",
"set",
"(",
")",
"for",
"generic_interface",
",",
"relations_states",
"in",
"incomplete_rel_data",
".",
"items",
"(",
")",
":",
"related_interface",
"=",
"None",
"missing_data",
"=",
"{",
"}",
"# Related or not?",
"for",
"interface",
",",
"relation_state",
"in",
"relations_states",
".",
"items",
"(",
")",
":",
"if",
"relation_state",
".",
"get",
"(",
"'related'",
")",
":",
"related_interface",
"=",
"interface",
"missing_data",
"=",
"relation_state",
".",
"get",
"(",
"'missing_data'",
")",
"break",
"# No relation ID for the generic_interface?",
"if",
"not",
"related_interface",
":",
"juju_log",
"(",
"\"{} relation is missing and must be related for \"",
"\"functionality. \"",
".",
"format",
"(",
"generic_interface",
")",
",",
"'WARN'",
")",
"state",
"=",
"'blocked'",
"missing_relations",
".",
"add",
"(",
"generic_interface",
")",
"else",
":",
"# Relation ID eists but no related unit",
"if",
"not",
"missing_data",
":",
"# Edge case - relation ID exists but departings",
"_hook_name",
"=",
"hook_name",
"(",
")",
"if",
"(",
"(",
"'departed'",
"in",
"_hook_name",
"or",
"'broken'",
"in",
"_hook_name",
")",
"and",
"related_interface",
"in",
"_hook_name",
")",
":",
"state",
"=",
"'blocked'",
"missing_relations",
".",
"add",
"(",
"generic_interface",
")",
"juju_log",
"(",
"\"{} relation's interface, {}, \"",
"\"relationship is departed or broken \"",
"\"and is required for functionality.\"",
"\"\"",
".",
"format",
"(",
"generic_interface",
",",
"related_interface",
")",
",",
"\"WARN\"",
")",
"# Normal case relation ID exists but no related unit",
"# (joining)",
"else",
":",
"juju_log",
"(",
"\"{} relations's interface, {}, is related but has\"",
"\" no units in the relation.\"",
"\"\"",
".",
"format",
"(",
"generic_interface",
",",
"related_interface",
")",
",",
"\"INFO\"",
")",
"# Related unit exists and data missing on the relation",
"else",
":",
"juju_log",
"(",
"\"{} relation's interface, {}, is related awaiting \"",
"\"the following data from the relationship: {}. \"",
"\"\"",
".",
"format",
"(",
"generic_interface",
",",
"related_interface",
",",
"\", \"",
".",
"join",
"(",
"missing_data",
")",
")",
",",
"\"INFO\"",
")",
"if",
"state",
"!=",
"'blocked'",
":",
"state",
"=",
"'waiting'",
"if",
"generic_interface",
"not",
"in",
"missing_relations",
":",
"incomplete_relations",
".",
"add",
"(",
"generic_interface",
")",
"if",
"missing_relations",
":",
"message",
"=",
"\"Missing relations: {}\"",
".",
"format",
"(",
"\", \"",
".",
"join",
"(",
"missing_relations",
")",
")",
"if",
"incomplete_relations",
":",
"message",
"+=",
"\"; incomplete relations: {}\"",
"\"\"",
".",
"format",
"(",
"\", \"",
".",
"join",
"(",
"incomplete_relations",
")",
")",
"state",
"=",
"'blocked'",
"elif",
"incomplete_relations",
":",
"message",
"=",
"\"Incomplete relations: {}\"",
"\"\"",
".",
"format",
"(",
"\", \"",
".",
"join",
"(",
"incomplete_relations",
")",
")",
"state",
"=",
"'waiting'",
"return",
"state",
",",
"message"
] |
Check the complete contexts to determine the workload status.
- Checks for missing or incomplete contexts
- juju log details of missing required data.
- determines the correct workload status
- creates an appropriate message for status_set(...)
if there are no problems then the function returns None, None
@param configs: a templating.OSConfigRenderer() object
@params required_interfaces: {generic_interface: [specific_interface], }
@returns state, message or None, None
|
[
"Check",
"the",
"complete",
"contexts",
"to",
"determine",
"the",
"workload",
"status",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/utils.py#L890-L969
|
12,799
|
juju/charm-helpers
|
charmhelpers/contrib/openstack/utils.py
|
_ows_check_services_running
|
def _ows_check_services_running(services, ports):
"""Check that the services that should be running are actually running
and that any ports specified are being listened to.
@param services: list of strings OR dictionary specifying services/ports
@param ports: list of ports
@returns state, message: strings or None, None
"""
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):
messages.append(
"Services not running that should be: {}"
.format(", ".join(_filter_tuples(services_running, False))))
state = 'blocked'
# also verify that the ports that should be open are open
# NB, that ServiceManager objects only OPTIONALLY have ports
map_not_open, ports_open = (
_check_listening_on_services_ports(services))
if not all(ports_open):
# find which service has missing ports. They are in service
# order which makes it a bit easier.
message_parts = {service: ", ".join([str(v) for v in open_ports])
for service, open_ports in map_not_open.items()}
message = ", ".join(
["{}: [{}]".format(s, sp) for s, sp in message_parts.items()])
messages.append(
"Services with ports not open that should be: {}"
.format(message))
state = 'blocked'
if ports is not None:
# and we can also check ports which we don't know the service for
ports_open, ports_open_bools = _check_listening_on_ports_list(ports)
if not all(ports_open_bools):
messages.append(
"Ports which should be open, but are not: {}"
.format(", ".join([str(p) for p, v in ports_open
if not v])))
state = 'blocked'
if state is not None:
message = "; ".join(messages)
return state, message
return None, None
|
python
|
def _ows_check_services_running(services, ports):
"""Check that the services that should be running are actually running
and that any ports specified are being listened to.
@param services: list of strings OR dictionary specifying services/ports
@param ports: list of ports
@returns state, message: strings or None, None
"""
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):
messages.append(
"Services not running that should be: {}"
.format(", ".join(_filter_tuples(services_running, False))))
state = 'blocked'
# also verify that the ports that should be open are open
# NB, that ServiceManager objects only OPTIONALLY have ports
map_not_open, ports_open = (
_check_listening_on_services_ports(services))
if not all(ports_open):
# find which service has missing ports. They are in service
# order which makes it a bit easier.
message_parts = {service: ", ".join([str(v) for v in open_ports])
for service, open_ports in map_not_open.items()}
message = ", ".join(
["{}: [{}]".format(s, sp) for s, sp in message_parts.items()])
messages.append(
"Services with ports not open that should be: {}"
.format(message))
state = 'blocked'
if ports is not None:
# and we can also check ports which we don't know the service for
ports_open, ports_open_bools = _check_listening_on_ports_list(ports)
if not all(ports_open_bools):
messages.append(
"Ports which should be open, but are not: {}"
.format(", ".join([str(p) for p, v in ports_open
if not v])))
state = 'blocked'
if state is not None:
message = "; ".join(messages)
return state, message
return None, None
|
[
"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",
")",
":",
"messages",
".",
"append",
"(",
"\"Services not running that should be: {}\"",
".",
"format",
"(",
"\", \"",
".",
"join",
"(",
"_filter_tuples",
"(",
"services_running",
",",
"False",
")",
")",
")",
")",
"state",
"=",
"'blocked'",
"# also verify that the ports that should be open are open",
"# NB, that ServiceManager objects only OPTIONALLY have ports",
"map_not_open",
",",
"ports_open",
"=",
"(",
"_check_listening_on_services_ports",
"(",
"services",
")",
")",
"if",
"not",
"all",
"(",
"ports_open",
")",
":",
"# find which service has missing ports. They are in service",
"# order which makes it a bit easier.",
"message_parts",
"=",
"{",
"service",
":",
"\", \"",
".",
"join",
"(",
"[",
"str",
"(",
"v",
")",
"for",
"v",
"in",
"open_ports",
"]",
")",
"for",
"service",
",",
"open_ports",
"in",
"map_not_open",
".",
"items",
"(",
")",
"}",
"message",
"=",
"\", \"",
".",
"join",
"(",
"[",
"\"{}: [{}]\"",
".",
"format",
"(",
"s",
",",
"sp",
")",
"for",
"s",
",",
"sp",
"in",
"message_parts",
".",
"items",
"(",
")",
"]",
")",
"messages",
".",
"append",
"(",
"\"Services with ports not open that should be: {}\"",
".",
"format",
"(",
"message",
")",
")",
"state",
"=",
"'blocked'",
"if",
"ports",
"is",
"not",
"None",
":",
"# and we can also check ports which we don't know the service for",
"ports_open",
",",
"ports_open_bools",
"=",
"_check_listening_on_ports_list",
"(",
"ports",
")",
"if",
"not",
"all",
"(",
"ports_open_bools",
")",
":",
"messages",
".",
"append",
"(",
"\"Ports which should be open, but are not: {}\"",
".",
"format",
"(",
"\", \"",
".",
"join",
"(",
"[",
"str",
"(",
"p",
")",
"for",
"p",
",",
"v",
"in",
"ports_open",
"if",
"not",
"v",
"]",
")",
")",
")",
"state",
"=",
"'blocked'",
"if",
"state",
"is",
"not",
"None",
":",
"message",
"=",
"\"; \"",
".",
"join",
"(",
"messages",
")",
"return",
"state",
",",
"message",
"return",
"None",
",",
"None"
] |
Check that the services that should be running are actually running
and that any ports specified are being listened to.
@param services: list of strings OR dictionary specifying services/ports
@param ports: list of ports
@returns state, message: strings or None, None
|
[
"Check",
"that",
"the",
"services",
"that",
"should",
"be",
"running",
"are",
"actually",
"running",
"and",
"that",
"any",
"ports",
"specified",
"are",
"being",
"listened",
"to",
"."
] |
aa785c40c3b7a8c69dbfbc7921d6b9f30142e171
|
https://github.com/juju/charm-helpers/blob/aa785c40c3b7a8c69dbfbc7921d6b9f30142e171/charmhelpers/contrib/openstack/utils.py#L998-L1046
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.