Move policy code to dedicated folder

Change-Id: I4407819b240b8352002c53d20bfae284d12b159f
This commit is contained in:
Anna Khmelnitsky 2019-01-02 18:28:21 -08:00
parent d55df96d27
commit 61548adc6c
13 changed files with 789 additions and 4653 deletions

View File

@ -1,35 +0,0 @@
# Copyright 2018 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_nsxlib.tests.unit.v3 import nsxlib_testcase
from vmware_nsxlib.v3 import client
from vmware_nsxlib.v3 import policy_defs as policy
BASE_POLICY_URI = "https://1.2.3.4/policy/api/v1/"
class TestPolicyApi(nsxlib_testcase.NsxClientTestCase):
def setUp(self):
self.client = self.new_mocked_client(client.NSX3Client,
url_prefix='policy/api/v1/')
self.policy_api = policy.NsxPolicyApi(self.client)
super(TestPolicyApi, self).setUp()
def assert_json_call(self, method, client, url, data=None):
url = BASE_POLICY_URI + url
return super(TestPolicyApi, self).assert_json_call(
method, client, url, data=data)

View File

@ -1,329 +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_nsxlib.tests.unit.v3 import policy_testcase
from vmware_nsxlib.v3 import nsx_constants
from vmware_nsxlib.v3 import policy_constants
from vmware_nsxlib.v3 import policy_defs as policy
class TestPolicyDomain(policy_testcase.TestPolicyApi):
def test_create(self):
domain_def = policy.DomainDef(
domain_id='archaea',
name='prokaryotic cells',
description='typically characterized by membrane lipids')
self.policy_api.create_or_update(domain_def)
self.assert_json_call('PATCH', self.client,
'infra/domains/archaea',
data=domain_def.get_obj_dict())
def test_delete(self):
domain_def = policy.DomainDef(domain_id='bacteria')
self.policy_api.delete(domain_def)
self.assert_json_call('DELETE', self.client,
'infra/domains/bacteria')
def test_get(self):
domain_def = policy.DomainDef(domain_id='eukarya')
self.policy_api.get(domain_def)
self.assert_json_call('GET', self.client,
'infra/domains/eukarya')
def test_list(self):
domain_def = policy.DomainDef()
self.policy_api.list(domain_def)
self.assert_json_call('GET', self.client, 'infra/domains')
class TestPolicyGroup(policy_testcase.TestPolicyApi):
def test_create(self):
group_def = policy.GroupDef(
domain_id='eukarya',
group_id='cats',
name='felis catus')
self.policy_api.create_or_update(group_def)
self.assert_json_call('PATCH', self.client,
'infra/domains/eukarya/groups/cats',
data=group_def.get_obj_dict())
def test_create_with_domain(self):
domain_def = policy.DomainDef(domain_id='eukarya',
name='eukarya',
description='dude with cell membranes')
group_def = policy.GroupDef(domain_id='eukarya',
group_id='cats',
name='Ailuropoda melanoleuca')
self.policy_api.create_with_parent(domain_def, group_def)
data = domain_def.get_obj_dict()
data['groups'] = [group_def.get_obj_dict()]
self.assert_json_call('PATCH', self.client,
'infra/domains/eukarya',
data=data)
def test_create_with_single_tag(self):
domain_def = policy.DomainDef(domain_id='eukarya')
group_def = policy.GroupDef(domain_id='eukarya', group_id='dogs',
conditions=policy.Condition('spaniel'))
self.policy_api.create_with_parent(domain_def, group_def)
data = domain_def.get_obj_dict()
data['groups'] = [group_def.get_obj_dict()]
# validate body structure and defaults
expected_condition = {'value': 'spaniel',
'operator': 'EQUALS',
'member_type': 'LogicalPort',
'resource_type': 'Condition',
'key': 'Tag'}
expected_group = {'id': 'dogs',
'resource_type': 'Group',
'expression': [expected_condition]}
expected_data = {'id': 'eukarya',
'resource_type': 'Domain',
'groups': [expected_group]}
self.assert_json_call('PATCH', self.client,
'infra/domains/eukarya',
data=expected_data)
def test_create_with_multi_tag(self):
domain_def = policy.DomainDef(domain_id='eukarya')
pines = policy.Condition(
'pine',
operator=policy_constants.CONDITION_OP_CONTAINS)
maples = policy.Condition(
'maple',
operator=policy_constants.CONDITION_OP_STARTS_WITH)
group_def = policy.GroupDef(domain_id='eukarya', group_id='trees',
conditions=[pines, maples])
self.policy_api.create_with_parent(domain_def, group_def)
data = domain_def.get_obj_dict()
data['groups'] = [group_def.get_obj_dict()]
self.assert_json_call('PATCH', self.client,
'infra/domains/eukarya',
data=data)
def test_delete(self):
group_def = policy.GroupDef(domain_id='eukarya', group_id='giraffe')
self.policy_api.delete(group_def)
self.assert_json_call('DELETE', self.client,
'infra/domains/eukarya/groups/giraffe')
class TestPolicyService(policy_testcase.TestPolicyApi):
def test_create(self):
service_def = policy.ServiceDef(service_id='roomservice')
self.policy_api.create_or_update(service_def)
self.assert_json_call('PATCH', self.client,
'infra/services/roomservice',
data=service_def.get_obj_dict())
def test_create_l4_with_parent(self):
service_def = policy.ServiceDef(service_id='roomservice')
entry_def = policy.L4ServiceEntryDef(service_id='roomservice',
protocol='TCP',
entry_id='http',
name='room http',
dest_ports=[80, 8080])
self.policy_api.create_with_parent(service_def, entry_def)
expected_entry = {'id': 'http',
'resource_type': 'L4PortSetServiceEntry',
'display_name': 'room http',
'l4_protocol': 'TCP',
'destination_ports': [80, 8080]}
expected_data = {'id': 'roomservice',
'resource_type': 'Service',
'service_entries': [expected_entry]}
self.assert_json_call('PATCH', self.client,
'infra/services/roomservice',
data=expected_data)
def test_create_icmp_with_parent(self):
service_def = policy.ServiceDef(name='icmpservice',
service_id='icmpservice')
entry_def = policy.IcmpServiceEntryDef(service_id='icmpservice',
version=4,
entry_id='icmp',
name='icmpv4')
self.policy_api.create_with_parent(service_def, entry_def)
expected_entry = {'id': 'icmp',
'resource_type': 'ICMPTypeServiceEntry',
'display_name': 'icmpv4',
'protocol': 'ICMPv4'}
expected_data = {'id': 'icmpservice',
'resource_type': 'Service',
'display_name': 'icmpservice',
'service_entries': [expected_entry]}
self.assert_json_call('PATCH', self.client,
'infra/services/icmpservice',
data=expected_data)
class TestPolicyCommunicationMap(policy_testcase.TestPolicyApi):
def setUp(self):
super(TestPolicyCommunicationMap, self).setUp()
self.entry1 = policy.CommunicationMapEntryDef(
domain_id='d1',
map_id='cm1',
entry_id='en1',
action='ALLOW',
sequence_number=12,
source_groups=["group1",
"group2"],
dest_groups=["group1"],
service_ids=["service1"],
direction=nsx_constants.IN_OUT)
self.entry2 = policy.CommunicationMapEntryDef(
domain_id='d1',
map_id='cm2',
entry_id='en2',
action='ALLOW',
sequence_number=13,
source_groups=["group1",
"group2"],
dest_groups=["group3"],
service_ids=["service2"],
direction=nsx_constants.IN)
self.expected_data1 = {'id': 'en1',
'resource_type': 'Rule',
'sequence_number': 12,
'action': 'ALLOW',
'source_groups':
['/infra/domains/d1/groups/group1',
'/infra/domains/d1/groups/group2'],
'destination_groups':
['/infra/domains/d1/groups/group1'],
'services':
['/infra/services/service1'],
'direction': 'IN_OUT'}
self.expected_data2 = {'id': 'en2',
'resource_type': 'Rule',
'sequence_number': 13,
'action': 'ALLOW',
'source_groups':
['/infra/domains/d1/groups/group1',
'/infra/domains/d1/groups/group2'],
'destination_groups':
['/infra/domains/d1/groups/group3'],
'services':
['/infra/services/service2'],
'direction': 'IN'}
def test_create_with_one_entry(self):
map_def = policy.CommunicationMapDef(domain_id='d1', map_id='cm1')
self.policy_api.create_with_parent(map_def, self.entry1)
expected_data = map_def.get_obj_dict()
expected_data['rules'] = [self.expected_data1]
self.assert_json_call('PATCH', self.client,
'infra/domains/d1/security-policies/cm1',
data=expected_data)
def test_create_with_two_entries(self):
map_def = policy.CommunicationMapDef(domain_id='d1', map_id='cm1')
self.policy_api.create_with_parent(map_def,
[self.entry1, self.entry2])
expected_data = map_def.get_obj_dict()
expected_data['rules'] = [self.expected_data1,
self.expected_data2]
self.assert_json_call('PATCH', self.client,
'infra/domains/d1/security-policies/cm1',
data=expected_data)
def test_update_entry(self):
self.policy_api.create_or_update(self.entry1)
self.assert_json_call('PATCH', self.client,
'infra/domains/d1/security-policies/cm1/'
'rules/en1',
data=self.expected_data1)
def test_delete_entry(self):
self.policy_api.delete(self.entry2)
self.assert_json_call('DELETE', self.client,
'infra/domains/d1/security-policies/cm2/'
'rules/en2')
class TestPolicyEnforcementPoint(policy_testcase.TestPolicyApi):
def test_create(self):
ep_def = policy.EnforcementPointDef(ep_id='ep1', name='The Point',
ip_address='1.1.1.1',
username='admin',
password='a')
self.policy_api.create_or_update(ep_def)
ep_path = policy.EnforcementPointDef(ep_id='ep1').get_resource_path()
self.assert_json_call('PATCH', self.client,
ep_path,
data=ep_def.get_obj_dict())
class TestPolicyTransportZone(policy_testcase.TestPolicyApi):
def test_get(self):
tz_def = policy.TransportZoneDef(tz_id='tz1', ep_id='default')
self.policy_api.get(tz_def)
tz_path = tz_def.get_resource_path()
self.assert_json_call('GET', self.client, tz_path)
class TestPolicyDeploymentMap(policy_testcase.TestPolicyApi):
def test_create(self):
map_def = policy.DeploymentMapDef(map_id='dm1',
domain_id='d1',
ep_id='ep1')
self.policy_api.create_or_update(map_def)
ep_path = policy.EnforcementPointDef(
ep_id='ep1').get_resource_full_path()
expected_data = {'id': 'dm1',
'resource_type': 'DeploymentMap',
'enforcement_point_path': ep_path}
self.assert_json_call('PATCH', self.client,
'infra/domains/d1/domain-deployment-maps/dm1',
data=expected_data)
class TestPolicyTier1(policy_testcase.TestPolicyApi):
def test_create(self):
name = 'test'
description = 'desc'
tier0_id = '000'
tier1_id = '111'
tier1_def = policy.Tier1Def(
tier1_id=tier1_id,
name=name, description=description,
tier0=tier0_id)
self.policy_api.create_or_update(tier1_def)
tier1_path = tier1_def.get_resource_path()
self.assert_json_call('PATCH', self.client,
tier1_path,
data=tier1_def.get_obj_dict())

File diff suppressed because it is too large Load Diff

View File

@ -1,120 +0,0 @@
# Copyright 2018 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 mock
from vmware_nsxlib.tests.unit.v3 import nsxlib_testcase
from vmware_nsxlib.tests.unit.v3 import policy_testcase
from vmware_nsxlib import v3
from vmware_nsxlib.v3 import policy_transaction as trans
class TestPolicyTransaction(policy_testcase.TestPolicyApi):
def setUp(self):
super(TestPolicyTransaction, self).setUp()
nsxlib_config = nsxlib_testcase.get_default_nsxlib_config()
# Mock the nsx-lib for the passthrough api
with mock.patch('vmware_nsxlib.v3.NsxLib'):
self.policy_lib = v3.NsxPolicyLib(nsxlib_config)
self.policy_api = self.policy_lib.policy_api
self.policy_api.client = self.client
def assert_infra_patch_call(self, body):
self.assert_json_call('PATCH', self.client, 'infra',
data=body)
def test_domains_only(self):
tags = [{'scope': 'color', 'tag': 'green'}]
d1 = {'resource_type': 'Domain', 'id': 'domain1',
'display_name': 'd1', 'description': 'first domain',
'tags': tags}
d2 = {'resource_type': 'Domain', 'id': 'domain2',
'display_name': 'd2', 'description': 'no tags',
'tags': None}
with trans.NsxPolicyTransaction():
for d in (d1, d2):
self.policy_lib.domain.create_or_overwrite(
d['display_name'],
d['id'],
d['description'],
tags=d['tags'] if 'tags' in d else None)
expected_body = {'resource_type': 'Infra',
'children': [{'resource_type': 'ChildDomain',
'Domain': d1},
{'resource_type': 'ChildDomain',
'Domain': d2}]}
self.assert_infra_patch_call(expected_body)
def test_domains_and_groups(self):
tags = [{'scope': 'color', 'tag': 'green'}]
g1 = {'resource_type': 'Group', 'id': 'group1',
'display_name': 'g1',
'description': 'first group',
'tags': None}
g2 = {'resource_type': 'Group', 'id': 'group2',
'description': 'second group',
'display_name': 'g2',
'tags': tags}
g3 = {'resource_type': 'Group', 'id': 'group3',
'display_name': 'g3',
'description': 'third group',
'tags': None}
d1 = {'resource_type': 'Domain', 'id': 'domain1',
'display_name': 'd1', 'description': 'first domain',
'tags': tags}
d2 = {'resource_type': 'Domain', 'id': 'domain2',
'display_name': 'd2', 'description': 'no tags',
'tags': None}
with trans.NsxPolicyTransaction():
for d in (d1, d2):
self.policy_lib.domain.create_or_overwrite(
d['display_name'],
d['id'],
d['description'],
tags=d['tags'] if 'tags' in d else None)
d['children'] = []
for g in (g1, g2, g3):
self.policy_lib.group.create_or_overwrite(
g['display_name'],
d['id'],
g['id'],
g['description'],
tags=g['tags'] if 'tags' in g else None)
d['children'].append({'resource_type': 'ChildGroup',
'Group': g})
expected_body = {'resource_type': 'Infra',
'children': [{'resource_type': 'ChildDomain',
'Domain': d1},
{'resource_type': 'ChildDomain',
'Domain': d2}]}
self.assert_infra_patch_call(expected_body)

View File

@ -13,24 +13,18 @@
# License for the specific language governing permissions and limitations
# under the License.
import abc
import copy
from distutils import version
from oslo_log import log
import six
from vmware_nsxlib._i18n import _
from vmware_nsxlib.v3 import client
from vmware_nsxlib.v3 import cluster
from vmware_nsxlib.v3 import core_resources
from vmware_nsxlib.v3 import exceptions
from vmware_nsxlib.v3 import lib
from vmware_nsxlib.v3 import load_balancer
from vmware_nsxlib.v3 import native_dhcp
from vmware_nsxlib.v3 import nsx_constants
from vmware_nsxlib.v3 import policy_defs
from vmware_nsxlib.v3 import policy_load_balancer
from vmware_nsxlib.v3 import policy_resources
from vmware_nsxlib.v3 import resources
from vmware_nsxlib.v3 import router
from vmware_nsxlib.v3 import security
@ -41,207 +35,7 @@ from vmware_nsxlib.v3 import vpn_ipsec
LOG = log.getLogger(__name__)
@six.add_metaclass(abc.ABCMeta)
class NsxLibBase(object):
def __init__(self, nsxlib_config):
self.set_config(nsxlib_config)
# create the Cluster
self.cluster = cluster.NSXClusteredAPI(self.nsxlib_config)
# create the Client
self.client = client.NSX3Client(
self.cluster,
nsx_api_managers=self.nsxlib_config.nsx_api_managers,
max_attempts=self.nsxlib_config.max_attempts,
url_path_base=self.client_url_prefix,
rate_limit_retry=self.nsxlib_config.rate_limit_retry)
self.general_apis = utils.NsxLibApiBase(
self.client, self.nsxlib_config)
self.nsx_version = None
self.init_api()
super(NsxLibBase, self).__init__()
def set_config(self, nsxlib_config):
"""Set config user provided and extend it according to application"""
self.nsxlib_config = nsxlib_config
self.nsxlib_config.extend(
keepalive_section=self.keepalive_section,
validate_connection_method=self.validate_connection_method,
url_base=self.client_url_prefix)
@abc.abstractproperty
def client_url_prefix(self):
pass
@abc.abstractproperty
def keepalive_section(self):
pass
@abc.abstractproperty
def validate_connection_method(self):
pass
@abc.abstractmethod
def init_api(self):
pass
@abc.abstractmethod
def feature_supported(self, feature):
pass
def build_v3_api_version_tag(self):
return self.general_apis.build_v3_api_version_tag()
def is_internal_resource(self, nsx_resource):
return self.general_apis.is_internal_resource(nsx_resource)
def build_v3_api_version_project_tag(self, project_name, project_id=None):
return self.general_apis.build_v3_api_version_project_tag(
project_name, project_id=project_id)
def build_v3_tags_payload(self, resource, resource_type, project_name):
return self.general_apis.build_v3_tags_payload(
resource, resource_type, project_name)
def reinitialize_cluster(self, resource, event, trigger, payload=None):
self.cluster._reinit_cluster()
def subscribe(self, callback, event):
self.cluster.subscribe(callback, event)
# TODO(abhiraut): Revisit this method to generate complex boolean
# queries to search resources.
def search_by_tags(self, tags, resource_type=None, cursor=None,
page_size=None):
"""Return the list of resources searched based on tags.
Currently the query only supports AND boolean operator.
:param tags: List of dictionaries containing tags. Each
NSX tag dictionary is of the form:
{'scope': <scope_key>, 'tag': <tag_value>}
:param resource_type: Optional string parameter to limit the
scope of the search to the given ResourceType.
:param cursor: Opaque cursor to be used for getting next page of
records (supplied by current result page).
:param page_size: Maximum number of results to return in this page.
"""
if not tags:
reason = _("Missing required argument 'tags'")
raise exceptions.NsxSearchInvalidQuery(reason=reason)
# Query will return nothing if the same scope is repeated.
query_tags = self._build_query(tags)
query = 'resource_type:%s' % resource_type if resource_type else None
if query:
query += " AND %s" % query_tags
else:
query = query_tags
url = "search?query=%s" % query
if cursor:
url += "&cursor=%d" % cursor
if page_size:
url += "&page_size=%d" % page_size
# Retry the search on case of error
@utils.retry_upon_exception(exceptions.NsxIndexingInProgress,
max_attempts=self.client.max_attempts)
def do_search(url):
return self.client.url_get(url)
return do_search(url)
def search_all_by_tags(self, tags, resource_type=None):
"""Return all the results searched based on tags."""
results = []
cursor = 0
while True:
response = self.search_by_tags(resource_type=resource_type,
tags=tags, cursor=cursor)
if not response['results']:
return results
results.extend(response['results'])
cursor = int(response['cursor'])
result_count = int(response['result_count'])
if cursor >= result_count:
return results
def get_id_by_resource_and_tag(self, resource_type, scope, tag,
alert_not_found=False,
alert_multiple=False):
"""Search a resource type by 1 scope&tag.
Return the id of the result only if it is single.
"""
query_tags = [{'scope': utils.escape_tag_data(scope),
'tag': utils.escape_tag_data(tag)}]
query_result = self.search_by_tags(
tags=query_tags, resource_type=resource_type)
if not query_result['result_count']:
if alert_not_found:
msg = _("No %(type)s found for tag '%(scope)s:%(tag)s'") % {
'type': resource_type,
'scope': scope,
'tag': tag}
LOG.warning(msg)
raise exceptions.ResourceNotFound(
manager=self.nsxlib_config.nsx_api_managers,
operation=msg)
elif query_result['result_count'] == 1:
return query_result['results'][0]['id']
else:
# multiple results
if alert_multiple:
msg = _("Multiple %(type)s found for tag '%(scope)s:"
"%(tag)s'") % {
'type': resource_type,
'scope': scope,
'tag': tag}
LOG.warning(msg)
raise exceptions.ManagerError(
manager=self.nsxlib_config.nsx_api_managers,
operation=msg,
details='')
def _build_tag_query(self, tag):
# Validate that the correct keys are used
if set(tag.keys()) - set(('scope', 'tag')):
reason = _("Only 'scope' and 'tag' keys are supported")
raise exceptions.NsxSearchInvalidQuery(reason=reason)
_scope = tag.get('scope')
_tag = tag.get('tag')
if _scope and _tag:
return 'tags.scope:%s AND tags.tag:%s' % (_scope, _tag)
elif _scope:
return 'tags.scope:%s' % _scope
else:
return 'tags.tag:%s' % _tag
def _build_query(self, tags):
return " AND ".join([self._build_tag_query(item) for item in tags])
def get_tag_limits(self):
try:
result = self.client.url_get('spec/vmware/types/Tag')
scope_length = result['properties']['scope']['maxLength']
tag_length = result['properties']['tag']['maxLength']
except Exception as e:
LOG.error("Unable to read tag limits. Reason: %s", e)
scope_length = utils.MAX_RESOURCE_TYPE_LEN
tag_length = utils.MAX_TAG_LEN
try:
result = self.client.url_get('spec/vmware/types/ManagedResource')
max_tags = result['properties']['tags']['maxItems']
except Exception as e:
LOG.error("Unable to read maximum tags. Reason: %s", e)
max_tags = utils.MAX_TAGS
return utils.TagLimits(scope_length, tag_length, max_tags)
class NsxLib(NsxLibBase):
class NsxLib(lib.NsxLibBase):
def init_api(self):
self.port_mirror = core_resources.NsxLibPortMirror(
@ -397,120 +191,3 @@ class NsxLib(NsxLibBase):
@property
def client_url_prefix(self):
return client.NSX3Client.NSX_V1_API_PREFIX
class NsxPolicyLib(NsxLibBase):
def init_api(self):
# Initialize the policy client
self.policy_api = policy_defs.NsxPolicyApi(self.client)
# NSX manager api will be used as a pass-through for apis which are
# not implemented by the policy manager yet
if self.nsxlib_config.allow_passthrough:
config = copy.deepcopy(self.nsxlib_config)
# X-Allow-Overwrite must be set for passthrough apis
config.allow_overwrite_header = True
self.nsx_api = NsxLib(config)
else:
self.nsx_api = None
self.nsx_version = self.get_version()
args = (self.policy_api, self.nsx_api, self.nsx_version,
self.nsxlib_config)
# Initialize all the different resources
self.domain = policy_resources.NsxPolicyDomainApi(*args)
self.group = policy_resources.NsxPolicyGroupApi(*args)
self.service = policy_resources.NsxPolicyL4ServiceApi(*args)
self.icmp_service = policy_resources.NsxPolicyIcmpServiceApi(
*args)
self.ip_protocol_service = (
policy_resources.NsxPolicyIPProtocolServiceApi(*args))
self.tier0 = policy_resources.NsxPolicyTier0Api(*args)
self.tier1 = policy_resources.NsxPolicyTier1Api(*args)
self.tier1_segment = policy_resources.NsxPolicyTier1SegmentApi(*args)
self.tier1_nat_rule = policy_resources.NsxPolicyTier1NatRuleApi(
*args)
self.tier1_static_route = (
policy_resources.NsxPolicyTier1StaticRouteApi(*args))
self.segment = policy_resources.NsxPolicySegmentApi(*args)
self.segment_port = policy_resources.NsxPolicySegmentPortApi(
*args)
self.tier1_segment_port = (
policy_resources.NsxPolicyTier1SegmentPortApi(*args))
self.comm_map = policy_resources.NsxPolicyCommunicationMapApi(
*args)
self.enforcement_point = policy_resources.NsxPolicyEnforcementPointApi(
*args)
self.transport_zone = policy_resources.NsxPolicyTransportZoneApi(
*args)
self.deployment_map = policy_resources.NsxPolicyDeploymentMapApi(
*args)
self.ip_block = policy_resources.NsxPolicyIpBlockApi(*args)
self.ip_pool = policy_resources.NsxPolicyIpPoolApi(*args)
self.segment_security_profile = (
policy_resources.NsxSegmentSecurityProfileApi(*args))
self.qos_profile = (
policy_resources.NsxQosProfileApi(*args))
self.spoofguard_profile = (
policy_resources.NsxSpoofguardProfileApi(*args))
self.ip_discovery_profile = (
policy_resources.NsxIpDiscoveryProfileApi(*args))
self.mac_discovery_profile = (
policy_resources.NsxMacDiscoveryProfileApi(*args))
self.segment_port_security_profiles = (
policy_resources.SegmentPortSecurityProfilesBindingMapApi(
*args))
self.segment_port_discovery_profiles = (
policy_resources.SegmentPortDiscoveryProfilesBindingMapApi(
*args))
self.segment_port_qos_profiles = (
policy_resources.SegmentPortQosProfilesBindingMapApi(
*args))
self.load_balancer = (
policy_load_balancer.NsxPolicyLoadBalancerApi(*args))
@property
def keepalive_section(self):
return 'infra'
@property
def validate_connection_method(self):
# TODO(asarfaty): Find an equivalent api to check policy status
pass
def get_version(self):
"""Get the NSX Policy manager version
Currently the backend does not support it, so the nsx-manager api
will be used temporarily as a passthrough.
"""
if self.nsx_version:
return self.nsx_version
if self.nsx_api:
self.nsx_version = self.nsx_api.get_version()
else:
# return the initial supported version
self.nsx_version = nsx_constants.NSX_VERSION_2_4_0
return self.nsx_version
def feature_supported(self, feature):
if (version.LooseVersion(self.get_version()) >=
version.LooseVersion(nsx_constants.NSX_VERSION_2_4_0)):
# Features available since 2.4
if (feature == nsx_constants.FEATURE_NSX_POLICY_NETWORKING):
return True
return (feature == nsx_constants.FEATURE_NSX_POLICY)
def reinitialize_cluster(self, resource, event, trigger, payload=None):
super(NsxPolicyLib, self).reinitialize_cluster(
resource, event, trigger, payload=payload)
if self.nsx_api:
self.nsx_api.reinitialize_cluster(resource, event, trigger,
payload)
@property
def client_url_prefix(self):
return client.NSX3Client.NSX_POLICY_V1_API_PREFIX

227
vmware_nsxlib/v3/lib.py Normal file
View File

@ -0,0 +1,227 @@
# Copyright 2016 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 abc
from oslo_log import log
import six
from vmware_nsxlib._i18n import _
from vmware_nsxlib.v3 import client
from vmware_nsxlib.v3 import cluster
from vmware_nsxlib.v3 import exceptions
from vmware_nsxlib.v3 import utils
LOG = log.getLogger(__name__)
@six.add_metaclass(abc.ABCMeta)
class NsxLibBase(object):
def __init__(self, nsxlib_config):
self.set_config(nsxlib_config)
# create the Cluster
self.cluster = cluster.NSXClusteredAPI(self.nsxlib_config)
# create the Client
self.client = client.NSX3Client(
self.cluster,
nsx_api_managers=self.nsxlib_config.nsx_api_managers,
max_attempts=self.nsxlib_config.max_attempts,
url_path_base=self.client_url_prefix,
rate_limit_retry=self.nsxlib_config.rate_limit_retry)
self.general_apis = utils.NsxLibApiBase(
self.client, self.nsxlib_config)
self.nsx_version = None
self.init_api()
super(NsxLibBase, self).__init__()
def set_config(self, nsxlib_config):
"""Set config user provided and extend it according to application"""
self.nsxlib_config = nsxlib_config
self.nsxlib_config.extend(
keepalive_section=self.keepalive_section,
validate_connection_method=self.validate_connection_method,
url_base=self.client_url_prefix)
@abc.abstractproperty
def client_url_prefix(self):
pass
@abc.abstractproperty
def keepalive_section(self):
pass
@abc.abstractproperty
def validate_connection_method(self):
pass
@abc.abstractmethod
def init_api(self):
pass
@abc.abstractmethod
def feature_supported(self, feature):
pass
def build_v3_api_version_tag(self):
return self.general_apis.build_v3_api_version_tag()
def is_internal_resource(self, nsx_resource):
return self.general_apis.is_internal_resource(nsx_resource)
def build_v3_api_version_project_tag(self, project_name, project_id=None):
return self.general_apis.build_v3_api_version_project_tag(
project_name, project_id=project_id)
def build_v3_tags_payload(self, resource, resource_type, project_name):
return self.general_apis.build_v3_tags_payload(
resource, resource_type, project_name)
def reinitialize_cluster(self, resource, event, trigger, payload=None):
self.cluster._reinit_cluster()
def subscribe(self, callback, event):
self.cluster.subscribe(callback, event)
# TODO(abhiraut): Revisit this method to generate complex boolean
# queries to search resources.
def search_by_tags(self, tags, resource_type=None, cursor=None,
page_size=None):
"""Return the list of resources searched based on tags.
Currently the query only supports AND boolean operator.
:param tags: List of dictionaries containing tags. Each
NSX tag dictionary is of the form:
{'scope': <scope_key>, 'tag': <tag_value>}
:param resource_type: Optional string parameter to limit the
scope of the search to the given ResourceType.
:param cursor: Opaque cursor to be used for getting next page of
records (supplied by current result page).
:param page_size: Maximum number of results to return in this page.
"""
if not tags:
reason = _("Missing required argument 'tags'")
raise exceptions.NsxSearchInvalidQuery(reason=reason)
# Query will return nothing if the same scope is repeated.
query_tags = self._build_query(tags)
query = 'resource_type:%s' % resource_type if resource_type else None
if query:
query += " AND %s" % query_tags
else:
query = query_tags
url = "search?query=%s" % query
if cursor:
url += "&cursor=%d" % cursor
if page_size:
url += "&page_size=%d" % page_size
# Retry the search on case of error
@utils.retry_upon_exception(exceptions.NsxIndexingInProgress,
max_attempts=self.client.max_attempts)
def do_search(url):
return self.client.url_get(url)
return do_search(url)
def search_all_by_tags(self, tags, resource_type=None):
"""Return all the results searched based on tags."""
results = []
cursor = 0
while True:
response = self.search_by_tags(resource_type=resource_type,
tags=tags, cursor=cursor)
if not response['results']:
return results
results.extend(response['results'])
cursor = int(response['cursor'])
result_count = int(response['result_count'])
if cursor >= result_count:
return results
def get_id_by_resource_and_tag(self, resource_type, scope, tag,
alert_not_found=False,
alert_multiple=False):
"""Search a resource type by 1 scope&tag.
Return the id of the result only if it is single.
"""
query_tags = [{'scope': utils.escape_tag_data(scope),
'tag': utils.escape_tag_data(tag)}]
query_result = self.search_by_tags(
tags=query_tags, resource_type=resource_type)
if not query_result['result_count']:
if alert_not_found:
msg = _("No %(type)s found for tag '%(scope)s:%(tag)s'") % {
'type': resource_type,
'scope': scope,
'tag': tag}
LOG.warning(msg)
raise exceptions.ResourceNotFound(
manager=self.nsxlib_config.nsx_api_managers,
operation=msg)
elif query_result['result_count'] == 1:
return query_result['results'][0]['id']
else:
# multiple results
if alert_multiple:
msg = _("Multiple %(type)s found for tag '%(scope)s:"
"%(tag)s'") % {
'type': resource_type,
'scope': scope,
'tag': tag}
LOG.warning(msg)
raise exceptions.ManagerError(
manager=self.nsxlib_config.nsx_api_managers,
operation=msg,
details='')
def _build_tag_query(self, tag):
# Validate that the correct keys are used
if set(tag.keys()) - set(('scope', 'tag')):
reason = _("Only 'scope' and 'tag' keys are supported")
raise exceptions.NsxSearchInvalidQuery(reason=reason)
_scope = tag.get('scope')
_tag = tag.get('tag')
if _scope and _tag:
return 'tags.scope:%s AND tags.tag:%s' % (_scope, _tag)
elif _scope:
return 'tags.scope:%s' % _scope
else:
return 'tags.tag:%s' % _tag
def _build_query(self, tags):
return " AND ".join([self._build_tag_query(item) for item in tags])
def get_tag_limits(self):
try:
result = self.client.url_get('spec/vmware/types/Tag')
scope_length = result['properties']['scope']['maxLength']
tag_length = result['properties']['tag']['maxLength']
except Exception as e:
LOG.error("Unable to read tag limits. Reason: %s", e)
scope_length = utils.MAX_RESOURCE_TYPE_LEN
tag_length = utils.MAX_TAG_LEN
try:
result = self.client.url_get('spec/vmware/types/ManagedResource')
max_tags = result['properties']['tags']['maxItems']
except Exception as e:
LOG.error("Unable to read maximum tags. Reason: %s", e)
max_tags = utils.MAX_TAGS
return utils.TagLimits(scope_length, tag_length, max_tags)

View File

@ -0,0 +1,147 @@
# Copyright 2016 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 copy
from distutils import version
from oslo_log import log
from vmware_nsxlib import v3
from vmware_nsxlib.v3 import client
from vmware_nsxlib.v3 import lib
from vmware_nsxlib.v3 import nsx_constants
from vmware_nsxlib.v3.policy import core_defs
from vmware_nsxlib.v3.policy import core_resources
from vmware_nsxlib.v3.policy import lb_resources
LOG = log.getLogger(__name__)
class NsxPolicyLib(lib.NsxLibBase):
def init_api(self):
# Initialize the policy client
# TODO(annak): move the API class to separate file
self.policy_api = core_defs.NsxPolicyApi(self.client)
# NSX manager api will be used as a pass-through for apis which are
# not implemented by the policy manager yet
if self.nsxlib_config.allow_passthrough:
config = copy.deepcopy(self.nsxlib_config)
# X-Allow-Overwrite must be set for passthrough apis
config.allow_overwrite_header = True
self.nsx_api = v3.NsxLib(config)
else:
self.nsx_api = None
self.nsx_version = self.get_version()
args = (self.policy_api, self.nsx_api, self.nsx_version,
self.nsxlib_config)
# Initialize all the different resources
self.domain = core_resources.NsxPolicyDomainApi(*args)
self.group = core_resources.NsxPolicyGroupApi(*args)
self.service = core_resources.NsxPolicyL4ServiceApi(*args)
self.icmp_service = core_resources.NsxPolicyIcmpServiceApi(
*args)
self.ip_protocol_service = (
core_resources.NsxPolicyIPProtocolServiceApi(*args))
self.tier0 = core_resources.NsxPolicyTier0Api(*args)
self.tier1 = core_resources.NsxPolicyTier1Api(*args)
self.tier1_segment = core_resources.NsxPolicyTier1SegmentApi(*args)
self.tier1_nat_rule = core_resources.NsxPolicyTier1NatRuleApi(
*args)
self.tier1_static_route = (
core_resources.NsxPolicyTier1StaticRouteApi(*args))
self.segment = core_resources.NsxPolicySegmentApi(*args)
self.segment_port = core_resources.NsxPolicySegmentPortApi(
*args)
self.tier1_segment_port = (
core_resources.NsxPolicyTier1SegmentPortApi(*args))
self.comm_map = core_resources.NsxPolicyCommunicationMapApi(
*args)
self.enforcement_point = core_resources.NsxPolicyEnforcementPointApi(
*args)
self.transport_zone = core_resources.NsxPolicyTransportZoneApi(
*args)
self.deployment_map = core_resources.NsxPolicyDeploymentMapApi(
*args)
self.ip_block = core_resources.NsxPolicyIpBlockApi(*args)
self.ip_pool = core_resources.NsxPolicyIpPoolApi(*args)
self.segment_security_profile = (
core_resources.NsxSegmentSecurityProfileApi(*args))
self.qos_profile = (
core_resources.NsxQosProfileApi(*args))
self.spoofguard_profile = (
core_resources.NsxSpoofguardProfileApi(*args))
self.ip_discovery_profile = (
core_resources.NsxIpDiscoveryProfileApi(*args))
self.mac_discovery_profile = (
core_resources.NsxMacDiscoveryProfileApi(*args))
self.segment_port_security_profiles = (
core_resources.SegmentPortSecurityProfilesBindingMapApi(
*args))
self.segment_port_discovery_profiles = (
core_resources.SegmentPortDiscoveryProfilesBindingMapApi(
*args))
self.segment_port_qos_profiles = (
core_resources.SegmentPortQosProfilesBindingMapApi(
*args))
self.load_balancer = lb_resources.NsxPolicyLoadBalancerApi(*args)
@property
def keepalive_section(self):
return 'infra'
@property
def validate_connection_method(self):
# TODO(asarfaty): Find an equivalent api to check policy status
pass
def get_version(self):
"""Get the NSX Policy manager version
Currently the backend does not support it, so the nsx-manager api
will be used temporarily as a passthrough.
"""
if self.nsx_version:
return self.nsx_version
if self.nsx_api:
self.nsx_version = self.nsx_api.get_version()
else:
# return the initial supported version
self.nsx_version = nsx_constants.NSX_VERSION_2_4_0
return self.nsx_version
def feature_supported(self, feature):
if (version.LooseVersion(self.get_version()) >=
version.LooseVersion(nsx_constants.NSX_VERSION_2_4_0)):
# Features available since 2.4
if (feature == nsx_constants.FEATURE_NSX_POLICY_NETWORKING):
return True
return (feature == nsx_constants.FEATURE_NSX_POLICY)
def reinitialize_cluster(self, resource, event, trigger, payload=None):
super(NsxPolicyLib, self).reinitialize_cluster(
resource, event, trigger, payload=payload)
if self.nsx_api:
self.nsx_api.reinitialize_cluster(resource, event, trigger,
payload)
@property
def client_url_prefix(self):
return client.NSX3Client.NSX_POLICY_V1_API_PREFIX

View File

@ -18,9 +18,10 @@ import abc
import six
from vmware_nsxlib.v3 import policy_constants
from vmware_nsxlib.v3 import utils
from vmware_nsxlib.v3.policy import constants
TENANTS_PATH_PATTERN = "%s/"
DOMAINS_PATH_PATTERN = TENANTS_PATH_PATTERN + "domains/"
IP_BLOCKS_PATH_PATTERN = TENANTS_PATH_PATTERN + "ip-blocks/"
@ -111,7 +112,7 @@ class ResourceDef(object):
if self.attrs.get('tenant'):
return self.attrs.get('tenant')
return policy_constants.POLICY_INFRA_TENANT
return constants.POLICY_INFRA_TENANT
def get_section_path(self):
path_ids = [self.get_attr(path_id) for path_id in self.path_ids[:-1]]
@ -562,7 +563,7 @@ class SegmentDef(BaseSegmentDef):
if self.get_attr('transport_zone_id'):
tz = TransportZoneDef(
tz_id=self.get_attr('transport_zone_id'),
ep_id=policy_constants.DEFAULT_ENFORCEMENT_POINT,
ep_id=constants.DEFAULT_ENFORCEMENT_POINT,
tenant=self.get_tenant())
path = tz.get_resource_full_path()
self._set_attr_if_specified(body, 'transport_zone_id',
@ -866,9 +867,9 @@ class IpPoolBlockSubnetDef(ResourceDef):
class Condition(object):
def __init__(self, value, key=policy_constants.CONDITION_KEY_TAG,
member_type=policy_constants.CONDITION_MEMBER_PORT,
operator=policy_constants.CONDITION_OP_EQUALS):
def __init__(self, value, key=constants.CONDITION_KEY_TAG,
member_type=constants.CONDITION_MEMBER_PORT,
operator=constants.CONDITION_OP_EQUALS):
self.value = value
self.key = key
self.member_type = member_type
@ -892,7 +893,7 @@ class IPAddressExpression(object):
class ConjunctionOperator(object):
def __init__(self, operator=policy_constants.CONDITION_OP_AND):
def __init__(self, operator=constants.CONDITION_OP_AND):
self.operator = operator
def get_obj_dict(self):
@ -1060,7 +1061,7 @@ class CommunicationMapDef(ResourceDef):
class CommunicationMapEntryDef(ResourceDef):
def get_groups_path(self, domain_id, group_ids):
if not group_ids:
return [policy_constants.ANY_GROUP]
return [constants.ANY_GROUP]
return [GroupDef(domain_id=domain_id,
group_id=group_id,
tenant=self.get_tenant()).get_resource_full_path()
@ -1076,7 +1077,7 @@ class CommunicationMapEntryDef(ResourceDef):
return [self.get_service_path(service_id)
for service_id in service_ids]
return [policy_constants.ANY_SERVICE]
return [constants.ANY_SERVICE]
@property
def path_pattern(self):

View File

@ -14,7 +14,7 @@
# under the License.
#
from vmware_nsxlib.v3.policy_defs import ResourceDef
from vmware_nsxlib.v3.policy.core_defs import ResourceDef
TENANTS_PATH_PATTERN = "%s/"
LB_VIRTUAL_SERVERS_PATH_PATTERN = TENANTS_PATH_PATTERN + "lb-virtual-servers/"

View File

@ -16,10 +16,11 @@
from oslo_log import log as logging
from vmware_nsxlib.v3 import policy_constants
from vmware_nsxlib.v3 import policy_defs_load_balancer
from vmware_nsxlib.v3.policy_resources import IGNORE
from vmware_nsxlib.v3.policy_resources import NsxPolicyResourceBase
from vmware_nsxlib.v3.policy import constants
from vmware_nsxlib.v3.policy import lb_defs
from vmware_nsxlib.v3.policy.core_resources import IGNORE
from vmware_nsxlib.v3.policy.core_resources import NsxPolicyResourceBase
LOG = logging.getLogger(__name__)
@ -46,7 +47,7 @@ class NsxPolicyLBAppProfileBase(NsxPolicyResourceBase):
response_timeout=IGNORE,
x_forwarded_for=IGNORE,
tags=IGNORE,
tenant=policy_constants.POLICY_INFRA_TENANT):
tenant=constants.POLICY_INFRA_TENANT):
lb_app_profile_id = self._init_obj_uuid(lb_app_profile_id)
lb_app_profile_def = self._init_def(
lb_app_profile_id=lb_app_profile_id,
@ -67,20 +68,20 @@ class NsxPolicyLBAppProfileBase(NsxPolicyResourceBase):
return lb_app_profile_id
def delete(self, lb_app_profile_id,
tenant=policy_constants.POLICY_INFRA_TENANT):
tenant=constants.POLICY_INFRA_TENANT):
lb_app_profile_def = self.entry_def(
lb_app_profile_id=lb_app_profile_id,
tenant=tenant)
self.policy_api.delete(lb_app_profile_def)
def get(self, lb_app_profile_id,
tenant=policy_constants.POLICY_INFRA_TENANT):
tenant=constants.POLICY_INFRA_TENANT):
lb_app_profile_def = self.entry_def(
lb_app_profile_id=lb_app_profile_id,
tenant=tenant)
self.policy_api.get(lb_app_profile_def)
def list(self, tenant=policy_constants.POLICY_INFRA_TENANT):
def list(self, tenant=constants.POLICY_INFRA_TENANT):
lb_app_profile_def = self.entry_def(tenant=tenant)
return self._list(lb_app_profile_def)
@ -97,7 +98,7 @@ class NsxPolicyLBAppProfileBase(NsxPolicyResourceBase):
response_timeout=IGNORE,
x_forwarded_for=IGNORE,
tags=IGNORE,
tenant=policy_constants.POLICY_INFRA_TENANT):
tenant=constants.POLICY_INFRA_TENANT):
self._update(
lb_app_profile_id=lb_app_profile_id,
name=name,
@ -120,7 +121,7 @@ class NsxPolicyLBAppProfileHttpApi(NsxPolicyLBAppProfileBase):
@property
def entry_def(self):
return policy_defs_load_balancer.LBHttpProfileDef
return lb_defs.LBHttpProfileDef
class NsxPolicyLBAppProfileFastTcpApi(
@ -129,7 +130,7 @@ class NsxPolicyLBAppProfileFastTcpApi(
@property
def entry_def(self):
return policy_defs_load_balancer.LBFastTcpProfile
return lb_defs.LBFastTcpProfile
class NsxPolicyLBAppProfileFastUdpApi(
@ -138,7 +139,7 @@ class NsxPolicyLBAppProfileFastUdpApi(
@property
def entry_def(self):
return policy_defs_load_balancer.LBFastUdpProfile
return lb_defs.LBFastUdpProfile
class NsxPolicyLoadBalancerLBClientSSLProfileApi(NsxPolicyResourceBase):
@ -146,14 +147,14 @@ class NsxPolicyLoadBalancerLBClientSSLProfileApi(NsxPolicyResourceBase):
@property
def entry_def(self):
return policy_defs_load_balancer.LBClientSslProfileDef
return lb_defs.LBClientSslProfileDef
def create_or_overwrite(self, name,
client_ssl_profile_id=None,
description=IGNORE,
tags=IGNORE,
protocols=IGNORE,
tenant=policy_constants.POLICY_INFRA_TENANT):
tenant=constants.POLICY_INFRA_TENANT):
client_ssl_profile_id = self._init_obj_uuid(
client_ssl_profile_id)
lb_client_ssl_profile_def = self._init_def(
@ -167,20 +168,20 @@ class NsxPolicyLoadBalancerLBClientSSLProfileApi(NsxPolicyResourceBase):
return client_ssl_profile_id
def delete(self, client_ssl_profile_id,
tenant=policy_constants.POLICY_INFRA_TENANT):
tenant=constants.POLICY_INFRA_TENANT):
lb_client_ssl_profile_def = self.entry_def(
client_ssl_profile_id=client_ssl_profile_id,
tenant=tenant)
self.policy_api.delete(lb_client_ssl_profile_def)
def get(self, client_ssl_profile_id,
tenant=policy_constants.POLICY_INFRA_TENANT):
tenant=constants.POLICY_INFRA_TENANT):
lb_client_ssl_profile_def = self.entry_def(
client_ssl_profile_id=client_ssl_profile_id,
tenant=tenant)
self.policy_api.get(lb_client_ssl_profile_def)
def list(self, tenant=policy_constants.POLICY_INFRA_TENANT):
def list(self, tenant=constants.POLICY_INFRA_TENANT):
lb_client_ssl_profile_def = self.entry_def(tenant=tenant)
return self._list(lb_client_ssl_profile_def)
@ -189,7 +190,7 @@ class NsxPolicyLoadBalancerLBClientSSLProfileApi(NsxPolicyResourceBase):
description=IGNORE,
tags=IGNORE,
protocols=IGNORE,
tenant=policy_constants.POLICY_INFRA_TENANT):
tenant=constants.POLICY_INFRA_TENANT):
self._update(
client_ssl_profile_id=client_ssl_profile_id,
name=name,
@ -205,7 +206,7 @@ class NsxPolicyLoadBalancerLBCookiePersistenceProfileApi(
@property
def entry_def(self):
return policy_defs_load_balancer.LBCookiePersistenceProfileDef
return lb_defs.LBCookiePersistenceProfileDef
def create_or_overwrite(self, name,
persistence_profile_id=None,
@ -217,7 +218,7 @@ class NsxPolicyLoadBalancerLBCookiePersistenceProfileApi(
cookie_path=IGNORE,
cookie_time=IGNORE,
persistence_shared=IGNORE,
tenant=policy_constants.POLICY_INFRA_TENANT):
tenant=constants.POLICY_INFRA_TENANT):
persistence_profile_id = self._init_obj_uuid(
persistence_profile_id)
lb_cookie_persistence_profile_def = self._init_def(
@ -236,20 +237,20 @@ class NsxPolicyLoadBalancerLBCookiePersistenceProfileApi(
return persistence_profile_id
def delete(self, persistence_profile_id,
tenant=policy_constants.POLICY_INFRA_TENANT):
tenant=constants.POLICY_INFRA_TENANT):
lb_cookie_persistence_profile_def = self.entry_def(
persistence_profile_id=persistence_profile_id,
tenant=tenant)
self.policy_api.delete(lb_cookie_persistence_profile_def)
def get(self, persistence_profile_id,
tenant=policy_constants.POLICY_INFRA_TENANT):
tenant=constants.POLICY_INFRA_TENANT):
lb_cookie_persistence_profile_def = self.entry_def(
persistence_profile_id=persistence_profile_id,
tenant=tenant)
self.policy_api.get(lb_cookie_persistence_profile_def)
def list(self, tenant=policy_constants.POLICY_INFRA_TENANT):
def list(self, tenant=constants.POLICY_INFRA_TENANT):
lb_cookie_persistence_profile_def = self.entry_def(tenant=tenant)
return self._list(lb_cookie_persistence_profile_def)
@ -263,7 +264,7 @@ class NsxPolicyLoadBalancerLBCookiePersistenceProfileApi(
cookie_path=IGNORE,
cookie_time=IGNORE,
persistence_shared=IGNORE,
tenant=policy_constants.POLICY_INFRA_TENANT):
tenant=constants.POLICY_INFRA_TENANT):
self._update(
persistence_profile_id=persistence_profile_id,
name=name,
@ -284,7 +285,7 @@ class NsxPolicyLoadBalancerLBSourceIpPersistenceProfileApi(
@property
def entry_def(self):
return policy_defs_load_balancer.LBSourceIpPersistenceProfileDef
return lb_defs.LBSourceIpPersistenceProfileDef
def create_or_overwrite(self, name,
persistence_profile_id=None,
@ -294,7 +295,7 @@ class NsxPolicyLoadBalancerLBSourceIpPersistenceProfileApi(
persistence_shared=IGNORE,
purge=IGNORE,
timeout=IGNORE,
tenant=policy_constants.POLICY_INFRA_TENANT):
tenant=constants.POLICY_INFRA_TENANT):
persistence_profile_id = self._init_obj_uuid(
persistence_profile_id)
lb_source_ip_persistence_profile_def = self._init_def(
@ -311,20 +312,20 @@ class NsxPolicyLoadBalancerLBSourceIpPersistenceProfileApi(
return persistence_profile_id
def delete(self, persistence_profile_id,
tenant=policy_constants.POLICY_INFRA_TENANT):
tenant=constants.POLICY_INFRA_TENANT):
lb_source_ip_persistence_profile_def = self.entry_def(
persistence_profile_id=persistence_profile_id,
tenant=tenant)
self.policy_api.delete(lb_source_ip_persistence_profile_def)
def get(self, persistence_profile_id,
tenant=policy_constants.POLICY_INFRA_TENANT):
tenant=constants.POLICY_INFRA_TENANT):
lb_source_ip_persistence_profile_def = self.entry_def(
persistence_profile_id=persistence_profile_id,
tenant=tenant)
self.policy_api.get(lb_source_ip_persistence_profile_def)
def list(self, tenant=policy_constants.POLICY_INFRA_TENANT):
def list(self, tenant=constants.POLICY_INFRA_TENANT):
lb_source_ip_persistence_profile_def = self.entry_def(tenant=tenant)
return self._list(lb_source_ip_persistence_profile_def)
@ -336,7 +337,7 @@ class NsxPolicyLoadBalancerLBSourceIpPersistenceProfileApi(
persistence_shared=IGNORE,
purge=IGNORE,
timeout=IGNORE,
tenant=policy_constants.POLICY_INFRA_TENANT):
tenant=constants.POLICY_INFRA_TENANT):
self._update(
persistence_profile_id=persistence_profile_id,
name=name,
@ -353,13 +354,13 @@ class NsxPolicyLoadBalancerPoolApi(NsxPolicyResourceBase):
"""NSX Policy LBService."""
@property
def entry_def(self):
return policy_defs_load_balancer.LBPoolDef
return lb_defs.LBPoolDef
def create_or_overwrite(self, name, lb_pool_id=None, description=IGNORE,
tags=IGNORE, members=IGNORE, algorithm=IGNORE,
active_monitor_paths=IGNORE, member_group=IGNORE,
snat_translation=IGNORE,
tenant=policy_constants.POLICY_INFRA_TENANT):
tenant=constants.POLICY_INFRA_TENANT):
lb_pool_id = self._init_obj_uuid(lb_pool_id)
lb_pool_def = self._init_def(
lb_pool_id=lb_pool_id,
@ -377,18 +378,18 @@ class NsxPolicyLoadBalancerPoolApi(NsxPolicyResourceBase):
return lb_pool_id
def delete(self, lb_pool_id,
tenant=policy_constants.POLICY_INFRA_TENANT):
tenant=constants.POLICY_INFRA_TENANT):
lb_pool_def = self.entry_def(
lb_pool_id=lb_pool_id, tenant=tenant)
self.policy_api.delete(lb_pool_def)
def get(self, lb_pool_id, tenant=policy_constants.POLICY_INFRA_TENANT,
def get(self, lb_pool_id, tenant=constants.POLICY_INFRA_TENANT,
silent=False):
lb_pool_def = self.entry_def(
lb_pool_id=lb_pool_id, tenant=tenant)
return self.policy_api.get(lb_pool_def)
def list(self, tenant=policy_constants.POLICY_INFRA_TENANT):
def list(self, tenant=constants.POLICY_INFRA_TENANT):
lb_pool_def = self.entry_def(tenant=tenant)
return self.policy_api.list(lb_pool_def)['results']
@ -396,7 +397,7 @@ class NsxPolicyLoadBalancerPoolApi(NsxPolicyResourceBase):
tags=IGNORE, members=IGNORE, algorithm=IGNORE,
active_monitor_paths=IGNORE, member_group=IGNORE,
snat_translation=IGNORE,
tenant=policy_constants.POLICY_INFRA_TENANT):
tenant=constants.POLICY_INFRA_TENANT):
self._update(
lb_pool_id=lb_pool_id,
name=name,
@ -410,7 +411,7 @@ class NsxPolicyLoadBalancerPoolApi(NsxPolicyResourceBase):
tenant=tenant)
def add_monitor_to_pool(self, lb_pool_id, active_monitor_paths,
tenant=policy_constants.POLICY_INFRA_TENANT):
tenant=constants.POLICY_INFRA_TENANT):
lb_pool_def = self.entry_def(
lb_pool_id=lb_pool_id, tenant=tenant)
lb_pool = self.policy_api.get(lb_pool_def)
@ -419,7 +420,7 @@ class NsxPolicyLoadBalancerPoolApi(NsxPolicyResourceBase):
self.update(lb_pool_id, active_monitor_paths=monitor_paths)
def remove_monitor_from_pool(self, lb_pool_id, monitor_path,
tenant=policy_constants.POLICY_INFRA_TENANT):
tenant=constants.POLICY_INFRA_TENANT):
lb_pool_def = self.entry_def(
lb_pool_id=lb_pool_id, tenant=tenant)
lb_pool = self.policy_api.get(lb_pool_def)
@ -430,12 +431,12 @@ class NsxPolicyLoadBalancerPoolApi(NsxPolicyResourceBase):
def create_pool_member_and_add_to_pool(
self, lb_pool_id, ip_address, port=None,
display_name=None, weight=None,
tenant=policy_constants.POLICY_INFRA_TENANT):
lb_pool_member = policy_defs_load_balancer.LBPoolMemberDef(
tenant=constants.POLICY_INFRA_TENANT):
lb_pool_member = lb_defs.LBPoolMemberDef(
ip_address, port=port,
name=display_name,
weight=weight)
lb_pool_def = policy_defs_load_balancer.LBPoolDef(
lb_pool_def = lb_defs.LBPoolDef(
lb_pool_id=lb_pool_id, tenant=tenant)
lb_pool = self.policy_api.get(lb_pool_def)
lb_pool_members = lb_pool.get('members', [])
@ -444,8 +445,8 @@ class NsxPolicyLoadBalancerPoolApi(NsxPolicyResourceBase):
return lb_pool_member
def remove_pool_member(self, lb_pool_id, ip_address, port=None,
tenant=policy_constants.POLICY_INFRA_TENANT):
lb_pool_def = policy_defs_load_balancer.LBPoolDef(
tenant=constants.POLICY_INFRA_TENANT):
lb_pool_def = lb_defs.LBPoolDef(
lb_pool_id=lb_pool_id, tenant=tenant)
lb_pool = self.policy_api.get(lb_pool_def)
lb_pool_members = lb_pool.get('members', [])
@ -459,13 +460,13 @@ class NsxPolicyLoadBalancerServiceApi(NsxPolicyResourceBase):
"""NSX Policy LBService."""
@property
def entry_def(self):
return policy_defs_load_balancer.LBServiceDef
return lb_defs.LBServiceDef
def create_or_overwrite(self, name, lb_service_id=None,
description=IGNORE,
tags=IGNORE,
size=IGNORE,
tenant=policy_constants.POLICY_INFRA_TENANT):
tenant=constants.POLICY_INFRA_TENANT):
lb_service_id = self._init_obj_uuid(lb_service_id)
lb_service_def = self._init_def(
lb_service_id=lb_service_id,
@ -479,23 +480,23 @@ class NsxPolicyLoadBalancerServiceApi(NsxPolicyResourceBase):
return lb_service_id
def delete(self, lb_service_id,
tenant=policy_constants.POLICY_INFRA_TENANT):
tenant=constants.POLICY_INFRA_TENANT):
lb_service_def = self.entry_def(
lb_service_id=lb_service_id, tenant=tenant)
self.policy_api.delete(lb_service_def)
def get(self, lb_service_id, tenant=policy_constants.POLICY_INFRA_TENANT):
def get(self, lb_service_id, tenant=constants.POLICY_INFRA_TENANT):
lb_service_def = self.entry_def(
lb_service_id=lb_service_id, tenant=tenant)
return self.policy_api.get(lb_service_def)
def list(self, tenant=policy_constants.POLICY_INFRA_TENANT):
lb_service_def = policy_defs_load_balancer.LBServiceDef(tenant=tenant)
def list(self, tenant=constants.POLICY_INFRA_TENANT):
lb_service_def = lb_defs.LBServiceDef(tenant=tenant)
return self.policy_api.list(lb_service_def)['results']
def update(self, lb_service_id, name=IGNORE,
description=IGNORE, tags=IGNORE,
size=IGNORE, tenant=policy_constants.POLICY_INFRA_TENANT):
size=IGNORE, tenant=constants.POLICY_INFRA_TENANT):
self._update(lb_service_id=lb_service_id,
name=name,
description=description,
@ -505,15 +506,15 @@ class NsxPolicyLoadBalancerServiceApi(NsxPolicyResourceBase):
def get_status(self, lb_service_id):
lb_service_status_def = (
policy_defs_load_balancer.LBServiceStatisticsDef(
lb_defs.LBServiceStatisticsDef(
lb_service_id=lb_service_id,
tenant=policy_constants.POLICY_INFRA_TENANT))
tenant=constants.POLICY_INFRA_TENANT))
return self.policy_api.get(lb_service_status_def)
def get_usage(self, lb_service_id):
lb_service_status_def = policy_defs_load_balancer.LBServiceUsageDef(
lb_service_status_def = lb_defs.LBServiceUsageDef(
lb_service_id=lb_service_id,
tenant=policy_constants.POLICY_INFRA_TENANT)
tenant=constants.POLICY_INFRA_TENANT)
return self.policy_api.get(lb_service_status_def)
@ -522,7 +523,7 @@ class NsxPolicyLoadBalancerVirtualServerAPI(NsxPolicyResourceBase):
@property
def entry_def(self):
return policy_defs_load_balancer.LBVirtualServerDef
return lb_defs.LBVirtualServerDef
def create_or_overwrite(self, name, virtual_server_id=None,
description=IGNORE,
@ -533,7 +534,7 @@ class NsxPolicyLoadBalancerVirtualServerAPI(NsxPolicyResourceBase):
lb_persistence_profile_id=IGNORE,
ports=IGNORE,
server_ssl_profile_binding=IGNORE,
tenant=policy_constants.POLICY_INFRA_TENANT,
tenant=constants.POLICY_INFRA_TENANT,
tags=IGNORE):
virtual_server_id = self._init_obj_uuid(virtual_server_id)
lbvs_def = self._init_def(
@ -555,18 +556,18 @@ class NsxPolicyLoadBalancerVirtualServerAPI(NsxPolicyResourceBase):
return self.policy_api.create_or_update(lbvs_def)
def delete(self, virtual_server_id,
tenant=policy_constants.POLICY_INFRA_TENANT):
tenant=constants.POLICY_INFRA_TENANT):
lbvs_def = self.entry_def(
virtual_server_id=virtual_server_id, tenant=tenant)
self.policy_api.delete(lbvs_def)
def get(self, virtual_server_id,
tenant=policy_constants.POLICY_INFRA_TENANT):
tenant=constants.POLICY_INFRA_TENANT):
lbvs_def = self.entry_def(
virtual_server_id=virtual_server_id, tenant=tenant)
return self.policy_api.get(lbvs_def)
def list(self, tenant=policy_constants.POLICY_INFRA_TENANT):
def list(self, tenant=constants.POLICY_INFRA_TENANT):
lbvs_def = self.entry_def(tenant=tenant)
return self.policy_api.list(lbvs_def)['results']
@ -579,7 +580,7 @@ class NsxPolicyLoadBalancerVirtualServerAPI(NsxPolicyResourceBase):
ports=IGNORE,
server_ssl_profile_binding=IGNORE,
tags=IGNORE,
tenant=policy_constants.POLICY_INFRA_TENANT):
tenant=constants.POLICY_INFRA_TENANT):
self._update(
virtual_server_id=virtual_server_id,
name=name,
@ -647,7 +648,7 @@ class NsxPolicyLoadBalancerVirtualServerAPI(NsxPolicyResourceBase):
ssl_profile_path=None,
client_auth_ca_paths=None,
client_auth=None):
return policy_defs_load_balancer.ClientSSLProfileBindingDef(
return lb_defs.ClientSSLProfileBindingDef(
default_certificate_path,
sni_certificate_paths=sni_certificate_paths,
ssl_profile_path=ssl_profile_path,
@ -661,10 +662,10 @@ class NsxPolicyLoadBalancerVirtualServerAPI(NsxPolicyResourceBase):
client_auth=None):
lbvs_def = self.entry_def(
virtual_server_id=virtual_server_id,
tenant=policy_constants.POLICY_INFRA_TENANT)
tenant=constants.POLICY_INFRA_TENANT)
body = self.policy_api.get(lbvs_def)
app_profile_id = body['application_profile_path'].split('/')[-1]
client_ssl_def = policy_defs_load_balancer.ClientSSLProfileBindingDef(
client_ssl_def = lb_defs.ClientSSLProfileBindingDef(
default_certificate_path,
sni_certificate_paths=sni_certificate_paths,
ssl_profile_path=ssl_profile_path,
@ -678,17 +679,17 @@ class NsxPolicyLoadBalancerVirtualServerAPI(NsxPolicyResourceBase):
def build_lb_rule(self, actions=None, display_name=None,
match_conditions=None, match_strategy=None, phase=None):
return policy_defs_load_balancer.LBRuleDef(
return lb_defs.LBRuleDef(
actions, match_conditions, display_name, match_strategy, phase)
def add_lb_rule(self, virtual_server_id, actions=None,
name=None, match_conditions=None,
match_strategy=None, phase=None):
lb_rule = policy_defs_load_balancer.LBRuleDef(
lb_rule = lb_defs.LBRuleDef(
actions, match_conditions, name, match_strategy, phase)
lbvs_def = self.entry_def(
virtual_server_id=virtual_server_id,
tenant=policy_constants.POLICY_INFRA_TENANT)
tenant=constants.POLICY_INFRA_TENANT)
body = self.policy_api.get(lbvs_def)
app_profile_id = body['application_profile_path'].split('/')[-1]
lb_rules = body.get('rules', [])
@ -700,7 +701,7 @@ class NsxPolicyLoadBalancerVirtualServerAPI(NsxPolicyResourceBase):
def remove_lb_rule(self, virtual_server_id, lb_rule_name):
lbvs_def = self.entry_def(virtual_server_id=virtual_server_id,
tenant=policy_constants.POLICY_INFRA_TENANT)
tenant=constants.POLICY_INFRA_TENANT)
body = self.policy_api.get(lbvs_def)
app_profile_id = body['application_profile_path'].split('/')[-1]
lb_rules = body.get('rules', [])

View File

@ -19,8 +19,9 @@ import threading
from vmware_nsxlib._i18n import _
from vmware_nsxlib.v3 import exceptions
from vmware_nsxlib.v3 import policy_constants
from vmware_nsxlib.v3 import policy_defs
from vmware_nsxlib.v3.policy import constants
from vmware_nsxlib.v3.policy import core_defs
class NsxPolicyTransactionException(exceptions.NsxLibException):
@ -35,8 +36,8 @@ class NsxPolicyTransaction(object):
def __init__(self):
# For now only infra tenant is supported
self.defs = [policy_defs.TenantDef(
tenant=policy_constants.POLICY_INFRA_TENANT)]
self.defs = [core_defs.TenantDef(
tenant=constants.POLICY_INFRA_TENANT)]
self.client = None
def __enter__(self):