Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def add_nagios_user():
c = get_db_cursor()
if c.execute("SELECT User from mysql.user where User='nagios'"):
log('User nagios already exists, skipping')
else:
log('Creating "nagios" database user')
password = nagios_password()
c.execute("CREATE USER 'nagios'@'localhost' IDENTIFIED BY '{}'"
"".format(password))
try:
c.execute("SHOW GRANTS FOR 'nagios'@'localhost'")
grants = [i[0] for i in c.fetchall()]
except MySQLdb.OperationalError:
grants = []
for grant in grants:
if "GRANT PROCESS ON *.*" in grant:
log('User already has permissions, skipping')
c.close()
return
log('Granting "PROCESS" privilege to nagios user')
like::
{% for unit in interface -%}
{{ unit['key'] }}{% if not loop.last %},{% endif %}
{%- endfor %}
Note that since all sets of relation data from all related services and
units are in a single list, if you need to know which service or unit a
set of data came from, you'll need to extend this class to preserve
that information.
"""
if not hookenv.relation_ids(self.name):
return
ns = self.setdefault(self.name, [])
for rid in sorted(hookenv.relation_ids(self.name)):
for unit in sorted(hookenv.related_units(rid)):
reldata = hookenv.relation_get(rid=rid, unit=unit)
if self._is_ready(reldata):
ns.append(reldata)
def statistics_interface():
config = config_get()
enable_monitoring = config['enable_monitoring']
monitoring_port = config['monitoring_port']
monitoring_password = get_monitoring_password()
monitoring_username = config['monitoring_username']
for relid in get_relation_ids('statistics'):
if not enable_monitoring:
relation_set(relation_id=relid,
enabled=enable_monitoring)
else:
relation_set(relation_id=relid,
enabled=enable_monitoring,
port=monitoring_port,
password=monitoring_password,
user=monitoring_username)
def install_hook():
# Run both during initial install and during upgrade-charm.
if not os.path.exists(default_haproxy_service_config_dir):
os.mkdir(default_haproxy_service_config_dir, 0o600)
config_data = config_get()
source = config_data.get('source')
if source == 'backports':
release = lsb_release()['DISTRIB_CODENAME']
source = apt_backports_template % {'release': release}
add_backports_preferences(release)
add_source(source, config_data.get('key'))
apt_update(fatal=True)
apt_install(['haproxy', 'python-jinja2'], fatal=True)
# Install pyasn1 library and modules for inspecting SSL certificates
apt_install(['python-pyasn1', 'python-pyasn1-modules'], fatal=False)
ensure_package_status(service_affecting_packages,
config_data['package_status'])
enable_haproxy()
def data_relation_gone():
hookenv.log('Data relation no longer present, stopping MysQL.')
host.service_stop('mysql')
def plugins(fetch_handlers=None):
if not fetch_handlers:
fetch_handlers = FETCH_HANDLERS
plugin_list = []
for handler_name in fetch_handlers:
package, classname = handler_name.rsplit('.', 1)
try:
handler_class = getattr(
importlib.import_module(package),
classname)
plugin_list.append(handler_class())
except (ImportError, AttributeError):
# Skip missing plugins so that they can be ommitted from
# installation if desired
log("FetchHandler {} not found, skipping plugin".format(
handler_name))
return plugin_list
def resolve_address(endpoint_type=PUBLIC):
resolved_address = None
if is_clustered():
if config(_address_map[endpoint_type]['config']) is None:
# Assume vip is simple and pass back directly
resolved_address = config('vip')
else:
for vip in config('vip').split():
if is_address_in_network(
config(_address_map[endpoint_type]['config']),
vip):
resolved_address = vip
else:
if config('prefer-ipv6'):
fallback_addr = get_ipv6_addr(exc_list=[config('vip')])[0]
else:
fallback_addr = unit_get(_address_map[endpoint_type]['fallback'])
resolved_address = get_address_in_network(
config(_address_map[endpoint_type]['config']), fallback_addr)
if resolved_address is None:
raise ValueError('Unable to resolve a suitable IP address'
' based on charm state and configuration')
else:
return resolved_address
def upgrade_monitor(new_version):
current_version = get_version()
status_set("maintenance", "Upgrading monitor")
log("Current ceph version is {}".format(current_version))
log("Upgrading to: {}".format(new_version))
try:
add_source(config('source'), config('key'))
apt_update(fatal=True)
except subprocess.CalledProcessError as err:
log("Adding the ceph source failed with message: {}".format(
err.message))
status_set("blocked", "Upgrade to {} failed".format(new_version))
sys.exit(1)
try:
if systemd():
for mon_id in get_local_mon_ids():
service_stop('ceph-mon@{}'.format(mon_id))
else:
def peer_retrieve(key, relation_name='cluster'):
"""Retrieve a named key from peer relation `relation_name`."""
cluster_rels = relation_ids(relation_name)
if len(cluster_rels) > 0:
cluster_rid = cluster_rels[0]
return relation_get(attribute=key, rid=cluster_rid,
unit=local_unit())
else:
raise ValueError('Unable to detect'
'peer relation {}'.format(relation_name))
dev_name = None
path_parts = os.path.split(block_dev)
if len(path_parts) == 2:
dev_name = path_parts[1]
else:
log('Unable to determine the block device name from path: {}'.format(
block_dev))
# Play it safe and bail
return
max_sectors_kb = get_max_sectors_kb(dev_name=dev_name)
max_hw_sectors_kb = get_max_hw_sectors_kb(dev_name=dev_name)
if max_sectors_kb < max_hw_sectors_kb:
# OK we have a situation where the hardware supports more than Linux is
# currently requesting
config_max_sectors_kb = hookenv.config('max-sectors-kb')
if config_max_sectors_kb < max_hw_sectors_kb:
# Set the max_sectors_kb to the config.yaml value if it is less
# than the max_hw_sectors_kb
log('Setting max_sectors_kb for device {} to {}'.format(
dev_name, config_max_sectors_kb))
save_settings_dict[
"drive_settings"][uuid][
"read_ahead_sect"] = config_max_sectors_kb
set_max_sectors_kb(dev_name=dev_name,
max_sectors_size=config_max_sectors_kb)
else:
# Set to the max_hw_sectors_kb
log('Setting max_sectors_kb for device {} to {}'.format(
dev_name, max_hw_sectors_kb))
save_settings_dict[
"drive_settings"][uuid]['read_ahead_sect'] = max_hw_sectors_kb