diff --git a/vmware_nsxlib/tests/unit/v3/policy/test_resources.py b/vmware_nsxlib/tests/unit/v3/policy/test_resources.py index f4e3da2a..cd96c672 100644 --- a/vmware_nsxlib/tests/unit/v3/policy/test_resources.py +++ b/vmware_nsxlib/tests/unit/v3/policy/test_resources.py @@ -5421,3 +5421,18 @@ class TestPolicyTier0PrefixList(NsxPolicyLibTestCase): self.assertEqual(le, prefix_entry.le) self.assertEqual(ge, prefix_entry.ge) self.assertEqual(action, prefix_entry.action) + + +class TestNsxSearch(NsxPolicyLibTestCase): + + def test_nsx_search_by_realization(self): + """Test search of resources with the specified tag.""" + with mock.patch.object(self.policy_lib.client, 'url_get') as search: + realized_id = 'xxx' + realized_type = 'RealizedLogicalSwitch' + query = ('resource_type:GenericPolicyRealizedResource AND ' + 'realization_specific_identifier:%s AND ' + 'entity_type:%s' % (realized_id, realized_type)) + self.policy_lib.search_resource_by_realized_id( + realized_id, realized_type) + search.assert_called_with('search?query=%s' % query) diff --git a/vmware_nsxlib/v3/policy/__init__.py b/vmware_nsxlib/v3/policy/__init__.py index fa23d62f..8144687f 100644 --- a/vmware_nsxlib/v3/policy/__init__.py +++ b/vmware_nsxlib/v3/policy/__init__.py @@ -20,8 +20,10 @@ from oslo_log import log from vmware_nsxlib import v3 from vmware_nsxlib.v3 import client +from vmware_nsxlib.v3 import exceptions from vmware_nsxlib.v3 import lib from vmware_nsxlib.v3 import nsx_constants +from vmware_nsxlib.v3 import utils as lib_utils from vmware_nsxlib.v3.policy import core_defs from vmware_nsxlib.v3.policy import core_resources @@ -196,3 +198,28 @@ class NsxPolicyLib(lib.NsxLibBase): "value": "0 */%d * * * *" % interval_min} body = {"keyValuePairs": [realization_config]} self.client.patch("system-config", body) + + def search_resource_by_realized_id(self, realized_id, realized_type): + """Search resources by a realized id & type + + :returns: a list of resource pathes matching the realized id and type. + """ + if not realized_type or not realized_id: + raise exceptions.NsxSearchInvalidQuery( + reason=_("Resource type or id was not specified")) + query = ('resource_type:GenericPolicyRealizedResource AND ' + 'realization_specific_identifier:%s AND ' + 'entity_type:%s' % (realized_id, realized_type)) + url = "search?query=%s" % query + + # Retry the search on case of error + @lib_utils.retry_upon_exception(exceptions.NsxSearchError, + max_attempts=self.client.max_attempts) + def do_search(url): + return self.client.url_get(url) + + results = do_search(url) + pathes = [] + for resource in results['results']: + pathes.extend(resource.get('intent_paths', [])) + return pathes