Beispiel #1
0
def config_php_settings():
    '''
    Detects changes in configuration and renders the phpmodule for
    nextcloud (nextcloud.ini)
    This is instead of manipulating the system wide php.ini
    which might be overwitten or changed from elsewhere.
    '''
    phpmod_context = {
        'max_file_uploads': config('php_max_file_uploads'),
        'upload_max_filesize': config('php_upload_max_filesize'),
        'post_max_size': config('php_post_max_size'),
        'memory_limit': config('php_memory_limit')
    }

    templating.render(source="nextcloud.ini",
                      target='/etc/php/7.2/mods-available/nextcloud.ini',
                      context=phpmod_context)

    subprocess.check_call(['phpenmod', 'nextcloud'])

    if is_state("apache.started"):

        log("reloading apache2 after reconfiguration")

        host.service_reload('apache2')

    flags=['config.changed.php_max_file_uploads',
           'config.changed.php_upload_max_filesize',
           'config.changed.php_memory_limit',
           'config.changed.php_post_max_size']

    for f in flags:
        clear_flag(f)
def configure_site(site, template, **kwargs):
    """ configures vhost

    Arguments:
    site: Site name
    template: template to process in templates/<template.conf>
    **kwargs: additional dict items to append to template variables exposed
              through the site.toml
    """
    hookenv.status_set('maintenance', 'Configuring site {}'.format(site))

    config = hookenv.config()
    context = load_site()
    context['host'] = config['host']
    context['port'] = config['port']
    context.update(**kwargs)
    conf_path = '/etc/nginx/sites-available/{}'.format(site)
    if os.path.exists(conf_path):
        os.remove(conf_path)
    render(source=template,
           target=conf_path,
           context=context)

    symlink_path = '/etc/nginx/sites-enabled/{}'.format(site)
    if os.path.exists(symlink_path):
        os.unlink(symlink_path)
    os.symlink(conf_path, symlink_path)
    hookenv.log('Wrote vhost config {} to {}'.format(context, template),
                'info')

    if not remove_default_site():
        host.service_reload('nginx', restart_on_failure=True)
    hookenv.status_set('active', '')
Beispiel #3
0
def configure_site(site, template, **kwargs):
    """ configures vhost

    Arguments:
    site: Site name
    template: template to process in templates/<template.conf>
    **kwargs: additional dict items to append to template variables exposed
              through the site.toml
    """
    hookenv.status_set('maintenance', 'Configuring site {}'.format(site))

    config = hookenv.config()
    context = load_site()
    context['host'] = config['host']
    context['port'] = config['port']
    context.update(**kwargs)
    render(source=template,
           target='/etc/nginx/sites-enabled/{}'.format(site),
           context=context)
    hookenv.log('Wrote vhost config {} to {}'.format(context, template),
                'info')

    if 'packages' in context:
        install_extra_packages(context['packages'])

    host.service_reload('nginx')
Beispiel #4
0
    def save_config(self):
        # Render new cfg file
        Render(self.proxy_config).dumps_to(self.proxy_config_file)
        host.service_reload('haproxy.service')

        # Check the juju ports match the config
        self.update_ports()
Beispiel #5
0
def migrate_to_mount(new_path):
    """Invoked when new mountpoint appears. This function safely migrates
    MySQL data from local disk to persistent storage (only if needed)
    """
    old_path = '/var/lib/mysql'
    if os.path.islink(old_path):
        hookenv.log('{} is already a symlink, skipping migration'.format(
            old_path))
        return True
    # Ensure our new mountpoint is empty. Otherwise error and allow
    # users to investigate and migrate manually
    files = os.listdir(new_path)
    try:
        files.remove('lost+found')
    except ValueError:
        pass
    if files:
        raise RuntimeError('Persistent storage contains old data. '
                           'Please investigate and migrate data manually '
                           'to: {}'.format(new_path))
    os.chmod(new_path, 0o700)
    if os.path.isdir('/etc/apparmor.d/local'):
        render('apparmor.j2', '/etc/apparmor.d/local/usr.sbin.mysqld',
               context={'path': os.path.join(new_path, '')})
        host.service_reload('apparmor')
    host.service_stop('mysql')
    host.rsync(os.path.join(old_path, ''),  # Ensure we have trailing slashes
               os.path.join(new_path, ''),
               options=['--archive'])
    shutil.rmtree(old_path)
    os.symlink(new_path, old_path)
    host.service_start('mysql')
def configure_https():
    """Enables SSL API Apache config if appropriate and kicks identity-service
    with any required api updates.
    """
    # need to write all to ensure changes to the entire request pipeline
    # propagate (c-api, haprxy, apache)
    CONFIGS.write_all()
    if 'https' in CONFIGS.complete_contexts():
        cmd = ['a2ensite', 'openstack_https_frontend']
        check_call(cmd)
    else:
        cmd = ['a2dissite', 'openstack_https_frontend']
        check_call(cmd)

    # Apache 2.4 required enablement of configuration
    if os.path.exists('/usr/sbin/a2enconf'):
        check_call(['a2enconf', 'swift-rings'])

    if not openstack.is_unit_paused_set():
        # TODO: improve this by checking if local CN certs are available
        # first then checking reload status (see LP #1433114).
        service_reload('apache2', restart_on_failure=True)

    for rid in relation_ids('identity-service'):
        keystone_joined(relid=rid)

    env_vars = {
        'OPENSTACK_SERVICE_SWIFT': 'proxy-server',
        'OPENSTACK_PORT_API': config('bind-port'),
        'OPENSTACK_PORT_MEMCACHED': 11211
    }
    openstack.save_script_rc(**env_vars)
Beispiel #7
0
def migrate_to_mount(new_path):
    """Invoked when new mountpoint appears. This function safely migrates
    MySQL data from local disk to persistent storage (only if needed)
    """
    old_path = '/var/lib/mysql'
    if os.path.islink(old_path):
        hookenv.log('{} is already a symlink, skipping migration'.format(
            old_path))
        return True
    # Ensure our new mountpoint is empty. Otherwise error and allow
    # users to investigate and migrate manually
    files = os.listdir(new_path)
    try:
        files.remove('lost+found')
    except ValueError:
        pass
    if files:
        raise RuntimeError('Persistent storage contains old data. '
                           'Please investigate and migrate data manually '
                           'to: {}'.format(new_path))
    os.chmod(new_path, 0o700)
    if os.path.isdir('/etc/apparmor.d/local'):
        render('apparmor.j2', '/etc/apparmor.d/local/usr.sbin.mysqld',
               context={'path': os.path.join(new_path, '')})
        host.service_reload('apparmor')
    host.service_stop('mysql')
    host.rsync(os.path.join(old_path, ''),  # Ensure we have trailing slashes
               os.path.join(new_path, ''),
               options=['--archive'])
    shutil.rmtree(old_path)
    os.symlink(new_path, old_path)
    host.service_start('mysql')
Beispiel #8
0
def configure_site(site, template, **kwargs):
    """ configures vhost

    Arguments:
    site: Site name
    template: template to process in templates/<template.conf>
    **kwargs: additional dict items to append to template variables exposed
              through the site.toml
    """
    hookenv.status_set('maintenance', 'Configuring site {}'.format(site))

    config = hookenv.config()
    context = load_site()
    context['host'] = config['host']
    context['port'] = config['port']
    context.update(**kwargs)
    conf_path = '/etc/nginx/sites-enabled/{}'.format(site)
    if os.path.exists(conf_path):
        os.remove(conf_path)
    render(source=template,
           target=conf_path,
           context=context)
    hookenv.log('Wrote vhost config {} to {}'.format(context, template),
                'info')

    host.service_reload('nginx')
Beispiel #9
0
def relation_changed():
    template_data = get_template_data()

    # Check required keys
    for k in ('etcd_servers',):
        if not template_data.get(k):
            print "Missing data for", k, template_data
            return

    print "Running with\n", template_data

    # Render and restart as needed
    for n in ('apiserver', 'controller-manager', 'scheduler'):
        if render_file(n, template_data) or not host.service_running(n):
            host.service_restart(n)

    # Render the file that makes the kubernetes binaries available to minions.
    if render_file(
            'distribution', template_data,
            'conf.tmpl', '/etc/nginx/sites-enabled/distribution') or \
            not host.service_running('nginx'):
        host.service_reload('nginx')
    # Render the default nginx template.
    if render_file(
            'nginx', template_data,
            'conf.tmpl', '/etc/nginx/sites-enabled/default') or \
            not host.service_running('nginx'):
        host.service_reload('nginx')

    # Send api endpoint to minions
    notify_minions()
def configure_https():
    """Enables SSL API Apache config if appropriate and kicks identity-service
    with any required api updates.
    """
    # need to write all to ensure changes to the entire request pipeline
    # propagate (c-api, haprxy, apache)
    CONFIGS.write_all()
    if 'https' in CONFIGS.complete_contexts():
        cmd = ['a2ensite', 'openstack_https_frontend']
        check_call(cmd)
    else:
        cmd = ['a2dissite', 'openstack_https_frontend']
        check_call(cmd)

    # Apache 2.4 required enablement of configuration
    if os.path.exists('/usr/sbin/a2enconf'):
        check_call(['a2enconf', 'swift-rings'])

    if not is_paused():
        # TODO: improve this by checking if local CN certs are available
        # first then checking reload status (see LP #1433114).
        service_reload('apache2', restart_on_failure=True)

    for rid in relation_ids('identity-service'):
        keystone_joined(relid=rid)

    env_vars = {'OPENSTACK_SERVICE_SWIFT': 'proxy-server',
                'OPENSTACK_PORT_API': config('bind-port'),
                'OPENSTACK_PORT_MEMCACHED': 11211}
    openstack.save_script_rc(**env_vars)
Beispiel #11
0
 def start(self):
     '''
     Starts the Registry service.
     '''
     if self.is_running():
         host.service_reload(KSQL_SERVICE)
     else:
         host.service_start(KSQL_SERVICE)
def certs_changed(relation_id=None, unit=None):
    process_certificates('horizon',
                         relation_id,
                         unit,
                         custom_hostname_link='dashboard')
    CONFIGS.write_all()
    service_reload('apache2')
    enable_ssl()
Beispiel #13
0
 def start(self):
     '''
     Starts the Kafka service.
     '''
     if self.is_running():
         host.service_reload(KAFKA_SERVICE)
     else:
         host.service_start(KAFKA_SERVICE)
Beispiel #14
0
    def save_config(self):
        """Save the updated configuration."""
        # Render new cfg file
        Render(self.proxy_config).dumps_to(self.proxy_config_file)
        host.service_reload("haproxy.service")

        # Check the juju ports match the config
        self.update_ports()
 def enable_webserver_site(self):
     """Enable Octavia API apache2 site if rendered or installed"""
     if os.path.exists(OCTAVIA_WSGI_CONF):
         check_enabled = subprocess.call(
             ['a2query', '-s', OCTAVIA_WEBSERVER_SITE])
         if check_enabled != 0:
             subprocess.check_call(['a2ensite', OCTAVIA_WEBSERVER_SITE])
             ch_host.service_reload('apache2', restart_on_failure=True)
Beispiel #16
0
def reload_system_daemons():
    ''' Reload the system daemons from on-disk configuration changes '''
    lsb = lsb_release()
    code = lsb['DISTRIB_CODENAME']
    if code != 'trusty':
        command = ['systemctl', 'daemon-reload']
        check_call(command)
    else:
        service_reload('docker')
def reload_system_daemons():
    ''' Reload the system daemons from on-disk configuration changes '''
    log('Reloading system daemons.')
    lsb = host.lsb_release()
    code = lsb['DISTRIB_CODENAME']
    if code != 'trusty':
        command = ['systemctl', 'daemon-reload']
        check_call(command)
    else:
        host.service_reload('docker')
Beispiel #18
0
def configure_apache():
    hookenv.log("Configuring apache vhost for ganglia master")
    if not os.path.exists(APACHE_CONFIG):
        os.symlink(GANGLIA_APACHE_CONFIG, APACHE_CONFIG)
        command = [
            'a2ensite',
            os.path.basename(APACHE_CONFIG)
        ]
        subprocess.check_call(command)
    host.service_reload(APACHE)
Beispiel #19
0
 def enable_apache2_site(self):
     """Enable Panko API apache2 site if rendered or installed"""
     if os.path.exists(PANKO_WSGI_CONF):
         check_enabled = subprocess.call(
             ['a2query', '-s', PANKO_APACHE_SITE]
         )
         if check_enabled != 0:
             subprocess.check_call(['a2ensite',
                                    PANKO_APACHE_SITE])
             host.service_reload('apache2',
                                 restart_on_failure=True)
Beispiel #20
0
def reload(args):
    """Reload the Vault service.

    The result of this action will be to have vault daemon
    reloaded (preferably with HUP signal in systemd).
    That allows for live changes in listener (only certs)
    without need of User intervention to unseal the vault.
    Unfortunately other options like disable_mlock, ui
    are not supported.

    """
    host.service_reload(service_name='vault')
Beispiel #21
0
    def enable_apache_ssl_vhost(self):
        """Enable Apache vhost for SSL termination

        Enable Apache vhost for SSL termination if vhost exists and it is not
        curently enabled
        """
        if os.path.exists(self.apache_vhost_file):
            check_enabled = subprocess.call(
                ['a2query', '-s', 'openstack_https_frontend'])
            if check_enabled != 0:
                subprocess.check_call(['a2ensite', 'openstack_https_frontend'])
                ch_host.service_reload('apache2', restart_on_failure=True)
Beispiel #22
0
def aa_profile_changed(service_name='ceph-osd-all'):
    """
    Reload AA profie and restart OSD processes.
    """
    log("Loading new AppArmor profile")
    service_reload('apparmor')
    log("Restarting ceph-osd services with new AppArmor profile")
    if ceph.systemd():
        for osd_id in ceph.get_local_osd_ids():
            service_restart('ceph-osd@{}'.format(osd_id))
    else:
        service_restart(service_name)
Beispiel #23
0
    def enable_apache_ssl_vhost(self):
        """Enable Apache vhost for SSL termination

        Enable Apache vhost for SSL termination if vhost exists and it is not
        curently enabled
        """
        if os.path.exists(self.apache_vhost_file):
            check_enabled = subprocess.call(
                ['a2query', '-s', 'openstack_https_frontend'])
            if check_enabled != 0:
                subprocess.check_call(['a2ensite', 'openstack_https_frontend'])
                ch_host.service_reload('apache2', restart_on_failure=True)
def aa_profile_changed(service_name='ceph-osd-all'):
    """
    Reload AA profie and restart OSD processes.
    """
    log("Loading new AppArmor profile")
    service_reload('apparmor')
    log("Restarting ceph-osd services with new AppArmor profile")
    if ceph.systemd():
        for osd_id in ceph.get_local_osd_ids():
            service_restart('ceph-osd@{}'.format(osd_id))
    else:
        service_restart(service_name)
    def set_apparmor(self):
        """Disbale apparmor for named

        This is currently specified in the designate documentation
        http://docs.openstack.org/developer/designate/getting-started.html

        TODO: Check this is *really* needed

        :returns: None
        """
        apparmor_file = '/etc/apparmor.d/disable/usr.sbin.named'
        if not os.path.isfile(apparmor_file):
            open(apparmor_file, 'w').close()
            host.service_reload('apparmor')
Beispiel #26
0
    def set_apparmor(self):
        """Disbale apparmor for named

        This is currently specified in the designate documentation
        http://docs.openstack.org/developer/designate/getting-started.html

        TODO: Check this is *really* needed

        :returns: None
        """
        apparmor_file = '/etc/apparmor.d/disable/usr.sbin.named'
        if not os.path.isfile(apparmor_file):
            open(apparmor_file, 'w').close()
            host.service_reload('apparmor')
def reload_system_daemons():
    """
    Reload the system daemons from on-disk configuration changes.

    :return: None
    """
    hookenv.log("Reloading system daemons.")
    lsb = host.lsb_release()
    code = lsb["DISTRIB_CODENAME"]
    if code != "trusty":
        command = ["systemctl", "daemon-reload"]
        check_call(command)
    else:
        host.service_reload("docker")
Beispiel #28
0
def setup(reverseproxy):
    services = reverseproxy.services()
    if not data_changed('reverseproxy.services', services):
        return
    config = hookenv.config()
    render(source="default",
        target="/etc/nginx/sites-available/default",
        owner="root",
        perms=0o644,
        context={
            'cfg': config,
            'services': services,
        })
    host.service_reload('nginx')
def remove_default_site():
    """
    Remove the default enabled 
    site.

    :return: Boolean
    """
    site_path = '/etc/nginx/sites-enabled/default'
    if os.path.isfile(site_path):
        os.remove(site_path)
        host.service_reload('nginx', restart_on_failure=True)
        return True

    return False
Beispiel #30
0
def setup_dovecot():
    config = hookenv.config()
    certkey = pki.certkey()
    for filename in ('10-master.conf', '10-ssl.conf'):
        render(source=filename,
            target="/etc/dovecot/conf.d/%s" % (filename),
            owner="root",
            perms=0o644,
            context={
                'cfg': config,
                'certkey': certkey,
            })
    if host.service_running('dovecot'):
        host.service_reload('dovecot')
    set_state('dovecot.start')
def configure_https():
    CONFIGS.write_all()
    if 'https' in CONFIGS.complete_contexts():
        cmd = ['a2ensite', 'openstack_https_frontend']
    else:
        cmd = ['a2dissite', 'openstack_https_frontend']

    subprocess.check_call(cmd)

    # TODO: improve this by checking if local CN certs are available
    # first then checking reload status (see LP #1433114).
    service_reload('apache2', restart_on_failure=True)

    for rid in relation_ids('identity-service'):
        identity_joined(rid=rid)
Beispiel #32
0
    def renew_cert(self, full=True):
        """Renew certificates."""
        hookenv.log("Renewing cert", "INFO")

        if full:
            # Calling a full disable/enable to clean and re-write the config
            # to catch domain changes in the charm config
            hookenv.log("Performing full domain register", "INFO")
            self.disable_letsencrypt()
            self.enable_letsencrypt()
        else:
            hookenv.log("Performing renew only", "INFO")
            letsencrypt.renew()
            # create the merged .pem for HAProxy
            self.merge_letsencrypt_cert()
            host.service_reload("haproxy.service")
Beispiel #33
0
def render_mysql_root_config():
    mysqlroot_endpoint = endpoint_from_flag('mysql-root.available')

    render(
        'mysql-config.j2', '/var/www/mysql-proxy/mysql-root-config.html', {
            'db_pass': mysqlroot_endpoint.password(),
            'db_dbname': mysqlroot_endpoint.database(),
            'db_host': mysqlroot_endpoint.host(),
            'db_user': mysqlroot_endpoint.user(),
            'db_port': mysqlroot_endpoint.port(),
        })

    log('--- NA RENDER ROOT')
    host.service_reload('apache2')
    set_flag('webapp.mysqlroot.configured')
    status_set('active', 'mysql-root done!')
Beispiel #34
0
def render_pgsql_config():
    pgsql_endpoint = endpoint_from_flag('pgsql.master.available')

    render(
        'postgres-config.j2', '/var/www/postgres-proxy/postgres-config.html', {
            'db_master': pgsql_endpoint.master,
            'db_pass': pgsql_endpoint.master['password'],
            'db_dbname': pgsql_endpoint.master['dbname'],
            'db_host': pgsql_endpoint.master['host'],
            'db_user': pgsql_endpoint.master['user'],
            'db_port': pgsql_endpoint.master['port'],
        })

    host.service_reload('apache2')
    set_flag('webapp.pgsql.configured')
    status_set('active', 'Apache/Proxy ready!')
Beispiel #35
0
def install_apparmor_profile():
    """
    Install ceph apparmor profiles and configure
    based on current setting of 'aa-profile-mode'
    configuration option.
    """
    log('Installing apparmor profile for ceph-osd')
    copy_profile_into_place()
    if config().changed('aa-profile-mode'):
        aa_context = CephOsdAppArmorContext()
        aa_context.setup_aa_profile()
        service_reload('apparmor')
        if ceph.systemd():
            for osd_id in ceph.get_local_osd_ids():
                service_restart('ceph-osd@{}'.format(osd_id))
        else:
            service_restart('ceph-osd-all')
Beispiel #36
0
def ensure_running(changed):
    '''
    Reload the consul service if running and the configuration has changed,
    otherwise start the consul service.
    '''
    if host.service_running('consul'):
        if changed:
            print('Reloading the consul process.')
            # Reloading configuration does not reload all configuration items.
            # The items which are reloaded include: Log level, Checks,
            # Services, Watches, HTTP Client Address
            host.service_reload('consul', True)
        else:
            print('Consul server already running.')
        return
    print('Starting consul server.')
    host.service_start('consul')
Beispiel #37
0
def ensure_running(changed):
    '''
    Reload the consul service if running and the configuration has changed,
    otherwise start the consul service.
    '''
    if host.service_running('consul'):
        if changed:
            print('Reloading the consul process.')
            # Reloading configuration does not reload all configuration items.
            # The items which are reloaded include: Log level, Checks,
            # Services, Watches, HTTP Client Address
            host.service_reload('consul', True)
        else:
            print('Consul server already running.')
        return
    print('Starting consul server.')
    host.service_start('consul')
Beispiel #38
0
    def configure_ssl(self, keystone_interface=None):
        """Configure SSL certificates and keys

        NOTE(AJK): This function tries to minimise the work it does,
        particularly with writing files and restarting apache.

        @param keystone_interface KeystoneRequires class
        """
        keystone_interface = (
            relations.endpoint_from_flag('identity-service.available.ssl') or
            relations
            .endpoint_from_flag('identity-service.available.ssl_legacy'))
        certificates_interface = relations.endpoint_from_flag(
            'certificates.batch.cert.available')
        ssl_objects = self.get_certs_and_keys(
            keystone_interface=keystone_interface,
            certificates_interface=certificates_interface)
        with is_data_changed('configure_ssl.ssl_objects',
                             ssl_objects) as changed:
            if ssl_objects:
                # NOTE(fnordahl): regardless of changes to data we may
                # have other changes we want to apply to the files.
                # (e.g. ownership, permissions)
                #
                # Also note that c-h.host.write_file used in configure_cert()
                # has it's own logic to detect data changes.
                #
                # LP: #1821314
                for ssl in ssl_objects:
                    self.set_state('ssl.requested', True)
                    self.configure_cert(
                        ssl['cert'], ssl['key'], cn=ssl['cn'])
                    self.configure_ca(ssl['ca'])
                cert_utils.create_ip_cert_links(
                    os.path.join('/etc/apache2/ssl/', self.name))
                if not os_utils.snap_install_requested() and changed:
                    self.configure_apache()
                    ch_host.service_reload('apache2')

                self.remove_state('ssl.requested')
                self.set_state('ssl.enabled', True)
            else:
                self.set_state('ssl.enabled', False)
        amqp_ssl = relations.endpoint_from_flag('amqp.available.ssl')
        if amqp_ssl:
            self.configure_rabbit_cert(amqp_ssl)
Beispiel #39
0
    def configure_ssl(self, keystone_interface=None):
        """Configure SSL certificates and keys

        NOTE(AJK): This function tries to minimise the work it does,
        particularly with writing files and restarting apache.

        @param keystone_interface KeystoneRequires class
        """
        keystone_interface = (
            relations.endpoint_from_flag('identity-service.available.ssl')
            or relations.endpoint_from_flag(
                'identity-service.available.ssl_legacy'))
        certificates_interface = relations.endpoint_from_flag(
            'certificates.batch.cert.available')
        ssl_objects = self.get_certs_and_keys(
            keystone_interface=keystone_interface,
            certificates_interface=certificates_interface)
        with is_data_changed('configure_ssl.ssl_objects',
                             ssl_objects) as changed:
            if ssl_objects:
                # NOTE(fnordahl): regardless of changes to data we may
                # have other changes we want to apply to the files.
                # (e.g. ownership, permissions)
                #
                # Also note that c-h.host.write_file used in configure_cert()
                # has it's own logic to detect data changes.
                #
                # LP: #1821314
                for ssl in ssl_objects:
                    self.set_state('ssl.requested', True)
                    self.configure_cert(ssl['cert'], ssl['key'], cn=ssl['cn'])
                    self.configure_ca(ssl['ca'])
                cert_utils.create_ip_cert_links(
                    os.path.join('/etc/apache2/ssl/', self.name))
                if not os_utils.snap_install_requested() and changed:
                    self.configure_apache()
                    ch_host.service_reload('apache2')

                self.remove_state('ssl.requested')
                self.set_state('ssl.enabled', True)
            else:
                self.set_state('ssl.enabled', False)
        amqp_ssl = relations.endpoint_from_flag('amqp.available.ssl')
        if amqp_ssl:
            self.configure_rabbit_cert(amqp_ssl)
Beispiel #40
0
    def configure_tls(self, certificates_interface=None):
        """Configure TLS certificates and keys

        NOTE(AJK): This function tries to minimise the work it does,
        particularly with writing files and restarting apache.

        :param certificates_interface: certificates relation endpoint
        :type certificates_interface: TlsRequires(Endpoint) object
        """
        # this takes care of writing out the CA certificate
        tls_objects = super().configure_tls(
            certificates_interface=certificates_interface)
        with is_data_changed(
                'configure_ssl.ssl_objects', tls_objects) as changed:
            if tls_objects:
                # NOTE(fnordahl): regardless of changes to data we may
                # have other changes we want to apply to the files.
                # (e.g. ownership, permissions)
                #
                # Also note that c-h.host.write_file used in configure_cert()
                # has it's own logic to detect data changes.
                #
                # LP: #1821314
                for tls_object in tls_objects:
                    self.set_state('ssl.requested', True)
                    if os_utils.snap_install_requested():
                        path = ('/var/snap/{snap_name}/common/etc/nginx/ssl'
                                .format(snap_name=self.primary_snap))
                    else:
                        path = os.path.join('/etc/apache2/ssl/', self.name)
                    self.configure_cert(
                        path,
                        tls_object['cert'],
                        tls_object['key'],
                        cn=tls_object['cn'])
                cert_utils.create_ip_cert_links(
                    os.path.join('/etc/apache2/ssl/', self.name))
                if not os_utils.snap_install_requested() and changed:
                    self.configure_apache()
                    ch_host.service_reload('apache2')

                self.remove_state('ssl.requested')
                self.set_state('ssl.enabled', True)
            else:
                self.set_state('ssl.enabled', False)
Beispiel #41
0
def render_mysql_config():
    mysql_endpoint = endpoint_from_flag('mysql-shared.available')

    render(
        'mysql-config.j2',
        '/var/www/mysql-proxy/mysql-config.html',
        {
            'db_pass': mysql_endpoint.password("proxy"),
            'db_dbname': mysql_endpoint.database("proxy"),
            'db_host': mysql_endpoint.db_host(),
            'hostname': mysql_endpoint.hostname("proxy"),
            'db_user': mysql_endpoint.username("proxy"),  # note no port :/
        })
    log('--- NA RENDER SHARED')

    host.service_reload('apache2')
    set_flag('webapp.mysqlshared.configured')
    status_set('active', 'mysql shared done!')
Beispiel #42
0
def configure_https():
    """Enables SSL API Apache config if appropriate."""
    # need to write all to ensure changes to the entire request pipeline
    # propagate (c-api, haprxy, apache)
    CONFIGS.write_all()
    if 'https' in CONFIGS.complete_contexts():
        cmd = ['a2ensite', 'openstack_https_frontend']
        subprocess.check_call(cmd)
    else:
        cmd = ['a2dissite', 'openstack_https_frontend']
        subprocess.check_call(cmd)

    # TODO: improve this by checking if local CN certs are available
    # first then checking reload status (see LP #1433114).
    service_reload('apache2', restart_on_failure=True)

    for rid in relation_ids('identity-service'):
        identity_joined(rid=rid)
Beispiel #43
0
def setup_postfix():
    remove_state('postfix.start')

    config = hookenv.config()
    certkey = pki.certkey()
    for filename in ('main.cf', 'master.cf'):
        render(source=filename,
            target="/etc/postfix/%s" % (filename),
            owner="root",
            perms=0o644,
            context={
                'cfg': config,
                'certkey': certkey,
            })

    if host.service_running('postfix'):
        host.service_reload('postfix')
    set_state('postfix.start')
def configure_https():
    '''Enables SSL API Apache config if appropriate and kicks
    identity-service and image-service with any required
    updates
    '''
    CONFIGS.write_all()
    if 'https' in CONFIGS.complete_contexts():
        cmd = ['a2ensite', 'openstack_https_frontend']
        check_call(cmd)
    else:
        cmd = ['a2dissite', 'openstack_https_frontend']
        check_call(cmd)

    # TODO: improve this by checking if local CN certs are available
    # first then checking reload status (see LP #1433114).
    service_reload('apache2', restart_on_failure=True)

    for r_id in relation_ids('identity-service'):
        keystone_joined(relation_id=r_id)
    for r_id in relation_ids('image-service'):
        image_service_joined(relation_id=r_id)
Beispiel #45
0
    def configure_ssl(self, keystone_interface=None):
        """Configure SSL certificates and keys

        NOTE(AJK): This function tries to minimise the work it does,
        particularly with writing files and restarting apache.

        @param keystone_interface KeystoneRequires class
        """
        keystone_interface = (
            relations.endpoint_from_flag('identity-service.available.ssl') or
            relations
            .endpoint_from_flag('identity-service.available.ssl_legacy'))
        certificates_interface = relations.endpoint_from_flag(
            'certificates.batch.cert.available')
        ssl_objects = self.get_certs_and_keys(
            keystone_interface=keystone_interface,
            certificates_interface=certificates_interface)
        with is_data_changed('configure_ssl.ssl_objects',
                             ssl_objects) as changed:
            if ssl_objects:
                if changed:
                    for ssl in ssl_objects:
                        self.set_state('ssl.requested', True)
                        self.configure_cert(
                            ssl['cert'], ssl['key'], cn=ssl['cn'])
                        self.configure_ca(ssl['ca'])
                    cert_utils.create_ip_cert_links(
                        os.path.join('/etc/apache2/ssl/', self.name))
                    if not os_utils.snap_install_requested():
                        self.configure_apache()
                        ch_host.service_reload('apache2')

                    self.remove_state('ssl.requested')
                self.set_state('ssl.enabled', True)
            else:
                self.set_state('ssl.enabled', False)
        amqp_ssl = relations.endpoint_from_flag('amqp.available.ssl')
        if amqp_ssl:
            self.configure_rabbit_cert(amqp_ssl)
def configure_https():
    '''
    Enables SSL API Apache config if appropriate and kicks identity-service
    with any required api updates.
    '''
    # need to write all to ensure changes to the entire request pipeline
    # propagate (c-api, haprxy, apache)
    CONFIGS.write_all()
    if 'https' in CONFIGS.complete_contexts():
        cmd = ['a2ensite', 'openstack_https_frontend']
        subprocess.check_call(cmd)
    else:
        cmd = ['a2dissite', 'openstack_https_frontend']
        subprocess.check_call(cmd)

    # TODO: improve this by checking if local CN certs are available
    # first then checking reload status (see LP #1433114).
    if not ch_utils.is_unit_paused_set():
        ch_host.service_reload('apache2', restart_on_failure=True)

    for rid in hookenv.relation_ids('identity-service'):
        identity_joined(rid=rid)
Beispiel #47
0
def config_changed():
    config = hookenv.config()
    if not reactive.is_state('apache.available') or not config.changed('port'):
        return
    with open('apache.yaml') as fp:
        workload = yaml.safe_load(fp)
    for name, site in workload['sites'].items():
        configure_site(name, site)
    if reactive.is_state('apache.started'):
        hookenv.close_port(config.previous('port'))
        assert host.service_reload('apache2'), 'Failed to reload Apache'
        hookenv.open_port(config['port'])
    hookenv.status_set('maintenance', '')
Beispiel #48
0
def configure_https():
    '''Enables SSL API Apache config if appropriate and kicks
    identity-service and image-service with any required
    updates
    '''
    CONFIGS.write_all()
    if 'https' in CONFIGS.complete_contexts():
        cmd = ['a2ensite', 'openstack_https_frontend']
        subprocess.check_call(cmd)
    else:
        cmd = ['a2dissite', 'openstack_https_frontend']
        try:
            subprocess.check_call(cmd)
        except subprocess.CalledProcessError:
            # The site is not yet enabled or
            # https is not configured
            pass

    # TODO: improve this by checking if local CN certs are available
    # first then checking reload status (see LP #1433114).
    if not is_unit_paused_set():
        service_reload('apache2', restart_on_failure=True)
Beispiel #49
0
def start():
    host.service_reload('apache2')
    host.service_restart('collectorweb')
Beispiel #50
0
def stop():
    apache2.disable_site('cabs-graphite')
    os.remove('/etc/apache2/sites-available/cabs-graphite.conf')
    host.service_reload('apache2')
    host.service_stop('carbon-cache')
    host.service_stop('collectorweb')
Beispiel #51
0
 def reload_config(self):
     service_reload("bind9")
def certs_changed(relation_id=None, unit=None):
    process_certificates('horizon', relation_id, unit)
    CONFIGS.write_all()
    service_reload('apache2')
    enable_ssl()
Beispiel #53
0
def config_changed():
    """
    On the execution of the juju event 'config-changed' this function
    determines the appropriate architecture and the configured version to
    create kubernetes binary files.
    """
    hookenv.log('Starting config-changed')
    charm_dir = Path(hookenv.charm_dir())
    config = hookenv.config()
    # Get the version of kubernetes to install.
    version = config['version']
    username = config['username']
    password = config['password']
    certificate = config['apiserver-cert']
    key = config['apiserver-key']

    if version == 'master':
        # The 'master' branch of kuberentes is used when master is configured.
        branch = 'master'
    elif version == 'local':
        # Check for kubernetes binaries in the local files/output directory.
        branch = None
    else:
        # Create a branch to a tag to get the release version.
        branch = 'tags/{0}'.format(version)

    cert_file = '/srv/kubernetes/apiserver.crt'
    key_file = '/srv/kubernetes/apiserver.key'
    # When the cert or key changes we need to restart the apiserver.
    if config.changed('apiserver-cert') or config.changed('apiserver-key'):
        hookenv.log('Certificate or key has changed.')
        if not certificate or not key:
            generate_cert(key=key_file, cert=cert_file)
        else:
            hookenv.log('Writing new certificate and key to server.')
            with open(key_file, 'w') as file:
                file.write(key)
            with open(cert_file, 'w') as file:
                file.write(certificate)
        # Restart apiserver as the certificate or key has changed.
        if host.service_running('apiserver'):
            host.service_restart('apiserver')
        # Reload nginx because it proxies https to apiserver.
        if host.service_running('nginx'):
            host.service_reload('nginx')

    if config.changed('username') or config.changed('password'):
        hookenv.log('Username or password changed, creating authentication.')
        basic_auth(username, username, password)
        if host.service_running('apiserver'):
            host.service_restart('apiserver')

    # Get package architecture, rather than arch from the kernel (uname -m).
    arch = subprocess.check_output(['dpkg', '--print-architecture']).strip()

    if not branch:
        output_path = charm_dir / 'files/output'
        kube_installer = KubernetesInstaller(arch, version, output_path)
    else:

        # Build the kuberentes binaries from source on the units.
        kubernetes_dir = Path('/opt/kubernetes')

        # Construct the path to the binaries using the arch.
        output_path = kubernetes_dir / '_output/local/bin/linux' / arch
        kube_installer = KubernetesInstaller(arch, version, output_path)

        if not kubernetes_dir.exists():
            message = 'The kubernetes source directory {0} does not exist. ' \
                'Was the kubernetes repository cloned during the install?'
            print(message.format(kubernetes_dir))
            exit(1)

        # Change to the kubernetes directory (git repository).
        with kubernetes_dir:
            # Create a command to get the current branch.
            git_branch = 'git branch | grep "\*" | cut -d" " -f2'
            current_branch = subprocess.check_output(git_branch, shell=True)
            current_branch = current_branch.strip()
            print('Current branch: ', current_branch)
            # Create the path to a file to indicate if the build was broken.
            broken_build = charm_dir / '.broken_build'
            # write out the .broken_build file while this block is executing.
            with check_sentinel(broken_build) as last_build_failed:
                print('Last build failed: ', last_build_failed)
                # Rebuild if current version is different or last build failed.
                if current_branch != version or last_build_failed:
                    kube_installer.build(branch)
            if not output_path.isdir():
                broken_build.touch()

    # Create the symoblic links to the right directories.
    kube_installer.install()

    relation_changed()

    hookenv.log('The config-changed hook completed successfully.')
Beispiel #54
0
 def reload_config(self):
     service_reload('bind9')