示例#1
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))
def nsx_delete_security_groups(resource, event, trigger, **kwargs):
    if kwargs['force'] is False:
        if nsx_list_security_groups(resource, event, trigger, **kwargs):
            msg = ('Do you want to delete the following NSX firewall '
                   'sections/nsgroups?')
            user_confirm = admin_utils.query_yes_no(msg, default='no')

            if user_confirm is False:
                LOG.info(_LI('NSX security groups cleanup aborted by user'))
                return

    sections = firewall.list_sections()
    # NOTE(roeyc): We use -2 indexing because don't want to delete the
    # default firewall sections.
    if sections:
        NON_DEFAULT_SECURITY_GROUPS = -2
        for section in sections[:NON_DEFAULT_SECURITY_GROUPS]:
            LOG.info(_LI("Deleting firewall section %(display_name)s, "
                         "section id %(id)s"),
                     {'display_name': section['display_name'],
                      'id': section['id']})
            firewall.delete_section(section['id'])

    nsgroups = firewall.list_nsgroups()
    if nsgroups:
        for nsgroup in [nsg for nsg in nsgroups
                        if not utils.is_internal_resource(nsg)]:
            LOG.info(_LI("Deleting ns-group %(display_name)s, "
                         "ns-group id %(id)s"),
                     {'display_name': nsgroup['display_name'],
                      'id': nsgroup['id']})
            firewall.delete_nsgroup(nsgroup['id'])
示例#3
0
def delete_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
    portgroups = _get_nsx_portgroups(dvs_id)
    if not portgroups:
        LOG.info("No NSX portgroups found for %s", dvs_id)
        return

    if not kwargs.get('force'):
        #ask for the user confirmation
        confirm = admin_utils.query_yes_no(
            "Do you want to delete all NSX portgroups for %s" % dvs_id,
            default="no")
        if not confirm:
            LOG.info("NSX portgroups deletion aborted by user")
            return

    vcns = utils.get_nsxv_client()
    for portgroup in portgroups:
        try:
            vcns.delete_port_group(dvs_id, portgroup['moref'])
        except Exception as e:
            LOG.error("Failed to delete portgroup %(pg)s: %(e)s", {
                'pg': portgroup['moref'],
                'e': e
            })
            sys.exc_clear()
        else:
            LOG.info("Successfully deleted portgroup %(pg)s",
                     {'pg': portgroup['moref']})
    LOG.info("Done.")
示例#4
0
def nsx_clean_backup_edge(resource, event, trigger, **kwargs):
    """Delete backup edge"""
    errmsg = ("Need to specify edge-id property. Add --property "
              "edge-id=<edge-id>")
    if not kwargs.get('property'):
        LOG.error(_LE("%s"), errmsg)
        return
    properties = admin_utils.parse_multi_keyval_opt(kwargs['property'])
    edge_id = properties.get('edge-id')
    if not edge_id:
        LOG.error(_LE("%s"), errmsg)
        return
    try:
        edge = nsxv.get_edge(edge_id)
    except exceptions.NeutronException as x:
        LOG.error(_LE("%s"), str(x))
    else:
        # edge[0] is response status code
        # edge[1] is response body
        backup_edges = [e['id'] for e in get_nsxv_backup_edges()]
        if (not edge[1]['name'].startswith('backup-')
            or edge[1]['id'] not in backup_edges):
            LOG.error(
                _LE('Edge: %s is not a backup edge; aborting delete'), edge_id)
            return

        confirm = admin_utils.query_yes_no(
            "Do you want to delete edge: %s" % edge_id, default="no")
        if not confirm:
            LOG.info(_LI("Backup edge deletion aborted by user"))
            return
        _delete_edge_from_nsx_and_neutron(edge_id, edge[1]['name'])
示例#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))
示例#6
0
def neutron_delete_security_groups(resource, event, trigger, **kwargs):
    if kwargs['force'] is False:
        if neutron_list_security_groups(resource, event, trigger, **kwargs):
            msg = ('Do you want to delete the following neutron '
                   'security groups?')
            user_confirm = admin_utils.query_yes_no(msg, default='no')
            if user_confirm is False:
                LOG.info(
                    _LI('Neutron security groups cleanup aborted by '
                        'user'))
                return

    security_groups = neutron_sg.get_security_groups()
    if not security_groups:
        return

    for security_group in security_groups:
        try:
            LOG.info(_LI('Trying to delete %(sg_id)s'),
                     {'sg_id': security_group['id']})
            neutron_sg.delete_security_group(security_group['id'])
            LOG.info(_LI("Deleted security group name: %(name)s id: %(id)s"), {
                'name': security_group['name'],
                'id': security_group['id']
            })
        except Exception as e:
            LOG.warning(str(e))
示例#7
0
def nsx_delete_security_groups(resource, event, trigger, **kwargs):
    if kwargs['force'] is False:
        if nsx_list_security_groups(resource, event, trigger, **kwargs):
            msg = ('Do you want to delete the following NSX firewall '
                   'sections/nsgroups?')
            user_confirm = admin_utils.query_yes_no(msg, default='no')

            if user_confirm is False:
                LOG.info(_LI('NSX security groups cleanup aborted by user'))
                return

    sections = firewall.list_sections()
    # NOTE(gangila): We use -1 indexing because we trying to delete default
    # security group on NSX Manager raises an exception.
    if sections:
        NON_DEFAULT_SECURITY_GROUPS = -1
        for section in sections[:NON_DEFAULT_SECURITY_GROUPS]:
            LOG.info(_LI("Deleting firewall section %(display_name)s, "
                         "section id %(id)s"),
                     {'display_name': section['display_name'],
                      'id': section['id']})
            firewall.delete_section(section['id'])

    nsgroups = firewall.list_nsgroups()
    if nsgroups:
        for nsgroup in nsgroups:
            LOG.info(_LI("Deleting ns-group %(display_name)s, "
                         "ns-group id %(id)s"),
                     {'display_name': nsgroup['display_name'],
                      'id': nsgroup['id']})
            firewall.delete_nsgroup(nsgroup['id'])
示例#8
0
def delete_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
    portgroups = _get_nsx_portgroups(dvs_id)
    if not portgroups:
        LOG.info("No NSX portgroups found for %s", dvs_id)
        return

    if not kwargs.get('force'):
        #ask for the user confirmation
        confirm = admin_utils.query_yes_no(
            "Do you want to delete all NSX portgroups for %s" % dvs_id,
            default="no")
        if not confirm:
            LOG.info("NSX portgroups deletion aborted by user")
            return

    vcns = utils.get_nsxv_client()
    for portgroup in portgroups:
        try:
            vcns.delete_port_group(dvs_id, portgroup['moref'])
        except Exception as e:
            LOG.error("Failed to delete portgroup %(pg)s: %(e)s",
                      {'pg': portgroup['moref'], 'e': e})
            sys.exc_clear()
        else:
            LOG.info("Successfully deleted portgroup %(pg)s",
                     {'pg': portgroup['moref']})
    LOG.info("Done.")
示例#9
0
def nsx_clean_spoofguard_policy(resource, event, trigger, **kwargs):
    """Delete spoofguard policy"""
    errmsg = ("Need to specify policy-id. Add --property "
              "policy-id=<policy-id>")
    if not kwargs.get('property'):
        LOG.error("%s", errmsg)
        return
    properties = admin_utils.parse_multi_keyval_opt(kwargs['property'])
    policy_id = properties.get('policy-id')
    if not policy_id:
        LOG.error("%s", errmsg)
        return
    try:
        h, c = nsxv.get_spoofguard_policy(policy_id)
    except exceptions.NeutronException as e:
        LOG.error("Unable to retrieve policy %(p)s: %(e)s",
                  {'p': policy_id, 'e': str(e)})
    else:
        if not c.get('spoofguardList'):
            LOG.error("Policy %s does not exist", policy_id)
            return
        confirm = admin_utils.query_yes_no(
            "Do you want to delete spoofguard-policy: %s" % policy_id,
            default="no")
        if not confirm:
            LOG.info("spoofguard-policy deletion aborted by user")
            return
        try:
            nsxv.delete_spoofguard_policy(policy_id)
        except Exception as e:
            LOG.error("%s", str(e))
        LOG.info('spoofguard-policy successfully deleted.')
示例#10
0
def neutron_delete_security_groups(resource, event, trigger, **kwargs):
    if kwargs['force'] is False:
        if neutron_list_security_groups(resource, event, trigger, **kwargs):
            msg = ('Do you want to delete the following neutron '
                   'security groups?')
            user_confirm = admin_utils.query_yes_no(msg, default='no')
            if user_confirm is False:
                LOG.info(_LI('Neutron security groups cleanup aborted by '
                             'user'))
                return

    security_groups = neutron_sg.get_security_groups()
    if not security_groups:
        return

    for security_group in security_groups:
        try:
            LOG.info(_LI('Trying to delete %(sg_id)s'),
                     {'sg_id': security_group['id']})
            neutron_sg.delete_security_group(security_group['id'])
            LOG.info(_LI("Deleted security group name: %(name)s id: %(id)s"),
                     {'name': security_group['name'],
                      'id': security_group['id']})
        except Exception as e:
            LOG.warning(str(e))
def nsx_clean_spoofguard_policy(resource, event, trigger, **kwargs):
    """Delete spoofguard policy"""
    errmsg = ("Need to specify policy-id. Add --property "
              "policy-id=<policy-id>")
    if not kwargs.get('property'):
        LOG.error(_LE("%s"), errmsg)
        return
    properties = admin_utils.parse_multi_keyval_opt(kwargs['property'])
    policy_id = properties.get('policy-id')
    if not policy_id:
        LOG.error(_LE("%s"), errmsg)
        return
    try:
        nsxv.get_spoofguard_policy(policy_id)
    except exceptions.NeutronException as e:
        LOG.error(_LE("Unable to retrieve policy %(p)s: %(e)s"),
                  {'p': policy_id, 'e': str(e)})
    else:
        confirm = admin_utils.query_yes_no(
            "Do you want to delete spoofguard-policy: %s" % policy_id,
            default="no")
        if not confirm:
            LOG.info(_LI("spoofguard-policy deletion aborted by user"))
            return
        try:
            nsxv.delete_spoofguard_policy(policy_id)
        except Exception as e:
            LOG.error(_LE("%s"), str(e))
        LOG.info(_LI('spoofguard-policy successfully deleted.'))
示例#12
0
def nsx_clean_all_backup_edges(resource, event, trigger, **kwargs):
    """Delete all backup edges"""
    scope = "all"
    if kwargs.get('property'):
        properties = admin_utils.parse_multi_keyval_opt(kwargs['property'])
        scope = properties.get("scope", "all")
        if scope not in ["neutron", "all"]:
            LOG.error("Need to specify the scope in ['neutron', 'all']")
            return

    backup_edges = get_nsxv_backup_edges(scope=scope)

    if not kwargs.get('force'):
        #ask for the user confirmation
        confirm = admin_utils.query_yes_no(
            "Do you want to delete %s backup edges?" % len(backup_edges),
            default="no")
        if not confirm:
            LOG.info("Backup edges deletion aborted by user")
            return

    deleted_cnt = 0
    for edge in backup_edges:
        # delete the backup edge
        if _nsx_delete_backup_edge(edge['id'], backup_edges):
            deleted_cnt = deleted_cnt + 1

    LOG.info('Done Deleting %s backup edges', deleted_cnt)
示例#13
0
def nsx_redo_metadata_cfg_all(context, plugin):
    user_confirm = admin_utils.query_yes_no("Do you want to setup metadata "
                                            "infrastructure for all the edges",
                                            default="no")
    if not user_confirm:
        LOG.info("NSXv vnics deletion aborted by user")
        return

    config.register_nsxv_azs(cfg.CONF, cfg.CONF.nsxv.availability_zones)
    conf_az = nsx_az.NsxVAvailabilityZones()
    az_list = conf_az.list_availability_zones_objects()
    for az in az_list:
        if az.supports_metadata():
            nsx_redo_metadata_cfg_for_az(context, plugin, az.name, False)
        else:
            LOG.info("Skipping availability zone: %s - no metadata "
                     "configuration", az.name)
示例#14
0
def nsx_clean_backup_edge(resource, event, trigger, **kwargs):
    """Delete backup edge"""
    errmsg = ("Need to specify edge-id property. Add --property "
              "edge-id=<edge-id>")
    if not kwargs.get('property'):
        LOG.error(_LE("%s"), errmsg)
        return
    properties = admin_utils.parse_multi_keyval_opt(kwargs['property'])
    edge_id = properties.get('edge-id')
    if not edge_id:
        LOG.error(_LE("%s"), errmsg)
        return
    try:
        edge = nsxv.get_edge(edge_id)
    except exceptions.NeutronException as x:
        LOG.error(_LE("%s"), str(x))
    else:
        # edge[0] is response status code
        # edge[1] is response body
        backup_edges = [e['id'] for e in get_nsxv_backup_edges()]
        if (not edge[1]['name'].startswith('backup-')
                or edge[1]['id'] not in backup_edges):
            LOG.error(_LE('Edge: %s is not a backup edge; aborting delete'),
                      edge_id)
            return

        confirm = admin_utils.query_yes_no("Do you want to delete edge: %s" %
                                           edge_id,
                                           default="no")
        if not confirm:
            LOG.info(_LI("Backup edge deletion aborted by user"))
            return
        try:
            with locking.LockManager.get_lock(edge_id):
                # Delete from NSXv backend
                nsxv.delete_edge(edge_id)
                # Remove bindings from Neutron DB
                edgeapi = utils.NeutronDbClient()
                nsxv_db.delete_nsxv_router_binding(edgeapi.context.session,
                                                   edge[1]['name'])
                nsxv_db.clean_edge_vnic_binding(edgeapi.context.session,
                                                edge_id)
        except Exception as expt:
            LOG.error(_LE("%s"), str(expt))
示例#15
0
def nsx_clean_backup_edge(resource, event, trigger, **kwargs):
    """Delete backup edge"""
    errmsg = ("Need to specify edge-id property. Add --property "
              "edge-id=<edge-id>")
    if not kwargs.get('property'):
        LOG.error(_LE("%s"), errmsg)
        return
    properties = admin_utils.parse_multi_keyval_opt(kwargs['property'])
    edge_id = properties.get('edge-id')
    if not edge_id:
        LOG.error(_LE("%s"), errmsg)
        return
    try:
        edge = nsxv.get_edge(edge_id)
    except exceptions.NeutronException as e:
        LOG.error(_LE("%s"), str(e))
    else:
        # edge[0] is response status code
        # edge[1] is response body
        backup_edges = [e['id'] for e in get_nsxv_backup_edges()]
        if (not edge[1]['name'].startswith('backup-')
            or edge[1]['id'] not in backup_edges):
            LOG.error(
                _LE('Edge: %s is not a backup edge; aborting delete'), edge_id)
            return

        confirm = admin_utils.query_yes_no(
            "Do you want to delete edge: %s" % edge_id, default="no")
        if not confirm:
            LOG.info(_LI("Backup edge deletion aborted by user"))
            return
        try:
            with locking.LockManager.get_lock(edge_id):
                # Delete from NSXv backend
                nsxv.delete_edge(edge_id)
                # Remove bindings from Neutron DB
                edgeapi = utils.NeutronDbClient()
                nsxv_db.delete_nsxv_router_binding(
                    edgeapi.context.session, edge[1]['name'])
                nsxv_db.clean_edge_vnic_binding(edgeapi.context.session,
                                                edge_id)
        except Exception as e:
            LOG.error(_LE("%s"), str(e))
示例#16
0
def nsx_clean_all_backup_edges(resource, event, trigger, **kwargs):
    """Delete all backup edges"""
    backup_edges = get_nsxv_backup_edges()

    #ask for the user confirmation
    confirm = admin_utils.query_yes_no(
        "Do you want to delete %s backup edges?" % len(backup_edges),
        default="no")
    if not confirm:
        LOG.info("Backup edges deletion aborted by user")
        return

    deleted_cnt = 0
    for edge in backup_edges:
        # delete the backup edge
        if _nsx_delete_backup_edge(edge['id'], backup_edges):
            deleted_cnt = deleted_cnt + 1

    LOG.info('Done Deleting %s backup edges', deleted_cnt)
示例#17
0
def nsx_delete_orphaned_edges(resource, event, trigger, **kwargs):
    """Delete orphaned edges from NSXv backend"""
    orphaned_edges = get_orphaned_edges()
    LOG.info("Before delete; Orphaned Edges: %s", orphaned_edges)

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

    nsxv = utils.get_nsxv_client()
    for edge in orphaned_edges:
        LOG.info("Deleting edge: %s", edge)
        nsxv.delete_edge(edge)

    LOG.info("After delete; Orphaned Edges: \n%s",
             pprint.pformat(get_orphaned_edges()))
示例#18
0
def nsx_delete_orphaned_edges(resource, event, trigger, **kwargs):
    """Delete orphaned edges from NSXv backend"""
    orphaned_edges = get_orphaned_edges()
    LOG.info(_LI("Before delete; Orphaned Edges: %s"), orphaned_edges)

    if not kwargs['force']:
        if len(orphaned_edges):
            user_confirm = admin_utils.query_yes_no("Do you want to delete "
                                                    "orphaned edges",
                                                    default="no")
            if not user_confirm:
                LOG.info(_LI("NSXv Edge deletion aborted by user"))
                return

    nsxv = utils.get_nsxv_client()
    for edge in orphaned_edges:
        LOG.info(_LI("Deleting edge: %s"), edge)
        nsxv.delete_edge(edge)

    LOG.info(_LI("After delete; Orphaned Edges: \n%s"),
        pprint.pformat(get_orphaned_edges()))
示例#19
0
def nsx_clean_backup_edge(resource, event, trigger, **kwargs):
    """Delete backup edge"""
    errmsg = ("Need to specify edge-id property. Add --property "
              "edge-id=<edge-id>")
    if not kwargs.get('property'):
        LOG.error("%s", errmsg)
        return
    properties = admin_utils.parse_multi_keyval_opt(kwargs['property'])
    edge_id = properties.get('edge-id')
    if not edge_id:
        LOG.error("%s", errmsg)
        return
    if not kwargs.get('force'):
        #ask for the user confirmation
        confirm = admin_utils.query_yes_no(
            "Do you want to delete edge: %s" % edge_id, default="no")
        if not confirm:
            LOG.info("Backup edge deletion aborted by user")
            return
    # delete the backup edge
    _nsx_delete_backup_edge(edge_id, get_nsxv_backup_edges())
示例#20
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'])
示例#21
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'])
示例#22
0
def nsx_delete_security_groups(resource, event, trigger, **kwargs):
    if kwargs['force'] is False:
        if nsx_list_security_groups(resource, event, trigger, **kwargs):
            msg = ('Do you want to delete the following NSX firewall '
                   'sections/nsgroups?')
            user_confirm = admin_utils.query_yes_no(msg, default='no')

            if user_confirm is False:
                LOG.info(_LI('NSX security groups cleanup aborted by user'))
                return

    sections = firewall.list_sections()
    # NOTE(roeyc): We use -2 indexing because don't want to delete the
    # default firewall sections.
    if sections:
        NON_DEFAULT_SECURITY_GROUPS = -2
        for section in sections[:NON_DEFAULT_SECURITY_GROUPS]:
            LOG.info(
                _LI("Deleting firewall section %(display_name)s, "
                    "section id %(id)s"), {
                        'display_name': section['display_name'],
                        'id': section['id']
                    })
            firewall.delete_section(section['id'])

    nsgroups = firewall.list_nsgroups()
    if nsgroups:
        for nsgroup in [
                nsg for nsg in nsgroups if not utils.is_internal_resource(nsg)
        ]:
            LOG.info(
                _LI("Deleting ns-group %(display_name)s, "
                    "ns-group id %(id)s"), {
                        'display_name': nsgroup['display_name'],
                        'id': nsgroup['id']
                    })
            firewall.delete_nsgroup(nsgroup['id'])
示例#23
0
def migrate_v_project_to_t(resource, event, trigger, **kwargs):
    """Migrate 1 project from v to t with all its resources"""

    # filter out the plugins INFO logging
    # TODO(asarfaty): Consider this for all admin utils
    LOG.logger.setLevel(logging.INFO)
    logging.getLogger(None).logger.setLevel(logging.WARN)

    # get the configuration: tenant + public network + from file flag
    usage = ("Usage: nsxadmin -r projects -o %s --property project-id=<> "
             "--property external-net=<NSX-T external network to be used> "
             "<--property from-file=True>" %
             shell.Operations.NSX_MIGRATE_V_V3.value)
    if not kwargs.get('property'):
        LOG.error("Missing parameters: %s", usage)
        return
    properties = admin_utils.parse_multi_keyval_opt(kwargs['property'])
    project = properties.get('project-id')
    ext_net_id = properties.get('external-net')
    from_file = properties.get('from-file', 'false').lower() == "true"
    # TODO(asarfaty): get files path
    if not project:
        LOG.error("Missing project-id parameter: %s", usage)
        return
    if not ext_net_id:
        LOG.error("Missing external-net parameter: %s", usage)
        return

    # check if files exist in the current directory
    try:
        filename = get_resource_file_name(project, 'network')
        file = open(filename, 'r')
        if file.read():
            if not from_file:
                from_file = admin_utils.query_yes_no(
                    "Use existing resources files for this project?",
                    default="yes")
        file.close()
    except Exception:
        sys.exc_clear()
        if from_file:
            LOG.error("Cannot run from file: files not found")
            return

    # validate tenant id and public network
    ctx = n_context.get_admin_context()
    mapping = db.get_project_plugin_mapping(ctx.session, project)
    current_plugin = mapping.plugin
    if not mapping:
        LOG.error("Project %s is unknown", project)
        return
    if not from_file and current_plugin != projectpluginmap.NsxPlugins.NSX_V:
        LOG.error("Project %s belongs to plugin %s.", project, mapping.plugin)
        return

    with v3_utils.NsxV3PluginWrapper() as plugin:
        try:
            plugin.get_network(ctx, ext_net_id)
        except exceptions.NetworkNotFound:
            LOG.error("Network %s was not found", ext_net_id)
            return
        if not plugin._network_is_external(ctx, ext_net_id):
            LOG.error("Network %s is not external", ext_net_id)
            return

    if from_file:
        # read resources from files
        objects = read_v_resources_from_files(project)
    else:
        # read all V resources and dump to a file
        objects = read_v_resources_to_files(ctx, project)

    # delete all the V resources (reading it from the files)
    if current_plugin == projectpluginmap.NsxPlugins.NSX_V:
        delete_v_resources(ctx, objects)

    # change the mapping of this tenant to T
    db.update_project_plugin_mapping(ctx.session, project,
                                     projectpluginmap.NsxPlugins.NSX_T)

    # use api replay flag to allow keeping the IDs
    cfg.CONF.set_override('api_replay_mode', True)

    # add resources 1 by one after adapting them to T (api-replay code)
    create_t_resources(ctx, objects, ext_net_id)

    # reset api replay flag to allow keeping the IDs
    cfg.CONF.set_override('api_replay_mode', False)
示例#24
0
def nsx_fix_name_mismatch(resource, event, trigger, **kwargs):
    errmsg = ("Need to specify edge-id property. Add --property "
              "edge-id=<edge-id>")
    if not kwargs.get('property'):
        LOG.error(_LE("%s"), errmsg)
        return
    properties = admin_utils.parse_multi_keyval_opt(kwargs['property'])
    edgeapi = utils.NeutronDbClient()
    edge_id = properties.get('edge-id')
    if not edge_id:
        LOG.error(_LE("%s"), errmsg)
        return
    try:
        # edge[0] is response status code
        # edge[1] is response body
        edge = nsxv.get_edge(edge_id)[1]
    except exceptions.NeutronException as e:
        LOG.error(_LE("%s"), str(e))
    else:
        if edge['name'].startswith('backup-'):

            rtr_binding = nsxv_db.get_nsxv_router_binding_by_edge(
                    edgeapi.context.session, edge['id'])

            if rtr_binding['router_id'] == edge['name']:
                LOG.error(
                    _LE('Edge %s no mismatch with NSX'), edge_id)
                return

            try:
                with locking.LockManager.get_lock(edge_id):
                    # Update edge at NSXv backend
                    if rtr_binding['router_id'].startswith('dhcp-'):
                        # Edge is a DHCP edge - just use router_id as name
                        edge['name'] = rtr_binding['router_id']
                    else:
                        # This is a router - if shared, prefix with 'shared-'
                        nsx_attr = (edgeapi.context.session.query(
                            nsxv_models.NsxvRouterExtAttributes).filter_by(
                                router_id=rtr_binding['router_id']).first())
                        if nsx_attr and nsx_attr['router_type'] == 'shared':
                            edge['name'] = ('shared-' + _uuid())[
                                           :vcns_const.EDGE_NAME_LEN]
                        elif (nsx_attr
                              and nsx_attr['router_type'] == 'exclusive'):
                            rtr_db = (edgeapi.context.session.query(
                                l3_db.Router).filter_by(
                                    id=rtr_binding['router_id']).first())
                            if rtr_db:
                                edge['name'] = (
                                    rtr_db['name'][
                                        :nsxv_constants.ROUTER_NAME_LENGTH -
                                        len(rtr_db['id'])] +
                                    '-' + rtr_db['id'])
                            else:
                                LOG.error(
                                    _LE('No database entry for router id %s'),
                                    rtr_binding['router_id'])

                        else:
                            LOG.error(
                                _LE('Could not determine the name for '
                                    'Edge %s'), edge_id)
                            return

                    confirm = admin_utils.query_yes_no(
                        "Do you want to rename edge %s to %s" % (edge_id,
                                                                 edge['name']),
                        default="no")

                    if not confirm:
                        LOG.info(_LI("Edge rename aborted by user"))
                        return
                    LOG.info(_LI("Edge rename started"))
                    # remove some keys that will fail the NSX transaction
                    edge_utils.remove_irrelevant_keys_from_edge_request(edge)
                    try:
                        LOG.error(_LE("Update edge..."))
                        nsxv.update_edge(edge_id, edge)
                    except Exception as e:
                        LOG.error(_LE("Update failed - %s"), (e))
            except Exception as e:
                LOG.error(_LE("%s"), str(e))
        else:
            LOG.error(
                _LE('Edge %s has no backup prefix on NSX'), edge_id)
            return
示例#25
0
def nsx_fix_name_mismatch(resource, event, trigger, **kwargs):
    errmsg = ("Need to specify edge-id property. Add --property "
              "edge-id=<edge-id>")
    if not kwargs.get('property'):
        LOG.error("%s", errmsg)
        return
    properties = admin_utils.parse_multi_keyval_opt(kwargs['property'])
    edgeapi = utils.NeutronDbClient()
    edge_id = properties.get('edge-id')
    if not edge_id:
        LOG.error("%s", errmsg)
        return
    try:
        # edge[0] is response status code
        # edge[1] is response body
        edge = nsxv.get_edge(edge_id)[1]
    except exceptions.NeutronException as e:
        LOG.error("%s", str(e))
    else:
        if edge['name'].startswith('backup-'):

            rtr_binding = nsxv_db.get_nsxv_router_binding_by_edge(
                    edgeapi.context.session, edge['id'])

            if rtr_binding['router_id'] == edge['name']:
                LOG.error('Edge %s no mismatch with NSX', edge_id)
                return

            try:
                with locking.LockManager.get_lock(edge_id):
                    # Update edge at NSXv backend
                    if rtr_binding['router_id'].startswith('dhcp-'):
                        # Edge is a DHCP edge - just use router_id as name
                        edge['name'] = rtr_binding['router_id']
                    else:
                        # This is a router - if shared, prefix with 'shared-'
                        nsx_attr = (edgeapi.context.session.query(
                            nsxv_models.NsxvRouterExtAttributes).filter_by(
                                router_id=rtr_binding['router_id']).first())
                        if nsx_attr and nsx_attr['router_type'] == 'shared':
                            edge['name'] = ('shared-' + _uuid())[
                                           :vcns_const.EDGE_NAME_LEN]
                        elif (nsx_attr and
                              nsx_attr['router_type'] == 'exclusive'):
                            rtr_db = (edgeapi.context.session.query(
                                l3_db.Router).filter_by(
                                    id=rtr_binding['router_id']).first())
                            if rtr_db:
                                edge['name'] = (
                                    rtr_db['name'][
                                        :nsxv_constants.ROUTER_NAME_LENGTH -
                                        len(rtr_db['id'])] +
                                    '-' + rtr_db['id'])
                            else:
                                LOG.error(
                                    'No database entry for router id %s',
                                    rtr_binding['router_id'])

                        else:
                            LOG.error(
                                'Could not determine the name for '
                                'Edge %s', edge_id)
                            return

                    if not kwargs.get('force'):
                        confirm = admin_utils.query_yes_no(
                            "Do you want to rename edge %s to %s" %
                            (edge_id, edge['name']),
                            default="no")

                        if not confirm:
                            LOG.info("Edge rename aborted by user")
                            return
                    LOG.info("Edge rename started")
                    # remove some keys that will fail the NSX transaction
                    edge_utils.remove_irrelevant_keys_from_edge_request(edge)
                    try:
                        LOG.error("Update edge...")
                        nsxv.update_edge(edge_id, edge)
                    except Exception as e:
                        LOG.error("Update failed - %s", (e))
            except Exception as e:
                LOG.error("%s", str(e))
        else:
            LOG.error(
                'Edge %s has no backup prefix on NSX', edge_id)
            return