Remove vmware_nsx_tempest

This now existsin the vmware_nsx_tempest_plugin

Change-Id: I76e5856deeeb06b87675314635d06aa0291143eb
Depends-On: I804c3fd1e0c9cbeb454677e7951072ad74391fec
This commit is contained in:
Gary Kotton authored and garyk committed 2017-08-15 17:02:55 +00:00
1 parent 02c28ee5ea
commit 508c6262a2
143 files changed
-30124

No files matched your search

-4
View File
@@ -21,8 +21,6 @@ classifier =
[files]
packages =
vmware_nsx
vmware_nsx_tempest
[entry_points]
console_scripts =
neutron-check-nsx-config = vmware_nsx.check_nsx_config:main
@@ -53,8 +51,6 @@ vmware_nsx.neutron.nsxv.router_type_drivers =
shared = vmware_nsx.plugins.nsx_v.drivers.shared_router_driver:RouterSharedDriver
distributed = vmware_nsx.plugins.nsx_v.drivers.distributed_router_driver:RouterDistributedDriver
exclusive = vmware_nsx.plugins.nsx_v.drivers.exclusive_router_driver:RouterExclusiveDriver
tempest.test_plugins =
vmware-nsx-tempest-plugin = vmware_nsx_tempest.plugin:VMwareNsxTempestPlugin
oslo.config.opts =
nsx = vmware_nsx.opts:list_opts
networking_sfc.flowclassifier.drivers =
-13
View File
@@ -59,23 +59,10 @@ check_identical_policy_files () {
fi
}
check_no_duplicate_api_test_idempotent_ids() {
# For API tests, an idempotent ID is assigned to each single API test,
# those IDs should be unique
output=$(check-uuid --package vmware_nsx_tempest)
if [ "$?" -ne 0 ]; then
echo "There are duplicate idempotent ids in the API tests" >>$FAILURES
echo "please, assign unique uuids to each API test:" >>$FAILURES
echo "$output" >>$FAILURES
fi
}
# Add your checks here...
check_no_symlinks_allowed
check_pot_files_errors
#check_identical_policy_files
# Remove the comment below when we figure out how to consume pyshark
#check_no_duplicate_api_test_idempotent_ids
# Fail, if there are emitted failures
if [ -f $FAILURES ]; then
-1
View File
@@ -106,7 +106,6 @@ import-order-style = pep8
[hacking]
import_exceptions = vmware_nsx._i18n,
vmware_nsx_tempest._i18n
local-check-factory = neutron_lib.hacking.checks.factory
[testenv:genconfig]
-92
View File
@@ -1,92 +0,0 @@
Welcome!
========
vmware_nsx_tempest is a plugin module to openstack tempest project.
If you are not familiar with tempest, please refer to::
https://docs.openstack.org/developer/tempest
It is implemented with tempest external plugin.
The official design sepcification is at::
https://review.openstack.org/#/c/184992/
Overview
========
vmware_nsx_tempest hosts vmware_nsx's functional api and scenario tests.
All vmware_nsx_tempest tests are in "master" branch. For this reason,
it is recommended to have your own developer version of vmware-nsx repo
installed outside the devstack folder, /opt/stack/.
For example at /opt/devtest folder. In doing so, you can install
editable vmware-nsx repo under tempest VENV environemnt.
Installation:
-------------
#. On your own development folder, for example /opt/devtest/,
install your own tempest development env at /opt/devtest/os-tempest/::
$ cd /opt/devtest
$ git clone https://github.com/openstack/tempest os-tempest
#. Install virtualenv with the following command::
$ cd /opt/devtest/os-tempest
$ ./run_tempest.sh -u not_exist_tests
#. Install vmware-nsx master branch at /opt/devtest/vmware-nsx::
$ cd /opt/devtest
$ git clone https://github.com/openstack/vmware-nsx
#. Install vmware_nsx_tempest in your tempest development environment::
$ cd /opt/devtest/os-tempest
$ source .venv/bin/activate
$ pip install -e /opt/devtest/vmware-nsx/
Run command::
$ pip show vmware-nsx
You should observe the following statements::
Location: /opt/devtest/vmware-nsx
and under section of Entry-points::
[tempest.test_plugins]
vmware-nsx-tempest-plugin = vmware_nsx_tempest.plugin:VMwareNsxTempestPlugin
#. Validate installed vmware_nsx_tempest successfully do::
$ cd /opt/devtest/os-tempest
$ tools/with_venv.sh testr list-tests vmware_nsx_tempest.*l2_gateway
Your installation failed, if no tests are shown.
Execution:
----------
vmware_nsx_tempest tests are tempest tests, you need to
run from tempest directory. For example, to run only l2-gateway tests::
$ cd /opt/devtest/os-tempest
$ ./run_tempest.sh -t vmware_nsx_tempest.*test_l2_gateway
$ ./run_tempest.sh -d vmware_nsx_tempest.tests.nsxv.api.test_l2_gateway_connection.L2GatewayConnectionTest.test_csuld_single_device_interface_vlan
TechNote on vmware_nsx_tempest:
-------------------------------
vmware_nsx_tempest is a plugin to tempest, not neutron, nor vmware_nsx.
It is defined by tempest.test_plugins.
Modules within vmware_nsx_tempest can not see resources defined
by vmware_nsx. Commands like following are not acceptable, unless
vmware_nsx is installed in your tempest environment::
import vmware_nsx.shell.admin.plugins.common.utils as admin_utils
View File
Whitespace-only changes.
-32
View File
@@ -1,32 +0,0 @@
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import oslo_i18n
DOMAIN = "vmware-nsx-tempest"
_translators = oslo_i18n.TranslatorFactory(domain=DOMAIN)
# The primary translation function using the well-known name "_"
_ = _translators.primary
# The contextual translation function using the name "_C"
_C = _translators.contextual_form
# The plural translation function using the name "_P"
_P = _translators.plural_form
def get_available_languages():
return oslo_i18n.get_available_languages(DOMAIN)
Whitespace-only changes.
-61
View File
@@ -1,61 +0,0 @@
# Copyright 2017 VMware, Inc.
# All Rights Reserved
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from oslo_log import log
LOG = log.getLogger(__name__)
# General constants.
ONE_SEC = 1
# L2GW constants.
L2GW = "l2_gateway"
L2GWS = L2GW + "s"
L2_GWS_BASE_URI = "/l2-gateways"
EXPECTED_HTTP_RESPONSE_200 = "200"
EXPECTED_HTTP_RESPONSE_201 = "201"
EXPECTED_HTTP_RESPONSE_204 = "204"
L2GWC = "l2_gateway_connection"
# MAC Learning constants
MAC_SW_PROFILE = "MacManagementSwitchingProfile"
PORT_SEC_PROFILE = "SpoofGuardSwitchingProfile"
SEC_GRPS_PROFILE = "SwitchSecuritySwitchingProfile"
# NSXV3 MDProxy constants.
MD_ERROR_CODE_WHEN_LS_BOUNDED = "10026"
INTERVAL_BETWEEN_EXEC_RETRY_ON_SSH = 5
MAX_NO_OF_TIMES_EXECUTION_OVER_SSH = 30
MD_BASE_URL = "http://169.254.169.254/"
# NSXV3 Port Security constants.
NSX_BACKEND_TIME_INTERVAL = 30
NSX_BACKEND_SMALL_TIME_INTERVAL = 10
NSX_BACKEND_VERY_SMALL_TIME_INTERVAL = 5
# DFW
NSX_FIREWALL_REALIZED_TIMEOUT = 120
# FWaaS
NO_OF_ENTRIES = 20
EXCLUSIVE_ROUTER = 'exclusive'
DISTRIBUTED_ROUTER = 'distributed'
TCP_PROTOCOL = 'tcp'
ICMP_PROTOCOL = 'icmp'
# NSXV3 Firewall
NSX_FIREWALL_REALIZED_DELAY = 2
APPLIANCE_NAME_STARTS_WITH = "vmw_"
-199
View File
@@ -1,199 +0,0 @@
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from oslo_config import cfg
from tempest import config
service_option = cfg.BoolOpt("vmware_nsx",
default=True,
help="Whether or not vmware_nsx is expected to be"
" available")
scenario_group = config.scenario_group
ScenarioGroup = [
cfg.FloatOpt('waitfor_disassoc',
default=15.0,
help="Wait for seconds after disassociation."),
cfg.FloatOpt('waitfor_assoc',
default=5.0,
help="Waitfor seconds after association."),
cfg.FloatOpt('waitfor_connectivity',
default=120.0,
help="Wait for seconds to become connected."),
cfg.ListOpt('outside_world_servers',
default=["8.8.8.8", "8.8.4.4"],
help="List of servers reside outside of openstack env."
" which is used to test default gateway behavior"
" when VMs are under logical routers,"
" & DNS are local to provider's settings."),
cfg.DictOpt('flat_alloc_pool_dict',
default={},
help="Define flat network ip range."
" required attributes are gateway, start, end"
" and cidr. Example value: gateway:10.1.1.253,"
" start:10.1.1.30,end:10.1.1.49,cidr=10.1.1.0/24"),
cfg.DictOpt('xnet_multiple_subnets_dict',
default={},
help="External network with multiple subnets."
" The primary subnet ip-range will be shrinked,"
" This is for the 2nd subnet, required attrs:"
" start:10.1.1.31,end:10.1.1.33,cidr=10.1.2.0/24"
" AND limit to only 3 ip addresses defined."),
]
network_group = config.network_group
NetworkGroup = [
cfg.StrOpt('l2gw_switch',
default='',
help="Distributed Virtual Portgroup to create VLAN port."),
cfg.DictOpt('l2gw_switch_dict',
default={},
help="dict version of l2gw_switch:"
"device_name:,interfaces:,segmentation_id:,"),
cfg.StrOpt('dns_search_domain',
default='vmware.com',
help="a valid domain that contains host defined at"
" attribute host_in_search_domain"),
cfg.StrOpt('host_in_search_domain',
default='mail',
help="host exists in dns_search_domain"),
cfg.StrOpt('public_network_cidr',
default='',
help="Public network cidr which provides external network"
" connectivity"),
cfg.StrOpt('backend',
default='nsxv',
help="NSX backend, valid values are nsxv|nsxv3"),
]
nsxv_group = cfg.OptGroup(name='nsxv',
title="NSX-v Configuration Options")
NSXvGroup = [
cfg.StrOpt('manager_uri',
default='https://10.0.0.10',
help="NSX-v manager ip address"),
cfg.StrOpt('user',
default='admin',
help="NSX-v manager username"),
cfg.StrOpt('password',
default='default',
help="NSX-v manager password"),
cfg.StrOpt('vdn_scope_id',
default='vdnscope-1',
help="NSX-v vdn scope id"),
cfg.IntOpt('max_mtz',
default=3,
help="Max Multiple Transport Zones used for testing."),
cfg.DictOpt('flat_alloc_pool_dict',
default={},
help=" Define flat network ip range."
" required attributes are gateway, start, end"
" and cidr. Example value: gateway:10.1.1.253,"
" start:10.1.1.30,end:10.1.1.49,cidr=10.1.1.0/24"),
cfg.StrOpt('vlan_physical_network',
default='',
help="physval_network to create vlan."),
cfg.IntOpt('provider_vlan_id',
default=888,
help="The default vlan_id for admin vlan."),
cfg.IntOpt('create_router_http_timeout',
default=900,
help="Specific for router_size tests. This value defines"
" how long http.request should retry."),
cfg.BoolOpt('no_router_type',
default=False,
help="router_type is NSXv extension."
"Set it to True allow tests to remove this attribute"
" when creating router."),
cfg.ListOpt('bugs_to_resolve',
default=[],
help="Bugs to be resolved. Define this at tempest.conf and"
" test case testtools.skipIf(condition, reasons) to"
" skip test cannot be run at specific plugin env."),
cfg.StrOpt('default_policy_id',
default='',
help="NSX security-policy ID used to create all tenants"
" default security-group-policy."
" This must be the same as the one at vmware/nsx.ini"),
cfg.StrOpt('alt_policy_id',
default='',
help="NSX security-policy ID used to create the 2nd"
" security-group-policy, and != default_policy_id."),
cfg.BoolOpt('allow_tenant_rules_with_policy',
default=False,
help="Default=False; a tenant cannot create security-group."
" If True, tenant can create non-policy security-group."
" Sync this value with nsx.ini file."),
]
l2gw_group = cfg.OptGroup(name='l2gw',
title="l2-gateway Configuration Options")
L2gwGroup = [
cfg.DictOpt('vlan_subnet_ipv4_dict',
default={},
help="Tenant's VLAN subnet cdir to connect to l2gw/VXLAN."
" Example: cidr=192.168.99.0/24,start:192.168.99.41"
" ,end:192.168.99.50,gateway=192.168.99.253"),
cfg.StrOpt('device_one_vlan',
default="",
help="l2g2 device with one VLAN"
" l2gw-1::dvportgroup-14420|3845"),
cfg.StrOpt('device_multiple_vlans',
default="",
help="l2gw device with multiple VLANs"
" l2gw-x::dvportgroup-14429|3880#3381#3382"),
cfg.StrOpt('multiple_interfaces_multiple_vlans',
default="",
help="l2gw multiple devices, interface has multiple VLANs"
" m-ifs::dvportgroup-144|138#246;dvportgroup-155|339"),
cfg.StrOpt('vlan_1',
default="16",
help="VLAN id"),
cfg.StrOpt('vlan_2',
default="17",
help="VLAN id"),
cfg.StrOpt("subnet_1_cidr",
default="192.168.1.0/24",
help="Subnet 1 network cidr."
"Example: 1.1.1.0/24"),
cfg.StrOpt('vm_on_vds_tz1_vlan16_ip',
default="192.168.1.203",
help="IPv4 IP address of VM3"),
cfg.StrOpt('vm_on_switch_vlan16',
default="192.168.1.204",
help="IPv4 IP address of VM4"),
cfg.StrOpt('vm_on_vds_tz2_vlan16_ip',
default="192.168.1.205",
help="IPv4 IP address of VM5"),
cfg.StrOpt('vm_on_vds_tz2_vlan17_ip',
default="192.168.1.206",
help="IPv4 IP address of VM6"),
]
nsxv3_group = cfg.OptGroup(name='nsxv3',
title="NSXv3 Configuration Options")
NSXv3Group = [
cfg.StrOpt('nsx_manager',
default='',
help="NSX manager IP address"),
cfg.StrOpt('nsx_user',
default='admin',
help="NSX manager username"),
cfg.StrOpt('nsx_password',
default='default',
help="NSX manager password"),
cfg.BoolOpt('native_dhcp_metadata',
default=False,
help="Enable or disable Native DHCP and MDProxy for nsxv3"),
]
@@ -1,90 +0,0 @@
Admin Policy
============
Admin policy, neutron extension secuirty-group-policy provides organization
to enforce traffic forwarding utilizing NSX security policy.
The "Admin Policy" feature is admin priviledge, normal project/tenant is not
able to create security-group-policy.
This feature can be enabled from devstack or manually.
Enable security-group-policy extention at bring up devstack
===========================================================
You can enable security-group-policy when starting up devstack.
However, if the policy-id does not exist, starting will fail.
To enable it, add the following tokens to local.conf:
NSXV_USE_NSX_POLICIES=True
NSXV_DEFAULT_POLICY_ID=policy-11
NSXV_ALLOW_TENANT_RULES_WITH_POLICY=True
Change values according to your needs though.
Enable security-group-policy extention manually
===============================================
Instruction is from the view of devstack
#. Add following items to /etc/neutron/policy.json::
"create_security_group:logging": "rule:admin_only",
"update_security_group:logging": "rule:admin_only",
"get_security_group:logging": "rule:admin_only",
"create_security_group:provider": "rule:admin_only",
"create_port:provider_security_groups": "rule:admin_only",
"create_security_group:policy": "rule:admin_only",
"update_security_group:policy": "rule:admin_only",
#. Add following key=value pair to session [nsxv] of /etc/neutron/plugin/vmware/nsx.ini::
use_nsx_policies = True
default_policy_id = policy-11
allow_tenant_rules_with_policy = False
# NOTE: For automation, set allow_tenant_rules_with_policy to True
tempest.conf
============
At session [nsxv] add the following 3 key=value pair:
default_policy_id = policy-11
alt_policy_id = policy-22
allow_tenant_rules_with_policy = False
# NOTE: default_policy_id and allow_tenant_rules_with_policy need to match nsx.ini
default_policy_id and alt_policy_id:
For API tests, both must exist at NSX.
For scenario tests, please refer to nsxv/scenario/test_admin_policy_basic_ops.py
In short::
policy-11 (policy-AA at script & test-plan) firewall rules::
action-1: dhcp-in/any/policy-security-groups/dhcp/Allow
action-2: dhcp-out/policy-security-groups/dhcp/Allow
action-3: ping-in/any/policy-security-groups/ICMP/Allow
action-4: ping-out/policy-security-groups/any/ICMP/Allow/
action-5: ssh-in/any/policy-security-groups/SSH/Allow/
action-6: ssh-in/any/policy-security-groups/SSH/Allow/
action-7: http-ok/any/policy-security-groups/HTTP,HTTPS/Allow/
action-8: sorry-nothing-allowed/any/policy-security-groups/Any/Reject
You can import policy-AA to NSX using the admin-policy-AA.blueprint
policy-22 (policy-BB at script & test-plan) firewall rules::
action-1: dhcp-in/any/policy-security-groups/dhcp/Allow
action-2: dhcp-out/policy-security-groups/dhcp/Allow
action-3: group-ping/policy-security-groups/policy-security-groups/ICMP/Allow/
action-4: ssh-in/any/policy-security-groups/SSH/Allow/
action-5: ssh-in/any/policy-security-groups/SSH/Allow/
action-6: http-ok/any/policy-security-groups/HTTP,HTTPS/Allow/
pction-7: sorry-nothing-allowed/any/policy-security-groups/Any/Reject
NOTE on ping: same as policy-11 but only allowed from policy-security-groups
You can import policy-BB to NSX using the admin-policy-BB.blueprint
-74
View File
@@ -1,74 +0,0 @@
Overview
========
This document describes what LBaaS tests are not supported at different
NSX plugin's and backends.
NOTE::
All LBaaS API & Scenario tests should PASS with exceptions
due to NSX plugins and features supported by backend.
For how tests can be skipped for specific plugin and backend,
please refer to paragraph "Config for Test Execution".
NOTE::
We no longer support LBaaS v1. So this document and LBaaS tests
only applys to releases from Mitaka/Marvin or later.
Limitation:
-----------
NSX-v with VMware LBaaS driver::
#. LBaaS networks need to attach to exclusive router
#. One tenant per subnet
#. L7 switching not supported
NSX-v3 with Octavia driver::
#. upstream implemenation - all tests should PASS.
#. scenario tests take long time, it might fail with fixture timeout.
Config for Test execution:
--------------------------
Following configuration attributes used to controll test execution::
#. no_router_type at group/session nsxv
Default is False, and is used to run LBaaS tests in NSX-v environment.
To run in NSX-t environment, set it to True
#. bugs_to_resolve at group/session nsxv
For test to skip if bug-ID presented in this attribute.
The test will use testtools.skipIf(condition, reason) to skip if its ID in the bugs_to_resolve list.
local.conf:
----------
NSX-v::
[nsxv]
no_router_type=False
bugs_to_resolve=1641902,1715126,1703396,1739510
NSX-v3::
[compute]
build_timeout=900
build_interval=2
[nsxv]
no_router_type=True
Execution:
----------
#. Use testr list-tests command to generate test suite for run API and Scenario tests::
tools/with_venv.sh testr list-tests nsxv.api.lbaas
tools/with_venv.sh testr list-tests nsxv.scenarion.test_lbaas
#. l7 switching tests take long time to complete. If got fixture timeout, do::
OS_TEST_TIMEOUT=2400 ./run_tempest.sh -t test_lbaas_l7_switching_ops
@@ -1,341 +0,0 @@
<securityPolicyHierarchy>
<name>admin-policy-AA</name>
<description>8 firewall rules - ping, ssh from anywhere are OK</description>
<securityPolicy>
<revision>0</revision>
<name>security-policy-AA</name>
<description>Security Policy AA</description>
<clientHandle></clientHandle>
<isUniversal>false</isUniversal>
<universalRevision>0</universalRevision>
<inheritanceAllowed>false</inheritanceAllowed>
<precedence>5500</precedence>
<actionsByCategory>
<category>firewall</category>
<action class="firewallSecurityAction">
<revision>0</revision>
<name>dhcp-in</name>
<clientHandle></clientHandle>
<isUniversal>false</isUniversal>
<universalRevision>0</universalRevision>
<category>firewall</category>
<executionOrder>1</executionOrder>
<isEnabled>true</isEnabled>
<isActionEnforced>false</isActionEnforced>
<invalidSecondaryContainers>false</invalidSecondaryContainers>
<applications>
<application>
<revision>0</revision>
<name>DHCP-Client</name>
<clientHandle></clientHandle>
<isUniversal>false</isUniversal>
<universalRevision>0</universalRevision>
<inheritanceAllowed>true</inheritanceAllowed>
<element>
<applicationProtocol>UDP</applicationProtocol>
<value>68</value>
</element>
</application>
<application>
<revision>0</revision>
<name>DHCP-Server</name>
<clientHandle></clientHandle>
<isUniversal>false</isUniversal>
<universalRevision>0</universalRevision>
<inheritanceAllowed>true</inheritanceAllowed>
<element>
<applicationProtocol>UDP</applicationProtocol>
<value>67</value>
</element>
</application>
</applications>
<invalidApplications>false</invalidApplications>
<logged>false</logged>
<action>allow</action>
<direction>inbound</direction>
<outsideSecondaryContainer>false</outsideSecondaryContainer>
</action>
<action class="firewallSecurityAction">
<revision>0</revision>
<name>dhcp-out</name>
<clientHandle></clientHandle>
<isUniversal>false</isUniversal>
<universalRevision>0</universalRevision>
<category>firewall</category>
<executionOrder>2</executionOrder>
<isEnabled>true</isEnabled>
<isActionEnforced>false</isActionEnforced>
<invalidSecondaryContainers>false</invalidSecondaryContainers>
<applications>
<application>
<revision>0</revision>
<name>DHCP-Client</name>
<clientHandle></clientHandle>
<isUniversal>false</isUniversal>
<universalRevision>0</universalRevision>
<inheritanceAllowed>true</inheritanceAllowed>
<element>
<applicationProtocol>UDP</applicationProtocol>
<value>68</value>
</element>
</application>
<application>
<revision>0</revision>
<name>DHCP-Server</name>
<clientHandle></clientHandle>
<isUniversal>false</isUniversal>
<universalRevision>0</universalRevision>
<inheritanceAllowed>true</inheritanceAllowed>
<element>
<applicationProtocol>UDP</applicationProtocol>
<value>67</value>
</element>
</application>
</applications>
<invalidApplications>false</invalidApplications>
<logged>false</logged>
<action>allow</action>
<direction>outbound</direction>
<outsideSecondaryContainer>false</outsideSecondaryContainer>
</action>
<action class="firewallSecurityAction">
<revision>0</revision>
<name>ping-in</name>
<description>Everyone can ping me</description>
<clientHandle></clientHandle>
<isUniversal>false</isUniversal>
<universalRevision>0</universalRevision>
<category>firewall</category>
<executionOrder>3</executionOrder>
<isEnabled>true</isEnabled>
<isActionEnforced>false</isActionEnforced>
<invalidSecondaryContainers>false</invalidSecondaryContainers>
<applications>
<application>
<revision>0</revision>
<name>ICMP Echo</name>
<clientHandle></clientHandle>
<isUniversal>false</isUniversal>
<universalRevision>0</universalRevision>
<inheritanceAllowed>true</inheritanceAllowed>
<element>
<applicationProtocol>ICMP</applicationProtocol>
<value>echo-request</value>
</element>
</application>
<application>
<revision>0</revision>
<name>ICMP Redirect</name>
<clientHandle></clientHandle>
<isUniversal>false</isUniversal>
<universalRevision>0</universalRevision>
<inheritanceAllowed>true</inheritanceAllowed>
<element>
<applicationProtocol>ICMP</applicationProtocol>
<value>redirect</value>
</element>
</application>
<application>
<revision>0</revision>
<name>ICMP Echo Reply</name>
<clientHandle></clientHandle>
<isUniversal>false</isUniversal>
<universalRevision>0</universalRevision>
<inheritanceAllowed>true</inheritanceAllowed>
<element>
<applicationProtocol>ICMP</applicationProtocol>
<value>echo-reply</value>
</element>
</application>
</applications>
<invalidApplications>false</invalidApplications>
<logged>false</logged>
<action>allow</action>
<direction>inbound</direction>
<outsideSecondaryContainer>false</outsideSecondaryContainer>
</action>
<action class="firewallSecurityAction">
<revision>0</revision>
<name>ping-out</name>
<clientHandle></clientHandle>
<isUniversal>false</isUniversal>
<universalRevision>0</universalRevision>
<category>firewall</category>
<executionOrder>4</executionOrder>
<isEnabled>true</isEnabled>
<isActionEnforced>false</isActionEnforced>
<invalidSecondaryContainers>false</invalidSecondaryContainers>
<applications>
<application>
<revision>0</revision>
<name>ICMP Echo</name>
<clientHandle></clientHandle>
<isUniversal>false</isUniversal>
<universalRevision>0</universalRevision>
<inheritanceAllowed>true</inheritanceAllowed>
<element>
<applicationProtocol>ICMP</applicationProtocol>
<value>echo-request</value>
</element>
</application>
<application>
<revision>0</revision>
<name>ICMP Redirect</name>
<clientHandle></clientHandle>
<isUniversal>false</isUniversal>
<universalRevision>0</universalRevision>
<inheritanceAllowed>true</inheritanceAllowed>
<element>
<applicationProtocol>ICMP</applicationProtocol>
<value>redirect</value>
</element>
</application>
<application>
<revision>0</revision>
<name>ICMP Echo Reply</name>
<clientHandle></clientHandle>
<isUniversal>false</isUniversal>
<universalRevision>0</universalRevision>
<inheritanceAllowed>true</inheritanceAllowed>
<element>
<applicationProtocol>ICMP</applicationProtocol>
<value>echo-reply</value>
</element>
</application>
</applications>
<invalidApplications>false</invalidApplications>
<logged>false</logged>
<action>allow</action>
<direction>outbound</direction>
<outsideSecondaryContainer>false</outsideSecondaryContainer>
</action>
<action class="firewallSecurityAction">
<revision>0</revision>
<name>ssh-in-ok</name>
<clientHandle></clientHandle>
<isUniversal>false</isUniversal>
<universalRevision>0</universalRevision>
<category>firewall</category>
<executionOrder>5</executionOrder>
<isEnabled>true</isEnabled>
<isActionEnforced>false</isActionEnforced>
<invalidSecondaryContainers>false</invalidSecondaryContainers>
<applications>
<application>
<revision>0</revision>
<name>SSH</name>
<clientHandle></clientHandle>
<isUniversal>false</isUniversal>
<universalRevision>0</universalRevision>
<inheritanceAllowed>true</inheritanceAllowed>
<element>
<applicationProtocol>TCP</applicationProtocol>
<value>22</value>
</element>
</application>
</applications>
<invalidApplications>false</invalidApplications>
<logged>false</logged>
<action>allow</action>
<direction>inbound</direction>
<outsideSecondaryContainer>false</outsideSecondaryContainer>
</action>
<action class="firewallSecurityAction">
<revision>0</revision>
<name>ssh-out-ok</name>
<clientHandle></clientHandle>
<isUniversal>false</isUniversal>
<universalRevision>0</universalRevision>
<category>firewall</category>
<executionOrder>6</executionOrder>
<isEnabled>true</isEnabled>
<isActionEnforced>false</isActionEnforced>
<invalidSecondaryContainers>false</invalidSecondaryContainers>
<applications>
<application>
<revision>0</revision>
<name>SSH</name>
<clientHandle></clientHandle>
<isUniversal>false</isUniversal>
<universalRevision>0</universalRevision>
<inheritanceAllowed>true</inheritanceAllowed>
<element>
<applicationProtocol>TCP</applicationProtocol>
<value>22</value>
</element>
</application>
</applications>
<invalidApplications>false</invalidApplications>
<logged>false</logged>
<action>allow</action>
<direction>outbound</direction>
<outsideSecondaryContainer>false</outsideSecondaryContainer>
</action>
<action class="firewallSecurityAction">
<revision>0</revision>
<name>HTTP-ok</name>
<description>All can http(s) me</description>
<clientHandle></clientHandle>
<isUniversal>false</isUniversal>
<universalRevision>0</universalRevision>
<category>firewall</category>
<executionOrder>7</executionOrder>
<isEnabled>true</isEnabled>
<isActionEnforced>false</isActionEnforced>
<invalidSecondaryContainers>false</invalidSecondaryContainers>
<applications>
<application>
<revision>0</revision>
<name>HTTP</name>
<clientHandle></clientHandle>
<isUniversal>false</isUniversal>
<universalRevision>0</universalRevision>
<inheritanceAllowed>true</inheritanceAllowed>
<element>
<applicationProtocol>TCP</applicationProtocol>
<value>80</value>
</element>
</application>
<application>
<revision>0</revision>
<name>HTTPS</name>
<clientHandle></clientHandle>
<isUniversal>false</isUniversal>
<universalRevision>0</universalRevision>
<inheritanceAllowed>true</inheritanceAllowed>
<element>
<applicationProtocol>TCP</applicationProtocol>
<value>443</value>
</element>
</application>
</applications>
<invalidApplications>false</invalidApplications>
<logged>false</logged>
<action>allow</action>
<direction>inbound</direction>
<outsideSecondaryContainer>false</outsideSecondaryContainer>
</action>
<action class="firewallSecurityAction">
<revision>0</revision>
<name>sorry-nothing-allowed</name>
<clientHandle></clientHandle>
<isUniversal>false</isUniversal>
<universalRevision>0</universalRevision>
<category>firewall</category>
<executionOrder>8</executionOrder>
<isEnabled>true</isEnabled>
<isActionEnforced>false</isActionEnforced>
<invalidSecondaryContainers>false</invalidSecondaryContainers>
<invalidApplications>false</invalidApplications>
<logged>false</logged>
<action>reject</action>
<direction>inbound</direction>
<outsideSecondaryContainer>false</outsideSecondaryContainer>
</action>
</actionsByCategory>
<statusesByCategory>
<category>firewall</category>
<status>in_sync</status>
</statusesByCategory>
</securityPolicy>
</securityPolicyHierarchy>
@@ -1,285 +0,0 @@
<securityPolicyHierarchy>
<name>admin-policy-BB</name>
<description>policy-BB, ssh from anywhere are OK, but ping limited to same security-group</description>
<securityPolicy>
<revision>0</revision>
<name>security-policy-BB</name>
<description>Security Policy BB</description>
<clientHandle></clientHandle>
<isUniversal>false</isUniversal>
<universalRevision>0</universalRevision>
<inheritanceAllowed>false</inheritanceAllowed>
<precedence>5600</precedence>
<actionsByCategory>
<category>firewall</category>
<action class="firewallSecurityAction">
<revision>0</revision>
<name>dhcp-in</name>
<clientHandle></clientHandle>
<isUniversal>false</isUniversal>
<universalRevision>0</universalRevision>
<category>firewall</category>
<executionOrder>1</executionOrder>
<isEnabled>true</isEnabled>
<isActionEnforced>false</isActionEnforced>
<invalidSecondaryContainers>false</invalidSecondaryContainers>
<applications>
<application>
<revision>0</revision>
<name>DHCP-Client</name>
<clientHandle></clientHandle>
<isUniversal>false</isUniversal>
<universalRevision>0</universalRevision>
<inheritanceAllowed>true</inheritanceAllowed>
<element>
<applicationProtocol>UDP</applicationProtocol>
<value>68</value>
</element>
</application>
<application>
<revision>0</revision>
<name>DHCP-Server</name>
<clientHandle></clientHandle>
<isUniversal>false</isUniversal>
<universalRevision>0</universalRevision>
<inheritanceAllowed>true</inheritanceAllowed>
<element>
<applicationProtocol>UDP</applicationProtocol>
<value>67</value>
</element>
</application>
</applications>
<invalidApplications>false</invalidApplications>
<logged>false</logged>
<action>allow</action>
<direction>inbound</direction>
<outsideSecondaryContainer>false</outsideSecondaryContainer>
</action>
<action class="firewallSecurityAction">
<revision>0</revision>
<name>dhcp-out</name>
<clientHandle></clientHandle>
<isUniversal>false</isUniversal>
<universalRevision>0</universalRevision>
<category>firewall</category>
<executionOrder>2</executionOrder>
<isEnabled>true</isEnabled>
<isActionEnforced>false</isActionEnforced>
<invalidSecondaryContainers>false</invalidSecondaryContainers>
<applications>
<application>
<revision>0</revision>
<name>DHCP-Client</name>
<clientHandle></clientHandle>
<isUniversal>false</isUniversal>
<universalRevision>0</universalRevision>
<inheritanceAllowed>true</inheritanceAllowed>
<element>
<applicationProtocol>UDP</applicationProtocol>
<value>68</value>
</element>
</application>
<application>
<revision>0</revision>
<name>DHCP-Server</name>
<clientHandle></clientHandle>
<isUniversal>false</isUniversal>
<universalRevision>0</universalRevision>
<inheritanceAllowed>true</inheritanceAllowed>
<element>
<applicationProtocol>UDP</applicationProtocol>
<value>67</value>
</element>
</application>
</applications>
<invalidApplications>false</invalidApplications>
<logged>false</logged>
<action>allow</action>
<direction>outbound</direction>
<outsideSecondaryContainer>false</outsideSecondaryContainer>
</action>
<action class="firewallSecurityAction">
<revision>0</revision>
<name>group-ping-ok</name>
<description>icmp only allowed from VM with same security-policy</description>
<clientHandle></clientHandle>
<isUniversal>false</isUniversal>
<universalRevision>0</universalRevision>
<category>firewall</category>
<executionOrder>3</executionOrder>
<isEnabled>true</isEnabled>
<isActionEnforced>false</isActionEnforced>
<invalidSecondaryContainers>false</invalidSecondaryContainers>
<applications>
<application>
<revision>0</revision>
<name>ICMP Echo</name>
<clientHandle></clientHandle>
<isUniversal>false</isUniversal>
<universalRevision>0</universalRevision>
<inheritanceAllowed>true</inheritanceAllowed>
<element>
<applicationProtocol>ICMP</applicationProtocol>
<value>echo-request</value>
</element>
</application>
<application>
<revision>0</revision>
<name>ICMP Redirect</name>
<clientHandle></clientHandle>
<isUniversal>false</isUniversal>
<universalRevision>0</universalRevision>
<inheritanceAllowed>true</inheritanceAllowed>
<element>
<applicationProtocol>ICMP</applicationProtocol>
<value>redirect</value>
</element>
</application>
<application>
<revision>0</revision>
<name>ICMP Echo Reply</name>
<clientHandle></clientHandle>
<isUniversal>false</isUniversal>
<universalRevision>0</universalRevision>
<inheritanceAllowed>true</inheritanceAllowed>
<element>
<applicationProtocol>ICMP</applicationProtocol>
<value>echo-reply</value>
</element>
</application>
</applications>
<invalidApplications>false</invalidApplications>
<logged>false</logged>
<action>allow</action>
<direction>intra</direction>
<outsideSecondaryContainer>false</outsideSecondaryContainer>
</action>
<action class="firewallSecurityAction">
<revision>0</revision>
<name>ssh-in-ok</name>
<clientHandle></clientHandle>
<isUniversal>false</isUniversal>
<universalRevision>0</universalRevision>
<category>firewall</category>
<executionOrder>4</executionOrder>
<isEnabled>true</isEnabled>
<isActionEnforced>false</isActionEnforced>
<invalidSecondaryContainers>false</invalidSecondaryContainers>
<applications>
<application>
<revision>0</revision>
<name>SSH</name>
<clientHandle></clientHandle>
<isUniversal>false</isUniversal>
<universalRevision>0</universalRevision>
<inheritanceAllowed>true</inheritanceAllowed>
<element>
<applicationProtocol>TCP</applicationProtocol>
<value>22</value>
</element>
</application>
</applications>
<invalidApplications>false</invalidApplications>
<logged>false</logged>
<action>allow</action>
<direction>inbound</direction>
<outsideSecondaryContainer>false</outsideSecondaryContainer>
</action>
<action class="firewallSecurityAction">
<revision>0</revision>
<name>ssh-out-ok</name>
<clientHandle></clientHandle>
<isUniversal>false</isUniversal>
<universalRevision>0</universalRevision>
<category>firewall</category>
<executionOrder>5</executionOrder>
<isEnabled>true</isEnabled>
<isActionEnforced>false</isActionEnforced>
<invalidSecondaryContainers>false</invalidSecondaryContainers>
<applications>
<application>
<revision>0</revision>
<name>SSH</name>
<clientHandle></clientHandle>
<isUniversal>false</isUniversal>
<universalRevision>0</universalRevision>
<inheritanceAllowed>true</inheritanceAllowed>
<element>
<applicationProtocol>TCP</applicationProtocol>
<value>22</value>
</element>
</application>
</applications>
<invalidApplications>false</invalidApplications>
<logged>false</logged>
<action>allow</action>
<direction>outbound</direction>
<outsideSecondaryContainer>false</outsideSecondaryContainer>
</action>
<action class="firewallSecurityAction">
<revision>0</revision>
<name>group-HTTP</name>
<clientHandle></clientHandle>
<isUniversal>false</isUniversal>
<universalRevision>0</universalRevision>
<category>firewall</category>
<executionOrder>6</executionOrder>
<isEnabled>true</isEnabled>
<isActionEnforced>false</isActionEnforced>
<invalidSecondaryContainers>false</invalidSecondaryContainers>
<applications>
<application>
<revision>0</revision>
<name>HTTP</name>
<clientHandle></clientHandle>
<isUniversal>false</isUniversal>
<universalRevision>0</universalRevision>
<inheritanceAllowed>true</inheritanceAllowed>
<element>
<applicationProtocol>TCP</applicationProtocol>
<value>80</value>
</element>
</application>
<application>
<revision>0</revision>
<name>HTTPS</name>
<clientHandle></clientHandle>
<isUniversal>false</isUniversal>
<universalRevision>0</universalRevision>
<inheritanceAllowed>true</inheritanceAllowed>
<element>
<applicationProtocol>TCP</applicationProtocol>
<value>443</value>
</element>
</application>
</applications>
<invalidApplications>false</invalidApplications>
<logged>false</logged>
<action>allow</action>
<direction>intra</direction>
<outsideSecondaryContainer>false</outsideSecondaryContainer>
</action>
<action class="firewallSecurityAction">
<revision>0</revision>
<name>sorry-nothing-allowed</name>
<clientHandle></clientHandle>
<isUniversal>false</isUniversal>
<universalRevision>0</universalRevision>
<category>firewall</category>
<executionOrder>7</executionOrder>
<isEnabled>true</isEnabled>
<isActionEnforced>false</isActionEnforced>
<invalidSecondaryContainers>false</invalidSecondaryContainers>
<invalidApplications>false</invalidApplications>
<logged>false</logged>
<action>reject</action>
<direction>inbound</direction>
<outsideSecondaryContainer>false</outsideSecondaryContainer>
</action>
</actionsByCategory>
<statusesByCategory>
<category>firewall</category>
<status>in_sync</status>
</statusesByCategory>
</securityPolicy>
</securityPolicyHierarchy>
View File
Whitespace-only changes.
-234
View File
@@ -1,234 +0,0 @@
# Copyright 2017 VMware Inc
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import collections
import netaddr
from oslo_log import log as logging
from tempest import config
from tempest.lib.common.utils import data_utils
from tempest.lib.common.utils import test_utils
from tempest.lib import exceptions as lib_exc
from vmware_nsx_tempest.common import constants
from vmware_nsx_tempest.tests.scenario import manager
CONF = config.CONF
LOG = logging.getLogger(__name__)
class ApplianceManager(manager.NetworkScenarioTest):
server_details = collections.namedtuple('server_details',
['server', 'floating_ip',
'networks'])
def setUp(self):
super(ApplianceManager, self).setUp()
self.topology_routers = {}
self.topology_networks = {}
self.topology_subnets = {}
self.topology_servers = {}
self.topology_servers_floating_ip = []
self.topology_public_network_id = CONF.network.public_network_id
self.topology_config_drive = CONF.compute_feature_enabled.config_drive
self.topology_keypairs = {}
self.servers_details = {}
def get_internal_ips(self, server, network, device="network"):
internal_ips = [p['fixed_ips'][0]['ip_address'] for p in
self.os_admin.ports_client.list_ports(
tenant_id=server['tenant_id'],
network_id=network['id'])['ports'] if
p['device_owner'].startswith(device)]
return internal_ips
def _verify_empty_security_group_status(self, security_group):
ip_protocols = ["IPV6", "IPV4"]
nsx_fw_section, nsx_fw_section_rules = \
self.nsx_client.get_firewall_section_and_rules(
security_group['name'], security_group['id'])
msg = "Newly created empty security group does not meet criteria !!!"
self.assertEqual(nsx_fw_section["rule_count"], 2, msg)
self.assertEqual(nsx_fw_section_rules[0]["action"], "ALLOW", msg)
self.assertEqual(nsx_fw_section_rules[1]["action"], "ALLOW", msg)
self.assertEqual(nsx_fw_section_rules[0]["direction"], "OUT", msg)
self.assertEqual(nsx_fw_section_rules[1]["direction"], "OUT", msg)
self.assertIn(nsx_fw_section_rules[0]["ip_protocol"], ip_protocols,
msg)
self.assertIn(nsx_fw_section_rules[1]["ip_protocol"], ip_protocols,
msg)
def create_topology_empty_security_group(self, namestart="vmw_"):
security_group = self._create_empty_security_group(namestart=namestart)
self._verify_empty_security_group_status(security_group)
return security_group
def add_security_group_rule(self, security_group, rule):
return self._create_security_group_rule(secgroup=security_group,
**rule)
def get_server_key(self, server):
return self.topology_keypairs[server['key_name']]['private_key']
def create_topology_router(self, router_name, routers_client=None,
**kwargs):
if not routers_client:
routers_client = self.routers_client
router_name_ = constants.APPLIANCE_NAME_STARTS_WITH + router_name
router = self._create_router(namestart=router_name_, **kwargs)
public_network_info = {"external_gateway_info": dict(
network_id=self.topology_public_network_id)}
routers_client.update_router(router['id'], **public_network_info)
self.topology_routers[router_name] = router
return router
def create_topology_network(self, network_name, networks_client=None,
tenant_id=None, port_security_enabled=True, **kwargs):
if not networks_client:
networks_client = self.networks_client
if not tenant_id:
tenant_id = networks_client.tenant_id
network_name_ = constants.APPLIANCE_NAME_STARTS_WITH + network_name
name = data_utils.rand_name(network_name_)
# Neutron disables port security by default so we have to check the
# config before trying to create the network with port_security_enabled
if CONF.network_feature_enabled.port_security:
port_security_enabled = True
result = networks_client.create_network(
name=name, tenant_id=tenant_id,
port_security_enabled=port_security_enabled, **kwargs)
network = result['network']
self.assertEqual(network['name'], name)
self.addCleanup(test_utils.call_and_ignore_notfound_exc,
networks_client.delete_network, network['id'])
self.topology_networks[network_name] = network
return network
def create_topology_subnet(
self, subnet_name, network, routers_client=None,
subnets_client=None, router_id=None, ip_version=4, cidr=None,
mask_bits=None, **kwargs):
subnet_name_ = constants.APPLIANCE_NAME_STARTS_WITH + subnet_name
if not subnets_client:
subnets_client = self.subnets_client
if not routers_client:
routers_client = self.routers_client
def cidr_in_use(cidr, tenant_id):
"""Check cidr existence
:returns: True if subnet with cidr already exist in tenant
False else
"""
cidr_in_use = \
self.os_admin.subnets_client.list_subnets(tenant_id=tenant_id,
cidr=cidr)['subnets']
return len(cidr_in_use) != 0
if ip_version == 6:
tenant_cidr = (cidr or netaddr.IPNetwork(
CONF.network.project_network_v6_cidr))
mask_bits = mask_bits or CONF.network.project_network_v6_mask_bits
else:
tenant_cidr = cidr or netaddr.IPNetwork(
CONF.network.project_network_cidr)
mask_bits = mask_bits or CONF.network.project_network_mask_bits
str_cidr = str(tenant_cidr)
if not cidr:
# Repeatedly attempt subnet creation with sequential cidr
# blocks until an unallocated block is found.
for subnet_cidr in tenant_cidr.subnet(mask_bits):
str_cidr = str(subnet_cidr)
if not cidr_in_use(str_cidr, tenant_id=network['tenant_id']):
break
else:
if cidr_in_use(str_cidr, tenant_id=network['tenant_id']):
LOG.error("Specified subnet %r is in use" % str_cidr)
raise
subnet = dict(name=data_utils.rand_name(subnet_name_),
network_id=network['id'], tenant_id=network['tenant_id'],
cidr=str_cidr, ip_version=ip_version, **kwargs)
try:
result = None
result = subnets_client.create_subnet(**subnet)
except lib_exc.Conflict as e:
is_overlapping_cidr = 'overlaps with another subnet' in str(e)
if not is_overlapping_cidr:
raise
self.assertIsNotNone(result, 'Unable to allocate tenant network')
subnet = result['subnet']
self.assertEqual(subnet['cidr'], str_cidr)
self.addCleanup(test_utils.call_and_ignore_notfound_exc,
subnets_client.delete_subnet, subnet['id'])
self.topology_subnets[subnet_name] = subnet
if router_id:
if not routers_client:
routers_client = self.routers_client
routers_client.add_router_interface(
router_id, subnet_id=subnet["id"])
self.addCleanup(
test_utils.call_and_ignore_notfound_exc,
routers_client.remove_router_interface, router_id,
subnet_id=subnet["id"])
return subnet
def create_topology_security_group(self, **kwargs):
return self._create_security_group(**kwargs)
def create_topology_instance(
self, server_name, networks, security_groups=None,
config_drive=None, keypair=None, image_id=None,
clients=None, create_floating_ip=True, **kwargs):
# Define security group for server.
if security_groups:
kwargs["security_groups"] = security_groups
else:
_sg = self.create_topology_security_group()
_security_groups = [{'name': _sg['name']}]
kwargs["security_groups"] = _security_groups
# Define config drive for server.
if not config_drive:
kwargs["config_drive"] = self.topology_config_drive
else:
kwargs["config_drive"] = config_drive
if not keypair:
keypair = self.create_keypair()
self.topology_keypairs[keypair['name']] = keypair
kwargs["key_name"] = keypair['name']
else:
kwargs["key_name"] = keypair['name']
# Define image id for server.
if image_id:
kwargs["image_id"] = image_id
server_name_ = constants.APPLIANCE_NAME_STARTS_WITH + server_name
# Collect all the networks for server.
networks_ = []
for net in networks:
net_ = {"uuid": net["id"]}
networks_.append(net_)
# Deploy server with all teh args.
server = self.create_server(
name=server_name_, networks=networks_, clients=clients, **kwargs)
if create_floating_ip:
floating_ip = self.create_floating_ip(server)
server["floating_ip"] = floating_ip
self.topology_servers_floating_ip.append(floating_ip)
else:
floating_ip = None
server_details = self.server_details(server=server,
floating_ip=floating_ip,
networks=networks)
self.servers_details[server_name] = server_details
self.topology_servers[server_name] = server
return server
-172
View File
@@ -1,172 +0,0 @@
# Copyright 2017 VMware Inc
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from tempest import config
from tempest.lib.common.utils import test_utils
from vmware_nsx_tempest._i18n import _
from vmware_nsx_tempest.common import constants
from vmware_nsx_tempest.lib import traffic_manager
from vmware_nsx_tempest.services import nsx_client
from vmware_nsx_tempest.services import openstack_network_clients
LOG = constants.log.getLogger(__name__)
CONF = config.CONF
# It includes feature related function such CRUD Mdproxy, L2GW or QoS
class FeatureManager(traffic_manager.TrafficManager):
@classmethod
def setup_clients(cls):
"""
Create various client connections. Such as NSXv3 and L2 Gateway.
"""
super(FeatureManager, cls).setup_clients()
try:
manager = getattr(cls.os_admin, "manager", cls.os_admin)
net_client = getattr(manager, "networks_client")
_params = manager.default_params_withy_timeout_values.copy()
except AttributeError as attribute_err:
LOG.warning(
"Failed to locate the attribute, Error: %(err_msg)s",
{"err_msg": attribute_err.__str__()})
_params = {}
cls.l2gw_client = openstack_network_clients.L2GatewayClient(
net_client.auth_provider,
net_client.service,
net_client.region,
net_client.endpoint_type,
**_params)
cls.nsx_client = nsx_client.NSXClient(
CONF.network.backend,
CONF.nsxv3.nsx_manager,
CONF.nsxv3.nsx_user,
CONF.nsxv3.nsx_password)
cls.l2gwc_client = openstack_network_clients.L2GatewayConnectionClient(
net_client.auth_provider,
net_client.service,
net_client.region,
net_client.endpoint_type,
**_params)
#
# L2Gateway base class. To get basics of L2GW.
#
def create_l2gw(self, l2gw_name, l2gw_param):
"""
Creates L2GW and returns the response.
:param l2gw_name: name of the L2GW
:param l2gw_param: L2GW parameters
:return: response of L2GW create API
"""
LOG.info("l2gw name: %(name)s, l2gw_param: %(devices)s ",
{"name": l2gw_name, "devices": l2gw_param})
devices = []
for device_dict in l2gw_param:
interface = [{"name": device_dict["iname"],
"segmentation_id": device_dict[
"vlans"]}] if "vlans" in device_dict else [
{"name": device_dict["iname"]}]
device = {"device_name": device_dict["dname"],
"interfaces": interface}
devices.append(device)
l2gw_request_body = {"devices": devices}
LOG.info(" l2gw_request_body: %s", l2gw_request_body)
rsp = self.l2gw_client.create_l2_gateway(
name=l2gw_name, **l2gw_request_body)
LOG.info(" l2gw response: %s", rsp)
self.addCleanup(
test_utils.call_and_ignore_notfound_exc,
self.l2gw_client.delete_l2_gateway, rsp[constants.L2GW]["id"])
return rsp, devices
def delete_l2gw(self, l2gw_id):
"""
Delete L2gw.
:param l2gw_id: L2GW id to delete l2gw.
:return: response of the l2gw delete API.
"""
LOG.info("L2GW id: %(id)s to be deleted.", {"id": l2gw_id})
rsp = self.l2gw_client.delete_l2_gateway(l2gw_id)
LOG.info("response : %(rsp)s", {"rsp": rsp})
return rsp
def update_l2gw(self, l2gw_id, l2gw_new_name, devices):
"""
Update existing L2GW.
:param l2gw_id: L2GW id to update its parameters.
:param l2gw_new_name: name of the L2GW.
:param devices: L2GW parameters.
:return: Response of the L2GW update API.
"""
rsp = self.l2gw_client.update_l2_gateway(l2gw_id,
name=l2gw_new_name, **devices)
return rsp
def nsx_bridge_cluster_info(self):
"""
Collect the device and interface name of the nsx brdige cluster.
:return: nsx bridge id and display name.
"""
response = self.nsx_client.get_bridge_cluster_info()
if len(response) == 0:
raise RuntimeError(_("NSX bridge cluster information is null"))
return [(x.get("id"), x.get("display_name")) for x in response]
def create_l2gw_connection(self, l2gwc_param):
"""
Creates L2GWC and return the response.
:param l2gwc_param: L2GWC parameters.
:return: response of L2GWC create API.
"""
LOG.info("l2gwc param: %(param)s ", {"param": l2gwc_param})
l2gwc_request_body = {"l2_gateway_id": l2gwc_param["l2_gateway_id"],
"network_id": l2gwc_param["network_id"]}
if "segmentation_id" in l2gwc_param:
l2gwc_request_body["segmentation_id"] = l2gwc_param[
"segmentation_id"]
LOG.info("l2gwc_request_body: %s", l2gwc_request_body)
rsp = self.l2gwc_client.create_l2_gateway_connection(
**l2gwc_request_body)
LOG.info("l2gwc response: %s", rsp)
self.addCleanup(
test_utils.call_and_ignore_notfound_exc,
self.l2gwc_client.delete_l2_gateway_connection,
rsp[constants.L2GWC]["id"])
return rsp
def delete_l2gw_connection(self, l2gwc_id):
"""
Delete L2GWC and returns the response.
:param l2gwc_id: L2GWC id to delete L2GWC.
:return: response of the l2gwc delete API.
"""
LOG.info("L2GW connection id: %(id)s to be deleted",
{"id": l2gwc_id})
rsp = self.l2gwc_client.delete_l2_gateway_connection(l2gwc_id)
LOG.info("response : %(rsp)s", {"rsp": rsp})
return rsp
-65
View File
@@ -1,65 +0,0 @@
# Copyright 2017 VMware Inc
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from vmware_nsx_tempest.lib import appliance_manager
class TrafficManager(appliance_manager.ApplianceManager):
def check_server_internal_ips_using_floating_ip(self, floating_ip, server,
address_list, should_connect=True):
ip_address = floating_ip['floating_ip_address']
private_key = self.get_server_key(server)
ssh_source = self.get_remote_client(ip_address,
private_key=private_key)
for remote_ip in address_list:
self.check_remote_connectivity(ssh_source, remote_ip,
should_succeed=should_connect)
def check_network_internal_connectivity(self, network, floating_ip, server,
should_connect=True):
"""via ssh check VM internal connectivity:
- ping internal gateway and DHCP port, implying in-tenant connectivity
pinging both, because L3 and DHCP agents might be on different nodes
"""
# get internal ports' ips:
# get all network ports in the new network
internal_ips = self.get_internal_ips(server, network, device="network")
self.check_server_internal_ips_using_floating_ip(floating_ip, server,
internal_ips, should_connect)
def check_vm_internal_connectivity(self, network, floating_ip, server,
should_connect=True):
# test internal connectivity to the other VM on the same network
compute_ips = self.get_internal_ips(server, network, device="compute")
self.check_server_internal_ips_using_floating_ip(floating_ip, server,
compute_ips, should_connect)
def using_floating_ip_check_server_and_project_network_connectivity(self,
server_details, network=None):
if not network:
network = server_details.networks[0]
floating_ip = server_details.floating_ip
server = server_details.server
self.check_network_internal_connectivity(network, floating_ip, server)
self.check_vm_internal_connectivity(network, floating_ip, server)
def check_cross_network_connectivity(self, network1,
floating_ip_on_network2, server_on_network2, should_connect=False):
# test internal connectivity to the other VM on the same network
remote_ips = self.get_internal_ips(server_on_network2, network1,
device="compute")
self.check_server_internal_ips_using_floating_ip(
floating_ip_on_network2, server_on_network2, remote_ips,
should_connect)
-60
View File
@@ -1,60 +0,0 @@
# Copyright 2015 VMware, Inc.
#
# All Rights Reserved
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import os
from tempest import config
from tempest.test_discover import plugins
from vmware_nsx_tempest import config as config_nsx
_opts = [
(config_nsx.scenario_group, config_nsx.ScenarioGroup),
(config_nsx.network_group, config_nsx.NetworkGroup),
(config_nsx.nsxv_group, config_nsx.NSXvGroup),
(config_nsx.l2gw_group, config_nsx.L2gwGroup),
(config_nsx.nsxv3_group, config_nsx.NSXv3Group)
]
class VMwareNsxTempestPlugin(plugins.TempestPlugin):
"""Our addon configuration is defined at vmware_nsx_tempest/config.py
1. register_opts() to register group/opts to Tempest
2. get_opt_lists() to pass config to Tempest
The official plugin is defined at
https://docs.openstack.org/developer/tempest/plugin.html
"""
def load_tests(self):
mydir = os.path.dirname(os.path.abspath(__file__))
base_path = os.path.split(mydir)[0]
test_dir = "vmware_nsx_tempest/tests"
test_fullpath = os.path.join(base_path, test_dir)
return test_fullpath, base_path
def register_opts(self, conf):
conf.register_opt(config_nsx.service_option,
group='service_available')
for group, option in _opts:
config.register_opt_group(conf, group, option)
def get_opt_lists(self):
return [(group.name, option) for group, option in _opts
].append(('service_available', [config_nsx.service_option]))
-42
View File
@@ -1,42 +0,0 @@
This folder contains services for managing NSX-v, NSX-v3.
Services provided:
# OpenStack tempest service clients
l2_gateway_client.py
based on tempest BaseNetworkClient implements client APIs to manage
neutron l2-gateway resources
l2_gateway_connection_client.py
based on tempest BaseNetworkClient implements client APIs to manage
neutron l2-gateway-connection resources
lbaas v2 clients: ported from neutron_lbaas to comply with tempest services.
lbaas/load_balancers_client.py
lbaas/listeners_client.py
lbaas/pools_client.py
lbaas/health_monitorys_client.py
lbaas/members_client.py
lbv1_client.py
based on tempest BaseNetworkClient implements client APIs to manage
neutron v1 load-balancer resources
network_client_base.py
due to tempest network services are in the process of migrating to
tempest-lib, some features to be used by tests are not in
BaseNetworkClient. Inherent here and used by all vmware-nsx-tempest
client for now.
# NSX speific services
nsxv_client.py implements API to manage NSX-v components
- Logical switch (Tenant network)
- Edge (Service edge, DHCP edge, and VDR edge)
- DFW firewall rules (Security group)
- SpoofGuard
nsxv3_client.py implements API to manage NSX backend resources:
- logical switch
- firewall section
- nsgroup
- logical router
Whitespace-only changes.
-103
View File
@@ -1,103 +0,0 @@
# Copyright 2016 VMware Inc
# All Rights Reserved.
#
# Copyright 2015 Hewlett-Packard Development Company, L.P.
# Copyright 2015 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from tempest import config
from vmware_nsx_tempest.common import constants
LOG = constants.log.getLogger(__name__)
CONF = config.CONF
SEGMENTATION_ID_DELIMITER = "#"
INTERFACE_SEG_ID_DELIMITER = "|"
DEVICE_INTERFACE_DELIMITER = "::"
DEVICE_DELIMITER = ","
INTERFACE_DELIMITER = ";"
"""
Sample for providing input for gateway creation in config is noted below
Options provide flexibility to user to create l2gateway
For single device ,single interface with single vlan
l2gw_switch = device_name1::int_name1|vlan1
For single device multiple interfaces with single or multiple vlans
l2gw_switch = device_name1::int_name1|vlan1#vlan2;int_name2|vlan3
For multiple devices with mutiple interfaces having single or mutiple vlan
l2gw_switch = device_n1::int_n1|vlan1,device_n2::int_n2|vlan2#vlan3
"""
def get_interface(interfaces):
interface_dict = []
for interface in interfaces:
if INTERFACE_SEG_ID_DELIMITER in interface:
int_name = interface.split(INTERFACE_SEG_ID_DELIMITER)[0]
segid = interface.split(INTERFACE_SEG_ID_DELIMITER)[1]
if SEGMENTATION_ID_DELIMITER in segid:
segid = segid.split(SEGMENTATION_ID_DELIMITER)
else:
segid = [segid]
interface_detail = {'name': int_name, 'segmentation_id': segid}
else:
interface_detail = {'name': interface}
interface_dict.append(interface_detail)
return interface_dict
def get_device_interface(device_name, interface):
if INTERFACE_DELIMITER in interface:
interface_dict = interface.split(INTERFACE_DELIMITER)
interfaces = get_interface(interface_dict)
else:
interfaces = get_interface([interface])
device = {'device_name': device_name,
'interfaces': interfaces}
return device
def get_l2gw_body(l2gw_conf):
device_dict = []
devices = l2gw_conf.split(DEVICE_DELIMITER)
for device in devices:
if DEVICE_INTERFACE_DELIMITER in device:
device_name = device.split(DEVICE_INTERFACE_DELIMITER)[0]
interface = device.split(DEVICE_INTERFACE_DELIMITER)[1]
device = get_device_interface(device_name, interface)
device_dict.append(device)
body = {'devices': device_dict}
return body
def form_dict_devices(devices):
seg_ids = []
devices1 = dict()
int_seg = []
for device in devices:
device_name = device['device_name']
interfaces = device['interfaces']
for interface in interfaces:
interface_name = interface['name']
int_seg.append(interface_name)
seg_id = interface['segmentation_id']
if type(seg_id) is list:
for segid in seg_id:
seg_ids.append(segid)
else:
seg_ids.append(seg_id)
int_seg.append(seg_id)
devices1.setdefault(device_name, []).append(int_seg)
int_seg = []
return devices1
-131
View File
@@ -1,131 +0,0 @@
# Copyright (c) 2015 Midokura SARL
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from tempest import config
from tempest.lib import exceptions as lib_exc
from vmware_nsx_tempest.services import network_client_base as base
CONF = config.CONF
class FWaaSV1Client(base.BaseNetworkClient):
def create_firewall(self, **kwargs):
uri = '/fw/firewalls'
post_data = {'firewall': kwargs}
return self.create_resource(uri, post_data)
def update_firewall(self, firewall_id, **kwargs):
uri = '/fw/firewalls/%s' % firewall_id
post_data = {'firewall': kwargs}
return self.update_resource(uri, post_data)
def show_firewall(self, firewall_id, **fields):
uri = '/fw/firewalls/%s' % firewall_id
return self.show_resource(uri, **fields)
def delete_firewall(self, firewall_id):
uri = '/fw/firewalls/%s' % firewall_id
return self.delete_resource(uri)
def list_firewalls(self, **filters):
uri = '/fw/firewalls'
return self.list_resources(uri, **filters)
def create_firewall_rule(self, **kwargs):
uri = '/fw/firewall_rules'
post_data = {'firewall_rule': kwargs}
return self.create_resource(uri, post_data)
def update_firewall_rule(self, firewall_rule_id, **kwargs):
uri = '/fw/firewall_rules/%s' % firewall_rule_id
post_data = {'firewall_rule': kwargs}
return self.update_resource(uri, post_data)
def show_firewall_rule(self, firewall_rule_id, **fields):
uri = '/fw/firewall_rules/%s' % firewall_rule_id
return self.show_resource(uri, **fields)
def delete_firewall_rule(self, firewall_rule_id):
uri = '/fw/firewall_rules/%s' % firewall_rule_id
return self.delete_resource(uri)
def list_firewall_rules(self, **filters):
uri = '/fw/firewall_rules'
return self.list_resources(uri, **filters)
def is_resource_deleted(self, id):
try:
self.show_firewall(id)
except lib_exc.NotFound:
return True
return False
def create_firewall_policy(self, **kwargs):
uri = '/fw/firewall_policies'
post_data = {'firewall_policy': kwargs}
return self.create_resource(uri, post_data)
def update_firewall_policy(self, firewall_policy_id, **kwargs):
uri = '/fw/firewall_policies/%s' % firewall_policy_id
post_data = {'firewall_policy': kwargs}
return self.update_resource(uri, post_data)
def show_firewall_policy(self, firewall_policy_id, **fields):
uri = '/fw/firewall_policies/%s' % firewall_policy_id
return self.show_resource(uri, **fields)
def delete_firewall_policy(self, firewall_policy_id):
uri = '/fw/firewall_policies/%s' % firewall_policy_id
return self.delete_resource(uri)
def list_firewall_policies(self, **filters):
uri = '/fw/firewall_policies'
return self.list_resources(uri, **filters)
def insert_firewall_rule_in_policy(self, firewall_policy_id,
firewall_rule_id, insert_after='',
insert_before=''):
uri = '/fw/firewall_policies/%s/insert_rule' % firewall_policy_id
data = {
'firewall_rule_id': firewall_rule_id,
'insert_after': insert_after,
'insert_before': insert_before,
}
return self.update_resource(uri, data)
def remove_firewall_rule_from_policy(self, firewall_policy_id,
firewall_rule_id):
uri = '/fw/firewall_policies/%s/remove_rule' % firewall_policy_id
data = {
'firewall_rule_id': firewall_rule_id,
}
return self.update_resource(uri, data)
def get_client(client_mgr):
manager = getattr(client_mgr, 'manager', client_mgr)
net_client = getattr(manager, 'networks_client')
try:
_params = base.default_params_with_timeout_values.copy()
except Exception:
_params = {}
client = FWaaSV1Client(net_client.auth_provider,
net_client.service,
net_client.region,
net_client.endpoint_type,
**_params)
return client
@@ -1,82 +0,0 @@
# Copyright 2016 VMware, Inc.
# All Rights Reserved
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from oslo_log import log
from tempest.lib.services.network import base
from vmware_nsx_tempest.common import constants
LOG = log.getLogger(__name__)
class L2GatewayClient(base.BaseNetworkClient):
"""
Request resources via API for L2GatewayClient
l2 gateway create request
l2 gateway update request
l2 gateway show request
l2 gateway delete request
l2 gateway list all request
"""
def create_l2_gateway(self, **kwargs):
uri = constants.L2_GWS_BASE_URI
post_data = {constants.L2GW: kwargs}
LOG.info("URI : %(uri)s, posting data : %(post_data)s",
{"uri": uri, "post_data": post_data})
return self.create_resource(uri, post_data)
def update_l2_gateway(self, l2_gateway_id, **kwargs):
uri = constants.L2_GWS_BASE_URI + "/" + l2_gateway_id
post_data = {constants.L2GW: kwargs}
constants.LOG.info(
"URI : %(uri)s, posting data : %(post_data)s",
{"uri": uri, "post_data": post_data})
return self.update_resource(uri, post_data)
def show_l2_gateway(self, l2_gateway_id, **fields):
uri = constants.L2_GWS_BASE_URI + "/" + l2_gateway_id
LOG.info("URI : %(uri)s", {"uri": uri})
return self.show_resource(uri, **fields)
def delete_l2_gateway(self, l2_gateway_id):
uri = constants.L2_GWS_BASE_URI + "/" + l2_gateway_id
LOG.info("URI : %(uri)s", {"uri": uri})
return self.delete_resource(uri)
def list_l2_gateways(self, **filters):
uri = constants.L2_GWS_BASE_URI
LOG.info("URI : %(uri)s", {"uri": uri})
return self.list_resources(uri, **filters)
def get_client(client_mgr):
"""
Create a l2-gateway client from manager or networks_client
"""
try:
manager = getattr(client_mgr, "manager", client_mgr)
net_client = getattr(manager, "networks_client")
_params = manager.default_params_withy_timeout_values.copy()
except AttributeError as attribute_err:
LOG.warning("Failed to locate the attribute, Error: %(err_msg)s",
{"err_msg": attribute_err.__str__()})
_params = {}
client = L2GatewayClient(net_client.auth_provider,
net_client.service,
net_client.region,
net_client.endpoint_type,
**_params)
return client
@@ -1,69 +0,0 @@
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from tempest.lib.services.network import base
from vmware_nsx_tempest.services import network_client_base as base_client
class L2GatewayConnectionClient(base.BaseNetworkClient):
resource = 'l2_gateway_connection'
resource_plural = 'l2_gateway_connections'
path = 'l2-gateway-connections'
resource_base_path = '/%s' % path
resource_object_path = '/%s/%%s' % path
def create_l2_gateway_connection(self, **kwargs):
uri = self.resource_base_path
post_data = {self.resource: kwargs}
return self.create_resource(uri, post_data)
def update_l2_gateway_connection(self, l2_gateway_id, **kwargs):
uri = self.resource_object_path % l2_gateway_id
post_data = {self.resource: kwargs}
return self.update_resource(uri, post_data)
def show_l2_gateway_connection(self, l2_gateway_id, **fields):
uri = self.resource_object_path % l2_gateway_id
return self.show_resource(uri, **fields)
def delete_l2_gateway_connection(self, l2_gateway_id):
uri = self.resource_object_path % l2_gateway_id
return self.delete_resource(uri)
def list_l2_gateway_connections(self, **filters):
uri = self.resource_base_path
return self.list_resources(uri, **filters)
def get_client(client_mgr):
"""create a l2-gateway client from manager or networks_client
For itempest user:
from itempest import load_our_solar_system as osn
from vmware_nsx_tempest.services import l2_gateway_connection_client
l2gwc_client = l2_gateway_connection_client.get_client(osn.adm.manager)
For tempest user:
l2gwc_client = l2_gateway_connection_client.get_client(cls.os_adm)
"""
manager = getattr(client_mgr, 'manager', client_mgr)
net_client = getattr(manager, 'networks_client')
try:
_params = base_client.default_params_with_timeout_values.copy()
except Exception:
_params = {}
client = L2GatewayConnectionClient(net_client.auth_provider,
net_client.service,
net_client.region,
net_client.endpoint_type,
**_params)
return client
Whitespace-only changes.
@@ -1,72 +0,0 @@
# Copyright 2014 Rackspace US Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from tempest.lib.services.network import base
from vmware_nsx_tempest.services import network_client_base as base_client
class HealthMonitorsClient(base.BaseNetworkClient):
resource = 'healthmonitor'
resource_plural = 'healthmonitors'
path = 'lbaas/healthmonitors'
resource_base_path = '/%s' % path
resource_object_path = '/%s/%%s' % path
def create_health_monitor(self, **kwargs):
uri = self.resource_base_path
post_data = {self.resource: kwargs}
return self.create_resource(uri, post_data)
def update_health_monitor(self, health_monitor_id, **kwargs):
uri = self.resource_object_path % health_monitor_id
post_data = {self.resource: kwargs}
return self.update_resource(uri, post_data)
def show_health_monitor(self, health_monitor_id, **fields):
uri = self.resource_object_path % health_monitor_id
return self.show_resource(uri, **fields)
def delete_health_monitor(self, health_monitor_id):
uri = self.resource_object_path % health_monitor_id
return self.delete_resource(uri)
def list_health_monitors(self, **filters):
uri = self.resource_base_path
return self.list_resources(uri, **filters)
def get_client(client_mgr):
"""create a lbaas health_monitors client from manager or networks_client
For itempest user:
from itempest import load_our_solar_system as osn
from vmware_nsx_tempest.services.lbaas import health_monitors_client
healthmonitors_client = health_monitors_client.get_client(
osn.adm.manager)
For tempest user:
healthmonitors_client = health_monitors_client.get_client(osn.adm)
"""
manager = getattr(client_mgr, 'manager', client_mgr)
net_client = getattr(manager, 'networks_client')
try:
_params = base_client.default_params_with_timeout_values.copy()
except Exception:
_params = {}
client = HealthMonitorsClient(net_client.auth_provider,
net_client.service,
net_client.region,
net_client.endpoint_type,
**_params)
return client
@@ -1,59 +0,0 @@
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from tempest.lib.services.network import base
from vmware_nsx_tempest.services import network_client_base as base_client
class L7PoliciesClient(base.BaseNetworkClient):
resource = 'l7policy'
resource_plural = 'l7policies'
resource_base_path = '/lbaas/l7policies'
resource_object_path = '/lbaas/l7policies/%s'
def create_l7policy(self, **kwargs):
uri = self.resource_base_path
post_data = {self.resource: kwargs}
return self.create_resource(uri, post_data)
def update_l7policy(self, policy_id, **kwargs):
uri = self.resource_object_path % (policy_id)
post_data = {self.resource: kwargs}
return self.update_resource(uri, post_data)
def show_l7policy(self, policy_id, **fields):
uri = self.resource_object_path % (policy_id)
return self.show_resource(uri, **fields)
def delete_l7policy(self, policy_id):
uri = self.resource_object_path % (policy_id)
return self.delete_resource(uri)
def list_l7policies(self, **filters):
uri = self.resource_base_path
return self.list_resources(uri, **filters)
def get_client(client_mgr):
"""create a lbaas l7policies client from manager or networks_client"""
manager = getattr(client_mgr, 'manager', client_mgr)
net_client = getattr(manager, 'networks_client')
try:
_params = base_client.default_params_with_timeout_values.copy()
except Exception:
_params = {}
client = L7PoliciesClient(net_client.auth_provider,
net_client.service,
net_client.region,
net_client.endpoint_type,
**_params)
return client
@@ -1,60 +0,0 @@
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from tempest.lib.services.network import base
from vmware_nsx_tempest.services import network_client_base as base_client
class L7RulesClient(base.BaseNetworkClient):
resource = 'rule'
resource_plural = 'rules'
resource_base_path = '/lbaas/l7policies/%s/rules'
resource_object_path = '/lbaas/l7policies/%s/rules/%s'
def create_l7rule(self, policy_id, **kwargs):
uri = self.resource_base_path % policy_id
post_data = {self.resource: kwargs}
return self.create_resource(uri, post_data)
def update_l7rule(self, policy_id, rule_id, **kwargs):
uri = self.resource_object_path % (policy_id, rule_id)
post_data = {self.resource: kwargs}
return self.update_resource(uri, post_data)
def show_l7rule(self, policy_id, rule_id, **fields):
uri = self.resource_object_path % (policy_id, rule_id)
return self.show_resource(uri, **fields)
def delete_l7rule(self, policy_id, rule_id):
uri = self.resource_object_path % (policy_id, rule_id)
return self.delete_resource(uri)
def list_l7rules(self, policy_id, **filters):
uri = self.resource_base_path % policy_id
return self.list_resources(uri, **filters)
def get_client(client_mgr):
"""create a lbaas l7rules client from manager or networks_client"""
manager = getattr(client_mgr, 'manager', client_mgr)
net_client = getattr(manager, 'networks_client')
try:
_params = base_client.default_params_with_timeout_values.copy()
except Exception:
_params = {}
client = L7RulesClient(net_client.auth_provider,
net_client.service,
net_client.region,
net_client.endpoint_type,
**_params)
return client
@@ -1,71 +0,0 @@
# Copyright 2014 Rackspace US Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from tempest.lib.services.network import base
from vmware_nsx_tempest.services import network_client_base as base_client
class ListenersClient(base.BaseNetworkClient):
resource = 'listener'
resource_plural = 'listeners'
path = 'lbaas/listeners'
resource_base_path = '/%s' % path
resource_object_path = '/%s/%%s' % path
def create_listener(self, **kwargs):
uri = self.resource_base_path
post_data = {self.resource: kwargs}
return self.create_resource(uri, post_data)
def update_listener(self, listener_id, **kwargs):
uri = self.resource_object_path % listener_id
post_data = {self.resource: kwargs}
return self.update_resource(uri, post_data)
def show_listener(self, listener_id, **fields):
uri = self.resource_object_path % listener_id
return self.show_resource(uri, **fields)
def delete_listener(self, listener_id):
uri = self.resource_object_path % listener_id
return self.delete_resource(uri)
def list_listeners(self, **filters):
uri = self.resource_base_path
return self.list_resources(uri, **filters)
def get_client(client_mgr):
"""create a lbaas listener client from manager or networks_client
For itempest user:
from itempest import load_our_solar_system as osn
from vmware_nsx_tempest.services.lbaas import pools_client
lbaas_client = pools_client.get_client(osn.adm.manager)
For tempest user:
lbaas_client = pools_client.get_client(osn.adm)
"""
manager = getattr(client_mgr, 'manager', client_mgr)
net_client = getattr(manager, 'networks_client')
try:
_params = base_client.default_params_with_timeout_values.copy()
except Exception:
_params = {}
client = ListenersClient(net_client.auth_provider,
net_client.service,
net_client.region,
net_client.endpoint_type,
**_params)
return client
@@ -1,141 +0,0 @@
# Copyright 2014 Rackspace US Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import time
from tempest.lib import exceptions
from tempest.lib.services.network import base
from vmware_nsx_tempest._i18n import _
from vmware_nsx_tempest.services import network_client_base as base_client
LB_NOTFOUND = "loadbalancer {lb_id} not found"
class LoadBalancersClient(base.BaseNetworkClient):
resource = 'loadbalancer'
resource_plural = 'loadbalancers'
path = 'lbaas/loadbalancers'
resource_base_path = '/%s' % path
resource_object_path = '/%s/%%s' % path
resource_object_status_path = '/%s/%%s/statuses' % path
resource_object_stats_path = '/%s/%%s/stats' % path
def create_load_balancer(self, **kwargs):
uri = self.resource_base_path
post_data = {self.resource: kwargs}
return self.create_resource(uri, post_data)
def update_load_balancer(self, load_balancer_id, **kwargs):
uri = self.resource_object_path % load_balancer_id
post_data = {self.resource: kwargs}
return self.update_resource(uri, post_data)
def show_load_balancer(self, load_balancer_id, **fields):
uri = self.resource_object_path % load_balancer_id
return self.show_resource(uri, **fields)
def show_load_balancer_status_tree(self, load_balancer_id, **fields):
uri = self.resource_object_status_path % load_balancer_id
return self.show_resource(uri, **fields)
def show_load_balancer_stats(self, load_balancer_id, **fields):
uri = self.resource_object_stats_path % load_balancer_id
return self.show_resource(uri, **fields)
def delete_load_balancer(self, load_balancer_id):
uri = self.resource_object_path % load_balancer_id
return self.delete_resource(uri)
def list_load_balancers(self, **filters):
uri = self.resource_base_path
return self.list_resources(uri, **filters)
def wait_for_load_balancer_status(self, load_balancer_id,
provisioning_status='ACTIVE',
operating_status='ONLINE',
is_delete_op=False):
"""Must have utility method for load-balancer CRUD operation.
This is the method you must call to make sure load_balancer_id is
in provisioning_status=ACTIVE and opration_status=ONLINE status
before manipulating any lbaas resource under load_balancer_id.
"""
interval_time = self.build_interval
timeout = self.build_timeout
end_time = time.time() + timeout
lb = None
while time.time() < end_time:
try:
lb = self.show_load_balancer(load_balancer_id)
if not lb:
if is_delete_op:
break
else:
raise Exception(
LB_NOTFOUND.format(lb_id=load_balancer_id))
lb = lb.get(self.resource, lb)
if (lb.get('provisioning_status') == provisioning_status and
lb.get('operating_status') == operating_status):
break
time.sleep(interval_time)
except exceptions.NotFound as e:
if is_delete_op:
break
else:
raise e
else:
if is_delete_op:
raise exceptions.TimeoutException(
_("Waited for load balancer {lb_id} to be deleted for "
"{timeout} seconds but can still observe that it "
"exists.").format(
lb_id=load_balancer_id,
timeout=timeout))
else:
raise exceptions.TimeoutException(
_("Wait for load balancer ran for {timeout} seconds and "
"did not observe {lb_id} reach {provisioning_status} "
"provisioning status and {operating_status} "
"operating status.").format(
timeout=timeout,
lb_id=load_balancer_id,
provisioning_status=provisioning_status,
operating_status=operating_status))
return lb
def get_client(client_mgr):
"""create a lbaas load-balancers client from manager or networks_client
For itempest user:
from itempest import load_our_solar_system as osn
from vmware_nsx_tempest.services.lbaas import load_balancers_client
lbaas_client = load_balancers_client.get_client(osn.adm.manager)
For tempest user:
lbaas_client = load_balancers_client.get_client(osn.adm)
"""
manager = getattr(client_mgr, 'manager', client_mgr)
net_client = getattr(manager, 'networks_client')
try:
_params = base_client.default_params_with_timeout_values.copy()
except Exception:
_params = {}
client = LoadBalancersClient(net_client.auth_provider,
net_client.service,
net_client.region,
net_client.endpoint_type,
**_params)
return client
@@ -1,70 +0,0 @@
# Copyright 2014 Rackspace US Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from tempest.lib.services.network import base
from vmware_nsx_tempest.services import network_client_base as base_client
class MembersClient(base.BaseNetworkClient):
resource = 'member'
resource_plural = 'members'
path = 'lbaas/members'
resource_base_path = '/lbaas/pools/%s/members'
resource_object_path = '/lbaas/pools/%s/members/%s'
def create_member(self, pool_id, **kwargs):
uri = self.resource_base_path % pool_id
post_data = {self.resource: kwargs}
return self.create_resource(uri, post_data)
def update_member(self, pool_id, member_id, **kwargs):
uri = self.resource_object_path % (pool_id, member_id)
post_data = {self.resource: kwargs}
return self.update_resource(uri, post_data)
def show_member(self, pool_id, member_id, **fields):
uri = self.resource_object_path % (pool_id, member_id)
return self.show_resource(uri, **fields)
def delete_member(self, pool_id, member_id):
uri = self.resource_object_path % (pool_id, member_id)
return self.delete_resource(uri)
def list_members(self, pool_id, **filters):
uri = self.resource_base_path % pool_id
return self.list_resources(uri, **filters)
def get_client(client_mgr):
"""create a lbaas members client from manager or networks_client
For itempest user:
from itempest import load_our_solar_system as osn
from vmware_nsx_tempest.services.lbaas import members_client
members_client = members_client.get_client(osn.adm.manager)
For tempest user:
members_client = members_client.get_client(osn.adm)
"""
manager = getattr(client_mgr, 'manager', client_mgr)
net_client = getattr(manager, 'networks_client')
try:
_params = base_client.default_params_with_timeout_values.copy()
except Exception:
_params = {}
client = MembersClient(net_client.auth_provider,
net_client.service,
net_client.region,
net_client.endpoint_type,
**_params)
return client
@@ -1,70 +0,0 @@
# Copyright 2014 Rackspace US Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from tempest.lib.services.network import base
from vmware_nsx_tempest.services import network_client_base as base_client
class PoolsClient(base.BaseNetworkClient):
resource = 'pool'
resource_plural = 'pools'
path = 'lbaas/pools'
resource_base_path = '/%s' % path
resource_object_path = '/%s/%%s' % path
def create_pool(self, **kwargs):
uri = self.resource_base_path
post_data = {self.resource: kwargs}
return self.create_resource(uri, post_data)
def update_pool(self, pool_id, **kwargs):
uri = self.resource_object_path % pool_id
post_data = {self.resource: kwargs}
return self.update_resource(uri, post_data)
def show_pool(self, pool_id, **fields):
uri = self.resource_object_path % pool_id
return self.show_resource(uri, **fields)
def delete_pool(self, pool_id):
uri = self.resource_object_path % pool_id
return self.delete_resource(uri)
def list_pools(self, **filters):
uri = self.resource_base_path
return self.list_resources(uri, **filters)
def get_client(client_mgr):
"""create a lbaas pools client from manager or networks_client
For itempest user:
from itempest import load_our_solar_system as osn
from vmware_nsx_tempest.services.lbaas import pools_client
pools_client = pools_client.get_client(osn.adm.manager)
For tempest user:
pools_client = pools_client.get_client(osn.adm)
"""
manager = getattr(client_mgr, 'manager', client_mgr)
net_client = getattr(manager, 'networks_client')
try:
_params = base_client.default_params_with_timeout_values.copy()
except Exception:
_params = {}
client = PoolsClient(net_client.auth_provider,
net_client.service,
net_client.region,
net_client.endpoint_type,
**_params)
return client
@@ -1,320 +0,0 @@
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import time
from tempest.lib.common.utils import misc as misc_utils
from tempest.lib import exceptions as lib_exc
from tempest import exceptions
from vmware_nsx_tempest._i18n import _
from vmware_nsx_tempest.services import network_client_base as base
POOL_RID = 'pools'
VIP_RID = 'vips'
HEALTHMONITOR_RID = 'health_monitors'
MEMBER_RID = 'members'
class LoadBalancerV1Client(base.BaseNetworkClient):
def _list_lb(self, lb_resource, **filters):
resource_name_s, resource_name_p = _g_resource_namelist(lb_resource)
req_uri = '/lb/%s' % (resource_name_p)
return self.list_resources(req_uri, **filters)
def _show_lb(self, lb_resource, resource_id, **fields):
resource_name_s, resource_name_p = _g_resource_namelist(lb_resource)
req_uri = '/lb/%s/%s' % (resource_name_p, resource_id)
return self.show_resource(req_uri, **fields)
def _delete_lb(self, lb_resource, resource_id):
resource_name_s, resource_name_p = _g_resource_namelist(lb_resource)
req_uri = '/lb/%s/%s' % (resource_name_p, resource_id)
return self.delete_resource(req_uri)
def _create_lb(self, lb_resource, **kwargs):
resource_name_s, resource_name_p = _g_resource_namelist(lb_resource)
req_uri = '/lb/%s' % (resource_name_p)
post_body = {resource_name_s: kwargs}
return self.create_resource(req_uri, post_body)
def _update_lb(self, lb_resource, resource_id, **kwargs):
resource_name_s, resource_name_p = _g_resource_namelist(lb_resource)
req_uri = '/lb/%s/%s' % (resource_name_p, resource_id)
post_body = {resource_name_s: kwargs}
return self.update_resource(req_uri, post_body)
def show_agent_hosting_pool(self, pool_id):
"""Get loadbalancer agent hosting a pool."""
req_uri = "/lb/pools/%s/loadbalancer-agent" % (pool_id)
return self.show_resource(req_uri)
def associate_health_monitor_with_pool(self, health_monitor_id, pool_id):
"""Create a mapping between a health monitor and a pool."""
post_body = {'health_monitor': {'id': health_monitor_id}}
req_uri = '/lb/pools/%s/%s' % (pool_id, HEALTHMONITOR_RID)
return self.create_resource(req_uri, post_body)
def create_health_monitor(self, **kwargs):
"""Create a health monitor."""
create_kwargs = dict(
type=kwargs.pop('type', 'TCP'),
max_retries=kwargs.pop('nax_retries', 3),
timeout=kwargs.pop('timeout', 1),
delay=kwargs.pop('delay', 4),
)
create_kwargs.update(**kwargs)
return self._create_lb(HEALTHMONITOR_RID, **create_kwargs)
def delete_health_monitor(self, health_monitor_id):
"""Delete a given health monitor."""
return self._delete_lb(HEALTHMONITOR_RID, health_monitor_id)
def disassociate_health_monitor_with_pool(self, health_monitor_id,
pool_id):
"""Remove a mapping from a health monitor to a pool."""
req_uri = ('/lb/pools/%s/%s/%s'
% (pool_id, HEALTHMONITOR_RID, health_monitor_id))
return self.delete_resource(req_uri)
def list_health_monitors(self, **filters):
"""List health monitors that belong to a given tenant."""
return self._list_lb(HEALTHMONITOR_RID, **filters)
def show_health_monitor(self, health_monitor_id):
"""Show information of a given health monitor."""
return self._show_lb(HEALTHMONITOR_RID, health_monitor_id)
def update_health_monitor(self, health_monitor_id,
show_then_update=False, **kwargs):
"""Update a given health monitor."""
body = (self.show_health_monitor(health_monitor_id)['health_monitor']
if show_then_update else {})
body.update(**kwargs)
return self._update_lb(HEALTHMONITOR_RID,
health_monitor_id, **body)
# tempest create_member(self,protocol_port, pool, ip_version)
# we use pool_id
def create_member(self, protocol_port, pool_id,
ip_version=4, **kwargs):
"""Create a member."""
create_kwargs = dict(
protocol_port=protocol_port,
pool_id=pool_id,
address=("fd00:abcd" if ip_version == 6 else "10.0.9.46"),
)
create_kwargs.update(**kwargs)
return self._create_lb(MEMBER_RID, **create_kwargs)
def delete_member(self, member_id):
"""Delete a given member."""
return self._delete_lb(MEMBER_RID, member_id)
def list_members(self, **filters):
"""List members that belong to a given tenant."""
return self._list_lb(MEMBER_RID, **filters)
def show_member(self, member_id):
"""Show information of a given member."""
return self._show_lb(MEMBER_RID, member_id)
def update_member(self, member_id,
show_then_update=False, **kwargs):
"""Update a given member."""
body = (self.show_member(member_id)['member']
if show_then_update else {})
body.update(**kwargs)
return self._update_lb(MEMBER_RID, member_id, **body)
def create_pool(self, name, lb_method, protocol, subnet_id,
**kwargs):
"""Create a pool."""
lb_method = lb_method or 'ROUND_ROBIN'
protocol = protocol or 'HTTP'
create_kwargs = dict(
name=name, lb_method=lb_method,
protocol=protocol, subnet_id=subnet_id,
)
create_kwargs.update(kwargs)
return self._create_lb(POOL_RID, **create_kwargs)
def delete_pool(self, pool_id):
"""Delete a given pool."""
return self._delete_lb(POOL_RID, pool_id)
def list_pools(self, **filters):
"""List pools that belong to a given tenant."""
return self._list_lb(POOL_RID, **filters)
def list_lb_pool_stats(self, pool_id, **filters):
"""Retrieve stats for a given pool."""
req_uri = '/lb/pools/%s/stats' % (pool_id)
return self.list_resources(req_uri, **filters)
def list_pool_on_agents(self, **filters):
"""List the pools on a loadbalancer agent."""
pass
def show_pool(self, pool_id):
"""Show information of a given pool."""
return self._show_lb(POOL_RID, pool_id)
def update_pool(self, pool_id, show_then_update=False, **kwargs):
"""Update a given pool."""
body = (self.show_pool(pool_id)['pool']
if show_then_update else {})
body.update(**kwargs)
return self._update_lb(POOL_RID, pool_id, **body)
def create_vip(self, pool_id, **kwargs):
"""Create a vip."""
create_kwargs = dict(
pool_id=pool_id,
protocol=kwargs.pop('protocol', 'HTTP'),
protocol_port=kwargs.pop('protocol_port', 80),
name=kwargs.pop('name', None),
address=kwargs.pop('address', None),
)
for k in create_kwargs.keys():
if create_kwargs[k] is None:
create_kwargs.pop(k)
create_kwargs.update(**kwargs)
# subnet_id needed to create vip
return self._create_lb(VIP_RID, **create_kwargs)
def delete_vip(self, vip_id):
"""Delete a given vip."""
return self._delete_lb(VIP_RID, vip_id)
def list_vips(self, **filters):
"""List vips that belong to a given tenant."""
return self._list_lb(VIP_RID, **filters)
def show_vip(self, vip_id):
"""Show information of a given vip."""
return self._show_lb(VIP_RID, vip_id)
def update_vip(self, vip_id, show_then_update=False, **kwargs):
"""Update a given vip."""
body = (self.show_vip(vip_id)['vip']
if show_then_update else {})
body.update(**kwargs)
return self._update_lb(VIP_RID, vip_id, **body)
# Following 3 methods are specifically to load-balancer V1 client.
# They are being implemented by the pareant tempest.lib.common.rest_client
# with different calling signatures, only id, no resoure_type. Because,
# starting in Liberty release, each resource should have its own client.
# Since V1 is deprecated, we are not going to change it, and
# copy following 2 methods for V1 LB client only.
def wait_for_resource_deletion(self, resource_type, id, client=None):
"""Waits for a resource to be deleted."""
start_time = int(time.time())
while True:
if self.is_resource_deleted(resource_type, id, client=client):
return
if int(time.time()) - start_time >= self.build_timeout:
raise exceptions.TimeoutException
time.sleep(self.build_interval)
def is_resource_deleted(self, resource_type, id, client=None):
if client is None:
client = self
method = 'show_' + resource_type
try:
getattr(client, method)(id)
except AttributeError:
raise Exception(_("Unknown resource type %s ") % resource_type)
except lib_exc.NotFound:
return True
return False
def wait_for_resource_status(self, fetch, status, interval=None,
timeout=None):
"""This has different calling signature then rest_client.
@summary: Waits for a network resource to reach a status
@param fetch: the callable to be used to query the resource status
@type fecth: callable that takes no parameters and returns the resource
@param status: the status that the resource has to reach
@type status: String
@param interval: the number of seconds to wait between each status
query
@type interval: Integer
@param timeout: the maximum number of seconds to wait for the resource
to reach the desired status
@type timeout: Integer
"""
if not interval:
interval = self.build_interval
if not timeout:
timeout = self.build_timeout
start_time = time.time()
while time.time() - start_time <= timeout:
resource = fetch()
if resource['status'] == status:
return
time.sleep(interval)
# At this point, the wait has timed out
message = 'Resource %s' % (str(resource))
message += ' failed to reach status %s' % status
message += ' (current: %s)' % resource['status']
message += ' within the required time %s' % timeout
caller = misc_utils.find_test_caller()
if caller:
message = '(%s) %s' % (caller, message)
raise exceptions.TimeoutException(message)
def _g_resource_namelist(lb_resource):
if lb_resource[-1] == 's':
return (lb_resource[:-1], lb_resource)
return (lb_resource, lb_resource + "s")
def destroy_tenant_lb(lbv1_client):
for o in lbv1_client.list_members():
lbv1_client.delete_member(o['id'])
for o in lbv1_client.list_health_monitors():
lbv1_client.delete_health_monitor(o['id'])
for o in lbv1_client.list_vips():
lbv1_client.delete_vip(o['id'])
for o in lbv1_client.list_pools():
lbv1_client.delete_pool(o['id'])
def get_client(client_mgr):
"""create a v1 load balancer client
For itempest user:
from itempest import load_our_solar_system as osn
from vmware_nsx_tempest.services import load_balancer_v1_client
lbv1 = load_balancer_v1_client.get_client(osn.adm.manager)
For tempest user:
lbv1 = load_balancer_v1_client.get_client(cls.os_adm)
"""
manager = getattr(client_mgr, 'manager', client_mgr)
net_client = getattr(manager, 'networks_client')
try:
_params = base.default_params_with_timeout_values.copy()
except Exception:
_params = {}
client = LoadBalancerV1Client(net_client.auth_provider,
net_client.service,
net_client.region,
net_client.endpoint_type,
**_params)
return client
@@ -1,52 +0,0 @@
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from tempest import config
from tempest.lib.services.network import base
CONF = config.CONF
# netowrk/json/base.py does not include thoese method in network_client
class BaseNetworkClient(base.BaseNetworkClient):
def __init__(self, auth_provider, service, region,
endpoint_type=None, build_interval=None, build_timeout=None,
disable_ssl_certificate_validation=None, ca_certs=None,
trace_requests=None, **kwargs):
dsca = disable_ssl_certificate_validation
super(base.BaseNetworkClient, self).__init__(
auth_provider, service, region,
endpoint_type=endpoint_type,
build_interval=build_interval,
build_timeout=build_timeout,
disable_ssl_certificate_validation=dsca,
ca_certs=ca_certs,
trace_requests=trace_requests)
default_params = {
'disable_ssl_certificate_validation': True,
'ca_certs': None,
'trace_requests': ''}
default_params_2 = {
'catalog_type': 'network',
'region': 'nova',
'endpoint_type': 'publicURL',
'build_timeout': 300,
'build_interval': 1}
default_params_3 = config.service_client_config()
default_params_with_timeout_values = {
'build_interval': CONF.network.build_interval,
'build_timeout': CONF.network.build_timeout
}
default_params_with_timeout_values.update(default_params_3)
-46
View File
@@ -1,46 +0,0 @@
# Copyright 2017 VMware Inc
# All Rights Reserved
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from oslo_log import log as logging
from vmware_nsx_tempest.services import nsxv3_client
LOG = logging.getLogger(__name__)
class NSXClient(object):
"""Base NSX REST client"""
def __init__(self, backend, host, username, password, *args, **kwargs):
self.backend = backend.lower()
self.host = host
self.username = username
self.password = password
if backend.lower() == "nsxv3":
self.nsx = nsxv3_client.NSXV3Client(host, username, password)
def get_firewall_section_and_rules(self, *args, **kwargs):
if self.backend == "nsxv3":
firewall_section = self.nsx.get_firewall_section(
*args, **kwargs)
firewall_section_rules = self.nsx.get_firewall_section_rules(
firewall_section)
return firewall_section, firewall_section_rules
else:
#TODO(ddoshi) define else for nsxv
pass
def get_bridge_cluster_info(self, *args, **kwargs):
if self.backend == "nsxv3":
return self.nsx.get_bridge_cluster_info(
*args, **kwargs)
-560
View File
@@ -1,560 +0,0 @@
# Copyright 2016 VMware Inc
# All Rights Reserved
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import base64
from copy import deepcopy
import time
import requests
import six.moves.urllib.parse as urlparse
from oslo_log import log as logging
from oslo_serialization import jsonutils
from vmware_nsx_tempest.common import constants
requests.packages.urllib3.disable_warnings()
LOG = logging.getLogger(__name__)
class NSXV3Client(object):
"""Base NSXv3 REST client"""
API_VERSION = "v1"
def __init__(self, host, username, password, *args, **kwargs):
self.host = host
self.username = username
self.password = password
self.version = None
self.endpoint = None
self.content_type = "application/json"
self.accept_type = "application/json"
self.verify = False
self.secure = True
self.interface = "json"
self.url = None
self.headers_non_super_admin = self.__set_headers()
self.headers = deepcopy(self.headers_non_super_admin)
self.headers_super_admin = self.__set_headers(super_admin=True)
self.api_version = NSXV3Client.API_VERSION
def __set_endpoint(self, endpoint):
self.endpoint = endpoint
def get_endpoint(self):
return self.endpoint
def __set_content_type(self, content_type):
self.content_type = content_type
def get_content_type(self):
return self.content_type
def __set_accept_type(self, accept_type):
self.accept_type = accept_type
def get_accept_type(self):
return self.accept_type
def __set_api_version(self, api_version):
self.api_version = api_version
def get_api_version(self):
return self.api_version
def __set_url(self, api=None, secure=None, host=None, endpoint=None):
api = self.api_version if api is None else api
secure = self.secure if secure is None else secure
host = self.host if host is None else host
endpoint = self.endpoint if endpoint is None else endpoint
http_type = 'https' if secure else 'http'
self.url = '%s://%s/api/%s%s' % (http_type, host, api, endpoint)
def get_url(self):
return self.url
def __set_headers(self, content=None, accept=None, super_admin=False):
content_type = self.content_type if content is None else content
accept_type = self.accept_type if accept is None else accept
auth_cred = self.username + ":" + self.password
auth = base64.b64encode(auth_cred)
headers = {}
headers['Authorization'] = "Basic %s" % auth
headers['Content-Type'] = content_type
headers['Accept'] = accept_type
if super_admin:
headers['X-Allow-Overwrite'] = 'true'
return headers
def get(self, endpoint=None, params=None, cursor=None):
"""
Basic query method for json API request
"""
self.__set_url(endpoint=endpoint)
if cursor:
op = "&" if urlparse.urlparse(self.url).query else "?"
self.url += op + "cursor=" + cursor
response = requests.get(self.url, headers=self.headers,
verify=self.verify, params=params)
return response
def put(self, endpoint=None, body=None):
"""
Basic put API method on endpoint
"""
self.__set_url(endpoint=endpoint)
response = requests.put(self.url, headers=self.headers,
verify=self.verify, data=jsonutils.dumps(body))
return response
def ca_put_request(self, component, comp_id, body):
"""
NSX-T API Put request for certificate Management
"""
endpoint = ("/%s/%s" % (component, comp_id))
response = self.put(endpoint=endpoint, body=body)
return response
def delete(self, endpoint=None, params=None):
"""
Basic delete API method on endpoint
"""
self.__set_url(endpoint=endpoint)
response = requests.delete(self.url, headers=self.headers,
verify=self.verify, params=params)
return response
def ca_delete_request(self, component=None, comp_id=None):
"""
NSX-T API delete request for certificate Management
"""
endpoint = ("/%s/%s" % (component, comp_id))
response = self.delete(endpoint=endpoint)
return response
def delete_super_admin(self, endpoint=None, params=None):
"""
Basic delete API method for NSX super admin on endpoint
"""
self.__set_url(endpoint=endpoint)
response = requests.delete(self.url, headers=self.headers_super_admin,
verify=self.verify, params=params)
return response
def post(self, endpoint=None, body=None):
"""
Basic post API method on endpoint
"""
self.__set_url(endpoint=endpoint)
response = requests.post(self.url, headers=self.headers,
verify=self.verify,
data=jsonutils.dumps(body))
return response
def get_logical_resources(self, endpoint):
"""
Get logical resources based on the endpoint
Getting the logical resource based on the end point. Parse the response
for the cursor. If cursor is present, query url for multiple pages to
get all the logical resources.
"""
results = []
response = self.get(endpoint=endpoint)
res_json = response.json()
cursor = res_json.get("cursor")
if res_json.get("results"):
results.extend(res_json["results"])
while cursor:
page = self.get(endpoint=endpoint, cursor=cursor).json()
results.extend(page.get("results", []))
cursor = page.get("cursor")
return results
def get_transport_zones(self):
"""
Retrieve all transport zones
"""
return self.get_logical_resources("/transport-zones")
def get_logical_ports(self):
"""
Retrieve all logical ports on NSX backend
"""
return self.get_logical_resources("/logical-ports")
def get_logical_port(self, os_name):
"""
Get the logical port based on the os_name provided.
The name of the logical port shoud match the os_name.
Return the logical port if found, otherwise return None.
"""
if not os_name:
LOG.error("Name of OS port should be present "
"in order to query backend logical port created")
return None
lports = self.get_logical_ports()
return self.get_nsx_resource_by_name(lports, os_name)
def get_logical_port_info(self, lport):
"""
Retrieve attributes of a given logical port
"""
lport_uri = "/logical-ports/%s" % lport
response = self.get(endpoint=lport_uri)
res_json = response.json()
return res_json
def get_switching_profile(self, switch_profile):
"""
Retrieve attributes of a given nsx switching profile
"""
sw_profile_uri = "/switching-profiles/%s" % switch_profile
response = self.get(endpoint=sw_profile_uri)
res_json = response.json()
return res_json
def get_os_logical_ports(self):
"""
Retrieve all logical ports created from OpenStack
"""
lports = self.get_logical_ports()
return self.get_os_resources(lports)
def update_logical_port_attachment(self, lports):
"""
Update the logical port attachment
In order to delete logical ports, we need to detach
the VIF attachment on the ports first.
"""
for p in lports:
p['attachment'] = None
endpoint = "/logical-ports/%s" % p['id']
response = self.put(endpoint=endpoint, body=p)
if response.status_code != requests.codes.ok:
LOG.error("Failed to update lport %s", p['id'])
def cleanup_os_logical_ports(self):
"""
Delete all logical ports created by OpenStack
"""
lports = self.get_logical_ports()
os_lports = self.get_os_resources(lports)
LOG.info("Number of OS Logical Ports to be deleted: %s",
len(os_lports))
# logical port vif detachment
self.update_logical_port_attachment(os_lports)
for p in os_lports:
endpoint = '/logical-ports/%s' % p['id']
response = self.delete(endpoint=endpoint)
if response.status_code == requests.codes.ok:
LOG.info("Successfully deleted logical port %s", p['id'])
else:
LOG.error("Failed to delete lport %(port_id)s, response "
"code %(code)s",
{'port_id': p['id'], 'code': response.status_code})
def get_os_resources(self, resources):
"""
Get all logical resources created by OpenStack
"""
os_resources = [r for r in resources if 'tags' in r
for tag in r['tags']
if 'os-project-id' in tag.values()]
return os_resources
def get_nsx_resource_by_name(self, nsx_resources, nsx_name):
"""
Get the NSX component created from OpenStack by name.
The name should be converted from os_name to nsx_name.
If found exact one match return it, otherwise report error.
"""
nsx_resource = [n for n in nsx_resources if
n['display_name'] == nsx_name]
if len(nsx_resource) == 0:
LOG.warning("Backend nsx resource %s NOT found!", nsx_name)
return None
if len(nsx_resource) > 1:
LOG.error("More than 1 nsx resources found: %s!",
nsx_resource)
return None
else:
LOG.info("Found nsgroup: %s", nsx_resource[0])
return nsx_resource[0]
def get_logical_switches(self):
"""
Retrieve all logical switches on NSX backend
"""
return self.get_logical_resources("/logical-switches")
def get_logical_switch_profiles(self):
"""
Retrieve all switching profiles on NSX backend
"""
return self.get_logical_resources("/switching-profiles")
def get_switching_profiles(self):
"""
Retrieve all switching profiles on NSX backend
"""
return self.get_logical_resources("/switching-profiles")
def get_bridge_cluster_info(self):
"""
Get bridge cluster information.
:return: returns bridge cluster id and bridge cluster name.
"""
return self.get_logical_resources("/bridge-clusters")
def get_logical_switch(self, os_name, os_uuid):
"""
Get the logical switch based on the name and uuid provided.
The name of the logical switch should follow
<os_network_name>_<first 5 os uuid>...<last 5 os uuid>
Return logical switch if found, otherwise return None
"""
if not os_name or not os_uuid:
LOG.error("Name and uuid of OpenStack L2 network need to be "
"present in order to query backend logical switch!")
return None
nsx_name = os_name + "_" + os_uuid[:5] + "..." + os_uuid[-5:]
lswitches = self.get_logical_switches()
return self.get_nsx_resource_by_name(lswitches, nsx_name)
def get_lswitch_ports(self, ls_id):
"""
Return all the logical ports that belong to this lswitch
"""
lports = self.get_logical_ports()
return [p for p in lports if p['logical_switch_id'] is ls_id]
def get_firewall_sections(self):
"""
Retrieve all firewall sections
"""
return self.get_logical_resources("/firewall/sections")
def get_firewall_section(self, os_name, os_uuid):
"""
Get the firewall section by os_name and os_uuid
"""
if not os_name or not os_uuid:
LOG.error("Name and uuid of OS security group should be "
"present in order to query backend FW section "
"created")
return None
nsx_name = os_name + " - " + os_uuid
nsx_firewall_time_counter = 0
nsx_dfw_section = None
# wait till timeout or till dfw section
while nsx_firewall_time_counter < \
constants.NSX_FIREWALL_REALIZED_TIMEOUT and \
not nsx_dfw_section:
nsx_firewall_time_counter += 1
fw_sections = self.get_firewall_sections()
nsx_dfw_section = self.get_nsx_resource_by_name(fw_sections,
nsx_name)
time.sleep(constants.ONE_SEC)
return nsx_dfw_section
def get_firewall_section_rules(self, fw_section):
"""
Retrieve all fw rules for a given fw section
"""
endpoint = "/firewall/sections/%s/rules" % fw_section['id']
return self.get_logical_resources(endpoint)
def get_firewall_section_rule(self, fw_section, os_uuid):
"""
Get the firewall section rule based on the name
"""
fw_rules = self.get_firewall_section_rules(fw_section)
nsx_name = os_uuid
return self.get_nsx_resource_by_name(fw_rules, nsx_name)
def get_ns_groups(self):
"""
Retrieve all NSGroups on NSX backend
"""
return self.get_logical_resources("/ns-groups")
def get_neutron_ns_group_id(self):
"""
Retrieve NSGroup Id
"""
nsx_nsgroup = self.get_ns_groups()
for group in nsx_nsgroup:
if group['display_name'] == 'neutron_excluded_port_nsgroup':
nsgroup_id = group['id']
return nsgroup_id
def get_ns_group_port_members(self, ns_group_id):
"""
Retrieve NSGroup port members
"""
endpoint = "/ns-groups/%s/effective-logical-port-members" % ns_group_id
response = self.get(endpoint=endpoint)
res_json = response.json()
return res_json
def get_ns_group(self, os_name, os_uuid):
"""
Get the NSGroup based on the name provided.
The name of the nsgroup should follow
<os_sg_name> - <os_sg_uuid>
Return nsgroup if found, otherwise return None
"""
if not os_name or not os_uuid:
LOG.error("Name and uuid of OS security group should be "
"present in order to query backend nsgroup created")
return None
nsx_name = os_name + " - " + os_uuid
nsgroups = self.get_ns_groups()
return self.get_nsx_resource_by_name(nsgroups, nsx_name)
def get_logical_routers(self, tier=None):
"""
Retrieve all the logical routers based on router type. If tier
is None, it will return all logical routers.
"""
if tier:
endpoint = "/logical-routers?router_type=%s" % tier
else:
endpoint = "/logical-routers"
return self.get_logical_resources(endpoint)
def get_logical_router(self, os_name, os_uuid):
"""
Get the logical router based on the os_name and os_uuid provided.
The name of the logical router shoud follow
<os_router_name>_<starting_5_uuid>...<trailing_5_uuid>
Return the logical router if found, otherwise return None.
"""
if not os_name or not os_uuid:
LOG.error("Name and uuid of OS router should be present "
"in order to query backend logical router created")
return None
nsx_name = os_name + "_" + os_uuid[:5] + "..." + os_uuid[-5:]
lrouters = self.get_logical_routers()
return self.get_nsx_resource_by_name(lrouters, nsx_name)
def get_logical_router_ports(self, lrouter):
"""
Get all logical ports attached to lrouter
"""
endpoint = "/logical-router-ports?logical_router_id=%s" % lrouter['id']
return self.get_logical_resources(endpoint)
def get_logical_router_nat_rules(self, lrouter):
"""
Get all user defined NAT rules of the specific logical router
"""
if not lrouter:
LOG.error("Logical router needs to be present in order "
"to get the NAT rules")
return None
endpoint = "/logical-routers/%s/nat/rules" % lrouter['id']
return self.get_logical_resources(endpoint)
def get_logical_router_advertisement(self, lrouter):
"""Get logical router advertisement"""
if not lrouter:
LOG.error("Logical router needs to be present in order "
"to get router advertisement!")
return None
endpoint = "/logical-routers/%s/routing/advertisement" % lrouter['id']
response = self.get(endpoint)
return response.json()
def get_logical_dhcp_servers(self):
"""
Get all logical DHCP servers on NSX backend
"""
return self.get_logical_resources("/dhcp/servers")
def get_logical_dhcp_server(self, os_name, os_uuid):
"""
Get the logical dhcp server based on the name and uuid provided.
The name of the logical dhcp server should follow
<os_network_name>_<first 5 os uuid>...<last 5 os uuid>
Return logical dhcp server if found, otherwise return None
"""
if not os_name or not os_uuid:
LOG.error("Name and uuid of OpenStack L2 network need to be "
"present in order to query backend logical dhcp "
"server!")
return None
nsx_name = os_name + "_" + os_uuid[:5] + "..." + os_uuid[-5:]
dhcp_servers = self.get_logical_dhcp_servers()
return self.get_nsx_resource_by_name(dhcp_servers, nsx_name)
def get_dhcp_server_static_bindings(self, dhcp_server):
"""
Get all DHCP static bindings of a logical DHCP server
"""
endpoint = "/dhcp/servers/%s/static-bindings" % dhcp_server
return self.get_logical_resources(endpoint)
def get_md_proxies(self):
"""
Get md proxies.
:return: returns list of md proxies information.
"""
return self.get_logical_resources("/md-proxies")
def get_nsx_certificate(self):
"""
Get all certificates registered with backend
"""
endpoint = "/trust-management/certificates/"
response = self.get(endpoint)
return response.json()
def get_openstack_client_certificate(self):
"""
Get self signed openstack client certificate
"""
cert_response = self.get_nsx_certificate()
for cert in cert_response['results']:
if (cert["_create_user"] == "admin" and cert[
"resource_type"] == "certificate_self_signed" and cert[
"display_name"] != "NSX MP Client Certificate for Key "
"Manager"):
LOG.info('Client certificate created')
return cert
LOG.error("Client Certificate not created")
return None
def delete_md_proxy(self, uuid):
"""
Delete md proxies.
"""
return self.delete_logical_resources("/md-proxies/%s" % uuid)
def delete_logical_resources(self, endpoint):
"""
Delete logical resources based on the endpoint.
"""
response = self.delete(endpoint=endpoint)
return response.json()
-347
View File
@@ -1,347 +0,0 @@
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import base64
import re
from oslo_log import log as logging
from oslo_serialization import jsonutils
import requests
from tempest import config
import vmware_nsx_tempest.services.utils as utils
requests.packages.urllib3.disable_warnings()
CONF = config.CONF
LOG = logging.getLogger(__name__)
class VSMClient(object):
"""NSX-v client.
The client provides the API operations on its components.
The purpose of this rest client is to query backend components after
issuing corresponding API calls from OpenStack. This is to make sure
the API calls has been realized on the NSX-v backend.
"""
API_VERSION = "2.0"
def __init__(self, host, username, password, *args, **kwargs):
self.force = True if 'force' in kwargs else False
self.host = host
self.username = username
self.password = password
self.version = None
self.endpoint = None
self.content_type = "application/json"
self.accept_type = "application/json"
self.verify = False
self.secure = True
self.interface = "json"
self.url = None
self.headers = None
self.api_version = VSMClient.API_VERSION
self.default_scope_id = None
self.__set_headers()
self._version = self.get_vsm_version()
def __set_endpoint(self, endpoint):
self.endpoint = endpoint
def get_endpoint(self):
return self.endpoint
def __set_content_type(self, content_type):
self.content_type = content_type
def get_content_type(self):
return self.content_type
def __set_accept_type(self, accept_type):
self.accept_type = accept_type
def get_accept_type(self):
return self.accept_type
def __set_api_version(self, api_version):
self.api_version = api_version
def get_api_version(self):
return self.api_version
def __set_url(self, version=None, secure=None, host=None, endpoint=None):
version = self.api_version if version is None else version
secure = self.secure if secure is None else secure
host = self.host if host is None else host
endpoint = self.endpoint if endpoint is None else endpoint
http_type = 'https' if secure else 'http'
self.url = '%s://%s/api/%s%s' % (http_type, host, version, endpoint)
def get_url(self):
return self.url
def __set_headers(self, content=None, accept=None):
content_type = self.content_type if content is None else content
accept_type = self.accept_type if accept is None else accept
auth_cred = self.username + ":" + self.password
auth = base64.b64encode(auth_cred)
headers = {}
headers['Authorization'] = "Basic %s" % auth
headers['Content-Type'] = content_type
headers['Accept'] = accept_type
self.headers = headers
def get(self, endpoint=None, params=None):
"""Basic query GET method for json API request."""
self.__set_url(endpoint=endpoint)
response = requests.get(self.url, headers=self.headers,
verify=self.verify, params=params)
return response
def delete(self, endpoint=None, params=None):
"""Basic delete API method on endpoint."""
self.__set_url(endpoint=endpoint)
response = requests.delete(self.url, headers=self.headers,
verify=self.verify, params=params)
return response
def post(self, endpoint=None, body=None):
"""Basic post API method on endpoint."""
self.__set_url(endpoint=endpoint)
response = requests.post(self.url, headers=self.headers,
verify=self.verify,
data=jsonutils.dumps(body))
return response
def get_all_vdn_scopes(self):
"""Retrieve existing network scopes"""
self.__set_api_version('2.0')
self.__set_endpoint("/vdn/scopes")
response = self.get()
return response.json()['allScopes']
# return the vdn_scope_id for the priamry Transport Zone
def get_vdn_scope_id(self):
"""Retrieve existing network scope id."""
scopes = self.get_all_vdn_scopes()
if len(scopes) == 0:
return scopes[0]['objectId']
return CONF.nsxv.vdn_scope_id
def get_vdn_scope_by_id(self, scope_id):
"""Retrieve existing network scopes id"""
self.__set_api_version('2.0')
self.__set_endpoint("/vdn/scopes/%s" % scope_id)
return self.get().json()
def get_vdn_scope_by_name(self, name):
"""Retrieve network scope id of existing scope name:
nsxv_client.get_vdn_scope_id_by_name('TZ1')
"""
scopes = self.get_all_vdn_scopes()
if name is None:
for scope in scopes:
if scope['objectId'] == CONF.nsxv.vdn_scope_id:
return scope
else:
for scope in scopes:
if scope['name'] == name:
return scope
return None
def get_all_logical_switches(self, vdn_scope_id=None):
lswitches = []
self.__set_api_version('2.0')
vdn_scope_id = vdn_scope_id or self.get_vdn_scope_id()
endpoint = "/vdn/scopes/%s/virtualwires" % (vdn_scope_id)
self.__set_endpoint(endpoint)
response = self.get()
paging_info = response.json()['dataPage']['pagingInfo']
page_size = int(paging_info['pageSize'])
total_count = int(paging_info['totalCount'])
msg = ("There are total %s logical switches and page size is %s"
% (total_count, page_size))
LOG.debug(msg)
pages = utils.ceil(total_count, page_size)
LOG.debug("Total pages: %s" % pages)
for i in range(pages):
start_index = page_size * i
params = {'startindex': start_index}
response = self.get(params=params)
lswitches += response.json()['dataPage']['data']
return lswitches
def get_logical_switch(self, name):
"""Get the logical switch based on the name.
The uuid of the OpenStack L2 network. Return ls if found,
otherwise return None.
"""
lswitches = self.get_all_logical_switches()
lswitch = [ls for ls in lswitches if ls['name'] == name]
if len(lswitch) == 0:
LOG.debug('logical switch %s NOT found!' % name)
lswitch = None
else:
ls = lswitch[0]
LOG.debug('Found lswitch: %s' % ls)
return ls
def delete_logical_switch(self, name):
"""Delete logical switch based on name.
The name of the logical switch on NSX-v is the uuid
of the openstack l2 network.
"""
ls = self.get_logical_switch(name)
if ls is not None:
endpoint = '/vdn/virtualwires/%s' % ls['objectId']
response = self.delete(endpoint=endpoint)
if response.status_code == 200:
LOG.debug('Successfully deleted logical switch %s' % name)
else:
LOG.debug('ERROR @delete ls=%s failed with response code %s' %
(name, response.status_code))
def get_all_edges(self):
"""Get all edges on NSX-v backend."""
self.__set_api_version('4.0')
self.__set_endpoint('/edges')
edges = []
response = self.get()
paging_info = response.json()['edgePage']['pagingInfo']
page_size = int(paging_info['pageSize'])
total_count = int(paging_info['totalCount'])
msg = "There are total %s edges and page size is %s" % (total_count,
page_size)
LOG.debug(msg)
pages = utils.ceil(total_count, page_size)
for i in range(pages):
start_index = page_size * i
params = {'startindex': start_index}
response = self.get(params=params)
edges += response.json()['edgePage']['data']
return edges
def get_edge_firewall_rules(self, edge_Id):
"""Get nsx-edge firewall info based on edge_id.
Return firewall rules if found ,else return None.
"""
self.__set_api_version('4.0')
self.__set_endpoint('/edges/%s/firewall/config ' % edge_Id)
response = self.get()
rules = response.json()['firewallRules']['firewallRules']
if len(rules) == 0:
rules = None
return rules
def get_firewall(self):
"""Get all firewall on NSX-v beckend.
Return firewalls if found, else return None.
"""
self.__set_api_version('4.0')
self.__set_endpoint('/firewall/globalroot-0/config')
response = self.get()
paging_info = response.json()
if len(paging_info) == 0:
paging_info = None
return paging_info
def get_edge(self, name):
"""Get edge based on the name, which is OpenStack router.
Return edge if found, else return None.
"""
edges = self.get_all_edges()
edge = [e for e in edges if e['name'] == name]
if len(edge) == 0:
LOG.debug('Edge %s NOT found!' % name)
edge = None
else:
edge = edge[0]
LOG.debug('Found edge: %s' % edge)
return edge
def get_dhcp_edge_config(self, edge_id):
"""Get dhcp edge config.
Return edge information.
"""
self.__set_api_version('4.0')
self.__set_endpoint('/edges/%s/dhcp/config' % edge_id)
response = self.get()
return response
def get_excluded_vm_name_list(self):
"""Get excluded vm's list info from beckend.
After disabling port security of vm port, vm will get added
in exclude list.This method returns the list of vm's present
in exclude list.
Returns exclude list of vm's name.
"""
self.__set_api_version('2.1')
self.__set_endpoint('/app/excludelist')
response = self.get()
response_list = []
exclude_list = []
response_list = response.json()[
'excludeListConfigurationDto']['excludeMembers']
exclude_list = [member['member']['name'] for member in response_list
if member['member']['name']]
return exclude_list
def get_dhcp_edge_info(self):
"""Get dhcp edge info.
Return edge if found, else return None.
"""
edges = self.get_all_edges()
edge_list = []
for e in edges:
if (not e['edgeStatus'] == 'GREY'
and not e['state'] == 'undeployed'):
p = re.compile(r'dhcp*')
if (p.match(e['name'])):
edge_list.append(e['recentJobInfo']['edgeId'])
count = 0
result_edge = {}
for edge_id in edge_list:
response = self.get_dhcp_edge_config(edge_id)
paging_info = response.json()
if (paging_info['staticBindings']['staticBindings']):
result_edge[count] = paging_info
count += 1
else:
LOG.debug('Host Routes are not avilable for %s ' % edge_id)
if (count > 0):
edge = result_edge[0]
else:
edge = None
return edge
def get_vsm_version(self):
"""Get the VSM client version including major, minor, patch, & build#.
Build number, e.g. 6.2.0.2986609
return: vsm version
"""
self.__set_api_version('1.0')
self.__set_endpoint('/appliance-management/global/info')
response = self.get()
json_ver = response.json()['versionInfo']
return '.'.join([json_ver['majorVersion'], json_ver['minorVersion'],
json_ver['patchVersion'], json_ver['buildNumber']])
@@ -1,100 +0,0 @@
# Copyright 2017 VMware, Inc.
# All Rights Reserved
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from oslo_log import log
from tempest.lib.services.network import base
from vmware_nsx_tempest.common import constants
LOG = log.getLogger(__name__)
class L2GatewayClient(base.BaseNetworkClient):
"""
Request resources via API for L2GatewayClient
l2 gateway create request
l2 gateway update request
l2 gateway show request
l2 gateway delete request
l2 gateway list all request
"""
def create_l2_gateway(self, **kwargs):
uri = constants.L2_GWS_BASE_URI
post_data = {constants.L2GW: kwargs}
LOG.info("URI : %(uri)s, posting data : %(post_data)s",
{"uri": uri, "post_data": post_data})
return self.create_resource(uri, post_data)
def update_l2_gateway(self, l2_gateway_id, **kwargs):
uri = constants.L2_GWS_BASE_URI + "/" + l2_gateway_id
post_data = {constants.L2GW: kwargs}
constants.LOG.info(
"URI : %(uri)s, posting data : %(post_data)s",
{"uri": uri, "post_data": post_data})
return self.update_resource(uri, post_data)
def show_l2_gateway(self, l2_gateway_id, **fields):
uri = constants.L2_GWS_BASE_URI + "/" + l2_gateway_id
LOG.info("URI : %(uri)s", {"uri": uri})
return self.show_resource(uri, **fields)
def delete_l2_gateway(self, l2_gateway_id):
uri = constants.L2_GWS_BASE_URI + "/" + l2_gateway_id
LOG.info("URI : %(uri)s", {"uri": uri})
return self.delete_resource(uri)
def list_l2_gateways(self, **filters):
uri = constants.L2_GWS_BASE_URI
LOG.info("URI : %(uri)s", {"uri": uri})
return self.list_resources(uri, **filters)
class L2GatewayConnectionClient(base.BaseNetworkClient):
"""
Request resources via API for L2GatewayClient
l2 gateway connection create request
l2 gateway connection update request
l2 gateway connection show request
l2 gateway connection delete request
l2 gateway connection list all request
"""
resource = 'l2_gateway_connection'
resource_plural = 'l2_gateway_connections'
path = 'l2-gateway-connections'
resource_base_path = '/%s' % path
resource_object_path = '/%s/%%s' % path
def create_l2_gateway_connection(self, **kwargs):
uri = self.resource_base_path
post_data = {self.resource: kwargs}
return self.create_resource(uri, post_data)
def update_l2_gateway_connection(self, l2_gateway_id, **kwargs):
uri = self.resource_object_path % l2_gateway_id
post_data = {self.resource: kwargs}
return self.update_resource(uri, post_data)
def show_l2_gateway_connection(self, l2_gateway_id, **fields):
uri = self.resource_object_path % l2_gateway_id
return self.show_resource(uri, **fields)
def delete_l2_gateway_connection(self, l2_gateway_id):
uri = self.resource_object_path % l2_gateway_id
return self.delete_resource(uri)
def list_l2_gateway_connections(self, **filters):
uri = self.resource_base_path
return self.list_resources(uri, **filters)
Whitespace-only changes.
@@ -1,68 +0,0 @@
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from tempest.lib.services.network import base
from vmware_nsx_tempest.services import network_client_base as base_client
class BandwidthLimitRulesClient(base.BaseNetworkClient):
resource = 'bandwidth_limit_rule'
resource_plural = 'bandwidth_limit_rules'
path = 'qos/policies'
resource_base_path = '/%s/%%s/bandwidth_limit_rules' % path
resource_object_path = '/%s/%%s/bandwidth_limit_rules/%%s' % path
def create_bandwidth_limit_rule(self, policy_id, **kwargs):
uri = self.resource_base_path % policy_id
post_data = {self.resource: kwargs}
return self.create_resource(uri, post_data)
def update_bandwidth_limit_rule(self, rule_id, policy_id, **kwargs):
uri = self.resource_object_path % (policy_id, rule_id)
post_data = {self.resource: kwargs}
return self.update_resource(uri, post_data)
def show_bandwidth_limit_rule(self, rule_id, policy_id, **fields):
uri = self.resource_object_path % (policy_id, rule_id)
return self.show_resource(uri, **fields)
def delete_bandwidth_limit_rule(self, rule_id, policy_id):
uri = self.resource_object_path % (policy_id, rule_id)
return self.delete_resource(uri)
def list_bandwidth_limit_rules(self, policy_id, **filters):
uri = self.resource_base_path % policy_id
return self.list_resources(uri, **filters)
def get_client(client_mgr,
set_property=False,
with_name="qos_bandwidth_limit_rules_client"):
"""create a qos bandwidth limit rules client
For tempest user:
client = bandwidth_limit_rules_client.get_client(osn.adm)
"""
manager = getattr(client_mgr, 'manager', client_mgr)
net_client = getattr(manager, 'networks_client')
try:
_params = base_client.default_params_with_timeout_values.copy()
except Exception:
_params = {}
client = BandwidthLimitRulesClient(net_client.auth_provider,
net_client.service,
net_client.region,
net_client.endpoint_type,
**_params)
if set_property:
setattr(manager, with_name, client)
return client
-147
View File
@@ -1,147 +0,0 @@
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from vmware_nsx_tempest.services.qos import (
bandwidth_limit_rules_client as bandwidth_limit_rules_client)
from vmware_nsx_tempest.services.qos import (
dscp_marking_rules_client as dscp_marking_rules_client)
from vmware_nsx_tempest.services.qos import (
policies_client as policies_client)
from vmware_nsx_tempest.services.qos import (
rule_types_client as rule_types_client)
RULE_TYPE_BANDWIDTH_LIMIT = "bandwidth_limit"
RULE_TYPE_DSCP_MARK = "dscp_marking"
VALID_RULE_TYPES = [RULE_TYPE_BANDWIDTH_LIMIT, RULE_TYPE_DSCP_MARK]
QOS_POLICY_ID = 'qos_policy_id'
class BaseQosClient(object):
def __init__(self, manager, set_property=True):
self.policies_client = policies_client.get_client(
manager, set_property)
self.bandwidths_client = (
bandwidth_limit_rules_client.get_client(
manager, set_property))
self.dscps_client = dscp_marking_rules_client.get_client(
manager, set_property)
self.types_client = rule_types_client.get_client(manager, True)
def resp_body(self, result, item):
return result.get(item, result)
def create_policy(self, name, description, shared, **kwargs):
result = self.policies_client.create_policy(
name=name,
description=description,
shared=shared,
**kwargs
)
return self.resp_body(result, 'policy')
def delete_policy(self, policy_id_or_name):
policy_id = self.get_policy_id(policy_id_or_name)
result = self.policies_client.delete_policy(policy_id)
return self.resp_body(result, 'policy')
def list_policies(self, **filters):
result = self.policies_client.list_policies(**filters)
return self.resp_body(result, 'policies')
def update_policy(self, policy_id_or_name, **kwargs):
policy_id = self.get_policy_id(policy_id_or_name)
result = self.policies_client.update_policy(policy_id, **kwargs)
return self.resp_body(result, 'policy')
def show_policy(self, policy_id_or_name, **fields):
policy_id = self.get_policy_id(policy_id_or_name)
result = self.policies_client.show_policy(policy_id, **fields)
return self.resp_body(result, 'policy')
def create_bandwidth_limit_rule(self, policy_id_or_name,
max_kbps, max_burst_kbps,
**kwargs):
policy_id = self.get_policy_id(policy_id_or_name)
result = self.bandwidths_client.create_bandwidth_limit_rule(
policy_id,
max_kbps=max_kbps, max_burst_kbps=max_burst_kbps,
**kwargs)
return self.resp_body(result, 'bandwidth_limit_rule')
def delete_bandwidth_limit_rule(self, rule_id, policy_id_or_name):
policy_id = self.get_policy_id(policy_id_or_name)
result = self.bandwidths_client.delete_bandwidth_limit_rule(
rule_id, policy_id)
return self.resp_body(result, 'bandwidth_limit_rule')
def update_bandwidth_limit_rule(self, rule_id, policy_id_or_name,
**kwargs):
policy_id = self.get_policy_id(policy_id_or_name)
result = self.bandwidths_client.update_bandwidth_limit_rule(
rule_id, policy_id, **kwargs)
return self.resp_body(result, 'bandwidth_limit_rule')
def list_bandwidth_limit_rules(self, policy_id_or_name, **filters):
policy_id = self.get_policy_id(policy_id_or_name)
result = self.bandwidths_client.list_bandwidth_limit_rules(
policy_id, **filters)
return self.resp_body(result, 'bandwidth_limit_rules')
def show_bandwidth_limit_rule(self, rule_id, policy_id_or_name,
**fields):
policy_id = self.get_policy_id(policy_id_or_name)
result = self.bandwidths_client.show_bandwidth_limit_rule(
rule_id, policy_id)
return self.resp_body(result, 'bandwidth_limit_rule')
def create_dscp_marking_rule(self, policy_id_or_name, dscp_mark,
**kwargs):
policy_id = self.get_policy_id(policy_id_or_name)
kwargs['dscp_mark'] = dscp_mark
result = self.dscps_client.create_dscp_marking_rule(
policy_id, **kwargs)
return self.resp_body(result, 'dscp_marking_rule')
def delete_dscp_marking_rule(self, rule_id, policy_id_or_name):
policy_id = self.get_policy_id(policy_id_or_name)
result = self.dscps_client.delete_dscp_marking_rule(rule_id,
policy_id)
return self.resp_body(result, 'dscp_marking_rule')
def update_dscp_marking_rule(self, rule_id, policy_id_or_name,
**kwargs):
policy_id = self.get_policy_id(policy_id_or_name)
result = self.dscps_client.update_dscp_marking_rule(
rule_id, policy_id, **kwargs)
return self.resp_body(result, 'dscp_marking_rule')
def list_dscp_marking_rules(self, policy_id_or_name, **filters):
policy_id = self.get_policy_id(policy_id_or_name)
result = self.dscps_client.list_dscp_marking_rules(
policy_id, **filters)
return self.resp_body(result, 'dscp_marking_rules')
def show_dscp_marking_rule(self, rule_id, policy_id_or_name, **fields):
policy_id = self.get_policy_id(policy_id_or_name)
result = self.dscps_client.show_dscp_marking_rule(
rule_id, policy_id, **fields)
return self.resp_body(result, 'dscp_marking_rule')
def list_rule_types(self):
result = self.types_client.list_rule_types()
return self.resp_body(result, 'rule_types')
def available_rule_types(self):
return self.list_rule_types()
def get_policy_id(self, policy_id_or_name):
return self.policies_client.get_policy_id(policy_id_or_name)
@@ -1,68 +0,0 @@
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from tempest.lib.services.network import base
from vmware_nsx_tempest.services import network_client_base as base_client
class DscpMarkingRulesClient(base.BaseNetworkClient):
resource = 'dscp_marking_rule'
resource_plural = 'dscp_marking_rules'
path = 'qos/policies'
resource_base_path = '/%s/%%s/dscp_marking_rules' % path
resource_object_path = '/%s/%%s/dscp_marking_rules/%%s' % path
def create_dscp_marking_rule(self, policy_id, **kwargs):
uri = self.resource_base_path % policy_id
post_data = {self.resource: kwargs}
return self.create_resource(uri, post_data)
def update_dscp_marking_rule(self, rule_id, policy_id, **kwargs):
uri = self.resource_object_path % (policy_id, rule_id)
post_data = {self.resource: kwargs}
return self.update_resource(uri, post_data)
def show_dscp_marking_rule(self, rule_id, policy_id, **fields):
uri = self.resource_object_path % (policy_id, rule_id)
return self.show_resource(uri, **fields)
def delete_dscp_marking_rule(self, rule_id, policy_id):
uri = self.resource_object_path % (policy_id, rule_id)
return self.delete_resource(uri)
def list_dscp_marking_rules(self, policy_id, **filters):
uri = self.resource_base_path % policy_id
return self.list_resources(uri, **filters)
def get_client(client_mgr,
set_property=False,
with_name="qos_dscp_marking_rules_client"):
"""create a qos dscp marking rules client
For tempest user:
client = dscp_marking_rules_client.get_client(osn.adm)
"""
manager = getattr(client_mgr, 'manager', client_mgr)
net_client = getattr(manager, 'networks_client')
try:
_params = base_client.default_params_with_timeout_values.copy()
except Exception:
_params = {}
client = DscpMarkingRulesClient(net_client.auth_provider,
net_client.service,
net_client.region,
net_client.endpoint_type,
**_params)
if set_property:
setattr(manager, with_name, client)
return client
@@ -1,76 +0,0 @@
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from tempest.lib.services.network import base
from vmware_nsx_tempest.services import network_client_base as base_client
class PoliciesClient(base.BaseNetworkClient):
resource = 'policy'
resource_plural = 'policies'
path = 'qos/policies'
resource_base_path = '/%s' % path
resource_object_path = '/%s/%%s' % path
def create_policy(self, **kwargs):
uri = self.resource_base_path
post_data = {self.resource: kwargs}
return self.create_resource(uri, post_data)
def update_policy(self, policy_id, **kwargs):
uri = self.resource_object_path % policy_id
post_data = {self.resource: kwargs}
return self.update_resource(uri, post_data)
def show_policy(self, policy_id, **fields):
uri = self.resource_object_path % policy_id
return self.show_resource(uri, **fields)
def delete_policy(self, policy_id):
uri = self.resource_object_path % policy_id
return self.delete_resource(uri)
def list_policies(self, **filters):
uri = self.resource_base_path
return self.list_resources(uri, **filters)
# utility
def get_policy_id(self, policy_id_or_name):
policies = self.list_policies(name=policy_id_or_name)
policy_list = policies[self.resource_plural]
if len(policy_list) > 0:
return policy_list[0]['id']
return policy_id_or_name
def get_client(client_mgr,
set_property=False,
with_name="qos_policies_client"):
"""create a qos policies client from manager or networks_client
For tempest user:
client = policies_client.get_client(osn.adm)
"""
manager = getattr(client_mgr, 'manager', client_mgr)
net_client = getattr(manager, 'networks_client')
try:
_params = base_client.default_params_with_timeout_values.copy()
except Exception:
_params = {}
client = PoliciesClient(net_client.auth_provider,
net_client.service,
net_client.region,
net_client.endpoint_type,
**_params)
if set_property:
setattr(manager, with_name, client)
return client
@@ -1,50 +0,0 @@
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from tempest.lib.services.network import base
from vmware_nsx_tempest.services import network_client_base as base_client
class RuleTypesClient(base.BaseNetworkClient):
resource = 'rule_type'
resource_plural = 'rule_types'
path = 'qos/rule-types'
resource_base_path = '/%s' % path
resource_object_path = '/%s/%%s' % path
def list_rule_types(self):
uri = self.resource_base_path
return self.list_resources(uri)
def get_client(client_mgr,
set_property=False,
with_name="qos_rule_types_client"):
"""create a qos rule_types client from manager or networks_client
For tempest user:
client = rule_types_client.get_client(osn.adm)
"""
manager = getattr(client_mgr, 'manager', client_mgr)
net_client = getattr(manager, 'networks_client')
try:
_params = base_client.default_params_with_timeout_values.copy()
except Exception:
_params = {}
client = RuleTypesClient(net_client.auth_provider,
net_client.service,
net_client.region,
net_client.endpoint_type,
**_params)
if set_property:
setattr(manager, with_name, client)
return client
-137
View File
@@ -1,137 +0,0 @@
# Copyright 2016 VMware, Inc.
# All Rights Reserved
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from oslo_serialization import jsonutils
from tempest.lib.services.network import base
from vmware_nsx_tempest.services import network_client_base as base_client
class BaseTagsClient(base.BaseNetworkClient):
"""Why base client for tags_client:
https://bugs.launchpad.net/neutron/+bug/1606659
tag-add is a CREATE operation; then expected resp_code is 201
however it is using http PUT operation to accomplish it.
"""
def update_resource(self, uri, post_data, resp_code=None):
"""allow different response code."""
if resp_code:
req_uri = self.uri_prefix + uri
req_post_data = jsonutils.dumps(post_data)
resp, body = self.put(req_uri, req_post_data)
body = jsonutils.loads(body)
self.expected_success(resp_code, resp.status)
return base.rest_client.ResponseBody(
resp, body)
else:
return super(BaseTagsClient, self).update_resource(
uri, post_data)
class TagsClient(BaseTagsClient):
resource_base_path = '/{resource_type}/{resource_id}/tags'
resource_object_path = '/{resource_type}/{resource_id}/tags/{tag}'
def add_tag(self, **kwargs):
"""add a tag to network resource.
neutron tag-add
--resource resource
--resource-type network --tag TAG
"""
uri = self.resource_object_path.format(
**self._fix_args(**kwargs))
# https://bugs.launchpad.net/neutron/+bug/1606659
return self.update_resource(uri, None, 201)
def remove_tag(self, **kwargs):
"""remove a tag from network resource.
neutron tag-remove
--resource resource
--resource-type network --tag TAG
"""
if 'all' in kwargs:
return self.remove_all_tags(**kwargs)
uri = self.resource_object_path.format(
**self._fix_args(**kwargs))
return self.delete_resource(uri)
def remove_all_tags(self, **kwargs):
"""remove all tags from network resource.
neutron tag-remove
--resource resource
--resource-type network --all
"""
uri = self.resource_base_path.format(
**self._fix_args(**kwargs))
return self.delete_resource(uri)
def replace_tag(self, **kwargs):
"""replace network resource's tag with list of tags.
neutron tag-replace
--resource resource
--resource-type network --tag TAG
"""
tag_list = kwargs.pop('tags', None)
kwargs = self._fix_args(**kwargs)
if 'tag' in kwargs:
uri = self.resource_object_path.format(**kwargs)
else:
uri = self.resource_base_path.format(**kwargs)
update_body = None if tag_list is None else {"tags": tag_list}
return self.update_resource(uri, update_body)
def _fix_args(self, **kwargs):
"""Fix key-value of input fields.
resource can be name, to simplify the design, only ID accepted.
"""
if 'resource' in kwargs and 'resource_id' not in kwargs:
kwargs['resource_id'] = kwargs['resource']
if 'resource_type' in kwargs:
if kwargs['resource_type'][-1] != 's':
kwargs['resource_type'] += "s"
else:
kwargs['resource_type'] = 'networks'
return kwargs
def get_client(client_mgr,
set_property=False, with_name="tags_client"):
"""create tags_client from networks_client.
Create network tags_client from manager or networks_client.
client = tags_client.get_client(manager)
"""
manager = getattr(client_mgr, 'manager', client_mgr)
net_client = getattr(manager, 'networks_client')
try:
_params = base_client.default_params_with_timeout_values.copy()
except Exception:
_params = {}
client = TagsClient(net_client.auth_provider,
net_client.service,
net_client.region,
net_client.endpoint_type,
**_params)
if set_property:
setattr(manager, with_name, client)
return client
-21
View File
@@ -1,21 +0,0 @@
# Copyright 2015 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
def ceil(a, b):
if b == 0:
return 0
div = a / b
mod = 0 if a % b is 0 else 1
return div + mod
Whitespace-only changes.
Whitespace-only changes.
@@ -1,446 +0,0 @@
# Copyright 2016 VMware, Inc.
# All Rights Reserved
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from oslo_log import log as logging
from tempest.api.network import base
from tempest import config
from tempest.lib import decorators
from tempest.lib import exceptions
from tempest import test
from vmware_nsx_tempest._i18n import _
from vmware_nsx_tempest.services import tags_client
CONF = config.CONF
LOG = logging.getLogger(__name__)
MAX_TAG_LEN = 60
class BaseTagsTest(base.BaseNetworkTest):
"""Base class for Tags Test."""
@classmethod
def skip_checks(cls):
"""skip tests if the tags feauture is not enabled."""
super(BaseTagsTest, cls).skip_checks()
if not test.is_extension_enabled('tag', 'network'):
msg = "network tag extension not enabled."
raise cls.skipException(msg)
@classmethod
def resource_setup(cls):
"""setup resources."""
super(BaseTagsTest, cls).resource_setup()
cls.primary_mgr = cls.get_client_manager()
cls.tags_client = tags_client.get_client(cls.primary_mgr)
@classmethod
def resource_cleanup(cls):
"""cleanup resources before handing over to framework."""
super(BaseTagsTest, cls).resource_cleanup()
@classmethod
def list_networks(cls, **filters):
nets = cls.networks_client.list_networks(**filters)
return nets.get('networks')
@classmethod
def tag_add(cls, network_id, tag, resource_type='network'):
cls.tags_client.add_tag(resource_type=resource_type,
resource_id=network_id,
tag=tag)
network = cls.networks_client.show_network(network_id)
return network.get('network')
@classmethod
def tag_remove(cls, network_id, tag, resource_type='network'):
cls.tags_client.remove_tag(resource_type=resource_type,
resource_id=network_id,
tag=tag)
network = cls.networks_client.show_network(network_id)
return network.get('network')
@classmethod
def tag_replace(cls, network_id, tags, resource_type='network'):
req_body = dict(resource_type=resource_type, resource_id=network_id)
if type(tags) in (list, tuple, set):
req_body['tags'] = tags
else:
req_body['tags'] = [tags]
cls.tags_client.replace_tag(**req_body)
network = cls.networks_client.show_network(network_id)
return network.get('network')
def network_add_tag(self, network_id, tag):
network = self.tag_add(network_id, tag, 'network')
self.assertIn(tag, network['tags'])
return network
def network_remove_tag(self, network_id, tag):
network = self.tag_remove(network_id, tag, 'network')
self.assertNotIn(tag, network['tags'])
return network
def network_replace_tags(self, network_id, tags=None):
if tags is None:
tags = ['a', 'ab', 'abc']
network = self.tag_replace(network_id, tags, 'network')
self.assertEqual(len(tags), len(network['tags']))
for tag in tags:
self.assertIn(tag, network['tags'])
return network
class NetworkTagAddTest(BaseTagsTest):
"""neutron tag-add test."""
@classmethod
def resource_setup(cls):
"""setup resources."""
super(NetworkTagAddTest, cls).resource_setup()
cls.net = cls.create_network()
@decorators.idempotent_id('0e37a579-aff3-47ba-9f1f-3ac4482fce16')
def test_add_tags(self):
"""neutron tag-add operations."""
tags = ['a', 'gold', 'T' * MAX_TAG_LEN]
network_id = self.net.get('id')
# check we can add tag one at time
for tag in tags:
network = self.network_add_tag(network_id, tag)
# and all added tags exist.
for tag in tags:
self.assertIn(tag, network['tags'])
@decorators.idempotent_id('eb52eac3-5e79-4183-803a-a3d97ceb171d')
@decorators.attr(type='negative')
def test_add_tag_one_char_too_long(self):
tag_too_long = 'a' * (MAX_TAG_LEN + 1)
network_id = self.net.get('id')
self.assertRaises(exceptions.BadRequest,
self.network_add_tag,
network_id, tag_too_long)
@decorators.idempotent_id('d08f3fbe-dc6f-4f3c-b9b2-4d9957884edf')
@decorators.attr(type='negative')
def test_add_tag_empty_one(self):
network_id = self.net.get('id')
self.assertRaises(exceptions.NotFound,
self.network_add_tag,
network_id, '')
class NetworkTagRemoveTest(BaseTagsTest):
"""neutron tag-remove test."""
@classmethod
def resource_setup(cls):
"""setup resources."""
super(NetworkTagRemoveTest, cls).resource_setup()
cls.net = cls.create_network()
@decorators.idempotent_id('178fbd96-900f-4c3d-8cd1-5525f4cf2b81')
def test_remove_tags(self):
"""neutron tag-remove operations."""
network_id = self.net.get('id')
tag = 'spinning-tail'
self.network_add_tag(network_id, tag)
self.network_remove_tag(network_id, tag)
@decorators.idempotent_id('1fe5a8b2-ff5d-4250-b930-21b1a3b48055')
@decorators.attr(type='negative')
def test_remove_all_tags(self):
network_id = self.net.get('id')
self.network_replace_tags(network_id)
req_body = dict(resource_type='network',
resource_id=network_id, all=True)
self.tags_client.remove_tag(**req_body)
network = self.networks_client.show_network(network_id)['network']
self.assertEqual(len(network['tags']), 0)
@decorators.idempotent_id('591337b0-a2e6-4d72-984c-e5b6a6ec12d2')
@decorators.attr(type='negative')
def test_remove_not_exist_tag(self):
"""neutron tag-remove operations."""
network_id = self.net.get('id')
tag_not_tagged = 'talking-head'
self.assertRaises(exceptions.NotFound,
self.network_remove_tag,
network_id, tag_not_tagged)
class NetworkTagReplaceTest(BaseTagsTest):
"""neutron tag-replace test."""
@classmethod
def resource_setup(cls):
"""setup resources."""
super(NetworkTagReplaceTest, cls).resource_setup()
cls.net = cls.create_network()
@decorators.idempotent_id('7d4fb288-2f2d-4f47-84af-be3175b057b5')
def test_replace_tags(self):
"""neutron tag-replace operations."""
network_id = self.net.get('id')
tags = ['east', 'south', 'west', 'north']
self.network_replace_tags(network_id, tags)
new_tags = ['BIG', 'small']
self.network_replace_tags(network_id, new_tags)
# EQ to remove all
empty_tags = []
self.network_replace_tags(network_id, empty_tags)
@decorators.idempotent_id('20a05e9e-0b25-4085-b89f-fd5f0c57d2fa')
@decorators.attr(type='negative')
def test_replace_tags_one_char_too_long(self):
tags_too_long = ['aaa', 'z' * (MAX_TAG_LEN + 1)]
network_id = self.net.get('id')
self.assertRaises(exceptions.BadRequest,
self.network_replace_tags,
network_id, tags_too_long)
class NetworkTagFilterTest(BaseTagsTest):
"""searching networks using tags querying params.
Four query parameters are supported:
Q-param Q-procedure
------------ -----------
tags x_and_y
tags-any x_or_y
not-tags not_x_and_y
not-tags-any not_x_or_y
"""
@classmethod
def resource_setup(cls):
"""setup default values for filtering tests."""
super(NetworkTagFilterTest, cls).resource_setup()
cls.a_b_c = ['a', 'ab', 'abc']
cls.not_tagged_tags = ['talking-head', 'spinning-tail']
cls._tags = (['east', 'gold', 'production'],
['west', 'silver', 'development'],
['north', 'brown', 'development', 'abc'],
['south', 'brown', 'testing', 'a'],
['west', 'gold', 'production', 'ab'],
['east', 'silver', 'testing'],
['north', 'gold', 'production'],
['south', 'silver', 'testing'])
cls.QQ = {'router:external': False}
cls.GG = {}
for ix in range(0, len(cls._tags)):
net = cls.create_network()
tags = cls._tags[ix]
net = cls.tag_replace(net['id'], tags=tags)
if not (set(net['tags']) == set(cls._tags[ix])):
raise Exception(
_("tags[%s] are not tag-replace successfully.") % tags)
net_id = net['id']
cls.GG[net_id] = set(net['tags'])
def check_matched_search_list(self, matched_nets, m_net_list, title):
LOG.info(_("Expected_nets[{0}]: {1}").format(title, m_net_list))
LOG.info(_("Number of matched_nets: {0}").format(len(matched_nets)))
self.assertEqual(len(matched_nets), len(m_net_list))
for net in matched_nets:
self.assertIn(net['id'], m_net_list)
@decorators.idempotent_id('9646af99-7e04-4724-ac54-4a938de764f1')
def test_tags_only_one_network(self):
"""each tag in self.a_b_c only tag one network."""
for tag in self.a_b_c:
filters = {'tags': tag}
filters.update(self.QQ)
nets = self.list_networks(**filters)
self.assertEqual(len(nets), 1)
@decorators.idempotent_id('5632b745-651a-444f-922d-6434e060991a')
def test_tags_any_only_one_network(self):
"""each tag in self.a_b_c only tag one network."""
for tag in self.a_b_c:
filters = {'tags-any': tag}
filters.update(self.QQ)
nets = self.list_networks(**filters)
self.assertEqual(len(nets), 1)
@decorators.idempotent_id('a0d8c21b-1ec0-4c6d-b5d8-72baebabde26')
def test_tags_not_tagged(self):
"""search with tags for tags not being tagged."""
for tag in self.not_tagged_tags:
filters = {'tags': tag}
filters.update(self.QQ)
nets = self.list_networks(**filters)
self.assertEqual(len(nets), 0)
@decorators.idempotent_id('1049eac1-028b-4664-aeb7-c7656240622d')
def test_tags_any_not_tagged(self):
"""search with tags-any for tags not being tagged."""
for tag in self.not_tagged_tags:
filters = {'tags-any': tag}
filters.update(self.QQ)
nets = self.list_networks(**filters)
self.assertEqual(len(nets), 0)
@decorators.idempotent_id('a9b42503-5dd1-490d-b0c6-673951cc86a1')
def test_tags(self):
"""find networks having tags (and operation)"""
tags = ['gold', 'production']
m_net_list = x_and_y(tags, self.GG)
filters = {'tags': tags}
filters.update(self.QQ)
nets = self.list_networks(**filters)
self.check_matched_search_list(nets, m_net_list, 'tags')
@decorators.idempotent_id('c38e788d-749e-401a-8bbb-26e36a7b573f')
def test_tags_any(self):
"""find networks having tags-any (or operation)"""
tags = ['gold', 'production']
m_net_list = x_or_y(tags, self.GG)
filters = {'tags-any': tags}
filters.update(self.QQ)
nets = self.list_networks(**filters)
self.check_matched_search_list(nets, m_net_list, 'tags-any')
@decorators.idempotent_id('e7bb1cea-3271-418c-bfe2-038fff6187e6')
def test_not_tags(self):
"""find networks not having not-tags (and operation)"""
tags = ['gold', 'production']
m_net_list = not_x_and_y(tags, self.GG)
filters = {'not-tags': tags}
filters.update(self.QQ)
nets = self.list_networks(**filters)
self.check_matched_search_list(nets, m_net_list, 'not-tags')
@decorators.idempotent_id('c36a1d00-c131-4297-86c1-a3fc06c61629')
def test_not_tags_any(self):
"""find networks not having not-tags-any (or operation)"""
tags = ['gold', 'production']
m_net_list = not_x_or_y(tags, self.GG)
filters = {'not-tags-any': tags}
filters.update(self.QQ)
nets = self.list_networks(**filters)
self.check_matched_search_list(nets, m_net_list, 'not-tags-any')
@decorators.idempotent_id('4345e944-6b2b-4106-a208-ce07cefe764f')
def test_tags_any_not_tags(self):
"""find networks having tags-any and not-tags."""
tags = ['gold', 'production']
not_tags = ['west']
m_net_list = not_x_and_y(not_tags, self.GG,
x_or_y(tags, self.GG))
filters = {'tags-any': tags, 'not-tags': not_tags}
filters.update(self.QQ)
nets = self.list_networks(**filters)
self.check_matched_search_list(nets, m_net_list,
'tags-any & not-tags')
@decorators.idempotent_id('0d635ba7-5c94-4a24-b7a8-d3b413d1ec83')
@decorators.skip_because(bug="1611054")
def test_tags_tags_any(self):
"""finding networks using tags and tags-any."""
tags = ['production']
tags_any = ['east', 'west']
m_net_list = x_or_y(tags_any, self.GG,
x_and_y(tags, self.GG))
filters = {'tags': tags, 'tags-any': tags_any}
filters.update(self.QQ)
nets = self.list_networks(**filters)
self.check_matched_search_list(nets, m_net_list,
'tags & tags-any')
@decorators.idempotent_id('2067a8fc-2d7b-4085-a6c2-7e454f6f26f3')
def test_tags_not_tags_any(self):
"""finding networks using tags and not-tags-any."""
tags = ['gold', 'production']
not_tags = ['east', 'west', 'silver']
m_net_list = not_x_or_y(not_tags, self.GG,
x_and_y(tags, self.GG))
filters = {'tags': tags, 'not-tags-any': not_tags}
filters.update(self.QQ)
nets = self.list_networks(**filters)
self.check_matched_search_list(nets, m_net_list,
'tags & not-tags-any')
@decorators.idempotent_id('f2bbf51c-e32e-4664-a0db-59eed493c3d1')
def test_tags_not_tags_any2(self):
"""finding networks using tags and not-tags-any."""
tags = ['gold', 'production']
not_tags = ['west', 'east']
m_net_list = not_x_or_y(not_tags, self.GG,
x_and_y(tags, self.GG))
filters = {'tags': tags, 'not-tags-any': not_tags}
filters.update(self.QQ)
nets = self.list_networks(**filters)
self.check_matched_search_list(nets, m_net_list,
'tags & not-tags-any2')
@decorators.idempotent_id('7b17dfa8-f7ac-47c2-b814-35c5ed1c325b')
def test_tags_not_tags(self):
"""finding networks using tags and not-tags."""
tags = ['gold', 'production']
not_tags = ['west']
m_net_list = not_x_and_y(not_tags, self.GG,
x_and_y(tags, self.GG))
filters = {'tags': tags, 'not-tags': not_tags}
filters.update(self.QQ)
nets = self.list_networks(**filters)
self.check_matched_search_list(nets, m_net_list,
'tags & not-tags')
@decorators.idempotent_id('f723f717-660b-4d8e-ae9f-014f0a3f812d')
def test_tags_not_tags_itself(self):
""""tags and not-tags itself is always an empty set."""
tags = ['gold', 'production']
not_x_and_y(tags, self.GG, x_and_y(tags, self.GG))
filters = {'tags': tags, 'not-tags': tags}
filters.update(self.QQ)
nets = self.list_networks(**filters)
self.assertEqual(0, len(nets))
# search/filter methods
# K_sets: Dict of sets
def x_and_y(x_and_y, K_sets, on_keys=None):
"""tags=x_and_y"""
s_xy = set(x_and_y)
xy_s = [k for k, S in K_sets.items()
if (on_keys is None or k in on_keys) and s_xy.issubset(S)]
return xy_s
def not_x_and_y(x_and_y, K_sets, on_keys=None):
"""not-tags=x_and_y"""
s_xy = set(x_and_y)
xy_s = [k for k, S in K_sets.items()
if (on_keys is None or k in on_keys) and not s_xy.issubset(S)]
return xy_s
def x_or_y(x_or_y, K_sets, on_keys=None):
"""tags-any=x_or_y"""
s_xy = set(x_or_y)
xy_s = [k for k, S in K_sets.items()
if (on_keys is None or k in on_keys) and len(S & s_xy) > 0]
return xy_s
def not_x_or_y(x_or_y, K_sets, on_keys=None):
"""not tags-any=x_or_y"""
s_xy = set(x_or_y)
xy_s = [k for k, S in K_sets.items()
if (on_keys is None or k in on_keys) and len(S & s_xy) == 0]
return xy_s
-856
View File
@@ -1,856 +0,0 @@
# Copyright 2017 VMware, Inc.
# All Rights Reserved
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import testtools
from tempest.api.network import base
from tempest import config
from tempest.lib.common.utils import data_utils
from tempest.lib.common.utils import test_utils
from tempest.lib import decorators
from tempest.lib import exceptions
from tempest import test
from vmware_nsx_tempest.services.qos import base_qos
CONF = config.CONF
class BaseQosTest(base.BaseAdminNetworkTest):
"""Base class for Qos Test.
1. Setup QoS clients for admin and primary users.
2. Manages qos resources creation and deletion.
3. Manages network/port creation and deletion as network cannot be
deleted if ports are associated which test framework won't handle.
"""
@classmethod
def skip_checks(cls):
"""skip tests if qos is not enabled."""
super(BaseQosTest, cls).skip_checks()
if not test.is_extension_enabled('qos', 'network'):
msg = "q-qos extension not enabled."
raise cls.skipException(msg)
@classmethod
def resource_setup(cls):
"""setup resources."""
super(BaseQosTest, cls).resource_setup()
cls.admin_mgr = cls.get_client_manager(credential_type='admin')
cls.primary_mgr = cls.get_client_manager()
cls.adm_qos_client = base_qos.BaseQosClient(cls.admin_mgr)
cls.pri_qos_client = base_qos.BaseQosClient(cls.primary_mgr)
cls.qos_available_rule_types = (
cls.adm_qos_client.available_rule_types())
cls.policies_created = []
@classmethod
def resource_cleanup(cls):
"""cleanup resources before handing over to framework."""
for network in cls.networks:
# network cannot be deleted if its ports have policy associated.
port_list = cls.admin_mgr.ports_client.list_ports(
network_id=network['id'])['ports']
for port in port_list:
test_utils.call_and_ignore_notfound_exc(
cls.delete_port, port['id'])
test_utils.call_and_ignore_notfound_exc(
cls.delete_network, network['id'])
for policy in cls.policies_created:
test_utils.call_and_ignore_notfound_exc(
cls.adm_qos_client.delete_policy, policy['id'])
super(BaseQosTest, cls).resource_cleanup()
@classmethod
def create_port(cls, network, client_mgr=None, **kwargs):
"""create port."""
client_mgr = client_mgr if client_mgr else cls.admin_mgr
body = client_mgr.ports_client.create_port(
network_id=network['id'], **kwargs)
port = body.get('port', body)
cls.ports.append(port)
return port
@classmethod
def update_port(cls, port_id, client_mgr=None, **kwargs):
"""update port."""
client_mgr = client_mgr if client_mgr else cls.admin_mgr
body = client_mgr.ports_client.update_port(
port_id, **kwargs)
return body.get('port', body)
@classmethod
def show_port(cls, port_id, client_mgr=None):
"""show port."""
client_mgr = client_mgr if client_mgr else cls.admin_mgr
body = client_mgr.ports_client.show_port(port_id)
return body.get('port', body)
@classmethod
def delete_port(cls, port_id, client_mgr=None, **kwargs):
"""delete port."""
client_mgr = client_mgr if client_mgr else cls.admin_mgr
body = client_mgr.ports_client.delete_port(port_id)
return body.get('port', body)
@classmethod
def create_network(cls, network_name=None, client_mgr=None, **kwargs):
"""create network."""
network_name = network_name or data_utils.rand_name('qos-net')
client_mgr = client_mgr if client_mgr else cls.admin_mgr
body = client_mgr.networks_client.create_network(
name=network_name, **kwargs)
network = body['network']
cls.networks.append(network)
return network
@classmethod
def create_shared_network(cls, network_name=None, client_mgr=None,
**kwargs):
"""create shared network."""
return cls.create_network(network_name, client_mgr,
shared=True, **kwargs)
@classmethod
def show_network(cls, network_id, client_mgr=None):
"""show network."""
client_mgr = client_mgr if client_mgr else cls.admin_mgr
network = client_mgr.networks_client.show_network(network_id)
return network.get('network', network)
@classmethod
def update_network(cls, network_id, client_mgr=None, **kwargs):
"""update network."""
client_mgr = client_mgr if client_mgr else cls.admin_mgr
network = client_mgr.networks_client.update_network(
network_id, **kwargs)
return network.get('network', network)
@classmethod
def delete_network(cls, network_id, client_mgr=None):
"""delete network."""
client_mgr = client_mgr if client_mgr else cls.admin_mgr
network = client_mgr.networks_client.delete_network(network_id)
return network.get('network', network)
@classmethod
def create_qos_policy(cls, name='test-policy',
description='test policy desc',
shared=False,
qos_client=None, **kwargs):
"""create qos policy."""
qos_client = qos_client if qos_client else cls.adm_qos_client
policy = qos_client.create_policy(
name=name, description=description,
shared=shared, **kwargs)
cls.policies_created.append(policy)
return policy
@classmethod
def create_qos_bandwidth_limit_rule(cls, policy_id,
qos_client=None, **kwargs):
"""create qos-bandwidth-limit-rule."""
qos_client = qos_client if qos_client else cls.adm_qos_client
rule = qos_client.create_bandwidth_limit_rule(policy_id, **kwargs)
return rule
@classmethod
def create_qos_dscp_marking_rule(cls, policy_id, dscp_mark,
qos_client=None, **kwargs):
"""create qos-dscp-marking-rule."""
qos_client = qos_client if qos_client else cls.adm_qos_client
rule = qos_client.create_dscp_marking_rule(
policy_id, dscp_mark, **kwargs)
return rule
class QosPolicyTest(BaseQosTest):
"""QoS Policy CURD operations.
test qos policies and network/port association and disassociation.
"""
@decorators.idempotent_id('108fbdf7-3463-4e47-9871-d07f3dcf5bbb')
def test_create_policy(self):
"""qos-policy-create: create policy."""
policy = self.create_qos_policy(name='test-policy',
description='test policy desc1',
shared=False)
self.addCleanup(test_utils.call_and_ignore_notfound_exc,
self.adm_qos_client.delete_policy, policy['id'])
# Test 'show policy'
retrieved_policy = self.adm_qos_client.show_policy(policy['id'])
self.assertEqual('test-policy', retrieved_policy['name'])
self.assertEqual('test policy desc1',
retrieved_policy['description'])
self.assertFalse(retrieved_policy['shared'])
# Test 'list policies'
policies = self.adm_qos_client.list_policies()
policies_ids = [p['id'] for p in policies]
self.assertIn(policy['id'], policies_ids)
@decorators.idempotent_id('f8d20e92-f06d-4805-b54f-230f77715815')
def test_list_policy_filter_by_name(self):
"""qos-policy-list --name=<name>: list policies."""
name1 = data_utils.rand_name('test-policy')
name2 = name1 + "0"
policy_name1 = self.create_qos_policy(
name=name1, description='test policy', shared=False)
self.addCleanup(test_utils.call_and_ignore_notfound_exc,
self.adm_qos_client.delete_policy, policy_name1['id'])
policy_name2 = self.create_qos_policy(
name=name2, description='test policy', shared=False)
self.addCleanup(test_utils.call_and_ignore_notfound_exc,
self.adm_qos_client.delete_policy, policy_name2['id'])
policies = self.adm_qos_client.list_policies(name=name1)
self.assertEqual(1, len(policies))
retrieved_policy = policies[0]
self.assertEqual(name1, retrieved_policy['name'])
@decorators.idempotent_id('8e88a54b-f0b2-4b7d-b061-a15d93c2c7d6')
def test_policy_update(self):
"""qos-policy-update POLICY_ID."""
policy = self.create_qos_policy(name='test-policy',
description='',
shared=False)
self.addCleanup(test_utils.call_and_ignore_notfound_exc,
self.adm_qos_client.delete_policy, policy['id'])
self.adm_qos_client.update_policy(policy['id'],
description='test policy desc2',
shared=True)
retrieved_policy = self.adm_qos_client.show_policy(policy['id'])
self.assertEqual('test policy desc2',
retrieved_policy['description'])
self.assertTrue(retrieved_policy['shared'])
self.assertEmpty(retrieved_policy['rules'])
@decorators.idempotent_id('1cb42653-54bd-4a9a-b888-c55e18199201')
def test_delete_policy(self):
"""qos-policy-delete POLICY_ID."""
policy = self.create_qos_policy(
'test-policy', 'desc', True)
self.addCleanup(test_utils.call_and_ignore_notfound_exc,
self.adm_qos_client.delete_policy, policy['id'])
retrieved_policy = self.adm_qos_client.show_policy(policy['id'])
self.assertEqual('test-policy', retrieved_policy['name'])
self.adm_qos_client.delete_policy(policy['id'])
self.assertRaises(exceptions.NotFound,
self.adm_qos_client.show_policy, policy['id'])
def _test_list_admin_rule_types(self):
"""qos-available-rule-types: available rule type from admin view."""
self._test_list_rule_types(self.adm_qos_client)
def _test_list_regular_rule_types(self):
"""qos-available-rule-types: available rule type from project view."""
self._test_list_rule_types(self.pri_qos_client)
def _test_list_rule_types(self, client):
# List supported rule types
# TODO(QoS): since in gate we run both ovs and linuxbridge ml2 drivers,
# and since Linux Bridge ml2 driver does not have QoS support yet, ml2
# plugin reports no rule types are supported. Once linuxbridge will
# receive support for QoS, the list of expected rule types will change.
#
# In theory, we could make the test conditional on which ml2 drivers
# are enabled in gate (or more specifically, on which supported qos
# rules are claimed by core plugin), but that option doesn't seem to be
# available thru tempest.lib framework
expected_rule_types = []
expected_rule_details = ['type']
rule_types = client.available_rule_types()
actual_rule_types = [rule['type'] for rule in rule_types]
# TODO(akang): seems not correct
# Verify that only required fields present in rule details
for rule in actual_rule_types:
self.assertEqual(tuple(rule.keys()), tuple(expected_rule_details))
# Verify if expected rules are present in the actual rules list
for rule in expected_rule_types:
self.assertIn(rule, actual_rule_types)
def _disassociate_network(self, network_id, client_mgr=None):
self.update_network(network_id, client_mgr=client_mgr,
qos_policy_id=None)
updated_network = self.show_network(network_id,
client_mgr=client_mgr)
self.assertIsNone(updated_network['qos_policy_id'])
@decorators.idempotent_id('65b9ef75-1911-406a-bbdb-ca1d68d528b0')
def test_policy_association_with_admin_network(self):
"""admin can create network with non-shared policy."""
policy = self.create_qos_policy(name='test-policy',
description='test policy',
shared=False)
self.addCleanup(test_utils.call_and_ignore_notfound_exc,
self.adm_qos_client.delete_policy, policy['id'])
network = self.create_shared_network('test network',
qos_policy_id=policy['id'])
self.addCleanup(test_utils.call_and_ignore_notfound_exc,
self.delete_network, network['id'])
retrieved_network = self.show_network(network['id'])
self.assertEqual(
policy['id'], retrieved_network['qos_policy_id'])
self._disassociate_network(network['id'], self.admin_mgr)
@decorators.idempotent_id('1738de5d-0476-4163-9022-5e1b548c208e')
def test_policy_association_with_tenant_network(self):
"""project/tenant can create network with shared policy."""
policy = self.create_qos_policy(name='test-policy',
description='test policy',
shared=True)
self.addCleanup(test_utils.call_and_ignore_notfound_exc,
self.adm_qos_client.delete_policy, policy['id'])
network = self.create_network('test network',
client_mgr=self.primary_mgr,
qos_policy_id=policy['id'])
self.addCleanup(test_utils.call_and_ignore_notfound_exc,
self.delete_network, network['id'])
retrieved_network = self.show_network(network['id'],
client_mgr=self.primary_mgr)
self.assertEqual(
policy['id'], retrieved_network['qos_policy_id'])
self._disassociate_network(network['id'], self.primary_mgr)
@decorators.attr(type='negative')
@decorators.idempotent_id('9efe63d0-836f-4cc2-b00c-468e63aa614e')
def test_policy_association_with_network_nonexistent_policy(self):
"""Can not attach network to a nonexist policy."""
network = self.create_network(
'test network',
qos_policy_id='9efe63d0-836f-4cc2-b00c-468e63aa614e')
self.addCleanup(test_utils.call_and_ignore_notfound_exc,
self.delete_network, network['id'])
retrieved_network = self.show_network(network['id'])
# check if network is not attached to the policy
self.assertIsNone(retrieved_network['qos_policy_id'],
'Error: Network is attached to non-existent policy')
@decorators.attr(type='negative')
@decorators.idempotent_id('1aa55a79-324f-47d9-a076-894a8fc2448b')
def test_policy_association_with_network_non_shared_policy(self):
"""tenant/project can not attach network with not-shared policy."""
policy = self.create_qos_policy(name='test-policy',
description='test policy',
shared=False)
self.addCleanup(test_utils.call_and_ignore_notfound_exc,
self.adm_qos_client.delete_policy, policy['id'])
network = self.create_network(
'test network',
qos_policy_id=policy['id'],
client_mgr=self.primary_mgr)
self.addCleanup(test_utils.call_and_ignore_notfound_exc,
self.delete_network, network['id'])
retrieved_network = self.show_network(network['id'],
client_mgr=self.primary_mgr)
# check if network is not attached to the policy
self.assertIsNone(retrieved_network['qos_policy_id'],
'Error: Network is attached to QoS policy')
@decorators.idempotent_id('10a9392c-1359-4cbb-989f-fb768e5834a8')
def test_policy_update_association_with_admin_network(self):
"""admin can create associate non-shared policy to network."""
policy = self.create_qos_policy(name='test-policy',
description='test policy',
shared=False)
self.addCleanup(test_utils.call_and_ignore_notfound_exc,
self.adm_qos_client.delete_policy, policy['id'])
network = self.create_shared_network('test network')
self.addCleanup(test_utils.call_and_ignore_notfound_exc,
self.delete_network, network['id'])
retrieved_network = self.show_network(network['id'])
self.assertIsNone(retrieved_network['qos_policy_id'])
self.update_network(
network['id'], qos_policy_id=policy['id'])
retrieved_network = self.show_network(network['id'])
self.assertEqual(
policy['id'], retrieved_network['qos_policy_id'])
self._disassociate_network(network['id'], self.admin_mgr)
def _disassociate_port(self, port_id, client_mgr=None):
client_mgr = client_mgr if client_mgr else self.admin_mgr
self.update_port(port_id, qos_policy_id=None,
client_mgr=client_mgr)
updated_port = self.show_port(port_id, client_mgr=client_mgr)
self.assertIsNone(updated_port['qos_policy_id'])
@decorators.attr(type='nsxv3')
@decorators.attr(type='negative')
@decorators.idempotent_id('98fcd95e-84cf-4746-860e-44692e674f2e')
def test_policy_association_with_port_shared_policy(self):
"""test port can associate shared policy."""
policy = self.create_qos_policy(name='test-policy',
description='test policy',
shared=True)
self.addCleanup(test_utils.call_and_ignore_notfound_exc,
self.adm_qos_client.delete_policy, policy['id'])
network = self.create_shared_network('test network')
self.addCleanup(test_utils.call_and_ignore_notfound_exc,
self.delete_network, network['id'])
port = self.create_port(network, qos_policy_id=policy['id'],
client_mgr=self.primary_mgr)
self.addCleanup(test_utils.call_and_ignore_notfound_exc,
self.delete_port, port['id'])
retrieved_port = self.show_port(port['id'],
client_mgr=self.primary_mgr)
self.assertEqual(
policy['id'], retrieved_port['qos_policy_id'])
self._disassociate_port(port['id'], client_mgr=self.primary_mgr)
@decorators.attr(type='negative')
@decorators.attr(type='nsxv3')
@decorators.idempotent_id('49e02f5a-e1dd-41d5-9855-cfa37f2d195e')
def test_policy_association_with_port_nonexistent_policy(self):
"""test port cannot be created with nonexist policy."""
network = self.create_shared_network('test network')
self.addCleanup(test_utils.call_and_ignore_notfound_exc,
self.delete_network, network['id'])
self.assertRaises(
exceptions.NotFound,
self.create_port,
network,
qos_policy_id='49e02f5a-e1dd-41d5-9855-cfa37f2d195e')
@decorators.attr(type='negative')
@decorators.attr(type='nsxv3')
@decorators.idempotent_id('f53d961c-9fe5-4422-8b66-7add972c6031')
def test_policy_association_with_port_non_shared_policy(self):
"""project/tenant can not associate port with non-shared policy."""
policy = self.create_qos_policy(name='test-policy',
description='test policy',
shared=False)
self.addCleanup(test_utils.call_and_ignore_notfound_exc,
self.adm_qos_client.delete_policy, policy['id'])
network = self.create_shared_network('test network')
self.addCleanup(test_utils.call_and_ignore_notfound_exc,
self.delete_network, network['id'])
port = self.create_port(network, qos_policy_id=policy['id'],
client_mgr=self.primary_mgr)
self.addCleanup(test_utils.call_and_ignore_notfound_exc,
self.delete_port, port['id'])
retrieved_port = self.show_port(port['id'],
client_mgr=self.primary_mgr)
# check if port is not attached to the policy
self.assertIsNone(retrieved_port['qos_policy_id'],
'Error:Port is attached to qos policy')
@decorators.attr(type='nsxv3')
@decorators.idempotent_id('f8163237-fba9-4db5-9526-bad6d2343c76')
def test_policy_update_association_with_port_shared_policy(self):
"""project/tenant can update port with shared policy."""
policy = self.create_qos_policy(name='test-policy',
description='test policy',
shared=True)
self.addCleanup(test_utils.call_and_ignore_notfound_exc,
self.adm_qos_client.delete_policy, policy['id'])
network = self.create_shared_network('test network')
self.addCleanup(test_utils.call_and_ignore_notfound_exc,
self.delete_network, network['id'])
port = self.create_port(network, client_mgr=self.primary_mgr)
self.addCleanup(test_utils.call_and_ignore_notfound_exc,
self.delete_port, port['id'])
retrieved_port = self.show_port(port['id'],
client_mgr=self.primary_mgr)
self.assertIsNone(retrieved_port['qos_policy_id'])
self.update_port(port['id'], qos_policy_id=policy['id'],
client_mgr=self.primary_mgr)
retrieved_port = self.show_port(port['id'],
client_mgr=self.primary_mgr)
self.assertEqual(
policy['id'], retrieved_port['qos_policy_id'])
self._disassociate_port(port['id'])
@decorators.attr(type='negative')
@decorators.idempotent_id('18163237-8ba9-4db5-9525-bad6d2343c75')
def test_delete_not_allowed_if_policy_in_use_by_network(self):
"""can not delete policy if used by network."""
policy = self.create_qos_policy(name='test-policy',
description='test policy',
shared=True)
self.addCleanup(test_utils.call_and_ignore_notfound_exc,
self.adm_qos_client.delete_policy, policy['id'])
network = self.create_shared_network(
'test network', qos_policy_id=policy['id'])
self.addCleanup(test_utils.call_and_ignore_notfound_exc,
self.delete_network, network['id'])
self.assertRaises(
exceptions.Conflict,
self.adm_qos_client.delete_policy, policy['id'])
self._disassociate_network(network['id'], self.admin_mgr)
self.adm_qos_client.delete_policy(policy['id'])
@decorators.attr(type='negative')
@decorators.attr(type='nsxv3')
@decorators.idempotent_id('24153230-84a9-4dd5-9525-bad6d2343c75')
def test_delete_not_allowed_if_policy_in_use_by_port(self):
"""can not delete policy if used by port."""
policy = self.create_qos_policy(name='test-policy',
description='test policy',
shared=True)
self.addCleanup(test_utils.call_and_ignore_notfound_exc,
self.adm_qos_client.delete_policy, policy['id'])
network = self.create_shared_network('test network')
self.addCleanup(test_utils.call_and_ignore_notfound_exc,
self.delete_network, network['id'])
port = self.create_port(network, qos_policy_id=policy['id'],
client_mgr=self.primary_mgr)
self.addCleanup(test_utils.call_and_ignore_notfound_exc,
self.delete_port, port['id'])
self.assertRaises(
exceptions.Conflict,
self.adm_qos_client.delete_policy, policy['id'])
self._disassociate_port(port['id'], client_mgr=self.primary_mgr)
self.adm_qos_client.delete_policy(policy['id'])
@decorators.idempotent_id('a2a5849b-dd06-4b18-9664-0b6828a1fc27')
def test_qos_policy_delete_with_rules(self):
"""Policy with rules attached can be deleted."""
policy = self.create_qos_policy(name='test-policy',
description='test policy',
shared=False)
self.addCleanup(test_utils.call_and_ignore_notfound_exc,
self.adm_qos_client.delete_policy, policy['id'])
self.adm_qos_client.create_bandwidth_limit_rule(
policy['id'], 200, 1337)
self.adm_qos_client.delete_policy(policy['id'])
with testtools.ExpectedException(exceptions.NotFound):
self.adm_qos_client.show_policy(policy['id'])
class QosBandwidthLimitRuleTest(BaseQosTest):
"""QoS Bandwidth limit rule CURD operations."""
@decorators.idempotent_id('8a59b00b-3e9c-4787-92f8-93a5cdf5e378')
def test_rule_create(self):
"""qos-bandwidth-limit-rule-create POLICY_ID."""
qos_client = self.adm_qos_client
policy = self.create_qos_policy(name='test-policy',
description='test policy',
shared=False)
self.addCleanup(test_utils.call_and_ignore_notfound_exc,
self.adm_qos_client.delete_policy, policy['id'])
rule = self.create_qos_bandwidth_limit_rule(
policy_id=policy['id'], max_kbps=200, max_burst_kbps=1337)
# Test 'show rule'
retrieved_rule = qos_client.show_bandwidth_limit_rule(
rule['id'], policy['id'])
self.assertEqual(rule['id'], retrieved_rule['id'])
self.assertEqual(200, retrieved_rule['max_kbps'])
self.assertEqual(1337, retrieved_rule['max_burst_kbps'])
# Test 'list rules'
rules = qos_client.list_bandwidth_limit_rules(policy['id'])
rules_ids = [r['id'] for r in rules]
self.assertIn(rule['id'], rules_ids)
# Test 'show policy'
retrieved_policy = qos_client.show_policy(policy['id'])
policy_rules = retrieved_policy['rules']
self.assertEqual(1, len(policy_rules))
self.assertEqual(rule['id'], policy_rules[0]['id'])
self.assertEqual(base_qos.RULE_TYPE_BANDWIDTH_LIMIT,
policy_rules[0]['type'])
@decorators.attr(type='negative')
@decorators.idempotent_id('8a59b00b-ab01-4787-92f8-93a5cdf5e378')
def test_rule_create_fail_for_the_same_type(self):
"""One bandwidth limit rule per policy."""
policy = self.create_qos_policy(name='test-policy',
description='test policy',
shared=False)
self.addCleanup(test_utils.call_and_ignore_notfound_exc,
self.adm_qos_client.delete_policy, policy['id'])
self.create_qos_bandwidth_limit_rule(
policy_id=policy['id'], max_kbps=200, max_burst_kbps=1337)
self.assertRaises(exceptions.Conflict,
self.create_qos_bandwidth_limit_rule,
policy_id=policy['id'],
max_kbps=201, max_burst_kbps=1338)
@decorators.idempotent_id('149a6988-2568-47d2-931e-2dbc858943b3')
def test_rule_update(self):
"""qos-bandwidth-limit-rule-update RULE-ID POLICY_ID."""
qos_client = self.adm_qos_client
max_kbps = 200
max_burst_kbps = 1337
policy = self.create_qos_policy(name='test-policy',
description='test policy',
shared=False)
self.addCleanup(test_utils.call_and_ignore_notfound_exc,
self.adm_qos_client.delete_policy, policy['id'])
rule = self.create_qos_bandwidth_limit_rule(
policy_id=policy['id'], max_kbps=1, max_burst_kbps=1)
qos_client.update_bandwidth_limit_rule(
rule['id'], policy['id'],
max_kbps=max_kbps, max_burst_kbps=max_burst_kbps)
retrieved_rule = qos_client.show_bandwidth_limit_rule(
rule['id'], policy['id'])
self.assertEqual(max_kbps, retrieved_rule['max_kbps'])
self.assertEqual(max_burst_kbps, retrieved_rule['max_burst_kbps'])
@decorators.idempotent_id('67ee6efd-7b33-4a68-927d-275b4f8ba958')
def test_rule_delete(self):
"""qos-bandwidth-limit-rule-delete RULE-ID POLICY_ID."""
qos_client = self.adm_qos_client
max_kbps = 200
max_burst_kbps = 1337
policy = self.create_qos_policy(name='test-policy',
description='test policy',
shared=False)
self.addCleanup(test_utils.call_and_ignore_notfound_exc,
self.adm_qos_client.delete_policy, policy['id'])
rule = self.create_qos_bandwidth_limit_rule(
policy['id'],
max_kbps=max_kbps, max_burst_kbps=max_burst_kbps)
retrieved_rule = qos_client.show_bandwidth_limit_rule(
rule['id'], policy['id'])
self.assertEqual(rule['id'], retrieved_rule['id'])
qos_client.delete_bandwidth_limit_rule(
rule['id'], policy['id'])
self.assertRaises(exceptions.NotFound,
qos_client.show_bandwidth_limit_rule,
rule['id'], policy['id'])
@decorators.attr(type='negative')
@decorators.idempotent_id('f211222c-5808-46cb-a961-983bbab6b852')
def test_rule_create_rule_nonexistent_policy(self):
"""Cannot create rule with nonexist policy."""
self.assertRaises(
exceptions.NotFound,
self.create_qos_bandwidth_limit_rule,
'policy', max_kbps=200, max_burst_kbps=1337)
@decorators.attr(type='negative')
@decorators.idempotent_id('eed8e2a6-22da-421b-89b9-935a2c1a1b50')
def test_policy_create_forbidden_for_regular_tenants(self):
"""project/tenant cannot create policy."""
self.assertRaises(
exceptions.Forbidden,
self.create_qos_policy,
'test-policy', 'test policy', False,
qos_client=self.pri_qos_client)
@decorators.attr(type='negative')
@decorators.idempotent_id('a4a2e7ad-786f-4927-a85a-e545a93bd274')
def test_rule_create_forbidden_for_regular_tenants(self):
"""project/tenant cannot create rule."""
self.assertRaises(
exceptions.Forbidden,
self.create_qos_bandwidth_limit_rule,
'policy', max_kbps=1, max_burst_kbps=2,
qos_client=self.pri_qos_client)
@decorators.idempotent_id('ce0bd0c2-54d9-4e29-85f1-cfb36ac3ebe2')
def test_get_rules_by_policy(self):
"""qos-bandwidth-limit-rule-list POLICY_ID."""
policy1 = self.create_qos_policy(name='test-policy1',
description='test policy1',
shared=False)
self.addCleanup(test_utils.call_and_ignore_notfound_exc,
self.adm_qos_client.delete_policy, policy1['id'])
rule1 = self.create_qos_bandwidth_limit_rule(
policy_id=policy1['id'], max_kbps=200, max_burst_kbps=1337)
policy2 = self.create_qos_policy(name='test-policy2',
description='test policy2',
shared=False)
self.addCleanup(test_utils.call_and_ignore_notfound_exc,
self.adm_qos_client.delete_policy, policy2['id'])
rule2 = self.create_qos_bandwidth_limit_rule(
policy_id=policy2['id'], max_kbps=5000, max_burst_kbps=2523)
# Test 'list rules'
rules = self.adm_qos_client.list_bandwidth_limit_rules(policy1['id'])
rules_ids = [r['id'] for r in rules]
self.assertIn(rule1['id'], rules_ids)
self.assertNotIn(rule2['id'], rules_ids)
class QosDscpMarkingRuleTest(BaseQosTest):
"""QoS Dscp Marking Rule CRUD operation."""
VALID_DSCP_MARK1 = 56
VALID_DSCP_MARK2 = 48
@decorators.idempotent_id('8a59b40b-3e9c-4787-92f8-93a5cdf5e378')
def test_rule_create(self):
"""qos-dscp-marking-rule-create POLICY_ID."""
qos_client = self.adm_qos_client
policy = self.create_qos_policy(name='test-policy',
description='test policy',
shared=False)
self.addCleanup(test_utils.call_and_ignore_notfound_exc,
self.adm_qos_client.delete_policy, policy['id'])
rule = self.create_qos_dscp_marking_rule(
policy['id'], self.VALID_DSCP_MARK1)
# Test 'show rule'
retrieved_rule = qos_client.show_dscp_marking_rule(
rule['id'], policy['id'])
self.assertEqual(rule['id'], retrieved_rule['id'])
self.assertEqual(self.VALID_DSCP_MARK1, retrieved_rule['dscp_mark'])
# Test 'list rules'
rules = qos_client.list_dscp_marking_rules(policy['id'])
rules_ids = [r['id'] for r in rules]
self.assertIn(rule['id'], rules_ids)
# Test 'show policy'
retrieved_policy = qos_client.show_policy(policy['id'])
policy_rules = retrieved_policy['rules']
self.assertEqual(1, len(policy_rules))
self.assertEqual(rule['id'], policy_rules[0]['id'])
self.assertEqual(base_qos.RULE_TYPE_DSCP_MARK,
policy_rules[0]['type'])
@decorators.attr(type='negative')
@decorators.idempotent_id('8b59b10b-ab01-4787-92f8-93a5cdf5e378')
def test_rule_create_fail_for_the_same_type(self):
"""One dscp marking rule per policy."""
policy = self.create_qos_policy(name='test-policy',
description='test policy',
shared=False)
self.addCleanup(test_utils.call_and_ignore_notfound_exc,
self.adm_qos_client.delete_policy, policy['id'])
self.create_qos_dscp_marking_rule(
policy['id'], self.VALID_DSCP_MARK1)
self.assertRaises(exceptions.Conflict,
self.create_qos_dscp_marking_rule,
policy_id=policy['id'],
dscp_mark=self.VALID_DSCP_MARK2)
@decorators.idempotent_id('249a6988-2568-47d2-931e-2dbc858943b3')
def test_rule_update(self):
"""qos-dscp-marking-rule-create POLICY_ID."""
qos_client = self.adm_qos_client
policy = self.create_qos_policy(name='test-policy',
description='test policy',
shared=False)
self.addCleanup(test_utils.call_and_ignore_notfound_exc,
self.adm_qos_client.delete_policy, policy['id'])
rule = self.create_qos_dscp_marking_rule(
policy['id'], self.VALID_DSCP_MARK1)
qos_client.update_dscp_marking_rule(
rule['id'], policy['id'], dscp_mark=self.VALID_DSCP_MARK2)
retrieved_rule = qos_client.show_dscp_marking_rule(
rule['id'], policy['id'])
self.assertEqual(self.VALID_DSCP_MARK2, retrieved_rule['dscp_mark'])
@decorators.idempotent_id('67ed6efd-7b33-4a68-927d-275b4f8ba958')
def test_rule_delete(self):
"""qos-dscp-marking-rule-delete POLICY_ID."""
qos_client = self.adm_qos_client
policy = self.create_qos_policy(name='test-policy',
description='test policy',
shared=False)
self.addCleanup(test_utils.call_and_ignore_notfound_exc,
self.adm_qos_client.delete_policy, policy['id'])
rule = self.create_qos_dscp_marking_rule(
policy['id'], self.VALID_DSCP_MARK1)
retrieved_rule = qos_client.show_dscp_marking_rule(
rule['id'], policy['id'])
self.assertEqual(rule['id'], retrieved_rule['id'])
qos_client.delete_dscp_marking_rule(rule['id'], policy['id'])
self.assertRaises(exceptions.NotFound,
qos_client.show_dscp_marking_rule,
rule['id'], policy['id'])
@decorators.attr(type='negative')
@decorators.idempotent_id('f215222c-5808-46cb-a961-983bbab6b852')
def test_rule_create_rule_nonexistent_policy(self):
"""can not create dscp marking rule with nonexist policy."""
self.assertRaises(
exceptions.NotFound,
self.create_qos_dscp_marking_rule,
'policy', self.VALID_DSCP_MARK1)
@decorators.attr(type='negative')
@decorators.idempotent_id('a4a2e3ad-786f-4927-a85a-e545a93bd274')
def test_rule_create_forbidden_for_regular_tenants(self):
"""project/tenant can not create dscp marking rule."""
self.assertRaises(
exceptions.Forbidden,
self.create_qos_dscp_marking_rule,
'policy', self.VALID_DSCP_MARK1,
qos_client=self.pri_qos_client)
@decorators.attr(type='negative')
@decorators.idempotent_id('32646b08-4f05-4493-a48a-bde768a18533')
def test_invalid_rule_create(self):
"""Can not create rule with invalid dscp_mark value."""
policy = self.create_qos_policy(name='test-policy',
description='test policy',
shared=False)
self.addCleanup(test_utils.call_and_ignore_notfound_exc,
self.adm_qos_client.delete_policy, policy['id'])
self.assertRaises(
exceptions.BadRequest,
self.create_qos_dscp_marking_rule,
policy['id'], 58)
@decorators.idempotent_id('cf0bd0c2-54d9-4e29-85f1-cfb36ac3ebe2')
def test_get_rules_by_policy(self):
"""qos-dscp-marking-rule-list POLICY_ID."""
policy1 = self.create_qos_policy(name='test-policy1',
description='test policy1',
shared=False)
self.addCleanup(test_utils.call_and_ignore_notfound_exc,
self.adm_qos_client.delete_policy, policy1['id'])
rule1 = self.create_qos_dscp_marking_rule(
policy1['id'], self.VALID_DSCP_MARK1)
policy2 = self.create_qos_policy(name='test-policy2',
description='test policy2',
shared=False)
self.addCleanup(test_utils.call_and_ignore_notfound_exc,
self.adm_qos_client.delete_policy, policy2['id'])
rule2 = self.create_qos_dscp_marking_rule(
policy2['id'], self.VALID_DSCP_MARK2)
# Test 'list rules'
rules = self.adm_qos_client.list_dscp_marking_rules(policy1['id'])
rules_ids = [r['id'] for r in rules]
self.assertIn(rule1['id'], rules_ids)
self.assertNotIn(rule2['id'], rules_ids)
-23
View File
@@ -1,23 +0,0 @@
# -*- coding: utf-8 -*-
# Copyright 2010-2011 OpenStack Foundation
# Copyright (c) 2013 Hewlett-Packard Development Company, L.P.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from tempest.lib import base
class TestCase(base.BaseTestCase):
"""Test case base class for all unit tests."""
-6
View File
@@ -1,6 +0,0 @@
Placeholder for dvs plugin specific automated tests
directory:
dvs/
api/
scenario/
Whitespace-only changes.
Whitespace-only changes.
@@ -1,157 +0,0 @@
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import netaddr
from tempest.api.network import base
from tempest import config
from tempest import exceptions
from tempest.lib.common.utils import data_utils
import tempest.test
CONF = config.CONF
class BaseDvsAdminNetworkTest(base.BaseAdminNetworkTest):
@classmethod
def resource_cleanup(cls):
for port in cls.ports:
cls.admin_ports_client.delete_port(port['id'])
for subnet in cls.subnets:
cls.admin_subnets_client.delete_subnet(subnet['id'])
for network in cls.networks:
cls.admin_networks_client.delete_network(network['id'])
# clean up ports, subnets and networks
cls.ports = []
cls.subnets = []
cls.networks = []
@classmethod
def create_network(cls, **kwargs):
"""Wrapper utility that returns a test admin provider network."""
network_name = (kwargs.get('net_name')
or data_utils.rand_name('test-adm-net-'))
net_type = kwargs.get('net_type', "flat")
if tempest.test.is_extension_enabled('provider', 'network'):
body = {'name': network_name}
body.update({'provider:network_type': net_type,
'provider:physical_network': 'dvs'})
if net_type == 'vlan':
_vlanid = kwargs.get('seg_id')
body.update({'provider:segmentation_id': _vlanid})
body = cls.admin_networks_client.create_network(**body)
network = body['network']
cls.networks.append(network)
return network
@classmethod
def create_subnet(cls, network):
"""Wrapper utility that returns a test subnet."""
# The cidr and mask_bits depend on the ip version.
if cls._ip_version == 4:
cidr = netaddr.IPNetwork(CONF.network.project_network_cidr
or "192.168.101.0/24")
mask_bits = CONF.network.project_network_mask_bits or 24
elif cls._ip_version == 6:
cidr = netaddr.IPNetwork(CONF.network.project_network_v6_cidr)
mask_bits = CONF.network.project_network_v6_mask_bits
# Find a cidr that is not in use yet and create a subnet with it
for subnet_cidr in cidr.subnet(mask_bits):
try:
body = cls.admin_subnets_client.create_subnet(
network_id=network['id'],
cidr=str(subnet_cidr),
ip_version=cls._ip_version)
break
except exceptions.BadRequest as e:
is_overlapping_cidr = 'overlaps with another subnet' in str(e)
if not is_overlapping_cidr:
raise
else:
message = 'Available CIDR for subnet creation could not be found'
raise exceptions.BuildErrorException(message)
subnet = body['subnet']
cls.subnets.append(subnet)
return subnet
@classmethod
def create_port(cls, network_id, **kwargs):
"""Wrapper utility that returns a test port."""
body = cls.admin_ports_client.create_port(network_id=network_id,
**kwargs)
port = body['port']
cls.ports.append(port)
return port
@classmethod
def update_network(cls, network_id, client=None, **kwargs):
net_client = client if client else cls.admin_networks_client
return net_client.update_network(network_id, **kwargs)
@classmethod
def delete_network(cls, network_id, client=None):
net_client = client if client else cls.admin_networks_client
return net_client.delete_network(network_id)
@classmethod
def show_network(cls, network_id, client=None, **kwargs):
net_client = client if client else cls.admin_networks_client
return net_client.show_network(network_id, **kwargs)
@classmethod
def list_networks(cls, client=None, **kwargs):
net_client = client if client else cls.admin_networks_client
return net_client.list_networks(**kwargs)
@classmethod
def update_subnet(cls, subnet_id, client=None, **kwargs):
net_client = client if client else cls.admin_subnets_client
return net_client.update_subnet(subnet_id, **kwargs)
@classmethod
def delete_subnet(cls, subnet_id, client=None):
net_client = client if client else cls.admin_subnets_client
return net_client.delete_subnet(subnet_id)
@classmethod
def show_subnet(cls, subnet_id, client=None, **kwargs):
net_client = client if client else cls.admin_subnets_client
return net_client.show_subnet(subnet_id, **kwargs)
@classmethod
def list_subnets(cls, client=None, **kwargs):
net_client = client if client else cls.admin_subnets_client
return net_client.list_subnets(**kwargs)
@classmethod
def delete_port(cls, port_id, client=None):
net_client = client if client else cls.admin_ports_client
return net_client.delete_port(port_id)
@classmethod
def show_port(cls, port_id, client=None, **kwargs):
net_client = client if client else cls.admin_ports_client
return net_client.show_port(port_id, **kwargs)
@classmethod
def list_ports(cls, client=None, **kwargs):
net_client = client if client else cls.admin_ports_client
return net_client.list_ports(**kwargs)
@classmethod
def update_port(cls, port_id, client=None, **kwargs):
net_client = client if client else cls.admin_ports_client
return net_client.update_port(port_id, **kwargs)
@@ -1,122 +0,0 @@
# Copyright 2014 VMware.inc
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import base_dvs as base
from tempest.lib.common.utils import data_utils
from tempest.lib import decorators
class AdminNetworksTestJSON(base.BaseDvsAdminNetworkTest):
_interface = 'json'
"""
Test admin actions for networks, subnets.
create/update/delete an admin network
create/update/delete an admin subnets
"""
@classmethod
def resource_setup(cls):
super(AdminNetworksTestJSON, cls).resource_setup()
name = data_utils.rand_name('admin-network-')
cls.network = cls.create_network(net_name=name)
cls.name = cls.network['name']
cls.subnet = cls.create_subnet(cls.network)
cls.cidr = cls.subnet['cidr']
@decorators.attr(type='smoke')
@decorators.idempotent_id('1dcead1d-d773-4da1-9534-0b984ca684b3')
def test_create_update_delete_flat_network_subnet(self):
# Create an admin network
name = data_utils.rand_name('admin-network-')
network = self.create_network(net_name=name, net_type='flat')
net_id = network['id']
# Verify an exception thrown when updating network
new_name = "New_network"
# create a subnet and verify it is an admin tenant subnet
subnet = self.create_subnet(network)
subnet_id = subnet['id']
self.assertEqual(network['tenant_id'], subnet['tenant_id'])
# Verify subnet update
new_name = "New_subnet"
body = self.update_subnet(subnet_id, name=new_name)
updated_subnet = body['subnet']
self.assertEqual(updated_subnet['name'], new_name)
# Delete subnet and network
body = self.delete_subnet(subnet_id)
# Remove subnet from cleanup list
self.subnets.pop()
body = self.delete_network(net_id)
self.networks.pop()
@decorators.attr(type='smoke')
@decorators.idempotent_id('15d3d53c-3328-401f-b8f5-3a29aee2ea3a')
def test_create_update_delete_vlan_network_subnet(self):
# Create an admin network
name = data_utils.rand_name('admin-network-')
network = self.create_network(net_name=name,
net_type='vlan',
seg_id=1000)
net_id = network['id']
# Verify an exception thrown when updating network
new_name = "New_network"
# create a subnet and verify it is an admin tenant subnet
subnet = self.create_subnet(network)
subnet_id = subnet['id']
self.assertEqual(network['tenant_id'], subnet['tenant_id'])
# Verify subnet update
new_name = "New_subnet"
body = self.update_subnet(subnet_id, name=new_name)
updated_subnet = body['subnet']
self.assertEqual(updated_subnet['name'], new_name)
# Delete subnet and network
body = self.delete_subnet(subnet_id)
# Remove subnet from cleanup list
self.subnets.pop()
body = self.delete_network(net_id)
self.networks.pop()
@decorators.attr(type='smoke')
@decorators.idempotent_id('838aee5f-92f2-47b9-86c6-629a04aa6269')
def test_show_network(self):
# Verify the details of a network
body = self.show_network(self.network['id'])
network = body['network']
for key in ['id', 'name', 'provider:network_type',
'provider:physical_network']:
self.assertEqual(network[key], self.network[key])
@decorators.attr(type='smoke')
@decorators.idempotent_id('b86d50ef-39a7-4136-8c89-e5e534fe92aa')
def test_list_networks(self):
# Verify the network exists in the list of all networks
body = self.list_networks()
networks = [network['id'] for network in body['networks']
if network['id'] == self.network['id']]
self.assertNotEmpty(networks, "Created network not found in the list")
@decorators.attr(type='smoke')
@decorators.idempotent_id('ee3f8b79-da3f-4394-9bea-012488202257')
def test_show_subnet(self):
# Verify the details of a subnet
body = self.show_subnet(self.subnet['id'])
subnet = body['subnet']
self.assertNotEmpty(subnet, "Subnet returned has no fields")
for key in ['id', 'cidr']:
self.assertIn(key, subnet)
self.assertEqual(subnet[key], self.subnet[key])
@@ -1,98 +0,0 @@
# Copyright 2014 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import base_dvs as base
from tempest.lib.common.utils import data_utils
from tempest.lib import decorators
class AdminPortsTestJSON(base.BaseDvsAdminNetworkTest):
_interface = 'json'
"""
Test the following operations for ports:
port create
port delete
port list
port show
port update
"""
@classmethod
def resource_setup(cls):
super(AdminPortsTestJSON, cls).resource_setup()
name = data_utils.rand_name('admin-ports-')
cls.network = cls.create_network(net_name=name)
cls.port = cls.create_port(cls.network['id'])
@decorators.idempotent_id('c3f751d4-e358-44b9-bfd2-3d563c4a2d04')
def test_create_update_delete_port(self):
# Verify port creation
network_id = self.network['id']
port = self.create_port(network_id)
self.assertTrue(port['admin_state_up'])
# Verify port update
new_name = "New_Port"
body = self.update_port(
port['id'],
name=new_name,
admin_state_up=False)
updated_port = body['port']
self.assertEqual(updated_port['name'], new_name)
self.assertFalse(updated_port['admin_state_up'])
@decorators.attr(type='smoke')
@decorators.idempotent_id('d3dcd23b-7d5a-4720-8d88-473fb154d609')
def test_show_port(self):
# Verify the details of port
body = self.show_port(self.port['id'])
port = body['port']
self.assertIn('id', port)
self.assertEqual(port['id'], self.port['id'])
self.assertEqual(self.port['admin_state_up'], port['admin_state_up'])
self.assertEqual(self.port['device_id'], port['device_id'])
self.assertEqual(self.port['device_owner'], port['device_owner'])
self.assertEqual(self.port['mac_address'], port['mac_address'])
self.assertEqual(self.port['name'], port['name'])
self.assertEqual(self.port['security_groups'],
port['security_groups'])
self.assertEqual(self.port['network_id'], port['network_id'])
self.assertEqual(self.port['security_groups'],
port['security_groups'])
self.assertEqual(port['fixed_ips'], [])
@decorators.attr(type='smoke')
@decorators.idempotent_id('c5f74042-c512-4569-b9b9-bc2bf46e77e1')
def test_list_ports(self):
# Verify the port exists in the list of all ports
body = self.list_ports()
ports = [port['id'] for port in body['ports']
if port['id'] == self.port['id']]
self.assertNotEmpty(ports, "Created port not found in the list")
@decorators.idempotent_id('2775f96c-a09b-49e1-a5a4-adb83a3e91c7')
@decorators.attr(type='smoke')
def test_list_ports_fields(self):
# Verify specific fields of ports
fields = ['binding:vif_type', 'id', 'mac_address']
body = self.list_ports(fields=fields)
ports = body['ports']
self.assertNotEmpty(ports, "Port list returned is empty")
# Asserting the fields returned are correct
# Verify binding:vif_type is dvs
for port in ports:
self.assertEqual(sorted(fields), sorted(port.keys()))
self.assertEqual(port.get(fields[0]), 'dvs')
Whitespace-only changes.
@@ -1,193 +0,0 @@
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import netaddr
from oslo_log import log as logging
from tempest import config
from tempest import exceptions
from tempest.lib.common.utils import data_utils
from tempest.lib import decorators
from tempest import test
from vmware_nsx_tempest.tests.scenario import manager
CONF = config.CONF
LOG = logging.getLogger(__name__)
class TestDvsNetworkBasicOps(manager.NetworkScenarioTest):
"""
This smoke test suite assumes that Nova has been configured to
boot VM's with Neutron-managed VDS networking, and attempts to
verify network connectivity as follows:
"""
def setUp(self):
super(TestDvsNetworkBasicOps, self).setUp()
self._ip_version = 4
self.keypairs = {}
self.servers = []
self.admin_net_client = self.admin_manager.networks_client
self.admin_subnet_client = self.admin_manager.subnets_client
def _setup_network(self):
self.network = self._create_network()
self.subnet = self._create_subnet(self.network)
def _list_ports(self, *args, **kwargs):
"""List ports using admin creds """
ports_list = self.admin_manager.ports_client.list_ports(
*args, **kwargs)
return ports_list['ports']
def _create_network(self, network_name=None):
"""Wrapper utility that returns a test admin provider network."""
network_name = network_name or data_utils.rand_name('test-adm-net-')
if test.is_extension_enabled('provider', 'network'):
body = {'name': network_name}
body.update({'provider:network_type': 'flat',
'provider:physical_network': 'dvs',
'shared': True})
body = self.admin_net_client.create_network(**body)
self.addCleanup(self.admin_net_client.delete_network,
body['network']['id'])
return body['network']
def _create_subnet(self, network):
# The cidr and mask_bits depend on the ip version.
if self._ip_version == 4:
cidr = netaddr.IPNetwork(CONF.network.project_network_cidr
or "192.168.101.0/24")
mask_bits = CONF.network.project_network_mask_bits or 24
elif self._ip_version == 6:
cidr = netaddr.IPNetwork(CONF.network.project_network_v6_cidr)
mask_bits = CONF.network.project_network_v6_mask_bits
# Find a cidr that is not in use yet and create a subnet with it
for subnet_cidr in cidr.subnet(mask_bits):
try:
body = self.admin_subnet_client.create_subnet(
network_id=network['id'],
cidr=str(subnet_cidr),
ip_version=self._ip_version)
break
except exceptions.BadRequest as e:
is_overlapping_cidr = 'overlaps with another subnet' in str(e)
if not is_overlapping_cidr:
raise
else:
message = ('Available CIDR for subnet creation '
'could not be found')
raise exceptions.BuildErrorException(message)
return body['subnet']
def _check_networks(self):
"""
Checks that we see the newly created network/subnet via
checking the result of list_[networks,subnets]
"""
seen_nets = self.admin_manager.networks_client.list_networks()
seen_names = [n['name'] for n in seen_nets['networks']]
seen_ids = [n['id'] for n in seen_nets['networks']]
self.assertIn(self.network['name'], seen_names)
self.assertIn(self.network['id'], seen_ids)
seen_subnets = self.admin_manager.subnets_client.list_subnets()
seen_net_ids = [n['network_id'] for n in seen_subnets['subnets']]
seen_subnet_ids = [n['id'] for n in seen_subnets['subnets']]
self.assertIn(self.network['id'], seen_net_ids)
self.assertIn(self.subnet['id'], seen_subnet_ids)
def _create_server(self):
keypair = self.create_keypair()
self.keypairs[keypair['name']] = keypair
networks = [{'uuid': self.network['id']}]
name = data_utils.rand_name('server-smoke')
server = self.create_server(name=name,
networks=networks,
key_name=keypair['name'],
wait_until='ACTIVE')
self.servers.append(server)
return server
def _get_server_key(self, server):
return self.keypairs[server['key_name']]['private_key']
def _check_server_connectivity(self, address_list,
should_connect=True):
private_key = self._get_server_key(self.servers[0])
ip_address = address_list[0]
ssh_source = self.get_remote_client(ip_address,
private_key=private_key)
for remote_ip in address_list:
if should_connect:
msg = "Timed out waiting for "
"%s to become reachable" % remote_ip
else:
msg = "ip address %s is reachable" % remote_ip
try:
self.assertTrue(self._check_remote_connectivity
(ssh_source, remote_ip, should_connect),
msg)
except Exception:
LOG.exception("Unable to access {dest} via ping to "
"fix-ip {src}".format(dest=remote_ip,
src=ip_address))
raise
def _check_network_internal_connectivity(self, network,
should_connect=True):
"""
via ssh check VM internal connectivity:
- ping internal gateway and DHCP port, implying in-tenant connectivity
pinging both, because L3 and DHCP agents might be on different nodes
"""
server = self.servers[0]
# get internal ports' ips:
# get all network ports in the new network
internal_ips = ([p['fixed_ips'][0]['ip_address'] for p in
self._list_ports(tenant_id=server['tenant_id'],
network_id=network['id'])
if p['device_owner'].startswith('compute')])
self._check_server_connectivity(internal_ips,
should_connect)
@decorators.attr(type='smoke')
@test.services('compute', 'network')
@decorators.idempotent_id('b977dce6-6527-4676-9b66-862b22058f0f')
def test_network_basic_ops(self):
"""
For a freshly-booted VM with an IP address ("port") on a given
network:
- the Tempest host can ping the IP address. This implies, but
does not guarantee (see the ssh check that follows), that the
VM has been assigned the correct IP address and has
connectivity to the Tempest host.
- the Tempest host can perform key-based authentication to an
ssh server hosted at the IP address. This check guarantees
that the IP address is associated with the target VM.
- the Tempest host can ssh into the VM via the IP address and
successfully execute the following:
"""
self._setup_network()
self._check_networks()
self._create_server()
self._check_network_internal_connectivity(self.network)
-6
View File
@@ -1,6 +0,0 @@
Placeholder for NSX-v plugin specific automated tests
directory:
nsxv/
api/
scenario/
scale/
Whitespace-only changes.
@@ -1 +0,0 @@
Placeholder for nsxv neutron plugin specific API tests.
Whitespace-only changes.
@@ -1,215 +0,0 @@
# Copyright 2015 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import netaddr
from tempest.api.network import base
from tempest import config
from tempest.lib.common.utils import data_utils
from tempest.lib.common.utils import test_utils
from tempest.lib import exceptions
from tempest import test
CONF = config.CONF
class BaseAdminNetworkTest(base.BaseAdminNetworkTest):
# NOTE(akang): This class inherits from BaseAdminNetworkTest.
# By default client is cls.client, but for provider network,
# the client is admin_client. The test class should pass
# client=self.admin_client, if it wants to create provider
# network/subnet.
@classmethod
def skip_checks(cls):
super(BaseAdminNetworkTest, cls).skip_checks()
if not test.is_extension_enabled('provider', 'network'):
msg = "Network Provider Extension not enabled."
raise cls.skipException(msg)
@classmethod
def resource_setup(cls):
super(BaseAdminNetworkTest, cls).resource_setup()
cls.admin_netwk_info = []
cls.admin_port_info = []
@classmethod
def resource_cleanup(cls):
if CONF.service_available.neutron:
for netwk_info in cls.admin_netwk_info:
net_client, network = netwk_info
try:
test_utils.call_and_ignore_notfound_exc(
net_client.delete_network, network['id'])
except Exception:
pass
for port_info in cls.admin_port_info:
port_client, port = port_info
try:
test_utils.call_and_ignore_notfound_exc(
port_client.delete_port, port['id'])
except Exception:
pass
super(BaseAdminNetworkTest, cls).resource_cleanup()
@classmethod
def create_network(cls, network_name=None, client=None,
**kwargs):
net_client = client if client else cls.admin_networks_client
network_name = network_name or data_utils.rand_name('ADM-network-')
post_body = {'name': network_name}
post_body.update(kwargs)
body = net_client.create_network(**post_body)
network = body['network']
cls.admin_netwk_info.append([net_client, network])
return body
@classmethod
def update_network(cls, network_id, client=None, **kwargs):
net_client = client if client else cls.admin_networks_client
return net_client.update_network(network_id, **kwargs)
@classmethod
def delete_network(cls, network_id, client=None):
net_client = client if client else cls.admin_networks_client
return net_client.delete_network(network_id)
@classmethod
def show_network(cls, network_id, client=None, **kwargs):
net_client = client if client else cls.admin_networks_client
return net_client.show_network(network_id, **kwargs)
@classmethod
def list_networks(cls, client=None, **kwargs):
net_client = client if client else cls.admin_networks_client
return net_client.list_networks(**kwargs)
@classmethod
def create_subnet(cls, network, client=None,
gateway='', cidr=None, mask_bits=None,
ip_version=None, cidr_offset=0, **kwargs):
ip_version = (ip_version if ip_version is not None
else cls._ip_version)
net_client = client if client else cls.admin_subnets_client
post_body = get_subnet_create_options(
network['id'], ip_version,
gateway=gateway, cidr=cidr, cidr_offset=cidr_offset,
mask_bits=mask_bits, **kwargs)
return net_client.create_subnet(**post_body)
@classmethod
def update_subnet(cls, subnet_id, client=None, **kwargs):
net_client = client if client else cls.admin_subnets_client
return net_client.update_subnet(subnet_id, **kwargs)
@classmethod
def delete_subnet(cls, subnet_id, client=None):
net_client = client if client else cls.admin_subnets_client
return net_client.delete_subnet(subnet_id)
@classmethod
def show_subnet(cls, subnet_id, client=None, **kwargs):
net_client = client if client else cls.admin_subnets_client
return net_client.show_subnet(subnet_id, **kwargs)
@classmethod
def list_subnets(cls, client=None, **kwargs):
net_client = client if client else cls.admin_subnets_client
return net_client.list_subnets(**kwargs)
@classmethod
def create_port(cls, network_id, port_name=None, client=None, **kwargs):
port_client = client if client else cls.admin_ports_client
port_name = port_name or data_utils.rand_name('ADM-port-')
post_body = {'name': port_name,
'network_id': network_id}
post_body.update(kwargs)
body = port_client.create_port(**post_body)
port = body['port']
cls.admin_port_info.append([port_client, port])
return body
@classmethod
def update_port(cls, port_id, client=None, **kwargs):
port_client = client if client else cls.admin_ports_client
return port_client.update_port(port_id, **kwargs)
@classmethod
def delete_port(cls, port_id, client=None):
port_client = client if client else cls.admin_ports_client
return port_client.delete_port(port_id)
@classmethod
def list_ports(cls, client=None, **kwargs):
port_client = client if client else cls.admin_ports_client
return port_client.list_ports(**kwargs)
# add other create methods, i.e. security-group, port, floatingip
# if needed.
def get_subnet_create_options(network_id, ip_version=4,
gateway='', cidr=None, mask_bits=None,
num_subnet=1, gateway_offset=1, cidr_offset=0,
**kwargs):
"""When cidr_offset>0 it request only one subnet-options:
subnet = get_subnet_create_options('abcdefg', 4, num_subnet=4)[3]
subnet = get_subnet_create_options('abcdefg', 4, cidr_offset=3)
"""
gateway_not_set = (gateway == '')
if ip_version == 4:
cidr = cidr or netaddr.IPNetwork(CONF.network.project_network_cidr)
mask_bits = mask_bits or CONF.network.project_network_mask_bits
elif ip_version == 6:
cidr = (
cidr or netaddr.IPNetwork(CONF.network.project_network_v6_cidr))
mask_bits = mask_bits or CONF.network.project_network_v6_mask_bits
# Find a cidr that is not in use yet and create a subnet with it
subnet_list = []
if cidr_offset > 0:
num_subnet = cidr_offset + 1
for subnet_cidr in cidr.subnet(mask_bits):
if gateway_not_set:
gateway_ip = gateway or (
str(netaddr.IPAddress(subnet_cidr) + gateway_offset))
else:
gateway_ip = gateway
try:
subnet_body = dict(
network_id=network_id,
cidr=str(subnet_cidr),
ip_version=ip_version,
gateway_ip=gateway_ip,
**kwargs)
if num_subnet <= 1:
return subnet_body
subnet_list.append(subnet_body)
if len(subnet_list) >= num_subnet:
if cidr_offset > 0:
# user request the 'cidr_offset'th of cidr
return subnet_list[cidr_offset]
# user request list of cidr
return subnet_list
except exceptions.BadRequest as e:
is_overlapping_cidr = 'overlaps with another subnet' in str(e)
if not is_overlapping_cidr:
raise
else:
message = 'Available CIDR for subnet creation could not be found'
raise exceptions.BuildErrorException(message)
return {}
Whitespace-only changes.
@@ -1,516 +0,0 @@
# Copyright 2015 Rackspace
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
#
# 2016-03 (akang)
# ported from neutron-lbaas to comply to tempest framework
# NSX-v require vip-subnet attached to exclusive router
from oslo_log import log as logging
from tempest.api.network import base
from tempest import config
from tempest import test
from tempest.lib.common.utils import data_utils
from tempest.lib.common.utils import test_utils
from tempest.lib import exceptions
from vmware_nsx_tempest.services.lbaas import health_monitors_client
from vmware_nsx_tempest.services.lbaas import l7policies_client
from vmware_nsx_tempest.services.lbaas import l7rules_client
from vmware_nsx_tempest.services.lbaas import listeners_client
from vmware_nsx_tempest.services.lbaas import load_balancers_client
from vmware_nsx_tempest.services.lbaas import members_client
from vmware_nsx_tempest.services.lbaas import pools_client
CONF = config.CONF
LOG = logging.getLogger(__name__)
NO_ROUTER_TYPE = CONF.nsxv.no_router_type
L7_POLICY_ACTIONS = ('REJECT', 'REDIRECT_TO_URL', 'REDIRECT_TO_POOL')
L7_RULE_TYPES = ('HOSTNAME', 'PATH', 'FILE_TYPE', 'HEADER', 'COOKIE')
L7_RULE_COMPARISON_TYPES = ('REGEXP', 'STARTS_WITH', 'ENDS_WITH',
'CONTAINS', 'EQUAL_TO')
class BaseTestCase(base.BaseNetworkTest):
# This class picks non-admin credentials and run the tempest tests
_lbs_to_delete = []
_setup_lbaas_non_admin_resource = True
@classmethod
def skip_checks(cls):
super(BaseTestCase, cls).skip_checks()
if not test.is_extension_enabled('lbaasv2', 'network'):
msg = "lbaasv2 extension not enabled."
raise cls.skipException(msg)
@classmethod
def resource_setup(cls):
super(BaseTestCase, cls).resource_setup()
if cls._setup_lbaas_non_admin_resource:
mgr = cls.get_client_manager()
cls.create_lbaas_clients(mgr)
cls.setup_lbaas_core_network()
@classmethod
def create_lbaas_clients(cls, mgr):
cls.load_balancers_client = load_balancers_client.get_client(mgr)
cls.listeners_client = listeners_client.get_client(mgr)
cls.pools_client = pools_client.get_client(mgr)
cls.members_client = members_client.get_client(mgr)
cls.health_monitors_client = health_monitors_client.get_client(mgr)
# l7-switching clients
cls.l7policies_client = l7policies_client.get_client(cls.manager)
cls.l7rules_client = l7rules_client.get_client(cls.manager)
@classmethod
def setup_lbaas_core_network(cls):
rand_number = data_utils.rand_name()
network_name = 'lbaas-network-' + rand_number
router_name = 'lbaas-router-' + rand_number
cls.network = cls.create_network(network_name)
cls.subnet = cls.create_subnet(cls.network)
cls.tenant_id = cls.subnet.get('tenant_id')
cls.subnet_id = cls.subnet.get('id')
# NSX-v: load-balancer's subnet need to attach to exclusive-router
if not CONF.nsxv.manager_uri:
router_cfg = dict(router_name=router_name)
else:
router_cfg = dict(router_name=router_name, router_type='exclusive')
if NO_ROUTER_TYPE:
# router_type is NSX-v extension.
router_cfg.pop('router_type', None)
cls.router = cls.create_router(**router_cfg)
cls.create_router_interface(cls.router['id'], cls.subnet['id'])
@classmethod
def resource_cleanup(cls):
for lb_id in cls._lbs_to_delete:
try:
statuses = cls._show_load_balancer_status_tree(lb_id)
lb = statuses.get('loadbalancer')
except exceptions.NotFound:
continue
for listener in lb.get('listeners', []):
for policy in listener.get('l7policies'):
test_utils.call_and_ignore_notfound_exc(
cls.l7policies_client.delete_l7policy,
policy.get('id'))
cls._wait_for_load_balancer_status(lb_id)
for pool in listener.get('pools'):
cls.delete_lb_pool_resources(lb_id, pool)
# delete listener
test_utils.call_and_ignore_notfound_exc(
cls.listeners_client.delete_listener,
listener.get('id'))
cls._wait_for_load_balancer_status(lb_id)
# delete pools not attached to listener, but loadbalancer
for pool in lb.get('pools', []):
cls.delete_lb_pool_resources(lb_id, pool)
# delete load-balancer
test_utils.call_and_ignore_notfound_exc(
cls._delete_load_balancer, lb_id)
# NSX-v: delete exclusive router
cls.delete_router(cls.router)
super(BaseTestCase, cls).resource_cleanup()
@classmethod
def delete_lb_pool_resources(cls, lb_id, pool):
# delete pool's health-monitor
hm = pool.get('healthmonitor')
if hm:
test_utils.call_and_ignore_notfound_exc(
cls.health_monitors_client.delete_health_monitor,
pool.get('healthmonitor').get('id'))
cls._wait_for_load_balancer_status(lb_id)
# delete pool's members
members = pool.get('members', [])
for member in members:
test_utils.call_and_ignore_notfound_exc(
cls.members_client.delete_member,
pool.get('id'), member.get('id'))
cls._wait_for_load_balancer_status(lb_id)
# delete pool
test_utils.call_and_ignore_notfound_exc(
cls.pools_client.delete_pool, pool.get('id'))
cls._wait_for_load_balancer_status(lb_id)
@classmethod
def setUpClass(cls):
cls.LOG = logging.getLogger(cls._get_full_case_name())
super(BaseTestCase, cls).setUpClass()
def setUp(cls):
cls.LOG.info(('Starting: {0}').format(cls._testMethodName))
super(BaseTestCase, cls).setUp()
def tearDown(cls):
super(BaseTestCase, cls).tearDown()
cls.LOG.info(('Finished: {0}').format(cls._testMethodName))
@classmethod
def _create_load_balancer(cls, wait=True, **lb_kwargs):
lb = cls.load_balancers_client.create_load_balancer(**lb_kwargs)
lb = lb.get('loadbalancer', lb)
cls._lbs_to_delete.append(lb.get('id'))
if wait:
cls._wait_for_load_balancer_status(lb.get('id'))
port = cls.ports_client.show_port(lb['vip_port_id'])
cls.ports.append(port['port'])
return lb
@classmethod
def _create_active_load_balancer(cls, **kwargs):
lb = cls._create_load_balancer(**kwargs)
lb = lb.get('loadbalancer', lb)
lb = cls._wait_for_load_balancer_status(lb.get('id'))
return lb
@classmethod
def _delete_load_balancer(cls, load_balancer_id, wait=True):
cls.load_balancers_client.delete_load_balancer(load_balancer_id)
if wait: