Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def write_vaultlocker_conf(context, priority=100):
charm_vl_path = "/var/lib/charm/{}/vaultlocker.conf".format(
hookenv.service_name()
)
host.mkdir(os.path.dirname(charm_vl_path), perms=0o700)
templating.render(source='vaultlocker.conf.j2',
... | [
"Write vaultlocker configuration to disk and install alternative\n\n :param context: Dict of data from vault-kv relation\n :ptype: context: dict\n :param priority: Priority of alternative configuration\n :ptype: priority: int"
] |
Please provide a description of the function:def vault_relation_complete(backend=None):
vault_kv = VaultKVContext(secret_backend=backend or VAULTLOCKER_BACKEND)
vault_kv()
return vault_kv.complete | [
"Determine whether vault relation is complete\n\n :param backend: Name of secrets backend requested\n :ptype backend: string\n :returns: whether the relation to vault is complete\n :rtype: bool"
] |
Please provide a description of the function:def retrieve_secret_id(url, token):
import hvac
client = hvac.Client(url=url, token=token)
response = client._post('/v1/sys/wrapping/unwrap')
if response.status_code == 200:
data = response.json()
return data['data']['secret_id'] | [
"Retrieve a response-wrapped secret_id from Vault\n\n :param url: URL to Vault Server\n :ptype url: str\n :param token: One shot Token to use\n :ptype token: str\n :returns: secret_id to use for Vault Access\n :rtype: str"
] |
Please provide a description of the function:def retry_on_exception(num_retries, base_delay=0, exc_type=Exception):
def _retry_on_exception_inner_1(f):
def _retry_on_exception_inner_2(*args, **kwargs):
retries = num_retries
multiplier = 1
while True:
... | [
"If the decorated function raises exception exc_type, allow num_retries\n retry attempts before raise the exception.\n "
] |
Please provide a description of the function:def _snap_exec(commands):
assert type(commands) == list
retry_count = 0
return_code = None
while return_code is None or return_code == SNAP_NO_LOCK:
try:
return_code = subprocess.check_call(['snap'] + commands,
... | [
"\n Execute snap commands.\n\n :param commands: List commands\n :return: Integer exit code\n "
] |
Please provide a description of the function:def snap_remove(packages, *flags):
if type(packages) is not list:
packages = [packages]
flags = list(flags)
message = 'Removing snap(s) "%s"' % ', '.join(packages)
if flags:
message += ' with options "%s"' % ', '.join(flags)
log(me... | [
"\n Remove a snap package.\n\n :param packages: String or List String package name\n :param flags: List String flags to pass to remove command\n :return: Integer return code from snap\n "
] |
Please provide a description of the function:def persistent_modprobe(module):
if not os.path.exists('/etc/rc.modules'):
open('/etc/rc.modules', 'a')
os.chmod('/etc/rc.modules', 111)
with open('/etc/rc.modules', 'r+') as modules:
if module not in modules.read():
modules.w... | [
"Load a kernel module and configure for auto-load on reboot."
] |
Please provide a description of the function:def validate_endpoint_data(self, endpoints, admin_port, internal_port,
public_port, expected, openstack_release=None):
validation_function = self.validate_v2_endpoint_data
xenial_queens = OPENSTACK_RELEASES_PAIRS.index(... | [
"Validate endpoint data. Pick the correct validator based on\n OpenStack release. Expected data should be in the v2 format:\n {\n 'id': id,\n 'region': region,\n 'adminurl': adminurl,\n 'internalurl': internalurl,\n 'publicurl... |
Please provide a description of the function:def validate_v2_endpoint_data(self, endpoints, admin_port, internal_port,
public_port, expected):
self.log.debug('Validating endpoint data...')
self.log.debug('actual: {}'.format(repr(endpoints)))
found = Fal... | [
"Validate endpoint data.\n\n Validate actual endpoint data vs expected endpoint data. The ports\n are used to find the matching endpoint.\n "
] |
Please provide a description of the function:def validate_v3_endpoint_data(self, endpoints, admin_port, internal_port,
public_port, expected, expected_num_eps=3):
self.log.debug('Validating v3 endpoint data...')
self.log.debug('actual: {}'.format(repr(endpoints... | [
"Validate keystone v3 endpoint data.\n\n Validate the v3 endpoint data which has changed from v2. The\n ports are used to find the matching endpoint.\n\n The new v3 endpoint data looks like:\n\n [<Endpoint enabled=True,\n id=0432655fc2f74d1e9fa17bdaa6f6e60b,\n ... |
Please provide a description of the function:def convert_svc_catalog_endpoint_data_to_v3(self, ep_data):
self.log.warn("Endpoint ID and Region ID validation is limited to not "
"null checks after v2 to v3 conversion")
for svc in ep_data.keys():
assert len(ep_da... | [
"Convert v2 endpoint data into v3.\n\n {\n 'service_name1': [\n {\n 'adminURL': adminURL,\n 'id': id,\n 'region': region.\n 'publicURL': publicURL,\n 'internalURL':... |
Please provide a description of the function:def validate_svc_catalog_endpoint_data(self, expected, actual,
openstack_release=None):
validation_function = self.validate_v2_svc_catalog_endpoint_data
xenial_queens = OPENSTACK_RELEASES_PAIRS.index('xenial... | [
"Validate service catalog endpoint data. Pick the correct validator\n for the OpenStack version. Expected data should be in the v2 format:\n {\n 'service_name1': [\n {\n 'adminURL': adminURL,\n 'id': id,\n ... |
Please provide a description of the function:def validate_v2_svc_catalog_endpoint_data(self, expected, actual):
self.log.debug('Validating service catalog endpoint data...')
self.log.debug('actual: {}'.format(repr(actual)))
for k, v in six.iteritems(expected):
if k in actual... | [
"Validate service catalog endpoint data.\n\n Validate a list of actual service catalog endpoints vs a list of\n expected service catalog endpoints.\n "
] |
Please provide a description of the function:def validate_v3_svc_catalog_endpoint_data(self, expected, actual):
self.log.debug('Validating v3 service catalog endpoint data...')
self.log.debug('actual: {}'.format(repr(actual)))
for k, v in six.iteritems(expected):
if k in act... | [
"Validate the keystone v3 catalog endpoint data.\n\n Validate a list of dictinaries that make up the keystone v3 service\n catalogue.\n\n It is in the form of:\n\n\n {u'identity': [{u'id': u'48346b01c6804b298cdd7349aadb732e',\n u'interface': u'admin',\n ... |
Please provide a description of the function:def validate_tenant_data(self, expected, actual):
self.log.debug('Validating tenant data...')
self.log.debug('actual: {}'.format(repr(actual)))
for e in expected:
found = False
for act in actual:
a = {'... | [
"Validate tenant data.\n\n Validate a list of actual tenant data vs list of expected tenant\n data.\n "
] |
Please provide a description of the function:def validate_user_data(self, expected, actual, api_version=None):
self.log.debug('Validating user data...')
self.log.debug('actual: {}'.format(repr(actual)))
for e in expected:
found = False
for act in actual:
... | [
"Validate user data.\n\n Validate a list of actual user data vs a list of expected user\n data.\n "
] |
Please provide a description of the function:def validate_flavor_data(self, expected, actual):
self.log.debug('Validating flavor data...')
self.log.debug('actual: {}'.format(repr(actual)))
act = [a.name for a in actual]
return self._validate_list_data(expected, act) | [
"Validate flavor data.\n\n Validate a list of actual flavors vs a list of expected flavors.\n "
] |
Please provide a description of the function:def tenant_exists(self, keystone, tenant):
self.log.debug('Checking if tenant exists ({})...'.format(tenant))
return tenant in [t.name for t in keystone.tenants.list()] | [
"Return True if tenant exists."
] |
Please provide a description of the function:def keystone_wait_for_propagation(self, sentry_relation_pairs,
api_version):
for (sentry, relation_name) in sentry_relation_pairs:
rel = sentry.relation('identity-service',
r... | [
"Iterate over list of sentry and relation tuples and verify that\n api_version has the expected value.\n\n :param sentry_relation_pairs: list of sentry, relation name tuples used\n for monitoring propagation of relation\n dat... |
Please provide a description of the function:def keystone_configure_api_version(self, sentry_relation_pairs, deployment,
api_version):
self.log.debug("Setting keystone preferred-api-version: '{}'"
"".format(api_version))
config = {'... | [
"Configure preferred-api-version of keystone in deployment and\n monitor provided list of relation objects for propagation\n before returning to caller.\n\n :param sentry_relation_pairs: list of sentry, relation tuples used for\n monitoring propagation... |
Please provide a description of the function:def authenticate_cinder_admin(self, keystone, api_version=2):
self.log.debug('Authenticating cinder admin...')
_clients = {
1: cinder_client.Client,
2: cinder_clientv2.Client}
return _clients[api_version](session=keyst... | [
"Authenticates admin user with cinder."
] |
Please provide a description of the function:def authenticate_keystone(self, keystone_ip, username, password,
api_version=False, admin_port=False,
user_domain_name=None, domain_name=None,
project_domain_name=None, project_name=Non... | [
"Authenticate with Keystone"
] |
Please provide a description of the function:def get_keystone_session(self, keystone_ip, username, password,
api_version=False, admin_port=False,
user_domain_name=None, domain_name=None,
project_domain_name=None, project_name=None):
... | [
"Return a keystone session object"
] |
Please provide a description of the function:def get_keystone_endpoint(self, keystone_ip, api_version=None,
admin_port=False):
port = 5000
if admin_port:
port = 35357
base_ep = "http://{}:{}".format(keystone_ip.strip().decode('utf-8'),
... | [
"Return keystone endpoint"
] |
Please provide a description of the function:def get_default_keystone_session(self, keystone_sentry,
openstack_release=None, api_version=2):
self.log.debug('Authenticating keystone admin...')
# 11 => xenial_queens
if api_version == 3 or (openstack_re... | [
"Return a keystone session object and client object assuming standard\n default settings\n\n Example call in amulet tests:\n self.keystone_session, self.keystone = u.get_default_keystone_session(\n self.keystone_sentry,\n openstack_release=self._... |
Please provide a description of the function:def authenticate_keystone_admin(self, keystone_sentry, user, password,
tenant=None, api_version=None,
keystone_ip=None, user_domain_name=None,
project_domain_name=None... | [
"Authenticates admin user with the keystone admin endpoint."
] |
Please provide a description of the function:def authenticate_keystone_user(self, keystone, user, password, tenant):
self.log.debug('Authenticating keystone user ({})...'.format(user))
ep = keystone.service_catalog.url_for(service_type='identity',
i... | [
"Authenticates a regular user with the keystone public endpoint."
] |
Please provide a description of the function:def authenticate_glance_admin(self, keystone, force_v1_client=False):
self.log.debug('Authenticating glance admin...')
ep = keystone.service_catalog.url_for(service_type='image',
interface='adminURL')
... | [
"Authenticates admin user with glance."
] |
Please provide a description of the function:def authenticate_heat_admin(self, keystone):
self.log.debug('Authenticating heat admin...')
ep = keystone.service_catalog.url_for(service_type='orchestration',
interface='publicURL')
if keystone.s... | [
"Authenticates the admin user with heat."
] |
Please provide a description of the function:def authenticate_nova_user(self, keystone, user, password, tenant):
self.log.debug('Authenticating nova user ({})...'.format(user))
ep = keystone.service_catalog.url_for(service_type='identity',
interface... | [
"Authenticates a regular user with nova-api."
] |
Please provide a description of the function:def authenticate_swift_user(self, keystone, user, password, tenant):
self.log.debug('Authenticating swift user ({})...'.format(user))
ep = keystone.service_catalog.url_for(service_type='identity',
interfa... | [
"Authenticates a regular user with swift api."
] |
Please provide a description of the function:def create_flavor(self, nova, name, ram, vcpus, disk, flavorid="auto",
ephemeral=0, swap=0, rxtx_factor=1.0, is_public=True):
try:
nova.flavors.find(name=name)
except (exceptions.NotFound, exceptions.NoUniqueMatch):
... | [
"Create the specified flavor."
] |
Please provide a description of the function:def glance_create_image(self, glance, image_name, image_url,
download_dir='tests',
hypervisor_type=None,
disk_format='qcow2',
architecture='x86_64',
... | [
"Download an image and upload it to glance, validate its status\n and return an image object pointer. KVM defaults, can override for\n LXD.\n\n :param glance: pointer to authenticated glance api connection\n :param image_name: display name for new image\n :param image_url: url to ... |
Please provide a description of the function:def create_cirros_image(self, glance, image_name, hypervisor_type=None):
# /!\ DEPRECATION WARNING
self.log.warn('/!\\ DEPRECATION WARNING: use '
'glance_create_image instead of '
'create_cirros_image.')
... | [
"Download the latest cirros image and upload it to glance,\n validate and return a resource pointer.\n\n :param glance: pointer to authenticated glance connection\n :param image_name: display name for new image\n :param hypervisor_type: glance image hypervisor property\n :returns:... |
Please provide a description of the function:def delete_image(self, glance, image):
# /!\ DEPRECATION WARNING
self.log.warn('/!\\ DEPRECATION WARNING: use '
'delete_resource instead of delete_image.')
self.log.debug('Deleting glance image ({})...'.format(image))
... | [
"Delete the specified image."
] |
Please provide a description of the function:def create_instance(self, nova, image_name, instance_name, flavor):
self.log.debug('Creating instance '
'({}|{}|{})'.format(instance_name, image_name, flavor))
image = nova.glance.find_image(image_name)
flavor = nova.fl... | [
"Create the specified instance."
] |
Please provide a description of the function:def delete_instance(self, nova, instance):
# /!\ DEPRECATION WARNING
self.log.warn('/!\\ DEPRECATION WARNING: use '
'delete_resource instead of delete_instance.')
self.log.debug('Deleting instance ({})...'.format(insta... | [
"Delete the specified instance."
] |
Please provide a description of the function:def create_or_get_keypair(self, nova, keypair_name="testkey"):
try:
_keypair = nova.keypairs.get(keypair_name)
self.log.debug('Keypair ({}) already exists, '
'using it.'.format(keypair_name))
ret... | [
"Create a new keypair, or return pointer if it already exists."
] |
Please provide a description of the function:def create_cinder_volume(self, cinder, vol_name="demo-vol", vol_size=1,
img_id=None, src_vol_id=None, snap_id=None):
# Handle parameter input and avoid impossible combinations
if img_id and not src_vol_id and not snap_id:... | [
"Create cinder volume, optionally from a glance image, OR\n optionally as a clone of an existing volume, OR optionally\n from a snapshot. Wait for the new volume status to reach\n the expected status, validate and return a resource pointer.\n\n :param vol_name: cinder volume display nam... |
Please provide a description of the function:def delete_resource(self, resource, resource_id,
msg="resource", max_wait=120):
self.log.debug('Deleting OpenStack resource '
'{} ({})'.format(resource_id, msg))
num_before = len(list(resource.list()))
... | [
"Delete one openstack resource, such as one instance, keypair,\n image, volume, stack, etc., and confirm deletion within max wait time.\n\n :param resource: pointer to os resource type, ex:glance_client.images\n :param resource_id: unique name or id for the openstack resource\n :param ms... |
Please provide a description of the function:def resource_reaches_status(self, resource, resource_id,
expected_stat='available',
msg='resource', max_wait=120):
tries = 0
resource_stat = resource.get(resource_id).status
whi... | [
"Wait for an openstack resources status to reach an\n expected status within a specified time. Useful to confirm that\n nova instances, cinder vols, snapshots, glance images, heat stacks\n and other resources eventually reach the expected status.\n\n :param resource: pointer to... |
Please provide a description of the function:def get_ceph_pools(self, sentry_unit):
pools = {}
cmd = 'sudo ceph osd lspools'
output, code = sentry_unit.run(cmd)
if code != 0:
msg = ('{} `{}` returned {} '
'{}'.format(sentry_unit.info['unit_name'],
... | [
"Return a dict of ceph pools from a single ceph unit, with\n pool name as keys, pool id as vals."
] |
Please provide a description of the function:def get_ceph_df(self, sentry_unit):
cmd = 'sudo ceph df --format=json'
output, code = sentry_unit.run(cmd)
if code != 0:
msg = ('{} `{}` returned {} '
'{}'.format(sentry_unit.info['unit_name'],
... | [
"Return dict of ceph df json output, including ceph pool state.\n\n :param sentry_unit: Pointer to amulet sentry instance (juju unit)\n :returns: Dict of ceph df output\n "
] |
Please provide a description of the function:def get_ceph_pool_sample(self, sentry_unit, pool_id=0):
df = self.get_ceph_df(sentry_unit)
for pool in df['pools']:
if pool['id'] == pool_id:
pool_name = pool['name']
obj_count = pool['stats']['objects']
... | [
"Take a sample of attributes of a ceph pool, returning ceph\n pool name, object count and disk space used for the specified\n pool ID number.\n\n :param sentry_unit: Pointer to amulet sentry instance (juju unit)\n :param pool_id: Ceph pool ID\n :returns: List of pool name, object ... |
Please provide a description of the function:def validate_ceph_pool_samples(self, samples, sample_type="resource pool"):
original, created, deleted = range(3)
if samples[created] <= samples[original] or \
samples[deleted] >= samples[created]:
return ('Ceph {} samples... | [
"Validate ceph pool samples taken over time, such as pool\n object counts or pool kb used, before adding, after adding, and\n after deleting items which affect those pool attributes. The\n 2nd element is expected to be greater than the 1st; 3rd is expected\n to be less than the 2nd.\n\n... |
Please provide a description of the function:def rmq_wait_for_cluster(self, deployment, init_sleep=15, timeout=1200):
if init_sleep:
time.sleep(init_sleep)
message = re.compile('^Unit is ready and clustered$')
deployment._auto_wait_for_status(message=message,
... | [
"Wait for rmq units extended status to show cluster readiness,\n after an optional initial sleep period. Initial sleep is likely\n necessary to be effective following a config change, as status\n message may not instantly update to non-ready."
] |
Please provide a description of the function:def get_rmq_cluster_status(self, sentry_unit):
cmd = 'rabbitmqctl cluster_status'
output, _ = self.run_cmd_unit(sentry_unit, cmd)
self.log.debug('{} cluster_status:\n{}'.format(
sentry_unit.info['unit_name'], output))
retu... | [
"Execute rabbitmq cluster status command on a unit and return\n the full output.\n\n :param unit: sentry unit\n :returns: String containing console output of cluster status command\n "
] |
Please provide a description of the function:def get_rmq_cluster_running_nodes(self, sentry_unit):
# NOTE(beisner): rabbitmqctl cluster_status output is not
# json-parsable, do string chop foo, then json.loads that.
str_stat = self.get_rmq_cluster_status(sentry_unit)
if 'running... | [
"Parse rabbitmqctl cluster_status output string, return list of\n running rabbitmq cluster nodes.\n\n :param unit: sentry unit\n :returns: List containing node names of running nodes\n "
] |
Please provide a description of the function:def validate_rmq_cluster_running_nodes(self, sentry_units):
host_names = self.get_unit_hostnames(sentry_units)
errors = []
# Query every unit for cluster_status running nodes
for query_unit in sentry_units:
query_unit_nam... | [
"Check that all rmq unit hostnames are represented in the\n cluster_status output of all units.\n\n :param host_names: dict of juju unit names to host names\n :param units: list of sentry unit pointers (all rmq units)\n :returns: None if successful, otherwise return error message\n ... |
Please provide a description of the function:def rmq_ssl_is_enabled_on_unit(self, sentry_unit, port=None):
host = sentry_unit.info['public-address']
unit_name = sentry_unit.info['unit_name']
conf_file = '/etc/rabbitmq/rabbitmq.config'
conf_contents = str(self.file_contents_safe... | [
"Check a single juju rmq unit for ssl and port in the config file."
] |
Please provide a description of the function:def validate_rmq_ssl_enabled_units(self, sentry_units, port=None):
for sentry_unit in sentry_units:
if not self.rmq_ssl_is_enabled_on_unit(sentry_unit, port=port):
return ('Unexpected condition: ssl is disabled on unit '
... | [
"Check that ssl is enabled on rmq juju sentry units.\n\n :param sentry_units: list of all rmq sentry units\n :param port: optional ssl port override to validate\n :returns: None if successful, otherwise return error message\n "
] |
Please provide a description of the function:def validate_rmq_ssl_disabled_units(self, sentry_units):
for sentry_unit in sentry_units:
if self.rmq_ssl_is_enabled_on_unit(sentry_unit):
return ('Unexpected condition: ssl is enabled on unit '
'({})'.for... | [
"Check that ssl is enabled on listed rmq juju sentry units.\n\n :param sentry_units: list of all rmq sentry units\n :returns: True if successful. Raise on error.\n "
] |
Please provide a description of the function:def configure_rmq_ssl_on(self, sentry_units, deployment,
port=None, max_wait=60):
self.log.debug('Setting ssl charm config option: on')
# Enable RMQ SSL
config = {'ssl': 'on'}
if port:
config... | [
"Turn ssl charm config option on, with optional non-default\n ssl port specification. Confirm that it is enabled on every\n unit.\n\n :param sentry_units: list of sentry units\n :param deployment: amulet deployment object pointer\n :param port: amqp port, use defaults if None\n ... |
Please provide a description of the function:def configure_rmq_ssl_off(self, sentry_units, deployment, max_wait=60):
self.log.debug('Setting ssl charm config option: off')
# Disable RMQ SSL
config = {'ssl': 'off'}
deployment.d.configure('rabbitmq-server', config)
# Wa... | [
"Turn ssl charm config option off, confirm that it is disabled\n on every unit.\n\n :param sentry_units: list of sentry units\n :param deployment: amulet deployment object pointer\n :param max_wait: maximum time to wait in seconds to confirm\n :returns: None if successful. Raise ... |
Please provide a description of the function:def connect_amqp_by_unit(self, sentry_unit, ssl=False,
port=None, fatal=True,
username="testuser1", password="changeme"):
host = sentry_unit.info['public-address']
unit_name = sentry_unit.info... | [
"Establish and return a pika amqp connection to the rabbitmq service\n running on a rmq juju unit.\n\n :param sentry_unit: sentry unit pointer\n :param ssl: boolean, default to False\n :param port: amqp port, use defaults if None\n :param fatal: boolean, default to True (raises on... |
Please provide a description of the function:def publish_amqp_message_by_unit(self, sentry_unit, message,
queue="test", ssl=False,
username="testuser1",
password="changeme",
... | [
"Publish an amqp message to a rmq juju unit.\n\n :param sentry_unit: sentry unit pointer\n :param message: amqp message string\n :param queue: message queue, default to test\n :param username: amqp user name, default to testuser1\n :param password: amqp user password\n :par... |
Please provide a description of the function:def get_amqp_message_by_unit(self, sentry_unit, queue="test",
username="testuser1",
password="changeme",
ssl=False, port=None):
connection = self.connect_amqp_... | [
"Get an amqp message from a rmq juju unit.\n\n :param sentry_unit: sentry unit pointer\n :param queue: message queue, default to test\n :param username: amqp user name, default to testuser1\n :param password: amqp user password\n :param ssl: boolean, default to False\n :par... |
Please provide a description of the function:def validate_memcache(self, sentry_unit, conf, os_release,
earliest_release=5, section='keystone_authtoken',
check_kvs=None):
if os_release < earliest_release:
self.log.debug('Skipping memcache ... | [
"Check Memcache is running and is configured to be used\n\n Example call from Amulet test:\n\n def test_110_memcache(self):\n u.validate_memcache(self.neutron_api_sentry,\n '/etc/neutron/neutron.conf',\n self._get... |
Please provide a description of the function:def acquire(self, lock):
'''Acquire the named lock, non-blocking.
The lock may be granted immediately, or in a future hook.
Returns True if the lock has been granted. The lock will be
automatically released at the end of the hook in which it... | [] |
Please provide a description of the function:def granted(self, lock):
'''Return True if a previously requested lock has been granted'''
unit = hookenv.local_unit()
ts = self.requests[unit].get(lock)
if ts and self.grants.get(unit, {}).get(lock) == ts:
return True
retu... | [] |
Please provide a description of the function:def request_timestamp(self, lock):
'''Return the timestamp of our outstanding request for lock, or None.
Returns a datetime.datetime() UTC timestamp, with no tzinfo attribute.
'''
ts = self.requests[hookenv.local_unit()].get(lock, None)
... | [] |
Please provide a description of the function:def grant(self, lock, unit):
'''Maybe grant the lock to a unit.
The decision to grant the lock or not is made for $lock
by a corresponding method grant_$lock, which you may define
in a subclass. If no such method is defined, the default_grant... | [] |
Please provide a description of the function:def released(self, unit, lock, timestamp):
'''Called on the leader when it has released a lock.
By default, does nothing but log messages. Override if you
need to perform additional housekeeping when a lock is released,
for example recording ... | [] |
Please provide a description of the function:def require(self, lock, guard_func, *guard_args, **guard_kw):
def decorator(f):
@wraps(f)
def wrapper(*args, **kw):
if self.granted(lock):
self.msg('Granted {}'.format(lock))
ret... | [
"Decorate a function to be run only when a lock is acquired.\n\n The lock is requested if the guard function returns True.\n\n The decorated function is called if the lock has been granted.\n "
] |
Please provide a description of the function:def msg(self, msg):
'''Emit a message. Override to customize log spam.'''
hookenv.log('coordinator.{} {}'.format(self._name(), msg),
level=hookenv.INFO) | [] |
Please provide a description of the function:def deprecate(warning, date=None, log=None):
def wrap(f):
@functools.wraps(f)
def wrapped_f(*args, **kwargs):
try:
module = inspect.getmodule(f)
file = inspect.getsourcefile(f)
lines = insp... | [
"Add a deprecation warning the first time the function is used.\n The date, which is a string in semi-ISO8660 format indicate the year-month\n that the function is officially going to be removed.\n\n usage:\n\n @deprecate('use core/fetch/add_source() instead', '2017-04')\n def contributed_add_source_... |
Please provide a description of the function:def splituser(host):
'''urllib.splituser(), but six's support of this seems broken'''
_userprog = re.compile('^(.*)@(.*)$')
match = _userprog.match(host)
if match:
return match.group(1, 2)
return None, host | [] |
Please provide a description of the function:def splitpasswd(user):
'''urllib.splitpasswd(), but six's support of this is missing'''
_passwdprog = re.compile('^([^:]*):(.*)$', re.S)
match = _passwdprog.match(user)
if match:
return match.group(1, 2)
return user, None | [] |
Please provide a description of the function:def download(self, source, dest):
# propagate all exceptions
# URLError, OSError, etc
proto, netloc, path, params, query, fragment = urlparse(source)
if proto in ('http', 'https'):
auth, barehost = splituser(netloc)
... | [
"\n Download an archive file.\n\n :param str source: URL pointing to an archive file.\n :param str dest: Local path location to download archive file to.\n "
] |
Please provide a description of the function:def install(self, source, dest=None, checksum=None, hash_type='sha1'):
url_parts = self.parse_url(source)
dest_dir = os.path.join(os.environ.get('CHARM_DIR'), 'fetched')
if not os.path.exists(dest_dir):
mkdir(dest_dir, perms=0o755... | [
"\n Download and install an archive file, with optional checksum validation.\n\n The checksum can also be given on the `source` URL's fragment.\n For example::\n\n handler.install('http://example.com/file.tgz#sha1=deadbeef')\n\n :param str source: URL pointing to an archive fi... |
Please provide a description of the function:def set_trace(addr=DEFAULT_ADDR, port=DEFAULT_PORT):
atexit.register(close_port, port)
try:
log("Starting a remote python debugger session on %s:%s" % (addr,
port))
open_port(por... | [
"\n Set a trace point using the remote debugger\n "
] |
Please provide a description of the function:def device_info(device):
status = subprocess.check_output([
'ibstat', device, '-s']).splitlines()
regexes = {
"CA type: (.*)": "device_type",
"Number of ports: (.*)": "num_ports",
"Firmware version: (.*)": "fw_ver",
"Har... | [
"Returns a DeviceInfo object with the current device settings"
] |
Please provide a description of the function:def ipoib_interfaces():
interfaces = []
for interface in network_interfaces():
try:
driver = re.search('^driver: (.+)$', subprocess.check_output([
'ethtool', '-i',
interface]), re.M).group(1)
if d... | [
"Return a list of IPOIB capable ethernet interfaces"
] |
Please provide a description of the function:def get_audits():
audits = [TemplatedFile('/etc/login.defs', LoginContext(),
template_dir=TEMPLATES_DIR,
user='root', group='root', mode=0o0444)]
return audits | [
"Get OS hardening login.defs audits.\n\n :returns: dictionary of audits\n "
] |
Please provide a description of the function:def _get_defaults(modules):
default = os.path.join(os.path.dirname(__file__),
'defaults/%s.yaml' % (modules))
return yaml.safe_load(open(default)) | [
"Load the default config for the provided modules.\n\n :param modules: stack modules config defaults to lookup.\n :returns: modules default config dictionary.\n "
] |
Please provide a description of the function:def _get_schema(modules):
schema = os.path.join(os.path.dirname(__file__),
'defaults/%s.yaml.schema' % (modules))
return yaml.safe_load(open(schema)) | [
"Load the config schema for the provided modules.\n\n NOTE: this schema is intended to have 1-1 relationship with they keys in\n the default config and is used a means to verify valid overrides provided\n by the user.\n\n :param modules: stack modules config schema to lookup.\n :returns: modules defa... |
Please provide a description of the function:def _get_user_provided_overrides(modules):
overrides = os.path.join(os.environ['JUJU_CHARM_DIR'],
'hardening.yaml')
if os.path.exists(overrides):
log("Found user-provided config overrides file '%s'" %
(overrides),... | [
"Load user-provided config overrides.\n\n :param modules: stack modules to lookup in user overrides yaml file.\n :returns: overrides dictionary.\n "
] |
Please provide a description of the function:def _apply_overrides(settings, overrides, schema):
if overrides:
for k, v in six.iteritems(overrides):
if k in schema:
if schema[k] is None:
settings[k] = v
elif type(schema[k]) is dict:
... | [
"Get overrides config overlayed onto modules defaults.\n\n :param modules: require stack modules config.\n :returns: dictionary of modules config with user overrides applied.\n "
] |
Please provide a description of the function:def ensure_permissions(path, user, group, permissions, maxdepth=-1):
if not os.path.exists(path):
log("File '%s' does not exist - cannot set permissions" % (path),
level=WARNING)
return
_user = pwd.getpwnam(user)
os.chown(path, _... | [
"Ensure permissions for path.\n\n If path is a file, apply to file and return. If path is a directory,\n apply recursively (if required) to directory contents and return.\n\n :param user: user name\n :param group: group name\n :param permissions: octal permissions\n :param maxdepth: maximum recurs... |
Please provide a description of the function:def create(sysctl_dict, sysctl_file, ignore=False):
if type(sysctl_dict) is not dict:
try:
sysctl_dict_parsed = yaml.safe_load(sysctl_dict)
except yaml.YAMLError:
log("Error parsing YAML sysctl_dict: {}".format(sysctl_dict),
... | [
"Creates a sysctl.conf file from a YAML associative array\n\n :param sysctl_dict: a dict or YAML-formatted string of sysctl\n options eg \"{ 'kernel.max_pid': 1337 }\"\n :type sysctl_dict: str\n :param sysctl_file: path to the sysctl file to be saved\n :type sysctl_file: str or un... |
Please provide a description of the function:def canonical_url(configs, endpoint_type=PUBLIC):
scheme = _get_scheme(configs)
address = resolve_address(endpoint_type)
if is_ipv6(address):
address = "[{}]".format(address)
return '%s://%s' % (scheme, address) | [
"Returns the correct HTTP URL to this host given the state of HTTPS\n configuration, hacluster and charm configuration.\n\n :param configs: OSTemplateRenderer config templating object to inspect\n for a complete https context.\n :param endpoint_type: str endpoint type to resolve.\n :p... |
Please provide a description of the function:def _get_address_override(endpoint_type=PUBLIC):
override_key = ADDRESS_MAP[endpoint_type]['override']
addr_override = config(override_key)
if not addr_override:
return None
else:
return addr_override.format(service_name=service_name()) | [
"Returns any address overrides that the user has defined based on the\n endpoint type.\n\n Note: this function allows for the service name to be inserted into the\n address if the user specifies {service_name}.somehost.org.\n\n :param endpoint_type: the type of endpoint to retrieve the override\n ... |
Please provide a description of the function:def resolve_address(endpoint_type=PUBLIC, override=True):
resolved_address = None
if override:
resolved_address = _get_address_override(endpoint_type)
if resolved_address:
return resolved_address
vips = config('vip')
if vips:... | [
"Return unit address depending on net config.\n\n If unit is clustered with vip(s) and has net splits defined, return vip on\n correct network. If clustered with no nets defined, return primary vip.\n\n If not clustered, return unit address ensuring address is on configured net\n split if one is configu... |
Please provide a description of the function:def hugepage_support(user, group='hugetlb', nr_hugepages=256,
max_map_count=65536, mnt_point='/run/hugepages/kvm',
pagesize='2MB', mount=True, set_shmmax=False):
group_info = add_group(group)
gid = group_info.gr_gid
... | [
"Enable hugepages on system.\n\n Args:\n user (str) -- Username to allow access to hugepages to\n group (str) -- Group name to own hugepages\n nr_hugepages (int) -- Number of pages to reserve\n max_map_count (int) -- Number of Virtual Memory Areas a process can own\n mnt_point (str) -- Directory ... |
Please provide a description of the function:def ensure_compliance(self):
if not self.modules:
return
try:
loaded_modules = self._get_loaded_modules()
non_compliant_modules = []
for module in self.modules:
if module in loaded_modu... | [
"Ensures that the modules are not loaded."
] |
Please provide a description of the function:def _get_loaded_modules():
output = subprocess.check_output(['apache2ctl', '-M'])
if six.PY3:
output = output.decode('utf-8')
modules = []
for line in output.splitlines():
# Each line of the enabled module outp... | [
"Returns the modules which are enabled in Apache."
] |
Please provide a description of the function:def _disable_module(module):
try:
subprocess.check_call(['a2dismod', module])
except subprocess.CalledProcessError as e:
# Note: catch error here to allow the attempt of disabling
# multiple modules in one go rathe... | [
"Disables the specified module in Apache."
] |
Please provide a description of the function:def get_template_path(template_dir, path):
return os.path.join(template_dir, os.path.basename(path)) | [
"Returns the template file which would be used to render the path.\n\n The path to the template file is returned.\n :param template_dir: the directory the templates are located in\n :param path: the file path to be written to.\n :returns: path to the template file\n "
] |
Please provide a description of the function:def render_and_write(template_dir, path, context):
env = Environment(loader=FileSystemLoader(template_dir))
template_file = os.path.basename(path)
template = env.get_template(template_file)
log('Rendering from template: %s' % template.name, level=DEBUG)
... | [
"Renders the specified template into the file.\n\n :param template_dir: the directory to load the template from\n :param path: the path to write the templated contents to\n :param context: the parameters to pass to the rendering engine\n "
] |
Please provide a description of the function:def get_audits():
audits = [AptConfig([{'key': 'APT::Get::AllowUnauthenticated',
'expected': 'false'}])]
settings = get_settings('os')
clean_packages = settings['security']['packages_clean']
if clean_packages:
security_... | [
"Get OS hardening apt audits.\n\n :returns: dictionary of audits\n "
] |
Please provide a description of the function:def get_audits():
audits = []
settings = utils.get_settings('os')
if settings['auth']['pam_passwdqc_enable']:
audits.append(PasswdqcPAM('/etc/passwdqc.conf'))
if settings['auth']['retries']:
audits.append(Tally2PAM('/usr/share/pam-conf... | [
"Get OS hardening PAM authentication audits.\n\n :returns: dictionary of audits\n "
] |
Please provide a description of the function:def install_ansible_support(from_ppa=True, ppa_location='ppa:rquillo/ansible'):
if from_ppa:
charmhelpers.fetch.add_source(ppa_location)
charmhelpers.fetch.apt_update(fatal=True)
charmhelpers.fetch.apt_install('ansible')
with open(ansible_hos... | [
"Installs the ansible package.\n\n By default it is installed from the `PPA`_ linked from\n the ansible `website`_ or from a ppa specified by a charm config..\n\n .. _PPA: https://launchpad.net/~rquillo/+archive/ansible\n .. _website: http://docs.ansible.com/intro_installation.html#latest-releases-via-a... |
Please provide a description of the function:def execute(self, args):
hook_name = os.path.basename(args[0])
extra_vars = None
if hook_name in self._actions:
extra_vars = self._actions[hook_name](args[1:])
else:
super(AnsibleHooks, self).execute(args)
... | [
"Execute the hook followed by the playbook using the hook as tag."
] |
Please provide a description of the function:def action(self, *action_names):
def action_wrapper(decorated):
@functools.wraps(decorated)
def wrapper(argv):
kwargs = dict(arg.split('=') for arg in argv)
try:
return decorated(**... | [
"Decorator, registering them as actions"
] |
Please provide a description of the function:def get_logger(self, name="deployment-logger", level=logging.DEBUG):
log = logging
logger = log.getLogger(name)
fmt = log.Formatter("%(asctime)s %(funcName)s "
"%(levelname)s: %(message)s")
handler = log.S... | [
"Get a logger object that will log to stdout."
] |
Please provide a description of the function:def _determine_branch_locations(self, other_services):
self.log.info('OpenStackAmuletDeployment: determine branch locations')
# Charms outside the ~openstack-charmers
base_charms = {
'mysql': ['trusty'],
'mongodb': ... | [
"Determine the branch locations for the other services.\n\n Determine if the local branch being tested is derived from its\n stable or next (dev) branch, and based on this, use the corresonding\n stable or next branches for the other_services."
] |
Please provide a description of the function:def _add_services(self, this_service, other_services, use_source=None,
no_origin=None):
self.log.info('OpenStackAmuletDeployment: adding services')
other_services = self._determine_branch_locations(other_services)
sup... | [
"Add services to the deployment and optionally set\n openstack-origin/source.\n\n :param this_service dict: Service dictionary describing the service\n whose amulet tests are being run\n :param other_services dict: List of service dictionaries describing\n ... |
Please provide a description of the function:def _auto_wait_for_status(self, message=None, exclude_services=None,
include_only=None, timeout=None):
if not timeout:
timeout = int(os.environ.get('AMULET_SETUP_TIMEOUT', 1800))
self.log.info('Waiting for ex... | [
"Wait for all units to have a specific extended status, except\n for any defined as excluded. Unless specified via message, any\n status containing any case of 'ready' will be considered a match.\n\n Examples of message usage:\n\n Wait for all unit status to CONTAIN any case of 'ready... |
Please provide a description of the function:def _get_openstack_release(self):
# Must be ordered by OpenStack release (not by Ubuntu release):
for i, os_pair in enumerate(OPENSTACK_RELEASES_PAIRS):
setattr(self, os_pair, i)
releases = {
('trusty', None): self.tr... | [
"Get openstack release.\n\n Return an integer representing the enum value of the openstack\n release.\n "
] |
Please provide a description of the function:def _get_openstack_release_string(self):
releases = OrderedDict([
('trusty', 'icehouse'),
('xenial', 'mitaka'),
('yakkety', 'newton'),
('zesty', 'ocata'),
('artful', 'pike'),
('bionic', ... | [
"Get openstack release string.\n\n Return a string representing the openstack release.\n "
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.