How to use the charmhelpers.core.hookenv.log function in charmhelpers

To help you get started, we’ve selected a few charmhelpers examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github juju / charm-tools / tests / layers / mysql / hooks / nrpe_relations.py View on Github external
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')
github openstack / charm-percona-cluster / charmhelpers / fetch / __init__.py View on Github external
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
github openstack / charm-nova-cloud-controller / charmhelpers / contrib / openstack / ha / utils.py View on Github external
    @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)
github openstack / charm-nova-compute / hooks / charmhelpers / contrib / openstack / utils.py View on Github external
def is_db_initialised():
    """Check leader storage to see if database has been initialised.

    :returns: Whether DB has been initialised
    :rtype: bool
    """
    db_initialised = None
    if leader_get('db-initialised') is None:
        juju_log(
            'db-initialised key missing, assuming db is not initialised',
            'DEBUG')
        db_initialised = False
    else:
        db_initialised = bool_from_string(leader_get('db-initialised'))
    juju_log('Database initialised: {}'.format(db_initialised), 'DEBUG')
    return db_initialised
github openstack / charm-ceph-proxy / hooks / ceph_hooks.py View on Github external
'auth': config('auth-supported'),
            'ceph-public-address': ceph_addrs,
        }

        settings = relation_get(rid=relid, unit=unit) or {}
        """Process broker request(s)."""
        if 'broker_req' in settings:
            rsp = process_requests(settings['broker_req'])
            unit_id = unit.replace('/', '-')
            unit_response_key = 'broker-rsp-' + unit_id
            data[unit_response_key] = rsp

        log('relation_set (%s): %s' % (relid, str(data)), level=DEBUG)
        relation_set(relation_id=relid, relation_settings=data)
    else:
        log('FSID or admin key not provided, please configure them')
github k8snetworkplumbingwg / sriov-network-device-plugin / vendor / k8s.io / kubernetes / cluster / juju / layers / kubernetes-worker / reactive / kubernetes_worker.py View on Github external
def render_and_launch_ingress():
    ''' If configuration has ingress daemon set enabled, launch the ingress
    load balancer and default http backend. Otherwise attempt deletion. '''
    config = hookenv.config()
    # If ingress is enabled, launch the ingress controller
    if config.get('ingress'):
        launch_default_ingress_controller()
    else:
        hookenv.log('Deleting the http backend and ingress.')
        kubectl_manifest('delete',
                         '/root/cdk/addons/default-http-backend.yaml')
        kubectl_manifest('delete',
                         '/root/cdk/addons/ingress-daemon-set.yaml')  # noqa
        hookenv.close_port(80)
        hookenv.close_port(443)
github openstack / charm-nova-compute / hooks / nova_compute_utils.py View on Github external
def create_libvirt_secret(secret_file, secret_uuid, key):
    uri = LIBVIRT_URIS[config('virt-type')]
    cmd = ['virsh', '-c', uri, 'secret-list']
    if secret_uuid in check_output(cmd).decode('UTF-8'):
        old_key = check_output(['virsh', '-c', uri, 'secret-get-value',
                                secret_uuid]).decode('UTF-8')
        old_key = old_key.strip()
        if old_key == key:
            log('Libvirt secret already exists for uuid %s.' % secret_uuid,
                level=DEBUG)
            return
        else:
            log('Libvirt secret changed for uuid %s.' % secret_uuid,
                level=INFO)
    log('Defining new libvirt secret for uuid %s.' % secret_uuid)
    cmd = ['virsh', '-c', uri, 'secret-define', '--file', secret_file]
    check_call(cmd)
    cmd = ['virsh', '-c', uri, 'secret-set-value', '--secret', secret_uuid,
           '--base64', key]
    check_call(cmd)
github k3s-io / k3s / cluster / juju / layers / kubernetes-master / reactive / kubernetes_master.py View on Github external
'DefaultStorageClass',
        'DefaultTolerationSeconds',
        'MutatingAdmissionWebhook',
        'ValidatingAdmissionWebhook',
        'ResourceQuota'
    ]

    auth_mode = hookenv.config('authorization-mode')
    if 'Node' in auth_mode:
        admission_control.append('NodeRestriction')

    api_opts['authorization-mode'] = auth_mode

    kube_version = get_version('kube-apiserver')
    if kube_version < (1, 6):
        hookenv.log('Removing DefaultTolerationSeconds from admission-control')
        admission_control_pre_1_9.remove('DefaultTolerationSeconds')
    if kube_version < (1, 7):
        hookenv.log('Removing Initializers from admission-control')
        admission_control_pre_1_9.remove('Initializers')
    if kube_version < (1, 9):
        api_opts['admission-control'] = ','.join(admission_control_pre_1_9)
    else:
        api_opts['admission-control'] = ','.join(admission_control)

    if kube_version > (1, 6) and \
       hookenv.config('enable-metrics'):
        api_opts['requestheader-client-ca-file'] = ca_cert_path
        api_opts['requestheader-allowed-names'] = 'client'
        api_opts['requestheader-extra-headers-prefix'] = 'X-Remote-Extra-'
        api_opts['requestheader-group-headers'] = 'X-Remote-Group'
        api_opts['requestheader-username-headers'] = 'X-Remote-User'
github openstack / charm-swift-proxy / charmhelpers / contrib / openstack / utils.py View on Github external
def is_db_initialised():
    """Check leader storage to see if database has been initialised.

    :returns: Whether DB has been initialised
    :rtype: bool
    """
    db_initialised = None
    if leader_get('db-initialised') is None:
        juju_log(
            'db-initialised key missing, assuming db is not initialised',
            'DEBUG')
        db_initialised = False
    else:
        db_initialised = bool_from_string(leader_get('db-initialised'))
    juju_log('Database initialised: {}'.format(db_initialised), 'DEBUG')
    return db_initialised
github openstack / charm-swift-proxy / charmhelpers / contrib / openstack / utils.py View on Github external
def is_db_maintenance_mode(relid=None):
    """Check relation data from notifications of db in maintenance mode.

    :returns: Whether db has notified it is in maintenance mode.
    :rtype: bool
    """
    juju_log('Checking for maintenance notifications', 'DEBUG')
    if relid:
        r_ids = [relid]
    else:
        r_ids = relation_ids('shared-db')
    rids_units = [(r, u) for r in r_ids for u in related_units(r)]
    notifications = []
    for r_id, unit in rids_units:
        settings = relation_get(unit=unit, rid=r_id)
        for key, value in settings.items():
            if value and key in DB_MAINTENANCE_KEYS:
                juju_log(
                    'Unit: {}, Key: {}, Value: {}'.format(unit, key, value),
                    'DEBUG')
                try:
                    notifications.append(bool_from_string(value))
                except ValueError: