Exemplo n.º 1
0
def nsx_list_security_groups(resource, event, trigger, **kwargs):
    sections = firewall.list_sections()
    LOG.info(formatters.output_formatter(constants.FIREWALL_SECTIONS,
                                         sections, ['display_name', 'id']))
    nsgroups = firewall.list_nsgroups()
    LOG.info(formatters.output_formatter(constants.FIREWALL_NSX_GROUPS,
                                         nsgroups, ['display_name', 'id']))
    return bool(sections) or bool(nsgroups)
Exemplo n.º 2
0
def nsx_list_security_groups(resource, event, trigger, **kwargs):
    sections = firewall.list_sections()
    LOG.info(
        formatters.output_formatter(constants.FIREWALL_SECTIONS, sections,
                                    ['display_name', 'id']))
    nsgroups = firewall.list_nsgroups()
    LOG.info(
        formatters.output_formatter(constants.FIREWALL_NSX_GROUPS, nsgroups,
                                    ['display_name', 'id']))
    return bool(sections) or bool(nsgroups)
Exemplo n.º 3
0
def neutron_list_router_edge_bindings(resource, event, trigger, **kwargs):
    """List NSXv edges from Neutron DB"""
    edges = get_router_edge_bindings()
    LOG.info(
        formatters.output_formatter(
            constants.EDGES, edges,
            ['edge_id', 'router_id', 'availability_zone', 'status']))
Exemplo n.º 4
0
def clean_orphaned_router_bindings(resource, event, trigger, **kwargs):
    """Delete nsx router bindings entries without real objects behind them"""
    orphaned_list = get_orphaned_router_bindings()
    if not len(orphaned_list):
        LOG.info("No orphaned Router bindings found.")
        return

    LOG.info("Before delete; Orphaned Bindings:")
    LOG.info(
        formatters.output_formatter(
            constants.ORPHANED_BINDINGS, orphaned_list,
            ['edge_id', 'router_id', 'availability_zone', 'status']))

    if not kwargs.get('force'):
        if len(orphaned_list):
            user_confirm = admin_utils.query_yes_no(
                "Do you want to delete "
                "orphaned bindings", default="no")
            if not user_confirm:
                LOG.info("NSXv Router bindings deletion aborted by user")
                return

    edgeapi = utils.NeutronDbClient()
    for binding in orphaned_list:
        nsxv_db.delete_nsxv_router_binding(edgeapi.context.session,
                                           binding.router_id)

    LOG.info(
        "Deleted %s orphaned router bindings. You may need to check for "
        "orphaned edges now.", len(orphaned_list))
Exemplo n.º 5
0
def clean_orphaned_router_bindings(resource, event, trigger, **kwargs):
    """Delete nsx router bindings entries without real objects behind them"""
    orphaned_list = get_orphaned_router_bindings()
    if not len(orphaned_list):
        LOG.info("No orphaned Router bindings found.")
        return

    LOG.info("Before delete; Orphaned Bindings:")
    LOG.info(formatters.output_formatter(
        constants.ORPHANED_BINDINGS, orphaned_list,
        ['edge_id', 'router_id', 'availability_zone', 'status']))

    if not kwargs.get('force'):
        if len(orphaned_list):
            user_confirm = admin_utils.query_yes_no("Do you want to delete "
                                                    "orphaned bindings",
                                                    default="no")
            if not user_confirm:
                LOG.info("NSXv Router bindings deletion aborted by user")
                return

    edgeapi = utils.NeutronDbClient()
    for binding in orphaned_list:
        nsxv_db.delete_nsxv_router_binding(
            edgeapi.context.session, binding.router_id)

    LOG.info("Deleted %s orphaned router bindings. You may need to check for "
             "orphaned edges now.", len(orphaned_list))
Exemplo n.º 6
0
def list_missing_networks(resource, event, trigger, **kwargs):
    """List the neutron networks which are missing the backend moref
    """
    # get the neutron-nsx networks mapping from DB
    admin_context = context.get_admin_context()
    mappings = nsx_db.get_nsx_networks_mapping(admin_context.session)
    # get the list of backend networks:
    backend_networks = get_networks_name_map()
    missing_networks = []

    # For each neutron network - check if there is a matching backend network
    for entry in mappings:
        nsx_id = entry['nsx_id']
        dvs_id = entry['dvs_id']
        if nsx_id not in backend_networks.keys():
            missing_networks.append({
                'neutron_id': entry['neutron_id'],
                'moref': nsx_id,
                'dvs_id': dvs_id
            })
        elif dvs_id:
            netname = backend_networks[nsx_id]
            if not netname.startswith(dvs_id):
                missing_networks.append({
                    'neutron_id': entry['neutron_id'],
                    'moref': nsx_id,
                    'dvs_id': dvs_id
                })

    LOG.info(
        formatters.output_formatter(constants.MISSING_NETWORKS,
                                    missing_networks,
                                    ['neutron_id', 'moref', 'dvs_id']))
Exemplo n.º 7
0
def list_dhcp_bindings(resource, event, trigger, **kwargs):
    """List DHCP bindings in Neutron."""

    comp_ports = [port for port in neutron_client.get_ports()
                  if nsx_utils.is_port_dhcp_configurable(port)]
    LOG.info(formatters.output_formatter(constants.DHCP_BINDING, comp_ports,
                                         ['id', 'mac_address', 'fixed_ips']))
Exemplo n.º 8
0
def list_missing_routers(resource, event, trigger, **kwargs):
    """List neutron routers that are missing the NSX backend router
    """
    plugin = RoutersPlugin()
    admin_cxt = neutron_context.get_admin_context()
    neutron_routers = plugin.get_routers(admin_cxt)
    routers = []
    for router in neutron_routers:
        neutron_id = router['id']
        # get the router nsx id from the mapping table
        nsx_id = nsx_db.get_nsx_router_id(admin_cxt.session, neutron_id)
        if not nsx_id:
            routers.append({
                'name': router['name'],
                'neutron_id': neutron_id,
                'nsx_id': None
            })
        else:
            try:
                nsxlib.logical_router.get(nsx_id)
            except nsx_exc.ResourceNotFound:
                routers.append({
                    'name': router['name'],
                    'neutron_id': neutron_id,
                    'nsx_id': nsx_id
                })
    if len(routers) > 0:
        title = ("Found %d routers missing from the NSX "
                 "manager:") % len(routers)
        LOG.info(
            formatters.output_formatter(title, routers,
                                        ['name', 'neutron_id', 'nsx_id']))
    else:
        LOG.info("All routers exist on the NSX manager")
Exemplo n.º 9
0
def list_missing_networks(resource, event, trigger, **kwargs):
    """List the neutron networks which are missing the backend moref
    """
    # get the neutron-nsx networks mapping from DB
    admin_context = context.get_admin_context()
    mappings = nsx_db.get_nsx_networks_mapping(admin_context.session)
    # get the list of backend networks:
    backend_networks = get_networks_name_map()
    missing_networks = []

    # For each neutron network - check if there is a matching backend network
    for entry in mappings:
        nsx_id = entry['nsx_id']
        dvs_id = entry['dvs_id']
        if nsx_id not in backend_networks.keys():
            missing_networks.append({'neutron_id': entry['neutron_id'],
                                     'moref': nsx_id,
                                     'dvs_id': dvs_id})
        elif dvs_id:
            netname = backend_networks[nsx_id]
            if not netname.startswith(dvs_id):
                missing_networks.append({'neutron_id': entry['neutron_id'],
                                         'moref': nsx_id,
                                         'dvs_id': dvs_id})

    LOG.info(formatters.output_formatter(constants.MISSING_NETWORKS,
                                         missing_networks,
                                         ['neutron_id', 'moref', 'dvs_id']))
Exemplo n.º 10
0
def list_orphaned_router_bindings(resource, event, trigger, **kwargs):
    """List nsx router bindings entries without real objects behind them"""
    orphaned_list = get_orphaned_router_bindings()
    LOG.info(
        formatters.output_formatter(
            constants.ORPHANED_BINDINGS, orphaned_list,
            ['edge_id', 'router_id', 'availability_zone', 'status']))
Exemplo n.º 11
0
def nsx_list_missing_spoofguard_policies(resource, event, trigger, **kwargs):
    """List missing spoofguard policies on NSXv.

    Spoofguard policies that have a binding in Neutron Db but there is
    no policy on NSXv backend to back it.
    """
    props = kwargs.get('property')
    reverse = True if props and props[0] == 'reverse' else False
    if reverse:
        LOG.info(
            _LI("Spoofguard policies on NSXv but not present in "
                "Neutron Db"))
    else:
        LOG.info(
            _LI("Spoofguard policies in Neutron Db but not present "
                "on NSXv"))
    missing_policies = get_missing_spoofguard_policy_mappings(reverse)
    if not missing_policies:
        LOG.info(
            _LI("\nNo missing spoofguard policies found."
                "\nNeutron DB and NSXv backend are in sync\n"))
    else:
        LOG.info(missing_policies)
        missing_policies = [{'policy_id': pid} for pid in missing_policies]
        LOG.info(
            formatters.output_formatter(constants.SPOOFGUARD_POLICY,
                                        missing_policies, ['policy_id']))
Exemplo n.º 12
0
def list_missing_networks(resource, event, trigger, **kwargs):
    """List neutron networks that are missing the NSX backend network
    """
    plugin = db_base_plugin_v2.NeutronDbPluginV2()
    admin_cxt = neutron_context.get_admin_context()
    neutron_networks = plugin.get_networks(admin_cxt)
    networks = []
    for net in neutron_networks:
        neutron_id = net['id']
        # get the network nsx id from the mapping table
        nsx_id = get_network_nsx_id(admin_cxt, neutron_id)
        if not nsx_id:
            # skip external networks
            pass
        else:
            try:
                utils.get_connected_nsxlib().logical_switch.get(nsx_id)
            except nsx_exc.ResourceNotFound:
                networks.append({
                    'name': net['name'],
                    'neutron_id': neutron_id,
                    'nsx_id': nsx_id
                })
    if len(networks) > 0:
        title = _LI("Found %d internal networks missing from the NSX "
                    "manager:") % len(networks)
        LOG.info(
            formatters.output_formatter(title, networks,
                                        ['name', 'neutron_id', 'nsx_id']))
    else:
        LOG.info(_LI("All internal networks exist on the NSX manager"))
Exemplo n.º 13
0
def nsx_list_backup_edges(resource, event, trigger, **kwargs):
    """List backup edges"""
    backup_edges = get_nsxv_backup_edges()
    LOG.info(
        formatters.output_formatter(
            constants.BACKUP_EDGES, backup_edges,
            ['id', 'name', 'size', 'type', 'availability_zone', 'db_status']))
Exemplo n.º 14
0
def list_metadata_networks(resource, event, trigger, **kwargs):
    """List Metadata networks in Neutron."""
    if not cfg.CONF.nsx_v3.native_metadata_route:
        meta_networks = [network
                         for network in neutron_client.get_networks()
                         if _is_metadata_network(network)]
        LOG.info(formatters.output_formatter(constants.METADATA_PROXY,
                                             meta_networks,
                                             ['id', 'name', 'subnets']))
    else:
        nsxlib = utils.get_connected_nsxlib()
        tags = [{'scope': 'os-neutron-net-id'}]
        ports = nsxlib.search_by_tags(resource_type='LogicalPort', tags=tags)
        for port in ports['results']:
            if port['attachment']['attachment_type'] == 'METADATA_PROXY':
                net_id = None
                for tag in port['tags']:
                    if tag['scope'] == 'os-neutron-net-id':
                        net_id = tag['tag']
                        break
                uri = '/md-proxies/%s/%s/status' % (port['attachment']['id'],
                                                    port['logical_switch_id'])
                status = nsxlib.client.get(uri)
                LOG.info("Status for MD proxy on neutron network %s (logical "
                         "switch %s) is %s",
                         net_id,
                         port['logical_switch_id'],
                         status.get('proxy_status', 'Unknown'))
Exemplo n.º 15
0
def list_orphaned_routers(resource, event, trigger, **kwargs):
    nsxlib = utils.get_connected_nsxlib()
    admin_cxt = neutron_context.get_admin_context()
    missing_routers = v3_utils.get_orphaned_routers(admin_cxt, nsxlib)
    LOG.info(
        formatters.output_formatter(constants.ORPHANED_ROUTERS,
                                    missing_routers, ['id', 'display_name']))
Exemplo n.º 16
0
def list_missing_networks(resource, event, trigger, **kwargs):
    """List neutron networks that are missing the NSX backend network
    """
    nsxlib = utils.get_connected_nsxlib()
    plugin = db_base_plugin_v2.NeutronDbPluginV2()
    admin_cxt = neutron_context.get_admin_context()
    filters = utils.get_plugin_filters(admin_cxt)
    neutron_networks = plugin.get_networks(admin_cxt, filters=filters)
    networks = []
    for net in neutron_networks:
        neutron_id = net['id']
        # get the network nsx id from the mapping table
        nsx_id = get_network_nsx_id(admin_cxt, neutron_id)
        if not nsx_id:
            # skip external networks
            pass
        else:
            try:
                nsxlib.logical_switch.get(nsx_id)
            except nsx_exc.ResourceNotFound:
                networks.append({'name': net['name'],
                                 'neutron_id': neutron_id,
                                 'nsx_id': nsx_id})
    if len(networks) > 0:
        title = ("Found %d internal networks missing from the NSX "
                 "manager:") % len(networks)
        LOG.info(formatters.output_formatter(
            title, networks,
            ['name', 'neutron_id', 'nsx_id']))
    else:
        LOG.info("All internal networks exist on the NSX manager")
Exemplo n.º 17
0
def list_orphaned_networks(resource, event, trigger, **kwargs):
    nsxlib = utils.get_connected_nsxlib()
    admin_cxt = neutron_context.get_admin_context()
    missing_networks = v3_utils.get_orphaned_networks(admin_cxt, nsxlib)
    LOG.info(formatters.output_formatter(constants.ORPHANED_NETWORKS,
                                         missing_networks,
                                         ['id', 'display_name']))
Exemplo n.º 18
0
def list_orphaned_networks(resource, event, trigger, **kwargs):
    """List the NSX networks which are missing the neutron DB
    """
    admin_context = context.get_admin_context()
    missing_networks = []

    # get the list of backend networks:
    backend_networks = get_networks()
    for net in backend_networks:
        moref = net['moref']
        backend_name = net['name']
        if backend_name.startswith('edge-') or net['type'] == 'Network':
            # This is not a neutron network
            continue
        # get the list of neutron networks with this moref
        neutron_networks = nsx_db.get_nsx_network_mapping_for_nsx_id(
            admin_context.session, moref)
        if not neutron_networks:
            # no network found for this moref
            missing_networks.append(net)

        elif moref.startswith(PORTGROUP_PREFIX):
            # This is a VLAN network. Also verify that the DVS Id matches
            for entry in neutron_networks:
                if (not entry['dvs_id']
                        or backend_name.startswith(entry['dvs_id'])):
                    found = True
            # this moref & dvs-id does not appear in the DB
            if not found:
                missing_networks.append(net)

    LOG.info(
        formatters.output_formatter(constants.ORPHANED_NETWORKS,
                                    missing_networks,
                                    ['type', 'moref', 'name']))
Exemplo n.º 19
0
def list_metadata_networks(resource, event, trigger, **kwargs):
    """List Metadata networks in Neutron."""

    meta_networks = [network for network in neutron_client.get_networks()
                     if _is_metadata_network(network)]
    LOG.info(formatters.output_formatter(constants.METADATA_PROXY,
                                         meta_networks,
                                         ['id', 'name', 'subnets']))
Exemplo n.º 20
0
def list_orphaned_vnics(resource, event, trigger, **kwargs):
    """List router orphaned router vnics where the port was deleted"""
    orphaned_vnics = get_orphaned_vnics()
    if not orphaned_vnics:
        LOG.info("No orphaned router vnics found")
        return
    headers = ['edge_id', 'vnic_index', 'tunnel_index', 'network_id']
    LOG.info(formatters.output_formatter(constants.ORPHANED_VNICS,
                                         orphaned_vnics, headers))
Exemplo n.º 21
0
def nsx_list_edges(resource, event, trigger, **kwargs):
    """List edges from NSXv backend"""

    headers = ['id', 'name', 'type', 'size', 'ha']
    edges = utils.get_nsxv_backend_edges()
    if (kwargs.get('verbose')):
        headers += ['syslog']
        extend_edge_info(edges)

    LOG.info(formatters.output_formatter(constants.EDGES, edges, headers))
Exemplo n.º 22
0
def list_dhcp_bindings(resource, event, trigger, **kwargs):
    """List DHCP bindings in Neutron."""

    comp_ports = [
        port for port in neutron_client.get_ports()
        if port['device_owner'].startswith(const.DEVICE_OWNER_COMPUTE_PREFIX)
    ]
    LOG.info(
        formatters.output_formatter(constants.DHCP_BINDING, comp_ports,
                                    ['id', 'mac_address', 'fixed_ips']))
Exemplo n.º 23
0
def list_orphaned_vnics(resource, event, trigger, **kwargs):
    """List router orphaned router vnics where the port was deleted"""
    orphaned_vnics = get_orphaned_vnics()
    if not orphaned_vnics:
        LOG.info("No orphaned router vnics found")
        return
    headers = ['edge_id', 'vnic_index', 'tunnel_index', 'network_id']
    LOG.info(
        formatters.output_formatter(constants.ORPHANED_VNICS, orphaned_vnics,
                                    headers))
Exemplo n.º 24
0
def nsx_list_edges(resource, event, trigger, **kwargs):
    """List edges from NSXv backend"""

    headers = ['id', 'name', 'type', 'size', 'ha']
    edges = utils.get_nsxv_backend_edges()
    if (kwargs.get('verbose')):
        headers += ['syslog']
        extend_edge_info(edges)

    LOG.info(formatters.output_formatter(constants.EDGES, edges, headers))
Exemplo n.º 25
0
def create_redis_rule(resource, event, trigger, **kwargs):
    usage = ("nsxadmin -r routing-redistribution-rule -o create "
             "--property gw-edge-ids=<GW_EDGE_ID>[,...] "
             "[--property prefix=<NAME:CIDR>] "
             "--property learn-from=ospf,bgp,connected,static "
             "--property action=<permit/deny>")
    required_params = ('gw-edge-ids', 'learn-from', 'action')
    properties = admin_utils.parse_multi_keyval_opt(kwargs.get('property', []))
    if not properties or not set(required_params) <= set(properties.keys()):
        LOG.error(usage)
        return

    prefix = properties.get('prefix')
    if prefix:
        prefix_name, cidr = prefix.split(':')
        prefixes = [get_ip_prefix(prefix_name, cidr)] if cidr else []
    else:
        prefix_name = None
        prefixes = []

    learn_from = properties['learn-from'].split(',')

    rule = get_redistribution_rule(prefix_name, 'bgp' in learn_from, 'ospf'
                                   in learn_from, 'static' in learn_from,
                                   'connected' in learn_from,
                                   properties['action'])

    edge_ids = properties['gw-edge-ids'].split(',')
    for edge_id in edge_ids:
        try:
            bgp_config = nsxv.get_routing_bgp_config(edge_id)
            if not bgp_config['bgp'].get('enabled'):
                LOG.error("BGP is not enabled on edge %s", edge_id)
                return
            if not bgp_config['bgp']['redistribution']['enabled']:
                LOG.error("BGP redistribution is not enabled on edge %s",
                          edge_id)
                return
            nsxv.add_bgp_redistribution_rules(edge_id, prefixes, [rule])
        except exceptions.ResourceNotFound:
            LOG.error("Edge %s was not found", edge_id)
            return

    res = [{
        'edge_id': edge_id,
        'prefix': prefix_name if prefix_name else 'ANY',
        'learner-protocol': 'bgp',
        'learn-from': ', '.join(set(learn_from)),
        'action': properties['action']
    } for edge_id in edge_ids]

    headers = ['edge_id', 'prefix', 'learner-protocol', 'learn-from', 'action']
    LOG.info(
        formatters.output_formatter('Routing redistribution rule', res,
                                    headers))
Exemplo n.º 26
0
def nsx_list_name_mismatches(resource, event, trigger, **kwargs):
    edges = utils.get_nsxv_backend_edges()
    plugin_nsx_mismatch = []
    backend_edge_ids = []
    edgeapi = utils.NeutronDbClient()
    # Look for edges with the wrong names:
    for edge in edges:
        backend_edge_ids.append(edge['id'])
        rtr_binding = nsxv_db.get_nsxv_router_binding_by_edge(
            edgeapi.context.session, edge['id'])

        if (rtr_binding and edge['name'].startswith('backup-')
                and rtr_binding['router_id'] != edge['name']):
            plugin_nsx_mismatch.append({
                'edge_id': edge['id'],
                'edge_name': edge['name'],
                'router_id': rtr_binding['router_id']
            })

    LOG.info(
        formatters.output_formatter(
            constants.BACKUP_EDGES + ' with name mismatch:',
            plugin_nsx_mismatch, ['edge_id', 'edge_name', 'router_id']))

    # Also look for missing edges
    like_filters = {'router_id': vcns_const.BACKUP_ROUTER_PREFIX + "%"}
    rtr_bindings = nsxv_db.get_nsxv_router_bindings(edgeapi.context.session,
                                                    like_filters=like_filters)
    plugin_nsx_missing = []

    for rtr_binding in rtr_bindings:
        if rtr_binding['edge_id'] not in backend_edge_ids:
            plugin_nsx_missing.append({
                'edge_id': rtr_binding['edge_id'],
                'router_id': rtr_binding['router_id'],
                'db_status': rtr_binding['status']
            })

    LOG.info(
        formatters.output_formatter(
            constants.BACKUP_EDGES + ' missing from backend:',
            plugin_nsx_missing, ['edge_id', 'router_id', 'db_status']))
Exemplo n.º 27
0
def create_redis_rule(resource, event, trigger, **kwargs):
    usage = ("nsxadmin -r routing-redistribution-rule -o create "
             "--property gw-edge-ids=<GW_EDGE_ID>[,...] "
             "[--property prefix=<NAME:CIDR>] "
             "--property learn-from=ospf,bgp,connected,static "
             "--property action=<permit/deny>")
    required_params = ('gw-edge-ids', 'learn-from', 'action')
    properties = admin_utils.parse_multi_keyval_opt(kwargs.get('property', []))
    if not properties or not set(required_params) <= set(properties.keys()):
        LOG.error(usage)
        return

    prefix = properties.get('prefix')
    if prefix:
        prefix_name, cidr = prefix.split(':')
        prefixes = [get_ip_prefix(prefix_name, cidr)] if cidr else []
    else:
        prefix_name = None
        prefixes = []

    learn_from = properties['learn-from'].split(',')

    rule = get_redistribution_rule(prefix_name,
                                   'bgp' in learn_from,
                                   'ospf' in learn_from,
                                   'static' in learn_from,
                                   'connected' in learn_from,
                                   properties['action'])

    edge_ids = properties['gw-edge-ids'].split(',')
    for edge_id in edge_ids:
        try:
            bgp_config = nsxv.get_routing_bgp_config(edge_id)
            if not bgp_config['bgp'].get('enabled'):
                LOG.error("BGP is not enabled on edge %s", edge_id)
                return
            if not bgp_config['bgp']['redistribution']['enabled']:
                LOG.error("BGP redistribution is not enabled on edge %s",
                          edge_id)
                return
            nsxv.add_bgp_redistribution_rules(edge_id, prefixes, [rule])
        except exceptions.ResourceNotFound:
            LOG.error("Edge %s was not found", edge_id)
            return

    res = [{'edge_id': edge_id,
           'prefix': prefix_name if prefix_name else 'ANY',
            'learner-protocol': 'bgp',
           'learn-from': ', '.join(set(learn_from)),
           'action': properties['action']} for edge_id in edge_ids]

    headers = ['edge_id', 'prefix', 'learner-protocol', 'learn-from', 'action']
    LOG.info(formatters.output_formatter(
        'Routing redistribution rule', res, headers))
Exemplo n.º 28
0
def list_nsx_portgroups(resource, event, trigger, **kwargs):
    if not cfg.CONF.dvs.host_ip:
        LOG.info("Please configure the dvs section in the nsx configuration "
                 "file")
        return

    dvs_id = cfg.CONF.nsxv.dvs_id
    port_groups = _get_nsx_portgroups(dvs_id)
    LOG.info(formatters.output_formatter(
        constants.NSX_PORTGROUPS + " for %s" % dvs_id,
        port_groups, ['moref', 'type']))
Exemplo n.º 29
0
def nsx_list_lb_monitors(resource, event, trigger, **kwargs):

    if not nsxlib.feature_supported(consts.FEATURE_LOAD_BALANCER):
        LOG.error("This utility is not available for NSX version %s",
                  nsxlib.get_version())
        return

    lb_monitors = nsxlib.load_balancer.monitor.list()
    LOG.info(
        formatters.output_formatter(constants.LB_MONITORS, lb_monitors,
                                    ['display_name', 'id', 'resource_type']))
    return bool(lb_monitors)
Exemplo n.º 30
0
def list_nsx_portgroups(resource, event, trigger, **kwargs):
    if not cfg.CONF.dvs.host_ip:
        LOG.info("Please configure the dvs section in the nsx configuration "
                 "file")
        return

    dvs_id = cfg.CONF.nsxv.dvs_id
    port_groups = _get_nsx_portgroups(dvs_id)
    LOG.info(
        formatters.output_formatter(
            constants.NSX_PORTGROUPS + " for %s" % dvs_id, port_groups,
            ['moref', 'type']))
Exemplo n.º 31
0
def nsx_list_lb_pools(resource, event, trigger, **kwargs):

    nsxlib = utils.get_connected_nsxlib()
    if not nsxlib.feature_supported(consts.FEATURE_LOAD_BALANCER):
        LOG.error("This utility is not available for NSX version %s",
                  nsxlib.get_version())
        return

    lb_pools = nsxlib.load_balancer.pool.list()
    LOG.info(formatters.output_formatter(
        constants.LB_POOLS, [lb_pools['results']],
        ['display_name', 'id', 'active_monitor_ids', 'members']))
    return bool(lb_pools)
Exemplo n.º 32
0
def nsx_list_lb_services(resource, event, trigger, **kwargs):
    """List LB services on NSX backend"""

    if not nsxlib.feature_supported(consts.FEATURE_LOAD_BALANCER):
        LOG.error("This utility is not available for NSX version %s",
                  nsxlib.get_version())
        return

    lb_services = nsxlib.load_balancer.service.list()
    LOG.info(
        formatters.output_formatter(
            constants.LB_SERVICES, lb_services,
            ['display_name', 'id', 'virtual_server_ids', 'attachment']))
    return bool(lb_services)
Exemplo n.º 33
0
def nsx_list_lb_virtual_servers(resource, event, trigger, **kwargs):
    """List LB virtual servers on NSX backend"""

    nsxlib = utils.get_connected_nsxlib()
    if not nsxlib.feature_supported(consts.FEATURE_LOAD_BALANCER):
        LOG.error("This utility is not available for NSX version %s",
                  nsxlib.get_version())
        return

    lb_virtual_servers = nsxlib.load_balancer.virtual_server.list()
    LOG.info(formatters.output_formatter(
        constants.LB_VIRTUAL_SERVERS, [lb_virtual_servers['results']],
        ['display_name', 'id', 'ip_address', 'pool_id']))
    return bool(lb_virtual_servers)
Exemplo n.º 34
0
def _md_member_status(title, edge_ids):
    for edge_id in edge_ids:
        lb_stats = nsxv.get_loadbalancer_statistics(
            edge_id)
        pools_stats = lb_stats[1].get('pool', [])
        members = []
        for pool_stats in pools_stats:
            if pool_stats['name'] == md_proxy.METADATA_POOL_NAME:
                for member in pool_stats.get('member', []):
                    members.append({'member_ip': member['ipAddress'],
                                    'member_status': member['status']})

        LOG.info(formatters.output_formatter(
            title % edge_id,
            members, ['member_ip', 'member_status']))
Exemplo n.º 35
0
def list_bgp_edges(resource, event, trigger, **kwargs):
    bgp_edges = []
    edges = v_utils.get_nsxv_backend_edges()
    for edge in edges:
        bgp_config = nsxv.get_routing_bgp_config(edge['id'])
        if bgp_config['bgp']['enabled']:
            bgp_edges.append({'name': edge['name'],
                              'edge_id': edge['id'],
                              'local_as': bgp_config['bgp']['localAS']})
    if not bgp_edges:
        LOG.info("No BGP GW edges found")
        return

    headers = ['name', 'edge_id', 'local_as']
    LOG.info(formatters.output_formatter(constants.EDGES, bgp_edges, headers))
Exemplo n.º 36
0
def list_orphaned_routers(resource, event, trigger, **kwargs):
    nsx_routers = nsxlib.logical_router.list()['results']
    missing_routers = []
    for nsx_router in nsx_routers:
        # check if it exists in the neutron DB
        if not neutron_client.lrouter_id_to_router_id(nsx_router['id']):
            # Skip non-neutron routers, by tags
            for tag in nsx_router.get('tags', []):
                if tag.get('scope') == 'os-neutron-router-id':
                    missing_routers.append(nsx_router)
                    break

    LOG.info(
        formatters.output_formatter(constants.ORPHANED_ROUTERS,
                                    missing_routers, ['id', 'display_name']))
Exemplo n.º 37
0
def list_bgp_edges(resource, event, trigger, **kwargs):
    bgp_edges = []
    edges = v_utils.get_nsxv_backend_edges()
    for edge in edges:
        bgp_config = nsxv.get_routing_bgp_config(edge['id'])
        if bgp_config['bgp']['enabled']:
            bgp_edges.append({
                'name': edge['name'],
                'edge_id': edge['id'],
                'local_as': bgp_config['bgp']['localAS']
            })
    if not bgp_edges:
        LOG.info("No BGP GW edges found")
        return

    headers = ['name', 'edge_id', 'local_as']
    LOG.info(formatters.output_formatter(constants.EDGES, bgp_edges, headers))
Exemplo n.º 38
0
def list_orphaned_networks(resource, event, trigger, **kwargs):
    nsx_switches = nsxlib.logical_switch.list()['results']
    missing_networks = []
    for nsx_switch in nsx_switches:
        # check if it exists in the neutron DB
        if not neutron_client.lswitch_id_to_net_id(nsx_switch['id']):
            # Skip non-neutron networks, by tags
            neutron_net = False
            for tag in nsx_switch.get('tags', []):
                if tag.get('scope') == 'os-neutron-net-id':
                    neutron_net = True
                    break
            if neutron_net:
                missing_networks.append(nsx_switch)

    LOG.info(formatters.output_formatter(constants.ORPHANED_NETWORKS,
                                         missing_networks,
                                         ['id', 'display_name']))
Exemplo n.º 39
0
def list_missing_ports(resource, event, trigger, **kwargs):
    """List neutron ports that are missing the NSX backend port
    And ports with wrong switch profiles or bindings
    """
    admin_cxt = neutron_context.get_admin_context()
    filters = v3_utils.get_plugin_filters(admin_cxt)
    nsxlib = v3_utils.get_connected_nsxlib()
    with v3_utils.NsxV3PluginWrapper() as plugin:
        problems = plugin_utils.get_mismatch_logical_ports(
            admin_cxt, nsxlib, plugin, filters)

    if len(problems) > 0:
        title = ("Found internal ports misconfiguration on the "
                 "NSX manager:")
        LOG.info(formatters.output_formatter(
            title, problems,
            ['neutron_id', 'nsx_id', 'error']))
    else:
        LOG.info("All internal ports verified on the NSX manager")
Exemplo n.º 40
0
def nsx_list_orphaned_dhcp_servers(resource, event, trigger, **kwargs):
    """List logical DHCP servers without associated DHCP-enabled subnet."""

    nsxlib = utils.get_connected_nsxlib()
    nsx_version = nsxlib.get_version()
    if not nsx_utils.is_nsx_version_1_1_0(nsx_version):
        LOG.error("This utility is not available for NSX version %s",
                  nsx_version)
        return

    dhcp_profile_uuid = _get_dhcp_profile_uuid(**kwargs)
    if not dhcp_profile_uuid:
        LOG.error("dhcp_profile_uuid is not defined")
        return

    orphaned_servers = _get_orphaned_dhcp_servers(dhcp_profile_uuid)
    LOG.info(formatters.output_formatter(constants.ORPHANED_DHCP_SERVERS,
                                         orphaned_servers,
                                         ['id', 'neutron_net_id']))
Exemplo n.º 41
0
def list_missing_ports(resource, event, trigger, **kwargs):
    """List neutron ports that are missing the NSX backend port
    And ports with wrong switch profiles or bindings
    """
    admin_cxt = neutron_context.get_admin_context()
    filters = v3_utils.get_plugin_filters(admin_cxt)
    nsxlib = v3_utils.get_connected_nsxlib()
    with PortsPlugin() as plugin:
        problems = plugin_utils.get_mismatch_logical_ports(
            admin_cxt, nsxlib, plugin, filters)

    if len(problems) > 0:
        title = ("Found internal ports misconfiguration on the "
                 "NSX manager:")
        LOG.info(
            formatters.output_formatter(title, problems,
                                        ['neutron_id', 'nsx_id', 'error']))
    else:
        LOG.info("All internal ports verified on the NSX manager")
Exemplo n.º 42
0
def nsx_list_name_mismatches(resource, event, trigger, **kwargs):
    edges = nsxv.get_edges()[1]
    edges = edges['edgePage'].get('data', [])
    plugin_nsx_mismatch = []
    edgeapi = utils.NeutronDbClient()
    for edge in edges:
        rtr_binding = nsxv_db.get_nsxv_router_binding_by_edge(
                edgeapi.context.session, edge['id'])

        if (edge['name'].startswith('backup-')
            and rtr_binding['router_id'] != edge['name']):
            plugin_nsx_mismatch.append(
                    {'edge_id': edge['id'],
                     'edge_name': edge['name'],
                     'router_id': rtr_binding['router_id']})

    LOG.info(formatters.output_formatter(
            constants.BACKUP_EDGES, plugin_nsx_mismatch,
            ['edge_id', 'edge_name', 'router_id']))
Exemplo n.º 43
0
def nsx_list_orphaned_dhcp_servers(resource, event, trigger, **kwargs):
    """List logical DHCP servers without associated DHCP-enabled subnet."""

    nsxlib = utils.get_connected_nsxlib()
    nsx_version = nsxlib.get_version()
    if not nsx_utils.is_nsx_version_1_1_0(nsx_version):
        LOG.error("This utility is not available for NSX version %s",
                  nsx_version)
        return

    dhcp_profile_uuid = _get_dhcp_profile_uuid(**kwargs)
    if not dhcp_profile_uuid:
        LOG.error("dhcp_profile_uuid is not defined")
        return

    orphaned_servers = v3_utils.get_orphaned_dhcp_servers(
        context.get_admin_context(),
        neutron_client, nsxlib, dhcp_profile_uuid)
    LOG.info(formatters.output_formatter(
        constants.ORPHANED_DHCP_SERVERS,
        orphaned_servers,
        ['id', 'neutron_net_id', 'display_name']))
Exemplo n.º 44
0
def nsx_list_mismatch_addresses(resource, event, trigger, **kwargs):
    """List missing spoofguard policies approved addresses on NSXv.

    Address pairs defined on neutron compute ports that are missing from the
    NSX-V spoofguard policy of a specific/all networks.
    """
    network_id = None
    if kwargs.get('property'):
        properties = admin_utils.parse_multi_keyval_opt(kwargs['property'])
        network_id = properties.get('network')

    spgapi = utils.NeutronDbClient()

    if network_id:
        policy_id = nsxv_db.get_spoofguard_policy_id(
                spgapi.context.session, network_id)
        if not policy_id:
            LOG.error("Could not find spoofguard policy for neutron network "
                      "%s", network_id)
            return
        with utils.NsxVPluginWrapper() as plugin:
            missing_data = nsx_list_mismatch_addresses_for_net(
                spgapi.context, plugin, network_id, policy_id)
    else:
        with utils.NsxVPluginWrapper() as plugin:
            missing_data = []
            # Go over all the networks with spoofguard policies
            mappings = get_spoofguard_policy_network_mappings()
            for entry in mappings:
                missing_data.extend(nsx_list_mismatch_addresses_for_net(
                    spgapi.context, plugin, entry['network_id'],
                    entry['policy_id']))

    if missing_data:
        LOG.info(formatters.output_formatter(
            constants.SPOOFGUARD_POLICY, missing_data,
            ['network', 'policy', 'port', 'data']))
    else:
        LOG.info("No mismatches found.")
Exemplo n.º 45
0
def add_bgp_neighbour(resource, event, trigger, **kwargs):
    usage = ("nsxadmin -r bgp-neighbour -o create "
             "--property gw-edge-ids=<GW_EDGE_ID>[,...] "
             "--property ip-address=<IP_ADDRESS> "
             "--property remote-as=<AS_NUMBER> "
             "--property password=<PASSWORD>")
    required_params = ('gw-edge-ids', 'ip-address', 'remote-as', 'password')
    properties = admin_utils.parse_multi_keyval_opt(kwargs.get('property', []))
    if not properties or not set(required_params) <= set(properties.keys()):
        LOG.error(usage)
        return

    remote_as = properties['remote-as']
    if not _validate_asn(remote_as):
        return

    nbr = nsxv_bgp.gw_bgp_neighbour(properties['ip-address'],
                                    properties['remote-as'],
                                    properties['password'])

    edge_ids = properties['gw-edge-ids'].split(',')
    for edge_id in edge_ids:
        try:
            nsxv.add_bgp_neighbours(edge_id, [nbr])
        except exceptions.ResourceNotFound:
            LOG.error("Edge %s was not found", edge_id)
            return

    res = [{'edge_id': edge_id,
            'ip_address': properties['ip-address'],
            'remote_as': properties['remote-as'],
            'hold_down_timer': cfg.CONF.nsxv.bgp_neighbour_hold_down_timer,
            'keep_alive_timer': cfg.CONF.nsxv.bgp_neighbour_keep_alive_timer}
           for edge_id in edge_ids]
    headers = ['edge_id', 'ip_address', 'remote_as',
               'hold_down_timer', 'keep_alive_timer']
    LOG.info(formatters.output_formatter('New BPG neighbour',
                                         res, headers))
Exemplo n.º 46
0
def clean_orphaned_vnics(resource, event, trigger, **kwargs):
    """List router orphaned router vnics where the port was deleted"""
    orphaned_vnics = get_orphaned_vnics()
    if not orphaned_vnics:
        LOG.info("No orphaned router vnics found")
        return
    headers = ['edge_id', 'vnic_index', 'tunnel_index', 'network_id']
    LOG.info(formatters.output_formatter(constants.ORPHANED_VNICS,
                                         orphaned_vnics, headers))
    user_confirm = admin_utils.query_yes_no("Do you want to delete "
                                            "orphaned vnics",
                                            default="no")
    if not user_confirm:
        LOG.info("NSXv vnics deletion aborted by user")
        return

    context = n_context.get_admin_context()
    with utils.NsxVPluginWrapper() as plugin:
        nsxv_manager = vcns_driver.VcnsDriver(
            edge_utils.NsxVCallbacks(plugin))
        for vnic in orphaned_vnics:
            if not vnic['distributed']:
                try:
                    nsxv_manager.vcns.delete_interface(
                        vnic['edge_id'], vnic['vnic_index'])
                except Exception as e:
                    LOG.error("Failed to delete vnic from NSX: %s", e)
                nsxv_db.free_edge_vnic_by_network(
                    context.session, vnic['edge_id'], vnic['network_id'])
            else:
                try:
                    nsxv_manager.vcns.delete_vdr_internal_interface(
                        vnic['edge_id'], vnic['vnic_index'])
                except Exception as e:
                    LOG.error("Failed to delete vnic from NSX: %s", e)
                nsxv_db.delete_edge_vnic_binding_by_network(
                    context.session, vnic['edge_id'], vnic['network_id'])
Exemplo n.º 47
0
def nsx_list_missing_spoofguard_policies(resource, event, trigger,
                                         **kwargs):
    """List missing spoofguard policies on NSXv.

    Spoofguard policies that have a binding in Neutron Db but there is
    no policy on NSXv backend to back it.
    """
    props = kwargs.get('property')
    reverse = True if props and props[0] == 'reverse' else False
    if reverse:
        LOG.info(_LI("Spoofguard policies on NSXv but not present in "
                     "Neutron Db"))
    else:
        LOG.info(_LI("Spoofguard policies in Neutron Db but not present "
                     "on NSXv"))
    missing_policies = get_missing_spoofguard_policy_mappings(reverse)
    if not missing_policies:
        LOG.info(_LI("\nNo missing spoofguard policies found."
                     "\nNeutron DB and NSXv backend are in sync\n"))
    else:
        LOG.info(missing_policies)
        missing_policies = [{'policy_id': pid} for pid in missing_policies]
        LOG.info(formatters.output_formatter(
            constants.SPOOFGUARD_POLICY, missing_policies, ['policy_id']))
Exemplo n.º 48
0
def list_orphaned_networks(resource, event, trigger, **kwargs):
    """List the NSX networks which are missing the neutron DB
    """
    admin_context = context.get_admin_context()
    missing_networks = []

    # get all neutron distributed routers in advanced
    with utils.NsxVPluginWrapper() as plugin:
        neutron_routers = plugin.get_routers(
            admin_context, fields=['id', 'name', 'distributed'])
        neutron_dist_routers = [rtr for rtr in neutron_routers
                                if rtr['distributed']]

    # get the list of backend networks:
    backend_networks = get_networks()
    for net in backend_networks:
        moref = net['moref']
        backend_name = net['name']
        # Decide if this is a neutron network by its name (which should always
        # contain the net-id), and type
        if (backend_name.startswith('edge-') or len(backend_name) < 36 or
            net['type'] == 'Network'):
            # This is not a neutron network
            continue
        if backend_name.startswith('int-') and net['type'] == 'VirtualWire':
            # This is a PLR network. Check that the router exists
            found = False
            # compare the expected lswitch name by the dist router name & id
            for rtr in neutron_dist_routers:
                lswitch_name = ('int-' + rtr['name'] + rtr['id'])[:36]
                if lswitch_name == backend_name:
                    found = True
                    break
            # if the neutron router got renamed, this will not work.
            # compare ids prefixes instead (might cause false positives)
            for rtr in neutron_dist_routers:
                if rtr['id'][:5] in backend_name:
                    LOG.info("Logical switch %s probably matches distributed "
                             "router %s", backend_name, rtr['id'])
                    found = True
                    break
            if not found:
                missing_networks.append(net)
            continue

        # get the list of neutron networks with this moref
        neutron_networks = nsx_db.get_nsx_network_mapping_for_nsx_id(
            admin_context.session, moref)
        if not neutron_networks:
            # no network found for this moref
            missing_networks.append(net)

        elif moref.startswith(PORTGROUP_PREFIX):
            # This is a VLAN network. Also verify that the DVS Id matches
            for entry in neutron_networks:
                if (not entry['dvs_id'] or
                    backend_name.startswith(entry['dvs_id'])):
                    found = True
            # this moref & dvs-id does not appear in the DB
            if not found:
                missing_networks.append(net)

    LOG.info(formatters.output_formatter(constants.ORPHANED_NETWORKS,
                                         missing_networks,
                                         ['type', 'moref', 'name']))
Exemplo n.º 49
0
def _log_info(resource, data, attrs=['display_name', 'id']):
    LOG.info(formatters.output_formatter(resource, data, attrs))
Exemplo n.º 50
0
def list_orphaned_router_bindings(resource, event, trigger, **kwargs):
    """List nsx router bindings entries without real objects behind them"""
    orphaned_list = get_orphaned_router_bindings()
    LOG.info(formatters.output_formatter(
        constants.ORPHANED_BINDINGS, orphaned_list,
        ['edge_id', 'router_id', 'availability_zone', 'status']))
Exemplo n.º 51
0
def nsx_list_backup_edges(resource, event, trigger, **kwargs):
    """List backup edges"""
    backup_edges = get_nsxv_backup_edges()
    LOG.info(formatters.output_formatter(constants.BACKUP_EDGES, backup_edges,
                                         ['id']))
Exemplo n.º 52
0
def create_bgp_gw(resource, event, trigger, **kwargs):
    """Creates a new BGP GW edge"""
    usage = ("nsxadmin -r bgp-gw-edge -o create "
             "--property name=<GW_EDGE_NAME> "
             "--property local-as=<LOCAL_AS_NUMBER> "
             "--property external-iface=<PORTGROUP>:<IP_ADDRESS/PREFIX_LEN> "
             "--property internal-iface=<PORTGROUP>:<IP_ADDRESS/PREFIX_LEN> "
             "[--property default-gateway=<IP_ADDRESS>] "
             "[--property az-hint=<AZ_HINT>] "
             "[--property size=compact,large,xlarge,quadlarge]")
    required_params = ('name', 'local-as',
                       'internal-iface', 'external-iface')
    properties = admin_utils.parse_multi_keyval_opt(kwargs.get('property', []))
    if not properties or not set(required_params) <= set(properties.keys()):
        LOG.error(usage)
        return

    local_as = properties['local-as']
    if not _validate_asn(local_as):
        return

    size = properties.get('size', nsxv_constants.LARGE)
    if size not in vcns_const.ALLOWED_EDGE_SIZES:
        msg = ("Property 'size' takes one of the following values: %s."
               % ','.join(vcns_const.ALLOWED_EDGE_SIZES))
        LOG.error(msg)
        return

    external_iface_info = _extract_interface_info(properties['external-iface'])
    internal_iface_info = _extract_interface_info(properties['internal-iface'])
    if not (external_iface_info and internal_iface_info):
        return

    if 'default-gateway' in properties:
        default_gw = _extract_interface_info(properties['default-gateway'])
        if not default_gw:
            msg = ("Property 'default-gateway' doesn't contain a valid IP "
                   "address.")
            LOG.error(msg)
            return
        default_gw = default_gw[1]
    else:
        default_gw = None

    config.register_nsxv_azs(cfg.CONF, cfg.CONF.nsxv.availability_zones)
    az_hint = properties.get('az-hint', 'default')
    az = nsx_az.NsxVAvailabilityZones().get_availability_zone(az_hint)

    edge_id, gateway_ip = _assemble_gw_edge(properties['name'],
                                            size,
                                            external_iface_info,
                                            internal_iface_info,
                                            default_gw,
                                            az)
    nsxv.add_bgp_speaker_config(edge_id, gateway_ip, local_as,
                                True, [], [], [], default_originate=True)

    res = {'name': properties['name'],
           'edge_id': edge_id,
           'size': size,
           'availability_zone': az.name,
           'bgp_identifier': gateway_ip,
           'local_as': local_as}
    headers = ['name', 'edge_id', 'size', 'bgp_identifier',
               'availability_zone', 'local_as']
    LOG.info(formatters.output_formatter('BGP GW Edge', [res], headers))
Exemplo n.º 53
0
def neutron_list_spoofguard_policy_mappings(resource, event, trigger,
                                            **kwargs):
    mappings = get_spoofguard_policy_network_mappings()
    LOG.info(formatters.output_formatter(constants.SPOOFGUARD_POLICY, mappings,
                                         ['network_id', 'policy_id']))
Exemplo n.º 54
0
def nsx_list_spoofguard_policies(resource, event, trigger, **kwargs):
    """List spoofguard policies from NSXv backend"""
    policies = get_spoofguard_policies()
    LOG.info(formatters.output_formatter(constants.SPOOFGUARD_POLICY, policies,
                                         ['policyId', 'name']))
Exemplo n.º 55
0
def neutron_list_security_groups(resource, event, trigger, **kwargs):
    security_groups = neutron_sg.get_security_groups()
    LOG.info(formatters.output_formatter(constants.SECURITY_GROUPS,
                                         security_groups, ['name', 'id']))
    return bool(security_groups)
Exemplo n.º 56
0
def nsx_list_edges(resource, event, trigger, **kwargs):
    """List edges from NSXv backend"""
    edges = get_nsxv_edges()
    LOG.info(formatters.output_formatter(constants.EDGES, edges,
                                         ['id']))
Exemplo n.º 57
0
def neutron_list_networks(resource, event, trigger,
                          **kwargs):
    LOG.info(formatters.output_formatter(constants.NETWORKS, get_networks(),
                                         ['type', 'moref', 'name']))
Exemplo n.º 58
0
def neutron_list_router_edge_bindings(resource, event, trigger, **kwargs):
    """List NSXv edges from Neutron DB"""
    edges = get_router_edge_bindings()
    LOG.info(formatters.output_formatter(constants.EDGES, edges,
                                         ['edge_id', 'router_id']))