コード例 #1
0
ファイル: router.py プロジェクト: yuhui7red/neutron
def update_lrouter_port_ips(cluster, lrouter_id, lport_id,
                            ips_to_add, ips_to_remove):
    uri = _build_uri_path(LROUTERPORT_RESOURCE, lport_id, lrouter_id)
    try:
        port = do_request(HTTP_GET, uri, cluster=cluster)
        # TODO(salvatore-orlando): Enforce ips_to_add intersection with
        # ips_to_remove is empty
        ip_address_set = set(port['ip_addresses'])
        ip_address_set = ip_address_set - set(ips_to_remove)
        ip_address_set = ip_address_set | set(ips_to_add)
        # Set is not JSON serializable - convert to list
        port['ip_addresses'] = list(ip_address_set)
        do_request(HTTP_PUT, uri, jsonutils.dumps(port), cluster=cluster)
    except exception.NotFound as e:
        # FIXME(salv-orlando):avoid raising different exception
        data = {'lport_id': lport_id, 'lrouter_id': lrouter_id}
        msg = (_("Router Port %(lport_id)s not found on router "
                 "%(lrouter_id)s") % data)
        LOG.exception(msg)
        raise nvp_exc.NvpPluginException(err_msg=msg)
    except NvpApiClient.NvpApiException as e:
        msg = _("An exception occurred while updating IP addresses on a "
                "router logical port:%s") % str(e)
        LOG.exception(msg)
        raise nvp_exc.NvpPluginException(err_msg=msg)
コード例 #2
0
def update_lrouter_port_ips(cluster, lrouter_id, lport_id, ips_to_add,
                            ips_to_remove):
    uri = _build_uri_path(LROUTERPORT_RESOURCE, lport_id, lrouter_id)
    try:
        port = do_request(HTTP_GET, uri, cluster=cluster)
        # TODO(salvatore-orlando): Enforce ips_to_add intersection with
        # ips_to_remove is empty
        ip_address_set = set(port['ip_addresses'])
        ip_address_set = ip_address_set - set(ips_to_remove)
        ip_address_set = ip_address_set | set(ips_to_add)
        # Set is not JSON serializable - convert to list
        port['ip_addresses'] = list(ip_address_set)
        do_request(HTTP_PUT, uri, jsonutils.dumps(port), cluster=cluster)
    except exception.NotFound as e:
        # FIXME(salv-orlando):avoid raising different exception
        data = {'lport_id': lport_id, 'lrouter_id': lrouter_id}
        msg = (_("Router Port %(lport_id)s not found on router "
                 "%(lrouter_id)s") % data)
        LOG.exception(msg)
        raise nvp_exc.NvpPluginException(err_msg=msg)
    except NvpApiClient.NvpApiException as e:
        msg = _("An exception occurred while updating IP addresses on a "
                "router logical port:%s") % str(e)
        LOG.exception(msg)
        raise nvp_exc.NvpPluginException(err_msg=msg)
コード例 #3
0
def delete_networks(cluster, net_id, lswitch_ids):
    for ls_id in lswitch_ids:
        path = "/ws.v1/lswitch/%s" % ls_id
        try:
            do_request(HTTP_DELETE, path, cluster=cluster)
        except exception.NotFound as e:
            LOG.error(_("Network not found, Error: %s"), str(e))
            raise exception.NetworkNotFound(net_id=ls_id)
コード例 #4
0
ファイル: switch.py プロジェクト: yuhui7red/neutron
def delete_networks(cluster, net_id, lswitch_ids):
    for ls_id in lswitch_ids:
        path = "/ws.v1/lswitch/%s" % ls_id
        try:
            do_request(HTTP_DELETE, path, cluster=cluster)
        except exception.NotFound as e:
            LOG.error(_("Network not found, Error: %s"), str(e))
            raise exception.NetworkNotFound(net_id=ls_id)
コード例 #5
0
ファイル: router.py プロジェクト: yuhui7red/neutron
def delete_router_lport(cluster, lrouter_uuid, lport_uuid):
    """Creates a logical port on the assigned logical router."""
    path = _build_uri_path(LROUTERPORT_RESOURCE, lport_uuid, lrouter_uuid)
    do_request(HTTP_DELETE, path, cluster=cluster)
    LOG.debug(_("Delete logical router port %(lport_uuid)s on "
                "logical router %(lrouter_uuid)s"),
              {'lport_uuid': lport_uuid,
               'lrouter_uuid': lrouter_uuid})
コード例 #6
0
ファイル: secgroup.py プロジェクト: yuhui7red/neutron
def delete_security_profile(cluster, spid):
    path = "/ws.v1/security-profile/%s" % spid

    try:
        do_request(HTTP_DELETE, path, cluster=cluster)
    except exceptions.NotFound:
        # This is not necessarily an error condition
        LOG.warn(_("Unable to find security profile %s on NSX backend"), spid)
        raise
コード例 #7
0
def delete_lqueue(cluster, queue_id):
    try:
        do_request(HTTP_DELETE,
                   _build_uri_path(LQUEUE_RESOURCE, resource_id=queue_id),
                   cluster=cluster)
    except Exception:
        # FIXME(salv-orlando): This should not raise NeutronException
        with excutils.save_and_reraise_exception():
            raise exception.NeutronException()
コード例 #8
0
def delete_port(cluster, switch, port):
    uri = "/ws.v1/lswitch/" + switch + "/lport/" + port
    try:
        do_request(HTTP_DELETE, uri, cluster=cluster)
    except exception.NotFound:
        LOG.exception(_("Port or Network not found"))
        raise exception.PortNotFoundOnNetwork(net_id=switch, port_id=port)
    except NvpApiClient.NvpApiException:
        raise exception.NeutronException()
コード例 #9
0
ファイル: lsn.py プロジェクト: dsetia/neutron
def _lsn_configure_action(cluster, lsn_id, action, is_enabled, obj):
    lsn_obj = {"enabled": is_enabled}
    lsn_obj.update(obj)
    do_request(HTTP_PUT,
               _build_uri_path(LSERVICESNODE_RESOURCE,
                               resource_id=lsn_id,
                               extra_action=action),
               json.dumps(lsn_obj),
               cluster=cluster)
コード例 #10
0
ファイル: switch.py プロジェクト: yuhui7red/neutron
def delete_port(cluster, switch, port):
    uri = "/ws.v1/lswitch/" + switch + "/lport/" + port
    try:
        do_request(HTTP_DELETE, uri, cluster=cluster)
    except exception.NotFound:
        LOG.exception(_("Port or Network not found"))
        raise exception.PortNotFoundOnNetwork(
            net_id=switch, port_id=port)
    except NvpApiClient.NvpApiException:
        raise exception.NeutronException()
コード例 #11
0
ファイル: lsn.py プロジェクト: Taejun/neutron
def _lsn_port_host_action(
    cluster, lsn_id, lsn_port_id, host_obj, extra_action, action):
    do_request(HTTP_POST,
               _build_uri_path(LSERVICESNODEPORT_RESOURCE,
                               parent_resource_id=lsn_id,
                               resource_id=lsn_port_id,
                               extra_action=extra_action,
                               filters={"action": action}),
               json.dumps(host_obj),
               cluster=cluster)
コード例 #12
0
ファイル: lsn.py プロジェクト: dsetia/neutron
def lsn_port_host_entries_update(cluster, lsn_id, lsn_port_id, conf,
                                 hosts_data):
    hosts_obj = {'hosts': hosts_data}
    do_request(HTTP_PUT,
               _build_uri_path(LSERVICESNODEPORT_RESOURCE,
                               parent_resource_id=lsn_id,
                               resource_id=lsn_port_id,
                               extra_action=conf),
               json.dumps(hosts_obj),
               cluster=cluster)
コード例 #13
0
ファイル: lsn.py プロジェクト: Taejun/neutron
def lsn_port_host_entries_update(
    cluster, lsn_id, lsn_port_id, conf, hosts_data):
    hosts_obj = {'hosts': hosts_data}
    do_request(HTTP_PUT,
               _build_uri_path(LSERVICESNODEPORT_RESOURCE,
                               parent_resource_id=lsn_id,
                               resource_id=lsn_port_id,
                               extra_action=conf),
               json.dumps(hosts_obj),
               cluster=cluster)
コード例 #14
0
def delete_router_lport(cluster, lrouter_uuid, lport_uuid):
    """Creates a logical port on the assigned logical router."""
    path = _build_uri_path(LROUTERPORT_RESOURCE, lport_uuid, lrouter_uuid)
    do_request(HTTP_DELETE, path, cluster=cluster)
    LOG.debug(
        _("Delete logical router port %(lport_uuid)s on "
          "logical router %(lrouter_uuid)s"), {
              'lport_uuid': lport_uuid,
              'lrouter_uuid': lrouter_uuid
          })
コード例 #15
0
ファイル: secgroup.py プロジェクト: yuhui7red/neutron
def delete_security_profile(cluster, spid):
    path = "/ws.v1/security-profile/%s" % spid

    try:
        do_request(HTTP_DELETE, path, cluster=cluster)
    except exceptions.NotFound:
        # This is not necessarily an error condition
        LOG.warn(_("Unable to find security profile %s on NSX backend"),
                 spid)
        raise
コード例 #16
0
ファイル: lsn.py プロジェクト: dsetia/neutron
def _lsn_port_host_action(cluster, lsn_id, lsn_port_id, host_obj, extra_action,
                          action):
    do_request(HTTP_POST,
               _build_uri_path(LSERVICESNODEPORT_RESOURCE,
                               parent_resource_id=lsn_id,
                               resource_id=lsn_port_id,
                               extra_action=extra_action,
                               filters={"action": action}),
               json.dumps(host_obj),
               cluster=cluster)
コード例 #17
0
ファイル: lsn.py プロジェクト: Taejun/neutron
def _lsn_configure_action(
    cluster, lsn_id, action, is_enabled, obj):
    lsn_obj = {"enabled": is_enabled}
    lsn_obj.update(obj)
    do_request(HTTP_PUT,
               _build_uri_path(LSERVICESNODE_RESOURCE,
                               resource_id=lsn_id,
                               extra_action=action),
               json.dumps(lsn_obj),
               cluster=cluster)
コード例 #18
0
ファイル: router.py プロジェクト: yuhui7red/neutron
def update_default_gw_explicit_routing_lrouter(cluster, router_id, next_hop):
    default_route = get_default_route_explicit_routing_lrouter(cluster,
                                                               router_id)
    if next_hop != default_route["next_hop_ip"]:
        new_default_route = {"action": "accept",
                             "next_hop_ip": next_hop,
                             "prefix": "0.0.0.0/0",
                             "protocol": "static"}
        do_request(HTTP_PUT,
                   _build_uri_path(LROUTERRIB_RESOURCE,
                                   resource_id=default_route['uuid'],
                                   parent_resource_id=router_id),
                   jsonutils.dumps(new_default_route),
                   cluster=cluster)
コード例 #19
0
ファイル: lsn.py プロジェクト: dsetia/neutron
def _lsn_port_configure_action(cluster, lsn_id, lsn_port_id, action,
                               is_enabled, obj):
    do_request(HTTP_PUT,
               _build_uri_path(LSERVICESNODE_RESOURCE,
                               resource_id=lsn_id,
                               extra_action=action),
               json.dumps({"enabled": is_enabled}),
               cluster=cluster)
    do_request(HTTP_PUT,
               _build_uri_path(LSERVICESNODEPORT_RESOURCE,
                               parent_resource_id=lsn_id,
                               resource_id=lsn_port_id,
                               extra_action=action),
               json.dumps(obj),
               cluster=cluster)
コード例 #20
0
ファイル: lsn.py プロジェクト: Taejun/neutron
def _lsn_port_configure_action(
    cluster, lsn_id, lsn_port_id, action, is_enabled, obj):
    do_request(HTTP_PUT,
               _build_uri_path(LSERVICESNODE_RESOURCE,
                               resource_id=lsn_id,
                               extra_action=action),
               json.dumps({"enabled": is_enabled}),
               cluster=cluster)
    do_request(HTTP_PUT,
               _build_uri_path(LSERVICESNODEPORT_RESOURCE,
                               parent_resource_id=lsn_id,
                               resource_id=lsn_port_id,
                               extra_action=action),
               json.dumps(obj),
               cluster=cluster)
コード例 #21
0
ファイル: switch.py プロジェクト: yuhui7red/neutron
def update_port(cluster, lswitch_uuid, lport_uuid, neutron_port_id, tenant_id,
                display_name, device_id, admin_status_enabled,
                mac_address=None, fixed_ips=None, port_security_enabled=None,
                security_profiles=None, queue_id=None,
                mac_learning_enabled=None, allowed_address_pairs=None):
    lport_obj = dict(
        admin_status_enabled=admin_status_enabled,
        display_name=utils.check_and_truncate(display_name),
        tags=utils.get_tags(os_tid=tenant_id,
                            q_port_id=neutron_port_id,
                            vm_id=utils.device_id_to_vm_id(device_id)))

    _configure_extensions(lport_obj, mac_address, fixed_ips,
                          port_security_enabled, security_profiles,
                          queue_id, mac_learning_enabled,
                          allowed_address_pairs)

    path = "/ws.v1/lswitch/" + lswitch_uuid + "/lport/" + lport_uuid
    try:
        result = do_request(HTTP_PUT, path, json.dumps(lport_obj),
                            cluster=cluster)
        LOG.debug(_("Updated logical port %(result)s "
                    "on logical switch %(uuid)s"),
                  {'result': result['uuid'], 'uuid': lswitch_uuid})
        return result
    except exception.NotFound as e:
        LOG.error(_("Port or Network not found, Error: %s"), str(e))
        raise exception.PortNotFoundOnNetwork(
            port_id=lport_uuid, net_id=lswitch_uuid)
コード例 #22
0
def create_lswitch(cluster,
                   neutron_net_id,
                   tenant_id,
                   display_name,
                   transport_zones_config,
                   shared=None,
                   **kwargs):
    # The tag scope adopts a slightly different naming convention for
    # historical reasons
    lswitch_obj = {
        "display_name": utils.check_and_truncate(display_name),
        "transport_zones": transport_zones_config,
        "tags": utils.get_tags(os_tid=tenant_id, quantum_net_id=neutron_net_id)
    }
    # TODO(salv-orlando): Now that we have async status synchronization
    # this tag is perhaps not needed anymore
    if shared:
        lswitch_obj["tags"].append({"tag": "true", "scope": "shared"})
    if "tags" in kwargs:
        lswitch_obj["tags"].extend(kwargs["tags"])
    uri = _build_uri_path(LSWITCH_RESOURCE)
    lswitch = do_request(HTTP_POST,
                         uri,
                         json.dumps(lswitch_obj),
                         cluster=cluster)
    LOG.debug(_("Created logical switch: %s"), lswitch['uuid'])
    return lswitch
コード例 #23
0
ファイル: router.py プロジェクト: yuhui7red/neutron
def update_router_lport(cluster, lrouter_uuid, lrouter_port_uuid,
                        tenant_id, neutron_port_id, display_name,
                        admin_status_enabled, ip_addresses):
    """Updates a logical port on the assigned logical router."""
    lport_obj = dict(
        admin_status_enabled=admin_status_enabled,
        display_name=display_name,
        tags=utils.get_tags(os_tid=tenant_id, q_port_id=neutron_port_id),
        ip_addresses=ip_addresses,
        type="LogicalRouterPortConfig"
    )
    # Do not pass null items to NSX
    for key in lport_obj.keys():
        if lport_obj[key] is None:
            del lport_obj[key]
    path = _build_uri_path(LROUTERPORT_RESOURCE,
                           lrouter_port_uuid,
                           parent_resource_id=lrouter_uuid)
    result = do_request(HTTP_PUT, path,
                        jsonutils.dumps(lport_obj),
                        cluster=cluster)
    LOG.debug(_("Updated logical port %(lport_uuid)s on "
                "logical router %(lrouter_uuid)s"),
              {'lport_uuid': lrouter_port_uuid, 'lrouter_uuid': lrouter_uuid})
    return result
コード例 #24
0
ファイル: l2gateway.py プロジェクト: yuhui7red/neutron
def create_l2_gw_service(cluster, tenant_id, display_name, devices):
    """Create a NSX Layer-2 Network Gateway Service.

        :param cluster: The target NSX cluster
        :param tenant_id: Identifier of the Openstack tenant for which
        the gateway service.
        :param display_name: Descriptive name of this gateway service
        :param devices: List of transport node uuids (and network
        interfaces on them) to use for the network gateway service
        :raise NvpApiException: if there is a problem while communicating
        with the NSX controller
    """
    # NOTE(salvatore-orlando): This is a little confusing, but device_id in
    # NSX is actually the identifier a physical interface on the gateway
    # device, which in the Neutron API is referred as interface_name
    gateways = [{"transport_node_uuid": device['id'],
                 "device_id": device['interface_name'],
                 "type": "L2Gateway"} for device in devices]
    gwservice_obj = {
        "display_name": utils.check_and_truncate(display_name),
        "tags": utils.get_tags(os_tid=tenant_id),
        "gateways": gateways,
        "type": "L2GatewayServiceConfig"
    }
    return do_request(
        "POST", _build_uri_path(GWSERVICE_RESOURCE),
        json.dumps(gwservice_obj), cluster=cluster)
コード例 #25
0
ファイル: secgroup.py プロジェクト: yuhui7red/neutron
def update_security_group_rules(cluster, spid, rules):
    path = "/ws.v1/security-profile/%s" % spid

    # Allow all dhcp responses in
    rules['logical_port_egress_rules'].append({
        'ethertype': 'IPv4',
        'protocol': constants.PROTO_NUM_UDP,
        'port_range_min': constants.DHCP_RESPONSE_PORT,
        'port_range_max': constants.DHCP_RESPONSE_PORT,
        'ip_prefix': '0.0.0.0/0'
    })
    # If there are no ingress rules add bunk rule to drop all ingress traffic
    if not rules['logical_port_ingress_rules']:
        rules['logical_port_ingress_rules'].append({
            'ethertype': 'IPv4',
            'ip_prefix': '127.0.0.1/32'
        })
    try:
        body = mk_body(
            logical_port_ingress_rules=rules['logical_port_ingress_rules'],
            logical_port_egress_rules=rules['logical_port_egress_rules'])
        rsp = do_request(HTTP_PUT, path, body, cluster=cluster)
    except exceptions.NotFound as e:
        LOG.error(format_exception("Unknown", e, locals()))
        #FIXME(salvatore-orlando): This should not raise NeutronException
        raise exceptions.NeutronException()
    LOG.debug(_("Updated Security Profile: %s"), rsp)
    return rsp
コード例 #26
0
def update_router_lport(cluster, lrouter_uuid, lrouter_port_uuid, tenant_id,
                        neutron_port_id, display_name, admin_status_enabled,
                        ip_addresses):
    """Updates a logical port on the assigned logical router."""
    lport_obj = dict(admin_status_enabled=admin_status_enabled,
                     display_name=display_name,
                     tags=utils.get_tags(os_tid=tenant_id,
                                         q_port_id=neutron_port_id),
                     ip_addresses=ip_addresses,
                     type="LogicalRouterPortConfig")
    # Do not pass null items to NSX
    for key in lport_obj.keys():
        if lport_obj[key] is None:
            del lport_obj[key]
    path = _build_uri_path(LROUTERPORT_RESOURCE,
                           lrouter_port_uuid,
                           parent_resource_id=lrouter_uuid)
    result = do_request(HTTP_PUT,
                        path,
                        jsonutils.dumps(lport_obj),
                        cluster=cluster)
    LOG.debug(
        _("Updated logical port %(lport_uuid)s on "
          "logical router %(lrouter_uuid)s"), {
              'lport_uuid': lrouter_port_uuid,
              'lrouter_uuid': lrouter_uuid
          })
    return result
コード例 #27
0
ファイル: secgroup.py プロジェクト: yuhui7red/neutron
def create_security_profile(cluster, tenant_id, security_profile):
    path = "/ws.v1/security-profile"
    # Allow all dhcp responses and all ingress traffic
    hidden_rules = {'logical_port_egress_rules':
                    [{'ethertype': 'IPv4',
                      'protocol': constants.PROTO_NUM_UDP,
                      'port_range_min': constants.DHCP_RESPONSE_PORT,
                      'port_range_max': constants.DHCP_RESPONSE_PORT,
                      'ip_prefix': '0.0.0.0/0'}],
                    'logical_port_ingress_rules':
                    [{'ethertype': 'IPv4'},
                     {'ethertype': 'IPv6'}]}
    display_name = utils.check_and_truncate(security_profile.get('name'))
    body = mk_body(
        tags=utils.get_tags(os_tid=tenant_id), display_name=display_name,
        logical_port_ingress_rules=(
            hidden_rules['logical_port_ingress_rules']),
        logical_port_egress_rules=hidden_rules['logical_port_egress_rules']
    )
    rsp = do_request(HTTP_POST, path, body, cluster=cluster)
    if security_profile.get('name') == 'default':
        # If security group is default allow ip traffic between
        # members of the same security profile is allowed and ingress traffic
        # from the switch
        rules = {'logical_port_egress_rules': [{'ethertype': 'IPv4',
                                                'profile_uuid': rsp['uuid']},
                                               {'ethertype': 'IPv6',
                                                'profile_uuid': rsp['uuid']}],
                 'logical_port_ingress_rules': [{'ethertype': 'IPv4'},
                                                {'ethertype': 'IPv6'}]}

        update_security_group_rules(cluster, rsp['uuid'], rules)
    LOG.debug(_("Created Security Profile: %s"), rsp)
    return rsp
コード例 #28
0
ファイル: router.py プロジェクト: yuhui7red/neutron
def create_router_lport(cluster, lrouter_uuid, tenant_id, neutron_port_id,
                        display_name, admin_status_enabled, ip_addresses,
                        mac_address=None):
    """Creates a logical port on the assigned logical router."""
    lport_obj = dict(
        admin_status_enabled=admin_status_enabled,
        display_name=display_name,
        tags=utils.get_tags(os_tid=tenant_id, q_port_id=neutron_port_id),
        ip_addresses=ip_addresses,
        type="LogicalRouterPortConfig"
    )
    # Only add the mac_address to lport_obj if present. This is because
    # when creating the fake_ext_gw there is no mac_address present.
    if mac_address:
        lport_obj['mac_address'] = mac_address
    path = _build_uri_path(LROUTERPORT_RESOURCE,
                           parent_resource_id=lrouter_uuid)
    result = do_request(HTTP_POST, path, jsonutils.dumps(lport_obj),
                        cluster=cluster)

    LOG.debug(_("Created logical port %(lport_uuid)s on "
                "logical router %(lrouter_uuid)s"),
              {'lport_uuid': result['uuid'],
               'lrouter_uuid': lrouter_uuid})
    return result
コード例 #29
0
ファイル: switch.py プロジェクト: yuhui7red/neutron
def get_lswitches(cluster, neutron_net_id):

    def lookup_switches_by_tag():
        # Fetch extra logical switches
        lswitch_query_path = _build_uri_path(
            LSWITCH_RESOURCE,
            fields="uuid,display_name,tags,lport_count",
            relations="LogicalSwitchStatus",
            filters={'tag': neutron_net_id,
                     'tag_scope': 'quantum_net_id'})
        return get_all_query_pages(lswitch_query_path, cluster)

    lswitch_uri_path = _build_uri_path(LSWITCH_RESOURCE, neutron_net_id,
                                       relations="LogicalSwitchStatus")
    results = []
    try:
        ls = do_request(HTTP_GET, lswitch_uri_path, cluster=cluster)
        results.append(ls)
        for tag in ls['tags']:
            if (tag['scope'] == "multi_lswitch" and
                tag['tag'] == "True"):
                results.extend(lookup_switches_by_tag())
    except exception.NotFound:
        # This is legit if the neutron network was created using
        # a post-Havana version of the plugin
        results.extend(lookup_switches_by_tag())
    if results:
        return results
    else:
        raise exception.NetworkNotFound(net_id=neutron_net_id)
コード例 #30
0
def get_port_by_neutron_tag(cluster, lswitch_uuid, neutron_port_id):
    """Get port by neutron tag.

    Returns the NSX UUID of the logical port with tag q_port_id equal to
    neutron_port_id or None if the port is not Found.
    """
    uri = _build_uri_path(LSWITCHPORT_RESOURCE,
                          parent_resource_id=lswitch_uuid,
                          fields='uuid',
                          filters={
                              'tag': neutron_port_id,
                              'tag_scope': 'q_port_id'
                          })
    LOG.debug(
        _("Looking for port with q_port_id tag '%(neutron_port_id)s' "
          "on: '%(lswitch_uuid)s'"), {
              'neutron_port_id': neutron_port_id,
              'lswitch_uuid': lswitch_uuid
          })
    res = do_request(HTTP_GET, uri, cluster=cluster)
    num_results = len(res["results"])
    if num_results >= 1:
        if num_results > 1:
            LOG.warn(
                _("Found '%(num_ports)d' ports with "
                  "q_port_id tag: '%(neutron_port_id)s'. "
                  "Only 1 was expected."), {
                      'num_ports': num_results,
                      'neutron_port_id': neutron_port_id
                  })
        return res["results"][0]
コード例 #31
0
def get_lswitches(cluster, neutron_net_id):
    def lookup_switches_by_tag():
        # Fetch extra logical switches
        lswitch_query_path = _build_uri_path(
            LSWITCH_RESOURCE,
            fields="uuid,display_name,tags,lport_count",
            relations="LogicalSwitchStatus",
            filters={
                'tag': neutron_net_id,
                'tag_scope': 'quantum_net_id'
            })
        return get_all_query_pages(lswitch_query_path, cluster)

    lswitch_uri_path = _build_uri_path(LSWITCH_RESOURCE,
                                       neutron_net_id,
                                       relations="LogicalSwitchStatus")
    results = []
    try:
        ls = do_request(HTTP_GET, lswitch_uri_path, cluster=cluster)
        results.append(ls)
        for tag in ls['tags']:
            if (tag['scope'] == "multi_lswitch" and tag['tag'] == "True"):
                results.extend(lookup_switches_by_tag())
    except exception.NotFound:
        # This is legit if the neutron network was created using
        # a post-Havana version of the plugin
        results.extend(lookup_switches_by_tag())
    if results:
        return results
    else:
        raise exception.NetworkNotFound(net_id=neutron_net_id)
コード例 #32
0
ファイル: switch.py プロジェクト: yuhui7red/neutron
def get_port_by_neutron_tag(cluster, lswitch_uuid, neutron_port_id):
    """Get port by neutron tag.

    Returns the NSX UUID of the logical port with tag q_port_id equal to
    neutron_port_id or None if the port is not Found.
    """
    uri = _build_uri_path(LSWITCHPORT_RESOURCE,
                          parent_resource_id=lswitch_uuid,
                          fields='uuid',
                          filters={'tag': neutron_port_id,
                                   'tag_scope': 'q_port_id'})
    LOG.debug(_("Looking for port with q_port_id tag '%(neutron_port_id)s' "
                "on: '%(lswitch_uuid)s'"),
              {'neutron_port_id': neutron_port_id,
               'lswitch_uuid': lswitch_uuid})
    res = do_request(HTTP_GET, uri, cluster=cluster)
    num_results = len(res["results"])
    if num_results >= 1:
        if num_results > 1:
            LOG.warn(_("Found '%(num_ports)d' ports with "
                       "q_port_id tag: '%(neutron_port_id)s'. "
                       "Only 1 was expected."),
                     {'num_ports': num_results,
                      'neutron_port_id': neutron_port_id})
        return res["results"][0]
コード例 #33
0
ファイル: switch.py プロジェクト: yuhui7red/neutron
def create_lport(cluster, lswitch_uuid, tenant_id, neutron_port_id,
                 display_name, device_id, admin_status_enabled,
                 mac_address=None, fixed_ips=None, port_security_enabled=None,
                 security_profiles=None, queue_id=None,
                 mac_learning_enabled=None, allowed_address_pairs=None):
    """Creates a logical port on the assigned logical switch."""
    display_name = utils.check_and_truncate(display_name)
    lport_obj = dict(
        admin_status_enabled=admin_status_enabled,
        display_name=display_name,
        tags=utils.get_tags(os_tid=tenant_id,
                            q_port_id=neutron_port_id,
                            vm_id=utils.device_id_to_vm_id(device_id))
    )

    _configure_extensions(lport_obj, mac_address, fixed_ips,
                          port_security_enabled, security_profiles,
                          queue_id, mac_learning_enabled,
                          allowed_address_pairs)

    path = _build_uri_path(LSWITCHPORT_RESOURCE,
                           parent_resource_id=lswitch_uuid)
    result = do_request(HTTP_POST, path, json.dumps(lport_obj),
                        cluster=cluster)

    LOG.debug(_("Created logical port %(result)s on logical switch %(uuid)s"),
              {'result': result['uuid'], 'uuid': lswitch_uuid})
    return result
コード例 #34
0
ファイル: switch.py プロジェクト: yuhui7red/neutron
def plug_interface(cluster, lswitch_id, lport_id, att_obj):
    return do_request(HTTP_PUT,
                      _build_uri_path(LSWITCHPORT_RESOURCE,
                                      lport_id, lswitch_id,
                                      is_attachment=True),
                      json.dumps(att_obj),
                      cluster=cluster)
コード例 #35
0
 def test_update_security_profile_rules_noingress(self):
     sec_prof = secgrouplib.create_security_profile(self.fake_cluster,
                                                    'pippo',
                                                    {'name': 'test'})
     hidden_ingress_rule = {
         'ethertype': 'IPv4',
         'ip_prefix': '127.0.0.1/32'
     }
     egress_rule = {'ethertype': 'IPv4', 'profile_uuid': 'xyz'}
     new_rules = {
         'logical_port_egress_rules': [egress_rule],
         'logical_port_ingress_rules': []
     }
     secgrouplib.update_security_group_rules(self.fake_cluster,
                                             sec_prof['uuid'], new_rules)
     sec_prof_res = nsx_utils.do_request(nsx_utils.HTTP_GET,
                                         nsx_utils._build_uri_path(
                                             'security-profile',
                                             resource_id=sec_prof['uuid']),
                                         cluster=self.fake_cluster)
     self.assertEqual(sec_prof['uuid'], sec_prof_res['uuid'])
     # Check for builtin rules
     self.assertEqual(len(sec_prof_res['logical_port_egress_rules']), 2)
     self.assertIn(egress_rule, sec_prof_res['logical_port_egress_rules'])
     self.assertEqual(len(sec_prof_res['logical_port_ingress_rules']), 1)
     self.assertIn(hidden_ingress_rule,
                   sec_prof_res['logical_port_ingress_rules'])
コード例 #36
0
def create_router_lport(cluster,
                        lrouter_uuid,
                        tenant_id,
                        neutron_port_id,
                        display_name,
                        admin_status_enabled,
                        ip_addresses,
                        mac_address=None):
    """Creates a logical port on the assigned logical router."""
    lport_obj = dict(admin_status_enabled=admin_status_enabled,
                     display_name=display_name,
                     tags=utils.get_tags(os_tid=tenant_id,
                                         q_port_id=neutron_port_id),
                     ip_addresses=ip_addresses,
                     type="LogicalRouterPortConfig")
    # Only add the mac_address to lport_obj if present. This is because
    # when creating the fake_ext_gw there is no mac_address present.
    if mac_address:
        lport_obj['mac_address'] = mac_address
    path = _build_uri_path(LROUTERPORT_RESOURCE,
                           parent_resource_id=lrouter_uuid)
    result = do_request(HTTP_POST,
                        path,
                        jsonutils.dumps(lport_obj),
                        cluster=cluster)

    LOG.debug(
        _("Created logical port %(lport_uuid)s on "
          "logical router %(lrouter_uuid)s"), {
              'lport_uuid': result['uuid'],
              'lrouter_uuid': lrouter_uuid
          })
    return result
コード例 #37
0
ファイル: router.py プロジェクト: yuhui7red/neutron
def plug_router_port_attachment(cluster, router_id, port_id,
                                attachment_uuid, nsx_attachment_type,
                                attachment_vlan=None):
    """Attach a router port to the given attachment.

    Current attachment types:
       - PatchAttachment [-> logical switch port uuid]
       - L3GatewayAttachment [-> L3GatewayService uuid]
    For the latter attachment type a VLAN ID can be specified as well.
    """
    uri = _build_uri_path(LROUTERPORT_RESOURCE, port_id, router_id,
                          is_attachment=True)
    attach_obj = {}
    attach_obj["type"] = nsx_attachment_type
    if nsx_attachment_type == "PatchAttachment":
        attach_obj["peer_port_uuid"] = attachment_uuid
    elif nsx_attachment_type == "L3GatewayAttachment":
        attach_obj["l3_gateway_service_uuid"] = attachment_uuid
        if attachment_vlan:
            attach_obj['vlan_id'] = attachment_vlan
    else:
        raise nvp_exc.NvpInvalidAttachmentType(
            attachment_type=nsx_attachment_type)
    return do_request(
        HTTP_PUT, uri, jsonutils.dumps(attach_obj), cluster=cluster)
コード例 #38
0
def update_default_gw_explicit_routing_lrouter(cluster, router_id, next_hop):
    default_route = get_default_route_explicit_routing_lrouter(
        cluster, router_id)
    if next_hop != default_route["next_hop_ip"]:
        new_default_route = {
            "action": "accept",
            "next_hop_ip": next_hop,
            "prefix": "0.0.0.0/0",
            "protocol": "static"
        }
        do_request(HTTP_PUT,
                   _build_uri_path(LROUTERRIB_RESOURCE,
                                   resource_id=default_route['uuid'],
                                   parent_resource_id=router_id),
                   jsonutils.dumps(new_default_route),
                   cluster=cluster)
コード例 #39
0
def plug_router_port_attachment(cluster,
                                router_id,
                                port_id,
                                attachment_uuid,
                                nsx_attachment_type,
                                attachment_vlan=None):
    """Attach a router port to the given attachment.

    Current attachment types:
       - PatchAttachment [-> logical switch port uuid]
       - L3GatewayAttachment [-> L3GatewayService uuid]
    For the latter attachment type a VLAN ID can be specified as well.
    """
    uri = _build_uri_path(LROUTERPORT_RESOURCE,
                          port_id,
                          router_id,
                          is_attachment=True)
    attach_obj = {}
    attach_obj["type"] = nsx_attachment_type
    if nsx_attachment_type == "PatchAttachment":
        attach_obj["peer_port_uuid"] = attachment_uuid
    elif nsx_attachment_type == "L3GatewayAttachment":
        attach_obj["l3_gateway_service_uuid"] = attachment_uuid
        if attachment_vlan:
            attach_obj['vlan_id'] = attachment_vlan
    else:
        raise nvp_exc.NvpInvalidAttachmentType(
            attachment_type=nsx_attachment_type)
    return do_request(HTTP_PUT,
                      uri,
                      jsonutils.dumps(attach_obj),
                      cluster=cluster)
コード例 #40
0
def _create_lrouter_nat_rule(cluster, router_id, nat_rule_obj):
    LOG.debug(_("Creating NAT rule: %s"), nat_rule_obj)
    uri = _build_uri_path(LROUTERNAT_RESOURCE, parent_resource_id=router_id)
    return do_request(HTTP_POST,
                      uri,
                      jsonutils.dumps(nat_rule_obj),
                      cluster=cluster)
コード例 #41
0
def create_lqueue(cluster, queue_data):
    params = {
        'name': 'display_name',
        'qos_marking': 'qos_marking',
        'min': 'min_bandwidth_rate',
        'max': 'max_bandwidth_rate',
        'dscp': 'dscp'
    }
    queue_obj = dict((nvp_name, queue_data.get(api_name))
                     for api_name, nvp_name in params.iteritems()
                     if attr.is_attr_set(queue_data.get(api_name)))
    if 'display_name' in queue_obj:
        queue_obj['display_name'] = utils.check_and_truncate(
            queue_obj['display_name'])

    queue_obj['tags'] = utils.get_tags()
    try:
        return do_request(HTTP_POST,
                          _build_uri_path(LQUEUE_RESOURCE),
                          jsonutils.dumps(queue_obj),
                          cluster=cluster)['uuid']
    except NvpApiClient.NvpApiException:
        # FIXME(salv-orlando): This should not raise NeutronException
        with excutils.save_and_reraise_exception():
            raise exception.NeutronException()
コード例 #42
0
def create_l2_gw_service(cluster, tenant_id, display_name, devices):
    """Create a NSX Layer-2 Network Gateway Service.

        :param cluster: The target NSX cluster
        :param tenant_id: Identifier of the Openstack tenant for which
        the gateway service.
        :param display_name: Descriptive name of this gateway service
        :param devices: List of transport node uuids (and network
        interfaces on them) to use for the network gateway service
        :raise NvpApiException: if there is a problem while communicating
        with the NSX controller
    """
    # NOTE(salvatore-orlando): This is a little confusing, but device_id in
    # NSX is actually the identifier a physical interface on the gateway
    # device, which in the Neutron API is referred as interface_name
    gateways = [{
        "transport_node_uuid": device['id'],
        "device_id": device['interface_name'],
        "type": "L2Gateway"
    } for device in devices]
    gwservice_obj = {
        "display_name": utils.check_and_truncate(display_name),
        "tags": utils.get_tags(os_tid=tenant_id),
        "gateways": gateways,
        "type": "L2GatewayServiceConfig"
    }
    return do_request("POST",
                      _build_uri_path(GWSERVICE_RESOURCE),
                      json.dumps(gwservice_obj),
                      cluster=cluster)
コード例 #43
0
def plug_interface(cluster, lswitch_id, lport_id, att_obj):
    return do_request(HTTP_PUT,
                      _build_uri_path(LSWITCHPORT_RESOURCE,
                                      lport_id,
                                      lswitch_id,
                                      is_attachment=True),
                      json.dumps(att_obj),
                      cluster=cluster)
コード例 #44
0
def get_default_route_explicit_routing_lrouter_v33(cluster, router_id):
    static_filter = {"protocol": "static", "prefix": "0.0.0.0/0"}
    default_route = do_request(HTTP_GET,
                               _build_uri_path(LROUTERRIB_RESOURCE,
                                               filters=static_filter,
                                               fields="*",
                                               parent_resource_id=router_id),
                               cluster=cluster)["results"][0]
    return default_route
コード例 #45
0
def get_explicit_routes_lrouter(cluster, router_id, protocol_type='static'):
    static_filter = {'protocol': protocol_type}
    existing_routes = do_request(HTTP_GET,
                                 _build_uri_path(LROUTERRIB_RESOURCE,
                                                 filters=static_filter,
                                                 fields="*",
                                                 parent_resource_id=router_id),
                                 cluster=cluster)['results']
    return existing_routes
コード例 #46
0
def get_lswitch_by_id(cluster, lswitch_id):
    try:
        lswitch_uri_path = _build_uri_path(LSWITCH_RESOURCE,
                                           lswitch_id,
                                           relations="LogicalSwitchStatus")
        return do_request(HTTP_GET, lswitch_uri_path, cluster=cluster)
    except exception.NotFound:
        # FIXME(salv-orlando): this should not raise a neutron exception
        raise exception.NetworkNotFound(net_id=lswitch_id)
コード例 #47
0
ファイル: lsn.py プロジェクト: Taejun/neutron
def lsn_for_network_create(cluster, network_id):
    lsn_obj = {
        "service_cluster_uuid": cluster.default_service_cluster_uuid,
        "tags": utils.get_tags(n_network_id=network_id)
    }
    return do_request(HTTP_POST,
                      _build_uri_path(LSERVICESNODE_RESOURCE),
                      json.dumps(lsn_obj),
                      cluster=cluster)["uuid"]
コード例 #48
0
ファイル: switch.py プロジェクト: yuhui7red/neutron
def query_lswitch_lports(cluster, ls_uuid, fields="*",
                         filters=None, relations=None):
    # Fix filter for attachments
    if filters and "attachment" in filters:
        filters['attachment_vif_uuid'] = filters["attachment"]
        del filters['attachment']
    uri = _build_uri_path(LSWITCHPORT_RESOURCE, parent_resource_id=ls_uuid,
                          fields=fields, filters=filters, relations=relations)
    return do_request(HTTP_GET, uri, cluster=cluster)['results']
コード例 #49
0
ファイル: switch.py プロジェクト: yuhui7red/neutron
def get_lswitch_by_id(cluster, lswitch_id):
    try:
        lswitch_uri_path = _build_uri_path(
            LSWITCH_RESOURCE, lswitch_id,
            relations="LogicalSwitchStatus")
        return do_request(HTTP_GET, lswitch_uri_path, cluster=cluster)
    except exception.NotFound:
        # FIXME(salv-orlando): this should not raise a neutron exception
        raise exception.NetworkNotFound(net_id=lswitch_id)
コード例 #50
0
ファイル: lsn.py プロジェクト: dsetia/neutron
def lsn_for_network_create(cluster, network_id):
    lsn_obj = {
        "service_cluster_uuid": cluster.default_service_cluster_uuid,
        "tags": utils.get_tags(n_network_id=network_id)
    }
    return do_request(HTTP_POST,
                      _build_uri_path(LSERVICESNODE_RESOURCE),
                      json.dumps(lsn_obj),
                      cluster=cluster)["uuid"]
コード例 #51
0
ファイル: router.py プロジェクト: yuhui7red/neutron
def get_explicit_routes_lrouter(cluster, router_id, protocol_type='static'):
    static_filter = {'protocol': protocol_type}
    existing_routes = do_request(
        HTTP_GET,
        _build_uri_path(LROUTERRIB_RESOURCE,
                        filters=static_filter,
                        fields="*",
                        parent_resource_id=router_id),
        cluster=cluster)['results']
    return existing_routes
コード例 #52
0
def config_helper(config_entity, cluster):
    try:
        return nvplib.do_request('GET',
                                 "/ws.v1/%s?fields=uuid" % config_entity,
                                 cluster=cluster).get('results', [])
    except Exception as e:
        msg = (_("Error '%(err)s' when connecting to controller(s): %(ctl)s.")
               % {'err': str(e),
                  'ctl': ', '.join(get_nsx_controllers(cluster))})
        raise Exception(msg)
コード例 #53
0
def is_transport_node_connected(cluster, node_uuid):
    try:
        return nvplib.do_request('GET',
                                 "/ws.v1/transport-node/%s/status" % node_uuid,
                                 cluster=cluster)['connection']['connected']
    except Exception as e:
        msg = (_("Error '%(err)s' when connecting to controller(s): %(ctl)s.")
               % {'err': str(e),
                  'ctl': ', '.join(get_nsx_controllers(cluster))})
        raise Exception(msg)
コード例 #54
0
ファイル: l2gateway.py プロジェクト: yuhui7red/neutron
def update_l2_gw_service(cluster, gateway_id, display_name):
    # TODO(salvatore-orlando): Allow updates for gateways too
    gwservice_obj = get_l2_gw_service(cluster, gateway_id)
    if not display_name:
        # Nothing to update
        return gwservice_obj
    gwservice_obj["display_name"] = utils.check_and_truncate(display_name)
    return do_request("PUT", _build_uri_path(GWSERVICE_RESOURCE,
                                             resource_id=gateway_id),
                      json.dumps(gwservice_obj), cluster=cluster)
コード例 #55
0
ファイル: router.py プロジェクト: yuhui7red/neutron
def create_explicit_routing_lrouter(cluster, neutron_router_id, tenant_id,
                                    display_name, nexthop, distributed=None):
    lrouter_obj = _prepare_lrouter_body(
        display_name, neutron_router_id, tenant_id,
        "RoutingTableRoutingConfig", distributed=distributed)
    router = do_request(HTTP_POST, _build_uri_path(LROUTER_RESOURCE),
                        jsonutils.dumps(lrouter_obj), cluster=cluster)
    default_gw = {'prefix': '0.0.0.0/0', 'next_hop_ip': nexthop}
    create_explicit_route_lrouter(cluster, router['uuid'], default_gw)
    return router
コード例 #56
0
ファイル: lsn.py プロジェクト: Taejun/neutron
def lsn_for_network_get(cluster, network_id):
    filters = {"tag": network_id, "tag_scope": "n_network_id"}
    results = do_request(HTTP_GET,
                         _build_uri_path(LSERVICESNODE_RESOURCE,
                                         fields="uuid",
                                         filters=filters),
                         cluster=cluster)['results']
    if not results:
        raise exception.NotFound()
    elif len(results) == 1:
        return results[0]['uuid']
コード例 #57
0
ファイル: lsn.py プロジェクト: Taejun/neutron
def lsn_port_info_get(cluster, lsn_id, lsn_port_id):
    result = do_request(HTTP_GET,
                        _build_uri_path(LSERVICESNODEPORT_RESOURCE,
                                        parent_resource_id=lsn_id,
                                        resource_id=lsn_port_id),
                        cluster=cluster)
    for tag in result['tags']:
        if tag['scope'] == 'n_subnet_id':
            result['subnet_id'] = tag['tag']
            break
    return result
コード例 #58
0
def query_lrouter_lports(cluster,
                         lr_uuid,
                         fields="*",
                         filters=None,
                         relations=None):
    uri = _build_uri_path(LROUTERPORT_RESOURCE,
                          parent_resource_id=lr_uuid,
                          fields=fields,
                          filters=filters,
                          relations=relations)
    return do_request(HTTP_GET, uri, cluster=cluster)['results']