def install_custom_ca():
    """
    Installs a configured CA cert into the system-wide location.
    """
    ca_cert = hookenv.config().get('custom-registry-ca')
    if ca_cert:
        try:
            # decode to bytes, as that's what install_ca_cert wants
            _ca = b64decode(ca_cert)
        except Exception:
            status.blocked(
                'Invalid base64 value for custom-registry-ca config')
            return
        else:
            host.install_ca_cert(_ca, name='juju-custom-registry')
            charm = hookenv.charm_name()
            hookenv.log(
                'Custom registry CA has been installed for {}'.format(charm))

            # manage appropriate charm flags to recycle the runtime daemon
            if charm == 'docker':
                clear_flag('docker.available')
                set_flag('docker.restart')
            elif charm == 'containerd':
                set_flag('containerd.restart')
            else:
                hookenv.log('Unknown runtime: {}. '
                            'Cannot request a service restart.'.format(charm))
Esempio n. 2
0
def configure_registry():
    """
    Add docker registry config when present.

    :return: None
    """
    registry = endpoint_from_flag('endpoint.docker-registry.ready')

    docker_registry = {
        'host': strip_url(registry.registry_netloc),
        'url': registry.registry_netloc,
    }

    # Handle auth data.
    if registry.has_auth_basic():
        docker_registry['username'] = registry.basic_user
        docker_registry['password'] = registry.basic_password

    # Handle TLS data.
    if registry.has_tls():
        # Ensure the CA that signed our registry cert is trusted.
        host.install_ca_cert(registry.tls_ca, name='juju-docker-registry')

        docker_registry['ca'] = str(ca_crt_path)
        docker_registry['key'] = str(server_key_path)
        docker_registry['cert'] = str(server_crt_path)

    DB.set('registry', docker_registry)

    config_changed()
    set_state('containerd.registry.configured')
def config_changed():
    hookenv.log('begin config-changed hook.')
    configs = get_configs()
    configs.write_all()
    ensure_perms()

    update_nrpe_config()

    config = hookenv.config()

    if config.changed('frequency'):
        hookenv.log("'frequency' changed, removing cron job")
        uninstall_cron_script()

    if config['run']:
        hookenv.log("installing to cronjob to "
                    "/etc/cron.{}".format(config['frequency']))
        hookenv.log("installing {} for polling".format(CRON_POLL_FILEPATH))
        install_cron_poll()
        install_cron_script()
    else:
        hookenv.log("'run' set to False, removing cron jobs")
        uninstall_cron_script()
        uninstall_cron_poll()

    if config.get('ssl_ca'):
        install_ca_cert(base64.b64decode(config.get('ssl_ca')), )

    config.save()
Esempio n. 4
0
def configure_registry():
    """
    Add docker registry config when present.

    :return: None
    """
    registry = endpoint_from_flag("endpoint.docker-registry.ready")
    netloc = registry.registry_netloc

    # handle tls data
    cert_subdir = netloc
    cert_dir = os.path.join(CERTIFICATE_DIRECTORY, cert_subdir)
    insecure_opt = {"insecure-registry": netloc}
    if registry.has_tls():
        # ensure the CA that signed our registry cert is trusted
        install_ca_cert(registry.tls_ca, name="juju-docker-registry")
        # remove potential insecure docker opts related to this registry
        manage_docker_opts(insecure_opt, remove=True)
        manage_registry_certs(cert_dir, remove=False)
    else:
        manage_docker_opts(insecure_opt, remove=False)
        manage_registry_certs(cert_dir, remove=True)

    # handle auth data
    if registry.has_auth_basic():
        hookenv.log("Logging into docker registry: {}.".format(netloc))
        cmd = [
            "docker",
            "login",
            netloc,
            "-u",
            registry.basic_user,
            "-p",
            registry.basic_password,
        ]
        try:
            check_output(cmd, stderr=subprocess.STDOUT)
        except CalledProcessError as e:
            if b"http response" in e.output.lower():
                # non-tls login with basic auth will error like this:
                #  Error response ... server gave HTTP response to HTTPS client
                msg = "docker login requires a TLS-enabled registry"
            elif b"unauthorized" in e.output.lower():
                # invalid creds will error like this:
                #  Error response ... 401 Unauthorized
                msg = "Incorrect credentials for docker registry"
            else:
                msg = "docker login failed, see juju debug-log"
            status.blocked(msg)
    else:
        hookenv.log("Disabling auth for docker registry: {}.".format(netloc))
        # NB: it's safe to logout of a registry that was never logged in
        check_call(["docker", "logout", netloc])

    # NB: store our netloc so we can clean up if the registry goes away
    DB.set("registry_netloc", netloc)
    set_state("docker.registry.configured")
def configure_registry():
    '''Add docker registry config when present.'''
    registry = endpoint_from_flag('endpoint.docker-registry.ready')
    netloc = registry.registry_netloc

    # handle tls data
    cert_subdir = netloc
    insecure_opt = {'insecure-registry': netloc}
    if registry.has_tls():
        # ensure the CA that signed our registry cert is trusted
        install_ca_cert(registry.tls_ca, name='juju-docker-registry')
        # remove potential insecure docker opts related to this registry
        manage_docker_opts(insecure_opt, remove=True)
        manage_registry_certs(cert_subdir, remove=False)
    else:
        manage_docker_opts(insecure_opt, remove=False)
        manage_registry_certs(cert_subdir, remove=True)

    # handle auth data
    if registry.has_auth_basic():
        hookenv.log('Logging into docker registry: {}.'.format(netloc))
        cmd = ['docker', 'login', netloc,
               '-u', registry.basic_user, '-p', registry.basic_password]
        try:
            check_output(cmd, stderr=subprocess.STDOUT)
        except CalledProcessError as e:
            if b'http response' in e.output.lower():
                # non-tls login with basic auth will error like this:
                #  Error response ... server gave HTTP response to HTTPS client
                msg = 'docker login requires a TLS-enabled registry'
            elif b'unauthorized' in e.output.lower():
                # invalid creds will error like this:
                #  Error response ... 401 Unauthorized
                msg = 'Incorrect credentials for docker registry'
            else:
                msg = 'docker login failed, see juju debug-log'
            hookenv.status_set('blocked', msg)
    else:
        hookenv.log('Disabling auth for docker registry: {}.'.format(netloc))
        # NB: it's safe to logout of a registry that was never logged in
        check_call(['docker', 'logout', netloc])

    # NB: store our netloc so we can clean up if the registry goes away
    db.set('registry_netloc', netloc)
    set_state('kubernetes-master-worker-base.registry.configured')
Esempio n. 6
0
def _configure_local_client():
    '''Configure daemon.json and certs for the local docker client.'''
    charm_config = hookenv.config()

    # client config depends on whether the registry is secure or insecure
    netloc = get_netloc()
    if is_flag_set('charm.docker-registry.tls-enabled'):
        insecure_registry = ''

        # if our ca changed, install it into the default sys location
        # (docker client > 1.13 will use this)
        tls_ca = charm_config.get('tls-ca-path', '')
        if os.path.isfile(tls_ca) and any_file_changed([tls_ca]):
            ca_content = None
            with open(tls_ca, 'rb') as f:
                ca_content = f.read()
            if ca_content:
                host.install_ca_cert(ca_content)

        # Put our certs where the docker client expects to find them
        # NB: these are the same certs used to serve the registry, but have
        # strict path requirements when used for docker client auth.
        client_tls_dst = '/etc/docker/certs.d/{}'.format(netloc)
        os.makedirs(client_tls_dst, exist_ok=True)
        tls_cert = charm_config.get('tls-cert-path', '')
        if os.path.isfile(tls_cert) and any_file_changed([tls_cert]):
            tls_cert_link = '{}/client.cert'.format(client_tls_dst)
            _remove_if_exists(tls_cert_link)
            os.symlink(tls_cert, tls_cert_link)
        tls_key = charm_config.get('tls-key-path', '')
        if os.path.isfile(tls_key) and any_file_changed([tls_key]):
            tls_key_link = '{}/client.key'.format(client_tls_dst)
            _remove_if_exists(tls_key_link)
            os.symlink(tls_key, tls_key_link)
    else:
        insecure_registry = '"{}"'.format(netloc)

    templating.render('daemon.json', '/etc/docker/daemon.json',
                      {'registries': insecure_registry})
    host.service_restart('docker')
Esempio n. 7
0
def _manage_ca_certs(ca, cert_relation_id):
    """Manage CA certs.

    :param ca: CA Certificate from certificate relation.
    :type ca: str
    :param cert_relation_id: Relation id providing the certs
    :type cert_relation_id: str
    """
    config_ssl_ca = config('ssl_ca')
    config_cert_file = ca_cert_absolute_path(CONFIG_CA_CERT_FILE)
    if config_ssl_ca:
        log(
            "Installing CA certificate from charm ssl_ca config to {}".format(
                config_cert_file), INFO)
        install_ca_cert(b64decode(config_ssl_ca).rstrip(),
                        name=CONFIG_CA_CERT_FILE)
    elif os.path.exists(config_cert_file):
        log("Removing CA certificate {}".format(config_cert_file), INFO)
        os.remove(config_cert_file)
    log("Installing CA certificate from certificate relation", INFO)
    install_ca_cert(ca.encode(),
                    name=get_cert_relation_ca_name(cert_relation_id))
Esempio n. 8
0
 def configure_ca(self):
     ca_cert = config('ssl-ca')
     if ca_cert:
         install_ca_cert(b64decode(ca_cert))
Esempio n. 9
0
def install_ca_cert(ca_cert):
    host.install_ca_cert(ca_cert, CONFIG_CA_CERT_FILE)
def setup_ssl():
    ca = config('ssl_ca')
    install_ca_cert(b64decode(ca))
Esempio n. 11
0
def install_ca_cert(ca_cert):
    host.install_ca_cert(ca_cert, 'keystone_juju_ca_cert')
def install_root_ca_cert():
    cert_provider = endpoint_from_flag('certificates.ca.available')
    host.install_ca_cert(cert_provider.root_ca_cert)
    set_state('cert_provider.ca.changed')
Esempio n. 13
0
def install_ca_cert(ca_cert):
    host.install_ca_cert(ca_cert, 'keystone_juju_ca_cert')
Esempio n. 14
0
 def install_root_ca_cert():
     cert_provider = endpoint_from_flag('cert-provider.ca.available')
     host.install_ca_cert(cert_provider.root_ca_cert)
     clear_flag('cert-provider.ca.changed')