Example #1
0
def get_local_ip():
    fallback = get_host_ip(unit_get('private-address'))
    if config('os-data-network'):
        # NOTE: prefer any existing use of config based networking
        local_ip = get_address_in_network(config('os-data-network'), fallback)
    else:
        # NOTE: test out network-spaces support, then fallback
        try:
            local_ip = get_host_ip(network_get_primary_address('data'))
        except NotImplementedError:
            local_ip = fallback
    return local_ip
def get_local_ip():
    fallback = get_host_ip(unit_get('private-address'))
    if config('os-data-network'):
        # NOTE: prefer any existing use of config based networking
        local_ip = get_address_in_network(
            config('os-data-network'),
            fallback)
    else:
        # NOTE: test out network-spaces support, then fallback
        try:
            local_ip = get_host_ip(network_get_primary_address('data'))
        except NotImplementedError:
            local_ip = fallback
    return local_ip
def sapi_post_ips():
    """
    Posts PLUMgrid nodes IPs to solutions api server.
    """
    pg_edge_ips = _pg_edge_ips()
    pg_dir_ips = _pg_dir_ips()
    pg_gateway_ips = _pg_gateway_ips()
    pg_dir_ips.append(get_host_ip(unit_get('private-address')))
    pg_edge_ips = '"edge_ips"' + ':' \
        + '"{}"'.format(','.join(str(i) for i in pg_edge_ips))
    pg_dir_ips = '"director_ips"' + ':' \
        + '"{}"'.format(','.join(str(i) for i in pg_dir_ips))
    pg_gateway_ips = '"gateway_ips"' + ':' \
        + '"{}"'.format(','.join(str(i) for i in pg_gateway_ips))
    opsvm_ip = '"opsvm_ip"' + ':' + '"{}"'.format(config('opsvm-ip'))
    virtual_ip = '"virtual_ip"' + ':' \
        + '"{}"'.format(config('plumgrid-virtual-ip'))
    JSON_IPS = ','.join([pg_dir_ips, pg_edge_ips, pg_gateway_ips,
                        opsvm_ip, virtual_ip])
    status = (
        'curl -H \'Content-Type: application/json\' -X '
        'PUT -d \'{{{0}}}\' http://{1}' + ':' + '{2}/v1/zones/{3}/allIps'
    ).format(JSON_IPS, config('lcm-ip'), config('sapi-port'),
             config('sapi-zone'))
    POST_ZONE_IPs = _exec_cmd_output(
        status,
        'Posting Zone IPs to Solutions API server failed!')
    if POST_ZONE_IPs:
        if 'success' in POST_ZONE_IPs:
            log('Successfully posted Zone IPs to Solutions API server!')
        log(POST_ZONE_IPs)
Example #4
0
def setup_ufw():
    """Setup UFW firewall to ensure only swift-storage clients and storage
    peers have access to the swift daemons.

    :side effect: calls several external functions
    :return: None
    """

    if not config('enable-firewall'):
        log("Firewall has been administratively disabled", "DEBUG")
        return

    ports = [config('object-server-port'),
             config('container-server-port'),
             config('account-server-port')]

    # Storage peers
    allowed_hosts = RsyncContext()().get('allowed_hosts', '').split(' ')

    # Storage clients (swift-proxy)
    allowed_hosts += [get_host_ip(ingress_address(rid=u.rid, unit=u.unit))
                      for u in iter_units_for_relation_name('swift-storage')]

    # Grant access for peers and clients
    for host in allowed_hosts:
        for port in ports:
            grant_access(host, port)

    # Default deny for storage ports
    for port in ports:
        ufw.modify_access(src=None, dst='any', port=port,
                          proto='tcp', action='reject')
Example #5
0
def health_manager_bind_ip(cls):
    """IP address health manager process should bind to.

    The value is configured individually per unit and reflects the IP
    address assigned to the specific units tunnel port.

    :param cls: charms_openstack.adapters.ConfigurationAdapter derived class
                instance.  Charm class instance is at cls.charm_instance.
    :type: cls: charms_openstack.adapters.ConfiguartionAdapter
    :returns: IP address of unit local Health Manager interface.
    :rtype: str
    """

    # -> contrail addition
    return ch_net_ip.get_host_ip(ch_core.hookenv.network_get("public")["ingress-addresses"][0])
    # <- contrail addition

    ip_list = []
    for af in ['AF_INET6', 'AF_INET']:
        try:
            ip_list.extend(
                (ip for ip in
                    ch_net_ip.get_iface_addr(iface=OCTAVIA_MGMT_INTF,
                                             inet_type=af)
                    if '%' not in ip))
        except Exception:
            # ch_net_ip.get_iface_addr() throws an exception of type
            # Exception when the requested interface does not exist or if
            # it has no addresses in the requested address family.
            pass
    if ip_list:
        return ip_list[0]
Example #6
0
def controller_ip_port_list(cls):
    """List of ip:port pairs for Amphorae instances health reporting.

    The list is built based on information from individual Octavia units
    coordinated, stored and shared among all units trhough leader storage.

    :param cls: charms_openstack.adapters.ConfigurationAdapter derived class
                instance.  Charm class instance is at cls.charm_instance.
    :type: cls: charms_openstack.adapters.ConfiguartionAdapter
    :returns: Comma separated list of ip:port pairs.
    :rtype: str
    """

    # -> contrail addition
    return ch_net_ip.get_host_ip(ch_core.hookenv.network_get("public")["ingress-addresses"][0]) + ':' + OCTAVIA_HEALTH_LISTEN_PORT
    # <- contrail addition

    try:
        ip_list = json.loads(
            leadership.leader_get('controller-ip-port-list'))
    except TypeError:
        return
    if ip_list:
        port_suffix = ':' + OCTAVIA_HEALTH_LISTEN_PORT
        return (port_suffix + ', ').join(sorted(ip_list)) + port_suffix
Example #7
0
 def test_get_host_ip_with_hostname_no_dns(self, apt_install, socket,
                                           ns_query):
     ns_query.return_value = []
     fake_dns = FakeDNS(None)
     socket.return_value = '10.0.0.1'
     with patch(builtin_import, side_effect=[fake_dns]):
         ip = net_ip.get_host_ip('www.ubuntu.com')
     self.assertEquals(ip, '10.0.0.1')
Example #8
0
    def normalize_address(self, hostname):
        """Ensure that address returned is an IP address (i.e. not fqdn)"""
        if config_get('prefer-ipv6'):
            # TODO: add support for ipv6 dns
            return hostname

        if hostname != unit_get('private-address'):
            return get_host_ip(hostname, fallback=hostname)

        # Otherwise assume localhost
        return '127.0.0.1'
Example #9
0
    def normalize_address(self, hostname):
        """Ensure that address returned is an IP address (i.e. not fqdn)"""
        if config_get('prefer-ipv6'):
            # TODO: add support for ipv6 dns
            return hostname

        if hostname != unit_get('private-address'):
            return get_host_ip(hostname, fallback=hostname)

        # Otherwise assume localhost
        return '127.0.0.1'
Example #10
0
    def test_get_host_ip_with_hostname_fallback(self, apt_install, socket,
                                                ns_query, *args):
        ns_query.return_value = []
        fake_dns = FakeDNS(None)

        def r():
            raise Exception()

        socket.side_effect = r
        with patch(builtin_import, side_effect=[fake_dns]):
            ip = net_ip.get_host_ip('www.ubuntu.com', fallback='127.0.0.1')
        self.assertEquals(ip, '127.0.0.1')
def get_mgmt_interface():
    '''
    Returns the managment interface.
    '''
    mgmt_interface = config('mgmt-interface')
    if not mgmt_interface:
        try:
            return get_iface_from_addr(unit_get('private-address'))
        except:
            for bridge_interface in get_bridges():
                if (get_host_ip(unit_get('private-address'))
                        in get_iface_addr(bridge_interface)):
                    return bridge_interface
    elif interface_exists(mgmt_interface):
        return mgmt_interface
    else:
        log('Provided managment interface %s does not exist' % mgmt_interface)
        return get_iface_from_addr(unit_get('private-address'))
def get_mgmt_interface():
    '''
    Returns the managment interface.
    '''
    mgmt_interface = config('mgmt-interface')
    if not mgmt_interface:
        try:
            return get_iface_from_addr(unit_get('private-address'))
        except:
            for bridge_interface in get_bridges():
                if (get_host_ip(unit_get('private-address'))
                        in get_iface_addr(bridge_interface)):
                    return bridge_interface
    elif interface_exists(mgmt_interface):
        return mgmt_interface
    else:
        log('Provided managment interface %s does not exist'
            % mgmt_interface)
        return get_iface_from_addr(unit_get('private-address'))
Example #13
0
 def test_get_host_ip_with_ip(self, apt_install):
     fake_dns = FakeDNS('5.5.5.5')
     with patch(builtin_import, side_effect=[fake_dns]):
         ip = net_ip.get_host_ip('4.2.2.1')
     self.assertEquals(ip, '4.2.2.1')
Example #14
0
 def test_get_host_ip_with_hostname(self, apt_install):
     fake_dns = FakeDNS('10.0.0.1')
     with patch(builtin_import, side_effect=[fake_dns]):
         ip = net_ip.get_host_ip('www.ubuntu.com')
     self.assertEquals(ip, '10.0.0.1')
    def __call__(self):
        api_settings = super(NeutronGatewayContext, self).__call__()
        ctxt = {
            'shared_secret': get_shared_secret(),
            'core_plugin': core_plugin(),
            'plugin': config('plugin'),
            'debug': config('debug'),
            'verbose': config('verbose'),
            'instance_mtu': config('instance-mtu'),
            'dns_servers': config('dns-servers'),
            'l2_population': api_settings['l2_population'],
            'enable_dvr': api_settings['enable_dvr'],
            'enable_l3ha': api_settings['enable_l3ha'],
            'extension_drivers': api_settings['extension_drivers'],
            'dns_domain': api_settings['dns_domain'],
            'overlay_network_type':
            api_settings['overlay_network_type'],
            'rpc_response_timeout': api_settings['rpc_response_timeout'],
            'report_interval': api_settings['report_interval'],
            'enable_metadata_network': config('enable-metadata-network'),
            'enable_isolated_metadata': config('enable-isolated-metadata'),
        }

        fallback = get_host_ip(unit_get('private-address'))
        if config('os-data-network'):
            # NOTE: prefer any existing use of config based networking
            ctxt['local_ip'] = \
                get_address_in_network(config('os-data-network'),
                                       fallback)
        else:
            # NOTE: test out network-spaces support, then fallback
            try:
                ctxt['local_ip'] = get_host_ip(
                    network_get_primary_address('data')
                )
            except NotImplementedError:
                ctxt['local_ip'] = fallback

        mappings = config('bridge-mappings')
        if mappings:
            ctxt['bridge_mappings'] = ','.join(mappings.split())

        flat_providers = config('flat-network-providers')
        if flat_providers:
            ctxt['network_providers'] = ','.join(flat_providers.split())

        vlan_ranges = config('vlan-ranges')
        if vlan_ranges:
            ctxt['vlan_ranges'] = ','.join(vlan_ranges.split())

        dnsmasq_flags = config('dnsmasq-flags')
        if dnsmasq_flags:
            ctxt['dnsmasq_flags'] = config_flags_parser(dnsmasq_flags)

        net_dev_mtu = api_settings['network_device_mtu']
        if net_dev_mtu:
            ctxt['network_device_mtu'] = net_dev_mtu
            ctxt['veth_mtu'] = net_dev_mtu

        # Override user supplied config for these plugins as these settings are
        # mandatory
        if ctxt['plugin'] in ['nvp', 'nsx', 'n1kv']:
            ctxt['enable_metadata_network'] = True
            ctxt['enable_isolated_metadata'] = True

        return ctxt
    def __call__(self):
        if not relation_ids('mon'):
            return {}
        mon_hosts = []
        auths = []
        for relid in relation_ids('mon'):
            for unit in related_units(relid):
                ceph_public_addr = relation_get('ceph-public-address', unit,
                                                relid)
                if ceph_public_addr:
                    host_ip = format_ipv6_addr(ceph_public_addr) or \
                        get_host_ip(ceph_public_addr)
                    mon_hosts.append('{}:6789'.format(host_ip))
                    _auth = relation_get('auth', unit, relid)
                    if _auth:
                        auths.append(_auth)

        if len(set(auths)) != 1:
            e = ("Inconsistent or absent auth returned by mon units. Setting "
                 "auth_supported to 'none'")
            log(e, level=WARNING)
            auth = 'none'
        else:
            auth = auths[0]

        # /etc/init.d/radosgw mandates that a dns name is used for this
        # parameter so ensure that address is resolvable
        host = socket.gethostname()
        if config('prefer-ipv6'):
            ensure_host_resolvable_v6(host)

        port = determine_apache_port(config('port'), singlenode_mode=True)
        if config('prefer-ipv6'):
            port = "[::]:%s" % (port)

        mon_hosts.sort()
        ctxt = {
            'auth_supported': auth,
            'mon_hosts': ' '.join(mon_hosts),
            'hostname': host,
            'old_auth': cmp_pkgrevno('radosgw', "0.51") < 0,
            'use_syslog': str(config('use-syslog')).lower(),
            'embedded_webserver': config('use-embedded-webserver'),
            'loglevel': config('loglevel'),
            'port': port,
            'ipv6': config('prefer-ipv6')
        }

        certs_path = '/var/lib/ceph/nss'
        paths = [os.path.join(certs_path, 'ca.pem'),
                 os.path.join(certs_path, 'signing_certificate.pem')]
        if all([os.path.isfile(p) for p in paths]):
            ctxt['cms'] = True

        if (config('use-ceph-optimised-packages') and
                not config('use-embedded-webserver')):
            ctxt['disable_100_continue'] = False
        else:
            # NOTE: currently only applied if NOT using embedded webserver
            ctxt['disable_100_continue'] = True

        if self.context_complete(ctxt):
            return ctxt

        return {}