示例#1
0
    def setUpClass(cls):
        """Run class setup for running LBaaSv2 service tests."""
        super(LBAASv2Test, cls).setUpClass()
        cls.keystone_client = ObjectRetrierWraps(
            openstack_utils.get_keystone_session_client(cls.keystone_session))

        if (openstack_utils.get_os_release() >=
                openstack_utils.get_os_release('focal_wallaby')):
            # add role to admin user for the duration of the test
            grant_role_current_user(cls.keystone_client, cls.keystone_session,
                                    LBAAS_ADMIN_ROLE)

        cls.neutron_client = ObjectRetrierWraps(
            openstack_utils.get_neutron_session_client(cls.keystone_session))
        cls.octavia_client = ObjectRetrierWraps(
            openstack_utils.get_octavia_session_client(cls.keystone_session))
        cls.RESOURCE_PREFIX = 'zaza-octavia'

        # NOTE(fnordahl): in the event of a test failure we do not want to run
        # tear down code as it will make debugging a problem virtually
        # impossible.  To alleviate each test method will set the
        # `run_tearDown` instance variable at the end which will let us run
        # tear down only when there were no failure.
        cls.run_tearDown = False
        # List of load balancers created by this test
        cls.loadbalancers = []
        # List of floating IPs created by this test
        cls.fips = []
示例#2
0
    def test_create_loadbalancer(self):
        """Create load balancer."""
        keystone_session = openstack_utils.get_overcloud_keystone_session()
        neutron_client = openstack_utils.get_neutron_session_client(
            keystone_session)
        resp = neutron_client.list_networks(name='private')
        subnet_id = resp['networks'][0]['subnets'][0]
        octavia_client = openstack_utils.get_octavia_session_client(
            keystone_session)
        result = octavia_client.load_balancer_create(
            json={
                'loadbalancer': {
                    'description': 'Created by Zaza',
                    'admin_state_up': True,
                    'vip_subnet_id': subnet_id,
                    'name': 'zaza-lb-0',
                }})
        lb_id = result['loadbalancer']['id']

        @tenacity.retry(wait=tenacity.wait_fixed(1),
                        reraise=True, stop=tenacity.stop_after_delay(900))
        def wait_for_loadbalancer(octavia_client, load_balancer_id):
            resp = octavia_client.load_balancer_show(load_balancer_id)
            if resp['provisioning_status'] != 'ACTIVE':
                raise Exception('load balancer has not reached expected '
                                'status: {}'.format(resp))
            return resp
        logging.info('Awaiting loadbalancer to reach provisioning_status '
                     '"ACTIVE"')
        resp = wait_for_loadbalancer(octavia_client, lb_id)
        logging.info(resp)
示例#3
0
    def setUpClass(cls):
        """Run class setup for running Neutron Openvswitch tests."""
        super(NeutronOpenvSwitchTest, cls).setUpClass()

        # set up client
        cls.neutron_client = (
            openstack_utils.get_neutron_session_client(cls.keystone_session))
示例#4
0
    def test_vm_creation(self):
        """Tests to launch a cirros image."""
        cli_utils.setup_logging()
        keystone_session = openstack_utils.get_overcloud_keystone_session()
        # Retrieve necessary clients
        nova_client = openstack_utils.get_nova_session_client(keystone_session)
        neutron_client = openstack_utils.get_neutron_session_client(
            keystone_session)

        image = nova_client.glance.find_image("cirros")
        flavor = nova_client.flavors.find(name="m1.small")
        networks = neutron_client.list_networks(name=net_name)
        if len(networks['networks']) == 0:
            raise Exception('Network {} has not been created'.format(net_name))
        nics = [{'net-id': networks['networks'][0]['id']}]
        # Launch instance.
        logging.info('Launching instance {}'.format(vm_name))
        instance = nova_client.servers.create(name=vm_name,
                                              image=image,
                                              flavor=flavor,
                                              nics=nics)

        # Test Instance is ready.
        logging.info('Checking instance is active')
        openstack_utils.resource_reaches_status(nova_client.servers,
                                                instance.id,
                                                expected_status='ACTIVE')
示例#5
0
def setup_network():
    cli_utils.setup_logging()
    keystone_session = openstack_utils.get_overcloud_keystone_session()
    # Retrieve necessary clients
    keystone_client = openstack_utils.get_keystone_session_client(
        keystone_session)
    neutron_client = openstack_utils.get_neutron_session_client(
        keystone_session)
    # Retrieve necessary variables
    admin_domain = None
    if openstack_utils.get_keystone_api_version() > 2:
        admin_domain = "admin_domain"

    project_id = openstack_utils.get_project_id(
        keystone_client,
        "admin",
        domain_name=admin_domain,
    )
    # Create simple private network

    project_network = openstack_utils.create_project_network(
        neutron_client, project_id, shared=False, network_type="gre")

    openstack_utils.create_project_subnet(neutron_client,
                                          project_id,
                                          project_network,
                                          private_subnet,
                                          ip_version=4)
    def get_client_and_attempt_operation(self, ip):
        """Attempt to list the networks as a policyd override.

        This operation should pass normally for the demo_user, and fail when
        the rule has been overriden (see the `rule` class variable.

        :param ip: the IP address to get the session against.
        :type ip: str
        :raises: PolicydOperationFailedException if operation fails.
        """
        neutron_client = openstack_utils.get_neutron_session_client(
            self.get_keystone_session_demo_user(ip))
        try:
            # If we are allowed to create networks, this will return something.
            # if the policyd override is present, an exception will be raised
            created_network = neutron_client.create_network(
                {
                    'network': {
                        'name': 'zaza-policyd-test',
                    },
                })
            logging.debug("networks: {}".format(created_network))
            neutron_client.delete_network(created_network['network']['id'])
        except Exception:
            raise PolicydOperationFailedException()
 def __init__(self, prov_net_id=None):
     try:
         cacert = os.path.join(os.environ.get('MOJO_LOCAL_DIR'),
                               'cacert.pem')
         os.stat(cacert)
     except FileNotFoundError:
         cacert = None
     keystone_session = openstack_utils.get_undercloud_keystone_session(
         verify=cacert)
     neutronc = openstack_utils.get_neutron_session_client(
         keystone_session)
     if prov_net_id:
         net = neutronc.list_networks(id=prov_net_id)['networks'][0]
     else:
         net = openstack_utils.get_admin_net(neutronc)
     subnet_id = net['subnets'][0]
     subnet = neutronc.list_subnets(id=subnet_id)['subnets'][0]
     allocation_pools = subnet['allocation_pools']
     self.cidr = subnet['cidr']
     self.highest_assigned = netaddr.IPAddress(allocation_pools[0]['end'])
     # XXX look away now, nothing to see here, move along.
     #     If there is less than 30 free ips in the network after the top
     #     dhcp ip then eat into the top of the dhcp range
     available_ips = []
     for element in list(netaddr.IPNetwork(self.cidr)):
         if element == netaddr.IPAddress(self.highest_assigned) or \
                 available_ips:
             available_ips.append(element)
     if len(available_ips) < 30:
         self.highest_assigned = self.highest_assigned - 30
示例#8
0
    def setUpClass(cls):
        """Run class setup for running Neutron Gateway tests."""
        super(NeutronCreateNetworkTest, cls).setUpClass()
        cls.current_os_release = openstack_utils.get_os_release()

        # set up clients
        cls.neutron_client = (
            openstack_utils.get_neutron_session_client(cls.keystone_session))
示例#9
0
    def setUpClass(cls):
        """Run class setup for running Neutron Gateway tests."""
        super(NeutronGatewayTest, cls).setUpClass()
        cls.services = cls._get_services()

        # set up clients
        cls.neutron_client = (
            openstack_utils.get_neutron_session_client(cls.keystone_session))
示例#10
0
def centralized_fip_network():
    """Create network with centralized router for connecting lb and fips.

    There are currently a few outstanding upstream issues with connecting a
    Octavia loadbalancer to the outside world through a Floating IP when used
    in conjunction with Neutron DVR [0][1][2][3][4][5].

    Although there are some fixes provided in the referenced material, the
    current implementation still show issues and appearas to limit how we can
    model a DVR deployment.

    A approach to work around this is to create a separate non-distributed
    network for hosting the load balancer VIP and connecting it to a FIP.

    The payload- and loadbalancer- instances can stay in a distributed
    network, only the VIP must be in a non-distributed network.
    (although the actual hosting of said router can be on a compute host
    acting as a "centralized" snat router in a DVR deployment.)

    0: https://bit.ly/30LgX4T
    1: https://bugs.launchpad.net/neutron/+bug/1583694
    2: https://bugs.launchpad.net/neutron/+bug/1667877
    3: https://review.opendev.org/#/c/437970/
    4: https://review.opendev.org/#/c/437986/
    5: https://review.opendev.org/#/c/466434/
    """
    keystone_session = openstack.get_overcloud_keystone_session()
    neutron_client = openstack.get_neutron_session_client(keystone_session)

    resp = neutron_client.create_network(
        {'network': {
            'name': 'private_lb_fip_network'
        }})
    network = resp['network']
    resp = neutron_client.create_subnet({
        'subnets': [
            {
                'name': 'private_lb_fip_subnet',
                'network_id': network['id'],
                'ip_version': 4,
                'cidr': '10.42.0.0/24',
            },
        ],
    })
    subnet = resp['subnets'][0]
    resp = neutron_client.create_router({
        'router': {
            'name': 'lb_fip_router',
            'external_gateway_info': {
                'network_id': openstack.get_net_uuid(neutron_client,
                                                     'ext_net'),
            },
            'distributed': False,
        },
    })
    router = resp['router']
    neutron_client.add_interface_router(router['id'],
                                        {'subnet_id': subnet['id']})
示例#11
0
def setup_gateway_ext_port(network_config,
                           keystone_session=None,
                           limit_gws=None,
                           use_juju_wait=True):
    """Perform setup external port on Neutron Gateway.

    For OpenStack on OpenStack scenarios.

    :param network_config: Network configuration dictionary
    :type network_config: dict
    :param keystone_session: Keystone session object for undercloud
    :type keystone_session: keystoneauth1.session.Session object
    :param limit_gws: Limit the number of gateways that get a port attached
    :type limit_gws: Optional[int]
    :param use_juju_wait: Use juju wait (default True) for model to settle
    :type use_juju_wait: boolean
    :returns: None
    :rtype: None
    """
    # If a session has not been provided, acquire one
    if not keystone_session:
        keystone_session = openstack_utils.get_undercloud_keystone_session()

    # Get authenticated clients
    nova_client = openstack_utils.get_nova_session_client(keystone_session)
    neutron_client = openstack_utils.get_neutron_session_client(
        keystone_session)

    # Add an interface to the neutron-gateway units and tell juju to use it
    # as the external port.
    if "net_id" in network_config.keys():
        net_id = network_config["net_id"]
    else:
        net_id = None

    try:
        # If we're using netplan, we need to add the new interface to the guest
        current_release = openstack_utils.get_os_release()
        bionic_queens = openstack_utils.get_os_release('bionic_queens')
        if current_release >= bionic_queens:
            logging.warn("Adding second interface for dataport to guest "
                         "netplan for bionic-queens and later")
            add_dataport_to_netplan = True
        else:
            add_dataport_to_netplan = False
    except zaza.openstack.utilities.exceptions.ApplicationNotFound:
        # The setup_gateway_ext_port helper may be used with non-OpenStack
        # workloads.
        add_dataport_to_netplan = False

    logging.info("Configuring network for OpenStack undercloud/provider")
    openstack_utils.configure_gateway_ext_port(
        nova_client,
        neutron_client,
        net_id=net_id,
        add_dataport_to_netplan=add_dataport_to_netplan,
        limit_gws=limit_gws,
        use_juju_wait=use_juju_wait)
def main(argv):
    cli_utils.setup_logging()
    logging.getLogger("urllib3").setLevel(logging.WARNING)
    keystone_session_uc = openstack_utils.get_undercloud_keystone_session()
    under_novac = openstack_utils.get_nova_session_client(keystone_session_uc)

    keystone_session_oc = openstack_utils.get_overcloud_keystone_session()
    clients = {
        'neutron':
        openstack_utils.get_neutron_session_client(keystone_session_oc),
        'nova': openstack_utils.get_nova_session_client(keystone_session_oc),
        'glance': mojo_os_utils.get_glance_session_client(keystone_session_oc),
    }
    image_file = mojo_utils.get_mojo_file('images.yaml')
    image_config = generic_utils.get_yaml_config(image_file)
    image_password = image_config['cirros']['password']
    # Look for existing Cirros guest
    server, ip = get_cirros_server(clients, image_password)
    router = (clients['neutron'].list_routers(
        name='provider-router')['routers'][0])
    l3_agents = clients['neutron'].list_l3_agent_hosting_routers(
        router=router['id'])['agents']
    logging.info('Checking there are multiple L3 agents running tenant router')
    if len(l3_agents) != 2:
        raise Exception('Unexpected number of l3 agents')
    series = os.environ.get("MOJO_SERIES")
    for agent in l3_agents:
        gateway_hostname = agent['host']
        gateway_server = under_novac.servers.find(name=gateway_hostname)
        logging.info('Shutting down neutron gateway {} ({})'.format(
            gateway_hostname, gateway_server.id))
        gateway_server.stop()
        if not check_server_state(
                under_novac, 'SHUTOFF', server_name=gateway_hostname):
            raise Exception('Server failed to reach SHUTOFF state')
        logging.info('Neutron gateway %s has shutdown' % (gateway_hostname))
        logging.info('Checking connectivity to cirros guest')
        if not mojo_os_utils.wait_for_ping(ip, 90):
            raise Exception('Cirros guest not responding to ping')
        if not mojo_os_utils.ssh_test(
                'cirros', ip, server.name, password=image_password):
            raise Exception('Cirros guest issh connection failed')
        logging.info('Starting neutron gateway: ' + gateway_hostname)
        gateway_server.start()
        if not check_server_state(
                under_novac, 'ACTIVE', server_name=gateway_hostname):
            raise Exception('Server failed to reach SHUTOFF state')
        if not check_neutron_agent_states(clients['neutron'],
                                          gateway_hostname):
            raise Exception('Server agents failed to reach active state')
        if series == "xenial":
            logging.info(
                "Concluding tests as rebooting a xenial guest can cause "
                "network interfaces to be renamed which breaks the "
                "gateway")
            return
示例#13
0
    def setup_for_attempt_operation(self, ip):
        """Create a loadbalancer.

        This is necessary so that the attempt is to show the load-balancer and
        this is an operator that the policy can stop.  Unfortunately, octavia,
        whilst it has a policy for just listing load-balancers, unfortunately,
        it doesn't work; whereas showing the load-balancer can be stopped.

        NB this only works if the setup phase of the octavia tests have been
        completed.

        :param ip: the ip of for keystone.
        :type ip: str
        """
        logging.info("Setting up loadbalancer.")
        auth = openstack_utils.get_overcloud_auth(address=ip)
        sess = openstack_utils.get_keystone_session(auth)

        octavia_client = openstack_utils.get_octavia_session_client(sess)
        neutron_client = openstack_utils.get_neutron_session_client(sess)

        if openstack_utils.dvr_enabled():
            network_name = 'private_lb_fip_network'
        else:
            network_name = 'private'
        resp = neutron_client.list_networks(name=network_name)

        vip_subnet_id = resp['networks'][0]['subnets'][0]

        res = octavia_client.load_balancer_create(
            json={
                'loadbalancer': {
                    'description': 'Created by Zaza',
                    'admin_state_up': True,
                    'vip_subnet_id': vip_subnet_id,
                    'name': 'zaza-lb-0',
                }})
        self.lb_id = res['loadbalancer']['id']
        # now wait for it to get to the active state

        @tenacity.retry(wait=tenacity.wait_fixed(1),
                        reraise=True, stop=tenacity.stop_after_delay(900))
        def wait_for_lb_resource(client, resource_id):
            resp = client.load_balancer_show(resource_id)
            logging.info(resp['provisioning_status'])
            assert resp['provisioning_status'] == 'ACTIVE', (
                'load balancer resource has not reached '
                'expected provisioning status: {}'
                .format(resp))
            return resp

        logging.info('Awaiting loadbalancer to reach provisioning_status '
                     '"ACTIVE"')
        resp = wait_for_lb_resource(octavia_client, self.lb_id)
        logging.info(resp)
        logging.info("Setup loadbalancer complete.")
示例#14
0
 def get_port_ips(self):
     """Extract IP info from Neutron ports tagged with charm-octavia."""
     keystone_session = openstack_utils.get_overcloud_keystone_session()
     neutron_client = openstack_utils.get_neutron_session_client(
         keystone_session)
     resp = neutron_client.list_ports(tags='charm-octavia')
     neutron_ip_list = []
     for port in resp['ports']:
         for ip_info in port['fixed_ips']:
             neutron_ip_list.append(ip_info['ip_address'])
     return neutron_ip_list
示例#15
0
    def setUpClass(cls):
        """Run class setup for running Neutron Openvswitch tests."""
        super(NeutronOpenvSwitchTest, cls).setUpClass(cls)

        cls.compute_unit = zaza.model.get_units('nova-compute')[0]
        cls.neutron_api_unit = zaza.model.get_units('neutron-api')[0]
        cls.n_ovs_unit = zaza.model.get_units('neutron-openvswitch')[0]

        # set up client
        cls.neutron_client = (openstack_utils.get_neutron_session_client(
            cls.keystone_session))
示例#16
0
def setup_sdn_provider_vlan(network_config, keystone_session=None):
    """Perform setup for Software Defined Network, specifically a provider VLAN.

    :param network_config: Network configuration settings dictionary
    :type network_config: dict
    :param keystone_session: Keystone session object for overcloud
    :type keystone_session: keystoneauth1.session.Session object
    :returns: None
    :rtype: None
    """
    # If a session has not been provided, acquire one
    if not keystone_session:
        keystone_session = openstack_utils.get_overcloud_keystone_session()

    # Get authenticated clients
    keystone_client = openstack_utils.get_keystone_session_client(
        keystone_session)
    neutron_client = openstack_utils.get_neutron_session_client(
        keystone_session)

    admin_domain = None
    if openstack_utils.get_keystone_api_version() > 2:
        admin_domain = "admin_domain"
    # Resolve the project name from the overcloud openrc into a project id
    project_id = openstack_utils.get_project_id(
        keystone_client,
        "admin",
        domain_name=admin_domain,
    )

    logging.info("Configuring VLAN provider network")
    # Create the external network
    provider_vlan_network = openstack_utils.create_provider_network(
        neutron_client,
        project_id,
        net_name=network_config["provider_vlan_net_name"],
        external=False,
        shared=True,
        network_type='vlan',
        vlan_id=network_config["provider_vlan_id"])
    provider_vlan_subnet = openstack_utils.create_provider_subnet(
        neutron_client,
        project_id,
        provider_vlan_network,
        network_config["provider_vlan_subnet_name"],
        cidr=network_config["provider_vlan_cidr"],
        dhcp=True)
    openstack_utils.plug_subnet_into_router(neutron_client,
                                            network_config["router_name"],
                                            provider_vlan_network,
                                            provider_vlan_subnet)
    openstack_utils.add_neutron_secgroup_rules(neutron_client, project_id)
示例#17
0
def test_bgp_routes(peer_application_name="quagga", keystone_session=None):
    """Test BGP routes.

    :param peer_application_name: String name of BGP peer application
    :type peer_application_name: string
    :param keystone_session: Keystone session object for overcloud
    :type keystone_session: keystoneauth1.session.Session object
    :raises: AssertionError if expected BGP routes are not found
    :returns: None
    :rtype: None
    """
    # If a session has not been provided, acquire one
    if not keystone_session:
        keystone_session = openstack_utils.get_overcloud_keystone_session()

    # Get authenticated clients
    neutron_client = openstack_utils.get_neutron_session_client(
        keystone_session)

    # Get the peer unit
    peer_unit = model.get_units(peer_application_name)[0].entity_id

    # Get expected advertised routes
    private_cidr = neutron_client.list_subnets(
        name="private_subnet")["subnets"][0]["cidr"]
    floating_ip_cidr = "{}/32".format(
        neutron_client.list_floatingips()["floatingips"][0]
        ["floating_ip_address"])

    # This test may run immediately after configuration. It may take time for
    # routes to propogate via BGP. Do a binary backoff.
    @tenacity.retry(wait=tenacity.wait_exponential(multiplier=1, max=60),
                    reraise=True,
                    stop=tenacity.stop_after_attempt(10))
    def _assert_cidr_in_peer_routing_table(peer_unit, cidr):
        logging.debug("Checking for {} on BGP peer {}".format(cidr, peer_unit))
        # Run show ip route bgp on BGP peer
        routes = juju_utils.remote_run(
            peer_unit, remote_cmd='vtysh -c "show ip route bgp"')
        logging.info(routes)
        assert cidr in routes, (
            "CIDR, {}, not found in BGP peer's routing table: {}".format(
                cidr, routes))

    _assert_cidr_in_peer_routing_table(peer_unit, private_cidr)
    logging.info(
        "Private subnet CIDR, {}, found in routing table".format(private_cidr))
    _assert_cidr_in_peer_routing_table(peer_unit, floating_ip_cidr)
    logging.info("Floating IP CIDR, {}, found in routing table".format(
        floating_ip_cidr))
示例#18
0
    def setUpClass(cls, application_name='neutron-gateway', model_alias=None):
        """Run class setup for running Neutron Gateway tests."""
        super(NeutronGatewayShowActionsTest,
              cls).setUpClass(application_name, model_alias)
        # set up clients
        cls.neutron_client = (openstack_utils.get_neutron_session_client(
            cls.keystone_session))

        # Loadbalancer tests not supported on Train and above and on
        # releases Mitaka and below
        current = openstack_utils.get_os_release()
        bionic_train = openstack_utils.get_os_release('bionic_train')
        xenial_mitaka = openstack_utils.get_os_release('xenial_mitaka')
        cls.SKIP_LBAAS_TESTS = not (xenial_mitaka > current < bionic_train)
示例#19
0
 def setUpClass(cls):
     """Run class setup for running Neutron API Networking tests."""
     cls.keystone_session = (
         openstack_utils.get_overcloud_keystone_session())
     cls.nova_client = (
         openstack_utils.get_nova_session_client(cls.keystone_session))
     cls.neutron_client = (
         openstack_utils.get_neutron_session_client(cls.keystone_session))
     # NOTE(fnordahl): in the event of a test failure we do not want to run
     # tear down code as it will make debugging a problem virtually
     # impossible.  To alleviate each test method will set the
     # `run_tearDown` instance variable at the end which will let us run
     # tear down only when there were no failure.
     cls.run_tearDown = False
示例#20
0
def disable_ohm_port_security():
    """Disable port security on the health manager ports on octavia units."""
    keystone_session = openstack.get_overcloud_keystone_session()
    neutron_client = openstack.get_neutron_session_client(keystone_session)
    ports = [
        p for p in neutron_client.list_ports()['ports']
        if re.match('octavia-health-manager-.*-listen-port', p['name'])
    ]
    for port in ports:
        neutron_client.update_port(
            port['id'],
            {'port': {
                'port_security_enabled': False,
                'security_groups': []
            }})
示例#21
0
    def test_tunnel_datapath(self):
        """From ports list, connect to unit in one end, ping other end(s)."""
        keystone_session = openstack_utils.get_overcloud_keystone_session()
        neutron_client = openstack_utils.get_neutron_session_client(
            keystone_session)

        resp = neutron_client.list_ports()
        ports = resp['ports']
        host_port = {}
        for port in ports:
            if (port['device_owner'].startswith('network:')
                    or port['device_owner'].startswith('compute:')):
                continue
            host_port[port['binding:host_id']] = port

        for unit in zaza.model.get_units('neutron-openvswitch'):
            result = zaza.model.run_on_unit(unit.entity_id, 'hostname')
            hostname = result['Stdout'].rstrip()
            if hostname not in host_port:
                # no port bound to this host, skip
                continue
            # get interface name from unit OVS data
            ovs_interface = json.loads(
                zaza.model.run_on_unit(
                    unit.entity_id, 'ovs-vsctl -f json find Interface '
                    'external_ids:iface-id={}'.format(
                        host_port[hostname]['id']))['Stdout'])
            for (idx, heading) in enumerate(ovs_interface['headings']):
                if heading == 'name':
                    break
            else:
                raise Exception('Unable to find interface name from OVS')
            interface_name = ovs_interface['data'][0][idx]

            ip_unit = zaza.model.run_on_unit(
                unit.entity_id, 'ip addr show dev {}'.format(interface_name))
            for other_host in (set(host_port) - set([hostname])):
                for ip_info in host_port[other_host]['fixed_ips']:
                    logging.info('Local IP info: "{}"'.format(ip_unit))
                    logging.info('PING "{}" --> "{}"...'.format(
                        hostname, other_host))
                    result = zaza.model.run_on_unit(
                        unit.entity_id,
                        'ping -c 3 {}'.format(ip_info['ip_address']))
                    logging.info(result['Stdout'])
                    if result['Code'] == '1':
                        raise Exception('FAILED')
def setup_gateway_ext_port(network_config, keystone_session=None):
    """Perform setup external port on Neutron Gateway.

    For OpenStack on OpenStack scenarios.

    :param network_config: Network configuration dictionary
    :type network_config: dict
    :param keystone_session: Keystone session object for undercloud
    :type keystone_session: keystoneauth1.session.Session object
    :returns: None
    :rtype: None
    """
    # If a session has not been provided, acquire one
    if not keystone_session:
        keystone_session = openstack_utils.get_undercloud_keystone_session()

    # Get authenticated clients
    nova_client = openstack_utils.get_nova_session_client(keystone_session)
    neutron_client = openstack_utils.get_neutron_session_client(
        keystone_session)

    # Add an interface to the neutron-gateway units and tell juju to use it
    # as the external port.
    if "net_id" in network_config.keys():
        net_id = network_config["net_id"]
    else:
        net_id = None

    # If we're using netplan, we need to add the new interface to the guest
    current_release = openstack_utils.get_os_release()
    bionic_queens = openstack_utils.get_os_release('bionic_queens')
    if current_release >= bionic_queens:
        logging.warn("Adding second interface for dataport to guest netplan "
                     "for bionic-queens and later")
        add_dataport_to_netplan = True
    else:
        add_dataport_to_netplan = False

    logging.info("Configuring network for OpenStack undercloud/provider")
    openstack_utils.configure_gateway_ext_port(
        nova_client,
        neutron_client,
        dvr_mode=network_config.get("dvr_enabled", False),
        net_id=net_id,
        add_dataport_to_netplan=add_dataport_to_netplan)
示例#23
0
def prepare_payload_instance():
    """Prepare a instance we can use as payload test."""
    session = openstack.get_overcloud_keystone_session()
    keystone = openstack.get_keystone_session_client(session)
    neutron = openstack.get_neutron_session_client(session)
    project_id = openstack.get_project_id(keystone,
                                          'admin',
                                          domain_name='admin_domain')
    openstack.add_neutron_secgroup_rules(neutron, project_id,
                                         [{
                                             'protocol': 'tcp',
                                             'port_range_min': '80',
                                             'port_range_max': '80',
                                             'direction': 'ingress'
                                         }])
    zaza.openstack.configure.guest.launch_instance(
        glance_setup.LTS_IMAGE_NAME,
        userdata='#cloud-config\npackages:\n - apache2\n')
def main(argv):
    cli_utils.setup_logging()
    parser = argparse.ArgumentParser()
    parser.add_argument("router", nargs="?")
    options = parser.parse_args()
    router_name = cli_utils.parse_arg(options, 'router')
    try:
        cacert = os.path.join(os.environ.get('MOJO_LOCAL_DIR'), 'cacert.pem')
        os.stat(cacert)
    except FileNotFoundError:
        cacert = None
    keystone_session = openstack_utils.get_overcloud_keystone_session(
        verify=cacert)
    neutron_client = openstack_utils.get_neutron_session_client(
        keystone_session)
    router = neutron_client.list_routers(name=router_name)['routers'][0]['id']
    l3_agent = neutron_client.list_l3_agent_hosting_routers(router=router)
    hosting_machine = l3_agent['agents'][0]['host']
    mojo_utils.delete_machine(hosting_machine)
示例#25
0
    def test_gateway_failure(self):
        """Validate networking in the case of a gateway failure."""
        instance_1, instance_2 = self.retrieve_guests()
        if not all([instance_1, instance_2]):
            self.launch_guests()
            instance_1, instance_2 = self.retrieve_guests()
        self.check_connectivity(instance_1, instance_2)

        routers = self.neutron_client.list_routers(
            name='provider-router')['routers']
        assert len(routers) == 1, "Unexpected router count {}".format(
            len(routers))
        provider_router = routers[0]
        l3_agents = self.neutron_client.list_l3_agent_hosting_routers(
            router=provider_router['id'])['agents']
        logging.info(
            'Checking there are multiple L3 agents running tenant router')
        assert len(l3_agents) == 2, "Unexpected l3 agent count {}".format(
            len(l3_agents))
        uc_ks_session = openstack_utils.get_undercloud_keystone_session()
        uc_nova_client = openstack_utils.get_nova_session_client(uc_ks_session)
        uc_neutron_client = openstack_utils.get_neutron_session_client(
            uc_ks_session)
        for agent in l3_agents:
            gateway_hostname = agent['host']
            gateway_server = uc_nova_client.servers.find(name=gateway_hostname)
            logging.info("Shutting down {}".format(gateway_hostname))
            gateway_server.stop()
            self.check_server_state(
                uc_nova_client,
                'SHUTOFF',
                server_name=gateway_hostname)
            self.check_connectivity(instance_1, instance_2)
            gateway_server.start()
            self.check_server_state(
                uc_nova_client,
                'ACTIVE',
                server_name=gateway_hostname)
            self.check_neutron_agent_up(
                uc_neutron_client,
                gateway_hostname)
            self.check_connectivity(instance_1, instance_2)
示例#26
0
    def setUpClass(cls):
        """Run class setup for running LBaaSv2 service tests."""
        super(LBAASv2Test, cls).setUpClass()

        cls.keystone_session = openstack_utils.get_overcloud_keystone_session()
        cls.neutron_client = openstack_utils.get_neutron_session_client(
            cls.keystone_session)
        cls.octavia_client = openstack_utils.get_octavia_session_client(
            cls.keystone_session)

        # NOTE(fnordahl): in the event of a test failure we do not want to run
        # tear down code as it will make debugging a problem virtually
        # impossible.  To alleviate each test method will set the
        # `run_tearDown` instance variable at the end which will let us run
        # tear down only when there were no failure.
        cls.run_tearDown = False
        # List of load balancers created by this test
        cls.loadbalancers = []
        # LIst of floating IPs created by this test
        cls.fips = []
示例#27
0
    def tearDownClass(cls):
        """Run class teardown after tests finished."""
        # Cleanup Nova servers
        logging.info('Cleaning up test Nova servers')
        fips_reservations = []
        for vm in cls.nova_client.servers.list():
            fips_reservations += neutron_tests.floating_ips_from_instance(vm)
            vm.delete()
            openstack_utils.resource_removed(
                cls.nova_client.servers,
                vm.id,
                msg="Waiting for the Nova VM {} to be deleted".format(vm.name))

        # Delete FiPs reservations
        logging.info('Cleaning up test FiPs reservations')
        neutron = openstack_utils.get_neutron_session_client(
            session=cls.keystone_session)
        for fip in neutron.list_floatingips()['floatingips']:
            if fip['floating_ip_address'] in fips_reservations:
                neutron.delete_floatingip(fip['id'])

        # Cleanup Manila shares
        logging.info('Cleaning up test shares')
        for share in cls.manila_client.shares.list():
            share.delete()
            openstack_utils.resource_removed(
                cls.manila_client.shares,
                share.id,
                msg="Waiting for the Manila share {} to be deleted".format(
                    share.name))

        # Cleanup test Manila share servers (spawned by the driver when DHSS
        # is enabled).
        logging.info('Cleaning up test shares servers (if found)')
        for server in cls.manila_client.share_servers.list():
            server.delete()
            openstack_utils.resource_removed(
                cls.manila_client.share_servers,
                server.id,
                msg="Waiting for the share server {} to be deleted".format(
                    server.id))
示例#28
0
    def setUpClass(cls):
        """Run class setup for running Neutron Openvswitch tests."""
        super(NeutronOpenvSwitchTest, cls).setUpClass()

        cls.current_os_release = openstack_utils.get_os_release()

        cls.compute_unit = zaza.model.get_units('nova-compute')[0]
        cls.neutron_api_unit = zaza.model.get_units('neutron-api')[0]
        cls.n_ovs_unit = zaza.model.get_units('neutron-openvswitch')[0]

        cls.bionic_stein = openstack_utils.get_os_release('bionic_stein')
        cls.trusty_mitaka = openstack_utils.get_os_release('trusty_mitaka')

        if cls.current_os_release >= cls.bionic_stein:
            cls.pgrep_full = True
        else:
            cls.pgrep_full = False

        # set up client
        cls.neutron_client = (openstack_utils.get_neutron_session_client(
            cls.keystone_session))
示例#29
0
    def get_client_and_attempt_operation(self, ip):
        """Attempt to list the networks as a policyd override.

        This operation should pass normally for the demo_user, and fail when
        the rule has been overriden (see the `rule` class variable.

        :param ip: the IP address to get the session against.
        :type ip: str
        :raises: PolicydOperationFailedException if operation fails.
        """
        neutron_client = openstack_utils.get_neutron_session_client(
            self.get_keystone_session_demo_user(ip))
        try:
            # If we are allowed to list networks, this will return something.
            # if the policyd override is present, then no error is generated,
            # but no networks are returned.
            networks = neutron_client.list_networks()
            logging.debug("networks: {}".format(networks))
            if len(networks['networks']) == 0:
                raise PolicydOperationFailedException()
        except Exception:
            raise PolicydOperationFailedException()
示例#30
0
def add_neutron_config(ctxt, keystone_session):
    """Add neutron config to context.

    :param ctxt: Context dictionary
    :type ctxt: dict
    :param keystone_session: keystoneauth1.session.Session object
    :type: keystoneauth1.session.Session
    :returns: None
    :rtype: None
    """
    current_release = openstack_utils.get_os_release()
    focal_ussuri = openstack_utils.get_os_release('focal_ussuri')
    neutron_client = openstack_utils.get_neutron_session_client(
        keystone_session)
    net = neutron_client.find_resource("network", "ext_net")
    ctxt['ext_net'] = net['id']
    router = neutron_client.find_resource("router", "provider-router")
    ctxt['provider_router_id'] = router['id']
    # For focal+ with OVN, we use the same settings as upstream gate.
    # This is because the l3_agent_scheduler extension is only
    # applicable for OVN when conventional layer-3 agent enabled:
    # https://docs.openstack.org/networking-ovn/2.0.1/features.html
    # This enables test_list_show_extensions to run successfully.
    if current_release >= focal_ussuri:
        extensions = ('address-scope,agent,allowed-address-pairs,'
                      'auto-allocated-topology,availability_zone,'
                      'binding,default-subnetpools,external-net,'
                      'extra_dhcp_opt,multi-provider,net-mtu,'
                      'network_availability_zone,network-ip-availability,'
                      'port-security,provider,quotas,rbac-address-scope,'
                      'rbac-policies,standard-attr-revisions,security-group,'
                      'standard-attr-description,subnet_allocation,'
                      'standard-attr-tag,standard-attr-timestamp,trunk,'
                      'quota_details,router,extraroute,ext-gw-mode,'
                      'fip-port-details,pagination,sorting,project-id,'
                      'dns-integration,qos')
        ctxt['neutron_api_extensions'] = extensions
    else:
        ctxt['neutron_api_extensions'] = 'all'