def main(argv):
    cli_utils.setup_logging()
    overcloud_novarc = openstack_utils.get_overcloud_auth()
    user_file = mojo_utils.get_mojo_file('keystone_users.yaml')
    user_config = generic_utils.get_yaml_config(user_file)
    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)
    keystone_client = openstack_utils.get_keystone_session_client(
        keystone_session)
    if overcloud_novarc.get('API_VERSION', 2) == 2:
        projects = [user['project'] for user in user_config]
        mojo_os_utils.project_create(keystone_client, projects)
        mojo_os_utils.user_create_v2(keystone_client, user_config)
        # TODO validate this works without adding roles
        # mojo_os_utils.add_users_to_roles(keystone_client, user_config)
    else:
        for user in user_config:
            mojo_os_utils.domain_create(keystone_client, [user['domain']])
            mojo_os_utils.project_create(keystone_client, [user['project']],
                                         user['domain'])
        mojo_os_utils.user_create_v3(keystone_client, user_config)
Beispiel #2
0
 def setUpClass(cls):
     """Run setup for Series Upgrades."""
     cli_utils.setup_logging()
     cls.from_series = None
     cls.to_series = None
     cls.workaround_script = None
     cls.files = []
Beispiel #3
0
def basic_overcloud_network():
    """Run setup for neutron networking.

    Configure the following:
        The overcloud network using subnet pools

    """
    cli_utils.setup_logging()

    # Get network configuration settings
    network_config = {}
    # Declared overcloud settings
    network_config.update(OVERCLOUD_NETWORK_CONFIG)
    # Default undercloud settings
    network_config.update(DEFAULT_UNDERCLOUD_NETWORK_CONFIG)
    # Environment specific settings
    network_config.update(generic_utils.get_undercloud_env_vars())
    # Deployed model settings
    if (model.get_application_config('neutron-api').get('enable-dvr').get(
            'value')):
        network_config.update({"dvr_enabled": True})

    # Get keystone session
    keystone_session = openstack_utils.get_overcloud_keystone_session()

    # Handle network for Openstack-on-Openstack scenarios
    if juju_utils.get_provider_type() == "openstack":
        undercloud_ks_sess = openstack_utils.get_undercloud_keystone_session()
        network.setup_gateway_ext_port(network_config,
                                       keystone_session=undercloud_ks_sess)

    # Confugre the overcloud network
    network.setup_sdn(network_config, keystone_session=keystone_session)
Beispiel #4
0
def create_bm_flavors(nova_client=None):
    """Create baremetal flavors.

    :param nova_client: Authenticated nova client
    :type nova_client: novaclient.v2.client.Client
    """
    if not nova_client:
        keystone_session = openstack_utils.get_overcloud_keystone_session()
        nova_client = openstack_utils.get_nova_session_client(keystone_session)
    cli_utils.setup_logging()
    names = [flavor.name for flavor in nova_client.flavors.list()]
    # Disable scheduling based on standard flavor properties
    default_properties = {
        "resources:VCPU": 0,
        "resources:MEMORY_MB": 0,
        "resources:DISK_GB": 0,
    }
    for flavor in FLAVORS.keys():
        if flavor not in names:
            properties = copy.deepcopy(default_properties)
            properties.update(FLAVORS[flavor]["properties"])
            bm_flavor = nova_client.flavors.create(
                name=flavor,
                ram=FLAVORS[flavor]['ram'],
                vcpus=FLAVORS[flavor]['vcpus'],
                disk=FLAVORS[flavor]['disk'],
                flavorid=FLAVORS[flavor]['flavorid'])
            bm_flavor.set_keys(properties)
Beispiel #5
0
def main(argv):
    cli_utils.setup_logging()
    switch_map = {
        'neutron-gateway':
        'local:{}/{}'.format(os.environ['MOJO_SERIES'], 'neutron-gateway')
    }
    mojo_utils.upgrade_all_services(switch=switch_map)
Beispiel #6
0
def create_flavors(nova_client=None):
    """Create basic flavors.

    :param nova_client: Authenticated nova client
    :type nova_client: novaclient.v2.client.Client
    """
    if not nova_client:
        keystone_session = openstack_utils.get_overcloud_keystone_session()
        nova_client = openstack_utils.get_nova_session_client(keystone_session)
    cli_utils.setup_logging()

    for attempt in Retrying(stop=stop_after_attempt(3),
                            wait=wait_exponential(multiplier=1, min=2,
                                                  max=10)):
        with attempt:
            existing_flavors = nova_client.flavors.list()

    names = [flavor.name for flavor in existing_flavors]
    for flavor in nova_utils.FLAVORS.keys():
        if flavor not in names:
            nova_flavor = nova_client.flavors.create(
                name=flavor,
                ram=nova_utils.FLAVORS[flavor]['ram'],
                vcpus=nova_utils.FLAVORS[flavor]['vcpus'],
                disk=nova_utils.FLAVORS[flavor]['disk'],
                flavorid=nova_utils.FLAVORS[flavor]['flavorid'])
            if 'extra-specs' in nova_utils.FLAVORS[flavor]:
                nova_flavor.set_keys(nova_utils.FLAVORS[flavor]['extra-specs'])
Beispiel #7
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')
Beispiel #8
0
def main(argv):
    cli_utils.setup_logging()
    parser = argparse.ArgumentParser()
    parser.add_argument('-d',
                        '--domain_name',
                        help='DNS Domain Name. '
                        'Must end in a .',
                        default='mojo.serverstack.')
    options = parser.parse_args()
    domain_name = cli_utils.parse_arg(options, 'domain_name')

    os_version = openstack_utils.get_current_os_versions(
        'keystone')['keystone']
    if os_version >= 'mitaka':
        designate_api = '2'
    else:
        designate_api = '1'
    keystone_session = openstack_utils.get_overcloud_keystone_session()

    nova_client = openstack_utils.get_nova_session_client(keystone_session)
    des_client = mojo_os_utils.get_designate_session_client(
        keystone_session, all_tenants=True, client_version=designate_api)
    for server in nova_client.servers.list():
        for addr_info in server.addresses['private']:
            if addr_info['OS-EXT-IPS:type'] == 'floating':
                mojo_os_utils.check_dns_entry(
                    des_client, addr_info['addr'], domain_name,
                    '{}.{}'.format(server.name, domain_name))
Beispiel #9
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)
Beispiel #10
0
def basic_overcloud_network(limit_gws=None):
    """Run setup for neutron networking.

    Configure the following:
        The overcloud network using subnet pools

    :param limit_gws: Limit the number of gateways that get a port attached
    :type limit_gws: int
    """
    cli_utils.setup_logging()

    # Get network configuration settings
    network_config = {}
    # Declared overcloud settings
    network_config.update(OVERCLOUD_NETWORK_CONFIG)
    # Default undercloud settings
    network_config.update(DEFAULT_UNDERCLOUD_NETWORK_CONFIG)
    # Environment specific settings
    network_config.update(generic_utils.get_undercloud_env_vars())

    # Get keystone session
    keystone_session = openstack_utils.get_overcloud_keystone_session()

    # Perform undercloud and charm setup for network plumbing
    undercloud_and_charm_setup(limit_gws=limit_gws)

    # Configure the overcloud network
    network.setup_sdn(network_config, keystone_session=keystone_session)
Beispiel #11
0
def basic_overcloud_network(limit_gws=None):
    """Run setup for neutron networking.

    Configure the following:
        The overcloud network using subnet pools

    :param limit_gws: Limit the number of gateways that get a port attached
    :type limit_gws: int
    """
    cli_utils.setup_logging()

    # Get network configuration settings
    network_config = {}
    # Declared overcloud settings
    network_config.update(OVERCLOUD_NETWORK_CONFIG)
    # Default undercloud settings
    network_config.update(DEFAULT_UNDERCLOUD_NETWORK_CONFIG)
    # Environment specific settings
    network_config.update(generic_utils.get_undercloud_env_vars())

    # Get keystone session
    keystone_session = openstack_utils.get_overcloud_keystone_session()

    # Handle network for Openstack-on-Openstack scenarios
    if juju_utils.get_provider_type() == "openstack":
        undercloud_ks_sess = openstack_utils.get_undercloud_keystone_session()
        network.setup_gateway_ext_port(network_config,
                                       keystone_session=undercloud_ks_sess,
                                       limit_gws=None)

    # Confugre the overcloud network
    network.setup_sdn(network_config, keystone_session=keystone_session)
def main(argv):
    cli_utils.setup_logging()
    try:
        cacert = os.path.join(os.environ.get('MOJO_LOCAL_DIR'), 'cacert.pem')
        os.stat(cacert)
    except FileNotFoundError:
        cacert = None
    session = openstack_utils.get_overcloud_keystone_session(verify=cacert)
    glance_client = mojo_os_utils.get_glance_session_client(session)
    current_images = mojo_os_utils.get_images_list(glance_client)
    image_file = mojo_utils.get_mojo_file('images.yaml')
    image_config = generic_utils.get_yaml_config(image_file)
    cache_dir = '/tmp/img_cache'
    for image in image_config.keys():
        if image_config[image]['glance_name'] in current_images:
            logging.warning('Skipping %s it is already in'
                            'glance' % (image_config[image]['glance_name']))
            continue
        image_name = image_config[image]['url'].split('/')[-1]
        if os.path.exists(cache_dir + '/' + image_name):
            local_file = cache_dir + '/' + image_name
        else:
            local_file = mojo_os_utils.download_image(
                image_config[image]['url'])
        mojo_os_utils.upload_image(glance_client, local_file,
                                   image_config[image]['glance_name'],
                                   image_config[image]['visibility'],
                                   image_config[image]['disk_format'],
                                   image_config[image]['container_format'])
def main(argv):
    cli_utils.setup_logging()
    parser = argparse.ArgumentParser()
    parser.add_argument("services", nargs="*")
    options = parser.parse_args()
    services = cli_utils.parse_arg(options, 'services', multiargs=True)
    for service in services:
        mojo_utils.upgrade_service(service)
def main(argv):
    cli_utils.setup_logging()
    parser = argparse.ArgumentParser()
    parser.add_argument("application", nargs="*")
    options = parser.parse_args()
    unit_args = cli_utils.parse_arg(options, 'application', multiargs=True)
    for application in unit_args:
        mojo_utils.delete_application(application)
Beispiel #15
0
def main(argv):
    cli_utils.setup_logging()
    parser = argparse.ArgumentParser()
    parser.add_argument("units", nargs="*")
    options = parser.parse_args()
    unit_args = mojo_utils.parse_mojo_arg(options, 'units', multiargs=True)
    for unitreq in unit_args:
        service, count = unitreq.split(":")
        mojo_utils.add_unit(service, unit_num=count)
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
def main(argv):
    cli_utils.setup_logging()
    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)
    aodhc = mojo_os_utils.get_aodh_session_client(keystone_session)
    nova_client = openstack_utils.get_nova_session_client(keystone_session)

    servers = nova_client.servers.list()
    assert servers, "No servers available for AODH testing"
    if servers:
        alarm_name = 'mojo_instance_off'
        server = servers[0]
        assert server.status == 'ACTIVE', "Server {} not active".format(
            server.name)
        logging.info('Using server {} for aodh test'.format(server.name))
        server = nova_client.servers.find(name=server.name)
        logging.info('Deleting alarm {} if it exists'.format(alarm_name))
        mojo_os_utils.delete_alarm(aodhc, alarm_name, cache_wait=True)
        logging.info('Creating alarm {}'.format(alarm_name))
        alarm_def = {
            'type': 'event',
            'name': alarm_name,
            'description': 'Instance powered OFF',
            'alarm_actions': ['log://'],
            'ok_actions': ['log://'],
            'insufficient_data_actions': ['log://'],
            'event_rule': {
                'event_type':
                'compute.instance.power_off.*',
                'query': [{
                    'field': 'traits.instance_id',
                    'op': 'eq',
                    'type': 'string',
                    'value': server.id
                }]
            }
        }
        alarm_info = aodhc.alarm.create(alarm_def)
        logging.info('Stopping server {}'.format(server.name))
        server.stop()
        for i in range(10):
            alarm_state = mojo_os_utils.get_alarm_state(
                aodhc, alarm_info['alarm_id'])
            if alarm_state == 'alarm':
                logging.info('Alarm triggered')
                break
            else:
                time.sleep(15)
        else:
            raise Exception("Alarm failed to trigger")
Beispiel #18
0
def keystone_federation_setup(federated_domain=FEDERATED_DOMAIN,
                              federated_group=FEDERATED_GROUP,
                              idp_name=IDP,
                              idp_remote_id=REMOTE_ID):
    """Configure Keystone Federation."""
    cli_utils.setup_logging()
    keystone_session = openstack_utils.get_overcloud_keystone_session()
    keystone_client = openstack_utils.get_keystone_session_client(
        keystone_session)

    try:
        domain = keystone_client.domains.find(name=federated_domain)
    except keystoneauth1.exceptions.http.NotFound:
        domain = keystone_client.domains.create(federated_domain,
                                                description="Federated Domain",
                                                enabled=True)

    try:
        group = keystone_client.groups.find(name=federated_group,
                                            domain=domain)
    except keystoneauth1.exceptions.http.NotFound:
        group = keystone_client.groups.create(federated_group,
                                              domain=domain,
                                              enabled=True)

    role = keystone_client.roles.find(name=MEMBER)
    keystone_client.roles.grant(role, group=group, domain=domain)

    try:
        idp = keystone_client.federation.identity_providers.get(idp_name)
    except keystoneauth1.exceptions.http.NotFound:
        idp = keystone_client.federation.identity_providers.create(
            idp_name,
            remote_ids=[idp_remote_id],
            domain_id=domain.id,
            enabled=True)

    JSON_RULES = json.loads(
        MAP_TEMPLATE.format(domain_id=domain.id,
                            group_id=group.id,
                            role_name=MEMBER))

    map_name = "{}_mapping".format(idp_name)
    try:
        keystone_client.federation.mappings.get(map_name)
    except keystoneauth1.exceptions.http.NotFound:
        keystone_client.federation.mappings.create(map_name, rules=JSON_RULES)

    try:
        keystone_client.federation.protocols.get(idp_name, PROTOCOL_NAME)
    except keystoneauth1.exceptions.http.NotFound:
        keystone_client.federation.protocols.create(PROTOCOL_NAME,
                                                    mapping=map_name,
                                                    identity_provider=idp)
 def test_setup_logging_existing_handler(self):
     self.patch_object(cli_utils, "logging")
     _logformatter = mock.MagicMock()
     _logger = mock.MagicMock()
     _logger.hasHandlers.return_value = True
     _consolehandler = mock.MagicMock()
     self.logging.Formatter.return_value = _logformatter
     self.logging.getLogger.return_value = _logger
     self.logging.StreamHandler.return_value = _consolehandler
     cli_utils.setup_logging()
     self.assertFalse(_logger.addHandler.called)
Beispiel #20
0
def basic_overcloud_network(limit_gws=None):
    """Run setup for neutron networking.

    Configure the following:
        The overcloud network using subnet pools

    :param limit_gws: Limit the number of gateways that get a port attached
    :type limit_gws: int
    """
    cli_utils.setup_logging()

    # Get network configuration settings
    network_config = {}
    # Declared overcloud settings
    network_config.update(OVERCLOUD_NETWORK_CONFIG)
    # Default undercloud settings
    network_config.update(DEFAULT_UNDERCLOUD_NETWORK_CONFIG)
    # Environment specific settings
    network_config.update(generic_utils.get_undercloud_env_vars())

    # Get keystone session
    keystone_session = openstack_utils.get_overcloud_keystone_session()

    # Get optional use_juju_wait for netw ork option
    options = (lifecycle_utils
               .get_charm_config(fatal=False)
               .get('configure_options', {}))
    use_juju_wait = options.get(
        'configure_gateway_ext_port_use_juju_wait', True)

    # Handle network for OpenStack-on-OpenStack scenarios
    provider_type = juju_utils.get_provider_type()
    if provider_type == "openstack":
        undercloud_ks_sess = openstack_utils.get_undercloud_keystone_session()
        network.setup_gateway_ext_port(network_config,
                                       keystone_session=undercloud_ks_sess,
                                       limit_gws=limit_gws,
                                       use_juju_wait=use_juju_wait)
    elif provider_type == "maas":
        # NOTE(fnordahl): After validation of the MAAS+Netplan Open vSwitch
        # integration support, we would most likely want to add multiple modes
        # of operation with MAAS.
        #
        # Perform charm based OVS configuration
        openstack_utils.configure_charmed_openstack_on_maas(
            network_config, limit_gws=limit_gws)
    else:
        logging.warning('Unknown Juju provider type, "{}", will not perform'
                        ' charm network configuration.'
                        .format(provider_type))

    # Confugre the overcloud network
    network.setup_sdn(network_config, keystone_session=keystone_session)
 def setUpClass(cls):
     """Run setup for Series Upgrades."""
     # NOTE(ajkavanagh): Set the jujulib Connection frame size to 4GB to
     # cope with all the outputs from series upgrade; long term, don't send
     # that output back, which will require that the upgrade function in the
     # charm doesn't capture the output of the upgrade in the action, but
     # instead puts it somewhere that can by "juju scp"ed.
     juju.client.connection.Connection.MAX_FRAME_SIZE = 2**32
     cli_utils.setup_logging()
     cls.from_series = None
     cls.to_series = None
     cls.workaround_script = None
     cls.files = []
Beispiel #22
0
def main(argv):
    cli_utils.setup_logging()
    parser = argparse.ArgumentParser()
    parser.add_argument("--service")
    parser.add_argument("--resource")
    options = parser.parse_args()
    service = cli_utils.parse_arg(options, 'service')
    resource = cli_utils.parse_arg(options, 'resource')
    xenial = distro_info.UbuntuDistroInfo().all.index('xenial')
    series = os.environ.get('MOJO_SERIES')
    mojo_env = distro_info.UbuntuDistroInfo().all.index(series)
    if mojo_env >= xenial:
        resource = resource.replace('eth0', 'ens2')
    mojo_os_utils.delete_crm_leader(service, resource)
def main(argv):
    cli_utils.setup_logging()
    # Setup client
    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)
    os_version = openstack_utils.get_current_os_versions(
        'keystone')['keystone']

    if os_version >= 'mitaka':
        designate_api_version = '2'
    else:
        designate_api_version = '1'
    client = mojo_os_utils.get_designate_session_client(
        keystone_session, client_version=designate_api_version)

    zone = mojo_os_utils.create_or_return_zone(client, TEST_DOMAIN,
                                               TEST_DOMAIN_EMAIL)
    mojo_os_utils.create_or_return_recordset(client, zone['id'], 'www', 'A',
                                             [TEST_RECORD[TEST_WWW_RECORD]])

    # Test record is in bind and designate
    mojo_os_utils.check_dns_entry(client,
                                  TEST_RECORD[TEST_WWW_RECORD],
                                  TEST_DOMAIN,
                                  record_name=TEST_WWW_RECORD,
                                  designate_api=designate_api_version)

    mojo_utils.add_unit('designate-bind')

    mojo_os_utils.check_dns_entry(client,
                                  TEST_RECORD[TEST_WWW_RECORD],
                                  TEST_DOMAIN,
                                  record_name=TEST_WWW_RECORD,
                                  designate_api=designate_api_version)

    mojo_utils.delete_oldest('designate-bind')

    mojo_os_utils.check_dns_entry(client,
                                  TEST_RECORD[TEST_WWW_RECORD],
                                  TEST_DOMAIN,
                                  record_name=TEST_WWW_RECORD,
                                  designate_api=designate_api_version)
 def test_setup_logging(self):
     self.patch_object(cli_utils, "logging")
     _logformatter = mock.MagicMock()
     _logger = mock.MagicMock()
     _logger.hasHandlers.return_value = False
     _consolehandler = mock.MagicMock()
     self.logging.Formatter.return_value = _logformatter
     self.logging.getLogger.return_value = _logger
     self.logging.StreamHandler.return_value = _consolehandler
     cli_utils.setup_logging()
     self.logging.Formatter.assert_called_with(
         datefmt='%Y-%m-%d %H:%M:%S',
         fmt='%(asctime)s [%(levelname)s] %(message)s')
     self.logging.getLogger.assert_called_with()
     _logger.setLevel.assert_called_with("INFO")
     _consolehandler.setFormatter.assert_called_with(_logformatter)
     _logger.addHandler.assert_called_with(_consolehandler)
Beispiel #25
0
def manage_ssh_key(nova_client=None):
    """Create basic flavors.

    :param nova_client: Authenticated nova client
    :type nova_client: novaclient.v2.client.Client
    """
    if not nova_client:
        keystone_session = openstack_utils.get_overcloud_keystone_session()
        nova_client = openstack_utils.get_nova_session_client(keystone_session)
    cli_utils.setup_logging()
    if not openstack_utils.valid_key_exists(nova_client,
                                            nova_utils.KEYPAIR_NAME):
        key = openstack_utils.create_ssh_key(nova_client,
                                             nova_utils.KEYPAIR_NAME,
                                             replace=True)
        openstack_utils.write_private_key(nova_utils.KEYPAIR_NAME,
                                          key.private_key)
Beispiel #26
0
def run_from_cli():
    """Run test for BGP routes from CLI.

    :returns: None
    :rtype: None
    """
    cli_utils.setup_logging()
    parser = argparse.ArgumentParser()
    parser.add_argument("--peer-application",
                        "-a",
                        help="BGP Peer application name. Default: quagga",
                        default="quagga")
    options = parser.parse_args()

    peer_application_name = cli_utils.parse_arg(options, "peer_application")

    test_bgp_routes(peer_application_name)
Beispiel #27
0
def create_flavors(nova_client=None):
    """Create basic flavors.

    :param nova_client: Authenticated nova client
    :type nova_client: novaclient.v2.client.Client
    """
    if not nova_client:
        keystone_session = openstack_utils.get_overcloud_keystone_session()
        nova_client = openstack_utils.get_nova_session_client(keystone_session)
    cli_utils.setup_logging()
    names = [flavor.name for flavor in nova_client.flavors.list()]
    for flavor in nova_utils.FLAVORS.keys():
        if flavor not in names:
            nova_client.flavors.create(
                name=flavor,
                ram=nova_utils.FLAVORS[flavor]['ram'],
                vcpus=nova_utils.FLAVORS[flavor]['vcpus'],
                disk=nova_utils.FLAVORS[flavor]['disk'],
                flavorid=nova_utils.FLAVORS[flavor]['flavorid'])
Beispiel #28
0
def vlan_provider_overcloud_network():
    """Run setup to create a VLAN provider network."""
    cli_utils.setup_logging()

    # Get network configuration settings
    network_config = {}
    # Declared overcloud settings
    network_config.update(OVERCLOUD_NETWORK_CONFIG)
    # Declared provider vlan overcloud settings
    network_config.update(OVERCLOUD_PROVIDER_VLAN_NETWORK_CONFIG)
    # Environment specific settings
    network_config.update(generic_utils.get_undercloud_env_vars())

    # Get keystone session
    keystone_session = openstack_utils.get_overcloud_keystone_session()

    # Configure the overcloud network
    network.setup_sdn_provider_vlan(network_config,
                                    keystone_session=keystone_session)
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)
def main(argv):
    cli_utils.setup_logging()
    parser = argparse.ArgumentParser()
    parser.add_argument("term_method", default='juju', nargs='?')
    skip_applications = ['neutron-gateway', 'mongodb',
                         'heat', 'rabbitmq-server']
    princ_applications = mojo_utils.get_principle_applications()
    applications = [item for item in princ_applications
                    if item not in skip_applications]
    for svc in applications:
        doomed_application = applications.pop(0)
        mojo_utils.delete_juju_leader(doomed_application)
        mojo_utils.juju_check_hooks_complete()
        mojo_utils.juju_wait_finished()
        check_cluster_status(doomed_application)
        mojo_utils.add_unit(doomed_application, unit_num=1)
        mojo_utils.juju_wait_finished()
        mojo_utils.juju_check_hooks_complete()
        check_crm_status(doomed_application)