A common library that interfaces with VMware NSX.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

4144 lines
170 KiB

  1. # Copyright 2017 VMware, Inc.
  2. # All Rights Reserved
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License"); you may
  5. # not use this file except in compliance with the License. You may obtain
  6. # a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  12. # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  13. # License for the specific language governing permissions and limitations
  14. # under the License.
  15. #
  16. import abc
  17. import sys
  18. import decorator
  19. import eventlet
  20. from oslo_log import log as logging
  21. from oslo_utils import uuidutils
  22. import six
  23. from vmware_nsxlib._i18n import _
  24. from vmware_nsxlib.v3 import exceptions
  25. from vmware_nsxlib.v3 import nsx_constants
  26. from vmware_nsxlib.v3 import utils
  27. from vmware_nsxlib.v3.policy import constants
  28. from vmware_nsxlib.v3.policy import core_defs
  29. from vmware_nsxlib.v3.policy import transaction as trans
  30. from vmware_nsxlib.v3.policy import utils as p_utils
  31. LOG = logging.getLogger(__name__)
  32. # Sentitel object to indicate unspecified attribute value
  33. # None value in attribute would indicate "unset" functionality,
  34. # while "ignore" means that the value not be present in request
  35. # body
  36. IGNORE = object()
  37. DEFAULT_MAP_ID = 'DEFAULT'
  38. @decorator.decorator
  39. def check_allowed_passthrough(f, *args, **kwargs):
  40. resource_api = args[0]
  41. if not resource_api.nsx_api:
  42. caller = sys._getframe(1).f_code.co_name
  43. LOG.error("%s failed: Passthrough api is disabled", caller)
  44. return
  45. return f(*args, **kwargs)
  46. @six.add_metaclass(abc.ABCMeta)
  47. class NsxPolicyResourceBase(object):
  48. """Abstract class for NSX policy resources
  49. declaring the basic apis each policy resource should support,
  50. and implement some common apis and utilities
  51. """
  52. SINGLE_ENTRY_ID = 'entry'
  53. def __init__(self, policy_api, nsx_api, version, nsxlib_config):
  54. self.policy_api = policy_api
  55. self.nsx_api = nsx_api
  56. self.version = version
  57. self.nsxlib_config = nsxlib_config
  58. @property
  59. def entry_def(self):
  60. pass
  61. @abc.abstractmethod
  62. def list(self, *args, **kwargs):
  63. pass
  64. @abc.abstractmethod
  65. def get(self, uuid, *args, **kwargs):
  66. pass
  67. @abc.abstractmethod
  68. def delete(self, uuid, *args, **kwargs):
  69. pass
  70. @abc.abstractmethod
  71. def create_or_overwrite(self, *args, **kwargs):
  72. """Create new or overwrite existing resource
  73. Create would list keys and attributes, set defaults and
  74. perform necessary validations.
  75. If object with same IDs exists on backend, it will
  76. be overridden.
  77. """
  78. pass
  79. @abc.abstractmethod
  80. def update(self, *args, **kwargs):
  81. """Update existing resource
  82. Update is different from create since it specifies only
  83. attributes that need changing. Non-updateble attributes
  84. should not be listed as update arguments.
  85. Create_or_overwrite is not
  86. good enough since it sets defaults, and thus would return
  87. non-default values to default if not specified in kwargs.
  88. """
  89. pass
  90. def _any_arg_set(self, *args):
  91. """Helper to identify if user specified any of args"""
  92. for arg in args:
  93. if arg != IGNORE:
  94. return True
  95. return False
  96. def _get_user_args(self, **kwargs):
  97. return {key: value for key, value in kwargs.items()
  98. if value != IGNORE}
  99. def _init_def(self, **kwargs):
  100. """Helper for update function - ignore attrs without explicit value"""
  101. args = self._get_user_args(**kwargs)
  102. return self.entry_def(nsx_version=self.version, **args)
  103. def _init_parent_def(self, **kwargs):
  104. """Helper for update function - ignore attrs without explicit value"""
  105. args = self._get_user_args(**kwargs)
  106. return self.parent_entry_def(**args)
  107. def _get_and_update_def(self, **kwargs):
  108. """Helper for update function - ignore attrs without explicit value"""
  109. args = self._get_user_args(**kwargs)
  110. resource_def = self.entry_def(nsx_version=self.version, **args)
  111. body = self.policy_api.get(resource_def)
  112. if body:
  113. resource_def.set_obj_dict(body)
  114. return resource_def
  115. def _update(self, allow_partial_updates=True, **kwargs):
  116. """Helper for update function - ignore attrs without explicit value"""
  117. if (allow_partial_updates and
  118. self.policy_api.partial_updates_supported()):
  119. policy_def = self._init_def(**kwargs)
  120. partial_updates = True
  121. else:
  122. policy_def = self._get_and_update_def(**kwargs)
  123. partial_updates = False
  124. if policy_def.bodyless():
  125. # Nothing to update - only keys provided in kwargs
  126. return
  127. self.policy_api.create_or_update(
  128. policy_def, partial_updates=partial_updates)
  129. @staticmethod
  130. def _init_obj_uuid(obj_uuid):
  131. if not obj_uuid:
  132. # generate a random id
  133. obj_uuid = str(uuidutils.generate_uuid())
  134. return obj_uuid
  135. def _canonize_name(self, name):
  136. # remove spaces and slashes from objects names
  137. return name.replace(' ', '_').replace('/', '_')
  138. def get_by_name(self, name, *args, **kwargs):
  139. # Return first match by name
  140. resources_list = self.list(*args, **kwargs)
  141. for obj in resources_list:
  142. if obj.get('display_name') == name:
  143. return obj
  144. def _get_realization_info(self, resource_def, entity_type=None,
  145. silent=False):
  146. entities = []
  147. try:
  148. path = resource_def.get_resource_full_path()
  149. entities = self.policy_api.get_realized_entities(
  150. path, silent=silent)
  151. if entities:
  152. if entity_type:
  153. # look for the entry with the right entity_type
  154. for entity in entities:
  155. if entity.get('entity_type') == entity_type:
  156. return entity
  157. else:
  158. # return the first realization entry
  159. # (Useful for resources with single realization entity)
  160. return entities[0]
  161. except exceptions.ResourceNotFound:
  162. pass
  163. # If we got here the resource was not deployed yet
  164. if silent:
  165. LOG.debug("No realization info found for %(path)s type %(type)s: "
  166. "%(entities)s",
  167. {"path": path, "type": entity_type,
  168. "entities": entities})
  169. else:
  170. LOG.warning("No realization info found for %(path)s type %(type)s",
  171. {"path": path, "type": entity_type})
  172. def _get_realized_state(self, resource_def, entity_type=None,
  173. realization_info=None):
  174. if not realization_info:
  175. realization_info = self._get_realization_info(
  176. resource_def, entity_type=entity_type)
  177. if realization_info and realization_info.get('state'):
  178. return realization_info['state']
  179. def _get_realized_id(self, resource_def, entity_type=None,
  180. realization_info=None):
  181. if not realization_info:
  182. realization_info = self._get_realization_info(
  183. resource_def, entity_type=entity_type)
  184. if (realization_info and
  185. realization_info.get('realization_specific_identifier')):
  186. return realization_info['realization_specific_identifier']
  187. def _get_realization_error_message_and_code(self, info):
  188. error_msg = 'unknown'
  189. error_code = None
  190. related_error_codes = []
  191. if info.get('alarms'):
  192. alarm = info['alarms'][0]
  193. error_msg = alarm.get('message')
  194. if alarm.get('error_details'):
  195. error_code = alarm['error_details'].get('error_code')
  196. if alarm['error_details'].get('related_errors'):
  197. related = alarm['error_details']['related_errors']
  198. for err_obj in related:
  199. error_msg = '%s: %s' % (error_msg,
  200. err_obj.get('error_message'))
  201. if err_obj.get('error_code'):
  202. related_error_codes.append(err_obj['error_code'])
  203. return error_msg, error_code, related_error_codes
  204. def _wait_until_realized(self, resource_def, entity_type=None,
  205. sleep=None, max_attempts=None):
  206. """Wait until the resource has been realized
  207. Return the realization info, or raise an error
  208. """
  209. if sleep is None:
  210. sleep = self.nsxlib_config.realization_wait_sec
  211. if max_attempts is None:
  212. max_attempts = self.nsxlib_config.realization_max_attempts
  213. @utils.retry_upon_none_result(max_attempts, delay=sleep, random=True)
  214. def get_info():
  215. info = self._get_realization_info(
  216. resource_def, entity_type=entity_type, silent=True)
  217. if info:
  218. if info['state'] == constants.STATE_REALIZED:
  219. return info
  220. if info['state'] == constants.STATE_ERROR:
  221. error_msg, error_code, related_error_codes = \
  222. self._get_realization_error_message_and_code(info)
  223. raise exceptions.RealizationErrorStateError(
  224. resource_type=resource_def.resource_type(),
  225. resource_id=resource_def.get_id(),
  226. error=error_msg, error_code=error_code,
  227. related_error_codes=related_error_codes)
  228. try:
  229. return get_info()
  230. except exceptions.RealizationError as e:
  231. raise e
  232. except Exception:
  233. # max retries reached
  234. raise exceptions.RealizationTimeoutError(
  235. resource_type=resource_def.resource_type(),
  236. resource_id=resource_def.get_id(),
  237. attempts=max_attempts,
  238. sleep=sleep)
  239. @check_allowed_passthrough
  240. def _get_realized_id_using_search(self, policy_resource_path,
  241. mp_resource_type, resource_def=None,
  242. sleep=None, max_attempts=None):
  243. """Wait until the policy path will be found using search api
  244. And return the NSX ID of the MP resource that was found
  245. """
  246. if sleep is None:
  247. sleep = self.nsxlib_config.realization_wait_sec
  248. if max_attempts is None:
  249. max_attempts = self.nsxlib_config.realization_max_attempts
  250. check_status = 3
  251. tag = [{'scope': 'policyPath',
  252. 'tag': utils.escape_tag_data(policy_resource_path)}]
  253. test_num = 0
  254. while test_num < max_attempts:
  255. # Use the search api to find the realization id of this entity.
  256. resources = self.nsx_api.search_by_tags(
  257. tags=tag, resource_type=mp_resource_type)['results']
  258. if resources:
  259. return resources[0]['id']
  260. # From time to time also check the Policy realization state,
  261. # as if it is in ERROR waiting should be avoided.
  262. if resource_def and test_num % check_status == (check_status - 1):
  263. info = self._get_realization_info(resource_def)
  264. if info and info['state'] == constants.STATE_ERROR:
  265. error_msg, error_code, related_error_codes = \
  266. self._get_realization_error_message_and_code(info)
  267. raise exceptions.RealizationErrorStateError(
  268. resource_type=resource_def.resource_type(),
  269. resource_id=resource_def.get_id(),
  270. error=error_msg, error_code=error_code,
  271. related_error_codes=related_error_codes)
  272. if (info and info['state'] == constants.STATE_REALIZED and
  273. info.get('realization_specific_identifier')):
  274. LOG.warning("Realization ID for %s was not found via "
  275. "search api although it was realized",
  276. policy_resource_path)
  277. return info['realization_specific_identifier']
  278. eventlet.sleep(sleep)
  279. test_num += 1
  280. # max retries reached
  281. raise exceptions.RealizationTimeoutError(
  282. resource_type=mp_resource_type,
  283. resource_id=policy_resource_path,
  284. attempts=max_attempts,
  285. sleep=sleep)
  286. def _get_extended_attr_from_realized_info(self, realization_info,
  287. requested_attr):
  288. # Returns a list. In case a single value is expected,
  289. # caller must extract the first index to retrieve the value
  290. if realization_info:
  291. try:
  292. for attr in realization_info.get('extended_attributes', []):
  293. if attr.get('key') == requested_attr:
  294. return attr.get('values')
  295. except IndexError:
  296. return
  297. def _list(self, obj_def):
  298. return self.policy_api.list(obj_def).get('results', [])
  299. def _create_or_store(self, policy_def, child_def=None):
  300. transaction = trans.NsxPolicyTransaction.get_current()
  301. if transaction:
  302. # Store this def for batch apply for this transaction
  303. transaction.store_def(policy_def, self.policy_api.client)
  304. if child_def and not policy_def.mandatory_child_def:
  305. transaction.store_def(child_def, self.policy_api.client)
  306. else:
  307. # No transaction - apply now
  308. # in case the same object was just deleted, create may need to
  309. # be retried
  310. @utils.retry_upon_exception(
  311. exceptions.NsxPendingDelete,
  312. max_attempts=self.policy_api.client.max_attempts)
  313. def _do_create_with_retry():
  314. if child_def:
  315. self.policy_api.create_with_parent(policy_def, child_def)
  316. else:
  317. self.policy_api.create_or_update(policy_def)
  318. _do_create_with_retry()
  319. def _delete_or_store(self, policy_def):
  320. transaction = trans.NsxPolicyTransaction.get_current()
  321. if transaction:
  322. # Mark this resource is about to be deleted
  323. policy_def.set_delete()
  324. # Set some mandatory default values to avoid failure
  325. # TODO(asarfaty): This can be removed once platform bug is fixed
  326. policy_def.set_default_mandatory_vals()
  327. # Store this def for batch apply for this transaction
  328. transaction.store_def(policy_def, self.policy_api.client)
  329. else:
  330. # No transaction - apply now
  331. self.policy_api.delete(policy_def)
  332. class NsxPolicyDomainApi(NsxPolicyResourceBase):
  333. """NSX Policy Domain."""
  334. @property
  335. def entry_def(self):
  336. return core_defs.DomainDef
  337. def create_or_overwrite(self, name, domain_id=None,
  338. description=IGNORE,
  339. tags=IGNORE,
  340. tenant=constants.POLICY_INFRA_TENANT):
  341. domain_id = self._init_obj_uuid(domain_id)
  342. domain_def = self._init_def(domain_id=domain_id,
  343. name=name,
  344. description=description,
  345. tags=tags,
  346. tenant=tenant)
  347. self._create_or_store(domain_def)
  348. return domain_id
  349. def delete(self, domain_id, tenant=constants.POLICY_INFRA_TENANT):
  350. domain_def = core_defs.DomainDef(domain_id=domain_id, tenant=tenant)
  351. self.policy_api.delete(domain_def)
  352. def get(self, domain_id, tenant=constants.POLICY_INFRA_TENANT,
  353. silent=False):
  354. domain_def = core_defs.DomainDef(domain_id=domain_id, tenant=tenant)
  355. return self.policy_api.get(domain_def, silent=silent)
  356. def list(self, tenant=constants.POLICY_INFRA_TENANT):
  357. domain_def = core_defs.DomainDef(tenant=tenant)
  358. return self._list(domain_def)
  359. def update(self, domain_id, name=IGNORE,
  360. description=IGNORE,
  361. tags=IGNORE,
  362. tenant=constants.POLICY_INFRA_TENANT):
  363. self._update(domain_id=domain_id,
  364. name=name,
  365. description=description,
  366. tags=tags,
  367. tenant=tenant)
  368. class NsxPolicyGroupApi(NsxPolicyResourceBase):
  369. """NSX Policy Group (under a Domain) with condition/s"""
  370. @property
  371. def entry_def(self):
  372. return core_defs.GroupDef
  373. def create_or_overwrite(
  374. self, name, domain_id, group_id=None,
  375. description=IGNORE,
  376. cond_val=None,
  377. cond_key=constants.CONDITION_KEY_TAG,
  378. cond_op=constants.CONDITION_OP_EQUALS,
  379. cond_member_type=constants.CONDITION_MEMBER_PORT,
  380. tags=IGNORE,
  381. tenant=constants.POLICY_INFRA_TENANT):
  382. """Create a group with/without a condition.
  383. Empty condition value will result a group with no condition.
  384. """
  385. group_id = self._init_obj_uuid(group_id)
  386. # Prepare the condition
  387. if cond_val is not None:
  388. condition = core_defs.Condition(value=cond_val,
  389. key=cond_key,
  390. operator=cond_op,
  391. member_type=cond_member_type)
  392. conditions = [condition]
  393. else:
  394. conditions = []
  395. group_def = self._init_def(domain_id=domain_id,
  396. group_id=group_id,
  397. name=name,
  398. description=description,
  399. conditions=conditions,
  400. tags=tags,
  401. tenant=tenant)
  402. self._create_or_store(group_def)
  403. return group_id
  404. def build_condition(
  405. self, cond_val=None,
  406. cond_key=constants.CONDITION_KEY_TAG,
  407. cond_op=constants.CONDITION_OP_EQUALS,
  408. cond_member_type=constants.CONDITION_MEMBER_PORT):
  409. return core_defs.Condition(value=cond_val,
  410. key=cond_key,
  411. operator=cond_op,
  412. member_type=cond_member_type)
  413. def build_ip_address_expression(self, ip_addresses):
  414. return core_defs.IPAddressExpression(ip_addresses)
  415. def build_path_expression(self, paths):
  416. return core_defs.PathExpression(paths)
  417. def build_union_condition(self, operator=constants.CONDITION_OP_OR,
  418. conditions=None):
  419. expressions = []
  420. for cond in conditions:
  421. if len(expressions):
  422. expressions.append(core_defs.ConjunctionOperator(
  423. operator=operator))
  424. expressions.append(cond)
  425. return expressions
  426. def build_nested_condition(
  427. self, operator=constants.CONDITION_OP_AND,
  428. conditions=None):
  429. expressions = self.build_union_condition(
  430. operator=operator, conditions=conditions)
  431. return core_defs.NestedExpression(expressions=expressions)
  432. def create_or_overwrite_with_conditions(
  433. self, name, domain_id, group_id=None,
  434. description=IGNORE,
  435. conditions=IGNORE, tags=IGNORE,
  436. tenant=constants.POLICY_INFRA_TENANT):
  437. """Create a group with a list of conditions.
  438. To build the conditions in the list, build_condition
  439. or build_nested_condition can be used
  440. """
  441. group_id = self._init_obj_uuid(group_id)
  442. if not conditions:
  443. conditions = []
  444. group_def = self._init_def(domain_id=domain_id,
  445. group_id=group_id,
  446. name=name,
  447. description=description,
  448. conditions=conditions,
  449. tags=tags,
  450. tenant=tenant)
  451. self._create_or_store(group_def)
  452. return group_id
  453. def delete(self, domain_id, group_id,
  454. tenant=constants.POLICY_INFRA_TENANT):
  455. group_def = core_defs.GroupDef(domain_id=domain_id,
  456. group_id=group_id,
  457. tenant=tenant)
  458. self.policy_api.delete(group_def)
  459. def get(self, domain_id, group_id,
  460. tenant=constants.POLICY_INFRA_TENANT, silent=False):
  461. group_def = core_defs.GroupDef(domain_id=domain_id,
  462. group_id=group_id,
  463. tenant=tenant)
  464. return self.policy_api.get(group_def, silent=silent)
  465. def list(self, domain_id,
  466. tenant=constants.POLICY_INFRA_TENANT):
  467. """List all the groups of a specific domain."""
  468. group_def = core_defs.GroupDef(domain_id=domain_id,
  469. tenant=tenant)
  470. return self._list(group_def)
  471. def get_by_name(self, domain_id, name,
  472. tenant=constants.POLICY_INFRA_TENANT):
  473. """Return first group matched by name of this domain"""
  474. return super(NsxPolicyGroupApi, self).get_by_name(name, domain_id,
  475. tenant=tenant)
  476. def update(self, domain_id, group_id,
  477. name=IGNORE, description=IGNORE,
  478. tags=IGNORE, tenant=constants.POLICY_INFRA_TENANT):
  479. self._update(domain_id=domain_id,
  480. group_id=group_id,
  481. name=name,
  482. description=description,
  483. tags=tags,
  484. tenant=tenant)
  485. def update_with_conditions(
  486. self, domain_id, group_id,
  487. name=IGNORE, description=IGNORE, conditions=IGNORE,
  488. tags=IGNORE, tenant=constants.POLICY_INFRA_TENANT,
  489. update_payload_cbk=None):
  490. group_def = self._init_def(domain_id=domain_id,
  491. group_id=group_id,
  492. name=name,
  493. description=description,
  494. conditions=conditions,
  495. tags=tags,
  496. tenant=tenant)
  497. group_path = group_def.get_resource_path()
  498. @utils.retry_upon_exception(
  499. exceptions.StaleRevision,
  500. max_attempts=self.policy_api.client.max_attempts)
  501. def _update():
  502. # Get the current data of group
  503. group = self.policy_api.get(group_def)
  504. if update_payload_cbk:
  505. # The update_payload_cbk function takes two arguments.
  506. # The first one is the result from the internal GET request.
  507. # The second one is a dict of user-provided attributes,
  508. # which can be changed inside the callback function and
  509. # used as the new payload for the following PUT request.
  510. # For example, users want to combine the new conditions
  511. # passed to update_with_conditions() with the original
  512. # conditions retrieved from the internal GET request
  513. # instead of overriding the original conditions.
  514. update_payload_cbk(group, group_def.attrs)
  515. group_def.set_obj_dict(group)
  516. body = group_def.get_obj_dict()
  517. # Update the entire group at the NSX
  518. self.policy_api.client.update(group_path, body)
  519. _update()
  520. def get_realized_state(self, domain_id, group_id, entity_type=None,
  521. tenant=constants.POLICY_INFRA_TENANT,
  522. realization_info=None):
  523. group_def = core_defs.GroupDef(domain_id=domain_id,
  524. group_id=group_id,
  525. tenant=tenant)
  526. return self._get_realized_state(group_def, entity_type=entity_type,
  527. realization_info=realization_info)
  528. def get_realized_id(self, domain_id, group_id, entity_type=None,
  529. tenant=constants.POLICY_INFRA_TENANT,
  530. realization_info=None):
  531. group_def = core_defs.GroupDef(domain_id=domain_id,
  532. group_id=group_id,
  533. tenant=tenant)
  534. return self._get_realized_id(group_def, entity_type=entity_type,
  535. realization_info=realization_info)
  536. def get_realization_info(self, domain_id, group_id, entity_type=None,
  537. silent=False,
  538. tenant=constants.POLICY_INFRA_TENANT):
  539. group_def = core_defs.GroupDef(domain_id=domain_id,
  540. group_id=group_id,
  541. tenant=tenant)
  542. return self._get_realization_info(group_def, entity_type=entity_type,
  543. silent=silent)
  544. def get_path(self, domain_id, group_id,
  545. tenant=constants.POLICY_INFRA_TENANT):
  546. group_def = self.entry_def(domain_id=domain_id,
  547. group_id=group_id,
  548. tenant=tenant)
  549. return group_def.get_resource_full_path()
  550. def wait_until_realized(self, domain_id, group_id,
  551. entity_type=None,
  552. tenant=constants.POLICY_INFRA_TENANT,
  553. sleep=None, max_attempts=None):
  554. group_def = self.entry_def(domain_id=domain_id, group_id=group_id,
  555. tenant=tenant)
  556. return self._wait_until_realized(group_def, entity_type=entity_type,
  557. sleep=sleep,
  558. max_attempts=max_attempts)
  559. class NsxPolicyServiceBase(NsxPolicyResourceBase):
  560. """Base class for NSX Policy Service with a single entry.
  561. Note the nsx-policy backend supports multiple service entries per service.
  562. At this point this is not supported here.
  563. """
  564. @property
  565. def parent_entry_def(self):
  566. return core_defs.ServiceDef
  567. def delete(self, service_id,
  568. tenant=constants.POLICY_INFRA_TENANT):
  569. """Delete the service with all its entries"""
  570. service_def = core_defs.ServiceDef(service_id=service_id,
  571. tenant=tenant)
  572. self.policy_api.delete(service_def)
  573. def get(self, service_id,
  574. tenant=constants.POLICY_INFRA_TENANT, silent=False):
  575. service_def = core_defs.ServiceDef(service_id=service_id,
  576. tenant=tenant)
  577. return self.policy_api.get(service_def, silent=silent)
  578. def list(self, tenant=constants.POLICY_INFRA_TENANT):
  579. service_def = core_defs.ServiceDef(tenant=tenant)
  580. return self._list(service_def)
  581. def get_realized_state(self, service_id, entity_type=None,
  582. tenant=constants.POLICY_INFRA_TENANT,
  583. realization_info=None):
  584. service_def = core_defs.ServiceDef(service_id=service_id,
  585. tenant=tenant)
  586. return self._get_realized_state(service_def, entity_type=entity_type,
  587. realization_info=realization_info)
  588. def get_realized_id(self, service_id, entity_type=None,
  589. tenant=constants.POLICY_INFRA_TENANT,
  590. realization_info=None):
  591. service_def = core_defs.ServiceDef(service_id=service_id,
  592. tenant=tenant)
  593. return self._get_realized_id(service_def, entity_type=entity_type,
  594. realization_info=realization_info)
  595. def get_realization_info(self, service_id, entity_type=None,
  596. silent=False,
  597. tenant=constants.POLICY_INFRA_TENANT):
  598. service_def = core_defs.ServiceDef(service_id=service_id,
  599. tenant=tenant)
  600. return self._get_realization_info(service_def,
  601. entity_type=entity_type,
  602. silent=silent)
  603. class NsxPolicyL4ServiceApi(NsxPolicyServiceBase):
  604. """NSX Policy Service with a single L4 service entry.
  605. Note the nsx-policy backend supports multiple service entries per service.
  606. At this point this is not supported here.
  607. """
  608. @property
  609. def entry_def(self):
  610. return core_defs.L4ServiceEntryDef
  611. def create_or_overwrite(self, name, service_id=None,
  612. description=IGNORE,
  613. protocol=constants.TCP,
  614. dest_ports=IGNORE,
  615. source_ports=IGNORE,
  616. tags=IGNORE,
  617. tenant=constants.POLICY_INFRA_TENANT):
  618. service_id = self._init_obj_uuid(service_id)
  619. service_def = self._init_parent_def(service_id=service_id,
  620. name=name,
  621. description=description,
  622. tags=tags,
  623. tenant=tenant)
  624. entry_def = self._init_def(service_id=service_id,
  625. entry_id=self.SINGLE_ENTRY_ID,
  626. name=self.SINGLE_ENTRY_ID,
  627. protocol=protocol,
  628. dest_ports=dest_ports,
  629. source_ports=source_ports,
  630. tenant=tenant)
  631. service_def.mandatory_child_def = entry_def
  632. self._create_or_store(service_def, entry_def)
  633. return service_id
  634. def update(self, service_id,
  635. name=IGNORE, description=IGNORE,
  636. protocol=IGNORE, dest_ports=IGNORE, source_ports=IGNORE,
  637. tags=IGNORE, tenant=constants.POLICY_INFRA_TENANT):
  638. parent_def = self._init_parent_def(
  639. service_id=service_id,
  640. name=name,
  641. description=description,
  642. tags=tags,
  643. tenant=tenant)
  644. entry_def = self._get_and_update_def(
  645. service_id=service_id,
  646. entry_id=self.SINGLE_ENTRY_ID,
  647. protocol=protocol,
  648. dest_ports=dest_ports,
  649. source_ports=source_ports,
  650. tenant=tenant)
  651. self.policy_api.create_with_parent(parent_def, entry_def)
  652. def build_entry(self, name, service_id, entry_id,
  653. description=None, protocol=None,
  654. dest_ports=None, source_ports=None,
  655. tags=None, tenant=constants.POLICY_INFRA_TENANT):
  656. return self._init_def(service_id=service_id,
  657. entry_id=entry_id,
  658. name=name,
  659. description=description,
  660. protocol=protocol,
  661. dest_ports=dest_ports,
  662. source_ports=source_ports,
  663. tags=tags,
  664. tenant=tenant)
  665. class NsxPolicyIcmpServiceApi(NsxPolicyServiceBase):
  666. """NSX Policy Service with a single ICMP service entry.
  667. Note the nsx-policy backend supports multiple service entries per service.
  668. At this point this is not supported here.
  669. """
  670. @property
  671. def entry_def(self):
  672. return core_defs.IcmpServiceEntryDef
  673. def create_or_overwrite(self, name, service_id=None,
  674. description=IGNORE,
  675. version=4, icmp_type=IGNORE, icmp_code=IGNORE,
  676. tags=IGNORE,
  677. tenant=constants.POLICY_INFRA_TENANT):
  678. service_id = self._init_obj_uuid(service_id)
  679. service_def = self._init_parent_def(service_id=service_id,
  680. name=name,
  681. description=description,
  682. tags=tags,
  683. tenant=tenant)
  684. entry_def = self._init_def(
  685. service_id=service_id,
  686. entry_id=self.SINGLE_ENTRY_ID,
  687. name=self.SINGLE_ENTRY_ID,
  688. version=version,
  689. icmp_type=icmp_type,
  690. icmp_code=icmp_code,
  691. tenant=tenant)
  692. service_def.mandatory_child_def = entry_def
  693. self._create_or_store(service_def, entry_def)
  694. return service_id
  695. def update(self, service_id,
  696. name=IGNORE, description=IGNORE,
  697. version=IGNORE, icmp_type=IGNORE,
  698. icmp_code=IGNORE, tags=IGNORE,
  699. tenant=constants.POLICY_INFRA_TENANT):
  700. parent_def = self._init_parent_def(
  701. service_id=service_id,
  702. name=name,
  703. description=description,
  704. tags=tags,
  705. tenant=tenant)
  706. entry_def = self._get_and_update_def(
  707. service_id=service_id,
  708. entry_id=self.SINGLE_ENTRY_ID,
  709. version=version,
  710. icmp_type=icmp_type,
  711. icmp_code=icmp_code,
  712. tenant=tenant)
  713. return self.policy_api.create_with_parent(parent_def, entry_def)
  714. def build_entry(self, name, service_id, entry_id,
  715. description=None, version=4,
  716. icmp_type=None, icmp_code=None,
  717. tags=None, tenant=constants.POLICY_INFRA_TENANT):
  718. return self._init_def(service_id=service_id,
  719. entry_id=entry_id,
  720. name=name,
  721. description=description,
  722. version=version,
  723. icmp_type=icmp_type,
  724. icmp_code=icmp_code,
  725. tags=tags,
  726. tenant=tenant)
  727. class NsxPolicyIPProtocolServiceApi(NsxPolicyServiceBase):
  728. """NSX Policy Service with a single IPProtocol service entry.
  729. Note the nsx-policy backend supports multiple service entries per service.
  730. At this point this is not supported here.
  731. """
  732. @property
  733. def entry_def(self):
  734. return core_defs.IPProtocolServiceEntryDef
  735. def create_or_overwrite(self, name, service_id=None,
  736. description=IGNORE,
  737. protocol_number=IGNORE, tags=IGNORE,
  738. tenant=constants.POLICY_INFRA_TENANT):
  739. service_id = self._init_obj_uuid(service_id)
  740. service_def = self._init_parent_def(service_id=service_id,
  741. name=name,
  742. description=description,
  743. tags=tags,
  744. tenant=tenant)
  745. entry_def = self._init_def(
  746. service_id=service_id,
  747. entry_id=self.SINGLE_ENTRY_ID,
  748. name=self.SINGLE_ENTRY_ID,
  749. protocol_number=protocol_number,
  750. tenant=tenant)
  751. service_def.mandatory_child_def = entry_def
  752. self._create_or_store(service_def, entry_def)
  753. return service_id
  754. def update(self, service_id,
  755. name=IGNORE, description=IGNORE,
  756. protocol_number=IGNORE, tags=IGNORE,
  757. tenant=constants.POLICY_INFRA_TENANT):
  758. parent_def = self._init_parent_def(
  759. service_id=service_id,
  760. name=name,
  761. description=description,
  762. tags=tags,
  763. tenant=tenant)
  764. entry_def = self._get_and_update_def(
  765. service_id=service_id,
  766. entry_id=self.SINGLE_ENTRY_ID,
  767. protocol_number=protocol_number,
  768. tenant=tenant)
  769. return self.policy_api.create_with_parent(parent_def, entry_def)
  770. def build_entry(self, name, service_id, entry_id,
  771. description=None, protocol_number=None,
  772. tags=None, tenant=constants.POLICY_INFRA_TENANT):
  773. return self._init_def(service_id=service_id,
  774. entry_id=entry_id,
  775. name=name,
  776. protocol_number=protocol_number,
  777. tags=tags,
  778. tenant=tenant)
  779. class NsxPolicyMixedServiceApi(NsxPolicyServiceBase):
  780. """NSX Policy Service with mixed service entries."""
  781. def create_or_overwrite(self, name, service_id,
  782. description=IGNORE,
  783. entries=IGNORE,
  784. tags=IGNORE,
  785. tenant=constants.POLICY_INFRA_TENANT):
  786. service_def = self._init_parent_def(service_id=service_id,
  787. name=name,
  788. description=description,
  789. entries=entries,
  790. tags=tags,
  791. tenant=tenant)
  792. if entries != IGNORE:
  793. self._create_or_store(service_def, entries)
  794. else:
  795. self._create_or_store(service_def)
  796. return service_id
  797. def update(self, service_id,
  798. name=IGNORE, description=IGNORE,
  799. entries=IGNORE, tags=IGNORE,
  800. tenant=constants.POLICY_INFRA_TENANT):
  801. parent_def = self._init_parent_def(
  802. service_id=service_id,
  803. name=name,
  804. description=description,
  805. tags=tags,
  806. tenant=tenant)
  807. if entries != IGNORE:
  808. self.policy_api.create_with_parent(parent_def, entries)
  809. else:
  810. self.policy_api.create_or_update(parent_def)
  811. class NsxPolicyTier1Api(NsxPolicyResourceBase):
  812. """NSX Tier1 API """
  813. LOCALE_SERVICE_SUFF = '-0'
  814. @property
  815. def entry_def(self):
  816. return core_defs.Tier1Def
  817. def build_route_advertisement(self, static_routes=False, subnets=False,
  818. nat=False, lb_vip=False, lb_snat=False,
  819. ipsec_endpoints=False):
  820. return core_defs.RouteAdvertisement(static_routes=static_routes,
  821. subnets=subnets,
  822. nat=nat,
  823. lb_vip=lb_vip,
  824. lb_snat=lb_snat,
  825. ipsec_endpoints=ipsec_endpoints)
  826. def create_or_overwrite(self, name, tier1_id=None,
  827. description=IGNORE,
  828. tier0=IGNORE,
  829. force_whitelisting=IGNORE,
  830. failover_mode=constants.NON_PREEMPTIVE,
  831. route_advertisement=IGNORE,
  832. dhcp_config=IGNORE,
  833. disable_firewall=IGNORE,
  834. ipv6_ndra_profile_id=IGNORE,
  835. tags=IGNORE,
  836. tenant=constants.POLICY_INFRA_TENANT):
  837. tier1_id = self._init_obj_uuid(tier1_id)
  838. tier1_def = self._init_def(tier1_id=tier1_id,
  839. name=name,
  840. description=description,
  841. tier0=tier0,
  842. force_whitelisting=force_whitelisting,
  843. tags=tags,
  844. failover_mode=failover_mode,
  845. route_advertisement=route_advertisement,
  846. dhcp_config=dhcp_config,
  847. disable_firewall=disable_firewall,
  848. ipv6_ndra_profile_id=ipv6_ndra_profile_id,
  849. tenant=tenant)
  850. self._create_or_store(tier1_def)
  851. return tier1_id
  852. def delete(self, tier1_id, tenant=constants.POLICY_INFRA_TENANT):
  853. tier1_def = self.entry_def(tier1_id=tier1_id, tenant=tenant)
  854. self.policy_api.delete(tier1_def)
  855. def get(self, tier1_id, tenant=constants.POLICY_INFRA_TENANT,
  856. silent=False):
  857. tier1_def = self.entry_def(tier1_id=tier1_id, tenant=tenant)
  858. return self.policy_api.get(tier1_def, silent=silent)
  859. def get_path(self, tier1_id, tenant=constants.POLICY_INFRA_TENANT):
  860. tier1_def = self.entry_def(tier1_id=tier1_id, tenant=tenant)
  861. return tier1_def.get_resource_full_path()
  862. def list(self, tenant=constants.POLICY_INFRA_TENANT):
  863. tier1_def = self.entry_def(tenant=tenant)
  864. return self._list(tier1_def)
  865. def update(self, tier1_id, name=IGNORE, description=IGNORE,
  866. force_whitelisting=IGNORE,
  867. failover_mode=IGNORE, tier0=IGNORE,
  868. dhcp_config=IGNORE, tags=IGNORE,
  869. enable_standby_relocation=IGNORE,
  870. disable_firewall=IGNORE,
  871. ipv6_ndra_profile_id=IGNORE,
  872. route_advertisement=IGNORE,
  873. route_advertisement_rules=IGNORE,
  874. tenant=constants.POLICY_INFRA_TENANT,
  875. current_body=None):
  876. self._update(tier1_id=tier1_id,
  877. name=name,
  878. description=description,
  879. force_whitelisting=force_whitelisting,
  880. failover_mode=failover_mode,
  881. dhcp_config=dhcp_config,
  882. tier0=tier0,
  883. enable_standby_relocation=enable_standby_relocation,
  884. disable_firewall=disable_firewall,
  885. ipv6_ndra_profile_id=ipv6_ndra_profile_id,
  886. route_advertisement=route_advertisement,
  887. route_advertisement_rules=route_advertisement_rules,
  888. tags=tags,
  889. tenant=tenant)
  890. def update_route_advertisement(
  891. self, tier1_id,
  892. static_routes=None,
  893. subnets=None,
  894. nat=None,
  895. lb_vip=None,
  896. lb_snat=None,
  897. ipsec_endpoints=None,
  898. tier0=IGNORE,
  899. tenant=constants.POLICY_INFRA_TENANT):
  900. tier1_dict = self.get(tier1_id, tenant)
  901. route_adv = self.entry_def.get_route_adv(tier1_dict)
  902. route_adv.update(static_routes=static_routes,
  903. subnets=subnets,
  904. nat=nat,
  905. lb_vip=lb_vip,
  906. lb_snat=lb_snat,
  907. ipsec_endpoints=ipsec_endpoints)
  908. self.update(tier1_id,
  909. route_advertisement=route_adv,
  910. tier0=tier0,
  911. tenant=tenant)
  912. def add_advertisement_rule(
  913. self, tier1_id, name, action=None, prefix_operator=None,
  914. route_advertisement_types=None, subnets=None,
  915. tenant=constants.POLICY_INFRA_TENANT):
  916. tier1_dict = self.get(tier1_id, tenant)
  917. adv_rules = tier1_dict.get('route_advertisement_rules', [])
  918. adv_rules = [r for r in adv_rules if r.get('name') != name]
  919. adv_rule = core_defs.RouteAdvertisementRule(
  920. name=name, action=action, prefix_operator=prefix_operator,
  921. route_advertisement_types=route_advertisement_types,
  922. subnets=subnets)
  923. adv_rules.append(adv_rule)
  924. self.update(tier1_id,
  925. route_advertisement_rules=adv_rules,
  926. tenant=tenant,
  927. current_body=tier1_dict)
  928. def remove_advertisement_rule(self, tier1_id, name,
  929. tenant=constants.POLICY_INFRA_TENANT):
  930. tier1_dict = self.get(tier1_id, tenant)
  931. adv_rules = tier1_dict.get('route_advertisement_rules', [])
  932. updated_adv_rules = [r for r in adv_rules if r.get('name') != name]
  933. if updated_adv_rules != adv_rules:
  934. self.update(tier1_id,
  935. route_advertisement_rules=updated_adv_rules,
  936. tenant=tenant,
  937. current_body=tier1_dict)
  938. def build_advertisement_rule(self, name, action=None, prefix_operator=None,
  939. route_advertisement_types=None, subnets=None):
  940. return core_defs.RouteAdvertisementRule(
  941. name=name, action=action, prefix_operator=prefix_operator,
  942. route_advertisement_types=route_advertisement_types,
  943. subnets=subnets)
  944. def update_advertisement_rules(self, tier1_id, rules, name_prefix=None,
  945. tenant=constants.POLICY_INFRA_TENANT):
  946. """Update the router advertisement rules
  947. If name_prefix is None, replace the entire list of NSX rules with the
  948. new given 'rules'.
  949. Else - delete the NSX rules with this name prefix, and add 'rules' to
  950. the rest.
  951. """
  952. tier1_dict = self.get(tier1_id, tenant)
  953. current_rules = tier1_dict.get('route_advertisement_rules', [])
  954. if name_prefix:
  955. # delete rules with this prefix:
  956. new_rules = []
  957. for rule in current_rules:
  958. if (not rule.get('name') or
  959. not rule['name'].startswith(name_prefix)):
  960. new_rules.append(rule)
  961. # add new rules
  962. new_rules.extend(rules)
  963. else:
  964. new_rules = rules
  965. self.update(tier1_id,
  966. route_advertisement_rules=new_rules,
  967. tenant=tenant,
  968. current_body=tier1_dict)
  969. @staticmethod
  970. def _locale_service_id(tier1_id):
  971. # Supporting only a single locale-service per router for now
  972. # with the same id as the router id with a constant suffix
  973. return tier1_id + NsxPolicyTier1Api.LOCALE_SERVICE_SUFF
  974. def create_locale_service(self, tier1_id,
  975. tenant=constants.POLICY_INFRA_TENANT):
  976. t1service_def = core_defs.Tier1LocaleServiceDef(
  977. tier1_id=tier1_id,
  978. service_id=self._locale_service_id(tier1_id),
  979. tenant=tenant)
  980. self._create_or_store(t1service_def)
  981. def delete_locale_service(self, tier1_id,
  982. tenant=constants.POLICY_INFRA_TENANT):
  983. t1service_def = core_defs.Tier1LocaleServiceDef(
  984. tier1_id=tier1_id,
  985. service_id=self._locale_service_id(tier1_id),
  986. tenant=tenant)
  987. self.policy_api.delete(t1service_def)
  988. def set_edge_cluster_path(self, tier1_id, edge_cluster_path,
  989. tenant=constants.POLICY_INFRA_TENANT):
  990. t1service_def = core_defs.Tier1LocaleServiceDef(
  991. tier1_id=tier1_id,
  992. service_id=self._locale_service_id(tier1_id),
  993. edge_cluster_path=edge_cluster_path,
  994. tenant=tenant)
  995. self._create_or_store(t1service_def)
  996. def remove_edge_cluster(self, tier1_id,
  997. tenant=constants.POLICY_INFRA_TENANT):
  998. """Reset the path in the locale-service (deleting it is not allowed)"""
  999. t1service_def = core_defs.Tier1LocaleServiceDef(
  1000. tier1_id=tier1_id,
  1001. service_id=self._locale_service_id(tier1_id),
  1002. edge_cluster_path="",
  1003. tenant=tenant)
  1004. self.policy_api.create_or_update(t1service_def)
  1005. def get_edge_cluster_path(self, tier1_id,
  1006. tenant=constants.POLICY_INFRA_TENANT):
  1007. t1service_def = core_defs.Tier1LocaleServiceDef(
  1008. tier1_id=tier1_id,
  1009. service_id=self._locale_service_id(tier1_id),
  1010. tenant=tenant)
  1011. try:
  1012. t1service = self.policy_api.get(t1service_def)
  1013. return t1service.get('edge_cluster_path')
  1014. except exceptions.ResourceNotFound:
  1015. return
  1016. def get_edge_cluster_path_by_searching(
  1017. self, tier1_id, tenant=constants.POLICY_INFRA_TENANT):
  1018. """Get the edge_cluster path of a Tier1 router"""
  1019. services = self.get_locale_tier1_services(tier1_id, tenant=tenant)
  1020. for srv in services:
  1021. if 'edge_cluster_path' in srv:
  1022. return srv['edge_cluster_path']
  1023. def get_locale_tier1_services(self, tier1_id,
  1024. tenant=constants.POLICY_INFRA_TENANT):
  1025. t1service_def = core_defs.Tier1LocaleServiceDef(
  1026. tier1_id=tier1_id,
  1027. tenant=constants.POLICY_INFRA_TENANT)
  1028. return self.policy_api.list(t1service_def)['results']
  1029. def add_segment_interface(self, tier1_id, interface_id, segment_id,
  1030. subnets, ipv6_ndra_profile_id=IGNORE,
  1031. tenant=constants.POLICY_INFRA_TENANT):
  1032. args = {'tier1_id': tier1_id,
  1033. 'service_id': self._locale_service_id(tier1_id),
  1034. 'interface_id': interface_id,
  1035. 'segment_id': segment_id,
  1036. 'subnets': subnets,
  1037. 'tenant': tenant}
  1038. if ipv6_ndra_profile_id != IGNORE:
  1039. args['ipv6_ndra_profile_id'] = ipv6_ndra_profile_id
  1040. t1interface_def = core_defs.Tier1InterfaceDef(**args)
  1041. self.policy_api.create_or_update(t1interface_def)
  1042. def remove_segment_interface(self, tier1_id, interface_id,
  1043. tenant=constants.POLICY_INFRA_TENANT):
  1044. t1interface_def = core_defs.Tier1InterfaceDef(
  1045. tier1_id=tier1_id,
  1046. service_id=self._locale_service_id(tier1_id),
  1047. interface_id=interface_id,
  1048. tenant=tenant)
  1049. self.policy_api.delete(t1interface_def)
  1050. def list_segment_interface(self, tier1_id,
  1051. tenant=constants.POLICY_INFRA_TENANT):
  1052. t1interface_def = core_defs.Tier1InterfaceDef(
  1053. tier1_id=tier1_id,
  1054. service_id=self._locale_service_id(tier1_id),
  1055. tenant=tenant)
  1056. return self._list(t1interface_def)
  1057. def get_realized_state(self, tier1_id, entity_type=None,
  1058. tenant=constants.POLICY_INFRA_TENANT,
  1059. realization_info=None):
  1060. tier1_def = self.entry_def(tier1_id=tier1_id, tenant=tenant)
  1061. return self._get_realized_state(tier1_def, entity_type=entity_type,
  1062. realization_info=realization_info)
  1063. def get_realized_id(self, tier1_id, entity_type=None,
  1064. tenant=constants.POLICY_INFRA_TENANT,
  1065. realization_info=None):
  1066. tier1_def = self.entry_def(tier1_id=tier1_id, tenant=tenant)
  1067. if self.nsx_api:
  1068. # Use MP search api to find the LR ID as it is faster
  1069. return self._get_realized_id_using_search(
  1070. self.get_path(tier1_id, tenant=tenant),
  1071. self.nsx_api.logical_router.resource_type,
  1072. resource_def=tier1_def)
  1073. return self._get_realized_id(tier1_def, entity_type=entity_type,
  1074. realization_info=realization_info)
  1075. def get_realization_info(self, tier1_id, entity_type=None,
  1076. silent=False,
  1077. tenant=constants.POLICY_INFRA_TENANT):
  1078. tier1_def = self.entry_def(tier1_id=tier1_id, tenant=tenant)
  1079. return self._get_realization_info(tier1_def, silent=silent)
  1080. def wait_until_realized(self, tier1_id, entity_type=None,
  1081. tenant=constants.POLICY_INFRA_TENANT,
  1082. sleep=None, max_attempts=None):
  1083. tier1_def = self.entry_def(tier1_id=tier1_id, tenant=tenant)
  1084. return self._wait_until_realized(tier1_def, entity_type=entity_type,
  1085. sleep=sleep,
  1086. max_attempts=max_attempts)
  1087. @check_allowed_passthrough
  1088. def update_transport_zone(self, tier1_id, transport_zone_id,
  1089. tenant=constants.POLICY_INFRA_TENANT):
  1090. """Use the pass-through api to update the TZ zone on the NSX router"""
  1091. realization_info = self.wait_until_realized(
  1092. tier1_id, entity_type='RealizedLogicalRouter', tenant=tenant)
  1093. nsx_router_uuid = self.get_realized_id(
  1094. tier1_id, tenant=tenant, realization_info=realization_info)
  1095. self.nsx_api.logical_router.update(
  1096. nsx_router_uuid,
  1097. transport_zone_id=transport_zone_id)
  1098. @check_allowed_passthrough
  1099. def _get_realized_downlink_port(
  1100. self, tier1_id, segment_id,
  1101. tenant=constants.POLICY_INFRA_TENANT,
  1102. sleep=None, max_attempts=None):
  1103. """Return the realized ID of a tier1 downlink port of a segment
  1104. If not found, wait until it has been realized
  1105. """
  1106. if sleep is None:
  1107. sleep = self.nsxlib_config.realization_wait_sec
  1108. if max_attempts is None:
  1109. max_attempts = self.nsxlib_config.realization_max_attempts
  1110. tier1_def = self.entry_def(tier1_id=tier1_id, tenant=tenant)
  1111. path = tier1_def.get_resource_full_path()
  1112. test_num = 0
  1113. while test_num < max_attempts:
  1114. # get all the realized resources of the tier1
  1115. entities = self.policy_api.get_realized_entities(path)
  1116. for e in entities:
  1117. # Look for router ports
  1118. if (e['entity_type'] == 'RealizedLogicalRouterPort' and
  1119. e['state'] == constants.STATE_REALIZED):
  1120. # Get the NSX port to check if its the downlink port
  1121. port = self.nsx_api.logical_router_port.get(
  1122. e['realization_specific_identifier'])
  1123. # compare the segment ID to the port display name as this
  1124. # is the way policy sets it
  1125. port_type = port.get('resource_type')
  1126. if (port_type == nsx_constants.LROUTERPORT_DOWNLINK and
  1127. segment_id in port.get('display_name', '')):
  1128. return port['id']
  1129. eventlet.sleep(sleep)
  1130. test_num += 1
  1131. raise exceptions.DetailedRealizationTimeoutError(
  1132. resource_type='Tier1',
  1133. resource_id=tier1_id,
  1134. realized_type="downlink port",
  1135. related_type="segment",
  1136. related_id=segment_id,
  1137. attempts=max_attempts,
  1138. sleep=sleep)
  1139. @check_allowed_passthrough
  1140. def set_dhcp_relay(self, tier1_id, segment_id, relay_service_uuid,
  1141. tenant=constants.POLICY_INFRA_TENANT):
  1142. """Set relay service on the nsx logical router port
  1143. Using passthrough api, as the policy api does not support this yet
  1144. """
  1145. downlink_port_id = self._get_realized_downlink_port(
  1146. tier1_id, segment_id, tenant=tenant)
  1147. self.nsx_api.logical_router_port.update(
  1148. downlink_port_id, relay_service_uuid=relay_service_uuid)
  1149. def set_standby_relocation(self, tier1_id,
  1150. enable_standby_relocation=True,
  1151. tenant=constants.POLICY_INFRA_TENANT):
  1152. """Set the flag for standby relocation on the Tier1 router
  1153. """
  1154. return self.update(tier1_id,
  1155. enable_standby_relocation=enable_standby_relocation,
  1156. tenant=tenant)
  1157. class NsxPolicyTier0Api(NsxPolicyResourceBase):
  1158. """NSX Tier0 API """
  1159. @property
  1160. def entry_def(self):
  1161. return core_defs.Tier0Def
  1162. def create_or_overwrite(self, name, tier0_id=None,
  1163. description=IGNORE,
  1164. ha_mode=constants.ACTIVE_ACTIVE,
  1165. failover_mode=constants.NON_PREEMPTIVE,
  1166. dhcp_config=IGNORE,
  1167. force_whitelisting=IGNORE,
  1168. default_rule_logging=IGNORE,
  1169. transit_subnets=IGNORE,
  1170. disable_firewall=IGNORE,
  1171. ipv6_ndra_profile_id=IGNORE,
  1172. tags=IGNORE,
  1173. tenant=constants.POLICY_INFRA_TENANT):
  1174. tier0_id = self._init_obj_uuid(tier0_id)
  1175. tier0_def = self._init_def(tier0_id=tier0_id,
  1176. name=name,
  1177. description=description,
  1178. ha_mode=ha_mode,
  1179. failover_mode=failover_mode,
  1180. dhcp_config=dhcp_config,
  1181. force_whitelisting=force_whitelisting,
  1182. default_rule_logging=default_rule_logging,
  1183. transit_subnets=transit_subnets,
  1184. disable_firewall=disable_firewall,
  1185. ipv6_ndra_profile_id=ipv6_ndra_profile_id,
  1186. tags=tags,
  1187. tenant=tenant)
  1188. self.policy_api.create_or_update(tier0_def)
  1189. return tier0_id
  1190. def delete(self, tier0_id, tenant=constants.POLICY_INFRA_TENANT):
  1191. tier0_def = self.entry_def(tier0_id=tier0_id, tenant=tenant)
  1192. self.policy_api.delete(tier0_def)
  1193. def get(self, tier0_id, tenant=constants.POLICY_INFRA_TENANT,
  1194. silent=False):
  1195. tier0_def = self.entry_def(tier0_id=tier0_id, tenant=tenant)
  1196. return self.policy_api.get(tier0_def, silent=silent)
  1197. def get_path(self, tier0_id, tenant=constants.POLICY_INFRA_TENANT):
  1198. tier0_def = self.entry_def(tier0_id=tier0_id, tenant=tenant)
  1199. return tier0_def.get_resource_full_path()
  1200. def list(self, tenant=constants.POLICY_INFRA_TENANT):
  1201. tier0_def = self.entry_def(tenant=tenant)
  1202. return self._list(tier0_def)
  1203. def update(self, tier0_id, name=IGNORE, description=IGNORE,
  1204. failover_mode=IGNORE,
  1205. dhcp_config=IGNORE,
  1206. force_whitelisting=IGNORE,
  1207. default_rule_logging=IGNORE,
  1208. transit_subnets=IGNORE,
  1209. disable_firewall=IGNORE,
  1210. ipv6_ndra_profile_id=IGNORE,
  1211. tags=IGNORE,
  1212. tenant=constants.POLICY_INFRA_TENANT):
  1213. self._update(tier0_id=tier0_id,
  1214. name=name,
  1215. description=description,
  1216. failover_mode=failover_mode,
  1217. dhcp_config=dhcp_config,
  1218. force_whitelisting=force_whitelisting,
  1219. default_rule_logging=default_rule_logging,
  1220. transit_subnets=transit_subnets,
  1221. disable_firewall=disable_firewall,
  1222. ipv6_ndra_profile_id=ipv6_ndra_profile_id,
  1223. tags=tags,
  1224. tenant=tenant)
  1225. def get_locale_services(self, tier0_id,
  1226. tenant=constants.POLICY_INFRA_TENANT):
  1227. t0service_def = core_defs.Tier0LocaleServiceDef(
  1228. tier0_id=tier0_id,
  1229. tenant=constants.POLICY_INFRA_TENANT)
  1230. return self.policy_api.list(t0service_def)['results']
  1231. def get_edge_cluster_path(self, tier0_id,
  1232. tenant=constants.POLICY_INFRA_TENANT):
  1233. """Get the edge_cluster path of a Tier0 router"""
  1234. services = self.get_locale_services(tier0_id, tenant=tenant)
  1235. for srv in services:
  1236. if 'edge_cluster_path' in srv:
  1237. return srv['edge_cluster_path']
  1238. @check_allowed_passthrough
  1239. def get_overlay_transport_zone(
  1240. self, tier0_id,
  1241. tenant=constants.POLICY_INFRA_TENANT):
  1242. """Use the pass-through api to get the TZ zone of the NSX tier0"""
  1243. realization_info = self.wait_until_realized(
  1244. tier0_id, entity_type='RealizedLogicalRouter', tenant=tenant)
  1245. nsx_router_uuid = self.get_realized_id(
  1246. tier0_id, tenant=tenant,
  1247. realization_info=realization_info)
  1248. return self.nsx_api.router.get_tier0_router_overlay_tz(
  1249. nsx_router_uuid)
  1250. def get_realized_state(self, tier0_id, entity_type=None,
  1251. tenant=constants.POLICY_INFRA_TENANT,
  1252. realization_info=None):
  1253. tier0_def = self.entry_def(tier0_id=tier0_id, tenant=tenant)
  1254. return self._get_realized_state(tier0_def, entity_type=entity_type,
  1255. realization_info=realization_info)
  1256. def get_realized_id(self, tier0_id, entity_type=None,
  1257. tenant=constants.POLICY_INFRA_TENANT,
  1258. realization_info=None):
  1259. tier0_def = self.entry_def(tier0_id=tier0_id, tenant=tenant)
  1260. return self._get_realized_id(tier0_def, entity_type=entity_type,
  1261. realization_info=realization_info)
  1262. def get_realization_info(self, tier0_id, entity_type=None,
  1263. silent=False,
  1264. tenant=constants.POLICY_INFRA_TENANT):
  1265. tier0_def = self.entry_def(tier0_id=tier0_id, tenant=tenant)
  1266. return self._get_realization_info(tier0_def, entity_type=entity_type,
  1267. silent=silent)
  1268. def wait_until_realized(self, tier0_id, entity_type=None,
  1269. tenant=constants.POLICY_INFRA_TENANT,
  1270. sleep=None, max_attempts=None):
  1271. tier0_def = self.entry_def(tier0_id=tier0_id, tenant=tenant)
  1272. return self._wait_until_realized(tier0_def, entity_type=entity_type,
  1273. sleep=sleep,
  1274. max_attempts=max_attempts)
  1275. @check_allowed_passthrough
  1276. def get_transport_zones(self, tier0_id,
  1277. tenant=constants.POLICY_INFRA_TENANT):
  1278. """Return a list of the transport zones IDs connected to the tier0
  1279. Currently this is supported only with the passthrough api
  1280. """
  1281. realization_info = self.wait_until_realized(
  1282. tier0_id, entity_type='RealizedLogicalRouter', tenant=tenant)
  1283. nsx_router_uuid = self.get_realized_id(
  1284. tier0_id, tenant=tenant,
  1285. realization_info=realization_info)
  1286. return self.nsx_api.router.get_tier0_router_tz(
  1287. nsx_router_uuid)
  1288. def _get_uplink_subnets(self, tier0_id,
  1289. tenant=constants.POLICY_INFRA_TENANT):
  1290. subnets = []
  1291. services = self.get_locale_services(tier0_id, tenant=tenant)
  1292. for srv in services:
  1293. # get the interfaces of this service
  1294. t0interface_def = core_defs.Tier0InterfaceDef(
  1295. tier0_id=tier0_id,
  1296. service_id=srv['id'],
  1297. tenant=constants.POLICY_INFRA_TENANT)
  1298. interfaces = self.policy_api.list(
  1299. t0interface_def).get('results', [])
  1300. for interface in interfaces:
  1301. if interface.get('type') == 'EXTERNAL':
  1302. subnets.extend(interface.get('subnets', []))
  1303. return subnets
  1304. def get_uplink_ips(self, tier0_id, tenant=constants.POLICY_INFRA_TENANT):
  1305. """Return a link of all uplink ips of this tier0 router"""
  1306. subnets = self._get_uplink_subnets(tier0_id, tenant=tenant)
  1307. uplink_ips = []
  1308. for subnet in subnets:
  1309. uplink_ips.extend(subnet.get('ip_addresses', []))
  1310. return uplink_ips
  1311. def get_uplink_cidrs(self, tier0_id, tenant=constants.POLICY_INFRA_TENANT):
  1312. """Return a link of all uplink cidrs of this tier0 router"""
  1313. subnets = self._get_uplink_subnets(tier0_id, tenant=tenant)
  1314. cidrs = []
  1315. for subnet in subnets:
  1316. for ip_address in subnet.get('ip_addresses'):
  1317. cidrs.append('%s/%s' % (ip_address,
  1318. subnet.get('prefix_len')))
  1319. return cidrs
  1320. class NsxPolicyTier0NatRuleApi(NsxPolicyResourceBase):
  1321. DEFAULT_NAT_ID = 'USER'
  1322. @property
  1323. def entry_def(self):
  1324. return core_defs.Tier0NatRule
  1325. def create_or_overwrite(self, name, tier0_id,
  1326. nat_id=DEFAULT_NAT_ID,
  1327. nat_rule_id=None,
  1328. description=IGNORE,
  1329. source_network=IGNORE,
  1330. destination_network=IGNORE,
  1331. translated_network=IGNORE,
  1332. firewall_match=IGNORE,
  1333. action=IGNORE,
  1334. sequence_number=IGNORE,
  1335. log=IGNORE,
  1336. tags=IGNORE,
  1337. tenant=constants.POLICY_INFRA_TENANT,
  1338. enabled=IGNORE):
  1339. nat_rule_id = self._init_obj_uuid(nat_rule_id)
  1340. nat_rule_def = self._init_def(tier0_id=tier0_id,
  1341. nat_id=nat_id,
  1342. nat_rule_id=nat_rule_id,
  1343. name=name,
  1344. description=description,
  1345. source_network=source_network,
  1346. destination_network=destination_network,
  1347. translated_network=translated_network,
  1348. firewall_match=firewall_match,
  1349. action=action,
  1350. sequence_number=sequence_number,
  1351. log=log,
  1352. tags=tags,
  1353. tenant=tenant,
  1354. enabled=enabled)
  1355. self._create_or_store(nat_rule_def)
  1356. return nat_rule_id
  1357. def delete(self, tier0_id, nat_rule_id, nat_id=DEFAULT_NAT_ID,
  1358. tenant=constants.POLICY_INFRA_TENANT):
  1359. nat_rule_def = self.entry_def(tier0_id=tier0_id, nat_id=nat_id,
  1360. nat_rule_id=nat_rule_id, tenant=tenant)
  1361. self.policy_api.delete(nat_rule_def)
  1362. def get(self, tier0_id, nat_rule_id, nat_id=DEFAULT_NAT_ID,
  1363. tenant=constants.POLICY_INFRA_TENANT):
  1364. nat_rule_def = self.entry_def(tier0_id=tier0_id, nat_id=nat_id,
  1365. nat_rule_id=nat_rule_id, tenant=tenant)
  1366. return self.policy_api.get(nat_rule_def)
  1367. def list(self, tier0_id, nat_id=DEFAULT_NAT_ID,
  1368. tenant=constants.POLICY_INFRA_TENANT):
  1369. nat_rule_def = self.entry_def(tier0_id=tier0_id, nat_id=nat_id,
  1370. tenant=tenant)
  1371. return self._list(nat_rule_def)
  1372. def update(self, tier0_id, nat_rule_id,
  1373. nat_id=DEFAULT_NAT_ID,
  1374. name=IGNORE,
  1375. description=IGNORE,
  1376. source_network=IGNORE,
  1377. destination_network=IGNORE,
  1378. translated_network=IGNORE,
  1379. action=IGNORE,
  1380. sequence_number=IGNORE,
  1381. log=IGNORE,
  1382. tags=IGNORE,
  1383. tenant=constants.POLICY_INFRA_TENANT,
  1384. enabled=IGNORE):
  1385. self._update(tier0_id=tier0_id,
  1386. nat_id=nat_id,
  1387. nat_rule_id=nat_rule_id,
  1388. name=name,
  1389. description=description,
  1390. source_network=source_network,
  1391. destination_network=destination_network,
  1392. translated_network=translated_network,
  1393. action=action,
  1394. sequence_number=sequence_number,
  1395. log=log,
  1396. tags=tags,
  1397. tenant=tenant,
  1398. enabled=enabled)
  1399. class NsxPolicyTier1NatRuleApi(NsxPolicyResourceBase):
  1400. DEFAULT_NAT_ID = 'USER'
  1401. @property
  1402. def entry_def(self):
  1403. return core_defs.Tier1NatRule
  1404. def create_or_overwrite(self, name, tier1_id,
  1405. nat_id=DEFAULT_NAT_ID,
  1406. nat_rule_id=None,
  1407. description=IGNORE,
  1408. source_network=IGNORE,
  1409. destination_network=IGNORE,
  1410. translated_network=IGNORE,
  1411. firewall_match=IGNORE,
  1412. action=IGNORE,
  1413. sequence_number=IGNORE,
  1414. log=IGNORE,
  1415. tags=IGNORE,
  1416. tenant=constants.POLICY_INFRA_TENANT,
  1417. enabled=IGNORE):
  1418. nat_rule_id = self._init_obj_uuid(nat_rule_id)
  1419. nat_rule_def = self._init_def(tier1_id=tier1_id,
  1420. nat_id=nat_id,
  1421. nat_rule_id=nat_rule_id,
  1422. name=name,
  1423. description=description,
  1424. source_network=source_network,
  1425. destination_network=destination_network,
  1426. translated_network=translated_network,
  1427. firewall_match=firewall_match,
  1428. action=action,
  1429. sequence_number=sequence_number,
  1430. log=log,
  1431. tags=tags,
  1432. tenant=tenant,
  1433. enabled=enabled)
  1434. self._create_or_store(nat_rule_def)
  1435. return nat_rule_id
  1436. def delete(self, tier1_id, nat_rule_id, nat_id=DEFAULT_NAT_ID,
  1437. tenant=constants.POLICY_INFRA_TENANT):
  1438. nat_rule_def = self.entry_def(tier1_id=tier1_id, nat_id=nat_id,
  1439. nat_rule_id=nat_rule_id, tenant=tenant)
  1440. self._delete_or_store(nat_rule_def)
  1441. def get(self, tier1_id, nat_rule_id, nat_id=DEFAULT_NAT_ID,
  1442. tenant=constants.POLICY_INFRA_TENANT):
  1443. nat_rule_def = self.entry_def(tier1_id=tier1_id, nat_id=nat_id,
  1444. nat_rule_id=nat_rule_id, tenant=tenant)
  1445. return self.policy_api.get(nat_rule_def)
  1446. def list(self, tier1_id, nat_id=DEFAULT_NAT_ID,
  1447. tenant=constants.POLICY_INFRA_TENANT):
  1448. nat_rule_def = self.entry_def(tier1_id=tier1_id, nat_id=nat_id,
  1449. tenant=tenant)
  1450. return self._list(nat_rule_def)
  1451. def update(self, tier1_id, nat_rule_id,
  1452. nat_id=DEFAULT_NAT_ID,
  1453. name=IGNORE,
  1454. description=IGNORE,
  1455. source_network=IGNORE,
  1456. destination_network=IGNORE,
  1457. translated_network=IGNORE,
  1458. action=IGNORE,
  1459. sequence_number=IGNORE,
  1460. log=IGNORE,
  1461. tags=IGNORE,
  1462. tenant=constants.POLICY_INFRA_TENANT,
  1463. enabled=IGNORE):
  1464. self._update(tier1_id=tier1_id,
  1465. nat_id=nat_id,
  1466. nat_rule_id=nat_rule_id,
  1467. name=name,
  1468. description=description,
  1469. source_network=source_network,
  1470. destination_network=destination_network,
  1471. translated_network=translated_network,
  1472. action=action,
  1473. sequence_number=sequence_number,
  1474. log=log,
  1475. tags=tags,
  1476. tenant=tenant,
  1477. enabled=enabled)
  1478. class NsxPolicyTier1StaticRouteApi(NsxPolicyResourceBase):
  1479. @property
  1480. def entry_def(self):
  1481. return core_defs.Tier1StaticRoute
  1482. def create_or_overwrite(self, name, tier1_id,
  1483. static_route_id=None,
  1484. description=IGNORE,
  1485. network=IGNORE,
  1486. next_hop=IGNORE,
  1487. tags=IGNORE,
  1488. tenant=constants.POLICY_INFRA_TENANT):
  1489. static_route_id = self._init_obj_uuid(static_route_id)
  1490. static_route_def = self._init_def(tier1_id=tier1_id,
  1491. static_route_id=static_route_id,
  1492. name=name,
  1493. description=description,
  1494. network=network,
  1495. next_hop=next_hop,
  1496. tags=tags,
  1497. tenant=tenant)
  1498. self._create_or_store(static_route_def)
  1499. return static_route_id
  1500. def delete(self, tier1_id, static_route_id,
  1501. tenant=constants.POLICY_INFRA_TENANT):
  1502. static_route_def = self.entry_def(tier1_id=tier1_id,
  1503. static_route_id=static_route_id,
  1504. tenant=tenant)
  1505. self.policy_api.delete(static_route_def)
  1506. def get(self, tier1_id, static_route_id,
  1507. tenant=constants.POLICY_INFRA_TENANT):
  1508. static_route_def = self.entry_def(tier1_id=tier1_id,
  1509. static_route_id=static_route_id,
  1510. tenant=tenant)
  1511. return self.policy_api.get(static_route_def)
  1512. def list(self, tier1_id,
  1513. tenant=constants.POLICY_INFRA_TENANT):
  1514. static_route_def = self.entry_def(tier1_id=tier1_id,
  1515. tenant=tenant)
  1516. return self._list(static_route_def)
  1517. def update(self, tier1_id, static_route_id,
  1518. name=IGNORE,
  1519. description=IGNORE,
  1520. network=IGNORE,
  1521. next_hop=IGNORE,
  1522. tags=IGNORE,
  1523. tenant=constants.POLICY_INFRA_TENANT):
  1524. self._update(tier1_id=tier1_id,
  1525. static_route_id=static_route_id,
  1526. name=name,
  1527. description=description,
  1528. network=network,
  1529. next_hop=next_hop,
  1530. tags=tags,
  1531. tenant=tenant)
  1532. class NsxPolicyTier1SegmentApi(NsxPolicyResourceBase):
  1533. """NSX Tier1 Segment API """
  1534. @property
  1535. def entry_def(self):
  1536. return core_defs.Tier1SegmentDef
  1537. def build_subnet(self, gateway_address, dhcp_ranges=None):
  1538. return core_defs.Subnet(gateway_address, dhcp_ranges)
  1539. def create_or_overwrite(self, name, tier1_id,
  1540. segment_id=None,
  1541. description=IGNORE,
  1542. subnets=IGNORE,
  1543. dhcp_config=IGNORE,
  1544. dns_domain_name=IGNORE,
  1545. vlan_ids=IGNORE,
  1546. default_rule_logging=IGNORE,
  1547. ip_pool_id=IGNORE,
  1548. tags=IGNORE,
  1549. tenant=constants.POLICY_INFRA_TENANT):
  1550. segment_id = self._init_obj_uuid(segment_id)
  1551. segment_def = self._init_def(tier1_id=tier1_id,
  1552. segment_id=segment_id,
  1553. name=name,
  1554. description=description,
  1555. subnets=subnets,
  1556. dhcp_config=dhcp_config,
  1557. dns_domain_name=dns_domain_name,
  1558. vlan_ids=vlan_ids,
  1559. default_rule_logging=default_rule_logging,
  1560. ip_pool_id=ip_pool_id,
  1561. tags=tags,
  1562. tenant=tenant)
  1563. self._create_or_store(segment_def)
  1564. return segment_id
  1565. def delete(self, tier1_id, segment_id,
  1566. tenant=constants.POLICY_INFRA_TENANT):
  1567. segment_def = self.entry_def(tier1_id=tier1_id,
  1568. segment_id=segment_id,
  1569. tenant=tenant)
  1570. self.policy_api.delete(segment_def)
  1571. def get(self, tier1_id, segment_id,
  1572. tenant=constants.POLICY_INFRA_TENANT, silent=False):
  1573. segment_def = self.entry_def(tier1_id=tier1_id,
  1574. segment_id=segment_id,
  1575. tenant=tenant)
  1576. return self.policy_api.get(segment_def, silent=silent)
  1577. def list(self, tier1_id, tenant=constants.POLICY_INFRA_TENANT):
  1578. segment_def = self.entry_def(tier1_id=tier1_id, tenant=tenant)
  1579. return self._list(segment_def)
  1580. def update(self, tier1_id, segment_id,
  1581. name=IGNORE,
  1582. description=IGNORE,
  1583. subnets=IGNORE,
  1584. dhcp_config=IGNORE,
  1585. dns_domain_name=IGNORE,
  1586. vlan_ids=IGNORE,
  1587. default_rule_logging=IGNORE,
  1588. tags=IGNORE,
  1589. tenant=constants.POLICY_INFRA_TENANT):
  1590. self._update(tier1_id=tier1_id,
  1591. segment_id=segment_id,
  1592. name=name,
  1593. description=description,
  1594. subnets=subnets,
  1595. dhcp_config=dhcp_config,
  1596. dns_domain_name=dns_domain_name,
  1597. vlan_ids=vlan_ids,
  1598. default_rule_logging=default_rule_logging,
  1599. tags=tags,
  1600. tenant=tenant)
  1601. class NsxPolicySegmentApi(NsxPolicyResourceBase):
  1602. """NSX Infra Segment API """
  1603. @property
  1604. def entry_def(self):
  1605. return core_defs.SegmentDef
  1606. def build_subnet(self, gateway_address, dhcp_ranges=None):
  1607. return core_defs.Subnet(gateway_address, dhcp_ranges)
  1608. def create_or_overwrite(self, name,
  1609. segment_id=None,
  1610. tier1_id=IGNORE,
  1611. tier0_id=IGNORE,
  1612. description=IGNORE,
  1613. subnets=IGNORE,
  1614. dns_domain_name=IGNORE,
  1615. vlan_ids=IGNORE,
  1616. transport_zone_id=IGNORE,
  1617. ip_pool_id=IGNORE,
  1618. metadata_proxy_id=IGNORE,
  1619. tags=IGNORE,
  1620. tenant=constants.POLICY_INFRA_TENANT):
  1621. if tier0_id != IGNORE and tier1_id != IGNORE:
  1622. err_msg = (_("Cannot connect Segment to a Tier-0 and Tier-1 "
  1623. "Gateway simultaneously"))
  1624. raise exceptions.InvalidInput(details=err_msg)
  1625. segment_id = self._init_obj_uuid(segment_id)
  1626. segment_def = self._init_def(segment_id=segment_id,
  1627. name=name,
  1628. description=description,
  1629. tier1_id=tier1_id,
  1630. tier0_id=tier0_id,
  1631. subnets=subnets,
  1632. dns_domain_name=dns_domain_name,
  1633. vlan_ids=vlan_ids,
  1634. transport_zone_id=transport_zone_id,
  1635. ip_pool_id=ip_pool_id,
  1636. metadata_proxy_id=metadata_proxy_id,
  1637. tags=tags,
  1638. tenant=tenant)
  1639. self._create_or_store(segment_def)
  1640. return segment_id
  1641. def delete(self, segment_id,
  1642. tenant=constants.POLICY_INFRA_TENANT):
  1643. segment_def = self.entry_def(segment_id=segment_id, tenant=tenant)
  1644. @utils.retry_upon_exception(
  1645. exceptions.NsxSegemntWithVM,
  1646. delay=self.nsxlib_config.realization_wait_sec,
  1647. max_attempts=self.nsxlib_config.realization_max_attempts)
  1648. def do_delete():
  1649. self.policy_api.delete(segment_def)
  1650. do_delete()
  1651. def get(self, segment_id,
  1652. tenant=constants.POLICY_INFRA_TENANT, silent=False):
  1653. segment_def = self.entry_def(segment_id=segment_id, tenant=tenant)
  1654. return self.policy_api.get(segment_def, silent=silent)
  1655. def list(self, tenant=constants.POLICY_INFRA_TENANT):
  1656. segment_def = self.entry_def(tenant=tenant)
  1657. return self._list(segment_def)
  1658. def update(self, segment_id, name=IGNORE, description=IGNORE,
  1659. tier1_id=IGNORE, tier0_id=IGNORE, subnets=IGNORE,
  1660. dns_domain_name=IGNORE,
  1661. vlan_ids=IGNORE, tags=IGNORE, metadata_proxy_id=IGNORE,
  1662. tenant=constants.POLICY_INFRA_TENANT):
  1663. self._update(segment_id=segment_id,
  1664. name=name,
  1665. description=description,
  1666. tier1_id=tier1_id,
  1667. tier0_id=tier0_id,
  1668. subnets=subnets,
  1669. dns_domain_name=dns_domain_name,
  1670. vlan_ids=vlan_ids,
  1671. metadata_proxy_id=metadata_proxy_id,
  1672. tags=tags,
  1673. tenant=tenant)
  1674. def remove_connectivity_and_subnets(
  1675. self, segment_id,
  1676. tenant=constants.POLICY_INFRA_TENANT):
  1677. """Disconnect a segment from a router and remove its subnets.
  1678. PATCH does not support this action so PUT is used for this
  1679. """
  1680. # Get the current segment and update it
  1681. segment = self.get(segment_id)
  1682. segment['subnets'] = None
  1683. segment['connectivity_path'] = None
  1684. segment_def = self.entry_def(segment_id=segment_id, tenant=tenant)
  1685. path = segment_def.get_resource_path()
  1686. self.policy_api.client.update(path, segment)
  1687. def get_realized_state(self, segment_id, entity_type=None,
  1688. tenant=constants.POLICY_INFRA_TENANT,
  1689. realization_info=None):
  1690. segment_def = self.entry_def(segment_id=segment_id, tenant=tenant)
  1691. return self._get_realized_state(segment_def, entity_type=entity_type,
  1692. realization_info=realization_info)
  1693. def get_realized_id(self, segment_id, entity_type=None,
  1694. tenant=constants.POLICY_INFRA_TENANT,
  1695. realization_info=None):
  1696. segment_def = self.entry_def(segment_id=segment_id, tenant=tenant)
  1697. return self._get_realized_id(segment_def, entity_type=entity_type,
  1698. realization_info=realization_info)
  1699. def get_path(self, segment_id, tenant=constants.POLICY_INFRA_TENANT):
  1700. segment_def = self.entry_def(segment_id=segment_id, tenant=tenant)
  1701. return segment_def.get_resource_full_path()
  1702. def get_realized_logical_switch_id(self, segment_id,
  1703. tenant=constants.POLICY_INFRA_TENANT):
  1704. segment_def = self.entry_def(segment_id=segment_id, tenant=tenant)
  1705. if self.nsx_api:
  1706. # Use MP search api to find the LS ID as it is faster
  1707. return self._get_realized_id_using_search(
  1708. self.get_path(segment_id, tenant=tenant),
  1709. self.nsx_api.logical_switch.resource_type,
  1710. resource_def=segment_def)
  1711. realization_info = self._wait_until_realized(
  1712. segment_def, entity_type='RealizedLogicalSwitch')
  1713. return self._get_realized_id(segment_def,
  1714. realization_info=realization_info)
  1715. def get_realization_info(self, segment_id, entity_type=None,
  1716. silent=False,
  1717. tenant=constants.POLICY_INFRA_TENANT):
  1718. segment_def = self.entry_def(segment_id=segment_id, tenant=tenant)
  1719. return self._get_realization_info(segment_def,
  1720. entity_type=entity_type,
  1721. silent=silent)
  1722. def wait_until_realized(self, segment_id, entity_type=None,
  1723. tenant=constants.POLICY_INFRA_TENANT,
  1724. sleep=None, max_attempts=None):
  1725. segment_def = self.entry_def(segment_id=segment_id, tenant=tenant)
  1726. return self._wait_until_realized(segment_def, entity_type=entity_type,
  1727. sleep=sleep,
  1728. max_attempts=max_attempts)
  1729. @check_allowed_passthrough
  1730. def set_admin_state(self, segment_id, admin_state,
  1731. tenant=constants.POLICY_INFRA_TENANT):
  1732. """Set the segment admin state using the passthrough api"""
  1733. realization_info = self.wait_until_realized(
  1734. segment_id, entity_type='RealizedLogicalSwitch', tenant=tenant)
  1735. nsx_ls_uuid = self.get_realized_id(
  1736. segment_id, tenant=tenant, realization_info=realization_info)
  1737. self.nsx_api.logical_switch.update(
  1738. nsx_ls_uuid,
  1739. admin_state=admin_state)
  1740. def get_transport_zone_id(self, segment_id,
  1741. tenant=constants.POLICY_INFRA_TENANT):
  1742. segment = self.get(segment_id, tenant=tenant)
  1743. tz_path = segment.get('transport_zone_path')
  1744. if tz_path:
  1745. return p_utils.path_to_id(tz_path)
  1746. class NsxPolicySegmentPortApi(NsxPolicyResourceBase):
  1747. """NSX Segment Port API """
  1748. @property
  1749. def entry_def(self):
  1750. return core_defs.SegmentPortDef
  1751. def build_address_binding(self, ip_address, mac_address,
  1752. vlan_id=None):
  1753. return core_defs.PortAddressBinding(ip_address,
  1754. mac_address,
  1755. vlan_id)
  1756. def create_or_overwrite(self, name,
  1757. segment_id,
  1758. port_id=None,
  1759. description=IGNORE,
  1760. address_bindings=IGNORE,
  1761. attachment_type=IGNORE,
  1762. vif_id=IGNORE,
  1763. app_id=IGNORE,
  1764. context_id=IGNORE,
  1765. traffic_tag=IGNORE,
  1766. allocate_addresses=IGNORE,
  1767. hyperbus_mode=IGNORE,
  1768. tags=IGNORE,
  1769. tenant=constants.POLICY_INFRA_TENANT):
  1770. port_id = self._init_obj_uuid(port_id)
  1771. port_def = self._init_def(segment_id=segment_id,
  1772. port_id=port_id,
  1773. name=name,
  1774. description=description,
  1775. address_bindings=address_bindings,
  1776. attachment_type=attachment_type,
  1777. vif_id=vif_id,
  1778. app_id=app_id,
  1779. context_id=context_id,
  1780. traffic_tag=traffic_tag,
  1781. allocate_addresses=allocate_addresses,
  1782. hyperbus_mode=hyperbus_mode,
  1783. tags=tags,
  1784. tenant=tenant)
  1785. self._create_or_store(port_def)
  1786. return port_id
  1787. def delete(self, segment_id, port_id,
  1788. tenant=constants.POLICY_INFRA_TENANT):
  1789. port_def = self.entry_def(segment_id=segment_id,
  1790. port_id=port_id,
  1791. tenant=tenant)
  1792. self.policy_api.delete(port_def)
  1793. def get(self, segment_id, port_id,
  1794. tenant=constants.POLICY_INFRA_TENANT,
  1795. silent=False):
  1796. port_def = self.entry_def(segment_id=segment_id,
  1797. port_id=port_id,
  1798. tenant=tenant)
  1799. return self.policy_api.get(port_def, silent=silent)
  1800. def list(self, segment_id, tenant=constants.POLICY_INFRA_TENANT):
  1801. port_def = self.entry_def(segment_id=segment_id, tenant=tenant)
  1802. return self._list(port_def)
  1803. def update(self, segment_id, port_id,
  1804. name=IGNORE,
  1805. description=IGNORE,
  1806. address_bindings=IGNORE,
  1807. hyperbus_mode=IGNORE,
  1808. tags=IGNORE,
  1809. tenant=constants.POLICY_INFRA_TENANT):
  1810. self._update(segment_id=segment_id,
  1811. port_id=port_id,
  1812. name=name,
  1813. description=description,
  1814. address_bindings=address_bindings,
  1815. hyperbus_mode=hyperbus_mode,
  1816. tags=tags,
  1817. tenant=tenant)
  1818. def detach(self, segment_id, port_id, tags=IGNORE,
  1819. tenant=constants.POLICY_INFRA_TENANT):
  1820. port_def = self.entry_def(segment_id=segment_id,
  1821. port_id=port_id,
  1822. vif_id=None,
  1823. attachment_type=None,
  1824. tags=tags,
  1825. tenant=tenant)
  1826. self.policy_api.create_or_update(port_def)
  1827. def attach(self, segment_id, port_id,
  1828. attachment_type,
  1829. vif_id,
  1830. allocate_addresses=None,
  1831. app_id=None,
  1832. context_id=None,
  1833. traffic_tag=None,
  1834. hyperbus_mode=IGNORE,
  1835. tags=IGNORE,
  1836. tenant=constants.POLICY_INFRA_TENANT):
  1837. port_def = self._init_def(segment_id=segment_id,
  1838. port_id=port_id,
  1839. attachment_type=attachment_type,
  1840. allocate_addresses=allocate_addresses,
  1841. vif_id=vif_id,
  1842. app_id=app_id,
  1843. context_id=context_id,
  1844. traffic_tag=traffic_tag,
  1845. hyperbus_mode=hyperbus_mode,
  1846. tags=tags,
  1847. tenant=tenant)
  1848. self.policy_api.create_or_update(port_def)
  1849. def get_realized_state(self, segment_id, port_id, entity_type=None,
  1850. tenant=constants.POLICY_INFRA_TENANT,
  1851. realization_info=None):
  1852. port_def = self.entry_def(segment_id=segment_id,
  1853. port_id=port_id,
  1854. tenant=tenant)
  1855. return self._get_realized_state(port_def, entity_type=entity_type,
  1856. realization_info=realization_info)
  1857. def get_realized_id(self, segment_id, port_id, entity_type=None,
  1858. tenant=constants.POLICY_INFRA_TENANT,
  1859. realization_info=None):
  1860. port_def = self.entry_def(segment_id=segment_id,
  1861. port_id=port_id,
  1862. tenant=tenant)
  1863. return self._get_realized_id(port_def, entity_type=entity_type,
  1864. realization_info=realization_info)
  1865. def get_realization_info(self, segment_id, port_id, entity_type=None,
  1866. silent=False,
  1867. tenant=constants.POLICY_INFRA_TENANT):
  1868. port_def = self.entry_def(segment_id=segment_id,
  1869. port_id=port_id,
  1870. tenant=tenant)
  1871. return self._get_realization_info(port_def, entity_type=entity_type,
  1872. silent=silent)
  1873. def wait_until_realized(self, segment_id, port_id, entity_type=None,
  1874. tenant=constants.POLICY_INFRA_TENANT,
  1875. sleep=None, max_attempts=None):
  1876. port_def = self.entry_def(segment_id=segment_id, port_id=port_id,
  1877. tenant=tenant)
  1878. return self._wait_until_realized(port_def, entity_type=entity_type,
  1879. sleep=sleep,
  1880. max_attempts=max_attempts)
  1881. @check_allowed_passthrough
  1882. def set_admin_state(self, segment_id, port_id, admin_state,
  1883. tenant=constants.POLICY_INFRA_TENANT):
  1884. """Set the segment port admin state using the passthrough api"""
  1885. realization_info = self.wait_until_realized(
  1886. segment_id, port_id, entity_type='RealizedLogicalPort',
  1887. tenant=tenant)
  1888. nsx_lp_uuid = self.get_realized_id(
  1889. segment_id, port_id, tenant=tenant,
  1890. realization_info=realization_info)
  1891. self.nsx_api.logical_port.update(
  1892. nsx_lp_uuid, False,
  1893. admin_state=admin_state)
  1894. class SegmentProfilesBindingMapBaseApi(NsxPolicyResourceBase):
  1895. def delete(self, segment_id, map_id=DEFAULT_MAP_ID,
  1896. tenant=constants.POLICY_INFRA_TENANT):
  1897. map_def = self.entry_def(segment_id=segment_id,
  1898. map_id=map_id,
  1899. tenant=tenant)
  1900. self.policy_api.delete(map_def)
  1901. def get(self, segment_id, map_id=DEFAULT_MAP_ID,
  1902. tenant=constants.POLICY_INFRA_TENANT):
  1903. map_def = self.entry_def(segment_id=segment_id,
  1904. map_id=map_id,
  1905. tenant=tenant)
  1906. return self.policy_api.get(map_def)
  1907. def list(self, segment_id,
  1908. tenant=constants.POLICY_INFRA_TENANT):
  1909. map_def = self.entry_def(segment_id=segment_id,
  1910. tenant=tenant)
  1911. return self._list(map_def)
  1912. class SegmentSecurityProfilesBindingMapApi(SegmentProfilesBindingMapBaseApi):
  1913. @property
  1914. def entry_def(self):
  1915. return core_defs.SegmentSecProfilesBindingMapDef
  1916. def create_or_overwrite(self, name, segment_id,
  1917. map_id=DEFAULT_MAP_ID,
  1918. description=IGNORE,
  1919. segment_security_profile_id=IGNORE,
  1920. spoofguard_profile_id=IGNORE,
  1921. tags=IGNORE,
  1922. tenant=constants.POLICY_INFRA_TENANT):
  1923. map_id = self._init_obj_uuid(map_id)
  1924. map_def = self._init_def(
  1925. segment_id=segment_id,
  1926. map_id=map_id,
  1927. name=name,
  1928. description=description,
  1929. segment_security_profile_id=segment_security_profile_id,
  1930. spoofguard_profile_id=spoofguard_profile_id,
  1931. tags=tags,
  1932. tenant=tenant)
  1933. self._create_or_store(map_def)
  1934. return map_id
  1935. def update(self, segment_id,
  1936. map_id=DEFAULT_MAP_ID,
  1937. name=IGNORE,
  1938. description=IGNORE,
  1939. segment_security_profile_id=IGNORE,
  1940. spoofguard_profile_id=IGNORE,
  1941. tags=IGNORE,
  1942. tenant=constants.POLICY_INFRA_TENANT):
  1943. self._update(
  1944. segment_id=segment_id,
  1945. map_id=map_id,
  1946. name=name,
  1947. description=description,
  1948. segment_security_profile_id=segment_security_profile_id,
  1949. spoofguard_profile_id=spoofguard_profile_id,
  1950. tags=tags,
  1951. tenant=tenant)
  1952. class SegmentPortProfilesBindingMapBaseApi(NsxPolicyResourceBase):
  1953. def delete(self, segment_id, port_id, map_id=DEFAULT_MAP_ID,
  1954. tenant=constants.POLICY_INFRA_TENANT):
  1955. map_def = self.entry_def(segment_id=segment_id,
  1956. port_id=port_id,
  1957. map_id=map_id,
  1958. tenant=tenant)
  1959. self.policy_api.delete(map_def)
  1960. def get(self, segment_id, port_id, map_id=DEFAULT_MAP_ID,
  1961. tenant=constants.POLICY_INFRA_TENANT):
  1962. map_def = self.entry_def(segment_id=segment_id,
  1963. port_id=port_id,
  1964. map_id=map_id,
  1965. tenant=tenant)
  1966. return self.policy_api.get(map_def)
  1967. def list(self, segment_id, port_id,
  1968. tenant=constants.POLICY_INFRA_TENANT):
  1969. map_def = self.entry_def(segment_id=segment_id,
  1970. port_id=port_id,
  1971. tenant=tenant)
  1972. return self._list(map_def)
  1973. class SegmentPortSecurityProfilesBindingMapApi(
  1974. SegmentPortProfilesBindingMapBaseApi):
  1975. @property
  1976. def entry_def(self):
  1977. return core_defs.SegmentPortSecProfilesBindingMapDef
  1978. def create_or_overwrite(self, name, segment_id, port_id,
  1979. map_id=DEFAULT_MAP_ID,
  1980. description=IGNORE,
  1981. segment_security_profile_id=IGNORE,
  1982. spoofguard_profile_id=IGNORE,
  1983. tags=IGNORE,
  1984. tenant=constants.POLICY_INFRA_TENANT):
  1985. map_id = self._init_obj_uuid(map_id)
  1986. map_def = self._init_def(
  1987. segment_id=segment_id,
  1988. port_id=port_id,
  1989. map_id=map_id,
  1990. name=name,
  1991. description=description,
  1992. segment_security_profile_id=segment_security_profile_id,
  1993. spoofguard_profile_id=spoofguard_profile_id,
  1994. tags=tags,
  1995. tenant=tenant)
  1996. self._create_or_store(map_def)
  1997. return map_id
  1998. def update(self, segment_id, port_id,
  1999. map_id=DEFAULT_MAP_ID,
  2000. name=IGNORE,
  2001. description=IGNORE,
  2002. segment_security_profile_id=IGNORE,
  2003. spoofguard_profile_id=IGNORE,
  2004. tags=IGNORE,
  2005. tenant=constants.POLICY_INFRA_TENANT):
  2006. self._update(
  2007. segment_id=segment_id,
  2008. port_id=port_id,
  2009. map_id=map_id,
  2010. name=name,
  2011. description=description,
  2012. segment_security_profile_id=segment_security_profile_id,
  2013. spoofguard_profile_id=spoofguard_profile_id,
  2014. tags=tags,
  2015. tenant=tenant)
  2016. class SegmentPortDiscoveryProfilesBindingMapApi(
  2017. SegmentPortProfilesBindingMapBaseApi):
  2018. @property
  2019. def entry_def(self):
  2020. return core_defs.SegmentPortDiscoveryProfilesBindingMapDef
  2021. def create_or_overwrite(self, name, segment_id, port_id,
  2022. map_id=DEFAULT_MAP_ID,
  2023. description=IGNORE,
  2024. mac_discovery_profile_id=IGNORE,
  2025. ip_discovery_profile_id=IGNORE,
  2026. tags=IGNORE,
  2027. tenant=constants.POLICY_INFRA_TENANT):
  2028. map_id = self._init_obj_uuid(map_id)
  2029. map_def = self._init_def(
  2030. segment_id=segment_id,
  2031. port_id=port_id,
  2032. map_id=map_id,
  2033. name=name,
  2034. description=description,
  2035. mac_discovery_profile_id=mac_discovery_profile_id,
  2036. ip_discovery_profile_id=ip_discovery_profile_id,
  2037. tags=tags,
  2038. tenant=tenant)
  2039. self._create_or_store(map_def)
  2040. return map_id
  2041. def update(self, segment_id, port_id,
  2042. map_id=DEFAULT_MAP_ID,
  2043. name=IGNORE,
  2044. description=IGNORE,
  2045. mac_discovery_profile_id=IGNORE,
  2046. ip_discovery_profile_id=IGNORE,
  2047. tags=IGNORE,
  2048. tenant=constants.POLICY_INFRA_TENANT):
  2049. self._update(
  2050. segment_id=segment_id,
  2051. port_id=port_id,
  2052. map_id=map_id,
  2053. name=name,
  2054. description=description,
  2055. mac_discovery_profile_id=mac_discovery_profile_id,
  2056. ip_discovery_profile_id=ip_discovery_profile_id,
  2057. tags=tags,
  2058. tenant=tenant)
  2059. class SegmentPortQosProfilesBindingMapApi(
  2060. SegmentPortProfilesBindingMapBaseApi):
  2061. @property
  2062. def entry_def(self):
  2063. return core_defs.SegmentPortQoSProfilesBindingMapDef
  2064. def create_or_overwrite(self, name, segment_id, port_id,
  2065. map_id=DEFAULT_MAP_ID,
  2066. description=IGNORE,
  2067. qos_profile_id=IGNORE,
  2068. tags=IGNORE,
  2069. tenant=constants.POLICY_INFRA_TENANT):
  2070. map_id = self._init_obj_uuid(map_id)
  2071. map_def = self._init_def(
  2072. segment_id=segment_id,
  2073. port_id=port_id,
  2074. map_id=map_id,
  2075. name=name,
  2076. description=description,
  2077. qos_profile_id=qos_profile_id,
  2078. tags=tags,
  2079. tenant=tenant)
  2080. self._create_or_store(map_def)
  2081. return map_id
  2082. def update(self, segment_id, port_id,
  2083. map_id=DEFAULT_MAP_ID,
  2084. name=IGNORE,
  2085. description=IGNORE,
  2086. qos_profile_id=IGNORE,
  2087. tags=IGNORE,
  2088. tenant=constants.POLICY_INFRA_TENANT):
  2089. self._update(
  2090. segment_id=segment_id,
  2091. port_id=port_id,
  2092. map_id=map_id,
  2093. name=name,
  2094. description=description,
  2095. qos_profile_id=qos_profile_id,
  2096. tags=tags,
  2097. tenant=tenant)
  2098. class NsxPolicyTier1SegmentPortApi(NsxPolicyResourceBase):
  2099. """NSX Tier1 Segment Port API """
  2100. @property
  2101. def entry_def(self):
  2102. return core_defs.Tier1SegmentPortDef
  2103. def build_address_binding(self, ip_address, mac_address,
  2104. vlan_id=None):
  2105. return core_defs.PortAddressBinding(ip_address,
  2106. mac_address,
  2107. vlan_id)
  2108. def create_or_overwrite(self, name,
  2109. tier1_id,
  2110. segment_id,
  2111. port_id=None,
  2112. description=IGNORE,
  2113. address_bindings=IGNORE,
  2114. attachment_type=IGNORE,
  2115. vif_id=IGNORE,
  2116. app_id=IGNORE,
  2117. context_id=IGNORE,
  2118. traffic_tag=IGNORE,
  2119. allocate_addresses=IGNORE,
  2120. tags=IGNORE,
  2121. tenant=constants.POLICY_INFRA_TENANT):
  2122. port_id = self._init_obj_uuid(port_id)
  2123. port_def = self._init_def(segment_id=segment_id,
  2124. tier1_id=tier1_id,
  2125. port_id=port_id,
  2126. name=name,
  2127. description=description,
  2128. address_bindings=address_bindings,
  2129. attachment_type=attachment_type,
  2130. vif_id=vif_id,
  2131. app_id=app_id,
  2132. context_id=context_id,
  2133. traffic_tag=traffic_tag,
  2134. allocate_addresses=allocate_addresses,
  2135. tags=tags,
  2136. tenant=tenant)
  2137. self._create_or_store(port_def)
  2138. return port_id
  2139. def delete(self, tier1_id, segment_id, port_id,
  2140. tenant=constants.POLICY_INFRA_TENANT):
  2141. port_def = self.entry_def(segment_id=segment_id,
  2142. tier1_id=tier1_id,
  2143. port_id=port_id,
  2144. tenant=tenant)
  2145. self.policy_api.delete(port_def)
  2146. def get(self, tier1_id, segment_id, port_id,
  2147. tenant=constants.POLICY_INFRA_TENANT,
  2148. silent=False):
  2149. port_def = self.entry_def(segment_id=segment_id,
  2150. tier1_id=tier1_id,
  2151. port_id=port_id,
  2152. tenant=tenant)
  2153. return self.policy_api.get(port_def, silent=silent)
  2154. def list(self, tier1_id, segment_id,
  2155. tenant=constants.POLICY_INFRA_TENANT):
  2156. port_def = self.entry_def(segment_id=segment_id, tier1_id=tier1_id,
  2157. tenant=tenant)
  2158. return self._list(port_def)
  2159. def update(self, tier1_id, segment_id, port_id,
  2160. name=IGNORE,
  2161. description=IGNORE,
  2162. address_bindings=IGNORE,
  2163. tags=IGNORE,
  2164. tenant=constants.POLICY_INFRA_TENANT):
  2165. self._update(segment_id=segment_id,
  2166. tier1_id=tier1_id,
  2167. port_id=port_id,
  2168. name=name,
  2169. description=description,
  2170. address_bindings=address_bindings,
  2171. tags=tags,
  2172. tenant=tenant)
  2173. def detach(self, tier1_id, segment_id, port_id,
  2174. tenant=constants.POLICY_INFRA_TENANT):
  2175. port_def = self.entry_def(segment_id=segment_id,
  2176. tier1_id=tier1_id,
  2177. port_id=port_id,
  2178. attachment_type=None,
  2179. tenant=tenant)
  2180. self.policy_api.create_or_update(port_def)
  2181. def attach(self, tier1_id, segment_id, port_id,
  2182. attachment_type,
  2183. vif_id,
  2184. allocate_addresses,
  2185. app_id=None,
  2186. context_id=None,
  2187. tenant=constants.POLICY_INFRA_TENANT):
  2188. port_def = self.entry_def(segment_id=segment_id,
  2189. tier1_id=tier1_id,
  2190. port_id=port_id,
  2191. attachment_type=attachment_type,
  2192. allocate_addresses=allocate_addresses,
  2193. vif_id=vif_id,
  2194. app_id=app_id,
  2195. context_id=context_id,
  2196. tenant=tenant)
  2197. self.policy_api.create_or_update(port_def)
  2198. def get_realized_state(self, tier1_id, segment_id, port_id,
  2199. entity_type=None,
  2200. tenant=constants.POLICY_INFRA_TENANT,
  2201. realization_info=None):
  2202. port_def = self.entry_def(segment_id=segment_id,
  2203. tier1_id=tier1_id,
  2204. port_id=port_id,
  2205. tenant=tenant)
  2206. return self._get_realized_state(port_def, entity_type=entity_type,
  2207. realization_info=realization_info)
  2208. def get_realized_id(self, tier1_id, segment_id, port_id, entity_type=None,
  2209. tenant=constants.POLICY_INFRA_TENANT,
  2210. realization_info=None):
  2211. port_def = self.entry_def(segment_id=segment_id,
  2212. tier1_id=tier1_id,
  2213. port_id=port_id,
  2214. tenant=tenant)
  2215. return self._get_realized_id(port_def, entity_type=entity_type,
  2216. realization_info=realization_info)
  2217. def get_realization_info(self, tier1_id, segment_id, port_id,
  2218. entity_type=None, silent=False,
  2219. tenant=constants.POLICY_INFRA_TENANT):
  2220. port_def = self.entry_def(segment_id=segment_id,
  2221. tier1_id=tier1_id,
  2222. port_id=port_id,
  2223. tenant=tenant)
  2224. return self._get_realization_info(port_def, entity_type=entity_type,
  2225. silent=silent)
  2226. def wait_until_realized(self, tier1_id, segment_id, port_id,
  2227. entity_type=None,
  2228. tenant=constants.POLICY_INFRA_TENANT,
  2229. sleep=None, max_attempts=None):
  2230. port_def = self.entry_def(segment_id=segment_id, port_id=port_id,
  2231. tier1_id=tier1_id, tenant=tenant)
  2232. return self._wait_until_realized(port_def, entity_type=entity_type,
  2233. sleep=sleep,
  2234. max_attempts=max_attempts)
  2235. class NsxPolicyIpBlockApi(NsxPolicyResourceBase):
  2236. """NSX Policy IP Block API"""
  2237. @property
  2238. def entry_def(self):
  2239. return core_defs.IpBlockDef
  2240. def create_or_overwrite(self, name,
  2241. ip_block_id=None,
  2242. description=IGNORE,
  2243. cidr=IGNORE,
  2244. tags=IGNORE,
  2245. tenant=constants.POLICY_INFRA_TENANT):
  2246. ip_block_id = self._init_obj_uuid(ip_block_id)
  2247. ip_block_def = self._init_def(ip_block_id=ip_block_id,
  2248. name=name,
  2249. description=description,
  2250. cidr=cidr,
  2251. tags=tags,
  2252. tenant=tenant)
  2253. self._create_or_store(ip_block_def)
  2254. return ip_block_id
  2255. def delete(self, ip_block_id, tenant=constants.POLICY_INFRA_TENANT):
  2256. ip_block_def = self.entry_def(ip_block_id=ip_block_id,
  2257. tenant=tenant)
  2258. self.policy_api.delete(ip_block_def)
  2259. def get(self, ip_block_id, tenant=constants.POLICY_INFRA_TENANT,
  2260. silent=False):
  2261. ip_block_def = self.entry_def(ip_block_id=ip_block_id,
  2262. tenant=tenant)
  2263. return self.policy_api.get(ip_block_def, silent=silent)
  2264. def list(self, tenant=constants.POLICY_INFRA_TENANT):
  2265. ip_block_def = self.entry_def(tenant=tenant)
  2266. return self._list(ip_block_def)
  2267. def update(self, ip_block_id, name=IGNORE, description=IGNORE,
  2268. cidr=IGNORE, tags=IGNORE,
  2269. tenant=constants.POLICY_INFRA_TENANT):
  2270. self._update(ip_block_id=ip_block_id,
  2271. name=name,
  2272. description=description,
  2273. cidr=cidr,
  2274. tags=tags,
  2275. tenant=tenant)
  2276. class NsxPolicyIpPoolApi(NsxPolicyResourceBase):
  2277. """NSX Policy IP Pool API"""
  2278. @property
  2279. def entry_def(self):
  2280. return core_defs.IpPoolDef
  2281. def create_or_overwrite(self, name,
  2282. ip_pool_id=None,
  2283. description=IGNORE,
  2284. tags=IGNORE,
  2285. tenant=constants.POLICY_INFRA_TENANT):
  2286. ip_pool_id = self._init_obj_uuid(ip_pool_id)
  2287. ip_pool_def = self._init_def(ip_pool_id=ip_pool_id,
  2288. name=name,
  2289. description=description,
  2290. tags=tags,
  2291. tenant=tenant)
  2292. self._create_or_store(ip_pool_def)
  2293. return ip_pool_id
  2294. def delete(self, ip_pool_id, tenant=constants.POLICY_INFRA_TENANT):
  2295. ip_pool_def = self.entry_def(ip_pool_id=ip_pool_id,
  2296. tenant=tenant)
  2297. self.policy_api.delete(ip_pool_def)
  2298. def get(self, ip_pool_id, tenant=constants.POLICY_INFRA_TENANT):
  2299. ip_pool_def = self.entry_def(ip_pool_id=ip_pool_id,
  2300. tenant=tenant)
  2301. return self.policy_api.get(ip_pool_def)
  2302. def list(self, tenant=constants.POLICY_INFRA_TENANT):
  2303. ip_pool_def = self.entry_def(tenant=tenant)
  2304. return self._list(ip_pool_def)
  2305. def update(self, ip_pool_id, name=IGNORE, description=IGNORE,
  2306. tags=IGNORE,
  2307. tenant=constants.POLICY_INFRA_TENANT):
  2308. self._update(ip_pool_id=ip_pool_id,
  2309. name=name,
  2310. description=description,
  2311. tags=tags,
  2312. tenant=tenant)
  2313. def allocate_ip(self, ip_pool_id, ip_allocation_id=None, ip_address=IGNORE,
  2314. name=IGNORE, description=IGNORE, tags=IGNORE,
  2315. tenant=constants.POLICY_INFRA_TENANT):
  2316. # If ip_address is not set, a random IP will be allocated
  2317. # from the pool.
  2318. ip_allocation_id = self._init_obj_uuid(ip_allocation_id)
  2319. args = self._get_user_args(
  2320. ip_pool_id=ip_pool_id,
  2321. ip_allocation_id=ip_allocation_id,
  2322. allocation_ip=ip_address,
  2323. name=name,
  2324. description=description,
  2325. tags=tags,
  2326. tenant=tenant)
  2327. ip_allocation_def = core_defs.IpPoolAllocationDef(**args)
  2328. self._create_or_store(ip_allocation_def)
  2329. def release_ip(self, ip_pool_id, ip_allocation_id,
  2330. tenant=constants.POLICY_INFRA_TENANT):
  2331. ip_allocation_def = core_defs.IpPoolAllocationDef(
  2332. ip_allocation_id=ip_allocation_id,
  2333. ip_pool_id=ip_pool_id,
  2334. tenant=tenant)
  2335. self.policy_api.delete(ip_allocation_def)
  2336. def list_allocations(self, ip_pool_id,
  2337. tenant=constants.POLICY_INFRA_TENANT):
  2338. ip_allocation_def = core_defs.IpPoolAllocationDef(
  2339. ip_pool_id=ip_pool_id,
  2340. tenant=tenant)
  2341. return self._list(ip_allocation_def)
  2342. def get_allocation(self, ip_pool_id, ip_allocation_id,
  2343. tenant=constants.POLICY_INFRA_TENANT):
  2344. ip_allocation_def = core_defs.IpPoolAllocationDef(
  2345. ip_pool_id=ip_pool_id,
  2346. ip_allocation_id=ip_allocation_id,
  2347. tenant=tenant)
  2348. return self.policy_api.get(ip_allocation_def)
  2349. def allocate_block_subnet(self, ip_pool_id, ip_block_id, size,
  2350. ip_subnet_id=None, auto_assign_gateway=IGNORE,
  2351. name=IGNORE, description=IGNORE, tags=IGNORE,
  2352. tenant=constants.POLICY_INFRA_TENANT,
  2353. start_ip=IGNORE):
  2354. ip_subnet_id = self._init_obj_uuid(ip_subnet_id)
  2355. args = self._get_user_args(
  2356. ip_pool_id=ip_pool_id,
  2357. ip_block_id=ip_block_id,
  2358. ip_subnet_id=ip_subnet_id,
  2359. size=size,
  2360. auto_assign_gateway=auto_assign_gateway,
  2361. name=name,
  2362. description=description,
  2363. tags=tags,
  2364. tenant=tenant,
  2365. start_ip=start_ip)
  2366. ip_subnet_def = core_defs.IpPoolBlockSubnetDef(
  2367. nsx_version=self.version, **args)
  2368. self._create_or_store(ip_subnet_def)
  2369. def release_block_subnet(self, ip_pool_id, ip_subnet_id,
  2370. tenant=constants.POLICY_INFRA_TENANT):
  2371. ip_subnet_def = core_defs.IpPoolBlockSubnetDef(
  2372. ip_subnet_id=ip_subnet_id,
  2373. ip_pool_id=ip_pool_id,
  2374. tenant=tenant)
  2375. self.policy_api.delete(ip_subnet_def)
  2376. def list_block_subnets(self, ip_pool_id,
  2377. tenant=constants.POLICY_INFRA_TENANT):
  2378. ip_subnet_def = core_defs.IpPoolBlockSubnetDef(
  2379. ip_pool_id=ip_pool_id,
  2380. tenant=tenant)
  2381. subnets = self._list(ip_subnet_def)
  2382. block_subnets = []
  2383. for subnet in subnets:
  2384. if subnet['resource_type'] == ip_subnet_def.resource_type():
  2385. block_subnets.append(subnet)
  2386. return block_subnets
  2387. def get_ip_block_subnet(self, ip_pool_id, ip_subnet_id,
  2388. tenant=constants.POLICY_INFRA_TENANT):
  2389. ip_subnet_def = core_defs.IpPoolBlockSubnetDef(
  2390. ip_pool_id=ip_pool_id,
  2391. ip_subnet_id=ip_subnet_id,
  2392. tenant=tenant)
  2393. return self.policy_api.get(ip_subnet_def)
  2394. def get_ip_block_subnet_cidr(self, ip_pool_id, ip_subnet_id,
  2395. entity_type=None,
  2396. tenant=constants.POLICY_INFRA_TENANT,
  2397. wait=False, sleep=None,
  2398. max_attempts=None):
  2399. # Retrieve the allocated Subnet CIDR for Subnet ID
  2400. # Return None in case the CIDR is not yet allocated
  2401. realized_info = self.get_ip_subnet_realization_info(
  2402. ip_pool_id, ip_subnet_id, entity_type, tenant, wait,
  2403. sleep, max_attempts)
  2404. # Returns a list of CIDRs. In case a single value is expected,
  2405. # caller must extract the first index to retrieve the CIDR value
  2406. return self._get_extended_attr_from_realized_info(
  2407. realized_info, requested_attr='cidr')
  2408. def create_or_update_static_subnet(self, ip_pool_id, cidr,
  2409. allocation_ranges, ip_subnet_id=None,
  2410. name=IGNORE, description=IGNORE,
  2411. gateway_ip=IGNORE, tags=IGNORE,
  2412. tenant=constants.POLICY_INFRA_TENANT):
  2413. ip_subnet_id = self._init_obj_uuid(ip_subnet_id)
  2414. args = self._get_user_args(
  2415. ip_pool_id=ip_pool_id,
  2416. ip_subnet_id=ip_subnet_id,
  2417. cidr=cidr,
  2418. allocation_ranges=allocation_ranges,
  2419. name=name,
  2420. description=description,
  2421. tags=tags,
  2422. tenant=tenant)
  2423. ip_subnet_def = core_defs.IpPoolStaticSubnetDef(**args)
  2424. self._create_or_store(ip_subnet_def)
  2425. def release_static_subnet(self, ip_pool_id, ip_subnet_id,
  2426. tenant=constants.POLICY_INFRA_TENANT):
  2427. ip_subnet_def = core_defs.IpPoolStaticSubnetDef(
  2428. ip_subnet_id=ip_subnet_id,
  2429. ip_pool_id=ip_pool_id,
  2430. tenant=tenant)
  2431. self.policy_api.delete(ip_subnet_def)
  2432. def list_static_subnets(self, ip_pool_id,
  2433. tenant=constants.POLICY_INFRA_TENANT):
  2434. ip_subnet_def = core_defs.IpPoolStaticSubnetDef(
  2435. ip_pool_id=ip_pool_id,
  2436. tenant=tenant)
  2437. subnets = self._list(ip_subnet_def)
  2438. static_subnets = []
  2439. for subnet in subnets:
  2440. if subnet['resource_type'] == ip_subnet_def.resource_type():
  2441. static_subnets.append(subnet)
  2442. return static_subnets
  2443. def get_static_subnet(self, ip_pool_id, ip_subnet_id,
  2444. tenant=constants.POLICY_INFRA_TENANT):
  2445. ip_subnet_def = core_defs.IpPoolStaticSubnetDef(
  2446. ip_pool_id=ip_pool_id,
  2447. ip_subnet_id=ip_subnet_id,
  2448. tenant=tenant)
  2449. return self.policy_api.get(ip_subnet_def)
  2450. def get_realization_info(self, ip_pool_id, entity_type=None,
  2451. silent=False,
  2452. tenant=constants.POLICY_INFRA_TENANT):
  2453. ip_pool_def = self.entry_def(ip_pool_id=ip_pool_id, tenant=tenant)
  2454. return self._get_realization_info(ip_pool_def, entity_type=entity_type,
  2455. silent=silent)
  2456. def get_ip_subnet_realization_info(
  2457. self, ip_pool_id, ip_subnet_id,
  2458. entity_type=None,
  2459. tenant=constants.POLICY_INFRA_TENANT,
  2460. wait=False, sleep=None,
  2461. max_attempts=None,
  2462. subnet_type=constants.IPPOOL_BLOCK_SUBNET):
  2463. if subnet_type == constants.IPPOOL_BLOCK_SUBNET:
  2464. ip_subnet_def = core_defs.IpPoolBlockSubnetDef(
  2465. ip_pool_id=ip_pool_id,
  2466. ip_subnet_id=ip_subnet_id,
  2467. tenant=tenant)
  2468. else:
  2469. ip_subnet_def = core_defs.IpPoolStaticSubnetDef(
  2470. ip_pool_id=ip_pool_id,
  2471. ip_subnet_id=ip_subnet_id,
  2472. tenant=tenant)
  2473. if wait:
  2474. return self._wait_until_realized(
  2475. ip_subnet_def, entity_type=entity_type,
  2476. sleep=sleep, max_attempts=max_attempts)
  2477. return self._get_realization_info(ip_subnet_def,
  2478. entity_type=entity_type)
  2479. def get_ip_alloc_realization_info(self, ip_pool_id, ip_allocation_id,
  2480. entity_type=None,
  2481. tenant=constants.POLICY_INFRA_TENANT,
  2482. wait=False, sleep=None,
  2483. max_attempts=None):
  2484. ip_allocation_def = core_defs.IpPoolAllocationDef(
  2485. ip_pool_id=ip_pool_id,
  2486. ip_allocation_id=ip_allocation_id,
  2487. tenant=tenant)
  2488. if wait:
  2489. return self._wait_until_realized(
  2490. ip_allocation_def, entity_type=entity_type,
  2491. sleep=sleep, max_attempts=max_attempts)
  2492. return self._get_realization_info(ip_allocation_def,
  2493. entity_type=entity_type)
  2494. def get_realized_allocated_ip(self, ip_pool_id, ip_allocation_id,
  2495. entity_type=None,
  2496. tenant=constants.POLICY_INFRA_TENANT,
  2497. wait=False, sleep=None,
  2498. max_attempts=None):
  2499. # Retrieve the allocated IpAddress for allocation ID
  2500. # Return None in case the IP is not yet allocated
  2501. realized_info = self.get_ip_alloc_realization_info(
  2502. ip_pool_id, ip_allocation_id, entity_type, tenant, wait,
  2503. sleep, max_attempts)
  2504. if realized_info:
  2505. try:
  2506. return realized_info['extended_attributes'][0].get(
  2507. 'values')[0]
  2508. except IndexError:
  2509. return
  2510. def wait_until_realized(self, ip_pool_id, entity_type=None,
  2511. tenant=constants.POLICY_INFRA_TENANT,
  2512. sleep=None, max_attempts=None):
  2513. ip_pool_def = self.entry_def(ip_pool_id=ip_pool_id, tenant=tenant)
  2514. return self._wait_until_realized(ip_pool_def, entity_type=entity_type,
  2515. sleep=sleep,
  2516. max_attempts=max_attempts)
  2517. class NsxPolicySecurityPolicyBaseApi(NsxPolicyResourceBase):
  2518. def _get_last_seq_num(self, domain_id, map_id,
  2519. tenant=constants.POLICY_INFRA_TENANT):
  2520. # get the current entries, and choose the next unused sequence number
  2521. # between the entries under the same communication map
  2522. try:
  2523. com_map = self.get(domain_id, map_id, tenant=tenant)
  2524. com_entries = com_map.get('rules')
  2525. except exceptions.ResourceNotFound:
  2526. return -1
  2527. if not com_entries:
  2528. return 0
  2529. seq_nums = [int(cm['sequence_number']) for cm in com_entries]
  2530. seq_nums.sort()
  2531. return seq_nums[-1]
  2532. def _get_seq_num(self, last_sequence):
  2533. if last_sequence < 0:
  2534. return 1
  2535. return last_sequence + 1
  2536. def create_or_overwrite(self, name, domain_id, map_id=None,
  2537. description=IGNORE,
  2538. category=constants.CATEGORY_APPLICATION,
  2539. sequence_number=None, service_ids=IGNORE,
  2540. action=constants.ACTION_ALLOW,
  2541. scope=IGNORE,
  2542. source_groups=IGNORE, dest_groups=IGNORE,
  2543. direction=nsx_constants.IN_OUT,
  2544. logged=IGNORE, tags=IGNORE,
  2545. map_sequence_number=IGNORE,
  2546. tenant=constants.POLICY_INFRA_TENANT):
  2547. """Create CommunicationMap & Entry.
  2548. source_groups/dest_groups should be a list of group ids belonging
  2549. to the domain.
  2550. NOTE: In multi-connection environment, it is recommended to execute
  2551. this call under lock to prevent race condition where two entries
  2552. end up with same sequence number.
  2553. """
  2554. last_sequence = -1
  2555. if map_id:
  2556. if not sequence_number:
  2557. # get the next available sequence number
  2558. last_sequence = self._get_last_seq_num(domain_id, map_id,
  2559. tenant=tenant)
  2560. else:
  2561. map_id = self._init_obj_uuid(map_id)
  2562. if not sequence_number:
  2563. sequence_number = self._get_seq_num(last_sequence)
  2564. # Build the communication entry. Since we currently support only one
  2565. # it will have the same id as its parent
  2566. entry_def = self._init_def(
  2567. domain_id=domain_id,
  2568. map_id=map_id,
  2569. entry_id=self.SINGLE_ENTRY_ID,
  2570. name=name,
  2571. description=description,
  2572. sequence_number=sequence_number,
  2573. source_groups=source_groups,
  2574. dest_groups=dest_groups,
  2575. service_ids=service_ids,
  2576. action=action,
  2577. scope=scope,
  2578. direction=direction,
  2579. logged=logged,
  2580. tenant=tenant)
  2581. map_def = self._init_parent_def(
  2582. domain_id=domain_id, map_id=map_id,
  2583. tenant=tenant, name=name, description=description,
  2584. category=category, tags=tags,
  2585. map_sequence_number=map_sequence_number)
  2586. self._create_or_store(map_def, entry_def)
  2587. return map_id
  2588. def create_or_overwrite_map_only(
  2589. self, name, domain_id, map_id=None, description=IGNORE,
  2590. category=constants.CATEGORY_APPLICATION,
  2591. tags=IGNORE, map_sequence_number=IGNORE,
  2592. tenant=constants.POLICY_INFRA_TENANT):
  2593. """Create or update a CommunicationMap
  2594. Create a communication map without any entries, or update the
  2595. communication map itself, leaving the entries unchanged.
  2596. """
  2597. map_id = self._init_obj_uuid(map_id)
  2598. map_def = self._init_parent_def(
  2599. domain_id=domain_id, map_id=map_id,
  2600. tenant=tenant, name=name, description=description,
  2601. category=category, tags=tags,
  2602. map_sequence_number=map_sequence_number)
  2603. self._create_or_store(map_def)
  2604. return map_id
  2605. def build_entry(self, name, domain_id, map_id, entry_id=None,
  2606. description=None,
  2607. sequence_number=None, service_ids=None,
  2608. action=constants.ACTION_ALLOW,
  2609. scope=None,
  2610. source_groups=None, dest_groups=None,
  2611. direction=nsx_constants.IN_OUT, logged=False, tag=None,
  2612. ip_protocol=nsx_constants.IPV4_IPV6,
  2613. tenant=constants.POLICY_INFRA_TENANT):
  2614. """Get the definition of a single map entry"""
  2615. entry_id = self._init_obj_uuid(entry_id)
  2616. return self._init_def(domain_id=domain_id,
  2617. map_id=map_id,
  2618. entry_id=entry_id,
  2619. name=name,
  2620. description=description,
  2621. sequence_number=sequence_number,
  2622. source_groups=source_groups,
  2623. dest_groups=dest_groups,
  2624. service_ids=service_ids,
  2625. action=action,
  2626. scope=scope,
  2627. direction=direction,
  2628. ip_protocol=ip_protocol,
  2629. logged=logged,
  2630. tag=tag,
  2631. tenant=tenant)
  2632. def create_with_entries(
  2633. self, name, domain_id, map_id=None,
  2634. description=IGNORE,
  2635. category=constants.CATEGORY_APPLICATION,
  2636. entries=None, tags=IGNORE, map_sequence_number=IGNORE,
  2637. tenant=constants.POLICY_INFRA_TENANT):
  2638. """Create CommunicationMap with entries"""
  2639. map_id = self._init_obj_uuid(map_id)
  2640. map_def = self._init_parent_def(
  2641. domain_id=domain_id, map_id=map_id,
  2642. tenant=tenant, name=name, description=description,
  2643. category=category, tags=tags,
  2644. map_sequence_number=map_sequence_number)
  2645. # in case the same object was just deleted, create may need to
  2646. # be retried
  2647. @utils.retry_upon_exception(
  2648. exceptions.NsxPendingDelete,
  2649. delay=self.nsxlib_config.realization_wait_sec,
  2650. max_attempts=self.nsxlib_config.realization_max_attempts)
  2651. def _do_create_with_retry():
  2652. self._create_or_store(map_def, entries)
  2653. _do_create_with_retry()
  2654. return map_id
  2655. def create_entry(self, name, domain_id, map_id, entry_id=None,
  2656. description=None, sequence_number=None, service_ids=None,
  2657. action=constants.ACTION_ALLOW,
  2658. source_groups=None, dest_groups=None,
  2659. scope=None,
  2660. ip_protocol=nsx_constants.IPV4_IPV6,
  2661. direction=nsx_constants.IN_OUT,
  2662. logged=False, tag=None,
  2663. tenant=constants.POLICY_INFRA_TENANT):
  2664. """Create CommunicationMap Entry.
  2665. source_groups/dest_groups should be a list of group ids belonging
  2666. to the domain.
  2667. """
  2668. # get the next available sequence number
  2669. if not sequence_number:
  2670. last_sequence = self._get_last_seq_num(domain_id, map_id,
  2671. tenant=tenant)
  2672. sequence_number = self._get_seq_num(last_sequence)
  2673. entry_id = self._init_obj_uuid(entry_id)
  2674. # Build the communication entry
  2675. entry_def = self._init_def(domain_id=domain_id,
  2676. map_id=map_id,
  2677. entry_id=entry_id,
  2678. name=name,
  2679. description=description,
  2680. sequence_number=sequence_number,
  2681. source_groups=source_groups,
  2682. dest_groups=dest_groups,
  2683. service_ids=service_ids,
  2684. action=action,
  2685. scope=scope,
  2686. ip_protocol=ip_protocol,
  2687. direction=direction,
  2688. logged=logged,
  2689. tag=tag,
  2690. tenant=tenant)
  2691. self._create_or_store(entry_def)
  2692. return entry_id
  2693. def create_entry_from_def(self, entry_def):
  2694. """Create CommunicationMap Entry from a predefined entry def"""
  2695. self._create_or_store(entry_def)
  2696. def delete(self, domain_id, map_id,
  2697. tenant=constants.POLICY_INFRA_TENANT):
  2698. map_def = self._init_parent_def(
  2699. domain_id=domain_id,
  2700. map_id=map_id,
  2701. tenant=tenant)
  2702. self.policy_api.delete(map_def)
  2703. def delete_entry(self, domain_id, map_id, entry_id,
  2704. tenant=constants.POLICY_INFRA_TENANT):
  2705. entry_def = self.entry_def(
  2706. domain_id=domain_id,
  2707. map_id=map_id,
  2708. entry_id=entry_id,
  2709. tenant=tenant)
  2710. self.policy_api.delete(entry_def)
  2711. def get(self, domain_id, map_id,
  2712. tenant=constants.POLICY_INFRA_TENANT, silent=False):
  2713. map_def = self.parent_entry_def(
  2714. domain_id=domain_id,
  2715. map_id=map_id,
  2716. tenant=tenant)
  2717. return self.policy_api.get(map_def, silent=silent)
  2718. def get_entry(self, domain_id, map_id, entry_id,
  2719. tenant=constants.POLICY_INFRA_TENANT, silent=False):
  2720. entry_def = self.entry_def(
  2721. domain_id=domain_id,
  2722. map_id=map_id,
  2723. entry_id=entry_id,
  2724. tenant=tenant)
  2725. return self.policy_api.get(entry_def, silent=silent)
  2726. def get_by_name(self, domain_id, name,
  2727. tenant=constants.POLICY_INFRA_TENANT):
  2728. """Return first communication map entry matched by name"""
  2729. return super(NsxPolicySecurityPolicyBaseApi, self).get_by_name(
  2730. name, domain_id, tenant=tenant)
  2731. def list(self, domain_id,
  2732. tenant=constants.POLICY_INFRA_TENANT):
  2733. """List all the map entries of a specific domain."""
  2734. map_def = self.parent_entry_def(
  2735. domain_id=domain_id,
  2736. tenant=tenant)
  2737. return self._list(map_def)
  2738. def update(self, domain_id, map_id,
  2739. name=IGNORE, description=IGNORE,
  2740. sequence_number=IGNORE, service_ids=IGNORE,
  2741. action=IGNORE,
  2742. source_groups=IGNORE, dest_groups=IGNORE,
  2743. direction=IGNORE, logged=IGNORE, tags=IGNORE,
  2744. tenant=constants.POLICY_INFRA_TENANT):
  2745. # Note(asarfaty): Category is mandatory in update calls for now
  2746. # although it cannot change. Getting it from the NSX
  2747. orig_entry = self.get(domain_id, map_id, tenant=tenant)
  2748. category = orig_entry.get('category')
  2749. parent_def = self._init_parent_def(
  2750. domain_id=domain_id,
  2751. map_id=map_id,
  2752. name=name,
  2753. description=description,
  2754. category=category,
  2755. tags=tags,
  2756. tenant=tenant)
  2757. if self._any_arg_set(sequence_number, service_ids,
  2758. action, source_groups, dest_groups,
  2759. direction, logged):
  2760. # Update the entry only if relevant attributes were changed
  2761. entry_def = self._get_and_update_def(
  2762. domain_id=domain_id,
  2763. map_id=map_id,
  2764. entry_id=self.SINGLE_ENTRY_ID,
  2765. service_ids=service_ids,
  2766. source_groups=source_groups,
  2767. dest_groups=dest_groups,
  2768. sequence_number=sequence_number,
  2769. action=action,
  2770. direction=direction,
  2771. logged=logged,
  2772. tenant=tenant)
  2773. self.policy_api.create_with_parent(parent_def, entry_def)
  2774. else:
  2775. self.policy_api.create_or_update(parent_def)
  2776. def update_entry(self, domain_id, map_id, entry_id,
  2777. name=IGNORE, description=IGNORE,
  2778. sequence_number=IGNORE, service_ids=IGNORE,
  2779. action=IGNORE, source_groups=IGNORE, dest_groups=IGNORE,
  2780. scope=IGNORE, ip_protocol=IGNORE,
  2781. direction=IGNORE, logged=IGNORE, tags=IGNORE, tag=IGNORE,
  2782. tenant=constants.POLICY_INFRA_TENANT):
  2783. if self._any_arg_set(name, description, sequence_number, service_ids,
  2784. action, source_groups, dest_groups, scope,
  2785. ip_protocol, direction, logged, tags):
  2786. entry_def = self._get_and_update_def(
  2787. domain_id=domain_id,
  2788. map_id=map_id,
  2789. entry_id=entry_id,
  2790. name=name,
  2791. description=description,
  2792. sequence_number=sequence_number,
  2793. service_ids=service_ids,
  2794. action=action,
  2795. source_groups=source_groups,
  2796. dest_groups=dest_groups,
  2797. scope=scope,
  2798. ip_protocol=ip_protocol,
  2799. direction=direction,
  2800. logged=logged,
  2801. tags=tags,
  2802. tag=tag,
  2803. tenant=tenant)
  2804. self.policy_api.create_or_update(entry_def)
  2805. def update_entries(self, domain_id, map_id, entries,
  2806. category=constants.CATEGORY_APPLICATION,
  2807. tenant=constants.POLICY_INFRA_TENANT):
  2808. self.update_with_entries(domain_id, map_id, entries, category=category,
  2809. tenant=tenant)
  2810. def update_with_entries(self, domain_id, map_id, entries=IGNORE,
  2811. name=IGNORE, description=IGNORE,
  2812. category=constants.CATEGORY_APPLICATION,
  2813. tags=IGNORE, map_sequence_number=IGNORE,
  2814. tenant=constants.POLICY_INFRA_TENANT):
  2815. map_def = self._init_parent_def(
  2816. domain_id=domain_id, map_id=map_id,
  2817. tenant=tenant, name=name, description=description,
  2818. category=category, tags=tags,
  2819. map_sequence_number=map_sequence_number)
  2820. map_path = map_def.get_resource_path()
  2821. def _overwrite_entries(old_entries, new_entries, transaction):
  2822. # Replace old entries with new entries, but copy additional
  2823. # attributes from old entries for those kept in new entries
  2824. # and marked the unwanted ones in the old entries as deleted
  2825. # if it is in the transaction call.
  2826. old_rules = {entry["id"]: entry for entry in old_entries}
  2827. replaced_entries = []
  2828. for entry in new_entries:
  2829. rule_id = entry.get_id()
  2830. new_rule = entry.get_obj_dict()
  2831. old_rule = old_rules.get(rule_id)
  2832. if old_rule:
  2833. old_rules.pop(rule_id)
  2834. for key, value in old_rule.items():
  2835. if key not in new_rule:
  2836. new_rule[key] = value
  2837. replaced_entries.append(
  2838. self.entry_def.adapt_from_rule_dict(
  2839. new_rule, domain_id, map_id))
  2840. if transaction:
  2841. replaced_entries.extend(
  2842. _mark_delete_entries(old_rules.values()))
  2843. return replaced_entries
  2844. def _mark_delete_entries(delete_rule_dicts):
  2845. delete_entries = []
  2846. for delete_rule_dict in delete_rule_dicts:
  2847. delete_entry = self.entry_def.adapt_from_rule_dict(
  2848. delete_rule_dict, domain_id, map_id)
  2849. delete_entry.set_delete()
  2850. delete_entries.append(delete_entry)
  2851. return delete_entries
  2852. @utils.retry_upon_exception(
  2853. exceptions.StaleRevision,
  2854. max_attempts=self.policy_api.client.max_attempts)
  2855. def _update():
  2856. transaction = trans.NsxPolicyTransaction.get_current()
  2857. # Get the current data of communication map & its entries
  2858. comm_map = self.policy_api.get(map_def)
  2859. replaced_entries = None
  2860. ignore_entries = (entries == IGNORE)
  2861. if not ignore_entries:
  2862. replaced_entries = _overwrite_entries(comm_map['rules'],
  2863. entries, transaction)
  2864. comm_map.pop('rules')
  2865. map_def.set_obj_dict(comm_map)
  2866. # Update the entire map at the NSX
  2867. if transaction:
  2868. self._create_or_store(map_def, replaced_entries)
  2869. else:
  2870. body = map_def.get_obj_dict()
  2871. if not ignore_entries:
  2872. body['rules'] = [rule.get_obj_dict() for rule in
  2873. replaced_entries]
  2874. self.policy_api.client.update(map_path, body)
  2875. _update()
  2876. def update_entries_logged(self, domain_id, map_id, logged,
  2877. tenant=constants.POLICY_INFRA_TENANT):
  2878. """Update all communication map entries logged flags"""
  2879. map_def = self.parent_entry_def(
  2880. domain_id=domain_id,
  2881. map_id=map_id,
  2882. tenant=tenant)
  2883. map_path = map_def.get_resource_path()
  2884. @utils.retry_upon_exception(
  2885. exceptions.StaleRevision,
  2886. max_attempts=self.policy_api.client.max_attempts)
  2887. def _update():
  2888. # Get the current data of communication map & its' entries
  2889. comm_map = self.policy_api.get(map_def)
  2890. # Update the field in all the entries
  2891. if comm_map.get('rules'):
  2892. for comm_entry in comm_map['rules']:
  2893. comm_entry['logged'] = logged
  2894. # Update the entire map at the NSX
  2895. self.policy_api.client.update(map_path, comm_map)
  2896. _update()
  2897. def get_realized_state(self, domain_id, map_id, entity_type=None,
  2898. tenant=constants.POLICY_INFRA_TENANT,
  2899. realization_info=None):
  2900. map_def = self.parent_entry_def(map_id=map_id,
  2901. domain_id=domain_id,
  2902. tenant=tenant)
  2903. return self._get_realized_state(map_def, entity_type=entity_type,
  2904. realization_info=realization_info)
  2905. def get_realized_id(self, domain_id, map_id, entity_type=None,
  2906. tenant=constants.POLICY_INFRA_TENANT,
  2907. realization_info=None):
  2908. map_def = self.parent_entry_def(map_id=map_id,
  2909. domain_id=domain_id,
  2910. tenant=tenant)
  2911. return self._get_realized_id(map_def, entity_type=entity_type,
  2912. realization_info=realization_info)
  2913. def get_realization_info(self, domain_id, map_id, entity_type=None,
  2914. silent=False,
  2915. tenant=constants.POLICY_INFRA_TENANT):
  2916. map_def = self.parent_entry_def(map_id=map_id,
  2917. domain_id=domain_id,
  2918. tenant=tenant)
  2919. return self._get_realization_info(map_def, entity_type=entity_type,
  2920. silent=silent)
  2921. class NsxPolicyCommunicationMapApi(NsxPolicySecurityPolicyBaseApi):
  2922. """NSX Policy CommunicationMap (Under a Domain). AKA Security"""
  2923. @property
  2924. def entry_def(self):
  2925. return core_defs.CommunicationMapEntryDef
  2926. @property
  2927. def parent_entry_def(self):
  2928. return core_defs.CommunicationMapDef
  2929. class NsxPolicyGatewayPolicyApi(NsxPolicySecurityPolicyBaseApi):
  2930. """NSX Policy Gateway policy (Edge firewall)"""
  2931. @property
  2932. def entry_def(self):
  2933. return core_defs.GatewayPolicyRuleDef
  2934. @property
  2935. def parent_entry_def(self):
  2936. return core_defs.GatewayPolicyDef
  2937. class NsxPolicyEnforcementPointApi(NsxPolicyResourceBase):
  2938. """NSX Policy Enforcement Point."""
  2939. @property
  2940. def entry_def(self):
  2941. return core_defs.EnforcementPointDef
  2942. def create_or_overwrite(self, name, ep_id=None, description=IGNORE,
  2943. ip_address=IGNORE, username=IGNORE,
  2944. password=IGNORE, thumbprint=IGNORE,
  2945. edge_cluster_id=IGNORE,
  2946. transport_zone_id=IGNORE,
  2947. tenant=constants.POLICY_INFRA_TENANT):
  2948. if not ip_address or not username or password is None:
  2949. err_msg = (_("Cannot create an enforcement point without "
  2950. "ip_address, username and password"))
  2951. raise exceptions.ManagerError(details=err_msg)
  2952. ep_id = self._init_obj_uuid(ep_id)
  2953. ep_def = self._init_def(ep_id=ep_id,
  2954. name=name,
  2955. description=description,
  2956. ip_address=ip_address,
  2957. username=username,
  2958. password=password,
  2959. thumbprint=thumbprint,
  2960. edge_cluster_id=edge_cluster_id,
  2961. transport_zone_id=transport_zone_id,
  2962. tenant=tenant)
  2963. self._create_or_store(ep_def)
  2964. return ep_id
  2965. def delete(self, ep_id,
  2966. tenant=constants.POLICY_INFRA_TENANT):
  2967. ep_def = core_defs.EnforcementPointDef(
  2968. ep_id=ep_id, tenant=tenant)
  2969. self.policy_api.delete(ep_def)
  2970. def get(self, ep_id,
  2971. tenant=constants.POLICY_INFRA_TENANT, silent=False):
  2972. ep_def = core_defs.EnforcementPointDef(
  2973. ep_id=ep_id, tenant=tenant)
  2974. return self.policy_api.get(ep_def, silent=silent)
  2975. def list(self, tenant=constants.POLICY_INFRA_TENANT):
  2976. ep_def = core_defs.EnforcementPointDef(tenant=tenant)
  2977. return self._list(ep_def)
  2978. def update(self, ep_id, name=IGNORE, description=IGNORE,
  2979. ip_address=IGNORE, username=IGNORE,
  2980. password=IGNORE, thumbprint=IGNORE,
  2981. edge_cluster_id=IGNORE, transport_zone_id=IGNORE,
  2982. tenant=constants.POLICY_INFRA_TENANT):
  2983. """Update the enforcement point.
  2984. username & password must be defined
  2985. """
  2986. if not username or password is None:
  2987. # username/password must be provided
  2988. err_msg = (_("Cannot update an enforcement point without "
  2989. "username and password"))
  2990. raise exceptions.ManagerError(details=err_msg)
  2991. # Get the original body because ip & thumbprint are mandatory
  2992. ep_def = self._get_and_update_def(ep_id=ep_id,
  2993. name=name,
  2994. description=description,
  2995. ip_address=ip_address,
  2996. username=username,
  2997. password=password,
  2998. edge_cluster_id=edge_cluster_id,
  2999. transport_zone_id=transport_zone_id,
  3000. thumbprint=thumbprint,
  3001. tenant=tenant)
  3002. self.policy_api.create_or_update(ep_def)
  3003. def get_realized_state(self, ep_id, entity_type=None,
  3004. tenant=constants.POLICY_INFRA_TENANT,
  3005. realization_info=None):
  3006. ep_def = core_defs.EnforcementPointDef(ep_id=ep_id, tenant=tenant)
  3007. return self._get_realized_state(ep_def, entity_type=entity_type,
  3008. realization_info=realization_info)
  3009. def get_realization_info(self, ep_id, entity_type=None,
  3010. silent=False,
  3011. tenant=constants.POLICY_INFRA_TENANT,
  3012. realization_info=None):
  3013. ep_def = core_defs.EnforcementPointDef(ep_id=ep_id, tenant=tenant)
  3014. return self._get_realization_info(ep_def, entity_type=entity_type,
  3015. silent=silent,
  3016. realization_info=realization_info)
  3017. def reload(self, ep_id, tenant=constants.POLICY_INFRA_TENANT):
  3018. # Use post command to reload the enforcement point
  3019. ep_def = core_defs.EnforcementPointDef(ep_id=ep_id, tenant=tenant)
  3020. path = "%s?action=reload" % ep_def.get_resource_path()
  3021. self.policy_api.client.create(path)
  3022. class NsxPolicyTransportZoneApi(NsxPolicyResourceBase):
  3023. TZ_TYPE_OVERLAY = 'OVERLAY_STANDARD'
  3024. TZ_TYPE_ENS = 'OVERLAY_ENS'
  3025. TZ_TYPE_VLAN = 'VLAN_BACKED'
  3026. @property
  3027. def entry_def(self):
  3028. return core_defs.TransportZoneDef
  3029. def get(self, tz_id, ep_id=constants.DEFAULT_ENFORCEMENT_POINT,
  3030. tenant=constants.POLICY_INFRA_TENANT, silent=False):
  3031. tz_def = core_defs.TransportZoneDef(
  3032. ep_id=ep_id, tz_id=tz_id, tenant=tenant)
  3033. return self.policy_api.get(tz_def, silent=silent)
  3034. def get_tz_type(self, tz_id,
  3035. ep_id=constants.DEFAULT_ENFORCEMENT_POINT,
  3036. tenant=constants.POLICY_INFRA_TENANT):
  3037. tz = self.get(tz_id, ep_id=ep_id, tenant=tenant)
  3038. return tz.get('tz_type')
  3039. def get_transport_type(self, tz_id,
  3040. ep_id=constants.DEFAULT_ENFORCEMENT_POINT,
  3041. tenant=constants.POLICY_INFRA_TENANT):
  3042. """This api is consistent with the nsx manager resource api"""
  3043. tz_type = self.get_tz_type(tz_id, ep_id=ep_id, tenant=tenant)
  3044. if tz_type == self.TZ_TYPE_VLAN:
  3045. return nsx_constants.TRANSPORT_TYPE_VLAN
  3046. else:
  3047. return nsx_constants.TRANSPORT_TYPE_OVERLAY
  3048. def get_host_switch_mode(self, tz_id,
  3049. ep_id=constants.DEFAULT_ENFORCEMENT_POINT,
  3050. tenant=constants.POLICY_INFRA_TENANT):
  3051. """This api is consistent with the nsx manager resource api"""
  3052. tz_type = self.get_tz_type(tz_id, ep_id=ep_id, tenant=tenant)
  3053. if tz_type == self.TZ_TYPE_ENS:
  3054. return nsx_constants.HOST_SWITCH_MODE_ENS
  3055. else:
  3056. return nsx_constants.HOST_SWITCH_MODE_STANDARD
  3057. def list(self, ep_id=constants.DEFAULT_ENFORCEMENT_POINT,
  3058. tenant=constants.POLICY_INFRA_TENANT):
  3059. tz_def = core_defs.TransportZoneDef(ep_id=ep_id, tenant=tenant)
  3060. return self._list(tz_def)
  3061. def get_by_name(self, name,
  3062. ep_id=constants.DEFAULT_ENFORCEMENT_POINT,
  3063. tenant=constants.POLICY_INFRA_TENANT):
  3064. """Return first group matched by name"""
  3065. return super(NsxPolicyTransportZoneApi, self).get_by_name(
  3066. name, ep_id, tenant=tenant)
  3067. def create_or_overwrite(self, name, tz_id=None,
  3068. ep_id=constants.DEFAULT_ENFORCEMENT_POINT,
  3069. tenant=constants.POLICY_INFRA_TENANT):
  3070. err_msg = (_("This action is not supported"))
  3071. raise exceptions.ManagerError(details=err_msg)
  3072. def update(self, tz_id,
  3073. ep_id=constants.DEFAULT_ENFORCEMENT_POINT,
  3074. tenant=constants.POLICY_INFRA_TENANT):
  3075. err_msg = (_("This action is not supported"))
  3076. raise exceptions.ManagerError(details=err_msg)
  3077. def delete(self, tz_id,
  3078. ep_id=constants.DEFAULT_ENFORCEMENT_POINT,
  3079. tenant=constants.POLICY_INFRA_TENANT):
  3080. err_msg = (_("This action is not supported"))
  3081. raise exceptions.ManagerError(details=err_msg)
  3082. class NsxPolicyEdgeClusterApi(NsxPolicyResourceBase):
  3083. @property
  3084. def entry_def(self):
  3085. return core_defs.EdgeClusterDef
  3086. def get(self, ec_id, ep_id=constants.DEFAULT_ENFORCEMENT_POINT,
  3087. tenant=constants.POLICY_INFRA_TENANT, silent=False):
  3088. ec_def = core_defs.EdgeClusterDef(
  3089. ep_id=ep_id, ec_id=ec_id, tenant=tenant)
  3090. return self.policy_api.get(ec_def, silent=silent)
  3091. def list(self, ep_id=constants.DEFAULT_ENFORCEMENT_POINT,
  3092. tenant=constants.POLICY_INFRA_TENANT):
  3093. ec_def = core_defs.EdgeClusterDef(ep_id=ep_id, tenant=tenant)
  3094. return self._list(ec_def)
  3095. def get_by_name(self, name,
  3096. ep_id=constants.DEFAULT_ENFORCEMENT_POINT,
  3097. tenant=constants.POLICY_INFRA_TENANT):
  3098. """Return first group matched by name"""
  3099. return super(NsxPolicyEdgeClusterApi, self).get_by_name(
  3100. name, ep_id, tenant=tenant)
  3101. def create_or_overwrite(self, name, ec_id=None,
  3102. ep_id=constants.DEFAULT_ENFORCEMENT_POINT,
  3103. tenant=constants.POLICY_INFRA_TENANT):
  3104. err_msg = (_("This action is not supported"))
  3105. raise exceptions.ManagerError(details=err_msg)
  3106. def update(self, ec_id,
  3107. ep_id=constants.DEFAULT_ENFORCEMENT_POINT,
  3108. tenant=constants.POLICY_INFRA_TENANT):
  3109. err_msg = (_("This action is not supported"))
  3110. raise exceptions.ManagerError(details=err_msg)
  3111. def delete(self, ec_id,
  3112. ep_id=constants.DEFAULT_ENFORCEMENT_POINT,
  3113. tenant=constants.POLICY_INFRA_TENANT):
  3114. err_msg = (_("This action is not supported"))
  3115. raise exceptions.ManagerError(details=err_msg)
  3116. def get_path(self, ec_id,
  3117. ep_id=constants.DEFAULT_ENFORCEMENT_POINT,
  3118. tenant=constants.POLICY_INFRA_TENANT):
  3119. ec_def = core_defs.EdgeClusterDef(
  3120. ep_id=ep_id, ec_id=ec_id, tenant=tenant)
  3121. return ec_def.get_resource_full_path()
  3122. def get_edge_node_ids(self, ec_id,
  3123. ep_id=constants.DEFAULT_ENFORCEMENT_POINT,
  3124. tenant=constants.POLICY_INFRA_TENANT):
  3125. nodes_def = core_defs.EdgeClusterNodeDef(
  3126. ep_id=ep_id, ec_id=ec_id, tenant=tenant)
  3127. nodes = self._list(nodes_def)
  3128. return [node['id'] for node in nodes]
  3129. class NsxPolicyMetadataProxyApi(NsxPolicyResourceBase):
  3130. # Currently this is used as a ready only Api
  3131. @property
  3132. def entry_def(self):
  3133. return core_defs.MetadataProxyDef
  3134. def get(self, mdproxy_id,
  3135. tenant=constants.POLICY_INFRA_TENANT, silent=False):
  3136. md_def = core_defs.MetadataProxyDef(
  3137. mdproxy_id=mdproxy_id, tenant=tenant)
  3138. return self.policy_api.get(md_def, silent=silent)
  3139. def list(self, tenant=constants.POLICY_INFRA_TENANT):
  3140. md_def = core_defs.MetadataProxyDef(tenant=tenant)
  3141. return self._list(md_def)
  3142. def get_by_name(self, name,
  3143. tenant=constants.POLICY_INFRA_TENANT):
  3144. return super(NsxPolicyMetadataProxyApi, self).get_by_name(
  3145. name, tenant=tenant)
  3146. def create_or_overwrite(self, name, mdproxy_id=None,
  3147. tenant=constants.POLICY_INFRA_TENANT):
  3148. err_msg = (_("This action is not supported"))
  3149. raise exceptions.ManagerError(details=err_msg)
  3150. def update(self, mdproxy_id,
  3151. tenant=constants.POLICY_INFRA_TENANT):
  3152. err_msg = (_("This action is not supported"))
  3153. raise exceptions.ManagerError(details=err_msg)
  3154. def delete(self, mdproxy_id,
  3155. tenant=constants.POLICY_INFRA_TENANT):
  3156. err_msg = (_("This action is not supported"))
  3157. raise exceptions.ManagerError(details=err_msg)
  3158. def get_path(self, mdproxy_id,
  3159. tenant=constants.POLICY_INFRA_TENANT):
  3160. md_def = core_defs.MetadataProxyDef(
  3161. mdproxy_id=mdproxy_id, tenant=tenant)
  3162. return md_def.get_resource_full_path()
  3163. class NsxPolicyDeploymentMapApi(NsxPolicyResourceBase):
  3164. """NSX Policy Deployment Map."""
  3165. @property
  3166. def entry_def(self):
  3167. return core_defs.DeploymentMapDef
  3168. def create_or_overwrite(self, name, map_id=None,
  3169. description=IGNORE,
  3170. ep_id=IGNORE, domain_id=IGNORE,
  3171. tenant=constants.POLICY_INFRA_TENANT):
  3172. map_id = self._init_obj_uuid(map_id)
  3173. map_def = core_defs.DeploymentMapDef(
  3174. map_id=map_id,
  3175. name=name,
  3176. description=description,
  3177. ep_id=ep_id,
  3178. domain_id=domain_id,
  3179. tenant=tenant)
  3180. self._create_or_store(map_def)
  3181. return map_id
  3182. def delete(self, map_id, domain_id=None,
  3183. tenant=constants.POLICY_INFRA_TENANT):
  3184. if not domain_id:
  3185. # domain_id must be provided
  3186. err_msg = (_("Cannot delete deployment maps without a domain"))
  3187. raise exceptions.ManagerError(details=err_msg)
  3188. map_def = core_defs.DeploymentMapDef(
  3189. map_id=map_id, domain_id=domain_id, tenant=tenant)
  3190. self.policy_api.delete(map_def)
  3191. def get(self, map_id, domain_id=None,
  3192. tenant=constants.POLICY_INFRA_TENANT, silent=False):
  3193. if not domain_id:
  3194. # domain_id must be provided
  3195. err_msg = (_("Cannot get deployment maps without a domain"))
  3196. raise exceptions.ManagerError(details=err_msg)
  3197. map_def = core_defs.DeploymentMapDef(
  3198. map_id=map_id, domain_id=domain_id, tenant=tenant)
  3199. return self.policy_api.get(map_def, silent=silent)
  3200. def list(self, domain_id=None,
  3201. tenant=constants.POLICY_INFRA_TENANT):
  3202. if not domain_id:
  3203. # domain_id must be provided
  3204. err_msg = (_("Cannot list deployment maps without a domain"))
  3205. raise exceptions.ManagerError(details=err_msg)
  3206. map_def = core_defs.DeploymentMapDef(domain_id=domain_id,
  3207. tenant=tenant)
  3208. return self._list(map_def)
  3209. def update(self, map_id, name=IGNORE, description=IGNORE,
  3210. ep_id=IGNORE, domain_id=IGNORE,
  3211. tenant=constants.POLICY_INFRA_TENANT):
  3212. self._update(map_id=map_id,
  3213. name=name,
  3214. description=description,
  3215. ep_id=ep_id,
  3216. domain_id=domain_id,
  3217. tenant=tenant)
  3218. class NsxSegmentProfileBaseApi(NsxPolicyResourceBase):
  3219. """NSX Segment Profile base API"""
  3220. def create_or_overwrite(self, name,
  3221. profile_id=None,
  3222. description=IGNORE,
  3223. tags=IGNORE,
  3224. tenant=constants.POLICY_INFRA_TENANT):
  3225. profile_id = self._init_obj_uuid(profile_id)
  3226. profile_def = self._init_def(profile_id=profile_id,
  3227. name=name,
  3228. description=description,
  3229. tags=tags,
  3230. tenant=tenant)
  3231. self._create_or_store(profile_def)
  3232. return profile_id
  3233. def delete(self, profile_id, tenant=constants.POLICY_INFRA_TENANT):
  3234. profile_def = self.entry_def(profile_id=profile_id,
  3235. tenant=tenant)
  3236. self.policy_api.delete(profile_def)
  3237. def get(self, profile_id, tenant=constants.POLICY_INFRA_TENANT,
  3238. silent=False):
  3239. profile_def = self.entry_def(profile_id=profile_id,
  3240. tenant=tenant)
  3241. return self.policy_api.get(profile_def, silent=silent)
  3242. def list(self, tenant=constants.POLICY_INFRA_TENANT):
  3243. profile_def = self.entry_def(tenant=tenant)
  3244. return self._list(profile_def)
  3245. def get_by_name(self, name, tenant=constants.POLICY_INFRA_TENANT):
  3246. return super(NsxSegmentProfileBaseApi, self).get_by_name(
  3247. name, tenant=tenant)
  3248. def update(self, profile_id, name=IGNORE, description=IGNORE,
  3249. tags=IGNORE, tenant=constants.POLICY_INFRA_TENANT):
  3250. self._update(profile_id=profile_id,
  3251. name=name,
  3252. description=description,
  3253. tags=tags,
  3254. tenant=tenant)
  3255. def get_path(self, profile_id, tenant=constants.POLICY_INFRA_TENANT):
  3256. profile_def = self.entry_def(profile_id=profile_id, tenant=tenant)
  3257. return profile_def.get_resource_full_path()
  3258. class NsxSegmentSecurityProfileApi(NsxSegmentProfileBaseApi):
  3259. @property
  3260. def entry_def(self):
  3261. return core_defs.SegmentSecurityProfileDef
  3262. def create_or_overwrite(self, name,
  3263. profile_id=None,
  3264. description=IGNORE,
  3265. bpdu_filter_enable=IGNORE,
  3266. dhcp_client_block_enabled=IGNORE,
  3267. dhcp_client_block_v6_enabled=IGNORE,
  3268. dhcp_server_block_enabled=IGNORE,
  3269. dhcp_server_block_v6_enabled=IGNORE,
  3270. non_ip_traffic_block_enabled=IGNORE,
  3271. ra_guard_enabled=IGNORE,
  3272. rate_limits_enabled=IGNORE,
  3273. tags=IGNORE,
  3274. tenant=constants.POLICY_INFRA_TENANT):
  3275. profile_id = self._init_obj_uuid(profile_id)
  3276. profile_def = self._init_def(
  3277. profile_id=profile_id,
  3278. name=name,
  3279. description=description,
  3280. bpdu_filter_enable=bpdu_filter_enable,
  3281. dhcp_client_block_enabled=dhcp_client_block_enabled,
  3282. dhcp_client_block_v6_enabled=dhcp_client_block_v6_enabled,
  3283. dhcp_server_block_enabled=dhcp_server_block_enabled,
  3284. dhcp_server_block_v6_enabled=dhcp_server_block_v6_enabled,
  3285. non_ip_traffic_block_enabled=non_ip_traffic_block_enabled,
  3286. ra_guard_enabled=ra_guard_enabled,
  3287. rate_limits_enabled=rate_limits_enabled,
  3288. tags=tags,
  3289. tenant=tenant)
  3290. self._create_or_store(profile_def)
  3291. return profile_id
  3292. class NsxQosProfileApi(NsxSegmentProfileBaseApi):
  3293. @property
  3294. def entry_def(self):
  3295. return core_defs.QosProfileDef
  3296. def _build_rate_limiter(self, resource_type, average_bandwidth,
  3297. peak_bandwidth, burst_size, enabled):
  3298. return core_defs.QoSRateLimiter(
  3299. resource_type=resource_type,
  3300. average_bandwidth=average_bandwidth,
  3301. peak_bandwidth=peak_bandwidth,
  3302. burst_size=burst_size,
  3303. enabled=enabled)
  3304. def build_ingress_rate_limiter(
  3305. self,
  3306. average_bandwidth=None,
  3307. peak_bandwidth=None,
  3308. burst_size=None,
  3309. enabled=True):
  3310. return self._build_rate_limiter(
  3311. resource_type=core_defs.QoSRateLimiter.INGRESS_RATE_LIMITER_TYPE,
  3312. average_bandwidth=average_bandwidth,
  3313. peak_bandwidth=peak_bandwidth,
  3314. burst_size=burst_size,
  3315. enabled=enabled)
  3316. def build_egress_rate_limiter(
  3317. self,
  3318. average_bandwidth=None,
  3319. peak_bandwidth=None,
  3320. burst_size=None,
  3321. enabled=True):
  3322. return self._build_rate_limiter(
  3323. resource_type=core_defs.QoSRateLimiter.EGRESS_RATE_LIMITER_TYPE,
  3324. average_bandwidth=average_bandwidth,
  3325. peak_bandwidth=peak_bandwidth,
  3326. burst_size=burst_size,
  3327. enabled=enabled)
  3328. def build_dscp(self, trusted=False, priority=None):
  3329. mode = (core_defs.QoSDscp.QOS_DSCP_TRUSTED if trusted
  3330. else core_defs.QoSDscp.QOS_DSCP_UNTRUSTED)
  3331. return core_defs.QoSDscp(mode=mode, priority=priority)
  3332. def create_or_overwrite(self, name,
  3333. profile_id=None,
  3334. description=IGNORE,
  3335. class_of_service=IGNORE,
  3336. dscp=IGNORE,
  3337. shaper_configurations=IGNORE,
  3338. tags=IGNORE,
  3339. tenant=constants.POLICY_INFRA_TENANT):
  3340. profile_id = self._init_obj_uuid(profile_id)
  3341. profile_def = self._init_def(
  3342. profile_id=profile_id,
  3343. name=name,
  3344. description=description,
  3345. class_of_service=class_of_service,
  3346. dscp=dscp,
  3347. shaper_configurations=shaper_configurations,
  3348. tags=tags,
  3349. tenant=tenant)
  3350. self._create_or_store(profile_def)
  3351. return profile_id
  3352. class NsxSpoofguardProfileApi(NsxSegmentProfileBaseApi):
  3353. @property
  3354. def entry_def(self):
  3355. return core_defs.SpoofguardProfileDef
  3356. def create_or_overwrite(self, name,
  3357. profile_id=None,
  3358. description=IGNORE,
  3359. address_binding_whitelist=IGNORE,
  3360. tags=IGNORE,
  3361. tenant=constants.POLICY_INFRA_TENANT):
  3362. profile_id = self._init_obj_uuid(profile_id)
  3363. profile_def = self._init_def(
  3364. profile_id=profile_id,
  3365. name=name,
  3366. description=description,
  3367. address_binding_whitelist=address_binding_whitelist,
  3368. tags=tags,
  3369. tenant=tenant)
  3370. self._create_or_store(profile_def)
  3371. return profile_id
  3372. class NsxIpDiscoveryProfileApi(NsxSegmentProfileBaseApi):
  3373. @property
  3374. def entry_def(self):
  3375. return core_defs.IpDiscoveryProfileDef
  3376. class NsxWAFProfileApi(NsxSegmentProfileBaseApi):
  3377. @property
  3378. def entry_def(self):
  3379. return core_defs.WAFProfileDef
  3380. class NsxMacDiscoveryProfileApi(NsxSegmentProfileBaseApi):
  3381. @property
  3382. def entry_def(self):
  3383. return core_defs.MacDiscoveryProfileDef
  3384. def create_or_overwrite(self, name,
  3385. profile_id=None,
  3386. description=IGNORE,
  3387. mac_change_enabled=IGNORE,
  3388. mac_learning_enabled=IGNORE,
  3389. unknown_unicast_flooding_enabled=IGNORE,
  3390. mac_limit_policy=IGNORE,
  3391. mac_limit=IGNORE,
  3392. tags=IGNORE,
  3393. tenant=constants.POLICY_INFRA_TENANT):
  3394. profile_id = self._init_obj_uuid(profile_id)
  3395. profile_def = self._init_def(
  3396. profile_id=profile_id,
  3397. name=name,
  3398. description=description,
  3399. mac_change_enabled=mac_change_enabled,
  3400. mac_learning_enabled=mac_learning_enabled,
  3401. unknown_unicast_flooding_enabled=unknown_unicast_flooding_enabled,
  3402. mac_limit_policy=mac_limit_policy,
  3403. mac_limit=mac_limit,
  3404. tags=tags,
  3405. tenant=tenant)
  3406. self._create_or_store(profile_def)
  3407. return profile_id
  3408. class NsxIpv6NdraProfileApi(NsxPolicyResourceBase):
  3409. @property
  3410. def entry_def(self):
  3411. return core_defs.Ipv6NdraProfileDef
  3412. def create_or_overwrite(self, name,
  3413. profile_id=None,
  3414. description=IGNORE,
  3415. ra_mode=IGNORE,
  3416. reachable_timer=IGNORE,
  3417. retransmit_interval=IGNORE,
  3418. tags=IGNORE,
  3419. tenant=constants.POLICY_INFRA_TENANT):
  3420. profile_id = self._init_obj_uuid(profile_id)
  3421. profile_def = self._init_def(
  3422. profile_id=profile_id,
  3423. name=name,
  3424. description=description,
  3425. ra_mode=ra_mode,
  3426. reachable_timer=reachable_timer,
  3427. retransmit_interval=retransmit_interval,
  3428. tags=tags,
  3429. tenant=tenant)
  3430. self._create_or_store(profile_def)
  3431. return profile_id
  3432. def delete(self, profile_id, tenant=constants.POLICY_INFRA_TENANT):
  3433. profile_def = self.entry_def(profile_id=profile_id,
  3434. tenant=tenant)
  3435. self.policy_api.delete(profile_def)
  3436. def get(self, profile_id, tenant=constants.POLICY_INFRA_TENANT):
  3437. profile_def = self.entry_def(profile_id=profile_id,
  3438. tenant=tenant)
  3439. return self.policy_api.get(profile_def)
  3440. def list(self, tenant=constants.POLICY_INFRA_TENANT):
  3441. profile_def = self.entry_def(tenant=tenant)
  3442. return self._list(profile_def)
  3443. def get_by_name(self, name, tenant=constants.POLICY_INFRA_TENANT):
  3444. return super(NsxSegmentProfileBaseApi, self).get_by_name(
  3445. name, tenant=tenant)
  3446. def update(self, profile_id, name=IGNORE, description=IGNORE,
  3447. ra_mode=IGNORE, reachable_timer=IGNORE,
  3448. retransmit_interval=IGNORE,
  3449. tags=IGNORE, tenant=constants.POLICY_INFRA_TENANT):
  3450. self._update(profile_id=profile_id,
  3451. name=name,
  3452. description=description,
  3453. ra_mode=ra_mode,
  3454. reachable_timer=reachable_timer,
  3455. retransmit_interval=retransmit_interval,
  3456. tags=tags,
  3457. tenant=tenant)
  3458. class NsxDhcpRelayConfigApi(NsxPolicyResourceBase):
  3459. @property
  3460. def entry_def(self):
  3461. return core_defs.DhcpRelayConfigDef
  3462. def create_or_overwrite(self, name,
  3463. config_id=None,
  3464. description=None,
  3465. server_addresses=IGNORE,
  3466. tags=IGNORE,
  3467. tenant=constants.POLICY_INFRA_TENANT):
  3468. config_id = self._init_obj_uuid(config_id)
  3469. config_def = self._init_def(
  3470. config_id=config_id,
  3471. name=name,
  3472. description=description,
  3473. server_addresses=server_addresses,
  3474. tags=tags,
  3475. tenant=tenant)
  3476. self._create_or_store(config_def)
  3477. return config_id
  3478. def delete(self, config_id, tenant=constants.POLICY_INFRA_TENANT):
  3479. config_def = self.entry_def(config_id=config_id, tenant=tenant)
  3480. self.policy_api.delete(config_def)
  3481. def get(self, config_id, tenant=constants.POLICY_INFRA_TENANT,
  3482. silent=False):
  3483. config_def = self.entry_def(config_id=config_id, tenant=tenant)
  3484. return self.policy_api.get(config_def, silent=silent)
  3485. def list(self, tenant=constants.POLICY_INFRA_TENANT):
  3486. config_def = self.entry_def(tenant=tenant)
  3487. return self._list(config_def)
  3488. def update(self, config_id, name=IGNORE,
  3489. description=IGNORE,
  3490. server_addresses=IGNORE,
  3491. tags=IGNORE,
  3492. tenant=constants.POLICY_INFRA_TENANT):
  3493. self._update(config_id=config_id,
  3494. name=name,
  3495. description=description,
  3496. server_addresses=server_addresses,
  3497. tags=tags,
  3498. tenant=tenant)
  3499. class NsxPolicyCertApi(NsxPolicyResourceBase):
  3500. """NSX Policy Certificate API."""
  3501. @property
  3502. def entry_def(self):
  3503. return core_defs.CertificateDef
  3504. def create_or_overwrite(self, name, certificate_id=None,
  3505. pem_encoded=IGNORE, private_key=IGNORE,
  3506. passphrase=IGNORE,
  3507. key_algo=IGNORE,
  3508. description=IGNORE,
  3509. tags=IGNORE,
  3510. tenant=constants.POLICY_INFRA_TENANT):
  3511. certificate_id = self._init_obj_uuid(certificate_id)
  3512. certificate_def = self._init_def(certificate_id=certificate_id,
  3513. name=name,
  3514. private_key=private_key,
  3515. pem_encoded=pem_encoded,
  3516. passphrase=passphrase,
  3517. key_algo=key_algo,
  3518. description=description,
  3519. tags=tags,
  3520. tenant=tenant)
  3521. self._create_or_store(certificate_def)
  3522. return certificate_id
  3523. def delete(self, certificate_id,
  3524. tenant=constants.POLICY_INFRA_TENANT):
  3525. certificate_def = self.entry_def(certificate_id=certificate_id,
  3526. tenant=tenant)
  3527. self.policy_api.delete(certificate_def)
  3528. def get(self, certificate_id, tenant=constants.POLICY_INFRA_TENANT,
  3529. silent=False):
  3530. certificate_def = self.entry_def(certificate_id=certificate_id,
  3531. tenant=tenant)
  3532. return self.policy_api.get(certificate_def, silent=silent)
  3533. def list(self, tenant=constants.POLICY_INFRA_TENANT):
  3534. certificate_def = self.entry_def(tenant=tenant)
  3535. return self._list(certificate_def)
  3536. def update(self, certificate_id, name=IGNORE,
  3537. pem_encoded=IGNORE, private_key=IGNORE,
  3538. passphrase=IGNORE, key_algo=IGNORE, description=IGNORE,
  3539. tags=IGNORE, tenant=constants.POLICY_INFRA_TENANT):
  3540. self._update(certificate_id=certificate_id,
  3541. name=name,
  3542. description=description,
  3543. tags=tags,
  3544. private_key=private_key,
  3545. pem_encoded=pem_encoded,
  3546. passphrase=passphrase,
  3547. key_algo=key_algo,
  3548. tenant=tenant)
  3549. def get_path(self, certificate_id, tenant=constants.POLICY_INFRA_TENANT):
  3550. c_def = self.entry_def(certificate_id=certificate_id, tenant=tenant)
  3551. return c_def.get_resource_full_path()
  3552. def wait_until_realized(self, certificate_id, entity_type=None,
  3553. tenant=constants.POLICY_INFRA_TENANT,
  3554. sleep=None, max_attempts=None):
  3555. cert_def = self.entry_def(
  3556. certificate_id=certificate_id, tenant=tenant)
  3557. return self._wait_until_realized(
  3558. cert_def, entity_type=entity_type,
  3559. sleep=sleep, max_attempts=max_attempts)
  3560. class NsxPolicyExcludeListApi(NsxPolicyResourceBase):
  3561. """NSX Policy Exclude list."""
  3562. @property
  3563. def entry_def(self):
  3564. return core_defs.ExcludeListDef
  3565. def create_or_overwrite(self, members=IGNORE,
  3566. tenant=constants.POLICY_INFRA_TENANT):
  3567. exclude_list_def = self._init_def(members=members,
  3568. tenant=tenant)
  3569. self._create_or_store(exclude_list_def)
  3570. def delete(self, tenant=constants.POLICY_INFRA_TENANT):
  3571. err_msg = (_("This action is not supported"))
  3572. raise exceptions.ManagerError(details=err_msg)
  3573. def get(self, tenant=constants.POLICY_INFRA_TENANT, silent=False):
  3574. exclude_list_def = self.entry_def(tenant=tenant)
  3575. return self.policy_api.get(exclude_list_def, silent=silent)
  3576. def list(self, tenant=constants.POLICY_INFRA_TENANT):
  3577. err_msg = (_("This action is not supported"))
  3578. raise exceptions.ManagerError(details=err_msg)
  3579. def update(self, members=IGNORE,
  3580. tenant=constants.POLICY_INFRA_TENANT):
  3581. err_msg = (_("This action is not supported"))
  3582. raise exceptions.ManagerError(details=err_msg)
  3583. # TODO(asarfaty): Add support for add/remove member